diff --git a/.clang-format b/.clang-format index 58fb1d7a7..80f4f718b 100644 --- a/.clang-format +++ b/.clang-format @@ -42,6 +42,7 @@ SpaceInEmptyParentheses: false SpacesInCStyleCastParentheses: false SpaceAfterControlStatementKeyword: true SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: Never ContinuationIndentWidth: 4 SortIncludes: false SpaceAfterCStyleCast: false @@ -61,7 +62,7 @@ BraceWrapping: { AfterUnion : 'true', BeforeCatch : 'true', BeforeElse : 'true', - IndentBraces : 'false' + IndentBraces : 'false', SplitEmptyFunction: 'false' } ... diff --git a/.github/workflows/cmake_ubuntu.yml b/.github/workflows/cmake_ubuntu.yml index 3c0889ba7..aaf5f628d 100644 --- a/.github/workflows/cmake_ubuntu.yml +++ b/.github/workflows/cmake_ubuntu.yml @@ -19,13 +19,13 @@ jobs: steps: - uses: actions/checkout@v2 - + - name: Install Conan id: conan uses: turtlebrowser/get-conan@main with: version: 1.59.0 - + - name: Create default profile run: conan profile new default --detect @@ -50,11 +50,10 @@ jobs: shell: bash working-directory: ${{github.workspace}}/build run: cmake --build . --config ${{env.BUILD_TYPE}} - + - name: run test (Linux) working-directory: ${{github.workspace}}/build run: ./tests/behaviortree_cpp_test - + - name: Upload coverage reports to Codecov uses: codecov/codecov-action@v3 - diff --git a/.github/workflows/cmake_windows.yml b/.github/workflows/cmake_windows.yml index aed23392f..dc6c214a8 100644 --- a/.github/workflows/cmake_windows.yml +++ b/.github/workflows/cmake_windows.yml @@ -19,13 +19,13 @@ jobs: steps: - uses: actions/checkout@v2 - + - name: Install Conan id: conan uses: turtlebrowser/get-conan@main with: version: 1.59.0 - + - name: Create default profile run: conan profile new default --detect @@ -47,8 +47,7 @@ jobs: working-directory: ${{github.workspace}}/build shell: bash run: cmake --build . --config ${{env.BUILD_TYPE}} - + - name: run test (Windows) working-directory: ${{github.workspace}}/build run: $env:PATH+=";${{env.BUILD_TYPE}}"; tests/${{env.BUILD_TYPE}}/behaviortree_cpp_test.exe - diff --git a/.github/workflows/pixi.yaml b/.github/workflows/pixi.yaml index f6269ee7b..ac61b41f0 100644 --- a/.github/workflows/pixi.yaml +++ b/.github/workflows/pixi.yaml @@ -51,8 +51,4 @@ jobs: working-directory: ${{github.workspace}}/build-env run: | pixi task add tests ${{ matrix.tests_command }} - pixi run tests - - - - \ No newline at end of file + pixi run tests diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index ba5605993..e6ace8262 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -13,7 +13,7 @@ # # See https://github.com/pre-commit/pre-commit -exclude: ^3rdparty/|3rdparty +exclude: ^3rdparty/|3rdparty|^include/behaviortree_cpp/contrib/ repos: # Standard hooks diff --git a/CMakeLists.txt b/CMakeLists.txt index 263017c99..57a11ba1a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -220,4 +220,3 @@ INSTALL( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/ FILES_MATCHING PATTERN "*.h*") export_btcpp_package() - diff --git a/LICENSE b/LICENSE index f60806f21..e55a7557f 100644 --- a/LICENSE +++ b/LICENSE @@ -19,4 +19,3 @@ 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. - diff --git a/cmake/conan.cmake b/cmake/conan.cmake index 33512fcee..3fa9a26ba 100644 --- a/cmake/conan.cmake +++ b/cmake/conan.cmake @@ -146,7 +146,7 @@ macro(_conan_detect_compiler) set(COMPILER_VERSION ${MAJOR}) else() set(COMPILER_VERSION ${MAJOR}.${MINOR}) - endif() + endif() elseif (${CMAKE_${LANGUAGE}_COMPILER_ID} STREQUAL QCC) set(_CONAN_SETTING_COMPILER qcc) set(COMPILER_VERSION ${MAJOR}.${MINOR}) @@ -180,7 +180,7 @@ macro(_conan_detect_compiler) set(COMPILER_VERSION ${MAJOR}) else() set(COMPILER_VERSION ${MAJOR}.${MINOR}) - endif() + endif() set(_CONAN_SETTING_COMPILER_VERSION ${COMPILER_VERSION}) @@ -190,7 +190,7 @@ macro(_conan_detect_compiler) set(_CONAN_SETTING_COMPILER_LIBCXX ${_LIBCXX}) endif () elseif (${CMAKE_${LANGUAGE}_COMPILER_ID} STREQUAL Clang - AND NOT "${CMAKE_${LANGUAGE}_COMPILER_FRONTEND_VARIANT}" STREQUAL "MSVC" + AND NOT "${CMAKE_${LANGUAGE}_COMPILER_FRONTEND_VARIANT}" STREQUAL "MSVC" AND NOT "${CMAKE_${LANGUAGE}_SIMULATE_ID}" STREQUAL "MSVC") string(REPLACE "." ";" VERSION_LIST ${CMAKE_${LANGUAGE}_COMPILER_VERSION}) @@ -203,7 +203,7 @@ macro(_conan_detect_compiler) set(COMPILER_VERSION ${MAJOR}) else() set(COMPILER_VERSION ${MAJOR}.${MINOR}) - endif() + endif() set(_CONAN_SETTING_COMPILER_VERSION ${COMPILER_VERSION}) @@ -219,8 +219,8 @@ macro(_conan_detect_compiler) set(_CONAN_SETTING_COMPILER_LIBCXX ${_LIBCXX}) endif () elseif(${CMAKE_${LANGUAGE}_COMPILER_ID} STREQUAL MSVC - OR (${CMAKE_${LANGUAGE}_COMPILER_ID} STREQUAL Clang - AND "${CMAKE_${LANGUAGE}_COMPILER_FRONTEND_VARIANT}" STREQUAL "MSVC" + OR (${CMAKE_${LANGUAGE}_COMPILER_ID} STREQUAL Clang + AND "${CMAKE_${LANGUAGE}_COMPILER_FRONTEND_VARIANT}" STREQUAL "MSVC" AND "${CMAKE_${LANGUAGE}_SIMULATE_ID}" STREQUAL "MSVC")) set(_VISUAL "Visual Studio") @@ -475,7 +475,7 @@ function(conan_cmake_autodetect detected_settings) endfunction() macro(conan_parse_arguments) - set(options BASIC_SETUP CMAKE_TARGETS UPDATE KEEP_RPATHS NO_LOAD NO_OUTPUT_DIRS + set(options BASIC_SETUP CMAKE_TARGETS UPDATE KEEP_RPATHS NO_LOAD NO_OUTPUT_DIRS OUTPUT_QUIET NO_IMPORTS SKIP_STD) set(oneValueArgs CONANFILE ARCH BUILD_TYPE INSTALL_FOLDER OUTPUT_FOLDER CONAN_COMMAND) set(multiValueArgs DEBUG_PROFILE RELEASE_PROFILE RELWITHDEBINFO_PROFILE MINSIZEREL_PROFILE @@ -656,11 +656,11 @@ function(conan_cmake_install) if(DEFINED NO_IMPORTS) set(NO_IMPORTS --no-imports) endif() - set(install_args install ${PATH_OR_REFERENCE} ${REFERENCE} ${UPDATE} ${NO_IMPORTS} ${REMOTE} - ${LOCKFILE} ${LOCKFILE_OUT} ${LOCKFILE_NODE_ID} ${INSTALL_FOLDER} - ${OUTPUT_FOLDER} ${GENERATOR} ${BUILD} ${ENV} ${ENV_HOST} ${ENV_BUILD} - ${OPTIONS} ${OPTIONS_HOST} ${OPTIONS_BUILD} ${PROFILE} ${PROFILE_HOST} - ${PROFILE_BUILD} ${SETTINGS} ${SETTINGS_HOST} ${SETTINGS_BUILD} + set(install_args install ${PATH_OR_REFERENCE} ${REFERENCE} ${UPDATE} ${NO_IMPORTS} ${REMOTE} + ${LOCKFILE} ${LOCKFILE_OUT} ${LOCKFILE_NODE_ID} ${INSTALL_FOLDER} + ${OUTPUT_FOLDER} ${GENERATOR} ${BUILD} ${ENV} ${ENV_HOST} ${ENV_BUILD} + ${OPTIONS} ${OPTIONS_HOST} ${OPTIONS_BUILD} ${PROFILE} ${PROFILE_HOST} + ${PROFILE_BUILD} ${SETTINGS} ${SETTINGS_HOST} ${SETTINGS_BUILD} ${CONF} ${CONF_HOST} ${CONF_BUILD}) string(REPLACE ";" " " _install_args "${install_args}") @@ -764,12 +764,12 @@ function(conan_cmake_lock_create) set(BASE --base) endif() set(lock_create_Args lock create ${PATH} ${REFERENCE} ${UPDATE} ${BASE} ${REMOTE} ${LOCKFILE} ${LOCKFILE_OUT} ${LOCKFILE_NODE_ID} ${INSTALL_FOLDER} - ${GENERATOR} ${BUILD} ${ENV} ${ENV_HOST} ${ENV_BUILD} ${OPTIONS} ${OPTIONS_HOST} ${OPTIONS_BUILD} + ${GENERATOR} ${BUILD} ${ENV} ${ENV_HOST} ${ENV_BUILD} ${OPTIONS} ${OPTIONS_HOST} ${OPTIONS_BUILD} ${PROFILE} ${PROFILE_HOST} ${PROFILE_BUILD} ${SETTINGS} ${SETTINGS_HOST} ${SETTINGS_BUILD}) string(REPLACE ";" " " _lock_create_Args "${lock_create_Args}") message(STATUS "Conan executing: ${CONAN_CMD} ${_lock_create_Args}") - + if(ARGS_OUTPUT_QUIET) set(OUTPUT_OPT OUTPUT_QUIET) endif() @@ -1083,7 +1083,7 @@ function(conan_cmake_profile) set(profileMultiValueArgs SETTINGS OPTIONS CONF ENV BUILDENV RUNENV TOOL_REQUIRES) cmake_parse_arguments(ARGS "" "${profileOneValueArgs}" "${profileMultiValueArgs}" ${ARGN}) - if(DEFINED ARGS_FILEPATH) + if(DEFINED ARGS_FILEPATH) set(_FN "${ARGS_FILEPATH}") else() set(_FN "${CMAKE_CURRENT_BINARY_DIR}/profile") diff --git a/contributors.txt b/contributors.txt index 578b30da4..83ef7a03d 100644 --- a/contributors.txt +++ b/contributors.txt @@ -1,4 +1,3 @@ Davide Faconti Michele Colledanchise Rocco Santomo - diff --git a/convert_v3_to_v4.py b/convert_v3_to_v4.py index 027eebbca..0866ffcde 100755 --- a/convert_v3_to_v4.py +++ b/convert_v3_to_v4.py @@ -170,4 +170,4 @@ class ArgsType(typing.NamedTuple): if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/docs/substitution_sample.json b/docs/substitution_sample.json index b9d58de03..fd908e727 100644 --- a/docs/substitution_sample.json +++ b/docs/substitution_sample.json @@ -1,15 +1,15 @@ { - "TestNodeConfigs": { - "MyTest": { - "async_delay": 2000, - "return_status": "SUCCESS", - "post_script": "msg ='message SUBSTITUED'" - } - }, - - "SubstitutionRules": { - "mysub/action_*": "TestAction", - "talk": "TestSaySomething", - "last_action": "MyTest" + "TestNodeConfigs": { + "MyTest": { + "async_delay": 2000, + "return_status": "SUCCESS", + "post_script": "msg ='message SUBSTITUED'" } -} \ No newline at end of file + }, + + "SubstitutionRules": { + "mysub/action_*": "TestAction", + "talk": "TestSaySomething", + "last_action": "MyTest" + } +} diff --git a/examples/broken_sequence.cpp b/examples/broken_sequence.cpp index 51927f1bf..47c34b7ce 100644 --- a/examples/broken_sequence.cpp +++ b/examples/broken_sequence.cpp @@ -21,7 +21,7 @@ class ActionTestNode : public ActionNode time_ = 5; stop_loop_ = false; int i = 0; - while (!stop_loop_ && i++ < time_) + while(!stop_loop_ && i++ < time_) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } @@ -51,7 +51,7 @@ int main() NodeStatus status = NodeStatus::RUNNING; - while (status == NodeStatus::RUNNING) + while(status == NodeStatus::RUNNING) { status = root.executeTick(); diff --git a/examples/ex01_wrap_legacy.cpp b/examples/ex01_wrap_legacy.cpp index 80abf64f7..b6fb195da 100644 --- a/examples/ex01_wrap_legacy.cpp +++ b/examples/ex01_wrap_legacy.cpp @@ -20,7 +20,7 @@ class MyLegacyMoveTo bool go(Point3D goal) { printf("Going to: %f %f %f\n", goal.x, goal.y, goal.z); - return true; // true means success in my legacy code + return true; // true means success in my legacy code } }; @@ -33,7 +33,7 @@ Point3D convertFromString(StringView key) { // three real numbers separated by semicolons auto parts = BT::splitString(key, ';'); - if (parts.size() != 3) + if(parts.size() != 3) { throw RuntimeError("invalid input)"); } @@ -46,7 +46,7 @@ Point3D convertFromString(StringView key) return output; } } -} // namespace BT +} // namespace BT // clang-format off static const char* xml_text = R"( @@ -81,7 +81,7 @@ int main() // Register the lambda with BehaviorTreeFactory::registerSimpleAction - PortsList ports = {BT::InputPort("goal")}; + PortsList ports = { BT::InputPort("goal") }; factory.registerSimpleAction("MoveTo", MoveToWrapperWithLambda, ports); auto tree = factory.createTreeFromText(xml_text); diff --git a/examples/ex02_runtime_ports.cpp b/examples/ex02_runtime_ports.cpp index d6e645dc2..25a13beeb 100644 --- a/examples/ex02_runtime_ports.cpp +++ b/examples/ex02_runtime_ports.cpp @@ -17,8 +17,8 @@ static const char* xml_text = R"( class ThinkRuntimePort : public BT::SyncActionNode { public: - ThinkRuntimePort(const std::string& name, const BT::NodeConfig& config) : - BT::SyncActionNode(name, config) + ThinkRuntimePort(const std::string& name, const BT::NodeConfig& config) + : BT::SyncActionNode(name, config) {} BT::NodeStatus tick() override @@ -31,15 +31,15 @@ class ThinkRuntimePort : public BT::SyncActionNode class SayRuntimePort : public BT::SyncActionNode { public: - SayRuntimePort(const std::string& name, const BT::NodeConfig& config) : - BT::SyncActionNode(name, config) + SayRuntimePort(const std::string& name, const BT::NodeConfig& config) + : BT::SyncActionNode(name, config) {} // You must override the virtual function tick() BT::NodeStatus tick() override { auto msg = getInput("message"); - if (!msg) + if(!msg) { throw BT::RuntimeError("missing required input [message]: ", msg.error()); } @@ -54,12 +54,12 @@ int main() //-------- register ports that might be defined at runtime -------- // more verbose way - PortsList think_ports = {BT::OutputPort("text")}; + PortsList think_ports = { BT::OutputPort("text") }; factory.registerBuilder( CreateManifest("ThinkRuntimePort", think_ports), CreateBuilder()); // less verbose way - PortsList say_ports = {BT::InputPort("message")}; + PortsList say_ports = { BT::InputPort("message") }; factory.registerNodeType("SayRuntimePort", say_ports); factory.registerBehaviorTreeFromText(xml_text); diff --git a/examples/ex04_waypoints.cpp b/examples/ex04_waypoints.cpp index b1b389a42..bc226b6c9 100644 --- a/examples/ex04_waypoints.cpp +++ b/examples/ex04_waypoints.cpp @@ -21,16 +21,16 @@ struct Pose2D class GenerateWaypoints : public SyncActionNode { public: - GenerateWaypoints(const std::string& name, const NodeConfig& config) : - SyncActionNode(name, config) + GenerateWaypoints(const std::string& name, const NodeConfig& config) + : SyncActionNode(name, config) {} NodeStatus tick() override { auto shared_queue = std::make_shared>(); - for (int i = 0; i < 5; i++) + for(int i = 0; i < 5; i++) { - shared_queue->push_back(Pose2D{double(i), double(i), 0}); + shared_queue->push_back(Pose2D{ double(i), double(i), 0 }); } setOutput("waypoints", shared_queue); return NodeStatus::SUCCESS; @@ -38,21 +38,22 @@ class GenerateWaypoints : public SyncActionNode static PortsList providedPorts() { - return {OutputPort>("waypoints")}; + return { OutputPort>("waypoints") }; } }; //-------------------------------------------------------------- class PrintNumber : public SyncActionNode { - public: - PrintNumber(const std::string& name, const NodeConfig& config) : - SyncActionNode(name, config) +public: + PrintNumber(const std::string& name, const NodeConfig& config) + : SyncActionNode(name, config) {} NodeStatus tick() override { double value; - if (getInput("value", value)) { + if(getInput("value", value)) + { std::cout << "PrintNumber: " << value << "\n"; return NodeStatus::SUCCESS; } @@ -61,7 +62,7 @@ class PrintNumber : public SyncActionNode static PortsList providedPorts() { - return {InputPort("value")}; + return { InputPort("value") }; } }; @@ -73,14 +74,14 @@ class PrintNumber : public SyncActionNode class UseWaypoint : public ThreadedAction { public: - UseWaypoint(const std::string& name, const NodeConfig& config) : - ThreadedAction(name, config) + UseWaypoint(const std::string& name, const NodeConfig& config) + : ThreadedAction(name, config) {} NodeStatus tick() override { Pose2D wp; - if (getInput("waypoint", wp)) + if(getInput("waypoint", wp)) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::cout << "Using waypoint: " << wp.x << "/" << wp.y << std::endl; @@ -94,7 +95,7 @@ class UseWaypoint : public ThreadedAction static PortsList providedPorts() { - return {InputPort("waypoint")}; + return { InputPort("waypoint") }; } }; @@ -121,7 +122,7 @@ static const char* xml_tree = R"( int main() { BehaviorTreeFactory factory; - + factory.registerNodeType>("LoopPose"); factory.registerNodeType("UseWaypoint"); diff --git a/examples/ex05_subtree_model.cpp b/examples/ex05_subtree_model.cpp index dca3c6351..326fcf6c6 100644 --- a/examples/ex05_subtree_model.cpp +++ b/examples/ex05_subtree_model.cpp @@ -17,7 +17,7 @@ using namespace BT; * - sub_out_result (default remapping to port {output}) * - sub_out_state (no default) * - * The callee (parent tree, including the subtree) MUST specify those + * The callee (parent tree, including the subtree) MUST specify those * remapping which have no default value. */ diff --git a/examples/ex06_access_by_ptr.cpp b/examples/ex06_access_by_ptr.cpp index f0a0e74ea..253fcca5c 100644 --- a/examples/ex06_access_by_ptr.cpp +++ b/examples/ex06_access_by_ptr.cpp @@ -10,8 +10,8 @@ using namespace BT; class PushIntoVector : public SyncActionNode { public: - PushIntoVector(const std::string& name, const NodeConfig& config) : - SyncActionNode(name, config) + PushIntoVector(const std::string& name, const NodeConfig& config) + : SyncActionNode(name, config) {} NodeStatus tick() override @@ -27,28 +27,29 @@ class PushIntoVector : public SyncActionNode { // The entry hasn't been initialized by any other node, yet. // Let's initialize it ourselves - std::vector vect = {number}; + std::vector vect = { number }; any_ptr.assign(vect); - std::cout << "We created a new vector, containing value ["<< number <<"]\n"; + std::cout << "We created a new vector, containing value [" << number << "]\n"; } else if(auto* vect_ptr = any_ptr->castPtr>()) { // NOTE: vect_ptr would be nullptr, if we try to cast it to the wrong type vect_ptr->push_back(number); - std::cout << "Value ["<< number <<"] pushed into the vector. New size: " - << vect_ptr->size() << "\n"; + std::cout << "Value [" << number + << "] pushed into the vector. New size: " << vect_ptr->size() << "\n"; } return NodeStatus::SUCCESS; } - else { + else + { return NodeStatus::FAILURE; } } static PortsList providedPorts() { - return {BT::BidirectionalPort>("vector"), - BT::InputPort("value")}; + return { BT::BidirectionalPort>("vector"), BT::InputPort("valu" + "e") }; } }; diff --git a/examples/generate_log.cpp b/examples/generate_log.cpp index 2500f2609..1932cd8c8 100644 --- a/examples/generate_log.cpp +++ b/examples/generate_log.cpp @@ -8,9 +8,11 @@ int main(int argc, char** argv) { - if(argc < 2 || argc > 3) { + if(argc < 2 || argc > 3) + { std::cout << "Provide a XML file as first argument. " - "Second argument might be the name of the tree to instantiate." << std::endl; + "Second argument might be the name of the tree to instantiate." + << std::endl; return 1; } const std::string file = argv[1]; @@ -19,11 +21,13 @@ int main(int argc, char** argv) BT::Tree tree; - if(argc == 3) { + if(argc == 3) + { factory.registerBehaviorTreeFromFile(file); tree = factory.createTree(argv[2]); } - else { + else + { tree = factory.createTreeFromFile(file); } @@ -37,7 +41,8 @@ int main(int argc, char** argv) std::cout << "\nTree will run indefinitively. Press CTRL-C to stop\n"; - while(true) { + while(true) + { tree.tickWhileRunning(); } } diff --git a/examples/t01_build_your_first_tree.cpp b/examples/t01_build_your_first_tree.cpp index a11dbdebe..f27c85891 100644 --- a/examples/t01_build_your_first_tree.cpp +++ b/examples/t01_build_your_first_tree.cpp @@ -59,12 +59,14 @@ int main() // Registering a SimpleActionNode using a function pointer. // you may also use C++11 lambdas instead of std::bind - factory.registerSimpleCondition("CheckBattery", [&](TreeNode&) { return CheckBattery(); }); + factory.registerSimpleCondition("CheckBattery", + [&](TreeNode&) { return CheckBattery(); }); //You can also create SimpleActionNodes using methods of a class GripperInterface gripper; - factory.registerSimpleAction("OpenGripper", [&](TreeNode&){ return gripper.open(); } ); - factory.registerSimpleAction("CloseGripper", [&](TreeNode&){ return gripper.close(); } ); + factory.registerSimpleAction("OpenGripper", [&](TreeNode&) { return gripper.open(); }); + factory.registerSimpleAction("CloseGripper", + [&](TreeNode&) { return gripper.close(); }); #else // Load dynamically a plugin and register the TreeNodes it contains diff --git a/examples/t02_basic_ports.cpp b/examples/t02_basic_ports.cpp index 4cecf110b..ce383d901 100644 --- a/examples/t02_basic_ports.cpp +++ b/examples/t02_basic_ports.cpp @@ -45,8 +45,8 @@ static const char* xml_text = R"( class ThinkWhatToSay : public BT::SyncActionNode { public: - ThinkWhatToSay(const std::string& name, const BT::NodeConfig& config) : - BT::SyncActionNode(name, config) + ThinkWhatToSay(const std::string& name, const BT::NodeConfig& config) + : BT::SyncActionNode(name, config) {} // This Action simply write a value in the port "text" @@ -59,7 +59,7 @@ class ThinkWhatToSay : public BT::SyncActionNode // A node having ports MUST implement this STATIC method static BT::PortsList providedPorts() { - return {BT::OutputPort("text")}; + return { BT::OutputPort("text") }; } }; @@ -80,7 +80,7 @@ int main() // SimpleActionNodes can not define their own method providedPorts(), therefore // we have to pass the PortsList explicitly if we want the Action to use getInput() // or setOutput(); - PortsList say_something_ports = {InputPort("message")}; + PortsList say_something_ports = { InputPort("message") }; factory.registerSimpleAction("SaySomething2", SaySomethingSimple, say_something_ports); /* An INPUT can be either a string, for instance: diff --git a/examples/t03_generic_ports.cpp b/examples/t03_generic_ports.cpp index db1964f34..11b5a9b9e 100644 --- a/examples/t03_generic_ports.cpp +++ b/examples/t03_generic_ports.cpp @@ -23,7 +23,7 @@ inline Position2D convertFromString(StringView str) // real numbers separated by semicolons auto parts = splitString(str, ';'); - if (parts.size() != 2) + if(parts.size() != 2) { throw RuntimeError("invalid input)"); } @@ -35,38 +35,38 @@ inline Position2D convertFromString(StringView str) return output; } } -} // end namespace BT +} // end namespace BT class CalculateGoal : public SyncActionNode { public: - CalculateGoal(const std::string& name, const NodeConfig& config) : - SyncActionNode(name, config) + CalculateGoal(const std::string& name, const NodeConfig& config) + : SyncActionNode(name, config) {} NodeStatus tick() override { - Position2D mygoal = {1.1, 2.3}; + Position2D mygoal = { 1.1, 2.3 }; setOutput("goal", mygoal); return NodeStatus::SUCCESS; } static PortsList providedPorts() { - return {OutputPort("goal")}; + return { OutputPort("goal") }; } }; class PrintTarget : public SyncActionNode { public: - PrintTarget(const std::string& name, const NodeConfig& config) : - SyncActionNode(name, config) + PrintTarget(const std::string& name, const NodeConfig& config) + : SyncActionNode(name, config) {} NodeStatus tick() override { auto res = getInput("target"); - if (!res) + if(!res) { throw RuntimeError("error reading port [target]:", res.error()); } @@ -79,7 +79,7 @@ class PrintTarget : public SyncActionNode { // Optionally, a port can have a human readable description const char* description = "Simply print the target on console..."; - return {InputPort("target", description)}; + return { InputPort("target", description) }; } }; diff --git a/examples/t04_reactive_sequence.cpp b/examples/t04_reactive_sequence.cpp index 467113cb0..06b994ca2 100644 --- a/examples/t04_reactive_sequence.cpp +++ b/examples/t04_reactive_sequence.cpp @@ -67,7 +67,7 @@ int main() // 1) When Sequence is used, the ConditionNode is executed only __once__ because it returns SUCCESS. // 2) When ReactiveSequence is used, BatteryOK is executed at __each__ tick() - for (auto& xml_text : {xml_text_sequence, xml_text_reactive}) + for(auto& xml_text : { xml_text_sequence, xml_text_reactive }) { std::cout << "\n------------ BUILDING A NEW TREE ------------\n\n"; @@ -83,14 +83,14 @@ int main() #else // If we need to run code between one tick() and the next, // we can implement our own while loop - while (status != NodeStatus::SUCCESS) + while(status != NodeStatus::SUCCESS) { std::cout << "--- ticking\n"; status = tree.tickOnce(); std::cout << "--- status: " << toStr(status) << "\n\n"; // if still running, add some wait time - if (status == NodeStatus::RUNNING) + if(status == NodeStatus::RUNNING) { tree.sleep(std::chrono::milliseconds(100)); } diff --git a/examples/t07_load_multiple_xml.cpp b/examples/t07_load_multiple_xml.cpp index b0e12febb..795a5951c 100644 --- a/examples/t07_load_multiple_xml.cpp +++ b/examples/t07_load_multiple_xml.cpp @@ -50,7 +50,7 @@ int main() //Check that the BTs have been registered correctly std::cout << "Registered BehaviorTrees:" << std::endl; - for (const std::string& bt_name : factory.registeredBehaviorTrees()) + for(const std::string& bt_name : factory.registeredBehaviorTrees()) { std::cout << " - " << bt_name << std::endl; } diff --git a/examples/t08_additional_node_args.cpp b/examples/t08_additional_node_args.cpp index a11d2e693..5b0d55e5b 100644 --- a/examples/t08_additional_node_args.cpp +++ b/examples/t08_additional_node_args.cpp @@ -4,13 +4,19 @@ using namespace BT; // To demonstrate how to pass arguments by reference, we // use a simple non-copyable object -class NoCopyObj { +class NoCopyObj +{ public: - NoCopyObj(int val): _value(val) {} + NoCopyObj(int val) : _value(val) + {} + + NoCopyObj(const NoCopyObj&) = delete; + NoCopyObj& operator=(const NoCopyObj&) = delete; + int value() + { + return _value; + } - NoCopyObj(const NoCopyObj& ) = delete; - NoCopyObj& operator =(const NoCopyObj& ) = delete; - int value() { return _value; } private: int _value = 0; }; @@ -30,14 +36,14 @@ class Action_A : public SyncActionNode public: // additional arguments passed to the constructor Action_A(const std::string& name, const NodeConfig& config, int arg_int, - std::string arg_str, NoCopyObj& nc) : - SyncActionNode(name, config), _arg1(arg_int), _arg2(arg_str), _nc(nc) + std::string arg_str, NoCopyObj& nc) + : SyncActionNode(name, config), _arg1(arg_int), _arg2(arg_str), _nc(nc) {} NodeStatus tick() override { - std::cout << name() << ": " << _arg1 << " / " - << _arg2 << " / " << _nc.value() << std::endl; + std::cout << name() << ": " << _arg1 << " / " << _arg2 << " / " << _nc.value() + << std::endl; return NodeStatus::SUCCESS; } static PortsList providedPorts() @@ -55,8 +61,8 @@ class Action_A : public SyncActionNode class Action_B : public SyncActionNode { public: - Action_B(const std::string& name, const NodeConfig& config) : - SyncActionNode(name, config) + Action_B(const std::string& name, const NodeConfig& config) + : SyncActionNode(name, config) {} // we want this method to be called ONCE and BEFORE the first tick() @@ -112,7 +118,7 @@ int main() auto tree = factory.createTreeFromText(xml_text); auto visitor = [](TreeNode* node) { - if (auto action_B_node = dynamic_cast(node)) + if(auto action_B_node = dynamic_cast(node)) { action_B_node->initialize(69, "interesting_value"); } diff --git a/examples/t10_observer.cpp b/examples/t10_observer.cpp index ed919899e..468af45fe 100644 --- a/examples/t10_observer.cpp +++ b/examples/t10_observer.cpp @@ -55,15 +55,16 @@ int main() // Print the unique ID and the corresponding human readable path // Path is also expected to be unique. std::map ordered_UID_to_path; - for(const auto& [name, uid]: observer.pathToUID()) { + for(const auto& [name, uid] : observer.pathToUID()) + { ordered_UID_to_path[uid] = name; } - for(const auto& [uid, name]: ordered_UID_to_path) { + for(const auto& [uid, name] : ordered_UID_to_path) + { std::cout << uid << " -> " << name << std::endl; } - tree.tickWhileRunning(); // You can access a specific statistic, using is full path or the UID @@ -72,14 +73,12 @@ int main() std::cout << "----------------" << std::endl; // print all the statistics - for(const auto& [uid, name]: ordered_UID_to_path) { + for(const auto& [uid, name] : ordered_UID_to_path) + { const auto& stats = observer.getStatistics(uid); - std::cout << "[" << name - << "] \tT/S/F: " << stats.transitions_count - << "/" << stats.success_count - << "/" << stats.failure_count - << std::endl; + std::cout << "[" << name << "] \tT/S/F: " << stats.transitions_count << "/" + << stats.success_count << "/" << stats.failure_count << std::endl; } return 0; diff --git a/examples/t11_replace_rules.cpp b/examples/t11_replace_rules.cpp index c37b3b474..3bcfebd15 100644 --- a/examples/t11_replace_rules.cpp +++ b/examples/t11_replace_rules.cpp @@ -61,18 +61,18 @@ int main(int argc, char** argv) // a "dummy" node, that we want to create instead of a given one. // Simple node that just prints its name and return SUCCESS - factory.registerSimpleAction("DummyAction", [](BT::TreeNode& self){ - std::cout << "DummyAction substituting: "<< self.name() << std::endl; + factory.registerSimpleAction("DummyAction", [](BT::TreeNode& self) { + std::cout << "DummyAction substituting: " << self.name() << std::endl; return BT::NodeStatus::SUCCESS; }); // Action that is meant to substitute SaySomething. // It will try to use the input port "message" - factory.registerSimpleAction("TestSaySomething", [](BT::TreeNode& self){ + factory.registerSimpleAction("TestSaySomething", [](BT::TreeNode& self) { auto msg = self.getInput("message"); - if (!msg) + if(!msg) { - throw BT::RuntimeError( "missing required input [message]: ", msg.error() ); + throw BT::RuntimeError("missing required input [message]: ", msg.error()); } std::cout << "TestSaySomething: " << msg.value() << std::endl; return BT::NodeStatus::SUCCESS; @@ -92,7 +92,8 @@ int main(int argc, char** argv) { factory.loadSubstitutionRuleFromJSON(json_text); } - else { + else + { // Substitute nodes which match this wildcard pattern with TestAction factory.addSubstitutionRule("mysub/action_*", "TestAction"); diff --git a/examples/t12_groot_howto.cpp b/examples/t12_groot_howto.cpp index e5fb78460..fd20c2ee2 100644 --- a/examples/t12_groot_howto.cpp +++ b/examples/t12_groot_howto.cpp @@ -11,7 +11,8 @@ */ // A custom structuree that I want to visualize in Groot2 -struct Position2D { +struct Position2D +{ double x; double y; }; @@ -25,13 +26,15 @@ void PositionToJson(nlohmann::json& j, const Position2D& p) } // Simple Action that updates an instance of Position2D in the blackboard -class UpdatePosition: public BT::SyncActionNode +class UpdatePosition : public BT::SyncActionNode { public: - UpdatePosition(const std::string& name, const BT::NodeConfig& config): - BT::SyncActionNode(name, config) {} + UpdatePosition(const std::string& name, const BT::NodeConfig& config) + : BT::SyncActionNode(name, config) + {} - BT::NodeStatus tick() override { + BT::NodeStatus tick() override + { _pos.x += 0.2; _pos.y += 0.1; setOutput("pos", _pos); @@ -40,10 +43,11 @@ class UpdatePosition: public BT::SyncActionNode static BT::PortsList providedPorts() { - return {BT::OutputPort("pos")}; + return { BT::OutputPort("pos") }; } + private: - Position2D _pos = {0, 0}; + Position2D _pos = { 0, 0 }; }; // clang-format off diff --git a/examples/t13_custom_type.hpp b/examples/t13_custom_type.hpp index 99f786ed0..4afde9cc1 100644 --- a/examples/t13_custom_type.hpp +++ b/examples/t13_custom_type.hpp @@ -23,23 +23,24 @@ inline void ToJson(nlohmann::json& dest, const Vector4D& pose) dest["z"] = pose.z; } -namespace BT { +namespace BT +{ -template <> inline - Vector4D convertFromString(StringView key) +template <> +inline Vector4D convertFromString(StringView key) { const auto parts = BT::splitString(key, ','); - if (parts.size() != 4) + if(parts.size() != 4) { throw BT::RuntimeError("invalid input)"); } Vector4D output; output.w = convertFromString(parts[0]); - output.x = convertFromString(parts[1]); - output.y = convertFromString(parts[2]); + output.x = convertFromString(parts[1]); + output.y = convertFromString(parts[2]); output.z = convertFromString(parts[3]); return output; } -} +} // namespace BT diff --git a/examples/t13_plugin_action.cpp b/examples/t13_plugin_action.cpp index aa3d7d922..cd05b2677 100644 --- a/examples/t13_plugin_action.cpp +++ b/examples/t13_plugin_action.cpp @@ -6,8 +6,7 @@ class PrintVector : public BT::SyncActionNode public: PrintVector(const std::string& name, const BT::NodeConfig& config) : BT::SyncActionNode(name, config) - { - } + {} BT::NodeStatus tick() override { @@ -19,7 +18,7 @@ class PrintVector : public BT::SyncActionNode // It is mandatory to define this static method. static BT::PortsList providedPorts() { - return{ BT::InputPort("value") }; + return { BT::InputPort("value") }; } }; diff --git a/examples/t13_plugin_executor.cpp b/examples/t13_plugin_executor.cpp index 1dbc32eae..7eb29b25c 100644 --- a/examples/t13_plugin_executor.cpp +++ b/examples/t13_plugin_executor.cpp @@ -28,7 +28,8 @@ int main(int argc, char** argv) std::string plugin_path = "t13_plugin_action.so"; // if you don't want to use the hardcoded path, pass it as an argument - if(argc == 2) { + if(argc == 2) + { plugin_path = argv[1]; } @@ -43,4 +44,3 @@ int main(int argc, char** argv) return 0; } - diff --git a/examples/test_files/subtree_test.xml b/examples/test_files/subtree_test.xml index 195bca0ec..ff8c6caea 100644 --- a/examples/test_files/subtree_test.xml +++ b/examples/test_files/subtree_test.xml @@ -13,4 +13,3 @@ - diff --git a/include/behaviortree_cpp/action_node.h b/include/behaviortree_cpp/action_node.h index 93a4a996f..3f9b64bf4 100644 --- a/include/behaviortree_cpp/action_node.h +++ b/include/behaviortree_cpp/action_node.h @@ -116,8 +116,8 @@ class SimpleActionNode : public SyncActionNode class ThreadedAction : public ActionNodeBase { public: - ThreadedAction(const std::string& name, const NodeConfig& config) : - ActionNodeBase(name, config) + ThreadedAction(const std::string& name, const NodeConfig& config) + : ActionNodeBase(name, config) {} bool isHaltRequested() const @@ -159,8 +159,8 @@ using AsyncActionNode = ThreadedAction; class StatefulActionNode : public ActionNodeBase { public: - StatefulActionNode(const std::string& name, const NodeConfig& config) : - ActionNodeBase(name, config) + StatefulActionNode(const std::string& name, const NodeConfig& config) + : ActionNodeBase(name, config) {} /// Method called once, when transitioning from the state IDLE. @@ -222,13 +222,12 @@ class CoroActionNode : public ActionNodeBase void halt() override; protected: - struct Pimpl; // The Pimpl idiom + struct Pimpl; // The Pimpl idiom std::unique_ptr _p; void destroyCoroutine(); }; - -} // namespace BT +} // namespace BT #endif diff --git a/include/behaviortree_cpp/actions/always_failure_node.h b/include/behaviortree_cpp/actions/always_failure_node.h index 4e6ec2c97..9de60dbb2 100644 --- a/include/behaviortree_cpp/actions/always_failure_node.h +++ b/include/behaviortree_cpp/actions/always_failure_node.h @@ -33,4 +33,4 @@ class AlwaysFailureNode : public SyncActionNode return NodeStatus::FAILURE; } }; -} // namespace BT +} // namespace BT diff --git a/include/behaviortree_cpp/actions/always_success_node.h b/include/behaviortree_cpp/actions/always_success_node.h index d536d0ed8..777710521 100644 --- a/include/behaviortree_cpp/actions/always_success_node.h +++ b/include/behaviortree_cpp/actions/always_success_node.h @@ -33,4 +33,4 @@ class AlwaysSuccessNode : public SyncActionNode return NodeStatus::SUCCESS; } }; -} // namespace BT +} // namespace BT diff --git a/include/behaviortree_cpp/actions/pop_from_queue.hpp b/include/behaviortree_cpp/actions/pop_from_queue.hpp index 0201a9280..a2ebb1fe1 100644 --- a/include/behaviortree_cpp/actions/pop_from_queue.hpp +++ b/include/behaviortree_cpp/actions/pop_from_queue.hpp @@ -17,7 +17,6 @@ #include "behaviortree_cpp/action_node.h" #include "behaviortree_cpp/decorator_node.h" - /** * Template Action used in ex04_waypoints.cpp example. * @@ -35,8 +34,8 @@ namespace BT template struct ProtectedQueue { - std::list items; - std::mutex mtx; + std::list items; + std::mutex mtx; }; /* @@ -52,45 +51,47 @@ struct ProtectedQueue * * */ - template class PopFromQueue : public SyncActionNode { - public: - PopFromQueue(const std::string& name, const NodeConfig& config) - : SyncActionNode(name, config) - { - } - - NodeStatus tick() override +public: + PopFromQueue(const std::string& name, const NodeConfig& config) + : SyncActionNode(name, config) + {} + + NodeStatus tick() override + { + std::shared_ptr> queue; + if(getInput("queue", queue) && queue) { - std::shared_ptr> queue; - if( getInput("queue", queue) && queue ) - { - std::unique_lock lk(queue->mtx); - auto& items = queue->items; + std::unique_lock lk(queue->mtx); + auto& items = queue->items; - if( items.empty() ) - { - return NodeStatus::FAILURE; - } - else{ - T val = items.front(); - items.pop_front(); - setOutput("popped_item", val); - return NodeStatus::SUCCESS; - } - } - else{ - return NodeStatus::FAILURE; - } + if(items.empty()) + { + return NodeStatus::FAILURE; + } + else + { + T val = items.front(); + items.pop_front(); + setOutput("popped_item", val); + return NodeStatus::SUCCESS; + } } - - static PortsList providedPorts() + else { - return { InputPort>>("queue"), - OutputPort("popped_item")}; + return NodeStatus::FAILURE; } + } + + static PortsList providedPorts() + { + return { InputPort>>("queue"), OutputPort("poppe" + "d_" + "ite" + "m") }; + } }; /** @@ -107,39 +108,37 @@ class PopFromQueue : public SyncActionNode template class QueueSize : public SyncActionNode { - public: - QueueSize(const std::string& name, const NodeConfig& config) - : SyncActionNode(name, config) +public: + QueueSize(const std::string& name, const NodeConfig& config) + : SyncActionNode(name, config) + {} + + NodeStatus tick() override + { + std::shared_ptr> queue; + if(getInput("queue", queue) && queue) { - } + std::unique_lock lk(queue->mtx); + auto& items = queue->items; - NodeStatus tick() override - { - std::shared_ptr> queue; - if( getInput("queue", queue) && queue ) - { - std::unique_lock lk(queue->mtx); - auto& items = queue->items; - - if( items.empty() ) - { - return NodeStatus::FAILURE; - } - else{ - setOutput("size", int(items.size()) ); - return NodeStatus::SUCCESS; - } - } + if(items.empty()) + { return NodeStatus::FAILURE; + } + else + { + setOutput("size", int(items.size())); + return NodeStatus::SUCCESS; + } } - - static PortsList providedPorts() - { - return { InputPort>>("queue"), - OutputPort("size")}; - } + return NodeStatus::FAILURE; + } + + static PortsList providedPorts() + { + return { InputPort>>("queue"), + OutputPort("size") }; + } }; - -} - +} // namespace BT diff --git a/include/behaviortree_cpp/actions/script_condition.h b/include/behaviortree_cpp/actions/script_condition.h index ed9bab7c2..a063c1eca 100644 --- a/include/behaviortree_cpp/actions/script_condition.h +++ b/include/behaviortree_cpp/actions/script_condition.h @@ -25,8 +25,8 @@ namespace BT class ScriptCondition : public ConditionNode { public: - ScriptCondition(const std::string& name, const NodeConfig& config) : - ConditionNode(name, config) + ScriptCondition(const std::string& name, const NodeConfig& config) + : ConditionNode(name, config) { setRegistrationID("ScriptCondition"); loadExecutor(); @@ -34,7 +34,8 @@ class ScriptCondition : public ConditionNode static PortsList providedPorts() { - return {InputPort("code", "Piece of code that can be parsed. Must return false or true")}; + return { InputPort("code", "Piece of code that can be parsed. Must return false or " + "true") }; } private: @@ -42,25 +43,24 @@ class ScriptCondition : public ConditionNode { loadExecutor(); - Ast::Environment env = {config().blackboard, config().enums}; + Ast::Environment env = { config().blackboard, config().enums }; auto result = _executor(env); - return (result.cast()) ? - NodeStatus::SUCCESS : NodeStatus::FAILURE; + return (result.cast()) ? NodeStatus::SUCCESS : NodeStatus::FAILURE; } void loadExecutor() { std::string script; - if (!getInput("code", script)) + if(!getInput("code", script)) { throw RuntimeError("Missing port [code] in ScriptCondition"); } - if (script == _script) + if(script == _script) { return; } auto executor = ParseScript(script); - if (!executor) + if(!executor) { throw RuntimeError(executor.error()); } @@ -75,4 +75,4 @@ class ScriptCondition : public ConditionNode ScriptFunction _executor; }; -} // namespace BT +} // namespace BT diff --git a/include/behaviortree_cpp/actions/script_node.h b/include/behaviortree_cpp/actions/script_node.h index a313a424a..c54585c7d 100644 --- a/include/behaviortree_cpp/actions/script_node.h +++ b/include/behaviortree_cpp/actions/script_node.h @@ -21,8 +21,8 @@ namespace BT class ScriptNode : public SyncActionNode { public: - ScriptNode(const std::string& name, const NodeConfig& config) : - SyncActionNode(name, config) + ScriptNode(const std::string& name, const NodeConfig& config) + : SyncActionNode(name, config) { setRegistrationID("ScriptNode"); @@ -31,16 +31,16 @@ class ScriptNode : public SyncActionNode static PortsList providedPorts() { - return {InputPort("code", "Piece of code that can be parsed")}; + return { InputPort("code", "Piece of code that can be parsed") }; } private: virtual BT::NodeStatus tick() override { loadExecutor(); - if (_executor) + if(_executor) { - Ast::Environment env = {config().blackboard, config().enums}; + Ast::Environment env = { config().blackboard, config().enums }; _executor(env); } return NodeStatus::SUCCESS; @@ -49,16 +49,16 @@ class ScriptNode : public SyncActionNode void loadExecutor() { std::string script; - if (!getInput("code", script)) + if(!getInput("code", script)) { throw RuntimeError("Missing port [code] in Script"); } - if (script == _script) + if(script == _script) { return; } auto executor = ParseScript(script); - if (!executor) + if(!executor) { throw RuntimeError(executor.error()); } @@ -73,4 +73,4 @@ class ScriptNode : public SyncActionNode ScriptFunction _executor; }; -} // namespace BT +} // namespace BT diff --git a/include/behaviortree_cpp/actions/set_blackboard_node.h b/include/behaviortree_cpp/actions/set_blackboard_node.h index 3b59960be..9882cea6f 100644 --- a/include/behaviortree_cpp/actions/set_blackboard_node.h +++ b/include/behaviortree_cpp/actions/set_blackboard_node.h @@ -36,24 +36,24 @@ namespace BT class SetBlackboardNode : public SyncActionNode { public: - SetBlackboardNode(const std::string& name, const NodeConfig& config) : - SyncActionNode(name, config) + SetBlackboardNode(const std::string& name, const NodeConfig& config) + : SyncActionNode(name, config) { setRegistrationID("SetBlackboard"); } static PortsList providedPorts() { - return {InputPort("value", "Value to be written int othe output_key"), - BidirectionalPort("output_key", "Name of the blackboard entry where the " - "value should be written")}; + return { InputPort("value", "Value to be written int othe output_key"), + BidirectionalPort("output_key", "Name of the blackboard entry where the " + "value should be written") }; } private: virtual BT::NodeStatus tick() override { std::string output_key; - if (!getInput("output_key", output_key)) + if(!getInput("output_key", output_key)) { throw RuntimeError("missing port [output_key]"); } @@ -64,8 +64,10 @@ class SetBlackboardNode : public SyncActionNode if(isBlackboardPointer(value_str, &stripped_key)) { const auto input_key = std::string(stripped_key); - std::shared_ptr src_entry = config().blackboard->getEntry(input_key); - std::shared_ptr dst_entry = config().blackboard->getEntry(output_key); + std::shared_ptr src_entry = + config().blackboard->getEntry(input_key); + std::shared_ptr dst_entry = + config().blackboard->getEntry(output_key); if(!src_entry) { @@ -86,6 +88,6 @@ class SetBlackboardNode : public SyncActionNode return NodeStatus::SUCCESS; } }; -} // namespace BT +} // namespace BT #endif diff --git a/include/behaviortree_cpp/actions/sleep_node.h b/include/behaviortree_cpp/actions/sleep_node.h index b97e3cdaa..5a14f3eb5 100644 --- a/include/behaviortree_cpp/actions/sleep_node.h +++ b/include/behaviortree_cpp/actions/sleep_node.h @@ -15,7 +15,6 @@ namespace BT class SleepNode : public StatefulActionNode { public: - SleepNode(const std::string& name, const NodeConfig& config); ~SleepNode() override @@ -31,7 +30,7 @@ class SleepNode : public StatefulActionNode static PortsList providedPorts() { - return {InputPort("msec")}; + return { InputPort("msec") }; } private: @@ -42,4 +41,4 @@ class SleepNode : public StatefulActionNode std::mutex delay_mutex_; }; -} // namespace BT +} // namespace BT diff --git a/include/behaviortree_cpp/actions/test_node.h b/include/behaviortree_cpp/actions/test_node.h index e56c6a978..43c48e6ba 100644 --- a/include/behaviortree_cpp/actions/test_node.h +++ b/include/behaviortree_cpp/actions/test_node.h @@ -61,9 +61,8 @@ class TestNode : public BT::StatefulActionNode { public: TestNode(const std::string& name, const NodeConfig& config, - TestNodeConfig test_config = {}) : - StatefulActionNode(name, config), - _test_config(std::move(test_config)) + TestNodeConfig test_config = {}) + : StatefulActionNode(name, config), _test_config(std::move(test_config)) { setRegistrationID("TestNode"); } @@ -76,7 +75,6 @@ class TestNode : public BT::StatefulActionNode void setConfig(const TestNodeConfig& config); private: - virtual NodeStatus onStart() override; virtual NodeStatus onRunning() override; @@ -91,4 +89,4 @@ class TestNode : public BT::StatefulActionNode std::atomic_bool _completed = false; }; -} // namespace BT +} // namespace BT diff --git a/include/behaviortree_cpp/actions/unset_blackboard_node.h b/include/behaviortree_cpp/actions/unset_blackboard_node.h index aa98a58ee..875d1de7e 100644 --- a/include/behaviortree_cpp/actions/unset_blackboard_node.h +++ b/include/behaviortree_cpp/actions/unset_blackboard_node.h @@ -22,8 +22,8 @@ namespace BT class UnsetBlackboardNode : public SyncActionNode { public: - UnsetBlackboardNode(const std::string& name, const NodeConfig& config) : - SyncActionNode(name, config) + UnsetBlackboardNode(const std::string& name, const NodeConfig& config) + : SyncActionNode(name, config) { setRegistrationID("UnsetBlackboard"); } @@ -37,7 +37,7 @@ class UnsetBlackboardNode : public SyncActionNode virtual BT::NodeStatus tick() override { std::string key; - if (!getInput("key", key)) + if(!getInput("key", key)) { throw RuntimeError("missing input port [key]"); } @@ -45,4 +45,4 @@ class UnsetBlackboardNode : public SyncActionNode return NodeStatus::SUCCESS; } }; -} // namespace BT +} // namespace BT diff --git a/include/behaviortree_cpp/basic_types.h b/include/behaviortree_cpp/basic_types.h index 4243c39c2..772f914b3 100644 --- a/include/behaviortree_cpp/basic_types.h +++ b/include/behaviortree_cpp/basic_types.h @@ -61,10 +61,9 @@ using StringView = std::string_view; // vector of key/value pairs using KeyValueVector = std::vector>; - struct AnyTypeAllowed -{}; - +{ +}; /** * convertFromString is used to convert a string into a custom type. @@ -74,8 +73,8 @@ struct AnyTypeAllowed * * If you have a custom type, you need to implement the corresponding template specialization. */ -template [[nodiscard]] -inline T convertFromString(StringView /*str*/) +template +[[nodiscard]] inline T convertFromString(StringView /*str*/) { auto type_name = BT::demangle(typeid(T)); @@ -88,77 +87,77 @@ inline T convertFromString(StringView /*str*/) type_name); } -template <> [[nodiscard]] -std::string convertFromString(StringView str); +template <> +[[nodiscard]] std::string convertFromString(StringView str); -template <> [[nodiscard]] -const char* convertFromString(StringView str); +template <> +[[nodiscard]] const char* convertFromString(StringView str); -template <> [[nodiscard]] -int convertFromString(StringView str); +template <> +[[nodiscard]] int convertFromString(StringView str); -template <> [[nodiscard]] -unsigned convertFromString(StringView str); +template <> +[[nodiscard]] unsigned convertFromString(StringView str); -template <> [[nodiscard]] -long convertFromString(StringView str); +template <> +[[nodiscard]] long convertFromString(StringView str); -template <> [[nodiscard]] -unsigned long convertFromString(StringView str); +template <> +[[nodiscard]] unsigned long convertFromString(StringView str); -template <> [[nodiscard]] -float convertFromString(StringView str); +template <> +[[nodiscard]] float convertFromString(StringView str); -template <> [[nodiscard]] -double convertFromString(StringView str); +template <> +[[nodiscard]] double convertFromString(StringView str); // Integer numbers separated by the character ";" -template <> [[nodiscard]] -std::vector convertFromString>(StringView str); +template <> +[[nodiscard]] std::vector convertFromString>(StringView str); // Real numbers separated by the character ";" -template <> [[nodiscard]] -std::vector convertFromString>(StringView str); +template <> +[[nodiscard]] std::vector convertFromString>(StringView str); // This recognizes either 0/1, true/false, TRUE/FALSE -template <> [[nodiscard]] -bool convertFromString(StringView str); +template <> +[[nodiscard]] bool convertFromString(StringView str); // Names with all capital letters -template <> [[nodiscard]] -NodeStatus convertFromString(StringView str); +template <> +[[nodiscard]] NodeStatus convertFromString(StringView str); // Names with all capital letters -template <> [[nodiscard]] -NodeType convertFromString(StringView str); +template <> +[[nodiscard]] NodeType convertFromString(StringView str); -template <> [[nodiscard]] -PortDirection convertFromString(StringView str); +template <> +[[nodiscard]] PortDirection convertFromString(StringView str); using StringConverter = std::function; using StringConvertersMap = std::unordered_map; // helper function -template [[nodiscard]] -inline StringConverter GetAnyFromStringFunctor() +template +[[nodiscard]] inline StringConverter GetAnyFromStringFunctor() { if constexpr(std::is_constructible_v) { return [](StringView str) { return Any(str); }; } - else if constexpr(std::is_same_v || - std::is_enum_v) + else if constexpr(std::is_same_v || std::is_enum_v) { return {}; } - else { + else + { return [](StringView str) { return Any(convertFromString(str)); }; } } -template <> [[nodiscard]] -inline StringConverter GetAnyFromStringFunctor() +template <> +[[nodiscard]] inline StringConverter GetAnyFromStringFunctor() { return {}; } @@ -172,55 +171,53 @@ constexpr bool IsConvertibleToString() std::is_convertible_v; } -template [[nodiscard]] -std::string toStr(const T& value) +template +[[nodiscard]] std::string toStr(const T& value) { - if constexpr (IsConvertibleToString()) + if constexpr(IsConvertibleToString()) { return static_cast(value); } else if constexpr(!std::is_arithmetic_v) { - throw LogicError( - StrCat("Function BT::toStr() not specialized for type [", - BT::demangle(typeid(T)), "]") - ); + throw LogicError(StrCat("Function BT::toStr() not specialized for type [", + BT::demangle(typeid(T)), "]")); } - else { + else + { return std::to_string(value); } } -template <> [[nodiscard]] -std::string toStr(const bool& value); +template <> +[[nodiscard]] std::string toStr(const bool& value); -template <> [[nodiscard]] -std::string toStr(const std::string& value); +template <> +[[nodiscard]] std::string toStr(const std::string& value); -template <> [[nodiscard]] -std::string toStr(const BT::NodeStatus& status); +template <> +[[nodiscard]] std::string toStr(const BT::NodeStatus& status); /** * @brief toStr converts NodeStatus to string. Optionally colored. */ -[[nodiscard]] -std::string toStr(BT::NodeStatus status, bool colored); +[[nodiscard]] std::string toStr(BT::NodeStatus status, bool colored); std::ostream& operator<<(std::ostream& os, const BT::NodeStatus& status); -template <> [[nodiscard]] -std::string toStr(const BT::NodeType& type); +template <> +[[nodiscard]] std::string toStr(const BT::NodeType& type); std::ostream& operator<<(std::ostream& os, const BT::NodeType& type); -template <> [[nodiscard]] -std::string toStr(const BT::PortDirection& direction); +template <> +[[nodiscard]] std::string toStr(const BT::PortDirection& direction); std::ostream& operator<<(std::ostream& os, const BT::PortDirection& type); // Small utility, unless you want to use -[[nodiscard]] -std::vector splitString(const StringView& strToSplit, char delimeter); +[[nodiscard]] std::vector splitString(const StringView& strToSplit, + char delimeter); template using enable_if = typename std::enable_if::type*; @@ -272,25 +269,22 @@ using Optional = nonstd::expected; * */ using Result = Expected; -[[nodiscard]] -bool IsAllowedPortName(StringView str); +[[nodiscard]] bool IsAllowedPortName(StringView str); class TypeInfo { public: - template - static TypeInfo Create() { - return TypeInfo{typeid(T), GetAnyFromStringFunctor()}; + static TypeInfo Create() + { + return TypeInfo{ typeid(T), GetAnyFromStringFunctor() }; } - TypeInfo(): type_info_(typeid(AnyTypeAllowed)), - type_str_("AnyTypeAllowed") + TypeInfo() : type_info_(typeid(AnyTypeAllowed)), type_str_("AnyTypeAllowed") {} - TypeInfo(std::type_index type_info, StringConverter conv) : - type_info_(type_info), converter_(conv), - type_str_(BT::demangle(type_info)) + TypeInfo(std::type_index type_info, StringConverter conv) + : type_info_(type_info), converter_(conv), type_str_(BT::demangle(type_info)) {} [[nodiscard]] const std::type_index& type() const; @@ -301,8 +295,8 @@ class TypeInfo [[nodiscard]] Any parseString(const std::string& str) const; - template [[nodiscard]] - Any parseString(const T&) const + template + [[nodiscard]] Any parseString(const T&) const { // avoid compilation errors return {}; @@ -310,8 +304,7 @@ class TypeInfo [[nodiscard]] bool isStronglyTyped() const { - return type_info_ != typeid(AnyTypeAllowed) && - type_info_ != typeid(BT::Any); + return type_info_ != typeid(AnyTypeAllowed) && type_info_ != typeid(BT::Any); } [[nodiscard]] const StringConverter& converter() const @@ -320,23 +313,20 @@ class TypeInfo } private: - std::type_index type_info_; StringConverter converter_; std::string type_str_; }; - -class PortInfo: public TypeInfo +class PortInfo : public TypeInfo { public: - - PortInfo(PortDirection direction = PortDirection::INOUT) : - TypeInfo(), direction_(direction) + PortInfo(PortDirection direction = PortDirection::INOUT) + : TypeInfo(), direction_(direction) {} - PortInfo(PortDirection direction, std::type_index type_info, StringConverter conv) : - TypeInfo(type_info, conv), direction_(direction) + PortInfo(PortDirection direction, std::type_index type_info, StringConverter conv) + : TypeInfo(type_info, conv), direction_(direction) {} [[nodiscard]] PortDirection direction() const; @@ -344,12 +334,15 @@ class PortInfo: public TypeInfo void setDescription(StringView description); template - void setDefaultValue(const T& default_value) { + void setDefaultValue(const T& default_value) + { default_value_ = Any(default_value); - try{ + try + { default_value_str_ = BT::toStr(default_value); } - catch(LogicError&) {} + catch(LogicError&) + {} } [[nodiscard]] const std::string& description() const; @@ -365,13 +358,13 @@ class PortInfo: public TypeInfo std::string default_value_str_; }; -template [[nodiscard]] -std::pair CreatePort(PortDirection direction, - StringView name, - StringView description = {}) +template +[[nodiscard]] std::pair CreatePort(PortDirection direction, + StringView name, + StringView description = {}) { auto sname = static_cast(name); - if (!IsAllowedPortName(sname)) + if(!IsAllowedPortName(sname)) { throw RuntimeError("The name of a port must not be `name` or `ID` " "and must start with an alphabetic character. " @@ -380,15 +373,15 @@ std::pair CreatePort(PortDirection direction, std::pair out; - if (std::is_same::value) + if(std::is_same::value) { - out = {sname, PortInfo(direction)}; + out = { sname, PortInfo(direction) }; } else { - out = {sname, PortInfo(direction, typeid(T), GetAnyFromStringFunctor())}; + out = { sname, PortInfo(direction, typeid(T), GetAnyFromStringFunctor()) }; } - if (!description.empty()) + if(!description.empty()) { out.second.setDescription(description); } @@ -401,9 +394,9 @@ std::pair CreatePort(PortDirection direction, * @param name the name of the port * @param description optional human-readable description */ -template [[nodiscard]] -inline std::pair InputPort(StringView name, - StringView description = {}) +template +[[nodiscard]] inline std::pair +InputPort(StringView name, StringView description = {}) { return CreatePort(PortDirection::INPUT, name, description); } @@ -413,9 +406,9 @@ inline std::pair InputPort(StringView name, * @param name the name of the port * @param description optional human-readable description */ -template [[nodiscard]] -inline std::pair OutputPort(StringView name, - StringView description = {}) +template +[[nodiscard]] inline std::pair +OutputPort(StringView name, StringView description = {}) { return CreatePort(PortDirection::OUTPUT, name, description); } @@ -425,26 +418,24 @@ inline std::pair OutputPort(StringView name, * @param name the name of the port * @param description optional human-readable description */ -template [[nodiscard]] -inline std::pair BidirectionalPort(StringView name, - StringView description = {}) +template +[[nodiscard]] inline std::pair +BidirectionalPort(StringView name, StringView description = {}) { return CreatePort(PortDirection::INOUT, name, description); } //---------- -namespace details { +namespace details +{ -template [[nodiscard]] -inline std::pair PortWithDefault( - PortDirection direction, - StringView name, - const DefaultT& default_value, - StringView description) +template +[[nodiscard]] inline std::pair +PortWithDefault(PortDirection direction, StringView name, const DefaultT& default_value, + StringView description) { - static_assert(IsConvertibleToString() || - std::is_convertible_v || - std::is_constructible_v, + static_assert(IsConvertibleToString() || std::is_convertible_v || + std::is_constructible_v, "The default value must be either the same of the port or string"); auto out = CreatePort(direction, name, description); @@ -457,13 +448,14 @@ inline std::pair PortWithDefault( { out.second.setDefaultValue(std::string(default_value)); } - else { + else + { out.second.setDefaultValue(default_value); } return out; } -} // end namespace details +} // end namespace details /** Syntactic sugar to invoke CreatePort(PortDirection::INPUT,...) * It also sets the PortInfo::defaultValue() @@ -472,12 +464,12 @@ inline std::pair PortWithDefault( * @param default_value default value of the port, either type T of BlackboardKey * @param description optional human-readable description */ -template [[nodiscard]] -inline std::pair InputPort(StringView name, - const DefaultT& default_value, - StringView description) +template +[[nodiscard]] inline std::pair +InputPort(StringView name, const DefaultT& default_value, StringView description) { - return details::PortWithDefault(PortDirection::INPUT, name, default_value, description); + return details::PortWithDefault(PortDirection::INPUT, name, default_value, + description); } /** Syntactic sugar to invoke CreatePort(PortDirection::INOUT,...) @@ -487,12 +479,12 @@ inline std::pair InputPort(StringView name, * @param default_value default value of the port, either type T of BlackboardKey * @param description optional human-readable description */ -template [[nodiscard]] -inline std::pair BidirectionalPort(StringView name, - const DefaultT& default_value, - StringView description) +template +[[nodiscard]] inline std::pair +BidirectionalPort(StringView name, const DefaultT& default_value, StringView description) { - return details::PortWithDefault(PortDirection::INOUT, name, default_value, description); + return details::PortWithDefault(PortDirection::INOUT, name, default_value, + description); } /** Syntactic sugar to invoke CreatePort(PortDirection::OUTPUT,...) @@ -502,15 +494,15 @@ inline std::pair BidirectionalPort(StringView name, * @param default_value default blackboard entry where the output is written * @param description optional human-readable description */ -template [[nodiscard]] -inline std::pair OutputPort( - StringView name, - StringView default_value, - StringView description) +template +[[nodiscard]] inline std::pair OutputPort(StringView name, + StringView default_value, + StringView description) { if(default_value.empty() || default_value.front() != '{' || default_value.back() != '}') { - throw LogicError("Output port can only refer to blackboard entries, i.e. use the syntax '{port_name}'"); + throw LogicError("Output port can only refer to blackboard entries, i.e. use the " + "syntax '{port_name}'"); } auto out = CreatePort(PortDirection::OUTPUT, name, description); out.second.setDefaultValue(default_value); @@ -542,20 +534,21 @@ struct has_static_method_metadata : std::false_type template struct has_static_method_metadata< T, typename std::enable_if< - std::is_same::value>::type> + std::is_same::value>::type> : std::true_type { }; -template [[nodiscard]] -inline PortsList getProvidedPorts(enable_if> = nullptr) +template +[[nodiscard]] inline PortsList +getProvidedPorts(enable_if> = nullptr) { return T::providedPorts(); } -template [[nodiscard]] -inline PortsList - getProvidedPorts(enable_if_not> = nullptr) +template +[[nodiscard]] inline PortsList +getProvidedPorts(enable_if_not> = nullptr) { return {}; } @@ -563,4 +556,4 @@ inline PortsList using TimePoint = std::chrono::high_resolution_clock::time_point; using Duration = std::chrono::high_resolution_clock::duration; -} // namespace BT +} // namespace BT diff --git a/include/behaviortree_cpp/behavior_tree.h b/include/behaviortree_cpp/behavior_tree.h index f3a94d6c6..e26cf53e2 100644 --- a/include/behaviortree_cpp/behavior_tree.h +++ b/include/behaviortree_cpp/behavior_tree.h @@ -95,9 +95,8 @@ inline NodeType getType() // clang-format on } - const char* LibraryVersionString(); int LibraryVersionNumber(); -} // namespace BT +} // namespace BT diff --git a/include/behaviortree_cpp/blackboard.h b/include/behaviortree_cpp/blackboard.h index ca94a87f8..9422d6432 100644 --- a/include/behaviortree_cpp/blackboard.h +++ b/include/behaviortree_cpp/blackboard.h @@ -26,7 +26,6 @@ using AnyPtrLocked = LockedPtr; */ class Blackboard { - public: using Ptr = std::shared_ptr; @@ -36,14 +35,13 @@ class Blackboard {} public: - struct Entry { Any value; TypeInfo info; StringConverter string_converter; mutable std::mutex entry_mutex; - + Entry(const TypeInfo& _info) : info(_info) {} }; @@ -68,19 +66,18 @@ class Blackboard [[nodiscard]] AnyPtrLocked getAnyLocked(const std::string& key) const; - [[deprecated("Use getAnyLocked instead")]] - const Any* getAny(const std::string& key) const; + [[deprecated("Use getAnyLocked instead")]] const Any* + getAny(const std::string& key) const; - [[deprecated("Use getAnyLocked instead")]] - Any* getAny(const std::string& key); + [[deprecated("Use getAnyLocked instead")]] Any* getAny(const std::string& key); /** Return true if the entry with the given key was found. * Note that this method may throw an exception if the cast to T failed. */ - template [[nodiscard]] - bool get(const std::string& key, T& value) const + template + [[nodiscard]] bool get(const std::string& key, T& value) const { - if (auto any_ref = getAnyLocked(key)) + if(auto any_ref = getAnyLocked(key)) { value = any_ref.get()->cast(); return true; @@ -91,15 +88,16 @@ class Blackboard /** * Version of get() that throws if it fails. */ - template [[nodiscard]] - T get(const std::string& key) const + template + [[nodiscard]] T get(const std::string& key) const { - if (auto any_ref = getAnyLocked(key)) + if(auto any_ref = getAnyLocked(key)) { const auto& any = any_ref.get(); if(any->empty()) { - throw RuntimeError("Blackboard::get() error. Entry [", key, "] hasn't been initialized, yet"); + throw RuntimeError("Blackboard::get() error. Entry [", key, + "] hasn't been initialized, yet"); } return any_ref.get()->cast(); } @@ -117,25 +115,26 @@ class Blackboard // check local storage auto it = storage_.find(key); - if (it == storage_.end()) + if(it == storage_.end()) { // create a new entry Any new_value(value); lock.unlock(); std::shared_ptr entry; // if a new generic port is created with a string, it's type should be AnyTypeAllowed - if constexpr (std::is_same_v) + if constexpr(std::is_same_v) { entry = createEntryImpl(key, PortInfo(PortDirection::INOUT)); } - else { + else + { PortInfo new_port(PortDirection::INOUT, new_value.type(), GetAnyFromStringFunctor()); entry = createEntryImpl(key, new_port); } lock.lock(); - storage_.insert( {key, entry} ); + storage_.insert({ key, entry }); entry->value = new_value; } else @@ -150,7 +149,7 @@ class Blackboard Any new_value(value); // special case: entry exists but it is not strongly typed... yet - if (!entry.info.isStronglyTyped()) + if(!entry.info.isStronglyTyped()) { // Use the new type to create a new entry that is strongly typed. entry.info = TypeInfo::Create(); @@ -161,14 +160,13 @@ class Blackboard std::type_index previous_type = entry.info.type(); // check type mismatch - if (previous_type != std::type_index(typeid(T)) && - previous_type != new_value.type()) + if(previous_type != std::type_index(typeid(T)) && previous_type != new_value.type()) { bool mismatching = true; - if (std::is_constructible::value) + if(std::is_constructible::value) { Any any_from_string = entry.info.parseString(value); - if (any_from_string.empty() == false) + if(any_from_string.empty() == false) { mismatching = false; new_value = std::move(any_from_string); @@ -185,14 +183,16 @@ class Blackboard } } - if (mismatching) + if(mismatching) { debugMessage(); - auto msg = StrCat("Blackboard::set(", key, "): once declared, " + auto msg = StrCat("Blackboard::set(", key, + "): once declared, " "the type of a port shall not change. " - "Previously declared type [", BT::demangle(previous_type), - "], current type [", BT::demangle(typeid(T)), "]"); + "Previously declared type [", + BT::demangle(previous_type), "], current type [", + BT::demangle(typeid(T)), "]"); throw LogicError(msg); } } @@ -201,7 +201,8 @@ class Blackboard { previous_any = new_value; } - else { + else + { // copy only if the type is compatible new_value.copyInto(previous_any); } @@ -214,7 +215,7 @@ class Blackboard // check local storage auto it = storage_.find(key); - if (it == storage_.end()) + if(it == storage_.end()) { // No entry, nothing to do. return; @@ -233,9 +234,9 @@ class Blackboard void clear(); - [[deprecated("Use getAnyLocked to access safely an Entry")]] - std::recursive_mutex& entryMutex() const; - + [[deprecated("Use getAnyLocked to access safely an Entry")]] std::recursive_mutex& + entryMutex() const; + void createEntry(const std::string& key, const TypeInfo& info); private: @@ -244,11 +245,10 @@ class Blackboard std::unordered_map> storage_; std::weak_ptr parent_bb_; std::unordered_map internal_to_external_; - - std::shared_ptr createEntryImpl(const std::string &key, const TypeInfo& info); + + std::shared_ptr createEntryImpl(const std::string& key, const TypeInfo& info); bool autoremapping_ = false; }; -} // namespace BT - +} // namespace BT diff --git a/include/behaviortree_cpp/bt_factory.h b/include/behaviortree_cpp/bt_factory.h index fc771181f..ecaba2aae 100644 --- a/include/behaviortree_cpp/bt_factory.h +++ b/include/behaviortree_cpp/bt_factory.h @@ -45,24 +45,24 @@ template inline TreeNodeManifest CreateManifest(const std::string& ID, PortsList portlist = getProvidedPorts()) { - if constexpr( has_static_method_metadata::value ) + if constexpr(has_static_method_metadata::value) { - return {getType(), ID, portlist, T::metadata()}; + return { getType(), ID, portlist, T::metadata() }; } - return {getType(), ID, portlist, {}}; + return { getType(), ID, portlist, {} }; } #ifdef BT_PLUGIN_EXPORT #if defined(_WIN32) - #define BTCPP_EXPORT extern "C" __declspec(dllexport) +#define BTCPP_EXPORT extern "C" __declspec(dllexport) #else - // Unix-like OSes - #define BTCPP_EXPORT extern "C" __attribute__ ((visibility ("default"))) +// Unix-like OSes +#define BTCPP_EXPORT extern "C" __attribute__((visibility("default"))) #endif #else - #define BTCPP_EXPORT static +#define BTCPP_EXPORT static #endif /* Use this macro to automatically register one or more custom Nodes * into a factory. For instance: @@ -85,7 +85,7 @@ inline TreeNodeManifest CreateManifest(const std::string& ID, constexpr const char* PLUGIN_SYMBOL = "BT_RegisterNodesFromPlugin"; -bool WildcardMatch(const std::string &str, StringView filter); +bool WildcardMatch(const std::string& str, StringView filter); /** * @brief Struct used to store a tree. @@ -160,13 +160,19 @@ class Tree /// /// move_nodes = tree.getNodesByPath("move_*"); /// - template [[nodiscard]] - std::vector getNodesByPath(StringView wildcard_filter) const { + template + [[nodiscard]] std::vector + getNodesByPath(StringView wildcard_filter) const + { std::vector nodes; - for (auto const& subtree : subtrees) { - for (auto const& node : subtree->nodes) { - if(auto node_recast = dynamic_cast(node.get())) { - if(WildcardMatch(node->fullPath(), wildcard_filter)) { + for(auto const& subtree : subtrees) + { + for(auto const& node : subtree->nodes) + { + if(auto node_recast = dynamic_cast(node.get())) + { + if(WildcardMatch(node->fullPath(), wildcard_filter)) + { nodes.push_back(node.get()); } } @@ -175,7 +181,6 @@ class Tree return nodes; } - private: std::shared_ptr wake_up_; @@ -295,8 +300,7 @@ class BehaviorTreeFactory /// Returns the ID of the trees registered either with /// registerBehaviorTreeFromFile or registerBehaviorTreeFromText. - [[nodiscard]] - std::vector registeredBehaviorTrees() const; + [[nodiscard]] std::vector registeredBehaviorTrees() const; /** * @brief Clear previously-registered behavior trees. @@ -311,10 +315,8 @@ class BehaviorTreeFactory * @param config configuration that is passed to the constructor of the TreeNode. * @return new node. */ - [[nodiscard]] - std::unique_ptr instantiateTreeNode(const std::string& name, - const std::string& ID, - const NodeConfig& config) const; + [[nodiscard]] std::unique_ptr instantiateTreeNode( + const std::string& name, const std::string& ID, const NodeConfig& config) const; /** registerNodeType where you explicitly pass the list of ports. * Doesn't require the implementation of static method providedPorts() @@ -323,9 +325,9 @@ class BehaviorTreeFactory void registerNodeType(const std::string& ID, const PortsList& ports, ExtraArgs... args) { static_assert(std::is_base_of::value || - std::is_base_of::value || - std::is_base_of::value || - std::is_base_of::value, + std::is_base_of::value || + std::is_base_of::value || + std::is_base_of::value, "[registerNode]: accepts only classed derived from either " "ActionNodeBase, " "DecoratorNode, ControlNode or ConditionNode"); @@ -358,15 +360,18 @@ class BehaviorTreeFactory template void registerNodeType(const std::string& ID, ExtraArgs... args) { - if constexpr(std::is_abstract_v) { + if constexpr(std::is_abstract_v) + { // check first if the given class is abstract static_assert(!std::is_abstract_v, "The Node type can't be abstract. " "Did you forget to implement an abstract " "method in the derived class?"); } - else { + else + { constexpr bool param_constructable = - std::is_constructible::value; + std::is_constructible::value; constexpr bool has_static_ports_list = has_static_method_providedPorts::value; // clang-format off @@ -384,16 +389,14 @@ class BehaviorTreeFactory } /// All the builders. Made available mostly for debug purposes. - [[nodiscard]] - const std::unordered_map& builders() const; + [[nodiscard]] const std::unordered_map& builders() const; /// Manifests of all the registered TreeNodes. - [[nodiscard]] - const std::unordered_map& manifests() const; + [[nodiscard]] const std::unordered_map& + manifests() const; /// List of builtin IDs. - [[nodiscard]] - const std::set& builtinNodes() const; + [[nodiscard]] const std::set& builtinNodes() const; /** * @brief createTreeFromText will parse the XML directly from string. @@ -406,9 +409,8 @@ class BehaviorTreeFactory * @param blackboard blackboard of the root tree * @return the newly created tree */ - [[nodiscard]] - Tree createTreeFromText(const std::string& text, - Blackboard::Ptr blackboard = Blackboard::create()); + [[nodiscard]] Tree createTreeFromText( + const std::string& text, Blackboard::Ptr blackboard = Blackboard::create()); /** * @brief createTreeFromFile will parse the XML from a given file. @@ -421,18 +423,16 @@ class BehaviorTreeFactory * @param blackboard blackboard of the root tree * @return the newly created tree */ - [[nodiscard]] - Tree createTreeFromFile(const std::filesystem::path& file_path, - Blackboard::Ptr blackboard = Blackboard::create()); + [[nodiscard]] Tree + createTreeFromFile(const std::filesystem::path& file_path, + Blackboard::Ptr blackboard = Blackboard::create()); - [[nodiscard]] - Tree createTree(const std::string& tree_name, - Blackboard::Ptr blackboard = Blackboard::create()); + [[nodiscard]] Tree createTree(const std::string& tree_name, + Blackboard::Ptr blackboard = Blackboard::create()); /// Add metadata to a specific manifest. This metadata will be added /// to with the function writeTreeNodesModelXML() - void addMetadataToManifest(const std::string& node_id, - const KeyValueVector& metadata); + void addMetadataToManifest(const std::string& node_id, const KeyValueVector& metadata); /** * @brief Add an Enum to the scripting language. @@ -461,7 +461,7 @@ class BehaviorTreeFactory void registerScriptingEnums() { constexpr auto entries = magic_enum::enum_entries(); - for (const auto& it : entries) + for(const auto& it : entries) { registerScriptingEnum(it.second, static_cast(it.first)); } @@ -496,17 +496,14 @@ class BehaviorTreeFactory /** * @brief substitutionRules return the current substitution rules. */ - [[nodiscard]] - const std::unordered_map& + [[nodiscard]] const std::unordered_map& substitutionRules() const; private: - struct PImpl; std::unique_ptr _p; - }; -} // namespace BT +} // namespace BT -#endif // BT_FACTORY_H +#endif // BT_FACTORY_H diff --git a/include/behaviortree_cpp/bt_parser.h b/include/behaviortree_cpp/bt_parser.h index 9b442a90b..3b6bcb637 100644 --- a/include/behaviortree_cpp/bt_parser.h +++ b/include/behaviortree_cpp/bt_parser.h @@ -36,7 +36,8 @@ class Parser Parser(Parser&& other) = default; Parser& operator=(Parser&& other) = default; - virtual void loadFromFile(const std::filesystem::path& filename, bool add_includes = true) = 0; + virtual void loadFromFile(const std::filesystem::path& filename, + bool add_includes = true) = 0; virtual void loadFromText(const std::string& xml_text, bool add_includes = true) = 0; @@ -48,4 +49,4 @@ class Parser virtual void clearInternalState(){}; }; -} // namespace BT +} // namespace BT diff --git a/include/behaviortree_cpp/condition_node.h b/include/behaviortree_cpp/condition_node.h index 97fd9ee18..3c6299d2a 100644 --- a/include/behaviortree_cpp/condition_node.h +++ b/include/behaviortree_cpp/condition_node.h @@ -63,6 +63,6 @@ class SimpleConditionNode : public ConditionNode TickFunctor tick_functor_; }; -} // namespace BT +} // namespace BT #endif diff --git a/include/behaviortree_cpp/contrib/json.hpp b/include/behaviortree_cpp/contrib/json.hpp index 2448bf22d..07a8ad3ae 100644 --- a/include/behaviortree_cpp/contrib/json.hpp +++ b/include/behaviortree_cpp/contrib/json.hpp @@ -18,18 +18,18 @@ #ifndef INCLUDE_NLOHMANN_JSON_HPP_ #define INCLUDE_NLOHMANN_JSON_HPP_ -#include // all_of, find, for_each -#include // nullptr_t, ptrdiff_t, size_t -#include // hash, less -#include // initializer_list +#include // all_of, find, for_each +#include // nullptr_t, ptrdiff_t, size_t +#include // hash, less +#include // initializer_list #ifndef JSON_NO_IO - #include // istream, ostream -#endif // JSON_NO_IO -#include // random_access_iterator_tag -#include // unique_ptr -#include // string, stoi, to_string -#include // declval, forward, move, pair, swap -#include // vector +#include // istream, ostream +#endif // JSON_NO_IO +#include // random_access_iterator_tag +#include // unique_ptr +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap +#include // vector // #include // __ _____ _____ _____ @@ -40,8 +40,6 @@ // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann // SPDX-License-Identifier: MIT - - #include // #include @@ -53,16 +51,16 @@ // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann // SPDX-License-Identifier: MIT - - // This file contains all macro definitions affecting or depending on the ABI #ifndef JSON_SKIP_LIBRARY_VERSION_CHECK - #if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH) - #if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 11 || NLOHMANN_JSON_VERSION_PATCH != 2 - #warning "Already included a different version of the library!" - #endif - #endif +#if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && \ + defined(NLOHMANN_JSON_VERSION_PATCH) +#if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 11 || \ + NLOHMANN_JSON_VERSION_PATCH != 2 +#warning "Already included a different version of the library!" +#endif +#endif #endif #define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum) @@ -70,80 +68,75 @@ #define NLOHMANN_JSON_VERSION_PATCH 2 // NOLINT(modernize-macro-to-enum) #ifndef JSON_DIAGNOSTICS - #define JSON_DIAGNOSTICS 0 +#define JSON_DIAGNOSTICS 0 #endif #ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON - #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 +#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 #endif #if JSON_DIAGNOSTICS - #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag +#define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag #else - #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS +#define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS #endif #if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON - #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp +#define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp #else - #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON +#define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON #endif #ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION - #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 +#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 #endif // Construct the namespace ABI tags component -#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) json_abi ## a ## b -#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b) \ - NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) +#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) json_abi##a##b +#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b) NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) -#define NLOHMANN_JSON_ABI_TAGS \ - NLOHMANN_JSON_ABI_TAGS_CONCAT( \ - NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \ - NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON) +#define NLOHMANN_JSON_ABI_TAGS \ + NLOHMANN_JSON_ABI_TAGS_CONCAT(NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \ + NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON) // Construct the namespace version component -#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \ - _v ## major ## _ ## minor ## _ ## patch -#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \ - NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \ + _v##major##_##minor##_##patch +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) #if NLOHMANN_JSON_NAMESPACE_NO_VERSION #define NLOHMANN_JSON_NAMESPACE_VERSION #else -#define NLOHMANN_JSON_NAMESPACE_VERSION \ - NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \ - NLOHMANN_JSON_VERSION_MINOR, \ - NLOHMANN_JSON_VERSION_PATCH) +#define NLOHMANN_JSON_NAMESPACE_VERSION \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \ + NLOHMANN_JSON_VERSION_MINOR, \ + NLOHMANN_JSON_VERSION_PATCH) #endif // Combine namespace components -#define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a ## b -#define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) \ - NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) +#define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a##b +#define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) #ifndef NLOHMANN_JSON_NAMESPACE -#define NLOHMANN_JSON_NAMESPACE \ - nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT( \ - NLOHMANN_JSON_ABI_TAGS, \ - NLOHMANN_JSON_NAMESPACE_VERSION) +#define NLOHMANN_JSON_NAMESPACE \ + nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT(NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) #endif #ifndef NLOHMANN_JSON_NAMESPACE_BEGIN -#define NLOHMANN_JSON_NAMESPACE_BEGIN \ - namespace nlohmann \ - { \ - inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT( \ - NLOHMANN_JSON_ABI_TAGS, \ - NLOHMANN_JSON_NAMESPACE_VERSION) \ - { +#define NLOHMANN_JSON_NAMESPACE_BEGIN \ + namespace nlohmann \ + { \ + inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT(NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) \ + { #endif #ifndef NLOHMANN_JSON_NAMESPACE_END -#define NLOHMANN_JSON_NAMESPACE_END \ - } /* namespace (inline namespace) NOLINT(readability/namespace) */ \ - } // namespace nlohmann +#define NLOHMANN_JSON_NAMESPACE_END \ + } /* namespace (inline namespace) NOLINT(readability/namespace) */ \ + } // namespace nlohmann #endif // #include @@ -155,19 +148,17 @@ // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann // SPDX-License-Identifier: MIT - - -#include // transform -#include // array -#include // forward_list -#include // inserter, front_inserter, end -#include // map -#include // string -#include // tuple, make_tuple -#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible -#include // unordered_map -#include // pair, declval -#include // valarray +#include // transform +#include // array +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray // #include // __ _____ _____ _____ @@ -178,16 +169,14 @@ // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann // SPDX-License-Identifier: MIT - - -#include // nullptr_t -#include // exception +#include // nullptr_t +#include // exception #if JSON_DIAGNOSTICS - #include // accumulate +#include // accumulate #endif -#include // runtime_error -#include // to_string -#include // vector +#include // runtime_error +#include // to_string +#include // vector // #include // __ _____ _____ _____ @@ -198,12 +187,10 @@ // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann // SPDX-License-Identifier: MIT - - -#include // array -#include // size_t -#include // uint8_t -#include // string +#include // array +#include // size_t +#include // uint8_t +#include // string // #include // __ _____ _____ _____ @@ -214,9 +201,7 @@ // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann // SPDX-License-Identifier: MIT - - -#include // declval, pair +#include // declval, pair // #include // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ @@ -226,8 +211,6 @@ // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann // SPDX-License-Identifier: MIT - - #include // #include @@ -239,25 +222,23 @@ // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann // SPDX-License-Identifier: MIT - - // #include - NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { -template struct make_void +template +struct make_void { - using type = void; + using type = void; }; -template using void_t = typename make_void::type; +template +using void_t = typename make_void::type; } // namespace detail NLOHMANN_JSON_NAMESPACE_END - NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { @@ -265,59 +246,56 @@ namespace detail // https://en.cppreference.com/w/cpp/experimental/is_detected struct nonesuch { - nonesuch() = delete; - ~nonesuch() = delete; - nonesuch(nonesuch const&) = delete; - nonesuch(nonesuch const&&) = delete; - void operator=(nonesuch const&) = delete; - void operator=(nonesuch&&) = delete; + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; }; -template class Op, - class... Args> +template class Op, class... Args> struct detector { - using value_t = std::false_type; - using type = Default; + using value_t = std::false_type; + using type = Default; }; -template class Op, class... Args> +template class Op, class... Args> struct detector>, Op, Args...> { - using value_t = std::true_type; - using type = Op; + using value_t = std::true_type; + using type = Op; }; -template class Op, class... Args> +template