From 007629941b6ca1c389d6178cdf1e66d2516bc7ef Mon Sep 17 00:00:00 2001 From: methylDragon Date: Wed, 5 Oct 2022 05:55:38 -0700 Subject: [PATCH 1/4] ign -> gz Migrate Ignition Headers : gz-common (#418) * Migrate headers Signed-off-by: methylDragon * Add redirection headers Signed-off-by: methylDragon * Migrate include statements Signed-off-by: methylDragon * Leave ignition as primary in headers to fix ABI Signed-off-by: methylDragon * remove comments Signed-off-by: Nate Koenig Signed-off-by: methylDragon Signed-off-by: Nate Koenig Co-authored-by: Nate Koenig --- BUILD.bazel | 2 +- CMakeLists.txt | 4 +- Changelog.md | 4 +- av/include/CMakeLists.txt | 2 + .../ignition => av/include/gz}/CMakeLists.txt | 0 av/include/gz/common/AudioDecoder.hh | 76 ++++ .../{ignition => gz}/common/CMakeLists.txt | 0 .../{ignition => gz}/common/HWEncoder.hh | 10 +- av/include/gz/common/HWVideo.hh | 56 +++ av/include/gz/common/Video.hh | 86 ++++ av/include/gz/common/VideoEncoder.hh | 232 ++++++++++ av/include/gz/common/av/Util.hh | 31 ++ av/include/gz/common/ffmpeg_inc.hh | 98 ++++ av/include/ignition/common/AudioDecoder.hh | 93 +--- av/include/ignition/common/HWVideo.hh | 47 +- av/include/ignition/common/Video.hh | 75 +--- av/include/ignition/common/VideoEncoder.hh | 221 +-------- av/include/ignition/common/av.hh | 19 + av/include/ignition/common/av/Export.hh | 19 + av/include/ignition/common/av/Util.hh | 20 +- av/include/ignition/common/ffmpeg_inc.hh | 85 +--- av/src/AudioDecoder.cc | 10 +- av/src/AudioDecoder_TEST.cc | 4 +- av/src/HWEncoder.cc | 10 +- av/src/Util.cc | 8 +- av/src/Video.cc | 12 +- av/src/VideoEncoder.cc | 12 +- av/src/VideoEncoder_TEST.cc | 4 +- av/src/ffmpeg_inc.cc | 2 +- events/include/CMakeLists.txt | 2 + events/include/gz/CMakeLists.txt | 1 + .../{ignition => gz}/common/CMakeLists.txt | 0 events/include/gz/common/Event.hh | 279 ++++++++++++ events/include/gz/common/KeyEvent.hh | 120 +++++ events/include/gz/common/MouseEvent.hh | 214 +++++++++ events/include/gz/common/events/Types.hh | 36 ++ events/include/ignition/common/Event.hh | 266 +---------- events/include/ignition/common/KeyEvent.hh | 109 +---- events/include/ignition/common/MouseEvent.hh | 203 +-------- events/include/ignition/common/events.hh | 19 + .../include/ignition/common/events/Export.hh | 19 + .../include/ignition/common/events/Types.hh | 25 +- events/src/Event.cc | 4 +- events/src/Event_TEST.cc | 2 +- events/src/KeyEvent.cc | 4 +- events/src/KeyEvent_TEST.cc | 2 +- events/src/MouseEvent.cc | 6 +- events/src/MouseEvent_TEST.cc | 4 +- examples/assert_example.cc | 2 +- examples/console.cc | 4 +- examples/events.cc | 2 +- examples/profiler.cc | 12 +- graphics/include/CMakeLists.txt | 2 + graphics/include/gz/CMakeLists.txt | 1 + graphics/include/gz/common/Animation.hh | 292 ++++++++++++ graphics/include/gz/common/BVHLoader.hh | 52 +++ .../{ignition => gz}/common/CMakeLists.txt | 0 graphics/include/gz/common/ColladaExporter.hh | 65 +++ graphics/include/gz/common/ColladaLoader.hh | 52 +++ graphics/include/gz/common/Dem.hh | 143 ++++++ graphics/include/gz/common/GTSMeshUtils.hh | 63 +++ graphics/include/gz/common/HeightmapData.hh | 63 +++ graphics/include/gz/common/Image.hh | 270 +++++++++++ graphics/include/gz/common/ImageHeightmap.hh | 69 +++ graphics/include/gz/common/KeyFrame.hh | 112 +++++ graphics/include/gz/common/Material.hh | 293 ++++++++++++ graphics/include/gz/common/Mesh.hh | 214 +++++++++ graphics/include/gz/common/MeshCSG.hh | 70 +++ graphics/include/gz/common/MeshExporter.hh | 48 ++ graphics/include/gz/common/MeshLoader.hh | 47 ++ graphics/include/gz/common/MeshManager.hh | 297 ++++++++++++ graphics/include/gz/common/NodeAnimation.hh | 117 +++++ graphics/include/gz/common/NodeTransform.hh | 131 ++++++ graphics/include/gz/common/OBJLoader.hh | 57 +++ graphics/include/gz/common/Pbr.hh | 241 ++++++++++ graphics/include/gz/common/STLLoader.hh | 95 ++++ graphics/include/gz/common/SVGLoader.hh | 135 ++++++ graphics/include/gz/common/Skeleton.hh | 178 ++++++++ .../include/gz/common/SkeletonAnimation.hh | 143 ++++++ graphics/include/gz/common/SkeletonNode.hh | 200 +++++++++ graphics/include/gz/common/SubMesh.hh | 425 ++++++++++++++++++ graphics/include/gz/common/graphics/Types.hh | 51 +++ graphics/include/ignition/common/Animation.hh | 281 +----------- graphics/include/ignition/common/BVHLoader.hh | 41 +- .../ignition/common/ColladaExporter.hh | 54 +-- .../include/ignition/common/ColladaLoader.hh | 41 +- graphics/include/ignition/common/Dem.hh | 132 +----- .../include/ignition/common/GTSMeshUtils.hh | 52 +-- .../include/ignition/common/HeightmapData.hh | 52 +-- graphics/include/ignition/common/Image.hh | 259 +---------- .../include/ignition/common/ImageHeightmap.hh | 58 +-- graphics/include/ignition/common/KeyFrame.hh | 101 +---- graphics/include/ignition/common/Material.hh | 282 +----------- graphics/include/ignition/common/Mesh.hh | 203 +-------- graphics/include/ignition/common/MeshCSG.hh | 59 +-- .../include/ignition/common/MeshExporter.hh | 37 +- .../include/ignition/common/MeshLoader.hh | 36 +- .../include/ignition/common/MeshManager.hh | 286 +----------- .../include/ignition/common/NodeAnimation.hh | 106 +---- .../include/ignition/common/NodeTransform.hh | 120 +---- graphics/include/ignition/common/OBJLoader.hh | 46 +- graphics/include/ignition/common/Pbr.hh | 228 +--------- graphics/include/ignition/common/STLLoader.hh | 84 +--- graphics/include/ignition/common/SVGLoader.hh | 124 +---- graphics/include/ignition/common/Skeleton.hh | 167 +------ .../ignition/common/SkeletonAnimation.hh | 132 +----- .../include/ignition/common/SkeletonNode.hh | 189 +------- graphics/include/ignition/common/SubMesh.hh | 414 +---------------- graphics/include/ignition/common/graphics.hh | 19 + .../ignition/common/graphics/Export.hh | 19 + .../include/ignition/common/graphics/Types.hh | 40 +- graphics/src/Animation.cc | 14 +- graphics/src/Animation_TEST.cc | 8 +- graphics/src/BVHLoader.cc | 10 +- graphics/src/ColladaExporter.cc | 16 +- graphics/src/ColladaExporter_TEST.cc | 10 +- graphics/src/ColladaLoader.cc | 28 +- graphics/src/ColladaLoader_TEST.cc | 12 +- graphics/src/Dem.cc | 8 +- graphics/src/Dem_TEST.cc | 6 +- graphics/src/GTSMeshUtils.cc | 8 +- graphics/src/GTSMeshUtils_TEST.cc | 6 +- graphics/src/Image.cc | 6 +- graphics/src/ImageHeightmap.cc | 4 +- graphics/src/ImageHeightmap_TEST.cc | 2 +- graphics/src/Image_TEST.cc | 2 +- graphics/src/KeyFrame.cc | 2 +- graphics/src/Material.cc | 8 +- graphics/src/Material_TEST.cc | 4 +- graphics/src/Mesh.cc | 14 +- graphics/src/MeshCSG.cc | 8 +- graphics/src/MeshExporter.cc | 2 +- graphics/src/MeshManager.cc | 194 ++++---- graphics/src/MeshManager_TEST.cc | 8 +- graphics/src/Mesh_TEST.cc | 10 +- graphics/src/NodeAnimation.cc | 8 +- graphics/src/NodeTransform.cc | 4 +- graphics/src/OBJLoader.cc | 12 +- graphics/src/OBJLoader_TEST.cc | 8 +- graphics/src/Pbr.cc | 6 +- graphics/src/Pbr_TEST.cc | 70 +-- graphics/src/STLLoader.cc | 10 +- graphics/src/SVGLoader.cc | 8 +- graphics/src/SVGLoader_TEST.cc | 2 +- graphics/src/Skeleton.cc | 10 +- graphics/src/SkeletonAnimation.cc | 8 +- graphics/src/SkeletonNode.cc | 6 +- graphics/src/SubMesh.cc | 10 +- graphics/src/SubMesh_TEST.cc | 8 +- graphics/src/tiny_obj_loader.h | 6 +- include/CMakeLists.txt | 3 +- include/gz/CMakeLists.txt | 1 + include/gz/common/Base64.hh | 44 ++ include/gz/common/Battery.hh | 178 ++++++++ .../{ignition => gz}/common/CMakeLists.txt | 0 include/gz/common/Console.hh | 298 ++++++++++++ include/gz/common/EnumIface.hh | 242 ++++++++++ include/gz/common/Filesystem.hh | 305 +++++++++++++ include/gz/common/FlagSet.hh | 402 +++++++++++++++++ include/gz/common/MaterialDensity.hh | 143 ++++++ include/gz/common/MovingWindowFilter.hh | 186 ++++++++ include/gz/common/Plugin.hh | 196 ++++++++ include/gz/common/PluginInfo.hh | 61 +++ include/gz/common/PluginLoader.hh | 104 +++++ include/gz/common/PluginMacros.hh | 142 ++++++ include/gz/common/PluginPtr.hh | 231 ++++++++++ include/gz/common/SignalHandler.hh | 80 ++++ include/gz/common/SingletonT.hh | 57 +++ include/gz/common/SpecializedPlugin.hh | 170 +++++++ include/gz/common/SpecializedPluginPtr.hh | 81 ++++ include/gz/common/StringUtils.hh | 97 ++++ include/gz/common/SuppressWarning.hh | 76 ++++ include/gz/common/SystemPaths.hh | 227 ++++++++++ include/gz/common/TemplateHelpers.hh | 51 +++ include/gz/common/Time.hh | 324 +++++++++++++ include/gz/common/Timer.hh | 70 +++ include/gz/common/URI.hh | 353 +++++++++++++++ include/gz/common/Util.hh | 335 ++++++++++++++ include/gz/common/Uuid.hh | 75 ++++ include/gz/common/WorkerPool.hh | 72 +++ include/{ignition => gz}/common/config.hh.in | 9 + .../{ignition => gz}/common/detail/Plugin.hh | 6 +- .../common/detail/PluginLoader.hh | 6 +- .../common/detail/PluginMacros.hh | 8 +- .../common/detail/PluginPtr.hh | 8 +- .../common/detail/SpecializedPlugin.hh | 6 +- .../common/detail/SuppressWarning.hh | 4 +- .../common/detail/TemplateHelpers.hh | 4 +- include/ignition/common.hh | 19 + include/ignition/common/Base64.hh | 33 +- include/ignition/common/Battery.hh | 167 +------ include/ignition/common/Console.hh | 287 +----------- include/ignition/common/EnumIface.hh | 231 +--------- include/ignition/common/Export.hh | 19 + include/ignition/common/Filesystem.hh | 292 +----------- include/ignition/common/FlagSet.hh | 405 +---------------- include/ignition/common/MaterialDensity.hh | 132 +----- include/ignition/common/MovingWindowFilter.hh | 175 +------- include/ignition/common/Plugin.hh | 183 +------- include/ignition/common/PluginInfo.hh | 48 +- include/ignition/common/PluginLoader.hh | 91 +--- include/ignition/common/PluginMacros.hh | 129 +----- include/ignition/common/PluginPtr.hh | 218 +-------- include/ignition/common/SignalHandler.hh | 69 +-- include/ignition/common/SingletonT.hh | 46 +- include/ignition/common/SpecializedPlugin.hh | 157 +------ .../ignition/common/SpecializedPluginPtr.hh | 68 +-- include/ignition/common/StringUtils.hh | 84 +--- include/ignition/common/SuppressWarning.hh | 62 +-- include/ignition/common/SystemPaths.hh | 216 +-------- include/ignition/common/TemplateHelpers.hh | 38 +- include/ignition/common/Time.hh | 313 +------------ include/ignition/common/Timer.hh | 59 +-- include/ignition/common/URI.hh | 342 +------------- include/ignition/common/Util.hh | 324 +------------ include/ignition/common/Uuid.hh | 64 +-- include/ignition/common/WorkerPool.hh | 61 +-- include/ignition/common/config.hh | 22 + profiler/include/CMakeLists.txt | 2 + profiler/include/gz/common/Profiler.hh | 165 +++++++ profiler/include/ignition/common/Profiler.hh | 150 +------ .../ignition/common/profiler/Export.hh | 19 + profiler/src/Profiler.cc | 4 +- profiler/src/ProfilerImpl.hh | 6 +- profiler/src/Profiler_Disabled_TEST.cc | 6 +- profiler/src/Profiler_Remotery_TEST.cc | 6 +- profiler/src/RemoteryProfilerImpl.cc | 6 +- profiler/src/RemoteryProfilerImpl.hh | 6 +- src/Base64.cc | 2 +- src/Base64_TEST.cc | 2 +- src/Battery.cc | 6 +- src/Battery_TEST.cc | 2 +- src/Console.cc | 4 +- src/Console_TEST.cc | 8 +- src/EnumIface_TEST.cc | 2 +- src/Filesystem.cc | 14 +- src/FilesystemBoost.cc | 4 +- src/Filesystem_TEST.cc | 12 +- src/FlagSet_TEST.cc | 34 +- src/MaterialDensity.cc | 4 +- src/MaterialDensity_TEST.cc | 2 +- src/MovingWindowFilter_TEST.cc | 4 +- src/Plugin.cc | 6 +- src/PluginLoader.cc | 16 +- src/PluginLoader_TEST.cc | 20 +- src/PluginUtils.hh | 6 +- src/PluginUtils_TEST.cc | 4 +- src/PrintWindowsSystemWarning.hh | 8 +- src/SignalHandler.cc | 6 +- src/SignalHandler_TEST.cc | 4 +- src/StringUtils.cc | 2 +- src/StringUtils_TEST.cc | 2 +- src/SystemPaths.cc | 10 +- src/SystemPaths_TEST.cc | 6 +- src/TemplateHelpers_TEST.cc | 2 +- src/Time.cc | 6 +- src/Time_TEST.cc | 4 +- src/Timer.cc | 2 +- src/URI.cc | 12 +- src/URI_TEST.cc | 2 +- src/Util.cc | 82 ++-- src/Util_TEST.cc | 2 +- src/Uuid.cc | 2 +- src/Uuid_TEST.cc | 2 +- src/WorkerPool.cc | 4 +- src/WorkerPool_TEST.cc | 8 +- test/integration/console.cc | 2 +- test/integration/deprecated_TEST.cc | 26 ++ test/integration/encoder_timing.cc | 4 +- test/integration/mesh.cc | 16 +- test/integration/plugin.cc | 74 +-- test/integration/video_encoder.cc | 6 +- test/performance/logging.cc | 4 +- test/performance/plugin_specialization.cc | 28 +- test/plugins/BadPluginAPIVersionNew.cc | 6 +- test/plugins/BadPluginAPIVersionOld.cc | 6 +- test/plugins/BadPluginAlign.cc | 8 +- test/plugins/BadPluginSize.cc | 8 +- test/plugins/DummyPlugins.cc | 2 +- test/plugins/DummyPlugins.hh | 6 +- .../plugin_bad_const_assignment.cc | 6 +- .../plugin_bad_const_construct.cc | 4 +- .../static_assertions/plugin_no_base_class.cc | 2 +- .../plugin_not_fully_qualified_base.cc | 2 +- .../plugin_not_fully_qualified_class.cc | 2 +- .../static_assertions/plugin_not_global_ns.cc | 2 +- .../plugin_wrong_base_class.cc | 2 +- test/test_config.h.in | 12 +- tutorials/hw-encoding.md | 4 +- tutorials/profiler.md | 4 +- 290 files changed, 11071 insertions(+), 9593 deletions(-) create mode 100644 av/include/CMakeLists.txt rename {include/ignition => av/include/gz}/CMakeLists.txt (100%) create mode 100644 av/include/gz/common/AudioDecoder.hh rename av/include/{ignition => gz}/common/CMakeLists.txt (100%) rename av/include/{ignition => gz}/common/HWEncoder.hh (94%) create mode 100644 av/include/gz/common/HWVideo.hh create mode 100644 av/include/gz/common/Video.hh create mode 100644 av/include/gz/common/VideoEncoder.hh create mode 100644 av/include/gz/common/av/Util.hh create mode 100644 av/include/gz/common/ffmpeg_inc.hh create mode 100644 av/include/ignition/common/av.hh create mode 100644 av/include/ignition/common/av/Export.hh create mode 100644 events/include/CMakeLists.txt create mode 100644 events/include/gz/CMakeLists.txt rename events/include/{ignition => gz}/common/CMakeLists.txt (100%) create mode 100644 events/include/gz/common/Event.hh create mode 100644 events/include/gz/common/KeyEvent.hh create mode 100644 events/include/gz/common/MouseEvent.hh create mode 100644 events/include/gz/common/events/Types.hh create mode 100644 events/include/ignition/common/events.hh create mode 100644 events/include/ignition/common/events/Export.hh create mode 100644 graphics/include/CMakeLists.txt create mode 100644 graphics/include/gz/CMakeLists.txt create mode 100644 graphics/include/gz/common/Animation.hh create mode 100644 graphics/include/gz/common/BVHLoader.hh rename graphics/include/{ignition => gz}/common/CMakeLists.txt (100%) create mode 100644 graphics/include/gz/common/ColladaExporter.hh create mode 100644 graphics/include/gz/common/ColladaLoader.hh create mode 100644 graphics/include/gz/common/Dem.hh create mode 100644 graphics/include/gz/common/GTSMeshUtils.hh create mode 100644 graphics/include/gz/common/HeightmapData.hh create mode 100644 graphics/include/gz/common/Image.hh create mode 100644 graphics/include/gz/common/ImageHeightmap.hh create mode 100644 graphics/include/gz/common/KeyFrame.hh create mode 100644 graphics/include/gz/common/Material.hh create mode 100644 graphics/include/gz/common/Mesh.hh create mode 100644 graphics/include/gz/common/MeshCSG.hh create mode 100644 graphics/include/gz/common/MeshExporter.hh create mode 100644 graphics/include/gz/common/MeshLoader.hh create mode 100644 graphics/include/gz/common/MeshManager.hh create mode 100644 graphics/include/gz/common/NodeAnimation.hh create mode 100644 graphics/include/gz/common/NodeTransform.hh create mode 100644 graphics/include/gz/common/OBJLoader.hh create mode 100644 graphics/include/gz/common/Pbr.hh create mode 100644 graphics/include/gz/common/STLLoader.hh create mode 100644 graphics/include/gz/common/SVGLoader.hh create mode 100644 graphics/include/gz/common/Skeleton.hh create mode 100644 graphics/include/gz/common/SkeletonAnimation.hh create mode 100644 graphics/include/gz/common/SkeletonNode.hh create mode 100644 graphics/include/gz/common/SubMesh.hh create mode 100644 graphics/include/gz/common/graphics/Types.hh create mode 100644 graphics/include/ignition/common/graphics.hh create mode 100644 graphics/include/ignition/common/graphics/Export.hh create mode 100644 include/gz/CMakeLists.txt create mode 100644 include/gz/common/Base64.hh create mode 100644 include/gz/common/Battery.hh rename include/{ignition => gz}/common/CMakeLists.txt (100%) create mode 100644 include/gz/common/Console.hh create mode 100644 include/gz/common/EnumIface.hh create mode 100644 include/gz/common/Filesystem.hh create mode 100644 include/gz/common/FlagSet.hh create mode 100644 include/gz/common/MaterialDensity.hh create mode 100644 include/gz/common/MovingWindowFilter.hh create mode 100644 include/gz/common/Plugin.hh create mode 100644 include/gz/common/PluginInfo.hh create mode 100644 include/gz/common/PluginLoader.hh create mode 100644 include/gz/common/PluginMacros.hh create mode 100644 include/gz/common/PluginPtr.hh create mode 100644 include/gz/common/SignalHandler.hh create mode 100644 include/gz/common/SingletonT.hh create mode 100644 include/gz/common/SpecializedPlugin.hh create mode 100644 include/gz/common/SpecializedPluginPtr.hh create mode 100644 include/gz/common/StringUtils.hh create mode 100644 include/gz/common/SuppressWarning.hh create mode 100644 include/gz/common/SystemPaths.hh create mode 100644 include/gz/common/TemplateHelpers.hh create mode 100644 include/gz/common/Time.hh create mode 100644 include/gz/common/Timer.hh create mode 100644 include/gz/common/URI.hh create mode 100644 include/gz/common/Util.hh create mode 100644 include/gz/common/Uuid.hh create mode 100644 include/gz/common/WorkerPool.hh rename include/{ignition => gz}/common/config.hh.in (89%) rename include/{ignition => gz}/common/detail/Plugin.hh (96%) rename include/{ignition => gz}/common/detail/PluginLoader.hh (86%) rename include/{ignition => gz}/common/detail/PluginMacros.hh (97%) rename include/{ignition => gz}/common/detail/PluginPtr.hh (97%) rename include/{ignition => gz}/common/detail/SpecializedPlugin.hh (98%) rename include/{ignition => gz}/common/detail/SuppressWarning.hh (97%) rename include/{ignition => gz}/common/detail/TemplateHelpers.hh (91%) create mode 100644 include/ignition/common.hh create mode 100644 include/ignition/common/Export.hh create mode 100644 include/ignition/common/config.hh create mode 100644 profiler/include/CMakeLists.txt create mode 100644 profiler/include/gz/common/Profiler.hh create mode 100644 profiler/include/ignition/common/profiler/Export.hh create mode 100644 test/integration/deprecated_TEST.cc diff --git a/BUILD.bazel b/BUILD.bazel index 7693c24a9..6d7024713 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -43,7 +43,7 @@ ign_export_header( public_headers_no_gen = glob([ "include/ignition/common/*.hh", - "include/ignition/common/detail/*.hh" + "include/gz/common/detail/*.hh" ]) private_headers = [ diff --git a/CMakeLists.txt b/CMakeLists.txt index 7e8a2885a..80fce181e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,7 +14,9 @@ set(IGN_CMAKE_VER ${ignition-cmake2_VERSION_MAJOR}) #============================================================================ # Configure the project #============================================================================ -ign_configure_project() +ign_configure_project( + REPLACE_IGNITION_INCLUDE_PATH gz/common +) #============================================================================ # Set project-specific options diff --git a/Changelog.md b/Changelog.md index 5c7f950d7..403ee8e54 100644 --- a/Changelog.md +++ b/Changelog.md @@ -195,7 +195,7 @@ ## Ignition Common 3.8.0 (2020-12-08) -1. Call ignition::common::load() from Video constructor +1. Call gz::common::load() from Video constructor * [Pull Request 111](https://github.com/ignitionrobotics/ign-common/pull/111) 1. Cleanup @@ -352,7 +352,7 @@ ## Ignition Common 3.2.0 (2019-08-07) -1. Allow ignLogInit to use an absolute path. Added a timeToIso that converts a given time to an ISO string. Some console timestamps were using `IGN_SYSTEM_TIME_NS()` and others `ignition::common::systemTimeISO()`. Switched all to use `ignition::common::systemTimeISO()`. +1. Allow ignLogInit to use an absolute path. Added a timeToIso that converts a given time to an ISO string. Some console timestamps were using `IGN_SYSTEM_TIME_NS()` and others `gz::common::systemTimeISO()`. Switched all to use `gz::common::systemTimeISO()`. * [BitBucket pull request 203](https://osrf-migration.github.io/ignition-gh-pages/#!/ignitionrobotics/ign-common/pull-requests/203) 1. Port ColladaLoader fix: use default value of 1 for stride parameter when unset. diff --git a/av/include/CMakeLists.txt b/av/include/CMakeLists.txt new file mode 100644 index 000000000..4b2bdd7bb --- /dev/null +++ b/av/include/CMakeLists.txt @@ -0,0 +1,2 @@ +add_subdirectory(gz) +install(DIRECTORY ignition DESTINATION ${IGN_INCLUDE_INSTALL_DIR_FULL}) diff --git a/include/ignition/CMakeLists.txt b/av/include/gz/CMakeLists.txt similarity index 100% rename from include/ignition/CMakeLists.txt rename to av/include/gz/CMakeLists.txt diff --git a/av/include/gz/common/AudioDecoder.hh b/av/include/gz/common/AudioDecoder.hh new file mode 100644 index 000000000..aff0e8107 --- /dev/null +++ b/av/include/gz/common/AudioDecoder.hh @@ -0,0 +1,76 @@ +/* +* Copyright (C) 2016 Open Source Robotics Foundation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ +#ifndef GZ_COMMON_AUDIO_DECODER_HH_ +#define GZ_COMMON_AUDIO_DECODER_HH_ + +#include +#include +#include + +#include +#include + +namespace ignition +{ + namespace common + { + /// \brief Forward declaration of private data class + class AudioDecoderPrivate; + + /// \class AudioDecoder AudioDecoder.hh ignition/common/common.hh + /// \brief An audio decoder based on FFMPEG. + class IGNITION_COMMON_AV_VISIBLE AudioDecoder + { + /// \brief Constructor. + public: AudioDecoder(); + + /// \brief Destructor. + public: virtual ~AudioDecoder(); + + /// \brief Set the file to decode. + /// \param[in] _filename Path to an audio file. + /// \return True if the file was successfull opened. + public: bool SetFile(const std::string &_filename); + + /// \brief Get the audio filename that was set. + /// \return The name of the set audio file. + /// \sa AudioDecoder::SetFile + public: std::string File() const; + + /// \brief Decode the loaded audio file. + /// \sa AudioDecoder::SetFile + /// \param[out] _outBuffer Buffer that holds the decoded audio data. + /// \param[out] _outBufferSize Size of the _outBuffer. + /// \return True if decoding was succesful. + public: bool Decode(uint8_t **_outBuffer, unsigned int *_outBufferSize); + + /// \brief Get the sample rate from the latest decoded file. + /// \return Integer sample rate, such as 44100. + /// If no file is decoded, -1 is returned. + public: int SampleRate(); + + /// \brief Free audio object, close files, streams. + private: void Cleanup(); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief Private data pointer + private: std::unique_ptr data; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} +#endif diff --git a/av/include/ignition/common/CMakeLists.txt b/av/include/gz/common/CMakeLists.txt similarity index 100% rename from av/include/ignition/common/CMakeLists.txt rename to av/include/gz/common/CMakeLists.txt diff --git a/av/include/ignition/common/HWEncoder.hh b/av/include/gz/common/HWEncoder.hh similarity index 94% rename from av/include/ignition/common/HWEncoder.hh rename to av/include/gz/common/HWEncoder.hh index 2353a9528..2e48c2d08 100644 --- a/av/include/ignition/common/HWEncoder.hh +++ b/av/include/gz/common/HWEncoder.hh @@ -20,11 +20,11 @@ #include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include /// This is an internal-use only class encapsulating HW video encoding. All /// symbols defined here are hidden from the public API. diff --git a/av/include/gz/common/HWVideo.hh b/av/include/gz/common/HWVideo.hh new file mode 100644 index 000000000..704624bb5 --- /dev/null +++ b/av/include/gz/common/HWVideo.hh @@ -0,0 +1,56 @@ +/* + * Copyright 2020 Martin Pecka + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ +#ifndef IGNITION_COMMON_HWVIDEO_HH +#define IGNITION_COMMON_HWVIDEO_HH + +#include + +namespace ignition::common +{ + enum class IGNITION_COMMON_AV_VISIBLE HWEncoderType + { + NONE, + NVENC, // Linux device is /dev/nvidia* + // Windows is the same (even though such file doesn't exist) + VAAPI, // Linux device /dev/dri/renderD* or display number (e.g. :0) + VDPAU, // Not supported (probably only for decoding?) + QSV, // Win device is 0-based GPU index, + // Linux uses /dev/dri/renderD* or display number (e.g. :0) + VIDEOTOOLBOX, // Not yet suported + AMF, // Not yet suported + OMX, // Not yet suported + V4L2M2M, // Not yet suported + DXVA2, // Not yet suported + _ // For FlagSet to work. + }; + + IGN_ENUM(HWEncoderTypeParser, HWEncoderType, + HWEncoderType::NONE, HWEncoderType::_, + "NONE", + "NVENC", + "VAAPI", + "VDPAU", + "QSV", + "VIDEOTOOLBOX", + "AMF", + "OMX", + "V4L2M2M", + "DXVA2", + "INVALID" + ) +} + +#endif diff --git a/av/include/gz/common/Video.hh b/av/include/gz/common/Video.hh new file mode 100644 index 000000000..353a14886 --- /dev/null +++ b/av/include/gz/common/Video.hh @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_VIDEO_HH_ +#define GZ_COMMON_VIDEO_HH_ + +#include +#include + +#include +#include + +struct AVFormatContext; +struct AVCodecContext; +struct AVFrame; +struct AVPicture; +struct SwsContext; + +namespace ignition +{ + namespace common + { + // Forward declare private data class + class VideoPrivate; + + /// \brief Handle video encoding and decoding using libavcodec + class IGNITION_COMMON_AV_VISIBLE Video + { + /// \brief Constructor + public: Video(); + + /// \brief Destructor + public: virtual ~Video(); + + /// \brief Load a video file + /// \param[in] _filename Full path of the video file + /// \return false if a video stream can't be found + public: bool Load(const std::string &_filename); + + /// \brief Get the width of the video in pixels + /// \return the width + public: int Width() const; + + /// \brief Get the height of the video in pixels + /// \return the height + public: int Height() const; + + /// \brief Convenience type alias for duration + /// where 1000000 is the same as AV_TIME_BASE fractional seconds + public: + using Length = std::chrono::duration>; + + /// \brief Get the duration of the video + /// \return the duration + public: Length Duration() const; + + /// \brief Get the next frame of the video. + /// \param[out] _buffer Allocated buffer in which the frame is stored + /// (size has to be width * height * 3 bytes). + /// \return false on error or end of file + public: bool NextFrame(unsigned char **_buffer); + + /// \brief free up open Video object, close files, streams + private: void Cleanup(); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief Private data pointer + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} +#endif diff --git a/av/include/gz/common/VideoEncoder.hh b/av/include/gz/common/VideoEncoder.hh new file mode 100644 index 000000000..12a2e34c0 --- /dev/null +++ b/av/include/gz/common/VideoEncoder.hh @@ -0,0 +1,232 @@ +/* + * Copyright 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_VIDEOENCODER_HH_ +#define GZ_COMMON_VIDEOENCODER_HH_ + +#include +#include +#include +#include + +#include +#include +#include +#include + +// Default bitrate (0) indicates that a bitrate should be calculated when +// Start is called. +#define VIDEO_ENCODER_BITRATE_DEFAULT 0 +#define VIDEO_ENCODER_WIDTH_DEFAULT 1280 +#define VIDEO_ENCODER_HEIGHT_DEFAULT 720 +#define VIDEO_ENCODER_FPS_DEFAULT 25 +#define VIDEO_ENCODER_FORMAT_DEFAULT "mp4" + +namespace ignition +{ + namespace common + { + // Forward declare private data class + class VideoEncoderPrivate; + + /// \brief The VideoEncoder class supports encoding a series of images + /// to a video format, and then writing the video to disk. + class IGNITION_COMMON_AV_VISIBLE VideoEncoder + { + /// \brief Constructor + public: VideoEncoder(); + + /// \brief Destructor + public: virtual ~VideoEncoder(); + + /// \brief Start the encoder. This should be called once. Add new + /// frames to the video using the AddFrame function. Use SaveToFile + /// when the video is complete. + /// \param[in] _width Width in pixels of the output video. + /// \param[in] _height Height in pixels of the output video. + /// \param[in] _format String that represents the video type. + /// Supported types include: "avi", "ogv", mp4", "v4l2". If using + /// "v4l2", you must also specify a _filename. + /// \param[in] _bitRate Bit rate to encode the video. A value of zero + /// will cause this function to automatically compute a bitrate. + /// \param[in] _filename Name of the file that stores the video while it + /// is being created. This is a temporary file when recording to + /// disk, or a video4linux loopback device like /dev/video0 when + /// the _format is "v4l2". If blank, a default temporary file is used. + /// However, the "v4l2" _format must be accompanied with a video + /// loopback device filename. + /// \return True on success. Do NOT ignore the return value. If Start() + /// failed, encoding will not work. If Start() function failed, you can + /// try running the overload with _allowHwAccel=false to see if the + /// failure isn't a result of faulty HW encoding (e.g. when NVENC sessions + /// are exhausted). + /// \note This will automatically select a HW-accelerated encoder based + /// on the values of environment variables IGN_VIDEO_ALLOWED_ENCODERS, + /// IGN_VIDEO_ENCODER_DEVICE and IGN_VIDEO_ENCODER_USE_HW_SURFACE. + /// To completely avoid trying to set up HW accelerated encoding, + /// set IGN_VIDEO_ALLOWED_ENCODERS to value NONE or leave it empty or + /// unset. + /// The meaning of these variables is the following: + /// - IGN_VIDEO_ALLOWED_ENCODERS is a colon-separated list of values of + /// HWEncoderType enum, or ALL to allow all encoders. Default is NONE. + /// - IGN_VIDEO_ENCODER_DEVICE optionally specifies the HW device + /// to use for encoding (used only when a matching encoder is found + /// first). By default, an empty string is used, which means to use + /// whatever device is found to work first. + /// - IGN_VIDEO_USE_HW_SURFACE specifies whether the encoder should use + /// an explicit GPU buffer for video frames. Some codecs do this + /// implicitly, and then this setting has no meaning (setting it to 1 can + /// actually decrease performance). For codecs that need to set this + /// explicitly, this variable is checked for three values: 1, 0 and empty. + /// Empty value means that the implementation should guess whether + /// explicit GPU buffers are worth it or not. + public: bool Start( + const std::string &_format = VIDEO_ENCODER_FORMAT_DEFAULT, + const std::string &_filename = "", + const unsigned int _width = VIDEO_ENCODER_WIDTH_DEFAULT, + const unsigned int _height = VIDEO_ENCODER_HEIGHT_DEFAULT, + const unsigned int _fps = VIDEO_ENCODER_FPS_DEFAULT, + const unsigned int _bitRate = VIDEO_ENCODER_BITRATE_DEFAULT); + + /// \brief Start the encoder. This should be called once. Add new + /// frames to the video using the AddFrame function. Use SaveToFile + /// when the video is complete. + /// \param[in] _width Width in pixels of the output video. + /// \param[in] _height Height in pixels of the output video. + /// \param[in] _format String that represents the video type. + /// Supported types include: "avi", "ogv", mp4", "v4l2". If using + /// "v4l2", you must also specify a _filename. + /// \param[in] _bitRate Bit rate to encode the video. A value of zero + /// will cause this function to automatically compute a bitrate. + /// \param[in] _filename Name of the file that stores the video while it + /// is being created. This is a temporary file when recording to + /// disk, or a video4linux loopback device like /dev/video0 when + /// the _format is "v4l2". If blank, a default temporary file is used. + /// However, the "v4l2" _format must be accompanied with a video + /// loopback device filename. + /// \param[in] _allowHwAccel If true, HW acceleration settings are read + /// from environment variables (see the other Start() overload for the + /// loading mechanism description). If set to false, only SW encoding will + /// be done. + /// \return True on success. Do NOT ignore the return value. If Start() + /// failed, encoding will not work. If Start() function failed and you ran + /// it with allowed HW acceleration, you can try running it once more + /// without it (this can help in case the HW encoder can be found and + /// detected, but it fails to start, e.g. when NVENC sessions are + /// exhausted). + public: bool Start( + const std::string &_format, + const std::string &_filename, + const unsigned int _width, + const unsigned int _height, + const unsigned int _fps, + const unsigned int _bitRate, + const bool _allowHwAccel); + + /// \brief Start the encoder. This should be called once. Add new + /// frames to the video using the AddFrame function. Use SaveToFile + /// when the video is complete. + /// \param[in] _width Width in pixels of the output video. + /// \param[in] _height Height in pixels of the output video. + /// \param[in] _format String that represents the video type. + /// Supported types include: "avi", "ogv", mp4", "v4l2". If using + /// "v4l2", you must also specify a _filename. + /// \param[in] _bitRate Bit rate to encode the video. A value of zero + /// will cause this function to automatically compute a bitrate. + /// \param[in] _filename Name of the file that stores the video while it + /// is being created. This is a temporary file when recording to + /// disk, or a video4linux loopback device like /dev/video0 when + /// the _format is "v4l2". If blank, a default temporary file is used. + /// However, the "v4l2" _format must be accompanied with a video + /// loopback device filename. + /// \param[in] _allowedHwAccel Allowed HW acceleration frameworks to + /// probe (as a bitmask of values of HWAccelerationDevice enum). + /// Set to HWAccelerationDevice::NONE to force software encoding only. + /// \param[in] _hwAccelDevice If nonempty, specifies the HW device to use + /// for encoding. If empty, the framework search method will look for some + /// default devices. + /// \return True on success. Do NOT ignore the return value. If Start() + /// failed, encoding will not work. If Start() function failed and you ran + /// it with some HW acceleration, you can try running it once more + /// with a different acceleration config (this can help in case the HW + /// encoder can be found and detected, but it fails to start, e.g. when + /// NVENC sessions are exhausted). + public: bool Start( + const std::string &_format, + const std::string &_filename, + unsigned int _width, + unsigned int _height, + unsigned int _fps, + unsigned int _bitRate, + const FlagSet& _allowedHwAccel, + const std::string& _hwAccelDevice = "", + std::optional _useHwSurface = {}); + + /// \brief Stop the encoder. The SaveToFile function also calls this + /// function. + /// \return True on success. + public: bool Stop(); + + /// \brief True if the enoder has been started, false otherwise + /// \return True if Start has been called. + public: bool IsEncoding() const; + + /// \brief Add a single frame to be encoded + /// \param[in] _frame Image buffer to be encoded + /// \param[in] _width Input frame width + /// \param[in] _height Input frame height + /// \return True on success + public: bool AddFrame(const unsigned char *_frame, + const unsigned int _width, + const unsigned int _height); + + /// \brief Add a single timestamped frame to be encoded + /// \param[in] _frame Image buffer to be encoded + /// \param[in] _width Input frame width + /// \param[in] _height Input frame height + /// \param[in] _timestamp Timestamp of the image frame + /// \return True on success. + public: bool AddFrame(const unsigned char *_frame, + const unsigned int _width, + const unsigned int _height, + const std::chrono::steady_clock::time_point &_timestamp); + + /// \brief Write the video to disk + /// param[in] _filename File in which to save the encoded data + /// \return True on success. + public: bool SaveToFile(const std::string &_filename); + + /// \brief Get the encoding format + /// \return Encoding format + public: std::string Format() const; + + /// \brief Get the bit rate + /// \return Bit rate + public: unsigned int BitRate() const; + + /// \brief Reset to default video properties and clean up allocated + /// memory. This will also delete any temporary files. + public: void Reset(); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \internal + /// \brief Private data pointer + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} +#endif diff --git a/av/include/gz/common/av/Util.hh b/av/include/gz/common/av/Util.hh new file mode 100644 index 000000000..58d3ad756 --- /dev/null +++ b/av/include/gz/common/av/Util.hh @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2018 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +#ifndef GZ_COMMON_AV_UTIL_HH_ +#define GZ_COMMON_AV_UTIL_HH_ + +namespace ignition +{ + namespace common + { + /// \brief Load external libraries, such as libav. It is safe to call + /// this multiple times. + void load(); + } +} + +#endif diff --git a/av/include/gz/common/ffmpeg_inc.hh b/av/include/gz/common/ffmpeg_inc.hh new file mode 100644 index 000000000..5ca16c5a9 --- /dev/null +++ b/av/include/gz/common/ffmpeg_inc.hh @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_FFMPEG_INC_HH_ +#define GZ_COMMON_FFMPEG_INC_HH_ + +#include + +#include + +#ifndef _WIN32 +#pragma GCC system_header +#endif + +#ifndef INT64_C +#define INT64_C(c) (c ## LL) +#define UINT64_C(c) (c ## ULL) +#endif + +#ifndef AV_ERROR_MAX_STRING_SIZE +#define AV_ERROR_MAX_STRING_SIZE 64 +#endif + +extern "C" { +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) && defined(HAVE_AVDEVICE) +#include +#endif +} + +#include + +namespace ignition +{ + namespace common + { + /// \brief Helper function to avoid deprecation warnings. + IGNITION_COMMON_AV_VISIBLE + AVFrame *AVFrameAlloc(void); + + /// \brief Helper function to avoid deprecation warnings. + IGNITION_COMMON_AV_VISIBLE + void AVFrameUnref(AVFrame *_frame); + + /// \brief Helper function to avoid deprecation warnings. + /// \param[in] _packet AVPacket structure that stores compressed data + IGNITION_COMMON_AV_VISIBLE + void AVPacketUnref(AVPacket *_packet); + + /// \brief Helper function to avoid deprecation warnings + /// from av_codec_decode_video2. + /// \param[in] _codecCtx Codec context. + /// \param[out] _frame AVFrame in which decoded video frame is stored. + /// \param[out] _gotFrame Zero if no frame could be decompressed, + /// otherwise nonzero. + /// \param[in] _packet AVPacket structure that stores compressed data. + /// \return On error or eof, a negative value is returned, otherwise + /// the number of bytes used. + /// \note If the codec is in draining mode, _packet can be null. The return + /// value on success will then be 0, but _gotFrame will be non-zero. + IGNITION_COMMON_AV_VISIBLE + int AVCodecDecode(AVCodecContext *_codecCtx, + AVFrame *_frame, int *_gotFrame, AVPacket *_packet); + + // av_err2str only works in C99, this is a version that works in C++; + // https://github.com/joncampbell123/composite-video-simulator/issues/5#issuecomment-611885908 + inline std::string av_err2str_cpp(int errnum) + { + thread_local char buf[AV_ERROR_MAX_STRING_SIZE]; + memset(buf, 0, sizeof(buf)); + // lavu 51.58.100 + return av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, errnum); + } + } +} + +#endif diff --git a/av/include/ignition/common/AudioDecoder.hh b/av/include/ignition/common/AudioDecoder.hh index da9479a87..b287c4fc9 100644 --- a/av/include/ignition/common/AudioDecoder.hh +++ b/av/include/ignition/common/AudioDecoder.hh @@ -1,76 +1,19 @@ /* -* Copyright (C) 2016 Open Source Robotics Foundation -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -*/ -#ifndef IGNITION_COMMON_AUDIO_DECODER_HH_ -#define IGNITION_COMMON_AUDIO_DECODER_HH_ - -#include -#include -#include - -#include -#include - -namespace ignition -{ - namespace common - { - /// \brief Forward declaration of private data class - class AudioDecoderPrivate; - - /// \class AudioDecoder AudioDecoder.hh ignition/common/common.hh - /// \brief An audio decoder based on FFMPEG. - class IGNITION_COMMON_AV_VISIBLE AudioDecoder - { - /// \brief Constructor. - public: AudioDecoder(); - - /// \brief Destructor. - public: virtual ~AudioDecoder(); - - /// \brief Set the file to decode. - /// \param[in] _filename Path to an audio file. - /// \return True if the file was successfull opened. - public: bool SetFile(const std::string &_filename); - - /// \brief Get the audio filename that was set. - /// \return The name of the set audio file. - /// \sa AudioDecoder::SetFile - public: std::string File() const; - - /// \brief Decode the loaded audio file. - /// \sa AudioDecoder::SetFile - /// \param[out] _outBuffer Buffer that holds the decoded audio data. - /// \param[out] _outBufferSize Size of the _outBuffer. - /// \return True if decoding was succesful. - public: bool Decode(uint8_t **_outBuffer, unsigned int *_outBufferSize); - - /// \brief Get the sample rate from the latest decoded file. - /// \return Integer sample rate, such as 44100. - /// If no file is decoded, -1 is returned. - public: int SampleRate(); - - /// \brief Free audio object, close files, streams. - private: void Cleanup(); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief Private data pointer - private: std::unique_ptr data; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} -#endif + * Copyright (C) 2022 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include diff --git a/av/include/ignition/common/HWVideo.hh b/av/include/ignition/common/HWVideo.hh index 1d3da6491..66b59b6a9 100644 --- a/av/include/ignition/common/HWVideo.hh +++ b/av/include/ignition/common/HWVideo.hh @@ -1,5 +1,5 @@ /* - * Copyright 2020 Martin Pecka + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -12,45 +12,8 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ -#ifndef IGNITION_COMMON_HWVIDEO_HH -#define IGNITION_COMMON_HWVIDEO_HH - -#include - -namespace ignition::common -{ - enum class IGNITION_COMMON_AV_VISIBLE HWEncoderType - { - NONE, - NVENC, // Linux device is /dev/nvidia* - // Windows is the same (even though such file doesn't exist) - VAAPI, // Linux device /dev/dri/renderD* or display number (e.g. :0) - VDPAU, // Not supported (probably only for decoding?) - QSV, // Win device is 0-based GPU index, - // Linux uses /dev/dri/renderD* or display number (e.g. :0) - VIDEOTOOLBOX, // Not yet suported - AMF, // Not yet suported - OMX, // Not yet suported - V4L2M2M, // Not yet suported - DXVA2, // Not yet suported - _ // For FlagSet to work. - }; - - IGN_ENUM(HWEncoderTypeParser, HWEncoderType, - HWEncoderType::NONE, HWEncoderType::_, - "NONE", - "NVENC", - "VAAPI", - "VDPAU", - "QSV", - "VIDEOTOOLBOX", - "AMF", - "OMX", - "V4L2M2M", - "DXVA2", - "INVALID" - ) -} + * + */ -#endif +#include +#include diff --git a/av/include/ignition/common/Video.hh b/av/include/ignition/common/Video.hh index ee5fe14a6..dec3619c5 100644 --- a/av/include/ignition/common/Video.hh +++ b/av/include/ignition/common/Video.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,74 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_VIDEO_HH_ -#define IGNITION_COMMON_VIDEO_HH_ + */ -#include -#include - -#include -#include - -struct AVFormatContext; -struct AVCodecContext; -struct AVFrame; -struct AVPicture; -struct SwsContext; - -namespace ignition -{ - namespace common - { - // Forward declare private data class - class VideoPrivate; - - /// \brief Handle video encoding and decoding using libavcodec - class IGNITION_COMMON_AV_VISIBLE Video - { - /// \brief Constructor - public: Video(); - - /// \brief Destructor - public: virtual ~Video(); - - /// \brief Load a video file - /// \param[in] _filename Full path of the video file - /// \return false if a video stream can't be found - public: bool Load(const std::string &_filename); - - /// \brief Get the width of the video in pixels - /// \return the width - public: int Width() const; - - /// \brief Get the height of the video in pixels - /// \return the height - public: int Height() const; - - /// \brief Convenience type alias for duration - /// where 1000000 is the same as AV_TIME_BASE fractional seconds - public: - using Length = std::chrono::duration>; - - /// \brief Get the duration of the video - /// \return the duration - public: Length Duration() const; - - /// \brief Get the next frame of the video. - /// \param[out] _buffer Allocated buffer in which the frame is stored - /// (size has to be width * height * 3 bytes). - /// \return false on error or end of file - public: bool NextFrame(unsigned char **_buffer); - - /// \brief free up open Video object, close files, streams - private: void Cleanup(); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief Private data pointer - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} -#endif +#include +#include diff --git a/av/include/ignition/common/VideoEncoder.hh b/av/include/ignition/common/VideoEncoder.hh index 9c838e8c9..dc22cf1a8 100644 --- a/av/include/ignition/common/VideoEncoder.hh +++ b/av/include/ignition/common/VideoEncoder.hh @@ -1,5 +1,5 @@ /* - * Copyright 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,220 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_VIDEOENCODER_HH_ -#define IGNITION_COMMON_VIDEOENCODER_HH_ + */ -#include -#include -#include -#include - -#include -#include -#include -#include - -// Default bitrate (0) indicates that a bitrate should be calculated when -// Start is called. -#define VIDEO_ENCODER_BITRATE_DEFAULT 0 -#define VIDEO_ENCODER_WIDTH_DEFAULT 1280 -#define VIDEO_ENCODER_HEIGHT_DEFAULT 720 -#define VIDEO_ENCODER_FPS_DEFAULT 25 -#define VIDEO_ENCODER_FORMAT_DEFAULT "mp4" - -namespace ignition -{ - namespace common - { - // Forward declare private data class - class VideoEncoderPrivate; - - /// \brief The VideoEncoder class supports encoding a series of images - /// to a video format, and then writing the video to disk. - class IGNITION_COMMON_AV_VISIBLE VideoEncoder - { - /// \brief Constructor - public: VideoEncoder(); - - /// \brief Destructor - public: virtual ~VideoEncoder(); - - /// \brief Start the encoder. This should be called once. Add new - /// frames to the video using the AddFrame function. Use SaveToFile - /// when the video is complete. - /// \param[in] _width Width in pixels of the output video. - /// \param[in] _height Height in pixels of the output video. - /// \param[in] _format String that represents the video type. - /// Supported types include: "avi", "ogv", mp4", "v4l2". If using - /// "v4l2", you must also specify a _filename. - /// \param[in] _bitRate Bit rate to encode the video. A value of zero - /// will cause this function to automatically compute a bitrate. - /// \param[in] _filename Name of the file that stores the video while it - /// is being created. This is a temporary file when recording to - /// disk, or a video4linux loopback device like /dev/video0 when - /// the _format is "v4l2". If blank, a default temporary file is used. - /// However, the "v4l2" _format must be accompanied with a video - /// loopback device filename. - /// \return True on success. Do NOT ignore the return value. If Start() - /// failed, encoding will not work. If Start() function failed, you can - /// try running the overload with _allowHwAccel=false to see if the - /// failure isn't a result of faulty HW encoding (e.g. when NVENC sessions - /// are exhausted). - /// \note This will automatically select a HW-accelerated encoder based - /// on the values of environment variables IGN_VIDEO_ALLOWED_ENCODERS, - /// IGN_VIDEO_ENCODER_DEVICE and IGN_VIDEO_ENCODER_USE_HW_SURFACE. - /// To completely avoid trying to set up HW accelerated encoding, - /// set IGN_VIDEO_ALLOWED_ENCODERS to value NONE or leave it empty or - /// unset. - /// The meaning of these variables is the following: - /// - IGN_VIDEO_ALLOWED_ENCODERS is a colon-separated list of values of - /// HWEncoderType enum, or ALL to allow all encoders. Default is NONE. - /// - IGN_VIDEO_ENCODER_DEVICE optionally specifies the HW device - /// to use for encoding (used only when a matching encoder is found - /// first). By default, an empty string is used, which means to use - /// whatever device is found to work first. - /// - IGN_VIDEO_USE_HW_SURFACE specifies whether the encoder should use - /// an explicit GPU buffer for video frames. Some codecs do this - /// implicitly, and then this setting has no meaning (setting it to 1 can - /// actually decrease performance). For codecs that need to set this - /// explicitly, this variable is checked for three values: 1, 0 and empty. - /// Empty value means that the implementation should guess whether - /// explicit GPU buffers are worth it or not. - public: bool Start( - const std::string &_format = VIDEO_ENCODER_FORMAT_DEFAULT, - const std::string &_filename = "", - const unsigned int _width = VIDEO_ENCODER_WIDTH_DEFAULT, - const unsigned int _height = VIDEO_ENCODER_HEIGHT_DEFAULT, - const unsigned int _fps = VIDEO_ENCODER_FPS_DEFAULT, - const unsigned int _bitRate = VIDEO_ENCODER_BITRATE_DEFAULT); - - /// \brief Start the encoder. This should be called once. Add new - /// frames to the video using the AddFrame function. Use SaveToFile - /// when the video is complete. - /// \param[in] _width Width in pixels of the output video. - /// \param[in] _height Height in pixels of the output video. - /// \param[in] _format String that represents the video type. - /// Supported types include: "avi", "ogv", mp4", "v4l2". If using - /// "v4l2", you must also specify a _filename. - /// \param[in] _bitRate Bit rate to encode the video. A value of zero - /// will cause this function to automatically compute a bitrate. - /// \param[in] _filename Name of the file that stores the video while it - /// is being created. This is a temporary file when recording to - /// disk, or a video4linux loopback device like /dev/video0 when - /// the _format is "v4l2". If blank, a default temporary file is used. - /// However, the "v4l2" _format must be accompanied with a video - /// loopback device filename. - /// \param[in] _allowHwAccel If true, HW acceleration settings are read - /// from environment variables (see the other Start() overload for the - /// loading mechanism description). If set to false, only SW encoding will - /// be done. - /// \return True on success. Do NOT ignore the return value. If Start() - /// failed, encoding will not work. If Start() function failed and you ran - /// it with allowed HW acceleration, you can try running it once more - /// without it (this can help in case the HW encoder can be found and - /// detected, but it fails to start, e.g. when NVENC sessions are - /// exhausted). - public: bool Start( - const std::string &_format, - const std::string &_filename, - const unsigned int _width, - const unsigned int _height, - const unsigned int _fps, - const unsigned int _bitRate, - const bool _allowHwAccel); - - /// \brief Start the encoder. This should be called once. Add new - /// frames to the video using the AddFrame function. Use SaveToFile - /// when the video is complete. - /// \param[in] _width Width in pixels of the output video. - /// \param[in] _height Height in pixels of the output video. - /// \param[in] _format String that represents the video type. - /// Supported types include: "avi", "ogv", mp4", "v4l2". If using - /// "v4l2", you must also specify a _filename. - /// \param[in] _bitRate Bit rate to encode the video. A value of zero - /// will cause this function to automatically compute a bitrate. - /// \param[in] _filename Name of the file that stores the video while it - /// is being created. This is a temporary file when recording to - /// disk, or a video4linux loopback device like /dev/video0 when - /// the _format is "v4l2". If blank, a default temporary file is used. - /// However, the "v4l2" _format must be accompanied with a video - /// loopback device filename. - /// \param[in] _allowedHwAccel Allowed HW acceleration frameworks to - /// probe (as a bitmask of values of HWAccelerationDevice enum). - /// Set to HWAccelerationDevice::NONE to force software encoding only. - /// \param[in] _hwAccelDevice If nonempty, specifies the HW device to use - /// for encoding. If empty, the framework search method will look for some - /// default devices. - /// \return True on success. Do NOT ignore the return value. If Start() - /// failed, encoding will not work. If Start() function failed and you ran - /// it with some HW acceleration, you can try running it once more - /// with a different acceleration config (this can help in case the HW - /// encoder can be found and detected, but it fails to start, e.g. when - /// NVENC sessions are exhausted). - public: bool Start( - const std::string &_format, - const std::string &_filename, - unsigned int _width, - unsigned int _height, - unsigned int _fps, - unsigned int _bitRate, - const FlagSet& _allowedHwAccel, - const std::string& _hwAccelDevice = "", - std::optional _useHwSurface = {}); - - /// \brief Stop the encoder. The SaveToFile function also calls this - /// function. - /// \return True on success. - public: bool Stop(); - - /// \brief True if the enoder has been started, false otherwise - /// \return True if Start has been called. - public: bool IsEncoding() const; - - /// \brief Add a single frame to be encoded - /// \param[in] _frame Image buffer to be encoded - /// \param[in] _width Input frame width - /// \param[in] _height Input frame height - /// \return True on success - public: bool AddFrame(const unsigned char *_frame, - const unsigned int _width, - const unsigned int _height); - - /// \brief Add a single timestamped frame to be encoded - /// \param[in] _frame Image buffer to be encoded - /// \param[in] _width Input frame width - /// \param[in] _height Input frame height - /// \param[in] _timestamp Timestamp of the image frame - /// \return True on success. - public: bool AddFrame(const unsigned char *_frame, - const unsigned int _width, - const unsigned int _height, - const std::chrono::steady_clock::time_point &_timestamp); - - /// \brief Write the video to disk - /// param[in] _filename File in which to save the encoded data - /// \return True on success. - public: bool SaveToFile(const std::string &_filename); - - /// \brief Get the encoding format - /// \return Encoding format - public: std::string Format() const; - - /// \brief Get the bit rate - /// \return Bit rate - public: unsigned int BitRate() const; - - /// \brief Reset to default video properties and clean up allocated - /// memory. This will also delete any temporary files. - public: void Reset(); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \internal - /// \brief Private data pointer - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} -#endif +#include +#include diff --git a/av/include/ignition/common/av.hh b/av/include/ignition/common/av.hh new file mode 100644 index 000000000..e31d7dc42 --- /dev/null +++ b/av/include/ignition/common/av.hh @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2022 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include diff --git a/av/include/ignition/common/av/Export.hh b/av/include/ignition/common/av/Export.hh new file mode 100644 index 000000000..c51d279e4 --- /dev/null +++ b/av/include/ignition/common/av/Export.hh @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2022 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include diff --git a/av/include/ignition/common/av/Util.hh b/av/include/ignition/common/av/Util.hh index e8aabc9e2..5798cf171 100644 --- a/av/include/ignition/common/av/Util.hh +++ b/av/include/ignition/common/av/Util.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,19 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ + */ -#ifndef IGNITION_COMMON_AV_UTIL_HH_ -#define IGNITION_COMMON_AV_UTIL_HH_ - -namespace ignition -{ - namespace common - { - /// \brief Load external libraries, such as libav. It is safe to call - /// this multiple times. - void load(); - } -} - -#endif +#include +#include diff --git a/av/include/ignition/common/ffmpeg_inc.hh b/av/include/ignition/common/ffmpeg_inc.hh index be0c07124..a6f036078 100644 --- a/av/include/ignition/common/ffmpeg_inc.hh +++ b/av/include/ignition/common/ffmpeg_inc.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,86 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_FFMPEG_INC_HH_ -#define IGNITION_COMMON_FFMPEG_INC_HH_ - -#include + */ +#include #include - -#ifndef _WIN32 -#pragma GCC system_header -#endif - -#ifndef INT64_C -#define INT64_C(c) (c ## LL) -#define UINT64_C(c) (c ## ULL) -#endif - -#ifndef AV_ERROR_MAX_STRING_SIZE -#define AV_ERROR_MAX_STRING_SIZE 64 -#endif - -extern "C" { -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(__linux__) && defined(HAVE_AVDEVICE) -#include -#endif -} - -#include - -namespace ignition -{ - namespace common - { - /// \brief Helper function to avoid deprecation warnings. - IGNITION_COMMON_AV_VISIBLE - AVFrame *AVFrameAlloc(void); - - /// \brief Helper function to avoid deprecation warnings. - IGNITION_COMMON_AV_VISIBLE - void AVFrameUnref(AVFrame *_frame); - - /// \brief Helper function to avoid deprecation warnings. - /// \param[in] _packet AVPacket structure that stores compressed data - IGNITION_COMMON_AV_VISIBLE - void AVPacketUnref(AVPacket *_packet); - - /// \brief Helper function to avoid deprecation warnings - /// from av_codec_decode_video2. - /// \param[in] _codecCtx Codec context. - /// \param[out] _frame AVFrame in which decoded video frame is stored. - /// \param[out] _gotFrame Zero if no frame could be decompressed, - /// otherwise nonzero. - /// \param[in] _packet AVPacket structure that stores compressed data. - /// \return On error or eof, a negative value is returned, otherwise - /// the number of bytes used. - /// \note If the codec is in draining mode, _packet can be null. The return - /// value on success will then be 0, but _gotFrame will be non-zero. - IGNITION_COMMON_AV_VISIBLE - int AVCodecDecode(AVCodecContext *_codecCtx, - AVFrame *_frame, int *_gotFrame, AVPacket *_packet); - - // av_err2str only works in C99, this is a version that works in C++; - // https://github.com/joncampbell123/composite-video-simulator/issues/5#issuecomment-611885908 - inline std::string av_err2str_cpp(int errnum) - { - thread_local char buf[AV_ERROR_MAX_STRING_SIZE]; - memset(buf, 0, sizeof(buf)); - // lavu 51.58.100 - return av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, errnum); - } - } -} - -#endif diff --git a/av/src/AudioDecoder.cc b/av/src/AudioDecoder.cc index 8fcdab44b..32fef0779 100644 --- a/av/src/AudioDecoder.cc +++ b/av/src/AudioDecoder.cc @@ -15,10 +15,10 @@ * */ -#include -#include -#include -#include +#include +#include +#include +#include #define AUDIO_INBUF_SIZE (20480 * 2) #define AUDIO_REFILL_THRESH 4096 @@ -26,7 +26,7 @@ using namespace ignition; using namespace common; -class ignition::common::AudioDecoderPrivate +class gz::common::AudioDecoderPrivate { /// \brief libav Format I/O context. public: AVFormatContext *formatCtx; diff --git a/av/src/AudioDecoder_TEST.cc b/av/src/AudioDecoder_TEST.cc index 91562d42e..ed77faa5a 100644 --- a/av/src/AudioDecoder_TEST.cc +++ b/av/src/AudioDecoder_TEST.cc @@ -16,8 +16,8 @@ */ #include -#include -#include +#include +#include #include "test_config.h" diff --git a/av/src/HWEncoder.cc b/av/src/HWEncoder.cc index 91525bd98..9daaf646b 100644 --- a/av/src/HWEncoder.cc +++ b/av/src/HWEncoder.cc @@ -20,16 +20,16 @@ #include #include -#include "ignition/common/ffmpeg_inc.hh" -#include "ignition/common/HWEncoder.hh" -#include "ignition/common/StringUtils.hh" -#include "ignition/common/Console.hh" +#include "gz/common/ffmpeg_inc.hh" +#include "gz/common/HWEncoder.hh" +#include "gz/common/StringUtils.hh" +#include "gz/common/Console.hh" using namespace ignition; using namespace common; using namespace std; -class ignition::common::HWVideoPrivate +class gz::common::HWVideoPrivate { /// \brief Device reference for HW-accelerated encoding. public: AVBufferRef* hwDevice = nullptr; diff --git a/av/src/Util.cc b/av/src/Util.cc index 1cf75596b..14ccf29e8 100644 --- a/av/src/Util.cc +++ b/av/src/Util.cc @@ -17,9 +17,9 @@ #include -#include -#include -#include +#include +#include +#include ///////////////////////////////////////////////// // avcodec log callback. We use this to redirect message to gazebo's console @@ -67,7 +67,7 @@ void logCallback(void *_ptr, int _level, const char *_fmt, va_list _args) } ///////////////////////////////////////////////// -void ignition::common::load() +void gz::common::load() { static bool first = true; if (first) diff --git a/av/src/Video.cc b/av/src/Video.cc index b51234f67..2e916f089 100644 --- a/av/src/Video.cc +++ b/av/src/Video.cc @@ -14,17 +14,17 @@ * limitations under the License. * */ -#include "ignition/common/config.hh" -#include "ignition/common/Console.hh" -#include "ignition/common/ffmpeg_inc.hh" -#include "ignition/common/Video.hh" -#include "ignition/common/av/Util.hh" +#include "gz/common/config.hh" +#include "gz/common/Console.hh" +#include "gz/common/ffmpeg_inc.hh" +#include "gz/common/Video.hh" +#include "gz/common/av/Util.hh" using namespace ignition; using namespace common; // Private data structure for the Video class -class ignition::common::VideoPrivate +class gz::common::VideoPrivate { /// \brief libav Format I/O context public: AVFormatContext *formatCtx = nullptr; diff --git a/av/src/VideoEncoder.cc b/av/src/VideoEncoder.cc index 6d118df6a..34f7e617b 100644 --- a/av/src/VideoEncoder.cc +++ b/av/src/VideoEncoder.cc @@ -18,14 +18,14 @@ #include -#include -#include "ignition/common/ffmpeg_inc.hh" -#include "ignition/common/Console.hh" -#include "ignition/common/VideoEncoder.hh" -#include "ignition/common/StringUtils.hh" +#include +#include "gz/common/ffmpeg_inc.hh" +#include "gz/common/Console.hh" +#include "gz/common/VideoEncoder.hh" +#include "gz/common/StringUtils.hh" #ifdef IGN_COMMON_BUILD_HW_VIDEO -#include "ignition/common/HWEncoder.hh" +#include "gz/common/HWEncoder.hh" #endif using namespace ignition; diff --git a/av/src/VideoEncoder_TEST.cc b/av/src/VideoEncoder_TEST.cc index c4cc1316a..a51d9883d 100644 --- a/av/src/VideoEncoder_TEST.cc +++ b/av/src/VideoEncoder_TEST.cc @@ -15,8 +15,8 @@ */ #include -#include "ignition/common/Console.hh" -#include "ignition/common/VideoEncoder.hh" +#include "gz/common/Console.hh" +#include "gz/common/VideoEncoder.hh" #include "test_config.h" using namespace ignition; diff --git a/av/src/ffmpeg_inc.cc b/av/src/ffmpeg_inc.cc index 2899b2ca9..287bfbe5c 100644 --- a/av/src/ffmpeg_inc.cc +++ b/av/src/ffmpeg_inc.cc @@ -14,7 +14,7 @@ * limitations under the License. * */ -#include "ignition/common/ffmpeg_inc.hh" +#include "gz/common/ffmpeg_inc.hh" using namespace ignition; diff --git a/events/include/CMakeLists.txt b/events/include/CMakeLists.txt new file mode 100644 index 000000000..4b2bdd7bb --- /dev/null +++ b/events/include/CMakeLists.txt @@ -0,0 +1,2 @@ +add_subdirectory(gz) +install(DIRECTORY ignition DESTINATION ${IGN_INCLUDE_INSTALL_DIR_FULL}) diff --git a/events/include/gz/CMakeLists.txt b/events/include/gz/CMakeLists.txt new file mode 100644 index 000000000..e4717b2d6 --- /dev/null +++ b/events/include/gz/CMakeLists.txt @@ -0,0 +1 @@ +add_subdirectory(common) diff --git a/events/include/ignition/common/CMakeLists.txt b/events/include/gz/common/CMakeLists.txt similarity index 100% rename from events/include/ignition/common/CMakeLists.txt rename to events/include/gz/common/CMakeLists.txt diff --git a/events/include/gz/common/Event.hh b/events/include/gz/common/Event.hh new file mode 100644 index 000000000..471c58216 --- /dev/null +++ b/events/include/gz/common/Event.hh @@ -0,0 +1,279 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_EVENT_HH_ +#define GZ_COMMON_EVENT_HH_ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace ignition +{ + namespace common + { + /// \class Event Event.hh ignition/common/Event.hh + /// \brief Base class for all events + class IGNITION_COMMON_EVENTS_VISIBLE Event + { + /// \brief Constructor + public: Event(); + + /// \brief Destructor + public: virtual ~Event(); + + /// \brief Disconnect + /// \param[in] _id Integer ID of a connection + public: virtual void Disconnect(int _id) = 0; + + /// \brief Get whether this event has been signaled. + /// \return True if the event has been signaled. + public: bool Signaled() const; + + /// \brief Set whether this event has been signaled. + /// \param[in] _sig True if the event has been signaled. + public: void SetSignaled(const bool _sig); + + /// \brief True if the event has been signaled. + private: bool signaled; + }; + + /// \brief A class that encapsulates a connection. + class IGNITION_COMMON_EVENTS_VISIBLE Connection + { + /// \brief Constructor. + /// \param[in] _e Event pointer to connect with. + /// \param[in] _i Unique id. + public: Connection(Event *_e, const int _i); + + /// \brief Destructor. + public: ~Connection(); + + /// \brief Get the id of this connection. + /// \return The id of this connection. + public: int Id() const; + + /// \brief the event for this connection + private: Event *event = nullptr; + + /// \brief the id set in the constructor + private: int id = -1; + +#ifdef _WIN32 +// Disable warning C4251 +#pragma warning(push) +#pragma warning(disable: 4251) +#endif + /// \brief set during the constructor + private: std::chrono::time_point creationTime; +#ifdef _WIN32 +#pragma warning(pop) +#endif + + /// \brief Friend class. + public: template friend class EventT; + }; + + /// \brief A class for event processing. + /// \tparam T function event callback function signature + /// \tparam N optional additional type to disambiguate events with same + /// function signature + template + class EventT : public Event + { + public: using CallbackT = std::function; + static_assert(std::is_same::value, + "Event callback must have void return type"); + + /// \brief Constructor. + public: EventT(); + + /// \brief Destructor. + public: virtual ~EventT(); + + /// \brief Connect a callback to this event. + /// \param[in] _subscriber Pointer to a callback function. + /// \return A Connection object, which will automatically call + /// Disconnect when it goes out of scope. + public: ConnectionPtr Connect(const CallbackT &_subscriber); + + /// \brief Disconnect a callback to this event. + /// \param[in] _id The id of the connection to disconnect. + public: virtual void Disconnect(int _id); + + /// \brief Get the number of connections. + /// \return Number of connection to this Event. + public: unsigned int ConnectionCount() const; + + /// \brief Access the signal. + public: template + void operator()(Args && ... args) + { + this->Signal(std::forward(args)...); + } + + /// \brief Signal the event for all subscribers. + public: template + void Signal(Args && ... args) + { + this->Cleanup(); + + this->SetSignaled(true); + for (const auto &iter : this->connections) + { + if (iter.second->on) + iter.second->callback(std::forward(args)...); + } + } + + /// \internal + /// \brief Removes queued connections. + /// We assume that this function is called from a Signal function. + private: void Cleanup(); + + /// \brief A private helper class used in maintaining connections. + private: class EventConnection + { + /// \brief Constructor + public: EventConnection(const bool _on, const std::function &_cb, + const ConnectionPtr &_publicConn) + : callback(_cb), publicConnection(_publicConn) + { + // Windows Visual Studio 2012 does not have atomic_bool constructor, + // so we have to set "on" using operator= + this->on = _on; + } + + /// \brief On/off value for the event callback + public: std::atomic_bool on; + + /// \brief Callback function + public: std::function callback; + + /// \brief A weak pointer to the Connection pointer returned by Connect. + /// This is used to clear the Connection's Event pointer during + /// destruction of an Event. + public: std::weak_ptr publicConnection; + }; + + /// \def EvtConnectionMap + /// \brief Event Connection map typedef. + typedef std::map> EvtConnectionMap; + + /// \brief Array of connection callbacks. + private: EvtConnectionMap connections; + + /// \brief A thread lock. + private: std::mutex mutex; + + /// \brief List of connections to remove + private: std::list + connectionsToRemove; + }; + + /// \brief Constructor. + template + EventT::EventT() + : Event() + { + } + + /// \brief Destructor. Deletes all the associated connections. + template + EventT::~EventT() + { + // Clear the Event pointer on all connections so that they are not + // accessed after this Event is destructed. + for (auto &conn : this->connections) + { + auto publicCon = conn.second->publicConnection.lock(); + if (publicCon) + { + publicCon->event = nullptr; + } + } + this->connections.clear(); + } + + /// \brief Adds a connection. + /// \param[in] _subscriber the subscriber to connect. + template + ConnectionPtr EventT::Connect(const std::function &_subscriber) + { + int index = 0; + if (!this->connections.empty()) + { + auto const &iter = this->connections.rbegin(); + index = iter->first + 1; + } + auto connection = ConnectionPtr(new Connection(this, index)); + this->connections[index].reset( + new EventConnection(true, _subscriber, connection)); + return connection; + } + + /// \brief Get the number of connections. + /// \return Number of connections. + template + unsigned int EventT::ConnectionCount() const + { + return this->connections.size(); + } + + /// \brief Removes a connection. + /// \param[in] _id the connection index. + template + void EventT::Disconnect(int _id) + { + // Find the connection + auto const &it = this->connections.find(_id); + + if (it != this->connections.end()) + { + it->second->on = false; + // The destructor of std::function seems to crashes if the function it + // points to is in a shared library and has been unloaded by the time + // the destructor is invoked. It's not clear whether this is a bug in + // the implementation of std::function or not. To avoid the crash, + // we call the destructor here by setting `callback = nullptr` because + // it is likely that EventT::Disconnect is called before the shared + // library is unloaded via Connection::~Connection. + it->second->callback = nullptr; + this->connectionsToRemove.push_back(it); + } + } + + ///////////////////////////////////////////// + template + void EventT::Cleanup() + { + std::lock_guard lock(this->mutex); + // Remove all queue connections. + for (auto &conn : this->connectionsToRemove) + this->connections.erase(conn); + this->connectionsToRemove.clear(); + } + } +} +#endif diff --git a/events/include/gz/common/KeyEvent.hh b/events/include/gz/common/KeyEvent.hh new file mode 100644 index 000000000..325d3b21d --- /dev/null +++ b/events/include/gz/common/KeyEvent.hh @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_KEYEVENT_HH_ +#define GZ_COMMON_KEYEVENT_HH_ + +#include +#include + +#include +#include + +namespace ignition +{ + namespace common + { + // Forward declare private data class + class KeyEventPrivate; + + /// \class KeyEvent KeyEvent.hh ignition/common/KeyEvent.hh + /// \brief Generic description of a keyboard event. + class IGNITION_COMMON_EVENTS_VISIBLE KeyEvent + { + /// \brief Key event types enumeration. + public: enum EventType {NO_EVENT, PRESS, RELEASE}; + + /// \brief Constructor. + public: KeyEvent(); + + /// \brief Copy constructor. + /// \param[in] _other Other key event + public: KeyEvent(const KeyEvent &_other); + + // \brief Move constructor. + /// \param[in] _other Other key event + public: KeyEvent(KeyEvent &&_other); + + /// \brief Destructor + public: ~KeyEvent(); + + /// \brief Get the event type + /// \return The key event type + public: EventType Type() const; + + /// \brief Set the event type + /// \param[in] _type Event type + public: void SetType(const EventType _type); + + /// \brief Get the key number + /// \return The key number + public: int Key() const; + + /// \brief Set the key + /// \param[in] _key The key number + public: void SetKey(const int _key); + + /// \brief Get the formatted string of the key pressed (could be + /// uppercase). + /// \return The formatted string of the key pressed. + public: std::string Text() const; + + /// \brief Set the formatted string of the key pressed. + /// \param[in] _text Formatted string of the key pressed. + public: void SetText(const std::string &_text); + + /// \brief Get whether the control key was held during this key event + /// \return True if the control key was pressed + public: bool Control() const; + + /// \brief Set whether the control key was held during this key event + /// \param[in] _control Status of the control key + public: void SetControl(const bool _control); + + /// \brief Get whether the shift key was held during this key event + /// \return True if the shift key was pressed + public: bool Shift() const; + + /// \brief Set whether the shift key was held during this key event + /// \param[in] _shift Status of the shift key + public: void SetShift(const bool _shift); + + /// \brief Get whether the alt key was held during this key event + /// \return True if the alt key was pressed + public: bool Alt() const; + + /// \brief Set whether the alt key was held during this key event + /// \param[in] _alt Status of the alt key + public: void SetAlt(const bool _alt); + + /// \brief Assignment operator + /// \param[in] _other Other key event + /// \return this + public: KeyEvent &operator=(const KeyEvent &_other); + + /// \brief Move assignment operator. + /// \param[in] _other Other key event + /// \return this + public: KeyEvent& operator=(KeyEvent&& other); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief Private data pointer + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} +#endif diff --git a/events/include/gz/common/MouseEvent.hh b/events/include/gz/common/MouseEvent.hh new file mode 100644 index 000000000..006701a00 --- /dev/null +++ b/events/include/gz/common/MouseEvent.hh @@ -0,0 +1,214 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_MOUSEEVENT_HH_ +#define GZ_COMMON_MOUSEEVENT_HH_ + +#include +#include + +#include +#include + +namespace ignition +{ + namespace common + { + /// Forward declare private data + class MouseEventPrivate; + + /// \class MouseEvent MouseEvent.hh ignition/common/MouseEvent.hh + /// \brief Generic description of a mouse event. + class IGNITION_COMMON_EVENTS_VISIBLE MouseEvent + { + /// \brief Standard mouse buttons enumeration. + public: enum MouseButton + { + /// \brief No button + NO_BUTTON = 0x0, + + /// \brief Left button + LEFT = 0x1, + + /// \brief Middle button + MIDDLE = 0x2, + + /// \brief Right button + RIGHT = 0x4 + }; + + /// \brief Mouse event types enumeration. + public: enum EventType + { + /// \brief No event + NO_EVENT, + + /// \brief Move event + MOVE, + + /// \brief Press event + PRESS, + + /// \brief Release event + RELEASE, + + /// \brief Scroll event + SCROLL + }; + + /// \brief Constructor. + public: MouseEvent(); + + /// \brief Copy constructor. + /// \param[in] _other Other mouse event + public: MouseEvent(const MouseEvent &_other); + + /// \brief Destructor + public: virtual ~MouseEvent(); + + /// \brief Get mouse pointer position on the screen. + /// \return Mouse pointer position on the screen. + public: gz::math::Vector2i Pos() const; + + /// \brief Set mouse pointer position on the screen. + /// \param[in] _pos Mouse pointer position on the screen. + public: void SetPos(const gz::math::Vector2i &_pos); + + /// \brief Set mouse pointer position on the screen. + /// \param[in] _x Mouse pointer X position on the screen. + /// \param[in] _y Mouse pointer Y position on the screen. + public: void SetPos(const int _x, const int _y); + + /// \brief Get the previous position. + /// \return The previous mouse position. + public: gz::math::Vector2i PrevPos() const; + + /// \brief Set the previous position. + /// \param[in] _pos Previous mouse pointer position on the screen. + public: void SetPrevPos(const gz::math::Vector2i &_pos); + + /// \brief Set the previous position. + /// \param[in] _x Previous mouse pointer X position on the screen. + /// \param[in] _y Previous mouse pointer Y position on the screen. + public: void SetPrevPos(const int _x, const int _y); + + /// \brief Get the position of button press. + /// \return Screen position of a button press. + public: gz::math::Vector2i PressPos() const; + + /// \brief Set the position of button press. + /// \param[in] _pos Mouse pointer position on the screen. + public: void SetPressPos(const gz::math::Vector2i &_pos); + + /// \brief Set the position of button press. + /// \param[in] _x Mouse pointer X position on the screen. + /// \param[in] _y Mouse pointer Y position on the screen. + public: void SetPressPos(const int _x, const int _y); + + /// \brief Get the scroll position. + /// \return The scroll position. + public: gz::math::Vector2i Scroll() const; + + /// \brief Set the scroll position. + /// \param[in] _scroll Scroll position. + public: void SetScroll(const gz::math::Vector2i &_scroll); + + /// \brief Set the scroll position. + /// \param[in] _x Scroll X position. + /// \param[in] _y Scroll Y position. + public: void SetScroll(const int _x, const int _y); + + /// \brief Get the scaling factor. + /// \return The move scaling factor. + public: float MoveScale() const; + + /// \brief Set the scaling factor. + /// \param[in] _scale The move scaling factor. + public: void SetMoveScale(const float _scale); + + /// \brief Get the flag for mouse drag motion + /// \return True if dragging, usually indicating a mouse move with + /// mouse button pressed. + public: bool Dragging() const; + + /// \brief Set the flag for mouse drag motion + /// \param[in] _dragging The dragging flag. + public: void SetDragging(const bool _dragging); + + /// \brief Get the event type. + /// \return The EventType. + public: EventType Type() const; + + /// \brief Set the event type. + /// \param[in] _type The EventType. + public: void SetType(const EventType _type) const; + + /// \brief Get the button which caused this event. + /// \return The button which caused this event. + public: MouseEvent::MouseButton Button() const; + + /// \brief Set the button which caused the event. + /// \param[in] _button The button which caused this event. + public: void SetButton(const MouseEvent::MouseButton _button) const; + + /// \brief Get the state of the buttons when the event was generated. + /// \return The state of the buttons, which can be a bitwise + /// combination of MouseEvent::MouseButton. + public: unsigned int Buttons() const; + + /// \brief Set the state of the buttons when the event was generated. + /// \param[in] _buttons The state of the buttons, which can be a bitwise + /// combination of MouseEvent::MouseButton. + public: void SetButtons(const unsigned int &_buttons); + + /// \brief Get the shift key press flag. + /// \return True if the shift key is pressed. + public: bool Shift() const; + + /// \brief Set the shift key press flag. + /// \param[in] _shift The shift key press flag. + public: void SetShift(const bool _shift) const; + + /// \brief Get the alt key press flag. + /// \return True if the alt key is pressed. + public: bool Alt() const; + + /// \brief Set the alt key press flag. + /// \param[in] _alt The alt key flag. + public: void SetAlt(const bool _alt); + + /// \brief Get the control key press flag. + /// \return True if the control key is pressed. + public: bool Control() const; + + /// \brief Set the control key press flag. + /// \param[in] _control The control key flag. + public: void SetControl(const bool _control) const; + + /// \brief Assignment operator + /// \param[in] _other Other mouse event + /// \return this + public: MouseEvent &operator=(const MouseEvent &_other); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \internal + /// \brief Private data pointer + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} +#endif diff --git a/events/include/gz/common/events/Types.hh b/events/include/gz/common/events/Types.hh new file mode 100644 index 000000000..f1ba2544f --- /dev/null +++ b/events/include/gz/common/events/Types.hh @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2018 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +#ifndef GZ_COMMON_EVENTS_TYPES_HH_ +#define GZ_COMMON_EVENTS_TYPES_HH_ + +#include + +// This header contains forward declarations for some event types +namespace ignition +{ + namespace common + { + class Connection; + + /// \def ConnectionPtr + /// \brief Shared pointer to a Connection object + using ConnectionPtr = std::shared_ptr; + } +} + +#endif diff --git a/events/include/ignition/common/Event.hh b/events/include/ignition/common/Event.hh index d1097613b..77d79b6de 100644 --- a/events/include/ignition/common/Event.hh +++ b/events/include/ignition/common/Event.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,267 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_EVENT_HH_ -#define IGNITION_COMMON_EVENT_HH_ - -#include -#include -#include -#include -#include -#include -#include + */ +#include #include -#include -#include - -namespace ignition -{ - namespace common - { - /// \class Event Event.hh ignition/common/Event.hh - /// \brief Base class for all events - class IGNITION_COMMON_EVENTS_VISIBLE Event - { - /// \brief Constructor - public: Event(); - - /// \brief Destructor - public: virtual ~Event(); - - /// \brief Disconnect - /// \param[in] _id Integer ID of a connection - public: virtual void Disconnect(int _id) = 0; - - /// \brief Get whether this event has been signaled. - /// \return True if the event has been signaled. - public: bool Signaled() const; - - /// \brief Set whether this event has been signaled. - /// \param[in] _sig True if the event has been signaled. - public: void SetSignaled(const bool _sig); - - /// \brief True if the event has been signaled. - private: bool signaled; - }; - - /// \brief A class that encapsulates a connection. - class IGNITION_COMMON_EVENTS_VISIBLE Connection - { - /// \brief Constructor. - /// \param[in] _e Event pointer to connect with. - /// \param[in] _i Unique id. - public: Connection(Event *_e, const int _i); - - /// \brief Destructor. - public: ~Connection(); - - /// \brief Get the id of this connection. - /// \return The id of this connection. - public: int Id() const; - - /// \brief the event for this connection - private: Event *event = nullptr; - - /// \brief the id set in the constructor - private: int id = -1; - -#ifdef _WIN32 -// Disable warning C4251 -#pragma warning(push) -#pragma warning(disable: 4251) -#endif - /// \brief set during the constructor - private: std::chrono::time_point creationTime; -#ifdef _WIN32 -#pragma warning(pop) -#endif - - /// \brief Friend class. - public: template friend class EventT; - }; - - /// \brief A class for event processing. - /// \tparam T function event callback function signature - /// \tparam N optional additional type to disambiguate events with same - /// function signature - template - class EventT : public Event - { - public: using CallbackT = std::function; - static_assert(std::is_same::value, - "Event callback must have void return type"); - - /// \brief Constructor. - public: EventT(); - - /// \brief Destructor. - public: virtual ~EventT(); - - /// \brief Connect a callback to this event. - /// \param[in] _subscriber Pointer to a callback function. - /// \return A Connection object, which will automatically call - /// Disconnect when it goes out of scope. - public: ConnectionPtr Connect(const CallbackT &_subscriber); - - /// \brief Disconnect a callback to this event. - /// \param[in] _id The id of the connection to disconnect. - public: virtual void Disconnect(int _id); - - /// \brief Get the number of connections. - /// \return Number of connection to this Event. - public: unsigned int ConnectionCount() const; - - /// \brief Access the signal. - public: template - void operator()(Args && ... args) - { - this->Signal(std::forward(args)...); - } - - /// \brief Signal the event for all subscribers. - public: template - void Signal(Args && ... args) - { - this->Cleanup(); - - this->SetSignaled(true); - for (const auto &iter : this->connections) - { - if (iter.second->on) - iter.second->callback(std::forward(args)...); - } - } - - /// \internal - /// \brief Removes queued connections. - /// We assume that this function is called from a Signal function. - private: void Cleanup(); - - /// \brief A private helper class used in maintaining connections. - private: class EventConnection - { - /// \brief Constructor - public: EventConnection(const bool _on, const std::function &_cb, - const ConnectionPtr &_publicConn) - : callback(_cb), publicConnection(_publicConn) - { - // Windows Visual Studio 2012 does not have atomic_bool constructor, - // so we have to set "on" using operator= - this->on = _on; - } - - /// \brief On/off value for the event callback - public: std::atomic_bool on; - - /// \brief Callback function - public: std::function callback; - - /// \brief A weak pointer to the Connection pointer returned by Connect. - /// This is used to clear the Connection's Event pointer during - /// destruction of an Event. - public: std::weak_ptr publicConnection; - }; - - /// \def EvtConnectionMap - /// \brief Event Connection map typedef. - typedef std::map> EvtConnectionMap; - - /// \brief Array of connection callbacks. - private: EvtConnectionMap connections; - - /// \brief A thread lock. - private: std::mutex mutex; - - /// \brief List of connections to remove - private: std::list - connectionsToRemove; - }; - - /// \brief Constructor. - template - EventT::EventT() - : Event() - { - } - - /// \brief Destructor. Deletes all the associated connections. - template - EventT::~EventT() - { - // Clear the Event pointer on all connections so that they are not - // accessed after this Event is destructed. - for (auto &conn : this->connections) - { - auto publicCon = conn.second->publicConnection.lock(); - if (publicCon) - { - publicCon->event = nullptr; - } - } - this->connections.clear(); - } - - /// \brief Adds a connection. - /// \param[in] _subscriber the subscriber to connect. - template - ConnectionPtr EventT::Connect(const std::function &_subscriber) - { - int index = 0; - if (!this->connections.empty()) - { - auto const &iter = this->connections.rbegin(); - index = iter->first + 1; - } - auto connection = ConnectionPtr(new Connection(this, index)); - this->connections[index].reset( - new EventConnection(true, _subscriber, connection)); - return connection; - } - - /// \brief Get the number of connections. - /// \return Number of connections. - template - unsigned int EventT::ConnectionCount() const - { - return this->connections.size(); - } - - /// \brief Removes a connection. - /// \param[in] _id the connection index. - template - void EventT::Disconnect(int _id) - { - // Find the connection - auto const &it = this->connections.find(_id); - - if (it != this->connections.end()) - { - it->second->on = false; - // The destructor of std::function seems to crashes if the function it - // points to is in a shared library and has been unloaded by the time - // the destructor is invoked. It's not clear whether this is a bug in - // the implementation of std::function or not. To avoid the crash, - // we call the destructor here by setting `callback = nullptr` because - // it is likely that EventT::Disconnect is called before the shared - // library is unloaded via Connection::~Connection. - it->second->callback = nullptr; - this->connectionsToRemove.push_back(it); - } - } - - ///////////////////////////////////////////// - template - void EventT::Cleanup() - { - std::lock_guard lock(this->mutex); - // Remove all queue connections. - for (auto &conn : this->connectionsToRemove) - this->connections.erase(conn); - this->connectionsToRemove.clear(); - } - } -} -#endif diff --git a/events/include/ignition/common/KeyEvent.hh b/events/include/ignition/common/KeyEvent.hh index a318cb2d0..5774badbb 100644 --- a/events/include/ignition/common/KeyEvent.hh +++ b/events/include/ignition/common/KeyEvent.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,108 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_KEYEVENT_HH_ -#define IGNITION_COMMON_KEYEVENT_HH_ + */ -#include -#include - -#include -#include - -namespace ignition -{ - namespace common - { - // Forward declare private data class - class KeyEventPrivate; - - /// \class KeyEvent KeyEvent.hh ignition/common/KeyEvent.hh - /// \brief Generic description of a keyboard event. - class IGNITION_COMMON_EVENTS_VISIBLE KeyEvent - { - /// \brief Key event types enumeration. - public: enum EventType {NO_EVENT, PRESS, RELEASE}; - - /// \brief Constructor. - public: KeyEvent(); - - /// \brief Copy constructor. - /// \param[in] _other Other key event - public: KeyEvent(const KeyEvent &_other); - - // \brief Move constructor. - /// \param[in] _other Other key event - public: KeyEvent(KeyEvent &&_other); - - /// \brief Destructor - public: ~KeyEvent(); - - /// \brief Get the event type - /// \return The key event type - public: EventType Type() const; - - /// \brief Set the event type - /// \param[in] _type Event type - public: void SetType(const EventType _type); - - /// \brief Get the key number - /// \return The key number - public: int Key() const; - - /// \brief Set the key - /// \param[in] _key The key number - public: void SetKey(const int _key); - - /// \brief Get the formatted string of the key pressed (could be - /// uppercase). - /// \return The formatted string of the key pressed. - public: std::string Text() const; - - /// \brief Set the formatted string of the key pressed. - /// \param[in] _text Formatted string of the key pressed. - public: void SetText(const std::string &_text); - - /// \brief Get whether the control key was held during this key event - /// \return True if the control key was pressed - public: bool Control() const; - - /// \brief Set whether the control key was held during this key event - /// \param[in] _control Status of the control key - public: void SetControl(const bool _control); - - /// \brief Get whether the shift key was held during this key event - /// \return True if the shift key was pressed - public: bool Shift() const; - - /// \brief Set whether the shift key was held during this key event - /// \param[in] _shift Status of the shift key - public: void SetShift(const bool _shift); - - /// \brief Get whether the alt key was held during this key event - /// \return True if the alt key was pressed - public: bool Alt() const; - - /// \brief Set whether the alt key was held during this key event - /// \param[in] _alt Status of the alt key - public: void SetAlt(const bool _alt); - - /// \brief Assignment operator - /// \param[in] _other Other key event - /// \return this - public: KeyEvent &operator=(const KeyEvent &_other); - - /// \brief Move assignment operator. - /// \param[in] _other Other key event - /// \return this - public: KeyEvent& operator=(KeyEvent&& other); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief Private data pointer - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} -#endif +#include +#include diff --git a/events/include/ignition/common/MouseEvent.hh b/events/include/ignition/common/MouseEvent.hh index b57ad5c4d..2cf06492d 100644 --- a/events/include/ignition/common/MouseEvent.hh +++ b/events/include/ignition/common/MouseEvent.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,202 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_MOUSEEVENT_HH_ -#define IGNITION_COMMON_MOUSEEVENT_HH_ + */ -#include -#include - -#include -#include - -namespace ignition -{ - namespace common - { - /// Forward declare private data - class MouseEventPrivate; - - /// \class MouseEvent MouseEvent.hh ignition/common/MouseEvent.hh - /// \brief Generic description of a mouse event. - class IGNITION_COMMON_EVENTS_VISIBLE MouseEvent - { - /// \brief Standard mouse buttons enumeration. - public: enum MouseButton - { - /// \brief No button - NO_BUTTON = 0x0, - - /// \brief Left button - LEFT = 0x1, - - /// \brief Middle button - MIDDLE = 0x2, - - /// \brief Right button - RIGHT = 0x4 - }; - - /// \brief Mouse event types enumeration. - public: enum EventType - { - /// \brief No event - NO_EVENT, - - /// \brief Move event - MOVE, - - /// \brief Press event - PRESS, - - /// \brief Release event - RELEASE, - - /// \brief Scroll event - SCROLL - }; - - /// \brief Constructor. - public: MouseEvent(); - - /// \brief Copy constructor. - /// \param[in] _other Other mouse event - public: MouseEvent(const MouseEvent &_other); - - /// \brief Destructor - public: virtual ~MouseEvent(); - - /// \brief Get mouse pointer position on the screen. - /// \return Mouse pointer position on the screen. - public: ignition::math::Vector2i Pos() const; - - /// \brief Set mouse pointer position on the screen. - /// \param[in] _pos Mouse pointer position on the screen. - public: void SetPos(const ignition::math::Vector2i &_pos); - - /// \brief Set mouse pointer position on the screen. - /// \param[in] _x Mouse pointer X position on the screen. - /// \param[in] _y Mouse pointer Y position on the screen. - public: void SetPos(const int _x, const int _y); - - /// \brief Get the previous position. - /// \return The previous mouse position. - public: ignition::math::Vector2i PrevPos() const; - - /// \brief Set the previous position. - /// \param[in] _pos Previous mouse pointer position on the screen. - public: void SetPrevPos(const ignition::math::Vector2i &_pos); - - /// \brief Set the previous position. - /// \param[in] _x Previous mouse pointer X position on the screen. - /// \param[in] _y Previous mouse pointer Y position on the screen. - public: void SetPrevPos(const int _x, const int _y); - - /// \brief Get the position of button press. - /// \return Screen position of a button press. - public: ignition::math::Vector2i PressPos() const; - - /// \brief Set the position of button press. - /// \param[in] _pos Mouse pointer position on the screen. - public: void SetPressPos(const ignition::math::Vector2i &_pos); - - /// \brief Set the position of button press. - /// \param[in] _x Mouse pointer X position on the screen. - /// \param[in] _y Mouse pointer Y position on the screen. - public: void SetPressPos(const int _x, const int _y); - - /// \brief Get the scroll position. - /// \return The scroll position. - public: ignition::math::Vector2i Scroll() const; - - /// \brief Set the scroll position. - /// \param[in] _scroll Scroll position. - public: void SetScroll(const ignition::math::Vector2i &_scroll); - - /// \brief Set the scroll position. - /// \param[in] _x Scroll X position. - /// \param[in] _y Scroll Y position. - public: void SetScroll(const int _x, const int _y); - - /// \brief Get the scaling factor. - /// \return The move scaling factor. - public: float MoveScale() const; - - /// \brief Set the scaling factor. - /// \param[in] _scale The move scaling factor. - public: void SetMoveScale(const float _scale); - - /// \brief Get the flag for mouse drag motion - /// \return True if dragging, usually indicating a mouse move with - /// mouse button pressed. - public: bool Dragging() const; - - /// \brief Set the flag for mouse drag motion - /// \param[in] _dragging The dragging flag. - public: void SetDragging(const bool _dragging); - - /// \brief Get the event type. - /// \return The EventType. - public: EventType Type() const; - - /// \brief Set the event type. - /// \param[in] _type The EventType. - public: void SetType(const EventType _type) const; - - /// \brief Get the button which caused this event. - /// \return The button which caused this event. - public: MouseEvent::MouseButton Button() const; - - /// \brief Set the button which caused the event. - /// \param[in] _button The button which caused this event. - public: void SetButton(const MouseEvent::MouseButton _button) const; - - /// \brief Get the state of the buttons when the event was generated. - /// \return The state of the buttons, which can be a bitwise - /// combination of MouseEvent::MouseButton. - public: unsigned int Buttons() const; - - /// \brief Set the state of the buttons when the event was generated. - /// \param[in] _buttons The state of the buttons, which can be a bitwise - /// combination of MouseEvent::MouseButton. - public: void SetButtons(const unsigned int &_buttons); - - /// \brief Get the shift key press flag. - /// \return True if the shift key is pressed. - public: bool Shift() const; - - /// \brief Set the shift key press flag. - /// \param[in] _shift The shift key press flag. - public: void SetShift(const bool _shift) const; - - /// \brief Get the alt key press flag. - /// \return True if the alt key is pressed. - public: bool Alt() const; - - /// \brief Set the alt key press flag. - /// \param[in] _alt The alt key flag. - public: void SetAlt(const bool _alt); - - /// \brief Get the control key press flag. - /// \return True if the control key is pressed. - public: bool Control() const; - - /// \brief Set the control key press flag. - /// \param[in] _control The control key flag. - public: void SetControl(const bool _control) const; - - /// \brief Assignment operator - /// \param[in] _other Other mouse event - /// \return this - public: MouseEvent &operator=(const MouseEvent &_other); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \internal - /// \brief Private data pointer - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} -#endif +#include +#include diff --git a/events/include/ignition/common/events.hh b/events/include/ignition/common/events.hh new file mode 100644 index 000000000..cecf803e1 --- /dev/null +++ b/events/include/ignition/common/events.hh @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2022 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include diff --git a/events/include/ignition/common/events/Export.hh b/events/include/ignition/common/events/Export.hh new file mode 100644 index 000000000..b2711adf6 --- /dev/null +++ b/events/include/ignition/common/events/Export.hh @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2022 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include diff --git a/events/include/ignition/common/events/Types.hh b/events/include/ignition/common/events/Types.hh index 114e0d7ab..5ba3da7bb 100644 --- a/events/include/ignition/common/events/Types.hh +++ b/events/include/ignition/common/events/Types.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,24 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ + */ -#ifndef IGNITION_COMMON_EVENTS_TYPES_HH_ -#define IGNITION_COMMON_EVENTS_TYPES_HH_ - -#include - -// This header contains forward declarations for some event types -namespace ignition -{ - namespace common - { - class Connection; - - /// \def ConnectionPtr - /// \brief Shared pointer to a Connection object - using ConnectionPtr = std::shared_ptr; - } -} - -#endif +#include +#include diff --git a/events/src/Event.cc b/events/src/Event.cc index 62b5f058b..4ccacc5a0 100644 --- a/events/src/Event.cc +++ b/events/src/Event.cc @@ -15,8 +15,8 @@ * */ -#include "ignition/common/Console.hh" -#include "ignition/common/Event.hh" +#include "gz/common/Console.hh" +#include "gz/common/Event.hh" using namespace ignition; using namespace common; diff --git a/events/src/Event_TEST.cc b/events/src/Event_TEST.cc index 388bd6b0d..df51685e3 100644 --- a/events/src/Event_TEST.cc +++ b/events/src/Event_TEST.cc @@ -20,7 +20,7 @@ #include "test_config.h" #include -#include +#include using namespace ignition; diff --git a/events/src/KeyEvent.cc b/events/src/KeyEvent.cc index feeb9096e..285d6c973 100644 --- a/events/src/KeyEvent.cc +++ b/events/src/KeyEvent.cc @@ -14,12 +14,12 @@ * limitations under the License. * */ -#include "ignition/common/KeyEvent.hh" +#include "gz/common/KeyEvent.hh" using namespace ignition; using namespace common; -class ignition::common::KeyEventPrivate +class gz::common::KeyEventPrivate { /// \brief Event type. public: KeyEvent::EventType type = KeyEvent::NO_EVENT; diff --git a/events/src/KeyEvent_TEST.cc b/events/src/KeyEvent_TEST.cc index cd9d1fe60..1bb875f7c 100644 --- a/events/src/KeyEvent_TEST.cc +++ b/events/src/KeyEvent_TEST.cc @@ -16,7 +16,7 @@ */ #include -#include "ignition/common/KeyEvent.hh" +#include "gz/common/KeyEvent.hh" using namespace ignition; using namespace common; diff --git a/events/src/MouseEvent.cc b/events/src/MouseEvent.cc index bf196f09d..de74e2a61 100644 --- a/events/src/MouseEvent.cc +++ b/events/src/MouseEvent.cc @@ -15,14 +15,14 @@ * */ -#include -#include "ignition/common/MouseEvent.hh" +#include +#include "gz/common/MouseEvent.hh" using namespace ignition; using namespace common; /// \brief Mouse event private data -class ignition::common::MouseEventPrivate +class gz::common::MouseEventPrivate { /// \brief Constructor. public: MouseEventPrivate() diff --git a/events/src/MouseEvent_TEST.cc b/events/src/MouseEvent_TEST.cc index aed936ded..018a6929a 100644 --- a/events/src/MouseEvent_TEST.cc +++ b/events/src/MouseEvent_TEST.cc @@ -18,8 +18,8 @@ #include #include "test_config.h" -#include "ignition/common/MouseEvent.hh" -#include "ignition/common/config.hh" +#include "gz/common/MouseEvent.hh" +#include "gz/common/config.hh" using namespace ignition; diff --git a/examples/assert_example.cc b/examples/assert_example.cc index 2fa852de3..99c5a1896 100644 --- a/examples/assert_example.cc +++ b/examples/assert_example.cc @@ -1,4 +1,4 @@ -#include +#include int main(int argc, char **argv) { diff --git a/examples/console.cc b/examples/console.cc index 0fe561a48..ea50cf8c6 100644 --- a/examples/console.cc +++ b/examples/console.cc @@ -14,7 +14,7 @@ * limitations under the License. * */ -#include +#include int main(int argc, char **argv) { @@ -25,7 +25,7 @@ int main(int argc, char **argv) ignerr << "This is an error" << std::endl; // Change verbosity to level 4, all messages show - ignition::common::Console::SetVerbosity(4); + gz::common::Console::SetVerbosity(4); igndbg << "This is a debug message" << std::endl; ignmsg << "This is an informational message" << std::endl; ignwarn << "This is a warning" << std::endl; diff --git a/examples/events.cc b/examples/events.cc index 62e7bf22f..82276813c 100644 --- a/examples/events.cc +++ b/examples/events.cc @@ -17,7 +17,7 @@ #include #include -#include +#include using namespace ignition; diff --git a/examples/profiler.cc b/examples/profiler.cc index 7144a11ab..9688f99ae 100644 --- a/examples/profiler.cc +++ b/examples/profiler.cc @@ -18,10 +18,10 @@ #include #include -#include "ignition/common/Console.hh" -#include "ignition/common/Profiler.hh" -#include "ignition/common/SignalHandler.hh" -#include "ignition/common/Time.hh" +#include "gz/common/Console.hh" +#include "gz/common/Profiler.hh" +#include "gz/common/SignalHandler.hh" +#include "gz/common/Time.hh" std::atomic running; @@ -116,13 +116,13 @@ void sigHandler(int _signal) int main(int argc, char** argv) { - ignition::common::Console::SetVerbosity(4); + gz::common::Console::SetVerbosity(4); IGN_PROFILE_THREAD_NAME("main"); running = true; // Connect signal handler - ignition::common::SignalHandler handler; + gz::common::SignalHandler handler; handler.AddCallback(sigHandler); // Spin up a couple threads with interesting content. diff --git a/graphics/include/CMakeLists.txt b/graphics/include/CMakeLists.txt new file mode 100644 index 000000000..4b2bdd7bb --- /dev/null +++ b/graphics/include/CMakeLists.txt @@ -0,0 +1,2 @@ +add_subdirectory(gz) +install(DIRECTORY ignition DESTINATION ${IGN_INCLUDE_INSTALL_DIR_FULL}) diff --git a/graphics/include/gz/CMakeLists.txt b/graphics/include/gz/CMakeLists.txt new file mode 100644 index 000000000..e4717b2d6 --- /dev/null +++ b/graphics/include/gz/CMakeLists.txt @@ -0,0 +1 @@ +add_subdirectory(common) diff --git a/graphics/include/gz/common/Animation.hh b/graphics/include/gz/common/Animation.hh new file mode 100644 index 000000000..7969a08a3 --- /dev/null +++ b/graphics/include/gz/common/Animation.hh @@ -0,0 +1,292 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_ANIMATION_HH_ +#define GZ_COMMON_ANIMATION_HH_ + +#include +#include +#include + +#include +#include +#include + +#include + +namespace ignition +{ + namespace common + { + class KeyFrame; + class PoseKeyFrame; + class NumericKeyFrame; + class TrajectoryInfoPrivate; + + /// \class Animation Animation.hh ignition/common/Animation.hh + /// \brief Manages an animation, which is a collection of keyframes and + /// the ability to interpolate between the keyframes + class IGNITION_COMMON_GRAPHICS_VISIBLE Animation + { + /// \brief Constructor + /// \param[in] _name Name of the animation, should be unique + /// \param[in] _length Duration of the animation in seconds + /// \param[in] _loop Set to true if the animation should repeat + public: Animation(const std::string &_name, + const double _length, const bool _loop); + + /// \brief Destructor + public: virtual ~Animation(); + + /// \brief Return the duration of the animation + /// \return Duration of the animation in seconds + public: double Length() const; + + /// \brief Set the duration of the animation + /// \param[in] _len The length of the animation in seconds + public: void Length(const double _len); + + /// \brief Set the current time position of the animation + /// \param[in] _time The time position in seconds + public: void Time(const double _time); + + /// \brief Add time to the animation + /// \param[in] _time The amount of time to add in seconds + public: void AddTime(const double _time); + + /// \brief Return the current time position + /// \return The time position in seconds + public: double Time() const; + + /// \brief Return the interpolateX value + /// \return The interpolateX value + public: bool InterpolateX() const; + + /// \brief Set the interpolateX value + /// \param[in] _interpolateX The interpolateX value + public: void SetInterpolateX(const bool _interpolateX); + + /// \brief Return the number of key frames in the animation + /// \return The number of keyframes + public: unsigned int KeyFrameCount() const; + + /// \brief Get a key frame using an index value + /// \param[in] _index The index of the key frame + /// \return A pointer the keyframe, NULL if the _index is invalid + public: common::KeyFrame *KeyFrame(const unsigned int _index) const; + + /// \brief Get the two key frames that bound a time value + /// \param[in] _time The time in seconds + /// \param[out] _kf1 Lower bound keyframe that is returned + /// \param[out] _kf2 Upper bound keyframe that is returned + /// \param[out] _firstKeyIndex Index of the lower bound key frame + /// \return The time between the two keyframe + protected: double KeyFramesAtTime( + double _time, common::KeyFrame **_kf1, + common::KeyFrame **_kf2, + unsigned int &_firstKeyIndex) const; + +#ifdef _WIN32 +// Disable warning C4251 which is triggered by +// std::unique_ptr +#pragma warning(push) +#pragma warning(disable: 4251) +#endif + + /// \brief animation name + protected: std::string name; + + /// \brief animation duration + protected: double length; + + /// \brief current time position + protected: double timePos; + + /// \brief determines if the interpolation splines need building + protected: mutable bool build; + + /// \brief true if animation repeats + protected: bool loop; + + /// \brief array of keyframe type alias + protected: typedef std::vector KeyFrame_V; + + /// \brief array of key frames + protected: KeyFrame_V keyFrames; +#ifdef _WIN32 +#pragma warning(pop) +#endif + }; + + /// \brief A pose animation. + class IGNITION_COMMON_GRAPHICS_VISIBLE PoseAnimation : public Animation + { + /// \brief Constructor + /// \param[in] _name String name of the animation. This should be unique. + /// \param[in] _length Length of the animation in seconds + /// \param[in] _loop True == loop the animation + public: PoseAnimation(const std::string &_name, + const double _length, const bool _loop); + + /// \brief Destructor + public: virtual ~PoseAnimation(); + + /// \brief Create a pose keyframe at the given time + /// \param[in] _time Time at which to create the keyframe + /// \return Pointer to the new keyframe + public: PoseKeyFrame *CreateKeyFrame(const double _time); + + /// \brief Get a keyframe using the animation's current time. + /// \param[out] _kf PoseKeyFrame reference to hold the interpolated result + public: void InterpolatedKeyFrame(PoseKeyFrame &_kf) const; + + /// \brief Get a keyframe using a passed in time. + /// \param[in] _time Time in seconds + /// \param[out] _kf PoseKeyFrame reference to hold the interpolated result + protected: void InterpolatedKeyFrame(const double _time, + PoseKeyFrame &_kf) const; + + /// \brief Update the pose splines + protected: void BuildInterpolationSplines() const; + + /// \brief smooth interpolation for position + private: mutable math::Spline *positionSpline; + + /// \brief smooth interpolation for rotation + private: mutable math::RotationSpline *rotationSpline; + }; + + /// \brief A numeric animation. + class IGNITION_COMMON_GRAPHICS_VISIBLE NumericAnimation : public Animation + { + /// \brief Constructor + /// \param[in] _name String name of the animation. This should be unique. + /// \param[in] _length Length of the animation in seconds + /// \param[in] _loop True == loop the animation + public: NumericAnimation(const std::string &_name, + const double _length, const bool _loop); + + /// \brief Destructor + public: virtual ~NumericAnimation(); + + /// \brief Create a numeric keyframe at the given time + /// \param[in] _time Time at which to create the keyframe + /// \return Pointer to the new keyframe + public: NumericKeyFrame *CreateKeyFrame(const double _time); + + /// \brief Get a keyframe using the animation's current time. + /// \param[out] _kf NumericKeyFrame reference to hold the + /// interpolated result + public: void InterpolatedKeyFrame(NumericKeyFrame &_kf) const; + }; + + /// \brief Information about a trajectory for an animation (e.g., Actor) + /// This contains the keyframe information. + class IGNITION_COMMON_GRAPHICS_VISIBLE TrajectoryInfo + { + /// \brief Constructor + public: TrajectoryInfo(); + + /// \brief Copy constructor + /// \param[in] _trajInfo TrajectoryInfo to copy. + public: TrajectoryInfo(const TrajectoryInfo &_trajInfo); + + /// \brief Move constructor + /// \param[in] _trajInfo TrajectoryInfo to move. + public: TrajectoryInfo(TrajectoryInfo &&_trajInfo) noexcept; + + /// \brief Destructor + public: ~TrajectoryInfo(); + + /// \brief Assignment operator. + /// \param[in] _trajInfo The TrajectoryInfo to set values from. + /// \return *this + public: TrajectoryInfo &operator=(const TrajectoryInfo &_trajInfo); + + /// \brief Copy TrajectoryInfo from a TrajectoryInfo instance. + /// \param[in] _trajInfo The TrajectoryInfo to set values from. + public: void CopyFrom(const TrajectoryInfo &_trajInfo); + + /// \brief Return the id of the trajectory + /// \return Id of the trajectory + public: unsigned int Id() const; + + /// \brief Set the id of the trajectory + /// \param[in] _id Id for the trajectory + public: void SetId(unsigned int _id); + + /// \brief Return the animation index + /// \return Index of the associated animation + public: unsigned int AnimIndex() const; + + /// \brief Set the animation index + /// \param[in] _index Animation index + /// (auto-generated according to the type) + public: void SetAnimIndex(unsigned int _index); + + /// \brief Return the duration of the trajectory. + /// \return Duration of the animation. + public: std::chrono::steady_clock::duration Duration() const; + + /// \brief Get the distance covered by the trajectory by a given time. + /// \param[in] _time Time from trajectory start to check the distance. + /// \return Distance in meters covered by the trajectory. + public: double DistanceSoFar( + const std::chrono::steady_clock::duration &_time) const; + + /// \brief Return the start time of the trajectory. + /// \return Start time of the trajectory. + public: std::chrono::steady_clock::time_point StartTime() const; + + /// \brief Set the start time of the trajectory. + /// \param[in] _startTime Trajectory start time. + public: void SetStartTime( + const std::chrono::steady_clock::time_point &_startTime); + + /// \brief Return the end time of the trajectory + /// \return End time of the trajectory in seconds + public: std::chrono::steady_clock::time_point EndTime() const; + + /// \brief Set the end time of the trajectory. + /// \param[in] _endTime Trajectory end time. + public: void SetEndTime( + const std::chrono::steady_clock::time_point &_endTime); + + /// \brief Return whether the trajectory is translated + /// \return True if the trajectory is translated + public: bool Translated() const; + + /// \brief Set whether the trajectory is translated + /// \param[in] _translated True if the trajectory is translated + public: void SetTranslated(bool _translated); + + /// \brief Return the waypoints in the trajectory + /// \return Waypoints represented in pose animation format + public: common::PoseAnimation *Waypoints() const; + + /// \brief Load all waypoints in the trajectory + /// \param[in] _waypoints Map of waypoints, where the key is the absolute + /// time of the waypoint and the value is the pose. + public: void SetWaypoints( + std::map + _waypoints); + + /// \brief Private data pointer. + private: TrajectoryInfoPrivate *dataPtr{nullptr}; + }; + } +} +#endif diff --git a/graphics/include/gz/common/BVHLoader.hh b/graphics/include/gz/common/BVHLoader.hh new file mode 100644 index 000000000..db2feb3f2 --- /dev/null +++ b/graphics/include/gz/common/BVHLoader.hh @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_BVHLOADER_HH_ +#define GZ_COMMON_BVHLOADER_HH_ + +#include +#include + +#include +#include + +namespace ignition +{ + namespace common + { + class Skeleton; + + /// \class BVHLoader BVHLoader.hh ignition/common/BVHLoader.hh + /// \brief Handles loading BVH animation files + class IGNITION_COMMON_GRAPHICS_VISIBLE BVHLoader + { + /// \brief Constructor + public: BVHLoader(); + + /// \brief Desutrctor + public: ~BVHLoader(); + + /// \brief Load a BVH file + /// \param[in] _filename BVH file to load + /// \param[in] _scale Scaling factor to apply to the skeleton + /// \return A pointer to a new Skeleton + public: std::unique_ptr Load( + const std::string &_filename, const double _scale); + }; + } +} + +#endif diff --git a/graphics/include/ignition/common/CMakeLists.txt b/graphics/include/gz/common/CMakeLists.txt similarity index 100% rename from graphics/include/ignition/common/CMakeLists.txt rename to graphics/include/gz/common/CMakeLists.txt diff --git a/graphics/include/gz/common/ColladaExporter.hh b/graphics/include/gz/common/ColladaExporter.hh new file mode 100644 index 000000000..e5399758f --- /dev/null +++ b/graphics/include/gz/common/ColladaExporter.hh @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_COLLADAEXPORTER_HH_ +#define GZ_COMMON_COLLADAEXPORTER_HH_ + +#include +#include +#include + +#include +#include +#include + +#include + +namespace ignition +{ + namespace common + { + class ColladaExporterPrivate; + + /// \brief Class used to export Collada mesh files + class IGNITION_COMMON_GRAPHICS_VISIBLE ColladaExporter : public MeshExporter + { + /// \brief Constructor + public: ColladaExporter(); + + /// \brief Destructor + public: virtual ~ColladaExporter(); + + /// \brief Export a mesh to a file + /// \param[in] _mesh Pointer to the mesh to be exported + /// \param[in] _filename Exported file's path and name + /// \param[in] _exportTextures True to export texture images to + /// '../materials/textures' folder + public: virtual void Export(const Mesh *_mesh, + const std::string &_filename, bool _exportTextures = false); + + public: void Export(const Mesh *_mesh, + const std::string &_filename, bool _exportTextures, + const std::vector &_submeshToMatrix); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \internal + /// \brief Pointer to private data. + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} +#endif diff --git a/graphics/include/gz/common/ColladaLoader.hh b/graphics/include/gz/common/ColladaLoader.hh new file mode 100644 index 000000000..372a8c880 --- /dev/null +++ b/graphics/include/gz/common/ColladaLoader.hh @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_COLLADALOADER_HH_ +#define GZ_COMMON_COLLADALOADER_HH_ + +#include +#include +#include + +namespace ignition +{ + namespace common + { + // Forward declare private data class + class ColladaLoaderPrivate; + + /// \class ColladaLoader ColladaLoader.hh ignition/common/ColladaLoader.hh + /// \brief Class used to load Collada mesh files + class IGNITION_COMMON_GRAPHICS_VISIBLE ColladaLoader : public MeshLoader + { + /// \brief Constructor + public: ColladaLoader(); + + /// \brief Destructor + public: virtual ~ColladaLoader(); + + /// \brief Load a mesh + /// \param[in] _filename Collada file to load + /// \return Pointer to a new Mesh + public: virtual Mesh *Load(const std::string &_filename); + + /// \internal + /// \brief Pointer to private data. + private: ColladaLoaderPrivate *dataPtr; + }; + } +} +#endif diff --git a/graphics/include/gz/common/Dem.hh b/graphics/include/gz/common/Dem.hh new file mode 100644 index 000000000..088ef60ab --- /dev/null +++ b/graphics/include/gz/common/Dem.hh @@ -0,0 +1,143 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_DEM_HH_ +#define GZ_COMMON_DEM_HH_ + +#include +#include +#include + +#include +#include + +#ifdef HAVE_GDAL +# include +# include + +# include + +namespace ignition +{ + namespace common + { + class DemPrivate; + + /// \class DEM DEM.hh common/common.hh + /// \brief Encapsulates a DEM (Digital Elevation Model) file. + class IGNITION_COMMON_GRAPHICS_VISIBLE Dem : public HeightmapData + { + /// \brief Constructor. + public: Dem(); + + /// \brief Destructor. + public: virtual ~Dem(); + + /// \brief Load a DEM file. + /// \param[in] _filename the path to the terrain file. + /// \return 0 when the operation succeeds to open a file. + public: int Load(const std::string &_filename = ""); + + /// \brief Get the elevation of a terrain's point in meters. + /// \param[in] _x X coordinate of the terrain. + /// \param[in] _y Y coordinate of the terrain. + /// \return Terrain's elevation at (x,y) in meters. + public: double Elevation(double _x, double _y); + + /// \brief Get the terrain's minimum elevation in meters. + /// \return The minimum elevation (meters). + public: float MinElevation() const; + + /// \brief Get the terrain's maximum elevation in meters. + /// \return The maximum elevation (meters). + public: float MaxElevation() const; + + /// \brief Get the georeferenced coordinates (lat, long) of the terrain's + /// origin in WGS84. + /// \param[out] _latitude Georeferenced latitude. + /// \param[out] _longitude Georeferenced longitude. + public: void GeoReferenceOrigin(gz::math::Angle &_latitude, + gz::math::Angle &_longitude) const; + + /// \brief Get the terrain's height. Due to the Ogre constrains, this + /// value will be a power of two plus one. The value returned might be + /// different that the original DEM height because Data() adds the + /// padding if necessary. + /// \return The terrain's height (points) satisfying the ogre constrains + /// (squared terrain with a height value that must be a power of two plus + /// one). + public: unsigned int Height() const; + + /// \brief Get the terrain's width. Due to the Ogre constrains, this + /// value will be a power of two plus one. The value returned might be + /// different that the original DEM width because GetData() adds the + /// padding if necessary. + /// \return The terrain's width (points) satisfying the ogre constrains + /// (squared terrain with a width value that must be a power of two plus + /// one). + public: unsigned int Width() const; + + /// \brief Get the real world width in meters. + /// \return Terrain's real world width in meters. + public: double WorldWidth() const; + + /// \brief Get the real world height in meters. + /// \return Terrain's real world height in meters. + public: double WorldHeight() const; + + /// \brief Create a lookup table of the terrain's height. + /// \param[in] _subsampling Multiplier used to increase the resolution. + /// Ex: A subsampling of 2 in a terrain of 129x129 means that the height + /// vector will be 257 * 257. + /// \param[in] _vertSize Number of points per row. + /// \param[in] _size Real dimmensions of the terrain in meters. + /// \param[in] _scale Vector3 used to scale the height. + /// \param[in] _flipY If true, it inverts the order in which the vector + /// is filled. + /// \param[out] _heights Vector containing the terrain heights. + public: void FillHeightMap(const int _subSampling, + const unsigned int _vertSize, + const gz::math::Vector3d &_size, + const gz::math::Vector3d &_scale, + const bool _flipY, + std::vector &_heights); + + /// \brief Get the georeferenced coordinates (lat, long) of a terrain's + /// pixel in WGS84. + /// \param[in] _x X coordinate of the terrain. + /// \param[in] _y Y coordinate of the terrain. + /// \param[out] _latitude Georeferenced latitude. + /// \param[out] _longitude Georeferenced longitude. + private: void GeoReference(double _x, double _y, + gz::math::Angle &_latitude, + gz::math::Angle &_longitude) const; + + /// \brief Get the terrain file as a data array. Due to the Ogre + /// constrains, the data might be stored in a bigger vector representing + /// a squared terrain with padding. + /// \return 0 when the operation succeeds to open a file. + private: int LoadData(); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// internal + /// \brief Pointer to the private data. + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} +#endif +#endif diff --git a/graphics/include/gz/common/GTSMeshUtils.hh b/graphics/include/gz/common/GTSMeshUtils.hh new file mode 100644 index 000000000..c92673217 --- /dev/null +++ b/graphics/include/gz/common/GTSMeshUtils.hh @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GZ_COMMON_GTSMESHUTILS_HH_ +#define GZ_COMMON_GTSMESHUTILS_HH_ + +#include + +#include +#include + + +struct _GtsSurface; +typedef _GtsSurface GtsSurface; + +namespace ignition +{ + namespace common + { + class SubMesh; + + /// \class GTSMeshUtils GTSMeshUtils.hh ignition/common/GTSMeshUtils.hh + /// \brief Creates GTS utilities for meshes + class IGNITION_COMMON_GRAPHICS_VISIBLE GTSMeshUtils + { + /// \brief Perform delaunay triangulation on input vertices. + /// \param[in] _vertices A list of all vertices + /// \param[in] _edges A list of edges. Each edge is made of 2 vertex + /// indices from _vertices + /// \param[out] _submesh A submesh that will be populated with the + /// resulting triangles. + /// \return True on success. + public: static bool DelaunayTriangulation( + const std::vector &_vertices, + const std::vector &_edges, + SubMesh *_submesh); + + /// \brief Perform delaunay triangulation on input vertices. + /// \param[in] _vertices A list of all vertices + /// \param[in] _edges A list of edges. Each edge is made of 2 vertex + /// indices from _vertices + /// \return Triangulated GTS surface. + private: static GtsSurface *DelaunayTriangulation( + const std::vector &_vertices, + const std::vector &_edges); + }; + } +} +#endif diff --git a/graphics/include/gz/common/HeightmapData.hh b/graphics/include/gz/common/HeightmapData.hh new file mode 100644 index 000000000..c8fd68084 --- /dev/null +++ b/graphics/include/gz/common/HeightmapData.hh @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_HEIGHTMAPDATA_HH_ +#define GZ_COMMON_HEIGHTMAPDATA_HH_ + +#include +#include +#include + +namespace ignition +{ + namespace common + { + /// \brief Encapsulates a generic heightmap data file. + class IGNITION_COMMON_GRAPHICS_VISIBLE HeightmapData + { + /// \brief Destructor. + public: virtual ~HeightmapData() = default; + + /// \brief Create a lookup table of the terrain's height. + /// \param[in] _subsampling Multiplier used to increase the resolution. + /// Ex: A subsampling of 2 in a terrain of 129x129 means that the height + /// vector will be 257 * 257. + /// \param[in] _vertSize Number of points per row. + /// \param[in] _size Real dimmensions of the terrain. + /// \param[in] _scale Vector3 used to scale the height. + /// \param[in] _flipY If true, it inverts the order in which the vector + /// is filled. + /// \param[out] _heights Vector containing the terrain heights. + public: virtual void FillHeightMap(int _subSampling, + unsigned int _vertSize, const gz::math::Vector3d &_size, + const gz::math::Vector3d &_scale, bool _flipY, + std::vector &_heights) = 0; + + /// \brief Get the terrain's height. + /// \return The terrain's height. + public: virtual unsigned int Height() const = 0; + + /// \brief Get the terrain's width. + /// \return The terrain's width. + public: virtual unsigned int Width() const = 0; + + /// \brief Get the maximum terrain's elevation. + /// \return The maximum terrain's elevation. + public: virtual float MaxElevation() const = 0; + }; + } +} +#endif diff --git a/graphics/include/gz/common/Image.hh b/graphics/include/gz/common/Image.hh new file mode 100644 index 000000000..3ea29d0d0 --- /dev/null +++ b/graphics/include/gz/common/Image.hh @@ -0,0 +1,270 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_IMAGE_HH_ +#define GZ_COMMON_IMAGE_HH_ + +#include +#include +#include +#include +#include +#include +#include + +namespace ignition +{ + namespace common + { + /// \brief Forward declaration of private data class + class ImagePrivate; + + /// \brief String names for the pixel formats. + /// \sa Image::PixelFormat. + static std::string PixelFormatNames[] = + { + "UNKNOWN_PIXEL_FORMAT", + "L_INT8", + "L_INT16", + "RGB_INT8", + "RGBA_INT8", + "BGRA_INT8", + "RGB_INT16", + "RGB_INT32", + "BGR_INT8", + "BGR_INT16", + "BGR_INT32", + "R_FLOAT16", + "RGB_FLOAT16", + "R_FLOAT32", + "RGB_FLOAT32", + "BAYER_RGGB8", + "BAYER_RGGR8", + "BAYER_GBRG8", + "BAYER_GRBG8", + "BAYER_BGGR8" + }; + + /// \class Image Image.hh ignition/common/common.hh + /// \brief Encapsulates an image + class IGNITION_COMMON_GRAPHICS_VISIBLE Image + { + /// \brief Pixel formats enumeration + public: enum PixelFormatType + { + UNKNOWN_PIXEL_FORMAT = 0, + L_INT8, + L_INT16, + RGB_INT8, + RGBA_INT8, + BGRA_INT8, + RGB_INT16, + RGB_INT32, + BGR_INT8, + BGR_INT16, + BGR_INT32, + R_FLOAT16, + RGB_FLOAT16, + R_FLOAT32, + RGB_FLOAT32, + BAYER_RGGB8, + BAYER_RGGR8, + BAYER_GBRG8, + BAYER_GRBG8, + PIXEL_FORMAT_COUNT, + BAYER_BGGR8 + }; + + + /// \brief Convert a string to a Image::PixelFormat. + /// \param[in] _format Pixel format string. \sa Image::PixelFormatNames + /// \return Image::PixelFormat + public: static Image::PixelFormatType ConvertPixelFormat( + const std::string &_format); + + /// \brief Constructor + /// \param[in] _filename the path to the image + public: explicit Image(const std::string &_filename = ""); + + /// \brief Destructor + public: virtual ~Image(); + + /// \brief Load an image. Return 0 on success + /// \param[in] _filename the path to the image file + /// \return 0 when the operation succeeds to open a file or -1 when fails. + public: int Load(const std::string &_filename); + + /// \brief Save the image in PNG format + /// \param[in] _filename The name of the saved image + public: void SavePNG(const std::string &_filename); + + /// \brief Save the image in PNG format + /// \param[in] _filename The name of the saved image + public: void SavePNGToBuffer(std::vector &_buffer); + + /// \brief Set the image from raw data + /// \param[in] _data Pointer to the raw image data + /// \param[in] _width Width in pixels + /// \param[in] _height Height in pixels + /// \param[in] _format Pixel format of the provided data + public: void SetFromData(const unsigned char *_data, + unsigned int _width, + unsigned int _height, + Image::PixelFormatType _format); + + /// \brief Get the image as a data array + /// \param[out] _data Pointer to a NULL array of char. + /// \param[out] _count The resulting data array size + public: void Data(unsigned char **_data, + unsigned int &_count) const; + + /// \brief Get only the RGB data from the image. This will drop the + /// alpha channel if one is present. + /// \param[out] _data Pointer to a NULL array of char. + /// \param[out] _count The resulting data array size + public: void RGBData(unsigned char **_data, + unsigned int &_count) const; + + /// \brief Get the width + /// \return The image width + public: unsigned int Width() const; + + /// \brief Get the height + /// \return The image height + public: unsigned int Height() const; + + /// \brief Get the size of one pixel in bits + /// \return The BPP of the image + public: unsigned int BPP() const; + + // \brief Get the size of a row of pixel + /// \return The pitch of the image + public: int Pitch() const; + + /// \brief Get the full filename of the image + /// \return The filename used to load the image + public: std::string Filename() const; + + /// \brief Get the pixel format + /// \return PixelFormat + public: PixelFormatType PixelFormat() const; + + /// \brief Get a pixel color value + /// \param[in] _x Column location in the image + /// \param[in] _y Row location in the image + /// \return The color of the given pixel + public: math::Color Pixel(const unsigned int _x, + const unsigned int _y) const; + + /// \brief Get the average color + /// \return The average color + public: math::Color AvgColor(); + + /// \brief Get the max color + /// \return The max color + public: math::Color MaxColor() const; + + /// \brief Rescale the image + /// \param[in] _width New image width + /// \param[in] _height New image height + public: void Rescale(const int _width, const int _height); + + /// \brief Returns whether this is a valid image + /// \return true if image has a bitmap + public: bool Valid() const; + + /// \brief Convert a single channel image data buffer into an RGB image. + /// During the conversion, the input image data are normalized to 8 bit + /// values i.e. [0, 255]. Optionally, specify min and max values to use + /// when normalizing the input image data. For example, if min and max + /// are set to 1 and 10, a data value 2 will be normalized to: + /// (2 - 1) / (10 - 1) * 255. + /// \param[in] _data input image data buffer + /// \param[in] _width image width + /// \param[in] _height image height + /// \param[out] _output Output RGB image + /// \param[in] _min Minimum value to be used when normalizing the input + /// image data to RGB. + /// \param[in] _max Maximum value to be used when normalizing the input + /// image data to RGB. + /// \param[in] _flip True to flip the values after normalization, i.e. + /// lower values are converted to brigher pixels. + public: template + static void ConvertToRGBImage(const void *_data, + unsigned int _width, unsigned int _height, Image &_output, + T _min = std::numeric_limits::max(), + T _max = std::numeric_limits::lowest(), bool _flip = false) + { + unsigned int samples = _width * _height; + unsigned int bufferSize = samples * sizeof(T); + + auto buffer = std::vector(samples); + memcpy(buffer.data(), _data, bufferSize); + + auto outputRgbBuffer = std::vector(samples * 3); + + // use min and max values found in the data if not specified + T min = std::numeric_limits::max(); + T max = std::numeric_limits::lowest(); + if (_min > max) + { + for (unsigned int i = 0; i < samples; ++i) + { + auto v = buffer[i]; + // ignore inf values when computing min/max + // cast to float when calling isinf to avoid compile error on + // windows + if (v > max && !std::isinf(static_cast(v))) + max = v; + if (v < min && !std::isinf(static_cast(v))) + min = v; + } + } + min = math::equal(_min, std::numeric_limits::max()) ? min : _min; + max = math::equal(_max, std::numeric_limits::lowest()) ? max : _max; + + // convert to rgb image + // color is grayscale, i.e. r == b == g + double range = static_cast(max - min); + if (gz::math::equal(range, 0.0)) + range = 1.0; + unsigned int idx = 0; + for (unsigned int j = 0; j < _height; ++j) + { + for (unsigned int i = 0; i < _width; ++i) + { + auto v = buffer[idx++]; + double t = static_cast(v - min) / range; + if (_flip) + t = 1.0 - t; + uint8_t r = static_cast(255*t); + unsigned int outIdx = j * _width * 3 + i * 3; + outputRgbBuffer[outIdx] = r; + outputRgbBuffer[outIdx + 1] = r; + outputRgbBuffer[outIdx + 2] = r; + } + } + _output.SetFromData(outputRgbBuffer.data(), _width, _height, RGB_INT8); + } + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief Private data pointer + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} +#endif diff --git a/graphics/include/gz/common/ImageHeightmap.hh b/graphics/include/gz/common/ImageHeightmap.hh new file mode 100644 index 000000000..edc3d07b8 --- /dev/null +++ b/graphics/include/gz/common/ImageHeightmap.hh @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_IMAGEHEIGHTMAPDATA_HH_ +#define GZ_COMMON_IMAGEHEIGHTMAPDATA_HH_ + +#include +#include +#include + +#include +#include +#include + +namespace ignition +{ + namespace common + { + /// \brief Encapsulates an image that will be interpreted as a heightmap. + class IGNITION_COMMON_GRAPHICS_VISIBLE ImageHeightmap + : public gz::common::HeightmapData + { + /// \brief Constructor + /// \param[in] _filename the path to the image + public: ImageHeightmap(); + + /// \brief Load an image file as a heightmap. + /// \param[in] _filename the path to the image file. + /// \return True when the operation succeeds to open a file. + public: int Load(const std::string &_filename = ""); + + // Documentation inherited. + public: void FillHeightMap(int _subSampling, unsigned int _vertSize, + const gz::math::Vector3d &_size, + const gz::math::Vector3d &_scale, bool _flipY, + std::vector &_heights); + + /// \brief Get the full filename of the image + /// \return The filename used to load the image + public: std::string Filename() const; + + // Documentation inherited. + public: unsigned int Height() const; + + // Documentation inherited. + public: unsigned int Width() const; + + // Documentation inherited. + public: float MaxElevation() const; + + /// \brief Image containing the heightmap data. + private: gz::common::Image img; + }; + } +} +#endif diff --git a/graphics/include/gz/common/KeyFrame.hh b/graphics/include/gz/common/KeyFrame.hh new file mode 100644 index 000000000..13e25ffc6 --- /dev/null +++ b/graphics/include/gz/common/KeyFrame.hh @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_KEYFRAME_HH_ +#define GZ_COMMON_KEYFRAME_HH_ + +#include +#include +#include + +namespace ignition +{ + namespace common + { + /// \class KeyFrame KeyFrame.hh ignition/common/KeyFrame.hh + /// \brief A key frame in an animation + class IGNITION_COMMON_GRAPHICS_VISIBLE KeyFrame + { + /// \brief Constructor + /// \param[in] _time Time of the keyframe in seconds + public: explicit KeyFrame(const double _time); + + /// \brief Destructor + public: virtual ~KeyFrame(); + + /// \brief Get the time of the keyframe + /// \return the time + public: double Time() const; + + /// \brief time of key frame + protected: double time; + }; + + /// \brief A keyframe for a PoseAnimation + class IGNITION_COMMON_GRAPHICS_VISIBLE PoseKeyFrame : public KeyFrame + { + /// \brief Constructor + /// \param[in] _time of the keyframe + public: explicit PoseKeyFrame(const double _time); + + /// \brief Destructor + public: virtual ~PoseKeyFrame(); + + /// \brief Set the translation for the keyframe + /// \param[in] _trans Translation amount + public: void Translation(const math::Vector3d &_trans); + + /// \brief Get the translation of the keyframe + /// \return The translation amount + public: const math::Vector3d &Translation() const; + + /// \brief Set the rotation for the keyframe + /// \param[in] _rot Rotation amount + public: void Rotation(const math::Quaterniond &_rot); + + /// \brief Get the rotation of the keyframe + /// \return The rotation amount + public: const math::Quaterniond &Rotation() const; + +#ifdef _WIN32 +// Disable warning C4251 which is triggered by +// std::unique_ptr +#pragma warning(push) +#pragma warning(disable: 4251) +#endif + /// \brief the translation vector + protected: math::Vector3d translate; + + /// \brief the rotation quaternion + protected: math::Quaterniond rotate; +#ifdef _WIN32 +#pragma warning(pop) +#endif + }; + + /// \brief A keyframe for a NumericAnimation + class IGNITION_COMMON_GRAPHICS_VISIBLE NumericKeyFrame : public KeyFrame + { + /// \brief Constructor + /// \param[in] _time Time of the keyframe + public: explicit NumericKeyFrame(const double _time); + + /// \brief Destructor + public: virtual ~NumericKeyFrame(); + + /// \brief Set the value of the keyframe + /// \param[in] _value The new value + public: void Value(const double &_value); + + /// \brief Get the value of the keyframe + /// \return the value of the keyframe + public: const double &Value() const; + + /// \brief numeric value + protected: double value; + }; + } +} +#endif diff --git a/graphics/include/gz/common/Material.hh b/graphics/include/gz/common/Material.hh new file mode 100644 index 000000000..c4861df8c --- /dev/null +++ b/graphics/include/gz/common/Material.hh @@ -0,0 +1,293 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_MATERIAL_HH_ +#define GZ_COMMON_MATERIAL_HH_ + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace ignition +{ + namespace common + { + // Forward declare private data class + class MaterialPrivate; + + /// \brief Encapsulates description of a material + class IGNITION_COMMON_GRAPHICS_VISIBLE Material + { + /// \def Shade modes + /// \brief Enumeration of shade mode types + public: enum ShadeMode + { + /// \internal + /// \brief Indicator used to create an iterator over the + /// enum. Do not use this. + SHADE_MODE_BEGIN = 0, + + /// \brief Flat shading + FLAT = 0, + + /// \brief Gouraud shading + GOURAUD = 1, + + /// \brief Phong shading + PHONG = 2, + + /// \brief Blinn shading + BLINN = 3, + + /// \internal + /// \brief Indicator used to create an iterator over the + /// enum. Do not use this. + SHADE_MODE_END + }; + + /// \def Blend modes + /// \brief Enumeration of blend mode types + public: enum BlendMode + { + /// \internal + /// \brief Indicator used to create an iterator over the + /// enum. Do not use this. + BLEND_MODE_BEGIN = 0, + + /// \brief Add mode + ADD = 0, + + /// \brief Modulate mode + MODULATE = 1, + + /// \brief Replace mode + REPLACE = 2, + + /// \internal + /// \brief Indicator used to create an iterator over the + /// enum. Do not use this. + BLEND_MODE_END + }; + + /// \brief Constructor + public: Material(); + + /// \brief Destructor + public: ~Material(); + + /// \brief Create a material with a default color + /// \param[in] _clr Color of the material + public: explicit Material(const math::Color &_clr); + + /// \brief Get the name of the material + /// \return The name of the material + public: std::string Name() const; + + /// \brief Set a texture image + /// \param[in] _tex The name of the texture, which must be in the + /// resource path + public: void SetTextureImage(const std::string &_tex); + + /// \brief Set a texture image + /// \param[in] _tex The name of the texture + /// \param[in] _resourcePath Path which contains _tex + public: void SetTextureImage(const std::string &_tex, + const std::string &_resourcePath); + + /// \brief Get a texture image + /// \return The name of the texture image (if one exists) or an empty + /// string + public: std::string TextureImage() const; + + /// \brief Set the ambient color + /// \param[in] _clr The ambient color + public: void SetAmbient(const math::Color &_clr); + + /// \brief Get the ambient color + /// \return The ambient color + public: math::Color Ambient() const; + + /// \brief Set the diffuse color + /// \param[in] _clr The diffuse color + public: void SetDiffuse(const math::Color &_clr); + + /// \brief Get the diffuse color + /// \return The diffuse color + public: math::Color Diffuse() const; + + /// \brief Set the specular color + /// \param[in] _clr The specular color + public: void SetSpecular(const math::Color &_clr); + + /// \brief Get the specular color + /// \return The specular color + public: math::Color Specular() const; + + /// \brief Set the emissive color + /// \param[in] _clr The emissive color + public: void SetEmissive(const math::Color &_clr); + + /// \brief Get the emissive color + /// \return The emissive color + public: math::Color Emissive() const; + + /// \brief Set the transparency percentage (0..1) + /// \param[in] _t The amount of transparency (0..1) where a value of 1 + /// is fully transparent and 0 is not transparent. + public: void SetTransparency(double _t); + + /// \brief Get the transparency percentage (0..1) + /// A value of 1 is fully transparent and 0 is not transparent. + /// \return The transparency percentage + public: double Transparency() const; + + /// \brief Set the material to use the alpha channel from the textures + /// \param[in] _enabled Enable alpha channel based rendering + /// \param[in] _alpha Set the alpha threshold value + /// \param[in] _twoSided Enable two sided rendering + public: void SetAlphaFromTexture(bool _enabled, + double _alpha = 0.5, bool _twoSided = true); + + /// \brief Get the enable alpha from textures + /// \return The enable alpha value + public: bool TextureAlphaEnabled() const; + + /// \brief Get the alpha threshold + /// \return The alpha threshold value + public: double AlphaThreshold() const; + + /// \brief Get the enable two sided rendering + /// \return The enable two sided rendering value + public: bool TwoSidedEnabled() const; + + /// \brief Set the render order. The higher value will be rendered on top + /// of the other coplanar polygons. + /// \param[in] _renderOrder The render order value + public: void SetRenderOrder(float _renderOrder); + + /// \brief Get the render order + /// \return The render order value + public: float RenderOrder() const; + + /// \brief Set the shininess + /// \param[in] _t The shininess value + public: void SetShininess(double _t); + + /// \brief Get the shininess + /// \return The shininess value + public: double Shininess() const; + + /// \brief Set the blend factors. Will be interpreted as: + /// (texture * _srcFactor) + (scene_pixel * _dstFactor) + /// \param[in] _srcFactor The source factor + /// \param[in] _dstFactor The destination factor + public: void SetBlendFactors(double _srcFactor, double _dstFactor); + + /// \brief Get the blend factors + /// \param[in] _srcFactor Source factor is returned in this variable + /// \param[in] _dstFactor Destination factor is returned in this variable + public: void BlendFactors(double &_srcFactor, double &_dstFactor) const; + + /// \brief Set the blending mode + /// \param[in] _b the blend mode + public: void SetBlend(BlendMode _b); + + /// \brief Get the blending mode + /// \return the blend mode + public: BlendMode Blend() const; + + /// \brief Get the blend mode string + public: std::string BlendStr() const; + + /// \brief Get the shade mode string + public: std::string ShadeStr() const; + + /// \brief Set the shading mode + /// param[in] the shading mode + public: void SetShade(ShadeMode _b); + + /// \brief Get the shading mode + /// \return the shading mode + public: ShadeMode Shade() const; + + /// \brief Set the point size + /// \param[in] _size the size + public: void SetPointSize(double _size); + + /// \brief Get the point size + /// \return the point size + public: double PointSize() const; + + /// \brief Set depth write + /// \param[in] _value the depth write enabled state + public: void SetDepthWrite(bool _value); + + /// \brief Get depth write + /// \return the depth write enabled state + public: bool DepthWrite() const; + + /// \brief Set lighting enabled + /// \param[in] _value the lighting enabled state + public: void SetLighting(bool _value); + + /// \brief Get lighting enabled + /// \return the lighting enabled state + public: bool Lighting() const; + + /// \brief Set the Physically Based Rendering (PBR) material + /// \return The PBR material to set to. + public: void SetPbrMaterial(const Pbr &_pbr); + + /// \brief Get the Physically Based Rendering (PBR) material + /// \return Pointer to the PBR material. Null if it does not exist. + public: Pbr *PbrMaterial() const; + + /// \brief Stream insertion operator + /// param[in] _out the output stream to extract from + /// param[out] _m the material information + public: friend std::ostream &operator<<(std::ostream &_out, + const gz::common::Material &_m) + { + _out << "Material:\n"; + _out << " Name: " << _m.Name() << "\n"; + _out << " Texture: " << _m.TextureImage() << "\n"; + _out << " Ambient: " << _m.Ambient() << "\n"; + _out << " Diffuse: " << _m.Diffuse() << "\n"; + _out << " Specular: " << _m.Specular() << "\n"; + _out << " Emissive: " << _m.Emissive() << "\n"; + _out << " Transparency: " << _m.Transparency() << "\n"; + _out << " Shininess: " << _m.Shininess() << "\n"; + _out << " Render order: " << _m.RenderOrder() << "\n"; + _out << " BlendMode: " << _m.BlendStr() << "\n"; + _out << " ShadeMode: " << _m.ShadeStr() << "\n"; + _out << " DepthWrite: " << _m.DepthWrite() << "\n"; + return _out; + } + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief destination blend factor + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} +#endif diff --git a/graphics/include/gz/common/Mesh.hh b/graphics/include/gz/common/Mesh.hh new file mode 100644 index 000000000..6e50b8921 --- /dev/null +++ b/graphics/include/gz/common/Mesh.hh @@ -0,0 +1,214 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_MESH_HH_ +#define GZ_COMMON_MESH_HH_ + +#include +#include +#include + +#include +#include + +#include +#include +#include + +namespace ignition +{ + namespace common + { + class Material; + class Skeleton; + class MeshPrivate; + + /// \class Mesh Mesh.hh ignition/common/Mesh.hh + /// \brief A 3D mesh + class IGNITION_COMMON_GRAPHICS_VISIBLE Mesh + { + /// \brief Constructor + public: Mesh(); + + /// \brief Destructor + public: virtual ~Mesh(); + + /// \brief Set the path which contains the mesh resource + /// \param[in] _path The file path + public: void SetPath(const std::string &_path); + + /// \brief Get the path which contains the mesh resource + /// \return The path to the mesh resource + public: std::string Path() const; + + /// \brief Set the name of this mesh + /// \param[in] _name The name to set + public: void SetName(const std::string &_name); + + /// \brief Get the name of this mesh + /// \return Name of the mesh. + public: std::string Name() const; + + /// \brief Get the maximun X, Y, Z values + /// \return The upper bounds of the bounding box + public: gz::math::Vector3d Max() const; + + /// \brief Get the minimum X, Y, Z values + /// \return The lower bounds of the bounding box + public: gz::math::Vector3d Min() const; + + /// \brief Get the number of vertices + /// \return The number of vertices + public: unsigned int VertexCount() const; + + /// \brief Get the number of normals + /// \return The number of normals + public: unsigned int NormalCount() const; + + /// \brief Get the number of indices + /// \return The number of indices + public: unsigned int IndexCount() const; + + /// \brief Get the number of texture coordinates + /// \return The number of texture coordinates + public: unsigned int TexCoordCount() const; + + /// \brief Add a submesh mesh. + /// This can be an expensive since _child is copied into this mesh. + /// \sa AddSubMesh(std::unique_ptr _child); + /// \param[in] _child the submesh + /// \return Weak pointer to the added submesh + public: std::weak_ptr AddSubMesh(const SubMesh &_child); + + /// \brief Add a submesh mesh. This transfers ownership of _child + /// to this mesh. The value of _child after this call is nullptr. + /// \param[in] _child the submesh + /// \return Weak pointer to the added submesh + public: std::weak_ptr AddSubMesh( + std::unique_ptr _child); + + /// \brief Get the number of child submeshes. + /// \return The number of submeshes. + public: unsigned int SubMeshCount() const; + + /// \brief Add a material to the mesh + /// \param[in] _mat The material to add. + /// \return Index of this material + public: int AddMaterial(const MaterialPtr &_mat); + + /// \brief Get the number of materials + /// \return The number of materials + public: unsigned int MaterialCount() const; + + /// \brief Get a material by index + /// \param[in] _index The index of the material. + /// \return The material or NULL if the index is out of bounds + public: MaterialPtr MaterialByIndex(const unsigned int _index) const; + + /// \brief Get the index of material + /// \param[in] _mat The material + /// \return The index of the material or -1 if not found, or _mat is + /// null. + public: int IndexOfMaterial(const Material *_mat) const; + + /// \brief Get a child submesh by index + /// \param[in] _index Index of the submesh + /// \return The submesh or nullptr if the index is out of bounds. + public: std::weak_ptr SubMeshByIndex( + const unsigned int _index) const; + + /// \brief Get a child submesh by name. + /// \param[in] _name Name of the submesh. + /// \return The submesh or nullptr if the _name is not found. + public: std::weak_ptr SubMeshByName( + const std::string &_name) const; + + /// \brief Put all the data into flat arrays + /// \param[out] _vertArr the vertex array + /// \param[out] _indArr the index array + public: void FillArrays(double **_vertArr, int **_indArr) const; + + /// \brief Recalculate all the normals of each face defined by three + /// indices. + public: void RecalculateNormals(); + + /// \brief Get axis-aligned bounding box in the mesh frame + /// \param[out] _center Center of the bounding box + /// \param[out] _minXYZ Bounding box minimum values + /// \param[out] _maxXYZ Bounding box maximum values + public: void AABB(gz::math::Vector3d &_center, + gz::math::Vector3d &_minXYZ, + gz::math::Vector3d &_maxXYZ) const; + + /// \brief Generate texture coordinates using spherical projection + /// from center + /// \param[in] _center Center of the projection + public: void GenSphericalTexCoord( + const gz::math::Vector3d &_center); + + /// \brief Get the skeleton to which this mesh is attached. + /// \return Pointer to skeleton or nullptr if none is present. + public: SkeletonPtr MeshSkeleton() const; + + /// \brief Set the mesh skeleton + /// \param[in] _skel Skeleton to attach to the mesh. + public: void SetSkeleton(const SkeletonPtr &_skel); + + /// \brief Check if mesh is attached to a skeleton. + /// \return True if mesh is attached to a skeleton. + public: bool HasSkeleton() const; + + /// \brief Scale all vertices by _factor + /// \param _factor Scaling factor + public: void Scale(const gz::math::Vector3d &_factor); + + /// \brief Set the scale all vertices + /// \param[in] _factor Scaling vector + public: void SetScale(const gz::math::Vector3d &_factor); + + /// \brief Move the center of the mesh to the given coordinate in the + /// mesh frame. This will move all the vertices in all submeshes. + /// \param[in] _center Location of the mesh center. + public: void Center(const gz::math::Vector3d &_center = + gz::math::Vector3d::Zero); + + /// \brief Move all vertices in all submeshes by _vec. + /// \param[in] _vec Amount to translate vertices. + public: void Translate(const gz::math::Vector3d &_vec); + + /// \brief Compute the volume of this mesh. The primitive type + /// must be TRIANGLES. + /// + /// This function utilizes the mesh volume formula from + /// "Efficient feature extraction for 2d/3d objects in mesh + /// representation" by Cha Zhang and Tsuhan Chen. Link: + /// http://chenlab.ece.cornell.edu/Publication/Cha/icip01_Cha.pdf. + /// The formula does not check for a closed (water tight) mesh. + /// + /// \return The mesh's volume. The volume can be zero if + /// the primitive type of the submeshes is not TRIANGLES, + /// or there are no submeshes. + public: double Volume() const; + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief Private data pointer. + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} + +#endif diff --git a/graphics/include/gz/common/MeshCSG.hh b/graphics/include/gz/common/MeshCSG.hh new file mode 100644 index 000000000..6aed14500 --- /dev/null +++ b/graphics/include/gz/common/MeshCSG.hh @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_MESHCSG_HH_ +#define GZ_COMMON_MESHCSG_HH_ + +#include + +#include + +struct _GtsSurface; +typedef _GtsSurface GtsSurface; +struct _GPtrArray; +typedef _GPtrArray GPtrArray; + +namespace ignition +{ + namespace common + { + class Mesh; + + /// \class MeshCSG MeshCSG.hh ignition/common/MeshCSG.hh + /// \brief Creates CSG meshes + class IGNITION_COMMON_GRAPHICS_VISIBLE MeshCSG + { + /// \brief An enumeration of the boolean operations + public: enum BooleanOperation {UNION, INTERSECTION, DIFFERENCE}; + + /// \brief Constructor + public: MeshCSG(); + + /// \brief Destructor. + public: virtual ~MeshCSG(); + + /// \brief Create a boolean mesh from two meshes + /// \param[in] _m1 the parent mesh in the boolean operation + /// \param[in] _m2 the child mesh in the boolean operation + /// \param[in] _operation the boolean operation applied to the two meshes + /// \param[in] _offset _m2's pose offset from _m1 + /// \return a pointer to the created mesh + public: Mesh *CreateBoolean(const Mesh *_m1, const Mesh *_m2, + const int _operation, + const gz::math::Pose3d &_offset = gz::math::Pose3d::Zero); + + /// \brief Helper method for converting Mesh to GTS Surface + private: void ConvertMeshToGTS(const Mesh *mesh, GtsSurface *surface); + + /// \brief Helper method for merging neighborhood vertices whose positions + // are within epsilon + /// \param[in] _vertices Array of GTS vertices. + /// \param[in] _epsilon Epsilon + private: void MergeVertices(GPtrArray * _vertices, double _epsilon); + }; + } +} + +#endif diff --git a/graphics/include/gz/common/MeshExporter.hh b/graphics/include/gz/common/MeshExporter.hh new file mode 100644 index 000000000..2372b14a1 --- /dev/null +++ b/graphics/include/gz/common/MeshExporter.hh @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_MESHEXPORTER_HH_ +#define GZ_COMMON_MESHEXPORTER_HH_ + +#include +#include + +namespace ignition +{ + namespace common + { + class Mesh; + + /// \brief Base class for exporting meshes + class IGNITION_COMMON_GRAPHICS_VISIBLE MeshExporter + { + /// \brief Constructor + public: MeshExporter(); + + /// \brief Destructor + public: virtual ~MeshExporter(); + + /// \brief Export a mesh to a file + /// \param[in] _mesh Pointer to the mesh to be exported + /// \param[in] _filename Exported file's path and name + /// \param[in] _exportTextures True to export texture images to + /// '../materials/textures' folder + public: virtual void Export(const Mesh *_mesh, + const std::string &_filename, bool _exportTextures = false) = 0; + }; + } +} +#endif diff --git a/graphics/include/gz/common/MeshLoader.hh b/graphics/include/gz/common/MeshLoader.hh new file mode 100644 index 000000000..2a5ca6e94 --- /dev/null +++ b/graphics/include/gz/common/MeshLoader.hh @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_MESHLOADER_HH_ +#define GZ_COMMON_MESHLOADER_HH_ + +#include + +#include + +namespace ignition +{ + namespace common + { + class Mesh; + + /// \class MeshLoader MeshLoader.hh ignition/common/MeshLoader.hh + /// \brief Base class for loading meshes + class IGNITION_COMMON_GRAPHICS_VISIBLE MeshLoader + { + /// \brief Constructor + public: MeshLoader() = default; + + /// \brief Destructor + public: virtual ~MeshLoader() = default; + + /// \brief Load a 3D mesh + /// \param[in] _filename the path to the mesh + /// \return a pointer to the created mesh + public: virtual Mesh *Load(const std::string &_filename) = 0; + }; + } +} +#endif diff --git a/graphics/include/gz/common/MeshManager.hh b/graphics/include/gz/common/MeshManager.hh new file mode 100644 index 000000000..f069d6c81 --- /dev/null +++ b/graphics/include/gz/common/MeshManager.hh @@ -0,0 +1,297 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_MESHMANAGER_HH_ +#define GZ_COMMON_MESHMANAGER_HH_ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace ignition +{ + namespace common + { + /// \brief forward declaration + class Mesh; + class SubMesh; + class MeshManagerPrivate; + + /// \class MeshManager MeshManager.hh ignition/common/MeshManager.hh + /// \brief Maintains and manages all meshes + class IGNITION_COMMON_GRAPHICS_VISIBLE MeshManager + : public SingletonT + { + /// \brief Constructor + private: MeshManager(); + + /// \brief Destructor. + /// + /// Destroys the collada loader, the stl loader and all the meshes + private: virtual ~MeshManager(); + + /// \brief Load a mesh from a file. + /// The mesh will be searched on the global SystemPaths instance provided + /// by Util.hh. + /// \param[in] _filename the path to the mesh + /// \return a pointer to the created mesh + public: const Mesh *Load(const std::string &_filename); + + /// \brief Export a mesh to a file + /// \param[in] _mesh Pointer to the mesh to be exported + /// \param[in] _filename Exported file's path and name + /// \param[in] _extension Exported file's format ("dae" for Collada) + /// \param[in] _exportTextures True to export texture images to + /// '../materials/textures' folder + public: void Export(const Mesh *_mesh, const std::string &_filename, + const std::string &_extension, bool _exportTextures = false); + + /// \brief Checks a path extension against the list of valid extensions. + /// \return true if the file extension is loadable + public: bool IsValidFilename(const std::string &_filename); + + /// \brief Get mesh aabb and center. + /// \param[in] _mesh the mesh + /// \param[out] _center the AAB center position + /// \param[out] _min_xyz the bounding box minimum + /// \param[out] _max_xyz the bounding box maximum + public: void MeshAABB(const Mesh *_mesh, + gz::math::Vector3d &_center, + gz::math::Vector3d &_min_xyz, + gz::math::Vector3d &_max_xyz); + + /// \brief generate spherical texture coordinates + /// \param[in] _mesh Pointer to the mesh + /// \param[in] _center Center of the mesh + public: void GenSphericalTexCoord(const Mesh *_mesh, + const gz::math::Vector3d &_center); + + /// \brief Add a mesh to the manager. + /// + /// This MeshManager takes ownership of the mesh and will destroy it. + /// See ~MeshManager. + /// \param[in] the mesh to add. + public: void AddMesh(Mesh *_mesh); + + /// \brief Get a mesh by name. + /// \param[in] _name the name of the mesh to look for + /// \return the mesh or nullptr if not found + public: const gz::common::Mesh *MeshByName( + const std::string &_name) const; + + /// \brief Return true if the mesh exists. + /// \param[in] _name the name of the mesh + public: bool HasMesh(const std::string &_name) const; + + /// \brief Create a sphere mesh. + /// \param[in] _name the name of the mesh + /// \param[in] _radius radius of the sphere in meter + /// \param[in] _rings number of circles on th y axis + /// \param[in] _segments number of segment per circle + public: void CreateSphere(const std::string &_name, const float _radius, + const int _rings, const int _segments); + + /// \brief Create a Box mesh + /// \param[in] _name the name of the new mesh + /// \param[in] _sides the x y x dimentions of eah side in meter + /// \param[in] _uvCoords the texture coordinates + public: void CreateBox(const std::string &_name, + const gz::math::Vector3d &_sides, + const gz::math::Vector2d &_uvCoords); + + /// \brief Create an extruded mesh from polylines. The polylines are + /// assumed to be closed and non-intersecting. Delaunay triangulation is + /// applied to create the resulting mesh. If there is more than one + /// polyline, a ray casting algorithm will be used to identify the + /// exterior/interior edges and remove holes from the 2D shape before + /// extrusion. + /// \param[in] _name the name of the new mesh + /// \param[in] _vertices A multidimensional vector of polylines and their + /// vertices. Each element in the outer vector consists of a vector of + /// vertices that describe one polyline. + /// edges and remove the holes in the shape. + /// \param[in] _height the height of extrusion + public: void CreateExtrudedPolyline(const std::string &_name, + const std::vector > + &_vertices, const double _height); + + /// \brief Create a cylinder mesh + /// \param[in] _name the name of the new mesh + /// \param[in] _radius the radius of the cylinder in the x y plane + /// \param[in] _height the height along z + /// \param[in] _rings the number of circles along the height + /// \param[in] _segments the number of segment per circle + public: void CreateCylinder(const std::string &_name, + const float _radius, + const float _height, + const int _rings, + const int _segments); + + /// \brief Create a ellipsoid mesh + /// \param[in] _name the name of the new mesh + /// \param[in] _radii the three radius that define a ellipsoid + /// \param[in] _rings the number of circles along the height + /// \param[in] _segments the number of segment per circle + public: void CreateEllipsoid(const std::string &_name, + const gz::math::Vector3d &_radii, + const unsigned int _rings, + const unsigned int _segments); + + /// \brief Create a capsule mesh + /// \param[in] _name the name of the new mesh + /// \param[in] _radius the radius of the capsule in the x y plane + /// \param[in] _length length of the body + /// \param[in] _rings the number of circles along the height + /// \param[in] _segments the number of segment per circle + public: void CreateCapsule(const std::string &_name, + const double radius, + const double length, + const unsigned int _rings, + const unsigned int _segments); + + /// \brief Create a cone mesh + /// \param[in] _name the name of the new mesh + /// \param[in] _radius the radius of the cylinder in the x y plane + /// \param[in] _height the height along z + /// \param[in] _rings the number of circles along the height + /// \param[in] _segments the number of segment per circle + public: void CreateCone(const std::string &_name, + const float _radius, + const float _height, + const int _rings, + const int _segments); + + /// \brief Create a tube mesh. + /// + /// Generates rings inside and outside the cylinder + /// Needs at least two rings and 3 segments + /// \param[in] _name the name of the new mesh + /// \param[in] _innerRadius the inner radius of the tube in the x y plane + /// \param[in] _outterRadius the outer radius of the tube in the x y plane + /// \param[in] _height the height along z + /// \param[in] _rings the number of circles along the height + /// \param[in] _segments the number of segment per circle + /// \param[in] _arc the arc angle in radians + public: void CreateTube(const std::string &_name, + const float _innerRadius, + const float _outterRadius, + const float _height, + const int _rings, + const int _segments, + const double _arc = 2.0 * IGN_PI); + + /// \brief Create mesh for a plane + /// \param[in] _name + /// \param[in] _plane plane parameters + /// \param[in] _segments number of segments in x and y + /// \param[in] _uvTile the texture tile size in x and y + public: void CreatePlane(const std::string &_name, + const gz::math::Planed &_plane, + const gz::math::Vector2d &_segments, + const gz::math::Vector2d &_uvTile); + + /// \brief Create mesh for a plane + /// \param[in] _name the name of the new mesh + /// \param[in] _normal the normal to the plane + /// \param[in] _d distance from the origin along normal + /// \param[in] _size the size of the plane in x and y + /// \param[in] _segments the number of segments in x and y + /// \param[in] _uvTile the texture tile size in x and y + public: void CreatePlane(const std::string &_name, + const gz::math::Vector3d &_normal, + const double _d, + const gz::math::Vector2d &_size, + const gz::math::Vector2d &_segments, + const gz::math::Vector2d &_uvTile); + + /// \brief Tesselate a 2D mesh + /// + /// Makes a zigzag pattern compatible with strips + /// \param[in] _sm the mesh to tesselate + /// \param[in] _meshWith mesh width + /// \param[in] _meshHeight the mesh height + /// \param[in] _doubleSided flag to specify single or double sided + private: void Tesselate2DMesh(SubMesh *_sm, + const int _meshWidth, + const int _meshHeight, + const bool _doubleSided); + + /// \brief Create a Camera mesh + /// \param[in] _name name of the new mesh + /// \param[in] _scale scaling factor for the camera + public: void CreateCamera(const std::string &_name, const float _scale); + + /// \brief Create a boolean mesh from two meshes + /// \param[in] _name the name of the new mesh + /// \param[in] _m1 the parent mesh in the boolean operation + /// \param[in] _m2 the child mesh in the boolean operation + /// \param[in] _operation the boolean operation applied to the two meshes + /// \param[in] _offset _m2's pose offset from _m1 + public: void CreateBoolean(const std::string &_name, const Mesh *_m1, + const Mesh *_m2, const int _operation, + const gz::math::Pose3d &_offset = gz::math::Pose3d::Zero); + + /// \brief Converts a vector of polylines into a table of vertices and + /// a list of edges (each made of 2 points from the table of vertices. + /// \param[in] _polys the polylines + /// \param[in] _tol tolerence for 2 vertices to be considered the same + /// \param[out] _vertices a table of unique vertices + /// \param[out] _edges a list of edges (made of start/end point indices + /// from the vertex table) + private: static void ConvertPolylinesToVerticesAndEdges( + const std::vector > + &_polys, + const double _tol, + std::vector &_vertices, + std::vector &_edges); + + /// \brief Check a point againts a list, and only adds it to the list + /// if it is not there already. + /// \param[in,out] _vertices the vertex table where points are stored + /// \param[in] _p the point coordinates + /// \param[in] _tol the maximum distance under which 2 points are + /// considered to be the same point. + /// \return the index of the point. + private: static size_t AddUniquePointToVerticesTable( + std::vector &_vertices, + const gz::math::Vector2d &_p, + const double _tol); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief Pointer to private data + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + + /// \brief Singleton implementation + private: friend class SingletonT; + }; + } +} +#endif diff --git a/graphics/include/gz/common/NodeAnimation.hh b/graphics/include/gz/common/NodeAnimation.hh new file mode 100644 index 000000000..82dc844f6 --- /dev/null +++ b/graphics/include/gz/common/NodeAnimation.hh @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_NODE_ANIMATION_HH_ +#define GZ_COMMON_NODE_ANIMATION_HH_ + +#include +#include + +#include +#include + +#include + +namespace ignition +{ + namespace common + { + class NodeAnimationPrivate; + + /// \class NodeAnimation NodeAnimation.hh ignition/common/NodeAnimation.hh + /// \brief Node animation + class IGNITION_COMMON_GRAPHICS_VISIBLE NodeAnimation + { + /// \brief constructor + /// \param[in] _name the name of the node + public: explicit NodeAnimation(const std::string &_name); + + /// \brief Destructor. + public: ~NodeAnimation(); + + /// \brief Changes the name of the animation + /// \param[in] the new name + public: void SetName(const std::string &_name); + + /// \brief Returns the name + /// \return the name + public: std::string Name() const; + + /// \brief Adds a key frame at a specific time + /// \param[in] _time the time of the key frame + /// \param[in] _trans the transformation + public: void AddKeyFrame(const double _time, + const math::Matrix4d &_trans); + + /// \brief Adds a key frame at a specific time + /// \param[in] _time the tiem of the key frame + /// \param[in] _pose the pose + public: void AddKeyFrame(const double _time, const math::Pose3d &_pose); + + /// \brief Returns the number of key frames. + /// \return the count + public: unsigned int FrameCount() const; + + /// \brief Finds a key frame using the index. Note the index of a key + /// frame can change as frames are added. + /// \param[in] _i the index + /// \param[out] _time the time of the frame, or -1 if the index id is out + /// of bounds + /// \param[out] _trans the transformation for this key frame + public: void KeyFrame(const unsigned int _i, double &_time, + math::Matrix4d &_trans) const; + + /// \brief Returns a key frame using the index. Note the index of a key + /// frame can change as frames are added. + /// \param[in] _i the index + /// \return a pair that contains the time and transformation. Time is -1 + /// if the index is out of bounds + public: std::pair KeyFrame( + const unsigned int _i) const; + + /// \brief Returns the duration of the animations + /// \return the time of the last animation + public: double Length() const; + + /// \brief Returns a frame transformation at a specific time + /// if a node does not exist at that time (with tolerance of 1e-6 sec), + /// the transformation is interpolated. + /// \param[in] _time the time + /// \param[in] _loop when true, the time is divided by the duration + /// (see GetLength) + public: gz::math::Matrix4d FrameAt(const double _time, + const bool _loop = true) const; + + /// \brief Scales each transformation in the key frames. This only affects + /// the translational values. + /// \param[in] _scale the scaling factor + public: void Scale(const double _scale); + + /// \brief Returns the time where a transformation's translational value + /// along the X axis is equal to _x. + /// When no transformation is found (within a tolerance of 1e-6), the time + /// is interpolated. + /// \param[in] _x the value along x. You must ensure that _x is within a + /// valid range. + public: double TimeAtX(const double _x) const; + + /// \brief Private data pointer. + private: NodeAnimationPrivate *data; + }; + } +} + +#endif diff --git a/graphics/include/gz/common/NodeTransform.hh b/graphics/include/gz/common/NodeTransform.hh new file mode 100644 index 000000000..d560a2582 --- /dev/null +++ b/graphics/include/gz/common/NodeTransform.hh @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_NODE_TRANSFORM_HH_ +#define GZ_COMMON_NODE_TRANSFORM_HH_ +#include +#include + +#include +#include +#include +#include + +namespace ignition +{ + namespace common + { + /// Forward declare private data structure. + class NodeTransformPrivate; + + /// \class NodeTransform NodeTransform.hh ignition/common/NodeTransform.hh + /// \brief A transformation node + class IGNITION_COMMON_GRAPHICS_VISIBLE NodeTransform + { + /// \brief Constructor + /// \param[in] _type the type of transform + public: explicit NodeTransform(const NodeTransformType _type = MATRIX); + + /// \brief Copy constructor + /// \param[in] _other NodeTransform to copy + public: NodeTransform(const NodeTransform &_other); + + /// \brief Copy assignment + /// \param[in] _ther NodeTransform to copy + public: NodeTransform &operator=(const NodeTransform &_other); + + /// \brief Constructor + /// \param[in] _mat the matrix + /// \param[in] _sid identifier + /// \param[in] _type the type of transform + public: NodeTransform(const math::Matrix4d &_mat, + const std::string &_sid = "_default_", + const NodeTransformType _type = MATRIX); + + /// \brief Destructor. + public: ~NodeTransform(); + + /// \brief Assign a transformation + /// \param[in] _mat the transform + public: void Set(const math::Matrix4d &_mat); + + /// \brief Returns the transformation matrix + /// \return the matrix + public: math::Matrix4d Get() const; + + /// \brief Set transform type + /// \param[in] _type the type + public: void SetType(const NodeTransformType _type); + + /// \brief Returns the transformation type + /// \return the type + public: NodeTransformType Type() const; + + /// \brief Set the SID + /// \param[in] _sid the sid + public: void SetSID(const std::string &_sid); + + /// \brief Returns the SID + /// \return the SID + public: std::string SID() const; + + /// \brief Set a transformation matrix component value + /// \param[in] _idx the component index + /// \param[in] _value the value + public: void SetComponent(const unsigned int _idx, const double _value); + + /// \brief Set source data values + /// \param[in] _mat the values + public: void SetSourceValues(const math::Matrix4d &_mat); + + /// \brief Set source data values + /// \param[in] _vec the values + public: void SetSourceValues(const math::Vector3d &_vec); + + /// \brief Sets source matrix values from roation + /// \param[in] _axis of rotation + /// \param[in] _angle of rotation + public: void SetSourceValues(const math::Vector3d &_axis, + const double _angle); + + /// \brief Sets the transform matrix from the source according to the type + public: void RecalculateMatrix(); + + /// \brief Prints the transform matrix to standard out + public: void PrintSource() const; + + /// \brief Matrix cast operator + /// \return the transform + public: math::Matrix4d operator()() const; + + /// \brief Node transform multiplication operator + /// \param[in] _t a transform + /// \return transform matrix multiplied by _t's transform + public: math::Matrix4d operator*(const NodeTransform &_t) const; + + /// \brief Matrix multiplication operator + /// \param[in] _m a matrix + /// \return transform matrix multiplied by _m + public: math::Matrix4d operator*(const math::Matrix4d &_m) const; + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief Data pointer + private: std::unique_ptr data; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} +#endif diff --git a/graphics/include/gz/common/OBJLoader.hh b/graphics/include/gz/common/OBJLoader.hh new file mode 100644 index 000000000..cbfb04c5f --- /dev/null +++ b/graphics/include/gz/common/OBJLoader.hh @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +#ifndef GZ_COMMON_OBJLOADER_HH_ +#define GZ_COMMON_OBJLOADER_HH_ + +#include +#include + +#include +#include +#include + +namespace ignition +{ + namespace common + { + // class OBJ Loader private class; + class OBJLoaderPrivate; + + /// \brief Class used to load obj mesh files + class IGNITION_COMMON_GRAPHICS_VISIBLE OBJLoader : public MeshLoader + { + /// \brief Constructor + public: OBJLoader(); + + /// \brief Destructor + public: virtual ~OBJLoader(); + + /// \brief Load a mesh + /// \param[in] _filename OBJ file to load + /// \return Pointer to a new Mesh + public: virtual Mesh *Load(const std::string &_filename); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \internal + /// \brief Pointer to private data. + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} +#endif diff --git a/graphics/include/gz/common/Pbr.hh b/graphics/include/gz/common/Pbr.hh new file mode 100644 index 000000000..5dc135027 --- /dev/null +++ b/graphics/include/gz/common/Pbr.hh @@ -0,0 +1,241 @@ +/* + * Copyright 2020 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#ifndef GZ_COMMON_PBR_HH_ +#define GZ_COMMON_PBR_HH_ + +#include +#include + +namespace ignition +{ +namespace common +{ + // Forward declarations. + class PbrPrivate; + + /// \brief Type of PBR workflow. + enum class PbrType : int + { + /// \brief No workflow + NONE = 0, + + /// \brief Metal/Roughness workflow + METAL = 1, + + /// \brief Specular/Glossiness workflow + SPECULAR = 2, + }; + + /// \brief Space the normal map is defined in + enum class NormalMapSpace: int + { + /// \brief Tangent space + TANGENT = 0, + + /// \brief Object space + OBJECT = 1, + }; + + /// \brief This class contains Physically-Based-Rendering (PBR) workflow + /// properties. + class IGNITION_COMMON_GRAPHICS_VISIBLE Pbr + { + /// \brief Default constructor + public: Pbr(); + + /// \brief Copy constructor + /// \param[in] _pbr Pbr to copy. + public: Pbr(const Pbr &_pbr); + + /// \brief Move constructor + /// \param[in] _pbr to move. + public: Pbr(Pbr &&_pbr) noexcept; + + /// \brief Destructor + public: ~Pbr(); + + /// \brief Assignment operator. + /// \param[in] _pbr The pbr material to set values from. + /// \return *this + public: Pbr &operator=(const Pbr &_pbr); + + /// \brief Move assignment operator. + /// \param[in] _pbr The pbr material to move from. + /// \return *this + public: Pbr &operator=(Pbr &&_pbr); + + /// \brief Return true if both Pbr objects contain the same values. + /// \param[_in] _pbr Pbr value to compare. + /// \returen True if 'this' == _pbr. + public: bool operator==(const Pbr &_pbr) const; + + /// \brief Return true this Pbr object does not contain the same + /// values as the passed in parameter. + /// \param[_in] _pbr Pbr value to compare. + /// \returen True if 'this' != _pbr. + public: bool operator!=(const Pbr &_pbr) const; + + /// \brief Get the albedo map filename. This will be an empty string if + /// an albedo map has not been set. + /// \return Filename of the albedo map, or empty string if an albedo map + /// has not been specified. + public: std::string AlbedoMap() const; + + /// \brief Set the albedo map filename. + /// \param[in] _map Filename of the albedo map. + public: void SetAlbedoMap(const std::string &_map); + + /// \brief Get the normal map filename. This will be an empty string if + /// a normal map has not been set. + /// \return Filename of the normal map, or empty string if a normal map + /// has not been specified. + public: std::string NormalMap() const; + + /// \brief Set the normal map filename. + /// \param[in] _map Filename of the normal map. + /// \param[in] _space Space that the normal map is defined in. + /// Defaults to tangent space. + public: void SetNormalMap(const std::string &_map, + NormalMapSpace _space = NormalMapSpace::TANGENT); + + /// \brief Get the normal map type, either tangent or object space + /// \return Space that the normal map is defined in + public: NormalMapSpace NormalMapType() const; + + /// \brief Get the environment map filename. This will be an empty string + /// if an environment map has not been set. + /// \return Filename of the environment map, or empty string if an + /// environment map has not been specified. + public: std::string EnvironmentMap() const; + + /// \brief Set the environment map filename. + /// \param[in] _map Filename of the environment map. + public: void SetEnvironmentMap(const std::string &_map); + + /// \brief Get the ambient occlusion map filename. This will be an empty + /// string if an ambient occlusion map has not been set. + /// \return Filename of the ambient occlusion map, or empty string if an + /// ambient occlusion map has not been specified. + public: std::string AmbientOcclusionMap() const; + + /// \brief Set the ambient occlusion map filename. + /// \param[in] _map Filename of the ambient occlusion map. + public: void SetAmbientOcclusionMap(const std::string &_map); + + /// \brief Get the roughness map filename for metal workflow. This will be + /// an empty string if a roughness map has not been set. + /// \return Filename of the roughness map, or empty string if a roughness + /// map has not been specified. + public: std::string RoughnessMap() const; + + /// \brief Set the roughness map filename for metal workflow. + /// \param[in] _map Filename of the roughness map. + public: void SetRoughnessMap(const std::string &_map); + + /// \brief Get the metalness map filename for metal workflow. This will be + /// an empty string if a metalness map has not been set. + /// \return Filename of the metalness map, or empty string if a metalness + /// map has not been specified. + public: std::string MetalnessMap() const; + + /// \brief Set the metalness map filename for metal workflow. + /// \param[in] _map Filename of the metalness map. + public: void SetMetalnessMap(const std::string &_map); + + /// \brief Get the emissive map filename. This will be an empty string + /// if an emissive map has not been set. + /// \return Filename of the emissive map, or empty string if an emissive + /// map has not been specified. + public: std::string EmissiveMap() const; + + /// \brief Set the emissive map filename. + /// \param[in] _map Filename of the emissive map. + public: void SetEmissiveMap(const std::string &_map); + + /// \brief Get the light map filename. This will be an empty string + /// if an light map has not been set. + /// \return Filename of the light map, or empty string if a light + /// map has not been specified. + public: std::string LightMap() const; + + /// \brief Set the light map filename. + /// \param[in] _map Filename of the light map. + /// \param[in] _uvSet Index of the texture coordinate set + public: void SetLightMap(const std::string &_map, unsigned int _uvSet = 0u); + + /// \brief Get the light map texture coordinate set. + /// \return Index of the light map texture coordinate set + public: unsigned int LightMapTexCoordSet() const; + + /// \brief Get the metalness value of the material for metal workflow + /// \return metalness value of the material + public: double Metalness() const; + + /// \brief Set the metalness value of the material for metal workflow. + /// \param[in] _value Metalness value. + public: void SetMetalness(double _value); + + /// \brief Get the roughness value of the material for metal workflow + /// \return roughness value of the material + public: double Roughness() const; + + /// \brief Set the roughness value of the material for metal workflow. + /// \param[in] _value Roughness value. + public: void SetRoughness(double _value); + + /// \brief Get the glossiness map filename for specular workflow. This will + /// be an empty string if a glossiness map has not been set. + /// \return Filename of the glossiness map, or empty string if a glossiness + /// map has not been specified. + public: std::string GlossinessMap() const; + + /// \brief Set the glossiness map filename for specular workflow. + /// \param[in] _map Filename of the glossiness map. + public: void SetGlossinessMap(const std::string &_map); + + /// \brief Get the glossiness value of the material for specular workflow + /// \return Glossiness value of the material + public: double Glossiness() const; + + /// \brief Set the glossiness value of the material for specular workflow. + /// \param[in] _value Glossiness value. + public: void SetGlossiness(double _value); + + /// \brief Get the specular map filename for specular workflow. This will + /// be an empty string if a specular map has not been set. + /// \return Filename of the specular map, or empty string if a specular + /// map has not been specified. + public: std::string SpecularMap() const; + + /// \brief Set the specular map filename for specular workflow. + /// \param[in] _map Filename of the specular map. + public: void SetSpecularMap(const std::string &_map); + + /// \brief Get the workflow type. + /// \return PBR workflow type. + public: PbrType Type() const; + + /// \brief Set the PBR workflow to use + /// \param[in] _type Workflow type to use + public: void SetType(PbrType _type); + + /// \brief Private data pointer. + private: PbrPrivate *dataPtr = nullptr; + }; +} +} +#endif diff --git a/graphics/include/gz/common/STLLoader.hh b/graphics/include/gz/common/STLLoader.hh new file mode 100644 index 000000000..a94b87606 --- /dev/null +++ b/graphics/include/gz/common/STLLoader.hh @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_STLLOADER_HH_ +#define GZ_COMMON_STLLOADER_HH_ + +#include +#include + +#include "gz/common/MeshLoader.hh" +#include "gz/common/graphics/Export.hh" + +#define LINE_MAX_LEN 256 +#define COR3_MAX 200000 +#define ORDER_MAX 10 +#define FACE_MAX 200000 + +namespace ignition +{ + namespace common + { + /// \class STLLoader STLLoader.hh ignition/common/STLLoader.hh + /// \brief Class used to load STL mesh files + class IGNITION_COMMON_GRAPHICS_VISIBLE STLLoader : public MeshLoader + { + /// \brief Constructor + public: STLLoader(); + + /// \brief Destructor + public: virtual ~STLLoader(); + + /// \brief Creates a new mesh and loads the data from a file + /// \param[in] _filename the mesh file + public: virtual Mesh *Load(const std::string &_filename); + + /// \brief Reads an ASCII STL (stereolithography) file. + /// \param[in] _filein the file pointer + /// \param[out] _mesh the mesh where to load the data + /// \return true if read was successful + private: bool ReadAscii(FILE *_filein, Mesh *_mesh); + + /// \brief Reads a binary STL (stereolithography) file. + /// \param[in] _filein the file pointer + /// \param[out] the mesh where to load the data + /// \return true if read was successful + private: bool ReadBinary(FILE *_filein, Mesh *_mesh); + + /// \brief Compares two strings for equality, disregarding case. + /// \param[in] _string1 the first string + /// \param[in] _string2 the seconf string + /// \return true if the strings are equal (same content) + private: bool Leqi(char* _string1, char* _string2); + + /// \brief Finds if a vector occurs in a table. This is done using + /// floating point comparison with the default tolerance of 1e-6 + /// \param[in] _a the vector data + /// \param[in] _m the number of columns in the table + /// \param[in] _n the number of rows in the table + /// \return The column index of the vector + private: int RcolFind(float _a[][COR3_MAX], int _m, int _n, float _r[]); + + /// \brief Reads a long int from a binary file. + /// \param[in] _filein the file pointer + /// \return the value + private: uint32_t LongIntRead(FILE *_filein); + + /// \brief Reads a short int from a binary file. + /// \param[in] _filein the file pointer + /// \param[out] _value the value read + /// \return true + private: bool ShortIntRead(FILE *_filein, uint16_t &_value); + + /// \brief Read 1 double precision float from a binary file. + /// \param[in] _filein the file pointer + /// \param[out] the value + /// \return true + private: bool FloatRead(FILE *_filein, double &_value); + }; + } +} +#endif + diff --git a/graphics/include/gz/common/SVGLoader.hh b/graphics/include/gz/common/SVGLoader.hh new file mode 100644 index 000000000..7f21be18e --- /dev/null +++ b/graphics/include/gz/common/SVGLoader.hh @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#ifndef GZ_COMMON_SVGLOADER_HH_ +#define GZ_COMMON_SVGLOADER_HH_ + +#include +#include +#include + +#include +#include + +#include +#include +#include + +namespace ignition +{ + namespace common + { + // Forward declare private data class + class SVGLoaderPrivate; + + /// \brief SVG command data structure + class IGNITION_COMMON_GRAPHICS_VISIBLE SVGCommand + { + /// \brief Constructor + public: SVGCommand() : cmd(' ') {} + + /// \brief Destructor + public: virtual ~SVGCommand() = default; + + /// \brief A letter that describe the segment + public: char cmd; + +#ifdef _WIN32 +// Disable warning C4251 +#pragma warning(push) +#pragma warning(disable: 4251) +#endif + /// \brief Coordinates for the command + public: std::vector numbers; +#ifdef _WIN32 +#pragma warning(pop) +#endif + }; + + /// \brief An SVG path element data structure + struct IGNITION_COMMON_GRAPHICS_VISIBLE SVGPath + { +#ifdef _WIN32 +// Disable warning C4251 +#pragma warning(push) +#pragma warning(disable: 4251) +#endif + + /// \brief An id or name + std::string id; + + /// \brief The style (i.e. stroke style, color, thickness etc) + std::string style; + + /// \brief A 2D transform (or a list of transforms) + gz::math::Matrix3d transform; + + /// \brief A list of subpaths (as lists of commands) + std::vector< std::vector > subpaths; + + /// \brief The polylines described by the commands + std::vector< std::vector > polylines; +#ifdef _WIN32 +#pragma warning(pop) +#endif + }; + + /// \brief A loader for SVG files + class IGNITION_COMMON_GRAPHICS_VISIBLE SVGLoader + { + /// \brief Constructor + /// \param[in] _samples The number of points for cubic spline segments + /// Samples must be greater than zero. A value of one will be used if + /// _samples is set to zero. + public: explicit SVGLoader(const unsigned int _samples); + + /// \brief destructor + public: ~SVGLoader(); + + /// \brief Reads an SVG file and loads all the paths + /// \param[in] _filename The SVG file + /// \param[out] _paths Vector that receives path datai + /// \return false when the file cannot be processed + public: bool Parse(const std::string &_filename, + std::vector &_paths); + + /// \brief Reads in paths and outputs closed polylines and open polylines + /// \param[in] _paths The input paths + /// \param[in] _tol Tolerence when comparing distance between 2 points. + /// \param[out] _closedPolys A vector to collect new closed loops + /// \param[out] _openPolys A vector to collect non closed paths + public: static void PathsToClosedPolylines( + const std::vector &_paths, + const double _tol, + std::vector< std::vector > &_closedPolys, + std::vector< std::vector > &_openPolys); + + /// \brief Outputs the content of the paths to file (or console) + /// \param[in] _paths The paths + /// \param[in] _out The output stream (can be a file or std::cout) + public: void DumpPaths(const std::vector &_paths, + std::ostream &_out) const; + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \internal + /// \brief Pointer to private data + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} + +#endif diff --git a/graphics/include/gz/common/Skeleton.hh b/graphics/include/gz/common/Skeleton.hh new file mode 100644 index 000000000..8e483cda2 --- /dev/null +++ b/graphics/include/gz/common/Skeleton.hh @@ -0,0 +1,178 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_SKELETON_HH_ +#define GZ_COMMON_SKELETON_HH_ + +#include +#include +#include +#include + +#include +#include +#include + +namespace ignition +{ + namespace common + { + /// Forward declarations + class SkeletonPrivate; + class SkeletonAnimation; + + /// \class Skeleton Skeleton.hh ignition/common/Skeleton.hh + /// \brief A skeleton, usually used for animation purposes. + class IGNITION_COMMON_GRAPHICS_VISIBLE Skeleton + { + /// \brief Constructor + public: Skeleton(); + + /// \brief Constructor + /// \param[in] _root node + public: explicit Skeleton(SkeletonNode *_root); + + /// \brief Destructor + public: virtual ~Skeleton(); + + /// \brief Change the root node + /// \param[in] _node the new node + public: void RootNode(SkeletonNode *_node); + + /// \brief Return the root + /// \return the root + public: SkeletonNode *RootNode() const; + + /// \brief Find a node + /// \param[in] _name the name of the node to look for + /// \return the node, or NULL if not found + public: SkeletonNode *NodeByName(const std::string &_name) const; + + /// \brief Find node by index + /// \param[in] _id the index + /// \return the node, or NULL if not found + public: SkeletonNode *NodeById(const std::string &_id) const; + + /// \brief Find or create node with handle + /// \param[in] _handle + /// \return the node. A new node is created if it didn't exist + public: SkeletonNode *NodeByHandle(const unsigned int _handle) const; + + /// \brief Returns the node count + /// \return the count + public: unsigned int NodeCount() const; + + /// \brief Returns the number of joints + /// \return the count + public: unsigned int JointCount() const; + + /// \brief Scale all nodes, transforms and animation data + /// \param[in] the scaling factor + public: void Scale(const double _scale); + + /// \brief Set the bind pose skeletal transform + /// \param[in] _trans the transform + public: void SetBindShapeTransform(const math::Matrix4d &_trans); + + /// \brief Return bind pose skeletal transform + /// \return A matrix + public: math::Matrix4d BindShapeTransform() const; + + /// \brief Outputs the transforms to standard out + public: void PrintTransforms() const; + + /// \brief Get a copy or the node dictionary. + /// \return A copy of the nodes. + public: const SkeletonNodeMap &Nodes() const; + + /// \brief Resizes the raw node weight array + /// \param[in] _vertices the new size + public: void SetNumVertAttached(const unsigned int _vertices); + + /// \brief Add a new weight to a node (bone) + /// \param[in] _vertex index of the vertex + /// \param[in] _node name of the bone + /// \param[in] _weight the new weight (range 0 to 1) + public: void AddVertNodeWeight(const unsigned int _vertex, + const std::string &_node, const double _weight); + + /// \brief Returns the number of bone weights for a vertex + /// \param[in] _vertex the index of the vertex + /// \return the count + public: unsigned int VertNodeWeightCount( + const unsigned int _vertex) const; + + /// \brief Weight of a bone for a vertex + /// \param[in] _v the index of the vertex + /// \param[in] _i the index of the weight for that vertex + /// \return a pair containing the name of the node and the weight + public: std::pair VertNodeWeight( + const unsigned int _v, const unsigned int _i) const; + + /// \brief Returns the number of animations + /// \return the count + public: unsigned int AnimationCount() const; + + /// \brief Find animation + /// \param[in] _i the animation index + /// \return the animation, or NULL if _i is out of bounds + public: SkeletonAnimation *Animation(const unsigned int _i) const; + + /// \brief Add an animation. The skeleton does not take ownership of the + /// animation + /// \param[in] _anim the animation to add + public: void AddAnimation(SkeletonAnimation *_anim); + + /// \brief Add an animation from BVH file. + /// \param[in] _bvhFile the bvh file to load animation from + /// \param[in] _scale the scale of the animation + /// \return True if the BVH animation is compatible with skeleton + public: bool AddBvhAnimation(const std::string &_bvhFile, double _scale); + + /// \brief Finding the skin node name that corresponds to + /// the given animation node name. + /// \param[in] _index the animation index + /// \param[in] _animNodeName the given animation node name + /// \return The corresponding skin node name in the skeleton + public: std::string NodeNameAnimToSkin(unsigned int _index, + const std::string &_animNodeName); + + /// \brief Get the transformation to align translation from + /// the animation skeleton to skin skeleton + /// \param[in] _index the animation index + /// \param[in] _animNodeName the animation node name + /// \return The transformation to align translation + public: math::Matrix4d AlignTranslation(unsigned int _index, + const std::string &_animNodeName); + + /// \brief Get the transformation to align rotation from + /// the animation skeleton to skin skeleton + /// \param[in] _index the animation index + /// \param[in] _animNodeName the animation node name + /// \return The transformation to align rotation + public: math::Matrix4d AlignRotation(unsigned int _index, + const std::string &_animNodeName); + + /// \brief Initializes the hande numbers for each node in the map + /// using breadth first traversal + private: void BuildNodeMap(); + + /// \brief Private data pointer + private: SkeletonPrivate *data; + }; + } +} +#endif diff --git a/graphics/include/gz/common/SkeletonAnimation.hh b/graphics/include/gz/common/SkeletonAnimation.hh new file mode 100644 index 000000000..699de0267 --- /dev/null +++ b/graphics/include/gz/common/SkeletonAnimation.hh @@ -0,0 +1,143 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_SKELETONANIMATION_HH_ +#define GZ_COMMON_SKELETONANIMATION_HH_ + +#include +#include +#include + +#include +#include + +#include +#include + +namespace ignition +{ + namespace common + { + /// Forward declare private data class + class SkeletonAnimationPrivate; + + /// \class SkeletonAnimation SkeletonAnimation.hh + /// ignition/common/SkeletonAnimation.hh + /// \brief Skeleton animation + class IGNITION_COMMON_GRAPHICS_VISIBLE SkeletonAnimation + { + /// \brief The Constructor + /// \param[in] _name the name of the animation + public: explicit SkeletonAnimation(const std::string &_name); + + /// \brief The destructor. Clears the list without destroying + /// the animations + public: ~SkeletonAnimation(); + + // NOTE: this is not needed starting in ign-common4 since ign-common4 uses + // the IGN_UTILS_IMPL_PTR instead of a raw impl pointer. So, this + // method should not be included in forward ports from ign-common3 to + // ign-common4 + /// \brief Assignment operator + /// \param[in] _other The new SkeletonAnimation + /// \return A reference to this instance + public: SkeletonAnimation &operator=(const SkeletonAnimation &_other); + + /// \brief Changes the name + /// \param[in] _name the new name + public: void SetName(const std::string& _name); + + /// \brief Returns the name + /// \return the name + public: std::string Name() const; + + /// \brief Returns the number of animation nodes + /// \return the count + public: unsigned int NodeCount() const; + + /// \brief Returns the node animation for given node name + /// \param[in] _name Name of node + /// \return NodeAnimation object + public: NodeAnimation *NodeAnimationByName(const std::string &_name) + const; + + /// \brief Looks for a node with a specific name in the animations + /// \param[in] _node the name of the node + /// \return true if the node exits + public: bool HasNode(const std::string &_node) const; + + /// \brief Adds or replaces a named key frame at a specific time + /// \param[in] _node the name of the new or existing node + /// \param[in] _time the time + /// \param[in] _mat the key frame transformation + public: void AddKeyFrame(const std::string &_node, const double _time, + const math::Matrix4d &_mat); + + /// \brief Adds or replaces a named key frame at a specific time + /// \param[in] _node the name of the new or existing node + /// \param[in] _time the time + /// \param[in] _pose the key frame transformation as a math::Pose + public: void AddKeyFrame(const std::string &_node, const double _time, + const math::Pose3d &_pose); + + /// \brief Returns the key frame transformation for a named animation at + /// a specific time + /// if a node does not exist at that time (with tolerance of 1e-6 sec), + /// the transformation is interpolated. + /// \param[in] _node the name of the animation node + /// \param[in] _time the time + /// \param[in] _loop when true, the time is divided by the duration + /// (see GetLength) + /// \return the transformation + public: math::Matrix4d NodePoseAt(const std::string &_node, + const double _time, const bool _loop = true) const; + + /// \brief Returns a dictionary of transformations indexed by name at + /// a specific time + /// if a node does not exist at that specific time + /// (with tolerance of 1e-6 sec), the transformation is interpolated. + /// \param[in] _time the time + /// \param[in] _loop when true, the time is divided by the duration + /// (see GetLength) + /// \return the transformation for every node + public: std::map PoseAt( + const double _time, const bool _loop = true) const; + + /// \brief Returns a dictionary of transformations indexed by name where + /// a named node transformation's translational value along the X axis is + /// equal to _x. + /// \param[in] _x the value along x. You must ensure that _x is within a + /// valid range. + /// \param[in] _node the name of the animation node + /// \param[in] _loop when true, the time is divided by the duration + /// (see GetLength) + public: std::map PoseAtX(const double _x, + const std::string &_node, const bool _loop = true) const; + + /// \brief Scales every animation in the animations list + /// \param[in] _scale the scaling factor + public: void Scale(const double _scale); + + /// \brief Returns the duration of the animations + /// \return the duration in seconds + public: double Length() const; + + /// \brief Private data pointer + private: SkeletonAnimationPrivate *data; + }; + } +} +#endif diff --git a/graphics/include/gz/common/SkeletonNode.hh b/graphics/include/gz/common/SkeletonNode.hh new file mode 100644 index 000000000..4011a57b8 --- /dev/null +++ b/graphics/include/gz/common/SkeletonNode.hh @@ -0,0 +1,200 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_SKELETON_NODE_HH_ +#define GZ_COMMON_SKELETON_NODE_HH_ + +#include +#include +#include + +#include +#include + +namespace ignition +{ + namespace common + { + /// Forward declare private data class + class SkeletonNodePrivate; + + /// \class SkeletonNode Skeleton.hh ignition/common/SkeletonNode.hh + /// \brief A skeleton node + class IGNITION_COMMON_GRAPHICS_VISIBLE SkeletonNode + { + /// \brief enumeration of node types + public: enum SkeletonNodeType {NODE, JOINT}; + + /// \brief Constructor + /// \param[in] _parent The parent node + public: explicit SkeletonNode(SkeletonNode *_parent); + + /// \brief Constructor + /// \param[in] _parent the parent node + /// \param[in] _name name of node + /// \param[in] _id Id of node + /// \param[in] _type The type of this node + public: SkeletonNode(SkeletonNode *_parent, + const std::string &_name, + const std::string &_id, + const SkeletonNodeType _type = JOINT); + + /// \brief Destructor + public: virtual ~SkeletonNode(); + + /// \brief Change the name + /// \param[in] _name the new name + public: void Name(const std::string &_name); + + /// \brief Returns the name + /// \return the name + public: std::string Name() const; + + /// \brief Change the id string + /// \param[in] _id the new id string + public: void Id(const std::string &_id); + + /// \brief Returns the index + /// \return the id string + public: std::string Id() const; + + /// \brief Change the skeleton node type + /// \param[in] _type the new type + public: void SetType(const SkeletonNodeType _type); + + /// \brief Is a joint query + /// \return true if the skeleton type is a joint, false otherwise + public: bool IsJoint() const; + + /// \brief Set a transformation + /// \param[in] _trans the transformation + /// \param[in] _updateChildren when true the UpdateChildrenTransforms + /// operation is performed + public: void SetTransform(const math::Matrix4d &_trans, + const bool _updateChildren = true); + + /// \brief Set the model transformation + /// \param[in] _trans the transformation + /// \param[in] _updateChildren when true the UpdateChildrenTransforms + /// operation is performed + public: void SetModelTransform(const math::Matrix4d &_trans, + const bool _updateChildren = true); + + /// \brief Apply model transformations in order for each node in the tree + public: void UpdateChildrenTransforms(); + + /// \brief Sets the initial transformation + /// \param[in] _trans the transfromation matrix + public: void SetInitialTransform(const math::Matrix4d &_trans); + + /// \brief Reset the transformation to the initial transformation + /// \param[in] _resetChildren when true, performs the operation for every + /// node in the tree + public: void Reset(const bool _resetChildren); + + /// \brief Get transform relative to parent + public: math::Matrix4d Transform() const; + + /// \brief Set the parent node + /// \param[in] _parent the new parent + public: void SetParent(SkeletonNode *_parent); + + /// \brief Returns the parent node + /// \return the parent + public: SkeletonNode *Parent() const; + + /// \brief Queries wether a node has no parent parent + /// \return true if the node has no parent, fasle otherwise + public: bool IsRootNode() const; + + /// \brief Add a new child + /// \param[in] _child a child + public: void AddChild(SkeletonNode *_child); + + /// \brief Returns the children count + /// \return the count + public: unsigned int ChildCount() const; + + /// \brief Find a child by index + /// \param[in] _index the index + /// \return the child skeleton. + public: SkeletonNode *Child(const unsigned int _index) const; + + /// \brief Get child by name + /// \param[in] _name the name of the child skeleton + /// \return the skeleton, or NULL if not found + public: SkeletonNode *ChildByName(const std::string &_name) const; + + /// \brief Get child by string id + /// \param[in] _id the string id + /// \return the child skeleton or NULL if not found + public: SkeletonNode *ChildById(const std::string &_id) const; + + /// \brief Assign a handle number + /// \param[in] _h the handle + public: void Handle(const unsigned int _h); + + /// \brief Get the handle index + /// \return the handle index + public: unsigned int Handle() const; + + /// \brief Assign the inverse of the bind pose skeletal transform + /// \param[in] _invBM the transform + public: void SetInverseBindTransform(const math::Matrix4d &_invBM); + + /// \brief Retrieve the inverse of the bind pose skeletal transform + /// \return the transform + public: math::Matrix4d InverseBindTransform() const; + + /// \brief Returns true if the node has inv bind transform. + /// \detail to keep ABI compatibility, it checks if the inv bind transform + /// is the default value of zero. + /// \return true if the node has inv bind transform + public: bool HasInvBindTransform() const; + + /// \brief Retrieve the model transform + /// \return the transform + public: math::Matrix4d ModelTransform() const; + + /// \brief Retrieve the raw transformations + /// \return an array of transformations + public: std::vector RawTransforms() const; + + /// \brief Return the raw transformations count + /// \return the count + public: unsigned int RawTransformCount() const; + + /// \brief Find a raw transformation + /// \param[in] _i the index of the transformation + /// \return the node transform. + public: NodeTransform RawTransform(const unsigned int _i) const; + + /// \brief Add a raw transform + /// \param[in] _t the transform + public: void AddRawTransform(const NodeTransform &_t); + + /// \brief Returns a copy of the array of transformations. + /// \return the array of transform (These are the same as the raw trans) + public: std::vector Transforms() const; + + /// \brief Private data pointer + private: SkeletonNodePrivate *data; + }; + + typedef std::map SkeletonNodeMap; + } +} +#endif diff --git a/graphics/include/gz/common/SubMesh.hh b/graphics/include/gz/common/SubMesh.hh new file mode 100644 index 000000000..8ceb3b3c3 --- /dev/null +++ b/graphics/include/gz/common/SubMesh.hh @@ -0,0 +1,425 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_SUBMESH_HH_ +#define GZ_COMMON_SUBMESH_HH_ + +#include +#include +#include + +#include +#include + +#include +#include +#include + +namespace ignition +{ + namespace common + { + class SubMeshPrivate; + class Material; + class NodeAssignment; + + /// \brief A child mesh + class IGNITION_COMMON_GRAPHICS_VISIBLE SubMesh + { + /// \brief An enumeration of the geometric mesh primitives + public: enum PrimitiveType + { + /// \brief Point. 1 vertex per point + POINTS, + /// \brief Line. 2 vertices per line + LINES, + /// \brief Connected lines. 2 vertices for the first line and + /// every vertex specified afterwards creates a new line. + LINESTRIPS, + /// \brief Triangle type. 3 vertices per triangle. + TRIANGLES, + /// \brief Connected triangle in fan shape. 3 vertices for + /// the first triangle and every vertex specified afterwards + /// creates a new triangle. + TRIFANS, + /// \brief Connected triangle. 3 vertices for the first + /// triangle and every vertex specified afterwards creates a + /// new triangle. + TRISTRIPS + }; + + /// \brief Constructor + public: SubMesh(); + + /// \brief Constructor + /// \param _name Name of the submesh. + public: explicit SubMesh(const std::string &_name); + + /// \brief Copy Constructor + /// \brief _other Other mesh object + public: SubMesh(const SubMesh &_other); + + /// \brief Destructor + public: virtual ~SubMesh(); + + /// \brief Set the name of this mesh + /// \param[in] _n The name to set + public: void SetName(const std::string &_name); + + /// \brief Get the name of this mesh + /// \return The name + public: std::string Name() const; + + /// \brief Set the primitive type + /// \param[in] _type The primitive type + public: void SetPrimitiveType(PrimitiveType _type); + + /// \brief Get the primitive type + /// \return The primitive type + public: PrimitiveType SubMeshPrimitiveType() const; + + /// \brief Add an index to the mesh + /// \param[in] _index The new vertex index + public: void AddIndex(const unsigned int _index); + + /// \brief Add a vertex to the mesh + /// \param[in] _v The new position + public: void AddVertex(const gz::math::Vector3d &_v); + + /// \brief Add a vertex to the mesh + /// \param[in] _x Position along x + /// \param[in] _y Position along y + /// \param[in] _z Position along z + public: void AddVertex(const double _x, const double _y, const double _z); + + /// \brief Add a normal to the mesh + /// \param[in] _n The normal + public: void AddNormal(const gz::math::Vector3d &_n); + + /// \brief Add a normal to the mesh + /// \param[in] _x Position along x + /// \param[in] _y Position along y + /// \param[in] _z Position along z + public: void AddNormal(const double _x, const double _y, const double _z); + + /// \brief Add a texture coord to the mesh. If multiple texture + /// coordinate sets exist, this function adds it to the first texture + /// coordinate set in the submesh. If no previous texture coordinates + /// exist, it is added to set 0. + /// \param[in] _u Position along u + /// \param[in] _v Position along v + /// \sa AddTexCoordBySet + public: void AddTexCoord(const double _u, const double _v); + + /// \brief Add a texture coordinate to the mesh. If multiple texture + /// coordinate sets exist, this function adds it to the first texture + /// coordinate set in the submesh. If no previous texture coordinates + /// exist, it is added to set 0. + /// \param[in] _uv The texture coordinate + /// \sa AddTexCoordBySet + public: void AddTexCoord(const gz::math::Vector2d &_uv); + + /// \brief Add a texture coord to a texture coordinate set of the mesh + /// \param[in] _u Position along u + /// \param[in] _v Position along v + /// \param[in] _setIndex Texture coordinate set index + public: void AddTexCoordBySet(double _u, double _v, + unsigned int _setIndex); + + /// \brief Add a texture coord to a texture coordinate set of the mesh + /// \param[in] _u Position along u + /// \param[in] _v Position along v + /// \param[in] _setIndex Texture coordinate set index + public: void AddTexCoordBySet(const gz::math::Vector2d &_uv, + unsigned int _setIndex); + + /// \brief Add a vertex - skeleton node assignment + /// \param[in] _vertex The vertex index + /// \param[in] _node The node index + /// \param[in] _weight The weight (between 0 and 1) + public: void AddNodeAssignment(const unsigned int _vertex, + const unsigned int _node, + const float _weight); + /// \brief Get a vertex + /// \param[in] _index Index of the vertex + /// \return Coordinates of the vertex or gz::math::Vector3d::Zero + /// if the index is out of bounds. + /// \sa bool HasVertex(const unsigned int) const + public: gz::math::Vector3d Vertex(const unsigned int _index) const; + + /// \brief Set a vertex + /// \param[in] _index Index of the vertex + /// \param[in] _v The new vertex coordinate + public: void SetVertex(const unsigned int _index, + const gz::math::Vector3d &_v); + + /// \brief Get a normal + /// \param[in] _index The normal index + /// \return The normal direction or gz::math::Vector3d::Zero + /// if index is out of bounds. + /// \sa bool HasNormal(const unsigned int _index); + public: gz::math::Vector3d Normal(const unsigned int _index) const; + + /// \brief Set a normal + /// \param[in] _index Index of the normal that will be set. + /// \param[in] _n The new normal direction + public: void SetNormal(const unsigned int _index, + const gz::math::Vector3d &_n); + + /// \brief Get a texture coordinate + /// \param[in] _index the texture index + /// \return The texture coordinate or gz::math::Vector2d::Zero + /// if index is out of bounds. + /// \sa bool HasTexCoord(const unsigned int _index) const + public: gz::math::Vector2d TexCoord( + const unsigned int _index) const; + + /// \brief Get a texture coordinate for a texture coordinate set + /// \param[in] _index the texture index + /// \return The texture coordinate or gz::math::Vector2d::Zero + /// if index is out of bounds. + /// \param[in] _setIndex Texture coordinate set index + /// \sa bool HasTexCoordBySet(unsigned int _index, unsigned int _setIndex) + /// const + public: gz::math::Vector2d TexCoordBySet( + unsigned int _index, + unsigned int _setIndex) const; + + /// \brief Set a texture coordinate. If multiple texture + /// coordinate sets exist, this function sets the texture + /// coordinate in the first texture coordinate set in the submesh. + /// \param[in] _index Index of the texture coordinate that will be set. + /// \param[in] _uv The new texture coordinate + /// \sa SetTexCoordBySet + public: void SetTexCoord(const unsigned int _index, + const gz::math::Vector2d &_uv); + + /// \brief Set a texture coordinate for a texture coordinate set + /// \param[in] _index Index of the texture coordinate that will be set. + /// \param[in] _uv The new texture coordinate + /// \param[in] _setIndex Texture coordinate set index + public: void SetTexCoordBySet(unsigned int _index, + const gz::math::Vector2d &_uv, + unsigned int _setIdex); + + /// \brief Get an index value from the index array + /// \param[in] _index Array index. + /// \return The index, or -1 if the _index is out of bounds. + public: int Index(const unsigned int _index) const; + + /// \brief Set an index + /// \param[in] _index Index of the indices + /// \param[in] _i The new index value to set to + public: void SetIndex(const unsigned int _index, + const unsigned int _i); + + /// \brief Get a vertex - skeleton node assignment + /// \param[in] _index The index of the assignment + /// \return The skeleton node assignment, or a + /// default constructed skeleton node assignment when _index is + /// invalid. + /// \sa bool HasNodeAssignment(const unsigned int _index) const; + public: NodeAssignment NodeAssignmentByIndex( + const unsigned int _index) const; + + /// \brief Get the maximum X, Y, Z values from all the vertices + /// \return Max X,Y,Z values from all vertices in submesh + public: gz::math::Vector3d Max() const; + + /// \brief Get the minimum X, Y, Z values from all the vertices + /// \return Min X,Y,Z values from all vertices in submesh + public: gz::math::Vector3d Min() const; + + /// \brief Get the number of vertices + /// \return The number of vertices. + public: unsigned int VertexCount() const; + + /// \brief Return the number of normals + /// \return The number of normals. + public: unsigned int NormalCount() const; + + /// \brief Return the number of indices + /// \return The number of indices. + public: unsigned int IndexCount() const; + + /// \brief Return the number of texture coordinates. If multiple + /// texture coordinate sets exist, this function checks the first + /// texture coordinate set in the submesh, which by default is set 0, + /// unless AddTexCoordBySet is called with a different set index number + /// the first time a texture coordinate is added. + /// \return The number of texture coordinates. + /// \sa TexCoordCountBySet + public: unsigned int TexCoordCount() const; + + /// \brief Return the number of texture coordinates for a texture + /// coordinate set + /// \param[in] _setIndex Texture coordinate set index + /// \return The number of texture coordinates. + public: unsigned int TexCoordCountBySet(unsigned int _setIndex) const; + + /// \brief Return the number of texture coordinate sets + /// \return The number of texture coordinates sets. + public: unsigned int TexCoordSetCount() const; + + /// \brief Get the number of vertex-skeleton node assignments + /// \return The number of vertex-skeleton node assignments + public: unsigned int NodeAssignmentsCount() const; + + /// \brief Get the highest value in the index array. + /// \return The highest index value. + public: unsigned int MaxIndex() const; + + /// \brief Set the material index. Relates to the parent mesh material + /// list. + /// \param[in] _index Index to set the material to. + public: void SetMaterialIndex(const unsigned int _index); + + /// \brief Get the material index + /// \return The assigned material index. + public: unsigned int MaterialIndex() const; + + /// \brief Return true if this submesh has the vertex + /// \param[in] _v Vertex coordinate + /// \return Return true if this submesh has the vertex + public: bool HasVertex(const gz::math::Vector3d &_v) const; + + /// \brief Return true if this submesh has the vertex with the given + /// index + /// \param[in] _index Vertex index + /// \return Return true if this submesh has the vertex with the given + /// _index. + public: bool HasVertex(const unsigned int _index) const; + + /// \brief Return true if this submesh has the normal with the given + /// index + /// \param[in] _index Normal index + /// \return Return true if this submesh has the normal with the given + /// _index. + public: bool HasNormal(const unsigned int _index) const; + + /// \brief Return true if this submesh has the texture coordinate with + /// the given index. If multiple texture coordinate sets exist, this + /// function checks the first texture coordinate set in the submesh, + /// which by default is set 0 unless AddTexCoordBySet is called with + /// a different set index number the first time a texture coordinate is + /// added. + /// \param[in] _index Texture coordinate index + /// \return Return true if this submesh has the texture coordinate with + /// the given _index. + /// \sa HasTexCoordBySet + public: bool HasTexCoord(const unsigned int _index) const; + + /// \brief Return true if this submesh has the texture coordinate with + /// the given index in a texture coordinate set + /// \param[in] _index Texture coordinate index + /// \param[in] _setIndex Texture coordinate set index + /// \return Return true if this submesh has the texture coordinate with + /// the given _index. + public: bool HasTexCoordBySet(unsigned int _index, unsigned int _setIndex) + const; + + /// \brief Return true if this submesh has the node assignment with + /// the given index + /// \param[in] _index Node assignment index + /// \return Return true if this submesh has the node assignment with + /// the given _index. + public: bool HasNodeAssignment(const unsigned int _index) const; + + /// \brief Get the index of the vertex + /// \param[in] _v Vertex to check + /// \return Index of the vertex that matches _v. + public: int IndexOfVertex(const gz::math::Vector3d &_v) const; + + /// \brief Put all the data into flat arrays + /// \param[in] _verArr The vertex array to be filled. + /// \param[in] _indexndArr The index array to be filled. + public: void FillArrays(double **_vertArr, int **_indexndArr) const; + + /// \brief Recalculate all the normals. + public: void RecalculateNormals(); + + /// \brief Generate texture coordinates using spherical projection + /// from center + /// \param[in] _center Center of the projection. + public: void GenSphericalTexCoord( + const gz::math::Vector3d &_center); + + /// \brief Generate texture coordinates for a texture coordinate set + /// using spherical projection from center + /// \param[in] _center Center of the projection. + /// \param[in] _setIndex Texture coordinate set index + public: void GenSphericalTexCoordBySet( + const gz::math::Vector3d &_center, + unsigned int _setIndex); + + /// \brief Scale all vertices by _factor + /// \param[in] _factor Scaling factor + public: void Scale(const gz::math::Vector3d &_factor); + + /// \brief Scale all vertices by _factor + /// \param[in] _factor Scaling factor + public: void Scale(const double &_factor); + + /// \brief Move the center of the submesh to the given coordinate. This + /// will move all the vertices. + /// \param[in] _center Location of the mesh center. + public: void Center(const gz::math::Vector3d &_center = + gz::math::Vector3d::Zero); + + /// \brief Move all vertices by _vec. + /// \param[in] _vec Amount to translate vertices. + public: void Translate(const gz::math::Vector3d &_vec); + + /// \brief Compute the volume of this submesh. The primitive type + /// must be TRIANGLES. + /// + /// This function utilizes the mesh volume formula from + /// "Efficient feature extraction for 2d/3d objects in mesh + /// representation" by Cha Zhang and Tsuhan Chen. Link: + /// http://chenlab.ece.cornell.edu/Publication/Cha/icip01_Cha.pdf. + /// The formula does not check for a closed (water tight) mesh. + /// + /// \return The submesh's volume. The volume can be zero if + /// the primitive type is not TRIANGLES, or there are no triangles. + public: double Volume() const; + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief Private data pointer. + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + + /// \brief Vertex to node weighted assignement for skeleton animation + /// visualization + class IGNITION_COMMON_GRAPHICS_VISIBLE NodeAssignment + { + /// \brief Constructor. + public: NodeAssignment(); + + /// \brief Index of the vertex + public: unsigned int vertexIndex; + + /// \brief Node (or bone) index + public: unsigned int nodeIndex; + + /// \brief The weight (between 0 and 1). This determines how much the + /// node (bone) affects the vertex in animation. + public: float weight; + }; + } +} + +#endif diff --git a/graphics/include/gz/common/graphics/Types.hh b/graphics/include/gz/common/graphics/Types.hh new file mode 100644 index 000000000..f1202d2ea --- /dev/null +++ b/graphics/include/gz/common/graphics/Types.hh @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2018 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +#ifndef GZ_COMMON_GRAPHICS_TYPES_HH_ +#define GZ_COMMON_GRAPHICS_TYPES_HH_ + +#include + +// This header contains forward declarations for some graphics types +namespace ignition +{ + namespace common + { + class Material; + class Mesh; + class Skeleton; + class SubMesh; + + /// \def MaterialPtr + /// \brief Shared pointer to a Material object + using MaterialPtr = std::shared_ptr; + + /// \def MeshPtr + /// \brief Standrd shared pointer to a Mesh object + using MeshPtr = std::shared_ptr; + + /// \def SubMeshPtr + /// \brief Shared pointer to a SubMesh object + using SubMeshPtr = std::shared_ptr; + + /// \def SkeletonPtr + /// \brief Shared pointer to a Skeleton object + using SkeletonPtr = std::shared_ptr; + } +} + +#endif diff --git a/graphics/include/ignition/common/Animation.hh b/graphics/include/ignition/common/Animation.hh index c0843519f..30f8460f1 100644 --- a/graphics/include/ignition/common/Animation.hh +++ b/graphics/include/ignition/common/Animation.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,280 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_ANIMATION_HH_ -#define IGNITION_COMMON_ANIMATION_HH_ + */ -#include -#include -#include - -#include -#include -#include - -#include - -namespace ignition -{ - namespace common - { - class KeyFrame; - class PoseKeyFrame; - class NumericKeyFrame; - class TrajectoryInfoPrivate; - - /// \class Animation Animation.hh ignition/common/Animation.hh - /// \brief Manages an animation, which is a collection of keyframes and - /// the ability to interpolate between the keyframes - class IGNITION_COMMON_GRAPHICS_VISIBLE Animation - { - /// \brief Constructor - /// \param[in] _name Name of the animation, should be unique - /// \param[in] _length Duration of the animation in seconds - /// \param[in] _loop Set to true if the animation should repeat - public: Animation(const std::string &_name, - const double _length, const bool _loop); - - /// \brief Destructor - public: virtual ~Animation(); - - /// \brief Return the duration of the animation - /// \return Duration of the animation in seconds - public: double Length() const; - - /// \brief Set the duration of the animation - /// \param[in] _len The length of the animation in seconds - public: void Length(const double _len); - - /// \brief Set the current time position of the animation - /// \param[in] _time The time position in seconds - public: void Time(const double _time); - - /// \brief Add time to the animation - /// \param[in] _time The amount of time to add in seconds - public: void AddTime(const double _time); - - /// \brief Return the current time position - /// \return The time position in seconds - public: double Time() const; - - /// \brief Return the interpolateX value - /// \return The interpolateX value - public: bool InterpolateX() const; - - /// \brief Set the interpolateX value - /// \param[in] _interpolateX The interpolateX value - public: void SetInterpolateX(const bool _interpolateX); - - /// \brief Return the number of key frames in the animation - /// \return The number of keyframes - public: unsigned int KeyFrameCount() const; - - /// \brief Get a key frame using an index value - /// \param[in] _index The index of the key frame - /// \return A pointer the keyframe, NULL if the _index is invalid - public: common::KeyFrame *KeyFrame(const unsigned int _index) const; - - /// \brief Get the two key frames that bound a time value - /// \param[in] _time The time in seconds - /// \param[out] _kf1 Lower bound keyframe that is returned - /// \param[out] _kf2 Upper bound keyframe that is returned - /// \param[out] _firstKeyIndex Index of the lower bound key frame - /// \return The time between the two keyframe - protected: double KeyFramesAtTime( - double _time, common::KeyFrame **_kf1, - common::KeyFrame **_kf2, - unsigned int &_firstKeyIndex) const; - -#ifdef _WIN32 -// Disable warning C4251 which is triggered by -// std::unique_ptr -#pragma warning(push) -#pragma warning(disable: 4251) -#endif - - /// \brief animation name - protected: std::string name; - - /// \brief animation duration - protected: double length; - - /// \brief current time position - protected: double timePos; - - /// \brief determines if the interpolation splines need building - protected: mutable bool build; - - /// \brief true if animation repeats - protected: bool loop; - - /// \brief array of keyframe type alias - protected: typedef std::vector KeyFrame_V; - - /// \brief array of key frames - protected: KeyFrame_V keyFrames; -#ifdef _WIN32 -#pragma warning(pop) -#endif - }; - - /// \brief A pose animation. - class IGNITION_COMMON_GRAPHICS_VISIBLE PoseAnimation : public Animation - { - /// \brief Constructor - /// \param[in] _name String name of the animation. This should be unique. - /// \param[in] _length Length of the animation in seconds - /// \param[in] _loop True == loop the animation - public: PoseAnimation(const std::string &_name, - const double _length, const bool _loop); - - /// \brief Destructor - public: virtual ~PoseAnimation(); - - /// \brief Create a pose keyframe at the given time - /// \param[in] _time Time at which to create the keyframe - /// \return Pointer to the new keyframe - public: PoseKeyFrame *CreateKeyFrame(const double _time); - - /// \brief Get a keyframe using the animation's current time. - /// \param[out] _kf PoseKeyFrame reference to hold the interpolated result - public: void InterpolatedKeyFrame(PoseKeyFrame &_kf) const; - - /// \brief Get a keyframe using a passed in time. - /// \param[in] _time Time in seconds - /// \param[out] _kf PoseKeyFrame reference to hold the interpolated result - protected: void InterpolatedKeyFrame(const double _time, - PoseKeyFrame &_kf) const; - - /// \brief Update the pose splines - protected: void BuildInterpolationSplines() const; - - /// \brief smooth interpolation for position - private: mutable math::Spline *positionSpline; - - /// \brief smooth interpolation for rotation - private: mutable math::RotationSpline *rotationSpline; - }; - - /// \brief A numeric animation. - class IGNITION_COMMON_GRAPHICS_VISIBLE NumericAnimation : public Animation - { - /// \brief Constructor - /// \param[in] _name String name of the animation. This should be unique. - /// \param[in] _length Length of the animation in seconds - /// \param[in] _loop True == loop the animation - public: NumericAnimation(const std::string &_name, - const double _length, const bool _loop); - - /// \brief Destructor - public: virtual ~NumericAnimation(); - - /// \brief Create a numeric keyframe at the given time - /// \param[in] _time Time at which to create the keyframe - /// \return Pointer to the new keyframe - public: NumericKeyFrame *CreateKeyFrame(const double _time); - - /// \brief Get a keyframe using the animation's current time. - /// \param[out] _kf NumericKeyFrame reference to hold the - /// interpolated result - public: void InterpolatedKeyFrame(NumericKeyFrame &_kf) const; - }; - - /// \brief Information about a trajectory for an animation (e.g., Actor) - /// This contains the keyframe information. - class IGNITION_COMMON_GRAPHICS_VISIBLE TrajectoryInfo - { - /// \brief Constructor - public: TrajectoryInfo(); - - /// \brief Copy constructor - /// \param[in] _trajInfo TrajectoryInfo to copy. - public: TrajectoryInfo(const TrajectoryInfo &_trajInfo); - - /// \brief Move constructor - /// \param[in] _trajInfo TrajectoryInfo to move. - public: TrajectoryInfo(TrajectoryInfo &&_trajInfo) noexcept; - - /// \brief Destructor - public: ~TrajectoryInfo(); - - /// \brief Assignment operator. - /// \param[in] _trajInfo The TrajectoryInfo to set values from. - /// \return *this - public: TrajectoryInfo &operator=(const TrajectoryInfo &_trajInfo); - - /// \brief Copy TrajectoryInfo from a TrajectoryInfo instance. - /// \param[in] _trajInfo The TrajectoryInfo to set values from. - public: void CopyFrom(const TrajectoryInfo &_trajInfo); - - /// \brief Return the id of the trajectory - /// \return Id of the trajectory - public: unsigned int Id() const; - - /// \brief Set the id of the trajectory - /// \param[in] _id Id for the trajectory - public: void SetId(unsigned int _id); - - /// \brief Return the animation index - /// \return Index of the associated animation - public: unsigned int AnimIndex() const; - - /// \brief Set the animation index - /// \param[in] _index Animation index - /// (auto-generated according to the type) - public: void SetAnimIndex(unsigned int _index); - - /// \brief Return the duration of the trajectory. - /// \return Duration of the animation. - public: std::chrono::steady_clock::duration Duration() const; - - /// \brief Get the distance covered by the trajectory by a given time. - /// \param[in] _time Time from trajectory start to check the distance. - /// \return Distance in meters covered by the trajectory. - public: double DistanceSoFar( - const std::chrono::steady_clock::duration &_time) const; - - /// \brief Return the start time of the trajectory. - /// \return Start time of the trajectory. - public: std::chrono::steady_clock::time_point StartTime() const; - - /// \brief Set the start time of the trajectory. - /// \param[in] _startTime Trajectory start time. - public: void SetStartTime( - const std::chrono::steady_clock::time_point &_startTime); - - /// \brief Return the end time of the trajectory - /// \return End time of the trajectory in seconds - public: std::chrono::steady_clock::time_point EndTime() const; - - /// \brief Set the end time of the trajectory. - /// \param[in] _endTime Trajectory end time. - public: void SetEndTime( - const std::chrono::steady_clock::time_point &_endTime); - - /// \brief Return whether the trajectory is translated - /// \return True if the trajectory is translated - public: bool Translated() const; - - /// \brief Set whether the trajectory is translated - /// \param[in] _translated True if the trajectory is translated - public: void SetTranslated(bool _translated); - - /// \brief Return the waypoints in the trajectory - /// \return Waypoints represented in pose animation format - public: common::PoseAnimation *Waypoints() const; - - /// \brief Load all waypoints in the trajectory - /// \param[in] _waypoints Map of waypoints, where the key is the absolute - /// time of the waypoint and the value is the pose. - public: void SetWaypoints( - std::map - _waypoints); - - /// \brief Private data pointer. - private: TrajectoryInfoPrivate *dataPtr{nullptr}; - }; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/BVHLoader.hh b/graphics/include/ignition/common/BVHLoader.hh index b8c10e997..25808919a 100644 --- a/graphics/include/ignition/common/BVHLoader.hh +++ b/graphics/include/ignition/common/BVHLoader.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,40 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_BVHLOADER_HH_ -#define IGNITION_COMMON_BVHLOADER_HH_ + */ -#include -#include - -#include -#include - -namespace ignition -{ - namespace common - { - class Skeleton; - - /// \class BVHLoader BVHLoader.hh ignition/common/BVHLoader.hh - /// \brief Handles loading BVH animation files - class IGNITION_COMMON_GRAPHICS_VISIBLE BVHLoader - { - /// \brief Constructor - public: BVHLoader(); - - /// \brief Desutrctor - public: ~BVHLoader(); - - /// \brief Load a BVH file - /// \param[in] _filename BVH file to load - /// \param[in] _scale Scaling factor to apply to the skeleton - /// \return A pointer to a new Skeleton - public: std::unique_ptr Load( - const std::string &_filename, const double _scale); - }; - } -} - -#endif +#include +#include diff --git a/graphics/include/ignition/common/ColladaExporter.hh b/graphics/include/ignition/common/ColladaExporter.hh index 623c85a4a..75dda2a08 100644 --- a/graphics/include/ignition/common/ColladaExporter.hh +++ b/graphics/include/ignition/common/ColladaExporter.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,53 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_COLLADAEXPORTER_HH_ -#define IGNITION_COMMON_COLLADAEXPORTER_HH_ + */ -#include -#include -#include - -#include -#include -#include - -#include - -namespace ignition -{ - namespace common - { - class ColladaExporterPrivate; - - /// \brief Class used to export Collada mesh files - class IGNITION_COMMON_GRAPHICS_VISIBLE ColladaExporter : public MeshExporter - { - /// \brief Constructor - public: ColladaExporter(); - - /// \brief Destructor - public: virtual ~ColladaExporter(); - - /// \brief Export a mesh to a file - /// \param[in] _mesh Pointer to the mesh to be exported - /// \param[in] _filename Exported file's path and name - /// \param[in] _exportTextures True to export texture images to - /// '../materials/textures' folder - public: virtual void Export(const Mesh *_mesh, - const std::string &_filename, bool _exportTextures = false); - - public: void Export(const Mesh *_mesh, - const std::string &_filename, bool _exportTextures, - const std::vector &_submeshToMatrix); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \internal - /// \brief Pointer to private data. - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/ColladaLoader.hh b/graphics/include/ignition/common/ColladaLoader.hh index 144fba0f5..d01b3b580 100644 --- a/graphics/include/ignition/common/ColladaLoader.hh +++ b/graphics/include/ignition/common/ColladaLoader.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,40 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_COLLADALOADER_HH_ -#define IGNITION_COMMON_COLLADALOADER_HH_ + */ -#include -#include -#include - -namespace ignition -{ - namespace common - { - // Forward declare private data class - class ColladaLoaderPrivate; - - /// \class ColladaLoader ColladaLoader.hh ignition/common/ColladaLoader.hh - /// \brief Class used to load Collada mesh files - class IGNITION_COMMON_GRAPHICS_VISIBLE ColladaLoader : public MeshLoader - { - /// \brief Constructor - public: ColladaLoader(); - - /// \brief Destructor - public: virtual ~ColladaLoader(); - - /// \brief Load a mesh - /// \param[in] _filename Collada file to load - /// \return Pointer to a new Mesh - public: virtual Mesh *Load(const std::string &_filename); - - /// \internal - /// \brief Pointer to private data. - private: ColladaLoaderPrivate *dataPtr; - }; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/Dem.hh b/graphics/include/ignition/common/Dem.hh index 77ba3cf5b..6fb9de90d 100644 --- a/graphics/include/ignition/common/Dem.hh +++ b/graphics/include/ignition/common/Dem.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,131 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_DEM_HH_ -#define IGNITION_COMMON_DEM_HH_ + */ -#include -#include -#include - -#include -#include - -#ifdef HAVE_GDAL -# include -# include - -# include - -namespace ignition -{ - namespace common - { - class DemPrivate; - - /// \class DEM DEM.hh common/common.hh - /// \brief Encapsulates a DEM (Digital Elevation Model) file. - class IGNITION_COMMON_GRAPHICS_VISIBLE Dem : public HeightmapData - { - /// \brief Constructor. - public: Dem(); - - /// \brief Destructor. - public: virtual ~Dem(); - - /// \brief Load a DEM file. - /// \param[in] _filename the path to the terrain file. - /// \return 0 when the operation succeeds to open a file. - public: int Load(const std::string &_filename = ""); - - /// \brief Get the elevation of a terrain's point in meters. - /// \param[in] _x X coordinate of the terrain. - /// \param[in] _y Y coordinate of the terrain. - /// \return Terrain's elevation at (x,y) in meters. - public: double Elevation(double _x, double _y); - - /// \brief Get the terrain's minimum elevation in meters. - /// \return The minimum elevation (meters). - public: float MinElevation() const; - - /// \brief Get the terrain's maximum elevation in meters. - /// \return The maximum elevation (meters). - public: float MaxElevation() const; - - /// \brief Get the georeferenced coordinates (lat, long) of the terrain's - /// origin in WGS84. - /// \param[out] _latitude Georeferenced latitude. - /// \param[out] _longitude Georeferenced longitude. - public: void GeoReferenceOrigin(ignition::math::Angle &_latitude, - ignition::math::Angle &_longitude) const; - - /// \brief Get the terrain's height. Due to the Ogre constrains, this - /// value will be a power of two plus one. The value returned might be - /// different that the original DEM height because Data() adds the - /// padding if necessary. - /// \return The terrain's height (points) satisfying the ogre constrains - /// (squared terrain with a height value that must be a power of two plus - /// one). - public: unsigned int Height() const; - - /// \brief Get the terrain's width. Due to the Ogre constrains, this - /// value will be a power of two plus one. The value returned might be - /// different that the original DEM width because GetData() adds the - /// padding if necessary. - /// \return The terrain's width (points) satisfying the ogre constrains - /// (squared terrain with a width value that must be a power of two plus - /// one). - public: unsigned int Width() const; - - /// \brief Get the real world width in meters. - /// \return Terrain's real world width in meters. - public: double WorldWidth() const; - - /// \brief Get the real world height in meters. - /// \return Terrain's real world height in meters. - public: double WorldHeight() const; - - /// \brief Create a lookup table of the terrain's height. - /// \param[in] _subsampling Multiplier used to increase the resolution. - /// Ex: A subsampling of 2 in a terrain of 129x129 means that the height - /// vector will be 257 * 257. - /// \param[in] _vertSize Number of points per row. - /// \param[in] _size Real dimmensions of the terrain in meters. - /// \param[in] _scale Vector3 used to scale the height. - /// \param[in] _flipY If true, it inverts the order in which the vector - /// is filled. - /// \param[out] _heights Vector containing the terrain heights. - public: void FillHeightMap(const int _subSampling, - const unsigned int _vertSize, - const ignition::math::Vector3d &_size, - const ignition::math::Vector3d &_scale, - const bool _flipY, - std::vector &_heights); - - /// \brief Get the georeferenced coordinates (lat, long) of a terrain's - /// pixel in WGS84. - /// \param[in] _x X coordinate of the terrain. - /// \param[in] _y Y coordinate of the terrain. - /// \param[out] _latitude Georeferenced latitude. - /// \param[out] _longitude Georeferenced longitude. - private: void GeoReference(double _x, double _y, - ignition::math::Angle &_latitude, - ignition::math::Angle &_longitude) const; - - /// \brief Get the terrain file as a data array. Due to the Ogre - /// constrains, the data might be stored in a bigger vector representing - /// a squared terrain with padding. - /// \return 0 when the operation succeeds to open a file. - private: int LoadData(); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// internal - /// \brief Pointer to the private data. - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} -#endif -#endif +#include +#include diff --git a/graphics/include/ignition/common/GTSMeshUtils.hh b/graphics/include/ignition/common/GTSMeshUtils.hh index 7dc3a0d19..c495afbf8 100644 --- a/graphics/include/ignition/common/GTSMeshUtils.hh +++ b/graphics/include/ignition/common/GTSMeshUtils.hh @@ -1,11 +1,11 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,49 +15,5 @@ * */ -#ifndef IGNITION_COMMON_GTSMESHUTILS_HH_ -#define IGNITION_COMMON_GTSMESHUTILS_HH_ - -#include - -#include -#include - - -struct _GtsSurface; -typedef _GtsSurface GtsSurface; - -namespace ignition -{ - namespace common - { - class SubMesh; - - /// \class GTSMeshUtils GTSMeshUtils.hh ignition/common/GTSMeshUtils.hh - /// \brief Creates GTS utilities for meshes - class IGNITION_COMMON_GRAPHICS_VISIBLE GTSMeshUtils - { - /// \brief Perform delaunay triangulation on input vertices. - /// \param[in] _vertices A list of all vertices - /// \param[in] _edges A list of edges. Each edge is made of 2 vertex - /// indices from _vertices - /// \param[out] _submesh A submesh that will be populated with the - /// resulting triangles. - /// \return True on success. - public: static bool DelaunayTriangulation( - const std::vector &_vertices, - const std::vector &_edges, - SubMesh *_submesh); - - /// \brief Perform delaunay triangulation on input vertices. - /// \param[in] _vertices A list of all vertices - /// \param[in] _edges A list of edges. Each edge is made of 2 vertex - /// indices from _vertices - /// \return Triangulated GTS surface. - private: static GtsSurface *DelaunayTriangulation( - const std::vector &_vertices, - const std::vector &_edges); - }; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/HeightmapData.hh b/graphics/include/ignition/common/HeightmapData.hh index 22eeb4945..6b85b668b 100644 --- a/graphics/include/ignition/common/HeightmapData.hh +++ b/graphics/include/ignition/common/HeightmapData.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,51 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_HEIGHTMAPDATA_HH_ -#define IGNITION_COMMON_HEIGHTMAPDATA_HH_ + */ -#include -#include -#include - -namespace ignition -{ - namespace common - { - /// \brief Encapsulates a generic heightmap data file. - class IGNITION_COMMON_GRAPHICS_VISIBLE HeightmapData - { - /// \brief Destructor. - public: virtual ~HeightmapData() = default; - - /// \brief Create a lookup table of the terrain's height. - /// \param[in] _subsampling Multiplier used to increase the resolution. - /// Ex: A subsampling of 2 in a terrain of 129x129 means that the height - /// vector will be 257 * 257. - /// \param[in] _vertSize Number of points per row. - /// \param[in] _size Real dimmensions of the terrain. - /// \param[in] _scale Vector3 used to scale the height. - /// \param[in] _flipY If true, it inverts the order in which the vector - /// is filled. - /// \param[out] _heights Vector containing the terrain heights. - public: virtual void FillHeightMap(int _subSampling, - unsigned int _vertSize, const ignition::math::Vector3d &_size, - const ignition::math::Vector3d &_scale, bool _flipY, - std::vector &_heights) = 0; - - /// \brief Get the terrain's height. - /// \return The terrain's height. - public: virtual unsigned int Height() const = 0; - - /// \brief Get the terrain's width. - /// \return The terrain's width. - public: virtual unsigned int Width() const = 0; - - /// \brief Get the maximum terrain's elevation. - /// \return The maximum terrain's elevation. - public: virtual float MaxElevation() const = 0; - }; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/Image.hh b/graphics/include/ignition/common/Image.hh index b78d01b51..82a908de0 100644 --- a/graphics/include/ignition/common/Image.hh +++ b/graphics/include/ignition/common/Image.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,258 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_IMAGE_HH_ -#define IGNITION_COMMON_IMAGE_HH_ + */ -#include -#include -#include -#include -#include -#include -#include - -namespace ignition -{ - namespace common - { - /// \brief Forward declaration of private data class - class ImagePrivate; - - /// \brief String names for the pixel formats. - /// \sa Image::PixelFormat. - static std::string PixelFormatNames[] = - { - "UNKNOWN_PIXEL_FORMAT", - "L_INT8", - "L_INT16", - "RGB_INT8", - "RGBA_INT8", - "BGRA_INT8", - "RGB_INT16", - "RGB_INT32", - "BGR_INT8", - "BGR_INT16", - "BGR_INT32", - "R_FLOAT16", - "RGB_FLOAT16", - "R_FLOAT32", - "RGB_FLOAT32", - "BAYER_RGGB8", - "BAYER_RGGR8", - "BAYER_GBRG8", - "BAYER_GRBG8", - "BAYER_BGGR8" - }; - - /// \class Image Image.hh ignition/common/common.hh - /// \brief Encapsulates an image - class IGNITION_COMMON_GRAPHICS_VISIBLE Image - { - /// \brief Pixel formats enumeration - public: enum PixelFormatType - { - UNKNOWN_PIXEL_FORMAT = 0, - L_INT8, - L_INT16, - RGB_INT8, - RGBA_INT8, - BGRA_INT8, - RGB_INT16, - RGB_INT32, - BGR_INT8, - BGR_INT16, - BGR_INT32, - R_FLOAT16, - RGB_FLOAT16, - R_FLOAT32, - RGB_FLOAT32, - BAYER_RGGB8, - BAYER_RGGR8, - BAYER_GBRG8, - BAYER_GRBG8, - PIXEL_FORMAT_COUNT, - BAYER_BGGR8 - }; - - - /// \brief Convert a string to a Image::PixelFormat. - /// \param[in] _format Pixel format string. \sa Image::PixelFormatNames - /// \return Image::PixelFormat - public: static Image::PixelFormatType ConvertPixelFormat( - const std::string &_format); - - /// \brief Constructor - /// \param[in] _filename the path to the image - public: explicit Image(const std::string &_filename = ""); - - /// \brief Destructor - public: virtual ~Image(); - - /// \brief Load an image. Return 0 on success - /// \param[in] _filename the path to the image file - /// \return 0 when the operation succeeds to open a file or -1 when fails. - public: int Load(const std::string &_filename); - - /// \brief Save the image in PNG format - /// \param[in] _filename The name of the saved image - public: void SavePNG(const std::string &_filename); - - /// \brief Save the image in PNG format - /// \param[in] _filename The name of the saved image - public: void SavePNGToBuffer(std::vector &_buffer); - - /// \brief Set the image from raw data - /// \param[in] _data Pointer to the raw image data - /// \param[in] _width Width in pixels - /// \param[in] _height Height in pixels - /// \param[in] _format Pixel format of the provided data - public: void SetFromData(const unsigned char *_data, - unsigned int _width, - unsigned int _height, - Image::PixelFormatType _format); - - /// \brief Get the image as a data array - /// \param[out] _data Pointer to a NULL array of char. - /// \param[out] _count The resulting data array size - public: void Data(unsigned char **_data, - unsigned int &_count) const; - - /// \brief Get only the RGB data from the image. This will drop the - /// alpha channel if one is present. - /// \param[out] _data Pointer to a NULL array of char. - /// \param[out] _count The resulting data array size - public: void RGBData(unsigned char **_data, - unsigned int &_count) const; - - /// \brief Get the width - /// \return The image width - public: unsigned int Width() const; - - /// \brief Get the height - /// \return The image height - public: unsigned int Height() const; - - /// \brief Get the size of one pixel in bits - /// \return The BPP of the image - public: unsigned int BPP() const; - - // \brief Get the size of a row of pixel - /// \return The pitch of the image - public: int Pitch() const; - - /// \brief Get the full filename of the image - /// \return The filename used to load the image - public: std::string Filename() const; - - /// \brief Get the pixel format - /// \return PixelFormat - public: PixelFormatType PixelFormat() const; - - /// \brief Get a pixel color value - /// \param[in] _x Column location in the image - /// \param[in] _y Row location in the image - /// \return The color of the given pixel - public: math::Color Pixel(const unsigned int _x, - const unsigned int _y) const; - - /// \brief Get the average color - /// \return The average color - public: math::Color AvgColor(); - - /// \brief Get the max color - /// \return The max color - public: math::Color MaxColor() const; - - /// \brief Rescale the image - /// \param[in] _width New image width - /// \param[in] _height New image height - public: void Rescale(const int _width, const int _height); - - /// \brief Returns whether this is a valid image - /// \return true if image has a bitmap - public: bool Valid() const; - - /// \brief Convert a single channel image data buffer into an RGB image. - /// During the conversion, the input image data are normalized to 8 bit - /// values i.e. [0, 255]. Optionally, specify min and max values to use - /// when normalizing the input image data. For example, if min and max - /// are set to 1 and 10, a data value 2 will be normalized to: - /// (2 - 1) / (10 - 1) * 255. - /// \param[in] _data input image data buffer - /// \param[in] _width image width - /// \param[in] _height image height - /// \param[out] _output Output RGB image - /// \param[in] _min Minimum value to be used when normalizing the input - /// image data to RGB. - /// \param[in] _max Maximum value to be used when normalizing the input - /// image data to RGB. - /// \param[in] _flip True to flip the values after normalization, i.e. - /// lower values are converted to brigher pixels. - public: template - static void ConvertToRGBImage(const void *_data, - unsigned int _width, unsigned int _height, Image &_output, - T _min = std::numeric_limits::max(), - T _max = std::numeric_limits::lowest(), bool _flip = false) - { - unsigned int samples = _width * _height; - unsigned int bufferSize = samples * sizeof(T); - - auto buffer = std::vector(samples); - memcpy(buffer.data(), _data, bufferSize); - - auto outputRgbBuffer = std::vector(samples * 3); - - // use min and max values found in the data if not specified - T min = std::numeric_limits::max(); - T max = std::numeric_limits::lowest(); - if (_min > max) - { - for (unsigned int i = 0; i < samples; ++i) - { - auto v = buffer[i]; - // ignore inf values when computing min/max - // cast to float when calling isinf to avoid compile error on - // windows - if (v > max && !std::isinf(static_cast(v))) - max = v; - if (v < min && !std::isinf(static_cast(v))) - min = v; - } - } - min = math::equal(_min, std::numeric_limits::max()) ? min : _min; - max = math::equal(_max, std::numeric_limits::lowest()) ? max : _max; - - // convert to rgb image - // color is grayscale, i.e. r == b == g - double range = static_cast(max - min); - if (ignition::math::equal(range, 0.0)) - range = 1.0; - unsigned int idx = 0; - for (unsigned int j = 0; j < _height; ++j) - { - for (unsigned int i = 0; i < _width; ++i) - { - auto v = buffer[idx++]; - double t = static_cast(v - min) / range; - if (_flip) - t = 1.0 - t; - uint8_t r = static_cast(255*t); - unsigned int outIdx = j * _width * 3 + i * 3; - outputRgbBuffer[outIdx] = r; - outputRgbBuffer[outIdx + 1] = r; - outputRgbBuffer[outIdx + 2] = r; - } - } - _output.SetFromData(outputRgbBuffer.data(), _width, _height, RGB_INT8); - } - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief Private data pointer - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/ImageHeightmap.hh b/graphics/include/ignition/common/ImageHeightmap.hh index dd6cc2828..4821d1990 100644 --- a/graphics/include/ignition/common/ImageHeightmap.hh +++ b/graphics/include/ignition/common/ImageHeightmap.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,57 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_IMAGEHEIGHTMAPDATA_HH_ -#define IGNITION_COMMON_IMAGEHEIGHTMAPDATA_HH_ + */ -#include -#include -#include - -#include -#include -#include - -namespace ignition -{ - namespace common - { - /// \brief Encapsulates an image that will be interpreted as a heightmap. - class IGNITION_COMMON_GRAPHICS_VISIBLE ImageHeightmap - : public ignition::common::HeightmapData - { - /// \brief Constructor - /// \param[in] _filename the path to the image - public: ImageHeightmap(); - - /// \brief Load an image file as a heightmap. - /// \param[in] _filename the path to the image file. - /// \return True when the operation succeeds to open a file. - public: int Load(const std::string &_filename = ""); - - // Documentation inherited. - public: void FillHeightMap(int _subSampling, unsigned int _vertSize, - const ignition::math::Vector3d &_size, - const ignition::math::Vector3d &_scale, bool _flipY, - std::vector &_heights); - - /// \brief Get the full filename of the image - /// \return The filename used to load the image - public: std::string Filename() const; - - // Documentation inherited. - public: unsigned int Height() const; - - // Documentation inherited. - public: unsigned int Width() const; - - // Documentation inherited. - public: float MaxElevation() const; - - /// \brief Image containing the heightmap data. - private: ignition::common::Image img; - }; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/KeyFrame.hh b/graphics/include/ignition/common/KeyFrame.hh index e26f42dd7..4d288c097 100644 --- a/graphics/include/ignition/common/KeyFrame.hh +++ b/graphics/include/ignition/common/KeyFrame.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,100 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_KEYFRAME_HH_ -#define IGNITION_COMMON_KEYFRAME_HH_ + */ -#include -#include -#include - -namespace ignition -{ - namespace common - { - /// \class KeyFrame KeyFrame.hh ignition/common/KeyFrame.hh - /// \brief A key frame in an animation - class IGNITION_COMMON_GRAPHICS_VISIBLE KeyFrame - { - /// \brief Constructor - /// \param[in] _time Time of the keyframe in seconds - public: explicit KeyFrame(const double _time); - - /// \brief Destructor - public: virtual ~KeyFrame(); - - /// \brief Get the time of the keyframe - /// \return the time - public: double Time() const; - - /// \brief time of key frame - protected: double time; - }; - - /// \brief A keyframe for a PoseAnimation - class IGNITION_COMMON_GRAPHICS_VISIBLE PoseKeyFrame : public KeyFrame - { - /// \brief Constructor - /// \param[in] _time of the keyframe - public: explicit PoseKeyFrame(const double _time); - - /// \brief Destructor - public: virtual ~PoseKeyFrame(); - - /// \brief Set the translation for the keyframe - /// \param[in] _trans Translation amount - public: void Translation(const math::Vector3d &_trans); - - /// \brief Get the translation of the keyframe - /// \return The translation amount - public: const math::Vector3d &Translation() const; - - /// \brief Set the rotation for the keyframe - /// \param[in] _rot Rotation amount - public: void Rotation(const math::Quaterniond &_rot); - - /// \brief Get the rotation of the keyframe - /// \return The rotation amount - public: const math::Quaterniond &Rotation() const; - -#ifdef _WIN32 -// Disable warning C4251 which is triggered by -// std::unique_ptr -#pragma warning(push) -#pragma warning(disable: 4251) -#endif - /// \brief the translation vector - protected: math::Vector3d translate; - - /// \brief the rotation quaternion - protected: math::Quaterniond rotate; -#ifdef _WIN32 -#pragma warning(pop) -#endif - }; - - /// \brief A keyframe for a NumericAnimation - class IGNITION_COMMON_GRAPHICS_VISIBLE NumericKeyFrame : public KeyFrame - { - /// \brief Constructor - /// \param[in] _time Time of the keyframe - public: explicit NumericKeyFrame(const double _time); - - /// \brief Destructor - public: virtual ~NumericKeyFrame(); - - /// \brief Set the value of the keyframe - /// \param[in] _value The new value - public: void Value(const double &_value); - - /// \brief Get the value of the keyframe - /// \return the value of the keyframe - public: const double &Value() const; - - /// \brief numeric value - protected: double value; - }; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/Material.hh b/graphics/include/ignition/common/Material.hh index 179311ad8..b16efeba2 100644 --- a/graphics/include/ignition/common/Material.hh +++ b/graphics/include/ignition/common/Material.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,281 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_MATERIAL_HH_ -#define IGNITION_COMMON_MATERIAL_HH_ + */ -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace ignition -{ - namespace common - { - // Forward declare private data class - class MaterialPrivate; - - /// \brief Encapsulates description of a material - class IGNITION_COMMON_GRAPHICS_VISIBLE Material - { - /// \def Shade modes - /// \brief Enumeration of shade mode types - public: enum ShadeMode - { - /// \internal - /// \brief Indicator used to create an iterator over the - /// enum. Do not use this. - SHADE_MODE_BEGIN = 0, - - /// \brief Flat shading - FLAT = 0, - - /// \brief Gouraud shading - GOURAUD = 1, - - /// \brief Phong shading - PHONG = 2, - - /// \brief Blinn shading - BLINN = 3, - - /// \internal - /// \brief Indicator used to create an iterator over the - /// enum. Do not use this. - SHADE_MODE_END - }; - - /// \def Blend modes - /// \brief Enumeration of blend mode types - public: enum BlendMode - { - /// \internal - /// \brief Indicator used to create an iterator over the - /// enum. Do not use this. - BLEND_MODE_BEGIN = 0, - - /// \brief Add mode - ADD = 0, - - /// \brief Modulate mode - MODULATE = 1, - - /// \brief Replace mode - REPLACE = 2, - - /// \internal - /// \brief Indicator used to create an iterator over the - /// enum. Do not use this. - BLEND_MODE_END - }; - - /// \brief Constructor - public: Material(); - - /// \brief Destructor - public: ~Material(); - - /// \brief Create a material with a default color - /// \param[in] _clr Color of the material - public: explicit Material(const math::Color &_clr); - - /// \brief Get the name of the material - /// \return The name of the material - public: std::string Name() const; - - /// \brief Set a texture image - /// \param[in] _tex The name of the texture, which must be in the - /// resource path - public: void SetTextureImage(const std::string &_tex); - - /// \brief Set a texture image - /// \param[in] _tex The name of the texture - /// \param[in] _resourcePath Path which contains _tex - public: void SetTextureImage(const std::string &_tex, - const std::string &_resourcePath); - - /// \brief Get a texture image - /// \return The name of the texture image (if one exists) or an empty - /// string - public: std::string TextureImage() const; - - /// \brief Set the ambient color - /// \param[in] _clr The ambient color - public: void SetAmbient(const math::Color &_clr); - - /// \brief Get the ambient color - /// \return The ambient color - public: math::Color Ambient() const; - - /// \brief Set the diffuse color - /// \param[in] _clr The diffuse color - public: void SetDiffuse(const math::Color &_clr); - - /// \brief Get the diffuse color - /// \return The diffuse color - public: math::Color Diffuse() const; - - /// \brief Set the specular color - /// \param[in] _clr The specular color - public: void SetSpecular(const math::Color &_clr); - - /// \brief Get the specular color - /// \return The specular color - public: math::Color Specular() const; - - /// \brief Set the emissive color - /// \param[in] _clr The emissive color - public: void SetEmissive(const math::Color &_clr); - - /// \brief Get the emissive color - /// \return The emissive color - public: math::Color Emissive() const; - - /// \brief Set the transparency percentage (0..1) - /// \param[in] _t The amount of transparency (0..1) where a value of 1 - /// is fully transparent and 0 is not transparent. - public: void SetTransparency(double _t); - - /// \brief Get the transparency percentage (0..1) - /// A value of 1 is fully transparent and 0 is not transparent. - /// \return The transparency percentage - public: double Transparency() const; - - /// \brief Set the material to use the alpha channel from the textures - /// \param[in] _enabled Enable alpha channel based rendering - /// \param[in] _alpha Set the alpha threshold value - /// \param[in] _twoSided Enable two sided rendering - public: void SetAlphaFromTexture(bool _enabled, - double _alpha = 0.5, bool _twoSided = true); - - /// \brief Get the enable alpha from textures - /// \return The enable alpha value - public: bool TextureAlphaEnabled() const; - - /// \brief Get the alpha threshold - /// \return The alpha threshold value - public: double AlphaThreshold() const; - - /// \brief Get the enable two sided rendering - /// \return The enable two sided rendering value - public: bool TwoSidedEnabled() const; - - /// \brief Set the render order. The higher value will be rendered on top - /// of the other coplanar polygons. - /// \param[in] _renderOrder The render order value - public: void SetRenderOrder(float _renderOrder); - - /// \brief Get the render order - /// \return The render order value - public: float RenderOrder() const; - - /// \brief Set the shininess - /// \param[in] _t The shininess value - public: void SetShininess(double _t); - - /// \brief Get the shininess - /// \return The shininess value - public: double Shininess() const; - - /// \brief Set the blend factors. Will be interpreted as: - /// (texture * _srcFactor) + (scene_pixel * _dstFactor) - /// \param[in] _srcFactor The source factor - /// \param[in] _dstFactor The destination factor - public: void SetBlendFactors(double _srcFactor, double _dstFactor); - - /// \brief Get the blend factors - /// \param[in] _srcFactor Source factor is returned in this variable - /// \param[in] _dstFactor Destination factor is returned in this variable - public: void BlendFactors(double &_srcFactor, double &_dstFactor) const; - - /// \brief Set the blending mode - /// \param[in] _b the blend mode - public: void SetBlend(BlendMode _b); - - /// \brief Get the blending mode - /// \return the blend mode - public: BlendMode Blend() const; - - /// \brief Get the blend mode string - public: std::string BlendStr() const; - - /// \brief Get the shade mode string - public: std::string ShadeStr() const; - - /// \brief Set the shading mode - /// param[in] the shading mode - public: void SetShade(ShadeMode _b); - - /// \brief Get the shading mode - /// \return the shading mode - public: ShadeMode Shade() const; - - /// \brief Set the point size - /// \param[in] _size the size - public: void SetPointSize(double _size); - - /// \brief Get the point size - /// \return the point size - public: double PointSize() const; - - /// \brief Set depth write - /// \param[in] _value the depth write enabled state - public: void SetDepthWrite(bool _value); - - /// \brief Get depth write - /// \return the depth write enabled state - public: bool DepthWrite() const; - - /// \brief Set lighting enabled - /// \param[in] _value the lighting enabled state - public: void SetLighting(bool _value); - - /// \brief Get lighting enabled - /// \return the lighting enabled state - public: bool Lighting() const; - - /// \brief Set the Physically Based Rendering (PBR) material - /// \return The PBR material to set to. - public: void SetPbrMaterial(const Pbr &_pbr); - - /// \brief Get the Physically Based Rendering (PBR) material - /// \return Pointer to the PBR material. Null if it does not exist. - public: Pbr *PbrMaterial() const; - - /// \brief Stream insertion operator - /// param[in] _out the output stream to extract from - /// param[out] _m the material information - public: friend std::ostream &operator<<(std::ostream &_out, - const ignition::common::Material &_m) - { - _out << "Material:\n"; - _out << " Name: " << _m.Name() << "\n"; - _out << " Texture: " << _m.TextureImage() << "\n"; - _out << " Ambient: " << _m.Ambient() << "\n"; - _out << " Diffuse: " << _m.Diffuse() << "\n"; - _out << " Specular: " << _m.Specular() << "\n"; - _out << " Emissive: " << _m.Emissive() << "\n"; - _out << " Transparency: " << _m.Transparency() << "\n"; - _out << " Shininess: " << _m.Shininess() << "\n"; - _out << " Render order: " << _m.RenderOrder() << "\n"; - _out << " BlendMode: " << _m.BlendStr() << "\n"; - _out << " ShadeMode: " << _m.ShadeStr() << "\n"; - _out << " DepthWrite: " << _m.DepthWrite() << "\n"; - return _out; - } - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief destination blend factor - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/Mesh.hh b/graphics/include/ignition/common/Mesh.hh index c95430222..fec41893b 100644 --- a/graphics/include/ignition/common/Mesh.hh +++ b/graphics/include/ignition/common/Mesh.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,202 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_MESH_HH_ -#define IGNITION_COMMON_MESH_HH_ + */ -#include -#include -#include - -#include -#include - -#include -#include -#include - -namespace ignition -{ - namespace common - { - class Material; - class Skeleton; - class MeshPrivate; - - /// \class Mesh Mesh.hh ignition/common/Mesh.hh - /// \brief A 3D mesh - class IGNITION_COMMON_GRAPHICS_VISIBLE Mesh - { - /// \brief Constructor - public: Mesh(); - - /// \brief Destructor - public: virtual ~Mesh(); - - /// \brief Set the path which contains the mesh resource - /// \param[in] _path The file path - public: void SetPath(const std::string &_path); - - /// \brief Get the path which contains the mesh resource - /// \return The path to the mesh resource - public: std::string Path() const; - - /// \brief Set the name of this mesh - /// \param[in] _name The name to set - public: void SetName(const std::string &_name); - - /// \brief Get the name of this mesh - /// \return Name of the mesh. - public: std::string Name() const; - - /// \brief Get the maximun X, Y, Z values - /// \return The upper bounds of the bounding box - public: ignition::math::Vector3d Max() const; - - /// \brief Get the minimum X, Y, Z values - /// \return The lower bounds of the bounding box - public: ignition::math::Vector3d Min() const; - - /// \brief Get the number of vertices - /// \return The number of vertices - public: unsigned int VertexCount() const; - - /// \brief Get the number of normals - /// \return The number of normals - public: unsigned int NormalCount() const; - - /// \brief Get the number of indices - /// \return The number of indices - public: unsigned int IndexCount() const; - - /// \brief Get the number of texture coordinates - /// \return The number of texture coordinates - public: unsigned int TexCoordCount() const; - - /// \brief Add a submesh mesh. - /// This can be an expensive since _child is copied into this mesh. - /// \sa AddSubMesh(std::unique_ptr _child); - /// \param[in] _child the submesh - /// \return Weak pointer to the added submesh - public: std::weak_ptr AddSubMesh(const SubMesh &_child); - - /// \brief Add a submesh mesh. This transfers ownership of _child - /// to this mesh. The value of _child after this call is nullptr. - /// \param[in] _child the submesh - /// \return Weak pointer to the added submesh - public: std::weak_ptr AddSubMesh( - std::unique_ptr _child); - - /// \brief Get the number of child submeshes. - /// \return The number of submeshes. - public: unsigned int SubMeshCount() const; - - /// \brief Add a material to the mesh - /// \param[in] _mat The material to add. - /// \return Index of this material - public: int AddMaterial(const MaterialPtr &_mat); - - /// \brief Get the number of materials - /// \return The number of materials - public: unsigned int MaterialCount() const; - - /// \brief Get a material by index - /// \param[in] _index The index of the material. - /// \return The material or NULL if the index is out of bounds - public: MaterialPtr MaterialByIndex(const unsigned int _index) const; - - /// \brief Get the index of material - /// \param[in] _mat The material - /// \return The index of the material or -1 if not found, or _mat is - /// null. - public: int IndexOfMaterial(const Material *_mat) const; - - /// \brief Get a child submesh by index - /// \param[in] _index Index of the submesh - /// \return The submesh or nullptr if the index is out of bounds. - public: std::weak_ptr SubMeshByIndex( - const unsigned int _index) const; - - /// \brief Get a child submesh by name. - /// \param[in] _name Name of the submesh. - /// \return The submesh or nullptr if the _name is not found. - public: std::weak_ptr SubMeshByName( - const std::string &_name) const; - - /// \brief Put all the data into flat arrays - /// \param[out] _vertArr the vertex array - /// \param[out] _indArr the index array - public: void FillArrays(double **_vertArr, int **_indArr) const; - - /// \brief Recalculate all the normals of each face defined by three - /// indices. - public: void RecalculateNormals(); - - /// \brief Get axis-aligned bounding box in the mesh frame - /// \param[out] _center Center of the bounding box - /// \param[out] _minXYZ Bounding box minimum values - /// \param[out] _maxXYZ Bounding box maximum values - public: void AABB(ignition::math::Vector3d &_center, - ignition::math::Vector3d &_minXYZ, - ignition::math::Vector3d &_maxXYZ) const; - - /// \brief Generate texture coordinates using spherical projection - /// from center - /// \param[in] _center Center of the projection - public: void GenSphericalTexCoord( - const ignition::math::Vector3d &_center); - - /// \brief Get the skeleton to which this mesh is attached. - /// \return Pointer to skeleton or nullptr if none is present. - public: SkeletonPtr MeshSkeleton() const; - - /// \brief Set the mesh skeleton - /// \param[in] _skel Skeleton to attach to the mesh. - public: void SetSkeleton(const SkeletonPtr &_skel); - - /// \brief Check if mesh is attached to a skeleton. - /// \return True if mesh is attached to a skeleton. - public: bool HasSkeleton() const; - - /// \brief Scale all vertices by _factor - /// \param _factor Scaling factor - public: void Scale(const ignition::math::Vector3d &_factor); - - /// \brief Set the scale all vertices - /// \param[in] _factor Scaling vector - public: void SetScale(const ignition::math::Vector3d &_factor); - - /// \brief Move the center of the mesh to the given coordinate in the - /// mesh frame. This will move all the vertices in all submeshes. - /// \param[in] _center Location of the mesh center. - public: void Center(const ignition::math::Vector3d &_center = - ignition::math::Vector3d::Zero); - - /// \brief Move all vertices in all submeshes by _vec. - /// \param[in] _vec Amount to translate vertices. - public: void Translate(const ignition::math::Vector3d &_vec); - - /// \brief Compute the volume of this mesh. The primitive type - /// must be TRIANGLES. - /// - /// This function utilizes the mesh volume formula from - /// "Efficient feature extraction for 2d/3d objects in mesh - /// representation" by Cha Zhang and Tsuhan Chen. Link: - /// http://chenlab.ece.cornell.edu/Publication/Cha/icip01_Cha.pdf. - /// The formula does not check for a closed (water tight) mesh. - /// - /// \return The mesh's volume. The volume can be zero if - /// the primitive type of the submeshes is not TRIANGLES, - /// or there are no submeshes. - public: double Volume() const; - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief Private data pointer. - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} - -#endif +#include +#include diff --git a/graphics/include/ignition/common/MeshCSG.hh b/graphics/include/ignition/common/MeshCSG.hh index a2d445a0a..2db03bca8 100644 --- a/graphics/include/ignition/common/MeshCSG.hh +++ b/graphics/include/ignition/common/MeshCSG.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,58 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_MESHCSG_HH_ -#define IGNITION_COMMON_MESHCSG_HH_ + */ -#include - -#include - -struct _GtsSurface; -typedef _GtsSurface GtsSurface; -struct _GPtrArray; -typedef _GPtrArray GPtrArray; - -namespace ignition -{ - namespace common - { - class Mesh; - - /// \class MeshCSG MeshCSG.hh ignition/common/MeshCSG.hh - /// \brief Creates CSG meshes - class IGNITION_COMMON_GRAPHICS_VISIBLE MeshCSG - { - /// \brief An enumeration of the boolean operations - public: enum BooleanOperation {UNION, INTERSECTION, DIFFERENCE}; - - /// \brief Constructor - public: MeshCSG(); - - /// \brief Destructor. - public: virtual ~MeshCSG(); - - /// \brief Create a boolean mesh from two meshes - /// \param[in] _m1 the parent mesh in the boolean operation - /// \param[in] _m2 the child mesh in the boolean operation - /// \param[in] _operation the boolean operation applied to the two meshes - /// \param[in] _offset _m2's pose offset from _m1 - /// \return a pointer to the created mesh - public: Mesh *CreateBoolean(const Mesh *_m1, const Mesh *_m2, - const int _operation, - const ignition::math::Pose3d &_offset = ignition::math::Pose3d::Zero); - - /// \brief Helper method for converting Mesh to GTS Surface - private: void ConvertMeshToGTS(const Mesh *mesh, GtsSurface *surface); - - /// \brief Helper method for merging neighborhood vertices whose positions - // are within epsilon - /// \param[in] _vertices Array of GTS vertices. - /// \param[in] _epsilon Epsilon - private: void MergeVertices(GPtrArray * _vertices, double _epsilon); - }; - } -} - -#endif +#include +#include diff --git a/graphics/include/ignition/common/MeshExporter.hh b/graphics/include/ignition/common/MeshExporter.hh index a1e54e3aa..1bca3ec01 100644 --- a/graphics/include/ignition/common/MeshExporter.hh +++ b/graphics/include/ignition/common/MeshExporter.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,36 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_MESHEXPORTER_HH_ -#define IGNITION_COMMON_MESHEXPORTER_HH_ + */ -#include -#include - -namespace ignition -{ - namespace common - { - class Mesh; - - /// \brief Base class for exporting meshes - class IGNITION_COMMON_GRAPHICS_VISIBLE MeshExporter - { - /// \brief Constructor - public: MeshExporter(); - - /// \brief Destructor - public: virtual ~MeshExporter(); - - /// \brief Export a mesh to a file - /// \param[in] _mesh Pointer to the mesh to be exported - /// \param[in] _filename Exported file's path and name - /// \param[in] _exportTextures True to export texture images to - /// '../materials/textures' folder - public: virtual void Export(const Mesh *_mesh, - const std::string &_filename, bool _exportTextures = false) = 0; - }; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/MeshLoader.hh b/graphics/include/ignition/common/MeshLoader.hh index 4a7dd4a59..01e1a501b 100644 --- a/graphics/include/ignition/common/MeshLoader.hh +++ b/graphics/include/ignition/common/MeshLoader.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,35 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_MESHLOADER_HH_ -#define IGNITION_COMMON_MESHLOADER_HH_ + */ -#include - -#include - -namespace ignition -{ - namespace common - { - class Mesh; - - /// \class MeshLoader MeshLoader.hh ignition/common/MeshLoader.hh - /// \brief Base class for loading meshes - class IGNITION_COMMON_GRAPHICS_VISIBLE MeshLoader - { - /// \brief Constructor - public: MeshLoader() = default; - - /// \brief Destructor - public: virtual ~MeshLoader() = default; - - /// \brief Load a 3D mesh - /// \param[in] _filename the path to the mesh - /// \return a pointer to the created mesh - public: virtual Mesh *Load(const std::string &_filename) = 0; - }; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/MeshManager.hh b/graphics/include/ignition/common/MeshManager.hh index 28e9df2e0..988056c1b 100644 --- a/graphics/include/ignition/common/MeshManager.hh +++ b/graphics/include/ignition/common/MeshManager.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,285 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_MESHMANAGER_HH_ -#define IGNITION_COMMON_MESHMANAGER_HH_ + */ -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace ignition -{ - namespace common - { - /// \brief forward declaration - class Mesh; - class SubMesh; - class MeshManagerPrivate; - - /// \class MeshManager MeshManager.hh ignition/common/MeshManager.hh - /// \brief Maintains and manages all meshes - class IGNITION_COMMON_GRAPHICS_VISIBLE MeshManager - : public SingletonT - { - /// \brief Constructor - private: MeshManager(); - - /// \brief Destructor. - /// - /// Destroys the collada loader, the stl loader and all the meshes - private: virtual ~MeshManager(); - - /// \brief Load a mesh from a file. - /// The mesh will be searched on the global SystemPaths instance provided - /// by Util.hh. - /// \param[in] _filename the path to the mesh - /// \return a pointer to the created mesh - public: const Mesh *Load(const std::string &_filename); - - /// \brief Export a mesh to a file - /// \param[in] _mesh Pointer to the mesh to be exported - /// \param[in] _filename Exported file's path and name - /// \param[in] _extension Exported file's format ("dae" for Collada) - /// \param[in] _exportTextures True to export texture images to - /// '../materials/textures' folder - public: void Export(const Mesh *_mesh, const std::string &_filename, - const std::string &_extension, bool _exportTextures = false); - - /// \brief Checks a path extension against the list of valid extensions. - /// \return true if the file extension is loadable - public: bool IsValidFilename(const std::string &_filename); - - /// \brief Get mesh aabb and center. - /// \param[in] _mesh the mesh - /// \param[out] _center the AAB center position - /// \param[out] _min_xyz the bounding box minimum - /// \param[out] _max_xyz the bounding box maximum - public: void MeshAABB(const Mesh *_mesh, - ignition::math::Vector3d &_center, - ignition::math::Vector3d &_min_xyz, - ignition::math::Vector3d &_max_xyz); - - /// \brief generate spherical texture coordinates - /// \param[in] _mesh Pointer to the mesh - /// \param[in] _center Center of the mesh - public: void GenSphericalTexCoord(const Mesh *_mesh, - const ignition::math::Vector3d &_center); - - /// \brief Add a mesh to the manager. - /// - /// This MeshManager takes ownership of the mesh and will destroy it. - /// See ~MeshManager. - /// \param[in] the mesh to add. - public: void AddMesh(Mesh *_mesh); - - /// \brief Get a mesh by name. - /// \param[in] _name the name of the mesh to look for - /// \return the mesh or nullptr if not found - public: const ignition::common::Mesh *MeshByName( - const std::string &_name) const; - - /// \brief Return true if the mesh exists. - /// \param[in] _name the name of the mesh - public: bool HasMesh(const std::string &_name) const; - - /// \brief Create a sphere mesh. - /// \param[in] _name the name of the mesh - /// \param[in] _radius radius of the sphere in meter - /// \param[in] _rings number of circles on th y axis - /// \param[in] _segments number of segment per circle - public: void CreateSphere(const std::string &_name, const float _radius, - const int _rings, const int _segments); - - /// \brief Create a Box mesh - /// \param[in] _name the name of the new mesh - /// \param[in] _sides the x y x dimentions of eah side in meter - /// \param[in] _uvCoords the texture coordinates - public: void CreateBox(const std::string &_name, - const ignition::math::Vector3d &_sides, - const ignition::math::Vector2d &_uvCoords); - - /// \brief Create an extruded mesh from polylines. The polylines are - /// assumed to be closed and non-intersecting. Delaunay triangulation is - /// applied to create the resulting mesh. If there is more than one - /// polyline, a ray casting algorithm will be used to identify the - /// exterior/interior edges and remove holes from the 2D shape before - /// extrusion. - /// \param[in] _name the name of the new mesh - /// \param[in] _vertices A multidimensional vector of polylines and their - /// vertices. Each element in the outer vector consists of a vector of - /// vertices that describe one polyline. - /// edges and remove the holes in the shape. - /// \param[in] _height the height of extrusion - public: void CreateExtrudedPolyline(const std::string &_name, - const std::vector > - &_vertices, const double _height); - - /// \brief Create a cylinder mesh - /// \param[in] _name the name of the new mesh - /// \param[in] _radius the radius of the cylinder in the x y plane - /// \param[in] _height the height along z - /// \param[in] _rings the number of circles along the height - /// \param[in] _segments the number of segment per circle - public: void CreateCylinder(const std::string &_name, - const float _radius, - const float _height, - const int _rings, - const int _segments); - - /// \brief Create a ellipsoid mesh - /// \param[in] _name the name of the new mesh - /// \param[in] _radii the three radius that define a ellipsoid - /// \param[in] _rings the number of circles along the height - /// \param[in] _segments the number of segment per circle - public: void CreateEllipsoid(const std::string &_name, - const ignition::math::Vector3d &_radii, - const unsigned int _rings, - const unsigned int _segments); - - /// \brief Create a capsule mesh - /// \param[in] _name the name of the new mesh - /// \param[in] _radius the radius of the capsule in the x y plane - /// \param[in] _length length of the body - /// \param[in] _rings the number of circles along the height - /// \param[in] _segments the number of segment per circle - public: void CreateCapsule(const std::string &_name, - const double radius, - const double length, - const unsigned int _rings, - const unsigned int _segments); - - /// \brief Create a cone mesh - /// \param[in] _name the name of the new mesh - /// \param[in] _radius the radius of the cylinder in the x y plane - /// \param[in] _height the height along z - /// \param[in] _rings the number of circles along the height - /// \param[in] _segments the number of segment per circle - public: void CreateCone(const std::string &_name, - const float _radius, - const float _height, - const int _rings, - const int _segments); - - /// \brief Create a tube mesh. - /// - /// Generates rings inside and outside the cylinder - /// Needs at least two rings and 3 segments - /// \param[in] _name the name of the new mesh - /// \param[in] _innerRadius the inner radius of the tube in the x y plane - /// \param[in] _outterRadius the outer radius of the tube in the x y plane - /// \param[in] _height the height along z - /// \param[in] _rings the number of circles along the height - /// \param[in] _segments the number of segment per circle - /// \param[in] _arc the arc angle in radians - public: void CreateTube(const std::string &_name, - const float _innerRadius, - const float _outterRadius, - const float _height, - const int _rings, - const int _segments, - const double _arc = 2.0 * IGN_PI); - - /// \brief Create mesh for a plane - /// \param[in] _name - /// \param[in] _plane plane parameters - /// \param[in] _segments number of segments in x and y - /// \param[in] _uvTile the texture tile size in x and y - public: void CreatePlane(const std::string &_name, - const ignition::math::Planed &_plane, - const ignition::math::Vector2d &_segments, - const ignition::math::Vector2d &_uvTile); - - /// \brief Create mesh for a plane - /// \param[in] _name the name of the new mesh - /// \param[in] _normal the normal to the plane - /// \param[in] _d distance from the origin along normal - /// \param[in] _size the size of the plane in x and y - /// \param[in] _segments the number of segments in x and y - /// \param[in] _uvTile the texture tile size in x and y - public: void CreatePlane(const std::string &_name, - const ignition::math::Vector3d &_normal, - const double _d, - const ignition::math::Vector2d &_size, - const ignition::math::Vector2d &_segments, - const ignition::math::Vector2d &_uvTile); - - /// \brief Tesselate a 2D mesh - /// - /// Makes a zigzag pattern compatible with strips - /// \param[in] _sm the mesh to tesselate - /// \param[in] _meshWith mesh width - /// \param[in] _meshHeight the mesh height - /// \param[in] _doubleSided flag to specify single or double sided - private: void Tesselate2DMesh(SubMesh *_sm, - const int _meshWidth, - const int _meshHeight, - const bool _doubleSided); - - /// \brief Create a Camera mesh - /// \param[in] _name name of the new mesh - /// \param[in] _scale scaling factor for the camera - public: void CreateCamera(const std::string &_name, const float _scale); - - /// \brief Create a boolean mesh from two meshes - /// \param[in] _name the name of the new mesh - /// \param[in] _m1 the parent mesh in the boolean operation - /// \param[in] _m2 the child mesh in the boolean operation - /// \param[in] _operation the boolean operation applied to the two meshes - /// \param[in] _offset _m2's pose offset from _m1 - public: void CreateBoolean(const std::string &_name, const Mesh *_m1, - const Mesh *_m2, const int _operation, - const ignition::math::Pose3d &_offset = ignition::math::Pose3d::Zero); - - /// \brief Converts a vector of polylines into a table of vertices and - /// a list of edges (each made of 2 points from the table of vertices. - /// \param[in] _polys the polylines - /// \param[in] _tol tolerence for 2 vertices to be considered the same - /// \param[out] _vertices a table of unique vertices - /// \param[out] _edges a list of edges (made of start/end point indices - /// from the vertex table) - private: static void ConvertPolylinesToVerticesAndEdges( - const std::vector > - &_polys, - const double _tol, - std::vector &_vertices, - std::vector &_edges); - - /// \brief Check a point againts a list, and only adds it to the list - /// if it is not there already. - /// \param[in,out] _vertices the vertex table where points are stored - /// \param[in] _p the point coordinates - /// \param[in] _tol the maximum distance under which 2 points are - /// considered to be the same point. - /// \return the index of the point. - private: static size_t AddUniquePointToVerticesTable( - std::vector &_vertices, - const ignition::math::Vector2d &_p, - const double _tol); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief Pointer to private data - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - - /// \brief Singleton implementation - private: friend class SingletonT; - }; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/NodeAnimation.hh b/graphics/include/ignition/common/NodeAnimation.hh index f6e4bc887..d1a3c2205 100644 --- a/graphics/include/ignition/common/NodeAnimation.hh +++ b/graphics/include/ignition/common/NodeAnimation.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,105 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_NODE_ANIMATION_HH_ -#define IGNITION_COMMON_NODE_ANIMATION_HH_ + */ -#include -#include - -#include -#include - -#include - -namespace ignition -{ - namespace common - { - class NodeAnimationPrivate; - - /// \class NodeAnimation NodeAnimation.hh ignition/common/NodeAnimation.hh - /// \brief Node animation - class IGNITION_COMMON_GRAPHICS_VISIBLE NodeAnimation - { - /// \brief constructor - /// \param[in] _name the name of the node - public: explicit NodeAnimation(const std::string &_name); - - /// \brief Destructor. - public: ~NodeAnimation(); - - /// \brief Changes the name of the animation - /// \param[in] the new name - public: void SetName(const std::string &_name); - - /// \brief Returns the name - /// \return the name - public: std::string Name() const; - - /// \brief Adds a key frame at a specific time - /// \param[in] _time the time of the key frame - /// \param[in] _trans the transformation - public: void AddKeyFrame(const double _time, - const math::Matrix4d &_trans); - - /// \brief Adds a key frame at a specific time - /// \param[in] _time the tiem of the key frame - /// \param[in] _pose the pose - public: void AddKeyFrame(const double _time, const math::Pose3d &_pose); - - /// \brief Returns the number of key frames. - /// \return the count - public: unsigned int FrameCount() const; - - /// \brief Finds a key frame using the index. Note the index of a key - /// frame can change as frames are added. - /// \param[in] _i the index - /// \param[out] _time the time of the frame, or -1 if the index id is out - /// of bounds - /// \param[out] _trans the transformation for this key frame - public: void KeyFrame(const unsigned int _i, double &_time, - math::Matrix4d &_trans) const; - - /// \brief Returns a key frame using the index. Note the index of a key - /// frame can change as frames are added. - /// \param[in] _i the index - /// \return a pair that contains the time and transformation. Time is -1 - /// if the index is out of bounds - public: std::pair KeyFrame( - const unsigned int _i) const; - - /// \brief Returns the duration of the animations - /// \return the time of the last animation - public: double Length() const; - - /// \brief Returns a frame transformation at a specific time - /// if a node does not exist at that time (with tolerance of 1e-6 sec), - /// the transformation is interpolated. - /// \param[in] _time the time - /// \param[in] _loop when true, the time is divided by the duration - /// (see GetLength) - public: ignition::math::Matrix4d FrameAt(const double _time, - const bool _loop = true) const; - - /// \brief Scales each transformation in the key frames. This only affects - /// the translational values. - /// \param[in] _scale the scaling factor - public: void Scale(const double _scale); - - /// \brief Returns the time where a transformation's translational value - /// along the X axis is equal to _x. - /// When no transformation is found (within a tolerance of 1e-6), the time - /// is interpolated. - /// \param[in] _x the value along x. You must ensure that _x is within a - /// valid range. - public: double TimeAtX(const double _x) const; - - /// \brief Private data pointer. - private: NodeAnimationPrivate *data; - }; - } -} - -#endif +#include +#include diff --git a/graphics/include/ignition/common/NodeTransform.hh b/graphics/include/ignition/common/NodeTransform.hh index e647bc0c0..c27c74d4e 100644 --- a/graphics/include/ignition/common/NodeTransform.hh +++ b/graphics/include/ignition/common/NodeTransform.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,119 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_NODE_TRANSFORM_HH_ -#define IGNITION_COMMON_NODE_TRANSFORM_HH_ -#include -#include + */ -#include -#include -#include -#include - -namespace ignition -{ - namespace common - { - /// Forward declare private data structure. - class NodeTransformPrivate; - - /// \class NodeTransform NodeTransform.hh ignition/common/NodeTransform.hh - /// \brief A transformation node - class IGNITION_COMMON_GRAPHICS_VISIBLE NodeTransform - { - /// \brief Constructor - /// \param[in] _type the type of transform - public: explicit NodeTransform(const NodeTransformType _type = MATRIX); - - /// \brief Copy constructor - /// \param[in] _other NodeTransform to copy - public: NodeTransform(const NodeTransform &_other); - - /// \brief Copy assignment - /// \param[in] _ther NodeTransform to copy - public: NodeTransform &operator=(const NodeTransform &_other); - - /// \brief Constructor - /// \param[in] _mat the matrix - /// \param[in] _sid identifier - /// \param[in] _type the type of transform - public: NodeTransform(const math::Matrix4d &_mat, - const std::string &_sid = "_default_", - const NodeTransformType _type = MATRIX); - - /// \brief Destructor. - public: ~NodeTransform(); - - /// \brief Assign a transformation - /// \param[in] _mat the transform - public: void Set(const math::Matrix4d &_mat); - - /// \brief Returns the transformation matrix - /// \return the matrix - public: math::Matrix4d Get() const; - - /// \brief Set transform type - /// \param[in] _type the type - public: void SetType(const NodeTransformType _type); - - /// \brief Returns the transformation type - /// \return the type - public: NodeTransformType Type() const; - - /// \brief Set the SID - /// \param[in] _sid the sid - public: void SetSID(const std::string &_sid); - - /// \brief Returns the SID - /// \return the SID - public: std::string SID() const; - - /// \brief Set a transformation matrix component value - /// \param[in] _idx the component index - /// \param[in] _value the value - public: void SetComponent(const unsigned int _idx, const double _value); - - /// \brief Set source data values - /// \param[in] _mat the values - public: void SetSourceValues(const math::Matrix4d &_mat); - - /// \brief Set source data values - /// \param[in] _vec the values - public: void SetSourceValues(const math::Vector3d &_vec); - - /// \brief Sets source matrix values from roation - /// \param[in] _axis of rotation - /// \param[in] _angle of rotation - public: void SetSourceValues(const math::Vector3d &_axis, - const double _angle); - - /// \brief Sets the transform matrix from the source according to the type - public: void RecalculateMatrix(); - - /// \brief Prints the transform matrix to standard out - public: void PrintSource() const; - - /// \brief Matrix cast operator - /// \return the transform - public: math::Matrix4d operator()() const; - - /// \brief Node transform multiplication operator - /// \param[in] _t a transform - /// \return transform matrix multiplied by _t's transform - public: math::Matrix4d operator*(const NodeTransform &_t) const; - - /// \brief Matrix multiplication operator - /// \param[in] _m a matrix - /// \return transform matrix multiplied by _m - public: math::Matrix4d operator*(const math::Matrix4d &_m) const; - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief Data pointer - private: std::unique_ptr data; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/OBJLoader.hh b/graphics/include/ignition/common/OBJLoader.hh index bb156f3f1..a25245a16 100644 --- a/graphics/include/ignition/common/OBJLoader.hh +++ b/graphics/include/ignition/common/OBJLoader.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,45 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ + */ -#ifndef IGNITION_COMMON_OBJLOADER_HH_ -#define IGNITION_COMMON_OBJLOADER_HH_ - -#include -#include - -#include -#include -#include - -namespace ignition -{ - namespace common - { - // class OBJ Loader private class; - class OBJLoaderPrivate; - - /// \brief Class used to load obj mesh files - class IGNITION_COMMON_GRAPHICS_VISIBLE OBJLoader : public MeshLoader - { - /// \brief Constructor - public: OBJLoader(); - - /// \brief Destructor - public: virtual ~OBJLoader(); - - /// \brief Load a mesh - /// \param[in] _filename OBJ file to load - /// \return Pointer to a new Mesh - public: virtual Mesh *Load(const std::string &_filename); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \internal - /// \brief Pointer to private data. - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/Pbr.hh b/graphics/include/ignition/common/Pbr.hh index 68afde020..ff255b5c0 100644 --- a/graphics/include/ignition/common/Pbr.hh +++ b/graphics/include/ignition/common/Pbr.hh @@ -1,5 +1,5 @@ /* - * Copyright 2020 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,228 +14,6 @@ * limitations under the License. * */ -#ifndef IGNITION_COMMON_PBR_HH_ -#define IGNITION_COMMON_PBR_HH_ -#include -#include - -namespace ignition -{ -namespace common -{ - // Forward declarations. - class PbrPrivate; - - /// \brief Type of PBR workflow. - enum class PbrType : int - { - /// \brief No workflow - NONE = 0, - - /// \brief Metal/Roughness workflow - METAL = 1, - - /// \brief Specular/Glossiness workflow - SPECULAR = 2, - }; - - /// \brief Space the normal map is defined in - enum class NormalMapSpace: int - { - /// \brief Tangent space - TANGENT = 0, - - /// \brief Object space - OBJECT = 1, - }; - - /// \brief This class contains Physically-Based-Rendering (PBR) workflow - /// properties. - class IGNITION_COMMON_GRAPHICS_VISIBLE Pbr - { - /// \brief Default constructor - public: Pbr(); - - /// \brief Copy constructor - /// \param[in] _pbr Pbr to copy. - public: Pbr(const Pbr &_pbr); - - /// \brief Move constructor - /// \param[in] _pbr to move. - public: Pbr(Pbr &&_pbr) noexcept; - - /// \brief Destructor - public: ~Pbr(); - - /// \brief Assignment operator. - /// \param[in] _pbr The pbr material to set values from. - /// \return *this - public: Pbr &operator=(const Pbr &_pbr); - - /// \brief Move assignment operator. - /// \param[in] _pbr The pbr material to move from. - /// \return *this - public: Pbr &operator=(Pbr &&_pbr); - - /// \brief Return true if both Pbr objects contain the same values. - /// \param[_in] _pbr Pbr value to compare. - /// \returen True if 'this' == _pbr. - public: bool operator==(const Pbr &_pbr) const; - - /// \brief Return true this Pbr object does not contain the same - /// values as the passed in parameter. - /// \param[_in] _pbr Pbr value to compare. - /// \returen True if 'this' != _pbr. - public: bool operator!=(const Pbr &_pbr) const; - - /// \brief Get the albedo map filename. This will be an empty string if - /// an albedo map has not been set. - /// \return Filename of the albedo map, or empty string if an albedo map - /// has not been specified. - public: std::string AlbedoMap() const; - - /// \brief Set the albedo map filename. - /// \param[in] _map Filename of the albedo map. - public: void SetAlbedoMap(const std::string &_map); - - /// \brief Get the normal map filename. This will be an empty string if - /// a normal map has not been set. - /// \return Filename of the normal map, or empty string if a normal map - /// has not been specified. - public: std::string NormalMap() const; - - /// \brief Set the normal map filename. - /// \param[in] _map Filename of the normal map. - /// \param[in] _space Space that the normal map is defined in. - /// Defaults to tangent space. - public: void SetNormalMap(const std::string &_map, - NormalMapSpace _space = NormalMapSpace::TANGENT); - - /// \brief Get the normal map type, either tangent or object space - /// \return Space that the normal map is defined in - public: NormalMapSpace NormalMapType() const; - - /// \brief Get the environment map filename. This will be an empty string - /// if an environment map has not been set. - /// \return Filename of the environment map, or empty string if an - /// environment map has not been specified. - public: std::string EnvironmentMap() const; - - /// \brief Set the environment map filename. - /// \param[in] _map Filename of the environment map. - public: void SetEnvironmentMap(const std::string &_map); - - /// \brief Get the ambient occlusion map filename. This will be an empty - /// string if an ambient occlusion map has not been set. - /// \return Filename of the ambient occlusion map, or empty string if an - /// ambient occlusion map has not been specified. - public: std::string AmbientOcclusionMap() const; - - /// \brief Set the ambient occlusion map filename. - /// \param[in] _map Filename of the ambient occlusion map. - public: void SetAmbientOcclusionMap(const std::string &_map); - - /// \brief Get the roughness map filename for metal workflow. This will be - /// an empty string if a roughness map has not been set. - /// \return Filename of the roughness map, or empty string if a roughness - /// map has not been specified. - public: std::string RoughnessMap() const; - - /// \brief Set the roughness map filename for metal workflow. - /// \param[in] _map Filename of the roughness map. - public: void SetRoughnessMap(const std::string &_map); - - /// \brief Get the metalness map filename for metal workflow. This will be - /// an empty string if a metalness map has not been set. - /// \return Filename of the metalness map, or empty string if a metalness - /// map has not been specified. - public: std::string MetalnessMap() const; - - /// \brief Set the metalness map filename for metal workflow. - /// \param[in] _map Filename of the metalness map. - public: void SetMetalnessMap(const std::string &_map); - - /// \brief Get the emissive map filename. This will be an empty string - /// if an emissive map has not been set. - /// \return Filename of the emissive map, or empty string if an emissive - /// map has not been specified. - public: std::string EmissiveMap() const; - - /// \brief Set the emissive map filename. - /// \param[in] _map Filename of the emissive map. - public: void SetEmissiveMap(const std::string &_map); - - /// \brief Get the light map filename. This will be an empty string - /// if an light map has not been set. - /// \return Filename of the light map, or empty string if a light - /// map has not been specified. - public: std::string LightMap() const; - - /// \brief Set the light map filename. - /// \param[in] _map Filename of the light map. - /// \param[in] _uvSet Index of the texture coordinate set - public: void SetLightMap(const std::string &_map, unsigned int _uvSet = 0u); - - /// \brief Get the light map texture coordinate set. - /// \return Index of the light map texture coordinate set - public: unsigned int LightMapTexCoordSet() const; - - /// \brief Get the metalness value of the material for metal workflow - /// \return metalness value of the material - public: double Metalness() const; - - /// \brief Set the metalness value of the material for metal workflow. - /// \param[in] _value Metalness value. - public: void SetMetalness(double _value); - - /// \brief Get the roughness value of the material for metal workflow - /// \return roughness value of the material - public: double Roughness() const; - - /// \brief Set the roughness value of the material for metal workflow. - /// \param[in] _value Roughness value. - public: void SetRoughness(double _value); - - /// \brief Get the glossiness map filename for specular workflow. This will - /// be an empty string if a glossiness map has not been set. - /// \return Filename of the glossiness map, or empty string if a glossiness - /// map has not been specified. - public: std::string GlossinessMap() const; - - /// \brief Set the glossiness map filename for specular workflow. - /// \param[in] _map Filename of the glossiness map. - public: void SetGlossinessMap(const std::string &_map); - - /// \brief Get the glossiness value of the material for specular workflow - /// \return Glossiness value of the material - public: double Glossiness() const; - - /// \brief Set the glossiness value of the material for specular workflow. - /// \param[in] _value Glossiness value. - public: void SetGlossiness(double _value); - - /// \brief Get the specular map filename for specular workflow. This will - /// be an empty string if a specular map has not been set. - /// \return Filename of the specular map, or empty string if a specular - /// map has not been specified. - public: std::string SpecularMap() const; - - /// \brief Set the specular map filename for specular workflow. - /// \param[in] _map Filename of the specular map. - public: void SetSpecularMap(const std::string &_map); - - /// \brief Get the workflow type. - /// \return PBR workflow type. - public: PbrType Type() const; - - /// \brief Set the PBR workflow to use - /// \param[in] _type Workflow type to use - public: void SetType(PbrType _type); - - /// \brief Private data pointer. - private: PbrPrivate *dataPtr = nullptr; - }; -} -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/STLLoader.hh b/graphics/include/ignition/common/STLLoader.hh index d6e47642d..d719a6745 100644 --- a/graphics/include/ignition/common/STLLoader.hh +++ b/graphics/include/ignition/common/STLLoader.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,83 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_STLLOADER_HH_ -#define IGNITION_COMMON_STLLOADER_HH_ - -#include -#include - -#include "ignition/common/MeshLoader.hh" -#include "ignition/common/graphics/Export.hh" - -#define LINE_MAX_LEN 256 -#define COR3_MAX 200000 -#define ORDER_MAX 10 -#define FACE_MAX 200000 - -namespace ignition -{ - namespace common - { - /// \class STLLoader STLLoader.hh ignition/common/STLLoader.hh - /// \brief Class used to load STL mesh files - class IGNITION_COMMON_GRAPHICS_VISIBLE STLLoader : public MeshLoader - { - /// \brief Constructor - public: STLLoader(); - - /// \brief Destructor - public: virtual ~STLLoader(); - - /// \brief Creates a new mesh and loads the data from a file - /// \param[in] _filename the mesh file - public: virtual Mesh *Load(const std::string &_filename); - - /// \brief Reads an ASCII STL (stereolithography) file. - /// \param[in] _filein the file pointer - /// \param[out] _mesh the mesh where to load the data - /// \return true if read was successful - private: bool ReadAscii(FILE *_filein, Mesh *_mesh); - - /// \brief Reads a binary STL (stereolithography) file. - /// \param[in] _filein the file pointer - /// \param[out] the mesh where to load the data - /// \return true if read was successful - private: bool ReadBinary(FILE *_filein, Mesh *_mesh); - - /// \brief Compares two strings for equality, disregarding case. - /// \param[in] _string1 the first string - /// \param[in] _string2 the seconf string - /// \return true if the strings are equal (same content) - private: bool Leqi(char* _string1, char* _string2); - - /// \brief Finds if a vector occurs in a table. This is done using - /// floating point comparison with the default tolerance of 1e-6 - /// \param[in] _a the vector data - /// \param[in] _m the number of columns in the table - /// \param[in] _n the number of rows in the table - /// \return The column index of the vector - private: int RcolFind(float _a[][COR3_MAX], int _m, int _n, float _r[]); - - /// \brief Reads a long int from a binary file. - /// \param[in] _filein the file pointer - /// \return the value - private: uint32_t LongIntRead(FILE *_filein); - - /// \brief Reads a short int from a binary file. - /// \param[in] _filein the file pointer - /// \param[out] _value the value read - /// \return true - private: bool ShortIntRead(FILE *_filein, uint16_t &_value); - - /// \brief Read 1 double precision float from a binary file. - /// \param[in] _filein the file pointer - /// \param[out] the value - /// \return true - private: bool FloatRead(FILE *_filein, double &_value); - }; - } -} -#endif + */ +#include +#include diff --git a/graphics/include/ignition/common/SVGLoader.hh b/graphics/include/ignition/common/SVGLoader.hh index 39589e2ca..279669e56 100644 --- a/graphics/include/ignition/common/SVGLoader.hh +++ b/graphics/include/ignition/common/SVGLoader.hh @@ -1,11 +1,11 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,122 +14,6 @@ * limitations under the License. * */ -#ifndef IGNITION_COMMON_SVGLOADER_HH_ -#define IGNITION_COMMON_SVGLOADER_HH_ -#include -#include -#include - -#include -#include - -#include -#include -#include - -namespace ignition -{ - namespace common - { - // Forward declare private data class - class SVGLoaderPrivate; - - /// \brief SVG command data structure - class IGNITION_COMMON_GRAPHICS_VISIBLE SVGCommand - { - /// \brief Constructor - public: SVGCommand() : cmd(' ') {} - - /// \brief Destructor - public: virtual ~SVGCommand() = default; - - /// \brief A letter that describe the segment - public: char cmd; - -#ifdef _WIN32 -// Disable warning C4251 -#pragma warning(push) -#pragma warning(disable: 4251) -#endif - /// \brief Coordinates for the command - public: std::vector numbers; -#ifdef _WIN32 -#pragma warning(pop) -#endif - }; - - /// \brief An SVG path element data structure - struct IGNITION_COMMON_GRAPHICS_VISIBLE SVGPath - { -#ifdef _WIN32 -// Disable warning C4251 -#pragma warning(push) -#pragma warning(disable: 4251) -#endif - - /// \brief An id or name - std::string id; - - /// \brief The style (i.e. stroke style, color, thickness etc) - std::string style; - - /// \brief A 2D transform (or a list of transforms) - ignition::math::Matrix3d transform; - - /// \brief A list of subpaths (as lists of commands) - std::vector< std::vector > subpaths; - - /// \brief The polylines described by the commands - std::vector< std::vector > polylines; -#ifdef _WIN32 -#pragma warning(pop) -#endif - }; - - /// \brief A loader for SVG files - class IGNITION_COMMON_GRAPHICS_VISIBLE SVGLoader - { - /// \brief Constructor - /// \param[in] _samples The number of points for cubic spline segments - /// Samples must be greater than zero. A value of one will be used if - /// _samples is set to zero. - public: explicit SVGLoader(const unsigned int _samples); - - /// \brief destructor - public: ~SVGLoader(); - - /// \brief Reads an SVG file and loads all the paths - /// \param[in] _filename The SVG file - /// \param[out] _paths Vector that receives path datai - /// \return false when the file cannot be processed - public: bool Parse(const std::string &_filename, - std::vector &_paths); - - /// \brief Reads in paths and outputs closed polylines and open polylines - /// \param[in] _paths The input paths - /// \param[in] _tol Tolerence when comparing distance between 2 points. - /// \param[out] _closedPolys A vector to collect new closed loops - /// \param[out] _openPolys A vector to collect non closed paths - public: static void PathsToClosedPolylines( - const std::vector &_paths, - const double _tol, - std::vector< std::vector > &_closedPolys, - std::vector< std::vector > &_openPolys); - - /// \brief Outputs the content of the paths to file (or console) - /// \param[in] _paths The paths - /// \param[in] _out The output stream (can be a file or std::cout) - public: void DumpPaths(const std::vector &_paths, - std::ostream &_out) const; - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \internal - /// \brief Pointer to private data - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} - -#endif +#include +#include diff --git a/graphics/include/ignition/common/Skeleton.hh b/graphics/include/ignition/common/Skeleton.hh index 1921905f8..113ed68a5 100644 --- a/graphics/include/ignition/common/Skeleton.hh +++ b/graphics/include/ignition/common/Skeleton.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,166 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_SKELETON_HH_ -#define IGNITION_COMMON_SKELETON_HH_ + */ -#include -#include -#include -#include - -#include -#include -#include - -namespace ignition -{ - namespace common - { - /// Forward declarations - class SkeletonPrivate; - class SkeletonAnimation; - - /// \class Skeleton Skeleton.hh ignition/common/Skeleton.hh - /// \brief A skeleton, usually used for animation purposes. - class IGNITION_COMMON_GRAPHICS_VISIBLE Skeleton - { - /// \brief Constructor - public: Skeleton(); - - /// \brief Constructor - /// \param[in] _root node - public: explicit Skeleton(SkeletonNode *_root); - - /// \brief Destructor - public: virtual ~Skeleton(); - - /// \brief Change the root node - /// \param[in] _node the new node - public: void RootNode(SkeletonNode *_node); - - /// \brief Return the root - /// \return the root - public: SkeletonNode *RootNode() const; - - /// \brief Find a node - /// \param[in] _name the name of the node to look for - /// \return the node, or NULL if not found - public: SkeletonNode *NodeByName(const std::string &_name) const; - - /// \brief Find node by index - /// \param[in] _id the index - /// \return the node, or NULL if not found - public: SkeletonNode *NodeById(const std::string &_id) const; - - /// \brief Find or create node with handle - /// \param[in] _handle - /// \return the node. A new node is created if it didn't exist - public: SkeletonNode *NodeByHandle(const unsigned int _handle) const; - - /// \brief Returns the node count - /// \return the count - public: unsigned int NodeCount() const; - - /// \brief Returns the number of joints - /// \return the count - public: unsigned int JointCount() const; - - /// \brief Scale all nodes, transforms and animation data - /// \param[in] the scaling factor - public: void Scale(const double _scale); - - /// \brief Set the bind pose skeletal transform - /// \param[in] _trans the transform - public: void SetBindShapeTransform(const math::Matrix4d &_trans); - - /// \brief Return bind pose skeletal transform - /// \return A matrix - public: math::Matrix4d BindShapeTransform() const; - - /// \brief Outputs the transforms to standard out - public: void PrintTransforms() const; - - /// \brief Get a copy or the node dictionary. - /// \return A copy of the nodes. - public: const SkeletonNodeMap &Nodes() const; - - /// \brief Resizes the raw node weight array - /// \param[in] _vertices the new size - public: void SetNumVertAttached(const unsigned int _vertices); - - /// \brief Add a new weight to a node (bone) - /// \param[in] _vertex index of the vertex - /// \param[in] _node name of the bone - /// \param[in] _weight the new weight (range 0 to 1) - public: void AddVertNodeWeight(const unsigned int _vertex, - const std::string &_node, const double _weight); - - /// \brief Returns the number of bone weights for a vertex - /// \param[in] _vertex the index of the vertex - /// \return the count - public: unsigned int VertNodeWeightCount( - const unsigned int _vertex) const; - - /// \brief Weight of a bone for a vertex - /// \param[in] _v the index of the vertex - /// \param[in] _i the index of the weight for that vertex - /// \return a pair containing the name of the node and the weight - public: std::pair VertNodeWeight( - const unsigned int _v, const unsigned int _i) const; - - /// \brief Returns the number of animations - /// \return the count - public: unsigned int AnimationCount() const; - - /// \brief Find animation - /// \param[in] _i the animation index - /// \return the animation, or NULL if _i is out of bounds - public: SkeletonAnimation *Animation(const unsigned int _i) const; - - /// \brief Add an animation. The skeleton does not take ownership of the - /// animation - /// \param[in] _anim the animation to add - public: void AddAnimation(SkeletonAnimation *_anim); - - /// \brief Add an animation from BVH file. - /// \param[in] _bvhFile the bvh file to load animation from - /// \param[in] _scale the scale of the animation - /// \return True if the BVH animation is compatible with skeleton - public: bool AddBvhAnimation(const std::string &_bvhFile, double _scale); - - /// \brief Finding the skin node name that corresponds to - /// the given animation node name. - /// \param[in] _index the animation index - /// \param[in] _animNodeName the given animation node name - /// \return The corresponding skin node name in the skeleton - public: std::string NodeNameAnimToSkin(unsigned int _index, - const std::string &_animNodeName); - - /// \brief Get the transformation to align translation from - /// the animation skeleton to skin skeleton - /// \param[in] _index the animation index - /// \param[in] _animNodeName the animation node name - /// \return The transformation to align translation - public: math::Matrix4d AlignTranslation(unsigned int _index, - const std::string &_animNodeName); - - /// \brief Get the transformation to align rotation from - /// the animation skeleton to skin skeleton - /// \param[in] _index the animation index - /// \param[in] _animNodeName the animation node name - /// \return The transformation to align rotation - public: math::Matrix4d AlignRotation(unsigned int _index, - const std::string &_animNodeName); - - /// \brief Initializes the hande numbers for each node in the map - /// using breadth first traversal - private: void BuildNodeMap(); - - /// \brief Private data pointer - private: SkeletonPrivate *data; - }; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/SkeletonAnimation.hh b/graphics/include/ignition/common/SkeletonAnimation.hh index be9990c2d..5baf32acc 100644 --- a/graphics/include/ignition/common/SkeletonAnimation.hh +++ b/graphics/include/ignition/common/SkeletonAnimation.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,131 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_SKELETONANIMATION_HH_ -#define IGNITION_COMMON_SKELETONANIMATION_HH_ + */ -#include -#include -#include - -#include -#include - -#include -#include - -namespace ignition -{ - namespace common - { - /// Forward declare private data class - class SkeletonAnimationPrivate; - - /// \class SkeletonAnimation SkeletonAnimation.hh - /// ignition/common/SkeletonAnimation.hh - /// \brief Skeleton animation - class IGNITION_COMMON_GRAPHICS_VISIBLE SkeletonAnimation - { - /// \brief The Constructor - /// \param[in] _name the name of the animation - public: explicit SkeletonAnimation(const std::string &_name); - - /// \brief The destructor. Clears the list without destroying - /// the animations - public: ~SkeletonAnimation(); - - // NOTE: this is not needed starting in ign-common4 since ign-common4 uses - // the IGN_UTILS_IMPL_PTR instead of a raw impl pointer. So, this - // method should not be included in forward ports from ign-common3 to - // ign-common4 - /// \brief Assignment operator - /// \param[in] _other The new SkeletonAnimation - /// \return A reference to this instance - public: SkeletonAnimation &operator=(const SkeletonAnimation &_other); - - /// \brief Changes the name - /// \param[in] _name the new name - public: void SetName(const std::string& _name); - - /// \brief Returns the name - /// \return the name - public: std::string Name() const; - - /// \brief Returns the number of animation nodes - /// \return the count - public: unsigned int NodeCount() const; - - /// \brief Returns the node animation for given node name - /// \param[in] _name Name of node - /// \return NodeAnimation object - public: NodeAnimation *NodeAnimationByName(const std::string &_name) - const; - - /// \brief Looks for a node with a specific name in the animations - /// \param[in] _node the name of the node - /// \return true if the node exits - public: bool HasNode(const std::string &_node) const; - - /// \brief Adds or replaces a named key frame at a specific time - /// \param[in] _node the name of the new or existing node - /// \param[in] _time the time - /// \param[in] _mat the key frame transformation - public: void AddKeyFrame(const std::string &_node, const double _time, - const math::Matrix4d &_mat); - - /// \brief Adds or replaces a named key frame at a specific time - /// \param[in] _node the name of the new or existing node - /// \param[in] _time the time - /// \param[in] _pose the key frame transformation as a math::Pose - public: void AddKeyFrame(const std::string &_node, const double _time, - const math::Pose3d &_pose); - - /// \brief Returns the key frame transformation for a named animation at - /// a specific time - /// if a node does not exist at that time (with tolerance of 1e-6 sec), - /// the transformation is interpolated. - /// \param[in] _node the name of the animation node - /// \param[in] _time the time - /// \param[in] _loop when true, the time is divided by the duration - /// (see GetLength) - /// \return the transformation - public: math::Matrix4d NodePoseAt(const std::string &_node, - const double _time, const bool _loop = true) const; - - /// \brief Returns a dictionary of transformations indexed by name at - /// a specific time - /// if a node does not exist at that specific time - /// (with tolerance of 1e-6 sec), the transformation is interpolated. - /// \param[in] _time the time - /// \param[in] _loop when true, the time is divided by the duration - /// (see GetLength) - /// \return the transformation for every node - public: std::map PoseAt( - const double _time, const bool _loop = true) const; - - /// \brief Returns a dictionary of transformations indexed by name where - /// a named node transformation's translational value along the X axis is - /// equal to _x. - /// \param[in] _x the value along x. You must ensure that _x is within a - /// valid range. - /// \param[in] _node the name of the animation node - /// \param[in] _loop when true, the time is divided by the duration - /// (see GetLength) - public: std::map PoseAtX(const double _x, - const std::string &_node, const bool _loop = true) const; - - /// \brief Scales every animation in the animations list - /// \param[in] _scale the scaling factor - public: void Scale(const double _scale); - - /// \brief Returns the duration of the animations - /// \return the duration in seconds - public: double Length() const; - - /// \brief Private data pointer - private: SkeletonAnimationPrivate *data; - }; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/SkeletonNode.hh b/graphics/include/ignition/common/SkeletonNode.hh index e275f58bc..7a20f56fe 100644 --- a/graphics/include/ignition/common/SkeletonNode.hh +++ b/graphics/include/ignition/common/SkeletonNode.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,188 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_SKELETON_NODE_HH_ -#define IGNITION_COMMON_SKELETON_NODE_HH_ + */ -#include -#include -#include - -#include -#include - -namespace ignition -{ - namespace common - { - /// Forward declare private data class - class SkeletonNodePrivate; - - /// \class SkeletonNode Skeleton.hh ignition/common/SkeletonNode.hh - /// \brief A skeleton node - class IGNITION_COMMON_GRAPHICS_VISIBLE SkeletonNode - { - /// \brief enumeration of node types - public: enum SkeletonNodeType {NODE, JOINT}; - - /// \brief Constructor - /// \param[in] _parent The parent node - public: explicit SkeletonNode(SkeletonNode *_parent); - - /// \brief Constructor - /// \param[in] _parent the parent node - /// \param[in] _name name of node - /// \param[in] _id Id of node - /// \param[in] _type The type of this node - public: SkeletonNode(SkeletonNode *_parent, - const std::string &_name, - const std::string &_id, - const SkeletonNodeType _type = JOINT); - - /// \brief Destructor - public: virtual ~SkeletonNode(); - - /// \brief Change the name - /// \param[in] _name the new name - public: void Name(const std::string &_name); - - /// \brief Returns the name - /// \return the name - public: std::string Name() const; - - /// \brief Change the id string - /// \param[in] _id the new id string - public: void Id(const std::string &_id); - - /// \brief Returns the index - /// \return the id string - public: std::string Id() const; - - /// \brief Change the skeleton node type - /// \param[in] _type the new type - public: void SetType(const SkeletonNodeType _type); - - /// \brief Is a joint query - /// \return true if the skeleton type is a joint, false otherwise - public: bool IsJoint() const; - - /// \brief Set a transformation - /// \param[in] _trans the transformation - /// \param[in] _updateChildren when true the UpdateChildrenTransforms - /// operation is performed - public: void SetTransform(const math::Matrix4d &_trans, - const bool _updateChildren = true); - - /// \brief Set the model transformation - /// \param[in] _trans the transformation - /// \param[in] _updateChildren when true the UpdateChildrenTransforms - /// operation is performed - public: void SetModelTransform(const math::Matrix4d &_trans, - const bool _updateChildren = true); - - /// \brief Apply model transformations in order for each node in the tree - public: void UpdateChildrenTransforms(); - - /// \brief Sets the initial transformation - /// \param[in] _trans the transfromation matrix - public: void SetInitialTransform(const math::Matrix4d &_trans); - - /// \brief Reset the transformation to the initial transformation - /// \param[in] _resetChildren when true, performs the operation for every - /// node in the tree - public: void Reset(const bool _resetChildren); - - /// \brief Get transform relative to parent - public: math::Matrix4d Transform() const; - - /// \brief Set the parent node - /// \param[in] _parent the new parent - public: void SetParent(SkeletonNode *_parent); - - /// \brief Returns the parent node - /// \return the parent - public: SkeletonNode *Parent() const; - - /// \brief Queries wether a node has no parent parent - /// \return true if the node has no parent, fasle otherwise - public: bool IsRootNode() const; - - /// \brief Add a new child - /// \param[in] _child a child - public: void AddChild(SkeletonNode *_child); - - /// \brief Returns the children count - /// \return the count - public: unsigned int ChildCount() const; - - /// \brief Find a child by index - /// \param[in] _index the index - /// \return the child skeleton. - public: SkeletonNode *Child(const unsigned int _index) const; - - /// \brief Get child by name - /// \param[in] _name the name of the child skeleton - /// \return the skeleton, or NULL if not found - public: SkeletonNode *ChildByName(const std::string &_name) const; - - /// \brief Get child by string id - /// \param[in] _id the string id - /// \return the child skeleton or NULL if not found - public: SkeletonNode *ChildById(const std::string &_id) const; - - /// \brief Assign a handle number - /// \param[in] _h the handle - public: void Handle(const unsigned int _h); - - /// \brief Get the handle index - /// \return the handle index - public: unsigned int Handle() const; - - /// \brief Assign the inverse of the bind pose skeletal transform - /// \param[in] _invBM the transform - public: void SetInverseBindTransform(const math::Matrix4d &_invBM); - - /// \brief Retrieve the inverse of the bind pose skeletal transform - /// \return the transform - public: math::Matrix4d InverseBindTransform() const; - - /// \brief Returns true if the node has inv bind transform. - /// \detail to keep ABI compatibility, it checks if the inv bind transform - /// is the default value of zero. - /// \return true if the node has inv bind transform - public: bool HasInvBindTransform() const; - - /// \brief Retrieve the model transform - /// \return the transform - public: math::Matrix4d ModelTransform() const; - - /// \brief Retrieve the raw transformations - /// \return an array of transformations - public: std::vector RawTransforms() const; - - /// \brief Return the raw transformations count - /// \return the count - public: unsigned int RawTransformCount() const; - - /// \brief Find a raw transformation - /// \param[in] _i the index of the transformation - /// \return the node transform. - public: NodeTransform RawTransform(const unsigned int _i) const; - - /// \brief Add a raw transform - /// \param[in] _t the transform - public: void AddRawTransform(const NodeTransform &_t); - - /// \brief Returns a copy of the array of transformations. - /// \return the array of transform (These are the same as the raw trans) - public: std::vector Transforms() const; - - /// \brief Private data pointer - private: SkeletonNodePrivate *data; - }; - - typedef std::map SkeletonNodeMap; - } -} -#endif +#include +#include diff --git a/graphics/include/ignition/common/SubMesh.hh b/graphics/include/ignition/common/SubMesh.hh index 0a7ee0018..01fa03a6f 100644 --- a/graphics/include/ignition/common/SubMesh.hh +++ b/graphics/include/ignition/common/SubMesh.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,413 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_SUBMESH_HH_ -#define IGNITION_COMMON_SUBMESH_HH_ + */ -#include -#include -#include - -#include -#include - -#include -#include -#include - -namespace ignition -{ - namespace common - { - class SubMeshPrivate; - class Material; - class NodeAssignment; - - /// \brief A child mesh - class IGNITION_COMMON_GRAPHICS_VISIBLE SubMesh - { - /// \brief An enumeration of the geometric mesh primitives - public: enum PrimitiveType - { - /// \brief Point. 1 vertex per point - POINTS, - /// \brief Line. 2 vertices per line - LINES, - /// \brief Connected lines. 2 vertices for the first line and - /// every vertex specified afterwards creates a new line. - LINESTRIPS, - /// \brief Triangle type. 3 vertices per triangle. - TRIANGLES, - /// \brief Connected triangle in fan shape. 3 vertices for - /// the first triangle and every vertex specified afterwards - /// creates a new triangle. - TRIFANS, - /// \brief Connected triangle. 3 vertices for the first - /// triangle and every vertex specified afterwards creates a - /// new triangle. - TRISTRIPS - }; - - /// \brief Constructor - public: SubMesh(); - - /// \brief Constructor - /// \param _name Name of the submesh. - public: explicit SubMesh(const std::string &_name); - - /// \brief Copy Constructor - /// \brief _other Other mesh object - public: SubMesh(const SubMesh &_other); - - /// \brief Destructor - public: virtual ~SubMesh(); - - /// \brief Set the name of this mesh - /// \param[in] _n The name to set - public: void SetName(const std::string &_name); - - /// \brief Get the name of this mesh - /// \return The name - public: std::string Name() const; - - /// \brief Set the primitive type - /// \param[in] _type The primitive type - public: void SetPrimitiveType(PrimitiveType _type); - - /// \brief Get the primitive type - /// \return The primitive type - public: PrimitiveType SubMeshPrimitiveType() const; - - /// \brief Add an index to the mesh - /// \param[in] _index The new vertex index - public: void AddIndex(const unsigned int _index); - - /// \brief Add a vertex to the mesh - /// \param[in] _v The new position - public: void AddVertex(const ignition::math::Vector3d &_v); - - /// \brief Add a vertex to the mesh - /// \param[in] _x Position along x - /// \param[in] _y Position along y - /// \param[in] _z Position along z - public: void AddVertex(const double _x, const double _y, const double _z); - - /// \brief Add a normal to the mesh - /// \param[in] _n The normal - public: void AddNormal(const ignition::math::Vector3d &_n); - - /// \brief Add a normal to the mesh - /// \param[in] _x Position along x - /// \param[in] _y Position along y - /// \param[in] _z Position along z - public: void AddNormal(const double _x, const double _y, const double _z); - - /// \brief Add a texture coord to the mesh. If multiple texture - /// coordinate sets exist, this function adds it to the first texture - /// coordinate set in the submesh. If no previous texture coordinates - /// exist, it is added to set 0. - /// \param[in] _u Position along u - /// \param[in] _v Position along v - /// \sa AddTexCoordBySet - public: void AddTexCoord(const double _u, const double _v); - - /// \brief Add a texture coordinate to the mesh. If multiple texture - /// coordinate sets exist, this function adds it to the first texture - /// coordinate set in the submesh. If no previous texture coordinates - /// exist, it is added to set 0. - /// \param[in] _uv The texture coordinate - /// \sa AddTexCoordBySet - public: void AddTexCoord(const ignition::math::Vector2d &_uv); - - /// \brief Add a texture coord to a texture coordinate set of the mesh - /// \param[in] _u Position along u - /// \param[in] _v Position along v - /// \param[in] _setIndex Texture coordinate set index - public: void AddTexCoordBySet(double _u, double _v, - unsigned int _setIndex); - - /// \brief Add a texture coord to a texture coordinate set of the mesh - /// \param[in] _u Position along u - /// \param[in] _v Position along v - /// \param[in] _setIndex Texture coordinate set index - public: void AddTexCoordBySet(const ignition::math::Vector2d &_uv, - unsigned int _setIndex); - - /// \brief Add a vertex - skeleton node assignment - /// \param[in] _vertex The vertex index - /// \param[in] _node The node index - /// \param[in] _weight The weight (between 0 and 1) - public: void AddNodeAssignment(const unsigned int _vertex, - const unsigned int _node, - const float _weight); - /// \brief Get a vertex - /// \param[in] _index Index of the vertex - /// \return Coordinates of the vertex or ignition::math::Vector3d::Zero - /// if the index is out of bounds. - /// \sa bool HasVertex(const unsigned int) const - public: ignition::math::Vector3d Vertex(const unsigned int _index) const; - - /// \brief Set a vertex - /// \param[in] _index Index of the vertex - /// \param[in] _v The new vertex coordinate - public: void SetVertex(const unsigned int _index, - const ignition::math::Vector3d &_v); - - /// \brief Get a normal - /// \param[in] _index The normal index - /// \return The normal direction or ignition::math::Vector3d::Zero - /// if index is out of bounds. - /// \sa bool HasNormal(const unsigned int _index); - public: ignition::math::Vector3d Normal(const unsigned int _index) const; - - /// \brief Set a normal - /// \param[in] _index Index of the normal that will be set. - /// \param[in] _n The new normal direction - public: void SetNormal(const unsigned int _index, - const ignition::math::Vector3d &_n); - - /// \brief Get a texture coordinate - /// \param[in] _index the texture index - /// \return The texture coordinate or ignition::math::Vector2d::Zero - /// if index is out of bounds. - /// \sa bool HasTexCoord(const unsigned int _index) const - public: ignition::math::Vector2d TexCoord( - const unsigned int _index) const; - - /// \brief Get a texture coordinate for a texture coordinate set - /// \param[in] _index the texture index - /// \return The texture coordinate or ignition::math::Vector2d::Zero - /// if index is out of bounds. - /// \param[in] _setIndex Texture coordinate set index - /// \sa bool HasTexCoordBySet(unsigned int _index, unsigned int _setIndex) - /// const - public: ignition::math::Vector2d TexCoordBySet( - unsigned int _index, - unsigned int _setIndex) const; - - /// \brief Set a texture coordinate. If multiple texture - /// coordinate sets exist, this function sets the texture - /// coordinate in the first texture coordinate set in the submesh. - /// \param[in] _index Index of the texture coordinate that will be set. - /// \param[in] _uv The new texture coordinate - /// \sa SetTexCoordBySet - public: void SetTexCoord(const unsigned int _index, - const ignition::math::Vector2d &_uv); - - /// \brief Set a texture coordinate for a texture coordinate set - /// \param[in] _index Index of the texture coordinate that will be set. - /// \param[in] _uv The new texture coordinate - /// \param[in] _setIndex Texture coordinate set index - public: void SetTexCoordBySet(unsigned int _index, - const ignition::math::Vector2d &_uv, - unsigned int _setIdex); - - /// \brief Get an index value from the index array - /// \param[in] _index Array index. - /// \return The index, or -1 if the _index is out of bounds. - public: int Index(const unsigned int _index) const; - - /// \brief Set an index - /// \param[in] _index Index of the indices - /// \param[in] _i The new index value to set to - public: void SetIndex(const unsigned int _index, - const unsigned int _i); - - /// \brief Get a vertex - skeleton node assignment - /// \param[in] _index The index of the assignment - /// \return The skeleton node assignment, or a - /// default constructed skeleton node assignment when _index is - /// invalid. - /// \sa bool HasNodeAssignment(const unsigned int _index) const; - public: NodeAssignment NodeAssignmentByIndex( - const unsigned int _index) const; - - /// \brief Get the maximum X, Y, Z values from all the vertices - /// \return Max X,Y,Z values from all vertices in submesh - public: ignition::math::Vector3d Max() const; - - /// \brief Get the minimum X, Y, Z values from all the vertices - /// \return Min X,Y,Z values from all vertices in submesh - public: ignition::math::Vector3d Min() const; - - /// \brief Get the number of vertices - /// \return The number of vertices. - public: unsigned int VertexCount() const; - - /// \brief Return the number of normals - /// \return The number of normals. - public: unsigned int NormalCount() const; - - /// \brief Return the number of indices - /// \return The number of indices. - public: unsigned int IndexCount() const; - - /// \brief Return the number of texture coordinates. If multiple - /// texture coordinate sets exist, this function checks the first - /// texture coordinate set in the submesh, which by default is set 0, - /// unless AddTexCoordBySet is called with a different set index number - /// the first time a texture coordinate is added. - /// \return The number of texture coordinates. - /// \sa TexCoordCountBySet - public: unsigned int TexCoordCount() const; - - /// \brief Return the number of texture coordinates for a texture - /// coordinate set - /// \param[in] _setIndex Texture coordinate set index - /// \return The number of texture coordinates. - public: unsigned int TexCoordCountBySet(unsigned int _setIndex) const; - - /// \brief Return the number of texture coordinate sets - /// \return The number of texture coordinates sets. - public: unsigned int TexCoordSetCount() const; - - /// \brief Get the number of vertex-skeleton node assignments - /// \return The number of vertex-skeleton node assignments - public: unsigned int NodeAssignmentsCount() const; - - /// \brief Get the highest value in the index array. - /// \return The highest index value. - public: unsigned int MaxIndex() const; - - /// \brief Set the material index. Relates to the parent mesh material - /// list. - /// \param[in] _index Index to set the material to. - public: void SetMaterialIndex(const unsigned int _index); - - /// \brief Get the material index - /// \return The assigned material index. - public: unsigned int MaterialIndex() const; - - /// \brief Return true if this submesh has the vertex - /// \param[in] _v Vertex coordinate - /// \return Return true if this submesh has the vertex - public: bool HasVertex(const ignition::math::Vector3d &_v) const; - - /// \brief Return true if this submesh has the vertex with the given - /// index - /// \param[in] _index Vertex index - /// \return Return true if this submesh has the vertex with the given - /// _index. - public: bool HasVertex(const unsigned int _index) const; - - /// \brief Return true if this submesh has the normal with the given - /// index - /// \param[in] _index Normal index - /// \return Return true if this submesh has the normal with the given - /// _index. - public: bool HasNormal(const unsigned int _index) const; - - /// \brief Return true if this submesh has the texture coordinate with - /// the given index. If multiple texture coordinate sets exist, this - /// function checks the first texture coordinate set in the submesh, - /// which by default is set 0 unless AddTexCoordBySet is called with - /// a different set index number the first time a texture coordinate is - /// added. - /// \param[in] _index Texture coordinate index - /// \return Return true if this submesh has the texture coordinate with - /// the given _index. - /// \sa HasTexCoordBySet - public: bool HasTexCoord(const unsigned int _index) const; - - /// \brief Return true if this submesh has the texture coordinate with - /// the given index in a texture coordinate set - /// \param[in] _index Texture coordinate index - /// \param[in] _setIndex Texture coordinate set index - /// \return Return true if this submesh has the texture coordinate with - /// the given _index. - public: bool HasTexCoordBySet(unsigned int _index, unsigned int _setIndex) - const; - - /// \brief Return true if this submesh has the node assignment with - /// the given index - /// \param[in] _index Node assignment index - /// \return Return true if this submesh has the node assignment with - /// the given _index. - public: bool HasNodeAssignment(const unsigned int _index) const; - - /// \brief Get the index of the vertex - /// \param[in] _v Vertex to check - /// \return Index of the vertex that matches _v. - public: int IndexOfVertex(const ignition::math::Vector3d &_v) const; - - /// \brief Put all the data into flat arrays - /// \param[in] _verArr The vertex array to be filled. - /// \param[in] _indexndArr The index array to be filled. - public: void FillArrays(double **_vertArr, int **_indexndArr) const; - - /// \brief Recalculate all the normals. - public: void RecalculateNormals(); - - /// \brief Generate texture coordinates using spherical projection - /// from center - /// \param[in] _center Center of the projection. - public: void GenSphericalTexCoord( - const ignition::math::Vector3d &_center); - - /// \brief Generate texture coordinates for a texture coordinate set - /// using spherical projection from center - /// \param[in] _center Center of the projection. - /// \param[in] _setIndex Texture coordinate set index - public: void GenSphericalTexCoordBySet( - const ignition::math::Vector3d &_center, - unsigned int _setIndex); - - /// \brief Scale all vertices by _factor - /// \param[in] _factor Scaling factor - public: void Scale(const ignition::math::Vector3d &_factor); - - /// \brief Scale all vertices by _factor - /// \param[in] _factor Scaling factor - public: void Scale(const double &_factor); - - /// \brief Move the center of the submesh to the given coordinate. This - /// will move all the vertices. - /// \param[in] _center Location of the mesh center. - public: void Center(const ignition::math::Vector3d &_center = - ignition::math::Vector3d::Zero); - - /// \brief Move all vertices by _vec. - /// \param[in] _vec Amount to translate vertices. - public: void Translate(const ignition::math::Vector3d &_vec); - - /// \brief Compute the volume of this submesh. The primitive type - /// must be TRIANGLES. - /// - /// This function utilizes the mesh volume formula from - /// "Efficient feature extraction for 2d/3d objects in mesh - /// representation" by Cha Zhang and Tsuhan Chen. Link: - /// http://chenlab.ece.cornell.edu/Publication/Cha/icip01_Cha.pdf. - /// The formula does not check for a closed (water tight) mesh. - /// - /// \return The submesh's volume. The volume can be zero if - /// the primitive type is not TRIANGLES, or there are no triangles. - public: double Volume() const; - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief Private data pointer. - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - - /// \brief Vertex to node weighted assignement for skeleton animation - /// visualization - class IGNITION_COMMON_GRAPHICS_VISIBLE NodeAssignment - { - /// \brief Constructor. - public: NodeAssignment(); - - /// \brief Index of the vertex - public: unsigned int vertexIndex; - - /// \brief Node (or bone) index - public: unsigned int nodeIndex; - - /// \brief The weight (between 0 and 1). This determines how much the - /// node (bone) affects the vertex in animation. - public: float weight; - }; - } -} - -#endif +#include +#include diff --git a/graphics/include/ignition/common/graphics.hh b/graphics/include/ignition/common/graphics.hh new file mode 100644 index 000000000..f8ef1afa3 --- /dev/null +++ b/graphics/include/ignition/common/graphics.hh @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2022 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include diff --git a/graphics/include/ignition/common/graphics/Export.hh b/graphics/include/ignition/common/graphics/Export.hh new file mode 100644 index 000000000..92aec884e --- /dev/null +++ b/graphics/include/ignition/common/graphics/Export.hh @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2022 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include diff --git a/graphics/include/ignition/common/graphics/Types.hh b/graphics/include/ignition/common/graphics/Types.hh index bf0d619d1..cb4563e70 100644 --- a/graphics/include/ignition/common/graphics/Types.hh +++ b/graphics/include/ignition/common/graphics/Types.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,39 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ + */ -#ifndef IGNITION_COMMON_GRAPHICS_TYPES_HH_ -#define IGNITION_COMMON_GRAPHICS_TYPES_HH_ - -#include - -// This header contains forward declarations for some graphics types -namespace ignition -{ - namespace common - { - class Material; - class Mesh; - class Skeleton; - class SubMesh; - - /// \def MaterialPtr - /// \brief Shared pointer to a Material object - using MaterialPtr = std::shared_ptr; - - /// \def MeshPtr - /// \brief Standrd shared pointer to a Mesh object - using MeshPtr = std::shared_ptr; - - /// \def SubMeshPtr - /// \brief Shared pointer to a SubMesh object - using SubMeshPtr = std::shared_ptr; - - /// \def SkeletonPtr - /// \brief Shared pointer to a Skeleton object - using SkeletonPtr = std::shared_ptr; - } -} - -#endif +#include +#include diff --git a/graphics/src/Animation.cc b/graphics/src/Animation.cc index c577c75cf..46cdfe2c8 100644 --- a/graphics/src/Animation.cc +++ b/graphics/src/Animation.cc @@ -17,12 +17,12 @@ #include #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include using namespace ignition; using namespace common; @@ -80,7 +80,7 @@ static void DeleteAnimationDataPtr(Animation *_animation) } ///////////////////////////////////////////////// -class ignition::common::TrajectoryInfoPrivate +class gz::common::TrajectoryInfoPrivate { /// \brief ID of the trajectory public: unsigned int id{0}; diff --git a/graphics/src/Animation_TEST.cc b/graphics/src/Animation_TEST.cc index 4c1eccece..9ddc12449 100644 --- a/graphics/src/Animation_TEST.cc +++ b/graphics/src/Animation_TEST.cc @@ -19,10 +19,10 @@ #include "test_config.h" -#include -#include -#include -#include +#include +#include +#include +#include using namespace ignition; diff --git a/graphics/src/BVHLoader.cc b/graphics/src/BVHLoader.cc index 3a1ee7170..6ab960ee5 100644 --- a/graphics/src/BVHLoader.cc +++ b/graphics/src/BVHLoader.cc @@ -18,11 +18,11 @@ #include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include using namespace ignition; using namespace common; diff --git a/graphics/src/ColladaExporter.cc b/graphics/src/ColladaExporter.cc index ec0feaf47..92a32df78 100644 --- a/graphics/src/ColladaExporter.cc +++ b/graphics/src/ColladaExporter.cc @@ -14,14 +14,14 @@ * limitations under the License. * */ -#include +#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include "tinyxml2.h" @@ -78,7 +78,7 @@ static void LogTinyXml2DocumentError( } /// Private data for the ColladaExporter class -class ignition::common::ColladaExporterPrivate +class gz::common::ColladaExporterPrivate { /// \brief Geometry types public: enum GeometryType {POSITION, NORMAL, UVMAP}; diff --git a/graphics/src/ColladaExporter_TEST.cc b/graphics/src/ColladaExporter_TEST.cc index f005b163e..1d04981aa 100644 --- a/graphics/src/ColladaExporter_TEST.cc +++ b/graphics/src/ColladaExporter_TEST.cc @@ -18,11 +18,11 @@ #include "tinyxml2.h" #include "test_config.h" -#include "ignition/common/ColladaLoader.hh" -#include "ignition/common/ColladaExporter.hh" -#include "ignition/common/Filesystem.hh" -#include "ignition/common/Mesh.hh" -#include "ignition/common/SubMesh.hh" +#include "gz/common/ColladaLoader.hh" +#include "gz/common/ColladaExporter.hh" +#include "gz/common/Filesystem.hh" +#include "gz/common/Mesh.hh" +#include "gz/common/SubMesh.hh" #ifdef _WIN32 #define snprintf _snprintf diff --git a/graphics/src/ColladaLoader.cc b/graphics/src/ColladaLoader.cc index d9f3dff53..ef15c4cb9 100644 --- a/graphics/src/ColladaLoader.cc +++ b/graphics/src/ColladaLoader.cc @@ -20,23 +20,23 @@ #include #include -#include -#include -#include -#include +#include +#include +#include +#include #include "tinyxml2.h" -#include "ignition/common/graphics/Types.hh" -#include "ignition/common/Console.hh" -#include "ignition/common/Material.hh" -#include "ignition/common/SubMesh.hh" -#include "ignition/common/Mesh.hh" -#include "ignition/common/Skeleton.hh" -#include "ignition/common/SkeletonAnimation.hh" -#include "ignition/common/SystemPaths.hh" -#include "ignition/common/Util.hh" -#include "ignition/common/ColladaLoader.hh" +#include "gz/common/graphics/Types.hh" +#include "gz/common/Console.hh" +#include "gz/common/Material.hh" +#include "gz/common/SubMesh.hh" +#include "gz/common/Mesh.hh" +#include "gz/common/Skeleton.hh" +#include "gz/common/SkeletonAnimation.hh" +#include "gz/common/SystemPaths.hh" +#include "gz/common/Util.hh" +#include "gz/common/ColladaLoader.hh" using namespace ignition; using namespace common; diff --git a/graphics/src/ColladaLoader_TEST.cc b/graphics/src/ColladaLoader_TEST.cc index 9ad32fae1..6ee6d1554 100644 --- a/graphics/src/ColladaLoader_TEST.cc +++ b/graphics/src/ColladaLoader_TEST.cc @@ -17,12 +17,12 @@ #include #include "test_config.h" -#include "ignition/common/Mesh.hh" -#include "ignition/common/SubMesh.hh" -#include "ignition/common/Material.hh" -#include "ignition/common/ColladaLoader.hh" -#include "ignition/common/Skeleton.hh" -#include "ignition/common/SkeletonAnimation.hh" +#include "gz/common/Mesh.hh" +#include "gz/common/SubMesh.hh" +#include "gz/common/Material.hh" +#include "gz/common/ColladaLoader.hh" +#include "gz/common/Skeleton.hh" +#include "gz/common/SkeletonAnimation.hh" using namespace ignition; class ColladaLoader : public common::testing::AutoLogFixture { }; diff --git a/graphics/src/Dem.cc b/graphics/src/Dem.cc index c95b3b3f1..9344ff490 100644 --- a/graphics/src/Dem.cc +++ b/graphics/src/Dem.cc @@ -23,16 +23,16 @@ # pragma GCC diagnostic pop #endif -#include "ignition/common/Console.hh" -#include "ignition/common/Dem.hh" -#include "ignition/math/SphericalCoordinates.hh" +#include "gz/common/Console.hh" +#include "gz/common/Dem.hh" +#include "gz/math/SphericalCoordinates.hh" using namespace ignition; using namespace common; #ifdef HAVE_GDAL -class ignition::common::DemPrivate +class gz::common::DemPrivate { /// \brief A set of associated raster bands. public: GDALDataset *dataSet; diff --git a/graphics/src/Dem_TEST.cc b/graphics/src/Dem_TEST.cc index 1162e019d..fefc726ba 100644 --- a/graphics/src/Dem_TEST.cc +++ b/graphics/src/Dem_TEST.cc @@ -16,10 +16,10 @@ */ #include -#include -#include +#include +#include -#include "ignition/common/Dem.hh" +#include "gz/common/Dem.hh" #include "test_config.h" using namespace ignition; diff --git a/graphics/src/GTSMeshUtils.cc b/graphics/src/GTSMeshUtils.cc index debd44e47..f2f16ab65 100644 --- a/graphics/src/GTSMeshUtils.cc +++ b/graphics/src/GTSMeshUtils.cc @@ -18,10 +18,10 @@ #include -#include -#include -#include -#include +#include +#include +#include +#include using namespace ignition; using namespace common; diff --git a/graphics/src/GTSMeshUtils_TEST.cc b/graphics/src/GTSMeshUtils_TEST.cc index 489190ef0..0de5c4f7f 100644 --- a/graphics/src/GTSMeshUtils_TEST.cc +++ b/graphics/src/GTSMeshUtils_TEST.cc @@ -19,9 +19,9 @@ #include #include "test_config.h" -#include "ignition/common/GTSMeshUtils.hh" -#include "ignition/common/Mesh.hh" -#include "ignition/common/SubMesh.hh" +#include "gz/common/GTSMeshUtils.hh" +#include "gz/common/Mesh.hh" +#include "gz/common/SubMesh.hh" using namespace ignition; diff --git a/graphics/src/Image.cc b/graphics/src/Image.cc index 750c1306d..f1571eaa6 100644 --- a/graphics/src/Image.cc +++ b/graphics/src/Image.cc @@ -21,9 +21,9 @@ #include -#include -#include -#include +#include +#include +#include using namespace ignition; using namespace common; diff --git a/graphics/src/ImageHeightmap.cc b/graphics/src/ImageHeightmap.cc index b6a17765e..e2b9854b9 100644 --- a/graphics/src/ImageHeightmap.cc +++ b/graphics/src/ImageHeightmap.cc @@ -14,8 +14,8 @@ * limitations under the License. * */ -#include "ignition/common/Console.hh" -#include "ignition/common/ImageHeightmap.hh" +#include "gz/common/Console.hh" +#include "gz/common/ImageHeightmap.hh" using namespace ignition; using namespace common; diff --git a/graphics/src/ImageHeightmap_TEST.cc b/graphics/src/ImageHeightmap_TEST.cc index c2eb0617d..fa4f52720 100644 --- a/graphics/src/ImageHeightmap_TEST.cc +++ b/graphics/src/ImageHeightmap_TEST.cc @@ -16,7 +16,7 @@ */ #include -#include "ignition/common/ImageHeightmap.hh" +#include "gz/common/ImageHeightmap.hh" #include "test_config.h" #define ELEVATION_TOL 1e-8 diff --git a/graphics/src/Image_TEST.cc b/graphics/src/Image_TEST.cc index e072d45f5..e013a9743 100644 --- a/graphics/src/Image_TEST.cc +++ b/graphics/src/Image_TEST.cc @@ -17,7 +17,7 @@ #include -#include +#include #include "test_config.h" using namespace ignition; diff --git a/graphics/src/KeyFrame.cc b/graphics/src/KeyFrame.cc index 66ea2b36b..952f4728a 100644 --- a/graphics/src/KeyFrame.cc +++ b/graphics/src/KeyFrame.cc @@ -14,7 +14,7 @@ * limitations under the License. * */ -#include +#include using namespace ignition; using namespace common; diff --git a/graphics/src/Material.cc b/graphics/src/Material.cc index f325ce532..50e1779dd 100644 --- a/graphics/src/Material.cc +++ b/graphics/src/Material.cc @@ -15,10 +15,10 @@ * */ #include -#include +#include -#include "ignition/common/Material.hh" -#include "ignition/common/Console.hh" +#include "gz/common/Material.hh" +#include "gz/common/Console.hh" using namespace ignition; using namespace common; @@ -32,7 +32,7 @@ IGN_ENUM(blendModeIface, Material::BlendMode, "ADD", "MODULATE", "REPLACE") /// \brief Private data for Material -class ignition::common::MaterialPrivate +class gz::common::MaterialPrivate { /// \brief the name of the material public: std::string name; diff --git a/graphics/src/Material_TEST.cc b/graphics/src/Material_TEST.cc index add9e417f..67366ece6 100644 --- a/graphics/src/Material_TEST.cc +++ b/graphics/src/Material_TEST.cc @@ -17,8 +17,8 @@ #include #include "test_config.h" -#include "ignition/common/Material.hh" -#include "ignition/common/Pbr.hh" +#include "gz/common/Material.hh" +#include "gz/common/Pbr.hh" using namespace ignition; diff --git a/graphics/src/Mesh.cc b/graphics/src/Mesh.cc index 9aa422d7d..f3891700c 100644 --- a/graphics/src/Mesh.cc +++ b/graphics/src/Mesh.cc @@ -18,19 +18,19 @@ #include #include -#include "ignition/math/Helpers.hh" +#include "gz/math/Helpers.hh" -#include "ignition/common/Console.hh" -#include "ignition/common/Material.hh" -#include "ignition/common/Skeleton.hh" -#include "ignition/common/SubMesh.hh" -#include "ignition/common/Mesh.hh" +#include "gz/common/Console.hh" +#include "gz/common/Material.hh" +#include "gz/common/Skeleton.hh" +#include "gz/common/SubMesh.hh" +#include "gz/common/Mesh.hh" using namespace ignition; using namespace common; /// \brief Private data for Mesh -class ignition::common::MeshPrivate +class gz::common::MeshPrivate { /// \brief The name of the mesh public: std::string name; diff --git a/graphics/src/MeshCSG.cc b/graphics/src/MeshCSG.cc index 0fdb3e525..8e4813173 100644 --- a/graphics/src/MeshCSG.cc +++ b/graphics/src/MeshCSG.cc @@ -19,10 +19,10 @@ #include -#include "ignition/common/Console.hh" -#include "ignition/common/Mesh.hh" -#include "ignition/common/SubMesh.hh" -#include "ignition/common/MeshCSG.hh" +#include "gz/common/Console.hh" +#include "gz/common/Mesh.hh" +#include "gz/common/SubMesh.hh" +#include "gz/common/MeshCSG.hh" using namespace ignition; using namespace common; diff --git a/graphics/src/MeshExporter.cc b/graphics/src/MeshExporter.cc index 5503b2d74..a267d5055 100644 --- a/graphics/src/MeshExporter.cc +++ b/graphics/src/MeshExporter.cc @@ -14,7 +14,7 @@ * limitations under the License. * */ -#include "ignition/common/MeshExporter.hh" +#include "gz/common/MeshExporter.hh" using namespace ignition; using namespace common; diff --git a/graphics/src/MeshManager.cc b/graphics/src/MeshManager.cc index 9ef187ecf..ecb96a289 100644 --- a/graphics/src/MeshManager.cc +++ b/graphics/src/MeshManager.cc @@ -22,24 +22,24 @@ #include #ifndef _WIN32 - #include "ignition/common/GTSMeshUtils.hh" - #include "ignition/common/MeshCSG.hh" + #include "gz/common/GTSMeshUtils.hh" + #include "gz/common/MeshCSG.hh" #endif -#include "ignition/common/Console.hh" -#include "ignition/common/Mesh.hh" -#include "ignition/common/SubMesh.hh" -#include "ignition/common/ColladaLoader.hh" -#include "ignition/common/ColladaExporter.hh" -#include "ignition/common/OBJLoader.hh" -#include "ignition/common/STLLoader.hh" -#include "ignition/common/config.hh" +#include "gz/common/Console.hh" +#include "gz/common/Mesh.hh" +#include "gz/common/SubMesh.hh" +#include "gz/common/ColladaLoader.hh" +#include "gz/common/ColladaExporter.hh" +#include "gz/common/OBJLoader.hh" +#include "gz/common/STLLoader.hh" +#include "gz/common/config.hh" -#include "ignition/common/MeshManager.hh" +#include "gz/common/MeshManager.hh" using namespace ignition::common; -class ignition::common::MeshManagerPrivate +class gz::common::MeshManagerPrivate { #ifdef _WIN32 // Disable warning C4251 @@ -77,17 +77,17 @@ MeshManager::MeshManager() { // Create some basic shapes this->CreatePlane("unit_plane", - ignition::math::Planed( - ignition::math::Vector3d(0, 0, 1), ignition::math::Vector2d(1, 1), 0), - ignition::math::Vector2d(1, 1), - ignition::math::Vector2d(1, 1)); + gz::math::Planed( + gz::math::Vector3d(0, 0, 1), gz::math::Vector2d(1, 1), 0), + gz::math::Vector2d(1, 1), + gz::math::Vector2d(1, 1)); this->CreateSphere("unit_sphere", 0.5f, 32, 32); this->CreateSphere("joint_anchor", 0.01f, 32, 32); - this->CreateBox("body_cg", ignition::math::Vector3d(0.014, 0.014, 0.014), - ignition::math::Vector2d(0.014, 0.014)); - this->CreateBox("unit_box", ignition::math::Vector3d(1, 1, 1), - ignition::math::Vector2d(1, 1)); + this->CreateBox("body_cg", gz::math::Vector3d(0.014, 0.014, 0.014), + gz::math::Vector2d(0.014, 0.014)); + this->CreateBox("unit_box", gz::math::Vector3d(1, 1, 1), + gz::math::Vector2d(1, 1)); this->CreateCylinder("unit_cylinder", 0.5, 1.0, 1, 32); this->CreateCone("unit_cone", 0.5, 1.0, 5, 32); this->CreateCamera("unit_camera", 0.5); @@ -206,8 +206,8 @@ bool MeshManager::IsValidFilename(const std::string &_filename) ////////////////////////////////////////////////// void MeshManager::MeshAABB(const Mesh *_mesh, - ignition::math::Vector3d &_center, - ignition::math::Vector3d &_minXYZ, ignition::math::Vector3d &_maxXYZ) + gz::math::Vector3d &_center, + gz::math::Vector3d &_minXYZ, gz::math::Vector3d &_maxXYZ) { if (this->HasMesh(_mesh->Name())) this->dataPtr->meshes[_mesh->Name()]->AABB(_center, _minXYZ, _maxXYZ); @@ -215,7 +215,7 @@ void MeshManager::MeshAABB(const Mesh *_mesh, ////////////////////////////////////////////////// void MeshManager::GenSphericalTexCoord(const Mesh *_mesh, - const ignition::math::Vector3d &_center) + const gz::math::Vector3d &_center) { if (this->HasMesh(_mesh->Name())) this->dataPtr->meshes[_mesh->Name()]->GenSphericalTexCoord(_center); @@ -265,7 +265,7 @@ void MeshManager::CreateSphere(const std::string &name, float radius, int ring, seg; float deltaSegAngle = (2.0 * IGN_PI / segments); float deltaRingAngle = (IGN_PI / rings); - ignition::math::Vector3d vert, norm; + gz::math::Vector3d vert, norm; unsigned int verticeIndex = 0; Mesh *mesh = new Mesh(); @@ -315,9 +315,9 @@ void MeshManager::CreateSphere(const std::string &name, float radius, ////////////////////////////////////////////////// void MeshManager::CreatePlane(const std::string &_name, - const ignition::math::Planed &_plane, - const ignition::math::Vector2d &_segments, - const ignition::math::Vector2d &_uvTile) + const gz::math::Planed &_plane, + const gz::math::Vector2d &_segments, + const gz::math::Vector2d &_uvTile) { this->CreatePlane(_name, _plane.Normal(), _plane.Offset(), _plane.Size(), _segments, _uvTile); @@ -325,11 +325,11 @@ void MeshManager::CreatePlane(const std::string &_name, ////////////////////////////////////////////////// void MeshManager::CreatePlane(const std::string &_name, - const ignition::math::Vector3d &_normal, + const gz::math::Vector3d &_normal, const double _d, - const ignition::math::Vector2d &_size, - const ignition::math::Vector2d &_segments, - const ignition::math::Vector2d &_uvTile) + const gz::math::Vector2d &_size, + const gz::math::Vector2d &_segments, + const gz::math::Vector2d &_uvTile) { if (this->HasMesh(_name)) { @@ -342,16 +342,16 @@ void MeshManager::CreatePlane(const std::string &_name, SubMesh subMesh; - ignition::math::Vector3d zAxis, yAxis, xAxis; + gz::math::Vector3d zAxis, yAxis, xAxis; zAxis = _normal; zAxis.Normalize(); yAxis = zAxis.Perpendicular(); xAxis = yAxis.Cross(zAxis); - ignition::math::Matrix4d xlate, xform, rot; - xlate = rot = ignition::math::Matrix4d::Identity; + gz::math::Matrix4d xlate, xform, rot; + xlate = rot = gz::math::Matrix4d::Identity; - ignition::math::Matrix3d rot3; + gz::math::Matrix3d rot3; rot3.Axes(xAxis, yAxis, zAxis); rot = rot3; @@ -359,8 +359,8 @@ void MeshManager::CreatePlane(const std::string &_name, xlate.SetTranslation(_normal * -_d); xform = xlate * rot; - ignition::math::Vector3d vec; - ignition::math::Vector3d norm(0, 0, 1); + gz::math::Vector3d vec; + gz::math::Vector3d norm(0, 0, 1); double xSpace = _size.X() / _segments.X(); double ySpace = _size.Y() / _segments.Y(); double halfWidth = _size.X() / 2.0; @@ -412,8 +412,8 @@ void MeshManager::CreatePlane(const std::string &_name, ////////////////////////////////////////////////// void MeshManager::CreateBox(const std::string &_name, - const ignition::math::Vector3d &_sides, - const ignition::math::Vector2d &_uvCoords) + const gz::math::Vector3d &_sides, + const gz::math::Vector2d &_uvCoords) { int i, k; @@ -514,7 +514,7 @@ void MeshManager::CreateBox(const std::string &_name, ////////////////////////////////////////////////// void MeshManager::CreateExtrudedPolyline(const std::string &_name, - const std::vector > &_polys, + const std::vector > &_polys, double _height) { #ifndef _WIN32 @@ -549,8 +549,8 @@ void MeshManager::CreateExtrudedPolyline(const std::string &_name, SubMesh subMesh; - std::vector vertices; - std::vector edges; + std::vector vertices; + std::vector edges; MeshManager::ConvertPolylinesToVerticesAndEdges(polys, tol, vertices, @@ -562,23 +562,23 @@ void MeshManager::CreateExtrudedPolyline(const std::string &_name, return; } - std::vector normals; + std::vector normals; for (unsigned int i = 0; i < edges.size(); ++i) { // we retrieve each edge's coordinates int i0 = edges[i][0]; int i1 = edges[i][1]; - ignition::math::Vector2d edgeV0 = vertices[i0]; - ignition::math::Vector2d edgeV1 = vertices[i1]; + gz::math::Vector2d edgeV0 = vertices[i0]; + gz::math::Vector2d edgeV1 = vertices[i1]; // we look for those points in the subMesh (where indices may have changed) for (unsigned int j = 0; j < subMesh.IndexCount(); j+=3) { - ignition::math::Vector3d v0 = subMesh.Vertex(subMesh.Index(j)); - ignition::math::Vector3d v1 = subMesh.Vertex(subMesh.Index(j+1)); - ignition::math::Vector3d v2 = subMesh.Vertex(subMesh.Index(j+2)); + gz::math::Vector3d v0 = subMesh.Vertex(subMesh.Index(j)); + gz::math::Vector3d v1 = subMesh.Vertex(subMesh.Index(j+1)); + gz::math::Vector3d v2 = subMesh.Vertex(subMesh.Index(j+2)); - std::vector triangle; + std::vector triangle; triangle.push_back(v0); triangle.push_back(v1); triangle.push_back(v2); @@ -586,7 +586,7 @@ void MeshManager::CreateExtrudedPolyline(const std::string &_name, int ev0 = -1; for (unsigned int k = 0; k < triangle.size(); ++k) { - if (ignition::math::Vector2d(triangle[k].X(), triangle[k].Y()) == + if (gz::math::Vector2d(triangle[k].X(), triangle[k].Y()) == edgeV0) { // found a vertex in triangle that matches the vertex of the edge @@ -601,7 +601,7 @@ void MeshManager::CreateExtrudedPolyline(const std::string &_name, for (unsigned int k = 0; k < triangle.size()-1; ++k) { int index = (ev0 + k + 1) % triangle.size(); - ignition::math::Vector3d triV = triangle[index]; + gz::math::Vector3d triV = triangle[index]; if (math::Vector2d(triV.X(), triV.Y()) == edgeV1) { // found another vertex in triangle that matches the vertex of the @@ -618,11 +618,11 @@ void MeshManager::CreateExtrudedPolyline(const std::string &_name, // Found an edge in triangle that matches the exterior edge. // Now find its normal. - ignition::math::Vector3d edgeVec = triangle[ev0] - triangle[ev1]; + gz::math::Vector3d edgeVec = triangle[ev0] - triangle[ev1]; edgeVec.Normalize(); - ignition::math::Vector3d normal(edgeVec.Y(), -edgeVec.X(), 0); + gz::math::Vector3d normal(edgeVec.Y(), -edgeVec.X(), 0); - ignition::math::Vector3d otherEdgeVec = triangle[ev0] - triangle[ev2]; + gz::math::Vector3d otherEdgeVec = triangle[ev0] - triangle[ev2]; otherEdgeVec.Normalize(); double angle0 = otherEdgeVec.Dot(normal); double angle1 = otherEdgeVec.Dot(-normal); @@ -655,14 +655,14 @@ void MeshManager::CreateExtrudedPolyline(const std::string &_name, // add normal for bottom face for (unsigned int i = 0; i < numVertices; ++i) - subMesh.AddNormal(-ignition::math::Vector3d::UnitZ); + subMesh.AddNormal(-gz::math::Vector3d::UnitZ); // create the top face for (unsigned int i = 0; i < numVertices; ++i) { - ignition::math::Vector3d v = subMesh.Vertex(i); + gz::math::Vector3d v = subMesh.Vertex(i); subMesh.AddVertex(v.X(), v.Y(), _height); - subMesh.AddNormal(ignition::math::Vector3d::UnitZ); + subMesh.AddNormal(gz::math::Vector3d::UnitZ); } unsigned int numIndices = subMesh.IndexCount(); for (unsigned int i = 0; i < numIndices; i+=3) @@ -681,36 +681,36 @@ void MeshManager::CreateExtrudedPolyline(const std::string &_name, // we retrieve each edge's coordinates int i0 = edges[i][0]; int i1 = edges[i][1]; - ignition::math::Vector2d v0 = vertices[i0]; - ignition::math::Vector2d v1 = vertices[i1]; + gz::math::Vector2d v0 = vertices[i0]; + gz::math::Vector2d v1 = vertices[i1]; - ignition::math::Vector2d edge2d = v1 - v0; - ignition::math::Vector3d edge(edge2d.X(), edge2d.Y(), 0); - ignition::math::Vector3d cross = edge.Cross(normals[i]); + gz::math::Vector2d edge2d = v1 - v0; + gz::math::Vector3d edge(edge2d.X(), edge2d.Y(), 0); + gz::math::Vector3d cross = edge.Cross(normals[i]); unsigned int vCount = subMesh.VertexCount(); - subMesh.AddVertex(ignition::math::Vector3d(v0.X(), v0.Y(), 0)); + subMesh.AddVertex(gz::math::Vector3d(v0.X(), v0.Y(), 0)); if (cross.Z() >0) { - subMesh.AddVertex(ignition::math::Vector3d(v0.X(), v0.Y(), _height)); - subMesh.AddVertex(ignition::math::Vector3d(v1.X(), v1.Y(), _height)); + subMesh.AddVertex(gz::math::Vector3d(v0.X(), v0.Y(), _height)); + subMesh.AddVertex(gz::math::Vector3d(v1.X(), v1.Y(), _height)); } else { - subMesh.AddVertex(ignition::math::Vector3d(v1.X(), v1.Y(), _height)); - subMesh.AddVertex(ignition::math::Vector3d(v0.X(), v0.Y(), _height)); + subMesh.AddVertex(gz::math::Vector3d(v1.X(), v1.Y(), _height)); + subMesh.AddVertex(gz::math::Vector3d(v0.X(), v0.Y(), _height)); } - subMesh.AddVertex(ignition::math::Vector3d(v0.X(), v0.Y(), 0)); + subMesh.AddVertex(gz::math::Vector3d(v0.X(), v0.Y(), 0)); if (cross.Z() >0) { - subMesh.AddVertex(ignition::math::Vector3d(v1.X(), v1.Y(), _height)); - subMesh.AddVertex(ignition::math::Vector3d(v1.X(), v1.Y(), 0)); + subMesh.AddVertex(gz::math::Vector3d(v1.X(), v1.Y(), _height)); + subMesh.AddVertex(gz::math::Vector3d(v1.X(), v1.Y(), 0)); } else { - subMesh.AddVertex(ignition::math::Vector3d(v1.X(), v1.Y(), 0)); - subMesh.AddVertex(ignition::math::Vector3d(v1.X(), v1.Y(), _height)); + subMesh.AddVertex(gz::math::Vector3d(v1.X(), v1.Y(), 0)); + subMesh.AddVertex(gz::math::Vector3d(v1.X(), v1.Y(), _height)); } for (unsigned int j = 0; j < 6; ++j) { @@ -824,7 +824,7 @@ void MeshManager::CreateCamera(const std::string &_name, float _scale) ////////////////////////////////////////////////// void MeshManager::CreateEllipsoid(const std::string &_name, - const ignition::math::Vector3d &_radii, + const gz::math::Vector3d &_radii, const unsigned int _rings, const unsigned int _segments) { @@ -860,22 +860,22 @@ void MeshManager::CreateEllipsoid(const std::string &_name, const auto s_phi = sin(phi); // Compute vertex - subMesh.AddVertex(ignition::math::Vector3d( + subMesh.AddVertex(gz::math::Vector3d( _radii.X() * c_phi * c_theta, _radii.Y() * c_phi * s_theta, _radii.Z() * s_phi)); // Compute unit normal at vertex - ignition::math::Vector3d du( + gz::math::Vector3d du( -(_radii.X() * c_phi) * s_theta, +(_radii.Y() * c_phi) * c_theta, 0.0); - ignition::math::Vector3d dv( + gz::math::Vector3d dv( -_radii.X() * s_phi * c_theta, -_radii.Y() * s_phi * s_theta, _radii.Z() * c_phi); - ignition::math::Vector3d normal = du.Cross(dv); + gz::math::Vector3d normal = du.Cross(dv); subMesh.AddNormal(normal); @@ -944,11 +944,11 @@ void MeshManager::CreateCapsule(const std::string &_name, x = -sin(u * (IGN_PI * 2.0)); z = cos(u * (IGN_PI * 2.0)); - ignition::math::Vector3d p( + gz::math::Vector3d p( x * _radius * w, y, -z * _radius * w); // Compute vertex - subMesh.AddVertex(ignition::math::Vector3d( - p + ignition::math::Vector3d(0.0, 0.5 * _length, 0.0))); + subMesh.AddVertex(gz::math::Vector3d( + p + gz::math::Vector3d(0.0, 0.5 * _length, 0.0))); subMesh.AddTexCoord({u, v * oneThird}); subMesh.AddNormal(p.Normalize()); @@ -985,13 +985,13 @@ void MeshManager::CreateCapsule(const std::string &_name, x = -sin(u * (IGN_PI * 2.0)); z = cos(u * (IGN_PI * 2.0)); - ignition::math::Vector3d p( + gz::math::Vector3d p( x * _radius, y, -z * _radius); // Compute vertex subMesh.AddVertex(p); subMesh.AddTexCoord({u, oneThird + (v * oneThird)}); - subMesh.AddNormal(ignition::math::Vector3d(x, 0.0, -z)); + subMesh.AddNormal(gz::math::Vector3d(x, 0.0, -z)); point++; if (i > 0 && j > 0) { @@ -1026,11 +1026,11 @@ void MeshManager::CreateCapsule(const std::string &_name, x = -sin(u2 * (IGN_PI * 2.0)); z = cos(u2 * (IGN_PI * 2.0)); - ignition::math::Vector3d p( + gz::math::Vector3d p( x * _radius * w, y, -z * _radius * w); // Compute vertex - subMesh.AddVertex(ignition::math::Vector3d( - p + ignition::math::Vector3d(0.0, -0.5 * _length, 0.0))); + subMesh.AddVertex(gz::math::Vector3d( + p + gz::math::Vector3d(0.0, -0.5 * _length, 0.0))); subMesh.AddTexCoord({u2, twoThirds + ((v - 1.0) * oneThird)}); subMesh.AddNormal(p.Normalize()); point++; @@ -1057,7 +1057,7 @@ void MeshManager::CreateCapsule(const std::string &_name, void MeshManager::CreateCylinder(const std::string &name, float radius, float height, int rings, int segments) { - ignition::math::Vector3d vert, norm; + gz::math::Vector3d vert, norm; unsigned int verticeIndex = 0; int ring, seg; float deltaSegAngle = (2.0 * IGN_PI / segments); @@ -1174,7 +1174,7 @@ void MeshManager::CreateCylinder(const std::string &name, float radius, void MeshManager::CreateCone(const std::string &name, float radius, float height, int rings, int segments) { - ignition::math::Vector3d vert, norm; + gz::math::Vector3d vert, norm; unsigned int verticeIndex = 0; unsigned int i, j; int ring, seg; @@ -1284,7 +1284,7 @@ void MeshManager::CreateCone(const std::string &name, float radius, void MeshManager::CreateTube(const std::string &_name, float _innerRadius, float _outerRadius, float _height, int _rings, int _segments, double _arc) { - ignition::math::Vector3d vert, norm; + gz::math::Vector3d vert, norm; unsigned int verticeIndex = 0; int ring, seg; @@ -1419,7 +1419,7 @@ void MeshManager::CreateTube(const std::string &_name, float _innerRadius, } // Close ends in case it's not a full circle - if (!ignition::math::equal(_arc, 2.0 * IGN_PI)) + if (!gz::math::equal(_arc, 2.0 * IGN_PI)) { for (ring = 0; ring < rings; ++ring) { @@ -1515,7 +1515,7 @@ void MeshManager::Tesselate2DMesh(SubMesh *sm, int meshWidth, int meshHeight, ////////////////////////////////////////////////// void MeshManager::CreateBoolean(const std::string &_name, const Mesh *_m1, - const Mesh *_m2, int _operation, const ignition::math::Pose3d &_offset) + const Mesh *_m2, int _operation, const gz::math::Pose3d &_offset) { if (this->HasMesh(_name)) return; @@ -1530,8 +1530,8 @@ void MeshManager::CreateBoolean(const std::string &_name, const Mesh *_m1, ////////////////////////////////////////////////// size_t MeshManager::AddUniquePointToVerticesTable( - std::vector &_vertices, - const ignition::math::Vector2d &_p, + std::vector &_vertices, + const gz::math::Vector2d &_p, double _tol) { double sqrTol = _tol * _tol; @@ -1551,14 +1551,14 @@ size_t MeshManager::AddUniquePointToVerticesTable( ////////////////////////////////////////////////// void MeshManager::ConvertPolylinesToVerticesAndEdges( - const std::vector > &_polys, + const std::vector > &_polys, double _tol, - std::vector &_vertices, - std::vector &edges) + std::vector &_vertices, + std::vector &edges) { for (auto poly : _polys) { - ignition::math::Vector2d previous = poly[0]; + gz::math::Vector2d previous = poly[0]; for (auto i = 1u; i != poly.size(); ++i) { auto p = poly[i]; @@ -1574,7 +1574,7 @@ void MeshManager::ConvertPolylinesToVerticesAndEdges( continue; } // add the new edge - ignition::math::Vector2i e(startPointIndex, endPointIndex); + gz::math::Vector2i e(startPointIndex, endPointIndex); edges.push_back(e); } } diff --git a/graphics/src/MeshManager_TEST.cc b/graphics/src/MeshManager_TEST.cc index 742c6fe73..0c7798ef1 100644 --- a/graphics/src/MeshManager_TEST.cc +++ b/graphics/src/MeshManager_TEST.cc @@ -18,10 +18,10 @@ #include #include "test_config.h" -#include "ignition/common/Mesh.hh" -#include "ignition/common/SubMesh.hh" -#include "ignition/common/MeshManager.hh" -#include "ignition/common/config.hh" +#include "gz/common/Mesh.hh" +#include "gz/common/SubMesh.hh" +#include "gz/common/MeshManager.hh" +#include "gz/common/config.hh" using namespace ignition; diff --git a/graphics/src/Mesh_TEST.cc b/graphics/src/Mesh_TEST.cc index e714c317a..77268cdeb 100644 --- a/graphics/src/Mesh_TEST.cc +++ b/graphics/src/Mesh_TEST.cc @@ -18,11 +18,11 @@ #include #include "test_config.h" -#include "ignition/common/Material.hh" -#include "ignition/common/Mesh.hh" -#include "ignition/common/Skeleton.hh" -#include "ignition/common/SubMesh.hh" -#include "ignition/math/Vector3.hh" +#include "gz/common/Material.hh" +#include "gz/common/Mesh.hh" +#include "gz/common/Skeleton.hh" +#include "gz/common/SubMesh.hh" +#include "gz/math/Vector3.hh" using namespace ignition; diff --git a/graphics/src/NodeAnimation.cc b/graphics/src/NodeAnimation.cc index c77677408..cba56aadd 100644 --- a/graphics/src/NodeAnimation.cc +++ b/graphics/src/NodeAnimation.cc @@ -15,14 +15,14 @@ * */ #include -#include "ignition/common/Console.hh" -#include "ignition/common/NodeAnimation.hh" +#include "gz/common/Console.hh" +#include "gz/common/NodeAnimation.hh" using namespace ignition; using namespace common; /// \brief NodeAnimation private data -class ignition::common::NodeAnimationPrivate +class gz::common::NodeAnimationPrivate { /// \brief the name of the animation public: std::string name; @@ -222,5 +222,3 @@ double NodeAnimation::TimeAtX(const double _x) const return t1 + ((t2 - t1) * (_x - x1) / (x2 - x1)); } - - diff --git a/graphics/src/NodeTransform.cc b/graphics/src/NodeTransform.cc index bb03e2adf..f7b42848e 100644 --- a/graphics/src/NodeTransform.cc +++ b/graphics/src/NodeTransform.cc @@ -14,13 +14,13 @@ * limitations under the License. * */ -#include +#include using namespace ignition; using namespace common; /// \brief Private data for NodeTransform -class ignition::common::NodeTransformPrivate +class gz::common::NodeTransformPrivate { /// \brief the sid public: std::string sid; diff --git a/graphics/src/OBJLoader.cc b/graphics/src/OBJLoader.cc index 256460b72..7f46b4440 100644 --- a/graphics/src/OBJLoader.cc +++ b/graphics/src/OBJLoader.cc @@ -17,12 +17,12 @@ #include -#include "ignition/common/Console.hh" -#include "ignition/common/Filesystem.hh" -#include "ignition/common/Material.hh" -#include "ignition/common/Mesh.hh" -#include "ignition/common/SubMesh.hh" -#include "ignition/common/OBJLoader.hh" +#include "gz/common/Console.hh" +#include "gz/common/Filesystem.hh" +#include "gz/common/Material.hh" +#include "gz/common/Mesh.hh" +#include "gz/common/SubMesh.hh" +#include "gz/common/OBJLoader.hh" #define IGNITION_COMMON_TINYOBJLOADER_IMPLEMENTATION #include "tiny_obj_loader.h" diff --git a/graphics/src/OBJLoader_TEST.cc b/graphics/src/OBJLoader_TEST.cc index cb53f93bd..a05afae65 100644 --- a/graphics/src/OBJLoader_TEST.cc +++ b/graphics/src/OBJLoader_TEST.cc @@ -17,10 +17,10 @@ #include #include "test_config.h" -#include "ignition/common/Mesh.hh" -#include "ignition/common/SubMesh.hh" -#include "ignition/common/Material.hh" -#include "ignition/common/OBJLoader.hh" +#include "gz/common/Mesh.hh" +#include "gz/common/SubMesh.hh" +#include "gz/common/Material.hh" +#include "gz/common/OBJLoader.hh" using namespace ignition; diff --git a/graphics/src/Pbr.cc b/graphics/src/Pbr.cc index a25eb4ee1..cde56aec9 100644 --- a/graphics/src/Pbr.cc +++ b/graphics/src/Pbr.cc @@ -16,12 +16,12 @@ */ #include #include -#include +#include -#include "ignition/common/Pbr.hh" +#include "gz/common/Pbr.hh" /// \brief Private data for Pbr class -class ignition::common::PbrPrivate +class gz::common::PbrPrivate { /// \brief Workflow type public: PbrType type = PbrType::NONE; diff --git a/graphics/src/Pbr_TEST.cc b/graphics/src/Pbr_TEST.cc index de9a923d2..361049d8c 100644 --- a/graphics/src/Pbr_TEST.cc +++ b/graphics/src/Pbr_TEST.cc @@ -17,18 +17,18 @@ #include -#include -#include "ignition/common/Pbr.hh" +#include +#include "gz/common/Pbr.hh" ///////////////////////////////////////////////// TEST(Pbr, BasicAPI) { // initial state - ignition::common::Pbr pbr; - EXPECT_EQ(ignition::common::PbrType::NONE, pbr.Type()); + gz::common::Pbr pbr; + EXPECT_EQ(gz::common::PbrType::NONE, pbr.Type()); EXPECT_EQ(std::string(), pbr.AlbedoMap()); EXPECT_EQ(std::string(), pbr.NormalMap()); - EXPECT_EQ(ignition::common::NormalMapSpace::TANGENT, pbr.NormalMapType()); + EXPECT_EQ(gz::common::NormalMapSpace::TANGENT, pbr.NormalMapType()); EXPECT_EQ(std::string(), pbr.RoughnessMap()); EXPECT_EQ(std::string(), pbr.MetalnessMap()); EXPECT_EQ(std::string(), pbr.EmissiveMap()); @@ -43,8 +43,8 @@ TEST(Pbr, BasicAPI) EXPECT_EQ(std::string(), pbr.AmbientOcclusionMap()); // set / get - pbr.SetType(ignition::common::PbrType::METAL); - EXPECT_EQ(ignition::common::PbrType::METAL, pbr.Type()); + pbr.SetType(gz::common::PbrType::METAL); + EXPECT_EQ(gz::common::PbrType::METAL, pbr.Type()); pbr.SetAlbedoMap("metal_albedo_map.png"); EXPECT_EQ("metal_albedo_map.png", pbr.AlbedoMap()); @@ -88,8 +88,8 @@ TEST(Pbr, MoveCopy) { // copy constructor { - ignition::common::Pbr pbr; - pbr.SetType(ignition::common::PbrType::SPECULAR); + gz::common::Pbr pbr; + pbr.SetType(gz::common::PbrType::SPECULAR); pbr.SetAlbedoMap("specular_albedo_map.png"); pbr.SetNormalMap("specular_normal_map.png"); pbr.SetEnvironmentMap("specular_env_map.png"); @@ -100,11 +100,11 @@ TEST(Pbr, MoveCopy) pbr.SetSpecularMap("specular_map.png"); pbr.SetGlossiness(0.1); - ignition::common::Pbr pbr2(pbr); - EXPECT_EQ(ignition::common::PbrType::SPECULAR, pbr2.Type()); + gz::common::Pbr pbr2(pbr); + EXPECT_EQ(gz::common::PbrType::SPECULAR, pbr2.Type()); EXPECT_EQ("specular_albedo_map.png", pbr2.AlbedoMap()); EXPECT_EQ("specular_normal_map.png", pbr2.NormalMap()); - EXPECT_EQ(ignition::common::NormalMapSpace::TANGENT, pbr2.NormalMapType()); + EXPECT_EQ(gz::common::NormalMapSpace::TANGENT, pbr2.NormalMapType()); EXPECT_EQ("specular_env_map.png", pbr2.EnvironmentMap()); EXPECT_EQ("specular_ambient_occlusion_map.png", pbr2.AmbientOcclusionMap()); @@ -123,11 +123,11 @@ TEST(Pbr, MoveCopy) // move { - ignition::common::Pbr pbr; - pbr.SetType(ignition::common::PbrType::METAL); + gz::common::Pbr pbr; + pbr.SetType(gz::common::PbrType::METAL); pbr.SetAlbedoMap("metal_albedo_map.png"); pbr.SetNormalMap("metal_normal_map.png", - ignition::common::NormalMapSpace::TANGENT); + gz::common::NormalMapSpace::TANGENT); pbr.SetEnvironmentMap("metal_env_map.png"); pbr.SetAmbientOcclusionMap("metal_ambient_occlusion_map.png"); pbr.SetEmissiveMap("metal_emissive_map.png"); @@ -137,11 +137,11 @@ TEST(Pbr, MoveCopy) pbr.SetRoughness(0.8); pbr.SetMetalness(0.3); - ignition::common::Pbr pbr2(std::move(pbr)); - EXPECT_EQ(ignition::common::PbrType::METAL, pbr2.Type()); + gz::common::Pbr pbr2(std::move(pbr)); + EXPECT_EQ(gz::common::PbrType::METAL, pbr2.Type()); EXPECT_EQ("metal_albedo_map.png", pbr2.AlbedoMap()); EXPECT_EQ("metal_normal_map.png", pbr2.NormalMap()); - EXPECT_EQ(ignition::common::NormalMapSpace::TANGENT, pbr2.NormalMapType()); + EXPECT_EQ(gz::common::NormalMapSpace::TANGENT, pbr2.NormalMapType()); EXPECT_EQ("metal_env_map.png", pbr2.EnvironmentMap()); EXPECT_EQ("metal_ambient_occlusion_map.png", pbr2.AmbientOcclusionMap()); @@ -160,11 +160,11 @@ TEST(Pbr, MoveCopy) // move assignment { - ignition::common::Pbr pbr; - pbr.SetType(ignition::common::PbrType::METAL); + gz::common::Pbr pbr; + pbr.SetType(gz::common::PbrType::METAL); pbr.SetAlbedoMap("metal_albedo_map.png"); pbr.SetNormalMap("metal_normal_map.png", - ignition::common::NormalMapSpace::TANGENT); + gz::common::NormalMapSpace::TANGENT); pbr.SetEnvironmentMap("metal_env_map.png"); pbr.SetAmbientOcclusionMap("metal_ambient_occlusion_map.png"); pbr.SetEmissiveMap("metal_emissive_map.png"); @@ -174,12 +174,12 @@ TEST(Pbr, MoveCopy) pbr.SetRoughness(0.8); pbr.SetMetalness(0.3); - ignition::common::Pbr pbr2; + gz::common::Pbr pbr2; pbr2 = std::move(pbr); - EXPECT_EQ(ignition::common::PbrType::METAL, pbr2.Type()); + EXPECT_EQ(gz::common::PbrType::METAL, pbr2.Type()); EXPECT_EQ("metal_albedo_map.png", pbr2.AlbedoMap()); EXPECT_EQ("metal_normal_map.png", pbr2.NormalMap()); - EXPECT_EQ(ignition::common::NormalMapSpace::TANGENT, pbr2.NormalMapType()); + EXPECT_EQ(gz::common::NormalMapSpace::TANGENT, pbr2.NormalMapType()); EXPECT_EQ("metal_env_map.png", pbr2.EnvironmentMap()); EXPECT_EQ("metal_ambient_occlusion_map.png", pbr2.AmbientOcclusionMap()); @@ -199,8 +199,8 @@ TEST(Pbr, MoveCopy) // assignment { - ignition::common::Pbr pbr; - pbr.SetType(ignition::common::PbrType::METAL); + gz::common::Pbr pbr; + pbr.SetType(gz::common::PbrType::METAL); pbr.SetAlbedoMap("metal_albedo_map.png"); pbr.SetNormalMap("metal_normal_map.png"); pbr.SetEnvironmentMap("metal_env_map.png"); @@ -212,9 +212,9 @@ TEST(Pbr, MoveCopy) pbr.SetRoughness(0.18); pbr.SetMetalness(0.13); - ignition::common::Pbr pbr2; + gz::common::Pbr pbr2; pbr2 = pbr; - EXPECT_EQ(ignition::common::PbrType::METAL, pbr2.Type()); + EXPECT_EQ(gz::common::PbrType::METAL, pbr2.Type()); EXPECT_EQ("metal_albedo_map.png", pbr2.AlbedoMap()); EXPECT_EQ("metal_normal_map.png", pbr2.NormalMap()); EXPECT_EQ("metal_env_map.png", pbr2.EnvironmentMap()); @@ -235,19 +235,19 @@ TEST(Pbr, MoveCopy) // copy assignment after move { - ignition::common::Pbr pbr1; - pbr1.SetType(ignition::common::PbrType::METAL); + gz::common::Pbr pbr1; + pbr1.SetType(gz::common::PbrType::METAL); - ignition::common::Pbr pbr2; - pbr2.SetType(ignition::common::PbrType::SPECULAR); + gz::common::Pbr pbr2; + pbr2.SetType(gz::common::PbrType::SPECULAR); // This is similar to what std::swap does except it uses std::move for each // assignment - ignition::common::Pbr tmp = std::move(pbr1); + gz::common::Pbr tmp = std::move(pbr1); pbr1 = pbr2; pbr2 = tmp; - EXPECT_EQ(ignition::common::PbrType::SPECULAR, pbr1.Type()); - EXPECT_EQ(ignition::common::PbrType::METAL, pbr2.Type()); + EXPECT_EQ(gz::common::PbrType::SPECULAR, pbr1.Type()); + EXPECT_EQ(gz::common::PbrType::METAL, pbr2.Type()); } } diff --git a/graphics/src/STLLoader.cc b/graphics/src/STLLoader.cc index f9a97a352..46bc29fcf 100644 --- a/graphics/src/STLLoader.cc +++ b/graphics/src/STLLoader.cc @@ -19,11 +19,11 @@ #include #include -#include "ignition/math/Helpers.hh" -#include "ignition/common/Console.hh" -#include "ignition/common/Mesh.hh" -#include "ignition/common/SubMesh.hh" -#include "ignition/common/STLLoader.hh" +#include "gz/math/Helpers.hh" +#include "gz/common/Console.hh" +#include "gz/common/Mesh.hh" +#include "gz/common/SubMesh.hh" +#include "gz/common/STLLoader.hh" using namespace ignition; using namespace common; diff --git a/graphics/src/SVGLoader.cc b/graphics/src/SVGLoader.cc index 14cc57ad9..c0678f7fd 100644 --- a/graphics/src/SVGLoader.cc +++ b/graphics/src/SVGLoader.cc @@ -29,15 +29,15 @@ #endif #endif -#include "ignition/common/Console.hh" -#include "ignition/common/Util.hh" +#include "gz/common/Console.hh" +#include "gz/common/Util.hh" -#include "ignition/common/SVGLoader.hh" +#include "gz/common/SVGLoader.hh" using namespace ignition; using namespace common; -class ignition::common::SVGLoaderPrivate +class gz::common::SVGLoaderPrivate { /// \brief Generates polylines for each SVG subpath /// \param[in] _subpath The subpath commands diff --git a/graphics/src/SVGLoader_TEST.cc b/graphics/src/SVGLoader_TEST.cc index b3dd2ae0c..dcf1de7a2 100644 --- a/graphics/src/SVGLoader_TEST.cc +++ b/graphics/src/SVGLoader_TEST.cc @@ -19,7 +19,7 @@ #include "test_config.h" -#include "ignition/common/SVGLoader.hh" +#include "gz/common/SVGLoader.hh" using namespace ignition; using namespace common; diff --git a/graphics/src/Skeleton.cc b/graphics/src/Skeleton.cc index 87e6ca70a..8d33820e9 100644 --- a/graphics/src/Skeleton.cc +++ b/graphics/src/Skeleton.cc @@ -15,16 +15,16 @@ * */ #include -#include -#include -#include -#include +#include +#include +#include +#include using namespace ignition; using namespace common; /// Private data class -class ignition::common::SkeletonPrivate +class gz::common::SkeletonPrivate { typedef std::vector > > RawNodeWeights; diff --git a/graphics/src/SkeletonAnimation.cc b/graphics/src/SkeletonAnimation.cc index dc1603825..fc0667375 100644 --- a/graphics/src/SkeletonAnimation.cc +++ b/graphics/src/SkeletonAnimation.cc @@ -15,15 +15,15 @@ * */ -#include "ignition/common/Console.hh" -#include "ignition/common/NodeAnimation.hh" -#include "ignition/common/SkeletonAnimation.hh" +#include "gz/common/Console.hh" +#include "gz/common/NodeAnimation.hh" +#include "gz/common/SkeletonAnimation.hh" using namespace ignition; using namespace common; /// Prvate data class -class ignition::common::SkeletonAnimationPrivate +class gz::common::SkeletonAnimationPrivate { /// \brief the node name public: std::string name; diff --git a/graphics/src/SkeletonNode.cc b/graphics/src/SkeletonNode.cc index 39b097eb6..950ea4e5c 100644 --- a/graphics/src/SkeletonNode.cc +++ b/graphics/src/SkeletonNode.cc @@ -17,14 +17,14 @@ #include -#include "ignition/common/Console.hh" -#include "ignition/common/SkeletonNode.hh" +#include "gz/common/Console.hh" +#include "gz/common/SkeletonNode.hh" using namespace ignition; using namespace common; /// \brief SkeletonNode private data -class ignition::common::SkeletonNodePrivate +class gz::common::SkeletonNodePrivate { /// \brief the name of the skeletal node public: std::string name; diff --git a/graphics/src/SubMesh.cc b/graphics/src/SubMesh.cc index 818cc92c9..f5c0cb39d 100644 --- a/graphics/src/SubMesh.cc +++ b/graphics/src/SubMesh.cc @@ -19,17 +19,17 @@ #include #include -#include "ignition/math/Helpers.hh" +#include "gz/math/Helpers.hh" -#include "ignition/common/Console.hh" -#include "ignition/common/Material.hh" -#include "ignition/common/SubMesh.hh" +#include "gz/common/Console.hh" +#include "gz/common/Material.hh" +#include "gz/common/SubMesh.hh" using namespace ignition; using namespace common; /// \brief Private data for SubMesh -class ignition::common::SubMeshPrivate +class gz::common::SubMeshPrivate { /// \brief the vertex array public: std::vector vertices; diff --git a/graphics/src/SubMesh_TEST.cc b/graphics/src/SubMesh_TEST.cc index 8e633f3c3..60baf394b 100644 --- a/graphics/src/SubMesh_TEST.cc +++ b/graphics/src/SubMesh_TEST.cc @@ -18,10 +18,10 @@ #include #include "test_config.h" -#include "ignition/math/Vector3.hh" -#include "ignition/common/Mesh.hh" -#include "ignition/common/SubMesh.hh" -#include "ignition/common/MeshManager.hh" +#include "gz/math/Vector3.hh" +#include "gz/common/Mesh.hh" +#include "gz/common/SubMesh.hh" +#include "gz/common/MeshManager.hh" using namespace ignition; diff --git a/graphics/src/tiny_obj_loader.h b/graphics/src/tiny_obj_loader.h index a5859d128..7c69bd2c2 100644 --- a/graphics/src/tiny_obj_loader.h +++ b/graphics/src/tiny_obj_loader.h @@ -46,8 +46,8 @@ THE SOFTWARE. // #include "tiny_obj_loader.h" // -#ifndef IGNITION_COMMON_TINY_OBJ_LOADER_H_ -#define IGNITION_COMMON_TINY_OBJ_LOADER_H_ +#ifndef GZ_COMMON_TINY_OBJ_LOADER_H_ +#define GZ_COMMON_TINY_OBJ_LOADER_H_ #include #include @@ -399,7 +399,7 @@ bool ParseTextureNameAndOption(std::string *texname, texture_option_t *texopt, } // namespace tinyobj } // namespace ignition -#endif // IGNITION_COMMON_TINY_OBJ_LOADER_H_ +#endif // GZ_COMMON_TINY_OBJ_LOADER_H_ #ifdef IGNITION_COMMON_TINYOBJLOADER_IMPLEMENTATION #include diff --git a/include/CMakeLists.txt b/include/CMakeLists.txt index 25ec89762..4b2bdd7bb 100644 --- a/include/CMakeLists.txt +++ b/include/CMakeLists.txt @@ -1 +1,2 @@ -add_subdirectory(ignition) +add_subdirectory(gz) +install(DIRECTORY ignition DESTINATION ${IGN_INCLUDE_INSTALL_DIR_FULL}) diff --git a/include/gz/CMakeLists.txt b/include/gz/CMakeLists.txt new file mode 100644 index 000000000..e4717b2d6 --- /dev/null +++ b/include/gz/CMakeLists.txt @@ -0,0 +1 @@ +add_subdirectory(common) diff --git a/include/gz/common/Base64.hh b/include/gz/common/Base64.hh new file mode 100644 index 000000000..2f128c543 --- /dev/null +++ b/include/gz/common/Base64.hh @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_BASE64_HH_ +#define GZ_COMMON_BASE64_HH_ + +#include +#include + +namespace ignition +{ + namespace common + { + class IGNITION_COMMON_VISIBLE Base64 + { + /// \brief Encode a binary string into base 64, padded with '='. + /// \param[in] _bytesToEncode String of bytes to encode. + /// \param[in] _len Length of _bytesToEncode. + /// \param[out] _result Based64 string is appended to this string. + public: static void Encode(const char *_bytesToEncode, unsigned int _len, + std::string &_result); + + + /// \brief Decode a base64 string. + /// \param[in] _encodedString A base 64 encoded string. + /// \return The decoded string. + public: static std::string Decode(const std::string &_encodedString); + }; + } +} +#endif diff --git a/include/gz/common/Battery.hh b/include/gz/common/Battery.hh new file mode 100644 index 000000000..05786e9e1 --- /dev/null +++ b/include/gz/common/Battery.hh @@ -0,0 +1,178 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_BATTERY_HH_ +#define GZ_COMMON_BATTERY_HH_ + +#include +#include +#include +#include +#include +#include + +namespace ignition +{ + namespace common + { + // Forward declare private data class. + class BatteryPrivate; + + /// \brief A battery abstraction + /// + /// The default battery model is ideal: It just takes the initial voltage + /// value as its constant voltage value. This behavior can be changed by + /// specifying a custom update function. + /// + /// The battery handles a list of consumers. It updates itself after each + /// simulation iteration. The update function takes the power loads for each + /// consumer and current voltage value as inputs and returns a new voltage + /// value. + class IGNITION_COMMON_VISIBLE Battery + { + /// \brief Typedef the powerload map. + /// \sa SetUpdateFunc + public: typedef std::map PowerLoad_M; + + /// \brief Constructor + public: explicit Battery(); + + /// \brief Constructor that sets the name and initial voltage. + /// \param[in] _name Name of the battery + /// \param[in] _voltage Initial voltage of the battery + public: Battery(const std::string &_name, const double _voltage); + + /// \brief Copy constructor + /// \param[in] _battery Battery to copy. + public: Battery(const Battery &_battery); + + /// \brief Assignment operator + /// \param[in] _battery The new battery + /// \return a reference to this instance + public: Battery &operator=(const Battery &_battery); + + /// \brief Destructor. + public: virtual ~Battery(); + + /// \brief Equal to operator + /// \param[in] _battery the battery to compare to + /// \return true if names and initial voltages are the same, false + /// otherwise + public: bool operator==(const Battery &_battery) const; + + /// \brief Inequality operator + /// \param[in] _battery the battery to compare to + /// \return true if names or initial voltages are not the same, false + /// otherwise + public: bool operator!=(const Battery &_battery) const; + + /// \brief Initialize. + public: virtual void Init(); + + /// \brief Reset the battery voltage to the initial value. + /// The initial value might have been loaded from an sdf element. + /// \sa Load + public: virtual void ResetVoltage(); + + /// \brief Return the initial voltage. + /// \return The initial voltage. + public: double InitVoltage() const; + + /// \brief Set the initial voltage + /// \param[in] _voltage Initial voltage. + public: virtual void SetInitVoltage(const double _voltage); + + /// \brief Return the name of the battery. + /// \return The name of the battery. + public: std::string Name() const; + + /// \brief Set the name of the battery. + /// \param[in] _name Name of the battery. + public: void SetName(const std::string &_name) const; + + /// \brief Create a unique consumer. + /// \return Unique consumer identifier. + public: uint32_t AddConsumer(); + + /// \brief Remove a consumer. + /// \param[in] _consumerId Unique consumer identifier. + /// \return True if the consumer was removed. False if the consumer id + /// was not found. + public: bool RemoveConsumer(const uint32_t _consumerId); + + /// \brief Set consumer power load in watts. + /// \param[in] _consumerId Unique consumer identifier. + /// \param[in] _powerLoad Power load in watts. + /// \return True if setting the power load consumption was successful. + public: bool SetPowerLoad(const uint32_t _consumerId, + const double _powerLoad); + + /// \brief Get consumer power load in watts. + /// \param[in] _consumerId Unique consumer identifier. + /// \param[out] _powerLoad Power load consumption in watts. + /// \return True if getting the power load consumption was successful. + public: bool PowerLoad(const uint32_t _consumerId, + double &_powerLoad) const; + + /// \brief Get list of power loads in watts. + /// \return List of power loads in watts. + public: const PowerLoad_M &PowerLoads() const; + + /// \brief Get the real voltage in volts. + /// \return Voltage. + public: double Voltage() const; + + /// \brief Setup function to update voltage. + /// \param[in] _updateFunc The update function callback that is used + /// to modify the battery's voltage. The parameter to the update + /// function callback is a reference to an instance of + /// Battery::UpdateData. The update function must return the new + /// battery voltage as a double. + /// \sa UpdateData + public: void SetUpdateFunc( + std::function _updateFunc); + + /// \brief Reset function to update voltage, upon destruction of current + /// callback function. + /// \sa UpdateDefault + public: void ResetUpdateFunc(); + + /// \brief Update the battery. This will in turn trigger the function + /// set using the SetUpdateFunc function. + /// \sa SetUpdateFunc. + public: void Update(); + + /// \brief Initialize the list of consumers. + protected: void InitConsumers(); + + /// \brief Update voltage using an ideal battery model. + /// \param[in] _battery Pointer to the battery. + /// \return New battery voltage. + private: double UpdateDefault(Battery *_battery); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \internal + /// \brief Private data pointer. + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + + /// \def BatteryPtr + /// \brief Shared pointer to a battery + typedef std::shared_ptr BatteryPtr; + } +} +#endif diff --git a/include/ignition/common/CMakeLists.txt b/include/gz/common/CMakeLists.txt similarity index 100% rename from include/ignition/common/CMakeLists.txt rename to include/gz/common/CMakeLists.txt diff --git a/include/gz/common/Console.hh b/include/gz/common/Console.hh new file mode 100644 index 000000000..3e2910da6 --- /dev/null +++ b/include/gz/common/Console.hh @@ -0,0 +1,298 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_CONSOLE_HH_ +#define GZ_COMMON_CONSOLE_HH_ + +#include +#include +#include +#include + +#include +#include +#include + +namespace ignition +{ + namespace common + { + /// \brief Output an error message, if the verbose level is >= 1 + #define ignerr (ignition::common::Console::err(__FILE__, __LINE__)) + + /// \brief Output a warning message, if the verbose level is >= 2 + #define ignwarn (ignition::common::Console::warn(__FILE__, __LINE__)) + + /// \brief Output a message, if the verbose level is >= 3 + #define ignmsg (ignition::common::Console::msg()) + + /// \brief Output a debug message, if the verbose level is >= 4 + #define igndbg (ignition::common::Console::dbg(__FILE__, __LINE__)) + + /// \brief Output a message to a log file, regardless of verbosity level + #define ignlog (ignition::common::Console::log()) + + /// \brief Initialize log file with filename given by _dir/_file. + /// If called twice, it will close the file currently in use and open a new + /// log file. + /// \param[in] _dir Name of directory in which to store the log file. Note + /// that if _dir is not an absolute path, then _dir will + /// be relative to your home directory. + /// \param[in] _file Name of log file for ignlog messages. + #define ignLogInit(_dir, _file)\ + ignition::common::Console::log.Init(_dir, _file) + + /// \brief Close the file used for logging. + #define ignLogClose()\ + ignition::common::Console::log.Close() + + /// \brief Get the full path of the directory where the log files are stored + /// \return Full path of the directory + #define ignLogDirectory()\ + (ignition::common::Console::log.LogDirectory()) + + /// \class FileLogger FileLogger.hh common/common.hh + /// \brief A logger that outputs messages to a file. + class IGNITION_COMMON_VISIBLE FileLogger : public std::ostream + { + /// \brief Constructor. + /// \param[in] _filename Filename to write into. If empty, + /// FileLogger::Init must be called separately. + public: explicit FileLogger(const std::string &_filename = ""); + + /// \brief Destructor. + public: virtual ~FileLogger(); + + /// \brief Initialize the file logger. + /// \param[in] _directory Name of directory that holds the log file. + /// \param[in] _filename Name of the log file to write output into. + public: void Init(const std::string &_directory, + const std::string &_filename); + + /// \brief Close the open file handles. + public: void Close(); + + /// \brief Output a filename and line number, then return a reference + /// to the logger. + /// \return Reference to this logger. + public: virtual FileLogger &operator()(); + + /// \brief Output a filename and line number, then return a reference + /// to the logger. + /// \param[in] _file Filename to output. + /// \param[in] _line Line number in the _file. + /// \return Reference to this logger. + public: virtual FileLogger &operator()( + const std::string &_file, int _line); + + /// \brief Get the full path of the directory where all the log files + /// are stored. + /// \return Full path of the directory. + public: std::string LogDirectory() const; + + /// \brief String buffer for the file logger. + protected: class Buffer : public std::stringbuf + { + /// \brief Constructor. + /// \param[in] _filename Filename to write into. + public: explicit Buffer(const std::string &_filename); + + /// \brief Destructor. + public: virtual ~Buffer(); + + /// \brief Writes _count characters to the string buffer + /// \param[in] _char Input rharacter array. + /// \param[in] _count Number of characters in array. + /// \return The number of characters successfully written. + public: std::streamsize xsputn( + const char *_char, std::streamsize _count) override; + + /// \brief Sync the stream (output the string buffer + /// contents). + /// \return Return 0 on success. + public: int sync() override; + + /// \brief Stream to output information into. + public: std::ofstream *stream; + /// \brief Mutex to synchronize writes to the string buffer + /// and the output stream. + /// \todo(nkoenig) Put this back in for ign-common5, and + /// remove the corresponding static version. + // public: std::mutex syncMutex; + }; + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief Stores the full path of the directory where all the log files + /// are stored. + private: std::string logDirectory; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + + /// \brief True if initialized. + private: bool initialized; + }; + + /// \class Logger Logger.hh common/common.hh + /// \brief Terminal logger. + class IGNITION_COMMON_VISIBLE Logger : public std::ostream + { + /// \enum LogType. + /// \brief Output destination type. + public: enum LogType + { + /// \brief Output to stdout. + STDOUT, + /// \brief Output to stderr. + STDERR + }; + + /// \brief Constructor. + /// \param[in] _prefix String to use as prefix when logging to file. + /// \param[in] _color Color of the output stream. + /// \param[in] _type Output destination type (STDOUT, or STDERR) + /// \param[in] _verbosity Verbosity level. + public: Logger(const std::string &_prefix, const int _color, + const LogType _type, const int _verbosity); + + /// \brief Destructor. + public: virtual ~Logger(); + + /// \brief Access operator. + /// \return Reference to this logger. + public: virtual Logger &operator()(); + + /// \brief Output a filename and line number, then return a reference + /// to the logger. + /// \param[in] _file Filename to output. + /// \param[in] _line Line number in the _file. + /// \return Reference to this logger. + public: virtual Logger &operator()( + const std::string &_file, int _line); + + /// \brief String buffer for the base logger. + protected: class Buffer : public std::stringbuf + { + /// \brief Constructor. + /// \param[in] _type Output destination type + /// (STDOUT, or STDERR) + /// \param[in] _color Color of the output stream. + /// \param[in] _verbosity Verbosity level. + public: Buffer(LogType _type, const int _color, + const int _verbosity); + + /// \brief Destructor. + public: virtual ~Buffer(); + + /// \brief Writes _count characters to the string buffer + /// \param[in] _char Input rharacter array. + /// \param[in] _count Number of characters in array. + /// \return The number of characters successfully written. + public: std::streamsize xsputn( + const char *_char, std::streamsize _count) override; + + /// \brief Sync the stream (output the string buffer + /// contents). + /// \return Return 0 on success. + public: int sync() override; + + /// \brief Destination type for the messages. + public: LogType type; + + /// \brief ANSI color code using Select Graphic Rendition + /// parameters (SGR). See + /// http://en.wikipedia.org/wiki/ANSI_escape_code#Colors + public: int color; + + /// \brief Level of verbosity + public: int verbosity; + + /// \brief Mutex to synchronize writes to the string buffer + /// and the output stream. + /// \todo(nkoenig) Put this back in for ign-common5, and + /// remove the corresponding static version. + // public: std::mutex syncMutex; + }; + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief Prefix to use when logging to file. + private: std::string prefix; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + + /// \class Console Console.hh common/common.hh + /// \brief Container for loggers, and global logging options + /// (such as verbose vs. quiet output). + class IGNITION_COMMON_VISIBLE Console + { + /// \brief Set verbosity, where + /// <= 0: No output, + /// 1: Error messages, + /// 2: Error and warning messages, + /// 3: Error, warning, and info messages, + /// >= 4: Error, warning, info, and debug messages. + /// \param[in] _level The new verbose level. + public: static void SetVerbosity(const int _level); + + /// \brief Get the verbose level. + /// \return The level of verbosity. + /// \sa SetVerbosity(const int _level) + public: static int Verbosity(); + + /// \brief Add a custom prefix in front of the default prefixes. + /// + /// By default, the custom prefix is an empty string, so the messages + /// start as: + /// + /// [Err], [Wrn], [Msg], [Dbg] + /// + /// If you set the prefix to "-my-", for example, they become: + /// + /// -my-[Err], -my-[Wrn], -my-[Msg], -my-[Dbg] + /// + /// \param[in] _customPrefix Prefix string. + /// \sa std::string Prefix() const + public: static void SetPrefix(const std::string &_customPrefix); + + /// \brief Get custom prefix. This is empty by default. + /// \return The custom prefix. + /// \sa void SetPrefix(const std::string &_customPrefix) + public: static std::string Prefix(); + + /// \brief Global instance of the message logger. + public: static Logger msg; + + /// \brief Global instance of the error logger. + public: static Logger err; + + /// \brief Global instance of the debug logger. + public: static Logger dbg; + + /// \brief Global instance of the warning logger. + public: static Logger warn; + + /// \brief Global instance of the file logger. + public: static FileLogger log; + + /// \brief The level of verbosity, the default level is 1. + private: static int verbosity; + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief A custom prefix. See SetPrefix(). + private: static std::string customPrefix; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} +#endif diff --git a/include/gz/common/EnumIface.hh b/include/gz/common/EnumIface.hh new file mode 100644 index 000000000..b95ce1b39 --- /dev/null +++ b/include/gz/common/EnumIface.hh @@ -0,0 +1,242 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_ENUMITERATOR_HH_ +#define GZ_COMMON_ENUMITERATOR_HH_ + +#include +#include +#include +#include +#include + +namespace ignition +{ + namespace common + { + /// \brief A macro that allows an enum to have an iterator and string + /// conversion. + /// \param[in] name EnumIface instance name. + /// \param[in] enumType Enum type + /// \param[in] begin Enum value that marks the beginning of the enum + /// values. + /// \param[in] end Enum value that marks the end of the enum values. + /// \param[in] names A vector of strings, one for each enum value. + /// \sa EnumIface + /// \sa EnumIterator + #define IGN_ENUM(name, enumType, begin, end, ...) \ + static ignition::common::EnumIface name( \ + begin, end, {__VA_ARGS__}); + + /// \brief Enum interface. Use this interface to convert an enum to + /// a string, and set an enum from a string. + template + class EnumIface + { + /// \brief Constructor + /// \param[in] _start Starting enum value. + /// \param[in] _end Ending enum value. + /// \param[in] _names Name of each enum value. + public: EnumIface(T _start, T _end, + const std::vector &_names) + : names(_names) + { + this->range[0] = _start; + this->range[1] = _end; + } + + /// \brief Get the beginning enum value. + /// \return Enum value that marks the beginning of the enum list. + public: T Begin() + { + return range[0]; + } + + /// \brief Get the end enum value. + /// \return Enum value that marks the end of the enum list. + public: T End() + { + return range[1]; + } + + /// \brief Convert enum value to string. + /// \param[in] _e Enum value to convert. + /// \return String representation of the enum. An empty string is + /// returned if _e is invalid, or the names for the enum have not been + /// set. + public: std::string Str(T const &_e) + { + if (static_cast(_e) < names.size()) + return names[static_cast(_e)]; + else + return ""; + } + + /// \brief Set an enum from a string. This function requires a valid + /// string, and an array of names for the enum must exist. + /// \param[in] _str String value to convert to enum value. + /// \param[in] _e Enum variable to set. + /// \sa EnumIterator + public: void Set(T &_e, const std::string &_str) + { + auto begin = std::begin(names); + auto end = std::end(names); + + auto find = std::find(begin, end, _str); + if (find != end) + { + _e = static_cast(std::distance(begin, find)); + } + } + + /// \internal + /// \brief The beginning and end values. Do not use this directly. + public: T range[2]; + + /// \internal + /// \brief Array of string names for each element in the enum. Do not + /// use this directly. + public: std::vector names; + }; + + /// \brief An iterator over enum types. + /// + /// Example: + /// + /// \verbatim + /// enum MyType + /// { + /// MY_TYPE_BEGIN = 0, + /// TYPE1 = MY_TYPE_BEGIN, + /// TYPE2 = 1, + /// MY_TYPE_END + /// }; + /// + /// GZ_ENUM(myTypeIface, MyType, MY_TYPE_BEGIN, MY_TYPE_END, + /// "TYPE1", + /// "TYPE2", + /// "MY_TYPE_END") + /// + /// int main() + /// { + /// EnumIterator i = MY_TYPE_BEGIN; + /// std::cout << "Type Number[" << *i << "]\n"; + /// std::cout << "Type Name[" << myTypeIface.Str(*i) << "]\n"; + /// i++; + /// std::cout << "Type++ Number[" << *i << "]\n"; + /// std::cout << "Type++ Name[" << myTypeIface.Str(*i) << "]\n"; + /// } + /// \verbatim + template + class EnumIterator + : std::iterator + { + /// \brief Constructor + public: EnumIterator() + { + } + + /// \brief Constructor + /// \param[in] _c Enum value + // cppcheck-suppress noExplicitConstructor + public: EnumIterator(const Enum &_c) : c(_c) + { + } + + /// \brief Equal operator + /// \param[in] _c Enum value to copy + public: EnumIterator &operator=(const Enum &_c) + { + this->c = _c; + return *this; + } + + /// \brief Prefix increment operator. + /// \return Iterator pointing to the next value in the enum. + public: EnumIterator &operator++() + { + this->c = static_cast(static_cast(this->c) + 1); + return *this; + } + + /// \brief Postfix increment operator. + /// \return Iterator pointing to the next value in the enum. + public: EnumIterator operator++(const int) + { + EnumIterator cpy(*this); + ++*this; + return cpy; + } + + /// \brief Prefix decrement operator + /// \return Iterator pointing to the previous value in the enum + public: EnumIterator &operator--() + { + this->c = static_cast(static_cast(this->c) - 1); + return *this; + } + + /// \brief Postfix decrement operator + /// \return Iterator pointing to the previous value in the enum + public: EnumIterator operator--(const int) + { + EnumIterator cpy(*this); + --*this; + return cpy; + } + + /// \brief Dereference operator + /// \return Value of the iterator + public: Enum operator*() const + { + return c; + } + + /// \brief Get the enum value. + /// \return Value of the iterator + public: Enum Value() const + { + return this->c; + } + + /// \brief Enum value + /// Did not use a private data class since this should be the only + /// member value ever used. + private: Enum c; + }; + + /// \brief Equality operator + /// \param[in] _e1 First iterator + /// \param[in] _e1 Second iterator + /// \return True if the two iterators contain equal enum values. + template + bool operator==(EnumIterator _e1, EnumIterator _e2) + { + return _e1.Value() == _e2.Value(); + } + + /// \brief Inequality operator + /// \param[in] _e1 First iterator + /// \param[in] _e1 Second iterator + /// \return True if the two iterators do not contain equal enum values. + template + bool operator!=(EnumIterator _e1, EnumIterator _e2) + { + return !(_e1 == _e2); + } + } +} +#endif diff --git a/include/gz/common/Filesystem.hh b/include/gz/common/Filesystem.hh new file mode 100644 index 000000000..d1c2ea326 --- /dev/null +++ b/include/gz/common/Filesystem.hh @@ -0,0 +1,305 @@ +/* + * Copyright 2017 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GZ_COMMON_FILESYSTEM_HH_ +#define GZ_COMMON_FILESYSTEM_HH_ + +#include +#include + +#include +#include + +namespace ignition +{ + namespace common + { + /// \brief Options for how to handle errors that occur in functions that + /// manipulate the filesystem. + enum FilesystemWarningOp + { + /// \brief Errors that occur during filesystem manipulation should be + /// logged as warnings using ignwarn. (Recommended) + FSWO_LOG_WARNINGS = 0, + + /// \brief Errors that occur during filesystem manipulation should + /// not be logged. The user will be responsible for checking the + /// system's error flags. + FSWO_SUPPRESS_WARNINGS + }; + + /// \brief Determine whether the given path exists on the filesystem. + /// \param[in] _path The path to check for existence + /// \return True if the path exists on the filesystem, false otherwise. + bool IGNITION_COMMON_VISIBLE exists(const std::string &_path); + + /// \brief Determine whether the given path is a directory. + /// \param[in] _path The path to check + /// \return True if given path exists and is a directory, false otherwise. + bool IGNITION_COMMON_VISIBLE isDirectory(const std::string &_path); + + /// \brief Check if the given path is a file. + /// \param[in] _path Path to a file. + /// \return True if _path is a file. + bool IGNITION_COMMON_VISIBLE isFile(const std::string &_path); + + /// \brief Create a new directory on the filesystem. Intermediate + /// directories must already exist. + /// \param[in] _path The new directory path to create + /// \return True if directory creation was successful, false otherwise. + bool IGNITION_COMMON_VISIBLE createDirectory(const std::string &_path); + + /// \brief Create directories for the given path + /// \param[in] _path Path to create directories from + /// \return true on success + bool IGNITION_COMMON_VISIBLE createDirectories(const std::string &_path); + + /// \brief Append the preferred path separator character for this platform + /// onto the passed-in string. + /// \param[in] _s The path to start with. + /// \return The original path with the platform path separator appended. + std::string IGNITION_COMMON_VISIBLE const separator( + std::string const &_s); + + /// \brief Replace forward-slashes '/' with the preferred directory + /// separator of the current operating system. On Windows, this will turn + /// forward-slashes into backslashes. If forward-slash is the preferred + /// separator of the current operating system, this will do nothing. + /// + /// Note that this will NOT convert backslashes (or any other separator) + /// into forward slashes, even on operating systems that use + /// forward-slashes as separators. + /// + /// \param[out] _path This string will be directly modified by + /// replacing its + /// forward-slashes with the preferred directory separator of the current + /// operating system. + void IGNITION_COMMON_VISIBLE changeFromUnixPath(std::string &_path); + + /// \brief Returns a copy of _path which has been passed through + /// changeFromUnixPath. + /// + /// \param[in] _path The path to start with + /// \return A modified path that uses the preferred directory separator of + /// the current operating system. + std::string IGNITION_COMMON_VISIBLE copyFromUnixPath( + const std::string &_path); + + /// \brief Replace the preferred directory separator of the current + /// operating system with a forward-slash '/'. On Windows, this will turn + /// backslashes into forward-slashes. + /// + /// \param[out] _path This string will be directly modified to use forward + /// slashes to separate its directory names. + void IGNITION_COMMON_VISIBLE changeToUnixPath(std::string &_path); + + /// \brief Returns a copy of _path which has been passed through + /// changeToUnixPath. + /// + /// \param[in] _path The path to start with + /// \return A modified path that uses forward slashes to separate + /// directory names. + std::string IGNITION_COMMON_VISIBLE copyToUnixPath( + const std::string &_path); + + /// \brief Get the absolute path of a provided path. Relative paths are + /// resolved relative to the current working directory. + /// \param[in] _path Relative or absolute path. + /// \return Absolute path (with platform-dependent directory separators). + std::string IGNITION_COMMON_VISIBLE absPath(const std::string &_path); + + /// \brief Join two strings together to form a path + /// \param[in] _path1 the left portion of the path + /// \param[in] _path2 the right portion of the path + /// \return Joined path. The function can do simplifications such as + /// elimination of ../ and removal of duplicate // (but is not guaranteed to + /// do so). + std::string IGNITION_COMMON_VISIBLE joinPaths(const std::string &_path1, + const std::string &_path2); + + /// \brief base case for joinPaths(...) below + inline std::string joinPaths(const std::string &_path) + { + return _path; + } + + // The below is C++ variadic template magic to allow a joinPaths + // method that takes 1-n number of arguments to append together. + + /// \brief Append one or more additional path elements to the first + /// passed in argument. + /// \param[in] args The paths to append together + /// \return A new string with the paths appended together. + template + inline std::string joinPaths(const std::string &_path1, + const std::string &_path2, + Args const &..._args) + { + return joinPaths(joinPaths(_path1, _path2), + joinPaths(_args...)); + } + + /// \brief Get the current working directory + /// \return Name of the current directory + std::string IGNITION_COMMON_VISIBLE cwd(); + + /// \brief Change current working directory to _dir. + /// \param[in] _dir The directory to change to. + /// \return Whether the operation succeeded. + bool IGNITION_COMMON_VISIBLE chdir(const std::string &_dir); + + /// \brief Given a path, get just the basename portion. + /// \param[in] _path The full path. + /// \return A new string with just the basename portion of the path. + std::string IGNITION_COMMON_VISIBLE basename( + const std::string &_path); + + /// \brief Given a path, get just its parent path portion, without + /// separator at the end. + /// \param[in] _path Path of which to find parent path + /// \return A new string with just the parent path of the path. + std::string IGNITION_COMMON_VISIBLE parentPath( + const std::string &_path); + + /// \brief Copy a file. + /// \param[in] _existingFilename Path to an existing file. + /// \param[in] _newFilename Path of the new file. + /// \param[in] _warningOp Log or suppress warnings that may occur. + /// \return True on success. + bool IGNITION_COMMON_VISIBLE copyFile( + const std::string &_existingFilename, + const std::string &_newFilename, + const FilesystemWarningOp _warningOp = FSWO_LOG_WARNINGS); + + /// \brief Copy a directory, overwrite the destination directory if exists. + /// \param[in] _source Path to an existing directory to copy from. + /// \param[in] _destination Path to the destination directory. + /// \return True on success. + bool IGNITION_COMMON_VISIBLE copyDirectory( + const std::string &_existingDirname, + const std::string &_newDirname, + const FilesystemWarningOp _warningOp = FSWO_LOG_WARNINGS); + + /// \brief Move a file. + /// \param[in] _existingFilename Full path to an existing file. + /// \param[in] _newFilename Full path of the new file. + /// \param[in] _warningOp Log or suppress warnings that may occur. + /// \return True on success. + bool IGNITION_COMMON_VISIBLE moveFile( + const std::string &_existingFilename, + const std::string &_newFilename, + const FilesystemWarningOp _warningOp = FSWO_LOG_WARNINGS); + + /// \brief Remove an empty directory + /// \remarks the directory must be empty to be removed + /// \param[in] _path Path to a directory. + /// \param[in] _warningOp Log or suppress warnings that may occur. + /// \return True if _path is a directory and was removed. + bool IGNITION_COMMON_VISIBLE removeDirectory( + const std::string &_path, + const FilesystemWarningOp _warningOp = FSWO_LOG_WARNINGS); + + /// \brief Remove a file. + /// \param[in] _existingFilename Full path to an existing file. + /// \param[in] _warningOp Log or suppress warnings that may occur. + /// \return True on success. + bool IGNITION_COMMON_VISIBLE removeFile( + const std::string &_existingFilename, + const FilesystemWarningOp _warningOp = FSWO_LOG_WARNINGS); + + /// \brief Remove an empty directory or file. + /// \param[in] _path Path to a directory or file. + /// \param[in] _warningOp Log or suppress warnings that may occur. + /// \return True if _path was removed. + bool IGNITION_COMMON_VISIBLE removeDirectoryOrFile( + const std::string &_path, + const FilesystemWarningOp _warningOp = FSWO_LOG_WARNINGS); + + /// \brief Remove a file or a directory and all its contents. + /// \param[in] _path Path to a directory or file. + /// \param[in] _warningOp Log or suppress warnings that may occur. + /// \return True if _path was removed. + bool IGNITION_COMMON_VISIBLE removeAll( + const std::string &_path, + const FilesystemWarningOp _warningOp = FSWO_LOG_WARNINGS); + + /// \brief Generates a path for a file which doesn't collide with existing + /// files, by appending numbers to it (i.e. (0), (1), ...) + /// \param[in] _pathAndName Full absolute path and file name up to the + /// file extension. + /// \param[in] _extension File extension, such as "ddf". + /// \return Full path with name and extension, which doesn't collide with + /// existing files + std::string IGNITION_COMMON_VISIBLE uniqueFilePath( + const std::string &_pathAndName, const std::string &_extension); + + /// \brief Unique directory path to not overwrite existing directory + /// \param[in] _pathAndName Full absolute path + /// \return Full path which doesn't collide with existing files + std::string IGNITION_COMMON_VISIBLE uniqueDirectoryPath( + const std::string &_dir); + + /// \internal + class DirIterPrivate; + + /// \class DirIter Filesystem.hh + /// \brief A class for iterating over all items in a directory. + class IGNITION_COMMON_VISIBLE DirIter + { + /// \brief Constructor. + /// \param[in] _in Directory to iterate over. + public: explicit DirIter(const std::string &_in); + + /// \brief Constructor for end element. + public: DirIter(); + + /// \brief Dereference operator; returns current directory record. + /// \return A string representing the entire path of the directory + /// record. + public: std::string operator*() const; + + /// \brief Pre-increment operator; moves to next directory record. + /// \return This iterator. + public: const DirIter &operator++(); + + /// \brief Comparison operator to see if this iterator is at the + /// same point as another iterator. + /// \param[in] _other The other iterator to compare against. + /// \return true if the iterators are equal, false otherwise. + public: bool operator!=(const DirIter &_other) const; + + /// \brief Destructor + public: ~DirIter(); + + /// \brief Move to the next directory record, skipping . and .. records. + private: void Next(); + + /// \brief Set the internal variable to the empty string. + private: void SetInternalEmpty(); + + /// \brief Close an open directory handle. + private: void CloseHandle(); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief Private data. + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} + +#endif diff --git a/include/gz/common/FlagSet.hh b/include/gz/common/FlagSet.hh new file mode 100644 index 000000000..688e0d99f --- /dev/null +++ b/include/gz/common/FlagSet.hh @@ -0,0 +1,402 @@ +/* + * MIT License + * + * Copyright (c) 2019 Arnaud Kapp (Xaqq), Barry Revzin, Mart Sõmermaa + * Copyright (c) 2020 Martin Pecka + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef IGNITION_COMMON_FLAGSET_HH +#define IGNITION_COMMON_FLAGSET_HH + +// FlagSet is a type-safe class for using enums as flags in C++14 with an +// underlying std::bitset. +// See https://github.com/mrts/flag-set-cpp +// Licence: MIT + +#include +#include +#include +#include + +#include + +namespace ignition::common +{ + +/// \brief Set of flags defined by a C++11 enum class. +/// \note If the enum's last element is '_' (just underscore), the convenience +/// signature can be used specifying just the enum type (the underscore will be +/// automatically used as LastElement, and will be excluded from the list of +/// valid values). +/// \note FlagSet only works for enums that do not contain negative values. +/// \note The underlying bitset representing this FlagSet will have as many bits +/// as is the size_t value of LastElement (+- 1). Be aware of that when calling +/// Count(), Size() etc. Also be aware of that when creating a FlagSet of an +/// enum that would contain very high numbers in the underlying representation. +/// \tparam T The enum class type. The underlying type of the enum has to be +/// convertible to size_t. +/// \tparam LastElement Last element of the enum. If the enum's last element is +/// '_' (just underscore), it can be deduced automatically. +/// \tparam ExcludeLast If true, LastElement is considered as an element beyond +/// all valid elements and will not be treated as a valid value of the FlagSet. +/// If false, the last element is treated as a valid value. +template +class FlagSet +{ + /// \brief Create an empty FlagSet (no flags set). + public: FlagSet() = default; + + /// \brief Construct a FlagSet with the given flag set and all other unset. + /// \param[in] _val The flag to set. + /// \note This is intentionally not an explicit constructor so that values of + /// the enum can be implicitly converted to a FlagSet with just the one value + /// set. + // cppcheck-suppress noExplicitConstructor + public: FlagSet(const T& _val) + { + flags.set(static_cast(_val)); + } + + /// \brief Construct a FlagSet with the given flags set and all other unset. + /// \param[in] _list The list of flags to set. + public: explicit FlagSet(const std::initializer_list& _list) + { + for (const auto& val : _list) + { + flags.set(static_cast(val)); + } + } + + // Binary operations. + + /// \brief Return a FlagSet with only the given flag set (or even this one + /// unset if it wasn't set in this FlagSet before). + /// \param[in] _val The flag to set. + /// \return This. + public: FlagSet& operator&=(const T& _val) noexcept + { + bool tmp = flags.test(static_cast(_val)); + flags.reset(); + flags.set(static_cast(_val), tmp); + return *this; + } + + /// \brief Return a bit AND of this FlagSet and the argument. + /// \param[in] _o The other FlagSet. + /// \return This. + public: FlagSet& operator&=(const FlagSet& _o) noexcept + { + flags &= _o.flags; + return *this; + } + + /// \brief Set the given flag to true in this FlagSet. + /// \param[in] _val The flag to set. + /// \return This. + public: FlagSet& operator|=(const T& _val) noexcept + { + flags.set(static_cast(_val)); + return *this; + } + + /// \brief Return a bit OR of this FlagSet and the argument. + /// \param[in] _o The other FlagSet. + /// \return This. + public: FlagSet& operator|=(const FlagSet& _o) noexcept + { + flags |= _o.flags; + return *this; + } + + /// \brief Return a FlagSet with only the given flag set (or even this one + /// unset if it wasn't set in this FlagSet before). + /// \param[in] _val The flag to set. + /// \return The new FlagSet. + /// \note The resulting bitset can contain at most 1 bit set to true. + public: FlagSet operator&(const T& _val) const + { + FlagSet ret(*this); + ret &= _val; + + assert(ret.flags.count() <= 1); + return ret; + } + + /// \brief Return a bit AND of this FlagSet and the argument. + /// \param[in] _o The other FlagSet. + /// \return The new FlagSet. + public: FlagSet operator&(const FlagSet& _val) const + { + FlagSet ret(*this); + ret.flags &= _val.flags; + + return ret; + } + + /// \brief Return a FlagSet with the given flag set to true. + /// \param[in] _val The flag to set. + /// \return The new FlagSet. + /// \note The resulting bitset contains at least 1 bit set to true. + public: FlagSet operator|(const T& _val) const + { + FlagSet ret(*this); + ret |= _val; + + assert(ret.flags.count() >= 1); + return ret; + } + + /// \brief Return a bit OR of this FlagSet and the argument. + /// \param[in] _o The other FlagSet. + /// \return The new FlagSet. + public: FlagSet operator|(const FlagSet& _val) const + { + FlagSet ret(*this); + ret.flags |= _val.flags; + + return ret; + } + + /// \brief Return a negation of this FlagSet. + /// \return The negated FlagSet. + public: FlagSet operator~() const + { + FlagSet cp(*this); + cp.flags.flip(); + + return cp; + } + + /// \brief Return true if at least one flag is set to true. + /// \return Whether at least one flag is set. + public: explicit operator bool() const + { + return flags.any(); + } + + // Methods from std::bitset. + + /// \brief Test FlagSet equality. + /// \param[in] _o The other FlagSet. + /// \return Whether the FlagSets represent the same set of flags. + public: bool operator==(const FlagSet& _o) const + { + return flags == _o.flags; + } + + /// \brief Test FlagSet inequality. + /// \param[in] _o The other FlagSet. + /// \return Whether the FlagSets represent different sets of flags. + public: bool operator!=(const FlagSet& _o) const + { + return !(*this == _o); + } + + /// \brief Return the total number of flags represented by this FlagSet. + /// \note This corresponds to the value of the '_' element of the enum. + /// \return The number of flags in this FlagSet. + /// \sa Count() + public: std::size_t Size() const + { + return flags.size(); + } + + /// \brief Return the number of flags set to true. + /// \return The number of true flags in this FlagSet. + /// \sa Size() + public: std::size_t Count() const + { + return flags.count(); + } + + /// \brief Set all flags to true. + /// \return This. + public: FlagSet& Set() + { + flags.set(); + return *this; + } + + /// \brief Set all flags to false. + /// \return This. + public: FlagSet& Reset() + { + flags.reset(); + return *this; + } + + /// \brief Set all flags to their negation. + /// \return This. + public: FlagSet& Flip() + { + flags.flip(); + return *this; + } + + /// \brief Set the given flag to the specified value. + /// \param[in] _val The flag to set. + /// \param[in] _value The value to set. + /// \return This. + public: FlagSet& Set(const T& _val, bool _value = true) + { + flags.set(static_cast(_val), _value); + return *this; + } + + /// \brief Set the given flag to false. + /// \param[in] _val The flag to set. + /// \return This. + public: FlagSet& Reset(const T& _val) + { + flags.reset(static_cast(_val)); + return *this; + } + + /// \brief Negate the given flag. + /// \param[in] _val The flag to negate. + /// \return This. + public: FlagSet& Flip(const T& _val) + { + flags.flip(static_cast(_val)); + return *this; + } + + /// \brief Test whether any flag is set. + /// \return True if at least one flag is set to true. + public: bool Any() const + { + return flags.any(); + } + + /// \brief Test whether all flags are set. + /// \return True if at all flags are set to true. + public: bool All() const + { + return flags.all(); + } + + /// \brief Test whether no flag is set. + /// \return True if at no flag is set to true. + public: bool None() const + { + return flags.none(); + } + + /// \brief Retrurn a FlagSet with all flags set to true. + public: static FlagSet AllSet() + { + return FlagSet().Set(); + } + + /// \brief Retrurn a FlagSet with all flags set to false. + public: static FlagSet NoneSet() + { + return FlagSet(); + } + + /// \brief Return whether the given flag is set. + /// \param[in] _val The flag to test. + /// \return Whether the flag is set. + /// \note This only works for enums whose underlying type is unsigned. + public: constexpr bool operator[](const T& _val) const + { + return flags[static_cast(static_cast(_val))]; + } + + /// \brief Return a string describing this FlagSet. + /// \return The string. + public: std::string String() const + { + return flags.to_string(); + } + + /// \brief Operator for outputting to std::ostream. + /// \param[in,out] _stream The stream to write to. + /// \param[in] _self The FlagSet to write. + /// \return _stream with the contents of the given FlagSet written. + public: friend std::ostream& operator<<(std::ostream& _stream, + const FlagSet& _self) + { + return _stream << _self.flags; + } + + /// \brief Compute hash of the FlagSet. + /// \return The hash. + public: size_t Hash() const + { + return std::hashflags)>{}(this->flags); + } + + /// \brief The underlying type of the enum. + private: using UnderlyingType = std::underlying_type_t; + + /// \brief Number of elements of the bitset. + public: static constexpr size_t numElements = static_cast( + static_cast(LastElement) + + static_cast(1 - ExcludeLast)); + + /// \brief The bitset holding values for the flags. + private: std::bitset flags; +}; + +template +struct IsEnumThatContainsSentinel : std::false_type +{ +}; + +template +struct IsEnumThatContainsSentinel(T::_))> + : std::is_enum +{ +}; + +} + +// Operator that combines two enumeration values into a FlagSet only if the +// enumeration contains the sentinel `_`. +template +std::enable_if_t< + ignition::common::IsEnumThatContainsSentinel::value, + ignition::common::FlagSet +> +operator|(const T& _lhs, const T& _rhs) +{ + ignition::common::FlagSet fs; + fs |= _lhs; + fs |= _rhs; + + return fs; +} + +namespace std +{ +template +struct hash> +{ + std::size_t operator()( + const ignition::common::FlagSet& _s) + const noexcept + { + return _s.Hash(); + } +}; +} + +#endif diff --git a/include/gz/common/MaterialDensity.hh b/include/gz/common/MaterialDensity.hh new file mode 100644 index 000000000..7dfa3f089 --- /dev/null +++ b/include/gz/common/MaterialDensity.hh @@ -0,0 +1,143 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_MATERIALDENSITY_HH_ +#define GZ_COMMON_MATERIALDENSITY_HH_ + +#include +#include +#include +#include +#include "gz/common/Export.hh" + +namespace ignition +{ + namespace common + { + /// \brief Encapsulates density types. + class IGNITION_COMMON_VISIBLE MaterialDensity + { + /// \enum Type + /// \brief Types of materials. + /// Source: https://en.wikipedia.org/wiki/Density + public: enum class Type + { + /// \internal + /// \brief Indicator used to create an iterator over the enum. Do not + /// use this. + BEGIN = 0, + + /// \brief Styrofoam, density = 75.0 kg/m^3 + STYROFOAM = BEGIN, + + /// \brief Pine, density = 373.0 kg/m^3 + PINE, + + /// \brief Wood, density = 700.0 kg/m^3 + WOOD, + + /// \brief Oak, density = 710.0 kg/m^3 + OAK, + + /// \brief Ice, density = 916.0 kg/m^3 + ICE, + + /// \brief Water, density = 1000.0 kg/m^3 + WATER, + + /// \brief Plastic, density = 1175.0 kg/m^3 + PLASTIC, + + /// \brief Concrete, density = 2000.0 kg/m^3 + CONCRETE, + + /// \brief Aluminum, density = 2700.0 kg/m^3 + ALUMINUM, + + /// \brief Steel alloy, density = 7600.0 kg/m^3 + STEEL_ALLOY, + + /// \brief Stainless steel, density = 7800.0 kg/m^3 + STEEL_STAINLESS, + + /// \brief Iron, density = 7870.0 kg/m^3 + IRON, + + /// \brief Brass, density = 8600.0 kg/m^3 + BRASS, + + /// \brief Copper, density = 8940.0 kg/m^3 + COPPER, + + /// \brief Tungsten, density = 19300.0 kg/m^3 + TUNGSTEN, + + /// \internal + /// \brief Indicator used to create an iterator over the enum. Do not + /// use this. + END + }; + + /// \brief Accessor for retrieving density entries + /// \return List of entries. + public: static const std::map &Materials(); + + /// \brief Return the density of the given material name, or -1 + /// if the material is not found. + /// \param[in] _material Name of the material, See Type. + /// \return Matching density if found, otherwise -1. + public: static double Density(const std::string &_material); + + /// \brief Return the density of a material. + /// \param[in] _material Type of the material, See Type. + /// \return Matching density if found, otherwise -1. + public: static double Density(const Type _material); + + /// \brief Return the material with the closest density value within + /// _epsilon, or MATERIAL_TYPE_END if not found. + /// \param[in] _value Density value of entry to match. + /// \param[in] _epsilon Allowable range of difference between _value, + /// and a material's density. + /// \return A tuple where the first element is the Type, and + /// the second the density. A value of {MATERIAL_TYPE_END, -1} is + /// returned on error. + public: static std::tuple Nearest( + const double _value, + const double _epsilon = std::numeric_limits::max()); + + /// \brief Return the material with the closest density value within + /// _epsilon, or MATERIAL_TYPE_END if not found. + /// \param[in] _value Density value of entry to match. + /// \param[in] _epsilon Allowable range of difference between _value, + /// and a material's density. + /// \return The nearest material type. MATERIAL_TYPE_END on error. + public: static Type NearestMaterial(const double _value, + const double _epsilon = std::numeric_limits::max()); + +#ifdef _WIN32 +// Disable warning C4251 +#pragma warning(push) +#pragma warning(disable: 4251) +#endif + /// \brief List of density entries + private: static std::map materials; +#ifdef _WIN32 +#pragma warning(pop) +#endif + }; + } +} +#endif diff --git a/include/gz/common/MovingWindowFilter.hh b/include/gz/common/MovingWindowFilter.hh new file mode 100644 index 000000000..83938e495 --- /dev/null +++ b/include/gz/common/MovingWindowFilter.hh @@ -0,0 +1,186 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_MOVINGWINDOWFILTER_HH_ +#define GZ_COMMON_MOVINGWINDOWFILTER_HH_ + +#include +#include + +namespace ignition +{ + namespace common + { + /// \cond + /// \brief Private data members for MovingWindowFilter class. + /// This must be in the header due to templatization. + template< typename T> + class MovingWindowFilterPrivate + { + // \brief Constructor + public: MovingWindowFilterPrivate(); + + /// \brief For moving window smoothed value + public: unsigned int valWindowSize = 4; + + /// \brief buffer history of raw values + public: std::vector valHistory; + + /// \brief iterator pointing to current value in buffer + public: typename std::vector::iterator valIter; + + /// \brief keep track of running sum + public: T sum; + + /// \brief keep track of number of elements + public: unsigned int samples = 0; + }; + /// \endcond + + ////////////////////////////////////////////////// + template + MovingWindowFilterPrivate::MovingWindowFilterPrivate() + { + /// \TODO FIXME hardcoded initial value for now + this->valHistory.resize(this->valWindowSize); + this->valIter = this->valHistory.begin(); + this->sum = T(); + } + + /// \brief Base class for MovingWindowFilter + template< typename T> + class MovingWindowFilter + { + /// \brief Constructor + public: MovingWindowFilter(); + + /// \brief Destructor + public: virtual ~MovingWindowFilter(); + + /// \brief Update value of filter + /// \param[in] _val new raw value + public: void Update(T _val); + + /// \brief Set window size + /// \param[in] _n new desired window size + public: void SetWindowSize(unsigned int _n); + + /// \brief Get the window size. + /// \return The size of the moving window. + public: unsigned int WindowSize() const; + + /// \brief Get whether the window has been filled. + /// \return True if the window has been filled. + public: bool WindowFilled() const; + + /// \brief Get filtered result + /// \return Latest filtered value + public: T Value(); + + /// \brief Allow subclasses to initialize their own data pointer. + /// \param[in] _d Reference to data pointer. + protected: explicit MovingWindowFilter( + MovingWindowFilterPrivate &_d); + + /// \brief Data pointer. + protected: std::unique_ptr> dataPtr; + }; + + ////////////////////////////////////////////////// + template + MovingWindowFilter::MovingWindowFilter() + : dataPtr(new MovingWindowFilterPrivate()) + { + } + + ////////////////////////////////////////////////// + template + MovingWindowFilter::~MovingWindowFilter() + { + this->dataPtr->valHistory.clear(); + } + + ////////////////////////////////////////////////// + template + void MovingWindowFilter::Update(T _val) + { + // update sum and sample size with incoming _val + + // keep running sum + this->dataPtr->sum += _val; + + // shift pointer, wrap around if end has been reached. + ++this->dataPtr->valIter; + if (this->dataPtr->valIter == this->dataPtr->valHistory.end()) + { + // reset iterator to beginning of queue + this->dataPtr->valIter = this->dataPtr->valHistory.begin(); + } + + // increment sample size + ++this->dataPtr->samples; + + if (this->dataPtr->samples > this->dataPtr->valWindowSize) + { + // subtract old value if buffer already filled + this->dataPtr->sum -= (*this->dataPtr->valIter); + // put new value into queue + (*this->dataPtr->valIter) = _val; + // reduce sample size + --this->dataPtr->samples; + } + else + { + // put new value into queue + (*this->dataPtr->valIter) = _val; + } + } + + ////////////////////////////////////////////////// + template + void MovingWindowFilter::SetWindowSize(unsigned int _n) + { + this->dataPtr->valWindowSize = _n; + this->dataPtr->valHistory.clear(); + this->dataPtr->valHistory.resize(this->dataPtr->valWindowSize); + this->dataPtr->valIter = this->dataPtr->valHistory.begin(); + this->dataPtr->sum = T(); + this->dataPtr->samples = 0; + } + + ////////////////////////////////////////////////// + template + unsigned int MovingWindowFilter::WindowSize() const + { + return this->dataPtr->valWindowSize; + } + + ////////////////////////////////////////////////// + template + bool MovingWindowFilter::WindowFilled() const + { + return this->dataPtr->samples == this->dataPtr->valWindowSize; + } + + ////////////////////////////////////////////////// + template + T MovingWindowFilter::Value() + { + return this->dataPtr->sum / static_cast(this->dataPtr->samples); + } + } +} +#endif diff --git a/include/gz/common/Plugin.hh b/include/gz/common/Plugin.hh new file mode 100644 index 000000000..4c93e13fe --- /dev/null +++ b/include/gz/common/Plugin.hh @@ -0,0 +1,196 @@ +/* + * Copyright (C) 2017 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + + +#ifndef GZ_COMMON_PLUGIN_HH_ +#define GZ_COMMON_PLUGIN_HH_ + +#include +#include +#include + +#include +#include + +namespace ignition +{ + namespace common + { + // Forward declarations + struct PluginInfo; + class PluginPrivate; + namespace detail { template class ComposePlugin; } + + class IGNITION_COMMON_VISIBLE Plugin + { + // -------------------- Public API --------------------- + + /// \brief Get an interface of the specified type. Note that this function + /// only works when the Interface type is specialized using the macro + /// IGN_COMMON_SPECIALIZE_INTERFACE. For more general interfaces which do + /// not meet this condition, use + /// QueryInterface(_interfaceName). + /// + /// Note that the interface pointer you receive is owned by the Plugin + /// object. You MUST NOT ever try to deallocate it yourself. Moreover, the + /// pointer will be invalidated once all Plugin objects that refer to the + /// same Plugin instance are destructed. Use the QueryInterfaceSharedPtr + /// function in order to get a reference-counting pointer to an interface + /// of this Plugin object. The pointer will remain valid as long as the + /// std::shared_ptr provided by QueryInterfaceSharedPtr is alive. + public: template + Interface *QueryInterface(); + + /// \brief const-qualified version of QueryInterface() + public: template + const Interface *QueryInterface() const; + + /// \brief Get an interface with the given name, casted to the specified + /// class type. The template argument Interface must exactly match the + /// underlying type associated with _interfaceName, or else the behavior + /// of this function is undefined. + /// + /// Note that the interface pointer you receive is owned by the Plugin + /// object. You MUST NOT ever try to deallocate it yourself. Moreover, the + /// pointer will be invalidated once all Plugin objects that refer to the + /// same Plugin instance are destructed. Use the QueryInterfaceSharedPtr + /// function in order to get a reference-counting pointer to an interface + /// of this Plugin object. The pointer will remain valid as long as the + /// std::shared_ptr provided by QueryInterfaceSharedPtr is alive. + /// + /// \param[in] _interfaceName The name of the desired interface, as a + /// string. + /// \return A raw pointer to the specified interface. If the requested + /// _interfaceName is not provided by this Plugin, this returns a nullptr. + /// This pointer is invalidated when the reference count of the plugin + /// instance drops to zero. + public: template + Interface *QueryInterface(const std::string &_interfaceName); + + /// \brief const-qualified version of + /// QueryInterface(std::string) + public: template + const Interface *QueryInterface( + const std::string &_interfaceName) const; + + /// \brief Get the requested interface as a std::shared_ptr. Note that + /// this function only works when the Interface type is specialized using + /// the macro IGN_COMMON_SPECIALIZE_INTERFACE. For more general interfaces + /// which do not meet this condition, use + /// QueryInterfaceSharedPtr(const std::string&). + public: template + std::shared_ptr QueryInterfaceSharedPtr(); + + /// \brief Same as QueryInterfaceSharedPtr(), but it returns a + /// std::shared_ptr to a const-qualified Interface. + public: template + std::shared_ptr QueryInterfaceSharedPtr() const; + + /// \brief Get the requested interface as a std::shared_ptr. The template + /// argument Interface must exactly match the underlying type associated + /// with _interfaceName, or else the behavior of this function is + /// undefined. + /// + /// This std::shared_ptr and the interface+plugin that it refers to will + /// remain valid, even if all Plugin objects which refer to the plugin + /// instance are destructed. + /// + /// You MUST NOT attempt to pass a QueryInterface pointer into a + /// std::shared_ptr yourself; that will result in double-delete memory + /// errors. You must always call QueryInterfaceSharedPtr for a reference- + /// counting pointer to an interface. + /// + /// \param[in] _interfaceName The name of the desired interface, as a + /// string. + /// \return A reference-counting pointer to the specified interface. This + /// will keep the interface valid and the plugin instance alive, even if + /// all Plugin objects that refer to this plugin instance are destructed. + public: template + std::shared_ptr QueryInterfaceSharedPtr( + const std::string &_interfaceName); + + /// \brief Same as QueryInterfaceSharedPtr(std::string), but + /// it returns a std::shared_ptr to a const-qualified Interface. + public: template + std::shared_ptr QueryInterfaceSharedPtr( + const std::string &_interfaceName) const; + + /// \brief Returns true if this Plugin has the specified type of + /// interface. Note that this function only works when the Interface type + /// is specialized using the macro IGN_COMMON_SPECIALIZE_INTERFACE. For + /// more general interfaces which do not meet this condition, use + /// QueryInterface(_interfaceName). + public: template + bool HasInterface() const; + + /// \brief Returns true if this Plugin has the specified type of + /// interface, otherwise returns false. + /// + /// \param[in] _interfaceName The name of the desired interface, as a + /// string. + public: bool HasInterface(const std::string &_interfaceName) const; + + + // -------------------- Private API ----------------------- + + template friend class TemplatePluginPtr; + template friend class SpecializedPlugin; + template friend class detail::ComposePlugin; + + /// \brief Default constructor. This is kept private to ensure that + /// Plugins are always managed by a PluginPtr object. + private: Plugin(); + + /// \brief Type-agnostic retriever for interfaces + private: void *PrivateGetInterface( + const std::string &_interfaceName) const; + + /// \brief Copy the plugin instance from another Plugin object + private: void PrivateCopyPluginInstance(const Plugin &_other) const; + + /// \brief Create a new plugin instance based on the info provided + private: void PrivateSetPluginInstance(const PluginInfo *_info) const; + + /// \brief Get a reference to the std::shared_ptr being managed by this + /// wrapper + private: const std::shared_ptr& PrivateGetInstancePtr() const; + + /// \brief The InterfaceMap type needs to get used in several places, like + /// PluginPrivate and SpecializedPlugin. We make the typedef public so + /// that those other classes can use it without needing to be friends of + /// Plugin. End-users should not have any need for this typedef. + public: using InterfaceMap = std::map; + + /// \brief Get or create an iterator to the std::map that holds pointers + /// to the various interfaces provided by this plugin instance. + private: InterfaceMap::iterator PrivateGetOrCreateIterator( + const std::string &_interfaceName); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief PIMPL pointer to the implementation of this class. + private: const std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + + /// \brief Virtual destructor + public: virtual ~Plugin(); + }; + } +} + +#include "gz/common/detail/Plugin.hh" + +#endif diff --git a/include/gz/common/PluginInfo.hh b/include/gz/common/PluginInfo.hh new file mode 100644 index 000000000..4ae4941b6 --- /dev/null +++ b/include/gz/common/PluginInfo.hh @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2017 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + + +#ifndef GZ_COMMON_PLUGININFO_HH_ +#define GZ_COMMON_PLUGININFO_HH_ + +#include +#include +#include + +namespace ignition +{ + namespace common + { + /// \brief sentinel value to check if a plugin was built with the same + /// version of the PluginInfo struct + // + /// This must be incremented when the PluginInfo struct changes + const int PLUGIN_API_VERSION = 1; + + + /// \brief Holds info required to construct a plugin + struct PluginInfo + { + /// \brief The name of the plugin + std::string name; + + /// \brief The keys are the names of the types of interfaces that this + /// plugin provides. The values are functions that convert a void pointer + /// (which actually points to the plugin instance) to another void pointer + /// (which actually points to the location of the interface within the + /// plugin instance). + using InterfaceCastingMap = + std::unordered_map< std::string, std::function >; + InterfaceCastingMap interfaces; + + /// \brief A method that instantiates a new instance of a plugin + std::function factory; + + /// \brief A method that safely deletes an instance of the plugin + std::function deleter; + }; + } +} + +#endif diff --git a/include/gz/common/PluginLoader.hh b/include/gz/common/PluginLoader.hh new file mode 100644 index 000000000..a80a39d5a --- /dev/null +++ b/include/gz/common/PluginLoader.hh @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2017 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + + +#ifndef GZ_COMMON_PLUGINLOADER_HH_ +#define GZ_COMMON_PLUGINLOADER_HH_ + +#include +#include +#include +#include + +#include +#include +#include + +namespace ignition +{ + namespace common + { + /// \brief Forward declaration + class PluginLoaderPrivate; + struct PluginInfo; + + /// \brief Class for loading plugins + class IGNITION_COMMON_VISIBLE PluginLoader + { + /// \brief Constructor + public: PluginLoader(); + + /// \brief Destructor + public: ~PluginLoader(); + + /// \brief Makes a printable string with info about plugins + /// \returns A pretty string + public: std::string PrettyStr() const; + + /// \brief Get names of interfaces that the loader has plugins for + /// \returns Interfaces that are implemented + public: std::unordered_set InterfacesImplemented() const; + + /// \brief Get plugin names that implement the interface + /// \param[in] _interface Name of an interface + /// \returns Names of plugins that implement the interface + public: std::unordered_set PluginsImplementing( + const std::string &_interface) const; + + /// \brief Load a library at the given path + /// \param[in] _pathToLibrary is the path to a libaray + /// \returns The set of plugins that have been loaded from the library + public: std::unordered_set LoadLibrary( + const std::string &_pathToLibrary); + + /// \brief Instantiates a plugin for the given plugin name + /// + /// \param[in] _plugin name of the plugin to instantiate + /// \returns Pointer to instantiated plugin + public: PluginPtr Instantiate(const std::string &_pluginName) const; + + /// \brief Instantiates a plugin of PluginType for the given plugin name. + /// This can be used to create a specialized PluginPtr. + /// + /// \tparam PluginPtrType The specialized type of PluginPtrPtr that you + /// want to construct. + /// \param[in] _pluginName The name of the plugin that you want to + /// instantiate + /// \returns pointer for the instantiated PluginPtr + public: template + PluginPtrType Instantiate( + const std::string &_pluginName) const; + + /// \brief Get a pointer to the PluginInfo corresponding to _pluginName. + /// \param[in] _pluginName The name of the plugin that you want to + /// instantiate + /// \return Pointer to PluginInfo or nullptr if there is no info for the + /// requested _pluginName. + private: const PluginInfo *PrivateGetPluginInfo( + const std::string &_pluginName) const; + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief PIMPL pointer to class implementation + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} + +#include "gz/common/detail/PluginLoader.hh" + +#endif diff --git a/include/gz/common/PluginMacros.hh b/include/gz/common/PluginMacros.hh new file mode 100644 index 000000000..ce293e193 --- /dev/null +++ b/include/gz/common/PluginMacros.hh @@ -0,0 +1,142 @@ +/* + * Copyright (C) 2017 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + + +#ifndef GZ_COMMON_REGISTERMACROS_HH_ +#define GZ_COMMON_REGISTERMACROS_HH_ + +#include "gz/common/detail/PluginMacros.hh" + +// --------------- Specialize a plugin interface (optional) ------------------- + +/// \brief Call this macro inside a public scope of an interface in order to get +/// performance benefits for that interface in a SpecializedPlugin. Pass in +/// the fully qualified name of the interface class (i.e. explicitly include the +/// namespaces of the class). +/// +/// Usage example: +/// +/// \code +/// namespace mylibrary { +/// namespace ns { +/// class SomeInterface +/// { +/// public: +/// IGN_COMMON_SPECIALIZE_INTERFACE(mylibrary::ns::SomeInterface) +/// // ... declarations of interface functions ... +/// }; +/// } // namespace ns +/// } // namespace mylibrary +/// \endcode +/// +/// Interfaces with this macro can be utilized by SpecializedPlugin to get +/// high-speed access to this type of interface. Note that this performance +/// benefit is available even if the plugin that gets loaded does not offer this +/// interface; you just get high-speed access to a nullptr instead. Always be +/// sure to verify the existence of an interface that you query from a plugin by +/// checking whether it's a nullptr! +#define IGN_COMMON_SPECIALIZE_INTERFACE(interfaceName)\ + DETAIL_IGN_COMMON_SPECIALIZE_INTERFACE(interfaceName) + + +// ------------- Add a set of plugins or a set of interfaces ------------------ + +// The following three macros can be used to produce multiple plugins and/or +// multiple interfaces from your shared library. + +/* Usage example for multiple plugins and one interface: + * + * IGN_COMMON_BEGIN_ADDING_PLUGINS + * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeClass1, mylibrary::ns::SomeInterface) + * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeClass2, mylibrary::ns::SomeInterface) + * IGN_COMMON_FINISH_ADDING_PLUGINS + * + * + * Usage example for one plugin and multiple interfaces: + * + * IGN_COMMON_BEGIN_ADDING_PLUGINS + * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeClass, mylibrary::ns::Interface1) + * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeClass, mylibrary::ns::Interface2) + * IGN_COMMON_FINISH_ADDING_PLUGINS + * + * + * Usage example for multiple plugins and multiple interfaces: + * + * IGN_COMMON_BEGIN_ADDING_PLUGINS + * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeClass, mylibrary::ns::FooInterface) + * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeOtherClass, mylibrary::ns::BarInterface) + * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeClass, mylibrary::ns::SomeInterface) + * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeOtherClass, mylibrary::ns::FooInterface) + * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeOtherClass, mylibrary::ns::SomeInterface) + * IGN_COMMON_FINISH_ADDING_PLUGINS + */ + +// Note that the order in which (Plugin, Interface) pairs are added does not +// matter. Multiple plugins are allowed to provide the same interface. There is +// no inherent limit on the number of interfaces or plugins that are allowed. +// +// These macros MUST be called in the global namespace in a source file of your +// library's codebase. A single library is only allowed to have ONE block of +// these macros (i.e. if you find yourself invoking +// IGN_COMMON_BEGIN_ADDING_PLUGINS more than once in your library, then you are +// doing something that is not permitted). Recommended practice is to have a +// single source file (e.g. plugins.cpp) in your library's codebase that is +// dedicated to hosting these macros. + + +/// \brief Begin registering a set of plugins that are contained within this +/// shared library. After invoking this macro, use a sequence of calls to +/// IGN_COMMON_ADD_PLUGIN(~,~), passing in a different plugin and interface name +/// to each call. When all the plugins and interfaces have been added, call +/// IGN_COMMON_FINISH_ADDING_PLUGINS. +/// +/// Be sure to only use this macro in the global namespace, and only use it once +/// in your library. +#define IGN_COMMON_BEGIN_ADDING_PLUGINS\ + DETAIL_IGN_COMMON_BEGIN_ADDING_PLUGINS + + +/// \brief Add a plugin and interface from this shared library. This macro must +/// be called consecutively on each class that this shared library wants to +/// provide as a plugin or interface. This macro must be called in between +/// IGN_COMMON_BEGIN_ADDING_PLUGINS and IGN_COMMON_FINISH_ADDING_PLUGINS. If a +/// plugin provides multiple interfaces, then simply call this macro repeatedly +/// on the plugin, once for each interface. The multiple interfaces will +/// automatically be collapsed into one plugin that provides all of them. +#define IGN_COMMON_ADD_PLUGIN(plugin, interface)\ + DETAIL_IGN_COMMON_ADD_PLUGIN(plugin, interface) + + +/// \brief Call this macro after all calls to IGN_COMMON_ADD_PLUGIN have been +/// finished. +#define IGN_COMMON_FINISH_ADDING_PLUGINS\ + DETAIL_IGN_COMMON_FINISH_ADDING_PLUGINS + + +// -------------- Add a single plugin with a single interface ----------------- + +/// \brief Register a shared library with only one plugin and one interface. +/// This macro is NOT compatible with IGN_COMMON_ADD_PLUGIN or any of the +/// above macros for adding multiple plugins and/or multiple interfaces. This is +/// simply a convenience function if you want to add one plugin with one +/// interface from your library. +#define IGN_COMMON_REGISTER_SINGLE_PLUGIN(plugin, interface) \ + IGN_COMMON_BEGIN_ADDING_PLUGINS\ + IGN_COMMON_ADD_PLUGIN(plugin, interface)\ + IGN_COMMON_FINISH_ADDING_PLUGINS + +#endif diff --git a/include/gz/common/PluginPtr.hh b/include/gz/common/PluginPtr.hh new file mode 100644 index 000000000..0cc07abda --- /dev/null +++ b/include/gz/common/PluginPtr.hh @@ -0,0 +1,231 @@ +/* + * Copyright (C) 2017 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + + +#ifndef GZ_COMMON_PLUGINPTR_HH_ +#define GZ_COMMON_PLUGINPTR_HH_ + +#include +#include +#include + +#include "gz/common/Plugin.hh" + +namespace ignition +{ + namespace common + { + // Forward declarations + struct PluginInfo; + namespace detail { template class ComposePlugin; } + + /// \brief This class manages the lifecycle of a plugin instance. It can + /// receive a plugin instance from the ignition::common::PluginLoader class + /// or by copy-construction or assignment from another PluginPtr instance. + /// + /// This class behaves similarly to a std::shared_ptr where multiple + /// PluginPtr objects can share a single plugin instance, and the plugin + /// instance will not be deleted until all PluginPtr objects that refer to + /// it are either destroyed, cleared, or begin referring to a different + /// plugin instance. + /// + /// A PluginPtr object can be "cast" to a SpecializedPluginPtr object by + /// simply using the copy/move constructor or assignment operator of a + /// SpecializedPluginPtr object. Note that this "cast" does have a small + /// amount of overhead associated with it, but it may result in huge savings + /// after initialization is finished if you frequently access the interfaces + /// that the SpecializedPluginPtr is specialized for. + template + class TemplatePluginPtr final + { + /// \brief Destructor. Deletes this PluginPtr's reference to the plugin + /// instance. Once all PluginPtrs that refer to a plugin instance are + /// deleted, the plugin will also be deleted. + public: ~TemplatePluginPtr() = default; + + /// \brief Default constructor. Creates a PluginPtr object that does not + /// point to any plugin instance. IsEmpty() will return true until a + /// plugin instance is provided. + public: TemplatePluginPtr(); + + /// \brief Copy constructor. This PluginPtr will now point at the same + /// plugin instance as _other, and they will share ownership. + /// \param[in] _other Pointer to plugin being copied. + public: TemplatePluginPtr(const TemplatePluginPtr &_other); + + /// \brief Move constructor. This PluginPtr will take ownership of the + /// plugin instance held by _other. If this PluginPtr was holding an + /// instance to another plugin, that instance will be deleted if no other + /// PluginPtr is referencing it. + /// \param[in] _other Pointer to plugin being moved. + public: TemplatePluginPtr(TemplatePluginPtr &&_other); + + /// \brief Casting constructor. This PluginPtr will now point at the same + /// plugin instance as _other, and they will share ownership. This + /// essentially allows casting between PluginPtrs that are holding + /// different types of plugin wrappers (for example, you can cast a + /// generic PluginPtr to any SpecializedPluginPtr type, or you can cast + /// between different types of specializations). + /// \param[in] _other Another PluginPtr object. It may have a different + /// kind of specialization. + public: template + TemplatePluginPtr( + const TemplatePluginPtr &_other); + + /// \brief Copy assignment operator. This PluginPtr will now point at the + /// same plugin instance as _other, and they will share ownership. If this + /// PluginPtr was holding an instance to another plugin, that instance + /// will be deleted if no other PluginPtr is referencing it. + /// \param[in] _other Pointer to plugin being copied. + public: TemplatePluginPtr &operator =(const TemplatePluginPtr &_other); + + /// \brief Casting operator. This PluginPtr will now point at the same + /// plugin instance as _other, and they will share ownership. This + /// essentially allows casting between PluginPtrs that are holding + /// different types of plugin wrappers. + /// \param[in] _other Another PluginPtr object. It may have a different + /// kind of specialization. + /// \return A reference to this object. + public: template + TemplatePluginPtr &operator =( + const TemplatePluginPtr &_other); + + /// \brief Move assignment operator. This PluginPtr will take ownership + /// of the plugin instance held by _other. If this PluginPtr was holding + /// an instance to another plugin, that instance will be deleted if no + /// other PluginPtr is referencing it. + /// \param[in] _other Another PluginPtr object. + /// \return A reference to this object. + public: TemplatePluginPtr &operator =(TemplatePluginPtr &&_other); + + /// \brief nullptr assignment operator. Same as calling Clear() + /// \param[in] A nullptr object. + /// \return A reference to this object. + public: TemplatePluginPtr &operator =(std::nullptr_t); + + /// \brief Access the wrapper for the plugin instance and call one of its + /// member functions. + /// \return The ability to call a member function on the underlying Plugin + /// object. + public: PluginType *operator ->() const; + + /// \brief Get a reference to the wrapper for the plugin instance that is + /// being managed by this PluginPtr. + /// \return A reference to the underlying Plugin object. + public: PluginType &operator *() const; + + /// \brief Comparison operator. Returns true if this Plugin is holding the + /// same plugin instance as _other, otherwise returns false. + /// \param[in] _other Another PluginPtr object. + /// \return True if the value of this pointer is == _other. + public: bool operator ==(const TemplatePluginPtr &_other) const; + + /// \brief Comparison operator. + /// \param[in] _other Plugin to compare to. + /// \returns True if the pointer value of the plugin instance held + /// by this PluginPtr is less than the pointer value of the instance held + /// by _other. + /// \param[in] _other Another PluginPtr object. + /// \return True if the value of this pointer is < _other. + public: bool operator <(const TemplatePluginPtr &_other) const; + + /// \brief Comparison operator. + /// \param[in] _other Plugin to compare to. + /// \returns True if the pointer value of the plugin instance held + /// by this PluginPtr is greater than the pointer value of the instance + /// held by _other. + /// \param[in] _other Another PluginPtr object. + /// \return True if the value of this pointer is > _other. + public: bool operator >(const TemplatePluginPtr &_other) const; + + /// \brief Comparison operator. + /// \param[in] _other Plugin to compare to. + /// \returns True if the pointer instance held by this PluginPtr is + /// different from the pointer instance held by _other. + /// \param[in] _other Another PluginPtr object. + /// \return True if the value of this pointer is != _other. + public: bool operator !=(const TemplatePluginPtr &_other) const; + + /// \brief Comparison operator. + /// \param[in] _other Plugin to compare to. + /// \returns True if the value of the pointer instance held by this + /// PluginPtr is less than or equal to the value of the pointer instance + /// held by _other. + /// \param[in] _other Another PluginPtr object. + /// \return True if the value of this pointer is <= _other. + public: bool operator <=(const TemplatePluginPtr &_other) const; + + /// \brief Comparison operator. + /// \param[in] _other Plugin to compare to. + /// \returns True if the value of the pointer instance held by this + /// PluginPtr is greater than or equal to the value of the pointer + /// instance held by _other. + /// \param[in] _other Another PluginPtr object. + /// \return True if the value of this pointer is >= _other. + public: bool operator >=(const TemplatePluginPtr &_other) const; + + /// \brief Produces a hash for the plugin instance that this PluginPtr is + /// holding. This function allows PluginPtr instances to be used as values + /// in a std::unordered_set or keys in a + /// std::unordered_map. Using this function directly should + /// not normally be necessary. + /// \return A hash of the underlying pointer object. + public: std::size_t Hash() const; + + /// \brief Check if this PluginPtr is holding a plugin instance. + /// \return False if this PluginPtr contains a plugin instance. If it + /// instead contains a nullptr, this returns true. + public: bool IsEmpty() const; + + /// \brief Implicitly convert this PluginPtr to a boolean. + /// \return The opposite value of IsEmpty(). + public: operator bool() const; + + /// \brief Clears the Plugin instance from this PluginPtr. IsEmpty() will + /// return true after this is used, and none of the interfaces will be + /// available any longer. + public: void Clear(); + + /// \brief Private constructor. Creates a plugin instance based on the + /// PluginInfo provided. This should only be called by PluginLoader to + /// ensure that the PluginInfo is well-formed, so we keep it private. + /// \param[in] _info A PluginInfo instance that was generated by + /// PluginLoader. Alternatively, this can take a nullptr to create an + /// empty PluginPtr. + private: explicit TemplatePluginPtr(const PluginInfo *_info); + + /// \brief Pointer to the plugin wrapper that this PluginPtr is managing. + private: std::unique_ptr dataPtr; + + // Declare friendship + friend class PluginLoader; + template friend class TemplatePluginPtr; + }; + + /// \brief Typical usage for TemplatePluginPtr is to just hold a generic + /// Plugin type. + using PluginPtr = TemplatePluginPtr; + + /// \brief This produces a PluginPtr whose Plugin wrapper only grants access + /// to const-qualified interfaces of the plugin instance. + using ConstPluginPtr = TemplatePluginPtr; + } +} + +#include "gz/common/detail/PluginPtr.hh" + +#endif diff --git a/include/gz/common/SignalHandler.hh b/include/gz/common/SignalHandler.hh new file mode 100644 index 000000000..a8476de44 --- /dev/null +++ b/include/gz/common/SignalHandler.hh @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2018 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_SIGNALHANDLER_HH_ +#define GZ_COMMON_SIGNALHANDLER_HH_ + +#include + +#include + +namespace ignition +{ + namespace common + { + // Forward declarations. + class SignalHandlerPrivate; + + /// \brief Register callbacks that get triggered on SIGINT and SIGTERM. + /// + /// This class is a thread-safe interface to system signals (SIGINT and + /// SIGTERM). Use the AddCallback(std::function) + /// function to register callbacks that + /// should be called when a SIGINT or SIGTERM is triggered. + /// + /// Example using a lambda callback: + /// + /// ~~~ + /// ignition::common::SignalHandler handler; + /// handler.AddCallback([] (int _sig) + /// { + /// printf("Signal[%d] received\n", _sig); + /// }); + /// ~~~ + /// + class IGNITION_COMMON_VISIBLE SignalHandler + { + /// \brief Constructor + public: SignalHandler(); + + /// \brief Destructor. + public: virtual ~SignalHandler(); + + /// \brief Add a callback to execute when a signal is received. + /// \param[in] _cb Callback to execute. + /// \return True if the callback was added. A callback may not be + /// added if the SignalHandler was not successfully initialized. + /// \sa bool Initialized() const + public: bool AddCallback(std::function _cb); + + /// \brief Get whether the signal handlers were successfully + /// initialized. + /// \return True if the signal handlers were successfully created. + public: bool Initialized() const; + + /// \brief Set whether the signal handler was successfully + /// initialized. This function is here for testing purposes, and + /// if for some reason a person needs to create a subclass to control + /// the initialization value. + /// \param[in] _init New value of the initialized member variabl.e + protected: virtual void SetInitialized(const bool _init); + + /// \brief Private data pointer + private: SignalHandlerPrivate *dataPtr; + }; + } +} +#endif diff --git a/include/gz/common/SingletonT.hh b/include/gz/common/SingletonT.hh new file mode 100644 index 000000000..c7a556299 --- /dev/null +++ b/include/gz/common/SingletonT.hh @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_SINGLETONT_HH_ +#define GZ_COMMON_SINGLETONT_HH_ + +namespace ignition +{ + namespace common + { + /// \class SingletonT SingletonT.hh common/common.hh + /// \brief Singleton template class + template + class SingletonT + { + /// \brief Get an instance of the singleton + public: static T *Instance() + { + return &GetInstance(); + } + + /// \brief Constructor + protected: SingletonT() {} + + /// \brief Destructor + protected: virtual ~SingletonT() {} + + /// \brief Creates and returns a reference to the unique (static) instance + private: static T &GetInstance() + { + static T t; + return static_cast(t); + } + + /// \brief A reference to the unique instance + private: static T &myself; + }; + + /// \brief Initialization of the singleton instance. + template + T &SingletonT::myself = SingletonT::GetInstance(); + } +} +#endif diff --git a/include/gz/common/SpecializedPlugin.hh b/include/gz/common/SpecializedPlugin.hh new file mode 100644 index 000000000..0469b3587 --- /dev/null +++ b/include/gz/common/SpecializedPlugin.hh @@ -0,0 +1,170 @@ +/* + * Copyright (C) 2017 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#ifndef GZ_COMMON_SPECIALIZEDPLUGIN_HH_ +#define GZ_COMMON_SPECIALIZEDPLUGIN_HH_ + +#include + +#include "gz/common/Plugin.hh" + +namespace ignition +{ + namespace common + { + // Forward declarations + namespace detail { template class ComposePlugin; } + struct PluginInfo; + + // Forward declaration of the variadic template SpecializedPlugin class. + template + class SpecializedPlugin; + + /// \brief This class allows Plugin instances to have high-speed access to + /// interfaces that can be anticipated at compile time. The plugin does + /// not have to actually offer the specialized interface in order to get + /// this performance improvement. This template is variadic, so it can + /// support arbitrarily many interfaces. + /// + /// Usage example: + /// + /// \code + /// using MySpecialPluginPtr = SpecializedPluginPtr< + /// MyInterface1, FooInterface, MyInterface2, BarInterface>; + /// + /// MySpecialPluginPtr plugin = loader->Instantiate(pluginName); + /// \endcode + /// + /// Then, calling the function + /// + /// \code + /// plugin->QueryInterface(); + /// \endcode + /// + /// will have extremely high-speed associated with it. It will provide + /// direct access to the the `FooInterface*` of `plugin`. If `plugin` does + /// not actually offer `FooInterface`, then it will return a nullptr, still + /// at extremely high speed. + /// + /// Only interfaces that have been "specialized" can be passed as arguments + /// to the SpecializedPlugin template. To specialize an interface, simply + /// put the macro IGN_COMMON_SPECIALIZE_INTERFACE(~) from + /// ignition/common/PluginMacros.hh into a public location of its class + /// definition. + template + class SpecializedPlugin : public virtual Plugin + { + // -------------------- Public API --------------------- + + // Inherit function overloads + public: using Plugin::QueryInterface; + public: using Plugin::QueryInterfaceSharedPtr; + public: using Plugin::HasInterface; + + // Documentation inherited + public: template + Interface *QueryInterface(); + + // Documentation inherited + public: template + const Interface *QueryInterface() const; + + // Documentation inherited + public: template + std::shared_ptr QueryInterfaceSharedPtr(); + + // Documentation inherited + public: template + std::shared_ptr QueryInterfaceSharedPtr() const; + + // Documentation inherited + public: template + bool HasInterface() const; + + + // -------------------- Private API --------------------- + + // Declare friendship + template friend class SpecializedPlugin; + template friend class detail::ComposePlugin; + template friend class TemplatePluginPtr; + + /// \brief Default constructor + private: SpecializedPlugin(); + + /// \brief type is an empty placeholder class which is used by the private + /// member functions to provide two overloads: a high-performance one for + /// the specialized interface, and a normal-performance one for all other + /// Interface types. + private: template struct type { }; + + /// \brief Delegate the function to the standard Plugin method + /// \param[in] _type Empty object meant to guide the compiler to pick the + /// desired implementation. + /// \return Pointer to the interface + private: template + Interface *PrivateQueryInterface(type _type); + + /// \brief Use a high-speed accessor to provide this specialized interface + /// \param[in] _type Empty object meant to guide the compiler to pick the + /// desired implementation. + /// \return Pointer to the specialized interface + private: SpecInterface *PrivateQueryInterface( + type _type); + + /// \brief Delegate the function to the standard Plugin method + /// \param[in] _type Empty object meant to guide the compiler to pick the + /// desired implementation. + /// \return Pointer to the specialized interface + private: template + const Interface *PrivateQueryInterface(type _type) + const; + + /// \brief Use a high-speed accessor to provide this specialized interface + /// \param[in] _type Empty object meant to guide the compiler to pick the + /// desired implementation. + /// \return Pointer to the specialized interface + private: const SpecInterface *PrivateQueryInterface( + type _type) const; + + /// \brief Delegate the function to the standard PluginPtr method + /// \param[in] _type Empty object meant to guide the compiler to pick the + /// desired implementation. + /// \return True if the interface is present. + private: template + bool PrivateHasInterface(type _type) const; + + /// \brief Use a high-speed accessor to check this specialized interface + /// \param[in] _type Empty object meant to guide the compiler to pick the + /// desired implementation. + /// \return True if the interface is present. + private: bool PrivateHasInterface(type _type) const; + + /// \brief Iterator that points to the entry of the specialized interface + private: const Plugin::InterfaceMap::iterator + privateSpecializedInterfaceIterator; + + // Dev note (MXG): The privateSpecializedInterfaceIterator object must be + // available to the user during their compile time, so it cannot be hidden + // using PIMPL. The iterator is const because it must always point to the + // same entry throughout its entire lifecycle. + }; + } +} + +#include "gz/common/detail/SpecializedPlugin.hh" + +#endif diff --git a/include/gz/common/SpecializedPluginPtr.hh b/include/gz/common/SpecializedPluginPtr.hh new file mode 100644 index 000000000..199c21ba9 --- /dev/null +++ b/include/gz/common/SpecializedPluginPtr.hh @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2017 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + + +#ifndef GZ_COMMON_SPECIALIZEDPLUGINPTR_HH_ +#define GZ_COMMON_SPECIALIZEDPLUGINPTR_HH_ + +#include "gz/common/PluginPtr.hh" +#include "gz/common/SpecializedPlugin.hh" + +namespace ignition +{ + namespace common + { + /// \brief This alias allows PluginPtr instances to have high-speed access + /// to interfaces that can be anticipated at compile time. The plugin does + /// not have to actually offer the specialized interface in order to get + /// this performance improvement. This template is variadic, so it can + /// support arbitrarily many interfaces. + /// + /// Usage example: + /// + /// Suppose you want to instantiate a plugin that might (or might not) have + /// some combination of four interfaces which are known at compile time: + /// `MyInterface1`, `FooInterface`, `MyInterface2`, and `BarInterface`. You + /// can use SpecializedPluginPtr as shown here: + /// + /// \code + /// using MySpecialPluginPtr = SpecializedPluginPtr< + /// MyInterface1, FooInterface, MyInterface2, BarInterface>; + /// + /// MySpecialPluginPtr plugin = loader->Instantiate(pluginName); + /// \endcode + /// + /// Then, calling the function + /// + /// \code + /// plugin->QueryInterface(); + /// \endcode + /// + /// will have extremely high speed associated with it. It will provide + /// direct access to the the `FooInterface*` of `plugin`. If `plugin` does + /// not actually offer `FooInterface`, then it will return a nullptr, still + /// at extremely high speed. + /// + /// This same rule also applies to `MyInterface1`, `MyInterface2`, and + /// `BarInterface`, because those interfaces were also provided to + /// SpecializedPluginPtr<...> at compile time. + /// + /// Only interfaces that have been "specialized" can be passed as arguments + /// to the SpecializedPluginPtr template. To specialize an interface, simply + /// put the macro IGN_COMMON_SPECIALIZE_INTERFACE(~) from + /// ignition/common/PluginMacros.hh into a public location of its class + /// definition. + template + using SpecializedPluginPtr = + TemplatePluginPtr< SpecializedPlugin >; + + /// \brief This alias creates a specialized PluginPtr whose interfaces are + /// all const-qualified. + template + using ConstSpecializedPluginPtr = + TemplatePluginPtr< const SpecializedPlugin >; + } +} + +#endif diff --git a/include/gz/common/StringUtils.hh b/include/gz/common/StringUtils.hh new file mode 100644 index 000000000..cf0b601b0 --- /dev/null +++ b/include/gz/common/StringUtils.hh @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2017 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#ifndef GZ_COMMON_STRINGUTILS_HH_ +#define GZ_COMMON_STRINGUTILS_HH_ + +#include +#include + +#include + +namespace ignition +{ + namespace common + { + /// \brief split at a one character delimiter to get a vector of something + /// \param[in] _orig The string to split + /// \param[in] _delim a character to split the string at + /// \returns vector of split pieces of the string excluding the delimiter + std::vector IGNITION_COMMON_VISIBLE Split( + const std::string &_orig, char _delim); + + /// \brief Join a sequence of strings with a delimiter + /// + /// Note that this will skip any empty entries in the vector, + /// and will also not prepend or append the delimiter to the + /// final output string + /// + /// \param[in] _orig The input sequence of strings + /// \param[in] _delim a string delimiter to join the string with + /// \returns a single string composed of strings joined with the delimiter + std::string IGNITION_COMMON_VISIBLE Join( + const std::vector &_orig, const std::string &_delim); + + /// \brief Join a sequence of strings with a delimiter + /// + /// Note that this will skip any empty entries in the vector, + /// and will also not prepend or append the delimiter to the + /// final output string + /// + /// \param[in] _orig The input sequence of strings + /// \param[in] _delim a character to join the string with + /// \returns a single string composed of strings joined with the delimiter + std::string IGNITION_COMMON_VISIBLE Join( + const std::vector &_orig, char _delim); + + /// \brief return true if string starts with another string + /// \param[in] _s1 the string to check + /// \param[in] _s2 the possible prefix + /// \returns true if _s1 starts with _s2 + bool IGNITION_COMMON_VISIBLE StartsWith(const std::string &_s1, + const std::string &_s2); + + /// \brief return true if string ends with another string + /// \param[in] _s1 the string to check + /// \param[in] _s2 the possible suffix + /// \returns true if _s1 ends with _s2 + bool IGNITION_COMMON_VISIBLE EndsWith(const std::string &_s1, + const std::string &_s2); + + /// \brief Choose whether to use a singular or plural version of a noun + /// based on the value of an integer quantity. This version will simply add + /// an 's' character to _baseWord in the event that std::abs(_n) != 1, + /// otherwise it returns _baseWord. + /// \param[in] _baseWord the singular version of the word to return + /// \param[in] _n the quantity that _baseWord is describing + /// \return _baseWord if std::abs(_n)==1, otherwise return _baseWords + std::string IGNITION_COMMON_VISIBLE PluralCast( + const std::string &_baseWord, const int _n); + + /// \brief A version of PluralCast that works for irregular nouns. If + /// std::abs(_n)==1 then _singular is returned; otherwise _plural will be + /// returned. + /// \param[in] _singular the return value when std::abs(_n) == 1 + /// \param[in] _plural the return value when std::abs(_n) != 1 + /// \return _singular if std::abs(_n)==1, otherwise return _plural + std::string IGNITION_COMMON_VISIBLE PluralCast( + const std::string &_singular, + const std::string &_plural, + const int _n); + } +} + +#endif diff --git a/include/gz/common/SuppressWarning.hh b/include/gz/common/SuppressWarning.hh new file mode 100644 index 000000000..a270760b3 --- /dev/null +++ b/include/gz/common/SuppressWarning.hh @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2017 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + + +#ifndef GZ_COMMON_SUPPRESSWARNING_HH_ +#define GZ_COMMON_SUPPRESSWARNING_HH_ + +#include +#include + +// This header contains cross-platform macros for suppressing warnings. Please +// only use these macros responsibly when you are certain that the compiler is +// producing a warning that is not applicable to the specific instance. Do not +// use these macros to ignore legitimate warnings, even if you may find them +// irritating. + +/* + * Usage example: + * + * SomeClass* ptr = CreatePtr(); + * IGN_COMMON_WARN_IGNORE__DELETE_NON_VIRTUAL_DESTRUCTOR + * delete ptr; + * IGN_COMMON_WARN_RESUME__DELETE_NON_VIRTUAL_DESTRUCTOR + * + */ + +// Be sure to call the IGN_COMMON_WARN_RESUME__XXXXX macro at the end of the +// block of code where the warning suppression is needed. Otherwise, you might +// inadvertently suppress legitimate warnings. + +// ---- List of available suppressions ---- + +/// \brief Compilers might warn about deleting a pointer to a class that has +/// virtual functions without a virtual destructor or a `final` declaration, +/// because the pointer might secretly be pointing to a more derived class type. +/// We want to suppress this warning when we know for certain (via the design +/// of our implementation) that the pointer is definitely not pointing to a more +/// derived type. +#define IGN_COMMON_WARN_IGNORE__DELETE_NON_VIRTUAL_DESTRUCTOR \ + DETAIL_IGN_COMMON_WARN_IGNORE__DELETE_NON_VIRTUAL_DESTRUCTOR + +#define IGN_COMMON_WARN_RESUME__DELETE_NON_VIRTUAL_DESTRUCTOR \ + DETAIL_IGN_COMMON_WARN_RESUME__DELETE_NON_VIRTUAL_DESTRUCTOR + + +/// \brief Microsoft Visual Studio does not automatically export the interface +/// information for member variables that belong to interface classes of a DLL. +/// Instead it issues this warning. When the member variable is private, we +/// choose to suppress the warning instead of needlessly adding the class +/// information to the DLL interface. +#define IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING \ + DETAIL_IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + +#define IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING \ + DETAIL_IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + + +// TODO(anyone): Add more warning types as they become relevant. +// Do not add warning +// types to suppress unless they are genuinely necessary. + +#endif diff --git a/include/gz/common/SystemPaths.hh b/include/gz/common/SystemPaths.hh new file mode 100644 index 000000000..573e01a72 --- /dev/null +++ b/include/gz/common/SystemPaths.hh @@ -0,0 +1,227 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_SYSTEMPATHS_HH_ +#define GZ_COMMON_SYSTEMPATHS_HH_ + +#include + +#ifdef _WIN32 + #include + #define GetCurrentDir _getcwd +#else + #include + #define GetCurrentDir getcwd +#endif + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace ignition +{ + namespace common + { + // Forward declare private data class + class SystemPathsPrivate; + + /// \class SystemPaths SystemPaths.hh ignition/common/SystemPaths.hh + /// \brief Functions to handle getting system paths, keeps track of: + /// \li SystemPaths#pluginPaths - plugin library paths + /// for common::WorldPlugin + class IGNITION_COMMON_VISIBLE SystemPaths + { + /// \brief Constructor for SystemPaths + public: SystemPaths(); + + /// \brief Destructor + public: virtual ~SystemPaths(); + + /// \brief Get the log path. If IGN_LOG_PATH environment variable is set, + /// then this path is used. If not, the path is $HOME/.ignition, and in + /// case even HOME is not set, /tmp/ignition is used. If the directory + /// does not exist, it is created in the constructor of SystemPaths. + /// \return the path + public: std::string LogPath() const; + + /// \brief Get the plugin paths + /// \return a list of paths (with forward slashes as directory separators) + public: const std::list &PluginPaths(); + + /// \brief Find a file or path using a URI + /// \param[in] _uri the uniform resource identifier + /// \return Returns full path name to file with platform-specific + /// directory separators, or an empty string if URI couldn't be found. + public: std::string FindFileURI(const std::string &_uri) const; + + /// \brief Find a file or path using a URI + /// \param[in] _uri the uniform resource identifier + /// \return Returns full path name to file with platform-specific + /// directory separators, or an empty string if URI couldn't be found. + public: std::string FindFileURI(const ignition::common::URI &_uri) const; + + /// \brief Set the plugin path environment variable to use + /// \param [in] _env name of the environment variable + public: void SetPluginPathEnv(const std::string &_env); + + /// \brief Find a file in the set search paths (not recursive) + /// \param[in] _filename Name of the file to find. + /// \param[in] _searchLocalPath True to search in the current working + /// directory. + /// \return Returns full path name to file with platform-specific + /// directory separators, or empty string on error. + public: std::string FindFile(const std::string &_filename, + const bool _searchLocalPath = true) const; + + /// \brief Find a shared library by name in the plugin paths + /// + /// This will try different combinations of library names on different + /// platforms. For example searching for "MyLibName" may try finding + /// "MyLibName", "libMyLibName.so", "MyLibName.dll", etc... + /// \param[in] _libName Name of shared libary to look for + /// \return Path to file with platform-specific directory separators, + /// or empty string on error. + public: std::string FindSharedLibrary(const std::string &_libName); + + /// \brief Add colon (semicolon on windows) delimited paths to plugins + /// \param[in] _path the directory to add + public: void AddPluginPaths(const std::string &_path); + + /// \brief clear out SystemPaths#pluginPaths + public: void ClearPluginPaths(); + + /// \brief Set the file path environment variable to use, and clears + /// any previously set file paths. The default + /// environment variable is IGN_FILE_PATH. The + /// environment variable should be a set of colon (semicolon on windows) + /// delimited paths. These paths will be used with the FindFile function. + /// \param [in] _env name of the environment variable + /// \sa FilePathEnv + public: void SetFilePathEnv(const std::string &_env); + + /// \brief Get the file path environment variable in use. + /// The environment variable contains a set of colon (semicolon on + /// windows) delimited paths. These paths are used with the FindFile + /// functions. + /// \return Name of the environment variable + /// \sa SetFilePathEnv + public: std::string FilePathEnv() const; + + /// \brief Get the file paths + /// \return a list of paths (with forward slashes as directory separators) + public: const std::list &FilePaths(); + + /// \brief Add colon (semicolon on windows) delimited paths to find + /// files. These paths will be used with the FindFile function. + /// \param[in] _path A colon (semicolon on windows) delimited + /// string of paths. The path can have either forward slashes or platform- + /// specific directory separators, both are okay. + public: void AddFilePaths(const std::string &_path); + + /// \brief clear out SystemPaths#filePaths + public: void ClearFilePaths(); + + /// \brief add _suffix to the list of path search suffixes + /// \param[in] _suffix The suffix to add + public: void AddSearchPathSuffix(const std::string &_suffix); + + /// \brief Set the callback to use when ignition can't find a file. + /// The callback should return a complete path to the requested file, or + /// and empty string if the file was not found in the callback. The path + /// should use platform-specific directory separators. + /// \param[in] _cb The callback function. + /// \deprecated Use AddFindFileCallback instead + public: void IGN_DEPRECATED(3) SetFindFileCallback( + std::function _cb); + + /// \brief Add a callback to use when FindFile() can't find a file. + /// The callback should return a full local path to the requested file, or + /// and empty string if the file was not found in the callback. The path + /// should use platform-specific directory separators. + /// Callbacks will be called in the order they were added until a path is + /// found (if a callback is set using SetFindFileCallback(), that one is + /// called first). + /// \param[in] _cb The callback function, which takes a file path or URI + /// and returns the full local path. + public: void AddFindFileCallback( + std::function _cb); + + /// \brief Add a callback to use when FindFileURI() can't find a file. + /// The callback should return a full local path to the requested file, or + /// and empty string if the file was not found in the callback. The path + /// should use platform-specific directory separators. + /// Callbacks will be called in the order they were added until a path is + /// found (if a callback is set using SetFindFileURICallback(), that one + /// is called first). + /// \param[in] _cb The callback function, which takes a file path or URI + /// and returns the full local path. + public: void AddFindFileURICallback( + std::function _cb); + + /// \brief Set the callback to use when ignition can't find a file uri. + /// The callback should return a complete path to the requested file, or + /// and empty string if the file was not found in the callback. The path + /// should use platform-specific directory separators. + /// \param[in] _cb The callback function. + /// \deprecated Use AddFindFileURICallback instead + public: void IGN_DEPRECATED(3) SetFindFileURICallback( + std::function _cb); + + /// \brief look for a file in a set of search paths (not recursive) + /// \description This method checks if a file exists in given directories. + /// It does so by joining each path with the filename and + /// checking if the file exists. If the file exists in + /// multiple paths the first one is found. + /// \param[in] _filename Name of the file to find + /// \param[in] _paths paths to look for the file + /// \return Returns a path that will work from the current directory + /// or an empty string if the file was not found. The returned + /// path will be normalized, i.e. backslashes will be substituted + /// with forward slashes. + public: static std::string LocateLocalFile(const std::string &_filename, + const std::vector &_paths); + + /// \brief Format the directory path to use "/" as a separator with "/" + /// at the end. + /// \param[in] _path Path to normalize + /// \return Normalized path + public: static std::string NormalizeDirectoryPath( + const std::string &_path); + + /// \brief Return all paths given by an environment variable. + /// \param[in] _env Environment variable. + /// \return A list of paths listed by the environment variable. + public: static std::list PathsFromEnv( + const std::string &_env); + + /// \brief Get the delimiter that the current operating system + /// uses to separate different paths from each other. + public: static char Delimiter(); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief Private data pointer + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} +#endif diff --git a/include/gz/common/TemplateHelpers.hh b/include/gz/common/TemplateHelpers.hh new file mode 100644 index 000000000..f85d44d88 --- /dev/null +++ b/include/gz/common/TemplateHelpers.hh @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2017 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + + +#ifndef GZ_COMMON_TEMPLATEHELPERS_HH_ +#define GZ_COMMON_TEMPLATEHELPERS_HH_ + + +#include "gz/common/detail/TemplateHelpers.hh" + +namespace ignition +{ + namespace common + { + /// \brief Contains a static constexpr field named `value` which will be + /// true if the type `From` has a const-quality less than or equal to the + /// type `To`. + /// + /// The following expressions will return true: + /// + /// \code + /// ConstCompatible::value + /// ConstCompatible::value + /// \endcode + /// + /// The following expression will return false: + /// + /// \code + /// ConstCompatible::value + /// \endcode + /// + template + using ConstCompatible = detail::ConstCompatible; + } +} + +#endif diff --git a/include/gz/common/Time.hh b/include/gz/common/Time.hh new file mode 100644 index 000000000..1bc4cf1dc --- /dev/null +++ b/include/gz/common/Time.hh @@ -0,0 +1,324 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_TIME_HH_ +#define GZ_COMMON_TIME_HH_ + +#include +#include + +#include +#include + +namespace ignition +{ + namespace common + { + /// \class Time Time.hh common/common.hh + /// \brief A Time class, can be used to hold wall- or sim-time. + /// stored as sec and nano-sec. + class IGNITION_COMMON_VISIBLE Time + { + /// \brief A static zero time variable set to common::Time(0, 0). + public: static const Time Zero; + + /// \enum Format options + /// \brief Options for formatting time as a string. + public: enum class FormatOption + { + /// \brief Days + DAYS = 0, + /// \brief Hours + HOURS = 1, + /// \brief Minutes + MINUTES = 2, + /// \brief Seconds + SECONDS = 3, + /// \brief Milliseconds + MILLISECONDS = 4 + }; + + /// \brief Constructors + public: Time(); + + /// \brief Copy constructor + /// \param[in] time Time to copy + public: Time(const Time &_time); + + /// \brief Constructor + /// \param[in] _tv Time to initialize to + public: explicit Time(const struct timespec &_tv); + + /// \brief Constructor + /// \param[in] _sec Seconds + /// \param[in] _nsec Nanoseconds + public: Time(int32_t _sec, int32_t _nsec); + + /// \brief Constuctor + /// \param[in] _time Time in double format sec.nsec + public: explicit Time(double _time); + + /// \brief Destructor + public: virtual ~Time(); + + /// \brief Get the wall time + /// \return the current time + public: static const Time &SystemTime(); + + /// \brief Set to sec and nsec + /// \param[in] _sec Seconds + /// \param[in] _nsec Nanoseconds + public: void Set(int32_t _sec, int32_t _nsec); + + /// \brief Set to seconds + /// \param[in] _seconds Number of seconds + public: void Set(double _seconds); + + /// \brief Get the time as a double + /// \return Time as a double in seconds + public: double Double() const; + + /// \brief Get the time as a float + /// \return Time as a float in seconds + public: float Float() const; + + /// \brief Sleep for the specified time. + /// \param[in] _time Sleep time + /// \return On OSX and Linux the return value is the time slept, + /// as reported by `nanosleep` for OSX and `clock_nanosleep` for Linux. + /// The return value does not include time spent before and after the + /// actual call to the system's sleep function. + /// + /// On Windows the return value is always common::Time::Zero. + public: static Time Sleep(const common::Time &_time); + + /// \brief Get the time as a string formatted as "DD hh:mm:ss.mmm", with + /// the option to choose the start/end. + /// \param[in] _start Start point. + /// \param[in] _end End point. + /// \return String representing time. + public: std::string FormattedString( + FormatOption _start = FormatOption::DAYS, + FormatOption _end = FormatOption::MILLISECONDS) const; + + /// \brief Assignment operator + /// \param[in] _time the new time + /// \return a reference to this instance + public: Time &operator=(const Time &_time); + + /// \brief Addition operators + /// \param[in] _time The time to add + /// \return a Time instance + public: Time operator+(const Time &_time) const; + + /// \brief Addition assignemtn operator + /// \param[in] _time The time to add + /// \return a Time instance + public: const Time &operator +=(const Time &_time); + + /// \brief Subtraction operator + /// \param[in] _tv The time to subtract + /// \return a Time instance + public: Time operator -(const struct timespec &_tv) const; + + /// \brief Subtraction assignment operator + /// \param[in] _tv The time to subtract + /// \return a Time instance + public: const Time &operator -=(const struct timespec &_tv); + + /// \brief Subtraction operator + /// \param[in] _time The time to subtract + /// \return a Time instance + public: Time operator -(const Time &_time) const; + + /// \brief Subtraction assignment operator + /// \param[in] _time The time to subtract + /// \return a reference to this instance + public: const Time &operator -=(const Time &_time); + + /// \brief Multiplication operator + /// \param[in] _tv the scaling duration + /// \return Time instance + public: Time operator *(const struct timespec &_tv) const; + + /// \brief Multiplication assignment operator + /// \param[in] _tv the scaling duration + /// \return a reference to this instance + public: const Time &operator *=(const struct timespec &_tv); + + /// \brief Multiplication operators + /// \param[in] _time the scaling factor + /// \return a scaled Time instance + public: Time operator *(const Time &_time) const; + + /// \brief Multiplication operators + /// \param[in] _time scale factor + /// \return a scaled Time instance + public: const Time &operator *=(const Time &_time); + + /// \brief Division assignment operator + /// \param[in] _tv a divisor + /// \return a Time instance + public: const Time &operator /=(const struct timespec &_tv); + + /// \brief Division operator + /// \param[in] _time the divisor + /// \return a Time instance + public: Time operator /(const Time &_time) const; + + /// \brief Division assignment operator + /// \param[in] time the divisor + /// \return a Time instance + public: const Time &operator /=(const Time &time); + + /// \brief Equal to operator + /// \param[in] _time the time to compare to + /// \return true if values are the same, false otherwise + public: bool operator==(const Time &_time) const; + + /// \brief Equal to operator + /// \param[in] _time the time to compare to + /// \return true if values are the same, false otherwise + public: bool operator==(double _time) const; + + /// \brief Equal to operator + /// \param[in] _time the time to compare to + /// \return true if values are the same, false otherwise + public: bool operator!=(const Time &_time) const; + + /// \brief Equal to operator + /// \param[in] _time the time to compare to + /// \return true if values are the same, false otherwise + public: bool operator!=(double _time) const; + + /// \brief Less than operator + /// \param[in] _time the time to compare with + /// \return true if time is shorter than this, false otherwise + public: bool operator<(const Time &_time) const; + + /// \brief Less than operator + /// \param[in] _time the time to compare with + /// \return true if time is shorter than this, false otherwise + public: bool operator<(double _time) const; + + /// \brief Less than or equal to operator + /// \param[in] _time the time to compare with + /// \return true if time is shorter than or equal to this, false otherwise + public: bool operator<=(const Time &_time) const; + + /// \brief Less than or equal to operator + /// \param[in] _time the time to compare with + /// \return true if time is shorter than or equal to this, false otherwise + public: bool operator<=(double _time) const; + + /// \brief Greater than operator + /// \param[in] _tv the time to compare with + /// \return true if time is greater than this, false otherwise + public: bool operator>(const struct timespec &_tv) const; + + /// \brief Greater than operator + /// \param[in] _time the time to compare with + /// \return true if time is greater than this, false otherwise + public: bool operator>(const Time &_time) const; + + /// \brief Greater than operator + /// \param[in] _time the time to compare with + /// \return true if time is greater than this, false otherwise + public: bool operator>(double _time) const; + + /// \brief Greater than or equal operator + /// \param[in] _time the time to compare with + /// \return true if time is greater than or equal to this, false otherwise + public: bool operator>=(const Time &_time) const; + + /// \brief Greater than or equal operator + /// \param[in] _tv the time to compare with + /// \return true if tv is greater than or equal to this, false otherwise + public: bool operator>=(const struct timespec &_tv) const; + + /// \brief Greater than or equal operator + /// \param[in] _time the time to compare with + /// \return true if time is greater than or equal to this, false otherwise + public: bool operator>=(double _time) const; + + /// \brief Stream insertion operator + /// \param[in] _out the output stream + /// \param[in] _time time to write to the stream + /// \return the output stream + public: friend std::ostream &operator<<(std::ostream &_out, + const ignition::common::Time &_time) + { + _out << _time.sec << " " << _time.nsec; + return _out; + } + + /// \brief Stream extraction operator + /// \param[in] _in the input stream + /// \param[in] _time time to read from to the stream + /// \return the input stream + public: friend std::istream &operator>>(std::istream &_in, + ignition::common::Time &_time) + { + // Skip white spaces + _in.setf(std::ios_base::skipws); + _in >> _time.sec >> _time.nsec; + return _in; + } + + /// \brief Seconds + public: int32_t sec; + + /// \brief Nanoseconds + public: int32_t nsec; + + /// \brief a singleton value of the last GetWallTime() value + private: static Time wallTime; + + /// \brief Correct the time so that small additions/substractions + /// preserve the internal seconds and nanoseconds separation + private: inline void Correct() + { + // In the case sec and nsec have different signs, normalize + if (this->sec > 0 && this->nsec < 0) + { + int32_t n = abs(this->nsec / this->nsInSec) + 1; + this->sec -= n; + this->nsec += n * this->nsInSec; + } + if (this->sec < 0 && this->nsec > 0) + { + int32_t n = abs(this->nsec / this->nsInSec) + 1; + this->sec += n; + this->nsec -= n * this->nsInSec; + } + + // Make any corrections + this->sec += this->nsec / this->nsInSec; + this->nsec = this->nsec % this->nsInSec; + } + + /// \brief Constant multiplier to convert from nanoseconds to seconds. + private: static const int32_t nsInSec; + + /// \brief Constant multiplier to convert from nanoseconds to + /// milliseconds. + private: static const int32_t nsInMs; + + private: static struct timespec clockResolution; + }; + } +} +#endif diff --git a/include/gz/common/Timer.hh b/include/gz/common/Timer.hh new file mode 100644 index 000000000..7dbe5a938 --- /dev/null +++ b/include/gz/common/Timer.hh @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_TIMER_HH_ +#define GZ_COMMON_TIMER_HH_ + +#include +#include + +namespace ignition +{ + namespace common + { + /// \class Timer Timer.hh common/common.hh + /// \brief A timer class, used to time things in real world walltime + class IGNITION_COMMON_VISIBLE Timer + { + /// \brief Constructor + public: Timer(); + + /// \brief Destructor + public: virtual ~Timer(); + + /// \brief Start the timer + public: virtual void Start(); + + /// \brief Stop the timer + public: virtual void Stop(); + + /// \brief Returns true if the timer is running. + /// \return Tue if the timer has been started and not stopped. + public: bool Running() const; + + /// \brief Get the elapsed time + /// \return The time + public: Time Elapsed() const; + + /// \brief Stream operator friendly + public: friend std::ostream &operator<<(std::ostream &out, + const ignition::common::Timer &t) + { + out << t.Elapsed(); + return out; + } + + /// \brief The time of the last call to Start + private: Time start; + + /// \brief The time when Stop was called. + private: Time stop; + + /// \brief True if the timer is running. + private: bool running; + }; + } +} +#endif diff --git a/include/gz/common/URI.hh b/include/gz/common/URI.hh new file mode 100644 index 000000000..e771c5c2b --- /dev/null +++ b/include/gz/common/URI.hh @@ -0,0 +1,353 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_URI_HH_ +#define GZ_COMMON_URI_HH_ + +#include +#include + +#include +#include + +namespace ignition +{ + namespace common + { + // Forward declare private data classes. + class URIPathPrivate; + class URIQueryPrivate; + class URIFragmentPrivate; + class URIPrivate; + + /// \brief The path component of a URI + class IGNITION_COMMON_VISIBLE URIPath + { + /// \brief Constructor + public: URIPath(); + + /// \brief Copy constructor. + /// \param[in] _path Another URIPath. + public: URIPath(const URIPath &_path); + + /// \brief Construct a URIPath object from a string. + /// \param[in] _str A string. + public: explicit URIPath(const std::string &_str); + + /// \brief Destructor + public: virtual ~URIPath(); + + /// \brief Remove all parts of the path + public: void Clear(); + + /// \brief Returns whether the path is absolute or not. + /// \return Whether the path is absolute or not. + public: bool IsAbsolute() const; + + /// \brief Set whether the path is to be treated absolute or not. + /// \param[in] _absolute Whether the path is to be treated absolute or + /// not. + /// \note If this path starts with a Windows drive specifier (e.g. 'C:'), + /// it cannot be set non-absolute. + public: void SetAbsolute(bool _absolute = true); + + /// \brief Set the path to be relative. + /// \note If this path starts with a Windows drive specifier (e.g. 'C:'), + /// it cannot be set relative. + public: void SetRelative(); + + /// \brief Push a new part onto the front of this path. + /// \param[in] _part Path part to push + /// Empty _part is ignored. If _part starts with /, the path is set to + /// absolute (though calling SetAbsolute() is the preferred method). All + /// forward slashes inside the string are URI-encoded to %2F. The path is + /// also set to absolute if a Windows drive specifier (e.g. 'C:') is + /// pushed to the front. + public: void PushFront(const std::string &_part); + + /// \brief Push a new part onto the back of this path. + /// \param[in] _part Path part to push + /// \sa operator/ + /// Empty _part is ignored. If _part starts with / and the path is empty, + /// the path is set to absolute (though calling SetAbsolute() is the + /// preferred method). All forward slashes inside the string are + /// URI-encoded to %2F. The path is also set to absolute if it is empty + /// and a Windows drive specifier (e.g. 'C:') is pushed to it. + public: void PushBack(const std::string &_part); + + /// \brief Compound assignment operator. + /// \param[in] _part A new path to append. + /// \return A new Path that consists of "this / _part" + public: const URIPath &operator/=(const std::string &_part); + + /// \brief Get the current path with the _part added to the end. + /// \param[in] _part Path part. + /// \return A new Path that consists of "this / _part" + /// \sa PushBack + public: const URIPath operator/(const std::string &_part) const; + + /// \brief Return true if the two paths match. + /// \param[in] _part Path part. + /// return True of the paths match. + public: bool operator==(const URIPath &_path) const; + + /// \brief Get the path as a string. + /// \param[in] _delim Delimiter used to separate each part of the path. + /// \return The path as a string, with each path part separated by _delim. + public: std::string Str(const std::string &_delim = "/") const; + + /// \brief Assignment operator. + /// \param[in] _path Another URIPath. + /// \return Itself. + public: URIPath &operator=(const URIPath &_path); + + /// \brief Return true if the string is a valid path. + /// \param[in] _str String to check. + /// \return True if _str is a valid URI path. + public: static bool Valid(const std::string &_str); + + /// \brief Return true if this is a valid path. + /// \return True if this is a valid URI path. + public: bool Valid() const; + + /// \brief Parse a string as URIPath. + /// \param[in] _str A string. + /// \return True if the string could be parsed as a URIPath. + public: bool Parse(const std::string &_str); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \internal + /// \brief Pointer to private data. + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + + /// \brief The query component of a URI + class IGNITION_COMMON_VISIBLE URIQuery + { + /// \brief Constructor + public: URIQuery(); + + /// \brief Construct a URIQuery object from a string. + /// \param[in] _str A string. + public: explicit URIQuery(const std::string &_str); + + /// \brief Copy constructor + /// \param[in] _query Another query component + public: URIQuery(const URIQuery &_query); + + /// \brief Destructor + public: virtual ~URIQuery(); + + /// \brief Remove all values of the query + public: void Clear(); + + /// \brief Get this query with a new _key=_value pair added. + /// \param[in] _key Key of the query. + /// \param[in] _value Value of the query. + public: void Insert(const std::string &_key, + const std::string &_value); + + /// \brief Assignment operator. + /// \param[in] _query another URIQuery. + /// \return Itself. + public: URIQuery &operator=(const URIQuery &_query); + + /// \brief Return true if the two queries contain the same values. + /// \param[in] _query A URI query to compare. + /// return True if the queries match. + public: bool operator==(const URIQuery &_query) const; + + /// \brief Get the query as a string. + /// \param[in] _delim Delimiter used to separate each tuple of the query. + /// \return The query as a string, with each key,value pair separated by + /// _delim. + public: std::string Str(const std::string &_delim = "&") const; + + /// \brief Check if a string is a valid URI query. + /// \param[in] _str The string to check. + /// \return True if the string can be parsed as a URI query. + public: static bool Valid(const std::string &_str); + + /// \brief Check if this is a valid URI query. + /// \return True if this can be parsed as a URI query. + public: bool Valid() const; + + /// \brief Parse a string as URIQuery. + /// \param[in] _str A string. + /// \return True if the string can be parsed as a URIQuery. + public: bool Parse(const std::string &_string); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \internal + /// \brief Pointer to private data. + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + + /// \brief The fragment component of a URI + class IGNITION_COMMON_VISIBLE URIFragment + { + /// \brief Constructor + public: URIFragment(); + + /// \brief Construct a URIFragment object from a string. + /// \param[in] _str A string. + public: explicit URIFragment(const std::string &_str); + + /// \brief Copy constructor + /// \param[in] _fragment Another fragment component + public: URIFragment(const URIFragment &_fragment); + + /// \brief Destructor + public: virtual ~URIFragment(); + + /// \brief Remove all values of the fragment + public: void Clear(); + + /// \brief Assignment operator. + /// \param[in] _fragment another URIFragment. + /// \return Itself. + public: URIFragment &operator=(const URIFragment &_fragment); + + /// \brief Assignment operator. + /// \param[in] _fragment another URIFragment. + /// \return Itself. + public: URIFragment &operator=(const std::string &_fragment); + + /// \brief Return true if the two fragments contain the same values. + /// \param[in] _fragment A URI fragment to compare. + /// return True if the fragments match. + public: bool operator==(const URIFragment &_fragment) const; + + /// \brief Get the fragment as a string. + /// \return The fragment as a string. + public: std::string Str() const; + + /// \brief Check if a string is a valid URI fragment. + /// \param[in] _str The string to check. + /// \return True if the string can be parsed as a URI fragment. + public: static bool Valid(const std::string &_str); + + /// \brief Check if this is a valid URI fragment. + /// \return True if this can be parsed as a URI fragment. + public: bool Valid() const; + + /// \brief Parse a string as URIFragment. + /// \param[in] _str A string. + /// \return True if the string can be parsed as a URIFragment. + public: bool Parse(const std::string &_string); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \internal + /// \brief Pointer to private data. + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + + /// \brief A complete URI + // cppcheck-suppress class_X_Y + class IGNITION_COMMON_VISIBLE URI + { + /// \brief Default constructor + public: URI(); + + /// \brief Construct a URI object from a string. + /// \param[in] _str A string. + public: explicit URI(const std::string &_str); + + /// \brief Copy constructor + /// \param[in] _uri Another URI. + public: URI(const URI &_uri); + + /// \brief Destructor. + public: ~URI(); + + /// \brief Get the URI as a string, which has the form: + /// + /// scheme://path?query + /// + /// \return The full URI as a string + public: std::string Str() const; + + /// \brief Remove all components of the URI + public: void Clear(); + + /// \brief Get the URI's scheme + /// \return The scheme + public: std::string Scheme() const; + + /// \brief Set the URI's scheme + /// \param[in] _scheme New scheme. + public: void SetScheme(const std::string &_scheme); + + /// \brief Get a mutable version of the path component + /// \return A reference to the path + public: URIPath &Path(); + + /// \brief Get a const reference of the path component. + /// \return A const reference of the path. + public: const URIPath &Path() const; + + /// \brief Get a mutable version of the query component + /// \return A reference to the query + public: URIQuery &Query(); + + /// \brief Get a const reference of the query component. + /// \return A const reference of the query. + public: const URIQuery &Query() const; + + /// \brief Get a mutable version of the fragment component. + /// \return A reference to the fragment. + public: URIFragment &Fragment(); + + /// \brief Get a const reference of the fragment component. + /// \return A const reference of the fragment. + public: const URIFragment &Fragment() const; + + /// \brief Assignment operator. + /// \param[in] _uri Another URI. + /// \return Itself. + public: URI &operator=(const URI &_uri); + + /// \brief Return true if the two URIs match. + /// \param[in] _uri Another URI to compare. + /// \return True if the two URIs match. + public: bool operator==(const URI &_uri) const; + + /// \brief Validate this URI. + /// \return True if this can be parsed as a URI. + public: bool Valid() const; + + /// \brief Validate a string as URI. + /// \param[in] _str The string to validate. + /// \return True if the string can be parsed as a URI. + public: static bool Valid(const std::string &_str); + + /// \brief Parse a string as URI. + /// \param[in] _str A string. + /// \return True if the string can be parsed as a URI. + public: bool Parse(const std::string &_str); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \internal + /// \brief Pointer to private data. + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} +#endif diff --git a/include/gz/common/Util.hh b/include/gz/common/Util.hh new file mode 100644 index 000000000..f6055b6b1 --- /dev/null +++ b/include/gz/common/Util.hh @@ -0,0 +1,335 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_UTIL_HH_ +#define GZ_COMMON_UTIL_HH_ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +///////////////////////////////////////////////// +// Defines + +#ifdef _WIN32 +# define IGN_HOMEDIR "USERPROFILE" +#else +# define IGN_HOMEDIR "HOME" +#endif + +/// \brief Seconds in one nano second. +#define IGN_NANO_TO_SEC 1e-9 + +/// \brief Nano seconds in one second. +#define IGN_SEC_TO_NANO 1000000000 + +/// \brief Nano seconds in one millisecond. +#define IGN_MS_TO_NANO 1000000 + +/// \brief Nano seconds in one microsecond. +#define IGN_US_TO_NANO 1000 + +/// \brief Speed of light. +#define IGN_SPEED_OF_LIGHT = 299792458.0 + +/// \brief Sleep for the specifed number of seconds +#define IGN_SLEEP_S(_s) (std::this_thread::sleep_for(\ + std::chrono::seconds(_s))) + +/// \brief Sleep for the specifed number of microseconds +#define IGN_SLEEP_US(_us) (std::this_thread::sleep_for(\ + std::chrono::microseconds(_us))) + +/// \brief Sleep for the specifed number of milliseconds +#define IGN_SLEEP_MS(_ms) (std::this_thread::sleep_for(\ + std::chrono::milliseconds(_ms))) + +/// \brief Sleep for the specifed number of nanoseconds +#define IGN_SLEEP_NS(_ns) (std::this_thread::sleep_for(\ + std::chrono::nanoseconds(_ns))) + +/// \brief Get the system time. +#define IGN_SYSTEM_TIME() (std::chrono::system_clock::now()) + +/// \brief Get the system time in seconds since epoch. +#define IGN_SYSTEM_TIME_S() (std::chrono::duration_cast(\ + std::chrono::system_clock::now().time_since_epoch()).count()) + +/// \brief Get the system time in microseconds since epoch. +#define IGN_SYSTEM_TIME_US() (\ + std::chrono::duration_cast(\ + std::chrono::system_clock::now().time_since_epoch()).count()) + +/// \brief Get the system time in milliseconds since epoch. +#define IGN_SYSTEM_TIME_MS() (\ + std::chrono::duration_cast(\ + std::chrono::system_clock::now().time_since_epoch()).count()) + +/// \brief Get the system time in nanoseconds since epoch. +#define IGN_SYSTEM_TIME_NS() (\ + std::chrono::duration_cast(\ + std::chrono::system_clock::now().time_since_epoch()).count()) + +/// \brief This macro defines the standard way of launching an exception +/// inside ignition. +#define IGN_ASSERT(_expr, _msg) assert((_msg, _expr)) + +/// \brief Forward declarations for the common classes +namespace ignition +{ + namespace common + { + /// \brief Enumeration of the transform types + enum NodeTransformType {TRANSLATE, ROTATE, SCALE, MATRIX}; + + /// \brief A runtime error. + typedef std::runtime_error exception; + + /// \brief Please use systemTimeIso() as this function will be deprecated + /// in Ignition Common 4. + /// Get the wall time as an ISO string: YYYY-MM-DDTHH:MM:SS.NS + /// \return The current wall time as an ISO string. + /// \sa systemTimeIso(); + std::string IGNITION_COMMON_VISIBLE systemTimeISO(); + + /// \brief Get the wall time as an ISO string: YYYY-MM-DDTHH:MM:SS.NS + /// \return The current wall time as an ISO string. + std::string IGNITION_COMMON_VISIBLE systemTimeIso(); + + /// \brief Converts a time point to an ISO string: YYYY-MM-DDTHH:MM:SS.NS + /// \param[in] _time A time point, such as one created by + /// IGN_SYSTEM_TIME(). + /// \return An ISO string that represents the given _time. + std::string IGNITION_COMMON_VISIBLE timeToIso( + const std::chrono::time_point &_time); + + /// \brief Get the log path + /// \return the log path + std::string IGNITION_COMMON_VISIBLE logPath(); + + /// \brief add path suffix to common::SystemPaths + /// \param[in] _suffix The suffix to add. + void IGNITION_COMMON_VISIBLE addSearchPathSuffix( + const std::string &_suffix); + + /// \brief search for file in common::SystemPaths + /// \param[in] _file Name of the file to find. + /// \return The path containing the file. + std::string IGNITION_COMMON_VISIBLE findFile(const std::string &_file); + + /// \brief search for file in common::SystemPaths + /// \param[in] _file Name of the file to find. + /// \param[in] _searchLocalPath True to search in the current working + /// directory. + /// \return The path containing the file. + std::string IGNITION_COMMON_VISIBLE findFile(const std::string &_file, + bool _searchLocalPath); + + /// \brief search for a file in common::SystemPaths + /// \param[in] _file the file name to look for. + /// \return The path containing the file. + std::string IGNITION_COMMON_VISIBLE findFilePath(const std::string &_file); + + /// \brief Add a callback to use when findFile() can't find a file that is + /// a valid URI. + /// The callback should return a full local path to the requested file, or + /// and empty string if the file was not found in the callback. + /// Callbacks will be called in the order they were added until a path is + /// found. + /// \param[in] _cb The callback function, which takes a file path or URI + /// and returns the full local path. + void IGNITION_COMMON_VISIBLE addFindFileURICallback( + std::function _cb); + + /// \brief Get a pointer to the global system paths that is used by all + /// the findFile functions. + /// The returned instance has global shared state for a given process. + /// Care should be taken when manipulating global system paths + /// Caller should not assume ownership of the pointer. + /// \return A mutable reference to the system paths object. + common::SystemPaths IGNITION_COMMON_VISIBLE *systemPaths(); + + /// \brief Compute the SHA1 hash of an array of bytes. + /// \param[in] _buffer Input sequence. The permitted data types for this + /// function are std::string and any STL container. + /// \return The string representation (40 character) of the SHA1 hash. + template + std::string sha1(const T &_buffer); + + /// \brief Compute the SHA1 hash of an array of bytes. Use std::string + /// sha1(const T &_buffer) instead of this function + /// \param[in] _buffer Input sequence. The permitted data types for this + /// function are std::string and any STL container. + /// \return The string representation (40 character) of the SHA1 hash. + /// \sa sha1(const T &_buffer) + std::string IGNITION_COMMON_VISIBLE sha1( + void const *_buffer, std::size_t _byteCount); + + /// \brief fnv1a algorithm for 64-bit platforms. + /// \param[in] _key The input string. + /// \return A 64-bit unsigned hash value. + /// \ref https://notes.underscorediscovery.com/constexpr-fnv1a/ + constexpr uint64_t IGNITION_COMMON_VISIBLE hash64(std::string_view _key) + { + const char *data = _key.data(); + const auto len = _key.size(); + const uint64_t prime = 0x100000001b3; + uint64_t hash = 0xcbf29ce484222325; + + for (auto i = 0u; i < len; ++i) + { + uint8_t value = static_cast(data[i]); + hash = hash ^ value; + hash *= prime; + } + + return hash; + } + + /// \brief Find the environment variable '_name' and return its value. + /// + /// \TODO(mjcarroll): Deprecate and remove in tick-tock. + /// + /// \param[in] _name Name of the environment variable. + /// \param[out] _value Value if the variable was found. + /// \return True if the variable was found or false otherwise. + bool IGNITION_COMMON_VISIBLE env( + const std::string &_name, std::string &_value); + + /// \brief Find the environment variable '_name' and return its value. + /// \param[in] _name Name of the environment variable. + /// \param[out] _value Value if the variable was found. + /// \param[in] _allowEmpty Allow set-but-empty variables. + /// (Unsupported on Windows) + /// \return True if the variable was found or false otherwise. + bool IGNITION_COMMON_VISIBLE env( + const std::string &_name, std::string &_value, + bool _allowEmpty); + + /// \brief Set the environment variable '_name'. + /// + /// Note that on Windows setting an empty string (_value=="") + /// is the equivalent of unsetting the variable. + /// + /// \param[in] _name Name of the environment variable. + /// \param[in] _value Value of the variable to be set. + /// \return True if the variable was set or false otherwise. + bool IGNITION_COMMON_VISIBLE setenv( + const std::string &_name, const std::string &_value); + + /// \brief Unset the environment variable '_name'. + /// \param[in] _name Name of the environment variable. + /// \return True if the variable was unset or false otherwise. + bool IGNITION_COMMON_VISIBLE unsetenv(const std::string &_name); + + /// \brief Get a UUID + /// \return A UUID string + std::string IGNITION_COMMON_VISIBLE uuid(); + + /// \brief Splits a string into tokens. + /// \param[in] _str Input string. + /// \param[in] _delim Token delimiter. + /// \return Vector of tokens. + std::vector IGNITION_COMMON_VISIBLE split( + const std::string &_str, const std::string &_delim); + + /// \brief In place left trim + /// \param[in,out] _s String to trim + void IGNITION_COMMON_VISIBLE ltrim(std::string &_s); + + /// \brief In place right trim + /// \param[in,out] _s String to trim + void IGNITION_COMMON_VISIBLE rtrim(std::string &_s); + + /// \brief In place trim from both ends + /// \param[in,out] _s String to trim + void IGNITION_COMMON_VISIBLE trim(std::string &_s); + + /// \brief Copying left trim + /// \param[in] _s String to trim + /// \return Trimmed string + std::string IGNITION_COMMON_VISIBLE ltrimmed(std::string _s); + + /// \brief Copying right trim + /// \param[in] _s String to trim + /// \return Trimmed string + std::string IGNITION_COMMON_VISIBLE rtrimmed(std::string _s); + + /// \brief Copying trim from both ends + /// \param[in] _s String to trim + /// \return Trimmed string + std::string IGNITION_COMMON_VISIBLE trimmed(std::string _s); + + /// \brief Transforms a string to its lowercase equivalent + /// \param[in] _in String to convert to lowercase + /// \return Lowercase equilvalent of _in. + std::string IGNITION_COMMON_VISIBLE lowercase(const std::string &_in); + + /// \brief Transforms a string to its lowercase equivalent + /// \param[in] _in String to convert to lowercase + /// \return Lowercase equilvalent of _in. + std::string IGNITION_COMMON_VISIBLE lowercase(const char *_in); + + /// \brief Replace all occurances of _key with _replacement. + /// \param[out] _result The new string that has had _key replaced + /// with _replacement. + /// \param[in] _orig Original string. + /// \param[in] _key String to replace. + /// \param[in] _replacement The string that replaces _key. + /// \sa std::string replaceAll(const std::string &_orig, + /// const std::string &_key, const std::string &_replacement) + void IGNITION_COMMON_VISIBLE replaceAll(std::string &_result, + const std::string &_orig, + const std::string &_key, + const std::string &_replacement); + + /// \brief Replace all occurances of _key with _replacement. + /// \param[in] _orig Original string. + /// \param[in] _key String to replace. + /// \param[in] _replacement The string that replaces _key. + /// \return The new string that has had _key replaced with _replacement. + /// \sa void common::replaceAll(std::string &_result, + /// const std::string &_orig, const std::string &_key, + /// const std::string &_replacement) + std::string IGNITION_COMMON_VISIBLE replaceAll(const std::string &_orig, + const std::string &_key, + const std::string &_replacement); + } +} + +/////////////////////////////////////////////// +// Implementation of get_sha1 +template +std::string ignition::common::sha1(const T &_buffer) +{ + if (_buffer.size() == 0) + return ignition::common::sha1(NULL, 0); + else + { + return ignition::common::sha1( + &(_buffer[0]), _buffer.size() * sizeof(_buffer[0])); + } +} +#endif diff --git a/include/gz/common/Uuid.hh b/include/gz/common/Uuid.hh new file mode 100644 index 000000000..48a648c43 --- /dev/null +++ b/include/gz/common/Uuid.hh @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2016 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +#ifndef GZ_COMMON_UUID_HH_INCLUDED_ +#define GZ_COMMON_UUID_HH_INCLUDED_ + +#include +#include + +#include + +#ifdef _WIN32 + #include + #pragma comment(lib, "Rpcrt4.lib") + using portable_uuid_t = UUID; +// else unix +#else + #include + using portable_uuid_t = uuid_t; +#endif + +namespace ignition +{ + namespace common + { + /// \brief A portable class for representing a Universally Unique Identifier + class IGNITION_COMMON_VISIBLE Uuid + { + /// \brief Constructor. + public: Uuid(); + + /// \brief Destructor. + public: virtual ~Uuid(); + + /// \brief Return the string representation of the Uuid. + /// \return the UUID in string format. + public: std::string String() const; + + /// \brief Stream insertion operator. + /// \param[out] _out The output stream. + /// \param[in] _msg AdvMsg to write to the stream. + public: friend std::ostream &operator<<(std::ostream &_out, + const ignition::common::Uuid &_uuid) + { + _out << _uuid.String(); + return _out; + } + + /// \brief Length of a UUID in string format. + /// A UUID is a 16-octet number. In its string representation, every octet + /// is divided in two parts, and each part (4 bits) is represented as an + /// hexadecimal value. A UUID is also displayed in five groups separated + /// by hyphens, in the form 8-4-4-4-12 for a total of 36 characters. + /// To summarize: 36 octets + \0 = 37 octets. + private: static const int UuidStrLen = 37; + + /// \brief Internal representation. + private: portable_uuid_t data; + }; + } +} +#endif diff --git a/include/gz/common/WorkerPool.hh b/include/gz/common/WorkerPool.hh new file mode 100644 index 000000000..00d9949f0 --- /dev/null +++ b/include/gz/common/WorkerPool.hh @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2017 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +#ifndef GZ_COMMON_WORKER_POOL_HH_ +#define GZ_COMMON_WORKER_POOL_HH_ + +#include +#include + +#include +#include +#include + +namespace ignition +{ + namespace common + { + /// \brief forward declaration + class WorkerPoolPrivate; + + /// \brief A pool of worker threads that do stuff in parallel + class IGNITION_COMMON_VISIBLE WorkerPool + { + /// \brief Creates worker threads. The number of worker threads is + /// determined by max(std::thread::hardware_concurrency, _minThreadCount). + /// \param[in] _minThreadCount The minimum number of threads to + /// create in the pool. A value of zero is converted to a value of 1. + /// \note It's not recommended to set _minThreadCount greater than + /// std::thread::hardware_concurrency. + public: explicit WorkerPool(const unsigned int _minThreadCount = 1u); + + /// \brief closes worker threads + public: ~WorkerPool(); + + /// \brief Adds work to the worker pool with optional callback + /// \param[in] _work function to do one piece of work + /// \param[in] _cb optional callback when the work is done + /// \remark Typical work is a function bound with arguments. It must + // return within a finite amount of time. + public: void AddWork(std::function _work, + std::function _cb = std::function()); + + /// \brief Waits until all work is done and threads are idle + /// \param[in] _timeout How long to wait, default to forever + /// \returns true if all work was finished + /// \remarks The return value can be false even when waiting forever if + // the WorkerPool is destructed before all work is completed + public: bool WaitForResults(const Time &_timeout = Time::Zero); + + IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING + /// \brief private implementation pointer + private: std::unique_ptr dataPtr; + IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING + }; + } +} + +#endif diff --git a/include/ignition/common/config.hh.in b/include/gz/common/config.hh.in similarity index 89% rename from include/ignition/common/config.hh.in rename to include/gz/common/config.hh.in index 8c408fde1..14ee66732 100644 --- a/include/ignition/common/config.hh.in +++ b/include/gz/common/config.hh.in @@ -11,3 +11,12 @@ #define IGNITION_COMMON_VERSION_HEADER "Ignition common, version ${PROJECT_VERSION_FULL}\nCopyright (C) 2017 Open Source Robotics Foundation.\nReleased under the Apache 2.0 License.\n\n" #cmakedefine HAVE_AVDEVICE + +namespace ignition +{ +} + +namespace gz +{ + using namespace ignition; +} diff --git a/include/ignition/common/detail/Plugin.hh b/include/gz/common/detail/Plugin.hh similarity index 96% rename from include/ignition/common/detail/Plugin.hh rename to include/gz/common/detail/Plugin.hh index a7d2d2c22..3a8a048c1 100644 --- a/include/ignition/common/detail/Plugin.hh +++ b/include/gz/common/detail/Plugin.hh @@ -16,12 +16,12 @@ */ -#ifndef IGNITION_COMMON_DETAIL_PLUGIN_HH_ -#define IGNITION_COMMON_DETAIL_PLUGIN_HH_ +#ifndef GZ_COMMON_DETAIL_PLUGIN_HH_ +#define GZ_COMMON_DETAIL_PLUGIN_HH_ #include #include -#include "ignition/common/Plugin.hh" +#include "gz/common/Plugin.hh" namespace ignition { diff --git a/include/ignition/common/detail/PluginLoader.hh b/include/gz/common/detail/PluginLoader.hh similarity index 86% rename from include/ignition/common/detail/PluginLoader.hh rename to include/gz/common/detail/PluginLoader.hh index 84504470a..2ef11c625 100644 --- a/include/ignition/common/detail/PluginLoader.hh +++ b/include/gz/common/detail/PluginLoader.hh @@ -16,11 +16,11 @@ */ -#ifndef IGNITION_COMMON_DETAIL_PLUGINLOADER_HH_ -#define IGNITION_COMMON_DETAIL_PLUGINLOADER_HH_ +#ifndef GZ_COMMON_DETAIL_PLUGINLOADER_HH_ +#define GZ_COMMON_DETAIL_PLUGINLOADER_HH_ #include -#include "ignition/common/PluginLoader.hh" +#include "gz/common/PluginLoader.hh" namespace ignition { diff --git a/include/ignition/common/detail/PluginMacros.hh b/include/gz/common/detail/PluginMacros.hh similarity index 97% rename from include/ignition/common/detail/PluginMacros.hh rename to include/gz/common/detail/PluginMacros.hh index 5e1312cce..cca79731a 100644 --- a/include/ignition/common/detail/PluginMacros.hh +++ b/include/gz/common/detail/PluginMacros.hh @@ -16,16 +16,16 @@ */ -#ifndef IGNITION_COMMON_DETAIL_PLUGINMACROS_HH_ -#define IGNITION_COMMON_DETAIL_PLUGINMACROS_HH_ +#ifndef GZ_COMMON_DETAIL_PLUGINMACROS_HH_ +#define GZ_COMMON_DETAIL_PLUGINMACROS_HH_ #include #include #include #include #include -#include "ignition/common/PluginInfo.hh" -#include "ignition/common/SuppressWarning.hh" +#include "gz/common/PluginInfo.hh" +#include "gz/common/SuppressWarning.hh" #if defined _WIN32 || defined __CYGWIN__ diff --git a/include/ignition/common/detail/PluginPtr.hh b/include/gz/common/detail/PluginPtr.hh similarity index 97% rename from include/ignition/common/detail/PluginPtr.hh rename to include/gz/common/detail/PluginPtr.hh index 133bb2764..93952868e 100644 --- a/include/ignition/common/detail/PluginPtr.hh +++ b/include/gz/common/detail/PluginPtr.hh @@ -16,13 +16,13 @@ */ -#ifndef IGNITION_COMMON_DETAIL_PLUGINPTR_HH_ -#define IGNITION_COMMON_DETAIL_PLUGINPTR_HH_ +#ifndef GZ_COMMON_DETAIL_PLUGINPTR_HH_ +#define GZ_COMMON_DETAIL_PLUGINPTR_HH_ #include #include -#include "ignition/common/PluginPtr.hh" -#include "ignition/common/TemplateHelpers.hh" +#include "gz/common/PluginPtr.hh" +#include "gz/common/TemplateHelpers.hh" namespace ignition { diff --git a/include/ignition/common/detail/SpecializedPlugin.hh b/include/gz/common/detail/SpecializedPlugin.hh similarity index 98% rename from include/ignition/common/detail/SpecializedPlugin.hh rename to include/gz/common/detail/SpecializedPlugin.hh index 7c6bf31d2..dff284cca 100644 --- a/include/ignition/common/detail/SpecializedPlugin.hh +++ b/include/gz/common/detail/SpecializedPlugin.hh @@ -16,10 +16,10 @@ */ -#ifndef IGNITION_COMMON_DETAIL_SPECIALIZEDPLUGIN_HH_ -#define IGNITION_COMMON_DETAIL_SPECIALIZEDPLUGIN_HH_ +#ifndef GZ_COMMON_DETAIL_SPECIALIZEDPLUGIN_HH_ +#define GZ_COMMON_DETAIL_SPECIALIZEDPLUGIN_HH_ -#include "ignition/common/SpecializedPlugin.hh" +#include "gz/common/SpecializedPlugin.hh" #include // This preprocessor token should only be used by the unittest that is diff --git a/include/ignition/common/detail/SuppressWarning.hh b/include/gz/common/detail/SuppressWarning.hh similarity index 97% rename from include/ignition/common/detail/SuppressWarning.hh rename to include/gz/common/detail/SuppressWarning.hh index 535e7fa34..5aca44628 100644 --- a/include/ignition/common/detail/SuppressWarning.hh +++ b/include/gz/common/detail/SuppressWarning.hh @@ -16,8 +16,8 @@ */ -#ifndef IGNITION_COMMON_DETAIL_SUPPRESSWARNING_HH_ -#define IGNITION_COMMON_DETAIL_SUPPRESSWARNING_HH_ +#ifndef GZ_COMMON_DETAIL_SUPPRESSWARNING_HH_ +#define GZ_COMMON_DETAIL_SUPPRESSWARNING_HH_ #define DETAIL_IGN_COMMON_STRINGIFY(x) #x diff --git a/include/ignition/common/detail/TemplateHelpers.hh b/include/gz/common/detail/TemplateHelpers.hh similarity index 91% rename from include/ignition/common/detail/TemplateHelpers.hh rename to include/gz/common/detail/TemplateHelpers.hh index 7cecae948..332755ed8 100644 --- a/include/ignition/common/detail/TemplateHelpers.hh +++ b/include/gz/common/detail/TemplateHelpers.hh @@ -16,8 +16,8 @@ */ -#ifndef IGNITION_COMMON_DETAIL_TEMPLATEHELPERS_HH_ -#define IGNITION_COMMON_DETAIL_TEMPLATEHELPERS_HH_ +#ifndef GZ_COMMON_DETAIL_TEMPLATEHELPERS_HH_ +#define GZ_COMMON_DETAIL_TEMPLATEHELPERS_HH_ #include diff --git a/include/ignition/common.hh b/include/ignition/common.hh new file mode 100644 index 000000000..c97c90296 --- /dev/null +++ b/include/ignition/common.hh @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2022 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include diff --git a/include/ignition/common/Base64.hh b/include/ignition/common/Base64.hh index e362a497c..f5a2126a8 100644 --- a/include/ignition/common/Base64.hh +++ b/include/ignition/common/Base64.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,32 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_BASE64_HH_ -#define IGNITION_COMMON_BASE64_HH_ + */ -#include -#include - -namespace ignition -{ - namespace common - { - class IGNITION_COMMON_VISIBLE Base64 - { - /// \brief Encode a binary string into base 64, padded with '='. - /// \param[in] _bytesToEncode String of bytes to encode. - /// \param[in] _len Length of _bytesToEncode. - /// \param[out] _result Based64 string is appended to this string. - public: static void Encode(const char *_bytesToEncode, unsigned int _len, - std::string &_result); - - - /// \brief Decode a base64 string. - /// \param[in] _encodedString A base 64 encoded string. - /// \return The decoded string. - public: static std::string Decode(const std::string &_encodedString); - }; - } -} -#endif +#include +#include diff --git a/include/ignition/common/Battery.hh b/include/ignition/common/Battery.hh index 504d8361f..256c664dd 100644 --- a/include/ignition/common/Battery.hh +++ b/include/ignition/common/Battery.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,166 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_BATTERY_HH_ -#define IGNITION_COMMON_BATTERY_HH_ + */ -#include -#include -#include -#include -#include -#include - -namespace ignition -{ - namespace common - { - // Forward declare private data class. - class BatteryPrivate; - - /// \brief A battery abstraction - /// - /// The default battery model is ideal: It just takes the initial voltage - /// value as its constant voltage value. This behavior can be changed by - /// specifying a custom update function. - /// - /// The battery handles a list of consumers. It updates itself after each - /// simulation iteration. The update function takes the power loads for each - /// consumer and current voltage value as inputs and returns a new voltage - /// value. - class IGNITION_COMMON_VISIBLE Battery - { - /// \brief Typedef the powerload map. - /// \sa SetUpdateFunc - public: typedef std::map PowerLoad_M; - - /// \brief Constructor - public: explicit Battery(); - - /// \brief Constructor that sets the name and initial voltage. - /// \param[in] _name Name of the battery - /// \param[in] _voltage Initial voltage of the battery - public: Battery(const std::string &_name, const double _voltage); - - /// \brief Copy constructor - /// \param[in] _battery Battery to copy. - public: Battery(const Battery &_battery); - - /// \brief Assignment operator - /// \param[in] _battery The new battery - /// \return a reference to this instance - public: Battery &operator=(const Battery &_battery); - - /// \brief Destructor. - public: virtual ~Battery(); - - /// \brief Equal to operator - /// \param[in] _battery the battery to compare to - /// \return true if names and initial voltages are the same, false - /// otherwise - public: bool operator==(const Battery &_battery) const; - - /// \brief Inequality operator - /// \param[in] _battery the battery to compare to - /// \return true if names or initial voltages are not the same, false - /// otherwise - public: bool operator!=(const Battery &_battery) const; - - /// \brief Initialize. - public: virtual void Init(); - - /// \brief Reset the battery voltage to the initial value. - /// The initial value might have been loaded from an sdf element. - /// \sa Load - public: virtual void ResetVoltage(); - - /// \brief Return the initial voltage. - /// \return The initial voltage. - public: double InitVoltage() const; - - /// \brief Set the initial voltage - /// \param[in] _voltage Initial voltage. - public: virtual void SetInitVoltage(const double _voltage); - - /// \brief Return the name of the battery. - /// \return The name of the battery. - public: std::string Name() const; - - /// \brief Set the name of the battery. - /// \param[in] _name Name of the battery. - public: void SetName(const std::string &_name) const; - - /// \brief Create a unique consumer. - /// \return Unique consumer identifier. - public: uint32_t AddConsumer(); - - /// \brief Remove a consumer. - /// \param[in] _consumerId Unique consumer identifier. - /// \return True if the consumer was removed. False if the consumer id - /// was not found. - public: bool RemoveConsumer(const uint32_t _consumerId); - - /// \brief Set consumer power load in watts. - /// \param[in] _consumerId Unique consumer identifier. - /// \param[in] _powerLoad Power load in watts. - /// \return True if setting the power load consumption was successful. - public: bool SetPowerLoad(const uint32_t _consumerId, - const double _powerLoad); - - /// \brief Get consumer power load in watts. - /// \param[in] _consumerId Unique consumer identifier. - /// \param[out] _powerLoad Power load consumption in watts. - /// \return True if getting the power load consumption was successful. - public: bool PowerLoad(const uint32_t _consumerId, - double &_powerLoad) const; - - /// \brief Get list of power loads in watts. - /// \return List of power loads in watts. - public: const PowerLoad_M &PowerLoads() const; - - /// \brief Get the real voltage in volts. - /// \return Voltage. - public: double Voltage() const; - - /// \brief Setup function to update voltage. - /// \param[in] _updateFunc The update function callback that is used - /// to modify the battery's voltage. The parameter to the update - /// function callback is a reference to an instance of - /// Battery::UpdateData. The update function must return the new - /// battery voltage as a double. - /// \sa UpdateData - public: void SetUpdateFunc( - std::function _updateFunc); - - /// \brief Reset function to update voltage, upon destruction of current - /// callback function. - /// \sa UpdateDefault - public: void ResetUpdateFunc(); - - /// \brief Update the battery. This will in turn trigger the function - /// set using the SetUpdateFunc function. - /// \sa SetUpdateFunc. - public: void Update(); - - /// \brief Initialize the list of consumers. - protected: void InitConsumers(); - - /// \brief Update voltage using an ideal battery model. - /// \param[in] _battery Pointer to the battery. - /// \return New battery voltage. - private: double UpdateDefault(Battery *_battery); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \internal - /// \brief Private data pointer. - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - - /// \def BatteryPtr - /// \brief Shared pointer to a battery - typedef std::shared_ptr BatteryPtr; - } -} -#endif +#include +#include diff --git a/include/ignition/common/Console.hh b/include/ignition/common/Console.hh index dfd36ce67..19d1e2e1c 100644 --- a/include/ignition/common/Console.hh +++ b/include/ignition/common/Console.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,286 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_CONSOLE_HH_ -#define IGNITION_COMMON_CONSOLE_HH_ + */ -#include -#include -#include -#include - -#include -#include -#include - -namespace ignition -{ - namespace common - { - /// \brief Output an error message, if the verbose level is >= 1 - #define ignerr (ignition::common::Console::err(__FILE__, __LINE__)) - - /// \brief Output a warning message, if the verbose level is >= 2 - #define ignwarn (ignition::common::Console::warn(__FILE__, __LINE__)) - - /// \brief Output a message, if the verbose level is >= 3 - #define ignmsg (ignition::common::Console::msg()) - - /// \brief Output a debug message, if the verbose level is >= 4 - #define igndbg (ignition::common::Console::dbg(__FILE__, __LINE__)) - - /// \brief Output a message to a log file, regardless of verbosity level - #define ignlog (ignition::common::Console::log()) - - /// \brief Initialize log file with filename given by _dir/_file. - /// If called twice, it will close the file currently in use and open a new - /// log file. - /// \param[in] _dir Name of directory in which to store the log file. Note - /// that if _dir is not an absolute path, then _dir will - /// be relative to your home directory. - /// \param[in] _file Name of log file for ignlog messages. - #define ignLogInit(_dir, _file)\ - ignition::common::Console::log.Init(_dir, _file) - - /// \brief Close the file used for logging. - #define ignLogClose()\ - ignition::common::Console::log.Close() - - /// \brief Get the full path of the directory where the log files are stored - /// \return Full path of the directory - #define ignLogDirectory()\ - (ignition::common::Console::log.LogDirectory()) - - /// \class FileLogger FileLogger.hh common/common.hh - /// \brief A logger that outputs messages to a file. - class IGNITION_COMMON_VISIBLE FileLogger : public std::ostream - { - /// \brief Constructor. - /// \param[in] _filename Filename to write into. If empty, - /// FileLogger::Init must be called separately. - public: explicit FileLogger(const std::string &_filename = ""); - - /// \brief Destructor. - public: virtual ~FileLogger(); - - /// \brief Initialize the file logger. - /// \param[in] _directory Name of directory that holds the log file. - /// \param[in] _filename Name of the log file to write output into. - public: void Init(const std::string &_directory, - const std::string &_filename); - - /// \brief Close the open file handles. - public: void Close(); - - /// \brief Output a filename and line number, then return a reference - /// to the logger. - /// \return Reference to this logger. - public: virtual FileLogger &operator()(); - - /// \brief Output a filename and line number, then return a reference - /// to the logger. - /// \param[in] _file Filename to output. - /// \param[in] _line Line number in the _file. - /// \return Reference to this logger. - public: virtual FileLogger &operator()( - const std::string &_file, int _line); - - /// \brief Get the full path of the directory where all the log files - /// are stored. - /// \return Full path of the directory. - public: std::string LogDirectory() const; - - /// \brief String buffer for the file logger. - protected: class Buffer : public std::stringbuf - { - /// \brief Constructor. - /// \param[in] _filename Filename to write into. - public: explicit Buffer(const std::string &_filename); - - /// \brief Destructor. - public: virtual ~Buffer(); - - /// \brief Writes _count characters to the string buffer - /// \param[in] _char Input rharacter array. - /// \param[in] _count Number of characters in array. - /// \return The number of characters successfully written. - public: std::streamsize xsputn( - const char *_char, std::streamsize _count) override; - - /// \brief Sync the stream (output the string buffer - /// contents). - /// \return Return 0 on success. - public: int sync() override; - - /// \brief Stream to output information into. - public: std::ofstream *stream; - /// \brief Mutex to synchronize writes to the string buffer - /// and the output stream. - /// \todo(nkoenig) Put this back in for ign-common5, and - /// remove the corresponding static version. - // public: std::mutex syncMutex; - }; - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief Stores the full path of the directory where all the log files - /// are stored. - private: std::string logDirectory; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - - /// \brief True if initialized. - private: bool initialized; - }; - - /// \class Logger Logger.hh common/common.hh - /// \brief Terminal logger. - class IGNITION_COMMON_VISIBLE Logger : public std::ostream - { - /// \enum LogType. - /// \brief Output destination type. - public: enum LogType - { - /// \brief Output to stdout. - STDOUT, - /// \brief Output to stderr. - STDERR - }; - - /// \brief Constructor. - /// \param[in] _prefix String to use as prefix when logging to file. - /// \param[in] _color Color of the output stream. - /// \param[in] _type Output destination type (STDOUT, or STDERR) - /// \param[in] _verbosity Verbosity level. - public: Logger(const std::string &_prefix, const int _color, - const LogType _type, const int _verbosity); - - /// \brief Destructor. - public: virtual ~Logger(); - - /// \brief Access operator. - /// \return Reference to this logger. - public: virtual Logger &operator()(); - - /// \brief Output a filename and line number, then return a reference - /// to the logger. - /// \param[in] _file Filename to output. - /// \param[in] _line Line number in the _file. - /// \return Reference to this logger. - public: virtual Logger &operator()( - const std::string &_file, int _line); - - /// \brief String buffer for the base logger. - protected: class Buffer : public std::stringbuf - { - /// \brief Constructor. - /// \param[in] _type Output destination type - /// (STDOUT, or STDERR) - /// \param[in] _color Color of the output stream. - /// \param[in] _verbosity Verbosity level. - public: Buffer(LogType _type, const int _color, - const int _verbosity); - - /// \brief Destructor. - public: virtual ~Buffer(); - - /// \brief Writes _count characters to the string buffer - /// \param[in] _char Input rharacter array. - /// \param[in] _count Number of characters in array. - /// \return The number of characters successfully written. - public: std::streamsize xsputn( - const char *_char, std::streamsize _count) override; - - /// \brief Sync the stream (output the string buffer - /// contents). - /// \return Return 0 on success. - public: int sync() override; - - /// \brief Destination type for the messages. - public: LogType type; - - /// \brief ANSI color code using Select Graphic Rendition - /// parameters (SGR). See - /// http://en.wikipedia.org/wiki/ANSI_escape_code#Colors - public: int color; - - /// \brief Level of verbosity - public: int verbosity; - - /// \brief Mutex to synchronize writes to the string buffer - /// and the output stream. - /// \todo(nkoenig) Put this back in for ign-common5, and - /// remove the corresponding static version. - // public: std::mutex syncMutex; - }; - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief Prefix to use when logging to file. - private: std::string prefix; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - - /// \class Console Console.hh common/common.hh - /// \brief Container for loggers, and global logging options - /// (such as verbose vs. quiet output). - class IGNITION_COMMON_VISIBLE Console - { - /// \brief Set verbosity, where - /// <= 0: No output, - /// 1: Error messages, - /// 2: Error and warning messages, - /// 3: Error, warning, and info messages, - /// >= 4: Error, warning, info, and debug messages. - /// \param[in] _level The new verbose level. - public: static void SetVerbosity(const int _level); - - /// \brief Get the verbose level. - /// \return The level of verbosity. - /// \sa SetVerbosity(const int _level) - public: static int Verbosity(); - - /// \brief Add a custom prefix in front of the default prefixes. - /// - /// By default, the custom prefix is an empty string, so the messages - /// start as: - /// - /// [Err], [Wrn], [Msg], [Dbg] - /// - /// If you set the prefix to "-my-", for example, they become: - /// - /// -my-[Err], -my-[Wrn], -my-[Msg], -my-[Dbg] - /// - /// \param[in] _customPrefix Prefix string. - /// \sa std::string Prefix() const - public: static void SetPrefix(const std::string &_customPrefix); - - /// \brief Get custom prefix. This is empty by default. - /// \return The custom prefix. - /// \sa void SetPrefix(const std::string &_customPrefix) - public: static std::string Prefix(); - - /// \brief Global instance of the message logger. - public: static Logger msg; - - /// \brief Global instance of the error logger. - public: static Logger err; - - /// \brief Global instance of the debug logger. - public: static Logger dbg; - - /// \brief Global instance of the warning logger. - public: static Logger warn; - - /// \brief Global instance of the file logger. - public: static FileLogger log; - - /// \brief The level of verbosity, the default level is 1. - private: static int verbosity; - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief A custom prefix. See SetPrefix(). - private: static std::string customPrefix; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} -#endif +#include +#include diff --git a/include/ignition/common/EnumIface.hh b/include/ignition/common/EnumIface.hh index 898eeea70..59b47a812 100644 --- a/include/ignition/common/EnumIface.hh +++ b/include/ignition/common/EnumIface.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,230 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_ENUMITERATOR_HH_ -#define IGNITION_COMMON_ENUMITERATOR_HH_ + */ -#include -#include -#include -#include -#include - -namespace ignition -{ - namespace common - { - /// \brief A macro that allows an enum to have an iterator and string - /// conversion. - /// \param[in] name EnumIface instance name. - /// \param[in] enumType Enum type - /// \param[in] begin Enum value that marks the beginning of the enum - /// values. - /// \param[in] end Enum value that marks the end of the enum values. - /// \param[in] names A vector of strings, one for each enum value. - /// \sa EnumIface - /// \sa EnumIterator - #define IGN_ENUM(name, enumType, begin, end, ...) \ - static ignition::common::EnumIface name( \ - begin, end, {__VA_ARGS__}); - - /// \brief Enum interface. Use this interface to convert an enum to - /// a string, and set an enum from a string. - template - class EnumIface - { - /// \brief Constructor - /// \param[in] _start Starting enum value. - /// \param[in] _end Ending enum value. - /// \param[in] _names Name of each enum value. - public: EnumIface(T _start, T _end, - const std::vector &_names) - : names(_names) - { - this->range[0] = _start; - this->range[1] = _end; - } - - /// \brief Get the beginning enum value. - /// \return Enum value that marks the beginning of the enum list. - public: T Begin() - { - return range[0]; - } - - /// \brief Get the end enum value. - /// \return Enum value that marks the end of the enum list. - public: T End() - { - return range[1]; - } - - /// \brief Convert enum value to string. - /// \param[in] _e Enum value to convert. - /// \return String representation of the enum. An empty string is - /// returned if _e is invalid, or the names for the enum have not been - /// set. - public: std::string Str(T const &_e) - { - if (static_cast(_e) < names.size()) - return names[static_cast(_e)]; - else - return ""; - } - - /// \brief Set an enum from a string. This function requires a valid - /// string, and an array of names for the enum must exist. - /// \param[in] _str String value to convert to enum value. - /// \param[in] _e Enum variable to set. - /// \sa EnumIterator - public: void Set(T &_e, const std::string &_str) - { - auto begin = std::begin(names); - auto end = std::end(names); - - auto find = std::find(begin, end, _str); - if (find != end) - { - _e = static_cast(std::distance(begin, find)); - } - } - - /// \internal - /// \brief The beginning and end values. Do not use this directly. - public: T range[2]; - - /// \internal - /// \brief Array of string names for each element in the enum. Do not - /// use this directly. - public: std::vector names; - }; - - /// \brief An iterator over enum types. - /// - /// Example: - /// - /// \verbatim - /// enum MyType - /// { - /// MY_TYPE_BEGIN = 0, - /// TYPE1 = MY_TYPE_BEGIN, - /// TYPE2 = 1, - /// MY_TYPE_END - /// }; - /// - /// GZ_ENUM(myTypeIface, MyType, MY_TYPE_BEGIN, MY_TYPE_END, - /// "TYPE1", - /// "TYPE2", - /// "MY_TYPE_END") - /// - /// int main() - /// { - /// EnumIterator i = MY_TYPE_BEGIN; - /// std::cout << "Type Number[" << *i << "]\n"; - /// std::cout << "Type Name[" << myTypeIface.Str(*i) << "]\n"; - /// i++; - /// std::cout << "Type++ Number[" << *i << "]\n"; - /// std::cout << "Type++ Name[" << myTypeIface.Str(*i) << "]\n"; - /// } - /// \verbatim - template - class EnumIterator - : std::iterator - { - /// \brief Constructor - public: EnumIterator() - { - } - - /// \brief Constructor - /// \param[in] _c Enum value - // cppcheck-suppress noExplicitConstructor - public: EnumIterator(const Enum &_c) : c(_c) - { - } - - /// \brief Equal operator - /// \param[in] _c Enum value to copy - public: EnumIterator &operator=(const Enum &_c) - { - this->c = _c; - return *this; - } - - /// \brief Prefix increment operator. - /// \return Iterator pointing to the next value in the enum. - public: EnumIterator &operator++() - { - this->c = static_cast(static_cast(this->c) + 1); - return *this; - } - - /// \brief Postfix increment operator. - /// \return Iterator pointing to the next value in the enum. - public: EnumIterator operator++(const int) - { - EnumIterator cpy(*this); - ++*this; - return cpy; - } - - /// \brief Prefix decrement operator - /// \return Iterator pointing to the previous value in the enum - public: EnumIterator &operator--() - { - this->c = static_cast(static_cast(this->c) - 1); - return *this; - } - - /// \brief Postfix decrement operator - /// \return Iterator pointing to the previous value in the enum - public: EnumIterator operator--(const int) - { - EnumIterator cpy(*this); - --*this; - return cpy; - } - - /// \brief Dereference operator - /// \return Value of the iterator - public: Enum operator*() const - { - return c; - } - - /// \brief Get the enum value. - /// \return Value of the iterator - public: Enum Value() const - { - return this->c; - } - - /// \brief Enum value - /// Did not use a private data class since this should be the only - /// member value ever used. - private: Enum c; - }; - - /// \brief Equality operator - /// \param[in] _e1 First iterator - /// \param[in] _e1 Second iterator - /// \return True if the two iterators contain equal enum values. - template - bool operator==(EnumIterator _e1, EnumIterator _e2) - { - return _e1.Value() == _e2.Value(); - } - - /// \brief Inequality operator - /// \param[in] _e1 First iterator - /// \param[in] _e1 Second iterator - /// \return True if the two iterators do not contain equal enum values. - template - bool operator!=(EnumIterator _e1, EnumIterator _e2) - { - return !(_e1 == _e2); - } - } -} -#endif +#include +#include diff --git a/include/ignition/common/Export.hh b/include/ignition/common/Export.hh new file mode 100644 index 000000000..bd4b88b6a --- /dev/null +++ b/include/ignition/common/Export.hh @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2022 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include diff --git a/include/ignition/common/Filesystem.hh b/include/ignition/common/Filesystem.hh index 42e95b327..566ae9851 100644 --- a/include/ignition/common/Filesystem.hh +++ b/include/ignition/common/Filesystem.hh @@ -1,5 +1,5 @@ /* - * Copyright 2017 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,291 +15,5 @@ * */ -#ifndef IGNITION_COMMON_FILESYSTEM_HH_ -#define IGNITION_COMMON_FILESYSTEM_HH_ - -#include -#include - -#include -#include - -namespace ignition -{ - namespace common - { - /// \brief Options for how to handle errors that occur in functions that - /// manipulate the filesystem. - enum FilesystemWarningOp - { - /// \brief Errors that occur during filesystem manipulation should be - /// logged as warnings using ignwarn. (Recommended) - FSWO_LOG_WARNINGS = 0, - - /// \brief Errors that occur during filesystem manipulation should - /// not be logged. The user will be responsible for checking the - /// system's error flags. - FSWO_SUPPRESS_WARNINGS - }; - - /// \brief Determine whether the given path exists on the filesystem. - /// \param[in] _path The path to check for existence - /// \return True if the path exists on the filesystem, false otherwise. - bool IGNITION_COMMON_VISIBLE exists(const std::string &_path); - - /// \brief Determine whether the given path is a directory. - /// \param[in] _path The path to check - /// \return True if given path exists and is a directory, false otherwise. - bool IGNITION_COMMON_VISIBLE isDirectory(const std::string &_path); - - /// \brief Check if the given path is a file. - /// \param[in] _path Path to a file. - /// \return True if _path is a file. - bool IGNITION_COMMON_VISIBLE isFile(const std::string &_path); - - /// \brief Create a new directory on the filesystem. Intermediate - /// directories must already exist. - /// \param[in] _path The new directory path to create - /// \return True if directory creation was successful, false otherwise. - bool IGNITION_COMMON_VISIBLE createDirectory(const std::string &_path); - - /// \brief Create directories for the given path - /// \param[in] _path Path to create directories from - /// \return true on success - bool IGNITION_COMMON_VISIBLE createDirectories(const std::string &_path); - - /// \brief Append the preferred path separator character for this platform - /// onto the passed-in string. - /// \param[in] _s The path to start with. - /// \return The original path with the platform path separator appended. - std::string IGNITION_COMMON_VISIBLE const separator( - std::string const &_s); - - /// \brief Replace forward-slashes '/' with the preferred directory - /// separator of the current operating system. On Windows, this will turn - /// forward-slashes into backslashes. If forward-slash is the preferred - /// separator of the current operating system, this will do nothing. - /// - /// Note that this will NOT convert backslashes (or any other separator) - /// into forward slashes, even on operating systems that use - /// forward-slashes as separators. - /// - /// \param[out] _path This string will be directly modified by - /// replacing its - /// forward-slashes with the preferred directory separator of the current - /// operating system. - void IGNITION_COMMON_VISIBLE changeFromUnixPath(std::string &_path); - - /// \brief Returns a copy of _path which has been passed through - /// changeFromUnixPath. - /// - /// \param[in] _path The path to start with - /// \return A modified path that uses the preferred directory separator of - /// the current operating system. - std::string IGNITION_COMMON_VISIBLE copyFromUnixPath( - const std::string &_path); - - /// \brief Replace the preferred directory separator of the current - /// operating system with a forward-slash '/'. On Windows, this will turn - /// backslashes into forward-slashes. - /// - /// \param[out] _path This string will be directly modified to use forward - /// slashes to separate its directory names. - void IGNITION_COMMON_VISIBLE changeToUnixPath(std::string &_path); - - /// \brief Returns a copy of _path which has been passed through - /// changeToUnixPath. - /// - /// \param[in] _path The path to start with - /// \return A modified path that uses forward slashes to separate - /// directory names. - std::string IGNITION_COMMON_VISIBLE copyToUnixPath( - const std::string &_path); - - /// \brief Get the absolute path of a provided path. Relative paths are - /// resolved relative to the current working directory. - /// \param[in] _path Relative or absolute path. - /// \return Absolute path (with platform-dependent directory separators). - std::string IGNITION_COMMON_VISIBLE absPath(const std::string &_path); - - /// \brief Join two strings together to form a path - /// \param[in] _path1 the left portion of the path - /// \param[in] _path2 the right portion of the path - /// \return Joined path. The function can do simplifications such as - /// elimination of ../ and removal of duplicate // (but is not guaranteed to - /// do so). - std::string IGNITION_COMMON_VISIBLE joinPaths(const std::string &_path1, - const std::string &_path2); - - /// \brief base case for joinPaths(...) below - inline std::string joinPaths(const std::string &_path) - { - return _path; - } - - // The below is C++ variadic template magic to allow a joinPaths - // method that takes 1-n number of arguments to append together. - - /// \brief Append one or more additional path elements to the first - /// passed in argument. - /// \param[in] args The paths to append together - /// \return A new string with the paths appended together. - template - inline std::string joinPaths(const std::string &_path1, - const std::string &_path2, - Args const &..._args) - { - return joinPaths(joinPaths(_path1, _path2), - joinPaths(_args...)); - } - - /// \brief Get the current working directory - /// \return Name of the current directory - std::string IGNITION_COMMON_VISIBLE cwd(); - - /// \brief Change current working directory to _dir. - /// \param[in] _dir The directory to change to. - /// \return Whether the operation succeeded. - bool IGNITION_COMMON_VISIBLE chdir(const std::string &_dir); - - /// \brief Given a path, get just the basename portion. - /// \param[in] _path The full path. - /// \return A new string with just the basename portion of the path. - std::string IGNITION_COMMON_VISIBLE basename( - const std::string &_path); - - /// \brief Given a path, get just its parent path portion, without - /// separator at the end. - /// \param[in] _path Path of which to find parent path - /// \return A new string with just the parent path of the path. - std::string IGNITION_COMMON_VISIBLE parentPath( - const std::string &_path); - - /// \brief Copy a file. - /// \param[in] _existingFilename Path to an existing file. - /// \param[in] _newFilename Path of the new file. - /// \param[in] _warningOp Log or suppress warnings that may occur. - /// \return True on success. - bool IGNITION_COMMON_VISIBLE copyFile( - const std::string &_existingFilename, - const std::string &_newFilename, - const FilesystemWarningOp _warningOp = FSWO_LOG_WARNINGS); - - /// \brief Copy a directory, overwrite the destination directory if exists. - /// \param[in] _source Path to an existing directory to copy from. - /// \param[in] _destination Path to the destination directory. - /// \return True on success. - bool IGNITION_COMMON_VISIBLE copyDirectory( - const std::string &_existingDirname, - const std::string &_newDirname, - const FilesystemWarningOp _warningOp = FSWO_LOG_WARNINGS); - - /// \brief Move a file. - /// \param[in] _existingFilename Full path to an existing file. - /// \param[in] _newFilename Full path of the new file. - /// \param[in] _warningOp Log or suppress warnings that may occur. - /// \return True on success. - bool IGNITION_COMMON_VISIBLE moveFile( - const std::string &_existingFilename, - const std::string &_newFilename, - const FilesystemWarningOp _warningOp = FSWO_LOG_WARNINGS); - - /// \brief Remove an empty directory - /// \remarks the directory must be empty to be removed - /// \param[in] _path Path to a directory. - /// \param[in] _warningOp Log or suppress warnings that may occur. - /// \return True if _path is a directory and was removed. - bool IGNITION_COMMON_VISIBLE removeDirectory( - const std::string &_path, - const FilesystemWarningOp _warningOp = FSWO_LOG_WARNINGS); - - /// \brief Remove a file. - /// \param[in] _existingFilename Full path to an existing file. - /// \param[in] _warningOp Log or suppress warnings that may occur. - /// \return True on success. - bool IGNITION_COMMON_VISIBLE removeFile( - const std::string &_existingFilename, - const FilesystemWarningOp _warningOp = FSWO_LOG_WARNINGS); - - /// \brief Remove an empty directory or file. - /// \param[in] _path Path to a directory or file. - /// \param[in] _warningOp Log or suppress warnings that may occur. - /// \return True if _path was removed. - bool IGNITION_COMMON_VISIBLE removeDirectoryOrFile( - const std::string &_path, - const FilesystemWarningOp _warningOp = FSWO_LOG_WARNINGS); - - /// \brief Remove a file or a directory and all its contents. - /// \param[in] _path Path to a directory or file. - /// \param[in] _warningOp Log or suppress warnings that may occur. - /// \return True if _path was removed. - bool IGNITION_COMMON_VISIBLE removeAll( - const std::string &_path, - const FilesystemWarningOp _warningOp = FSWO_LOG_WARNINGS); - - /// \brief Generates a path for a file which doesn't collide with existing - /// files, by appending numbers to it (i.e. (0), (1), ...) - /// \param[in] _pathAndName Full absolute path and file name up to the - /// file extension. - /// \param[in] _extension File extension, such as "ddf". - /// \return Full path with name and extension, which doesn't collide with - /// existing files - std::string IGNITION_COMMON_VISIBLE uniqueFilePath( - const std::string &_pathAndName, const std::string &_extension); - - /// \brief Unique directory path to not overwrite existing directory - /// \param[in] _pathAndName Full absolute path - /// \return Full path which doesn't collide with existing files - std::string IGNITION_COMMON_VISIBLE uniqueDirectoryPath( - const std::string &_dir); - - /// \internal - class DirIterPrivate; - - /// \class DirIter Filesystem.hh - /// \brief A class for iterating over all items in a directory. - class IGNITION_COMMON_VISIBLE DirIter - { - /// \brief Constructor. - /// \param[in] _in Directory to iterate over. - public: explicit DirIter(const std::string &_in); - - /// \brief Constructor for end element. - public: DirIter(); - - /// \brief Dereference operator; returns current directory record. - /// \return A string representing the entire path of the directory - /// record. - public: std::string operator*() const; - - /// \brief Pre-increment operator; moves to next directory record. - /// \return This iterator. - public: const DirIter &operator++(); - - /// \brief Comparison operator to see if this iterator is at the - /// same point as another iterator. - /// \param[in] _other The other iterator to compare against. - /// \return true if the iterators are equal, false otherwise. - public: bool operator!=(const DirIter &_other) const; - - /// \brief Destructor - public: ~DirIter(); - - /// \brief Move to the next directory record, skipping . and .. records. - private: void Next(); - - /// \brief Set the internal variable to the empty string. - private: void SetInternalEmpty(); - - /// \brief Close an open directory handle. - private: void CloseHandle(); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief Private data. - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} - -#endif +#include +#include diff --git a/include/ignition/common/FlagSet.hh b/include/ignition/common/FlagSet.hh index 30e1d1c18..09c5c7b45 100644 --- a/include/ignition/common/FlagSet.hh +++ b/include/ignition/common/FlagSet.hh @@ -1,400 +1,19 @@ /* - * MIT License + * Copyright (C) 2022 Open Source Robotics Foundation * - * Copyright (c) 2019 Arnaud Kapp (Xaqq), Barry Revzin, Mart Sõmermaa - * Copyright (c) 2020 Martin Pecka + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: + * http://www.apache.org/licenses/LICENSE-2.0 * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. */ -#ifndef IGNITION_COMMON_FLAGSET_HH -#define IGNITION_COMMON_FLAGSET_HH -// FlagSet is a type-safe class for using enums as flags in C++14 with an -// underlying std::bitset. -// See https://github.com/mrts/flag-set-cpp -// Licence: MIT - -#include -#include -#include -#include - -namespace ignition::common -{ - -/// \brief Set of flags defined by a C++11 enum class. -/// \note If the enum's last element is '_' (just underscore), the convenience -/// signature can be used specifying just the enum type (the underscore will be -/// automatically used as LastElement, and will be excluded from the list of -/// valid values). -/// \note FlagSet only works for enums that do not contain negative values. -/// \note The underlying bitset representing this FlagSet will have as many bits -/// as is the size_t value of LastElement (+- 1). Be aware of that when calling -/// Count(), Size() etc. Also be aware of that when creating a FlagSet of an -/// enum that would contain very high numbers in the underlying representation. -/// \tparam T The enum class type. The underlying type of the enum has to be -/// convertible to size_t. -/// \tparam LastElement Last element of the enum. If the enum's last element is -/// '_' (just underscore), it can be deduced automatically. -/// \tparam ExcludeLast If true, LastElement is considered as an element beyond -/// all valid elements and will not be treated as a valid value of the FlagSet. -/// If false, the last element is treated as a valid value. -template -class FlagSet -{ - /// \brief Create an empty FlagSet (no flags set). - public: FlagSet() = default; - - /// \brief Construct a FlagSet with the given flag set and all other unset. - /// \param[in] _val The flag to set. - /// \note This is intentionally not an explicit constructor so that values of - /// the enum can be implicitly converted to a FlagSet with just the one value - /// set. - // cppcheck-suppress noExplicitConstructor - public: FlagSet(const T& _val) - { - flags.set(static_cast(_val)); - } - - /// \brief Construct a FlagSet with the given flags set and all other unset. - /// \param[in] _list The list of flags to set. - public: explicit FlagSet(const std::initializer_list& _list) - { - for (const auto& val : _list) - { - flags.set(static_cast(val)); - } - } - - // Binary operations. - - /// \brief Return a FlagSet with only the given flag set (or even this one - /// unset if it wasn't set in this FlagSet before). - /// \param[in] _val The flag to set. - /// \return This. - public: FlagSet& operator&=(const T& _val) noexcept - { - bool tmp = flags.test(static_cast(_val)); - flags.reset(); - flags.set(static_cast(_val), tmp); - return *this; - } - - /// \brief Return a bit AND of this FlagSet and the argument. - /// \param[in] _o The other FlagSet. - /// \return This. - public: FlagSet& operator&=(const FlagSet& _o) noexcept - { - flags &= _o.flags; - return *this; - } - - /// \brief Set the given flag to true in this FlagSet. - /// \param[in] _val The flag to set. - /// \return This. - public: FlagSet& operator|=(const T& _val) noexcept - { - flags.set(static_cast(_val)); - return *this; - } - - /// \brief Return a bit OR of this FlagSet and the argument. - /// \param[in] _o The other FlagSet. - /// \return This. - public: FlagSet& operator|=(const FlagSet& _o) noexcept - { - flags |= _o.flags; - return *this; - } - - /// \brief Return a FlagSet with only the given flag set (or even this one - /// unset if it wasn't set in this FlagSet before). - /// \param[in] _val The flag to set. - /// \return The new FlagSet. - /// \note The resulting bitset can contain at most 1 bit set to true. - public: FlagSet operator&(const T& _val) const - { - FlagSet ret(*this); - ret &= _val; - - assert(ret.flags.count() <= 1); - return ret; - } - - /// \brief Return a bit AND of this FlagSet and the argument. - /// \param[in] _o The other FlagSet. - /// \return The new FlagSet. - public: FlagSet operator&(const FlagSet& _val) const - { - FlagSet ret(*this); - ret.flags &= _val.flags; - - return ret; - } - - /// \brief Return a FlagSet with the given flag set to true. - /// \param[in] _val The flag to set. - /// \return The new FlagSet. - /// \note The resulting bitset contains at least 1 bit set to true. - public: FlagSet operator|(const T& _val) const - { - FlagSet ret(*this); - ret |= _val; - - assert(ret.flags.count() >= 1); - return ret; - } - - /// \brief Return a bit OR of this FlagSet and the argument. - /// \param[in] _o The other FlagSet. - /// \return The new FlagSet. - public: FlagSet operator|(const FlagSet& _val) const - { - FlagSet ret(*this); - ret.flags |= _val.flags; - - return ret; - } - - /// \brief Return a negation of this FlagSet. - /// \return The negated FlagSet. - public: FlagSet operator~() const - { - FlagSet cp(*this); - cp.flags.flip(); - - return cp; - } - - /// \brief Return true if at least one flag is set to true. - /// \return Whether at least one flag is set. - public: explicit operator bool() const - { - return flags.any(); - } - - // Methods from std::bitset. - - /// \brief Test FlagSet equality. - /// \param[in] _o The other FlagSet. - /// \return Whether the FlagSets represent the same set of flags. - public: bool operator==(const FlagSet& _o) const - { - return flags == _o.flags; - } - - /// \brief Test FlagSet inequality. - /// \param[in] _o The other FlagSet. - /// \return Whether the FlagSets represent different sets of flags. - public: bool operator!=(const FlagSet& _o) const - { - return !(*this == _o); - } - - /// \brief Return the total number of flags represented by this FlagSet. - /// \note This corresponds to the value of the '_' element of the enum. - /// \return The number of flags in this FlagSet. - /// \sa Count() - public: std::size_t Size() const - { - return flags.size(); - } - - /// \brief Return the number of flags set to true. - /// \return The number of true flags in this FlagSet. - /// \sa Size() - public: std::size_t Count() const - { - return flags.count(); - } - - /// \brief Set all flags to true. - /// \return This. - public: FlagSet& Set() - { - flags.set(); - return *this; - } - - /// \brief Set all flags to false. - /// \return This. - public: FlagSet& Reset() - { - flags.reset(); - return *this; - } - - /// \brief Set all flags to their negation. - /// \return This. - public: FlagSet& Flip() - { - flags.flip(); - return *this; - } - - /// \brief Set the given flag to the specified value. - /// \param[in] _val The flag to set. - /// \param[in] _value The value to set. - /// \return This. - public: FlagSet& Set(const T& _val, bool _value = true) - { - flags.set(static_cast(_val), _value); - return *this; - } - - /// \brief Set the given flag to false. - /// \param[in] _val The flag to set. - /// \return This. - public: FlagSet& Reset(const T& _val) - { - flags.reset(static_cast(_val)); - return *this; - } - - /// \brief Negate the given flag. - /// \param[in] _val The flag to negate. - /// \return This. - public: FlagSet& Flip(const T& _val) - { - flags.flip(static_cast(_val)); - return *this; - } - - /// \brief Test whether any flag is set. - /// \return True if at least one flag is set to true. - public: bool Any() const - { - return flags.any(); - } - - /// \brief Test whether all flags are set. - /// \return True if at all flags are set to true. - public: bool All() const - { - return flags.all(); - } - - /// \brief Test whether no flag is set. - /// \return True if at no flag is set to true. - public: bool None() const - { - return flags.none(); - } - - /// \brief Retrurn a FlagSet with all flags set to true. - public: static FlagSet AllSet() - { - return FlagSet().Set(); - } - - /// \brief Retrurn a FlagSet with all flags set to false. - public: static FlagSet NoneSet() - { - return FlagSet(); - } - - /// \brief Return whether the given flag is set. - /// \param[in] _val The flag to test. - /// \return Whether the flag is set. - /// \note This only works for enums whose underlying type is unsigned. - public: constexpr bool operator[](const T& _val) const - { - return flags[static_cast(static_cast(_val))]; - } - - /// \brief Return a string describing this FlagSet. - /// \return The string. - public: std::string String() const - { - return flags.to_string(); - } - - /// \brief Operator for outputting to std::ostream. - /// \param[in,out] _stream The stream to write to. - /// \param[in] _self The FlagSet to write. - /// \return _stream with the contents of the given FlagSet written. - public: friend std::ostream& operator<<(std::ostream& _stream, - const FlagSet& _self) - { - return _stream << _self.flags; - } - - /// \brief Compute hash of the FlagSet. - /// \return The hash. - public: size_t Hash() const - { - return std::hashflags)>{}(this->flags); - } - - /// \brief The underlying type of the enum. - private: using UnderlyingType = std::underlying_type_t; - - /// \brief Number of elements of the bitset. - public: static constexpr size_t numElements = static_cast( - static_cast(LastElement) + - static_cast(1 - ExcludeLast)); - - /// \brief The bitset holding values for the flags. - private: std::bitset flags; -}; - -template -struct IsEnumThatContainsSentinel : std::false_type -{ -}; - -template -struct IsEnumThatContainsSentinel(T::_))> - : std::is_enum -{ -}; - -} - -// Operator that combines two enumeration values into a FlagSet only if the -// enumeration contains the sentinel `_`. -template -std::enable_if_t< - ignition::common::IsEnumThatContainsSentinel::value, - ignition::common::FlagSet -> -operator|(const T& _lhs, const T& _rhs) -{ - ignition::common::FlagSet fs; - fs |= _lhs; - fs |= _rhs; - - return fs; -} - -namespace std -{ -template -struct hash> -{ - std::size_t operator()( - const ignition::common::FlagSet& _s) - const noexcept - { - return _s.Hash(); - } -}; -} - -#endif +#include +#include diff --git a/include/ignition/common/MaterialDensity.hh b/include/ignition/common/MaterialDensity.hh index 95de5e7d3..fae6ae619 100644 --- a/include/ignition/common/MaterialDensity.hh +++ b/include/ignition/common/MaterialDensity.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,131 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_MATERIALDENSITY_HH_ -#define IGNITION_COMMON_MATERIALDENSITY_HH_ + */ -#include -#include -#include -#include -#include "ignition/common/Export.hh" - -namespace ignition -{ - namespace common - { - /// \brief Encapsulates density types. - class IGNITION_COMMON_VISIBLE MaterialDensity - { - /// \enum Type - /// \brief Types of materials. - /// Source: https://en.wikipedia.org/wiki/Density - public: enum class Type - { - /// \internal - /// \brief Indicator used to create an iterator over the enum. Do not - /// use this. - BEGIN = 0, - - /// \brief Styrofoam, density = 75.0 kg/m^3 - STYROFOAM = BEGIN, - - /// \brief Pine, density = 373.0 kg/m^3 - PINE, - - /// \brief Wood, density = 700.0 kg/m^3 - WOOD, - - /// \brief Oak, density = 710.0 kg/m^3 - OAK, - - /// \brief Ice, density = 916.0 kg/m^3 - ICE, - - /// \brief Water, density = 1000.0 kg/m^3 - WATER, - - /// \brief Plastic, density = 1175.0 kg/m^3 - PLASTIC, - - /// \brief Concrete, density = 2000.0 kg/m^3 - CONCRETE, - - /// \brief Aluminum, density = 2700.0 kg/m^3 - ALUMINUM, - - /// \brief Steel alloy, density = 7600.0 kg/m^3 - STEEL_ALLOY, - - /// \brief Stainless steel, density = 7800.0 kg/m^3 - STEEL_STAINLESS, - - /// \brief Iron, density = 7870.0 kg/m^3 - IRON, - - /// \brief Brass, density = 8600.0 kg/m^3 - BRASS, - - /// \brief Copper, density = 8940.0 kg/m^3 - COPPER, - - /// \brief Tungsten, density = 19300.0 kg/m^3 - TUNGSTEN, - - /// \internal - /// \brief Indicator used to create an iterator over the enum. Do not - /// use this. - END - }; - - /// \brief Accessor for retrieving density entries - /// \return List of entries. - public: static const std::map &Materials(); - - /// \brief Return the density of the given material name, or -1 - /// if the material is not found. - /// \param[in] _material Name of the material, See Type. - /// \return Matching density if found, otherwise -1. - public: static double Density(const std::string &_material); - - /// \brief Return the density of a material. - /// \param[in] _material Type of the material, See Type. - /// \return Matching density if found, otherwise -1. - public: static double Density(const Type _material); - - /// \brief Return the material with the closest density value within - /// _epsilon, or MATERIAL_TYPE_END if not found. - /// \param[in] _value Density value of entry to match. - /// \param[in] _epsilon Allowable range of difference between _value, - /// and a material's density. - /// \return A tuple where the first element is the Type, and - /// the second the density. A value of {MATERIAL_TYPE_END, -1} is - /// returned on error. - public: static std::tuple Nearest( - const double _value, - const double _epsilon = std::numeric_limits::max()); - - /// \brief Return the material with the closest density value within - /// _epsilon, or MATERIAL_TYPE_END if not found. - /// \param[in] _value Density value of entry to match. - /// \param[in] _epsilon Allowable range of difference between _value, - /// and a material's density. - /// \return The nearest material type. MATERIAL_TYPE_END on error. - public: static Type NearestMaterial(const double _value, - const double _epsilon = std::numeric_limits::max()); - -#ifdef _WIN32 -// Disable warning C4251 -#pragma warning(push) -#pragma warning(disable: 4251) -#endif - /// \brief List of density entries - private: static std::map materials; -#ifdef _WIN32 -#pragma warning(pop) -#endif - }; - } -} -#endif +#include +#include diff --git a/include/ignition/common/MovingWindowFilter.hh b/include/ignition/common/MovingWindowFilter.hh index dc16df24f..c73682964 100644 --- a/include/ignition/common/MovingWindowFilter.hh +++ b/include/ignition/common/MovingWindowFilter.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,174 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_MOVINGWINDOWFILTER_HH_ -#define IGNITION_COMMON_MOVINGWINDOWFILTER_HH_ + */ -#include -#include - -namespace ignition -{ - namespace common - { - /// \cond - /// \brief Private data members for MovingWindowFilter class. - /// This must be in the header due to templatization. - template< typename T> - class MovingWindowFilterPrivate - { - // \brief Constructor - public: MovingWindowFilterPrivate(); - - /// \brief For moving window smoothed value - public: unsigned int valWindowSize = 4; - - /// \brief buffer history of raw values - public: std::vector valHistory; - - /// \brief iterator pointing to current value in buffer - public: typename std::vector::iterator valIter; - - /// \brief keep track of running sum - public: T sum; - - /// \brief keep track of number of elements - public: unsigned int samples = 0; - }; - /// \endcond - - ////////////////////////////////////////////////// - template - MovingWindowFilterPrivate::MovingWindowFilterPrivate() - { - /// \TODO FIXME hardcoded initial value for now - this->valHistory.resize(this->valWindowSize); - this->valIter = this->valHistory.begin(); - this->sum = T(); - } - - /// \brief Base class for MovingWindowFilter - template< typename T> - class MovingWindowFilter - { - /// \brief Constructor - public: MovingWindowFilter(); - - /// \brief Destructor - public: virtual ~MovingWindowFilter(); - - /// \brief Update value of filter - /// \param[in] _val new raw value - public: void Update(T _val); - - /// \brief Set window size - /// \param[in] _n new desired window size - public: void SetWindowSize(unsigned int _n); - - /// \brief Get the window size. - /// \return The size of the moving window. - public: unsigned int WindowSize() const; - - /// \brief Get whether the window has been filled. - /// \return True if the window has been filled. - public: bool WindowFilled() const; - - /// \brief Get filtered result - /// \return Latest filtered value - public: T Value(); - - /// \brief Allow subclasses to initialize their own data pointer. - /// \param[in] _d Reference to data pointer. - protected: explicit MovingWindowFilter( - MovingWindowFilterPrivate &_d); - - /// \brief Data pointer. - protected: std::unique_ptr> dataPtr; - }; - - ////////////////////////////////////////////////// - template - MovingWindowFilter::MovingWindowFilter() - : dataPtr(new MovingWindowFilterPrivate()) - { - } - - ////////////////////////////////////////////////// - template - MovingWindowFilter::~MovingWindowFilter() - { - this->dataPtr->valHistory.clear(); - } - - ////////////////////////////////////////////////// - template - void MovingWindowFilter::Update(T _val) - { - // update sum and sample size with incoming _val - - // keep running sum - this->dataPtr->sum += _val; - - // shift pointer, wrap around if end has been reached. - ++this->dataPtr->valIter; - if (this->dataPtr->valIter == this->dataPtr->valHistory.end()) - { - // reset iterator to beginning of queue - this->dataPtr->valIter = this->dataPtr->valHistory.begin(); - } - - // increment sample size - ++this->dataPtr->samples; - - if (this->dataPtr->samples > this->dataPtr->valWindowSize) - { - // subtract old value if buffer already filled - this->dataPtr->sum -= (*this->dataPtr->valIter); - // put new value into queue - (*this->dataPtr->valIter) = _val; - // reduce sample size - --this->dataPtr->samples; - } - else - { - // put new value into queue - (*this->dataPtr->valIter) = _val; - } - } - - ////////////////////////////////////////////////// - template - void MovingWindowFilter::SetWindowSize(unsigned int _n) - { - this->dataPtr->valWindowSize = _n; - this->dataPtr->valHistory.clear(); - this->dataPtr->valHistory.resize(this->dataPtr->valWindowSize); - this->dataPtr->valIter = this->dataPtr->valHistory.begin(); - this->dataPtr->sum = T(); - this->dataPtr->samples = 0; - } - - ////////////////////////////////////////////////// - template - unsigned int MovingWindowFilter::WindowSize() const - { - return this->dataPtr->valWindowSize; - } - - ////////////////////////////////////////////////// - template - bool MovingWindowFilter::WindowFilled() const - { - return this->dataPtr->samples == this->dataPtr->valWindowSize; - } - - ////////////////////////////////////////////////// - template - T MovingWindowFilter::Value() - { - return this->dataPtr->sum / static_cast(this->dataPtr->samples); - } - } -} -#endif +#include +#include diff --git a/include/ignition/common/Plugin.hh b/include/ignition/common/Plugin.hh index 92294d511..517cfdfb3 100644 --- a/include/ignition/common/Plugin.hh +++ b/include/ignition/common/Plugin.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,182 +15,5 @@ * */ - -#ifndef IGNITION_COMMON_PLUGIN_HH_ -#define IGNITION_COMMON_PLUGIN_HH_ - -#include -#include -#include - -#include -#include - -namespace ignition -{ - namespace common - { - // Forward declarations - struct PluginInfo; - class PluginPrivate; - namespace detail { template class ComposePlugin; } - - class IGNITION_COMMON_VISIBLE Plugin - { - // -------------------- Public API --------------------- - - /// \brief Get an interface of the specified type. Note that this function - /// only works when the Interface type is specialized using the macro - /// IGN_COMMON_SPECIALIZE_INTERFACE. For more general interfaces which do - /// not meet this condition, use - /// QueryInterface(_interfaceName). - /// - /// Note that the interface pointer you receive is owned by the Plugin - /// object. You MUST NOT ever try to deallocate it yourself. Moreover, the - /// pointer will be invalidated once all Plugin objects that refer to the - /// same Plugin instance are destructed. Use the QueryInterfaceSharedPtr - /// function in order to get a reference-counting pointer to an interface - /// of this Plugin object. The pointer will remain valid as long as the - /// std::shared_ptr provided by QueryInterfaceSharedPtr is alive. - public: template - Interface *QueryInterface(); - - /// \brief const-qualified version of QueryInterface() - public: template - const Interface *QueryInterface() const; - - /// \brief Get an interface with the given name, casted to the specified - /// class type. The template argument Interface must exactly match the - /// underlying type associated with _interfaceName, or else the behavior - /// of this function is undefined. - /// - /// Note that the interface pointer you receive is owned by the Plugin - /// object. You MUST NOT ever try to deallocate it yourself. Moreover, the - /// pointer will be invalidated once all Plugin objects that refer to the - /// same Plugin instance are destructed. Use the QueryInterfaceSharedPtr - /// function in order to get a reference-counting pointer to an interface - /// of this Plugin object. The pointer will remain valid as long as the - /// std::shared_ptr provided by QueryInterfaceSharedPtr is alive. - /// - /// \param[in] _interfaceName The name of the desired interface, as a - /// string. - /// \return A raw pointer to the specified interface. If the requested - /// _interfaceName is not provided by this Plugin, this returns a nullptr. - /// This pointer is invalidated when the reference count of the plugin - /// instance drops to zero. - public: template - Interface *QueryInterface(const std::string &_interfaceName); - - /// \brief const-qualified version of - /// QueryInterface(std::string) - public: template - const Interface *QueryInterface( - const std::string &_interfaceName) const; - - /// \brief Get the requested interface as a std::shared_ptr. Note that - /// this function only works when the Interface type is specialized using - /// the macro IGN_COMMON_SPECIALIZE_INTERFACE. For more general interfaces - /// which do not meet this condition, use - /// QueryInterfaceSharedPtr(const std::string&). - public: template - std::shared_ptr QueryInterfaceSharedPtr(); - - /// \brief Same as QueryInterfaceSharedPtr(), but it returns a - /// std::shared_ptr to a const-qualified Interface. - public: template - std::shared_ptr QueryInterfaceSharedPtr() const; - - /// \brief Get the requested interface as a std::shared_ptr. The template - /// argument Interface must exactly match the underlying type associated - /// with _interfaceName, or else the behavior of this function is - /// undefined. - /// - /// This std::shared_ptr and the interface+plugin that it refers to will - /// remain valid, even if all Plugin objects which refer to the plugin - /// instance are destructed. - /// - /// You MUST NOT attempt to pass a QueryInterface pointer into a - /// std::shared_ptr yourself; that will result in double-delete memory - /// errors. You must always call QueryInterfaceSharedPtr for a reference- - /// counting pointer to an interface. - /// - /// \param[in] _interfaceName The name of the desired interface, as a - /// string. - /// \return A reference-counting pointer to the specified interface. This - /// will keep the interface valid and the plugin instance alive, even if - /// all Plugin objects that refer to this plugin instance are destructed. - public: template - std::shared_ptr QueryInterfaceSharedPtr( - const std::string &_interfaceName); - - /// \brief Same as QueryInterfaceSharedPtr(std::string), but - /// it returns a std::shared_ptr to a const-qualified Interface. - public: template - std::shared_ptr QueryInterfaceSharedPtr( - const std::string &_interfaceName) const; - - /// \brief Returns true if this Plugin has the specified type of - /// interface. Note that this function only works when the Interface type - /// is specialized using the macro IGN_COMMON_SPECIALIZE_INTERFACE. For - /// more general interfaces which do not meet this condition, use - /// QueryInterface(_interfaceName). - public: template - bool HasInterface() const; - - /// \brief Returns true if this Plugin has the specified type of - /// interface, otherwise returns false. - /// - /// \param[in] _interfaceName The name of the desired interface, as a - /// string. - public: bool HasInterface(const std::string &_interfaceName) const; - - - // -------------------- Private API ----------------------- - - template friend class TemplatePluginPtr; - template friend class SpecializedPlugin; - template friend class detail::ComposePlugin; - - /// \brief Default constructor. This is kept private to ensure that - /// Plugins are always managed by a PluginPtr object. - private: Plugin(); - - /// \brief Type-agnostic retriever for interfaces - private: void *PrivateGetInterface( - const std::string &_interfaceName) const; - - /// \brief Copy the plugin instance from another Plugin object - private: void PrivateCopyPluginInstance(const Plugin &_other) const; - - /// \brief Create a new plugin instance based on the info provided - private: void PrivateSetPluginInstance(const PluginInfo *_info) const; - - /// \brief Get a reference to the std::shared_ptr being managed by this - /// wrapper - private: const std::shared_ptr& PrivateGetInstancePtr() const; - - /// \brief The InterfaceMap type needs to get used in several places, like - /// PluginPrivate and SpecializedPlugin. We make the typedef public so - /// that those other classes can use it without needing to be friends of - /// Plugin. End-users should not have any need for this typedef. - public: using InterfaceMap = std::map; - - /// \brief Get or create an iterator to the std::map that holds pointers - /// to the various interfaces provided by this plugin instance. - private: InterfaceMap::iterator PrivateGetOrCreateIterator( - const std::string &_interfaceName); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief PIMPL pointer to the implementation of this class. - private: const std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - - /// \brief Virtual destructor - public: virtual ~Plugin(); - }; - } -} - -#include "ignition/common/detail/Plugin.hh" - -#endif +#include +#include diff --git a/include/ignition/common/PluginInfo.hh b/include/ignition/common/PluginInfo.hh index c819c4a19..0e40a1efd 100644 --- a/include/ignition/common/PluginInfo.hh +++ b/include/ignition/common/PluginInfo.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,47 +15,5 @@ * */ - -#ifndef IGNITION_COMMON_PLUGININFO_HH_ -#define IGNITION_COMMON_PLUGININFO_HH_ - -#include -#include -#include - -namespace ignition -{ - namespace common - { - /// \brief sentinel value to check if a plugin was built with the same - /// version of the PluginInfo struct - // - /// This must be incremented when the PluginInfo struct changes - const int PLUGIN_API_VERSION = 1; - - - /// \brief Holds info required to construct a plugin - struct PluginInfo - { - /// \brief The name of the plugin - std::string name; - - /// \brief The keys are the names of the types of interfaces that this - /// plugin provides. The values are functions that convert a void pointer - /// (which actually points to the plugin instance) to another void pointer - /// (which actually points to the location of the interface within the - /// plugin instance). - using InterfaceCastingMap = - std::unordered_map< std::string, std::function >; - InterfaceCastingMap interfaces; - - /// \brief A method that instantiates a new instance of a plugin - std::function factory; - - /// \brief A method that safely deletes an instance of the plugin - std::function deleter; - }; - } -} - -#endif +#include +#include diff --git a/include/ignition/common/PluginLoader.hh b/include/ignition/common/PluginLoader.hh index dee83d7ee..51b8f5d00 100644 --- a/include/ignition/common/PluginLoader.hh +++ b/include/ignition/common/PluginLoader.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,90 +15,5 @@ * */ - -#ifndef IGNITION_COMMON_PLUGINLOADER_HH_ -#define IGNITION_COMMON_PLUGINLOADER_HH_ - -#include -#include -#include -#include - -#include -#include -#include - -namespace ignition -{ - namespace common - { - /// \brief Forward declaration - class PluginLoaderPrivate; - struct PluginInfo; - - /// \brief Class for loading plugins - class IGNITION_COMMON_VISIBLE PluginLoader - { - /// \brief Constructor - public: PluginLoader(); - - /// \brief Destructor - public: ~PluginLoader(); - - /// \brief Makes a printable string with info about plugins - /// \returns A pretty string - public: std::string PrettyStr() const; - - /// \brief Get names of interfaces that the loader has plugins for - /// \returns Interfaces that are implemented - public: std::unordered_set InterfacesImplemented() const; - - /// \brief Get plugin names that implement the interface - /// \param[in] _interface Name of an interface - /// \returns Names of plugins that implement the interface - public: std::unordered_set PluginsImplementing( - const std::string &_interface) const; - - /// \brief Load a library at the given path - /// \param[in] _pathToLibrary is the path to a libaray - /// \returns The set of plugins that have been loaded from the library - public: std::unordered_set LoadLibrary( - const std::string &_pathToLibrary); - - /// \brief Instantiates a plugin for the given plugin name - /// - /// \param[in] _plugin name of the plugin to instantiate - /// \returns Pointer to instantiated plugin - public: PluginPtr Instantiate(const std::string &_pluginName) const; - - /// \brief Instantiates a plugin of PluginType for the given plugin name. - /// This can be used to create a specialized PluginPtr. - /// - /// \tparam PluginPtrType The specialized type of PluginPtrPtr that you - /// want to construct. - /// \param[in] _pluginName The name of the plugin that you want to - /// instantiate - /// \returns pointer for the instantiated PluginPtr - public: template - PluginPtrType Instantiate( - const std::string &_pluginName) const; - - /// \brief Get a pointer to the PluginInfo corresponding to _pluginName. - /// \param[in] _pluginName The name of the plugin that you want to - /// instantiate - /// \return Pointer to PluginInfo or nullptr if there is no info for the - /// requested _pluginName. - private: const PluginInfo *PrivateGetPluginInfo( - const std::string &_pluginName) const; - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief PIMPL pointer to class implementation - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} - -#include "ignition/common/detail/PluginLoader.hh" - -#endif +#include +#include diff --git a/include/ignition/common/PluginMacros.hh b/include/ignition/common/PluginMacros.hh index ecc9b677f..10d307610 100644 --- a/include/ignition/common/PluginMacros.hh +++ b/include/ignition/common/PluginMacros.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,130 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ - - -#ifndef IGNITION_COMMON_REGISTERMACROS_HH_ -#define IGNITION_COMMON_REGISTERMACROS_HH_ - -#include "ignition/common/detail/PluginMacros.hh" - -// --------------- Specialize a plugin interface (optional) ------------------- - -/// \brief Call this macro inside a public scope of an interface in order to get -/// performance benefits for that interface in a SpecializedPlugin. Pass in -/// the fully qualified name of the interface class (i.e. explicitly include the -/// namespaces of the class). -/// -/// Usage example: -/// -/// \code -/// namespace mylibrary { -/// namespace ns { -/// class SomeInterface -/// { -/// public: -/// IGN_COMMON_SPECIALIZE_INTERFACE(mylibrary::ns::SomeInterface) -/// // ... declarations of interface functions ... -/// }; -/// } // namespace ns -/// } // namespace mylibrary -/// \endcode -/// -/// Interfaces with this macro can be utilized by SpecializedPlugin to get -/// high-speed access to this type of interface. Note that this performance -/// benefit is available even if the plugin that gets loaded does not offer this -/// interface; you just get high-speed access to a nullptr instead. Always be -/// sure to verify the existence of an interface that you query from a plugin by -/// checking whether it's a nullptr! -#define IGN_COMMON_SPECIALIZE_INTERFACE(interfaceName)\ - DETAIL_IGN_COMMON_SPECIALIZE_INTERFACE(interfaceName) - - -// ------------- Add a set of plugins or a set of interfaces ------------------ - -// The following three macros can be used to produce multiple plugins and/or -// multiple interfaces from your shared library. - -/* Usage example for multiple plugins and one interface: - * - * IGN_COMMON_BEGIN_ADDING_PLUGINS - * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeClass1, mylibrary::ns::SomeInterface) - * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeClass2, mylibrary::ns::SomeInterface) - * IGN_COMMON_FINISH_ADDING_PLUGINS - * - * - * Usage example for one plugin and multiple interfaces: - * - * IGN_COMMON_BEGIN_ADDING_PLUGINS - * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeClass, mylibrary::ns::Interface1) - * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeClass, mylibrary::ns::Interface2) - * IGN_COMMON_FINISH_ADDING_PLUGINS - * - * - * Usage example for multiple plugins and multiple interfaces: - * - * IGN_COMMON_BEGIN_ADDING_PLUGINS - * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeClass, mylibrary::ns::FooInterface) - * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeOtherClass, mylibrary::ns::BarInterface) - * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeClass, mylibrary::ns::SomeInterface) - * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeOtherClass, mylibrary::ns::FooInterface) - * IGN_COMMON_ADD_PLUGIN(mylibrary::ns::SomeOtherClass, mylibrary::ns::SomeInterface) - * IGN_COMMON_FINISH_ADDING_PLUGINS */ -// Note that the order in which (Plugin, Interface) pairs are added does not -// matter. Multiple plugins are allowed to provide the same interface. There is -// no inherent limit on the number of interfaces or plugins that are allowed. -// -// These macros MUST be called in the global namespace in a source file of your -// library's codebase. A single library is only allowed to have ONE block of -// these macros (i.e. if you find yourself invoking -// IGN_COMMON_BEGIN_ADDING_PLUGINS more than once in your library, then you are -// doing something that is not permitted). Recommended practice is to have a -// single source file (e.g. plugins.cpp) in your library's codebase that is -// dedicated to hosting these macros. - - -/// \brief Begin registering a set of plugins that are contained within this -/// shared library. After invoking this macro, use a sequence of calls to -/// IGN_COMMON_ADD_PLUGIN(~,~), passing in a different plugin and interface name -/// to each call. When all the plugins and interfaces have been added, call -/// IGN_COMMON_FINISH_ADDING_PLUGINS. -/// -/// Be sure to only use this macro in the global namespace, and only use it once -/// in your library. -#define IGN_COMMON_BEGIN_ADDING_PLUGINS\ - DETAIL_IGN_COMMON_BEGIN_ADDING_PLUGINS - - -/// \brief Add a plugin and interface from this shared library. This macro must -/// be called consecutively on each class that this shared library wants to -/// provide as a plugin or interface. This macro must be called in between -/// IGN_COMMON_BEGIN_ADDING_PLUGINS and IGN_COMMON_FINISH_ADDING_PLUGINS. If a -/// plugin provides multiple interfaces, then simply call this macro repeatedly -/// on the plugin, once for each interface. The multiple interfaces will -/// automatically be collapsed into one plugin that provides all of them. -#define IGN_COMMON_ADD_PLUGIN(plugin, interface)\ - DETAIL_IGN_COMMON_ADD_PLUGIN(plugin, interface) - - -/// \brief Call this macro after all calls to IGN_COMMON_ADD_PLUGIN have been -/// finished. -#define IGN_COMMON_FINISH_ADDING_PLUGINS\ - DETAIL_IGN_COMMON_FINISH_ADDING_PLUGINS - - -// -------------- Add a single plugin with a single interface ----------------- - -/// \brief Register a shared library with only one plugin and one interface. -/// This macro is NOT compatible with IGN_COMMON_ADD_PLUGIN or any of the -/// above macros for adding multiple plugins and/or multiple interfaces. This is -/// simply a convenience function if you want to add one plugin with one -/// interface from your library. -#define IGN_COMMON_REGISTER_SINGLE_PLUGIN(plugin, interface) \ - IGN_COMMON_BEGIN_ADDING_PLUGINS\ - IGN_COMMON_ADD_PLUGIN(plugin, interface)\ - IGN_COMMON_FINISH_ADDING_PLUGINS - -#endif +#include +#include diff --git a/include/ignition/common/PluginPtr.hh b/include/ignition/common/PluginPtr.hh index c202b84c0..b265078a4 100644 --- a/include/ignition/common/PluginPtr.hh +++ b/include/ignition/common/PluginPtr.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,217 +15,5 @@ * */ - -#ifndef IGNITION_COMMON_PLUGINPTR_HH_ -#define IGNITION_COMMON_PLUGINPTR_HH_ - -#include -#include -#include - -#include "ignition/common/Plugin.hh" - -namespace ignition -{ - namespace common - { - // Forward declarations - struct PluginInfo; - namespace detail { template class ComposePlugin; } - - /// \brief This class manages the lifecycle of a plugin instance. It can - /// receive a plugin instance from the ignition::common::PluginLoader class - /// or by copy-construction or assignment from another PluginPtr instance. - /// - /// This class behaves similarly to a std::shared_ptr where multiple - /// PluginPtr objects can share a single plugin instance, and the plugin - /// instance will not be deleted until all PluginPtr objects that refer to - /// it are either destroyed, cleared, or begin referring to a different - /// plugin instance. - /// - /// A PluginPtr object can be "cast" to a SpecializedPluginPtr object by - /// simply using the copy/move constructor or assignment operator of a - /// SpecializedPluginPtr object. Note that this "cast" does have a small - /// amount of overhead associated with it, but it may result in huge savings - /// after initialization is finished if you frequently access the interfaces - /// that the SpecializedPluginPtr is specialized for. - template - class TemplatePluginPtr final - { - /// \brief Destructor. Deletes this PluginPtr's reference to the plugin - /// instance. Once all PluginPtrs that refer to a plugin instance are - /// deleted, the plugin will also be deleted. - public: ~TemplatePluginPtr() = default; - - /// \brief Default constructor. Creates a PluginPtr object that does not - /// point to any plugin instance. IsEmpty() will return true until a - /// plugin instance is provided. - public: TemplatePluginPtr(); - - /// \brief Copy constructor. This PluginPtr will now point at the same - /// plugin instance as _other, and they will share ownership. - /// \param[in] _other Pointer to plugin being copied. - public: TemplatePluginPtr(const TemplatePluginPtr &_other); - - /// \brief Move constructor. This PluginPtr will take ownership of the - /// plugin instance held by _other. If this PluginPtr was holding an - /// instance to another plugin, that instance will be deleted if no other - /// PluginPtr is referencing it. - /// \param[in] _other Pointer to plugin being moved. - public: TemplatePluginPtr(TemplatePluginPtr &&_other); - - /// \brief Casting constructor. This PluginPtr will now point at the same - /// plugin instance as _other, and they will share ownership. This - /// essentially allows casting between PluginPtrs that are holding - /// different types of plugin wrappers (for example, you can cast a - /// generic PluginPtr to any SpecializedPluginPtr type, or you can cast - /// between different types of specializations). - /// \param[in] _other Another PluginPtr object. It may have a different - /// kind of specialization. - public: template - TemplatePluginPtr( - const TemplatePluginPtr &_other); - - /// \brief Copy assignment operator. This PluginPtr will now point at the - /// same plugin instance as _other, and they will share ownership. If this - /// PluginPtr was holding an instance to another plugin, that instance - /// will be deleted if no other PluginPtr is referencing it. - /// \param[in] _other Pointer to plugin being copied. - public: TemplatePluginPtr &operator =(const TemplatePluginPtr &_other); - - /// \brief Casting operator. This PluginPtr will now point at the same - /// plugin instance as _other, and they will share ownership. This - /// essentially allows casting between PluginPtrs that are holding - /// different types of plugin wrappers. - /// \param[in] _other Another PluginPtr object. It may have a different - /// kind of specialization. - /// \return A reference to this object. - public: template - TemplatePluginPtr &operator =( - const TemplatePluginPtr &_other); - - /// \brief Move assignment operator. This PluginPtr will take ownership - /// of the plugin instance held by _other. If this PluginPtr was holding - /// an instance to another plugin, that instance will be deleted if no - /// other PluginPtr is referencing it. - /// \param[in] _other Another PluginPtr object. - /// \return A reference to this object. - public: TemplatePluginPtr &operator =(TemplatePluginPtr &&_other); - - /// \brief nullptr assignment operator. Same as calling Clear() - /// \param[in] A nullptr object. - /// \return A reference to this object. - public: TemplatePluginPtr &operator =(std::nullptr_t); - - /// \brief Access the wrapper for the plugin instance and call one of its - /// member functions. - /// \return The ability to call a member function on the underlying Plugin - /// object. - public: PluginType *operator ->() const; - - /// \brief Get a reference to the wrapper for the plugin instance that is - /// being managed by this PluginPtr. - /// \return A reference to the underlying Plugin object. - public: PluginType &operator *() const; - - /// \brief Comparison operator. Returns true if this Plugin is holding the - /// same plugin instance as _other, otherwise returns false. - /// \param[in] _other Another PluginPtr object. - /// \return True if the value of this pointer is == _other. - public: bool operator ==(const TemplatePluginPtr &_other) const; - - /// \brief Comparison operator. - /// \param[in] _other Plugin to compare to. - /// \returns True if the pointer value of the plugin instance held - /// by this PluginPtr is less than the pointer value of the instance held - /// by _other. - /// \param[in] _other Another PluginPtr object. - /// \return True if the value of this pointer is < _other. - public: bool operator <(const TemplatePluginPtr &_other) const; - - /// \brief Comparison operator. - /// \param[in] _other Plugin to compare to. - /// \returns True if the pointer value of the plugin instance held - /// by this PluginPtr is greater than the pointer value of the instance - /// held by _other. - /// \param[in] _other Another PluginPtr object. - /// \return True if the value of this pointer is > _other. - public: bool operator >(const TemplatePluginPtr &_other) const; - - /// \brief Comparison operator. - /// \param[in] _other Plugin to compare to. - /// \returns True if the pointer instance held by this PluginPtr is - /// different from the pointer instance held by _other. - /// \param[in] _other Another PluginPtr object. - /// \return True if the value of this pointer is != _other. - public: bool operator !=(const TemplatePluginPtr &_other) const; - - /// \brief Comparison operator. - /// \param[in] _other Plugin to compare to. - /// \returns True if the value of the pointer instance held by this - /// PluginPtr is less than or equal to the value of the pointer instance - /// held by _other. - /// \param[in] _other Another PluginPtr object. - /// \return True if the value of this pointer is <= _other. - public: bool operator <=(const TemplatePluginPtr &_other) const; - - /// \brief Comparison operator. - /// \param[in] _other Plugin to compare to. - /// \returns True if the value of the pointer instance held by this - /// PluginPtr is greater than or equal to the value of the pointer - /// instance held by _other. - /// \param[in] _other Another PluginPtr object. - /// \return True if the value of this pointer is >= _other. - public: bool operator >=(const TemplatePluginPtr &_other) const; - - /// \brief Produces a hash for the plugin instance that this PluginPtr is - /// holding. This function allows PluginPtr instances to be used as values - /// in a std::unordered_set or keys in a - /// std::unordered_map. Using this function directly should - /// not normally be necessary. - /// \return A hash of the underlying pointer object. - public: std::size_t Hash() const; - - /// \brief Check if this PluginPtr is holding a plugin instance. - /// \return False if this PluginPtr contains a plugin instance. If it - /// instead contains a nullptr, this returns true. - public: bool IsEmpty() const; - - /// \brief Implicitly convert this PluginPtr to a boolean. - /// \return The opposite value of IsEmpty(). - public: operator bool() const; - - /// \brief Clears the Plugin instance from this PluginPtr. IsEmpty() will - /// return true after this is used, and none of the interfaces will be - /// available any longer. - public: void Clear(); - - /// \brief Private constructor. Creates a plugin instance based on the - /// PluginInfo provided. This should only be called by PluginLoader to - /// ensure that the PluginInfo is well-formed, so we keep it private. - /// \param[in] _info A PluginInfo instance that was generated by - /// PluginLoader. Alternatively, this can take a nullptr to create an - /// empty PluginPtr. - private: explicit TemplatePluginPtr(const PluginInfo *_info); - - /// \brief Pointer to the plugin wrapper that this PluginPtr is managing. - private: std::unique_ptr dataPtr; - - // Declare friendship - friend class PluginLoader; - template friend class TemplatePluginPtr; - }; - - /// \brief Typical usage for TemplatePluginPtr is to just hold a generic - /// Plugin type. - using PluginPtr = TemplatePluginPtr; - - /// \brief This produces a PluginPtr whose Plugin wrapper only grants access - /// to const-qualified interfaces of the plugin instance. - using ConstPluginPtr = TemplatePluginPtr; - } -} - -#include "ignition/common/detail/PluginPtr.hh" - -#endif +#include +#include diff --git a/include/ignition/common/SignalHandler.hh b/include/ignition/common/SignalHandler.hh index 5452eb094..e60d34cf4 100644 --- a/include/ignition/common/SignalHandler.hh +++ b/include/ignition/common/SignalHandler.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,68 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_SIGNALHANDLER_HH_ -#define IGNITION_COMMON_SIGNALHANDLER_HH_ + */ -#include - -#include - -namespace ignition -{ - namespace common - { - // Forward declarations. - class SignalHandlerPrivate; - - /// \brief Register callbacks that get triggered on SIGINT and SIGTERM. - /// - /// This class is a thread-safe interface to system signals (SIGINT and - /// SIGTERM). Use the AddCallback(std::function) - /// function to register callbacks that - /// should be called when a SIGINT or SIGTERM is triggered. - /// - /// Example using a lambda callback: - /// - /// ~~~ - /// ignition::common::SignalHandler handler; - /// handler.AddCallback([] (int _sig) - /// { - /// printf("Signal[%d] received\n", _sig); - /// }); - /// ~~~ - /// - class IGNITION_COMMON_VISIBLE SignalHandler - { - /// \brief Constructor - public: SignalHandler(); - - /// \brief Destructor. - public: virtual ~SignalHandler(); - - /// \brief Add a callback to execute when a signal is received. - /// \param[in] _cb Callback to execute. - /// \return True if the callback was added. A callback may not be - /// added if the SignalHandler was not successfully initialized. - /// \sa bool Initialized() const - public: bool AddCallback(std::function _cb); - - /// \brief Get whether the signal handlers were successfully - /// initialized. - /// \return True if the signal handlers were successfully created. - public: bool Initialized() const; - - /// \brief Set whether the signal handler was successfully - /// initialized. This function is here for testing purposes, and - /// if for some reason a person needs to create a subclass to control - /// the initialization value. - /// \param[in] _init New value of the initialized member variabl.e - protected: virtual void SetInitialized(const bool _init); - - /// \brief Private data pointer - private: SignalHandlerPrivate *dataPtr; - }; - } -} -#endif +#include +#include diff --git a/include/ignition/common/SingletonT.hh b/include/ignition/common/SingletonT.hh index 61127f957..85d180775 100644 --- a/include/ignition/common/SingletonT.hh +++ b/include/ignition/common/SingletonT.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,45 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_SINGLETONT_HH_ -#define IGNITION_COMMON_SINGLETONT_HH_ + */ -namespace ignition -{ - namespace common - { - /// \class SingletonT SingletonT.hh common/common.hh - /// \brief Singleton template class - template - class SingletonT - { - /// \brief Get an instance of the singleton - public: static T *Instance() - { - return &GetInstance(); - } - - /// \brief Constructor - protected: SingletonT() {} - - /// \brief Destructor - protected: virtual ~SingletonT() {} - - /// \brief Creates and returns a reference to the unique (static) instance - private: static T &GetInstance() - { - static T t; - return static_cast(t); - } - - /// \brief A reference to the unique instance - private: static T &myself; - }; - - /// \brief Initialization of the singleton instance. - template - T &SingletonT::myself = SingletonT::GetInstance(); - } -} -#endif +#include +#include diff --git a/include/ignition/common/SpecializedPlugin.hh b/include/ignition/common/SpecializedPlugin.hh index 8f4c86a8a..5c2d1a4cb 100644 --- a/include/ignition/common/SpecializedPlugin.hh +++ b/include/ignition/common/SpecializedPlugin.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,157 +14,6 @@ * limitations under the License. * */ -#ifndef IGNITION_COMMON_SPECIALIZEDPLUGIN_HH_ -#define IGNITION_COMMON_SPECIALIZEDPLUGIN_HH_ -#include - -#include "ignition/common/Plugin.hh" - -namespace ignition -{ - namespace common - { - // Forward declarations - namespace detail { template class ComposePlugin; } - struct PluginInfo; - - // Forward declaration of the variadic template SpecializedPlugin class. - template - class SpecializedPlugin; - - /// \brief This class allows Plugin instances to have high-speed access to - /// interfaces that can be anticipated at compile time. The plugin does - /// not have to actually offer the specialized interface in order to get - /// this performance improvement. This template is variadic, so it can - /// support arbitrarily many interfaces. - /// - /// Usage example: - /// - /// \code - /// using MySpecialPluginPtr = SpecializedPluginPtr< - /// MyInterface1, FooInterface, MyInterface2, BarInterface>; - /// - /// MySpecialPluginPtr plugin = loader->Instantiate(pluginName); - /// \endcode - /// - /// Then, calling the function - /// - /// \code - /// plugin->QueryInterface(); - /// \endcode - /// - /// will have extremely high-speed associated with it. It will provide - /// direct access to the the `FooInterface*` of `plugin`. If `plugin` does - /// not actually offer `FooInterface`, then it will return a nullptr, still - /// at extremely high speed. - /// - /// Only interfaces that have been "specialized" can be passed as arguments - /// to the SpecializedPlugin template. To specialize an interface, simply - /// put the macro IGN_COMMON_SPECIALIZE_INTERFACE(~) from - /// ignition/common/PluginMacros.hh into a public location of its class - /// definition. - template - class SpecializedPlugin : public virtual Plugin - { - // -------------------- Public API --------------------- - - // Inherit function overloads - public: using Plugin::QueryInterface; - public: using Plugin::QueryInterfaceSharedPtr; - public: using Plugin::HasInterface; - - // Documentation inherited - public: template - Interface *QueryInterface(); - - // Documentation inherited - public: template - const Interface *QueryInterface() const; - - // Documentation inherited - public: template - std::shared_ptr QueryInterfaceSharedPtr(); - - // Documentation inherited - public: template - std::shared_ptr QueryInterfaceSharedPtr() const; - - // Documentation inherited - public: template - bool HasInterface() const; - - - // -------------------- Private API --------------------- - - // Declare friendship - template friend class SpecializedPlugin; - template friend class detail::ComposePlugin; - template friend class TemplatePluginPtr; - - /// \brief Default constructor - private: SpecializedPlugin(); - - /// \brief type is an empty placeholder class which is used by the private - /// member functions to provide two overloads: a high-performance one for - /// the specialized interface, and a normal-performance one for all other - /// Interface types. - private: template struct type { }; - - /// \brief Delegate the function to the standard Plugin method - /// \param[in] _type Empty object meant to guide the compiler to pick the - /// desired implementation. - /// \return Pointer to the interface - private: template - Interface *PrivateQueryInterface(type _type); - - /// \brief Use a high-speed accessor to provide this specialized interface - /// \param[in] _type Empty object meant to guide the compiler to pick the - /// desired implementation. - /// \return Pointer to the specialized interface - private: SpecInterface *PrivateQueryInterface( - type _type); - - /// \brief Delegate the function to the standard Plugin method - /// \param[in] _type Empty object meant to guide the compiler to pick the - /// desired implementation. - /// \return Pointer to the specialized interface - private: template - const Interface *PrivateQueryInterface(type _type) - const; - - /// \brief Use a high-speed accessor to provide this specialized interface - /// \param[in] _type Empty object meant to guide the compiler to pick the - /// desired implementation. - /// \return Pointer to the specialized interface - private: const SpecInterface *PrivateQueryInterface( - type _type) const; - - /// \brief Delegate the function to the standard PluginPtr method - /// \param[in] _type Empty object meant to guide the compiler to pick the - /// desired implementation. - /// \return True if the interface is present. - private: template - bool PrivateHasInterface(type _type) const; - - /// \brief Use a high-speed accessor to check this specialized interface - /// \param[in] _type Empty object meant to guide the compiler to pick the - /// desired implementation. - /// \return True if the interface is present. - private: bool PrivateHasInterface(type _type) const; - - /// \brief Iterator that points to the entry of the specialized interface - private: const Plugin::InterfaceMap::iterator - privateSpecializedInterfaceIterator; - - // Dev note (MXG): The privateSpecializedInterfaceIterator object must be - // available to the user during their compile time, so it cannot be hidden - // using PIMPL. The iterator is const because it must always point to the - // same entry throughout its entire lifecycle. - }; - } -} - -#include "ignition/common/detail/SpecializedPlugin.hh" - -#endif +#include +#include diff --git a/include/ignition/common/SpecializedPluginPtr.hh b/include/ignition/common/SpecializedPluginPtr.hh index b09702f81..cbccb0d5c 100644 --- a/include/ignition/common/SpecializedPluginPtr.hh +++ b/include/ignition/common/SpecializedPluginPtr.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,67 +15,5 @@ * */ - -#ifndef IGNITION_COMMON_SPECIALIZEDPLUGINPTR_HH_ -#define IGNITION_COMMON_SPECIALIZEDPLUGINPTR_HH_ - -#include "ignition/common/PluginPtr.hh" -#include "ignition/common/SpecializedPlugin.hh" - -namespace ignition -{ - namespace common - { - /// \brief This alias allows PluginPtr instances to have high-speed access - /// to interfaces that can be anticipated at compile time. The plugin does - /// not have to actually offer the specialized interface in order to get - /// this performance improvement. This template is variadic, so it can - /// support arbitrarily many interfaces. - /// - /// Usage example: - /// - /// Suppose you want to instantiate a plugin that might (or might not) have - /// some combination of four interfaces which are known at compile time: - /// `MyInterface1`, `FooInterface`, `MyInterface2`, and `BarInterface`. You - /// can use SpecializedPluginPtr as shown here: - /// - /// \code - /// using MySpecialPluginPtr = SpecializedPluginPtr< - /// MyInterface1, FooInterface, MyInterface2, BarInterface>; - /// - /// MySpecialPluginPtr plugin = loader->Instantiate(pluginName); - /// \endcode - /// - /// Then, calling the function - /// - /// \code - /// plugin->QueryInterface(); - /// \endcode - /// - /// will have extremely high speed associated with it. It will provide - /// direct access to the the `FooInterface*` of `plugin`. If `plugin` does - /// not actually offer `FooInterface`, then it will return a nullptr, still - /// at extremely high speed. - /// - /// This same rule also applies to `MyInterface1`, `MyInterface2`, and - /// `BarInterface`, because those interfaces were also provided to - /// SpecializedPluginPtr<...> at compile time. - /// - /// Only interfaces that have been "specialized" can be passed as arguments - /// to the SpecializedPluginPtr template. To specialize an interface, simply - /// put the macro IGN_COMMON_SPECIALIZE_INTERFACE(~) from - /// ignition/common/PluginMacros.hh into a public location of its class - /// definition. - template - using SpecializedPluginPtr = - TemplatePluginPtr< SpecializedPlugin >; - - /// \brief This alias creates a specialized PluginPtr whose interfaces are - /// all const-qualified. - template - using ConstSpecializedPluginPtr = - TemplatePluginPtr< const SpecializedPlugin >; - } -} - -#endif +#include +#include diff --git a/include/ignition/common/StringUtils.hh b/include/ignition/common/StringUtils.hh index 6075fc935..dd59fc016 100644 --- a/include/ignition/common/StringUtils.hh +++ b/include/ignition/common/StringUtils.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,84 +14,6 @@ * limitations under the License. * */ -#ifndef IGNITION_COMMON_STRINGUTILS_HH_ -#define IGNITION_COMMON_STRINGUTILS_HH_ -#include -#include - -#include - -namespace ignition -{ - namespace common - { - /// \brief split at a one character delimiter to get a vector of something - /// \param[in] _orig The string to split - /// \param[in] _delim a character to split the string at - /// \returns vector of split pieces of the string excluding the delimiter - std::vector IGNITION_COMMON_VISIBLE Split( - const std::string &_orig, char _delim); - - /// \brief Join a sequence of strings with a delimiter - /// - /// Note that this will skip any empty entries in the vector, - /// and will also not prepend or append the delimiter to the - /// final output string - /// - /// \param[in] _orig The input sequence of strings - /// \param[in] _delim a string delimiter to join the string with - /// \returns a single string composed of strings joined with the delimiter - std::string IGNITION_COMMON_VISIBLE Join( - const std::vector &_orig, const std::string &_delim); - - /// \brief Join a sequence of strings with a delimiter - /// - /// Note that this will skip any empty entries in the vector, - /// and will also not prepend or append the delimiter to the - /// final output string - /// - /// \param[in] _orig The input sequence of strings - /// \param[in] _delim a character to join the string with - /// \returns a single string composed of strings joined with the delimiter - std::string IGNITION_COMMON_VISIBLE Join( - const std::vector &_orig, char _delim); - - /// \brief return true if string starts with another string - /// \param[in] _s1 the string to check - /// \param[in] _s2 the possible prefix - /// \returns true if _s1 starts with _s2 - bool IGNITION_COMMON_VISIBLE StartsWith(const std::string &_s1, - const std::string &_s2); - - /// \brief return true if string ends with another string - /// \param[in] _s1 the string to check - /// \param[in] _s2 the possible suffix - /// \returns true if _s1 ends with _s2 - bool IGNITION_COMMON_VISIBLE EndsWith(const std::string &_s1, - const std::string &_s2); - - /// \brief Choose whether to use a singular or plural version of a noun - /// based on the value of an integer quantity. This version will simply add - /// an 's' character to _baseWord in the event that std::abs(_n) != 1, - /// otherwise it returns _baseWord. - /// \param[in] _baseWord the singular version of the word to return - /// \param[in] _n the quantity that _baseWord is describing - /// \return _baseWord if std::abs(_n)==1, otherwise return _baseWords - std::string IGNITION_COMMON_VISIBLE PluralCast( - const std::string &_baseWord, const int _n); - - /// \brief A version of PluralCast that works for irregular nouns. If - /// std::abs(_n)==1 then _singular is returned; otherwise _plural will be - /// returned. - /// \param[in] _singular the return value when std::abs(_n) == 1 - /// \param[in] _plural the return value when std::abs(_n) != 1 - /// \return _singular if std::abs(_n)==1, otherwise return _plural - std::string IGNITION_COMMON_VISIBLE PluralCast( - const std::string &_singular, - const std::string &_plural, - const int _n); - } -} - -#endif +#include +#include diff --git a/include/ignition/common/SuppressWarning.hh b/include/ignition/common/SuppressWarning.hh index d989fec29..bc6bcc582 100644 --- a/include/ignition/common/SuppressWarning.hh +++ b/include/ignition/common/SuppressWarning.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,61 +15,5 @@ * */ - -#ifndef IGNITION_COMMON_SUPPRESSWARNING_HH_ -#define IGNITION_COMMON_SUPPRESSWARNING_HH_ - -#include - -// This header contains cross-platform macros for suppressing warnings. Please -// only use these macros responsibly when you are certain that the compiler is -// producing a warning that is not applicable to the specific instance. Do not -// use these macros to ignore legitimate warnings, even if you may find them -// irritating. - -/* - * Usage example: - * - * SomeClass* ptr = CreatePtr(); - * IGN_COMMON_WARN_IGNORE__DELETE_NON_VIRTUAL_DESTRUCTOR - * delete ptr; - * IGN_COMMON_WARN_RESUME__DELETE_NON_VIRTUAL_DESTRUCTOR - * - */ - -// Be sure to call the IGN_COMMON_WARN_RESUME__XXXXX macro at the end of the -// block of code where the warning suppression is needed. Otherwise, you might -// inadvertently suppress legitimate warnings. - -// ---- List of available suppressions ---- - -/// \brief Compilers might warn about deleting a pointer to a class that has -/// virtual functions without a virtual destructor or a `final` declaration, -/// because the pointer might secretly be pointing to a more derived class type. -/// We want to suppress this warning when we know for certain (via the design -/// of our implementation) that the pointer is definitely not pointing to a more -/// derived type. -#define IGN_COMMON_WARN_IGNORE__DELETE_NON_VIRTUAL_DESTRUCTOR \ - DETAIL_IGN_COMMON_WARN_IGNORE__DELETE_NON_VIRTUAL_DESTRUCTOR - -#define IGN_COMMON_WARN_RESUME__DELETE_NON_VIRTUAL_DESTRUCTOR \ - DETAIL_IGN_COMMON_WARN_RESUME__DELETE_NON_VIRTUAL_DESTRUCTOR - - -/// \brief Microsoft Visual Studio does not automatically export the interface -/// information for member variables that belong to interface classes of a DLL. -/// Instead it issues this warning. When the member variable is private, we -/// choose to suppress the warning instead of needlessly adding the class -/// information to the DLL interface. -#define IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING \ - DETAIL_IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - -#define IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING \ - DETAIL_IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - - -// TODO(anyone): Add more warning types as they become relevant. -// Do not add warning -// types to suppress unless they are genuinely necessary. - -#endif +#include +#include diff --git a/include/ignition/common/SystemPaths.hh b/include/ignition/common/SystemPaths.hh index e88f482e7..23d7c8f3c 100644 --- a/include/ignition/common/SystemPaths.hh +++ b/include/ignition/common/SystemPaths.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,215 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_SYSTEMPATHS_HH_ -#define IGNITION_COMMON_SYSTEMPATHS_HH_ + */ -#include - -#ifdef _WIN32 - #include - #define GetCurrentDir _getcwd -#else - #include - #define GetCurrentDir getcwd -#endif - -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace ignition -{ - namespace common - { - // Forward declare private data class - class SystemPathsPrivate; - - /// \class SystemPaths SystemPaths.hh ignition/common/SystemPaths.hh - /// \brief Functions to handle getting system paths, keeps track of: - /// \li SystemPaths#pluginPaths - plugin library paths - /// for common::WorldPlugin - class IGNITION_COMMON_VISIBLE SystemPaths - { - /// \brief Constructor for SystemPaths - public: SystemPaths(); - - /// \brief Destructor - public: virtual ~SystemPaths(); - - /// \brief Get the log path. If IGN_LOG_PATH environment variable is set, - /// then this path is used. If not, the path is $HOME/.ignition, and in - /// case even HOME is not set, /tmp/ignition is used. If the directory - /// does not exist, it is created in the constructor of SystemPaths. - /// \return the path - public: std::string LogPath() const; - - /// \brief Get the plugin paths - /// \return a list of paths (with forward slashes as directory separators) - public: const std::list &PluginPaths(); - - /// \brief Find a file or path using a URI - /// \param[in] _uri the uniform resource identifier - /// \return Returns full path name to file with platform-specific - /// directory separators, or an empty string if URI couldn't be found. - public: std::string FindFileURI(const std::string &_uri) const; - - /// \brief Find a file or path using a URI - /// \param[in] _uri the uniform resource identifier - /// \return Returns full path name to file with platform-specific - /// directory separators, or an empty string if URI couldn't be found. - public: std::string FindFileURI(const ignition::common::URI &_uri) const; - - /// \brief Set the plugin path environment variable to use - /// \param [in] _env name of the environment variable - public: void SetPluginPathEnv(const std::string &_env); - - /// \brief Find a file in the set search paths (not recursive) - /// \param[in] _filename Name of the file to find. - /// \param[in] _searchLocalPath True to search in the current working - /// directory. - /// \return Returns full path name to file with platform-specific - /// directory separators, or empty string on error. - public: std::string FindFile(const std::string &_filename, - const bool _searchLocalPath = true) const; - - /// \brief Find a shared library by name in the plugin paths - /// - /// This will try different combinations of library names on different - /// platforms. For example searching for "MyLibName" may try finding - /// "MyLibName", "libMyLibName.so", "MyLibName.dll", etc... - /// \param[in] _libName Name of shared libary to look for - /// \return Path to file with platform-specific directory separators, - /// or empty string on error. - public: std::string FindSharedLibrary(const std::string &_libName); - - /// \brief Add colon (semicolon on windows) delimited paths to plugins - /// \param[in] _path the directory to add - public: void AddPluginPaths(const std::string &_path); - - /// \brief clear out SystemPaths#pluginPaths - public: void ClearPluginPaths(); - - /// \brief Set the file path environment variable to use, and clears - /// any previously set file paths. The default - /// environment variable is IGN_FILE_PATH. The - /// environment variable should be a set of colon (semicolon on windows) - /// delimited paths. These paths will be used with the FindFile function. - /// \param [in] _env name of the environment variable - /// \sa FilePathEnv - public: void SetFilePathEnv(const std::string &_env); - - /// \brief Get the file path environment variable in use. - /// The environment variable contains a set of colon (semicolon on - /// windows) delimited paths. These paths are used with the FindFile - /// functions. - /// \return Name of the environment variable - /// \sa SetFilePathEnv - public: std::string FilePathEnv() const; - - /// \brief Get the file paths - /// \return a list of paths (with forward slashes as directory separators) - public: const std::list &FilePaths(); - - /// \brief Add colon (semicolon on windows) delimited paths to find - /// files. These paths will be used with the FindFile function. - /// \param[in] _path A colon (semicolon on windows) delimited - /// string of paths. The path can have either forward slashes or platform- - /// specific directory separators, both are okay. - public: void AddFilePaths(const std::string &_path); - - /// \brief clear out SystemPaths#filePaths - public: void ClearFilePaths(); - - /// \brief add _suffix to the list of path search suffixes - /// \param[in] _suffix The suffix to add - public: void AddSearchPathSuffix(const std::string &_suffix); - - /// \brief Set the callback to use when ignition can't find a file. - /// The callback should return a complete path to the requested file, or - /// and empty string if the file was not found in the callback. The path - /// should use platform-specific directory separators. - /// \param[in] _cb The callback function. - /// \deprecated Use AddFindFileCallback instead - public: void IGN_DEPRECATED(3) SetFindFileCallback( - std::function _cb); - - /// \brief Add a callback to use when FindFile() can't find a file. - /// The callback should return a full local path to the requested file, or - /// and empty string if the file was not found in the callback. The path - /// should use platform-specific directory separators. - /// Callbacks will be called in the order they were added until a path is - /// found (if a callback is set using SetFindFileCallback(), that one is - /// called first). - /// \param[in] _cb The callback function, which takes a file path or URI - /// and returns the full local path. - public: void AddFindFileCallback( - std::function _cb); - - /// \brief Add a callback to use when FindFileURI() can't find a file. - /// The callback should return a full local path to the requested file, or - /// and empty string if the file was not found in the callback. The path - /// should use platform-specific directory separators. - /// Callbacks will be called in the order they were added until a path is - /// found (if a callback is set using SetFindFileURICallback(), that one - /// is called first). - /// \param[in] _cb The callback function, which takes a file path or URI - /// and returns the full local path. - public: void AddFindFileURICallback( - std::function _cb); - - /// \brief Set the callback to use when ignition can't find a file uri. - /// The callback should return a complete path to the requested file, or - /// and empty string if the file was not found in the callback. The path - /// should use platform-specific directory separators. - /// \param[in] _cb The callback function. - /// \deprecated Use AddFindFileURICallback instead - public: void IGN_DEPRECATED(3) SetFindFileURICallback( - std::function _cb); - - /// \brief look for a file in a set of search paths (not recursive) - /// \description This method checks if a file exists in given directories. - /// It does so by joining each path with the filename and - /// checking if the file exists. If the file exists in - /// multiple paths the first one is found. - /// \param[in] _filename Name of the file to find - /// \param[in] _paths paths to look for the file - /// \return Returns a path that will work from the current directory - /// or an empty string if the file was not found. The returned - /// path will be normalized, i.e. backslashes will be substituted - /// with forward slashes. - public: static std::string LocateLocalFile(const std::string &_filename, - const std::vector &_paths); - - /// \brief Format the directory path to use "/" as a separator with "/" - /// at the end. - /// \param[in] _path Path to normalize - /// \return Normalized path - public: static std::string NormalizeDirectoryPath( - const std::string &_path); - - /// \brief Return all paths given by an environment variable. - /// \param[in] _env Environment variable. - /// \return A list of paths listed by the environment variable. - public: static std::list PathsFromEnv( - const std::string &_env); - - /// \brief Get the delimiter that the current operating system - /// uses to separate different paths from each other. - public: static char Delimiter(); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief Private data pointer - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} -#endif +#include +#include diff --git a/include/ignition/common/TemplateHelpers.hh b/include/ignition/common/TemplateHelpers.hh index 1dd9be5c1..f8d0af0db 100644 --- a/include/ignition/common/TemplateHelpers.hh +++ b/include/ignition/common/TemplateHelpers.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,37 +15,5 @@ * */ - -#ifndef IGNITION_COMMON_TEMPLATEHELPERS_HH_ -#define IGNITION_COMMON_TEMPLATEHELPERS_HH_ - - -#include "ignition/common/detail/TemplateHelpers.hh" - -namespace ignition -{ - namespace common - { - /// \brief Contains a static constexpr field named `value` which will be - /// true if the type `From` has a const-quality less than or equal to the - /// type `To`. - /// - /// The following expressions will return true: - /// - /// \code - /// ConstCompatible::value - /// ConstCompatible::value - /// \endcode - /// - /// The following expression will return false: - /// - /// \code - /// ConstCompatible::value - /// \endcode - /// - template - using ConstCompatible = detail::ConstCompatible; - } -} - -#endif +#include +#include diff --git a/include/ignition/common/Time.hh b/include/ignition/common/Time.hh index 9c36f293d..2a1f37d2d 100644 --- a/include/ignition/common/Time.hh +++ b/include/ignition/common/Time.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,312 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_TIME_HH_ -#define IGNITION_COMMON_TIME_HH_ + */ -#include -#include - -#include -#include - -namespace ignition -{ - namespace common - { - /// \class Time Time.hh common/common.hh - /// \brief A Time class, can be used to hold wall- or sim-time. - /// stored as sec and nano-sec. - class IGNITION_COMMON_VISIBLE Time - { - /// \brief A static zero time variable set to common::Time(0, 0). - public: static const Time Zero; - - /// \enum Format options - /// \brief Options for formatting time as a string. - public: enum class FormatOption - { - /// \brief Days - DAYS = 0, - /// \brief Hours - HOURS = 1, - /// \brief Minutes - MINUTES = 2, - /// \brief Seconds - SECONDS = 3, - /// \brief Milliseconds - MILLISECONDS = 4 - }; - - /// \brief Constructors - public: Time(); - - /// \brief Copy constructor - /// \param[in] time Time to copy - public: Time(const Time &_time); - - /// \brief Constructor - /// \param[in] _tv Time to initialize to - public: explicit Time(const struct timespec &_tv); - - /// \brief Constructor - /// \param[in] _sec Seconds - /// \param[in] _nsec Nanoseconds - public: Time(int32_t _sec, int32_t _nsec); - - /// \brief Constuctor - /// \param[in] _time Time in double format sec.nsec - public: explicit Time(double _time); - - /// \brief Destructor - public: virtual ~Time(); - - /// \brief Get the wall time - /// \return the current time - public: static const Time &SystemTime(); - - /// \brief Set to sec and nsec - /// \param[in] _sec Seconds - /// \param[in] _nsec Nanoseconds - public: void Set(int32_t _sec, int32_t _nsec); - - /// \brief Set to seconds - /// \param[in] _seconds Number of seconds - public: void Set(double _seconds); - - /// \brief Get the time as a double - /// \return Time as a double in seconds - public: double Double() const; - - /// \brief Get the time as a float - /// \return Time as a float in seconds - public: float Float() const; - - /// \brief Sleep for the specified time. - /// \param[in] _time Sleep time - /// \return On OSX and Linux the return value is the time slept, - /// as reported by `nanosleep` for OSX and `clock_nanosleep` for Linux. - /// The return value does not include time spent before and after the - /// actual call to the system's sleep function. - /// - /// On Windows the return value is always common::Time::Zero. - public: static Time Sleep(const common::Time &_time); - - /// \brief Get the time as a string formatted as "DD hh:mm:ss.mmm", with - /// the option to choose the start/end. - /// \param[in] _start Start point. - /// \param[in] _end End point. - /// \return String representing time. - public: std::string FormattedString( - FormatOption _start = FormatOption::DAYS, - FormatOption _end = FormatOption::MILLISECONDS) const; - - /// \brief Assignment operator - /// \param[in] _time the new time - /// \return a reference to this instance - public: Time &operator=(const Time &_time); - - /// \brief Addition operators - /// \param[in] _time The time to add - /// \return a Time instance - public: Time operator+(const Time &_time) const; - - /// \brief Addition assignemtn operator - /// \param[in] _time The time to add - /// \return a Time instance - public: const Time &operator +=(const Time &_time); - - /// \brief Subtraction operator - /// \param[in] _tv The time to subtract - /// \return a Time instance - public: Time operator -(const struct timespec &_tv) const; - - /// \brief Subtraction assignment operator - /// \param[in] _tv The time to subtract - /// \return a Time instance - public: const Time &operator -=(const struct timespec &_tv); - - /// \brief Subtraction operator - /// \param[in] _time The time to subtract - /// \return a Time instance - public: Time operator -(const Time &_time) const; - - /// \brief Subtraction assignment operator - /// \param[in] _time The time to subtract - /// \return a reference to this instance - public: const Time &operator -=(const Time &_time); - - /// \brief Multiplication operator - /// \param[in] _tv the scaling duration - /// \return Time instance - public: Time operator *(const struct timespec &_tv) const; - - /// \brief Multiplication assignment operator - /// \param[in] _tv the scaling duration - /// \return a reference to this instance - public: const Time &operator *=(const struct timespec &_tv); - - /// \brief Multiplication operators - /// \param[in] _time the scaling factor - /// \return a scaled Time instance - public: Time operator *(const Time &_time) const; - - /// \brief Multiplication operators - /// \param[in] _time scale factor - /// \return a scaled Time instance - public: const Time &operator *=(const Time &_time); - - /// \brief Division assignment operator - /// \param[in] _tv a divisor - /// \return a Time instance - public: const Time &operator /=(const struct timespec &_tv); - - /// \brief Division operator - /// \param[in] _time the divisor - /// \return a Time instance - public: Time operator /(const Time &_time) const; - - /// \brief Division assignment operator - /// \param[in] time the divisor - /// \return a Time instance - public: const Time &operator /=(const Time &time); - - /// \brief Equal to operator - /// \param[in] _time the time to compare to - /// \return true if values are the same, false otherwise - public: bool operator==(const Time &_time) const; - - /// \brief Equal to operator - /// \param[in] _time the time to compare to - /// \return true if values are the same, false otherwise - public: bool operator==(double _time) const; - - /// \brief Equal to operator - /// \param[in] _time the time to compare to - /// \return true if values are the same, false otherwise - public: bool operator!=(const Time &_time) const; - - /// \brief Equal to operator - /// \param[in] _time the time to compare to - /// \return true if values are the same, false otherwise - public: bool operator!=(double _time) const; - - /// \brief Less than operator - /// \param[in] _time the time to compare with - /// \return true if time is shorter than this, false otherwise - public: bool operator<(const Time &_time) const; - - /// \brief Less than operator - /// \param[in] _time the time to compare with - /// \return true if time is shorter than this, false otherwise - public: bool operator<(double _time) const; - - /// \brief Less than or equal to operator - /// \param[in] _time the time to compare with - /// \return true if time is shorter than or equal to this, false otherwise - public: bool operator<=(const Time &_time) const; - - /// \brief Less than or equal to operator - /// \param[in] _time the time to compare with - /// \return true if time is shorter than or equal to this, false otherwise - public: bool operator<=(double _time) const; - - /// \brief Greater than operator - /// \param[in] _tv the time to compare with - /// \return true if time is greater than this, false otherwise - public: bool operator>(const struct timespec &_tv) const; - - /// \brief Greater than operator - /// \param[in] _time the time to compare with - /// \return true if time is greater than this, false otherwise - public: bool operator>(const Time &_time) const; - - /// \brief Greater than operator - /// \param[in] _time the time to compare with - /// \return true if time is greater than this, false otherwise - public: bool operator>(double _time) const; - - /// \brief Greater than or equal operator - /// \param[in] _time the time to compare with - /// \return true if time is greater than or equal to this, false otherwise - public: bool operator>=(const Time &_time) const; - - /// \brief Greater than or equal operator - /// \param[in] _tv the time to compare with - /// \return true if tv is greater than or equal to this, false otherwise - public: bool operator>=(const struct timespec &_tv) const; - - /// \brief Greater than or equal operator - /// \param[in] _time the time to compare with - /// \return true if time is greater than or equal to this, false otherwise - public: bool operator>=(double _time) const; - - /// \brief Stream insertion operator - /// \param[in] _out the output stream - /// \param[in] _time time to write to the stream - /// \return the output stream - public: friend std::ostream &operator<<(std::ostream &_out, - const ignition::common::Time &_time) - { - _out << _time.sec << " " << _time.nsec; - return _out; - } - - /// \brief Stream extraction operator - /// \param[in] _in the input stream - /// \param[in] _time time to read from to the stream - /// \return the input stream - public: friend std::istream &operator>>(std::istream &_in, - ignition::common::Time &_time) - { - // Skip white spaces - _in.setf(std::ios_base::skipws); - _in >> _time.sec >> _time.nsec; - return _in; - } - - /// \brief Seconds - public: int32_t sec; - - /// \brief Nanoseconds - public: int32_t nsec; - - /// \brief a singleton value of the last GetWallTime() value - private: static Time wallTime; - - /// \brief Correct the time so that small additions/substractions - /// preserve the internal seconds and nanoseconds separation - private: inline void Correct() - { - // In the case sec and nsec have different signs, normalize - if (this->sec > 0 && this->nsec < 0) - { - int32_t n = abs(this->nsec / this->nsInSec) + 1; - this->sec -= n; - this->nsec += n * this->nsInSec; - } - if (this->sec < 0 && this->nsec > 0) - { - int32_t n = abs(this->nsec / this->nsInSec) + 1; - this->sec += n; - this->nsec -= n * this->nsInSec; - } - - // Make any corrections - this->sec += this->nsec / this->nsInSec; - this->nsec = this->nsec % this->nsInSec; - } - - /// \brief Constant multiplier to convert from nanoseconds to seconds. - private: static const int32_t nsInSec; - - /// \brief Constant multiplier to convert from nanoseconds to - /// milliseconds. - private: static const int32_t nsInMs; - - private: static struct timespec clockResolution; - }; - } -} -#endif +#include +#include diff --git a/include/ignition/common/Timer.hh b/include/ignition/common/Timer.hh index 6e10e66e6..baa130ace 100644 --- a/include/ignition/common/Timer.hh +++ b/include/ignition/common/Timer.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,58 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_TIMER_HH_ -#define IGNITION_COMMON_TIMER_HH_ + */ -#include -#include - -namespace ignition -{ - namespace common - { - /// \class Timer Timer.hh common/common.hh - /// \brief A timer class, used to time things in real world walltime - class IGNITION_COMMON_VISIBLE Timer - { - /// \brief Constructor - public: Timer(); - - /// \brief Destructor - public: virtual ~Timer(); - - /// \brief Start the timer - public: virtual void Start(); - - /// \brief Stop the timer - public: virtual void Stop(); - - /// \brief Returns true if the timer is running. - /// \return Tue if the timer has been started and not stopped. - public: bool Running() const; - - /// \brief Get the elapsed time - /// \return The time - public: Time Elapsed() const; - - /// \brief Stream operator friendly - public: friend std::ostream &operator<<(std::ostream &out, - const ignition::common::Timer &t) - { - out << t.Elapsed(); - return out; - } - - /// \brief The time of the last call to Start - private: Time start; - - /// \brief The time when Stop was called. - private: Time stop; - - /// \brief True if the timer is running. - private: bool running; - }; - } -} -#endif +#include +#include diff --git a/include/ignition/common/URI.hh b/include/ignition/common/URI.hh index 9c8ade21a..a1816db26 100644 --- a/include/ignition/common/URI.hh +++ b/include/ignition/common/URI.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,341 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_URI_HH_ -#define IGNITION_COMMON_URI_HH_ + */ -#include -#include - -#include -#include - -namespace ignition -{ - namespace common - { - // Forward declare private data classes. - class URIPathPrivate; - class URIQueryPrivate; - class URIFragmentPrivate; - class URIPrivate; - - /// \brief The path component of a URI - class IGNITION_COMMON_VISIBLE URIPath - { - /// \brief Constructor - public: URIPath(); - - /// \brief Copy constructor. - /// \param[in] _path Another URIPath. - public: URIPath(const URIPath &_path); - - /// \brief Construct a URIPath object from a string. - /// \param[in] _str A string. - public: explicit URIPath(const std::string &_str); - - /// \brief Destructor - public: virtual ~URIPath(); - - /// \brief Remove all parts of the path - public: void Clear(); - - /// \brief Returns whether the path is absolute or not. - /// \return Whether the path is absolute or not. - public: bool IsAbsolute() const; - - /// \brief Set whether the path is to be treated absolute or not. - /// \param[in] _absolute Whether the path is to be treated absolute or - /// not. - /// \note If this path starts with a Windows drive specifier (e.g. 'C:'), - /// it cannot be set non-absolute. - public: void SetAbsolute(bool _absolute = true); - - /// \brief Set the path to be relative. - /// \note If this path starts with a Windows drive specifier (e.g. 'C:'), - /// it cannot be set relative. - public: void SetRelative(); - - /// \brief Push a new part onto the front of this path. - /// \param[in] _part Path part to push - /// Empty _part is ignored. If _part starts with /, the path is set to - /// absolute (though calling SetAbsolute() is the preferred method). All - /// forward slashes inside the string are URI-encoded to %2F. The path is - /// also set to absolute if a Windows drive specifier (e.g. 'C:') is - /// pushed to the front. - public: void PushFront(const std::string &_part); - - /// \brief Push a new part onto the back of this path. - /// \param[in] _part Path part to push - /// \sa operator/ - /// Empty _part is ignored. If _part starts with / and the path is empty, - /// the path is set to absolute (though calling SetAbsolute() is the - /// preferred method). All forward slashes inside the string are - /// URI-encoded to %2F. The path is also set to absolute if it is empty - /// and a Windows drive specifier (e.g. 'C:') is pushed to it. - public: void PushBack(const std::string &_part); - - /// \brief Compound assignment operator. - /// \param[in] _part A new path to append. - /// \return A new Path that consists of "this / _part" - public: const URIPath &operator/=(const std::string &_part); - - /// \brief Get the current path with the _part added to the end. - /// \param[in] _part Path part. - /// \return A new Path that consists of "this / _part" - /// \sa PushBack - public: const URIPath operator/(const std::string &_part) const; - - /// \brief Return true if the two paths match. - /// \param[in] _part Path part. - /// return True of the paths match. - public: bool operator==(const URIPath &_path) const; - - /// \brief Get the path as a string. - /// \param[in] _delim Delimiter used to separate each part of the path. - /// \return The path as a string, with each path part separated by _delim. - public: std::string Str(const std::string &_delim = "/") const; - - /// \brief Assignment operator. - /// \param[in] _path Another URIPath. - /// \return Itself. - public: URIPath &operator=(const URIPath &_path); - - /// \brief Return true if the string is a valid path. - /// \param[in] _str String to check. - /// \return True if _str is a valid URI path. - public: static bool Valid(const std::string &_str); - - /// \brief Return true if this is a valid path. - /// \return True if this is a valid URI path. - public: bool Valid() const; - - /// \brief Parse a string as URIPath. - /// \param[in] _str A string. - /// \return True if the string could be parsed as a URIPath. - public: bool Parse(const std::string &_str); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \internal - /// \brief Pointer to private data. - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - - /// \brief The query component of a URI - class IGNITION_COMMON_VISIBLE URIQuery - { - /// \brief Constructor - public: URIQuery(); - - /// \brief Construct a URIQuery object from a string. - /// \param[in] _str A string. - public: explicit URIQuery(const std::string &_str); - - /// \brief Copy constructor - /// \param[in] _query Another query component - public: URIQuery(const URIQuery &_query); - - /// \brief Destructor - public: virtual ~URIQuery(); - - /// \brief Remove all values of the query - public: void Clear(); - - /// \brief Get this query with a new _key=_value pair added. - /// \param[in] _key Key of the query. - /// \param[in] _value Value of the query. - public: void Insert(const std::string &_key, - const std::string &_value); - - /// \brief Assignment operator. - /// \param[in] _query another URIQuery. - /// \return Itself. - public: URIQuery &operator=(const URIQuery &_query); - - /// \brief Return true if the two queries contain the same values. - /// \param[in] _query A URI query to compare. - /// return True if the queries match. - public: bool operator==(const URIQuery &_query) const; - - /// \brief Get the query as a string. - /// \param[in] _delim Delimiter used to separate each tuple of the query. - /// \return The query as a string, with each key,value pair separated by - /// _delim. - public: std::string Str(const std::string &_delim = "&") const; - - /// \brief Check if a string is a valid URI query. - /// \param[in] _str The string to check. - /// \return True if the string can be parsed as a URI query. - public: static bool Valid(const std::string &_str); - - /// \brief Check if this is a valid URI query. - /// \return True if this can be parsed as a URI query. - public: bool Valid() const; - - /// \brief Parse a string as URIQuery. - /// \param[in] _str A string. - /// \return True if the string can be parsed as a URIQuery. - public: bool Parse(const std::string &_string); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \internal - /// \brief Pointer to private data. - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - - /// \brief The fragment component of a URI - class IGNITION_COMMON_VISIBLE URIFragment - { - /// \brief Constructor - public: URIFragment(); - - /// \brief Construct a URIFragment object from a string. - /// \param[in] _str A string. - public: explicit URIFragment(const std::string &_str); - - /// \brief Copy constructor - /// \param[in] _fragment Another fragment component - public: URIFragment(const URIFragment &_fragment); - - /// \brief Destructor - public: virtual ~URIFragment(); - - /// \brief Remove all values of the fragment - public: void Clear(); - - /// \brief Assignment operator. - /// \param[in] _fragment another URIFragment. - /// \return Itself. - public: URIFragment &operator=(const URIFragment &_fragment); - - /// \brief Assignment operator. - /// \param[in] _fragment another URIFragment. - /// \return Itself. - public: URIFragment &operator=(const std::string &_fragment); - - /// \brief Return true if the two fragments contain the same values. - /// \param[in] _fragment A URI fragment to compare. - /// return True if the fragments match. - public: bool operator==(const URIFragment &_fragment) const; - - /// \brief Get the fragment as a string. - /// \return The fragment as a string. - public: std::string Str() const; - - /// \brief Check if a string is a valid URI fragment. - /// \param[in] _str The string to check. - /// \return True if the string can be parsed as a URI fragment. - public: static bool Valid(const std::string &_str); - - /// \brief Check if this is a valid URI fragment. - /// \return True if this can be parsed as a URI fragment. - public: bool Valid() const; - - /// \brief Parse a string as URIFragment. - /// \param[in] _str A string. - /// \return True if the string can be parsed as a URIFragment. - public: bool Parse(const std::string &_string); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \internal - /// \brief Pointer to private data. - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - - /// \brief A complete URI - // cppcheck-suppress class_X_Y - class IGNITION_COMMON_VISIBLE URI - { - /// \brief Default constructor - public: URI(); - - /// \brief Construct a URI object from a string. - /// \param[in] _str A string. - public: explicit URI(const std::string &_str); - - /// \brief Copy constructor - /// \param[in] _uri Another URI. - public: URI(const URI &_uri); - - /// \brief Destructor. - public: ~URI(); - - /// \brief Get the URI as a string, which has the form: - /// - /// scheme://path?query - /// - /// \return The full URI as a string - public: std::string Str() const; - - /// \brief Remove all components of the URI - public: void Clear(); - - /// \brief Get the URI's scheme - /// \return The scheme - public: std::string Scheme() const; - - /// \brief Set the URI's scheme - /// \param[in] _scheme New scheme. - public: void SetScheme(const std::string &_scheme); - - /// \brief Get a mutable version of the path component - /// \return A reference to the path - public: URIPath &Path(); - - /// \brief Get a const reference of the path component. - /// \return A const reference of the path. - public: const URIPath &Path() const; - - /// \brief Get a mutable version of the query component - /// \return A reference to the query - public: URIQuery &Query(); - - /// \brief Get a const reference of the query component. - /// \return A const reference of the query. - public: const URIQuery &Query() const; - - /// \brief Get a mutable version of the fragment component. - /// \return A reference to the fragment. - public: URIFragment &Fragment(); - - /// \brief Get a const reference of the fragment component. - /// \return A const reference of the fragment. - public: const URIFragment &Fragment() const; - - /// \brief Assignment operator. - /// \param[in] _uri Another URI. - /// \return Itself. - public: URI &operator=(const URI &_uri); - - /// \brief Return true if the two URIs match. - /// \param[in] _uri Another URI to compare. - /// \return True if the two URIs match. - public: bool operator==(const URI &_uri) const; - - /// \brief Validate this URI. - /// \return True if this can be parsed as a URI. - public: bool Valid() const; - - /// \brief Validate a string as URI. - /// \param[in] _str The string to validate. - /// \return True if the string can be parsed as a URI. - public: static bool Valid(const std::string &_str); - - /// \brief Parse a string as URI. - /// \param[in] _str A string. - /// \return True if the string can be parsed as a URI. - public: bool Parse(const std::string &_str); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \internal - /// \brief Pointer to private data. - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} -#endif +#include +#include diff --git a/include/ignition/common/Util.hh b/include/ignition/common/Util.hh index 5390d08ca..8300d84f8 100644 --- a/include/ignition/common/Util.hh +++ b/include/ignition/common/Util.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,323 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_UTIL_HH_ -#define IGNITION_COMMON_UTIL_HH_ + */ -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -///////////////////////////////////////////////// -// Defines - -#ifdef _WIN32 -# define IGN_HOMEDIR "USERPROFILE" -#else -# define IGN_HOMEDIR "HOME" -#endif - -/// \brief Seconds in one nano second. -#define IGN_NANO_TO_SEC 1e-9 - -/// \brief Nano seconds in one second. -#define IGN_SEC_TO_NANO 1000000000 - -/// \brief Nano seconds in one millisecond. -#define IGN_MS_TO_NANO 1000000 - -/// \brief Nano seconds in one microsecond. -#define IGN_US_TO_NANO 1000 - -/// \brief Speed of light. -#define IGN_SPEED_OF_LIGHT = 299792458.0 - -/// \brief Sleep for the specifed number of seconds -#define IGN_SLEEP_S(_s) (std::this_thread::sleep_for(\ - std::chrono::seconds(_s))) - -/// \brief Sleep for the specifed number of microseconds -#define IGN_SLEEP_US(_us) (std::this_thread::sleep_for(\ - std::chrono::microseconds(_us))) - -/// \brief Sleep for the specifed number of milliseconds -#define IGN_SLEEP_MS(_ms) (std::this_thread::sleep_for(\ - std::chrono::milliseconds(_ms))) - -/// \brief Sleep for the specifed number of nanoseconds -#define IGN_SLEEP_NS(_ns) (std::this_thread::sleep_for(\ - std::chrono::nanoseconds(_ns))) - -/// \brief Get the system time. -#define IGN_SYSTEM_TIME() (std::chrono::system_clock::now()) - -/// \brief Get the system time in seconds since epoch. -#define IGN_SYSTEM_TIME_S() (std::chrono::duration_cast(\ - std::chrono::system_clock::now().time_since_epoch()).count()) - -/// \brief Get the system time in microseconds since epoch. -#define IGN_SYSTEM_TIME_US() (\ - std::chrono::duration_cast(\ - std::chrono::system_clock::now().time_since_epoch()).count()) - -/// \brief Get the system time in milliseconds since epoch. -#define IGN_SYSTEM_TIME_MS() (\ - std::chrono::duration_cast(\ - std::chrono::system_clock::now().time_since_epoch()).count()) - -/// \brief Get the system time in nanoseconds since epoch. -#define IGN_SYSTEM_TIME_NS() (\ - std::chrono::duration_cast(\ - std::chrono::system_clock::now().time_since_epoch()).count()) - -/// \brief This macro defines the standard way of launching an exception -/// inside ignition. -#define IGN_ASSERT(_expr, _msg) assert((_msg, _expr)) - -/// \brief Forward declarations for the common classes -namespace ignition -{ - namespace common - { - /// \brief Enumeration of the transform types - enum NodeTransformType {TRANSLATE, ROTATE, SCALE, MATRIX}; - - /// \brief A runtime error. - typedef std::runtime_error exception; - - /// \brief Please use systemTimeIso() as this function will be deprecated - /// in Ignition Common 4. - /// Get the wall time as an ISO string: YYYY-MM-DDTHH:MM:SS.NS - /// \return The current wall time as an ISO string. - /// \sa systemTimeIso(); - std::string IGNITION_COMMON_VISIBLE systemTimeISO(); - - /// \brief Get the wall time as an ISO string: YYYY-MM-DDTHH:MM:SS.NS - /// \return The current wall time as an ISO string. - std::string IGNITION_COMMON_VISIBLE systemTimeIso(); - - /// \brief Converts a time point to an ISO string: YYYY-MM-DDTHH:MM:SS.NS - /// \param[in] _time A time point, such as one created by - /// IGN_SYSTEM_TIME(). - /// \return An ISO string that represents the given _time. - std::string IGNITION_COMMON_VISIBLE timeToIso( - const std::chrono::time_point &_time); - - /// \brief Get the log path - /// \return the log path - std::string IGNITION_COMMON_VISIBLE logPath(); - - /// \brief add path suffix to common::SystemPaths - /// \param[in] _suffix The suffix to add. - void IGNITION_COMMON_VISIBLE addSearchPathSuffix( - const std::string &_suffix); - - /// \brief search for file in common::SystemPaths - /// \param[in] _file Name of the file to find. - /// \return The path containing the file. - std::string IGNITION_COMMON_VISIBLE findFile(const std::string &_file); - - /// \brief search for file in common::SystemPaths - /// \param[in] _file Name of the file to find. - /// \param[in] _searchLocalPath True to search in the current working - /// directory. - /// \return The path containing the file. - std::string IGNITION_COMMON_VISIBLE findFile(const std::string &_file, - bool _searchLocalPath); - - /// \brief search for a file in common::SystemPaths - /// \param[in] _file the file name to look for. - /// \return The path containing the file. - std::string IGNITION_COMMON_VISIBLE findFilePath(const std::string &_file); - - /// \brief Add a callback to use when findFile() can't find a file that is - /// a valid URI. - /// The callback should return a full local path to the requested file, or - /// and empty string if the file was not found in the callback. - /// Callbacks will be called in the order they were added until a path is - /// found. - /// \param[in] _cb The callback function, which takes a file path or URI - /// and returns the full local path. - void IGNITION_COMMON_VISIBLE addFindFileURICallback( - std::function _cb); - - /// \brief Get a pointer to the global system paths that is used by all - /// the findFile functions. - /// The returned instance has global shared state for a given process. - /// Care should be taken when manipulating global system paths - /// Caller should not assume ownership of the pointer. - /// \return A mutable reference to the system paths object. - common::SystemPaths IGNITION_COMMON_VISIBLE *systemPaths(); - - /// \brief Compute the SHA1 hash of an array of bytes. - /// \param[in] _buffer Input sequence. The permitted data types for this - /// function are std::string and any STL container. - /// \return The string representation (40 character) of the SHA1 hash. - template - std::string sha1(const T &_buffer); - - /// \brief Compute the SHA1 hash of an array of bytes. Use std::string - /// sha1(const T &_buffer) instead of this function - /// \param[in] _buffer Input sequence. The permitted data types for this - /// function are std::string and any STL container. - /// \return The string representation (40 character) of the SHA1 hash. - /// \sa sha1(const T &_buffer) - std::string IGNITION_COMMON_VISIBLE sha1( - void const *_buffer, std::size_t _byteCount); - - /// \brief fnv1a algorithm for 64-bit platforms. - /// \param[in] _key The input string. - /// \return A 64-bit unsigned hash value. - /// \ref https://notes.underscorediscovery.com/constexpr-fnv1a/ - constexpr uint64_t IGNITION_COMMON_VISIBLE hash64(std::string_view _key) - { - const char *data = _key.data(); - const auto len = _key.size(); - const uint64_t prime = 0x100000001b3; - uint64_t hash = 0xcbf29ce484222325; - - for (auto i = 0u; i < len; ++i) - { - uint8_t value = static_cast(data[i]); - hash = hash ^ value; - hash *= prime; - } - - return hash; - } - - /// \brief Find the environment variable '_name' and return its value. - /// - /// \TODO(mjcarroll): Deprecate and remove in tick-tock. - /// - /// \param[in] _name Name of the environment variable. - /// \param[out] _value Value if the variable was found. - /// \return True if the variable was found or false otherwise. - bool IGNITION_COMMON_VISIBLE env( - const std::string &_name, std::string &_value); - - /// \brief Find the environment variable '_name' and return its value. - /// \param[in] _name Name of the environment variable. - /// \param[out] _value Value if the variable was found. - /// \param[in] _allowEmpty Allow set-but-empty variables. - /// (Unsupported on Windows) - /// \return True if the variable was found or false otherwise. - bool IGNITION_COMMON_VISIBLE env( - const std::string &_name, std::string &_value, - bool _allowEmpty); - - /// \brief Set the environment variable '_name'. - /// - /// Note that on Windows setting an empty string (_value=="") - /// is the equivalent of unsetting the variable. - /// - /// \param[in] _name Name of the environment variable. - /// \param[in] _value Value of the variable to be set. - /// \return True if the variable was set or false otherwise. - bool IGNITION_COMMON_VISIBLE setenv( - const std::string &_name, const std::string &_value); - - /// \brief Unset the environment variable '_name'. - /// \param[in] _name Name of the environment variable. - /// \return True if the variable was unset or false otherwise. - bool IGNITION_COMMON_VISIBLE unsetenv(const std::string &_name); - - /// \brief Get a UUID - /// \return A UUID string - std::string IGNITION_COMMON_VISIBLE uuid(); - - /// \brief Splits a string into tokens. - /// \param[in] _str Input string. - /// \param[in] _delim Token delimiter. - /// \return Vector of tokens. - std::vector IGNITION_COMMON_VISIBLE split( - const std::string &_str, const std::string &_delim); - - /// \brief In place left trim - /// \param[in,out] _s String to trim - void IGNITION_COMMON_VISIBLE ltrim(std::string &_s); - - /// \brief In place right trim - /// \param[in,out] _s String to trim - void IGNITION_COMMON_VISIBLE rtrim(std::string &_s); - - /// \brief In place trim from both ends - /// \param[in,out] _s String to trim - void IGNITION_COMMON_VISIBLE trim(std::string &_s); - - /// \brief Copying left trim - /// \param[in] _s String to trim - /// \return Trimmed string - std::string IGNITION_COMMON_VISIBLE ltrimmed(std::string _s); - - /// \brief Copying right trim - /// \param[in] _s String to trim - /// \return Trimmed string - std::string IGNITION_COMMON_VISIBLE rtrimmed(std::string _s); - - /// \brief Copying trim from both ends - /// \param[in] _s String to trim - /// \return Trimmed string - std::string IGNITION_COMMON_VISIBLE trimmed(std::string _s); - - /// \brief Transforms a string to its lowercase equivalent - /// \param[in] _in String to convert to lowercase - /// \return Lowercase equilvalent of _in. - std::string IGNITION_COMMON_VISIBLE lowercase(const std::string &_in); - - /// \brief Transforms a string to its lowercase equivalent - /// \param[in] _in String to convert to lowercase - /// \return Lowercase equilvalent of _in. - std::string IGNITION_COMMON_VISIBLE lowercase(const char *_in); - - /// \brief Replace all occurances of _key with _replacement. - /// \param[out] _result The new string that has had _key replaced - /// with _replacement. - /// \param[in] _orig Original string. - /// \param[in] _key String to replace. - /// \param[in] _replacement The string that replaces _key. - /// \sa std::string replaceAll(const std::string &_orig, - /// const std::string &_key, const std::string &_replacement) - void IGNITION_COMMON_VISIBLE replaceAll(std::string &_result, - const std::string &_orig, - const std::string &_key, - const std::string &_replacement); - - /// \brief Replace all occurances of _key with _replacement. - /// \param[in] _orig Original string. - /// \param[in] _key String to replace. - /// \param[in] _replacement The string that replaces _key. - /// \return The new string that has had _key replaced with _replacement. - /// \sa void common::replaceAll(std::string &_result, - /// const std::string &_orig, const std::string &_key, - /// const std::string &_replacement) - std::string IGNITION_COMMON_VISIBLE replaceAll(const std::string &_orig, - const std::string &_key, - const std::string &_replacement); - } -} - -/////////////////////////////////////////////// -// Implementation of get_sha1 -template -std::string ignition::common::sha1(const T &_buffer) -{ - if (_buffer.size() == 0) - return ignition::common::sha1(NULL, 0); - else - { - return ignition::common::sha1( - &(_buffer[0]), _buffer.size() * sizeof(_buffer[0])); - } -} -#endif +#include +#include diff --git a/include/ignition/common/Uuid.hh b/include/ignition/common/Uuid.hh index d9718951f..a92225277 100644 --- a/include/ignition/common/Uuid.hh +++ b/include/ignition/common/Uuid.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,63 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ -#ifndef IGNITION_COMMON_UUID_HH_INCLUDED_ -#define IGNITION_COMMON_UUID_HH_INCLUDED_ + */ -#include -#include - -#include - -#ifdef _WIN32 - #include - #pragma comment(lib, "Rpcrt4.lib") - using portable_uuid_t = UUID; -// else unix -#else - #include - using portable_uuid_t = uuid_t; -#endif - -namespace ignition -{ - namespace common - { - /// \brief A portable class for representing a Universally Unique Identifier - class IGNITION_COMMON_VISIBLE Uuid - { - /// \brief Constructor. - public: Uuid(); - - /// \brief Destructor. - public: virtual ~Uuid(); - - /// \brief Return the string representation of the Uuid. - /// \return the UUID in string format. - public: std::string String() const; - - /// \brief Stream insertion operator. - /// \param[out] _out The output stream. - /// \param[in] _msg AdvMsg to write to the stream. - public: friend std::ostream &operator<<(std::ostream &_out, - const ignition::common::Uuid &_uuid) - { - _out << _uuid.String(); - return _out; - } - - /// \brief Length of a UUID in string format. - /// A UUID is a 16-octet number. In its string representation, every octet - /// is divided in two parts, and each part (4 bits) is represented as an - /// hexadecimal value. A UUID is also displayed in five groups separated - /// by hyphens, in the form 8-4-4-4-12 for a total of 36 characters. - /// To summarize: 36 octets + \0 = 37 octets. - private: static const int UuidStrLen = 37; - - /// \brief Internal representation. - private: portable_uuid_t data; - }; - } -} -#endif +#include +#include diff --git a/include/ignition/common/WorkerPool.hh b/include/ignition/common/WorkerPool.hh index 64d5d14ac..9e6833f36 100644 --- a/include/ignition/common/WorkerPool.hh +++ b/include/ignition/common/WorkerPool.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,60 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * -*/ + */ -#ifndef IGNITION_COMMON_WORKER_POOL_HH_ -#define IGNITION_COMMON_WORKER_POOL_HH_ - -#include -#include - -#include -#include -#include - -namespace ignition -{ - namespace common - { - /// \brief forward declaration - class WorkerPoolPrivate; - - /// \brief A pool of worker threads that do stuff in parallel - class IGNITION_COMMON_VISIBLE WorkerPool - { - /// \brief Creates worker threads. The number of worker threads is - /// determined by max(std::thread::hardware_concurrency, _minThreadCount). - /// \param[in] _minThreadCount The minimum number of threads to - /// create in the pool. A value of zero is converted to a value of 1. - /// \note It's not recommended to set _minThreadCount greater than - /// std::thread::hardware_concurrency. - public: explicit WorkerPool(const unsigned int _minThreadCount = 1u); - - /// \brief closes worker threads - public: ~WorkerPool(); - - /// \brief Adds work to the worker pool with optional callback - /// \param[in] _work function to do one piece of work - /// \param[in] _cb optional callback when the work is done - /// \remark Typical work is a function bound with arguments. It must - // return within a finite amount of time. - public: void AddWork(std::function _work, - std::function _cb = std::function()); - - /// \brief Waits until all work is done and threads are idle - /// \param[in] _timeout How long to wait, default to forever - /// \returns true if all work was finished - /// \remarks The return value can be false even when waiting forever if - // the WorkerPool is destructed before all work is completed - public: bool WaitForResults(const Time &_timeout = Time::Zero); - - IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING - /// \brief private implementation pointer - private: std::unique_ptr dataPtr; - IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING - }; - } -} - -#endif +#include +#include diff --git a/include/ignition/common/config.hh b/include/ignition/common/config.hh new file mode 100644 index 000000000..cb276a428 --- /dev/null +++ b/include/ignition/common/config.hh @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2022 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef IGNITION_COMMON__CONFIG_HH_ +#define IGNITION_COMMON__CONFIG_HH_ + +#include +#endif diff --git a/profiler/include/CMakeLists.txt b/profiler/include/CMakeLists.txt new file mode 100644 index 000000000..4b2bdd7bb --- /dev/null +++ b/profiler/include/CMakeLists.txt @@ -0,0 +1,2 @@ +add_subdirectory(gz) +install(DIRECTORY ignition DESTINATION ${IGN_INCLUDE_INSTALL_DIR_FULL}) diff --git a/profiler/include/gz/common/Profiler.hh b/profiler/include/gz/common/Profiler.hh new file mode 100644 index 000000000..ef218f83f --- /dev/null +++ b/profiler/include/gz/common/Profiler.hh @@ -0,0 +1,165 @@ +/* + * Copyright (C) 2018 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GZ_COMMON_PROFILER_HH_ +#define GZ_COMMON_PROFILER_HH_ + +#include +#include + +#include +#include +#include + +namespace ignition +{ + namespace common + { + class ProfilerImpl; + + /// \brief Used to perform application-wide performance profiling + /// + /// This class provides the necessary infrastructure for recording profiling + /// information of an application while it is running. The actual profiler + /// implementation can be choosen at runtime, and is invoked through a + /// series of macros found below. + /// + /// In general, users shouldn't directly interface with this class, + /// but instead use the profiling macros, which can be enabled/disabled + /// at compile time, which eliminates any performance impact of profiling. + /// + /// Profiler is enabled by setting IGN_ENABLE_PROFILER at compile time. + /// + /// The profiler header also exports several convenience macros to make + /// adding inspection points easier. + /// + /// * IGN_PROFILE_THREAD_NAME - Set the name of the current profiled thread. + /// * IGN_PROFILE_LOG_TEXT - Log text to the profiler console (if supported) + /// * IGN_PROFILE_BEGIN - Begin a named profile sample + /// * IGN_PROFILE_END - End a named profile sample + /// * IGN_PROFILE - RAII-style profile sample. The sample will end at the + /// end of the current scope. + class IGNITION_COMMON_PROFILER_VISIBLE Profiler + : public virtual SingletonT + { + /// \brief Constructor + protected: Profiler(); + + /// \brief Destructor + protected: ~Profiler(); + + /// \brief Set the name of the current thread + /// \param[in] _name Name to set + public: void SetThreadName(const char *_name); + + /// \brief Log text to profiler output (if supported) + /// If the underlying profiler implementation supports additional + /// log messages, this can be used to send. + /// + /// Currently, the Remotery implentation supports this functionality. + /// \param[in] _text Text to log. + public: void LogText(const char *_text); + + /// \brief Begin a named profiling sample. + /// Begins a CPU profiler sample with a given name. Can optionally take + /// a hash parameter to be cached between executions of `BeginSample`, so + /// that hashes don't need to be recomputed. + /// \param[in] _name Name of the sample + /// \param[in,out] _hash An optional hash value that can be cached + /// between executions. + public: void BeginSample(const char *_name, uint32_t *_hash = nullptr); + + /// \brief End a profiling sample. + public: void EndSample(); + + /// \brief Get the underlying profiler implentation name + public: std::string ImplementationName() const; + + /// \brief Detect if profiler is enabled and has an implementation + public: bool Valid() const; + + /// \brief Pointer to the profiler implementation + private: ProfilerImpl *impl; + + /// \brief Needed for SingletonT. + private: friend class SingletonT; + }; + + /// \brief Used to provide C++ RAII-style profiling sample. + /// The sample will start on the construction of the `ScopedProfile` object + /// and stop when the object leaves scope. + class IGNITION_COMMON_PROFILER_VISIBLE ScopedProfile + { + /// \brief Constructor. Starts profile sample. + /// \param[in] _name Name of the sample + /// \param[in,out] _hash An optional hash value that can be cached + /// between executions. + public: ScopedProfile(const char *_name, uint32_t *_hash) + { + Profiler::Instance()->BeginSample(_name, _hash); + } + + /// \brief Destructor. Stops profile sample. + public: ~ScopedProfile() + { + Profiler::Instance()->EndSample(); + } + }; + } +} + +#ifndef IGN_PROFILER_ENABLE +/// Always set this variable to some value +#define IGN_PROFILER_ENABLE 0 +#endif + +#if IGN_PROFILER_ENABLE +/// \brief Set name of profiled thread +#define IGN_PROFILE_THREAD_NAME(name) \ + ignition::common::Profiler::Instance()->SetThreadName(name); +/// \brief Log profiling text, if supported by implementation +#define IGN_PROFILE_LOG_TEXT(name) \ + ignition::common::Profiler::Instance()->LogText(name); +/// \brief Being profiling sample +#define IGN_PROFILE_BEGIN(name) \ + ignition::common::Profiler::Instance()->BeginSample(name) +/// \brief End profiling sample +#define IGN_PROFILE_END() \ + ignition::common::Profiler::Instance()->EndSample() + +/// \brief Convenience wrapper for scoped profiling sample. Use IGN_PROFILE +#define IGN_PROFILE_L(name, line) \ +static uint32_t __hash##line = 0; \ +gz::common::ScopedProfile __profile##line(name, &__hash##line); +/// \brief Scoped profiling sample. Sample will stop at end of scope. +#define IGN_PROFILE(name) IGN_PROFILE_L(name, __LINE__); + +#else + +#define IGN_PROFILE_THREAD_NAME(name) ((void) name) +#define IGN_PROFILE_LOG_TEXT(name) ((void) name) +#define IGN_PROFILE_BEGIN(name) ((void) name) +#define IGN_PROFILE_END() ((void) 0) +#define IGN_PROFILE_L(name, line) ((void) name) +#define IGN_PROFILE(name) ((void) name) +#endif // IGN_PROFILER_ENABLE + +/// \brief Macro to determine if profiler is enabled and has an implementation. +#define IGN_PROFILER_VALID \ + IGN_PROFILER_ENABLE && ignition::common::Profiler::Instance()->Valid() + +#endif // GZ_COMMON_PROFILER_HH_ diff --git a/profiler/include/ignition/common/Profiler.hh b/profiler/include/ignition/common/Profiler.hh index 8190a113b..0857564ce 100644 --- a/profiler/include/ignition/common/Profiler.hh +++ b/profiler/include/ignition/common/Profiler.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 Open Source Robotics Foundation + * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,151 +15,5 @@ * */ -#ifndef IGNITION_COMMON_PROFILER_HH_ -#define IGNITION_COMMON_PROFILER_HH_ - -#include -#include - -#include -#include +#include #include - -namespace ignition -{ - namespace common - { - class ProfilerImpl; - - /// \brief Used to perform application-wide performance profiling - /// - /// This class provides the necessary infrastructure for recording profiling - /// information of an application while it is running. The actual profiler - /// implementation can be choosen at runtime, and is invoked through a - /// series of macros found below. - /// - /// In general, users shouldn't directly interface with this class, - /// but instead use the profiling macros, which can be enabled/disabled - /// at compile time, which eliminates any performance impact of profiling. - /// - /// Profiler is enabled by setting IGN_ENABLE_PROFILER at compile time. - /// - /// The profiler header also exports several convenience macros to make - /// adding inspection points easier. - /// - /// * IGN_PROFILE_THREAD_NAME - Set the name of the current profiled thread. - /// * IGN_PROFILE_LOG_TEXT - Log text to the profiler console (if supported) - /// * IGN_PROFILE_BEGIN - Begin a named profile sample - /// * IGN_PROFILE_END - End a named profile sample - /// * IGN_PROFILE - RAII-style profile sample. The sample will end at the - /// end of the current scope. - class IGNITION_COMMON_PROFILER_VISIBLE Profiler - : public virtual SingletonT - { - /// \brief Constructor - protected: Profiler(); - - /// \brief Destructor - protected: ~Profiler(); - - /// \brief Set the name of the current thread - /// \param[in] _name Name to set - public: void SetThreadName(const char *_name); - - /// \brief Log text to profiler output (if supported) - /// If the underlying profiler implementation supports additional - /// log messages, this can be used to send. - /// - /// Currently, the Remotery implentation supports this functionality. - /// \param[in] _text Text to log. - public: void LogText(const char *_text); - - /// \brief Begin a named profiling sample. - /// Begins a CPU profiler sample with a given name. Can optionally take - /// a hash parameter to be cached between executions of `BeginSample`, so - /// that hashes don't need to be recomputed. - /// \param[in] _name Name of the sample - /// \param[in,out] _hash An optional hash value that can be cached - /// between executions. - public: void BeginSample(const char *_name, uint32_t *_hash = nullptr); - - /// \brief End a profiling sample. - public: void EndSample(); - - /// \brief Get the underlying profiler implentation name - public: std::string ImplementationName() const; - - /// \brief Detect if profiler is enabled and has an implementation - public: bool Valid() const; - - /// \brief Pointer to the profiler implementation - private: ProfilerImpl *impl; - - /// \brief Needed for SingletonT. - private: friend class SingletonT; - }; - - /// \brief Used to provide C++ RAII-style profiling sample. - /// The sample will start on the construction of the `ScopedProfile` object - /// and stop when the object leaves scope. - class IGNITION_COMMON_PROFILER_VISIBLE ScopedProfile - { - /// \brief Constructor. Starts profile sample. - /// \param[in] _name Name of the sample - /// \param[in,out] _hash An optional hash value that can be cached - /// between executions. - public: ScopedProfile(const char *_name, uint32_t *_hash) - { - Profiler::Instance()->BeginSample(_name, _hash); - } - - /// \brief Destructor. Stops profile sample. - public: ~ScopedProfile() - { - Profiler::Instance()->EndSample(); - } - }; - } -} - -#ifndef IGN_PROFILER_ENABLE -/// Always set this variable to some value -#define IGN_PROFILER_ENABLE 0 -#endif - -#if IGN_PROFILER_ENABLE -/// \brief Set name of profiled thread -#define IGN_PROFILE_THREAD_NAME(name) \ - ignition::common::Profiler::Instance()->SetThreadName(name); -/// \brief Log profiling text, if supported by implementation -#define IGN_PROFILE_LOG_TEXT(name) \ - ignition::common::Profiler::Instance()->LogText(name); -/// \brief Being profiling sample -#define IGN_PROFILE_BEGIN(name) \ - ignition::common::Profiler::Instance()->BeginSample(name) -/// \brief End profiling sample -#define IGN_PROFILE_END() \ - ignition::common::Profiler::Instance()->EndSample() - -/// \brief Convenience wrapper for scoped profiling sample. Use IGN_PROFILE -#define IGN_PROFILE_L(name, line) \ -static uint32_t __hash##line = 0; \ -ignition::common::ScopedProfile __profile##line(name, &__hash##line); -/// \brief Scoped profiling sample. Sample will stop at end of scope. -#define IGN_PROFILE(name) IGN_PROFILE_L(name, __LINE__); - -#else - -#define IGN_PROFILE_THREAD_NAME(name) ((void) name) -#define IGN_PROFILE_LOG_TEXT(name) ((void) name) -#define IGN_PROFILE_BEGIN(name) ((void) name) -#define IGN_PROFILE_END() ((void) 0) -#define IGN_PROFILE_L(name, line) ((void) name) -#define IGN_PROFILE(name) ((void) name) -#endif // IGN_PROFILER_ENABLE - -/// \brief Macro to determine if profiler is enabled and has an implementation. -#define IGN_PROFILER_VALID \ - IGN_PROFILER_ENABLE && ignition::common::Profiler::Instance()->Valid() - -#endif // IGNITION_COMMON_PROFILER_HH_ diff --git a/profiler/include/ignition/common/profiler/Export.hh b/profiler/include/ignition/common/profiler/Export.hh new file mode 100644 index 000000000..a807b235c --- /dev/null +++ b/profiler/include/ignition/common/profiler/Export.hh @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2022 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include diff --git a/profiler/src/Profiler.cc b/profiler/src/Profiler.cc index 333eb13ef..8d6e13b6b 100644 --- a/profiler/src/Profiler.cc +++ b/profiler/src/Profiler.cc @@ -14,8 +14,8 @@ * limitations under the License. * */ -#include "ignition/common/Profiler.hh" // NOLINT(*) -#include "ignition/common/Console.hh" +#include "gz/common/Profiler.hh" // NOLINT(*) +#include "gz/common/Console.hh" #include "ProfilerImpl.hh" diff --git a/profiler/src/ProfilerImpl.hh b/profiler/src/ProfilerImpl.hh index 3d910fec6..82d3ddad2 100644 --- a/profiler/src/ProfilerImpl.hh +++ b/profiler/src/ProfilerImpl.hh @@ -15,8 +15,8 @@ * */ -#ifndef IGNITION_COMMON_PROFILERIMPL_HH_ -#define IGNITION_COMMON_PROFILERIMPL_HH_ +#ifndef GZ_COMMON_PROFILERIMPL_HH_ +#define GZ_COMMON_PROFILERIMPL_HH_ #include @@ -61,4 +61,4 @@ namespace ignition } } -#endif // IGNITION_COMMON_PROFILERIMPL_HH_ +#endif // GZ_COMMON_PROFILERIMPL_HH_ diff --git a/profiler/src/Profiler_Disabled_TEST.cc b/profiler/src/Profiler_Disabled_TEST.cc index c719434c7..3e4a17c50 100644 --- a/profiler/src/Profiler_Disabled_TEST.cc +++ b/profiler/src/Profiler_Disabled_TEST.cc @@ -15,13 +15,13 @@ * */ -#include "ignition/common/Profiler.hh" // NOLINT(*) +#include "gz/common/Profiler.hh" // NOLINT(*) #include // NOLINT(*) #include // NOLINT(*) #include // NOLINT(*) -#include "ignition/common/Util.hh" // NOLINT(*) -#include "ignition/common/Time.hh" // NOLINT(*) +#include "gz/common/Util.hh" // NOLINT(*) +#include "gz/common/Time.hh" // NOLINT(*) using namespace ignition; using namespace common; diff --git a/profiler/src/Profiler_Remotery_TEST.cc b/profiler/src/Profiler_Remotery_TEST.cc index 58a63a424..1181d6016 100644 --- a/profiler/src/Profiler_Remotery_TEST.cc +++ b/profiler/src/Profiler_Remotery_TEST.cc @@ -15,13 +15,13 @@ * */ -#include "ignition/common/Profiler.hh" // NOLINT(*) +#include "gz/common/Profiler.hh" // NOLINT(*) #include // NOLINT(*) #include // NOLINT(*) #include // NOLINT(*) -#include "ignition/common/Util.hh" // NOLINT(*) -#include "ignition/common/Time.hh" // NOLINT(*) +#include "gz/common/Util.hh" // NOLINT(*) +#include "gz/common/Time.hh" // NOLINT(*) using namespace ignition; using namespace common; diff --git a/profiler/src/RemoteryProfilerImpl.cc b/profiler/src/RemoteryProfilerImpl.cc index c78bdf0a9..bf3970ae9 100644 --- a/profiler/src/RemoteryProfilerImpl.cc +++ b/profiler/src/RemoteryProfilerImpl.cc @@ -15,11 +15,11 @@ * */ -#include "ignition/common/config.hh" +#include "gz/common/config.hh" #include "RemoteryProfilerImpl.hh" -#include "ignition/common/Console.hh" -#include "ignition/common/Util.hh" +#include "gz/common/Console.hh" +#include "gz/common/Util.hh" using namespace ignition; using namespace common; diff --git a/profiler/src/RemoteryProfilerImpl.hh b/profiler/src/RemoteryProfilerImpl.hh index a614ff20c..90acd261f 100644 --- a/profiler/src/RemoteryProfilerImpl.hh +++ b/profiler/src/RemoteryProfilerImpl.hh @@ -15,8 +15,8 @@ * */ -#ifndef IGNITION_COMMON_REMOTERYPROFILERIMPL_HH_ -#define IGNITION_COMMON_REMOTERYPROFILERIMPL_HH_ +#ifndef GZ_COMMON_REMOTERYPROFILERIMPL_HH_ +#define GZ_COMMON_REMOTERYPROFILERIMPL_HH_ #include @@ -89,4 +89,4 @@ namespace ignition } } -#endif // IGNITION_COMMON_PROFILERIMPL_HH_ +#endif // GZ_COMMON_PROFILERIMPL_HH_ diff --git a/src/Base64.cc b/src/Base64.cc index d82905fda..5bc748d73 100644 --- a/src/Base64.cc +++ b/src/Base64.cc @@ -39,7 +39,7 @@ René Nyffenegger rene.nyffenegger@adp-gmbh.ch */ -#include "ignition/common/Base64.hh" +#include "gz/common/Base64.hh" #include #include #include diff --git a/src/Base64_TEST.cc b/src/Base64_TEST.cc index 4aed870d0..13abcfc72 100644 --- a/src/Base64_TEST.cc +++ b/src/Base64_TEST.cc @@ -16,7 +16,7 @@ */ #include #include -#include +#include #include "test_config.h" diff --git a/src/Battery.cc b/src/Battery.cc index f9ef49532..336f98e4a 100644 --- a/src/Battery.cc +++ b/src/Battery.cc @@ -17,14 +17,14 @@ #include -#include -#include +#include +#include using namespace ignition; using namespace common; /// \brief Private data for the Battery class -class ignition::common::BatteryPrivate +class gz::common::BatteryPrivate { /// \brief Initial voltage in volts. public: double initVoltage = 0.0; diff --git a/src/Battery_TEST.cc b/src/Battery_TEST.cc index 6584fc5e2..43607c6f6 100644 --- a/src/Battery_TEST.cc +++ b/src/Battery_TEST.cc @@ -15,7 +15,7 @@ * */ #include -#include "ignition/common/Battery.hh" +#include "gz/common/Battery.hh" #include "test_config.h" using namespace ignition; diff --git a/src/Console.cc b/src/Console.cc index 5e20d7939..d6604448e 100644 --- a/src/Console.cc +++ b/src/Console.cc @@ -18,8 +18,8 @@ #include #include -#include -#include +#include +#include #ifdef _WIN32 #include diff --git a/src/Console_TEST.cc b/src/Console_TEST.cc index 15139a487..bb4c837c1 100644 --- a/src/Console_TEST.cc +++ b/src/Console_TEST.cc @@ -18,10 +18,10 @@ #include #include -#include "ignition/common/Console.hh" -#include "ignition/common/Filesystem.hh" -#include "ignition/common/Time.hh" -#include "ignition/common/Util.hh" +#include "gz/common/Console.hh" +#include "gz/common/Filesystem.hh" +#include "gz/common/Time.hh" +#include "gz/common/Util.hh" #include "test_config.h" diff --git a/src/EnumIface_TEST.cc b/src/EnumIface_TEST.cc index 90e68d5f7..69a70b77b 100644 --- a/src/EnumIface_TEST.cc +++ b/src/EnumIface_TEST.cc @@ -17,7 +17,7 @@ #include -#include "ignition/common/EnumIface.hh" +#include "gz/common/EnumIface.hh" #include "test_config.h" using namespace ignition; diff --git a/src/Filesystem.cc b/src/Filesystem.cc index fa353f399..b363ad91e 100644 --- a/src/Filesystem.cc +++ b/src/Filesystem.cc @@ -31,11 +31,11 @@ #include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #ifndef _WIN32 #include @@ -48,7 +48,7 @@ #include "PrintWindowsSystemWarning.hh" #endif -#include "ignition/common/Filesystem.hh" +#include "gz/common/Filesystem.hh" #ifdef _WIN32 # define IGN_PATH_MAX _MAX_PATH @@ -60,7 +60,7 @@ # define IGN_PATH_MAX _POSIX_PATH_MAX #endif -namespace igncmn = ignition::common; +namespace igncmn = gz::common; using namespace ignition; using namespace igncmn; diff --git a/src/FilesystemBoost.cc b/src/FilesystemBoost.cc index c09698e10..ea1ed04bd 100644 --- a/src/FilesystemBoost.cc +++ b/src/FilesystemBoost.cc @@ -55,8 +55,8 @@ #include #endif -#include "ignition/common/Console.hh" -#include "ignition/common/Filesystem.hh" +#include "gz/common/Console.hh" +#include "gz/common/Filesystem.hh" namespace ignition { diff --git a/src/Filesystem_TEST.cc b/src/Filesystem_TEST.cc index ed6b0e85b..dd5c63f54 100644 --- a/src/Filesystem_TEST.cc +++ b/src/Filesystem_TEST.cc @@ -25,7 +25,7 @@ #include #include -#include "ignition/common/Util.hh" +#include "gz/common/Util.hh" // The symlink tests should always work on UNIX systems #define BUILD_SYMLINK_TESTS @@ -35,7 +35,7 @@ bool create_and_switch_to_temp_dir(std::string &_new_temp_path) { std::string tmppath; - if (!ignition::common::env("TMPDIR", tmppath)) + if (!gz::common::env("TMPDIR", tmppath)) { tmppath = std::string("/tmp"); } @@ -176,7 +176,7 @@ bool create_new_file_symlink(const std::string &_symlink, if (!linked) { - ignition::common::PrintWindowsSystemWarning( + gz::common::PrintWindowsSystemWarning( "Failed to create file symlink from [" + _target + "] to [" + _symlink + "]"); } @@ -192,7 +192,7 @@ bool create_new_dir_symlink(const std::string &_symlink, SYMBOLIC_LINK_FLAG_DIRECTORY); if (!linked) { - ignition::common::PrintWindowsSystemWarning( + gz::common::PrintWindowsSystemWarning( "Failed to create directory symlink from [" + _target + "] to [" + _symlink + "]"); } @@ -210,8 +210,8 @@ bool create_new_file_hardlink(const std::string &_hardlink, #endif // _WIN32 #include // NOLINT -#include "ignition/common/Console.hh" -#include "ignition/common/Filesystem.hh" +#include "gz/common/Console.hh" +#include "gz/common/Filesystem.hh" using namespace ignition; using namespace common; diff --git a/src/FlagSet_TEST.cc b/src/FlagSet_TEST.cc index 047b8ad63..57911455e 100644 --- a/src/FlagSet_TEST.cc +++ b/src/FlagSet_TEST.cc @@ -23,12 +23,12 @@ * SOFTWARE. */ -// ignition::common::FlagSet is a type-safe class for using enums as flags in +// gz::common::FlagSet is a type-safe class for using enums as flags in // C++14 with an underlying std::bitset. // See https://github.com/mrts/flag-set-cpp // Licence: MIT -#include +#include #include #include @@ -66,7 +66,7 @@ enum class OptionsNoEnd : uint8_t TEST(FlagSet, TestAnd) { - ignition::common::FlagSet red( + gz::common::FlagSet red( Options::RED_FOREGROUND | Options::RED_BACKGROUND); auto result = red & Options::RED_BACKGROUND; @@ -85,26 +85,26 @@ TEST(FlagSet, TestAnd) EXPECT_FALSE(result); EXPECT_EQ(result.Count(), 0u); - ignition::common::FlagSet red_foreground(Options::RED_FOREGROUND); + gz::common::FlagSet red_foreground(Options::RED_FOREGROUND); red &= Options::RED_FOREGROUND; EXPECT_TRUE(red == red_foreground); } TEST(FlagSet, TestOr) { - ignition::common::FlagSet red; + gz::common::FlagSet red; red |= Options::RED_FOREGROUND | Options::RED_BACKGROUND; EXPECT_TRUE(red); EXPECT_EQ(red.Count(), 2u); - ignition::common::FlagSet options; + gz::common::FlagSet options; options |= (Options::FULLSCREEN | Options::FLASH); auto result = options & (Options::FULLSCREEN | Options::FLASH | Options::RED_FOREGROUND); EXPECT_TRUE(result); - ignition::common::FlagSet expected; + gz::common::FlagSet expected; expected |= Options::FULLSCREEN; EXPECT_EQ(options & expected, expected); @@ -122,7 +122,7 @@ TEST(FlagSet, TestOr) TEST(FlagSet, TestSetReset) { - ignition::common::FlagSet options; + gz::common::FlagSet options; EXPECT_EQ(options.Count(), 0u); options.Set(); @@ -147,7 +147,7 @@ TEST(FlagSet, TestSetReset) TEST(FlagSet, TestAnyAllNone) { - ignition::common::FlagSet options; + gz::common::FlagSet options; EXPECT_TRUE(options.None()); EXPECT_FALSE(options.Any()); EXPECT_FALSE(options.All()); @@ -204,13 +204,13 @@ TEST(FlagSet, TestConstructors) TEST(FlagSet, TestStaticConstructors) { - EXPECT_TRUE(ignition::common::FlagSet::AllSet().All()); - EXPECT_FALSE(ignition::common::FlagSet::AllSet().None()); - EXPECT_TRUE(ignition::common::FlagSet::AllSet().Any()); + EXPECT_TRUE(gz::common::FlagSet::AllSet().All()); + EXPECT_FALSE(gz::common::FlagSet::AllSet().None()); + EXPECT_TRUE(gz::common::FlagSet::AllSet().Any()); - EXPECT_FALSE(ignition::common::FlagSet::NoneSet().All()); - EXPECT_TRUE(ignition::common::FlagSet::NoneSet().None()); - EXPECT_FALSE(ignition::common::FlagSet::NoneSet().Any()); + EXPECT_FALSE(gz::common::FlagSet::NoneSet().All()); + EXPECT_TRUE(gz::common::FlagSet::NoneSet().None()); + EXPECT_FALSE(gz::common::FlagSet::NoneSet().Any()); } @@ -237,7 +237,7 @@ TEST(FlagSet, TestEnumWithoutUnderscore) { using ONU = OptionsNoUnderscore; - using TestSet = ignition::common::FlagSet; + using TestSet = gz::common::FlagSet; ASSERT_EQ(5u, TestSet::numElements); @@ -272,7 +272,7 @@ TEST(FlagSet, TestEnumWithoutEnd) { using ONE = OptionsNoEnd; - using TestSet = ignition::common::FlagSet; + using TestSet = gz::common::FlagSet; ASSERT_EQ(5u, TestSet::numElements); diff --git a/src/MaterialDensity.cc b/src/MaterialDensity.cc index 485f12376..90ce9a57f 100644 --- a/src/MaterialDensity.cc +++ b/src/MaterialDensity.cc @@ -16,8 +16,8 @@ */ #include #include -#include "ignition/common/EnumIface.hh" -#include "ignition/common/MaterialDensity.hh" +#include "gz/common/EnumIface.hh" +#include "gz/common/MaterialDensity.hh" using namespace ignition; using namespace common; diff --git a/src/MaterialDensity_TEST.cc b/src/MaterialDensity_TEST.cc index 184c7b9fc..0e3cad0c9 100644 --- a/src/MaterialDensity_TEST.cc +++ b/src/MaterialDensity_TEST.cc @@ -16,7 +16,7 @@ */ #include -#include "ignition/common/MaterialDensity.hh" +#include "gz/common/MaterialDensity.hh" #include "test_config.h" using namespace ignition; diff --git a/src/MovingWindowFilter_TEST.cc b/src/MovingWindowFilter_TEST.cc index d9b1c4538..a9c998e80 100644 --- a/src/MovingWindowFilter_TEST.cc +++ b/src/MovingWindowFilter_TEST.cc @@ -16,9 +16,9 @@ */ #include -#include +#include -#include "ignition/common/MovingWindowFilter.hh" +#include "gz/common/MovingWindowFilter.hh" using namespace ignition; diff --git a/src/Plugin.cc b/src/Plugin.cc index 6fbfc21a6..fcf07b2c6 100644 --- a/src/Plugin.cc +++ b/src/Plugin.cc @@ -16,9 +16,9 @@ */ -#include "ignition/common/Plugin.hh" -#include "ignition/common/PluginInfo.hh" -#include "ignition/common/Console.hh" +#include "gz/common/Plugin.hh" +#include "gz/common/PluginInfo.hh" +#include "gz/common/Console.hh" #include "PluginUtils.hh" namespace ignition diff --git a/src/PluginLoader.cc b/src/PluginLoader.cc index 230947407..c220c0949 100644 --- a/src/PluginLoader.cc +++ b/src/PluginLoader.cc @@ -23,12 +23,12 @@ #include #include -#include "ignition/common/Console.hh" -#include "ignition/common/PluginInfo.hh" -#include "ignition/common/PluginLoader.hh" -#include "ignition/common/PluginPtr.hh" -#include "ignition/common/StringUtils.hh" -#include "ignition/common/Util.hh" +#include "gz/common/Console.hh" +#include "gz/common/PluginInfo.hh" +#include "gz/common/PluginLoader.hh" +#include "gz/common/PluginPtr.hh" +#include "gz/common/StringUtils.hh" +#include "gz/common/Util.hh" #include "PluginUtils.hh" @@ -261,7 +261,7 @@ namespace ignition if (version < PLUGIN_API_VERSION) { ignwarn << "The library [" << _pathToLibrary <<"] is using an outdated " - << "version [" << version << "] of the ignition::common Plugin " + << "version [" << version << "] of the gz::common Plugin " << "API. The version in this library is [" << PLUGIN_API_VERSION << "].\n"; } @@ -269,7 +269,7 @@ namespace ignition if (version > PLUGIN_API_VERSION) { ignerr << "The library [" << _pathToLibrary << "] is using a newer " - << "version [" << version << "] of the ignition::common Plugin " + << "version [" << version << "] of the gz::common Plugin " << "API. The version in this library is [" << PLUGIN_API_VERSION << "].\n"; return loadedPlugins; diff --git a/src/PluginLoader_TEST.cc b/src/PluginLoader_TEST.cc index 12e4d2994..6096a983d 100644 --- a/src/PluginLoader_TEST.cc +++ b/src/PluginLoader_TEST.cc @@ -18,10 +18,10 @@ #include #include -#include "ignition/common/PluginLoader.hh" -#include "ignition/common/SystemPaths.hh" +#include "gz/common/PluginLoader.hh" +#include "gz/common/SystemPaths.hh" -#include "ignition/common/config.hh" +#include "gz/common/config.hh" #include "test_config.h" #ifndef IGN_COMMON_LIB_PATH @@ -31,14 +31,14 @@ ///////////////////////////////////////////////// TEST(PluginLoader, InitialNoInterfacesImplemented) { - ignition::common::PluginLoader pm; + gz::common::PluginLoader pm; EXPECT_EQ(0u, pm.InterfacesImplemented().size()); } ///////////////////////////////////////////////// TEST(PluginLoader, LoadNonexistantLibrary) { - ignition::common::PluginLoader pm; + gz::common::PluginLoader pm; EXPECT_TRUE(pm.LoadLibrary("/path/to/libDoesNotExist.so").empty()); } @@ -46,7 +46,7 @@ TEST(PluginLoader, LoadNonexistantLibrary) TEST(PluginLoader, LoadNonLibrary) { std::string projectPath(IGN_COMMON_LIB_PATH); - ignition::common::PluginLoader pm; + gz::common::PluginLoader pm; EXPECT_TRUE(pm.LoadLibrary(projectPath + "/test_config.h").empty()); } @@ -56,20 +56,20 @@ TEST(PluginLoader, LoadNonPluginLibrary) std::string libraryName("ignition-common"); libraryName += std::to_string(IGNITION_COMMON_MAJOR_VERSION); - ignition::common::SystemPaths sp; + gz::common::SystemPaths sp; sp.AddPluginPaths(IGN_COMMON_LIB_PATH); std::string path = sp.FindSharedLibrary(libraryName); ASSERT_FALSE(path.empty()); - ignition::common::PluginLoader pm; + gz::common::PluginLoader pm; EXPECT_TRUE(pm.LoadLibrary(path).empty()); } ///////////////////////////////////////////////// TEST(PluginLoader, InstantiateUnloadedPlugin) { - ignition::common::PluginLoader pm; - ignition::common::PluginPtr plugin = + gz::common::PluginLoader pm; + gz::common::PluginPtr plugin = pm.Instantiate("plugin::that::is::not::loaded"); EXPECT_FALSE(plugin); } diff --git a/src/PluginUtils.hh b/src/PluginUtils.hh index 4c1284592..9dfc9dca4 100644 --- a/src/PluginUtils.hh +++ b/src/PluginUtils.hh @@ -15,11 +15,11 @@ * */ -#ifndef IGNITION_COMMON_PLUGINUTILS_HH_ -#define IGNITION_COMMON_PLUGINUTILS_HH_ +#ifndef GZ_COMMON_PLUGINUTILS_HH_ +#define GZ_COMMON_PLUGINUTILS_HH_ #include -#include "ignition/common/StringUtils.hh" +#include "gz/common/StringUtils.hh" namespace ignition { diff --git a/src/PluginUtils_TEST.cc b/src/PluginUtils_TEST.cc index 4dfca4eba..0e8f7a7e1 100644 --- a/src/PluginUtils_TEST.cc +++ b/src/PluginUtils_TEST.cc @@ -30,8 +30,8 @@ TEST(PluginUtils, NormalizeName) EXPECT_EQ("::ignition", common::NormalizeName("ignition")); EXPECT_EQ("::ignition", common::NormalizeName("::ignition")); - EXPECT_EQ("::ignition::math", common::NormalizeName("ignition::math")); - EXPECT_EQ("::ignition::math", common::NormalizeName("::ignition::math")); + EXPECT_EQ("::gz::math", common::NormalizeName("gz::math")); + EXPECT_EQ("::gz::math", common::NormalizeName("::gz::math")); } ///////////////////////////////////////////////// diff --git a/src/PrintWindowsSystemWarning.hh b/src/PrintWindowsSystemWarning.hh index a2b2326e9..e53fb38cd 100644 --- a/src/PrintWindowsSystemWarning.hh +++ b/src/PrintWindowsSystemWarning.hh @@ -15,15 +15,15 @@ * */ -#ifndef IGNITION_COMMON_PRINTWINDOWSSYSTEMWARNING_HH_ -#define IGNITION_COMMON_PRINTWINDOWSSYSTEMWARNING_HH_ +#ifndef GZ_COMMON_PRINTWINDOWSSYSTEMWARNING_HH_ +#define GZ_COMMON_PRINTWINDOWSSYSTEMWARNING_HH_ #ifdef _WIN32 #include #include #include #include -#include +#include namespace ignition { @@ -31,7 +31,7 @@ namespace ignition { /// \brief This is a Windows-specific function that prints warnings from the /// system in a pretty and convenient way. They get logged using the - /// ignition::common::Console. + /// gz::common::Console. inline void PrintWindowsSystemWarning(const std::string &_flavorText) { // Based on example code by Microsoft: "Retrieving the Last-Error Code" diff --git a/src/SignalHandler.cc b/src/SignalHandler.cc index 4ea511546..0be795500 100644 --- a/src/SignalHandler.cc +++ b/src/SignalHandler.cc @@ -17,14 +17,14 @@ // Suppressing cpplint.py because tools/cpplint.py is old. Remove the NOLINT // comments when upgrading to ign-cmake's "make codecheck" -#include "ignition/common/SignalHandler.hh" // NOLINT(*) +#include "gz/common/SignalHandler.hh" // NOLINT(*) #include // NOLINT(*) #include // NOLINT(*) #include // NOLINT(*) #include // NOLINT(*) #include // NOLINT(*) #include // NOLINT(*) -#include "ignition/common/Console.hh" // NOLINT(*) +#include "gz/common/Console.hh" // NOLINT(*) using namespace ignition; using namespace common; @@ -47,7 +47,7 @@ void onSignal(int _value) } ///////////////////////////////////////////////// -class ignition::common::SignalHandlerPrivate +class gz::common::SignalHandlerPrivate { /// \brief Handle a signal. /// \param[in] _sig Signal number diff --git a/src/SignalHandler_TEST.cc b/src/SignalHandler_TEST.cc index c44fbdbb2..3f624e496 100644 --- a/src/SignalHandler_TEST.cc +++ b/src/SignalHandler_TEST.cc @@ -17,14 +17,14 @@ // Suppressing cpplint.py because tools/cpplint.py is old. Remove the NOLINT // comments when upgrading to ign-cmake's "make codecheck" -#include "ignition/common/SignalHandler.hh" // NOLINT(*) +#include "gz/common/SignalHandler.hh" // NOLINT(*) #include // NOLINT(*) #include // NOLINT(*) #include // NOLINT(*) #include // NOLINT(*) #include // NOLINT(*) #include // NOLINT(*) -#include "ignition/common/Util.hh" // NOLINT(*) +#include "gz/common/Util.hh" // NOLINT(*) using namespace ignition; diff --git a/src/StringUtils.cc b/src/StringUtils.cc index ebd5562ba..072684beb 100644 --- a/src/StringUtils.cc +++ b/src/StringUtils.cc @@ -16,7 +16,7 @@ */ #include -#include "ignition/common/StringUtils.hh" +#include "gz/common/StringUtils.hh" namespace ignition { diff --git a/src/StringUtils_TEST.cc b/src/StringUtils_TEST.cc index 5c7b31b48..0b5d0c3b1 100644 --- a/src/StringUtils_TEST.cc +++ b/src/StringUtils_TEST.cc @@ -19,7 +19,7 @@ #include -#include "ignition/common/StringUtils.hh" +#include "gz/common/StringUtils.hh" using namespace ignition; diff --git a/src/SystemPaths.cc b/src/SystemPaths.cc index 8e0f254b3..f9e970f3e 100644 --- a/src/SystemPaths.cc +++ b/src/SystemPaths.cc @@ -31,16 +31,16 @@ #include "win_dirent.h" #endif -#include "ignition/common/Console.hh" -#include "ignition/common/StringUtils.hh" -#include "ignition/common/SystemPaths.hh" -#include "ignition/common/Util.hh" +#include "gz/common/Console.hh" +#include "gz/common/StringUtils.hh" +#include "gz/common/SystemPaths.hh" +#include "gz/common/Util.hh" using namespace ignition; using namespace common; // Private data class -class ignition::common::SystemPathsPrivate +class gz::common::SystemPathsPrivate { /// \brief Name of the environment variable to check for plugin paths public: std::string pluginPathEnv = "IGN_PLUGIN_PATH"; diff --git a/src/SystemPaths_TEST.cc b/src/SystemPaths_TEST.cc index 742986b65..0711606b0 100644 --- a/src/SystemPaths_TEST.cc +++ b/src/SystemPaths_TEST.cc @@ -23,9 +23,9 @@ #include #include -#include "ignition/common/Util.hh" -#include "ignition/common/StringUtils.hh" -#include "ignition/common/SystemPaths.hh" +#include "gz/common/Util.hh" +#include "gz/common/StringUtils.hh" +#include "gz/common/SystemPaths.hh" #ifdef _WIN32 #define snprintf _snprintf diff --git a/src/TemplateHelpers_TEST.cc b/src/TemplateHelpers_TEST.cc index 91580a1db..b2a8f694c 100644 --- a/src/TemplateHelpers_TEST.cc +++ b/src/TemplateHelpers_TEST.cc @@ -18,7 +18,7 @@ #include #include -#include "ignition/common/TemplateHelpers.hh" +#include "gz/common/TemplateHelpers.hh" struct SomeType { }; diff --git a/src/Time.cc b/src/Time.cc index d461c1d16..a472b24e7 100644 --- a/src/Time.cc +++ b/src/Time.cc @@ -52,9 +52,9 @@ #include -#include -#include -#include +#include +#include +#include using namespace ignition; using namespace common; diff --git a/src/Time_TEST.cc b/src/Time_TEST.cc index 98e896400..b0fb8e874 100644 --- a/src/Time_TEST.cc +++ b/src/Time_TEST.cc @@ -17,8 +17,8 @@ #include -#include -#include +#include +#include using namespace ignition; diff --git a/src/Timer.cc b/src/Timer.cc index ae6b8c05d..4b882c24b 100644 --- a/src/Timer.cc +++ b/src/Timer.cc @@ -15,7 +15,7 @@ * */ -#include +#include using namespace ignition; using namespace common; diff --git a/src/URI.cc b/src/URI.cc index 12bb6f95a..9b32cd02d 100644 --- a/src/URI.cc +++ b/src/URI.cc @@ -22,8 +22,8 @@ #include #include -#include "ignition/common/Console.hh" -#include "ignition/common/URI.hh" +#include "gz/common/Console.hh" +#include "gz/common/URI.hh" using namespace ignition; using namespace common; @@ -31,7 +31,7 @@ using namespace common; static const char kSchemeDelim[] = "://"; /// \brief URIPath private data. -class ignition::common::URIPathPrivate +class gz::common::URIPathPrivate { /// \brief The parts of the path. public: std::list path; @@ -49,21 +49,21 @@ class ignition::common::URIPathPrivate }; /// \brief URIQuery private data. -class ignition::common::URIQueryPrivate +class gz::common::URIQueryPrivate { /// \brief The key/value tuples that compose the query. public: std::map values; }; /// \brief URIFragment private data. -class ignition::common::URIFragmentPrivate +class gz::common::URIFragmentPrivate { /// \brief The value of the fragment. public: std::string value; }; /// \brief URI private data. -class ignition::common::URIPrivate +class gz::common::URIPrivate { /// \brief The URI scheme. public: std::string scheme; diff --git a/src/URI_TEST.cc b/src/URI_TEST.cc index 7b38eddb7..8fcf1629a 100644 --- a/src/URI_TEST.cc +++ b/src/URI_TEST.cc @@ -16,7 +16,7 @@ */ #include -#include "ignition/common/URI.hh" +#include "gz/common/URI.hh" using namespace ignition; using namespace common; diff --git a/src/Util.cc b/src/Util.cc index de13ac071..b79e72b26 100644 --- a/src/Util.cc +++ b/src/Util.cc @@ -30,11 +30,11 @@ #include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #ifndef _WIN32 #include @@ -55,8 +55,8 @@ static const auto &ignstrtok = strtok_r; #endif -static std::unique_ptr gSystemPaths( - new ignition::common::SystemPaths); +static std::unique_ptr gSystemPaths( + new gz::common::SystemPaths); ///////////////////////////////////////////////// // Internal class for SHA1 computation @@ -238,13 +238,13 @@ bool Sha1::Digest(void const *_buffer, std::size_t _byteCount, } ///////////////////////////////////////////////// -std::string ignition::common::systemTimeISO() +std::string gz::common::systemTimeISO() { return timeToIso(IGN_SYSTEM_TIME()); } ///////////////////////////////////////////////// -std::string ignition::common::systemTimeIso() +std::string gz::common::systemTimeIso() { return timeToIso(IGN_SYSTEM_TIME()); } @@ -266,7 +266,7 @@ static bool PortableLocaltime(time_t seconds, struct tm* out) { } ///////////////////////////////////////////////// -std::string ignition::common::timeToIso( +std::string gz::common::timeToIso( const std::chrono::time_point &_time) { char isoStr[25]; @@ -284,32 +284,32 @@ std::string ignition::common::timeToIso( } ///////////////////////////////////////////////// -std::string ignition::common::logPath() +std::string gz::common::logPath() { return gSystemPaths->LogPath(); } ///////////////////////////////////////////////// -void ignition::common::addSearchPathSuffix(const std::string &_suffix) +void gz::common::addSearchPathSuffix(const std::string &_suffix) { gSystemPaths->AddSearchPathSuffix(_suffix); } ///////////////////////////////////////////////// -std::string ignition::common::findFile(const std::string &_file) +std::string gz::common::findFile(const std::string &_file) { return gSystemPaths->FindFile(_file, true); } ///////////////////////////////////////////////// -std::string ignition::common::findFile(const std::string &_file, +std::string gz::common::findFile(const std::string &_file, const bool _searchLocalPath) { return gSystemPaths->FindFile(_file, _searchLocalPath); } ///////////////////////////////////////////////// -std::string ignition::common::findFilePath(const std::string &_file) +std::string gz::common::findFilePath(const std::string &_file) { std::string filepath = findFile(_file); @@ -325,26 +325,26 @@ std::string ignition::common::findFilePath(const std::string &_file) } ///////////////////////////////////////////////// -void ignition::common::addFindFileURICallback( - std::function _cb) +void gz::common::addFindFileURICallback( + std::function _cb) { gSystemPaths->AddFindFileURICallback(_cb); } ///////////////////////////////////////////////// -ignition::common::SystemPaths *ignition::common::systemPaths() +gz::common::SystemPaths *gz::common::systemPaths() { return gSystemPaths.get(); } ///////////////////////////////////////////////// -bool ignition::common::env(const std::string &_name, std::string &_value) +bool gz::common::env(const std::string &_name, std::string &_value) { return env(_name, _value, false); } ///////////////////////////////////////////////// -bool ignition::common::env(const std::string &_name, +bool gz::common::env(const std::string &_name, std::string &_value, bool _allowEmpty) { @@ -391,7 +391,7 @@ bool ignition::common::env(const std::string &_name, } ///////////////////////////////////////////////// -bool ignition::common::setenv(const std::string &_name, +bool gz::common::setenv(const std::string &_name, const std::string &_value) { #ifdef _WIN32 @@ -414,7 +414,7 @@ bool ignition::common::setenv(const std::string &_name, return true; } ///////////////////////////////////////////////// -bool ignition::common::unsetenv(const std::string &_name) +bool gz::common::unsetenv(const std::string &_name) { #ifdef _WIN32 if (0 != _putenv_s(_name.c_str(), "")) @@ -437,7 +437,7 @@ bool ignition::common::unsetenv(const std::string &_name) } ///////////////////////////////////////////////// -std::string ignition::common::sha1(void const *_buffer, std::size_t _byteCount) +std::string gz::common::sha1(void const *_buffer, std::size_t _byteCount) { Sha1 sha1; std::stringstream stream; @@ -453,14 +453,14 @@ std::string ignition::common::sha1(void const *_buffer, std::size_t _byteCount) } ///////////////////////////////////////////////// -std::string ignition::common::uuid() +std::string gz::common::uuid() { - ignition::common::Uuid uuid; + gz::common::Uuid uuid; return uuid.String(); } ///////////////////////////////////////////////// -std::vector ignition::common::split(const std::string &_str, +std::vector gz::common::split(const std::string &_str, const std::string &_delim) { std::vector tokens; @@ -480,14 +480,14 @@ std::vector ignition::common::split(const std::string &_str, } ///////////////////////////////////////////////// -void ignition::common::ltrim(std::string &_s) +void gz::common::ltrim(std::string &_s) { _s.erase(_s.begin(), std::find_if(_s.begin(), _s.end(), [](int c) {return !std::isspace(c);})); } ///////////////////////////////////////////////// -void ignition::common::rtrim(std::string &_s) +void gz::common::rtrim(std::string &_s) { _s.erase(std::find_if(_s.rbegin(), _s.rend(), [](int c) {return !std::isspace(c);}).base(), @@ -495,35 +495,35 @@ void ignition::common::rtrim(std::string &_s) } ///////////////////////////////////////////////// -void ignition::common::trim(std::string &_s) +void gz::common::trim(std::string &_s) { - ignition::common::ltrim(_s); - ignition::common::rtrim(_s); + gz::common::ltrim(_s); + gz::common::rtrim(_s); } ///////////////////////////////////////////////// -std::string ignition::common::ltrimmed(std::string _s) +std::string gz::common::ltrimmed(std::string _s) { - ignition::common::ltrim(_s); + gz::common::ltrim(_s); return _s; } ///////////////////////////////////////////////// -std::string ignition::common::rtrimmed(std::string _s) +std::string gz::common::rtrimmed(std::string _s) { - ignition::common::rtrim(_s); + gz::common::rtrim(_s); return _s; } ///////////////////////////////////////////////// -std::string ignition::common::trimmed(std::string _s) +std::string gz::common::trimmed(std::string _s) { - ignition::common::trim(_s); + gz::common::trim(_s); return _s; } ///////////////////////////////////////////////// -std::string ignition::common::lowercase(const std::string &_in) +std::string gz::common::lowercase(const std::string &_in) { std::string out = _in; for (size_t i = 0; i < out.size(); ++i) @@ -532,14 +532,14 @@ std::string ignition::common::lowercase(const std::string &_in) } ///////////////////////////////////////////////// -std::string ignition::common::lowercase(const char *_in) +std::string gz::common::lowercase(const char *_in) { std::string ins = _in; return lowercase(ins); } ///////////////////////////////////////////////// -void ignition::common::replaceAll(std::string &_result, +void gz::common::replaceAll(std::string &_result, const std::string &_orig, const std::string &_key, const std::string &_replacement) @@ -554,7 +554,7 @@ void ignition::common::replaceAll(std::string &_result, } ///////////////////////////////////////////////// -std::string ignition::common::replaceAll(const std::string &_orig, +std::string gz::common::replaceAll(const std::string &_orig, const std::string &_key, const std::string &_replacement) { diff --git a/src/Util_TEST.cc b/src/Util_TEST.cc index 1b2a34de7..5059bf960 100644 --- a/src/Util_TEST.cc +++ b/src/Util_TEST.cc @@ -19,7 +19,7 @@ #include #include -#include +#include #include "test_config.h" using namespace ignition; diff --git a/src/Uuid.cc b/src/Uuid.cc index 46dac2872..712654fee 100644 --- a/src/Uuid.cc +++ b/src/Uuid.cc @@ -18,7 +18,7 @@ #include #include -#include "ignition/common/Uuid.hh" +#include "gz/common/Uuid.hh" using namespace ignition; using namespace common; diff --git a/src/Uuid_TEST.cc b/src/Uuid_TEST.cc index 37a2ba7af..3d43e38af 100644 --- a/src/Uuid_TEST.cc +++ b/src/Uuid_TEST.cc @@ -19,7 +19,7 @@ #include #include -#include "ignition/common/Uuid.hh" +#include "gz/common/Uuid.hh" #include "gtest/gtest.h" using namespace ignition; diff --git a/src/WorkerPool.cc b/src/WorkerPool.cc index ccfbea2b3..b4350b34d 100644 --- a/src/WorkerPool.cc +++ b/src/WorkerPool.cc @@ -20,9 +20,9 @@ #include #include -#include "ignition/common/WorkerPool.hh" +#include "gz/common/WorkerPool.hh" -namespace igncmn = ignition::common; +namespace igncmn = gz::common; using namespace igncmn; namespace ignition diff --git a/src/WorkerPool_TEST.cc b/src/WorkerPool_TEST.cc index 18ccb4104..e45c6af7a 100644 --- a/src/WorkerPool_TEST.cc +++ b/src/WorkerPool_TEST.cc @@ -19,11 +19,11 @@ #include -#include "ignition/common/Console.hh" -#include "ignition/common/WorkerPool.hh" -#include "ignition/utilities/ExtraTestMacros.hh" +#include "gz/common/Console.hh" +#include "gz/common/WorkerPool.hh" +#include "gz/utilities/ExtraTestMacros.hh" -namespace igncmn = ignition::common; +namespace igncmn = gz::common; using namespace igncmn; ////////////////////////////////////////////////// diff --git a/test/integration/console.cc b/test/integration/console.cc index 267e0020f..abc73df97 100644 --- a/test/integration/console.cc +++ b/test/integration/console.cc @@ -17,7 +17,7 @@ #include -#include "ignition/common/Console.hh" +#include "gz/common/Console.hh" #include "test_config.h" using namespace ignition; diff --git a/test/integration/deprecated_TEST.cc b/test/integration/deprecated_TEST.cc new file mode 100644 index 000000000..3919c1698 --- /dev/null +++ b/test/integration/deprecated_TEST.cc @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2022 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +#include +#include + +///////////////////////////////////////////////// +// Make sure the ignition namespace still works +TEST(Deprecated, IgnitionNamespace) +{ + ignition::common::Battery battery; +} diff --git a/test/integration/encoder_timing.cc b/test/integration/encoder_timing.cc index 7e2610479..365ff8478 100644 --- a/test/integration/encoder_timing.cc +++ b/test/integration/encoder_timing.cc @@ -15,8 +15,8 @@ */ #include #include -#include "ignition/common/VideoEncoder.hh" -#include "ignition/common/Video.hh" +#include "gz/common/VideoEncoder.hh" +#include "gz/common/Video.hh" #include "test_config.h" using namespace ignition; diff --git a/test/integration/mesh.cc b/test/integration/mesh.cc index c8c4f17cd..b99d64431 100644 --- a/test/integration/mesh.cc +++ b/test/integration/mesh.cc @@ -18,14 +18,14 @@ #include #include "test_config.h" -#include "ignition/common/ColladaLoader.hh" -#include "ignition/common/Material.hh" -#include "ignition/common/Mesh.hh" -#include "ignition/common/Skeleton.hh" -#include "ignition/common/SubMesh.hh" -#include "ignition/common/MeshManager.hh" -#include "ignition/common/SystemPaths.hh" -#include "ignition/math/Vector3.hh" +#include "gz/common/ColladaLoader.hh" +#include "gz/common/Material.hh" +#include "gz/common/Mesh.hh" +#include "gz/common/Skeleton.hh" +#include "gz/common/SubMesh.hh" +#include "gz/common/MeshManager.hh" +#include "gz/common/SystemPaths.hh" +#include "gz/math/Vector3.hh" using namespace ignition; using TestFile = common::testing::TestFile; diff --git a/test/integration/plugin.cc b/test/integration/plugin.cc index 74e0b850a..fdb19e2bc 100644 --- a/test/integration/plugin.cc +++ b/test/integration/plugin.cc @@ -25,12 +25,12 @@ #include #include #include -#include "ignition/common/Console.hh" -#include "ignition/common/Filesystem.hh" -#include "ignition/common/PluginLoader.hh" -#include "ignition/common/SystemPaths.hh" -#include "ignition/common/PluginPtr.hh" -#include "ignition/common/SpecializedPluginPtr.hh" +#include "gz/common/Console.hh" +#include "gz/common/Filesystem.hh" +#include "gz/common/PluginLoader.hh" +#include "gz/common/SystemPaths.hh" +#include "gz/common/PluginPtr.hh" +#include "gz/common/SpecializedPluginPtr.hh" #include "test_config.h" #include "DummyPluginsPath.h" @@ -40,9 +40,9 @@ TEST(PluginLoader, LoadBadPlugins) { std::string dummyPath = - ignition::common::copyFromUnixPath(IGN_DUMMY_PLUGIN_PATH); + gz::common::copyFromUnixPath(IGN_DUMMY_PLUGIN_PATH); - ignition::common::SystemPaths sp; + gz::common::SystemPaths sp; sp.AddPluginPaths(dummyPath); std::vector libraryNames = { @@ -55,10 +55,10 @@ TEST(PluginLoader, LoadBadPlugins) std::string path = sp.FindSharedLibrary(libraryName); ASSERT_FALSE(path.empty()); - ignition::common::PluginLoader pl; + gz::common::PluginLoader pl; // Make sure the expected plugins were loaded. - ignition::common::Console::SetVerbosity(2); + gz::common::Console::SetVerbosity(2); std::unordered_set pluginNames = pl.LoadLibrary(path); EXPECT_TRUE(pluginNames.empty()); } @@ -68,15 +68,15 @@ TEST(PluginLoader, LoadBadPlugins) TEST(PluginLoader, LoadExistingLibrary) { std::string dummyPath = - ignition::common::copyFromUnixPath(IGN_DUMMY_PLUGIN_PATH); + gz::common::copyFromUnixPath(IGN_DUMMY_PLUGIN_PATH); - ignition::common::SystemPaths sp; + gz::common::SystemPaths sp; sp.AddPluginPaths(dummyPath); std::string path = sp.FindSharedLibrary("IGNDummyPlugins"); ASSERT_FALSE(path.empty()); - ignition::common::PluginLoader pl; + gz::common::PluginLoader pl; // Make sure the expected plugins were loaded. std::unordered_set pluginNames = pl.LoadLibrary(path); @@ -93,7 +93,7 @@ TEST(PluginLoader, LoadExistingLibrary) EXPECT_EQ(1u, pl.PluginsImplementing("::test::util::DummyDoubleBase").size()); - ignition::common::PluginPtr firstPlugin = + gz::common::PluginPtr firstPlugin = pl.Instantiate("test::util::DummySinglePlugin"); EXPECT_FALSE(firstPlugin.IsEmpty()); EXPECT_TRUE(firstPlugin->HasInterface("test::util::DummyNameBase")); @@ -101,7 +101,7 @@ TEST(PluginLoader, LoadExistingLibrary) EXPECT_FALSE(firstPlugin->HasInterface("test::util::DummyIntBase")); EXPECT_FALSE(firstPlugin->HasInterface("test::util::DummySetterBase")); - ignition::common::PluginPtr secondPlugin = + gz::common::PluginPtr secondPlugin = pl.Instantiate("test::util::DummyMultiPlugin"); EXPECT_FALSE(secondPlugin.IsEmpty()); EXPECT_TRUE(secondPlugin->HasInterface("test::util::DummyNameBase")); @@ -156,19 +156,19 @@ class SomeInterface }; using SomeSpecializedPluginPtr = - ignition::common::SpecializedPluginPtr< + gz::common::SpecializedPluginPtr< SomeInterface, test::util::DummyIntBase, test::util::DummySetterBase>; TEST(SpecializedPluginPtr, Construction) { - ignition::common::SystemPaths sp; + gz::common::SystemPaths sp; sp.AddPluginPaths(IGN_DUMMY_PLUGIN_PATH); std::string path = sp.FindSharedLibrary("IGNDummyPlugins"); ASSERT_FALSE(path.empty()); - ignition::common::PluginLoader pl; + gz::common::PluginLoader pl; pl.LoadLibrary(path); SomeSpecializedPluginPtr plugin( @@ -223,8 +223,8 @@ TEST(SpecializedPluginPtr, Construction) template void TestSetAndMapUsage( - const ignition::common::PluginLoader &loader, - const ignition::common::PluginPtr &plugin) + const gz::common::PluginLoader &loader, + const gz::common::PluginPtr &plugin) { PluginPtrType1 plugin1 = plugin; PluginPtrType2 plugin2 = plugin1; @@ -237,22 +237,22 @@ void TestSetAndMapUsage( EXPECT_TRUE(plugin2 == plugin1); EXPECT_FALSE(plugin2 != plugin1); - std::set orderedSet; + std::set orderedSet; EXPECT_TRUE(orderedSet.insert(plugin1).second); EXPECT_FALSE(orderedSet.insert(plugin1).second); EXPECT_FALSE(orderedSet.insert(plugin2).second); - std::unordered_set unorderedSet; + std::unordered_set unorderedSet; EXPECT_TRUE(unorderedSet.insert(plugin1).second); EXPECT_FALSE(unorderedSet.insert(plugin1).second); EXPECT_FALSE(unorderedSet.insert(plugin2).second); - std::map orderedMap; + std::map orderedMap; EXPECT_TRUE(orderedMap.insert(std::make_pair(plugin1, "some string")).second); EXPECT_FALSE(orderedMap.insert(std::make_pair(plugin1, "a string")).second); EXPECT_FALSE(orderedMap.insert(std::make_pair(plugin2, "chars")).second); - std::unordered_map unorderedMap; + std::unordered_map unorderedMap; EXPECT_TRUE(unorderedMap.insert(std::make_pair(plugin1, "strings")).second); EXPECT_FALSE(unorderedMap.insert(std::make_pair(plugin1, "letters")).second); EXPECT_FALSE(unorderedMap.insert(std::make_pair(plugin2, "")).second); @@ -278,30 +278,30 @@ void TestSetAndMapUsage( } using SingleSpecializedPluginPtr = - ignition::common::SpecializedPluginPtr; + gz::common::SpecializedPluginPtr; using AnotherSpecializedPluginPtr = - ignition::common::SpecializedPluginPtr< + gz::common::SpecializedPluginPtr< SomeInterface, test::util::DummyIntBase>; TEST(PluginPtr, CopyMoveSemantics) { - ignition::common::PluginPtr plugin; + gz::common::PluginPtr plugin; EXPECT_TRUE(plugin.IsEmpty()); - ignition::common::SystemPaths sp; + gz::common::SystemPaths sp; sp.AddPluginPaths(IGN_DUMMY_PLUGIN_PATH); std::string path = sp.FindSharedLibrary("IGNDummyPlugins"); ASSERT_FALSE(path.empty()); - ignition::common::PluginLoader pl; + gz::common::PluginLoader pl; pl.LoadLibrary(path); plugin = pl.Instantiate("test::util::DummySinglePlugin"); EXPECT_FALSE(plugin.IsEmpty()); - ignition::common::PluginPtr otherPlugin = + gz::common::PluginPtr otherPlugin = pl.Instantiate("test::util::DummySinglePlugin"); EXPECT_FALSE(otherPlugin.IsEmpty()); @@ -314,14 +314,14 @@ TEST(PluginPtr, CopyMoveSemantics) igndbg << "Testing sets and maps with PluginPtr and PluginPtr\n"; TestSetAndMapUsage< - ignition::common::PluginPtr, - ignition::common::PluginPtr>( + gz::common::PluginPtr, + gz::common::PluginPtr>( pl, plugin); igndbg << "Testing sets and maps with PluginPtr and " << "SomeSpecializedPluginPtr\n"; TestSetAndMapUsage< - ignition::common::PluginPtr, + gz::common::PluginPtr, SomeSpecializedPluginPtr>( pl, plugin); @@ -339,7 +339,7 @@ TEST(PluginPtr, CopyMoveSemantics) SingleSpecializedPluginPtr>( pl, plugin); - ignition::common::ConstPluginPtr c_plugin(plugin); + gz::common::ConstPluginPtr c_plugin(plugin); EXPECT_FALSE(c_plugin.IsEmpty()); EXPECT_TRUE(c_plugin == plugin); @@ -370,17 +370,17 @@ void CheckSomeValues( TEST(PluginPtr, QueryInterfaceSharedPtr) { - ignition::common::SystemPaths sp; + gz::common::SystemPaths sp; sp.AddPluginPaths(IGN_DUMMY_PLUGIN_PATH); std::string path = sp.FindSharedLibrary("IGNDummyPlugins"); ASSERT_FALSE(path.empty()); - ignition::common::PluginLoader pl; + gz::common::PluginLoader pl; pl.LoadLibrary(path); // as_shared_pointer without specialization { - ignition::common::PluginPtr plugin = + gz::common::PluginPtr plugin = pl.Instantiate("test::util::DummyMultiPlugin"); std::shared_ptr int_ptr = diff --git a/test/integration/video_encoder.cc b/test/integration/video_encoder.cc index 2301ca142..278b6ed59 100644 --- a/test/integration/video_encoder.cc +++ b/test/integration/video_encoder.cc @@ -18,9 +18,9 @@ // needed on MacOS #include -#include "ignition/common/VideoEncoder.hh" -#include "ignition/common/Video.hh" -#include "ignition/common/ffmpeg_inc.hh" +#include "gz/common/VideoEncoder.hh" +#include "gz/common/Video.hh" +#include "gz/common/ffmpeg_inc.hh" #include "test_config.h" diff --git a/test/performance/logging.cc b/test/performance/logging.cc index d06868a23..328a0212c 100644 --- a/test/performance/logging.cc +++ b/test/performance/logging.cc @@ -20,7 +20,7 @@ #include #include -#include +#include namespace { // Lower value than spdlog to keep CI from flaking @@ -141,7 +141,7 @@ void SaveResultToBucketFile( void run(size_t number_of_threads) { g_counter = 0; - ignition::common::Console::SetVerbosity(4); + gz::common::Console::SetVerbosity(4); std::vector threads(number_of_threads); std::map> threads_result; diff --git a/test/performance/plugin_specialization.cc b/test/performance/plugin_specialization.cc index aca48c858..5c2bf3d85 100644 --- a/test/performance/plugin_specialization.cc +++ b/test/performance/plugin_specialization.cc @@ -20,10 +20,10 @@ #include #include -#include "ignition/common/PluginLoader.hh" -#include "ignition/common/SystemPaths.hh" -#include "ignition/common/SpecializedPluginPtr.hh" -#include "ignition/common/Console.hh" +#include "gz/common/PluginLoader.hh" +#include "gz/common/SystemPaths.hh" +#include "gz/common/SpecializedPluginPtr.hh" +#include "gz/common/Console.hh" #include "test_config.h" #include "DummyPluginsPath.h" @@ -55,26 +55,26 @@ IGN_CREATE_SPEC_INTERFACE(Interface19) // Specialize for only 1 type using Specialize1Type = - ignition::common::SpecializedPluginPtr; + gz::common::SpecializedPluginPtr; // Specialize for 3 different types, and put the type we care about first in // the list. using Specialize3Types_Leading = - ignition::common::SpecializedPluginPtr< + gz::common::SpecializedPluginPtr< test::util::DummySetterBase, Interface1, Interface2>; // Specialize for 3 different types, and put the type we care about last in // the list. using Specialize3Types_Trailing = - ignition::common::SpecializedPluginPtr< + gz::common::SpecializedPluginPtr< Interface1, Interface2, test::util::DummySetterBase>; // Specialize for 10 different types, and put the type we care about first in // the list. using Specialize10Types_Leading = - ignition::common::SpecializedPluginPtr< + gz::common::SpecializedPluginPtr< test::util::DummySetterBase, Interface1, Interface2, Interface3, Interface4, Interface5, Interface6, Interface7, Interface8, Interface9>; @@ -82,7 +82,7 @@ using Specialize10Types_Leading = // Specialize for 10 different types, and put the type we care about last in // the list. using Specialize10Types_Trailing = - ignition::common::SpecializedPluginPtr< + gz::common::SpecializedPluginPtr< Interface1, Interface2, Interface3, Interface4, Interface5, Interface6, Interface7, Interface8, Interface9, test::util::DummySetterBase>; @@ -90,7 +90,7 @@ using Specialize10Types_Trailing = // Specialize for 20 different types, and put the type we care about first in // the list. using Specialize20Types_Leading = - ignition::common::SpecializedPluginPtr< + gz::common::SpecializedPluginPtr< test::util::DummySetterBase, Interface1, Interface2, Interface3, Interface4, Interface5, Interface6, Interface7, Interface8, Interface9, Interface10, @@ -100,7 +100,7 @@ using Specialize20Types_Leading = // Specialize for 20 different types, and put the type we care about last in // the list. using Specialize20Types_Trailing = - ignition::common::SpecializedPluginPtr< + gz::common::SpecializedPluginPtr< Interface1, Interface2, Interface3, Interface4, Interface5, Interface6, Interface7, Interface8, Interface9, Interface10, Interface11, Interface12, Interface13, Interface14, Interface15, @@ -130,16 +130,16 @@ double RunPerformanceTest(const PluginType &plugin) ///////////////////////////////////////////////// TEST(PluginSpecialization, AccessTime) { - ignition::common::SystemPaths sp; + gz::common::SystemPaths sp; sp.AddPluginPaths(IGN_DUMMY_PLUGIN_PATH); std::string path = sp.FindSharedLibrary("IGNDummyPlugins"); ASSERT_FALSE(path.empty()); - ignition::common::PluginLoader pl; + gz::common::PluginLoader pl; pl.LoadLibrary(path); // Load up the generic plugin - ignition::common::PluginPtr plugin = + gz::common::PluginPtr plugin = pl.Instantiate("::test::util::DummyMultiPlugin"); // Create specialized versions diff --git a/test/plugins/BadPluginAPIVersionNew.cc b/test/plugins/BadPluginAPIVersionNew.cc index 681feca0e..66d12dd70 100644 --- a/test/plugins/BadPluginAPIVersionNew.cc +++ b/test/plugins/BadPluginAPIVersionNew.cc @@ -16,14 +16,14 @@ */ #include -#include "ignition/common/PluginMacros.hh" +#include "gz/common/PluginMacros.hh" extern "C" { std::size_t DETAIL_IGN_PLUGIN_VISIBLE IGNCOMMONPluginInfoSize = - sizeof(ignition::common::PluginInfo); + sizeof(gz::common::PluginInfo); std::size_t DETAIL_IGN_PLUGIN_VISIBLE IGNCOMMONPluginInfoAlignment = - alignof(ignition::common::PluginInfo); + alignof(gz::common::PluginInfo); int DETAIL_IGN_PLUGIN_VISIBLE IGNCOMMONPluginAPIVersion = std::numeric_limits::max(); diff --git a/test/plugins/BadPluginAPIVersionOld.cc b/test/plugins/BadPluginAPIVersionOld.cc index 342286789..113e01fdf 100644 --- a/test/plugins/BadPluginAPIVersionOld.cc +++ b/test/plugins/BadPluginAPIVersionOld.cc @@ -15,14 +15,14 @@ * */ -#include "ignition/common/PluginMacros.hh" +#include "gz/common/PluginMacros.hh" extern "C" { std::size_t DETAIL_IGN_PLUGIN_VISIBLE IGNCOMMONPluginInfoSize = - sizeof(ignition::common::PluginInfo); + sizeof(gz::common::PluginInfo); std::size_t DETAIL_IGN_PLUGIN_VISIBLE IGNCOMMONPluginInfoAlignment = - alignof(ignition::common::PluginInfo); + alignof(gz::common::PluginInfo); int DETAIL_IGN_PLUGIN_VISIBLE IGNCOMMONPluginAPIVersion = -1; } diff --git a/test/plugins/BadPluginAlign.cc b/test/plugins/BadPluginAlign.cc index 2d3607158..4815fcde5 100644 --- a/test/plugins/BadPluginAlign.cc +++ b/test/plugins/BadPluginAlign.cc @@ -15,17 +15,17 @@ * */ -#include "ignition/common/PluginMacros.hh" +#include "gz/common/PluginMacros.hh" extern "C" { std::size_t DETAIL_IGN_PLUGIN_VISIBLE IGNCOMMONPluginInfoSize = - sizeof(ignition::common::PluginInfo); + sizeof(gz::common::PluginInfo); std::size_t DETAIL_IGN_PLUGIN_VISIBLE IGNCOMMONPluginInfoAlignment = - 1 + alignof(ignition::common::PluginInfo); + 1 + alignof(gz::common::PluginInfo); int DETAIL_IGN_PLUGIN_VISIBLE IGNCOMMONPluginAPIVersion = - ignition::common::PLUGIN_API_VERSION; + gz::common::PLUGIN_API_VERSION; } extern "C" std::size_t DETAIL_IGN_PLUGIN_VISIBLE IGNCOMMONMultiPluginInfo( diff --git a/test/plugins/BadPluginSize.cc b/test/plugins/BadPluginSize.cc index 82e5deb54..5f3040190 100644 --- a/test/plugins/BadPluginSize.cc +++ b/test/plugins/BadPluginSize.cc @@ -15,17 +15,17 @@ * */ -#include "ignition/common/PluginMacros.hh" +#include "gz/common/PluginMacros.hh" extern "C" { std::size_t DETAIL_IGN_PLUGIN_VISIBLE IGNCOMMONPluginInfoSize = - 1 + sizeof(ignition::common::PluginInfo); + 1 + sizeof(gz::common::PluginInfo); std::size_t DETAIL_IGN_PLUGIN_VISIBLE IGNCOMMONPluginInfoAlignment = - alignof(ignition::common::PluginInfo); + alignof(gz::common::PluginInfo); int DETAIL_IGN_PLUGIN_VISIBLE IGNCOMMONPluginAPIVersion = - ignition::common::PLUGIN_API_VERSION; + gz::common::PLUGIN_API_VERSION; } extern "C" std::size_t DETAIL_IGN_PLUGIN_VISIBLE IGNCOMMONMultiPluginInfo( diff --git a/test/plugins/DummyPlugins.cc b/test/plugins/DummyPlugins.cc index 3f10594df..ab43bfce8 100644 --- a/test/plugins/DummyPlugins.cc +++ b/test/plugins/DummyPlugins.cc @@ -15,7 +15,7 @@ * */ -#include "ignition/common/PluginMacros.hh" +#include "gz/common/PluginMacros.hh" #include "DummyPlugins.hh" diff --git a/test/plugins/DummyPlugins.hh b/test/plugins/DummyPlugins.hh index eaaf8db77..378b7651e 100644 --- a/test/plugins/DummyPlugins.hh +++ b/test/plugins/DummyPlugins.hh @@ -16,13 +16,13 @@ */ -#ifndef IGNITION_COMMON_TEST_PLUGINS_DUMMY_PLUGINS_HH_ -#define IGNITION_COMMON_TEST_PLUGINS_DUMMY_PLUGINS_HH_ +#ifndef GZ_COMMON_TEST_PLUGINS_DUMMY_PLUGINS_HH_ +#define GZ_COMMON_TEST_PLUGINS_DUMMY_PLUGINS_HH_ #include #include -#include +#include namespace test { diff --git a/test/static_assertions/plugin_bad_const_assignment.cc b/test/static_assertions/plugin_bad_const_assignment.cc index ddab315db..5250fcc5f 100644 --- a/test/static_assertions/plugin_bad_const_assignment.cc +++ b/test/static_assertions/plugin_bad_const_assignment.cc @@ -15,11 +15,11 @@ * */ -#include "ignition/common/PluginPtr.hh" +#include "gz/common/PluginPtr.hh" int main() { - ignition::common::ConstPluginPtr const_ptr; - ignition::common::PluginPtr ptr; + gz::common::ConstPluginPtr const_ptr; + gz::common::PluginPtr ptr; ptr = const_ptr; } diff --git a/test/static_assertions/plugin_bad_const_construct.cc b/test/static_assertions/plugin_bad_const_construct.cc index 2d7375234..238750d02 100644 --- a/test/static_assertions/plugin_bad_const_construct.cc +++ b/test/static_assertions/plugin_bad_const_construct.cc @@ -15,9 +15,9 @@ * */ -#include "ignition/common/PluginPtr.hh" +#include "gz/common/PluginPtr.hh" int main() { - ignition::common::PluginPtr ptr{ignition::common::ConstPluginPtr()}; + gz::common::PluginPtr ptr{gz::common::ConstPluginPtr()}; } diff --git a/test/static_assertions/plugin_no_base_class.cc b/test/static_assertions/plugin_no_base_class.cc index d1a7622e9..e9b7b941e 100644 --- a/test/static_assertions/plugin_no_base_class.cc +++ b/test/static_assertions/plugin_no_base_class.cc @@ -15,7 +15,7 @@ * */ -#include "ignition/common/PluginMacros.hh" +#include "gz/common/PluginMacros.hh" class A { diff --git a/test/static_assertions/plugin_not_fully_qualified_base.cc b/test/static_assertions/plugin_not_fully_qualified_base.cc index 2e16293ac..a2d2adf9f 100644 --- a/test/static_assertions/plugin_not_fully_qualified_base.cc +++ b/test/static_assertions/plugin_not_fully_qualified_base.cc @@ -15,7 +15,7 @@ * */ -#include "ignition/common/PluginMacros.hh" +#include "gz/common/PluginMacros.hh" namespace ns { diff --git a/test/static_assertions/plugin_not_fully_qualified_class.cc b/test/static_assertions/plugin_not_fully_qualified_class.cc index 7e0d65572..fb7e879c7 100644 --- a/test/static_assertions/plugin_not_fully_qualified_class.cc +++ b/test/static_assertions/plugin_not_fully_qualified_class.cc @@ -15,7 +15,7 @@ * */ -#include "ignition/common/PluginMacros.hh" +#include "gz/common/PluginMacros.hh" namespace ns { diff --git a/test/static_assertions/plugin_not_global_ns.cc b/test/static_assertions/plugin_not_global_ns.cc index e97ed0738..112522938 100644 --- a/test/static_assertions/plugin_not_global_ns.cc +++ b/test/static_assertions/plugin_not_global_ns.cc @@ -15,7 +15,7 @@ * */ -#include "ignition/common/PluginMacros.hh" +#include "gz/common/PluginMacros.hh" namespace ns { diff --git a/test/static_assertions/plugin_wrong_base_class.cc b/test/static_assertions/plugin_wrong_base_class.cc index 1134a3641..cd014986c 100644 --- a/test/static_assertions/plugin_wrong_base_class.cc +++ b/test/static_assertions/plugin_wrong_base_class.cc @@ -15,7 +15,7 @@ * */ -#include "ignition/common/PluginMacros.hh" +#include "gz/common/PluginMacros.hh" namespace ns { diff --git a/test/test_config.h.in b/test/test_config.h.in index 0a4616552..60daf0215 100644 --- a/test/test_config.h.in +++ b/test/test_config.h.in @@ -5,15 +5,15 @@ * repo for the original source of this header. */ -#ifndef IGNITION_TESTING__TEST_CONFIG_H_ -#define IGNITION_TESTING__TEST_CONFIG_H_ +#ifndef GZ_TESTING__TEST_CONFIG_H_ +#define GZ_TESTING__TEST_CONFIG_H_ #include #include -#include "ignition/common/Console.hh" -#include "ignition/common/Filesystem.hh" -#include "ignition/common/Util.hh" +#include "gz/common/Console.hh" +#include "gz/common/Filesystem.hh" +#include "gz/common/Util.hh" #define PROJECT_BINARY_PATH "${PROJECT_BINARY_DIR}" #define PROJECT_SOURCE_PATH "${PROJECT_SOURCE_DIR}" @@ -202,4 +202,4 @@ namespace ignition -#endif // IGNITION_TESTING__TEST_CONFIG_H_ +#endif // GZ_TESTING__TEST_CONFIG_H_ diff --git a/tutorials/hw-encoding.md b/tutorials/hw-encoding.md index adc2ee1e4..0440e4955 100644 --- a/tutorials/hw-encoding.md +++ b/tutorials/hw-encoding.md @@ -1,6 +1,6 @@ \page hw-encoding Hardware-accelerated Video Encoding -When recording video using the `ignition::common::VideoEncoder` class, you can +When recording video using the `gz::common::VideoEncoder` class, you can opt-in to use hardware (HW) acceleration for the encoding process. By default, only software encoders are used. This tutorial will show how to configure the encoder for HW acceleration and will present ready-made commandlines for some typical use-cases. @@ -191,7 +191,7 @@ no effect then). This would be useful if you want to e.g. implement a GUI choose for the acceleration. The `FlagSet` captures a set of allowed encoders. Its value may be -e.g. `ignition::Common::HWEncoderType::QSV | ignition::common::HWEncoderType::NVENC`. +e.g. `gz::Common::HWEncoderType::QSV | gz::common::HWEncoderType::NVENC`. ## How do I know it's working diff --git a/tutorials/profiler.md b/tutorials/profiler.md index 02fa4ee07..44180b103 100644 --- a/tutorials/profiler.md +++ b/tutorials/profiler.md @@ -7,7 +7,7 @@ Next Tutorial: \ref hw-encoding This tutorial describes how to get started using the Ignition Common profiler to measure and visualize run-time performance of your software. -The `ignition::common::Profiler` provides a common interface that can allow for +The `gz::common::Profiler` provides a common interface that can allow for multiple underlying profiler implementations. Currently, the only available implementation is [Remotery](https://github.com/Celtoys/Remotery). @@ -31,7 +31,7 @@ The relevant corresponding C++ would be as follows: ```{.cpp} // Add the profiler header -#include +#include ... void thread(const char *_thread_name) From 4f2ae91c963233741cd82bc510bd5d2a8dfd8f22 Mon Sep 17 00:00:00 2001 From: Nate Koenig Date: Thu, 6 Oct 2022 05:20:28 -0700 Subject: [PATCH 2/4] 3.15.0 release (#447) Signed-off-by: Nate Koenig Signed-off-by: Nate Koenig Co-authored-by: Nate Koenig --- CMakeLists.txt | 2 +- Changelog.md | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 80fce181e..92f576de5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,7 +3,7 @@ cmake_minimum_required(VERSION 3.10.2 FATAL_ERROR) #============================================================================ # Initialize the project #============================================================================ -project(ignition-common3 VERSION 3.14.2) +project(ignition-common3 VERSION 3.15.0) #============================================================================ # Find ignition-cmake diff --git a/Changelog.md b/Changelog.md index 403ee8e54..65f02a64f 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,5 +1,10 @@ ## Gazebo Common 3.x +## Gazebo Common 3.15.0 (2022-10-06) + +1. ign -> gz Migrate Ignition Headers + * [Pull request #418](https://github.com/gazebosim/gz-common/pull/418) + ## Gazebo Common 3.14.2 (2022-08-16) 1. Fix deprecation warning from new `ffmpeg` From 490875445d9cf32f48e18e4942460049828e8f22 Mon Sep 17 00:00:00 2001 From: Steve Peters Date: Mon, 10 Oct 2022 12:24:01 -0700 Subject: [PATCH 3/4] Don't install CMakeLists.txt (#449) Signed-off-by: Steve Peters --- profiler/CMakeLists.txt | 7 ------- profiler/include/gz/CMakeLists.txt | 1 + profiler/include/gz/common/CMakeLists.txt | 2 ++ 3 files changed, 3 insertions(+), 7 deletions(-) delete mode 100644 profiler/CMakeLists.txt create mode 100644 profiler/include/gz/CMakeLists.txt create mode 100644 profiler/include/gz/common/CMakeLists.txt diff --git a/profiler/CMakeLists.txt b/profiler/CMakeLists.txt deleted file mode 100644 index 8ad3c2f9e..000000000 --- a/profiler/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ - -add_subdirectory(src) - -install( - DIRECTORY include/ - DESTINATION ${IGN_INCLUDE_INSTALL_DIR_FULL}) - diff --git a/profiler/include/gz/CMakeLists.txt b/profiler/include/gz/CMakeLists.txt new file mode 100644 index 000000000..e4717b2d6 --- /dev/null +++ b/profiler/include/gz/CMakeLists.txt @@ -0,0 +1 @@ +add_subdirectory(common) diff --git a/profiler/include/gz/common/CMakeLists.txt b/profiler/include/gz/common/CMakeLists.txt new file mode 100644 index 000000000..d60206d76 --- /dev/null +++ b/profiler/include/gz/common/CMakeLists.txt @@ -0,0 +1,2 @@ + +ign_install_all_headers(COMPONENT profiler) From 5183a5d961e96dcce6c3205275ff92792d2e2459 Mon Sep 17 00:00:00 2001 From: Michael Carroll Date: Tue, 11 Oct 2022 08:08:17 -0500 Subject: [PATCH 4/4] Change namespace location to apply to Windows Signed-off-by: Michael Carroll --- src/Filesystem_TEST.cc | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/Filesystem_TEST.cc b/src/Filesystem_TEST.cc index c7f2ea3e7..ab1122088 100644 --- a/src/Filesystem_TEST.cc +++ b/src/Filesystem_TEST.cc @@ -17,6 +17,8 @@ #include +#include "gz/common/Util.hh" +using namespace ignition; #ifndef _WIN32 #include @@ -26,13 +28,9 @@ #include #include -#include "gz/common/Util.hh" - // The symlink tests should always work on UNIX systems #define BUILD_SYMLINK_TESTS -using namespace ignition; - ///////////////////////////////////////////////// bool create_and_switch_to_temp_dir(std::string &_new_temp_path) {