b3RobotSimAPI.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. #include "b3RobotSimAPI.h"
  2. //#include "../CommonInterfaces/CommonGraphicsAppInterface.h"
  3. #include "Bullet3Common/b3Quaternion.h"
  4. #include "Bullet3Common/b3AlignedObjectArray.h"
  5. #include "../CommonInterfaces/CommonRenderInterface.h"
  6. //#include "../CommonInterfaces/CommonExampleInterface.h"
  7. #include "../CommonInterfaces/CommonGUIHelperInterface.h"
  8. #include "../SharedMemory/PhysicsServerSharedMemory.h"
  9. #include "../SharedMemory/PhysicsServerSharedMemory.h"
  10. #include "../SharedMemory/PhysicsClientC_API.h"
  11. #include "../SharedMemory/PhysicsDirectC_API.h"
  12. #include "../SharedMemory/PhysicsDirect.h"
  13. #include <string>
  14. #include "../Utils/b3Clock.h"
  15. #include "../MultiThreading/b3ThreadSupportInterface.h"
  16. void RobotThreadFunc(void* userPtr,void* lsMemory);
  17. void* RobotlsMemoryFunc();
  18. #define MAX_ROBOT_NUM_THREADS 1
  19. enum
  20. {
  21. numCubesX = 20,
  22. numCubesY = 20
  23. };
  24. enum TestRobotSimCommunicationEnums
  25. {
  26. eRequestTerminateRobotSim= 13,
  27. eRobotSimIsUnInitialized,
  28. eRobotSimIsInitialized,
  29. eRobotSimInitializationFailed,
  30. eRobotSimHasTerminated
  31. };
  32. enum MultiThreadedGUIHelperCommunicationEnums
  33. {
  34. eRobotSimGUIHelperIdle= 13,
  35. eRobotSimGUIHelperRegisterTexture,
  36. eRobotSimGUIHelperRegisterGraphicsShape,
  37. eRobotSimGUIHelperRegisterGraphicsInstance,
  38. eRobotSimGUIHelperCreateCollisionShapeGraphicsObject,
  39. eRobotSimGUIHelperCreateCollisionObjectGraphicsObject,
  40. eRobotSimGUIHelperRemoveAllGraphicsInstances,
  41. eRobotSimGUIHelperCopyCameraImageData,
  42. };
  43. #include <stdio.h>
  44. //#include "BulletMultiThreaded/PlatformDefinitions.h"
  45. #ifndef _WIN32
  46. #include "../MultiThreading/b3PosixThreadSupport.h"
  47. b3ThreadSupportInterface* createRobotSimThreadSupport(int numThreads)
  48. {
  49. b3PosixThreadSupport::ThreadConstructionInfo constructionInfo("RobotSimThreads",
  50. RobotThreadFunc,
  51. RobotlsMemoryFunc,
  52. numThreads);
  53. b3ThreadSupportInterface* threadSupport = new b3PosixThreadSupport(constructionInfo);
  54. return threadSupport;
  55. }
  56. #elif defined( _WIN32)
  57. #include "../MultiThreading/b3Win32ThreadSupport.h"
  58. b3ThreadSupportInterface* createRobotSimThreadSupport(int numThreads)
  59. {
  60. b3Win32ThreadSupport::Win32ThreadConstructionInfo threadConstructionInfo("RobotSimThreads",RobotThreadFunc,RobotlsMemoryFunc,numThreads);
  61. b3Win32ThreadSupport* threadSupport = new b3Win32ThreadSupport(threadConstructionInfo);
  62. return threadSupport;
  63. }
  64. #endif
  65. struct RobotSimArgs
  66. {
  67. RobotSimArgs()
  68. :m_physicsServerPtr(0)
  69. {
  70. }
  71. b3CriticalSection* m_cs;
  72. PhysicsServerSharedMemory* m_physicsServerPtr;
  73. b3AlignedObjectArray<b3Vector3> m_positions;
  74. };
  75. struct RobotSimThreadLocalStorage
  76. {
  77. int threadId;
  78. };
  79. void RobotThreadFunc(void* userPtr,void* lsMemory)
  80. {
  81. printf("RobotThreadFunc thread started\n");
  82. RobotSimThreadLocalStorage* localStorage = (RobotSimThreadLocalStorage*) lsMemory;
  83. RobotSimArgs* args = (RobotSimArgs*) userPtr;
  84. int workLeft = true;
  85. b3Clock clock;
  86. clock.reset();
  87. bool init = true;
  88. if (init)
  89. {
  90. args->m_cs->lock();
  91. args->m_cs->setSharedParam(0,eRobotSimIsInitialized);
  92. args->m_cs->unlock();
  93. do
  94. {
  95. //todo(erwincoumans): do we want some sleep to reduce CPU resources in this thread?
  96. #if 0
  97. double deltaTimeInSeconds = double(clock.getTimeMicroseconds())/1000000.;
  98. if (deltaTimeInSeconds<(1./260.))
  99. {
  100. if (deltaTimeInSeconds<.001)
  101. continue;
  102. }
  103. clock.reset();
  104. #endif //
  105. args->m_physicsServerPtr->processClientCommands();
  106. } while (args->m_cs->getSharedParam(0)!=eRequestTerminateRobotSim);
  107. } else
  108. {
  109. args->m_cs->lock();
  110. args->m_cs->setSharedParam(0,eRobotSimInitializationFailed);
  111. args->m_cs->unlock();
  112. }
  113. //do nothing
  114. }
  115. void* RobotlsMemoryFunc()
  116. {
  117. //don't create local store memory, just return 0
  118. return new RobotSimThreadLocalStorage;
  119. }
  120. ATTRIBUTE_ALIGNED16(class) MultiThreadedOpenGLGuiHelper2 : public GUIHelperInterface
  121. {
  122. CommonGraphicsApp* m_app;
  123. b3CriticalSection* m_cs;
  124. public:
  125. BT_DECLARE_ALIGNED_ALLOCATOR();
  126. GUIHelperInterface* m_childGuiHelper;
  127. const unsigned char* m_texels;
  128. int m_textureWidth;
  129. int m_textureHeight;
  130. int m_shapeIndex;
  131. const float* m_position;
  132. const float* m_quaternion;
  133. const float* m_color;
  134. const float* m_scaling;
  135. const float* m_vertices;
  136. int m_numvertices;
  137. const int* m_indices;
  138. int m_numIndices;
  139. int m_primitiveType;
  140. int m_textureId;
  141. int m_instanceId;
  142. MultiThreadedOpenGLGuiHelper2(CommonGraphicsApp* app, GUIHelperInterface* guiHelper)
  143. :m_app(app)
  144. ,m_cs(0),
  145. m_texels(0),
  146. m_textureId(-1)
  147. {
  148. m_childGuiHelper = guiHelper;;
  149. }
  150. virtual ~MultiThreadedOpenGLGuiHelper2()
  151. {
  152. delete m_childGuiHelper;
  153. }
  154. void setCriticalSection(b3CriticalSection* cs)
  155. {
  156. m_cs = cs;
  157. }
  158. b3CriticalSection* getCriticalSection()
  159. {
  160. return m_cs;
  161. }
  162. virtual void createRigidBodyGraphicsObject(btRigidBody* body,const btVector3& color)
  163. {
  164. createCollisionObjectGraphicsObject((btCollisionObject*)body, color);
  165. }
  166. btCollisionObject* m_obj;
  167. btVector3 m_color2;
  168. virtual void createCollisionObjectGraphicsObject(btCollisionObject* obj,const btVector3& color)
  169. {
  170. m_obj = obj;
  171. m_color2 = color;
  172. m_cs->lock();
  173. m_cs->setSharedParam(1,eRobotSimGUIHelperCreateCollisionObjectGraphicsObject);
  174. m_cs->unlock();
  175. while (m_cs->getSharedParam(1)!=eRobotSimGUIHelperIdle)
  176. {
  177. }
  178. }
  179. btCollisionShape* m_colShape;
  180. virtual void createCollisionShapeGraphicsObject(btCollisionShape* collisionShape)
  181. {
  182. m_colShape = collisionShape;
  183. m_cs->lock();
  184. m_cs->setSharedParam(1,eRobotSimGUIHelperCreateCollisionShapeGraphicsObject);
  185. m_cs->unlock();
  186. while (m_cs->getSharedParam(1)!=eRobotSimGUIHelperIdle)
  187. {
  188. }
  189. }
  190. virtual void syncPhysicsToGraphics(const btDiscreteDynamicsWorld* rbWorld)
  191. {
  192. //this check is to prevent a crash, in case we removed all graphics instances, but there are still physics objects.
  193. //the check will be obsolete, once we have a better/safer way of synchronizing physics->graphics transforms
  194. if ( m_childGuiHelper->getRenderInterface()->getTotalNumInstances()>0)
  195. {
  196. m_childGuiHelper->syncPhysicsToGraphics(rbWorld);
  197. }
  198. }
  199. virtual void render(const btDiscreteDynamicsWorld* rbWorld)
  200. {
  201. m_childGuiHelper->render(0);
  202. }
  203. virtual void createPhysicsDebugDrawer( btDiscreteDynamicsWorld* rbWorld){}
  204. virtual int registerTexture(const unsigned char* texels, int width, int height)
  205. {
  206. m_texels = texels;
  207. m_textureWidth = width;
  208. m_textureHeight = height;
  209. m_cs->lock();
  210. m_cs->setSharedParam(1,eRobotSimGUIHelperRegisterTexture);
  211. m_cs->unlock();
  212. while (m_cs->getSharedParam(1)!=eRobotSimGUIHelperIdle)
  213. {
  214. }
  215. return m_textureId;
  216. }
  217. virtual int registerGraphicsShape(const float* vertices, int numvertices, const int* indices, int numIndices,int primitiveType, int textureId)
  218. {
  219. m_vertices = vertices;
  220. m_numvertices = numvertices;
  221. m_indices = indices;
  222. m_numIndices = numIndices;
  223. m_primitiveType = primitiveType;
  224. m_textureId = textureId;
  225. m_cs->lock();
  226. m_cs->setSharedParam(1,eRobotSimGUIHelperRegisterGraphicsShape);
  227. m_cs->unlock();
  228. while (m_cs->getSharedParam(1)!=eRobotSimGUIHelperIdle)
  229. {
  230. }
  231. return m_shapeIndex;
  232. }
  233. virtual int registerGraphicsInstance(int shapeIndex, const float* position, const float* quaternion, const float* color, const float* scaling)
  234. {
  235. m_shapeIndex = shapeIndex;
  236. m_position = position;
  237. m_quaternion = quaternion;
  238. m_color = color;
  239. m_scaling = scaling;
  240. m_cs->lock();
  241. m_cs->setSharedParam(1,eRobotSimGUIHelperRegisterGraphicsInstance);
  242. m_cs->unlock();
  243. while (m_cs->getSharedParam(1)!=eRobotSimGUIHelperIdle)
  244. {
  245. }
  246. return m_instanceId;
  247. }
  248. virtual void removeAllGraphicsInstances()
  249. {
  250. m_cs->lock();
  251. m_cs->setSharedParam(1,eRobotSimGUIHelperRemoveAllGraphicsInstances);
  252. m_cs->unlock();
  253. while (m_cs->getSharedParam(1)!=eRobotSimGUIHelperIdle)
  254. {
  255. }
  256. }
  257. virtual Common2dCanvasInterface* get2dCanvasInterface()
  258. {
  259. return 0;
  260. }
  261. virtual CommonParameterInterface* getParameterInterface()
  262. {
  263. return 0;
  264. }
  265. virtual CommonRenderInterface* getRenderInterface()
  266. {
  267. return 0;
  268. }
  269. virtual CommonGraphicsApp* getAppInterface()
  270. {
  271. return m_childGuiHelper->getAppInterface();
  272. }
  273. virtual void setUpAxis(int axis)
  274. {
  275. m_childGuiHelper->setUpAxis(axis);
  276. }
  277. virtual void resetCamera(float camDist, float pitch, float yaw, float camPosX,float camPosY, float camPosZ)
  278. {
  279. }
  280. float m_viewMatrix[16];
  281. float m_projectionMatrix[16];
  282. unsigned char* m_pixelsRGBA;
  283. int m_rgbaBufferSizeInPixels;
  284. float* m_depthBuffer;
  285. int m_depthBufferSizeInPixels;
  286. int* m_segmentationMaskBuffer;
  287. int m_segmentationMaskBufferSizeInPixels;
  288. int m_startPixelIndex;
  289. int m_destinationWidth;
  290. int m_destinationHeight;
  291. int* m_numPixelsCopied;
  292. virtual void copyCameraImageData(const float viewMatrix[16], const float projectionMatrix[16],
  293. unsigned char* pixelsRGBA, int rgbaBufferSizeInPixels,
  294. float* depthBuffer, int depthBufferSizeInPixels,
  295. int* segmentationMaskBuffer, int segmentationMaskBufferSizeInPixels,
  296. int startPixelIndex, int destinationWidth,
  297. int destinationHeight, int* numPixelsCopied)
  298. {
  299. m_cs->lock();
  300. for (int i=0;i<16;i++)
  301. {
  302. m_viewMatrix[i] = viewMatrix[i];
  303. m_projectionMatrix[i] = projectionMatrix[i];
  304. }
  305. m_pixelsRGBA = pixelsRGBA;
  306. m_rgbaBufferSizeInPixels = rgbaBufferSizeInPixels;
  307. m_depthBuffer = depthBuffer;
  308. m_depthBufferSizeInPixels = depthBufferSizeInPixels;
  309. m_segmentationMaskBuffer = segmentationMaskBuffer;
  310. m_segmentationMaskBufferSizeInPixels = segmentationMaskBufferSizeInPixels;
  311. m_startPixelIndex = startPixelIndex;
  312. m_destinationWidth = destinationWidth;
  313. m_destinationHeight = destinationHeight;
  314. m_numPixelsCopied = numPixelsCopied;
  315. m_cs->setSharedParam(1,eRobotSimGUIHelperCopyCameraImageData);
  316. m_cs->unlock();
  317. while (m_cs->getSharedParam(1)!=eRobotSimGUIHelperIdle)
  318. {
  319. }
  320. }
  321. virtual void autogenerateGraphicsObjects(btDiscreteDynamicsWorld* rbWorld)
  322. {
  323. }
  324. virtual void drawText3D( const char* txt, float posX, float posZY, float posZ, float size)
  325. {
  326. }
  327. };
  328. struct b3RobotSimAPI_InternalData
  329. {
  330. //GUIHelperInterface* m_guiHelper;
  331. PhysicsServerSharedMemory m_physicsServer;
  332. b3PhysicsClientHandle m_physicsClient;
  333. b3ThreadSupportInterface* m_threadSupport;
  334. RobotSimArgs m_args[MAX_ROBOT_NUM_THREADS];
  335. MultiThreadedOpenGLGuiHelper2* m_multiThreadedHelper;
  336. PhysicsDirect* m_clientServerDirect;
  337. bool m_useMultiThreading;
  338. bool m_connected;
  339. b3RobotSimAPI_InternalData()
  340. :m_threadSupport(0),
  341. m_multiThreadedHelper(0),
  342. m_clientServerDirect(0),
  343. m_physicsClient(0),
  344. m_useMultiThreading(false),
  345. m_connected(false)
  346. {
  347. }
  348. };
  349. b3RobotSimAPI::b3RobotSimAPI()
  350. {
  351. m_data = new b3RobotSimAPI_InternalData;
  352. }
  353. void b3RobotSimAPI::stepSimulation()
  354. {
  355. b3SharedMemoryStatusHandle statusHandle;
  356. int statusType;
  357. b3Assert(b3CanSubmitCommand(m_data->m_physicsClient));
  358. if (b3CanSubmitCommand(m_data->m_physicsClient))
  359. {
  360. statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClient, b3InitStepSimulationCommand(m_data->m_physicsClient));
  361. statusType = b3GetStatusType(statusHandle);
  362. b3Assert(statusType==CMD_STEP_FORWARD_SIMULATION_COMPLETED);
  363. }
  364. }
  365. void b3RobotSimAPI::setGravity(const b3Vector3& gravityAcceleration)
  366. {
  367. b3SharedMemoryCommandHandle command = b3InitPhysicsParamCommand(m_data->m_physicsClient);
  368. b3SharedMemoryStatusHandle statusHandle;
  369. b3PhysicsParamSetGravity(command, gravityAcceleration[0],gravityAcceleration[1],gravityAcceleration[2]);
  370. statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClient, command);
  371. b3Assert(b3GetStatusType(statusHandle)==CMD_CLIENT_COMMAND_COMPLETED);
  372. }
  373. void b3RobotSimAPI::setNumSimulationSubSteps(int numSubSteps)
  374. {
  375. b3SharedMemoryCommandHandle command = b3InitPhysicsParamCommand(m_data->m_physicsClient);
  376. b3SharedMemoryStatusHandle statusHandle;
  377. b3PhysicsParamSetNumSubSteps(command, numSubSteps);
  378. statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClient, command);
  379. b3Assert(b3GetStatusType(statusHandle)==CMD_CLIENT_COMMAND_COMPLETED);
  380. }
  381. /*
  382. b3SharedMemoryCommandHandle b3CalculateInverseKinematicsCommandInit(b3PhysicsClientHandle physClient, int bodyIndex,
  383. const double* jointPositionsQ, double targetPosition[3]);
  384. int b3GetStatusInverseKinematicsJointPositions(b3SharedMemoryStatusHandle statusHandle,
  385. int* bodyUniqueId,
  386. int* dofCount,
  387. double* jointPositions);
  388. */
  389. bool b3RobotSimAPI::calculateInverseKinematics(const struct b3RobotSimInverseKinematicArgs& args, struct b3RobotSimInverseKinematicsResults& results)
  390. {
  391. btAssert(args.m_endEffectorLinkIndex>=0);
  392. btAssert(args.m_bodyUniqueId>=0);
  393. b3SharedMemoryCommandHandle command = b3CalculateInverseKinematicsCommandInit(m_data->m_physicsClient,args.m_bodyUniqueId);
  394. if ((args.m_flags & B3_HAS_IK_TARGET_ORIENTATION) && (args.m_flags & B3_HAS_NULL_SPACE_VELOCITY))
  395. {
  396. b3CalculateInverseKinematicsPosOrnWithNullSpaceVel(command, args.m_numDegreeOfFreedom, args.m_endEffectorLinkIndex, args.m_endEffectorTargetPosition, args.m_endEffectorTargetOrientation, &args.m_lowerLimits[0], &args.m_upperLimits[0], &args.m_jointRanges[0], &args.m_restPoses[0]);
  397. } else if (args.m_flags & B3_HAS_IK_TARGET_ORIENTATION)
  398. {
  399. b3CalculateInverseKinematicsAddTargetPositionWithOrientation(command,args.m_endEffectorLinkIndex,args.m_endEffectorTargetPosition,args.m_endEffectorTargetOrientation);
  400. } else if (args.m_flags & B3_HAS_NULL_SPACE_VELOCITY)
  401. {
  402. b3CalculateInverseKinematicsPosWithNullSpaceVel(command, args.m_numDegreeOfFreedom, args.m_endEffectorLinkIndex, args.m_endEffectorTargetPosition, &args.m_lowerLimits[0], &args.m_upperLimits[0], &args.m_jointRanges[0], &args.m_restPoses[0]);
  403. } else
  404. {
  405. b3CalculateInverseKinematicsAddTargetPurePosition(command,args.m_endEffectorLinkIndex,args.m_endEffectorTargetPosition);
  406. }
  407. b3SharedMemoryStatusHandle statusHandle;
  408. statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClient, command);
  409. int numPos=0;
  410. bool result = b3GetStatusInverseKinematicsJointPositions(statusHandle,
  411. &results.m_bodyUniqueId,
  412. &numPos,
  413. 0);
  414. if (result && numPos)
  415. {
  416. results.m_calculatedJointPositions.resize(numPos);
  417. result = b3GetStatusInverseKinematicsJointPositions(statusHandle,
  418. &results.m_bodyUniqueId,
  419. &numPos,
  420. &results.m_calculatedJointPositions[0]);
  421. }
  422. return result;
  423. }
  424. b3RobotSimAPI::~b3RobotSimAPI()
  425. {
  426. delete m_data;
  427. }
  428. void b3RobotSimAPI::processMultiThreadedGraphicsRequests()
  429. {
  430. if (0==m_data->m_multiThreadedHelper)
  431. return;
  432. switch (m_data->m_multiThreadedHelper->getCriticalSection()->getSharedParam(1))
  433. {
  434. case eRobotSimGUIHelperCreateCollisionShapeGraphicsObject:
  435. {
  436. m_data->m_multiThreadedHelper->m_childGuiHelper->createCollisionShapeGraphicsObject(m_data->m_multiThreadedHelper->m_colShape);
  437. m_data->m_multiThreadedHelper->getCriticalSection()->lock();
  438. m_data->m_multiThreadedHelper->getCriticalSection()->setSharedParam(1,eRobotSimGUIHelperIdle);
  439. m_data->m_multiThreadedHelper->getCriticalSection()->unlock();
  440. break;
  441. }
  442. case eRobotSimGUIHelperCreateCollisionObjectGraphicsObject:
  443. {
  444. m_data->m_multiThreadedHelper->m_childGuiHelper->createCollisionObjectGraphicsObject(m_data->m_multiThreadedHelper->m_obj,
  445. m_data->m_multiThreadedHelper->m_color2);
  446. m_data->m_multiThreadedHelper->getCriticalSection()->lock();
  447. m_data->m_multiThreadedHelper->getCriticalSection()->setSharedParam(1,eRobotSimGUIHelperIdle);
  448. m_data->m_multiThreadedHelper->getCriticalSection()->unlock();
  449. break;
  450. }
  451. case eRobotSimGUIHelperRegisterTexture:
  452. {
  453. m_data->m_multiThreadedHelper->m_textureId = m_data->m_multiThreadedHelper->m_childGuiHelper->registerTexture(m_data->m_multiThreadedHelper->m_texels,
  454. m_data->m_multiThreadedHelper->m_textureWidth,m_data->m_multiThreadedHelper->m_textureHeight);
  455. m_data->m_multiThreadedHelper->getCriticalSection()->lock();
  456. m_data->m_multiThreadedHelper->getCriticalSection()->setSharedParam(1,eRobotSimGUIHelperIdle);
  457. m_data->m_multiThreadedHelper->getCriticalSection()->unlock();
  458. break;
  459. }
  460. case eRobotSimGUIHelperRegisterGraphicsShape:
  461. {
  462. m_data->m_multiThreadedHelper->m_shapeIndex = m_data->m_multiThreadedHelper->m_childGuiHelper->registerGraphicsShape(
  463. m_data->m_multiThreadedHelper->m_vertices,
  464. m_data->m_multiThreadedHelper->m_numvertices,
  465. m_data->m_multiThreadedHelper->m_indices,
  466. m_data->m_multiThreadedHelper->m_numIndices,
  467. m_data->m_multiThreadedHelper->m_primitiveType,
  468. m_data->m_multiThreadedHelper->m_textureId);
  469. m_data->m_multiThreadedHelper->getCriticalSection()->lock();
  470. m_data->m_multiThreadedHelper->getCriticalSection()->setSharedParam(1,eRobotSimGUIHelperIdle);
  471. m_data->m_multiThreadedHelper->getCriticalSection()->unlock();
  472. break;
  473. }
  474. case eRobotSimGUIHelperRegisterGraphicsInstance:
  475. {
  476. m_data->m_multiThreadedHelper->m_instanceId = m_data->m_multiThreadedHelper->m_childGuiHelper->registerGraphicsInstance(
  477. m_data->m_multiThreadedHelper->m_shapeIndex,
  478. m_data->m_multiThreadedHelper->m_position,
  479. m_data->m_multiThreadedHelper->m_quaternion,
  480. m_data->m_multiThreadedHelper->m_color,
  481. m_data->m_multiThreadedHelper->m_scaling);
  482. m_data->m_multiThreadedHelper->getCriticalSection()->lock();
  483. m_data->m_multiThreadedHelper->getCriticalSection()->setSharedParam(1,eRobotSimGUIHelperIdle);
  484. m_data->m_multiThreadedHelper->getCriticalSection()->unlock();
  485. break;
  486. }
  487. case eRobotSimGUIHelperRemoveAllGraphicsInstances:
  488. {
  489. m_data->m_multiThreadedHelper->m_childGuiHelper->removeAllGraphicsInstances();
  490. int numRenderInstances = m_data->m_multiThreadedHelper->m_childGuiHelper->getRenderInterface()->getTotalNumInstances();
  491. b3Assert(numRenderInstances==0);
  492. m_data->m_multiThreadedHelper->getCriticalSection()->lock();
  493. m_data->m_multiThreadedHelper->getCriticalSection()->setSharedParam(1,eRobotSimGUIHelperIdle);
  494. m_data->m_multiThreadedHelper->getCriticalSection()->unlock();
  495. break;
  496. }
  497. case eRobotSimGUIHelperCopyCameraImageData:
  498. {
  499. m_data->m_multiThreadedHelper->m_childGuiHelper->copyCameraImageData(m_data->m_multiThreadedHelper->m_viewMatrix,
  500. m_data->m_multiThreadedHelper->m_projectionMatrix,
  501. m_data->m_multiThreadedHelper->m_pixelsRGBA,
  502. m_data->m_multiThreadedHelper->m_rgbaBufferSizeInPixels,
  503. m_data->m_multiThreadedHelper->m_depthBuffer,
  504. m_data->m_multiThreadedHelper->m_depthBufferSizeInPixels,
  505. m_data->m_multiThreadedHelper->m_segmentationMaskBuffer,
  506. m_data->m_multiThreadedHelper->m_segmentationMaskBufferSizeInPixels,
  507. m_data->m_multiThreadedHelper->m_startPixelIndex,
  508. m_data->m_multiThreadedHelper->m_destinationWidth,
  509. m_data->m_multiThreadedHelper->m_destinationHeight,
  510. m_data->m_multiThreadedHelper->m_numPixelsCopied);
  511. m_data->m_multiThreadedHelper->getCriticalSection()->lock();
  512. m_data->m_multiThreadedHelper->getCriticalSection()->setSharedParam(1,eRobotSimGUIHelperIdle);
  513. m_data->m_multiThreadedHelper->getCriticalSection()->unlock();
  514. break;
  515. }
  516. case eRobotSimGUIHelperIdle:
  517. default:
  518. {
  519. }
  520. }
  521. }
  522. b3SharedMemoryStatusHandle b3RobotSimAPI::submitClientCommandAndWaitStatusMultiThreaded(b3PhysicsClientHandle physClient, b3SharedMemoryCommandHandle commandHandle)
  523. {
  524. int timeout = 1024*1024*1024;
  525. b3SharedMemoryStatusHandle statusHandle=0;
  526. b3SubmitClientCommand(physClient,commandHandle);
  527. while ((statusHandle==0) && (timeout-- > 0))
  528. {
  529. statusHandle =b3ProcessServerStatus(physClient);
  530. processMultiThreadedGraphicsRequests();
  531. }
  532. return (b3SharedMemoryStatusHandle) statusHandle;
  533. }
  534. int b3RobotSimAPI::getNumJoints(int bodyUniqueId) const
  535. {
  536. return b3GetNumJoints(m_data->m_physicsClient,bodyUniqueId);
  537. }
  538. bool b3RobotSimAPI::getJointInfo(int bodyUniqueId, int jointIndex, b3JointInfo* jointInfo)
  539. {
  540. return (b3GetJointInfo(m_data->m_physicsClient,bodyUniqueId, jointIndex,jointInfo)!=0);
  541. }
  542. void b3RobotSimAPI::createJoint(int parentBodyIndex, int parentJointIndex, int childBodyIndex, int childJointIndex, b3JointInfo* jointInfo)
  543. {
  544. b3SharedMemoryStatusHandle statusHandle;
  545. b3Assert(b3CanSubmitCommand(m_data->m_physicsClient));
  546. if (b3CanSubmitCommand(m_data->m_physicsClient))
  547. {
  548. statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClient, b3CreateJoint(m_data->m_physicsClient, parentBodyIndex, parentJointIndex, childBodyIndex, childJointIndex, jointInfo));
  549. }
  550. }
  551. bool b3RobotSimAPI::getJointStates(int bodyUniqueId, b3JointStates& state)
  552. {
  553. b3SharedMemoryCommandHandle command = b3RequestActualStateCommandInit(m_data->m_physicsClient,bodyUniqueId);
  554. b3SharedMemoryStatusHandle statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClient, command);
  555. if (statusHandle)
  556. {
  557. double rootInertialFrame[7];
  558. const double* rootLocalInertialFrame;
  559. const double* actualStateQ;
  560. const double* actualStateQdot;
  561. const double* jointReactionForces;
  562. int stat = b3GetStatusActualState(statusHandle,
  563. &state.m_bodyUniqueId,
  564. &state.m_numDegreeOfFreedomQ,
  565. &state.m_numDegreeOfFreedomU,
  566. &rootLocalInertialFrame,
  567. &actualStateQ,
  568. &actualStateQdot,
  569. &jointReactionForces);
  570. if (stat)
  571. {
  572. state.m_actualStateQ.resize(state.m_numDegreeOfFreedomQ);
  573. state.m_actualStateQdot.resize(state.m_numDegreeOfFreedomU);
  574. for (int i=0;i<state.m_numDegreeOfFreedomQ;i++)
  575. {
  576. state.m_actualStateQ[i] = actualStateQ[i];
  577. }
  578. for (int i=0;i<state.m_numDegreeOfFreedomU;i++)
  579. {
  580. state.m_actualStateQdot[i] = actualStateQdot[i];
  581. }
  582. int numJoints = getNumJoints(bodyUniqueId);
  583. state.m_jointReactionForces.resize(6*numJoints);
  584. for (int i=0;i<numJoints*6;i++)
  585. {
  586. state.m_jointReactionForces[i] = jointReactionForces[i];
  587. }
  588. return true;
  589. }
  590. //rootInertialFrame,
  591. // &state.m_actualStateQ[0],
  592. // &state.m_actualStateQdot[0],
  593. // &state.m_jointReactionForces[0]);
  594. }
  595. return false;
  596. }
  597. void b3RobotSimAPI::setJointMotorControl(int bodyUniqueId, int jointIndex, const b3JointMotorArgs& args)
  598. {
  599. b3SharedMemoryStatusHandle statusHandle;
  600. switch (args.m_controlMode)
  601. {
  602. case CONTROL_MODE_VELOCITY:
  603. {
  604. b3SharedMemoryCommandHandle command = b3JointControlCommandInit2( m_data->m_physicsClient, bodyUniqueId, CONTROL_MODE_VELOCITY);
  605. b3JointInfo jointInfo;
  606. b3GetJointInfo(m_data->m_physicsClient, bodyUniqueId, jointIndex, &jointInfo);
  607. int uIndex = jointInfo.m_uIndex;
  608. b3JointControlSetKd(command,uIndex,args.m_kd);
  609. b3JointControlSetDesiredVelocity(command,uIndex,args.m_targetVelocity);
  610. b3JointControlSetMaximumForce(command,uIndex,args.m_maxTorqueValue);
  611. statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClient, command);
  612. break;
  613. }
  614. case CONTROL_MODE_POSITION_VELOCITY_PD:
  615. {
  616. b3SharedMemoryCommandHandle command = b3JointControlCommandInit2( m_data->m_physicsClient, bodyUniqueId, CONTROL_MODE_POSITION_VELOCITY_PD);
  617. b3JointInfo jointInfo;
  618. b3GetJointInfo(m_data->m_physicsClient, bodyUniqueId, jointIndex, &jointInfo);
  619. int uIndex = jointInfo.m_uIndex;
  620. int qIndex = jointInfo.m_qIndex;
  621. b3JointControlSetDesiredPosition(command,qIndex,args.m_targetPosition);
  622. b3JointControlSetKp(command,uIndex,args.m_kp);
  623. b3JointControlSetDesiredVelocity(command,uIndex,args.m_targetVelocity);
  624. b3JointControlSetKd(command,uIndex,args.m_kd);
  625. b3JointControlSetMaximumForce(command,uIndex,args.m_maxTorqueValue);
  626. statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClient, command);
  627. break;
  628. }
  629. case CONTROL_MODE_TORQUE:
  630. {
  631. b3SharedMemoryCommandHandle command = b3JointControlCommandInit2( m_data->m_physicsClient, bodyUniqueId, CONTROL_MODE_TORQUE);
  632. b3JointInfo jointInfo;
  633. b3GetJointInfo(m_data->m_physicsClient, bodyUniqueId, jointIndex, &jointInfo);
  634. int uIndex = jointInfo.m_uIndex;
  635. b3JointControlSetDesiredForceTorque(command,uIndex,args.m_maxTorqueValue);
  636. statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClient, command);
  637. break;
  638. }
  639. default:
  640. {
  641. b3Error("Unknown control command in b3RobotSimAPI::setJointMotorControl");
  642. }
  643. }
  644. }
  645. bool b3RobotSimAPI::loadFile(const struct b3RobotSimLoadFileArgs& args, b3RobotSimLoadFileResults& results)
  646. {
  647. bool statusOk = false;
  648. int robotUniqueId = -1;
  649. b3Assert(m_data->m_connected);
  650. switch (args.m_fileType)
  651. {
  652. case B3_URDF_FILE:
  653. {
  654. b3SharedMemoryStatusHandle statusHandle;
  655. int statusType;
  656. b3SharedMemoryCommandHandle command = b3LoadUrdfCommandInit(m_data->m_physicsClient, args.m_fileName.c_str());
  657. //setting the initial position, orientation and other arguments are optional
  658. b3LoadUrdfCommandSetStartPosition(command, args.m_startPosition[0],
  659. args.m_startPosition[1],
  660. args.m_startPosition[2]);
  661. b3LoadUrdfCommandSetStartOrientation(command,args.m_startOrientation[0]
  662. ,args.m_startOrientation[1]
  663. ,args.m_startOrientation[2]
  664. ,args.m_startOrientation[3]);
  665. if (args.m_forceOverrideFixedBase)
  666. {
  667. b3LoadUrdfCommandSetUseFixedBase(command,true);
  668. }
  669. b3LoadUrdfCommandSetUseMultiBody(command, args.m_useMultiBody);
  670. statusHandle = submitClientCommandAndWaitStatusMultiThreaded(m_data->m_physicsClient, command);
  671. statusType = b3GetStatusType(statusHandle);
  672. b3Assert(statusType==CMD_URDF_LOADING_COMPLETED);
  673. robotUniqueId = b3GetStatusBodyIndex(statusHandle);
  674. results.m_uniqueObjectIds.push_back(robotUniqueId);
  675. statusOk = true;
  676. break;
  677. }
  678. case B3_SDF_FILE:
  679. {
  680. b3SharedMemoryStatusHandle statusHandle;
  681. int statusType;
  682. b3SharedMemoryCommandHandle command = b3LoadSdfCommandInit(m_data->m_physicsClient, args.m_fileName.c_str());
  683. b3LoadSdfCommandSetUseMultiBody(command, args.m_useMultiBody);
  684. statusHandle = submitClientCommandAndWaitStatusMultiThreaded(m_data->m_physicsClient, command);
  685. statusType = b3GetStatusType(statusHandle);
  686. b3Assert(statusType == CMD_SDF_LOADING_COMPLETED);
  687. if (statusType == CMD_SDF_LOADING_COMPLETED)
  688. {
  689. int numBodies = b3GetStatusBodyIndices(statusHandle, 0,0);
  690. if (numBodies)
  691. {
  692. results.m_uniqueObjectIds.resize(numBodies);
  693. int numBodies = b3GetStatusBodyIndices(statusHandle, &results.m_uniqueObjectIds[0],results.m_uniqueObjectIds.size());
  694. }
  695. statusOk = true;
  696. }
  697. break;
  698. }
  699. default:
  700. {
  701. b3Warning("Unknown file type in b3RobotSimAPI::loadFile");
  702. }
  703. }
  704. return statusOk;
  705. }
  706. bool b3RobotSimAPI::connect(GUIHelperInterface* guiHelper)
  707. {
  708. if (m_data->m_useMultiThreading)
  709. {
  710. m_data->m_multiThreadedHelper = new MultiThreadedOpenGLGuiHelper2(guiHelper->getAppInterface(), guiHelper);
  711. MultiThreadedOpenGLGuiHelper2* guiHelperWrapper = new MultiThreadedOpenGLGuiHelper2(guiHelper->getAppInterface(), guiHelper);
  712. m_data->m_threadSupport = createRobotSimThreadSupport(MAX_ROBOT_NUM_THREADS);
  713. for (int i = 0; i < m_data->m_threadSupport->getNumTasks(); i++)
  714. {
  715. RobotSimThreadLocalStorage* storage = (RobotSimThreadLocalStorage*)m_data->m_threadSupport->getThreadLocalMemory(i);
  716. b3Assert(storage);
  717. storage->threadId = i;
  718. //storage->m_sharedMem = data->m_sharedMem;
  719. }
  720. for (int w = 0; w < MAX_ROBOT_NUM_THREADS; w++)
  721. {
  722. m_data->m_args[w].m_cs = m_data->m_threadSupport->createCriticalSection();
  723. m_data->m_args[w].m_cs->setSharedParam(0, eRobotSimIsUnInitialized);
  724. int numMoving = 0;
  725. m_data->m_args[w].m_positions.resize(numMoving);
  726. m_data->m_args[w].m_physicsServerPtr = &m_data->m_physicsServer;
  727. int index = 0;
  728. m_data->m_threadSupport->runTask(B3_THREAD_SCHEDULE_TASK, (void*)&m_data->m_args[w], w);
  729. while (m_data->m_args[w].m_cs->getSharedParam(0) == eRobotSimIsUnInitialized)
  730. {
  731. }
  732. }
  733. m_data->m_args[0].m_cs->setSharedParam(1, eRobotSimGUIHelperIdle);
  734. m_data->m_multiThreadedHelper->setCriticalSection(m_data->m_args[0].m_cs);
  735. bool serverConnected = m_data->m_physicsServer.connectSharedMemory(m_data->m_multiThreadedHelper);
  736. b3Assert(serverConnected);
  737. m_data->m_physicsClient = b3ConnectSharedMemory(SHARED_MEMORY_KEY);
  738. }
  739. else
  740. {
  741. m_data->m_clientServerDirect = new PhysicsDirect();
  742. bool connected = m_data->m_clientServerDirect->connect(guiHelper);
  743. m_data->m_physicsClient = (b3PhysicsClientHandle)m_data->m_clientServerDirect;
  744. }
  745. //client connected
  746. m_data->m_connected = b3CanSubmitCommand(m_data->m_physicsClient);
  747. b3Assert(m_data->m_connected);
  748. return m_data->m_connected && m_data->m_connected;
  749. }
  750. void b3RobotSimAPI::disconnect()
  751. {
  752. if (m_data->m_useMultiThreading)
  753. {
  754. for (int i = 0; i < MAX_ROBOT_NUM_THREADS; i++)
  755. {
  756. m_data->m_args[i].m_cs->lock();
  757. m_data->m_args[i].m_cs->setSharedParam(0, eRequestTerminateRobotSim);
  758. m_data->m_args[i].m_cs->unlock();
  759. }
  760. int numActiveThreads = MAX_ROBOT_NUM_THREADS;
  761. while (numActiveThreads)
  762. {
  763. int arg0, arg1;
  764. if (m_data->m_threadSupport->isTaskCompleted(&arg0, &arg1, 0))
  765. {
  766. numActiveThreads--;
  767. printf("numActiveThreads = %d\n", numActiveThreads);
  768. }
  769. else
  770. {
  771. }
  772. };
  773. printf("stopping threads\n");
  774. delete m_data->m_threadSupport;
  775. m_data->m_threadSupport = 0;
  776. }
  777. b3DisconnectSharedMemory(m_data->m_physicsClient);
  778. m_data->m_physicsServer.disconnectSharedMemory(true);
  779. m_data->m_connected = false;
  780. }
  781. void b3RobotSimAPI::debugDraw(int debugDrawMode)
  782. {
  783. if (m_data->m_clientServerDirect)
  784. {
  785. m_data->m_clientServerDirect->debugDraw(debugDrawMode);
  786. }
  787. }
  788. void b3RobotSimAPI::renderScene()
  789. {
  790. if (m_data->m_useMultiThreading)
  791. {
  792. if (m_data->m_multiThreadedHelper->m_childGuiHelper->getRenderInterface())
  793. {
  794. m_data->m_multiThreadedHelper->m_childGuiHelper->getRenderInterface()->writeTransforms();
  795. }
  796. }
  797. if (m_data->m_clientServerDirect)
  798. {
  799. m_data->m_clientServerDirect->renderScene();
  800. }
  801. m_data->m_physicsServer.renderScene();
  802. }
  803. void b3RobotSimAPI::getBodyJacobian(int bodyUniqueId, int linkIndex, const double* localPosition, const double* jointPositions, const double* jointVelocities, const double* jointAccelerations, double* linearJacobian, double* angularJacobian)
  804. {
  805. b3SharedMemoryCommandHandle command = b3CalculateJacobianCommandInit(m_data->m_physicsClient, bodyUniqueId, linkIndex, localPosition, jointPositions, jointVelocities, jointAccelerations);
  806. b3SharedMemoryStatusHandle statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClient, command);
  807. if (b3GetStatusType(statusHandle) == CMD_CALCULATED_JACOBIAN_COMPLETED)
  808. {
  809. b3GetStatusJacobian(statusHandle, linearJacobian, angularJacobian);
  810. }
  811. }
  812. void b3RobotSimAPI::getLinkState(int bodyUniqueId, int linkIndex, double* worldPosition, double* worldOrientation)
  813. {
  814. b3SharedMemoryCommandHandle command = b3RequestActualStateCommandInit(m_data->m_physicsClient,bodyUniqueId);
  815. b3SharedMemoryStatusHandle statusHandle = b3SubmitClientCommandAndWaitStatus(m_data->m_physicsClient, command);
  816. if (b3GetStatusType(statusHandle) == CMD_ACTUAL_STATE_UPDATE_COMPLETED)
  817. {
  818. b3LinkState linkState;
  819. b3GetLinkState(m_data->m_physicsClient, statusHandle, linkIndex, &linkState);
  820. worldPosition[0] = linkState.m_worldPosition[0];
  821. worldPosition[1] = linkState.m_worldPosition[1];
  822. worldPosition[2] = linkState.m_worldPosition[2];
  823. worldOrientation[0] = linkState.m_worldOrientation[0];
  824. worldOrientation[1] = linkState.m_worldOrientation[1];
  825. worldOrientation[2] = linkState.m_worldOrientation[2];
  826. worldOrientation[3] = linkState.m_worldOrientation[3];
  827. }
  828. }