trajopt
 All Classes Namespaces Files Functions Variables Typedefs Pages
openrave_userdata_utils.hpp
1 #pragma once
2 #include "macros.h"
3 #include <openrave/openrave.h>
4 #include <map>
5 #include "utils/logging.hpp"
6 
7 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
8 
9 class UserMap : public std::map<std::string, OpenRAVE::UserDataPtr>, public OpenRAVE::UserData {};
10 
11 namespace trajopt {
12 
13 #if OPENRAVE_VERSION_MINOR > 8
14 inline OpenRAVE::UserDataPtr GetUserData(const OpenRAVE::KinBody& body, const std::string& key) {
15  return body.GetUserData(key);
16 }
17 inline void SetUserData(OpenRAVE::KinBody& body, const std::string& key, OpenRAVE::UserDataPtr val) {
18  body.SetUserData(key, val);
19 }
20 inline void RemoveUserData(OpenRAVE::KinBody& body, const std::string& key) {
21  body.RemoveUserData(key);
22 }
23 #endif
24 
25 template <typename T>
26 OpenRAVE::UserDataPtr GetUserData(const T& env, const std::string& key) {
27  OpenRAVE::UserDataPtr ud = env.GetUserData();
28  if (!ud) return OpenRAVE::UserDataPtr();
29  else if (UserMap* um = dynamic_cast<UserMap*>(ud.get())) {
30  UserMap::iterator it = (*um).find(key);
31  if (it != (*um).end()) return it->second;
32  else return OpenRAVE::UserDataPtr();
33  }
34  else {
35  throw OpenRAVE::openrave_exception("Userdata has the wrong class!");
36  return OpenRAVE::UserDataPtr();
37  }
38 }
39 template <typename T>
40 void SetUserData(T& env, const std::string& key, OpenRAVE::UserDataPtr val) {
41  OpenRAVE::UserDataPtr ud = env.GetUserData();
42  if (!ud) {
43  ud = OpenRAVE::UserDataPtr(new UserMap());
44  env.SetUserData(ud);
45  }
46  if (UserMap* um = dynamic_cast<UserMap*>(ud.get())) {
47  (*um)[key] = val;
48  }
49  else {
50  throw OpenRAVE::openrave_exception("userdata has unexpected class");
51  }
52 }
53 template <typename T>
54 void RemoveUserData(T& body, const std::string& key) {
55  OpenRAVE::UserDataPtr ud = body.GetUserData();
56  if (UserMap* um = dynamic_cast<UserMap*>(ud.get())) {
57  if (um->find(key) == um->end()) LOG_WARN("tried to erase key %s but it's not in the userdata map!", key.c_str());
58  (*um).erase(key);
59  }
60  else {
61  LOG_ERROR("body %s has no userdata map", body.GetName().c_str());
62  }
63 }
64 
65 }