Files
chenlin c32df70326
Checks / Layout, translation and Colab checks (push) Has been cancelled
Checks / Ruff (push) Has been cancelled
Checks / Framework tests (native backend, CPU) (push) Has been cancelled
Checks / Portable Rust controller (push) Has been cancelled
release: v0.1 generic robot training and application platform
2026-11-05 11:05:01 +08:00

256 lines
12 KiB
Rust

//! Compile in every task's deploy hook; generate the DDS type descriptors, and
//! link the two native libraries.
//!
//! The hooks come first and run for every build (`task_hooks`). The rest is the
//! robot's bus and runs only for `device`.
//!
//! The descriptors are **generated here from `../dds/idl/`, never checked in**.
//! `idlc` turns an `.idl` into a `dds_topic_descriptor_t` that fixes the wire
//! layout and the type hash DDS matches on; generating it from the same IDL with
//! the same compiler the robot's side used is what makes the two byte-compatible
//! by construction. A descriptor checked in beside an IDL that later changed is
//! the failure this avoids -- and it would not be a build error, it would be a
//! reader that never pairs and a topic that stays empty.
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::process::Command;
/// Every task's deploy library, compiled in as a module of `src/hook.rs`.
///
/// A task's hook is `tasks/<family>/<task>/deploy/lib.rs`, and its task id is the
/// dotted path between `tasks/` and `deploy/`. For example,
/// `tasks/example/locomotion/` has task ID `example.locomotion`. This writes
/// `$OUT_DIR/task_hooks.rs`: one `#[path]` module per library, `TASKS`, and a
/// `builder` that maps an id to the library's `build`. So the crate's own source
/// names no task, and a task adds a hook by adding the file -- nothing here, in
/// `scripts/` or in any host changes.
///
/// Runs for every build rather than only `device`, because every host runs the
/// hooks: the browser and `play`'s extension are this crate too. A checkout with
/// no `tasks/` (the crate built on its own) compiles an empty table.
fn task_hooks() {
let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
let out = PathBuf::from(std::env::var("OUT_DIR").unwrap());
let root = manifest.join("../../tasks");
let mut found: Vec<(String, PathBuf)> = Vec::new();
if root.is_dir() {
find_task_hooks(&root, &root, &mut found);
// A directory: Cargo scans it whole, so a library added anywhere under it
// re-runs this. Editing an existing library needs nothing -- rustc
// records every `#[path]` module it compiles as an input.
println!("cargo:rerun-if-changed={}", root.display());
}
found.sort();
let mut src = String::from(
"// Generated by build.rs::task_hooks from tasks/**/deploy/lib.rs. Do not edit.\n",
);
for (id, lib) in &found {
let lib = lib.canonicalize().unwrap_or_else(|_| lib.clone());
// `allow`: the `__` that keeps `a.b_c` and `a_b.c` apart is not snake case.
writeln!(
src,
"#[path = {:?}]\n#[allow(non_snake_case)]\nmod {};",
lib.display().to_string(),
module_for(id)
)
.unwrap();
}
let ids: Vec<String> = found.iter().map(|(id, _)| format!("{id:?}")).collect();
writeln!(src, "pub const TASKS: &[&str] = &[{}];", ids.join(", ")).unwrap();
src.push_str("pub fn builder(task: &str) -> Option<crate::hook::HookBuilder> {\n match task {\n");
for (id, _) in &found {
writeln!(src, " {id:?} => Some({}::build),", module_for(id)).unwrap();
}
src.push_str(" _ => None,\n }\n}\n");
// Written only when it changed: a rewrite with the same bytes would still
// move its mtime and recompile the crate for nothing.
let path = out.join("task_hooks.rs");
if std::fs::read_to_string(&path).ok().as_deref() != Some(src.as_str()) {
std::fs::write(&path, src).expect("write task_hooks.rs");
}
}
/// `(task id, deploy/lib.rs)` for every task under `dir`, depth first.
fn find_task_hooks(root: &Path, dir: &Path, found: &mut Vec<(String, PathBuf)>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
if !path.is_dir() || name.starts_with('.') || name == "__pycache__" {
continue;
}
if name == "deploy" {
let lib = path.join("lib.rs");
if lib.is_file() {
let rel = dir.strip_prefix(root).expect("under tasks/");
let id: Vec<String> =
rel.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect();
found.push((id.join("."), lib));
}
continue;
}
find_task_hooks(root, &path, found);
}
}
/// The task ID `example.locomotion` becomes the module name `task_example__locomotion`.
fn module_for(id: &str) -> String {
format!("task_{}", id.replace('.', "__"))
}
/// Where CycloneDDS is installed. `/usr/local` is where a source build lands and
/// where the board image puts it; override for anything else.
fn cyclonedds_root() -> PathBuf {
PathBuf::from(std::env::var("CYCLONEDDS_HOME").unwrap_or_else(|_| "/usr/local".into()))
}
fn main() {
task_hooks();
// `play` on macOS. A Python extension leaves CPython's own symbols
// undefined, for the interpreter that loads it to supply, and Apple's
// linker refuses an undefined symbol unless told it is looked up at load
// time. Linux's accepts one as it is, and Windows links `python3.dll`
// instead (`generate-import-lib`, Cargo.toml). Here rather than in a
// `.cargo/config.toml`, so a Mac building the crate natively gets it as
// well as the cross build, and a `RUSTFLAGS` cannot replace it unnoticed.
if std::env::var("CARGO_FEATURE_PY").is_ok()
&& std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos")
{
println!("cargo:rustc-cdylib-link-arg=-undefined");
println!("cargo:rustc-cdylib-link-arg=dynamic_lookup");
}
// Nothing below is about the policy; it is all about the robot's bus. A build
// without `device` -- the browser, and any host that only wants the
// observation and FSM logic -- has no idlc, no CycloneDDS and no C compiler
// for a target that cannot use them, so this must not merely fail quietly
// later: it must not run.
if std::env::var("CARGO_FEATURE_DEVICE").is_err() {
println!("cargo:rerun-if-changed=build.rs");
return;
}
let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
let out = PathBuf::from(std::env::var("OUT_DIR").unwrap());
let dds = cyclonedds_root();
// The one IDL source, always. Which IDL a binary was built against is not
// visible in the binary and decides whether it can talk to the robot, so the
// build is kept hermetic: everything it consumes is in the repository. The
// committed copy's provenance -- the mbus revision it came from -- is
// recorded in ../dds/README.md, which is where freshness is checked.
let idl_dir = manifest.join("../dds/idl");
// `idl_common.idl` is listed even though it carries no topic. idlc generates
// a header **only for the files it is given**, and the other three
// `#include "idl_common.h"` -- so leaving it out does not fail the build on a
// machine that happens to have mbus installed. It silently compiles against
// `/usr/local/include/idl_common.h`, a header from a different build of the
// IDL. Found by the cross-compilation container, which has no mbus in it.
let idls = [
"idl_common.idl",
"idl_motor_control.idl",
"idl_robot_control.idl",
"idl_robot_control_raw.idl",
"idl_imu.idl",
];
println!("cargo:rerun-if-changed={}", idl_dir.display());
println!("cargo:rerun-if-env-changed=CYCLONEDDS_HOME");
// idlc writes next to its input, so the IDL is copied into OUT_DIR first --
// a build must not write into the source tree.
for f in std::fs::read_dir(&idl_dir).unwrap_or_else(|e| panic!("no {}: {e}", idl_dir.display())) {
let f = f.unwrap().path();
if f.extension().is_some_and(|e| e == "idl") {
std::fs::copy(&f, out.join(f.file_name().unwrap())).unwrap();
}
}
let mut build = cc::Build::new();
build.include(&out).include(dds.join("include"));
for idl in idls {
let status = Command::new("idlc")
.arg(idl)
.current_dir(&out)
.status()
.unwrap_or_else(|e| panic!("idlc not found ({e}); it ships with CycloneDDS"));
assert!(status.success(), "idlc failed on {idl}");
build.file(out.join(Path::new(idl).with_extension("c")));
}
build.compile("mjrl_dds_types");
// Rust mirrors of the generated IDL structs, generated in turn. These are
// nested (`Control` holds an array of `MotorCmd`, `State` holds an `ImuData`)
// and they change whenever the robot's message set does, so hand-mirroring
// them would be a standing invitation to a silent layout drift.
let mut bind = bindgen::Builder::default().derive_default(true);
for idl in idls {
bind = bind.header(out.join(Path::new(idl).with_extension("h")).to_string_lossy());
}
bind.clang_arg(format!("-I{}", out.display()))
.clang_arg(format!("-I{}", dds.join("include").display()))
.allowlist_type("MotorControl_.*")
.allowlist_type("RobotControl_.*")
.allowlist_type("RobotControlRaw_.*")
.allowlist_type("Imu_.*")
.allowlist_type("Common_.*")
.allowlist_var(".*_desc")
.generate()
.expect("bindgen failed on the idlc-generated headers")
.write_to_file(out.join("idl_bindings.rs"))
.expect("cannot write idl_bindings.rs");
println!("cargo:rustc-link-search=native={}", dds.join("lib").display());
println!("cargo:rustc-link-lib=dylib=ddsc");
// A macOS host has no `ldconfig`: a library under a prefix of one's own --
// the only place a source build lands without sudo -- is found through the
// binary's own rpath or not at all, and `cargo test` then links and aborts
// on `Library not loaded: @rpath/libddsc.11.dylib`. Linux leaves this to
// the loader's cache (section 2.2 of docs/AGENT_SETUP.md) and the board's
// build runs in Docker with the library where its loader looks, so the
// rpath is written for the macOS host alone, from the same `CYCLONEDDS_HOME`
// the library was linked from. Measured on an M3 Max on 2026-10-08: without
// it gate F fails after linking; with it, 195 crate tests list and pass.
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
println!("cargo:rustc-link-arg=-Wl,-rpath,{}", dds.join("lib").display());
}
// The Rust mirror of `rknn_tensor_attr` is checked against Rockchip's own
// header, and this compiles **always** -- headers are portable, only the
// `.so` is aarch64. So the FFI layout is verified on a development machine,
// where a mismatch is a failing test rather than a wrong number read off the
// NPU on a robot. Both files are Rockchip's and are fetched, not committed;
// without the check below a missing header surfaces as a C compiler error
// that does not say where the file was supposed to come from.
let rknpu2 = manifest.join("vendor/rknpu2");
assert!(
rknpu2.join("include/rknn_api.h").is_file(),
"vendor/rknpu2/include/rknn_api.h is missing: run `bash vendor/rknpu2/fetch.sh` \
(see vendor/rknpu2/README.md)"
);
println!("cargo:rerun-if-changed=src/rknn_layout_probe.c");
cc::Build::new()
.file("src/rknn_layout_probe.c")
.include(rknpu2.join("include"))
.compile("rknn_layout_probe");
// The NPU runtime is aarch64-only. The feature, not the architecture, is the
// switch: cross-compiling for the board from an x86 host has to link it, and
// a host-native build must not.
if std::env::var("CARGO_FEATURE_RKNN").is_ok() {
let lib = rknpu2.join("lib/aarch64");
assert!(
lib.join("librknnrt.so").is_file(),
"vendor/rknpu2/lib/aarch64/librknnrt.so is missing: run \
`bash vendor/rknpu2/fetch.sh` (see vendor/rknpu2/README.md)"
);
println!("cargo:rustc-link-search=native={}", lib.display());
println!("cargo:rustc-link-lib=dylib=rknnrt");
}
}