List of tutorials:
tutorial_agxTerrain.cpp
#include <agx/config/AGX_USE_AGXTERRAIN.h>
#if AGX_USE_AGXTERRAIN()
#include "terrain_shovel_utils.h"
namespace
{
template<size_t N>
size_t find(const char(&vs)[N], int v)
{
}
auto c = static_cast<char>( v );
auto it = std::find(b, e, c);
if ( it != e ) {
return it - b;
}
else {
}
}
{
public:
: m_renderer(renderer), m_state(0), m_text(text)
{
m_state.set(HEIGHTS, true);
m_state.set(SOIL_PARTICLES, true);
this->updateState();
}
virtual bool keyboard(int key, unsigned int , float , float , bool keydown)
{
if ( keydown ) {
return false;
}
const char keys[] = { 'a', 'z', 's', 'x' };
size_t index = find(keys, key);
return false;
}
m_state.set(index, !m_state.test(index));
this->updateState();
return true;
}
protected:
void updateState()
{
m_renderer->setRenderVoxelSolidMass(m_state.test(SOLID_VOXELS));
m_text->setText(1,
agx::String::format(
"RenderSolidVoxel[a]: %d", (
int)m_state.test(SOLID_VOXELS)));
m_renderer->setRenderVoxelFluidMass(m_state.test(FLUID_VOXELS));
m_text->setText(2,
agx::String::format(
"RenderFluidVoxel[z]: %d", (
int)m_state.test(FLUID_VOXELS)));
m_renderer->setRenderSoilParticles(m_state.test(SOIL_PARTICLES));
m_text->setText(3,
agx::String::format(
"RenderSoilParticles[s]: %d", (
int)m_state.test(SOIL_PARTICLES)));
m_renderer->setRenderHeightField(m_state.test(HEIGHTS));
m_text->setText(4,
agx::String::format(
"RenderHeightField[x]: %d", (
int)m_state.test(HEIGHTS)));
}
private:
enum { SOLID_VOXELS, FLUID_VOXELS, SOIL_PARTICLES, HEIGHTS };
agxOSG::TerrainVoxelRendererObserver m_renderer;
};
{
public:
: StepEventListener( StepEventListener::POST_STEP )
, m_shovelBody(shovelBody)
{ }
{
if ( t < 0.5 )
else if ( t < 7.5 )
m_shovelBody->setVelocity(1.0, 0.0, 0.0);
else if ( t < 8 )
else if ( t < 14 )
m_shovelBody->setVelocity(-1.0, 0.0, 0.0);
else
m_shovelBody->setVelocity(0.0, 0.0, 0.0);
}
private:
};
{
public:
float maxSpeed = 1.0,
: m_maxSpeed(maxSpeed)
, m_maxRotSpeed(maxRotSpeed)
{
kinematicSphere->setEnableCollisions(false);
m_kinematicBody->setRotation(shovelBody->
getRotation());
simulation->
add(m_kinematicBody);
m_joint->setEnableComputeForces(true);
simulation->
add(m_joint);
setName("keyboard listener");
}
bool keyboard(int key, unsigned modkeyMask, float , float , bool keyDown) {
bool handled = false;
if ( !keyDown ) {
m_kinematicBody->setVelocity(0, 0, 0);
m_kinematicBody->setAngularVelocity(0, 0, 0);
return handled;
}
switch ( key )
{
case 'a':
m_kinematicBody->setVelocity(-m_maxSpeed, 0, 0);
break;
case 'z':
m_kinematicBody->setVelocity(m_maxSpeed, 0, 0);
break;
case 's':
m_kinematicBody->setVelocity(0, m_maxSpeed, 0);
break;
case 'x':
m_kinematicBody->setVelocity(0, -m_maxSpeed, 0);
break;
case GuiEventListener::KEY_Page_Up:
if ( modkeyMask == GuiEventListener::MODKEY_LEFT_ALT )
m_kinematicBody->setAngularVelocity(0, m_maxRotSpeed, 0);
else
m_kinematicBody->setVelocity(0, 0, m_maxSpeed);
break;
case GuiEventListener::KEY_Page_Down:
if ( modkeyMask == GuiEventListener::MODKEY_LEFT_ALT )
m_kinematicBody->setAngularVelocity(0, -m_maxRotSpeed, 0);
else
m_kinematicBody->setVelocity(0, 0, -m_maxSpeed);
break;
default:
break;
}
return handled;
}
return m_joint;
}
private:
float m_maxSpeed;
float m_maxRotSpeed;
};
{
auto interface = terrain->getTerrainGridControl();
agx::Real numWidthPoints_2 = numWidthPoints * 0.5;
agx::Real numLenPoints_2 = numLenPoints * 0.5;
for ( int l=0; l < numLenPoints; l++ )
for ( int w=0; w < numLenPoints; w++ )
{
interface->addSolidOccupancyInColumnToHeight( gridPoint, h, static_cast<float>(compaction) );
}
}
{
public:
: m_sd(application->getSceneDecorator())
, m_soilSimulationInterface(terrain->getSoilSimulationInterface())
{
}
{
m_sd->setText(1,
agx::String::format(
"# Particles: %d", m_soilSimulationInterface->getNumSoilParticles()));
m_sd->setText(2,
agx::String::format(
"# Particles-particle contacts: %d", m_soilSimulationInterface->getParticleParticleContacts().size()));
m_sd->setText(3,
agx::String::format(
"# Particles-geometry contacts: %d", m_soilSimulationInterface->getParticleGeometryContacts().size()));
}
private:
};
}
{
osg::Group*
root =
new osg::Group();
size_t resolutionX = 51;
size_t resolutionY = 51;
simulation->
add( terrain );
terrain->loadLibraryMaterial( "dirt_1" );
simulation->
add(terrainMaterial);
terrain->setMaterial( terrainMaterial );
auto shovel = createSimpleShovelBody(simulation, root, shovelSize, shovelAngle);
agx::Vec3 cuttingPoint1 =
agx::Vec3{ 2 * shovelSize.
x() * std::cos(shovelAngle), -shovelSize.y(), 2 * shovelSize.x() * ( -0.5 - std::sin(shovelAngle) ) };
agx::Line cuttingEdge { cuttingPoint1, cuttingPoint2 };
agx::Vec3 cuttingVector{ cos( shovelAngle ), 0.0, -sin( shovelAngle ) };
terrain->add( terrainShovel );
terrainShovel->setVerticalBladeSoilMergeDistance(0.4);
terrainShovel->setNoMergeExtensionDistance(0.5);
terrainShovel->setPenetrationForceScaling(0);
shovel->setPosition(
agx::Vec3(-5.5, 0.0, shovelSize.x() * ( 1 + 2 * sin(shovelAngle) ) + 0.15));
simulation->
add(driver, 51);
agxOSG::TerrainVoxelRendererRef renderer = new agxOSG::TerrainVoxelRenderer(terrain, root);
renderer->setRenderVoxelSolidMass(false);
renderer->setRenderVoxelFluidMass(false);
renderer->setRenderNodes(false);
renderer->setRenderVoxelBoundingBox(false);
renderer->setRenderHeightField(true);
renderer->setRenderVelocityField(false);
renderer->setVelocityFieldLineColor(
Vec4(1.0, 1.0, 0, 1));
renderer->setRenderSoilParticles(true);
simulation->
add(renderer);
}
{
osg::Group* root = new osg::Group();
size_t resolutionX = 71;
size_t resolutionY = 71;
simulation->
add(terrain);
terrain->loadLibraryMaterial("dirt_1");
auto compactionProperties = terrain->getTerrainMaterial()->getCompactionProperties();
compactionProperties->setCompactionTimeRelaxationConstant(0.5);
compactionProperties->setCompressionIndex(0.11);
compactionProperties->setAngleOfReposeCompactionRate(50.0);
auto bulkProperties = terrain->getTerrainMaterial()->getBulkProperties();
bulkProperties->setMaximumDensity(bulkProperties->getDensity() * 2.0);
bulkProperties->setSwellFactor(1.25);
simulation->
add(terrainMaterial);
terrain->setMaterial(terrainMaterial);
agx::Real length = 6.0, width = 6.0, height = 2.5;
createPile( terrain,
length,
width,
height,
location,
compaction );
simulation->
add(deformerMaterial);
sphereGeometry->setMaterial(deformerMaterial);
sphereBody->getMassProperties()->setMass(5e3);
sphereBody->setPosition(
agx::Vec3(0.6, -0.25, 4.0));
simulation->
add( sphereBody );
sphereBody->setAngularVelocityDamping(
agx::Vec3f(0.75,0.75,0.75));
boxGeometry->setMaterial(deformerMaterial);
boxBody->getMassProperties()->setMass(1e5);
boxBody->setPosition(
agx::Vec3(-0.85, -0.5, 4.0));
simulation->
add(boxBody);
agxOSG::TerrainVoxelRendererRef renderer = new agxOSG::TerrainVoxelRenderer(terrain, root);
renderer->setRenderVoxelSolidMass(false);
renderer->setRenderVoxelFluidMass(false);
renderer->setRenderNodes(false);
renderer->setRenderVoxelBoundingBox(false);
renderer->setRenderHeightField(true);
renderer->setRenderSoilParticles(true);
simulation->
add(renderer);
}
{
osg::Group* root = new osg::Group();
size_t resolutionX = 81;
size_t resolutionY = 81;
simulation->
add(terrain);
terrain->loadLibraryMaterial("dirt_1");
terrain->getTerrainMaterial()->getBulkProperties()->setYoungsModulus(1e11);
terrain->getProperties()->setDeleteSoilParticlesOutsideBounds(true);
agx::Real length = 0.65, width = 0.6, height = 0.45, thickness = 0.05, topFraction = 0.25;
auto bucketShovelData = createSimpleBucket(simulation,
root,
length,
width,
height,
thickness,
topFraction);
bucketShovelData.shovelBody,
bucketShovelData.topEdge,
bucketShovelData.cuttingEdge,
bucketShovelData.cuttingDirection }
};
terrainShovel->getRigidBody()->setRotation({ 0, -
agx::PI / 10.0, 0 });
terrain->add(terrainShovel);
agx::Real plength = 2.5, pwidth = 2.5, pheight = 1.25;
createPile(terrain,
plength,
pwidth,
pheight,
location,
compaction1);
createPile(terrain,
plength,
pwidth,
pheight,
location2,
compaction2);
createPile(terrain,
plength,
pwidth,
pheight,
location3,
compaction3);
simulation->
add(shovelMaterial);
simulation->
add(terrainMaterial);
terrain->setMaterial(terrainMaterial);
auto shovelTerrainContactMaterial = simulation->
getMaterialManager()->getContactMaterialOrCreateImplicit(shovelMaterial, terrainMaterial);
shovelTerrainContactMaterial->setYoungsModulus(1e8);
simulation->
add(shovelTerrainContactMaterial);
auto shovelParticleContactMaterial = simulation->
getMaterialManager()->getContactMaterialOrCreateImplicit(shovelMaterial, particleMaterial);
shovelParticleContactMaterial->setYoungsModulus(1e8);
shovelParticleContactMaterial->setFrictionCoefficient(0.3);
shovelParticleContactMaterial->setRollingResistanceCoefficient(0.1);
shovelParticleContactMaterial->setRestitution(0.0);
simulation->
add(shovelParticleContactMaterial);
terrain->add(terrainShovel);
auto listener =
new ShovelKeyboardListener( simulation, terrainShovel->
getRigidBody(),
Vec3(0.7, 0.0, -0.0), 1.0 );
simulation->
add(listener);
{
listener->getLock()->getLastForce( terrainShovel->getRigidBody(), force, torque );
}, simulation);
agxOSG::TerrainVoxelRendererRef renderer = new agxOSG::TerrainVoxelRenderer(terrain, root);
renderer->setRenderVoxelSolidMass(false);
renderer->setRenderVoxelFluidMass(false);
renderer->setRenderNodes(false);
renderer->setRenderVoxelBoundingBox(false);
renderer->setRenderHeightField(true);
renderer->setRenderSoilParticles(true);
simulation->
add(renderer);
agx::Vec3 eye =
agx::Vec3(1.1446339652418182E+01, -4.0189526421746642E+00, 8.6762060961937877E+00);
agx::Vec3 center =
agx::Vec3(1.6077577107657193E+00, -7.9424674741572898E-01, 1.9513089499363527E+00);
agx::Vec3 up =
agx::Vec3(-5.1512025829023400E-01, 1.7720716398098579E-01, 8.3859927291455416E-01);
}
{
osg::Group* root = new osg::Group();
size_t resolution = 250;
agx::Real size = elementSize * (resolution - 1);
auto hfIndexToPosition = [](
size_t index,
size_t resolution,
agx::Real size ) {
return ( (static_cast<agx::Real>( index ) / (
static_cast<agx::Real>( resolution )) - 0.5) * size );
};
};
for ( size_t i = 0; i < resolution; i++)
{
for ( size_t j = 0; j < resolution; j++)
{
heightField->setHeight(i, j, heightFunction(hfIndexToPosition(i, resolution, size), hfIndexToPosition(j, resolution, size), height, size));
}
}
simulation->
add(terrain);
auto shovel = createSimpleShovelBody(simulation, root, shovelSize, shovelAngle);
terrain->loadLibraryMaterial("dirt_1");
shovelParticleContactMaterial->
setYoungsModulus(particleParticleCm->getYoungsModulus());
shovelParticleContactMaterial->
setRestitution(particleParticleCm->getRestitution());
simulation->
add(shovelParticleContactMaterial);
simulation->
add(shovelTerrainContactMaterial);
auto cuttingPoint1 =
agx::Vec3(2 * shovelSize.x() * cos(shovelAngle), -shovelSize.y(), 2 * shovelSize.x() * (-0.5 - std::sin(shovelAngle)));
auto cuttingPoint2 = cuttingPoint1 +
agx::Vec3(0.0, 2.0 * shovelSize.y(), 0.0);
auto topPoint1 =
agx::Vec3(0.0, -shovelSize.y(), shovelSize.x());
auto topPoint2 =
agx::Vec3(0.0, shovelSize.y(), shovelSize.x());
auto cuttingEdge =
agx::Line(cuttingPoint1, cuttingPoint2);
auto topEdge =
agx::Line(topPoint1, topPoint2);
auto forwardVector =
agx::Vec3(cos(shovelAngle), 0.0, -std::sin(shovelAngle));
terrainShovel->setVerticalBladeSoilMergeDistance(0.3);
terrainShovel->setNoMergeExtensionDistance(0.5);
terrain->add(terrainShovel);
shovel->setPosition(-12.0, 0.0, shovelSize.x() * (1 + 2 * std::sin(shovelAngle)) + heightFunction(-12.0, 0.0, height, size) - 0.1);
agxOSG::TerrainVoxelRendererRef renderer = new agxOSG::TerrainVoxelRenderer(terrain, root);
renderer->setRenderVoxelSolidMass(false);
renderer->setRenderVoxelFluidMass(false);
renderer->setRenderNodes(false);
renderer->setRenderHeightField(true);
renderer->setRenderVoxelBoundingBox(false);
renderer->setRenderSoilParticles(true);
simulation->
add(renderer);
{
private:
public:
{
m_terrainShovel = terrainShovel;
m_bladeOffset =
agx::Vec3(shovelSize.
x() * 2 * cos(shovelAngle), 0.0, -shovelSize.
x() * (1 + 2 * sin(shovelAngle)));
m_height = height;
m_size = size;
}
{
};
};
agx::Vec3 cuttingEdgePosition = pos + m_bladeOffset;
if (cuttingEdgePosition.
x() < 0)
{
if (cuttingEdgePosition.
z() > 0)
{
}
else
{
}
}
else if (cuttingEdgePosition.
x() >= 0)
{
if (heightFunction(cuttingEdgePosition.
x(), cuttingEdgePosition.
y(), m_height,
m_size) < -0.1)
{
}
else
{
}
}
return vel;
}
{
if (t < 24)
{
m_terrainShovel->getRigidBody()->setVelocity(this->getVelocity(m_terrainShovel->getRigidBody()->getPosition()));
}
else
{
m_terrainShovel->getRigidBody()->setVelocity(0.0, 0.0, 0.0);
}
}
};
simulation->
add(bladeDriver);
simulation->
add(measurementListener);
auto eye =
agx::Vec3(4.2554700794164848E+00, -1.8111588117481372E+01, 6.3025642249031311E+00);
auto center =
agx::Vec3(-9.4897856997624352E-01, -2.0127647520494536E+00, 7.1454264792766731E-01);
auto up =
agx::Vec3(-8.7901903076223503E-02, 3.0116556248169890E-01, 9.4951174790555393E-01);
}
int main( int argc, char** argv )
{
std::cout <<
"\tTutorial agxTerrain\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
application->addScene( buildTutorial3, '3' );
application->addScene( buildTutorial4, '4' );
if ( application->init( argc, argv ) )
{
return application->run();
}
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
#else
int main(int , char** )
{
"\tTutorial agxTerrain\n" <<
"AGX Dynamics built without support for agxTerrain" <<
LOGGER_ENDL();
return 0;
}
#endif
tutorial_basicSimulation.cpp
int main( int , char** )
{
std::cout <<
"\tBasic simulation tutorial\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
std::cerr << "Creating a simulation" << std::endl;
std::cerr << "Creating a body" << std::endl;
std::cerr << "Adding body to the simulation" << std::endl;
mySimulation->add( rb );
mySimulation->getDynamicsSystem()->getTimeGovernor()->setTimeStep( dt );
std::cerr << "Step system 3 seconds forward in time" << std::endl;
mySimulation->stepForward();
mySimulation->stepTo( mySimulation->getTimeStamp() + 3 );
}
catch(std::runtime_error& e)
{
std::cerr << "Caught exception: " << e.what() << std::endl;
}
std::cerr << "Shutting down AgX" << std::endl;
return 0;
}
tutorial_bodies.cpp
#include "tutorialUtils.h"
{
osg::Group* root = new osg::Group();
dynamicRBGeometry->add( dynamicRBBox );
dynamicRB->
add( dynamicRBGeometry );
simulation->
add( dynamicRB );
simulation->
add( staticRB );
}
{
osg::Group* root = new osg::Group();
simulation->
add( dynamicRB );
simulation->
add( staticRB );
}
{
osg::Group* root = new osg::Group();
agx::Vec3 boxGeometryHalfExtent( 10, 10, 0.2 );
simulation->
add( boxGeometry );
boxGeometry->setPosition( boxGeometry->getPosition() -
agx::Vec3( 0, 0, boxGeometryHalfExtent.z() ) );
simulation->
add( largeSphereRB );
simulation->
add( smallSphereRB );
}
{
osg::Group* root = new osg::Group();
agx::Vec3 boxGeometryHalfExtent( 10, 10, 0.2 );
simulation->
add( boxGeometry );
boxGeometry->setPosition( boxGeometry->getPosition() -
agx::Vec3( 0, 0, boxGeometryHalfExtent.z() ) );
agx::Vec3 dynamicsHalfExtent( 0.5, 0.5, 1.5 );
}
{
osg::Group* root = new osg::Group();
agx::Vec3 boxGeometryHalfExtent( 10, 10, 0.2 );
boxGeometry->setPosition( boxGeometry->getPosition() -
agx::Vec3( 0, 0, boxGeometryHalfExtent.z() ) );
simulation->
add( boxGeometry );
theABody->
add( side1Geometry );
agx::Vec3 sideLeftRightGeometryOffset( -1.0, 0, 0 );
side1Geometry->setLocalPosition( sideLeftRightGeometryOffset );
theABody->
add( side2Geometry );
side2Geometry->setLocalPosition( -sideLeftRightGeometryOffset );
theABody->
add( topGeometry );
topGeometry->setLocalPosition(
agx::Vec3( 0, 0, 1.2 ) );
theABody->
add( middleGeometry );
simulation->
add( theABody );
}
{
osg::Group* root = new osg::Group();
agx::Vec3 boxGeometryHalfExtent( 10, 10, 0.2 );
boxGeometry->setPosition( boxGeometry->getPosition() -
agx::Vec3( 0, 0, boxGeometryHalfExtent.z() ) );
simulation->
add( boxGeometry );
agx::Vec3 box1RightSurfaceLocalPoint( 2 * boxHalfExtent.x(), 0, 0 );
simulation->
add( box1Body );
simulation->
add( box2Body );
}
#define LEAF_SIZE 1.0
{
public:
LeafForceField(
const agx::Vec3& dropZone ) : m_torqueFactor(LEAF_SIZE*-0.0011), m_boyancyFactor(LEAF_SIZE*-0.2)
{
m_dropZone = dropZone;
}
private:
};
{
agx::Vec3( (0.1*0.1+LEAF_SIZE*LEAF_SIZE)*0.01,
2*LEAF_SIZE*LEAF_SIZE*0.01,
(0.1*0.1+LEAF_SIZE*LEAF_SIZE)*0.01));
agx::random( -m_dropZone[2]*0.1, m_dropZone[2]*0.1 ) ) );
}
{
for(agx::RigidBodyRefVector::iterator it = bodies.begin(); it != bodies.end(); ++it)
{
continue;
N[0] = m(0,2);
N[1] = m(1,2);
N[2] = m(2,2);
boyancy *=boyancy*sign*m_boyancyFactor;
agx::Vec3 torque = (N ^ v)*(m_torqueFactor*sign);
}
}
{
public:
AgeStepListener(
agx::Real maxAge ) : m_maxAge(maxAge) {}
{
agx::RigidBodyRefVector& bodies = getSimulation()->getDynamicsSystem()->getRigidBodies();
for(agx::RigidBodyRefVector::iterator it = bodies.begin(); it != bodies.end(); ++it)
{
{
double age = t - createTime;
if (age > m_maxAge)
{
LeafForceField::initBody(body);
createTime = t;
}
}
}
}
private:
};
{
osg::Group* root = new osg::Group();
srand(0);
for(size_t i=0; i < 500; i++)
{
boxGeometry->addGroup( 1 );
box1Body->
add( boxGeometry );
LeafForceField::initBody(box1Body);
simulation->
add( box1Body );
}
simulation->
add(
new AgeStepListener(10) );
}
int main( int argc, char** argv )
{
std::cout <<
"\tRigidBody tutorial 1\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
application->addScene( buildTutorial3, '3' );
application->addScene( buildTutorial4, '4' );
application->addScene( buildTutorial5, '5' );
application->addScene( buildTutorial6, '6' );
application->addScene( buildTutorial7, '7' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_cable.cpp
#include <tuple>
static bool g_isUnitTest = false;
namespace
{
std::tuple<agx::RigidBodyRef, agxCollide::GeometryRef> createBody(
{
return std::make_tuple(body,geometry);
}
}
{
osg::Group* root = new osg::Group();
std::cout << "Tutorial 1 - Basics of creating a cable." << std::endl;
if (!g_isUnitTest) {
}
}
namespace tutorial2_helpers
{
std::tuple<agx::RigidBodyRef, agx::RigidBodyRef, agx::RigidBodyRef>
{
std::tie(ground, groundGeom) = createBody(
simulation, root,
std::tie(wall, wallGeom) = createBody(
simulation, root,
std::tie(base, baseGeom) = createBody(
simulation, root,
std::tie(arm, armGeom) = createBody(
simulation, root,
simulation->
add(constraint1);
simulation->
add(constraint2);
{
{
public:
: m_hinge(hinge)
, m_minAngle(minAngle)
, m_maxAngle(maxAngle)
, m_speed(speed)
, m_ignoreUntil(2.0)
{
}
{
if (time > m_ignoreUntil)
{
if (m_hinge->getMotor1D()->getSpeed() >=
agx::Real(0.0))
{
if (m_hinge->getAngle() > m_maxAngle)
{
m_hinge->getMotor1D()->setSpeed(-m_speed);
}
else
{
m_hinge->getMotor1D()->setSpeed(m_speed);
}
}
else if (m_hinge->getMotor1D()->getSpeed() <
agx::Real(0.0))
{
if (m_hinge->getAngle() < m_minAngle)
{
m_hinge->getMotor1D()->setSpeed(m_speed);
}
else
{
m_hinge->getMotor1D()->setSpeed(-m_speed);
}
}
}
}
protected:
virtual ~HingeOperator() {}
private:
};
simulation->
add(
new HingeOperator(hinge, minAngle, maxAngle, speed));
};
return std::make_tuple(ground, base, arm);
}
}
{
std::cout << "Tutorial 2 - Attaching the cable to rigid bodies." << std::endl;
osg::Group* root = new osg::Group();
using namespace tutorial2_helpers;
std::tie(ground, base, arm) = createScene(simulation, root, baseLength, armLength, baseRadius, armRadius, machineHeight);
}
{
std::cout << "Tutorial 3 - Cable properties." << std::endl;
osg::Group* root = new osg::Group();
auto createBendTest = [simulation,
root, baseHe, &worldOffset](
agx::Real youngsModulus)
{
};
createBendTest(1e10);
createBendTest(2e10);
createBendTest(5e10);
createBendTest(1e11);
createBendTest(2e11);
createBendTest(5e11);
{
return cable;
};
cable2->setCableProperties(sharedProperties);
}
{
std::cout << "Tutorial 4 - Iterating over a cable." << std::endl;
osg::Group* root = new osg::Group();
unsigned counter(0);
while (!iterator.
isEnd()) {
agx::Vec3 beginPosition = iterator->getBeginPosition();
agx::Vec3 endPosition = iterator->getEndPosition();
++counter;
std::cout <<
"Segment " << counter <<
" extends from " << beginPosition.
x() <<
" to " << endPosition.
x() <<
"." << std::endl;
++iterator;
}
{
public:
: m_cable(cable)
, m_root(root)
{
}
{
for (auto segment : *m_cable)
{
agx::Real tension = segment->getStretchTension();
++segment;
}
}
private:
osg::Group* m_root;
};
simulation->
add(
new TensionRenderer(cable, root));
simulation->
add(longerCable);
for (auto segment : *longerCable)
{
}
{
public:
: m_cable(cable)
, m_root(root)
{
}
{
for (auto segment : *m_cable)
{
agx::Real tension = segment->getBendTension();
}
}
private:
osg::Group* m_root;
};
simulation->
add(
new BendTensionRenderer(longerCable, root));
}
{
for (auto segment : *cable)
{
}
}
{
std::cout << "Tutorial 5 - Routing parameters." << std::endl;
osg::Group* root = new osg::Group();
auto x = {0.0, 1.0, 1.1, 1.25, 2.0};
for (auto xPos : x) {
}
for (auto xPos : x) {
}
std::cout << "Cable created with " << cable1->getNumSegments() << " segments and resolution " << cable1->getResolution() << "." << std::endl;
for (auto xPos : x) {
}
std::cout <<
"\nFirst initialization attempt resulted in " << report.
getNumSegments() <<
". Resolution is " << cable2->getResolution() << std::endl;
report = cable2->tryInitialize(
agx::Real(0.051));
std::cout <<
"\nSecond initialization attempt resulted in " << report.
getNumSegments() <<
". Resolution is " << cable2->getResolution() << std::endl;
if (!g_isUnitTest) {
}
}
{
std::cout << "Tutorial 6 - Detecting collisions." << std::endl;
osg::Group* root = new osg::Group();
leftCable->setName("LeftCable");
simulation->
add(leftCable);
createCableRenderer(leftCable, red, root);
rightCable->setName("RightCable");
simulation->
add(rightCable);
createCableRenderer(rightCable, green, root);
{
public:
{
if (cable1 == nullptr && cable2 == nullptr)
std::cout << "Collision between body " << bodyName1 << " and body " << bodyName2 << '.' << std::endl;
else if (cable1 != nullptr && cable2 == nullptr)
std::cout <<
"Collision between cable " << cable1->
getName() <<
" and body " << bodyName2 <<
'.' << std::endl;
else if (cable1 == nullptr && cable2 != nullptr)
std::cout <<
"Collision between cable " << cable2->
getName() <<
" and body " << bodyName1 <<
'.' << std::endl;
else if (cable1 != nullptr && cable2 != nullptr)
std::cout <<
"Collision between cable " << cable1->
getName() <<
" and cable " << cable2->
getName() <<
'.' << std::endl;
return KEEP_CONTACT;
}
};
simulation->
add(
new CableContactFinder());
}
{
std::cout << "Tutorial 7 - Attaching objects along a cable after it has been initialized." << std::endl;
osg::Group* root = new osg::Group();
createCableRenderer(cable,
agx::Vec3f(1, 0, 0), root);
agx::Vec3 objectAttachPoint(objectHe.x(), -objectHe.y(), -objectHe.z());
cable->attach(segment, object, objectAttachPoint);
simulation->
add(rigidObject);
while (rigidSegment->getEndPosition().x() < rigidObject->
getPosition().
x())
++rigidSegment;
cable->attach(rigidSegment, rigidObject, transform);
}
{
std::cout << "Tutorial 8 - Using rebind to create a spiral." << std::endl;
osg::Group* root = new osg::Group();
cable->setPosition(0, 0, spiralHeight / 2);
agx::Real angleStep = 360.0 / angleResolution;
agx::Real heightStep = 0.2*radius + spiralHeight / (angleResolution * heightResolution);
while (z < zEnd)
{
for (auto a = 0.0; a < 360 - angleStep; a += angleStep)
{
z = z + heightStep;
}
}
cable->rebind();
createCableRenderer(cable,
agx::Vec3f(1, 0, 0), root);
}
{
std::cout << "Tutorial 9 - Control the precise initial location and orientation of segments." << std::endl;
osg::Group* root = new osg::Group();
struct Placement {
};
{
};
for (auto& placement : placements) {
node->getRigidBody()->setRotation(placement.rot);
cable->add(node);
}
cable->add(node);
std::cout <<
"\nInitialization resulted in " << report.
getNumSegments() <<
". Resolution is " << cable->getResolution() << std::endl;
}
{
};
for (auto& placement : placements) {
node->getRigidBody()->setRotation(placement.rot);
cable->add(node);
}
for (auto segment : cable->getSegments()) {
}
}
{
};
for (auto& placement : placements) {
node->getRigidBody()->setPosition(placement.pos);
}
else {
}
node->getRigidBody()->setRotation(placement.rot);
cable->add(node);
}
}
}
int main( int argc, char** argv )
{
std::cout <<
"\tTutorial Cable\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene(buildTutorial1, '1');
application->addScene(buildTutorial2, '2');
application->addScene(buildTutorial3, '3');
application->addScene(buildTutorial4, '4');
application->addScene(buildTutorial5, '5');
application->addScene(buildTutorial6, '6');
application->addScene(buildTutorial7, '7');
application->addScene(buildTutorial8, '8');
application->addScene(buildTutorial9, '9');
if ( application->init( argc, argv ) )
{
if (args->
read(
"--isLuaFileSanityUnitTest") || args->
read(
"--agxOnly"))
{
g_isUnitTest = true;
}
return application->run();
}
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_cableWindAndWater.cpp
#include "tutorialUtils.h"
namespace
{
{
return node;
}
}
{
osg::Group* root = new osg::Group( );
waterGeometry->setPosition( 0, 0, -5 );
waterGeometry->setMaterial( waterMaterial );
::createWaterVisual( waterGeometry, root );
controller->addWater( waterGeometry );
simulation->
add( controller );
simulation->
add( waterGeometry );
simulation->
add( cable1 );
simulation->
add( cable2 );
simulation->
add( cable3 );
size_t numSegments = cable3->getNumSegments();
int counter( 0 );
while ( !iterator.
isEnd() && counter < numSegments * 0.5 )
{
++counter;
iterator++;
}
}
{
osg::Group* root = new osg::Group( );
simulation->
add( controller );
simulation->
add( cable1 );
simulation->
add( cable2 );
controller->setEnableAerodynamics( cable2, true );
controller->getOrCreateAerodynamicsParameters( cable2 )->setCoefficient( agxModel::WindAndWaterParameters::Coefficient::PRESSURE_DRAG,
agx::Real( 1 ) );
simulation->
add( cable3 );
size_t numSegments = cable3->getNumSegments();
int counter( 0 );
while ( !iterator.
isEnd() && counter < numSegments * 0.5 )
{
controller->setEnableAerodynamics( rb, true );
++counter;
iterator++;
}
controller->getOrCreateAerodynamicsParameters( cable3 )->setCoefficient( agxModel::WindAndWaterParameters::Coefficient::PRESSURE_DRAG,
agx::Real( 1 ) );
}
int main( int argc, char** argv )
{
"\tTutorial cable - wind and water\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_cable_damage.cpp
{
std::cout << "Tutorial 1 - Basic usage.\n";
osg::Group* root = new osg::Group();
simulation->
add(obstacle);
cable->addComponent(damage);
damage->setStretchDeformationWeight(
agx::Real(100.0));
damage->setBendDeformationWeight(
agx::Real(1.0));
damage->setTwistDeformationWeight(
agx::Real(30.0));
damage->setStretchRateWeight(
agx::Real(100.0));
damage->setStretchTensionWeight(
agx::Real(1e-3));
damage->setBendTensionWeight(
agx::Real(0.02));
damage->setTwistTensionWeight(
agx::Real(0.04));
damage->setNormalForceWeight(
agx::Real(2e-4));
damage->setFrictionForceWeight(
agx::Real(2.0));
std::cout <<
"Total damage: " << segmentDamage.
total() <<
'\n';
std::cout <<
"Stretch tension: " << segmentDamage.
stretchTension() <<
'\n';
std::cout <<
"Stretch rate: " << segmentDamage.
stretchRate() <<
'\n';
std::cout <<
"Bend tension: " << segmentDamage.
bendTension() <<
'\n';
std::cout <<
"Bend rate: " << segmentDamage.
bendRate() <<
'\n';
std::cout <<
"Twist tension: " << segmentDamage.
twistTension() <<
'\n';
std::cout <<
"Twist rate: " << segmentDamage.
twistRate() <<
'\n';
std::cout << '\n';
std::cout <<
"Total damage: " << accumulatedSegmentDamage.
total() <<
'\n';
std::cout <<
"Stretch tension: " << accumulatedSegmentDamage.
stretchTension() <<
'\n';
std::cout <<
"Stretch rate: " << accumulatedSegmentDamage.
stretchRate() <<
'\n';
std::cout <<
"Bend tension: " << accumulatedSegmentDamage.
bendTension() <<
'\n';
std::cout <<
"Bend rate: " << accumulatedSegmentDamage.
bendRate() <<
'\n';
std::cout <<
"Twist tension: " << accumulatedSegmentDamage.
twistTension() <<
'\n';
std::cout <<
"Twist rate: " << accumulatedSegmentDamage.
twistRate() <<
'\n';
std::cout << '\n';
simulation->
add(renderer);
for (auto& d: damages) {
largest[i] =
std::max(largest[i], d[i]);
}
}
int i(0);
i++;
}, simulation);
}
int main(int argc, char** argv)
{
<< "\tTutorial cable damage\n" << "\t--------------------------------\n\n" << std::endl;
try {
application->addScene(buildTutorial1, '1');
if (application->init(argc, argv)) {
return application->run();
}
}
catch (std::exception& e) {
std::cerr << "\nMain caught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_car.cpp
#include "tutorialUtils.h"
using namespace tutorialUtils;
{
public:
enum GeometryType { CYLINDER = 0, SPHERE, DOUBLE_SPHERE };
CarWheel(
RigidBody* carBody,
const agx::String& bodyAttachmentName,
Real radius,
const Vec3& suspensionAxis,
const Vec3& drivingAxis, osg::Group* root, GeometryType geometryType = SPHERE )
: m_body( carBody ), m_bodyAttachmentName( bodyAttachmentName ), m_radius( radius ), m_suspensionAxis( suspensionAxis ),
m_drivingAxis( drivingAxis ), m_root( root ), m_geometryType( geometryType )
{
create();
}
{
}
RigidBody* getWheelSteeringAttachment() {
return m_wheelSteeringAttachment; }
const RigidBody* getBody()
const {
return m_body; }
Hinge* getDrivingHinge() {
return m_drivingHinge; }
Hinge* getSteeringHinge() {
return m_steeringHinge; }
{
getSuspension()->getLock1D(
Constraint2DOF::FIRST )->getRegularizationParameters()->setCompliance( lockCompliance );
getSuspension()->getLock1D(
Constraint2DOF::FIRST )->getRegularizationParameters()->setDamping( lockDamping );
}
private:
void create()
{
if ( m_geometryType == CYLINDER ) {
}
else if ( m_geometryType == SPHERE ) {
}
else if ( m_geometryType == DOUBLE_SPHERE ){
}
m_wheelSteeringAttachment->getMassProperties()->setMass( 45 );
add( m_wheel );
add( m_wheelSteeringAttachment );
m_wheelSteeringAttachment->addAttachment( suspensionFrame, "suspension" );
m_wheelSteeringAttachment->addAttachment( suspensionFrame, "steering" );
m_wheelSteeringAttachment->addAttachment( drivingFrame, "driving" );
Real distFromAttachment = 0.05;
m_wheel->addAttachment( wheelFrame, "driving" );
m_wheelSteeringAttachment->setPosition(
Vec3( 0, 0, 0 ) );
m_wheel->setPosition( m_drivingAxis * distFromAttachment );
m_steeringHinge =
new Hinge( m_body, m_body->getAttachment( m_bodyAttachmentName ), m_wheelSteeringAttachment, m_wheelSteeringAttachment->getAttachment(
"steering" ) );
m_steeringHinge->getMotor1D()->getRegularizationParameters()->setCompliance( 1E-10 );
m_steeringHinge->getMotor1D()->setForceRange(
RangeReal( 2E3 ) );
add( m_steeringHinge );
m_steeringAndSuspension =
new CylindricalJoint( m_body, m_body->getAttachment( m_bodyAttachmentName ), m_wheelSteeringAttachment, m_wheelSteeringAttachment->getAttachment(
"suspension" ) );
add( m_steeringAndSuspension );
m_drivingHinge =
new Hinge( m_wheel, m_wheel->getAttachment(
"driving" ), m_wheelSteeringAttachment, m_wheelSteeringAttachment->getAttachment(
"driving" ) );
add( m_drivingHinge );
}
using Assembly::addNotification;
using Assembly::removeNotification;
private:
osg::observer_ptr< osg::Group > m_root;
GeometryType m_geometryType;
};
{
public:
CarController( CarWheel* backRight, CarWheel* backLeft, CarWheel* frontRight, CarWheel* frontLeft,
Real maxTorque,
int keyAccelerate,
int keyBrake,
int keyGearUp,
int keyGearDown,
int keySteerLeft,
int keySteerRight )
: m_backRight( backRight ), m_backLeft( backLeft ), m_frontRight( frontRight ), m_frontLeft( frontLeft ), m_maxTorque( maxTorque ),
m_gearRatio( 8,
Real( 0 ) ), m_differentialRatio( 4.1 ), m_gasPedalInput( 0 ), m_brakePedalInput( 0 ), m_steeringInput( 0 )
{
setMask( PRE_STEP );
m_input = new CarControllerInput( m_gasPedalInput, m_brakePedalInput, m_steeringInput, int(m_gearRatio.size()), keyAccelerate, keyBrake, keyGearUp, keyGearDown, keySteerLeft, keySteerRight );
m_backRight->getDrivingHinge()->getMotor1D()->setEnable( true );
m_backLeft->getDrivingHinge()->getMotor1D()->setEnable( true );
m_backRight->getDrivingHinge()->getMotor1D()->setSpeed( -100 );
m_backLeft->getDrivingHinge()->getMotor1D()->setSpeed( 100 );
m_gearRatio[ 0 ] = 0;
m_gearRatio[ 1 ] = 3.15;
m_gearRatio[ 2 ] = 2.18;
m_gearRatio[ 3 ] = 1.57;
m_gearRatio[ 4 ] = 1.19;
m_gearRatio[ 5 ] = 0.94;
m_gearRatio[ 6 ] = 0.76;
m_gearRatio[ 7 ] = 4.1;
}
virtual void addNotification() override
{
getSimulation()->add( m_input );
}
virtual void removeNotification() override
{
getSimulation()->remove( m_input );
}
{
computeAndSetTorque( m_backRight->getDrivingHinge(), m_backLeft->getDrivingHinge() );
computeAndSetBrake( m_frontRight->getDrivingHinge(), m_frontLeft->getDrivingHinge() );
updateSteering( m_frontRight->getSteeringHinge(), m_frontLeft->getSteeringHinge() );
m_input->update( 0, 0 );
std::stringstream ss;
ss << "Speed: " << int( m_frontLeft->getBody()->getVelocity().length() * 3.6 ) << " km/h";
}
private:
void computeAndSetTorque(
Hinge* h1,
Hinge* h2 )
const {
agxAssert( m_input->getGear() < m_gearRatio.size() && m_gearRatio[ m_input->getGear() ] >= 0 && m_differentialRatio > 0 );
Real gearRatio = m_gearRatio[ m_input->getGear() ];
m_backRight->getDrivingHinge()->getMotor1D()->setSpeed( -getMaxWheelRPM( m_input->getGear() ) );
m_backLeft->getDrivingHinge()->getMotor1D()->setSpeed( getMaxWheelRPM( m_input->getGear() ) );
return;
}
Real omega0 = 0.5 * omegaTot / ( gearRatio * m_differentialRatio );
Real taue = m_gasPedalInput * getTorque( omega0 );
Real taud = gearRatio * m_differentialRatio * taue;
}
void computeAndSetBrake(
Hinge* h1,
Hinge* h2 )
const {
Real maxBrakeTorque = 2E3;
Real brakeTorque = maxBrakeTorque * m_brakePedalInput;
}
{
Real maxSteeringSpeed = 2;
return;
}
Real bodySpeed = m_frontLeft->getBody()->getVelocity().length();
}
{
return m_maxTorque;
}
Real getMaxWheelRPM(
size_t gear )
const {
int sgn = int(2 * ( gear != m_gearRatio.size() - 1 ) - 1);
return m_gearRatio[ gear ] > 0 ? sgn * 200 / m_gearRatio[ gear ] : 0;
}
private:
{
public:
CarControllerInput(
Real& gasPedalInput,
Real& brakePedalInput,
Real& steeringInput,
int numGearsIncReverse,
int keyAccelerate,
int keyBrake,
int keyGearUp,
int keyGearDown,
int keySteerLeft,
int keySteerRight )
: m_gasPedalInput( gasPedalInput ), m_brakePedalInput( brakePedalInput ), m_steeringInput( steeringInput ), m_numGears( numGearsIncReverse ),
m_keyAccelerate( keyAccelerate ), m_keyBrake( keyBrake ), m_keyGearUp( keyGearUp ), m_keyGearDown( keyGearDown ),
m_keySteerLeft( keySteerLeft ), m_keySteerRight( keySteerRight ), m_gear( 0 ), m_steeringReleased( true )
{
setMask( ActivationMask(KEYBOARD | UPDATE) );
}
virtual bool keyboard( int key, unsigned int , float , float , bool keydown )
{
bool handled = false;
if ( key == m_keyAccelerate ) {
m_gasPedalInput = (
Real)keydown;
handled = true;
}
else if ( key == m_keyBrake ) {
m_brakePedalInput = (
Real)keydown;
handled = true;
}
else if ( keydown && key == m_keyGearUp ) {
m_gear =
std::min( m_gear + 1, m_numGears - 2 );
handled = true;
}
else if ( keydown && key == m_keyGearDown ) {
handled = true;
}
else if ( key == m_keySteerLeft ) {
m_steeringReleased = !keydown;
m_steeringInput = -
Real( keydown );
handled = true;
}
else if ( key == m_keySteerRight ) {
m_steeringReleased = !keydown;
m_steeringInput =
Real( keydown );
handled = true;
}
return handled;
}
virtual void update( float , float )
{
std::stringstream gTxt;
gTxt << "Gear: " << ( m_gear == 0 ? "N" : m_gear < 0 ? "R" : "" );
if ( m_gear > 0 )
gTxt << m_gear;
}
size_t getGear() const
{
if ( m_gear < 0 )
return m_numGears - 1;
return m_gear;
}
bool getSteeringReleased() const
{
return m_steeringReleased;
}
protected:
virtual ~CarControllerInput() {}
private:
CarControllerInput& operator=(const CarControllerInput&) {return *this;}
private:
int m_numGears;
int m_keyAccelerate;
int m_keyBrake;
int m_keyGearUp;
int m_keyGearDown;
int m_keySteerLeft;
int m_keySteerRight;
int m_gear;
bool m_steeringReleased;
};
private:
CarWheelRef m_backRight;
CarWheelRef m_backLeft;
CarWheelRef m_frontRight;
CarWheelRef m_frontLeft;
Real m_differentialRatio;
CarControllerInputRef m_input;
};
{
osg::Group *root = new osg::Group;
simulation->
add( ground );
enum eWheel { RIGHT_BACK = 0, LEFT_BACK, RIGHT_FRONT, LEFT_FRONT };
Vec3 carBodyDim =
Vec3( 2.2, 0.75, 0.45 );
CarWheel::GeometryType geometryType = CarWheel::SPHERE;
simulation->
add( carBody );
carBody->
addAttachment( rightFrontWheelAttachment,
"rightFront" );
CarWheelRef wheels[4];
wheels[ RIGHT_BACK ] =
new CarWheel( carBody,
"rightBack", wheelRadius,
Vec3( 0, 0, 1 ),
Vec3( 0, -1, 0 ), root, geometryType );
wheels[ RIGHT_BACK ]->setPosition( rightBackWheelAttachment->
getTranslate() );
wheels[ LEFT_BACK ] =
new CarWheel( carBody,
"leftBack", wheelRadius,
Vec3( 0, 0, 1 ),
Vec3( 0, 1, 0 ), root, geometryType );
wheels[ LEFT_BACK ]->setPosition( leftBackWheelAttachment->
getTranslate() );
wheels[ RIGHT_FRONT ] =
new CarWheel( carBody,
"rightFront", wheelRadius,
Vec3( 0, 0, 1 ),
Vec3( 0, -1, 0 ), root, geometryType );
wheels[ RIGHT_FRONT ]->setPosition( rightFrontWheelAttachment->
getTranslate() );
wheels[ LEFT_FRONT ] =
new CarWheel( carBody,
"leftFront", wheelRadius,
Vec3( 0, 0, 1 ),
Vec3( 0, 1, 0 ), root, geometryType );
wheels[ LEFT_FRONT ]->setPosition( leftFrontWheelAttachment->
getTranslate() );
for ( int i = 0; i < 4; ++i ) {
simulation->
add( wheels[ i ] );
}
Real suspensionCompliance = 9.9E-6;
Real suspensionDamping = 6.0 / 60;
for ( int i = 0; i < 4; ++i ) {
wheels[ i ]->setSuspension( suspensionRange, suspensionCompliance, suspensionDamping );
}
wheels[ RIGHT_BACK ]->getSteeringHinge()->getLock1D()->setEnable( true );
wheels[ LEFT_BACK ]->getSteeringHinge()->getLock1D()->setEnable( true );
wheels[ RIGHT_FRONT ]->getSteeringHinge()->getRange1D()->setEnable( true );
wheels[ RIGHT_FRONT ]->getSteeringHinge()->getRange1D()->setRange( steeringRange );
wheels[ LEFT_FRONT ]->getSteeringHinge()->getRange1D()->setEnable( true );
wheels[ LEFT_FRONT ]->getSteeringHinge()->getRange1D()->setRange( steeringRange );
wheels[ RIGHT_FRONT ]->getSteeringHinge()->getMotor1D()->setEnable( true );
wheels[ LEFT_FRONT ]->getSteeringHinge()->getMotor1D()->setEnable( true );
wheels[ RIGHT_FRONT ]->getSteeringHinge()->getMotor1D()->setForceRange(
RangeReal( 1E3 ) );
wheels[ LEFT_FRONT ]->getSteeringHinge()->getMotor1D()->setForceRange(
RangeReal( 1E3 ) );
simulation->
add( groundMaterial );
simulation->
add( backWheelMaterial );
simulation->
add( frontWheelMaterial );
for ( int i = 0; i < 2; ++i ) {
}
simulation->
add( backWheelGroundContact );
simulation->
add( frontWheelGroundContact );
for ( int i = 0; i < 4; ++i )
wheels[ i ]->getWheel()->getMassProperties()->setMass( 90 );
simulation->
add(
new CarController( wheels[ RIGHT_BACK ], wheels[ LEFT_BACK ], wheels[ RIGHT_FRONT ], wheels[ LEFT_FRONT ], maxTorque,
std::cerr << "\n\n";
std::cerr << "Key binding for controlling the car: \n\n";
std::cerr << " \'a\': forward (remember to switch gears!)\n";
std::cerr << " \'z\': brake\n";
std::cerr << " \'s\': gear up\n";
std::cerr << " \'x\': gear down\n";
std::cerr << " Left: turn left\n";
std::cerr << " Right: turn right\n" << std::endl;
}
int main( int argc, char** argv )
{
std::cout <<
"\tCar tutorial\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorialCar, '1' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_collisionDetection.cpp
#include <iomanip>
{
public:
agxSDK::StepEventListener(
agxSDK::StepEventListener::POST_STEP),
m_app(app), m_textStartRow(textStartRow)
{
}
{
if (m_app && m_app->getSceneDecorator()) {
int textRowCount = 0;
const int w = 7;
for (size_t i = 0; i < m_bodies.size(); ++i) {
if (m_bodies[i].isValid()) {
agx::Vec3 omega = m_bodies[i]->getAngularVelocity();
std::stringstream ss;
ss.precision(3);
ss << std::fixed << "Body " << std::setw(2) << i << ": " << m_bodies[i]->getName()
<<
": Velocity: (" << std::setw(w) << v.
x() << std::setw(w) << v.
y() << std::setw(w) << v.
z() <<
") m/s" <<
"; Angular velocity : (" << std::setw(w) << omega.
x() << std::setw(w) << omega.
y() << std::setw(w) << omega.
z() <<
") rad/s";
m_app->getSceneDecorator()->setText(textRowCount + m_textStartRow, ss.str());
textRowCount++;
}
}
}
}
{
m_bodies.push_back(body);
}
protected:
virtual ~VelocityPrinter() {}
protected:
agx::RigidBodyObserverVector m_bodies;
int m_textStartRow;
};
{
osg::Group* root = new osg::Group();
assert(gearMesh);
gearGeometry->setMaterial(material);
assert(bowlMesh);
bowlGeometry->setMaterial(material);
app->
getSceneDecorator()->
setText(0,
"Gear resting in bowl. Press 'g' to toggle debug rendering, 'G' to toggle OSG rendering.");
VelocityPrinterRef velocityPrinter = new VelocityPrinter(app, 2);
sim->
add(velocityPrinter);
velocityPrinter->addBody(gear);
velocityPrinter->addBody(bowl);
velocityPrinter->post(0);
agx::Vec3 eye =
agx::Vec3(-3.0832610934950855E-001, -1.5247185050586647E+000, 1.0936281422567065E+000);
agx::Vec3 center =
agx::Vec3(3.1770658032579266E-002, -8.2853946902834041E-002, 1.7500546587327595E-001);
agx::Vec3 up =
agx::Vec3(1.0626159313065037E-001, 5.1633116377248522E-001, 8.4977091215379164E-001);
}
{
osg::Group* root = new osg::Group();
hinge1->getMotor1D()->setEnable(true);
hinge1->getMotor1D()->setSpeed(0.2);
app->
getSceneDecorator()->
setText(1,
"Note the difference in angular velocity due to non-perfect gear arrangement - this kind ");
VelocityPrinterRef velocityPrinter = new VelocityPrinter(app, 5);
sim->
add(velocityPrinter);
velocityPrinter->addBody(rb1);
velocityPrinter->addBody(rb2);
velocityPrinter->post(0);
agx::Vec3 eye =
agx::Vec3(2.7230274677276611E-001, -2.3059253137839035E+000, 1.7681157588958740E-001);
agx::Vec3 center =
agx::Vec3(2.7230274677276611E-001, -7.3146820068359375E-003, 1.7681157588958740E-001);
agx::Vec3 up =
agx::Vec3(0.0000000000000000E+000, 0.0000000000000000E+000, 1.0000000000000000E+000);
}
int main(int argc, char** argv)
{
std::cout <<
"\tCollision detection tutorial\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene(buildTutorial1, '1');
application->addScene(buildTutorial2, '2');
if (application->init(argc, argv))
return application->run();
}
catch (std::exception& e) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_constraints.cpp
#include "tutorialUtils.h"
#ifdef __clang__
# pragma clang diagnostic ignored "-Winvalid-source-encoding"
#endif
typedef std::pair< agx::RigidBody*, agx::RigidBody* > RigidBodyPtrPair;
{
if ( createGroundBox ) {
agx::Vec3 boxGeometryHalfExtent( 15, 15, 0.5 );
boxGeometry->setPosition( boxGeometry->getPosition() -
agx::Vec3( 0, 0, boxGeometryHalfExtent.z() ) );
simulation->
add( boxGeometry );
boxGeometry->setName( "boxGeometry" );
}
return std::make_pair( rb1, rb2 );
}
{
osg::Group* root = new osg::Group();
RigidBodyPtrPair rbPair = createDefaultScene(
agx::Vec3( -4, 2, 7 ),
agx::Vec3( 0, 2, 7 ), simulation, root );
rbPair = createDefaultScene(
agx::Vec3( -4, -2, 7 ),
agx::Vec3( 0, -2, 7 ), simulation, root,
false );
}
{
osg::Group* root = new osg::Group();
RigidBodyPtrPair rbPair = createDefaultScene(
agx::Vec3( -4, 0, 7 ),
agx::Vec3( 0, 0, 7 ), simulation, root );
h1->setCompliance( 0 );
h2->setCompliance( 0 );
}
{
public:
: m_constraint( constraint ), m_speed( speed ), m_keyPositive( keyPositive ), m_keyNegative( keyNegative )
{
if ( m_constraint.isValid() )
m_constraint->getMotor1D()->setEnable( true );
}
virtual bool keyboard(
int key,
unsigned int ,
float ,
float ,
bool keydown )
{
bool handled = false;
if ( !m_constraint.isValid() )
return false;
if ( key == m_keyPositive ) {
m_constraint->getMotor1D()->setSpeed( m_speed * int( keydown ) );
handled = true;
}
else if ( key == m_keyNegative ) {
m_constraint->getMotor1D()->setSpeed( -m_speed * int( keydown ) );
handled = true;
}
return handled;
}
private:
int m_keyPositive;
int m_keyNegative;
};
{
osg::Group* root = new osg::Group();
RigidBodyPtrPair rbPair = createDefaultScene(
agx::Vec3( -4, -2, 7 ),
agx::Vec3( 0, -2, 7 ), simulation, root );
h->setCompliance( 1.0E-11 );
l->setCompliance( 1.0E-10 );
l->setCompliance( 2.0E-7, 3 );
rbPair = createDefaultScene(
agx::Vec3( -4, 2, 7 ),
agx::Vec3( 0, 2, 7 ), simulation, root );
p->setCompliance( 1.0E-11 );
p->getRange1D()->setEnable( true );
p->getRange1D()->setForceRange(
agx::RangeReal( -std::numeric_limits<agx::Real>::infinity(), std::numeric_limits<agx::Real>::infinity() ) );
l2->setCompliance( 1.0E-10 );
l2->setCompliance( 2.0E-7, 0 );
std::cout << "Press left/right to operate prismatic constraint\n";
std::cout << "Press up/down to operate hinge constraint\n" << std::endl;
}
{
public:
: m_firstBody( firstBody )
{
setMask( KEYBOARD );
}
virtual bool keyboard( int key, unsigned int , float , float , bool ) override
{
bool handled = false;
if ( !m_firstBody.isValid() )
return false;
m_firstBody->setVelocity(m_firstBody->getVelocity() +
agx::Vec3(0, 0, 1));
handled = true;
}
m_firstBody->setVelocity(m_firstBody->getVelocity() +
agx::Vec3(0, 0, -1));
handled = true;
}
m_firstBody->setVelocity(m_firstBody->getVelocity() +
agx::Vec3(1, 0, 0));
handled = true;
}
m_firstBody->setVelocity(m_firstBody->getVelocity() +
agx::Vec3(-1, 0, 0));
handled = true;
}
return handled;
}
private:
};
{
osg::Group* root = new osg::Group();
agx::Vec3 boxGeometryHalfExtent( 15, 15, 0.5 );
boxGeometry->setPosition( boxGeometry->getPosition() -
agx::Vec3( 0, 0, boxGeometryHalfExtent.z() ) );
simulation->
add( boxGeometry );
boxGeometry->setName( "boxGeometry" );
const size_t numSegments = 30;
for( size_t i = 0; i < numSegments; ++i ) {
dynamicRbGeometry->add( dynamicRbCylinder );
dynamicRb->
add( dynamicRbGeometry );
simulation->
add( dynamicRb );
if ( prevRb != 0L ) {
ballJoint->setCompliance(
agx::Real( 1E-7 ) );
simulation->
add( ballJoint );
}
prevRb = dynamicRb;
}
simulation->
add(
new CableMoveKeyboardHandler( body ) );
}
{
public:
: m_rb1( rb1 ), m_rb2( rb2 )
{
setMask(CONTACT);
}
private:
};
{
std::cout << "Time: " << t << std::endl;
return KEEP_CONTACT;
m_rb2->setVelocity(
agx::Vec3( 0, 0, 0.2 ) );
std::cout << "Lifting" << std::endl;
return KEEP_CONTACT;
}
{
osg::Group* root = new osg::Group();
agx::Vec3 boxGeometryHalfExtent( 3, 3, 0.5 );
boxGeometry->setPosition( boxGeometry->getPosition() -
agx::Vec3( 0, 0, boxGeometryHalfExtent.z() ) );
simulation->
add( boxGeometry );
boxGeometry->setName( "boxGeometry" );
simulation->
add( grip1 );
simulation->
add( grip2 );
}
{
osg::Group* root = new osg::Group();
RigidBodyPtrPair rbPair = createDefaultScene(
agx::Vec3( -4, 0, 15 ),
agx::Vec3( 4, 0, 15 ), simulation, root,
false );
{
#if 1
#else
#endif
}
#if 0
{
h1->setCompliance( 1E-11 );
}
#endif
#if 0
{
}
#endif
#if 0
{
}
#endif
#if 0
{
h3->getRange1D()->setEnable( true );
h3->getRange1D()->setRange(-5, 5);
}
#endif
}
{
public:
{
create( dimension, numSegments, mass, compliance, root );
}
{
}
private:
{
agx::Real dl = dimension.
x() / ( numSegments - 1 );
for ( size_t i = 0; i < numSegments; ++i ) {
add( rb );
if ( prev == 0L ) {
m_first = rb;
}
else {
lock->setCompliance( compliance );
lock->getRegularizationParameters( j )->setDamping( damping );
add( lock );
}
prev = rb;
position.x() += dl;
}
m_last = prev;
++ms_index;
}
static size_t ms_index;
};
{
public:
{
create( radius, thickness, numSegments, mass, compliance, damping, root );
}
{
}
private:
{
agx::Real dPhi = 2 * M_PI / (numSegments - 1);
agx::Real xDim = 2 * M_PI * radius / ( numSegments - 1 );
for ( size_t i = 0; i < numSegments; ++i ) {
add( rb );
if ( first == 0L ) {
first = rb;
}
else {
lock->setCompliance( compliance );
lock->getRegularizationParameters( j )->setDamping( damping );
add( lock );
}
prev = rb;
}
lock->setCompliance( compliance );
lock->getRegularizationParameters( j )->setDamping( damping );
add( lock );
++ms_index;
}
static size_t ms_index;
};
size_t Beam::ms_index = 1;
size_t Wheel::ms_index = 123456;
{
osg::Group* root = new osg::Group();
size_t numSegments = 100;
agx::ref_ptr<Beam> beam1 =
new Beam( dimension, numSegments, totalMass, compliance, root );
simulation->
add( beam1 );
attLock->setCompliance( 1E-12 );
simulation->
add( attLock );
attLock->setCompliance( 1E-12 );
simulation->
add( attLock );
compliance = 1E-9;
totalMass = 12E3;
agx::ref_ptr<Beam> beam2 =
new Beam( dimension, numSegments, totalMass, compliance, root );
simulation->
add( beam2 );
beam2->setPosition(
agx::Vec3( 0, 0.5, 5 ) );
}
{
public:
: m_h1( h1 ), m_h2( h2 ), m_motorForce( motorForce ), m_motorSpeed( motorSpeed )
{
setMask( KEYBOARD );
}
bool keyboard( int key, unsigned int , float , float , bool keydown )
{
bool handled = false;
m_h1->getMotor1D()->setSpeed( m_motorSpeed * keydown );
m_h2->getMotor1D()->setSpeed(-m_motorSpeed * keydown );
m_h1->getMotor1D()->setForceRange(
agx::RangeReal( m_motorForce * keydown ) );
m_h2->getMotor1D()->setForceRange(
agx::RangeReal( m_motorForce * keydown ) );
handled = true;
}
m_h1->getMotor1D()->setSpeed(-m_motorSpeed * keydown );
m_h2->getMotor1D()->setSpeed( m_motorSpeed * keydown );
m_h1->getMotor1D()->setForceRange(
agx::RangeReal( m_motorForce * keydown ) );
m_h2->getMotor1D()->setForceRange(
agx::RangeReal( m_motorForce * keydown ) );
handled = true;
}
return handled;
}
private:
};
{
osg::Group* root = new osg::Group();
size_t numSegments = 500;
agx::ref_ptr<Beam> beam1 =
new Beam( dimension, numSegments, totalMass, compliance, root );
simulation->
add( beam1 );
#if 0
l->setCompliance( 1E-10 );
l->setCompliance( 1E-10 );
#else
att1->setCompliance( 1E-12 );
att2->setCompliance( 1E-12 );
att1->getMotor1D()->setEnable( true );
att2->getMotor1D()->setEnable( true );
simulation->
add(
new Tutorial58KeyboardController( att1, att2, motorForce, motorSpeed ) );
simulation->
add(
new tutorialUtils::TextEventListener(
"Rotate beam with LEFT/RIGHT keys",
agx::Vec2(0.1, 0.1),
agx::Vec3(1,0,0)));
#endif
}
{
osg::Group* root = new osg::Group();
simulation->
add( wheel1 );
simulation->
add( wheel2 );
simulation->
add( plane );
}
{
osg::Group* root = new osg::Group();
body1->
add( boxGeometry1 );
simulation->
add( body1 );
simulation->
add( lock1 );
body2->
add( boxGeometry2 );
simulation->
add( body2 );
simulation->
add( lock2 );
simulation->
add(
new tutorialUtils::TextEventListener(
"Pick bodies with CTRL+left mouse",
agx::Vec2( 0.1, 0.1 ),
agx::Vec3( 1, 0, 0 ) ) );
}
{
osg::Group* root = new osg::Group();
simulation->
add( prismatic );
std::cout << "Initial angle: " << prismatic->getAngle() << std::endl;
}
{
public:
:
agxSDK::StepEventListener(
agxSDK::StepEventListener::POST_STEP ), m_ec( ec ), m_sd( sd ), m_index( index )
{
update();
}
protected:
{
update();
}
private:
void update()
{
if ( m_ec == 0L || m_sd == 0L )
return;
m_sd->setText( (
int)m_index,
agx::String::format(
"Applied force by %s: %3.3f Nm", m_ec->getName().c_str(), m_ec->getCurrentForce() ) );
}
private:
osg::observer_ptr< agxOSG::SceneDecorator > m_sd;
size_t m_index;
};
{
osg::Group* root = new osg::Group();
simulation->
add( hinge );
hinge->getMotor1D()->setEnable( true );
hinge->getMotor1D()->setSpeed(
agx::Real( 1 ) );
agxAssert( hinge->getAttachmentPair()->getAngle( 0 ) != 0L );
hinge->addSecondaryConstraint( "FrictionController", frictionController );
hinge->addSecondaryConstraint( "RedundantRange", rangeController );
frictionController->setEnable( true );
frictionController->setSpeed(
agx::Real( 0 ) );
rangeController->setEnable( true );
rangeController->setCompliance(
agx::Real( 1E-10 ) );
simulation->
add(
new ElementaryConstraintCurrentForceReader( hinge->getMotor1D(), application->
getSceneDecorator(), 0 ) );
simulation->
add(
new ElementaryConstraintCurrentForceReader( frictionController, application->
getSceneDecorator(), 1 ) );
}
{
osg::Group* root = new osg::Group();
simulation->
add( cylindrical );
cylindrical->getScrew1D()->setEnable( true );
cylindrical->getScrew1D()->setLead(
agx::Real( 0.01 ) );
}
{
osg::Group* root = new osg::Group();
simulation->
add( universal );
}
{
osg::Group* root = new osg::Group();
simulation->
add( universal );
}
{
osg::Group* root = new osg::Group();
simulation->
add( universal );
simulation->
add(meshGeom);
}
int main( int argc, char** argv )
{
std::cout <<
"\tConstraints tutorial\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
application->addScene( buildTutorial3, '3' );
application->addScene( buildTutorial4, '4' );
application->addScene( buildTutorial5, '5' );
application->addScene( buildTutorial6, '6' );
application->addScene( buildTutorial7, '7' );
application->addScene( buildTutorial8, '8' );
application->addScene( buildTutorial9, '9' );
application->addScene( buildTutorial10, '0' );
application->addScene( buildTutorial11, '!' );
application->addScene( buildTutorial12, '"' );
application->addScene( buildTutorial13, '#' );
application->addScene( buildTutorial14, '%' );
application->addScene( buildTutorial15, '&' );
application->addScene( buildTutorial16, '/' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_contactForces.cpp
{
osg::Group* root = new osg::Group;
simulation->
add( ground );
{
sceneDecorator->setText( 0, "Tutorial contact forces: Normal force." );
if ( geometryContacts.empty() ) {
sceneDecorator->setText( 1, " - The box is currently not in contact with the ground." );
}
else {
auto geometryContact = geometryContacts.
front();
agx::Real expectedRestingNormalForce = geometryContact->rigidBody( 0 )->getMassProperties()->getMass() *
for ( const auto& p : geometryContact->points() )
currentNormalForce += p.getNormalForceMagnitude();
sceneDecorator->setText( 1,
agx::String::format(
" - Number of contact points: %d", geometryContact->points().size() ) );
sceneDecorator->setText( 2,
agx::String::format(
" - Contains impacts: %s", geometryContact->hasImpactingPoints() ?
"true" :
"false" ) );
sceneDecorator->setText( 3,
agx::String::format(
" - Current normal force: %.10f N", currentNormalForce ) );
sceneDecorator->setText( 4,
agx::String::format(
" - Expected resting normal force: %.10f N", expectedRestingNormalForce ) );
}
};
displayNormalForce( simulation );
}
{
osg::Group* root = new osg::Group;
simulation->
add( ground );
auto displayFrictionForce = [application, contactMaterial](
agxSDK::Simulation* simulation )
{
sceneDecorator->setText( 0, "Tutorial contact forces: Friction force." );
if ( geometryContacts.empty() ) {
sceneDecorator->setText( 1, " - The box is currently not in contact with the ground." );
}
else {
auto geometryContact = geometryContacts.
front();
agx::Real expectedRestingNormalForce = geometryContact->rigidBody( 0 )->getMassProperties()->getMass() *
for ( const auto& p : geometryContact->points() )
currentNormalForce += p.getNormalForceMagnitude();
for ( const auto& p : geometryContact->points() )
currentFrictionForce += p.getTangentialForceMagnitude();
agx::Real maxFrictionForce = contactMaterial->getFrictionCoefficient() *
expectedRestingNormalForce;
currentFrictionForce,
1.0E-4 ) ?
"true" :
"false" ) );
sceneDecorator->setText( 2,
agx::String::format(
" - Current friction force: %.5f N", currentFrictionForce ) );
sceneDecorator->setText( 3,
agx::String::format(
" - Max resting friction force: %.5f N", maxFrictionForce ) );
}
};
}
{
osg::Group* root = new osg::Group;
simulation->
add( ground );
contactMaterial->setAdhesion( 0.0, 5.0E-3 );
{
sceneDecorator->setText( 0, "Tutorial contact forces: Friction force." );
if ( geometryContacts.empty() ) {
sceneDecorator->setText( 1, " - The box is currently not in contact with the ground." );
}
else {
auto geometryContact = geometryContacts.
front();
sceneDecorator->setText( 1, " - Geometry contact state:" );
sceneDecorator->setText( 2,
agx::String::format(
" * Contains impacting contact points: %s", geometryContact->hasImpactingPoints() ?
"true" :
"false" ) );
sceneDecorator->setText( 3,
agx::String::format(
" * Interacting bodies: %s <-> %s", geometryContact->rigidBody( 0 )->getName().c_str(),
geometryContact->rigidBody( 1 )->getName().c_str() ) );
sceneDecorator->setText( 4,
agx::String::format(
" * Number of contact points: %d", geometryContact->points().size() ) );
for (
agx::UInt i = 0u; i < geometryContact->points().size(); ++i ) {
const auto& p = geometryContact->points()[ i ];
sceneDecorator->setText( 4 + (
int)i + 1,
agx::String::format(
" o Point %d: Is impacting [%s], Normal force [%4.2f N], Friction force [%4.2f N]",
(int)i + 1,
p.getNormalForceMagnitude(),
p.getTangentialForceMagnitude() ),
}
}
};
displayContactPointState( simulation );
}
int main( int argc, char** argv )
{
std::cout <<
"\tContact forces tutorial\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
application->addScene( buildTutorial3, '3' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_convex.cpp
#include "tutorialUtils.h"
#include <ostream>
{
}
{
osg::Group* root = new osg::Group();
createPyramid( 0.4, 0.8, vertices, indices );
convexRigidBody->
setName(
"fromAConvexMesh" );
simulation->
add( convexRigidBody );
srand(5);
for(size_t i=0; i < 30; i++)
{
}
convexRigidBody1->
setName(
"createConvexFromRandomPoints");
simulation->
add( convexRigidBody1 );
convexRigidBody2->
setName(
"CreatedFromMeshFile");
simulation->
add(convexRigidBody2);
staticRB->
add( staticBodyGeometry );
simulation->
add(staticRB);
}
{
osg::Group* root = new osg::Group();
std::cerr << "Creating Convex Decompositions" << std::endl;
for (size_t i = 0; i < 7; i++)
{
size_t resolution = 5+i*10;
timer.stop();
std::cout << "\tResolution " << resolution << " Time: " << timer.getTime() / 1000 << " Seconds." << std::endl;
for (auto c : result)
{
convexRigidBody->
add(geometry);
}
convexRigidBody->
setName(
"ConvexDecomposition");
simulation->
add(convexRigidBody);
}
staticRB->
add(staticBodyGeometry);
simulation->
add(staticRB);
}
namespace {
struct Settings {
int resolution = 0;
double alpha = 0;
double beta = 0;
double concavity = 0;
int numVertices = 0;
Settings(int res, double a, double b, double c, int n) :
resolution(res),
alpha(a),
beta(b),
concavity(c),
numVertices(n)
{
}
Settings(const Settings& s) :
resolution(s.resolution),
alpha(s.alpha),
beta(s.beta),
concavity(s.concavity),
numVertices(s.numVertices)
{
}
};
std::ostream&
operator <<(std::ostream& os,
const Settings& s)
{
os <<
agx::String::format(
"Resolution=%d, alpha=%f, beta=%f, concavity=%f, maxVertices=%d", s.resolution, s.alpha, s.beta, s.concavity, s.numVertices);
return os;
}
}
{
public:
ConvexCooker(
const agxIO::MeshReader* reader,
const Settings& s) : BasicThread(), m_reader(reader), m_settings(s), m_time(0)
{
}
double getTime() const
{
return m_time;
}
Settings getSettings() const
{
return m_settings;
}
{
if (!m_factory)
return m_factory->getConvexShapes();
}
void run() override
{
parameters->resolution = m_settings.resolution;
parameters->alpha = m_settings.alpha;
parameters->beta = m_settings.beta;
parameters->concavity = m_settings.concavity;
parameters->maxNumVerticesPerConvex = m_settings.numVertices;
timer.stop();
m_time = timer.getTime() / 1000;
}
private:
const Settings& m_settings;
double m_time;
};
{
osg::Group* root = new osg::Group();
if (!meshReader->readFile("models/bunny.obj"))
std::vector<Settings> settings = {
Settings({5,0,0,0.1,10}),
Settings({20,0.01,0.01,0.05,1000}),
Settings({30,0.001,0.01,0.01,1000}),
Settings({50,0.01,0.001,0.005,1000}),
};
std::cerr << "Creating Convex Decompositions..." << std::endl;
for (const auto& s : settings)
{
auto cooker = new ConvexCooker(meshReader, s);
cookers.push_back(cooker);
cooker->start();
}
std::for_each(cookers.begin(), cookers.end(), [](ConvexCooker* c) { c->join(); } );
int i = 0;
for (auto t : cookers)
{
std::cerr << t->getSettings() << ": " << t->getTime() << std::endl;
for (auto c : t->getConvexShapes())
{
convexRigidBody->
add(geometry);
}
convexRigidBody->
setName(
"ConvexDecomposition");
std::stringstream str;
str << t->getSettings() << std::ends;
simulation->
add(convexRigidBody);
i++;
}
cookers.clear();
staticRB->
add(staticBodyGeometry);
simulation->
add(staticRB);
}
int main( int argc, char** argv )
{
std::cout <<
"\tTutorial Convex\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
application->addScene( buildTutorial3, '3' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_create_oriented_bounding_volume.cpp
void createBoundingVolume(
osg::Group *root,
{
auto boundingVolumeShape = createShape(radiusHeight[0], radiusHeight[1]);
}
{
std::cout << "Creating oriented bounding volumes from mesh shapes\n";
osg::Group* root = new osg::Group();
std::string filename = "models/bunny.obj";
double scale = 4;
filename,
simulation->
add(mesh_geom);
simulation->
add(box_geometry);
root->addChild(axes_node);
std::function<bool(const agx::Vec3Vector&, agx::Vec2&, agx::AffineMatrix4x4&, agxUtil::ShapeOrientation::Orientation )>
{
};
std::function<bool(const agx::Vec3Vector&, agx::Vec2&, agx::AffineMatrix4x4&, agxUtil::ShapeOrientation::Orientation)>
{
};
std::function<agxCollide::Shape* (double, double)>
createCylinder = [](double radius,
{
};
std::function<agxCollide::Shape* (double, double)>
createCapsule = [](double radius,
{
};
createBoundingVolume(simulation, root, mesh_data,
agx::Vec3(1, 0, 0), computeOrientedCylinder, createCylinder);
createBoundingVolume(simulation, root, mesh_data,
agx::Vec3(3, 0, 0), computeOrientedCapsule, createCapsule);
sd->setEnableShadows(true);
}
int main(int argc, char** argv)
{
<< "\tTutorial oriented bounding volumes\n" << "\t--------------------------------\n\n" << std::endl;
try {
application->addScene(buildTutorial1, '1');
if (application->init(argc, argv)) {
return application->run();
}
}
catch (std::exception& e) {
std::cerr << "\nMain caught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_customConstraints.cpp
#include "tutorialUtils.h"
using namespace tutorialUtils;
{
public:
{
if ( rb1 == 0L || rb1 == rb2 )
return;
const Vec3 worldHingeAxis( 0, 1, 0 );
bool constructSuccess = construct( rb1, frame1, rb2, frame2, createFunc );
if ( !constructSuccess ) {
}
}
{
return createElementaryConstraints() && createSecondaryConstraints();
}
Bool createElementaryConstraints()
{
std::cout << "Constructing elementary primary constraints." << std::endl;
return true;
}
Bool createSecondaryConstraints()
{
return true;
}
{
if ( !isValid() )
return;
if ( line1 != 0L )
if ( line2 != 0L )
if ( line1 != 0L )
if ( line2 != 0L )
}
virtual ~MyHingeImplementation() {}
};
{
return dynamic_cast< MyHingeImplementation* >( implementation )->create();
}
{
public:
{
m_implementation = new MyHingeImplementation( rb1, rb2 );
}
virtual int getNumDOF() const override { return 5; }
protected:
{
if ( m_implementation != 0L )
static_cast< const MyHingeImplementation* >( m_implementation )->render( mgr, scale );
}
virtual ~MyHinge()
{
if ( m_implementation != 0L )
{
delete m_implementation;
m_implementation = 0L;
}
}
};
{
osg::Group *root = new osg::Group;
simulation->
add( ground );
simulation->
add( myHinge );
}
{
public:
MyElementaryDistanceData(
const Vec3& point1,
const Vec3& point2 )
: p1( point1 ), p2( point2 ) {}
MyElementaryDistanceData( const MyElementaryDistanceData& other )
: p1( other.p1 ), p2( other.p2 ) {}
virtual ~MyElementaryDistanceData() {}
private:
MyElementaryDistanceData& operator=(const MyElementaryDistanceData&) {return *this;}
};
{
public:
MyElementaryDistance( const MyElementaryDistanceData& data )
{
m_restLength = ( m_data.p1 - m_data.p2 ).
length();
m_currentLength = m_restLength;
}
virtual ~MyElementaryDistance() {}
{
Vec3 k = m_data.p1 - m_data.p2;
}
else if ( writeState == GWriteState::IGNORE_FIRST ) {
}
else {
agxAssert( writeState == GWriteState::WRITE_SECOND_FIRST );
}
return numBlocks;
}
{
g[ row ] = m_currentLength - m_restLength;
return 1;
}
protected:
};
{
public:
: m_distance( 0L )
{
if ( rb1 == 0L || rb2 == 0L )
return;
createData( rb1, rb2 );
m_distance = new MyElementaryDistance( MyElementaryDistanceData( m_p1, m_p2 ) );
m_ec.push_back( m_distance );
}
virtual ~MyDistanceJointImplementation() {}
virtual void prepare() override
{
m_p1 = m_bodies.front()->getPosition();
m_p2 = m_bodies.back()->getPosition();
}
{
if ( !isValid() )
return;
}
protected:
MyDistanceJointImplementation() : m_distance( 0L ) {}
{
m_bodies.push_back( rb1 );
m_bodies.push_back( rb2 );
prepare();
}
protected:
MyElementaryDistance* m_distance;
};
{
public:
{
m_implementation = new MyDistanceJointImplementation( rb1, rb2 );
}
protected:
MyDistanceJoint() {}
virtual ~MyDistanceJoint()
{
if ( m_implementation )
{
delete m_implementation;
m_implementation = 0;
}
}
virtual int getNumDOF() const override { return 1; }
{
static_cast< const MyDistanceJointImplementation* >( m_implementation )->render( mgr, scale );
}
};
{
osg::Group *root = new osg::Group;
simulation->
add( ground );
simulation->
add( distanceJoint );
}
class MyAdvancedElementaryDistance : public MyElementaryDistance
{
public:
MyAdvancedElementaryDistance(
const Vec3& p1,
const Vec3& p2 )
: MyElementaryDistance( MyElementaryDistanceData( p1, p2 ) ), m_desiredSpeed( 0 ) {}
virtual ~MyAdvancedElementaryDistance() {}
{
if ( getRegularizationParameters()->isHolonomic() )
return MyElementaryDistance::getViolation( g, row );
else
g[ row ] = 0;
return 1;
}
virtual UInt getVelocity(
Real* v,
UInt row )
const override {
if ( getRegularizationParameters()->isHolonomic() )
v[ row ] = 0;
else
v[ row ] = m_desiredSpeed;
return 1;
}
{
if ( !getRegularizationParameters()->isHolonomic() && !getForceRange().isInfinite() )
bounds[ row + 0 ] = getForceRange() * dt;
else
}
void setDesiredSpeed(
Real desiredSpeed )
{
m_desiredSpeed = desiredSpeed;
}
Real getDesiredSpeed()
const {
return m_desiredSpeed; }
void updateRestLength()
{
m_restLength = (m_data.p1 - m_data.p2).
length();
}
protected:
};
class MyAdvancedDistanceJointImplementation : public MyDistanceJointImplementation
{
public:
: m_advancedDistance( 0L )
{
if ( rb1 == 0L || rb2 == 0L )
return;
createData( rb1, rb2 );
m_distance = m_advancedDistance = new MyAdvancedElementaryDistance( m_p1, m_p2 );
m_ec.push_back( m_distance );
}
void setMotorEnable( bool enable )
{
if ( enable ) {
}
else {
m_advancedDistance->updateRestLength();
}
}
void setDesiredSpeed(
Real desiredSpeed )
{
m_advancedDistance->setDesiredSpeed( desiredSpeed );
}
void setForceRange(
Real lower,
Real upper )
{
m_advancedDistance->setForceRange( lower, upper );
}
protected:
MyAdvancedElementaryDistance* m_advancedDistance;
};
class MyAdvancedDistanceJoint : public MyDistanceJoint
{
public:
{
m_implementation = new MyAdvancedDistanceJointImplementation( rb1, rb2 );
}
void setMotorEnable( bool enable )
{
static_cast< MyAdvancedDistanceJointImplementation* >( m_implementation )->setMotorEnable( enable );
}
void setDesiredSpeed(
Real desiredSpeed )
{
static_cast< MyAdvancedDistanceJointImplementation* >( m_implementation )->setDesiredSpeed( desiredSpeed );
}
void setForceRange(
Real lower,
Real upper )
{
static_cast< MyAdvancedDistanceJointImplementation* >( m_implementation )->setForceRange( lower, upper );
}
virtual int getNumDOF() const override { return 1; }
protected:
virtual ~MyAdvancedDistanceJoint()
{
if (m_implementation)
{
delete m_implementation;
m_implementation = 0;
}
}
};
{
public:
MyDistanceJointKeyboardController( MyAdvancedDistanceJoint* distanceJoint,
Real speed,
int keyIn,
int keyOut )
: m_distanceJoint( distanceJoint ), m_speed( speed ), m_keyIn( keyIn ), m_keyOut( keyOut )
{
setMask( KEYBOARD );
}
bool keyboard( int key, unsigned int , float , float , bool keydown )
{
bool handled = key == m_keyIn || key == m_keyOut;
if ( !handled || !m_distanceJoint.isValid() )
return false;
m_distanceJoint->setMotorEnable( keydown );
m_distanceJoint->setDesiredSpeed( (key == m_keyOut) * m_speed - (key == m_keyIn) * m_speed );
return true;
}
private:
int m_keyIn;
int m_keyOut;
};
{
osg::Group *root = new osg::Group;
simulation->
add( ground );
simulation->
add( distanceJoint );
distanceJoint->setForceRange(
Real( -1E5 ),
Real( 1E5 ) );
if ( lock != 0L )
simulation->
add( hinge );
simulation->
add(
new MyDistanceJointKeyboardController( distanceJoint, speed, keyIn, keyOut ) );
}
{
return true;
}
{
public:
{
rb1LocalAxis,
rb1,
f1,
rb2,
f2 );
auto success = construct( rb1,
f1,
rb2,
f2,
createMyLock );
if ( !success )
for (
size_t i = 0u; i <
sizeof( m_offDiagonalParameters ) /
sizeof(
Real ); ++i )
m_offDiagonalParameters[ i ] = 0.0;
setSupportsComplianceMatrix( true );
}
{
return m_offDiagonalParameters[ calculateIndexAndValidate( row, col ) ];
}
void setOffDiagonalParameter(
UInt row,
UInt col,
Real value )
{
if ( value < 0.0 )
m_offDiagonalParameters[ calculateIndexAndValidate( row, col ) ] = value;
}
public:
{
for (
UInt32 row = 1u; row < 6u; ++row ) {
for (
UInt32 col = 0u; col < row && col < 5u; ++col ) {
matrix[ row ][ col ] = -m_offDiagonalParameters[ calculateIndex( row, col ) ];
}
}
}
private:
template<typename T>
T calculateIndex( T row, T col ) const
{
return (T)( row * ( row - 1 ) / 2 + col );
}
template<typename T>
T calculateIndexAndValidate( T row, T col ) const
{
if ( row >= 6 || col >= 6 )
if ( row == col )
if ( col > row )
return calculateIndex( row, col );
}
private:
Real m_offDiagonalParameters[ (6 * 6 - 6) / 2 ];
};
{
public:
MyBeam(
Vec3 halfExtents,
UInt numSegments )
{
const auto segmentHalfExtents =
Vec3( halfExtents.
x() / numSegments,
auto position =
Vec3( segmentHalfExtents.x(), 0, 0 );
for (
UInt i = 0u; i < numSegments; ++i ) {
position.
x() += 2.0 * segmentHalfExtents.x();
RigidBody* prevSegment = m_segments.empty() ?
nullptr :
m_segments.back();
if ( prevSegment == nullptr ) {
m_worldLock =
new LockJoint( segment,
Vec3( -segmentHalfExtents.x(), 0, 0 ) );
}
else {
MyLockJointImplementation* lock = new MyLockJointImplementation( prevSegment,
Vec3( segmentHalfExtents.x(), 0, 0 ),
segment );
getRep()->getSubConstraints().push_back( lock );
}
m_segments.push_back( segment );
}
}
{
for (
UInt i = 0u; i < m_segments.size(); ++i )
root ),
}
void setComplianceMatrixValue(
Real compliance,
int dof = -1 )
{
compliance =
std::max( compliance, 0.0 );
visit( [dof, compliance]( MyLockJointImplementation* lock )
{
lock->userAPIsetCompliance( compliance, dof );
} );
}
void setComplianceMatrixValue(
UInt row,
UInt col,
Real value )
{
if ( row == col ) {
setComplianceMatrixValue( value, (int)row );
return;
}
visit( [row, col, value]( MyLockJointImplementation* lock )
{
lock->setOffDiagonalParameter( row, col, value );
} );
}
public:
virtual void addNotification() override
{
getRep()->getSimulationProxy()->add( m_worldLock );
for ( auto segment : m_segments )
getRep()->getSimulationProxy()->add( segment );
}
virtual void removeNotification() override
{
getRep()->getSimulationProxy()->remove( m_worldLock );
for ( auto rb : m_segments )
getRep()->getSimulationProxy()->remove( rb );
}
{
visit( [mgr, scale]( MyLockJointImplementation* lock )
{
} );
}
virtual int getNumDOF() const override
{
return 0;
}
protected:
virtual ~MyBeam()
{
while ( !getRep()->getSubConstraints().empty() ) {
delete getRep()->getSubConstraints().back();
getRep()->getSubConstraints().pop_back();
}
delete getRep();
setRep( nullptr );
}
private:
void visit( std::function<void( MyLockJointImplementation* )> visitor ) const
{
for (
UInt i = 0u; i < getRep()->getSubConstraints().size(); ++i )
visitor( static_cast<MyLockJointImplementation*>( getRep()->getSubConstraints()[ i ] ) );
}
private:
RigidBodyRefVector m_segments;
};
{
osg::Group* root = new osg::Group;
MyBeamRef beam =
new MyBeam(
Vec3( 3, 0.25, 0.25 ), 10 );
beam->createVisual( root );
1.0E-3 );
}
int main( int argc, char** argv )
{
std::cout <<
"\tTutorial custom constraints\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorialMyHinge1, '1' );
application->addScene( buildTutorialMyDistanceJoint1, '2' );
application->addScene( buildTutorialMyDistanceJoint2, '3' );
application->addScene( buildTutorialMyLockJointComplianceMatrix, '4' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_customMergeSplitAlgorithm.cpp
namespace tutorial1
{
{
public:
BoxContactMergeSplitAlgorithm();
protected:
virtual ~BoxContactMergeSplitAlgorithm();
};
BoxContactMergeSplitAlgorithm::BoxContactMergeSplitAlgorithm()
: MergeSplitAlgorithm()
{
setEnableSerialization( false );
}
BoxContactMergeSplitAlgorithm::~BoxContactMergeSplitAlgorithm()
{
}
{
const auto& geometryContacts = getMergeSplitHandler()->getSimulation()->getSpace()->getGeometryContacts();
for ( const auto geometryContact : geometryContacts ) {
if ( !geometryContact->isValid() || !geometryContact->enabled() )
continue;
agxSDK::MergedState mergedState( geometryContact->geometry( 0 ), geometryContact->geometry( 1 ), getMergeSplitHandler() );
continue;
actions.
split( mergedState );
}
}
{
continue;
const auto mergedState = postSolveData.
createMergedState( i, *getMergeSplitHandler() );
continue;
if ( !geometryContact.body1() || !geometryContact.body2() )
continue;
if ( geometryContact.points().size() != 4 )
continue;
{
};
for ( auto contactPoint : geometryContact.points() ) {
if ( !contactPoint.enabled() )
continue;
maxSpeedInContact =
std::max(
agx::absolute( calculateSpeed( contactPoint.point(), contactPoint.normal() ) ), maxSpeedInContact );
maxSpeedInContact =
std::max(
agx::absolute( calculateSpeed( contactPoint.point(), contactPoint.tangentU() ) ), maxSpeedInContact );
maxSpeedInContact =
std::max(
agx::absolute( calculateSpeed( contactPoint.point(), contactPoint.tangentV() ) ), maxSpeedInContact );
}
if ( maxSpeedInContact < 0.3 )
}
}
}
{
osg::Group* root = new osg::Group();
simulation->
add( ground );
srand(5);
{
return;
}, simulation, firstSpawnTime );
for ( auto algorithm : algorithms )
}
namespace tutorial2
{
{
public:
InclinationTestMergeSplitAlgorithm();
protected:
virtual ~InclinationTestMergeSplitAlgorithm();
};
InclinationTestMergeSplitAlgorithm::InclinationTestMergeSplitAlgorithm()
: MergeSplitAlgorithm()
{
setEnableSerialization( false );
}
InclinationTestMergeSplitAlgorithm::~InclinationTestMergeSplitAlgorithm()
{
}
{
const auto& constraints = getMergeSplitHandler()->getSimulation()->getConstraints();
for ( const auto& constraint : constraints ) {
continue;
if ( mergedBody == nullptr )
return;
{
agxAssert( edge->isTagged( agx::MergedBody::EdgeInteraction::CONTACT ) );
};
mergedBody->
traverse( ground, edgeVisitor );
for ( auto edge : edges ) {
agx::RigidBody* otherRb = edge->getRigidBody1() == ground ? edge->getRigidBody2() : edge->getRigidBody1();
if ( otherRb == nullptr || !edge->isTagged( agx::MergedBody::EdgeInteraction::CONTACT ) )
continue;
agxSDK::MergedState state( edge->getRigidBody1(), edge->getRigidBody2(), getMergeSplitHandler() );
const agx::Vec3 gravity = getMergeSplitHandler()->getSimulation()->getGravityField()->calculateGravity( otherRb->
getPosition() );
getMergeSplitHandler() );
otherRb,
ground,
gravityForce,
gravity,
*getMergeSplitHandler() );
if ( result.shouldSplit )
actions.
split( state, edge );
}
}
}
}
{
osg::Group* root = new osg::Group();
simulation->
add( ground );
groundHinge->setCompliance( 0 );
groundHinge->getMotor1D()->setCompliance( 2.0E-10 );
groundHinge->getMotor1D()->setEnable( true );
simulation->
add( groundHinge );
{
};
agx::Vec3 boxPosition( 10, -0.5 * 2.0 * numBoxes + 1.0, 1.5 );
createMaterial( box, i );
{
else
}, simulation, box, node );
}
{
groundHinge->getMotor1D()->setSpeed( hingeSpeed );
else if ( std::abs( groundHinge->getAngle() ) > 35.0 *
agx::DEG_TO_RAD &&
agx::sign( groundHinge->getAngle() ) ==
agx::sign( groundHinge->getMotor1D()->getSpeed() ) )
groundHinge->getMotor1D()->setSpeed( -groundHinge->getMotor1D()->getSpeed() );
}, simulation );
}
int main( int argc, char** argv )
{
"\tTutorial custom merge-split algorithms\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_driveTrain_combustionEngine.cpp
#include "tutorialUtils.h"
namespace {
{
public:
m_engine(engine), m_step(0.1)
{
}
bool keyboard(
int key,
unsigned int ,
float ,
float ,
bool keyDown)
{
if (keyDown) {
agx::Real throttle = m_engine->getThrottle();
}
}
return true;
}
return false;
}
private:
};
{
public:
m_engine(engine), m_actuator(actuator), m_app(app)
{
}
{
if (m_num == 5) {
m_num = 0;
std::stringstream stream;
stream << "Engine RPM: " << m_engine->getRPM() << " Wheel RPM: " << m_actuator->getInputShaft()->getRPM();
std::string text = stream.str();
m_app->getSceneDecorator()->
setText(0, text);
std::stringstream stream2;
stream2 << "Throttle: " << m_engine->getThrottle();
std::string text2 = stream2.str();
m_app->getSceneDecorator()->setText(1, text2);
}
else {
m_num += 1;
}
}
private :
int m_num = 0;
};
{
tireGeom->setMaterial(material);
sim->add(tire);
sim->add(hinge);
return hinge;
}
{
sim->add(contactMaterial);
floorGeom->setMaterial(groundMaterial);
sim->add(floor);
sim->add(carBody);
createWheel(
agx::Vec3(-0.2, -0.2, 0.1), carBody, tireMaterial, sim, root);
createWheel(
agx::Vec3(0.2, 0.2, 0.1), carBody, tireMaterial, sim, root);
createWheel(
agx::Vec3(0.2, -0.2, 0.1), carBody, tireMaterial, sim, root);
return rightHinge;
}
}
void runTutorial1()
{
std::cout << "\nTutorial 1: Demonstrating basic combustion engine creation.\n\n";
sim->add(powerLine);
engine->setIdleThrottleAngle(
agx::Real(0.15));
powerLine->add(engine);
engine->setEnable(true);
std::cout << "Time(s)\tVelocity(RPM)\tThrottle" << std::endl;
std::cout << "0 \t" << engine->getRPM() << "\t\t" << engine->getThrottle() << std::endl;
std::cout << "5.0 \t" << engine->getRPM() << "\t\t" << engine->getThrottle() << std::endl;
std::cout << "10.0 \t" << engine->getRPM() << "\t\t" << engine->getThrottle() << std::endl;
}
void runTutorial2()
{
std::cout << "\nTutorial 2: Demonstrating connecting combustion engine to other drive train components.\n\n";
sim->add(powerLine);
powerLine->add(engine);
engine->connect(gear);
gear->connect(shaft);
engine->setEnable(true);
agx::Real angle = engine->getMaxThrottleAngle();
engine->setThrottleAngle(angle);
std::cout << "Time(s)\tVelocity(RPM)\tThrottle" << std::endl;
std::cout << 5.0 << "\t" << shaft->getRPM() << "\t\t" << engine->getThrottle() << std::endl;
std::cout << 10.0 << "\t" << shaft->getRPM() << "\t\t" << engine->getThrottle() << std::endl;
}
{
osg::Group* root = new osg::Group();
std::cout << "\nTutorial 3: Drive a simple car with the combustion engine.\n\n";
powerLine->add(actuator);
powerLine->add(gear);
powerLine->add(engine);
engine->setEnable(true);
engine->connect(gear);
gear->connect(actuator);
KeyboardListener* keyboardListener = new KeyboardListener(engine);
sim->
add(keyboardListener);
EngineListener* engineListener = new EngineListener(engine, actuator, app);
sim->
add(engineListener);
}
int main(int argc, char** argv)
{
std::cout <<
"\tTutorial Combustion Engine\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
runTutorial1();
runTutorial2();
application->addScene(runTutorial3);
if (application->init(argc, argv))
return application->run();
}
catch (std::exception& e) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_driveTrain_ElectricMotor.cpp
void runTutorial1()
{
std::cout << "\nTutorial 1: Demonstrating basic electric motor creation.\n\n";
simulation->add(powerLine);
inductance);
motor->setVoltage(voltage);
powerLine->add(motor);
std::cout << "Time(s)\tAngular velocity(rad/s)" << std::endl;
std::cout << "0 \t" << motor->getAngularVelocity() << std::endl;
std::cout << 5.0 << " \t" << motor->getAngularVelocity() << std::endl;
for (int i = 15; i <= 60; i += 15) {
std::cout << i << " \t" << motor->getAngularVelocity() << std::endl;
}
}
void runTutorial2()
{
std::cout << "\nTutorial 2: Demonstrating using electric motor with other drive train components.\n\n";
simulation->add(powerLine);
inductance);
motor->setVoltage(voltage);
motor->connect(gear);
gear->connect(shaft);
powerLine->add(motor);
std::cout << " Engine RPM after 0.5 seconds : " << motor->getRPM() << " RPM." << std::endl;
std::cout << " Shaft RPM after 0.5 seconds : " << shaft->getRPM() << " RPM." << std::endl;
std::cout << " Gear torque exposure after 0.5 seconds : " << gear->getConstraint()->getCurrentForce() << " Nm." << std::endl;
std::cout << " Engine RPM after 5.0 seconds : " << motor->getRPM() << " RPM." << std::endl;
std::cout << " Shaft RPM after 5.0 seconds : " << shaft->getRPM() << " RPM." << std::endl;
std::cout << " Gear torque exposure after 5.0 seconds : " << gear->getConstraint()->getCurrentForce() << " Nm." << std::endl;
std::cout << " Engine RPM after 10.0 seconds : " << motor->getRPM() << " RPM." << std::endl;
std::cout << " Shaft RPM after 10.0 seconds : " << shaft->getRPM() << " RPM." << std::endl;
std::cout << " Gear torque exposure after 10.0 seconds : " << gear->getConstraint()->getCurrentForce() << " Nm." << std::endl;
}
int main(int , char** )
{
std::cout <<
"\tTutorial Electric Motor\n" <<
"\t--------------------------------\n\n" << std::endl;
runTutorial1();
runTutorial2();
return 0;
}
tutorial_energyManager.cpp
#include "tutorialUtils.h"
{
osg::Group* root = new osg::Group();
simulation->
add( sphere );
simulation->
add( hinge );
energyManager->add( hinge );
energyManager->add( sphere );
rbKineticEnergy ) );
auto rbKineticEnergyChange = energyManager->getKineticEnergyChange( sphere );
rbKineticEnergyChange ) );
auto rbPotentialChange = energyManager->getPotentialChange( sphere );
rbPotentialChange ) );
auto rbDissipation = energyManager->getDissipation( sphere );
rbDissipation ) );
auto hingePotentialChange = energyManager->getPotentialChange( hinge );
hingePotentialChange ) );
auto hingeDissipation = energyManager->getDissipation( hinge );
hingeDissipation ) );
};
printEnergy( simulation );
}
{
osg::Group* root = new osg::Group();
auto motor = prismatic->getMotor1D();
motor->setEnable( true );
motor->setSpeed( 0.1 );
auto range = prismatic->getRange1D();
range->setEnable( true );
range->setRange( 0, 0.5 );
simulation->
add( prismatic );
energyManager->add( prismatic );
auto motorPower = energyManager->getPower( motor );
auto motorDissipation = energyManager->getDissipation( motor );
};
printEnergy( simulation );
}
{
osg::Group* root = new osg::Group();
simulation->
add( powerLine );
simulation->
add( sphere );
simulation->
add( hinge );
inductance );
motor->connect( rotationalActuator );
powerLine->add( motor );
motor->setVoltage( 2.0 );
auto angularVelocity = motor->getAngularVelocity();
angularVelocity ) );
};
printEnergy( simulation );
}
int main( int argc, char** argv )
{
std::cout <<
"\tEnergyManager tutorial\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
application->addScene( buildTutorial3, '3' );
if ( application->init( argc, argv ) )
return application->run();
} catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_driveTrain.cpp
#include <agx/config/AGX_USE_WEBPLOT.h>
#if AGX_USE_WEBPLOT()
#endif
namespace
{
{
public:
: m_shaft( shaft )
{
}
{
if ( m_shaft == nullptr )
{
return result;
}
result.
value = m_shaft->getRPM( );
return result;
}
private:
};
{
public:
: m_connector(connector)
{
}
{
if (m_connector == nullptr)
{
return result;
}
if (m_connector->getConstraint()->getEnable())
result.
value = m_connector->getConstraint()->getCurrentForce();
else
result.
value = m_connector->getOutputConnections().front()->getDimension()->getOutputLoad();
return result;
}
private:
};
{
public:
: m_rotationalActuator(rotationalActuator)
{
}
{
if (m_rotationalActuator == nullptr)
{
return result;
}
return result;
}
private:
};
{
public:
: m_engine( engine )
{
}
{
if ( m_engine == nullptr )
{
return result;
}
return result;
}
private:
};
{
public:
: m_engine(engine)
{
}
{
if (m_engine == nullptr)
{
return result;
}
result.
value = m_engine->getPowerGenerator()->getPowerTimeIntegralLookupTable()->lookupCurrent() * m_engine->getThrottle();
return result;
}
private:
};
}
void runTutorial1(bool )
{
std::cout << "\nTutorial 1: Demonstrating basic drive train component creation and assembly." << std::endl;
simulation->add(powerLine);
shaft1->connect(gearA);
gearA->connect(shaft2);
powerLine->add(shaft1);
powerLine->add(shaft3);
shaft1->getRotationalDimension()->setGradient(initialAngularVelocity);
shaft3->getRotationalDimension()->setGradient(initialAngularVelocity);
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(0.5));
std::cout << "Angular velocities shaft 1, 2, 3 & 4:" << std::endl;
std::cout << " Shaft1 : " << shaft1->getRotationalDimension()->getGradient() << " rad/s." << std::endl;
std::cout << " Shaft2 : " << shaft2->getRotationalDimension()->getGradient() << " rad/s." << std::endl;
std::cout << " Shaft3 : " << shaft3->getRotationalDimension()->getGradient() << " rad/s." << std::endl;
std::cout << " Shaft4 : " << shaft4->getRotationalDimension()->getGradient() << " rad/s." << std::endl;
}
void runTutorial2(bool showPlots)
{
std::cout << "\nTutorial 2: Demonstrating creation and configuration of an Engine." << std::endl;
simulation->add(powerLine);
engine->setRPMTorqueTable(rpm_torque);
engine->getPowerGenerator()->getPowerTimeIntegralLookupTable()->setDefaultValue(defaultTorque);
engine->ignition( true );
heavilyDampedShaft->getRotationalDimension()->setVelocityDamping(
agx::Real(1000.0) );
heavilyDampedShaft->setInertia(
agx::Real( 100 ) );
engine->connect(gear100);
gear100->connect(heavilyDampedShaft);
powerLine->add(engine);
if (showPlots) {
rpmSeries->setUnit("RPM");
torqueSeries->setUnit("Nm");
plotWindow->
add(rpmCurve);
plotWindow->
add(gearTorqueCurve);
#if AGX_USE_WEBPLOT()
plotSystem->
add(
new agxPlot::WebPlot(
true));
#endif
}
std::cout << " Engine RPM after 0.5 seconds : " << engine->getRPM( ) << " RPM." << std::endl;
std::cout << " Gear torque exposure after 0.5 seconds : " << gear100->getConstraint()->getCurrentForce() << " RPM." << std::endl;
std::cout << " Engine RPM after 5.0 seconds : " << engine->getRPM( ) << " RPM." << std::endl;
std::cout << " Gear torque exposure after 5.0 seconds : " << gear100->getConstraint( )->getCurrentForce( ) << " RPM." << std::endl;
std::cout << " Engine RPM after 10.0 seconds : " << engine->getRPM( ) << " RPM." << std::endl;
std::cout << " Gear torque exposure after 10.0 seconds : " << gear100->getConstraint( )->getCurrentForce( ) << " RPM." << std::endl;
std::cout << "See web plot or 'EngineDrivingHeavyShaft.dat' for full picture of engine RPM and gear torque" << std::endl;
}
void runTutorial3(bool showPlots)
{
std::cout << "\nTutorial 3: Demonstrating creation and configuration of an RotationalActuator." << std::endl;
simulation->add(powerLine);
engine->getPowerGenerator( )->getPowerTimeIntegralLookupTable( )->setDefaultValue( defaultTorque );
engine->ignition(true);
simulation->add(ground);
simulation->add(propeller);
simulation->add(hinge);
simulation->setUniformGravity(
agx::Vec3(0, 0, 0));
engine->connect(gear);
gear->connect(rotationalActuator);
powerLine->add(engine);
if (showPlots) {
rpmSeries->setUnit("RPM");
torqueSeries->setUnit("Nm");
relRpmSeries->setUnit("RPM");
plotWindow->
add(rpmCurve);
plotWindow->
add(gearTorqueCurve);
plotWindow->
add(relRpmCurve);
#if AGX_USE_WEBPLOT()
plotSystem->
add(
new agxPlot::WebPlot(
true));
#endif
}
std::cout << " Engine RPM after 0.5 seconds : " << engine->getRPM() << " RPM." << std::endl;
std::cout << " Gear torque exposure after 0.5 seconds : " << gear->getConstraint()->getCurrentForce() << " Nm." << std::endl;
std::cout << " Engine RPM after 5 seconds : " << engine->getRPM() << " RPM." << std::endl;
std::cout << " Gear torque exposure after 5 seconds : " << gear->getConstraint()->getCurrentForce() << " Nm." << std::endl;
std::cout << " Engine RPM after 10 seconds : " << engine->getRPM() << " RPM." << std::endl;
std::cout << " Gear torque exposure after 10 seconds : " << gear->getConstraint()->getCurrentForce() << " Nm." << std::endl;
std::cout << "See web plot or 'EngineDrivingRotationalActuator.dat' for full picture of RPM and torque" << std::endl;
}
namespace
{
{
engine->setRPMTorqueTable(rpm_torque);
engine->ignition(true);
return engine;
}
{
simulation->
add(propeller);
return rotationalActuator;
}
}
void runTutorial4(bool showPlots)
{
std::cout << "\nTutorial 4: Demonstrating RpmController for Engine." << std::endl;
simulation->add( powerLine );
engine->connect(gear);
gear->connect(rotationalActuator);
simulation->setUniformGravity(
agx::Vec3( 0, 0, 0 ) );
powerLine->add( engine );
engine->setThrottleCalculator( rpmController );
if (showPlots) {
rpmSeries->setUnit( "RPM" );
torqueSeries->setUnit( "Nm" );
throttleSeries->setUnit( "%" );
plotWindow->
add( rpmCurve );
plotWindow->
add( gearTorqueCurve );
plotWindow->
add( throttleCurve );
#if AGX_USE_WEBPLOT()
plotSystem->
add(
new agxPlot::WebPlot(
true));
#endif
}
std::cout << " Engine RPM after 0.5 seconds : " << engine->getRPM( ) << " RPM." << std::endl;
std::cout << " Gear torque exposure after 0.5 seconds : " << gear->getConstraint( )->getCurrentForce( ) << " Nm." << std::endl;
std::cout <<
" Engine throttle 0.5 seconds : " << engine->getThrottle()*
agx::Real(100) <<
"%" << std::endl;
std::cout << " Engine RPM after 5 seconds : " << engine->getRPM( ) << " RPM." << std::endl;
std::cout << " Gear torque exposure after 5 seconds : " << gear->getConstraint( )->getCurrentForce( ) << " Nm." << std::endl;
std::cout <<
" Engine throttle 5 seconds : " << engine->getThrottle( )*
agx::Real( 100 ) <<
"%" << std::endl;
std::cout << " Engine RPM after 10 seconds : " << engine->getRPM( ) << " RPM." << std::endl;
std::cout << " Gear torque exposure after 10 seconds : " << gear->getConstraint( )->getCurrentForce( ) << " Nm." << std::endl;
std::cout <<
" Engine throttle 10 seconds : " << engine->getThrottle( )*
agx::Real( 100 ) <<
"%" << std::endl;
std::cout << " Engine RPM after 20 seconds : " << engine->getRPM() << " RPM." << std::endl;
std::cout << " Gear torque exposure after 20 seconds : " << gear->getConstraint()->getCurrentForce() << " Nm." << std::endl;
std::cout <<
" Engine throttle 20 seconds : " << engine->getThrottle()*
agx::Real(100) <<
"%" << std::endl;
std::cout << "See web plot or 'EngineThrottle.dat' for full picture of RPM, torque and engine throttle." << std::endl;
}
namespace
{
{
}
}
void runTutorial5(bool showPlots)
{
std::cout << "\nTutorial 5: Demonstrating TorqueConverter functionality." << std::endl;
simulation->add(powerLine);
simulation->setUniformGravity(
agx::Vec3(0, 0, 0));
createRpmControllerAndInternalRotationalActuatorResistance(engine, rotationalActuator, constantFrictionForce);
torqueConverter->setEfficiencyTable(velRatio_efficiency);
engine->connect(torqueConverter);
torqueConverter->connect(rotationalActuator);
powerLine->add(engine);
torqueConverter->enableLockUp(true);
torqueConverter->enableLockUp(false);
if (showPlots) {
rpmSeries->setUnit("RPM");
torqueSeries->setUnit("Nm");
relRpmSeries->setUnit("RPM");
engineTorqueSeries->setUnit("Nm");
plotWindow->
add(rpmCurve);
plotWindow->
add(gearTorqueCurve);
plotWindow->
add(relRpmCurve);
plotWindow->
add(engineTorqueCurve);
#if AGX_USE_WEBPLOT()
plotSystem->
add(
new agxPlot::WebPlot(
true));
#endif
}
std::cout << " Engine RPM after 0.5 seconds : " << engine->getRPM() << " RPM." << std::endl;
std::cout << " Converter torque after 0.5 seconds : " << torqueConverter->getTurbineTorque() << " Nm." << std::endl;
std::cout << " Engine RPM after 2 seconds : " << engine->getRPM() << " RPM." << std::endl;
std::cout << " Converter torque after 2 seconds : " << torqueConverter-> getTurbineTorque() << " Nm." << std::endl;
std::cout << " Engine RPM after 4 seconds : " << engine->getRPM() << " RPM." << std::endl;
std::cout << " Converter torque after 4 seconds : " << torqueConverter->getTurbineTorque() << " Nm." << std::endl;
std::cout << " Engine RPM after 6 seconds : " << engine->getRPM() << " RPM." << std::endl;
std::cout << " Converter torque after 6 seconds : " << torqueConverter->getTurbineTorque() << " Nm." << std::endl;
std::cout << "See web plot or 'TorqueConverter.dat' for full picture of RPM and torque." << std::endl;
}
void runTutorial6(bool showPlots)
{
std::cout << "\nTutorial 6: Demonstrating Clutch functionality." << std::endl;
simulation->add(powerLine);
simulation->setUniformGravity(
agx::Vec3(0, 0, 0));
createRpmControllerAndInternalRotationalActuatorResistance(engine, rotationalActuator, constantFrictionForce);
engine->connect(clutch);
clutch->connect(rotationalActuator);
powerLine->add(engine);
if (showPlots) {
rpmSeries->setUnit("RPM");
torqueSeries->setUnit("Nm");
relRpmSeries->setUnit("RPM");
engineTorqueSeries->setUnit("Nm");
plotWindow->
add(rpmCurve);
plotWindow->
add(gearTorqueCurve);
plotWindow->
add(relRpmCurve);
plotWindow->
add(engineTorqueCurve);
#if AGX_USE_WEBPLOT()
plotSystem->
add(
new agxPlot::WebPlot(
true));
#endif
}
for (size_t i = 0; i < 600; ++i)
{
if (i % 100 == 0)
{
std::cout <<
" Engine RPM after" <<
agx::Real(i) /
agx::Real(60) <<
" seconds : " << engine->getRPM() <<
" RPM." << std::endl;
std::cout <<
" Clutch after" <<
agx::Real(i) /
agx::Real(60) <<
" seconds : " << clutch->getConstraint()->getCurrentForce() <<
" Nm." << std::endl;
std::cout <<
" Engine torque applied after" <<
agx::Real(i) /
agx::Real(60) <<
" seconds : " << engine->getPowerGenerator()->getPowerTimeIntegralLookupTable()->lookupCurrent() <<
" RPM." << std::endl;
}
simulation->stepForward();
}
}
void runTutorial7(bool showPlots)
{
std::cout << "\nTutorial 7: Demonstrating GearBox functionality." << std::endl;
simulation->add(powerLine);
simulation->setUniformGravity(
agx::Vec3(0, 0, 0));
createRpmControllerAndInternalRotationalActuatorResistance(engine, rotationalActuator, constantFrictionForce);
gearBox->setGearRatios(gearRatios);
engine->connect(gearBox);
gearBox->connect(rotationalActuator);
powerLine->add(engine);
if (showPlots) {
rpmSeries->setUnit("RPM");
torqueSeries->setUnit("Nm");
relRpmSeries->setUnit("RPM");
plotWindow->
add(rpmCurve);
plotWindow->
add(gearTorqueCurve);
plotWindow->
add(relRpmCurve);
#if AGX_USE_WEBPLOT()
plotSystem->
add(
new agxPlot::WebPlot(
true));
#endif
}
gearBox->setGear(1);
for (size_t i = 1; i < 600; ++i)
{
if (i % 100 == 0)
{
int gear = static_cast<int>(i) / 100;
std::cout << "using gear [" << i << "] with gear ratio " << gearBox->getGearRatio(gear) << std::endl;
gearBox->setGear(gear);
std::cout <<
" Engine RPM after" <<
agx::Real(i) /
agx::Real(60) <<
" seconds : " << engine->getRPM() <<
" RPM." << std::endl;
std::cout <<
" GearBox after" <<
agx::Real(i) /
agx::Real(60) <<
" seconds : " << gearBox->getConstraint()->getCurrentForce() <<
" Nm." << std::endl;
}
simulation->stepForward();
}
}
void runTutorial8(bool showPlots)
{
std::cout << "\nTutorial 8: Demonstrating Differential functionality." << std::endl;
simulation->add(powerLine);
simulation->setUniformGravity(
agx::Vec3(0, 0, 0));
createRpmControllerAndInternalRotationalActuatorResistance(engine, rotationalActuator, constantFrictionForce);
powerLine->add(engine);
if (showPlots) {
rpmSeries->setUnit("RPM");
relRpmSeries->setUnit("RPM");
relRpm2Series->setUnit("RPM");
plotWindow->
add(rpmCurve);
plotWindow->
add(relRpmCurve);
plotWindow->
add(relRpm2Curve);
#if AGX_USE_WEBPLOT()
plotSystem->
add(
new agxPlot::WebPlot(
true));
#endif
}
for (size_t i = 0; i < 600; ++i)
{
if (i % 100 == 0)
{
std::cout <<
" Engine RPM after" <<
agx::Real(i) /
agx::Real(60) <<
" seconds : " << engine->getRPM() <<
" RPM." << std::endl;
}
simulation->stepForward();
}
}
int main(int argc, char** )
{
std::cout <<
"\tTutorial Hydraulics\n" <<
"\t--------------------------------\n\n" << std::endl;
bool showPlots = argc <= 1;
runTutorial1(showPlots);
runTutorial2(showPlots);
runTutorial3(showPlots);
runTutorial4(showPlots);
runTutorial5(showPlots);
runTutorial6(showPlots);
runTutorial7(showPlots);
runTutorial8(showPlots);
return 0;
}
tutorial_fracture.cpp
{
osg::Group* root = new osg::Group;
simulation->
add(matIter);
geomPlane->setPosition(
Vec3(0, 0, -.5));
simulation->
add(geomPlane);
geomPlane->setMaterial(matIter);
geom->setMaterial(matIter);
simulation->
add(staticWireHolder);
wire->setMaterial(wireMaterial);
simulation->
add(wireRenderer);
wireRenderer->setColor(
agx::Vec4f(.75f, .75f, 0, 1));
fracture->setFractureMinimumSize(.1);
fracture->setNumFractureFragmentsInterval(50, 100);
simulation->
add(fracture);
size_t numWalls = 3;
for (size_t i = 0; i < numWalls; ++i)
{
wallGeom->setPosition(
Vec3(-4 +
Real(i), 0, wallWec.
z()));
simulation->
add(wallGeom);
wallGeom->setMaterial(matIter);
fracture->addBreakable(wallGeom);
}
fracture->addBreaker(geom);
{
};
fracture->setNewBodyCallback(callback);
}
{
osg::Group* root = new osg::Group;
simulation->
add(matIter);
geomPlane->setPosition(
Vec3(0, 0, -.5));
simulation->
add(geomPlane);
geomPlane->setMaterial(matIter);
fracture->setFractureMinimumSize(.1);
fracture->setNumFractureFragmentsInterval(10, 20);
simulation->
add(fracture);
fracture->addBreaker(geomPlane);
fracture->setAddFractureFragmentsToGenerator(false);
std::vector<std::string> rocks = {
"data\\models\\convex_stones\\convex_rock2.obj",
"data\\models\\convex_stones\\convex_rock3.obj",
"data\\models\\convex_stones\\convex_rock4.obj",
"data\\models\\convex_stones\\convex_rock5.obj",
"data\\models\\convex_stones\\convex_rock6.obj"
};
for (size_t i = 0; i < 10; ++i)
{
std::string sRock = rocks[agx::random<int>(0, static_cast<int>(rocks.size() - 1))];
rockRef->setMaterial(matIter);
Vec3 spawnVec = floorVec; spawnVec.
z() = 0;
fracture->addBreakable(rockRef);
}
{
};
fracture->setNewBodyCallback(callback);
}
{
osg::Group* root = new osg::Group;
simulation->
add(matIter);
geomPlane->setPosition(
Vec3(0, 0, -.5));
simulation->
add(geomPlane);
geomPlane->setMaterial(matIter);
fracture->setFractureMinimumSize(.5);
fracture->setNumFractureFragmentsInterval(2, 5);
simulation->
add(fracture);
fracture->addBreaker(geomPlane);
fracture->setAddFractureFragmentsToGenerator(true);
agx::String rock =
"data\\models\\convex_stones\\convex_rock2.obj";
rockRef->setMaterial(matIter);
fracture->addBreakable(rockRef);
{
};
fracture->setNewBodyCallback(callback);
}
{
osg::Group* root = new osg::Group;
simulation->
add(matIter);
geomPlane->setPosition(
Vec3(0, 0, -.5));
simulation->
add(geomPlane);
geomPlane->setMaterial(matIter);
fracture->setFractureMinimumSize(.1);
fracture->setNumFractureFragmentsInterval(10, 20);
simulation->
add(fracture);
fracture->addBreaker(geomPlane);
fracture->setAddFractureFragmentsToGenerator(true);
rockRef->setMaterial(matIter);
fracture->addBreakable(rockRef);
{
};
fracture->setNewBodyCallback(callback);
}
{
osg::Group* root = new osg::Group;
simulation->
add(matIter);
geomPlane->setPosition(
Vec3(0, 0, -.5));
simulation->
add(geomPlane);
geomPlane->setMaterial(matIter);
generator->setResolution(0.75);
auto fractureShape = [generator, simulation, matIter,
root](
const Vec3& posForFragments,
const Quat& rotForFragments)
{
std::cout <<
"3D Voronoi diagram of shape type '"<< shapeToFracture->getTypeName() <<
" took " << timer.
getTime() <<
" ms to compute."<< std::endl;
std::cout << "# Voronoi cells: " << data.size() << std::endl;
for (auto& cell : data)
{
volume += convex->getVolume();
geom->setMaterial(matIter);
simulation->add(rb);
}
Real oldVolume = shapeToFracture->getVolume();
Real relDiff = ((oldVolume - volume) / oldVolume) *
Real(100.0);
std::cout << "Relative volume difference: " << relDiff << " %" << std::endl;
};
}
int main(int argc, char** argv)
{
int status = 0;
"\tRigidBody demonstrator\n" <<
"\t--------------------------------\n\n" <<
LOGGER_END();
try {
application->addScene(buildTutorial1, '1');
application->addScene(buildTutorial2, '2');
application->addScene(buildTutorial3, '3');
application->addScene(buildTutorial4, '4');
application->addScene(buildTutorial5, '5');
if (application->init(argc, argv)) {
status = application->run();
}
}
catch (std::exception& e) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return status;
}
tutorial_frictionModels.cpp
{
osg::Group *root = new osg::Group;
simulation->
add( ground );
enum FrictionModelType { BOX, SCALE_BOX, ITERATIVE_PROJECTED };
FrictionModelType modelType = ITERATIVE_PROJECTED;
if ( modelType == BOX )
else if ( modelType == SCALE_BOX )
else if ( modelType == ITERATIVE_PROJECTED )
}
{
public:
GivenNormalForceBoxFrictionModel()
void setNormalForce(
Real normalForce )
{
m_normalForce = normalForce;
}
Real getNormalForce()
const {
return m_normalForce; }
virtual void calculateTangentPlane(
const agxCollide::Geometry* geometry1,
const agxCollide::Geometry* geometry2,
const Vec3& point,
const Vec3& normal,
const Real depth,
Vec3& ret_u,
Vec3& ret_v )
const override {
renderDirection( point, ret_u, ret_v );
}
virtual Real calculateNormalForce(
const agxCollide::Geometry* ,
const agxCollide::Geometry* ,
const Vec3& ,
const Vec3& ,
const Real ,
const Real ,
const size_t numPoints )
const override {
return getNormalForce() /
Real( numPoints );
}
protected:
virtual ~GivenNormalForceBoxFrictionModel() {}
void renderDirection(
const Vec3& point,
const Vec3& u,
const Vec3& v )
const {
}
protected:
};
class OrientedBoxGivenNormalForceBoxFrictionModel : public GivenNormalForceBoxFrictionModel
{
public:
OrientedBoxGivenNormalForceBoxFrictionModel(
RigidBody* rb,
const Vec3& primaryDirection )
: m_rb( rb ), m_primaryDirection( primaryDirection ) {}
protected:
OrientedBoxGivenNormalForceBoxFrictionModel() : m_rb( 0L ), m_primaryDirection() {}
virtual ~OrientedBoxGivenNormalForceBoxFrictionModel() {}
virtual void calculateTangentPlane(
const agxCollide::Geometry* geometry1,
const agxCollide::Geometry* geometry2,
const Vec3& point,
const Vec3& normal,
const Real depth,
Vec3& ret_u,
Vec3& ret_v )
const override {
ret_u = m_rb->getFrame()->transformVectorToWorld( m_primaryDirection );
ret_u -= normal * ( normal * ret_u );
return;
}
ret_v = normal ^ ret_u;
renderDirection( point, ret_u, ret_v );
}
protected:
};
{
}
{
}
void OrientedBoxGivenNormalForceBoxFrictionModel::store(
OutputArchive&
out )
const {
GivenNormalForceBoxFrictionModel::store( out );
}
void OrientedBoxGivenNormalForceBoxFrictionModel::restore(
InputArchive&
in )
{
GivenNormalForceBoxFrictionModel::restore( in );
m_rb = rb;
}
{
osg::Group *root = new osg::Group;
simulation->
add( ground );
simulation->
add( groundBox1ContactMaterial );
simulation->
add( groundBox2ContactMaterial );
GivenNormalForceBoxFrictionModel* box1FrictionModel = new GivenNormalForceBoxFrictionModel();
OrientedBoxGivenNormalForceBoxFrictionModel* box2FrictionModel =
new OrientedBoxGivenNormalForceBoxFrictionModel( box2,
Vec3( 1, 0, 0 ) );
}
int main( int argc, char** argv )
{
std::cout <<
"\tFriction model tutorial\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_gravityFields.cpp
#include "tutorialUtils.h"
{
agx::Vec3 currentPos(-boxLength * numBoxesAtBottomRow, 0.0, boxHeight);
for (int i = numBoxesAtBottomRow; i > 0; --i) {
for (int j = i; j > 0; --j) {
if (boxMass > 0)
currentPos.x() += (
agx::Real)2.0 * boxLength + eps;
}
currentPos.x() = boxLength * (-i + 1);
currentPos.z() += (
agx::Real)2.0 * boxHeight + eps;
}
return parent;
}
{
osg::Group* root = new osg::Group();
agx::Vec3 boxGeometryHalfExtent( 3, 3, 0.5 );
boxGeometry->setPosition( boxGeometry->getPosition() -
agx::Vec3( 0, 0, boxGeometryHalfExtent.z() ) );
simulation->
add( boxGeometry );
simulation->
add( parent );
gravityField->setGravity(
agx::Vec3(0, 0, -9.81));
}
{
osg::Group* root = new osg::Group();
gravityField->setGravity(9.81);
}
{
public:
MyGravityField() {}
{
return position*-1;
}
protected:
~MyGravityField() {}
};
{
osg::Group* root = new osg::Group();
}
int main( int argc, char** argv )
{
std::cout <<
"\nGravityModel tutorial\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
application->addScene( buildTutorial3, '3', false );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_hydraulics.cpp
void runTutorial1()
{
std::cout << "\nTutorial 1: Demonstrating basic hydraulic component creation and assembly." << std::endl;
simulation->add(powerLine);
shortMediumCoupling->connect(INPUT, OUTPUT, shortPipe);
shortMediumCoupling->connect(OUTPUT, INPUT, mediumPipe);
mediumPipe->connect(longPipe);
mediumLongCoupling = longPipe->getInputFlowConnector();
powerLine->setSource(shortPipe);
shortPipe->getFlowDimension()->setGradient(initialFlowRate);
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(0.5));
std::cout << "Flow rates throug the three pipes:" << std::endl;
std::cout << " Short pipe flow rate: " << shortPipe->getFlowRate() << " m^3/s." << std::endl;
std::cout << " Medium pipe flow rate: " << mediumPipe->getFlowRate() << " m^3/s." << std::endl;
std::cout << " Long pipe flow rate: " << longPipe->getFlowRate() << " m^3/s." << std::endl;
mediumLongCoupling->connect(OUTPUT, INPUT, secondLongPipe);
shortPipe->getFlowDimension()->setGradient(initialFlowRate);
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(0.5));
std::cout << "Flow rates after connecting the second long pipe:" << std::endl;
std::cout << " Short pipe flow rate: " << shortPipe->getFlowRate() << " m^3/s." << std::endl;
std::cout << " Medium pipe flow rate: " << mediumPipe->getFlowRate() << " m^3/s." << std::endl;
std::cout << " Long pipe flow rate: " << longPipe->getFlowRate() << " m^3/s." << std::endl;
std::cout << " Second long pipe flow rate: " << secondLongPipe->getFlowRate() << " m^3/s." << std::endl;
std::cout << " Sum flow in long pipes: " << longPipe->getFlowRate()+secondLongPipe->getFlowRate() <<" m^3/s." << std::endl;
}
void runTutorial2()
{
std::cout << "\nTutorial 2: Demonstrating pressure generation using an engine and a pump." << std::endl;
simulation->add(powerLine);
powerLine->add(engine);
pump->connect(INPUT, OUTPUT, engine);
pump->connect(OUTPUT, INPUT, shortPipe);
shortMediumConnector->connect(INPUT, OUTPUT, shortPipe);
shortMediumConnector->connect(OUTPUT, INPUT, mediumPipe);
mediumLongConnector->connect(INPUT, OUTPUT, mediumPipe);
mediumLongConnector->connect(OUTPUT, INPUT, longPipe);
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(20));
std::cout << "Connector pressures with pump at start:" << std::endl;
std::cout << " Pump pressure: " << pump->getPressure() << std::endl;
std::cout << " Short-to-medium: " << shortMediumConnector->getPressure() << std::endl;
std::cout << " Medium-to-long: " << mediumLongConnector->getPressure() << std::endl;
std::cout << " Flow rate: " << longPipe->getFlowRate() << std::endl;
tankShortConnector->connect(INPUT, OUTPUT, tankPipe);
tankShortConnector->connect(OUTPUT, INPUT, shortPipe);
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(10));
std::cout << "Connector pressures with tank pipe at start:" << std::endl;
std::cout << " Pump inlet pressure: " << tankShortConnector->getPressure() << std::endl;
std::cout << " Pump pressure: " << pump->getPressure() << std::endl;
std::cout << " Pump outlet pressure: " << shortMediumConnector->getPressure() << std::endl;
std::cout << " Medium-to-long: " << mediumLongConnector->getPressure() << std::endl;
std::cout << " Flow rate: " << longPipe->getFlowRate() << std::endl;
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(10));
std::cout << "Connector pressures with tank pipe at start and tank pressure:" << std::endl;
std::cout << " Pump inlet pressure: " << tankShortConnector->getPressure() << std::endl;
std::cout << " Pump pressure: " << pump->getPressure() << std::endl;
std::cout << " Pump outlet pressure: " << shortMediumConnector->getPressure() << std::endl;
std::cout << " Medium-to-long: " << mediumLongConnector->getPressure() << std::endl;
std::cout << " Flow rate: " << longPipe->getFlowRate() << std::endl;
std::cout << "Loads:" << std::endl;
std::cout << " TankPipe in: " << tankPipe->getFlowDimension()->getInputLoad() << std::endl;
std::cout << " TankPipe out: " << tankPipe->getFlowDimension()->getOutputLoad() << std::endl;
std::cout << " ShortPipe in: " << shortPipe->getFlowDimension()->getInputLoad() << std::endl;
std::cout << " ShortPipe out: " << shortPipe->getFlowDimension()->getOutputLoad() << std::endl;
std::cout << " MediumPipe in: " << mediumPipe->getFlowDimension()->getInputLoad() << std::endl;
std::cout << " MediumPipe out: " << mediumPipe->getFlowDimension()->getOutputLoad() << std::endl;
std::cout << " LongPipe in: " << longPipe->getFlowDimension()->getInputLoad() << std::endl;
std::cout << " LongPipe out: " << longPipe->getFlowDimension()->getOutputLoad() << std::endl;
}
namespace Tutorial_3
{
class Mechanics
{
public:
{
this->createFloor(simulation);
this->createCylinderBodies(simulation);
this->createPrismatic(simulation);
}
{
return m_base;
}
{
return m_head;
}
{
return m_prismatic;
}
private:
{
m_floor->setPosition(pos);
simulation->
add(m_floor);
}
{
m_base->setPosition(basePos);
m_head->setPosition(headPos);
}
{
simulation->
add(m_prismatic);
}
private:
};
}
void runTutorial3()
{
std::cout << "\nTutorial 3: Connection to mechanical system and more hydraulic components." << std::endl;
using namespace Tutorial_3;
Mechanics mechanics(simulation);
simulation->add(powerLine);
powerLine->add(inputPipe);
cylinderRange.
lower() = mechanics.getHead()->getPosition().z() - mechanics.getBase()->getPosition().z();
mechanics.getJoint()->getRange1D()->setRange(cylinderRange);
mechanics.getJoint()->getRange1D()->setEnable(true);
inputPipe->connect(cylinder);
cylinder->connect(outputPipe);
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(1));
std::cout << "At rest:" << std::endl;
std::cout << " Input pressure: " << inputPipe->getOutputFlowConnector()->getPressure() << std::endl;
std::cout << " Output pressure: " << outputPipe->getInputFlowConnector()->getPressure() << std::endl;
std::cout << " Input flow rate: " << inputPipe->getFlowRate() << std::endl;
std::cout << " Output flow rate: " << outputPipe->getFlowRate() << std::endl;
controlOutput->connect(INPUT, OUTPUT, flowRateControl);
controlOutput->connect(OUTPUT, INPUT, inputPipe);
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(1));
std::cout << "With passive constant flow valve:" << std::endl;
std::cout << " Input pressure: " << inputPipe->getOutputFlowConnector()->getPressure() << std::endl;
std::cout << " Output pressure: " << outputPipe->getInputFlowConnector()->getPressure() << std::endl;
std::cout << " Input flow rate: " << inputPipe->getFlowRate() << std::endl;
std::cout << " Output flow rate: " << outputPipe->getFlowRate() << std::endl;
flowRateControl->setAllowPumping(true);
simulation->stepForward();
std::cout << "One time step of active constant flow valve:" << std::endl;
std::cout << " Input pressure: " << inputPipe->getOutputFlowConnector()->getPressure() << std::endl;
std::cout << " Output pressure: " << outputPipe->getInputFlowConnector()->getPressure() << std::endl;
std::cout << " Input flow rate: " << inputPipe->getFlowRate() << std::endl;
std::cout << " Output flow rate: " << outputPipe->getFlowRate() << std::endl;
flowRateControl->setEnable(false);
flowRateControl->getFlowDimension()->setGradient(
agx::Real(0));
inputPipe->getFlowDimension()->setGradient(
agx::Real(0));
cylinder->getFrontChamber()->getFlowDimension()->setGradient(
agx::Real(0));
cylinder->getRearChamber()->getFlowDimension()->setGradient(
agx::Real(0));
outputPipe->getFlowDimension()->setGradient(
agx::Real(0));
mechanics.getBase()->setVelocity(
agx::Vec3());
mechanics.getHead()->setVelocity(
agx::Vec3());
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(1));
controlOutput->disconnect(inputPipe);
controlOutput->connect(OUTPUT, INPUT, reliefValve);
inpipeInput->connect(INPUT, OUTPUT, reliefValve);
inpipeInput->connect(OUTPUT, INPUT, inputPipe);
flowRateControl->setEnable(true);
simulation->stepForward();
std::cout << "One time step of active constant flow valve with relief valve:" << std::endl;
std::cout << " Input pressure: " << inputPipe->getOutputFlowConnector()->getPressure() << std::endl;
std::cout << " Output pressure: " << outputPipe->getInputFlowConnector()->getPressure() << std::endl;
std::cout << " Input flow rate: " << inputPipe->getFlowRate() << std::endl;
std::cout << " Output flow rate: " << outputPipe->getFlowRate() << std::endl;
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(1));
std::cout << "With relief valve:" << std::endl;
std::cout << " Input pressure: " << inputPipe->getOutputFlowConnector()->getPressure() << std::endl;
std::cout << " Output pressure: " << outputPipe->getInputFlowConnector()->getPressure() << std::endl;
std::cout << " Input flow rate: " << inputPipe->getFlowRate() << std::endl;
std::cout << " Output flow rate: " << outputPipe->getFlowRate() << std::endl;
}
void runTutorial4()
{
std::cout << "\nTutorial 4: Flow control using spool valve." << std::endl;
simulation->add(powerLine);
pump->getFlowDimension()->setName("PressureSource");
pump->setAllowPumping(true);
powerLine->add(pump);
pump->connect(relief);
pumpPipe->getFlowDimension()->setName("Pump");
forwardPipe->getFlowDimension()->setName("Forward");
backwardPipe->getFlowDimension()->setName("Backward");
tankPipe->getFlowDimension()->setName("Tank");
relief->connect(pumpPipe);
spool->connect(INPUT, OUTPUT, pumpPipe);
spool->connect(OUTPUT, INPUT, forwardPipe);
spool->connect(OUTPUT, INPUT, backwardPipe);
spool->connect(INPUT, INPUT, tankPipe);
coupling->connect(INPUT, OUTPUT, forwardPipe);
coupling->connect(OUTPUT, OUTPUT, backwardPipe);
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(1));
std::cout << "= Flow is blocked at spool valve." << std::endl;
std::cout << " Pump flow rate: " << pumpPipe->getFlowRate() << std::endl;
std::cout << " Forward flow rate: " << forwardPipe->getFlowRate() << std::endl;
std::cout << " Backward flow rate: " << backwardPipe->getFlowRate() << std::endl;
std::cout << " Tank flow rate: " << tankPipe->getFlowRate() << std::endl;
spool->link(pumpPipe, forwardPipe);
spool->link(tankPipe, backwardPipe);
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(3));
std::cout << "= Forward flow." << std::endl;
std::cout << " Pump flow rate: " << pumpPipe->getFlowRate() << std::endl;
std::cout << " Forward flow rate: " << forwardPipe->getFlowRate() << std::endl;
std::cout << " Backward flow rate:" << backwardPipe->getFlowRate() << std::endl;
std::cout << " Tank flow rate: " << tankPipe->getFlowRate() << std::endl;
spool->unlink(pumpPipe);
spool->unlink(tankPipe);
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(3));
std::cout << "= Flow is blocked at spool valve." << std::endl;
std::cout << " Pump flow rate: " << pumpPipe->getFlowRate() << std::endl;
std::cout << " Forward flow rate: " << forwardPipe->getFlowRate() << std::endl;
std::cout << " Backward flow rate: " << backwardPipe->getFlowRate() << std::endl;
std::cout << " Tank flow rate: " << tankPipe->getFlowRate() << std::endl;
spool->link(pumpPipe, backwardPipe);
spool->link(tankPipe, forwardPipe);
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(3));
std::cout << "= Backward flow." << std::endl;
std::cout << " Pump flow rate: " << pumpPipe->getFlowRate() << std::endl;
std::cout << " Forward flow rate: " << forwardPipe->getFlowRate() << std::endl;
std::cout << " Backward flow rate: " << backwardPipe->getFlowRate() << std::endl;
std::cout << " Tank flow rate: " << tankPipe->getFlowRate() << std::endl;
spool->unlink(forwardPipe);
spool->link(tankPipe, backwardPipe);
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(3));
std::cout << "= Flow to tank." << std::endl;
std::cout << " Pump flow rate: " << pumpPipe->getFlowRate() << std::endl;
std::cout << " Forward flow rate: " << forwardPipe->getFlowRate() << std::endl;
std::cout << " Backward flow rate: " << backwardPipe->getFlowRate() << std::endl;
std::cout << " Tank flow rate: " << tankPipe->getFlowRate() << std::endl;
}
namespace tutorial_5
{
class FourWayThreePositionSpoolValve
{
public:
FourWayThreePositionSpoolValve(
m_in1(in1), m_in2(in2),
m_out1(out1), m_out2(out2),
{
bool connected = true;
this->linkNone();
}
void linkNone()
{
m_spool->unlink(m_in1);
m_spool->unlink(m_in2);
agxVerify(m_spool->getNumLinks() == size_t(0));
}
void linkParallel()
{
this->linkNone();
m_spool->link(m_in1, m_out1);
m_spool->link(m_in2, m_out2);
agxVerify(m_spool->getNumLinks() == size_t(2));
}
void linkCross()
{
this->linkNone();
m_spool->link(m_in1, m_out2);
m_spool->link(m_in2, m_out1);
agxVerify(m_spool->getNumLinks() == size_t(2));
}
private:
};
}
void runTutorial5()
{
std::cout << "\nTutorial 5: Flow control using wrapped spool valve." << std::endl;
simulation->add(powerLine);
pump->getFlowDimension()->setName("PressureSource");
pump->setAllowPumping(true);
powerLine->add(pump);
pump->connect(relief);
pumpPipe->getFlowDimension()->setName("Pump");
forwardPipe->getFlowDimension()->setName("Forward");
backwardPipe->getFlowDimension()->setName("Backward");
tankPipe->getFlowDimension()->setName("Tank");
relief->connect(pumpPipe);
tutorial_5::FourWayThreePositionSpoolValve spool(
pumpPipe, OUTPUT,
tankPipe, INPUT,
forwardPipe, INPUT,
backwardPipe, INPUT);
coupling->connect(INPUT, OUTPUT, forwardPipe);
coupling->connect(OUTPUT, OUTPUT, backwardPipe);
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(3));
std::cout << "= Flow blocked at spool valve." << std::endl;
std::cout << " Pump flow rate: " << pumpPipe->getFlowRate() << std::endl;
std::cout << " Forward flow rate: " << forwardPipe->getFlowRate() << std::endl;
std::cout << " Backward flow rate: " << backwardPipe->getFlowRate() << std::endl;
std::cout << " Tank flow rate: " << tankPipe->getFlowRate() << std::endl;
spool.linkParallel();
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(3));
std::cout << "= Forward flow." << std::endl;
std::cout << " Pump flow rate: " << pumpPipe->getFlowRate() << std::endl;
std::cout << " Forward flow rate: " << forwardPipe->getFlowRate() << std::endl;
std::cout << " Backward flow rate: " << backwardPipe->getFlowRate() << std::endl;
std::cout << " Tank flow rate: " << tankPipe->getFlowRate() << std::endl;
spool.linkNone();
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(3));
std::cout << "= Flow blocked at spool valve." << std::endl;
std::cout << " Pump flow rate: " << pumpPipe->getFlowRate() << std::endl;
std::cout << " Forward flow rate: " << forwardPipe->getFlowRate() << std::endl;
std::cout << " Backward flow rate: " << backwardPipe->getFlowRate() << std::endl;
std::cout << " Tank flow rate: " << tankPipe->getFlowRate() << std::endl;
spool.linkCross();
simulation->stepTo(simulation->getTimeStamp() +
agx::Real(3));
std::cout << "= Backward flow." << std::endl;
std::cout << " Pump flow rate: " << pumpPipe->getFlowRate() << std::endl;
std::cout << " Forward flow rate: " << forwardPipe->getFlowRate() << std::endl;
std::cout << " Backward flow rate: " << backwardPipe->getFlowRate() << std::endl;
std::cout << " Tank flow rate: " << tankPipe->getFlowRate() << std::endl;
}
int main(int , char** )
{
std::cout <<
"\tTutorial Hydraulics\n" <<
"\t--------------------------------\n\n" << std::endl;
runTutorial1();
runTutorial2();
runTutorial3();
runTutorial4();
runTutorial5();
return 0;
}
tutorial_hydraulics_coupling.cpp
#include "HydraulicUtils.h"
class RotationalUnitInterface
{
public:
protected:
private:
};
class EngineInterface : public RotationalUnitInterface
{
public:
};
class PropellerInterface : public RotationalUnitInterface
{
public:
};
class ClutchInterface
{
public:
private:
};
class GearBoxInterface
{
public:
private:
};
{
public:
EngineInterface engine, PropellerInterface propeller,
ClutchInterface pumpClutch, GearBoxInterface pumpGearBox,
ClutchInterface propellerClutch, GearBoxInterface propellerGearBox);
protected:
virtual void updateEngineAgxState();
virtual void collectEngineAgxState();
virtual void updatePropellerAgxState();
virtual agx::Real calculatePropellerTorque();
virtual agx::Real calculatePropellerInertia();
virtual void collectPropellerAgxState();
private:
EngineInterface m_engine;
PropellerInterface m_propeller;
ClutchInterface m_pumpClutch;
GearBoxInterface m_pumpGearBox;
ClutchInterface m_propellerClutch;
GearBoxInterface m_propellerGearBox;
};
struct Foundation
{
StatsPrinter* printer;
bool writeToDisk;
};
class Scene
{
public:
Scene();
void construct(const Foundation& foundation);
public:
private:
void constructMechanics(const Foundation& foundation);
void constructPowerLine(const Foundation& foundation);
};
class DistanceScene
{
public:
DistanceScene(const Foundation& foundation);
private:
Scene m_scene;
};
class PrismaticScene
{
public:
PrismaticScene(const Foundation& foundation);
private:
Scene m_scene;
};
{
foundation.simulation->add(body);
return body;
}
{
}
{
if (engine != nullptr) {
} else {
}
}
agx::Real RotationalUnitInterface::getAngularVelocity()
const {
return m_unit->getRotationalDimension()->getGradient();
}
RotationalUnitInterface(engine)
{
}
RotationalUnitInterface(propeller)
{
}
{
}
void ClutchInterface::configure(
agx::Real engagement)
{
}
{
return m_clutch;
}
{
}
void GearBoxInterface::configure(
agx::Real gear)
{
m_gearBox->setGear((int)gear);
}
{
return m_gearBox;
}
void createClutchEvent(
ClutchInterface* clutch)
{
agxControl::Callback1ActionImplementation<agx::Real>* configureClutch =
new agxControl::Callback1ActionImplementation<agx::Real>(
time, &ClutchInterface::configure, clutch, fraction);
simulation->
add(
new agxControl::CallbackAction(configureClutch));
}
void createGearChangeEvent(
GearBoxInterface* gearBox)
{
agxControl::Callback1ActionImplementation<agx::Real>* setGear =
new agxControl::Callback1ActionImplementation<agx::Real>(
time, &GearBoxInterface::configure, gearBox, gear);
simulation->
add(
new agxControl::CallbackAction(setGear));
}
ClutchInterface* pumpClutch, ClutchInterface* propellerClutch,
GearBoxInterface* , GearBoxInterface* )
{
createClutchEvent(simulation, time,
agx::Real(1), pumpClutch);
createClutchEvent(simulation, time,
agx::Real(1), propellerClutch);
}
EngineInterface engine, PropellerInterface propeller,
ClutchInterface pumpClutch, GearBoxInterface pumpGearBox,
ClutchInterface propellerClutch, GearBoxInterface propellerGearBox)
:
agxSDK::StepEventListener(PRE_STEP | POST_STEP),
m_engine(engine), m_propeller(propeller),
m_pumpClutch(pumpClutch), m_pumpGearBox(pumpGearBox),
m_propellerClutch(propellerClutch), m_propellerGearBox(propellerGearBox),
m_lastEngineVelocity(0), m_lastPropellerVelocity(0)
{
buildEventList(simulation, &m_pumpClutch, &m_propellerClutch, &m_pumpGearBox, &m_propellerGearBox);
}
{
this->updateEngineAgxState();
this->updatePropellerAgxState();
}
{
this->collectEngineAgxState();
this->collectPropellerAgxState();
}
void External::updateEngineAgxState()
{
agx::Real newTorque = this->calculateEngineTorque();
agx::Real newInertia = this->calculateEngineInertia();
m_engine.configure(newTorque, newInertia);
}
{
if (m_lastEngineVelocity < cutoffVelocity)
return maxTorque;
agx::Real cutoffOvershoot = m_lastEngineVelocity - cutoffVelocity;
agx::Real cutoffRange = maxVelocity - cutoffVelocity;
return maxTorque - progress*maxTorque;
}
{
}
void External::collectEngineAgxState()
{
m_lastEngineVelocity = m_engine.getAngularVelocity();
}
void External::updatePropellerAgxState()
{
agx::Real newTorque = this->calculatePropellerTorque();
agx::Real newInertia = this->calculatePropellerInertia();
m_propeller.configure(newTorque, newInertia);
}
agx::Real External::calculatePropellerTorque()
{
return -scale * m_lastPropellerVelocity * m_lastPropellerVelocity;
}
agx::Real External::calculatePropellerInertia()
{
return baseInertia + scale*m_lastPropellerVelocity;
}
void External::collectPropellerAgxState()
{
m_lastPropellerVelocity = m_propeller.getAngularVelocity();
}
Scene::Scene() :
pipeLength(1),
fluidDensity(800),
baseHe(0.5),
baseAttachOffset(
agx::
Real(0.8)*baseHe),
armHalfLength(2.0),
armHalfWidth(0.1),
armHe(armHalfLength, armHalfWidth, armHalfWidth)
{
}
void Scene::construct(const Foundation& foundation)
{
this->constructMechanics(foundation);
this->constructPowerLine(foundation);
External* external = new External(foundation.simulation,
EngineInterface(engine), PropellerInterface(propeller),
ClutchInterface(pumpClutch), GearBoxInterface(pumpGearBox),
ClutchInterface(propellerClutch), GearBoxInterface(propellerGearBox));
foundation.simulation->add(external);
}
void Scene::constructMechanics(const Foundation& foundation)
{
lowerArm = createBox(armHe,
agx::Vec3(baseAttachOffset,
agx::Real(0), baseAttachOffset+armHalfLength),
"Lower arm", foundation);
agx::Vec3 circleDirection(std::cos(-upperArmAngle),
agx::Real(0), std::sin(-upperArmAngle));
agx::Vec3 upperArmPos = circleCenter + armHalfLength*circleDirection;
upperArm = createBox(armHe, upperArmPos, "Upper arm", foundation);
foundation.simulation->getSpace()->setEnableCollisions(base->getGeometries()[0], lowerArm->getGeometries()[0], false);
foundation.simulation->getSpace()->setEnableCollisions(lowerArm->getGeometries()[0], upperArm->getGeometries()[0], false);
lowerArm, lowerArmJointFrame,
upperArm, upperArmJointFrame);
armJoint =
new agx::Hinge(lowerArm, lowerArmJointFrame, upperArm, upperArmJointFrame);
foundation.simulation->add(armJoint);
base, baseJointFrame,
lowerArm, baseArmFrame);
baseJoint =
new agx::Hinge(base, baseJointFrame, lowerArm, baseArmFrame);
baseJoint->getLock1D()->setEnable(true);
foundation.simulation->add(baseJoint);
}
void Scene::constructPowerLine(const Foundation& foundation)
{
foundation.simulation->add(powerLine);
engine->ignition(true);
powerLine->setSource(engine);
pumpClutch->getRotationalDimension()->setName("PumpClutch");
pumpGearBox->setGearRatios(pumpGears);
pumpGearBox->setGear(0);
cutoffPressure, deadheadPressure, internalLeakage, flowRatio, compensatorArea);
pumpPipe->getFlowDimension()->setName("Pump pipe");
relief->getInputChamber()->getFlowDimension()->setName("Relief valve");
tankPipe->getFlowDimension()->setName("Tank pipe");
propellerClutch->setEfficiency(
agx::Real(1e100));
propellerClutch->getRotationalDimension()->setName("PropellerClutch");
propellerGearBox->setGearRatios(propellerGears);
propellerGearBox->setGear(0);
agxVerify(propellerClutch->connect(propellerGearBox));
agxVerify(propellerGearBox->connect(propeller));
foundation.printer->addPressureGauge(pump, "Pump");
foundation.printer->addFlowRateGauge(pumpPipe, "Pump");
foundation.printer->addCustomGauge(std::bind(&agxPowerLine::TranslationalDimension::getValue, pump->getPoppetDimension()), "PumpActivation", "");
if (foundation.writeToDisk)
{
foundation.simulation->add(dotWriter);
}
}
DistanceScene::DistanceScene(const Foundation& foundation)
{
m_scene.construct(foundation);
m_scene.lowerArm, m_scene.armHalfLength*agx::X_AXIS,
m_scene.upperArm, m_scene.armHalfLength*agx::X_AXIS);
m_distanceJoint->getRange1D()->setEnable(true);
m_distanceJoint->getLock1D()->setEnable(false);
foundation.simulation->add(m_distanceJoint);
m_distanceJoint, m_scene.barrelArea, m_scene.pistonArea, m_scene.fluidDensity);
bool success = true;
m_scene.pumpPipe->connect(m_scene.piston);
agxVerify(success);
m_scene.piston->connect(m_scene.tankPipe);
agxVerify(success);
foundation.printer->addFlowRateGauge(m_scene.piston->getRearChamber(), "RearChamber");
foundation.printer->addFlowRateGauge(m_scene.piston->getFrontChamber(), "FrontChamber");
}
PrismaticScene::PrismaticScene(const Foundation& foundation)
{
m_scene.construct(foundation);
}
{
const bool isUnitTest = arguments->
find(
"--isLuaFileSanityUnitTest") != -1;
const bool writeToDisk = !isUnitTest;
osg::Group* root = new osg::Group();
StatsPrinter* printer = new StatsPrinter(simulation, application, writeToDisk);
Foundation foundation = {simulation, application,
root, printer, writeToDisk};
DistanceScene scene(foundation);
}
int main(int argc, char** argv)
{
" External coupling demo application.\n" <<
" -----------------------------------------------------\n\n" <<
LOGGER_END();
{
try {
application->addScene( buildDistanceScene, '1' );
if (application->init(argc, argv)) {
return application->run();
}
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
}
return 0;
}
tutorial_hydrodynamics.cpp
#include "tutorialUtils.h"
namespace
{
{
float alpha( 0.3f );
return node;
}
{
agx::Vec3 pos( -sphereRadius * numSpheresBase, 0, sphereRadius );
for (
agx::UInt o = numSpheresBase; o > 0; --o ) {
assembly->add( sphere );
}
pos.
z() += std::sqrt(
agx::Real( 3 ) ) * sphereRadius + eps;
}
}
pos.
x() = -sphereRadius * numSpheresBase;
}
return assembly;
}
{
for (
agx::UInt i = 0, numVertices = vertices.
size(); i < numVertices; ++i )
}
{
public:
protected:
{
m_timer.reset( true );
}
{
return;
m_timer.stop();
if ( m_app != 0L ) {
m_app->getSceneDecorator()->setText( 0,
agx::String::format(
"Time to step forward: %6.2f ms (%6.1f fps)", time,
agx::Real( 1E3 ) / time ) );
}
}
protected:
};
}
{
osg::Group* root = new osg::Group();
waterGeometry->setPosition( 0, 0, -15 );
waterGeometry->setMaterial( waterMaterial );
::createWaterVisual( waterGeometry, root );
controller->addWater( waterGeometry );
simulation->
add( controller );
simulation->
add( waterGeometry );
pyramid->setPosition( 0, 0, 4 );
simulation->
add( pyramid );
simulation->
add(
new Printer( application ) );
}
{
osg::Group* root = new osg::Group();
waterGeometry->setPosition( 0, 0, -15 );
waterGeometry->setMaterial( waterMaterial );
::createWaterVisual( waterGeometry, root );
controller->addWater( waterGeometry );
simulation->
add( controller );
simulation->
add( waterGeometry );
std::srand( 4 );
for (
agx::UInt layer = 0; layer < numLayers; ++layer ) {
for (
agx::UInt i = 0; i < numPerLayer; ++i ) {
simulation->
add( torus );
}
pos.
y() = -
agx::Real( 0.5 ) * numPerLayer + layer + 1;
}
simulation->
add(
new Printer( application ) );
}
namespace
{
{
public:
protected:
virtual ~WaveGenerator();
protected:
osg::ref_ptr< agxOSG::GeometryNode > m_hfNode;
};
:
agxSDK::StepEventListener(
agxSDK::StepEventListener::PRE_COLLIDE ), m_hf( hf )
{
m_heights.resize( m_hf->getResolutionX() * m_hf->getResolutionY() );
}
WaveGenerator::~WaveGenerator()
{
}
{
if ( m_hf == 0L ) {
getSimulation()->remove( this );
return;
}
for ( unsigned int i = 0; i < m_hf->getResolutionY(); ++i ) {
for ( unsigned int j = 0; j < m_hf->getResolutionX(); ++j ) {
agx::UInt index = i * m_hf->getResolutionX() + j;
}
}
m_hf->setHeights( m_heights );
}
{
public:
private:
};
:
agxSDK::StepEventListener(
agxSDK::StepEventListener::PRE_COLLIDE ), m_ship( ship ), m_localPosition( localPosition ),
m_localForce( localForce )
{
}
{
if ( m_ship == 0L ) {
getSimulation()->remove( this );
return;
}
m_ship->addForceAtPosition( m_ship->getFrame()->transformVectorToWorld( m_localForce ), m_ship->getFrame()->transformPointToWorld( m_localPosition ) );
}
{
meshReader->readFile( "models/ship.obj" );
::scaleMesh( meshReader->getVertices(),
agx::Vec3( 0.01 ) );
shipMaterial->getBulkMaterial()->setDensity( 250 );
return ship;
}
}
{
osg::Group* root = new osg::Group();
waterGeometry->setPosition( 0, 0, 0 );
waterGeometry->setMaterial( waterMaterial );
controller->addWater( waterGeometry );
simulation->
add( controller );
simulation->
add( waterGeometry );
shipHydroParams->
setCoefficient(agxModel::WindAndWaterParameters::Coefficient::VISCOUS_DRAG, viscousDrag);
shipHydroParams->
setCoefficient(agxModel::WindAndWaterParameters::Coefficient::PRESSURE_DRAG, pressureDrag);
shipHydroParams->
setCoefficient(agxModel::WindAndWaterParameters::Coefficient::LIFT, lift);
bool useAeroDynamics = false;
if (useAeroDynamics) {
controller->setEnableAerodynamics(ship, true);
shipAeroParams->
setCoefficient(agxModel::WindAndWaterParameters::Coefficient::VISCOUS_DRAG, viscousDrag);
shipAeroParams->
setCoefficient(agxModel::WindAndWaterParameters::Coefficient::PRESSURE_DRAG, pressureDrag);
shipAeroParams->
setCoefficient(agxModel::WindAndWaterParameters::Coefficient::LIFT, lift);
}
pyramid->setPosition( 0, -10, 4 );
simulation->
add( pyramid );
::createWaterVisual(waterGeometry, root);
WaveGenerator* waveGenerator = new ::WaveGenerator( heightField );
waveGenerator->preCollide( 0 );
simulation->
add( waveGenerator );
simulation->
add(
new Printer( application ) );
}
{
osg::Group* root = new osg::Group();
waterGeometry->setPosition( 0, 0, -15 );
waterGeometry->setMaterial( waterMaterial );
::createWaterVisual( waterGeometry, root );
controller->addWater( waterGeometry );
simulation->
add( controller );
simulation->
add( waterGeometry );
pyramid->setPosition( 0, 0, 4 );
simulation->
add( pyramid );
}
namespace
{
{
public:
MyHydroSimulation(
const agxCollide::Geometry* waterGeometry, WaveGenerator* waveGenerator,
agx::RigidBody* ship, osg::Group* root );
private:
private:
WaveGeneratorRef m_waveGenerator;
};
MyHydroSimulation::MyHydroSimulation(
const agxCollide::Geometry* waterGeometry, WaveGenerator* waveGenerator,
agx::RigidBody* ship, osg::Group* root )
:
agxSDK::StepEventListener(
agxSDK::StepEventListener::PRE_COLLIDE ), m_waterGeometry( waterGeometry ),
m_waveGenerator( waveGenerator ), m_hydrodynamicsModule( new
agxModel::WindAndWaterController() ),
m_shipInAgX( ship ), m_time( 0 )
{
if ( root != 0L )
}
{
return m_shipInAgX != 0L && !m_shipInAgX->getGeometries().empty() ? m_shipInAgX->getGeometries()[ 0 ]->getShapes()[ 0 ] : 0L;
}
{
if ( m_shipInAgX == 0L ) {
getSimulation()->remove( this );
return;
}
if ( m_waveGenerator != 0L )
m_waveGenerator->preCollide( m_time );
if ( m_hydrodynamicsModule != 0L ) {
m_shipInAgX->getMassProperties()->setMassCoefficients( addedMassCoeffs );
m_shipInAgX->getMassProperties()->setInertiaTensorCoefficients( addedInertiaCoeffs );
}
m_time += getSimulation()->getTimeStep();
}
}
{
osg::Group* root = new osg::Group();
waterGeometry->setPosition( 0, 0, 0 );
waterGeometry->setMaterial( waterMaterial );
::createWaterVisual(waterGeometry, root);
::WaveGenerator* waveGenerator = new ::WaveGenerator( heightField );
waveGenerator->preCollide( 0 );
simulation->
add(
new MyHydroSimulation( waterGeometry, waveGenerator, ship, root ) );
}
namespace
{
{
public:
private:
private:
WaveGeneratorRef m_waveGenerator;
};
MyHydroSimulationAndStepper::MyHydroSimulationAndStepper(
const agxCollide::Geometry* waterGeometry,
const agx::RigidBody* ship,
agx::RigidBody* kinematicBody,
agx::LockJoint* lock, WaveGenerator* waveGenerator, osg::Group* root )
:
agxSDK::StepEventListener(
agxSDK::StepEventListener::PRE_COLLIDE ), m_waterGeometry( waterGeometry ),
m_waveGenerator( waveGenerator ), m_hydrodynamicsModule( new
agxModel::WindAndWaterController() ), m_shipInAgXDontTouch( ship ),
{
if ( m_lock != 0L )
m_lock->setEnableComputeForces( true );
if ( root != 0L )
}
{
return m_shipInAgXDontTouch != 0L && !m_shipInAgXDontTouch->getGeometries().empty() ? m_shipInAgXDontTouch->getGeometries()[ 0 ]->getShapes()[ 0 ] : 0L;
}
{
if ( m_shipInAgXDontTouch == 0L || m_kinematicBody == 0L ) {
getSimulation()->remove( this );
return;
}
if ( m_waveGenerator != 0L )
m_waveGenerator->preCollide( m_time );
const agx::Real timeStep = getSimulation()->getTimeStep();
totalForce += m_shipInAgXDontTouch->getMassProperties()->getMass() * m_gravity;
if ( m_hydrodynamicsModule != 0L ) {
}
if ( m_lock != 0L ) {
m_lock->getLastForce( m_kinematicBody, forceFromAgX, torqueFromAgX );
totalForce += forceFromAgX;
totalTorque += torqueFromAgX;
}
agx::Matrix3x3 shipWorldInertiaMatrix = shipRT *
agx::Matrix3x3( m_shipInAgXDontTouch->getMassProperties()->getPrincipalInertiae() ) * shipR;
agx::Vec3 linearVelocity = m_kinematicBody->getVelocity() + shipWorldMassMatrix.
inverse() * totalForce * timeStep;
agx::Vec3 angularVelocity = m_kinematicBody->getAngularVelocity() + shipWorldInertiaMatrix.
inverse() * totalTorque * timeStep;
agx::Vec3 position = m_kinematicBody->getPosition() + linearVelocity * timeStep;
m_kinematicBody->moveTo( position, orientation, timeStep );
m_time += timeStep;
}
}
{
osg::Group* root = new osg::Group();
waterGeometry->setPosition( 0, 0, 0 );
waterGeometry->setMaterial( waterMaterial );
::createWaterVisual(waterGeometry, root);
::WaveGenerator* waveGenerator = new ::WaveGenerator( heightField );
waveGenerator->preCollide( 0 );
simulation->
add( kinematicShipAttachmentBody );
simulation->
add(
new MyHydroSimulationAndStepper( waterGeometry, ship, kinematicShipAttachmentBody, lock, waveGenerator, root ) );
}
{
public:
m_app(app), m_body(body), m_left(left), m_right(right), m_leftRear(leftRear), m_rightRear(rightRear), m_rotator(rotator), m_wire(wire)
{
m_app->getSceneDecorator()->setText(6,
agx::String::format(
"up/down - Increase/decrease speed"));
}
bool keyboard(int key, unsigned int, float, float, bool down)
{
if (down && key == 'z') {
m_left->setSpeed(-0.5);
m_leftRear->setSpeed(-0.5);
return true;
}
if (!down && key == 'z') {
m_left->setSpeed(0);
m_leftRear->setSpeed(0);
return true;
}
if (down && key == 'a') {
m_left->setSpeed(0.5);
m_leftRear->setSpeed(0.5);
return true;
}
if (!down && key == 'a') {
m_left->setSpeed(0);
m_leftRear->setSpeed(0);
return true;
}
if (down && key == 'x') {
m_right->setSpeed(-0.5);
m_rightRear->setSpeed(-0.5);
return true;
}
if (!down && key == 'x') {
m_right->setSpeed(0);
m_rightRear->setSpeed(0);
return true;
}
if (down && key == 's') {
m_right->setSpeed(0.5);
m_rightRear->setSpeed(0.5);
return true;
}
if (!down && key == 's') {
m_right->setSpeed(0);
m_rightRear->setSpeed(0);
return true;
}
{
m_rotator->setSpeed(s);
std::cerr << "Speed: " << m_rotator->getSpeed() << std::endl;
return true;
}
{
m_rotator->setSpeed(s);
std::cerr << "Speed: " << m_rotator->getSpeed() << std::endl;
return true;
}
return false;
}
void update(float, float)
{
agx::Real tension = m_wire->getTension(2).smoothed;
m_app->getSceneDecorator()->setText(2,
agx::String::format(
"Tension: %6.2f kN", tension / 1000));
}
agx::Motor1D *m_left, *m_right, *m_leftRear, *m_rightRear, *m_rotator;
};
{
public:
m_controller(controller), m_root(root)
{
}
void visit(agxCollide::Geometry* geom) override
{
for (
size_t i = 0; i<shapes.
size(); i++)
{
}
}
osg::Group *m_root;
};
{
osg::Group* root = new osg::Group();
waterGeometry->setPosition(0, 0, -30);
waterGeometry->setMaterial(waterMaterial);
::createWaterVisual(waterGeometry, root);
controller->addWater(waterGeometry);
simulation->
add(controller);
simulation->
add(waterGeometry);
simulation->
add(bottomGeometry);
{
}
agxCollide::Geometry *bodyGeometry = simulation->
getGeometry(
"Body");
agxCollide::Geometry *wireConnection = simulation->
getGeometry(
"WireConnection");
if (!leftWing)
if (!rightWing)
if (!body)
if (!leftWingHinge)
if (!rightWingHinge)
if (!wireConnection)
if (!rightWingHingeRear)
if (!leftWingHingeRear)
if (!bodyGeometry)
submarine->setPosition(-45, -45, 0);
shipGeom->setEnableCollisions(false);
hinge->getMotor1D()->setEnable(true);
hinge->getMotor1D()->setSpeed(0.45);
simulation->
add(wireRenderer);
simulation->
add(
new GuiListener(application, body, leftWingHinge->
getMotor1D(), rightWingHinge->getMotor1D(),
leftWingHingeRear->getMotor1D(), rightWingHingeRear->getMotor1D(), hinge->getMotor1D(), wire));
PressureVisitor visitor(controller, root);
submarine->traverse(&visitor);
}
namespace
{
{
public:
: m_flowCoefficient( flowCoefficient ), m_center( center )
{
}
{
agx::Vec3 positionFromCenter = worldPoint - m_center;
agx::Real xVelocity = positionFromCenter.
x() - 2 * positionFromCenter.
y();
agx::Real yVelocity = 2 * positionFromCenter.
x() + positionFromCenter.
y();
return m_flowCoefficient *
agx::Vec3( xVelocity, yVelocity, 0 );
}
protected:
CustomWaterFlowGenerator() {}
private:
};
{
}
{
}
}
{
osg::Group* root = new osg::Group();
waterGeometry1->setPosition( position1 );
::createWaterVisual( waterGeometry1, root );
waterGeometry2->setPosition( position2 );
::createWaterVisual( waterGeometry2, root );
controller->addWater( waterGeometry1 );
controller->addWater( waterGeometry2 );
controller->setWaterFlowGenerator( waterGeometry2, new ::CustomWaterFlowGenerator(
agx::Real( 0.3 ), position2 ) );
simulation->
add( controller );
simulation->
add( waterGeometry1 );
simulation->
add( waterGeometry2 );
for ( int i = 0; i < 3; i++ ) {
for ( int j = 0; j < 3; j++ ) {
simulation->
add( sphere1 );
simulation->
add( sphere2 );
}
}
}
{
public:
WaveWaterWrapper()
{
return worldPoint.
z() - surfaceLevel;
}
};
{
osg::Group* root = new osg::Group();
waterGeometry->setPosition( position );
::createWaterVisual( waterGeometry, root );
controller->addWater( waterGeometry );
controller->setWaterWrapper( waterGeometry, new WaveWaterWrapper() );
simulation->
add( controller );
simulation->
add( waterGeometry );
for( int i = 0; i < 20; i++ ) {
simulation->
add( sphere );
}
}
int main( int argc, char** argv )
{
"\tTutorial hydrodynamics\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
application->addScene( buildTutorial3, '3' );
application->addScene( buildTutorial4, '4' );
application->addScene( buildTutorial5, '5' );
application->addScene( buildTutorial6, '6' );
application->addScene( buildTutorial7, '7' );
application->addScene( buildTutorial8, '8' );
application->addScene( buildTutorial9, '9' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_io.cpp
#include "tutorialUtils.h"
{
osg::Group* root = new osg::Group();
if (!meshReader->readFile( fileName ))
for(size_t n=0; n < 10; n++ )
{
if (!num_convex)
{
}
for(; shapeIt != convexShapes.
end(); ++shapeIt)
{
dynamicRBGeometry->add( shape );
dynamicRB->
add( dynamicRBGeometry );
dynamicRBGeometry->setRotation( euler );
}
simulation->
add( dynamicRB );
}
simulation->
add( staticRB );
}
{
osg::Group* root = new osg::Group;
if (image)
{
heightFieldGeometry = new agxCollide::Geometry();
hf = hfg->createHeightFieldFromImage(image, realSizeX, realSizeY, lowestHeight, highestHeight);
heightFieldGeometry->add(hf);
heightFieldBody->
add( heightFieldGeometry );
simulation->
add( heightFieldBody );
}
else
size_t nX=10;
size_t nY=10;
for ( size_t i = 0; i < nX; ++i )
for ( size_t j = 0; j < nY; ++j ) {
sphereBody->
add(geometry);
sphereBody->
setPosition(
agx::Vec3(-(nX*0.5*radius*2.1)+i*radius*2.1,-(nY*0.5*radius*2.1)+j*radius*2.1, 1.0 ));
simulation->
add( sphereBody );
}
}
{
osg::Group* root = new osg::Group;
simulation->
add( kinematicBody );
simulation->
add( cylinder );
simulation->
add( boxBody );
simulation->
add( staticRB );
}
{
public:
m_root(root), m_geomUuid(geomUuid), m_geomName(geomName)
{
}
osg::ref_ptr<osg::Group> m_root;
};
{
if (className == "agxCollide::Geometry")
{
agxCollide::Geometry* geometry = dynamic_cast<agxCollide::Geometry*>(obj);
if (geometry)
{
std::cerr <<
"Creating visual for Geometry: " << geometry->
getName() << std::endl;
if (geometry->
getName() == m_geomName)
{
if (geometry->
getUuid() == m_geomUuid)
std::cerr << "Uuid for restored geometry matches!!: " << m_geomUuid << std::endl;
else
std::cerr << "ERROR: Uuid for restored geometry does not match!!" << std::endl;
}
}
}
}
{
osg::Group* root = new osg::Group;
const agx::String cylinderGeometryName =
"CylinderGeometry";
cylGeom->setName(cylinderGeometryName);
agx::Uuid cylinderGeometryUuid = cylGeom->getUuid();
simulation->
add(cylinder);
boxGeom->setName("BoxGeometry");
simulation->
add(boxBody);
staticBoxGeom->setName("StaticBoxGeometry");
staticRB->
add( staticBoxGeom );
simulation->
add(staticRB);
#if 1 // Set to zero if you would like to see the scene before we store/restore it.
root->removeChild(0, root->getNumChildren());
bool binaryFormat = true;
simulation->
write(os, binaryFormat);
os.seekg(0);
is.str(os.str());
simulation->
addRestoreListener(
new MyRestoreListener(root, cylinderGeometryUuid, cylinderGeometryName));
simulation->
read(is, binaryFormat);
#endif
}
int main( int argc, char** argv )
{
std::cout <<
"\tIO tutorial\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
application->addScene( buildTutorial4, '4' );
application->addScene( buildTutorial5, '5' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_listeners.cpp
#include "tutorialUtils.h"
{
public:
: m_rb( rb )
{
}
virtual bool keyboard(
int key,
unsigned int modKeyMask,
float ,
float ,
bool keydown )
{
bool handled = false;
if ( !m_rb.isValid() )
return false;
switch ( key )
{
if ( leftCtrlDown )
m_rb->setAngularVelocity( m_rb->getFrame()->transformVectorToWorld(
agx::Vec3( 0, -angularSpeed*
int( keydown ), 0 ) ) );
else
m_rb->setAngularVelocity( m_rb->getFrame()->transformVectorToWorld(
agx::Vec3( 0, 0, -angularSpeed*
int( keydown ) ) ) );
handled = true;
break;
if ( leftCtrlDown )
m_rb->setAngularVelocity( m_rb->getFrame()->transformVectorToWorld(
agx::Vec3( 0, angularSpeed*
int( keydown ), 0 ) ) );
else
m_rb->setAngularVelocity( m_rb->getFrame()->transformVectorToWorld(
agx::Vec3( 0, 0, angularSpeed*
int( keydown ) ) ) );
handled = true;
break;
m_rb->setAngularVelocity( m_rb->getFrame()->transformVectorToWorld(
agx::Vec3( -angularSpeed*
int( keydown ), 0, 0 ) ) );
handled = true;
break;
m_rb->setAngularVelocity( m_rb->getFrame()->transformVectorToWorld(
agx::Vec3( angularSpeed*
int( keydown ), 0, 0 ) ) );
handled = true;
break;
case 'j':
if ( keydown ) {
handled = true;
}
break;
}
return handled;
}
virtual bool mouseDragged( MouseButtonMask ,
float ,
float ) {
return false; }
virtual bool mouseMoved(
float ,
float ) {
return false; }
virtual bool mouse( MouseButtonMask , MouseState ,
float ,
float ) {
return false; }
virtual void update(
float ,
float ) {}
private:
};
{
osg::Group* root = new osg::Group();
simulation->
add( kinematicCylinder );
simulation->
addEventListener(
new SimpleKeyboardListener( kinematicCylinder ) );
}
{
public:
MyContactListener()
: m_impactCounter( 0 )
{
setMask( IMPACT | CONTACT | SEPARATION );
}
{
++m_impactCounter;
std::cout << "Number of impacts: " << m_impactCounter;
if ( m_impactCounter > 2 ) {
std::cout << " is larger than 2, REMOVING CONTACT IMMEDIATELY!" << std::endl;
return REMOVE_CONTACT_IMMEDIATELY;
}
std::cout << std::endl;
return KEEP_CONTACT;
}
{
if ( m_impactCounter > 2 )
return REMOVE_CONTACT_IMMEDIATELY;
return KEEP_CONTACT;
}
{
if ( m_impactCounter > 2 )
return;
std::cout << "Separation: " << cd.first->getName() << " <-> " << cd.second->getName() << std::endl;
}
private:
size_t m_impactCounter;
};
{
osg::Group* root = new osg::Group();
agx::Vec3 boxGeometryHalfExtent( 15, 15, 0.5 );
boxGeometry->setPosition( boxGeometry->getPosition() -
agx::Vec3( 0, 0, boxGeometryHalfExtent.z() ) );
simulation->
add( boxGeometry );
boxGeometry->setName( "boxGeometry" );
sphereGeometry->setName( "sphereGeometry" );
sphere->
add( sphereGeometry );
simulation->
add( sphere );
MyContactListener *listener = new MyContactListener();
}
{
public:
: m_rb( rb ), m_targetPosition( targetPosition )
{
setMask( PRE_COLLIDE | POST_STEP );
if ( m_rb.isValid() )
m_rb->setPosition( m_targetPosition );
}
{
if ( !m_rb.isValid() ) {
getSimulation()->remove( this );
return;
}
if (
agx::equalsZero( (m_targetPosition - m_rb->getPosition()).length2() ) ) {
m_targetPosition = m_targetPosition ^
agx::Vec3( 0, 1, 0 );
m_rb->moveTo( targetTransform, 1.0 );
}
}
{
std::cout << "Current position: " << m_rb->getPosition() << std::endl;
std::cout << "Target position: " << m_targetPosition << std::endl;
std::cout <<
"Distance left: " << ( m_rb->getPosition() - m_targetPosition ).
length() << std::endl << std::endl;
}
private:
};
{
osg::Group* root = new osg::Group();
simulation->
add( kinematicBody );
simulation->
add(
new MyStepEventListener( kinematicBody,
agx::Vec3( -3, 0, -3 ) ) );
}
{
public:
OnSensorVelocityScaler(
agx::Real speedScale )
: m_speedScale( speedScale )
{
setMask( IMPACT | SEPARATION );
}
{
}
}
return KEEP_CONTACT;
}
{
if ( cd.first->isSensor() && cd.second->getRigidBody() )
cd.second->getRigidBody()->setVelocity( m_incidentVelocity );
else if ( cd.second->isSensor() && cd.first->getRigidBody() )
cd.first->getRigidBody()->setVelocity( m_incidentVelocity );
}
private:
};
{
osg::Group* root = new osg::Group();
simulation->
add( kinematicBody );
simulation->
add(
new MyStepEventListener( kinematicBody, initialPathPosition ) );
simulation->
add( sensor1 );
simulation->
add( sensor2 );
sensor1->setSensor( true );
sensor2->setSensor( true );
sensor1->setPosition(
agx::Vec3( 0, 0, initialPathPosition.z() ) );
sensor2->setPosition(
agx::Vec3( 0, 0,-initialPathPosition.z() ) );
OnSensorVelocityScaler *listener = new OnSensorVelocityScaler( 0.5 );
listener = new OnSensorVelocityScaler( 2.0 );
}
{
public:
public:
:
agxSDK::ContactEventListener(
agxSDK::ContactEventListener::IMPACT |
agxSDK::ContactEventListener::CONTACT )
{
setFilter( execFilter );
}
{
return storeContact( gc );
}
{
return storeContact( gc );
}
GeometryContactContainer& getContacts() { return m_contacts; }
const GeometryContactContainer& getContacts() const { return m_contacts; }
protected:
virtual ~MyContactEventListener() {}
{
m_contacts.push_back( *gc );
}
protected:
GeometryContactContainer m_contacts;
};
{
public:
ContactStepListener( MyContactEventListener* contactEvent )
:
agxSDK::StepEventListener(
agxSDK::StepEventListener::POST_STEP ),
m_contactEvent( contactEvent )
{
}
virtual void addNotification()
{
if ( m_contactEvent && m_contactEvent->getSimulation() == 0L )
getSimulation()->add( m_contactEvent );
}
virtual void removeNotification()
{
getSimulation()->remove( m_contactEvent );
}
{
MyContactEventListener::GeometryContactContainer& contacts = m_contactEvent->getContacts();
for ( size_t i = 0; i < contacts.size(); ++i ) {
continue;
for (
size_t j = 0; j < gc.
points().
size(); ++j ) {
else
std::cout << "Contact point " << j << ":" << std::endl;
}
std::cout <<
"Normal force sum: " << normalForceSum <<
" N. ((m1 + m2)g = " << (1 + 1) *
agx::GRAVITY_ACCELERATION <<
" N.)" << std::endl;
}
std::cout << std::endl;
contacts.clear();
}
protected:
virtual ~ContactStepListener() {}
protected:
};
{
osg::Group* root = new osg::Group();
agx::Vec3 boxGeometryHalfExtent( 15, 15, 0.5 );
boxGeometry->setPosition( boxGeometry->getPosition() -
agx::Vec3( 0, 0, boxGeometryHalfExtent.z() ) );
simulation->
add( boxGeometry );
boxGeometry->setName( "boxGeometry" );
box1->
add( box1Geometry );
box2->
add( box2Geometry );
simulation->
add(
new ContactStepListener(
new MyContactEventListener(
new agxSDK::GeometryFilter( boxGeometry, box1Geometry ) ) ) );
}
int main( int argc, char** argv )
{
std::cout <<
"\tListener tutorial\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
application->addScene( buildTutorial3, '3' );
application->addScene( buildTutorial4, '4' );
application->addScene( buildTutorial5, '5' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_material.cpp
#include "tutorialUtils.h"
{
osg::Group* root = new osg::Group();
agx::Vec3 boxGeometryHalfExtent( 15, 15, 0.5 );
boxGeometry->setPosition( boxGeometry->getPosition() -
agx::Vec3( 0, 0, boxGeometryHalfExtent.z() ) );
simulation->
add( boxGeometry );
rb->
add( sphereGeometry );
simulation->
add( sphereMaterial );
sphereGeometry->setMaterial( sphereMaterial );
boxGeometry->setMaterial( sphereMaterial );
}
{
osg::Group* root = new osg::Group();
agx::Vec3 boxGeometryHalfExtent( 15, 8, 0.5 );
boxGeometry->setPosition( boxGeometry->getPosition() -
agx::Vec3( 0, 0, boxGeometryHalfExtent.z() ) );
simulation->
add( boxGeometry );
agx::RigidBodyRefVector rbs( 3 );
for ( size_t i = 0; i < rbs.size(); ++i ) {
rbs[ i ]->add(
new agxCollide::Geometry(
new agxCollide::Box( boxHalfExtent ) ) );
rbs[ i ]->setRotation( boxGeometry->getRotation() );
simulation->
add( rbs[ i ] );
}
rbs[ 0 ]->setPosition( boxGeometry->getFrame()->transformPointToWorld(
agx::Vec3( -boxGeometryHalfExtent.x() + boxHalfExtent.x(),
-5,
boxGeometryHalfExtent.z() + boxHalfExtent.z() ) ) );
rbs[ 1 ]->setPosition( boxGeometry->getFrame()->transformPointToWorld(
agx::Vec3( -boxGeometryHalfExtent.x() + boxHalfExtent.x(),
0,
boxGeometryHalfExtent.z() + boxHalfExtent.z() ) ) );
rbs[ 2 ]->setPosition( boxGeometry->getFrame()->transformPointToWorld(
agx::Vec3( -boxGeometryHalfExtent.x() + boxHalfExtent.x(),
5,
boxGeometryHalfExtent.z() + boxHalfExtent.z() ) ) );
rbs[ 0 ]->getGeometries().front()->setMaterial( m1 );
rbs[ 1 ]->getGeometries().front()->setMaterial( m2 );
rbs[ 2 ]->getGeometries().front()->setMaterial( m3 );
}
{
osg::Group* root = new osg::Group();
agx::Vec3 boxGeometryHalfExtent( 15, 8, 0.5 );
boxGeometry->setPosition( boxGeometry->getPosition() -
agx::Vec3( 0, 0, boxGeometryHalfExtent.z() ) );
simulation->
add( boxGeometry );
sphere1->
add( sphere1Geometry );
simulation->
add( sphere1 );
sphere2->
add( sphere2Geometry );
simulation->
add( sphere2 );
boxGeometry->setMaterial( boxGeometryMat );
simulation->
add( boxGeometryMat );
sphere1Geometry->setMaterial( sphere1Mat );
simulation->
add( sphere1Mat );
sphere2Geometry->setMaterial( sphere2Mat );
simulation->
add( sphere2Mat );
simulation->
add( boxSphere1Contact );
simulation->
add( boxSphere2Contact );
}
{
public:
{
}
{
if ( !m_rb.isValid() )
return;
std::cout << "Name: " << m_rb->getName() << ": Speed: " << m_rb->getVelocity().length() << ": Velocity: " << m_rb->getVelocity() << std::endl;
}
private:
};
{
osg::Group* root = new osg::Group();
agx::Vec3 boxGeometryHalfExtent( 15, 8, 0.5 );
boxGeometry->setPosition( boxGeometry->getPosition() -
agx::Vec3( 0, 0, boxGeometryHalfExtent.z() ) );
simulation->
add( boxGeometry );
boxGeometry->setSurfaceVelocity( (
agx::Vec3f)surfaceVelocity );
simulation->
add( rbBox1 );
rbBox2->
add( rbBox2Geometry );
simulation->
add( rbBox2 );
rbBox2Geometry->setSurfaceVelocity(
agx::Vec3f( 5, (
float)-surfaceVelocity.
y(), 0 ) );
simulation->
add(
new PrintRBVelocityAndSpeed( rbBox1 ) );
}
{
public:
: m_position( position ), m_halfExtent( halfExtent ), m_time( time ), m_currentTime( 0 ), m_root( root )
{
setMask( PRE_COLLIDE );
}
virtual void addNotification()
{
createAndAdd();
}
{
if ( m_currentTime > m_time ) {
createAndAdd();
m_currentTime = 0;
return;
}
m_currentTime += getSimulation()->getDynamicsSystem()->getTimeGovernor()->getTimeStep();
}
private:
void createAndAdd()
{
agxAssert( getSimulation() && m_root.valid() );
rb->add(
new agxCollide::Geometry(
new agxCollide::Box( m_halfExtent ) ) );
std::stringstream ss;
ss <<
"Material" << material->
getIndex();
rb->getGeometries().front()->setMaterial( material );
rb->setPosition( m_position );
rb->getMassProperties()->setMass( 100 );
getSimulation()->add( rb );
}
private:
osg::observer_ptr< osg::Group > m_root;
};
{
public:
: m_position( position ), m_radius( radius ), m_height( height ), m_time( time ), m_currentTime( 0 ), m_root( root )
{
setMask( PRE_COLLIDE );
}
virtual void addNotification()
{
createAndAdd();
}
{
if ( m_currentTime > m_time ) {
createAndAdd();
m_currentTime = 0;
return;
}
m_currentTime += getSimulation()->getDynamicsSystem()->getTimeGovernor()->getTimeStep();
}
private:
void createAndAdd()
{
agxAssert( getSimulation() && m_root.valid() );
std::stringstream ss;
ss <<
"Material" << material->
getIndex();
rb->getGeometries().front()->setMaterial( material );
rb->setPosition( m_position );
rb->getMassProperties()->setMass( 100 );
getSimulation()->add( rb );
}
private:
osg::observer_ptr< osg::Group > m_root;
};
{
public:
KillerObject(
agx::Real z ) : m_z( z ) { setMask( PRE_COLLIDE ); }
{
agx::RigidBodyRefVector& bodies = getSimulation()->getDynamicsSystem()->getRigidBodies();
agx::RigidBodyRefVector remove;
for ( size_t i = 0; i < bodies.size(); ++i ) {
if ( bodies[ i ]->getPosition().z() < m_z )
remove.push_back( bodies[ i ] );
}
while ( !remove.empty() ) {
getSimulation()->remove( remove.back() );
remove.pop_back();
}
}
private:
};
{
osg::Group* root = new osg::Group();
agx::Vec3 boxGeometryHalfExtent( 15, 10, 0.5 );
boxGeometry->setPosition( boxGeometry->getPosition() -
agx::Vec3( 0, 0, boxGeometryHalfExtent.z() ) );
simulation->
add( boxGeometry );
convSec1RB->
add( convSec1Geom );
simulation->
add( convSec1RB );
convSec2RB->
add( convSec2Geom );
simulation->
add( convSec2RB );
convSec1Geom->setSurfaceVelocity(
agx::Vec3f(3,0,0) );
convSec2Geom->setSurfaceVelocity(
agx::Vec3f(3,0,0) );
simulation->
add(
new KillerObject( -100 ) );
}
{
osg::Group* root = new osg::Group();
agx::Vec3 boxGeometryHalfExtent( 15, 10, 0.5 );
boxGeometry->setPosition( boxGeometry->getPosition() -
agx::Vec3( 0, 0, boxGeometryHalfExtent.z() ) );
simulation->
add( boxGeometry );
convSec1RB->
add( convSec1Geom );
simulation->
add( convSec1RB );
convSec2RB->
add( convSec2Geom );
simulation->
add( convSec2RB );
convSec1Geom->setSurfaceVelocity(
agx::Vec3f( 3, 0, 0 ) );
convSec2Geom->setSurfaceVelocity(
agx::Vec3f( 3, 0, 0 ) );
simulation->
add(
new KillerObject( -100 ) );
}
{
private:
{
public:
StepListener()
{
setMask( PRE_STEP|LAST_STEP );
}
{
m_contactMaterials.push_back(cm);
}
{
m_contacts.push_back( contact );
}
{
getSimulation()->getSpace()->addGeometryContacts( m_contacts );
m_contacts.clear();
}
{
m_contactMaterials.clear();
}
ContactMaterialRefVector m_contactMaterials;
};
public:
{
setMask( CONTACT|IMPACT);
m_stepListener = new StepListener;
if (!m_textureImage->read( texture ))
}
void addNotification()
{
getSimulation()->add(m_stepListener);
}
void removeNotification()
{
getSimulation()->remove(m_stepListener);
}
{
return contact( ts, gc);
}
{
if (!image)
return 0.5;
unsigned int iy = (width-1)-agx::clamp<unsigned int>( (
unsigned int)(width*point.
y()/10), (
unsigned int)0, (width-1));
unsigned int ix = agx::clamp<unsigned int>((
unsigned int)(height*point.
x())/10, (
unsigned int)0,height-1);
agx::Real v = m_textureImage->getValueR(ix,iy);
return v;
}
{
for(size_t i=0; i < 5; i++)
m_decorator->setText((int)i, "" );
{
const agx::ContactMaterial *oldCM = getSimulation()->getMaterialManager()->getContactMaterial( m1, m2 );
m_stepListener->addMaterial(newCM);
if (i < 5)
m_decorator->setText((int)i, str );
newCM->transfer( getSimulation()->getMaterialManager()->getContactMaterialStorage() );
m_stepListener->addContact(contact);
}
return REMOVE_CONTACT;
}
};
{
osg::Group* root = new osg::Group();
agx::String surfaceTexture =
"data/textures/frictionmap.png";
agx::Vec3 boxGeometryHalfExtent( 5, 5, 0.5 );
boxGeometry->setPosition( boxGeometryHalfExtent );
simulation->
add( boxGeometry );
smallBox->
add(smallBoxGeometry);
simulation->
add( smallBox );
}
int main( int argc, char** argv )
{
std::cout <<
"\tMaterial tutorial\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
application->addScene( buildTutorial3, '3' );
application->addScene( buildTutorial4, '4' );
application->addScene( buildTutorial5, '5' );
application->addScene( buildTutorial6, '6' );
application->addScene( buildTutorial7, '7' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_mergedBody.cpp
namespace
{
{
if ( numBoxes < 1 )
return nullptr;
assembly->add( box );
}
return assembly;
}
{
public:
typedef std::function< void( agxCollide::GeometryContact* ) > Callback;
{
{
if ( mb == nullptr ) return;
};
}
public:
:
agxSDK::ContactEventListener(
agxSDK::ContactEventListener::IMPACT, filter ),
m_callback( callback )
{
}
{
if ( m_callback )
m_callback( gc );
}
private:
Callback m_callback;
};
}
{
osg::Group* root = new osg::Group();
simulation->
add( ground );
boxRow1->setPosition( 0, 1, 3 );
simulation->
add( boxRow1 );
boxRow2->setPosition( 0, -1, 3 );
simulation->
add( boxRow2 );
for (
agx::UInt i = 1; i < boxRow2->getRigidBodies().size(); ++i ) {
}
simulation->
add( mergedBody );
}
{
osg::Group* root = new osg::Group();
simulation->
add( ground );
simulation->
add( splitBox );
boxRow->setPosition( 0, 1, 3 );
simulation->
add( boxRow );
for (
agx::UInt i = 1; i < boxRow->getRigidBodies().size(); ++i ) {
}
simulation->
add( mergedBody );
{
agxAssert( mb1 ==
nullptr || mb2 ==
nullptr );
if ( mb == nullptr )
return;
};
}
{
osg::Group* root = new osg::Group();
simulation->
add( ground );
simulation->
add( mergedBody );
{
return rb;
};
::OnImpactCallback::createSplitOnImpact( rbLeft, simulation );
::OnImpactCallback::createSplitOnImpact( rbRight, simulation );
}
{
osg::Group* root = new osg::Group();
simulation->
add( ground );
simulation->
add( rb1Hinge );
simulation->
add( rb1Rb2Hinge );
simulation->
add( mergedBody );
{
std::cout << "Hinge edge interaction successfully removed? " << ( success ? "Yes!" : "No." ) << std::endl;
simulation->
remove( mergedBody );
}
std::cout << "Hinge edge interaction successfully added? " << ( success ? "Yes!" : "No." ) << std::endl;
if ( success )
simulation->
add( mergedBody );
}
}, simulation );
}
int main( int argc, char** argv )
{
"\tTutorial Merged Bodies\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
application->addScene( buildTutorial3, '3' );
application->addScene( buildTutorial4, '4' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_mergedSplitHandler.cpp
tutorial_particleSystem.cpp
#include "tutorialUtils.h"
{
std::cout << "\nBuilding Scene 1 - Single pillar of rigid particles" << std::endl;
std::cout << "Demonstrates how to create and initialize particles one by one." << std::endl;
osg::Group *root = new osg::Group;
simulation->
add(floorGeometry);
simulation->
add(particleSystem);
for(size_t i=1; i < 10; i++) {
particle->setPosition(
agx::Vec3(1, 1, i * 0.3));
particle->setRadius(0.1);
}
}
{
public:
ParticleEmitterMover(
agx::ParticleEmitter *emitter, agxCollide::Geometry *geom ) : m_emitter(emitter), m_emitterGeom(geom), m_speed(4.0)
{
setMask( ParticleEmitterMover::PRE_STEP );
}
{
if (!m_emitter) {
return;
}
m_emitter->setVelocity( m_emitterGeom->getTransform().transform3x3(
agx::Vec3(0,-1,0) )*m_speed );
}
};
{
std::cout << "Demonstrates how to use a particle emitter" << std::endl;
osg::Group *root = new osg::Group;
simulation->
add(floorGeometry);
simulation->
add(particleSystem);
spawnGeom->setPosition(0,2,1);
simulation->
add(spawnGeom);
emitter->setSeed(0);
emitter->setGeometry( spawnGeom );
simulation->
add(emitter);
emitter->setRate( 150 );
emitter->setLife( 3.0 );
simulation->
add(
new ParticleEmitterMover(emitter, spawnGeom) );
for(size_t i=0; i < 4; i++)
{
for(size_t j=0; j < 4; j++)
{
agx::Vec3 pos(startX+i*delta, startY+delta*j, z);
}
}
}
{
public:
protected:
};
{
if (!m_ps->getMaterial())
setMask(SmokeEffect::PRE_STEP);
}
{
if (!m_ps)
{
getSimulation()->remove(this);
return;
}
agx::Real radius = m_ps->getParticleRadius();
agx::Vec3 G = getSimulation()->getUniformGravity();
agx::Real volume = area*radius*four_over_three;
agx::Vec3 accel_force = G * (mass - density*volume);
size_t n = forces.size();
for (size_t i=0; i<n; ++i)
{
agx::Vec3 relative_wind = velocities[i]-m_wind;
agx::Vec3 wind_force = - relative_wind * area * (viscosityCoefficient + densityCoefficient*relative_wind.
length());
agx::Vec3 force = (wind_force+accel_force+boyancy);
forces[i] += force;
}
}
{
std::cout << "Demonstrates how to access and add forces to particles by simulating a very simple smoke." << std::endl;
osg::Group *root = new osg::Group;
simulation->
add(particleSystem);
simulation->
add(
new SmokeEffect(particleSystem));
spawnGeom->setPosition(0,0,0);
simulation->
add(spawnGeom);
emitter->setGeometry( spawnGeom );
emitter->setSeed(0);
simulation->
add(emitter);
emitter->setRate( 600 );
emitter->setLife( 10.0 );
int n = 15;
agx::Real xStart = 0.1+-n*(delta+radius*2)/2;
for (int i=0; i < n; i++)
{
g->setPosition(xStart+(delta+radius)*i, yStart,0.3);
}
}
int main( int argc, char** argv )
{
std::cout <<
"\tTutorial particle system\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
application->addScene( buildTutorial3, '3' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_rigidBodyEmitter.cpp
#include "tutorialUtils.h"
{
osg::Group* root = new osg::Group();
floor_geometry->setMaterial(floorMat);
emitter->setRate(30.0);
emitter->setMaximumEmittedQuantity(200);
emitter->setDistributionTable(distributionTable);
geometryTemplate1->setMaterial(rbMat);
bodyTemplate1->
add(geometryTemplate1);
geometryTemplate2->setMaterial(rbMat);
bodyTemplate2->
add(geometryTemplate2);
emitGeometry->setPosition(0.0, 0.0, 4.0);
emitGeometry->setSensor(true);
emitter->setGeometry(emitGeometry);
simulation->
add(emitGeometry);
simulation->
add(emitter);
}
int main(int argc, char** argv)
{
std::cout <<
"\tTutorial RigidBodyEmitter\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene(buildTutorial1, '1');
if (application->init(argc, argv))
return application->run();
}
catch (std::exception& e) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_statistics.cpp
{
dynamicRBGeometry->add(dynamicRBBox);
dynamicRB->
add(dynamicRBGeometry);
simulation->
add(dynamicRB);
simulation->
add(staticRB);
}
void printStatistics()
{
entryNames.
push_back(std::make_pair(
"Simulation",
"Step forward time"));
entryNames.
push_back(std::make_pair(
"Simulation",
"Dynamics-system time"));
entryNames.
push_back(std::make_pair(
"Simulation",
"Collision-detection time"));
entryNames.
push_back(std::make_pair(
"Simulation",
"Pre-collide event time"));
entryNames.
push_back(std::make_pair(
"Simulation",
"Pre-step event time"));
entryNames.
push_back(std::make_pair(
"Simulation",
"Post-step event time"));
entryNames.
push_back(std::make_pair(
"Simulation",
"Triggering contact events"));
entryNames.
push_back(std::make_pair(
"Simulation",
"Culling contacts"));
entryNames.
push_back(std::make_pair(
"Simulation",
"Triggering contact separation events"));
entryNames.
push_back(std::make_pair(
"Simulation",
"Contact reduction"));
entryNames.
push_back(std::make_pair(
"Simulation",
"Committing removed contacts"));
entryNames.
push_back(std::make_pair(
"Space",
"Broad-phase time"));
entryNames.
push_back(std::make_pair(
"Space",
"Narrow-phase time"));
entryNames.
push_back(std::make_pair(
"Space",
"Sync bounds time"));
entryNames.
push_back(std::make_pair(
"Space",
"Sync transforms time"));
entryNames.
push_back(std::make_pair(
"Space",
"Num geometries"));
entryNames.
push_back(std::make_pair(
"Space",
"Num geometry-geometry contact points"));
entryNames.
push_back(std::make_pair(
"Space",
"Num geometry-geometry contacts"));
entryNames.
push_back(std::make_pair(
"Space",
"Num narrow phase tests"));
entryNames.
push_back(std::make_pair(
"DynamicsSystem",
"Update time"));
entryNames.
push_back(std::make_pair(
"DynamicsSystem",
"Solver time"));
entryNames.
push_back(std::make_pair(
"DynamicsSystem",
"Sabre: Factoring"));
entryNames.
push_back(std::make_pair(
"DynamicsSystem",
"Sabre: Solve"));
entryNames.
push_back(std::make_pair(
"DynamicsSystem",
"Num multi-body constraints"));
entryNames.
push_back(std::make_pair(
"DynamicsSystem",
"Num solve islands"));
entryNames.
push_back(std::make_pair(
"DynamicsSystem",
"Num enabled rigid bodies"));
entryNames.
push_back(std::make_pair(
"DynamicsSystem",
"Num binary constraints"));
entryNames.
push_back(std::make_pair(
"DynamicsSystem",
"Num contact constraints"));
for (auto entry : entryNames) {
std::cout << entry.first <<
":" << entry.second <<
" " << info.
current <<
" (" << info.
accumulated <<
")" << std::endl;
}
}
void buildTutorial1()
{
createScene(simulation);
while (simulation->getTimeStamp() < 2)
{
simulation->stepForward();
printStatistics();
}
}
int main()
{
std::cout <<
"\tStatistics tutorial\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
buildTutorial1();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_terrain.cpp
#include "tutorialUtils.h"
#include "createExampleShovel.h"
template <class T>
{
public:
MotorizedJointKeyboardListener( T *joint, int keyA, int keyB, float maxSpeed = 1.0 ) :
m_joint(joint),
m_keyA(keyA),
m_keyB(keyB),
m_maxSpeed(maxSpeed)
{
setName( "keyboard listener" );
m_joint->getMotor1D()->setEnable( true );
}
bool keyboard( int key, unsigned , float , float , bool keyDown ) {
bool handled = false;
if ( key == m_keyA) {
if ( !keyDown ) {
m_joint->getMotor1D()->setSpeed( 0 );
return false;
}
m_joint->getMotor1D()->setSpeed( m_maxSpeed );
handled = true;
}
else if ( key == m_keyB) {
if ( !keyDown ) {
m_joint->getMotor1D()->setSpeed( 0 );
return false;
}
m_joint->getMotor1D()->setSpeed( -m_maxSpeed );
handled = true;
}
return handled;
}
private:
int m_keyA;
int m_keyB;
float m_maxSpeed;
};
{
osg::Group* root = new osg::Group();
size_t resolutionX = 64;
size_t resolutionY = 128;
agx::RangeReal youngsModulusRange( youngsModulusTerrain,youngsModulusTerrain );
simulation->
add( terrain,agxSDK::EventManager::DEFAULT_PRIORITY + 1 );
simulation->
add( terrainRenderer,agxSDK::EventManager::DEFAULT_PRIORITY );
sphere.getGeometry()->setMaterial(sphereMaterial);
sphere.getGeometry()->getPropertyContainer()->addPropertyBool("DynamicHeightFieldDeformer",true);
}
{
osg::Group* root = new osg::Group();
size_t resolutionX = 64;
size_t resolutionY = 128;
agx::RangeReal youngsModulusRange( youngsModulusTerrain,youngsModulusTerrain );
simulation->
add( terrain,agxSDK::EventManager::DEFAULT_PRIORITY + 1 );
simulation->
add( terrainRenderer,agxSDK::EventManager::DEFAULT_PRIORITY );
sphere.getGeometry()->getPropertyContainer()->addPropertyReal("AllowedTerrainOverlapProperty", 0.1);
}
{
if (image)
{
hf = hfg->createHeightFieldFromImage(image.
get(), sizeX, sizeY, low, high);
}
else
return hf;
}
{
osg::Group* root = new osg::Group();
agx::String filename =
"textures/terrain_test/terrain_height.png";
agxCollide::HeightField* heightField = createHeightFieldFromPngImage(filename,sizeSide,sizeSide,lowestHeight,highestHeight);
if ( heightField == 0L )
agx::RangeReal youngsModulusRange( youngsModulusTerrain,youngsModulusTerrain );
simulation->
add( terrain,agxSDK::EventManager::DEFAULT_PRIORITY + 1 );
simulation->
add( terrainRenderer,agxSDK::EventManager::DEFAULT_PRIORITY );
}
{
osg::Group* root = new osg::Group();
size_t resolutionX = 64;
size_t resolutionY = 128;
simulation->
add(softDirtMaterial);
simulation->
add(sandMaterial);
size_t materialIndexSoftDirt = 1;
terrainDataInterface->
add( softDirtMaterial ,materialIndexSoftDirt ,adhesiveForceSoftDirt ,deformabilitySoftDirt );
size_t materialIndexSand = 2;
terrainDataInterface->
add( sandMaterial ,materialIndexSand ,adhesiveForceSand ,deformabilitySand );
{
{
if ( i < resolutionX/2 )
else
}
}
agx::RangeReal youngsModulusRange( youngsModulusSoftDirt,youngsModulusSand );
simulation->
add( terrain,agxSDK::EventManager::DEFAULT_PRIORITY + 1 );
simulation->
add( terrainRenderer,agxSDK::EventManager::DEFAULT_PRIORITY );
}
{
osg::Group* root = new osg::Group();
size_t resolutionX = 64;
size_t resolutionY = 128;
simulation->
add(softDirtMaterial);
simulation->
add(sandMaterial);
agx::String filename =
"textures/terrain_test/BlackAndWhite.png";
size_t materialIndexSoftDirt = 0;
terrainDataInterface->
add( softDirtMaterial ,materialIndexSoftDirt ,adhesiveForceSoftDirt ,deformabilitySoftDirt );
size_t materialIndexSand = 255;
terrainDataInterface->
add( sandMaterial ,materialIndexSand ,adhesiveForceSand ,deformabilitySand );
agx::RangeReal youngsModulusRange( youngsModulusSoftDirt,youngsModulusSand );
simulation->
add( terrain,agxSDK::EventManager::DEFAULT_PRIORITY + 1 );
simulation->
add( terrainRenderer,agxSDK::EventManager::DEFAULT_PRIORITY );
}
{
agx::RigidBody* shovel = createExampleShovel(simulation,terrainGeometry);
return shovel;
}
{
agx::RigidBody* shovel = createShovel(simulation,root,terrainGeometry);
simulation->
add(worldBody);
simulation->
add(prismaticWorld);
agxOSG::SimulationObject shovelWheel = agxOSG::SimulationObject::createCylinder(
"ShovelWheel",
agx::AffineMatrix4x4::translate(0,0,3),1.8,1,root,simulation);
simulation->
add(worldBody);
simulation->
add(worldHinge);
agx::Vec3 worldAttachPoint = shovelWheel.getRigidBody()->getFrame()->transformPointToWorld(attachFrame->
getTranslate());
simulation->
add(attachHinge);
return worldBody;
}
{
simulation->
add(dirtMaterial);
size_t materialIndexSoftDirt = 1;
terrainDataInterface->
add( dirtMaterial ,materialIndexSoftDirt ,adhesiveForce ,deformabilityDirt );
{
{
}
}
simulation->
add( terrain,agxSDK::EventManager::DEFAULT_PRIORITY + 1 );
simulation->
add( terrainRenderer,agxSDK::EventManager::DEFAULT_PRIORITY );
return terrain;
}
{
osg::Group* root = new osg::Group();
createRotatingShovel(simulation,root,terrain->
getGeometry());
}
{
osg::Group* root = new osg::Group();
stopBlock->setPosition(
Vec3( -12,0,-8 ));
simulation->
add(stopBlock);
if ( dirtMaterial != 0L )
{
}
size_t resolutionX = 10;
size_t resolutionY = 10;
agxModel::Terrain* flatbed = createFlatTerrain(
"DirtMaterialFlatbed",simulation,root,0,resolutionX,resolutionY,sizeSide);
dirtMaterial = simulation->
getMaterial(
"DirtMaterialFlatbed");
if ( dirtMaterial != 0L )
{
}
simulation->
add(flatbedWall);
}
{
osg::Group* root = new osg::Group();
stopBlock->setPosition(
Vec3( -12,0,-8 ));
simulation->
add(stopBlock);
if ( dirtMaterial != 0L )
{
}
for (size_t i = 0; i < shovel->getGeometries().size(); ++i)
shovel->getGeometries()[i]->setMaterial(shovelMat);
size_t resolutionX = 10;
size_t resolutionY = 10;
agxModel::Terrain* flatbed = createFlatTerrain(
"DirtMaterialFlatbed",simulation,root,0,resolutionX,resolutionY,sizeSide);
dirtMaterial = simulation->
getMaterial(
"DirtMaterialFlatbed");
if ( dirtMaterial != 0L )
{
}
simulation->
add(flatbedWall);
}
{
osg::Group* root = new osg::Group();
stopBlock->setPosition(
Vec3( -12,0,-8 ));
simulation->
add(stopBlock);
size_t resolutionX = 10;
size_t resolutionY = 10;
agxModel::Terrain* flatbed = createFlatTerrain(
"DirtMaterialFlatbed",simulation,root,0,resolutionX,resolutionY,sizeSide);
simulation->
add(flatbedWall);
agxModel::Terrain* shovelbed = createFlatTerrain(
"DirtMaterialShovel",simulation,root,0,4,3,2,10);
}
{
osg::Group* root = new osg::Group();
createRotatingShovel(simulation,root,terrain->
getGeometry());
}
{
osg::Group* root = new osg::Group();
stopBlock->setPosition(
Vec3( -12,0,-8 ));
simulation->
add(stopBlock);
if ( dirtMaterial != 0L )
{
}
for (size_t i = 0; i < shovel->getGeometries().size(); ++i)
shovel->getGeometries()[i]->setMaterial(shovelMat);
size_t resolutionX = 10;
size_t resolutionY = 10;
agxModel::Terrain* flatbed = createFlatTerrain(
"DirtMaterialFlatbed",simulation,root,0,resolutionX,resolutionY,sizeSide);
dirtMaterial = simulation->
getMaterial(
"DirtMaterialFlatbed");
if ( dirtMaterial != 0L )
{
}
simulation->
add(flatbedWall);
}
{
osg::Group* root = new osg::Group();
spDirect->getGeometries().front()->setMaterial(directMaterial);
spIterative->getGeometries().front()->setMaterial(iterativeMaterial);
simulation->
add(spDirect);
simulation->
add(spIterative);
}
{
osg::Group* root = new osg::Group();
auto material = simulation->
getMaterial(
"DirtMaterial");
}
{
osg::Group* root = new osg::Group();
const size_t resolutionX = 128;
const size_t resolutionY = 128;
heights.
resize(resolutionX*resolutionY);
for (size_t i = 0; i < resolutionX; i++)
{
for (size_t j = 0; j < resolutionX; j++)
{
heights[j+resolutionX*i] = sin(i/10.0) * sin(j/10.0) * 2;
}
}
simulation->
add(terrainBody);
simulation->
add(terrainObserver);
agx::RangeReal youngsModulusRange(youngsModulusTerrain, youngsModulusTerrain);
simulation->
add(terrain, agxSDK::EventManager::DEFAULT_PRIORITY + 1);
simulation->
add(terrainRenderer, agxSDK::EventManager::DEFAULT_PRIORITY);
simulation->
add(sphereBody);
simulation->
add(sphereObserver);
sphereBody->
getGeometries()[0]->getPropertyContainer()->addPropertyReal(
"AllowedTerrainOverlapProperty", 0.1);
}
int main( int argc, char** argv )
{
std::cout <<
"\tTutorial Terrain\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1a, '1' );
application->addScene( buildTutorial1b, '2' );
application->addScene( buildTutorial2, '3' );
application->addScene( buildTutorial3, '4' );
application->addScene( buildTutorial4, '5' );
application->addScene( buildTutorial5, '6' );
application->addScene( buildTutorial6, '7' );
application->addScene( buildTutorial7, '8' );
application->addScene( buildTutorial8, '9' );
application->addScene( buildTutorial9, '0' );
application->addScene( buildTutorial10, '!' );
application->addScene( buildTutorial11, '"' );
application->addScene(buildTutorial12, '#');
application->addScene(buildTutorial13, '%');
if ( application->init( argc, argv ) )
{
return application->run();
}
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_terrainPager_tileEvents.cpp
#include <agx/config/AGX_USE_AGXTERRAIN.h>
#if AGX_USE_AGXTERRAIN()
#ifdef _MSC_VER
#include <process.h>
#define getpid _getpid
#else
#include <unistd.h>
#endif
{
public:
~DemoListener();
private:
size_t m_lastCount;
};
StepEventListener(
agxSDK::StepEventListener::LAST_STEP ), m_pager( pager )
{
m_lastCount = 0;
if ( m_pager ) {
m_pager->tileLoadEvent.addCallback( &m_loadCallback1 );
m_pager->tileUnloadEvent.addCallback( &m_unloadCallback1 );
m_pager->tileLoadEvent.addCallback( &m_loadCallback2 );
m_pager->tileUnloadEvent.addCallback( &m_unloadCallback2 );
}
else {
exit(1);
}
}
DemoListener::~DemoListener()
{
if ( m_pager ) {
m_pager->tileLoadEvent.removeCallback( &m_loadCallback1 );
m_pager->tileUnloadEvent.removeCallback( &m_unloadCallback1 );
m_pager->tileLoadEvent.removeCallback( &m_loadCallback2 );
m_pager->tileUnloadEvent.removeCallback( &m_unloadCallback2 );
}
}
assert( m_activeTiles.contains( t ) == false );
printf("\t+ Tile [%i,%i] was loaded\n", id[0], id[1] );
}
assert( m_activeTiles.contains( t ) == true );
m_activeTiles.erase( t );
printf("\t- Tile [%i,%i] was unloaded\n", id[0], id[1] );
}
{
printf("\t%+2i, tile id: [%i,%i]\n", num, id[0], id[1] );
}
if ( m_activeTiles.size() != m_lastCount ) {
m_lastCount = m_activeTiles.size();
printf("At T=%5.2f, the DemoListener knows about %i Terrain instances\n",
(float) time, (int) m_activeTiles.size() );
}
}
{
osg::Group* root = new osg::Group();
agxCollide::Geometry* geom = new agxCollide::Geometry( box );
tds->addSourceGeometry( geom );
size_t tileResolution = 51;
size_t tileOverlap = 5;
tp->setName("TerrainPager");
tp->setTerrainDataSource( tds );
if ( tmpDir.length() == 0 ) {
printf("Failed to created temp directory for terrain data");
exit(2);
}
else {
printf("Using %s for temp storage of terrain data\n", tmpDir.c_str() );
}
tp->setFileCacheDirectory( tmpDir );
tp->add( body, 1, 6 );
auto dl = new DemoListener( tp );
}
int main( int argc, char** argv )
{
std::cout <<
"\tTerrainPager and TileCallbacks\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
#else
int main( int, char** )
{
"\tTerrainPager and TileCallbacks\n" <<
"\t--------------------------------\n" <<
LOGGER_ENDL() <<
"AGX Dynamics built without support for agxTerrain" <<
LOGGER_ENDL();
return 0;
}
#endif
tutorial_threadAffinity.cpp
int tutorial_setAffinityAGXThreads()
{
const unsigned int NUM_THREADS = 4;
bool values[NUM_THREADS];
bool ok;
for (auto i = 1u; i < NUM_THREADS; ++i)
{
ok &= values[i];
}
for (auto i = 0u; i < NUM_THREADS; ++i)
{
std::cerr <<
agx::String::format(
"Status for setting affinity for thread %i: %i\n", i, values[i]) << std::endl;
}
return (ok ? 0 : 1);
}
{
public:
MyThread(unsigned int id ) : m_sum(0), m_id(id)
{
}
virtual ~MyThread() {}
double m_sum;
unsigned int m_id;
};
void MyThread::run()
{
while ( m_sum < 1000000000)
{
m_sum += std::exp2(2) * std::cos(0.4) * std::exp2(2);
}
}
void tutorial_createThreads()
{
const unsigned int NUM_THREADS = 6;
for (auto i = 0u; i < NUM_THREADS; i++)
{
}
std::cerr << "Starting threads" << std::endl;
for (auto thread : threads)
thread->start();
std::cerr << "Waiting for threads" << std::endl;
for (auto thread : threads)
{
thread->join();
}
std::cerr << "Shutting down" << std::endl;
threads.clear();
}
int main( int, char** )
{
tutorial_createThreads();
return tutorial_setAffinityAGXThreads();
}
tutorial_threads.cpp
{
public:
MyListener()
{}
{
if (!m_threads.contains(thread))
{
std::cerr << "In a pre-callback. Thread: " << thread << std::endl;
m_threads.insert(thread);
}
}
};
{
public:
{
m_block.reset();
}
void run();
void release()
{
m_block.release();
}
virtual ~MyThread() {}
};
void MyThread::run()
{
std::cerr << "Thread: " << thread << std::endl;
m_block.block();
m_block.reset();
while (sim->getTimeStamp() - t < 0.1)
{
sim->add(body);
sim->stepForward();
sim->remove(body);
}
}
void threadTutorial1()
{
std::cerr << "Running " << __FUNCTION__ << std::endl << std::endl;
sim->add(new MyListener);
std::cerr << "Main thread: " << thread << std::endl;
for (size_t i = 0; i < 4; i++)
{
MyThread *t = new MyThread(sim);
t->start();
}
for (
size_t i = 0; i < threads.
size(); i++)
{
MyThread *t = threads[i];
t->release();
t->join();
}
for (
size_t i = 0; i < threads.
size(); i++)
{
MyThread *t = threads[i];
delete t;
}
}
{
numVertices = trimeshShape->getNumVertices();
if (!trimeshShape)
{
return nullptr;
}
dynamicRBGeometry->setEnableCollisions(false);
dynamicRBGeometry->setMaterial(material);
dynamicRBGeometry->add(trimeshShape);
dynamicRB->
add(dynamicRBGeometry);
return dynamicRB;
}
{
public:
MyLoadingThread(int numObjects, const std::string& filename) : m_numObjects(numObjects), m_filename(filename)
{
}
void run();
virtual ~MyLoadingThread() {}
int m_numObjects;
std::string m_filename;
size_t m_numVertices;
agx::RigidBodyRefVector m_bodies;
};
void MyLoadingThread::run()
{
for (auto i = 0; i < m_numObjects; i++)
{
m_bodies.push_back(body);
}
}
void threadTutorial2()
{
std::cerr << std::endl << "Running " << __FUNCTION__ << std::endl << std::endl;
MyLoadingThread myThread(20, "models/torusRound.obj");
myThread.start();
std::cerr << "Simulating while creating";
while (simTimer.getTime() < 2000)
{
int i = (int)simTimer.getTime();
simulation->stepForward();
if ((i % 700) == 0)
std::cerr << ".";
}
std::cerr << std::endl << "Done Simulating " << std::endl;
myThread.join();
std::cerr << "Creating " << myThread.m_bodies.size() << " objects (each with " << myThread.m_numVertices << " num vertices) took " << myThread.m_time << "ms" << std::endl;
for (auto b : myThread.m_bodies)
simulation->add(b);
std::cerr <<
"Adding " << myThread.m_bodies.size() <<
" bodies to simulation took " << timer.
getTime() <<
"ms" << std::endl;
std::cerr << "Continue to simulate with the added bodies" << std::endl;
simTimer.reset(true);
while (simTimer.getTime() < 0.5)
{
int i = (int)simTimer.getTime();
simulation->stepForward();
if ((i % 700) == 0)
std::cerr << ".";
}
std::cerr << std::endl << "Done Simulating " << std::endl;
}
int main(int , char** )
{
std::cout <<
"\tTutorial Threads\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
threadTutorial1();
threadTutorial2();
}
catch (std::exception& e) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_tire.cpp
{
osg::Group* root = new osg::Group();
simulation->
add(tireOnGround);
simulation->
add(groundStraight);
groundStraight->setMaterial(groundMaterial);
groundStraight->setPosition(groundHalfExtent, 0, -0.5);
simulation->
add(groundRotated);
groundRotated->setMaterial(groundMaterial);
const agx::Vec3 chassisHalfExtents(1.2, 0.8, 0.2);
simulation->
add(chassis);
car->add(chassis);
for (int i = 0; i < 4; ++i) {
agx::Vec3 pos(i < 2 ? -1 : 1, (i % 2 == 1) ? -1 : 1, 0);
car->add(wheel);
car->add(tire);
tire->getRigidBody());
}
}
{
osg::Group* root = new osg::Group();
simulation->
add(tireOnGround);
simulation->
add(groundStraight);
groundStraight->setMaterial(groundMaterial);
groundStraight->setPosition(groundHalfExtent, 0, -0.5);
simulation->
add(groundRotated);
groundRotated->setMaterial(groundMaterial);
const agx::Vec3 chassisHalfExtents(1.2, 0.8, 0.2);
simulation->
add(chassis);
car->add(chassis);
for (int i = 0; i < 4; ++i) {
agx::Vec3 pos(i < 2 ? -1 : 1, (i % 2 == 1) ? -1 : 1, 0);
simulation->
add(hubRigidBody);
car->add(hubRigidBody);
simulation->
add(tireRigidBody);
car->add(tireRigidBody);
car->add(tire);
tire->getHubRigidBody());
}
}
int main( int argc, char** argv )
{
std::cout <<
"\tTutorial Tire\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorialOneBodyTire, '1' );
application->addScene( buildTutorialTwoBodyTire, '2' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_trimesh.cpp
#include "tutorialUtils.h"
{
osg::Group* root = new osg::Group();
triangleMeshRigidBody->
setName(
"handmade" );
triangleMeshRigidBody->
add(
new agxCollide::Geometry( triangleMesh ) );
simulation->
add( triangleMeshRigidBody );
}
{
osg::Group* root = new osg::Group();
const char* collisionModel = "models/torusRoundForCollision.obj";
const char* visualModel = "models/torusRound.obj";
if ( !trimeshShape )
{
}
dynamicRBGeometry->setMaterial( material );
dynamicRBGeometry->add( trimeshShape);
dynamicRB->
add( dynamicRBGeometry );
simulation->
add( dynamicRB );
if ( visualTrimesh )
geometryNode->addChild( visualTrimesh );
else
root->addChild( geometryNode );
staticRB->
add( staticBodyGeometry );
staticBodyGeometry->setMaterial( material );
simulation->
add( staticRB );
simulation->
add( staticRB );
}
{
osg::Group* root = new osg::Group();
const char* collisionModel = "models/torusRoundForCollision.obj";
size_t numMeshesPerDim = 3;
for (size_t i = 0; i < numMeshesPerDim; ++i) {
for (size_t j = 0; j < numMeshesPerDim; ++j) {
triangleMeshRigidBody->
setName(
"MeshCopy" );
geom->setMaterial( material );
triangleMeshRigidBody->
add( geom );
objectDistance);
simulation->
add( triangleMeshRigidBody );
}
}
staticGeometry->setMaterial( material );
staticRB->
add( staticGeometry );
simulation->
add( staticRB );
simulation->
add( staticRB );
}
{
osg::Group* root = new osg::Group;
geo->add( trimesh );
bool hasHalfEdge = trimesh->hasHalfEdge();
std::cout << "The trimesh has " << (hasHalfEdge? "a " : "no ") << "half edge structure.\n";
bool isClosed = trimesh->isValidAndClosed();
std::cout << "The trimesh is " << (isClosed? "" : "not ") << "closed.\n";
bool triangleValid = triangle.
isValid();
std::cout << "The triangle is " << (triangleValid? "" : "not ") << "valid.\n";
std::cout << "Triangle 0 has the neighboring triangle with triangle index " <<
neighborTriangleIndex << " at edge 1.\n"
<< "This triangle is " << (neighborTriangle.isValid() ? "" : "not ") << "valid\n";
size_t neighborEdgeIndex = triangle.getHalfEdgePartnerLocalEdgeIndex(1);
std::cout << "Edge 1 from triangle 0 has the index " << neighborEdgeIndex <<
" in the triangle with index " << neighborTriangleIndex << "\n";
}
namespace {
{
public:
IteratorMover( agxCollide::Geometry* geometry, unsigned int startTriangle, uint_fast8_t startVertex )
: m_geometry(geometry)
{
if (m_geometry) {
if (m_geometry->getShapes().size()) {
if (mesh) {
m_trimesh = mesh;
}
}
}
setMask( GuiEventListener::KEYBOARD );
}
virtual bool keyboard(
int key,
unsigned ,
float ,
float ,
bool keydown ) {
if ( keydown && ( key == GuiEventListener::KEY_Right ) ) {
std::cout << "pressed right" << std::endl;
m_circulator++;
RenderTriangle();
return true;
}
return false;
}
private:
void RenderTriangle()
{
if (m_trimesh && m_circulator.isValid()) {
return;
triangle.
getVertex(1) * m_geometry->getTransform(),
triangle.
getVertex(2) * m_geometry->getTransform() };
int index = m_circulator.getLocalEdgeIndex();
agx::Vec3 normalStart = (verts[index] + verts[(index + 1) % 3]) * 0.5;
}
}
};
}
namespace {
{
public:
TriangleTraverser(agxCollide::Geometry* trimeshGeo, agxCollide::Geometry* lineGeo,
const agx::Vec4& color,
size_t maxIt = 1000):
agxSDK::StepEventListener(
agxSDK::StepEventListener::POST_STEP),
m_trimeshGeo( trimeshGeo), m_lineGeo( lineGeo ), m_color(color), m_maxIt(maxIt)
{
updateValid();
}
private:
void updateValid()
{
if (!m_valid)
LOGGER_WARNING() <<
"TriangleTraverser should have one geometry with exactly one line and one with exactly one trimesh. Ignoring.\n" <<
LOGGER_END();
}
{
updateValid();
if (!m_valid)
return;
unsigned int triangleIndex;
trimeshToWorld = m_trimeshGeo->getShapes()[0]->getLocalTransform() * trimeshToWorld;
lineToWorld = m_lineGeo->getShapes()[0]->getLocalTransform() * lineToWorld;
if (!line) {
return;
}
if (!trimesh) {
return;
}
agx::Vec3 lineStartInTrimesh = lineStartInWorld * worldToTrimesh;
agx::Vec3 lineEndInTrimesh = lineEndInWorld * worldToTrimesh;
bool foundPoint = findIntersectionLineSegmentMesh( lineStartInTrimesh, lineEndInTrimesh, trimesh, lineSegmentT, triangleIndex );
if (!foundPoint)
return;
agx::Vec3 hitPointInWorld = lineStartInWorld * (1-lineSegmentT) + lineEndInWorld * lineSegmentT;
agx::Vec3 dirInTrimesh = lineEndInTrimesh - lineStartInTrimesh;
agx::Vec3 dirProjToTrimeshXY( dirInTrimesh[0], dirInTrimesh[1], 0 );
agx::Vec3 pointInTrimesh = hitPointInWorld * worldToTrimesh;
size_t numTriangles = 0;
size_t edgeIndex = 3;
bool atEndLength = false;
const agx::Real segmentRestLength = (lineEndInTrimesh - pointInTrimesh).
length();
while (numTriangles < m_maxIt && triangle.
isValid() && !atEndLength) {
uint_fast8_t newEdgeIndex = 3;
for (uint_fast8_t i = 0; i < 3; ++i) {
if (i == edgeIndex)
continue;
if (agxCollide::intersectLineSegmentHyperPlane(pointInTrimesh, lineEndInTrimesh,
if (tmpT >= 0 && tmpT < newT) {
newT = tmpT;
newEdgeIndex = i;
newPointInTrimesh = tmpPoint;
}
}
}
if (newEdgeIndex == 3) {
atEndLength = true;
}
else {
if ((newPointInTrimesh - lineEndInTrimesh) * dirProjToTrimeshXY > 0) {
atEndLength = true;
}
}
if (atEndLength) {
newPointInTrimesh = lineEndInTrimesh;
}
else {
LOGGER_WARNING() <<
"An error occurred while intersecting the ray with triangles:\n" <<
"tested triangle normal is orthogonal to terrain normal.\n" <<
LOGGER_END();
}
traversedLength += (newPointInTrimesh - pointInTrimesh).
length();
if ( traversedLength > segmentRestLength) {
atEndLength = true;
agx::Vec3 dir = newPointInTrimesh - pointInTrimesh;
newPointInTrimesh -= dir * (traversedLength - segmentRestLength);
}
pointInTrimesh = newPointInTrimesh;
if (!atEndLength){
}
numTriangles++;
}
}
private:
size_t m_maxIt;
bool m_valid;
};
}
{
std::cout << "Trimesh traversal along a line.\nPress 'g' to turn on debug rendering.\n" <<
"Observe how the lines attached to the sphere are projected to the trimesh, beginning from the first intersection.\n";
osg::Group* root = new osg::Group();
if ( trimesh ) {
trimeshGeo = new agxCollide::Geometry();
trimeshGeo->add( trimesh );
}
else
if ( trimeshGeo ) {
trimeshBody->
add( trimeshGeo );
}
else
simulation->
add( trimeshBody );
sphereBody->
add(sphereGeo);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 2; ++j) {
lineGeo->setEnableCollisions(trimeshGeo, false);
lineGeo->setSensor(true);
simulation->
add(
new TriangleTraverser(trimeshGeo, lineGeo,
agx::Vec4(dirs[i], 1)));
sphereBody->
add( lineGeo );
}
}
simulation->
add(sphereBody);
}
{
std::cout << "Trimesh traversal along a line.\nPress 'g' to turn on debug rendering.\n" <<
"Observe how the lines attached to the sphere are projected to the trimesh, beginning from the first intersection.\n";
osg::Group* root = new osg::Group();
if ( trimesh ) {
trimeshGeo = new agxCollide::Geometry();
trimeshGeo->add( trimesh );
}
else
if ( trimeshGeo ) {
trimeshBody->
add( trimeshGeo );
}
else
simulation->
add( trimeshBody );
sphereBody->
add(sphereGeo);
for (int i = 0; i < 3; ++i) {
{
lineGeo->setEnableCollisions(trimeshGeo, false);
lineGeo->setSensor(true);
simulation->
add(
new TriangleTraverser(trimeshGeo, lineGeo,
agx::Vec4(dirs[i], 1)));
sphereBody->
add( lineGeo );
}
{
lineGeo->setEnableCollisions(trimeshGeo, false);
lineGeo->setSensor(true);
simulation->
add(
new TriangleTraverser(trimeshGeo, lineGeo,
agx::Vec4(dirs[i], 1)));
sphereBody->
add( lineGeo );
}
}
simulation->
add(sphereBody);
}
namespace {
struct Settings {
double reductionRatio = 0;
double aggressiveness = 0;
Settings(double reduction, double agg) :
reductionRatio(reduction),
aggressiveness(agg)
{
}
Settings(const Settings& s) :
reductionRatio(s.reductionRatio),
aggressiveness(s.aggressiveness)
{
}
};
std::ostream&
operator <<(std::ostream& os,
const Settings& s)
{
os <<
agx::String::format(
"ReductionRatio=%f, aggressiveness=%f", s.reductionRatio, s.aggressiveness);
return os;
}
{
public:
MeshReducer(
const agxCollide::MeshData *meshData,
const Settings& settings) : BasicThread(), m_meshData(meshData), m_settings(settings), m_time(0)
{
}
double getTime() const
{
return m_time;
}
Settings getSettings() const
{
return m_settings;
}
{
return m_trimesh;
}
void run() override
{
agxUtil::reduceMesh(m_meshData->getVertices(), m_meshData->getIndices(), outVertices, outIndices, m_settings.reductionRatio, m_settings.aggressiveness);
}
private:
const Settings& m_settings;
double m_time;
};
}
{
osg::Group* root = new osg::Group();
"models/bunny.obj",
rotateAndScale);
if (!originalTrimesh)
std::vector<Settings> settings = {
Settings({0.99999,7}),
Settings({0.9,7}),
Settings({0.6,7}),
Settings({0.3,7}),
Settings({0.1,7}),
Settings({0.05,100}),
Settings({0.2,10}),
Settings({0.4,200}),
Settings({0.8,200}),
};
std::cerr << "Creating Mesh reducers..." << std::endl;
for (const auto& s : settings)
{
auto reducer = new MeshReducer(originalTrimesh->getMeshData(), s);
}
std::for_each(meshReducers.begin(), meshReducers.end(), [](MeshReducer* c) { c->start(); });
std::for_each(meshReducers.begin(), meshReducers.end(), [](MeshReducer* c) { c->join(); });
int i = 0;
for (auto t : meshReducers)
{
std::cerr << t->getSettings() << ": " << t->getTime() << " ms." << std::endl;
{
auto geometry = new agxCollide::Geometry(t->getTrimesh());
meshRigidBody->
add(geometry);
}
meshRigidBody->
setName(
"MeshReduction");
std::stringstream str;
str << t->getSettings() << ": " << t->getTrimesh()->getMeshData()->getIndices().size()/3 << " triangles" << std::ends;
simulation->
add(meshRigidBody);
i++;
}
meshReducers.clear();
staticRB->
add(staticBodyGeometry);
simulation->
add(staticRB);
}
int main( int argc, char** argv )
{
std::cout <<
"\tTutorial Trimesh\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
application->addScene( buildTutorial3, '3' );
application->addScene( traversalTutorial1, '5' );
application->addScene( traversalTutorial2, '6' );
application->addScene(traversalTutorial3, '7');
application->addScene(reduceMeshTutorial, '8');
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_wind.cpp
#include "tutorialUtils.h"
namespace
{
{
}
{
}
{
return getShape( getGeometry( rb ) );
}
{
public:
: m_windGenerator( windGenerator ), m_app( app ) {
setMask( KEYBOARD | UPDATE ); }
virtual bool keyboard(
int key,
unsigned int ,
float ,
float ,
bool down )
override {
m_windGenerator->setVelocity( m_windGenerator->getVelocity() +
agx::Real( 0.1 ) * m_windGenerator->getVelocity().normal() );
m_windGenerator->setVelocity( m_windGenerator->getVelocity() -
agx::Real( 0.1 ) * m_windGenerator->getVelocity().normal() );
m_windGenerator->setVelocity( dq * m_windGenerator->getVelocity() );
m_windGenerator->setVelocity( dq.conj() * m_windGenerator->getVelocity() );
}
virtual void update(
float ,
float )
override {
if ( m_app == 0L )
return;
m_app->getSceneDecorator()->setText( 0, "Change wind speed: Key up and key down." );
m_app->getSceneDecorator()->setText( 1, "Change wind direction (in xy plane): Key left and key right." );
m_app->getSceneDecorator()->setText( 2,
agx::String::format(
"Wind velocity: [%2.3f %2.3f %2.3f] m/s", m_windGenerator->getVelocity().x(), m_windGenerator->getVelocity().y(), m_windGenerator->getVelocity().z() ),
agxRender::Color::Red() );
}
private:
};
}
{
osg::Group* root = new osg::Group();
simulation->
add( controller );
simulation->
add( ground );
simulation->
add( sphere );
simulation->
add( boxWire );
controller->setEnableAerodynamics( sphere, true );
controller->setEnableAerodynamics( box, true );
controller->setWindGenerator( windGenerator );
simulation->
add( new ::Tutorial1WindControl( windGenerator, application ) );
}
namespace
{
{
public:
CustomWindGenerator(
const agxCollide::Geometry* shadowingGeometry,
const agx::Vec3& halfExtents,
const agx::Vec3& windVelocity )
: m_shadowingGeometry( shadowingGeometry ), m_halfExtents( halfExtents ), m_windVelocity( windVelocity )
{
}
virtual void prepare( const agxCollide::Geometry* ) override
{
m_cachedFarPlanePos[ 0 ] = m_shadowingGeometry->getPosition() + m_shadowingGeometry->getFrame()->transformVectorToWorld(
agx::Vec3( -m_halfExtents.x(), 0, 0 ) );
m_cachedFarPlanePos[ 1 ] = m_shadowingGeometry->getPosition() + m_shadowingGeometry->getFrame()->transformVectorToWorld(
agx::Vec3( 0, m_halfExtents.y(), 0 ) );
m_cachedFarPlanePos[ 2 ] = m_shadowingGeometry->getPosition() + m_shadowingGeometry->getFrame()->transformVectorToWorld(
agx::Vec3( 0, -m_halfExtents.y(), 0 ) );
m_cachedFarPlanePos[ 3 ] = m_shadowingGeometry->getPosition() + m_shadowingGeometry->getFrame()->transformVectorToWorld(
agx::Vec3( 0, 0, m_halfExtents.z() ) );
}
{
return isShadowed( worldPoint ) ?
agx::Vec3() : m_windVelocity;
}
protected:
CustomWindGenerator() {}
private:
{
return worldPoint.
x() < m_cachedFarPlanePos[ 0 ].x() &&
worldPoint.
y() < m_cachedFarPlanePos[ 1 ].y() &&
worldPoint.
y() > m_cachedFarPlanePos[ 2 ].y() &&
worldPoint.
z() < m_cachedFarPlanePos[ 3 ].z();
}
private:
};
{
out <<
agxStream::out(
"shadowingGeometry", m_shadowingGeometry.get() );
}
{
agxCollide::Geometry* shadowingGeometry = 0L;
m_shadowingGeometry = shadowingGeometry;
}
}
{
osg::Group* root = new osg::Group();
simulation->
add( controller );
simulation->
add( ground );
simulation->
add( shadowingBox );
simulation->
add( sphere1 );
simulation->
add( sphere2 );
simulation->
add( sphere3 );
simulation->
add( sphere4 );
controller->setEnableAerodynamics( sphere1, true );
controller->setEnableAerodynamics( sphere2, true );
controller->setEnableAerodynamics( sphere3, true );
controller->setEnableAerodynamics( sphere4, true );
sphere2AeroParameters->
setCoefficient( agxModel::WindAndWaterParameters::Coefficient::VISCOUS_DRAG,
agx::Real( 0.5 ) );
controller->setWindGenerator( new ::CustomWindGenerator( shadowingBox, shadowingBoxHalfExtents, windVelocity ) );
}
int main( int argc, char** argv )
{
"\tTutorial hydrodynamics\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_wire1.cpp
#include <osg/ShapeDrawable>
#include "tutorialUtils.h"
template < typename T >
{
public:
: m_wire( wire ), m_spline( new T() )
{
osg::Cylinder* cylinder = new osg::Cylinder();
cylinder->set(
osg::Vec3(), (
float)m_wire->getRadius(), 1 );
m_osgCylinder = new osg::Geode;
m_osgCylinder->setCullingActive( false );
osg::TessellationHints* th = new osg::TessellationHints();
th->setDetailRatio( 0.4f );
osg::ShapeDrawable* drawable = new osg::ShapeDrawable( cylinder, th );
m_osgCylinder->getOrCreateStateSet();
m_osgCylinder->addDrawable( drawable );
m_group = new osg::Group;
m_group->setDataVariance( osg::Object::STATIC );
root->addChild( m_group.get() );
}
protected:
virtual ~RenderWireListener() {}
{
if( m_wire.isValid() )
render();
}
{
if ( !m_wire.isValid() ) {
return;
}
render();
}
void render()
{
m_spline->clear();
size_t objCounter = 0;
if ( !m_wire->getRenderListEmpty() ) {
while ( renderIt != renderEndIt ) {
m_spline->add( node->
getWorldPosition(), agx::clamp< agx::Real >( m_wire->getTension( node ).prev.raw / refMaxTension, 0, 1 ) );
}
else
++renderIt;
}
m_spline->updateTangents();
const size_t numControlPoints = m_spline->getNumPoints() - 1;
const size_t numSegments = 40;
agxUtil::CubicSpline::Point prevPoint = m_spline->getPoints()[ 0 ];
for ( size_t i = 0; i < numControlPoints; ++i ) {
agxUtil::CubicSpline::Point point = m_spline->evaluate( i, t );
bool valid = addCylinder( prevPoint, point, objCounter );
objCounter += valid;
prevPoint = point;
}
start = 0;
}
}
if ( objCounter < m_group->getNumChildren() ) {
m_group->removeChildren( (unsigned int)objCounter, m_group->getNumChildren() - (unsigned int)objCounter );
}
}
{
if ( length < 1E-3 )
return false;
bool reused = index < m_group->getNumChildren();
osg::MatrixTransform* worldTransform = reused ? dynamic_cast< osg::MatrixTransform* >( m_group->getChild( (unsigned int)index ) ) : new osg::MatrixTransform;
assert( worldTransform );
assert( !reused || worldTransform->getNumChildren() == 1 );
osg::MatrixTransform* scaleTransform = reused ? dynamic_cast< osg::MatrixTransform* >( worldTransform->getChild( 0 ) ) : new osg::MatrixTransform;
assert( scaleTransform );
scaleTransform->setMatrix( osg::Matrix::scale( 1, length, 1 ) );
if ( !reused ) {
scaleTransform->addChild( m_osgCylinder.get() );
worldTransform->addChild( scaleTransform );
worldTransform->setDataVariance( osg::Object::STATIC );
worldTransform->computeBound();
m_group->addChild( worldTransform );
}
return true;
}
protected:
osg::ref_ptr< osg::Geode > m_osgCylinder;
osg::ref_ptr< osg::Group > m_group;
agxUtil::SplineRef m_spline;
};
{
osg::Group* root = new osg::Group();
agx::Real wireResolutionPerUnitLength( 0.5 );
bool collisionsEnabled = true;
}
{
osg::Group* root = new osg::Group();
agx::Real wireResolutionPerUnitLength( 0.5 );
bool collisionsEnabled = true;
{
wire->add( beginNode );
wire->add( endNode );
simulation->
add(
new RenderWireListener< agxUtil::CardinalSpline >( wire, root ) );
}
{
simulation->
add( rbBox );
wire->add( beginNode );
wire->add( endNode );
simulation->
add(
new RenderWireListener< agxUtil::CardinalSpline >( wire, root ) );
}
{
simulation->
add( rbBox );
wire->add( beginNode );
wire->add( boxNode1 );
wire->add( boxNode2 );
wire->add( endNode );
simulation->
add(
new RenderWireListener< agxUtil::CardinalSpline >( wire, root ) );
}
{
simulation->
add( beginBox );
simulation->
add( endBox );
simulation->
add( slidingBox1 );
simulation->
add( slidingBox2 );
wire->add( beginNode );
wire->add( eyeBox1 );
wire->add( eyeBox2 );
wire->add( endNode );
simulation->
add(
new RenderWireListener< agxUtil::CardinalSpline >( wire, root ) );
}
}
{
osg::Group* root = new osg::Group();
simulation->
add( rbBox1 );
simulation->
add( rbBox2 );
simulation->
add( rbBox3 );
{
winch->setForceRange( maxWinchForce );
winch->setSpeed( desiredWinchSpeed );
winch->setBrakeForceRange( brakeForce );
winch->setAutoFeed( true );
wire->add( winch, wireLength );
std::cout << " * Wire 1 *" << std::endl;
std::cout << " - Rest length after initialize: " << wire->getRestLength() << " m." << std::endl;
std::cout << " - Winch pulled in length after initialize: " << wire->getWinchController( 0 )->getPulledInWireLength( ) << " m." << std::endl << std::endl;
}
{
winch->setAutoFeed( false );
wire->add( winch, wireLengthInsideWinch );
std::cout << " * Wire 2 *" << std::endl;
std::cout << " - Rest length after initialize: " << wire->getRestLength() << " m." << std::endl;
std::cout << " - Winch pulled in length after initialize: " << wire->getWinchController( 0 )->getPulledInWireLength( ) << " m." << std::endl << std::endl;
}
{
agx::Real wireResolutionPerUnitLength( 0.333 );
winch1->setAutoFeed( true );
winch2->setAutoFeed( true );
wire->add( winch1, initialLengthInWinch1 );
wire->add( winch2, initialLengthInWinch2 );
std::cout << " * Wire 3 *" << std::endl;
std::cout << " - Rest length after initialize: " << wire->getRestLength() << " m." << std::endl;
std::cout << " - Winch 1 pulled in length after initialize: " << wire->getWinchController( 0 )->getPulledInWireLength( ) << " m." << std::endl;
std::cout << " - Winch 2 pulled in length after initialize: " << wire->getWinchController( 1 )->getPulledInWireLength( ) << " m." << std::endl << std::endl;
}
}
{
osg::Group* root = new osg::Group();
simulation->
add( assembly );
rbBox->
add( rbBoxGeometry );
rbBoxGeometry->setMaterial( rbBoxMaterial );
assembly->add( rbBox );
for ( size_t i = 0; i < 2; ++i ) {
assembly->add( rb1 );
assembly->add( rb2 );
simulation->
add( wires[ i ] );
}
wires[ 0 ]->setMaterial( wire1Material );
wires[ 1 ]->getMaterial()->getBulkMaterial()->setYoungsModulus( 2E8 );
}
{
osg::Group* root = new osg::Group();
simulation->
add( rbBox1 );
simulation->
add( slidingBox );
wire->add( eye );
eye->getMaterial()->setFrictionCoefficient(
agx::Real( 1.5 ) );
wire->setEnableCollisions( slidingBox, false );
}
{
osg::Group* root = new osg::Group();
simulation->
add( rbBox1 );
simulation->
add( rbBox2 );
simulation->
add( dynBox1 );
simulation->
add( dynBox2 );
wire->getMaterial()->getWireMaterial()->setYoungsModulusStretch( 1E9 );
wire->getMaterial()->getWireMaterial()->setYoungsModulusBend( 1 );
wire->getMaterial()->getBulkMaterial()->setDensity( 1000 );
wire->getMaterial()->getSurfaceMaterial()->setRoughness( 0 );
}
{
planeGeometry->setName("Plane1");
planeGeometry->setMaterial(planeMaterial);
simulation->
add(rbBoxPlane);
structure->
add(rbBoxPlane);
planeGeometry2->setName("Plane2");
planeGeometry2->setMaterial(planeMaterial);
simulation->
add(rbBoxPlane2);
structure->
add(rbBoxPlane2);
simulation->
add(rbBoxWinch);
structure->
add(rbBoxWinch);
pipeGeom->setName("Pipe");
pipeGeom->setMaterial(pipeMaterial);
simulation->
add(rbPipeMesh);
structure->
add(rbPipeMesh);
wire->setMaterial(wireMaterial);
winch->setForceRange(maxWinchForce);
winch->setSpeed(desiredWinchSpeed);
winch->setBrakeForceRange(brakeForce);
winch->setAutoFeed(true);
wire->add(winch, wireLength);
simulation->
add(structure);
return structure;
}
{
osg::Group* root = new osg::Group();
agxSDK::AssemblyRef s1 = createScene7Structure(simulation, application, root, !useDynamicContacts, -translate);
agxSDK::AssemblyRef s2 = createScene7Structure(simulation, application, root, useDynamicContacts, translate);
}
{
for(
agx::Int i = 0; i < numPoints; i++ ) {
convexPoints.
push_back(
agx::Vec3( radius * std::cos( angle ) * scaling.
x(), 0, radius * std::sin( angle ) * scaling.
z() ) + center );
angle += step;
}
return convexPoints;
}
{
for(
agx::UInt i = 0, numVertices = vertices.
size(); i < numVertices; ++i )
}
{
osg::Group* root = new osg::Group();
simulation->
add( rbBox );
{
simulation->
add( eyeNodeAreaBody );
simulation->
add( weight );
simulation->
add( eyeBody );
wire->add( eyeNode );
simulation->
add( wireRenderer );
simulation->
add( eyeNodeArea );
}
{
meshReader->readFile( "models/torusForCollision.obj" );
::scaleMesh( meshReader->getVertices(), scaling );
simulation->
add( eyeNodeAreaBody );
eyeNodeAreaBody->setPosition( 5, -4, 0 );
simulation->
add( weight );
simulation->
add( eyeBody );
eyeBody->
setPosition( eyeNodeAreaBody->getPosition() );
wire->add( eyeNode );
simulation->
add( wireRenderer );
auto convexPoints = createConvexPoints( 10, 0.8, eyeNodeAreaBody->getCmLocalTranslate(), scaling );
simulation->
add( eyeNodeArea );
}
}
int main( int argc, char** argv )
{
"\tTutorial wire\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
application->addScene( buildTutorial3, '3' );
application->addScene( buildTutorial4, '4' );
application->addScene( buildTutorial5, '5' );
application->addScene( buildTutorial6, '6');
application->addScene( buildTutorial7, '7' );
application->addScene( buildTutorial8, '8' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_wireLink.cpp
namespace
{
{
}
{
if ( root != 0L ) {
wireRenderer->setColor( color );
simulation->
add( wireRenderer );
}
}
}
{
osg::Group* root = new osg::Group();
link->getRigidBody()->setPosition( 0, 0, 2 );
wire1->add( link );
wire2->add( link );
simulation->
add( wire1 );
simulation->
add( wire2 );
}
{
osg::Group* root = new osg::Group();
beginLink->getRigidBody()->setPosition( -15, 0, 3 );
link12->getRigidBody()->setPosition( -5, 0, 0 );
link23->getRigidBody()->setPosition( 5, 0, 5 );
endLink->getRigidBody()->setPosition( 12, 0, -3 );
wire1->add( beginLink );
wire1->add( link12 );
wire2->add( link12 );
wire2->add( link23 );
wire3->add( link23 );
wire3->add( endLink );
simulation->
add( wire1 );
simulation->
add( wire2 );
simulation->
add( wire3 );
}
{
osg::Group* root = new osg::Group();
link->getRigidBody()->setPosition( 0, 0, 2 );
simulation->
add( winchRb );
wire1->add( winch );
wire1->add( link );
wire2->add( link );
simulation->
add( wire1 );
simulation->
add( wire2 );
}
{
osg::Group* root = new osg::Group();
simulation->
add( ground );
winch->add( pulledInWire1, 150 );
winch->add( pulledInWire2, 80 );
winch->add( pulledInWire3, 250 );
activeLink12->getRigidBody()->setPosition( 8, 0, 1 );
activeWire1->add( winch, 5 );
activeWire1->add( activeLink12 );
activeWire2->add( activeLink12 );
simulation->
add( activeWire1 );
simulation->
add( activeWire2 );
}
{
osg::Group* root = new osg::Group();
link1->getRigidBody()->setPosition( 0, -yOffset, 0 );
link2->getRigidBody()->setPosition( 0, 0, 0 );
link3->getRigidBody()->setPosition( 0, yOffset, 0 );
}
{
osg::Group* root = new osg::Group();
link1->getDefaultWireConnectionProperties()->setBendStiffness( connectionStiffness );
link2->getDefaultWireConnectionProperties()->setBendStiffness( connectionStiffness );
link3->getDefaultWireConnectionProperties()->setBendStiffness( connectionStiffness );
link1->getRigidBody()->setPosition( 0, -yOffset, 0 );
link2->getRigidBody()->setPosition( 0, 0, 0 );
link3->getRigidBody()->setPosition( 0, yOffset, 0 );
}
{
osg::Group* root = new osg::Group();
simulation->
add( ground );
link1->getRigidBody()->setPosition( -0.3, 0, 1 );
link2->getRigidBody()->setPosition( 0.3, 0, 1 );
wire1->add( link1,
agx::Vec3( -0.3, 0, 0 ) );
link1->connect( link2, agx::Constraint::createFromBody< agx::Hinge >(
agx::Vec3( 0.3, 0, 0 ),
agx::Vec3::X_AXIS(), link1->getRigidBody(), link2->getRigidBody() ) );
if ( link2ToLink1Connection != link1ToLink2Connection )
std::cout << "Expected: The nodes are not the same." << std::endl;
else
std::cout << "THE NODES ARE SAME?!" << std::endl;
if ( thisIsLink2ToLink1Connection == link2ToLink1Connection )
std::cout << "Expected: link2ToLink1Connection FOUND!" << std::endl;
else
std::cout << "link2ToLink1Connection LOST?!" << std::endl;
if ( h1 == h2 )
std::cout << "Expected: Access to the constraint from both links works!" << std::endl;
else
std::cout << "Where are the constraints?!" << std::endl;
link1->getRigidBody()->setAngularVelocity( 2.5, 0, 0 );
}
int main( int argc, char** argv )
{
application->addScene( buildScene1, '1' );
application->addScene( buildScene2, '2' );
application->addScene( buildScene3, '3' );
application->addScene( buildScene4, '4' );
application->addScene( buildScene5, '5' );
application->addScene( buildScene6, '6' );
application->addScene( buildScene7, '7' );
try {
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
tutorial_wireWindAndWater.cpp
#include "tutorialUtils.h"
namespace
{
{
return node;
}
}
{
osg::Group* root = new osg::Group( );
waterGeometry->setPosition( 0, 0, -10 );
waterGeometry->setMaterial( waterMaterial );
::createWaterVisual( waterGeometry, root );
controller->addWater( waterGeometry );
simulation->
add( controller );
simulation->
add( waterGeometry );
simulation->
add( wire1 );
wire1->setEnableCollisions( waterGeometry, false );
controller->setEnableAerodynamics( wire1, false );
simulation->
add( wireRenderer1 );
simulation->
add( wire2 );
simulation->
add( wireRenderer2 );
simulation->
add( wire3 );
controller->getOrCreateHydrodynamicsParameters( wire3 )->setCoefficient( agxModel::WindAndWaterParameters::Coefficient::PRESSURE_DRAG,
agx::Real( 1.5 ) );
simulation->
add( wireRenderer3 );
}
{
osg::Group* root = new osg::Group( );
simulation->
add( controller );
simulation->
add( wire1 );
simulation->
add( wireRenderer1 );
simulation->
add( wire2 );
controller->setEnableAerodynamics( wire2, true );
controller->getOrCreateAerodynamicsParameters( wire2 )->setCoefficient( agxModel::WindAndWaterParameters::Coefficient::PRESSURE_DRAG,
agx::Real( 1 ) );
simulation->
add( wireRenderer2 );
simulation->
add( wire3 );
controller->setEnableAerodynamics( wire3, true );
controller->getOrCreateAerodynamicsParameters( wire3 )->setCoefficient( agxModel::WindAndWaterParameters::Coefficient::PRESSURE_DRAG,
agx::Real( 2 ) );
simulation->
add( wireRenderer3 );
}
{
osg::Group* root = new osg::Group( );
simulation->
add( controller );
controller->setWindGenerator( windGenerator );
simulation->
add( wire1 );
simulation->
add( wireRenderer1 );
simulation->
add( wire2 );
controller->setEnableAerodynamics( wire2, true );
controller->getOrCreateAerodynamicsParameters( wire2 )->setCoefficient( agxModel::WindAndWaterParameters::Coefficient::PRESSURE_DRAG,
agx::Real( 1 ) );
simulation->
add( wireRenderer2 );
simulation->
add( wire3 );
controller->setEnableAerodynamics( wire3, true );
controller->getOrCreateAerodynamicsParameters( wire3 )->setCoefficient( agxModel::WindAndWaterParameters::Coefficient::PRESSURE_DRAG,
agx::Real( 2 ) );
simulation->
add( wireRenderer3 );
}
int main( int argc, char** argv )
{
"\tTutorial wire - wind and water\n" <<
"\t--------------------------------\n\n" << std::endl;
try {
application->addScene( buildTutorial1, '1' );
application->addScene( buildTutorial2, '2' );
application->addScene( buildTutorial3, '3' );
if ( application->init( argc, argv ) )
return application->run();
}
catch ( std::exception& e ) {
std::cerr << "\nCaught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}