7 #include "VsMovableItem.h"
10 #include "VsMotorizedJoint.h"
11 #include "VsRigidBody.h"
14 #include "VsClassFactory.h"
15 #include "VsSimulator.h"
18 #include "VsMouseSpring.h"
20 #include "VsCameraManipulator.h"
21 #include "VsDragger.h"
22 #include "MeshMinVertexDistanceVisitor.h"
32 VsSimulator::VsSimulator()
42 m_dblTotalStepTime = 0;
44 m_dblTotalStepTime= 0;
46 m_dblTotalVortexStepTime = 0;
47 m_lStepVortexTimeCount = 0;
49 m_osgAlphafunc = NULL;
52 VsSimulator::~VsSimulator()
72 {
Std_TraceMsg(0,
"Caught Error in desctructor of Simulator\r\n",
"", -1,
false,
true);}
75 VxUniverse *VsSimulator::Universe()
78 Vx::VxFrame* VsSimulator::Frame()
81 void VsSimulator::AlphaThreshold(
float fltValue)
83 Simulator::AlphaThreshold(fltValue);
90 #pragma region MutatorOverrides
94 Simulator::StabilityScale(fltVal);
95 SetSimulationStabilityParams();
100 Simulator::LinearCompliance(fltVal, bUseScaling);
101 SetSimulationStabilityParams();
106 Simulator::AngularCompliance(fltVal, bUseScaling);
107 SetSimulationStabilityParams();
112 Simulator::LinearDamping(fltVal, bUseScaling);
113 SetSimulationStabilityParams();
118 Simulator::AngularDamping(fltVal, bUseScaling);
119 SetSimulationStabilityParams();
124 Simulator::LinearKineticLoss(fltVal, bUseScaling);
125 SetSimulationStabilityParams();
130 Simulator::AngularKineticLoss(fltVal, bUseScaling);
131 SetSimulationStabilityParams();
136 Simulator::PhysicsTimeStep(fltVal);
141 SetSimulationStabilityParams();
147 Simulator::Gravity(fltVal, bUseScaling);
157 VxMaterialTable *lpMat = m_vxFrame->getMaterialTable();
160 return lpMat->getMaterialID(strID.c_str());
181 m_vxFrame->release();
186 if(m_osgCmdMgr.valid())
187 m_osgCmdMgr.release();
199 Simulator::ResetSimulation();
203 m_uUniverse->resetDynamics();
204 m_uUniverse->resetContacts();
227 void VsSimulator::InitializeVortexViewer(
int argc,
const char **argv)
229 osg::ArgumentParser arguments(&argc, (
char **) argv);
231 osg::setNotifyLevel(osg::NotifySeverity::NOTICE);
236 arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
237 arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+
" is the standard OpenSceneGraph example which loads and visualises 3d models.");
238 arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+
" [options] filename ...");
239 arguments.getApplicationUsage()->addCommandLineOption(
"-h or --help",
"Display this information");
242 osgDB::FilePathList aryList = osgDB::getLibraryFilePathList();
245 aryList.push_front(strPath);
246 osgDB::setLibraryFilePathList(aryList);
249 osgDB::getDataFilePathList().push_front(
"./Resources");
250 osgDB::getDataFilePathList().push_front(
"../Resources");
251 osgDB::getDataFilePathList().push_front(
"../../Resources");
253 std::string strFile = osgDB::findLibraryFile(
"osgdb_freetype.dll");
257 m_grpScene =
new osg::Group;
258 m_grpScene->setName(
"World");
261 m_grpScene->addChild(VsMouseSpring::GetInstance()->
GetNode());
267 if(!m_osgCmdMgr.valid())
268 m_osgCmdMgr =
new osgManipulator::CommandManager;
270 osg::StateSet* rootStateSet = m_grpScene->getOrCreateStateSet();
271 rootStateSet->setMode( GL_LIGHTING, osg::StateAttribute::ON );
272 rootStateSet->setMode( GL_LIGHT0, osg::StateAttribute::ON );
276 m_osgAlphafunc =
new osg::AlphaFunc;
278 rootStateSet->setAttributeAndModes(m_osgAlphafunc, osg::StateAttribute::ON);
283 void VsSimulator::SetSimulationStabilityParams()
312 VxSolverParameters* sp = m_uUniverse->getSolverParameters(0);
313 sp->setConstraintLinearKineticLoss(sp->getConstraintLinearKineticLoss()*
m_fltStabilityScale);
314 sp->setConstraintLinearKineticLoss(sp->getConstraintAngularKineticLoss()*
m_fltStabilityScale);
315 sp->setConstraintLinearCompliance(sp->getConstraintLinearCompliance()/
m_fltStabilityScale);
316 sp->setConstraintAngularCompliance(sp->getConstraintAngularCompliance()/
m_fltStabilityScale);
320 TRACE_DETAIL(
"Reset simulation stability params\r\n");
321 TRACE_DETAIL(
"Angular Compliance: " + STR(m_uUniverse->getSolverParameters(0)->getConstraintAngularCompliance()) +
"\r\n");
322 TRACE_DETAIL(
"Angular Damping: " + STR(m_uUniverse->getSolverParameters(0)->getConstraintAngularDamping()) +
"\r\n");
323 TRACE_DETAIL(
"Angular Kinetic Loss: " + STR(m_uUniverse->getSolverParameters(0)->getConstraintAngularKineticLoss()) +
"\r\n");
324 TRACE_DETAIL(
"Linear Compliance: " + STR(m_uUniverse->getSolverParameters(0)->getConstraintLinearCompliance()) +
"\r\n");
325 TRACE_DETAIL(
"Linear Damping: " + STR(m_uUniverse->getSolverParameters(0)->getConstraintLinearDamping()) +
"\r\n");
326 TRACE_DETAIL(
"Linear Kinetic Loss: " + STR(m_uUniverse->getSolverParameters(0)->getConstraintLinearKineticLoss()) +
"\r\n");
332 void VsSimulator::InitializeVortex(
int argc,
const char **argv)
334 InitializeVortexViewer(argc, argv);
337 int iCollisionCount = iObjectCount*40;
340 m_vxFrame = VxFrame::instance();
341 m_uUniverse =
new Vx::VxUniverse(iObjectCount, iCollisionCount);
344 m_vxFrame->addUniverse(m_uUniverse);
349 VxFrameRegisterAllInteractions(m_vxFrame);
351 SetSimulationStabilityParams();
354 m_uUniverse->addIntersectSubscriber(VxUniverse::kResponseSensor, VxUniverse::kResponsePart, VxUniverse::kEventFirst, &m_vsIntersect, 0);
355 m_uUniverse->addIntersectSubscriber(VxUniverse::kResponseSensor, VxUniverse::kResponsePart, VxUniverse::kEventDisjoint, &m_vsIntersect, 0);
359 Vx::VxTriangleMesh *VsSimulator::CreatTriangleMeshFromOsg(osg::Node *osgNode)
361 Vx::VxTriangleMesh *vxMesh = NULL;
362 vxMesh = VxTriangleMesh::createFromNode(osgNode);
367 osg::NotifySeverity VsSimulator::ConvertTraceLevelToOSG()
374 return osg::NotifySeverity::FATAL;
376 return osg::NotifySeverity::WARN;
378 return osg::NotifySeverity::INFO;
380 return osg::NotifySeverity::DEBUG_INFO;
382 return osg::NotifySeverity::DEBUG_FP;
384 return osg::NotifySeverity::WARN;
388 Vx::VxConvexMesh *VsSimulator::CreateConvexMeshFromOsg(osg::Node *osgNode)
390 Vx::VxConvexMesh *vxMesh = NULL;
391 vxMesh = VxConvexMesh::createFromNode(osgNode);
415 std::string strOrigFile = AnimatSim::GetFilePath(strPath, strOriginalMeshFile);
416 std::string strNewFile = AnimatSim::GetFilePath(strPath, strCollisionMeshFile);
418 osg::ref_ptr<osg::Node> osgNode = MeshMgr()->LoadMesh(strOrigFile);
422 THROW_PARAM_ERROR(Vs_Err_lErrorLoadingMesh, Vs_Err_strErrorLoadingMesh,
"Original Mesh file", strOriginalMeshFile);
425 Vx::VxConvexMesh *vxMesh = VxConvexMesh::createFromNode(osgNode.get());
428 osg::ref_ptr<osg::Geometry> osgGeom = CreateOsgFromVxConvexMesh(vxMesh);
429 osg::ref_ptr<osg::Geode> osgNewNode =
new osg::Geode;
430 osgNewNode->addDrawable(osgGeom.get());
432 osg::Matrix osgScale = osg::Matrix::scale(fltScaleX, fltScaleY, fltScaleZ);
433 osg::ref_ptr<osg::MatrixTransform> osgScaleMT =
new osg::MatrixTransform(osgScale);
434 osgScaleMT->addChild(osgNewNode.get());
435 osgScaleMT->setDataVariance(osg::Object::STATIC);
439 osgUtil::Optimizer optimizer;
440 optimizer.optimize(osgScaleMT.get(), osgUtil::Optimizer::FLATTEN_STATIC_TRANSFORMS);
443 osgDB::writeNodeFile(*osgNewNode, strNewFile.c_str());
447 Std_SetFileTime(strNewFile);
450 void VsSimulator::ConvertV1MeshFile(std::string strOriginalMeshFile, std::string strNewMeshFile, std::string strTexture)
454 std::string strOrigFile = AnimatSim::GetFilePath(strPath, strOriginalMeshFile);
455 std::string strNewFile = AnimatSim::GetFilePath(strPath, strNewMeshFile);
456 std::string strTextFile =
"";
459 strTextFile = AnimatSim::GetFilePath(strPath, strTexture);
461 osg::ref_ptr<osg::Node> osgNode = osgDB::readNodeFile(strOrigFile.c_str());
465 THROW_PARAM_ERROR(Vs_Err_lErrorLoadingMesh, Vs_Err_strErrorLoadingMesh,
"Original Mesh file", strOriginalMeshFile);
467 CStdFPoint vPos(0, 0, 0), vRot( -(osg::PI/2), 0, 0);
468 ApplyVertexTransform(osgNode.get(), SetupMatrix(vPos, vRot));
470 AddNodeTexture(osgNode.get(), strTextFile, GL_TEXTURE_2D);
473 osgDB::writeNodeFile(*osgNode, strNewFile.c_str());
485 void VsSimulator::GetPositionAndRotationFromD3DMatrix(
float (&aryTransform)[4][4], CStdFPoint &vPos, CStdFPoint &vRot)
487 osg::Matrix osgMT(aryTransform[0][0], aryTransform[0][1], aryTransform[0][2], aryTransform[0][3],
488 aryTransform[1][0], aryTransform[1][1], aryTransform[1][2], aryTransform[1][3],
489 aryTransform[2][0], aryTransform[2][1], aryTransform[2][2], aryTransform[2][3],
490 aryTransform[3][0], aryTransform[3][1], aryTransform[3][2], aryTransform[3][3]);
492 osg::Matrix osgFinal;
498 osg::Vec3 vL = osgFinal.getTrans();
499 vPos.Set(vL.x(), vL.y(), vL.z());
500 vPos.ClearNearZero();
504 VxOSG::copyOsgMatrix_to_VxReal44(osgFinal, vxTM);
505 Vx::VxTransform vTrans(vxTM);
507 vTrans.getRotationEulerAngles(vEuler);
508 vRot.Set(vEuler[0], vEuler[1] ,vEuler[2]);
509 vRot.ClearNearZero();
513 unsigned long long VsSimulator::GetTimerTick()
519 double VsSimulator::TimerDiff_n(
unsigned long long lStart,
unsigned long long lEnd)
520 {
return osg::Timer::instance()->delta_n(lStart, lEnd);}
522 double VsSimulator::TimerDiff_u(
unsigned long long lStart,
unsigned long long lEnd)
523 {
return osg::Timer::instance()->delta_u(lStart, lEnd);}
525 double VsSimulator::TimerDiff_m(
unsigned long long lStart,
unsigned long long lEnd)
526 {
return osg::Timer::instance()->delta_m(lStart, lEnd);}
528 double VsSimulator::TimerDiff_s(
unsigned long long lStart,
unsigned long long lEnd)
529 {
return osg::Timer::instance()->delta_s(lStart, lEnd);}
531 void VsSimulator::MicroSleep(
unsigned int iMicroTime)
532 {OpenThreads::Thread::microSleep(iMicroTime);}
534 void VsSimulator::WriteToConsole(std::string strMessage)
536 osg::notify(osg::NOTICE) << strMessage << std::endl;
541 InitializeVortex(argc, argv);
566 Simulator::StepSimulation();
568 unsigned long long lStart = GetTimerTick();
570 double dblVal = TimerDiff_s(lStart, GetTimerTick());
577 m_dblTotalVortexStepTime += dblVal;
578 m_lStepVortexTimeCount++;
582 double dblAvgStepTime = m_dblTotalVortexStepTime/m_lStepVortexTimeCount;
583 osg::notify(osg::NOTICE) <<
"Average step time: " << dblAvgStepTime << std::endl;
584 osg::notify(osg::NOTICE) <<
"Total vortex step time: " << m_dblTotalVortexStepTime << std::endl;
585 osg::notify(osg::NOTICE) <<
"Slice Time: " <<
m_lTimeSlice << std::endl;
586 osg::notify(osg::NOTICE) <<
"Sim Time: " <<
Time() << std::endl;
591 catch(CStdErrorInfo oError)
593 std::string strError =
"An error occurred while step the simulation.\nError: " + oError.m_strError;
594 HandleNonCriticalError(strError);
616 void VsSimulator::UpdateSimulationWindows()
624 m_vxFrame->release();
660 lpData = Simulator::GetDataPointer(strDataType);
662 THROW_TEXT_ERROR(Al_Err_lInvalidDataType, Al_Err_strInvalidDataType,
"Simulator DataType: " + strDataType);
673 THROW_TEXT_ERROR(Al_Err_lConvertingClassToType, Al_Err_strConvertingClassToType,
"KeyFrame");
680 VsSimulator *VsSimulator::ConvertSimulator(Simulator *lpSim)
683 THROW_ERROR(Al_Err_lSimulationNotDefined, Al_Err_strSimulationNotDefined);
688 THROW_ERROR(Vs_Err_lUnableToConvertToVsSimulator, Vs_Err_strUnableToConvertToVsSimulator);
695 std::string strOsgFile = strFile +
".osg";
696 std::string strVxFile = strFile +
".vxf";
697 std::string strUcon = strFile +
".ucon";
702 VxPersistence::saveFrame(strVxFile.c_str(), VxPersistence::kStandard);
704 catch(std::exception ex)
713 m_uUniverse->printContent(strUcon.c_str());
715 osgDB::writeNodeFile(*OSGRoot(), strOsgFile.c_str());
virtual float LinearDamping()
Gets the linear damping of the simulation.
KeyFrame * m_lpSimStopPoint
The pointer to a simulation stop point.
bool m_bPaused
true if the simulation is paused.
virtual float StabilityScale()
Sets the linear scaling factor that controls the simulation stability parameters. ...
virtual float AngularKineticLoss()
Gets the angular kinetic loss of teh simulation.
virtual void Reset()
Resets all objects of the simulation to their unloaded state.
virtual void SetSystemPointers(Simulator *lpSim, Structure *lpStructure, NeuralModule *lpModule, Node *lpNode, bool bVerify)
Sets the system pointers.
virtual void SimulateEnd()
Called at the end of the Simulate method.
virtual void Initialize()
Initializes this object.
virtual float Gravity()
Gets the gravity value.
float m_fltPhysicsStepTime
This is the time pers step for the physics engine.
ExternalStimuliMgr m_oExternalStimuliMgr
Manager for external stimuli.
bool m_bInitialized
true if the simulation has been initialized.
virtual void Realize()
Shows the windows.
virtual float PhysicsTimeStep()
Gets the integration time step for the physics engine.
virtual float LinearCompliance()
Gets the linear compliance of the simulation.
virtual float LinearKineticLoss()
Gets the linear kinetic loss of the simulation.
virtual Node * GetNode()
Gets the node.
LightManager m_oLightMgr
Manager for the light objects.
virtual void InitializeStructures()
Initializes all of the structures of this simulation.
bool m_bShuttingDown
True if the simulation is shutting down. This is used by other objects in their destructor to know wh...
virtual float AngularCompliance()
Gets the angular compliance of the simulation.
Declares the vortex organism class.
bool m_bForceSimulationStop
Set to true to stop the simulation. This is a more forceful way of stopping the sim.
long m_lTimeSlice
The current time slice. This a long value.
float m_fltAlphaThreshold
The threshold value to use when setting the AlphaFunc for the entire scene.
bool m_bSimRunning
true if the simulation is running
unsigned long long m_lLastTickTaken
This is the last tick taken by a GetTickCount. It is used in debugging.
SimulationWindowMgr * m_lpWinMgr
Manager for SimulationWindows.
virtual CStdSerialize * CreateObject(std::string strModule, std::string strClassName, std::string strType, bool bThrowError=true)
Creates an object using a class factory.
float m_fltStabilityScale
A linear scaling factor for setting the simulation parameters.
bool m_bStopSimulation
Set to true to stop the simulation.
virtual void AfterStepSimulation()
Method called for the base Simulator object to run code after the physics engine has been fully stepp...
virtual AnimatSim::Recording::SimulationRecorder * CreateSimulationRecorder()
Creates the simulation recorder.
virtual void ShutdownSimulation()
Shuts down the simulation.
virtual bool StartSimulation()
Starts the simulation.
DataChartMgr m_oDataChartMgr
Manager for data charts.
int Std_GetTraceLevel()
Gets the trace level.
virtual float * GetDataPointer(const std::string &strDataType)
Returns a float pointer to a data item of interest in this object.
virtual std::string ProjectPath()
Gets the project path.
virtual void StepSimulation()
Steps the entire simulation forward by one physics integration time step.
float m_fltGravity
The acceleration of gravity to use in the simulation.
SimulationRecorder * m_lpSimRecorder
The pointer to a simulation recorder.
Classes for implementing the cm-labs vortex physics engine for AnimatLab.
void Std_TraceMsg(const int iLevel, std::string strMessage, std::string strSourceFile, int iSourceLine, bool bLogToFile, bool bPrintHeader)
Traces a message to the debugger window.
virtual void ToggleSimulation()
Toggles the simulation between running and paused.
std::string m_strExecutablePath
The directory path where the executable is located.
virtual void ResetSimulation()
Resets the the simulation to its orginal settings at time 0.
unsigned long long m_lStartSimTick
The tick count for when the simulation first begins running.
virtual void Initialize()
Initializes this object with no argc/argv params.
bool Std_IsBlank(std::string strVal)
Trims a string and tests if a string is blank.
virtual void SimPausing()
Simulation pausing event.
virtual void Save(std::string strFile)
Saves the simulation file.
virtual bool Update()
Updates all of the windows.
std::string Std_CheckString(std::string strVal)
Converts a string to upper case and trims it.
Declares the vortex Light class.
virtual int GetMaterialID(std::string strID)
Gets a material identifier from the physics engine for the specified unique ID.
virtual void SnapshotStopFrame()
Takes a snapshot of the current frame.
virtual void SimStopping()
Simulation stopping event.
virtual float AngularDamping()
Gets the angular damping of the simulation.
virtual float Time()
Gets the current simulation time in seconds.
virtual void SimStarting()
Simulation starting event.
float m_fltPhysicsTimeStep
The time increment for each time slice of the physics simulation.
virtual void GenerateCollisionMeshFile(std::string strOriginalMeshFile, std::string strCollisionMeshFile, float fltScaleX, float fltScaleY, float fltScaleZ)
Generates a collision mesh file.
IStdClassFactory * m_lpAnimatClassFactory
virtual void StopSimulation()
Stops the simulation and resets it.
Declares the vortex structure class.
virtual bool PauseSimulation()
Pauses the simulation.