From 1bc0e176f66cdebf3982f2bc9d49ef621482b698 Mon Sep 17 00:00:00 2001 From: Jelly_Candy Date: Sat, 21 Nov 2026 18:18:04 +0800 Subject: [PATCH] improve: improved cross-platform compilability capabilities (** DO NOT USE ABSOLUTE PATH AGAIN ** ) --- .gitignore | 2 + src/sentry_nav/xmake.lua | 456 +++++++++++++++++++++++++--------- tools/resolve_ros_includes.py | 148 +++++++++++ 3 files changed, 491 insertions(+), 115 deletions(-) create mode 100644 tools/resolve_ros_includes.py diff --git a/.gitignore b/.gitignore index e7ea263..70836e1 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ build/ .xmake/ .vscode/ generated/ +install/ build.ninja # ---- 编译数据库:xmake 每次构建自动重写,本机绝对路径 ---- @@ -19,6 +20,7 @@ __pycache__/ # ---- 运行时临时文件 ---- *.log +log/ # ---- 原始高模:单文件 115 MB + 16 MB,仿真跑不动也用不上 ---- # 仿真实际加载的是 meshes/base.stl / meshes/wheel.stl(减面版) diff --git a/src/sentry_nav/xmake.lua b/src/sentry_nav/xmake.lua index d917d9e..ae2002c 100644 --- a/src/sentry_nav/xmake.lua +++ b/src/sentry_nav/xmake.lua @@ -1,113 +1,342 @@ + -- ============================================================================ --- sentry_nav 的目标定义(由仓库根的 xmake.lua 用 includes() 引入) --- ============================================================================ --- --- 从仓库根编(推荐): --- cd ~/Gazebo_projects/sentry_nav_dev && xmake --- 产物在仓库根的 build/linux/x86_64/release/{self_filter,patrol} --- --- 单独编这个子目录也能用(产物落在 src/sentry_nav/build/): --- cd src/sentry_nav && xmake --- --- 本工程**不使用 ament / colcon**,产物没有资源索引注册,所以 --- **不能 `ros2 run sentry_nav xxx`**,得直接跑二进制路径。 --- 整个工程的构建说明见根目录 README.md 与 docs/构建体系与代码分层.md。 --- --- --------------------------------------------------------------------------- --- 关键:为什么这里能用 xmake 编 ROS 节点(§81 时还编不过) --- --------------------------------------------------------------------------- --- §81 用 xmake 手写链接时失败: --- undefined reference to 'rcl_timer_call_with_info' --- liblibrcl.so: error adding symbols: DSO missing from command line --- 原因是 GNU ld 单遍扫描,库的先后顺序必须手工排好;而 ament 会自动展开整条依赖链。 --- --- 解法是 xmake 的 `add_linkgroups(..., {group = true})`,它展开成 --- -Wl,--start-group -lfoo -lbar ... -Wl,--end-group --- 让链接器在组内反复扫描,**顺序就无所谓了**。 --- --- 实测对比: --- · colcon/ament 生成的链接命令里有 **158 个库**(把 package.xml 的所有依赖都链了) --- · 这里只链 **约 40 个**真正需要的,靠 linkgroup 解决顺序 --- --- 参考:xmake 官方 skill `project-config/xmake-link-order` +-- ROS 2 dependency configuration -- ============================================================================ -set_languages("c++23") -set_warnings("all", "extra") -add_cxflags("-Wpedantic") +-- PCL dependency, discovered through pkg-config. +add_requires("pkgconfig::pcl_common", {system = true}) -local ROS = os.getenv("ROS_PREFIX") or "/opt/ros/lyrical" - --- 所有 ROS 包的 include 目录(每个包一个子目录) -local ros_includes = {ROS .. "/include", "include"} -for _, d in ipairs(os.dirs(ROS .. "/include/*")) do - table.insert(ros_includes, d) -end - --- 只保留真实存在的 .so(ROS 里不少包是 header-only,写成 -l 会报 cannot find) -local function existing(names) - local out = {} - for _, n in ipairs(names) do - if os.isfile(ROS .. "/lib/lib" .. n .. ".so") then - table.insert(out, n) - end - end - return out -end - --- ① 用到的消息包 → 各自的 typesupport 与 introspection 库 -local message_packages = { - "nav2_msgs", "sensor_msgs", "nav_msgs", "geometry_msgs", "std_msgs", - "tf2_msgs", "action_msgs", "unique_identifier_msgs", "builtin_interfaces", - "rosgraph_msgs", "rcl_interfaces", "service_msgs", - "type_description_interfaces", "statistics_msgs", +-- 1. ROS packages directly included by project source files. +-- Transitive dependencies are resolved through ament package metadata. +local ros_direct_packages = { + "rclcpp", + "rclcpp_action", + "nav2_msgs", + "nav_msgs", + "geometry_msgs", + "sensor_msgs", + "tf2_ros", + "tf2_sensor_msgs", + "pcl_conversions", + "action_msgs", } -local libs = {} -for _, pkg in ipairs(message_packages) do - for _, suffix in ipairs({ "__rosidl_typesupport_cpp", "__rosidl_typesupport_introspection_cpp" }) do - local name = pkg .. suffix - if os.isfile(ROS .. "/lib/lib" .. name .. ".so") then - table.insert(libs, name) - end - end -end --- ② rclcpp / tf2 / rmw 这一层 -for _, n in ipairs(existing({ - "rclcpp", "rclcpp_action", "rcl_action", "rcl", - "tf2", "tf2_ros", "tf2_sensor_msgs", "tf2_geometry_msgs", - "message_filters", "pcl_conversions", - "rosidl_typesupport_cpp", "rosidl_typesupport_c", - "rosidl_runtime_c", "rosidl_dynamic_typesupport", - "rmw", "rmw_implementation", "rmw_dds_common", - "rcutils", "rcpputils", "tracetools", - "rcl_logging_interface", "rcl_yaml_param_parser", - "libstatistics_collector", -})) do - table.insert(libs, n) -end +-- 2. ROS message typesupport libraries. +local message_packages = { + "nav2_msgs", + "sensor_msgs", + "nav_msgs", + "geometry_msgs", + "std_msgs", + "tf2_msgs", + "action_msgs", + "unique_identifier_msgs", + "builtin_interfaces", + "rosgraph_msgs", + "rcl_interfaces", + "service_msgs", + "type_description_interfaces", + "statistics_msgs", +} + +-- 3. Shared ROS configuration cache. +-- All ROS targets share the same dependency resolution result. +local ros_config_cache = nil + + +-- ============================================================================ +-- Common ROS target configuration +-- ============================================================================ --- ③ 公共编译选项(只能在 target 块内部调用:xmake 的 API 作用于"当前目标") local function ros_common() - add_includedirs(ros_includes) - add_defines("DEFAULT_RMW_IMPLEMENTATION=rmw_fastrtps_cpp") - add_linkdirs(ROS .. "/lib") - add_rpathdirs(ROS .. "/lib") + + on_load(function(target) + + -- -------------------------------------------------------------------- + -- Resolve ROS configuration. + -- + -- IMPORTANT: + -- This function is intentionally defined inside on_load(). + -- This ensures that os/path/io APIs are resolved in the script domain. + -- -------------------------------------------------------------------- + + local function get_ros_config() + + if ros_config_cache then + return ros_config_cache + end + + -- Discover ROS installation prefix. + local ROS = os.getenv("ROS_PREFIX") + + if ROS and ROS ~= "" then + + if not os.isdir(ROS .. "/include") + or not os.isdir(ROS .. "/lib") then + raise("Invalid ROS_PREFIX: " .. ROS) + end + + else + + local ament_prefix_path = os.getenv("AMENT_PREFIX_PATH") + ROS = nil + + if ament_prefix_path then + for prefix in string.gmatch( + ament_prefix_path, + "[^:]+" + ) do + + if os.isdir(prefix .. "/include") + and os.isdir(prefix .. "/lib") then + + ROS = prefix + break + end + end + end + + if not ROS then + raise( + "ROS installation not found. " + .. "Source ROS setup or set ROS_PREFIX." + ) + end + end + + -- ---------------------------------------------------------------- + -- Resolve include directories through ament metadata. + -- ---------------------------------------------------------------- + + local script = path.join( + target:scriptdir(), + "../../tools/resolve_ros_includes.py" + ) + + if not os.isfile(script) then + raise( + "ROS include resolver not found: " .. script + ) + end + + local output_file = path.join( + os.tmpdir(), + "sentry_nav_ros_include_dirs.txt" + ) + + local error_file = path.join( + os.tmpdir(), + "sentry_nav_ros_include_errors.txt" + ) + + -- Remove stale output before executing the resolver. + os.tryrm(output_file) + os.tryrm(error_file) + + -- Execute Python dependency resolver. + os.execv("python3", { + script, + "--prefix", ROS, + "--roots", table.concat(ros_direct_packages, ","), + }, { + stdout = output_file, + stderr = error_file, + }) + + -- Read generated include directories. + local file = io.open(output_file, "r") + + if not file then + + local error_message = "" + + local error_handle = io.open(error_file, "r") + if error_handle then + error_message = error_handle:read("*a") + error_handle:close() + end + + raise( + "Failed to read ROS dependency resolver output:\n" + .. error_message + ) + end + + local output = file:read("*a") + file:close() + + -- Read resolver diagnostics. + local errors = "" + + local error_handle = io.open(error_file, "r") + + if error_handle then + errors = error_handle:read("*a") + error_handle:close() + end + + if output == "" then + raise( + "ROS dependency resolver returned empty output:\n" + .. errors + ) + end + + -- Parse and deduplicate include directories. + -- Use an absolute path to avoid Xmake resolving it from the project root. + local project_include = path.join( + target:scriptdir(), + "include" + ) + + local ros_includes = {project_include} + + local include_seen = { + [project_include] = true + } + + for line in output:gmatch("[^\r\n]+") do + + line = line:gsub("^%s+", "") + line = line:gsub("%s+$", "") + + if line ~= "" and not include_seen[line] then + + table.insert(ros_includes, line) + include_seen[line] = true + + end + end + + if #ros_includes <= 1 then + raise( + "ROS dependency resolver returned no include directories." + ) + end + + -- ---------------------------------------------------------------- + -- Collect ROS message typesupport libraries. + -- ---------------------------------------------------------------- + + local libs = {} + + for _, pkg in ipairs(message_packages) do + + for _, suffix in ipairs({ + "__rosidl_typesupport_cpp", + "__rosidl_typesupport_introspection_cpp", + }) do + + local name = pkg .. suffix + + if os.isfile( + ROS .. "/lib/lib" .. name .. ".so" + ) then + + table.insert(libs, name) + + end + end + end + + -- ---------------------------------------------------------------- + -- Collect ROS runtime libraries. + -- ---------------------------------------------------------------- + + local runtime_libraries = { + "rclcpp", + "rclcpp_action", + "rcl_action", + "rcl", + "tf2", + "tf2_ros", + "tf2_sensor_msgs", + "tf2_geometry_msgs", + "message_filters", + "pcl_conversions", + "rosidl_typesupport_cpp", + "rosidl_typesupport_c", + "rosidl_runtime_c", + "rosidl_dynamic_typesupport", + "rmw", + "rmw_implementation", + "rmw_dds_common", + "rcutils", + "rcpputils", + "tracetools", + "rcl_logging_interface", + "rcl_yaml_param_parser", + "libstatistics_collector", + } + + for _, name in ipairs(runtime_libraries) do + + if os.isfile( + ROS .. "/lib/lib" .. name .. ".so" + ) then + + table.insert(libs, name) + + end + end + + -- Cache resolved configuration. + ros_config_cache = { + prefix = ROS, + includes = ros_includes, + libs = libs, + } + + return ros_config_cache + end + + -- -------------------------------------------------------------------- + -- Apply ROS configuration to current target. + -- -------------------------------------------------------------------- + + local config = get_ros_config() + + target:add("includedirs", config.includes) + + target:add( + "defines", + "DEFAULT_RMW_IMPLEMENTATION=rmw_fastrtps_cpp" + ) + + target:add( + "linkdirs", + config.prefix .. "/lib" + ) + + target:add( + "rpathdirs", + config.prefix .. "/lib" + ) + + target:add( + "linkgroups", + config.libs, + {group = true} + ) + + end) end --- ---- 纯算法核心(src/core/,刻意不依赖 ROS)---- + +-- ============================================================================ +-- Targets +-- ============================================================================ + +-- ---- ROS-independent algorithm core ---- + target("sentry_nav_core") set_kind("static") add_files("src/core/*.cpp") - add_includedirs("include", { public = true }) + add_includedirs("include", {public = true}) + + +-- ---- Unit tests ---- --- ---- 单元测试:不依赖 ROS,5 毫秒跑完 223 项 ---- --- xmake test 跑全部(推荐) --- xmake test test_self_filter_core/default 只跑一个(必须带 /default) --- xmake test -v 带上输出 --- xmake test -g unit 按 group 跑 --- --- 用 xmake 内置的 add_tests:测试程序返回 0 = 通过、非 0 = 失败,跟 xmake 的约定一致。 target("test_self_filter_core") set_kind("binary") add_files("tests/test_self_filter_core.cpp") @@ -115,6 +344,7 @@ target("test_self_filter_core") add_deps("sentry_nav_core") add_tests("default", {group = "unit"}) + target("test_waypoint_sequencer") set_kind("binary") add_files("tests/test_waypoint_sequencer.cpp") @@ -122,6 +352,7 @@ target("test_waypoint_sequencer") add_deps("sentry_nav_core") add_tests("default", {group = "unit"}) + target("test_geometry") set_kind("binary") add_files("tests/test_geometry.cpp") @@ -129,48 +360,43 @@ target("test_geometry") add_deps("sentry_nav_core") add_tests("default", {group = "unit"}) --- ---- 点云自滤节点 ---- + +-- ---- Point cloud self-filter ---- + target("self_filter") set_kind("binary") add_files("src/self_filter.cpp") - add_includedirs("/usr/include/pcl-1.15", "/usr/include/eigen3") add_deps("sentry_nav_core") - add_links("pcl_common", "pcl_io") - add_linkgroups(libs, { group = true }) + add_packages("pkgconfig::pcl_common") ros_common() --- ---- 航点巡逻节点 ---- + +-- ---- Waypoint patrol ---- + target("patrol") set_kind("binary") add_files("src/patrol.cpp") add_deps("sentry_nav_core") - add_linkgroups(libs, { group = true }) ros_common() --- ---- 导航测试客户端(C++ 版,替代原 tools/nav_client.py)---- --- 用法:build/linux/x86_64/release/nav_client [yaw度] [--force] --- 输出格式与原 Python 版一致(含导航耗时),文档按这个格式写。 + +-- ---- Navigation test client ---- + target("nav_client") set_kind("binary") add_files("src/nav_client.cpp") - add_linkgroups(libs, { group = true }) ros_common() --- ---- 运行时小节点(从 Python 移植,用户要求能 C++ 就 C++)---- --- odom_tf:/odom -> TF odom->base_link(sentry_up.sh 第 5 步用) + +-- ---- Runtime nodes ---- + target("odom_tf") set_kind("binary") add_files("src/odom_tf.cpp") - add_linkgroups(libs, { group = true }) ros_common() --- cmd_vel_relay:/cmd_vel_smoothed 优先转发到 /model/sentry/cmd_vel --- (sentry_up.sh 第 5.5 步用) + target("cmd_vel_relay") set_kind("binary") add_files("src/cmd_vel_relay.cpp") - add_linkgroups(libs, { group = true }) ros_common() - --- 编译数据库(compile_commands.json)的自动刷新规则定义在仓库根的 xmake.lua, --- 输出到仓库根 —— clangd 读的就是那里。 diff --git a/tools/resolve_ros_includes.py b/tools/resolve_ros_includes.py new file mode 100644 index 0000000..ed4adab --- /dev/null +++ b/tools/resolve_ros_includes.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +"""Resolve ROS 2 package include directories through the ament index.""" + +import argparse +import os +import sys +import xml.etree.ElementTree as ET +from pathlib import Path + + +def get_prefixes(explicit_prefix: str) -> list[Path]: + """Build an ordered list of ROS installation prefixes.""" + raw = [explicit_prefix] + raw.extend(os.environ.get("AMENT_PREFIX_PATH", "").split(os.pathsep)) + + prefixes = [] + seen = set() + + for item in raw: + if not item: + continue + + path = Path(item).resolve() + if path.is_dir() and path not in seen: + prefixes.append(path) + seen.add(path) + + return prefixes + + +def find_package(name: str, prefixes: list[Path]): + """Find a package through the ament resource index.""" + for prefix in prefixes: + marker = ( + prefix + / "share/ament_index/resource_index/packages" + / name + ) + manifest = prefix / "share" / name / "package.xml" + + if marker.is_file(): + if not manifest.is_file(): + raise RuntimeError( + f"Package '{name}' is indexed but package.xml " + f"is missing: {manifest}" + ) + return prefix, manifest + + return None + + +def get_dependencies(manifest: Path) -> list[str]: + """Read compile-relevant dependencies from package.xml.""" + root = ET.parse(manifest).getroot() + + dependency_tags = { + "depend", + "build_depend", + "build_export_depend", + "buildtool_export_depend", + } + + dependencies = set() + + for element in root: + tag = element.tag.split("}")[-1] + + if tag not in dependency_tags: + continue + + name = (element.text or "").strip() + if name: + dependencies.add(name) + + return sorted(dependencies) + + +def resolve(roots: list[str], prefixes: list[Path]) -> list[Path]: + """Recursively resolve packages and collect include directories.""" + visited = set() + include_dirs = [] + include_seen = set() + + def add_include(path: Path): + path = path.resolve() + if path.is_dir() and path not in include_seen: + include_dirs.append(path) + include_seen.add(path) + + def visit(name: str, is_root: bool = False): + if name in visited: + return + + visited.add(name) + result = find_package(name, prefixes) + + if result is None: + message = f"Package '{name}' not found in ament index" + + if is_root: + raise RuntimeError(message) + + print(f"[WARN] {message}", file=sys.stderr) + return + + prefix, manifest = result + + # Common ROS installation include directory. + add_include(prefix / "include") + + # ROS packages commonly install headers under include/. + add_include(prefix / "include" / name) + + print(f"[ROS DEP] {name}", file=sys.stderr) + + for dependency in get_dependencies(manifest): + visit(dependency) + + for root in roots: + visit(root, is_root=True) + + return include_dirs + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--prefix", required=True) + parser.add_argument("--roots", required=True) + args = parser.parse_args() + + roots = [item for item in args.roots.split(",") if item] + prefixes = get_prefixes(args.prefix) + + if not prefixes: + raise RuntimeError("No valid ROS installation prefixes found") + + include_dirs = resolve(roots, prefixes) + + for directory in include_dirs: + print(directory) + + +if __name__ == "__main__": + try: + main() + except Exception as error: + print(f"[ERROR] {error}", file=sys.stderr) + sys.exit(1)