Skip to content

Add built-in math functions to the scripting language - #1308

Open
physicalfleet-dev-team wants to merge 1 commit into
BehaviorTree:masterfrom
physicalfleet-dev-team:script-math-functions
Open

physicalfleet-dev-team wants to merge 1 commit into
BehaviorTree:masterfrom
physicalfleet-dev-team:script-math-functions

Conversation

@physicalfleet-dev-team

Copy link
Copy Markdown

Hi Davide! 👋

This adds built-in math functions to the scripting language, as requested in #1141: abs(x), sqrt(x), pow(x, y), exp(x), log(x), log10(x), sin/cos/tan/asin/acos/atan(x), atan2(y, x), floor/ceil/round(x), min(x, y), max(x, y) and clamp(x, lo, hi). Today these need ternary workarounds or a custom node, e.g. for distance thresholds or angle checks in preconditions:

<Script code="dist := sqrt(pow(dx, 2) + pow(dy, 2))" />
<MoveTo _skipIf="abs(heading_error) < 0.05" />

Closes #1141

How it works

  • Tokenizer: a new Comma token.
  • Parser: in parsePrefix(), an identifier directly followed by ( is parsed as a call of a built-in function (parseFunctionCall). The arguments are full expressions separated by commas. An unknown function name or a wrong number of arguments is a parse error, so ValidateScript() catches it when the tree is loaded, e.g. Function 'pow' at position 0 expects 2 argument(s), got 1. Calls count towards the existing nesting and expression-height limits.
  • AST: ExprFunctionCall in operators.hpp with a small fixed table of builtins (name, arity, function pointer). The arguments must be numbers, or strings holding a number (like the arithmetic operators accept); the result is a double, like the results of + - * /. A non-numeric or uninitialized argument raises a RuntimeError when the script runs. clamp() with lo > hi throws instead of hitting std::clamp's undefined behavior; other domain errors follow IEEE like division does (sqrt(-1) is NaN).
  • Blackboard entries named like a function keep working as variables: only name( is a call, so min + min(1, 2) works when min is an entry.

One behavior change to mention: before, name(...) was silently parsed as two statements (name and then (...), since semicolons are optional), so a script like abs(-3) returned -3 if an entry abs existed and failed otherwise. Now it is a call, and an unknown name( is rejected by ValidateScript(). I couldn't think of a reason anyone would rely on the old reading, but happy to change it (e.g. only treat known builtins as calls) if you prefer.

I picked the function-call syntax and the set from the issue and the closed #1213. Happy to trim the set or rename anything.

Tests

Three new tests in tests/script_parser_test.cpp:

  • ParserTest.MathFunctions: every builtin with int, double and numeric-string arguments from literals and the blackboard.
  • ParserTest.MathFunctionsInExpressions: nested calls, operators, unary minus, ternary, assignment, whitespace around arguments, and a blackboard entry named min.
  • ParserTest.MathFunctionErrors: unknown functions, wrong arity, malformed argument lists, 1, 2, error messages, non-numeric and uninitialized arguments, clamp bounds, and the nesting limit.

On an M1 Mac (Apple clang, CMake Release build with -DBTCPP_GROOT_INTERFACE=OFF -DBTCPP_EXAMPLES=OFF, SQLite logging on with the macOS SDK's SQLite, GoogleTest 1.15.2):

  • ./build/tests/behaviortree_cpp_test --gtest_filter='ParserTest.*': 28/28 passed (including the 3 new tests)
  • ctest --test-dir build --output-on-failure --repeat until-pass:3 -E "<the macOS CI exclusions>": 680/680 passed, none needed a retry
  • pre-commit run --files <changed files>: clang-format 17.0.6, codespell and the file checks pass (clang-tidy skipped, clangd-21 isn't installed here)

Thanks for maintaining BT.CPP, it's a joy to build on! 🙂

Scripts can now call abs, sqrt, pow, exp, log, log10, sin, cos, tan,
asin, acos, atan, atan2, floor, ceil, round, min, max and clamp, e.g.
"dist := sqrt(pow(dx, 2) + pow(dy, 2))".

An identifier followed by '(' is parsed as a call of a built-in
function. Unknown functions and wrong argument counts are parse errors,
so ValidateScript() reports them when the tree is loaded. Arguments
must be numbers (or numeric strings) and the result is a double, like
the arithmetic operators.

Closes BehaviorTree#1141

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Scripting math operators

1 participant