From 8441b4a06d6d09dcfb0b0f704df4d847d1437b92 Mon Sep 17 00:00:00 2001 From: Erin Catto Date: Tue, 30 Jun 2026 10:57:46 -0700 Subject: [PATCH] Missing functions (#21) - add some missing functions - added config.h for users that vendor Box3D - joint unit tests - improve joint limit consistency - extend build matrix --- .github/workflows/build.yml | 287 ++++++++--------- docs/foundation.md | 9 + include/box3d/base.h | 11 + include/box3d/box3d.h | 3 +- include/box3d/config.h | 31 ++ include/box3d/constants.h | 12 +- include/box3d/types.h | 24 +- samples/sample_robustness.cpp | 193 ----------- shared/CMakeLists.txt | 2 +- src/CMakeLists.txt | 3 +- src/body.c | 14 +- src/body.h | 2 +- src/ctz.h | 2 +- src/joint.c | 29 +- src/parallel_for.h | 2 +- src/physics_world.c | 22 ++ src/platform.h | 10 +- src/prismatic_joint.c | 41 +++ src/recording.c | 2 +- src/recording.h | 4 +- src/recording_replay.c | 6 +- src/recording_replay.h | 2 +- src/revolute_joint.c | 19 +- src/solver.c | 2 +- src/solver.h | 2 +- src/spherical_joint.c | 18 +- src/types.c | 7 + test/CMakeLists.txt | 1 + test/main.c | 2 + test/test_joint.c | 581 ++++++++++++++++++++++++++++++++++ test/test_recording.c | 9 +- 31 files changed, 930 insertions(+), 422 deletions(-) create mode 100644 include/box3d/config.h create mode 100644 test/test_joint.c diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ff98037..f50869d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -2,58 +2,77 @@ name: CI Build on: + push: + branches: [ main ] + pull_request: + branches: [ main ] workflow_dispatch: env: - BUILD_TYPE: Debug + BUILD_TYPE: Debug jobs: - build-ubuntu-gcc: - name: ubuntu-gcc - runs-on: ubuntu-latest - if: github.event_name == 'push' || github.event.pull_request.draft == false - timeout-minutes: 4 + test: + name: ${{ matrix.name }} + runs-on: ${{ matrix.os }} + timeout-minutes: ${{ matrix.timeout || 4 }} + if: github.event_name != 'pull_request' || github.event.pull_request.draft == false + strategy: + fail-fast: false + matrix: + include: + - name: ubuntu-gcc + os: ubuntu-latest + test: ./bin/test + - name: ubuntu-clang + os: ubuntu-latest + args: '-DCMAKE_CXX_COMPILER=clang++-18 -DCMAKE_C_COMPILER=clang-18 -DCMAKE_C_FLAGS="-fsanitize=thread -fno-omit-frame-pointer" -DCMAKE_CXX_FLAGS="-fsanitize=thread -fno-omit-frame-pointer" -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=thread"' + test: ./bin/test + - name: ubuntu-clang-msan + os: ubuntu-latest + timeout: 10 + args: '-DCMAKE_CXX_COMPILER=clang++-18 -DCMAKE_C_COMPILER=clang-18 -DCMAKE_C_FLAGS="-fsanitize=memory -fsanitize-memory-track-origins=1 -fno-omit-frame-pointer" -DCMAKE_CXX_FLAGS="-fsanitize=memory -fsanitize-memory-track-origins=1 -fno-omit-frame-pointer" -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=memory"' + test: ./bin/test + msan-options: abort_on_error=1:halt_on_error=1 + - name: macos + os: macos-latest + args: -DBOX3D_SANITIZE=ON + test: ./bin/test + - name: windows + os: windows-latest + msvc: true + args: -DBOX3D_SANITIZE=ON + test: ./bin/Debug/test + # Box3D is width-4 SIMD only, so this covers the clang-cl toolchain, not AVX2. + - name: windows-clang-cl + os: windows-latest + msvc: true + args: -T ClangCL + test: ./bin/Debug/test + - name: windows-arm64 + os: windows-11-arm + args: -A arm64 -DBOX3D_DISABLE_SIMD=TRUE -DBOX3D_SANITIZE=ON + test: ./bin/Debug/test + - name: ubuntu-gcc-double + os: ubuntu-latest + args: -DBOX3D_DOUBLE_PRECISION=ON + test: ./bin/test + - name: windows-double + os: windows-latest + msvc: true + args: -DBOX3D_DOUBLE_PRECISION=ON -DBOX3D_SANITIZE=ON + test: ./bin/Debug/test steps: - uses: actions/checkout@v6 - - name: Configure CMake - run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX3D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON - - - name: Build - run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} - - - name: Test - working-directory: ${{github.workspace}}/build - run: ./bin/test - - build-ubuntu-clang: - name: ubuntu-clang - runs-on: ubuntu-latest - if: github.event_name == 'push' || github.event.pull_request.draft == false - timeout-minutes: 4 - steps: - - uses: actions/checkout@v6 + - name: Setup MSVC dev command prompt + if: ${{ matrix.msvc }} + uses: TheMrMilchmann/setup-msvc-dev@v4 + with: + arch: x64 - name: Configure CMake - run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCMAKE_CXX_COMPILER=clang++-18 -DCMAKE_C_COMPILER=clang-18 -DCMAKE_C_FLAGS="-fsanitize=thread -fno-omit-frame-pointer" -DCMAKE_CXX_FLAGS="-fsanitize=thread -fno-omit-frame-pointer" -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=thread" -DBOX3D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON - - - name: Build - run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} - - - name: Test - working-directory: ${{github.workspace}}/build - run: ./bin/test - - build-ubuntu-clang-msan: - name: ubuntu-clang-msan - runs-on: ubuntu-latest - if: false # todo re-enable once repo is public - timeout-minutes: 10 - steps: - - uses: actions/checkout@v6 - - - name: Configure CMake - run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCMAKE_CXX_COMPILER=clang++-18 -DCMAKE_C_COMPILER=clang-18 -DCMAKE_C_FLAGS="-fsanitize=memory -fsanitize-memory-track-origins=1 -fno-omit-frame-pointer" -DCMAKE_CXX_FLAGS="-fsanitize=memory -fsanitize-memory-track-origins=1 -fno-omit-frame-pointer" -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=memory" -DBOX3D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON + run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX3D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON ${{ matrix.args }} - name: Build run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} @@ -61,132 +80,88 @@ jobs: - name: Test working-directory: ${{github.workspace}}/build env: - MSAN_OPTIONS: abort_on_error=1:halt_on_error=1 + MSAN_OPTIONS: ${{ matrix['msan-options'] || '' }} + run: ${{ matrix.test }} + + # mingw needs some extra setup so keeping it separate from the matrix. + build-windows-mingw: + name: windows-mingw + runs-on: windows-latest + timeout-minutes: 4 + if: github.event_name != 'pull_request' || github.event.pull_request.draft == false + defaults: + run: + shell: msys2 {0} + steps: + - uses: actions/checkout@v6 + + - name: Setup MSYS2 UCRT64 + uses: msys2/setup-msys2@v2 + with: + msystem: UCRT64 + update: true + install: >- + mingw-w64-ucrt-x86_64-gcc + mingw-w64-ucrt-x86_64-cmake + mingw-w64-ucrt-x86_64-ninja + + - name: Configure CMake + run: cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX3D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON + + - name: Build + run: cmake --build build --config ${{env.BUILD_TYPE}} + + - name: Test + working-directory: build run: ./bin/test - build-macos: - name: macos - runs-on: macos-latest - if: github.event_name == 'push' || github.event.pull_request.draft == false - timeout-minutes: 4 + samples: + name: ${{ matrix.name }} + runs-on: ${{ matrix.os }} + timeout-minutes: 8 + if: github.event_name != 'pull_request' || github.event.pull_request.draft == false + strategy: + fail-fast: false + matrix: + include: + - name: samples-ubuntu-gcc-static + os: ubuntu-latest + linux-deps: true + args: -DBUILD_SHARED_LIBS=OFF + - name: samples-macos-static + os: macos-latest + args: -DBUILD_SHARED_LIBS=OFF + - name: samples-macos-dynamic + os: macos-latest + args: -DBUILD_SHARED_LIBS=ON + - name: samples-windows-static + os: windows-latest + msvc: true + args: -DBUILD_SHARED_LIBS=OFF + - name: samples-windows-double + os: windows-latest + msvc: true + args: -DBOX3D_DOUBLE_PRECISION=ON -DBUILD_SHARED_LIBS=OFF + - name: samples-windows-dynamic + os: windows-latest + msvc: true + args: -DBUILD_SHARED_LIBS=ON steps: - uses: actions/checkout@v6 - - name: Configure CMake - run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX3D_SAMPLES=OFF -DBOX3D_SANITIZE=ON -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON - - - name: Build - run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} - - - name: Test - working-directory: ${{github.workspace}}/build - run: ./bin/test - - build-windows: - name: windows - runs-on: windows-latest - if: github.event_name == 'push' || github.event.pull_request.draft == false - timeout-minutes: 4 - steps: - - uses: actions/checkout@v6 - - - name: Configure CMake - run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX3D_SAMPLES=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON - - - name: Build - run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} - - - name: Test - working-directory: ${{github.workspace}}/build - run: ./bin/${{env.BUILD_TYPE}}/test - - build-ubuntu-double: - name: ubuntu-double-precision - runs-on: ubuntu-latest - if: github.event_name == 'push' || github.event.pull_request.draft == false - timeout-minutes: 4 - steps: - - uses: actions/checkout@v6 - - - name: Configure CMake - run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX3D_DOUBLE_PRECISION=ON -DBOX3D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON - - - name: Build - run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} - - - name: Test - working-directory: ${{github.workspace}}/build - run: ./bin/test - - build-windows-double: - name: windows-double-precision - runs-on: windows-latest - if: github.event_name == 'push' || github.event.pull_request.draft == false - timeout-minutes: 4 - steps: - - uses: actions/checkout@v6 - - - name: Configure CMake - run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX3D_DOUBLE_PRECISION=ON -DBOX3D_SAMPLES=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON - - - name: Build - run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} - - - name: Test - working-directory: ${{github.workspace}}/build - run: ./bin/${{env.BUILD_TYPE}}/test - - samples-windows: - name: samples-windows - runs-on: windows-latest - if: github.event_name == 'push' || github.event.pull_request.draft == false - timeout-minutes: 6 - steps: - - - uses: actions/checkout@v6 - - name: Setup MSVC dev command prompt + if: ${{ matrix.msvc }} uses: TheMrMilchmann/setup-msvc-dev@v4 with: arch: x64 - - name: Configure CMake - run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=Release -DBOX3D_SAMPLES=ON -DBUILD_SHARED_LIBS=OFF -DBOX3D_UNIT_TESTS=OFF - - - name: Build - run: cmake --build ${{github.workspace}}/build --config Release - - samples-macos: - name: samples-macos - runs-on: macos-latest - if: github.event_name == 'push' || github.event.pull_request.draft == false - timeout-minutes: 6 - steps: - - uses: actions/checkout@v6 + # sokol_app needs X11/Xi/Xcursor + GL, the file dialog needs GTK3. + - name: Install Linux sample dependencies + if: ${{ matrix['linux-deps'] }} + run: sudo apt-get update && sudo apt-get install -y libgl1-mesa-dev libx11-dev libxi-dev libxcursor-dev libgtk-3-dev - name: Configure CMake - run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=Release -DBOX3D_SAMPLES=ON -DBUILD_SHARED_LIBS=OFF -DBOX3D_UNIT_TESTS=OFF + run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=Release -DBOX3D_SAMPLES=ON -DBOX3D_UNIT_TESTS=OFF ${{ matrix.args }} - name: Build run: cmake --build ${{github.workspace}}/build --config Release - - samples-windows-double: - name: samples-windows-double-precision - runs-on: windows-latest - if: github.event_name == 'push' || github.event.pull_request.draft == false - timeout-minutes: 6 - steps: - - - uses: actions/checkout@v6 - - - name: Setup MSVC dev command prompt - uses: TheMrMilchmann/setup-msvc-dev@v4 - with: - arch: x64 - - - name: Configure CMake - run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=Release -DBOX3D_DOUBLE_PRECISION=ON -DBOX3D_SAMPLES=ON -DBUILD_SHARED_LIBS=OFF -DBOX3D_UNIT_TESTS=OFF - - - name: Build - run: cmake --build ${{github.workspace}}/build --config Release - \ No newline at end of file diff --git a/docs/foundation.md b/docs/foundation.md index 71a5a17..607b266 100644 --- a/docs/foundation.md +++ b/docs/foundation.md @@ -175,6 +175,15 @@ void MyFinishTask(void* userTask, void* userContext) } ``` +`MyFinishTask` must block until the task has completed. Because the step blocks here on the tasks it +spawned, `b3World_Step` holds its stack across every fork and join inside the step. This has a +consequence for how you drive it. Run `b3World_Step` from a thread you can dedicate to the step, or +from a fiber that `MyFinishTask` can park so the underlying thread is freed to run the queued tasks. +In a job system that cannot park a job's stack, do not call `b3World_Step` from inside a job: a job +that blocks on the sub-jobs it spawned without yielding its thread starves the workers it is waiting +on and can deadlock. The alternative is help-while-wait, where the waiting thread runs other pending +tasks itself. This is what the in-tree scheduler does, which is why it needs no fiber. + Box3D ships an in-tree scheduler (`src/scheduler.h`) used by the test suite and samples. You can adapt it or use it directly: diff --git a/include/box3d/base.h b/include/box3d/base.h index 595b74f..2c0bb93 100644 --- a/include/box3d/base.h +++ b/include/box3d/base.h @@ -6,9 +6,19 @@ #include #include +// Compile-time options. Edit box3d/config.h, or define BOX3D_USER_CONFIG to +// point at your own copy. +#ifdef BOX3D_USER_CONFIG +#include BOX3D_USER_CONFIG +#endif +#include "config.h" + // clang-format off // // Shared library macros +// Predefine BOX3D_EXPORT to reuse an existing export/import scheme, for example +// when compiling Box3D into another shared library. +#ifndef BOX3D_EXPORT #if defined(_WIN32) && defined(box3d_EXPORTS) // build the Windows DLL #define BOX3D_EXPORT __declspec(dllexport) @@ -22,6 +32,7 @@ // static library #define BOX3D_EXPORT #endif +#endif // C++ macros #ifdef __cplusplus diff --git a/include/box3d/box3d.h b/include/box3d/box3d.h index 9d0cfa1..2275663 100644 --- a/include/box3d/box3d.h +++ b/include/box3d/box3d.h @@ -500,7 +500,7 @@ B3_API b3BodyType b3Body_GetType( b3BodyId bodyId ); /// properties regardless of the automatic mass setting. B3_API void b3Body_SetType( b3BodyId bodyId, b3BodyType type ); -/// Set the body name. Up to B3_NAME_LENGTH characters including null termination. +/// Set the body name. Up to B3_BODY_NAME_LENGTH characters including null termination. B3_API void b3Body_SetName( b3BodyId bodyId, const char* name ); /// Get the body name. @@ -1382,7 +1382,6 @@ B3_API float b3PrismaticJoint_GetSpeed( b3JointId jointId ); * @defgroup revolute_joint Revolute Joint * @brief A revolute joint allows for relative rotation about a single axis with no relative translation. * - * The revolute joint is probably the most common joint. It can be used for ragdolls and chains. * Also called a *hinge* or *pin* joint. * @{ */ diff --git a/include/box3d/config.h b/include/box3d/config.h new file mode 100644 index 0000000..2790fc0 --- /dev/null +++ b/include/box3d/config.h @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +// Box3D compile-time options. +// +// Normally set by the CMake BOX3D_* options. If you build Box3D without its +// CMake (dropping the sources into another project), set them here so the +// library and your code agree. Edit this file, or keep your settings elsewhere +// and point Box3D at them from your build: +// +// #define BOX3D_USER_CONFIG "my_box3d_config.h" +// +// A define passed on the compiler command line still wins over this file. + +// Large world mode. Stores world positions in double precision. Affects ABI. +//#define BOX3D_DOUBLE_PRECISION + +// Build the scalar fallback instead of SSE2/NEON. +//#define BOX3D_DISABLE_SIMD + +// Enable internal validation in debug builds. +//#define BOX3D_VALIDATE + +// Decorate the public API with your own export macro instead of Box3D's +// box3d_EXPORTS/BOX3D_DLL scheme, for example when compiling Box3D into another +// shared library. A single value cannot switch between dllexport and dllimport, +// so this suits embedding more than shipping Box3D as its own DLL. +//#define BOX3D_EXPORT MYENGINE_API + diff --git a/include/box3d/constants.h b/include/box3d/constants.h index 1b07efa..e32b737 100644 --- a/include/box3d/constants.h +++ b/include/box3d/constants.h @@ -98,8 +98,16 @@ B3_API float b3GetStallThreshold( void ); #define B3_TIME_TO_SLEEP 0.5f /// Maximum length of the body name. Can be 0 if you don't need names. -#ifndef B3_NAME_LENGTH -#define B3_NAME_LENGTH 18 +/// Note: this gates recording capability. +#ifndef B3_BODY_NAME_LENGTH +#define B3_BODY_NAME_LENGTH 18 +#endif + +/// Maximum length of the shape name. Can be 0 if you don't need names. +/// Note: this gates recording capability. +/// todo waiting on this because it breaks existing recordings +#ifndef B3_SHAPE_NAME_LENGTH +#define B3_SHAPE_NAME_LENGTH 18 #endif /// The maximum number of contact points between two touching shapes. diff --git a/include/box3d/types.h b/include/box3d/types.h index 76af638..2c75977 100644 --- a/include/box3d/types.h +++ b/include/box3d/types.h @@ -30,7 +30,12 @@ typedef void b3TaskCallback( void* taskContext ); /// @ingroup world typedef void* b3EnqueueTaskCallback( b3TaskCallback* task, void* taskContext, void* userContext, const char* taskName ); -/// Finishes a user task object that wraps a Box3D task. +/// Finishes a user task object that wraps a Box3D task. This must block until the task has completed. +/// The step blocks here on the tasks it spawned, so b3World_Step holds its stack across every +/// fork/join. Drive it from a thread you can dedicate to the step, or from a fiber this callback can +/// park to free the underlying thread. In a job system that cannot park a job's stack, do not call +/// b3World_Step from inside a job: a job that blocks on its own sub-jobs without yielding its thread +/// can deadlock. The in-tree scheduler instead runs other pending tasks on the waiting thread. /// @ingroup world typedef void b3FinishTaskCallback( void* userTask, void* userContext ); @@ -175,10 +180,9 @@ typedef struct b3WorldDef /// Number of workers to use with the provided task system. Box3D performs best when using only /// performance cores and accessing a single L2 cache. Efficiency cores and hyper-threading provide /// little benefit and may even harm performance. - /// @note Box3D does not create threads. This is the number of threads your applications has created - /// that you are allocating to b3World_Step. - /// @warning Do not modify the default value unless you are also providing a task system and providing - /// task callbacks (enqueueTask and finishTask). + /// This is clamped to the range [1, B3_MAX_WORKERS]. Using a value above 1 will turn on multithreading. + /// If task callbacks are provided then Box3D will use the user provided task system. Otherwise Box3D + /// will create threads and use an internal scheduler. uint32_t workerCount; /// function to spawn task @@ -298,7 +302,7 @@ typedef struct b3BodyDef /// Sleep speed threshold, default is 0.05 meters per second float sleepThreshold; - /// Optional body name for debugging. Up to B3_NAME_LENGTH characters (including null termination) + /// Optional body name for debugging. Up to B3_BODY_NAME_LENGTH characters (including null termination) const char* name; /// Use this to store application specific body data. @@ -833,10 +837,10 @@ typedef struct b3RevoluteJointDef /// A flag to enable joint limits. bool enableLimit; - /// The lower angle for the joint limit in radians. + /// The lower angle for the joint limit in radians. Minimum of -0.99*pi radians. float lowerAngle; - /// The upper angle for the joint limit in radians. + /// The upper angle for the joint limit in radians. Maximum of 0.99*pi radians. float upperAngle; /// A flag to enable the joint motor. @@ -883,10 +887,10 @@ typedef struct b3SphericalJointDef /// A flag to enable the twist limit. The twist is centered on the frameB z-axis. bool enableTwistLimit; - /// The angle for the lower twist limit in radians. Valid range is [-pi, pi]. + /// The angle for the lower twist limit in radians. Minimum of -0.99*pi radians. float lowerTwistAngle; - /// The angle for the upper twist limit in radians. Valid range is [-pi, pi]. + /// The angle for the upper twist limit in radians. Maximum of 0.99*pi radians. float upperTwistAngle; /// A flag to enable the joint motor diff --git a/samples/sample_robustness.cpp b/samples/sample_robustness.cpp index 1be6b7f..d8473ac 100644 --- a/samples/sample_robustness.cpp +++ b/samples/sample_robustness.cpp @@ -240,199 +240,6 @@ public: static int sampleOverlapRecovery = RegisterSample( "Robustness", "Overlap Recovery", OverlapRecovery::Create ); -class Cart : public Sample -{ -public: - explicit Cart( SampleContext* context ) - : Sample( context ) - { - if ( context->restart == false ) - { - m_camera->SetView( 45.0f, 30.0f, 15.0f, { 0.0f, 2.0f, 0.0f } ); - //context->settings.subStepCount = 12; - - } - - AddGroundBox( 20.0f ); - - b3World_SetGravity( m_worldId, { 0, -22, 0 } ); - - m_contactHertz = 240.0f; - m_contactDampingRatio = 10.0f; - m_contactSpeed = 0.5f; - b3World_SetContactTuning( m_worldId, m_contactHertz, m_contactDampingRatio, m_contactSpeed ); - - m_constraintHertz = 240.0f; - m_constraintDampingRatio = 0.0f; - - m_chassisId = {}; - m_wheelId1 = {}; - m_wheelId2 = {}; - m_wheelId3 = {}; - m_wheelId4 = {}; - m_jointId1 = {}; - m_jointId2 = {}; - m_jointId3 = {}; - m_jointId4 = {}; - - CreateScene(); - } - - void CreateScene() - { - if ( B3_IS_NON_NULL( m_chassisId ) ) - { - b3DestroyBody( m_chassisId ); - } - - if ( B3_IS_NON_NULL( m_wheelId1 ) ) - { - b3DestroyBody( m_wheelId1 ); - } - - if ( B3_IS_NON_NULL( m_wheelId2 ) ) - { - b3DestroyBody( m_wheelId2 ); - } - - if ( B3_IS_NON_NULL( m_wheelId3 ) ) - { - b3DestroyBody( m_wheelId3 ); - } - - if ( B3_IS_NON_NULL( m_wheelId4 ) ) - { - b3DestroyBody( m_wheelId4 ); - } - - float yBase = 1.0f; - - b3BodyDef bodyDef = b3DefaultBodyDef(); - bodyDef.type = b3_dynamicBody; - bodyDef.position = { 0.0f, yBase, 0.0f }; - m_chassisId = b3CreateBody( m_worldId, &bodyDef ); - - b3ShapeDef shapeDef = b3DefaultShapeDef(); - shapeDef.density = 1000.0f; - - b3BoxHull box = b3MakeTransformedBoxHull( 1.0f, 0.25f, 0.5f, { { 0.0f, 0.25f, 0.0f }, b3Quat_identity } ); - b3CreateHullShape( m_chassisId, &shapeDef, &box.base ); - - shapeDef = b3DefaultShapeDef(); - shapeDef.baseMaterial.rollingResistance = 0.02f; - shapeDef.density = 200.0f; - - b3Sphere sphere = { b3Vec3_zero, 0.1f }; - bodyDef.position = { -0.9f, yBase - 0.15f, 0.4f }; - m_wheelId1 = b3CreateBody( m_worldId, &bodyDef ); - b3CreateSphereShape( m_wheelId1, &shapeDef, &sphere ); - - bodyDef.position = { 0.9f, yBase - 0.15f, 0.4f }; - m_wheelId2 = b3CreateBody( m_worldId, &bodyDef ); - b3CreateSphereShape( m_wheelId2, &shapeDef, &sphere ); - - bodyDef.position = { 0.9f, yBase - 0.15f, -0.4f }; - m_wheelId3 = b3CreateBody( m_worldId, &bodyDef ); - b3CreateSphereShape( m_wheelId3, &shapeDef, &sphere ); - - bodyDef.position = { -0.9f, yBase - 0.15f, -0.4f }; - m_wheelId4 = b3CreateBody( m_worldId, &bodyDef ); - b3CreateSphereShape( m_wheelId4, &shapeDef, &sphere ); - - b3SphericalJointDef jointDef = b3DefaultSphericalJointDef(); - jointDef.base.constraintHertz = m_constraintHertz; - jointDef.base.constraintDampingRatio = m_constraintDampingRatio; - jointDef.base.drawScale = 0.5f; - - jointDef.base.bodyIdA = m_chassisId; - jointDef.base.bodyIdB = m_wheelId1; - jointDef.base.localFrameA.p = { -0.9f, -0.15f, 0.4f }; - jointDef.base.localFrameB.p = { 0.0f, 0.0f, 0.0f }; - m_jointId1 = b3CreateSphericalJoint( m_worldId, &jointDef ); - - jointDef.base.bodyIdA = m_chassisId; - jointDef.base.bodyIdB = m_wheelId2; - jointDef.base.localFrameA.p = { 0.9f, -0.15f, 0.4f }; - jointDef.base.localFrameB.p = { 0.0f, 0.0f, 0.0f }; - m_jointId2 = b3CreateSphericalJoint( m_worldId, &jointDef ); - - jointDef.base.bodyIdA = m_chassisId; - jointDef.base.bodyIdB = m_wheelId3; - jointDef.base.localFrameA.p = { 0.9f, -0.15f, -0.4f }; - jointDef.base.localFrameB.p = { 0.0f, 0.0f, 0.0f }; - m_jointId3 = b3CreateSphericalJoint( m_worldId, &jointDef ); - - jointDef.base.bodyIdA = m_chassisId; - jointDef.base.bodyIdB = m_wheelId4; - jointDef.base.localFrameA.p = { -0.9f, -0.15f, -0.4f }; - jointDef.base.localFrameB.p = { 0.0f, 0.0f, 0.0f }; - m_jointId4 = b3CreateSphericalJoint( m_worldId, &jointDef ); - } - - bool DrawControls() override - { - ImGui::PushItemWidth( 6.0f * ImGui::GetFontSize() ); - - bool changed = false; - ImGui::Text( "Contact" ); - changed = changed || ImGui::SliderFloat( "Hertz##contact", &m_contactHertz, 0.0f, 240.0f, "%.f" ); - changed = changed || ImGui::SliderFloat( "Damping Ratio##contact", &m_contactDampingRatio, 0.0f, 100.0f, "%.f" ); - changed = changed || ImGui::SliderFloat( "Speed", &m_contactSpeed, 0.0f, 5.0f, "%.1f" ); - - if ( changed ) - { - b3World_SetContactTuning( m_worldId, m_contactHertz, m_contactDampingRatio, m_contactSpeed ); - CreateScene(); - } - - ImGui::Separator(); - - changed = false; - ImGui::Text( "Joint" ); - changed = changed || ImGui::SliderFloat( "Hertz##joint", &m_constraintHertz, 0.0f, 240.0f, "%.f" ); - changed = changed || ImGui::SliderFloat( "Damping Ratio##joint", &m_constraintDampingRatio, 0.0f, 20.0f, "%.f" ); - - ImGui::Separator(); - - changed = changed || ImGui::Button( "Reset Scene" ); - - if ( changed ) - { - b3Joint_SetConstraintTuning( m_jointId1, m_constraintHertz, m_constraintDampingRatio ); - b3Joint_SetConstraintTuning( m_jointId2, m_constraintHertz, m_constraintDampingRatio ); - b3Joint_SetConstraintTuning( m_jointId3, m_constraintHertz, m_constraintDampingRatio ); - b3Joint_SetConstraintTuning( m_jointId4, m_constraintHertz, m_constraintDampingRatio ); - CreateScene(); - } - - ImGui::PopItemWidth(); - return true; - } - - static Sample* Create( SampleContext* context ) - { - return new Cart( context ); - } - - b3BodyId m_chassisId; - b3BodyId m_wheelId1; - b3BodyId m_wheelId2; - b3BodyId m_wheelId3; - b3BodyId m_wheelId4; - b3JointId m_jointId1; - b3JointId m_jointId2; - b3JointId m_jointId3; - b3JointId m_jointId4; - - float m_contactHertz; - float m_contactDampingRatio; - float m_contactSpeed; - float m_constraintHertz; - float m_constraintDampingRatio; -}; - -static int sampleCart = RegisterSample( "Robustness", "Cart", Cart::Create ); - // This forces a constraint graph color overflow class OverflowColorPile : public Sample { diff --git a/shared/CMakeLists.txt b/shared/CMakeLists.txt index f2cc0f2..c33e6dc 100644 --- a/shared/CMakeLists.txt +++ b/shared/CMakeLists.txt @@ -15,7 +15,7 @@ set(BOX3D_SHARED_FILES utils.h ) -add_library(shared ${BOX3D_SHARED_FILES}) +add_library(shared STATIC ${BOX3D_SHARED_FILES}) set_target_properties(shared PROPERTIES C_STANDARD 17 diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index d9cd14f..95b0d8b 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -93,6 +93,7 @@ set(BOX3D_INCLUDE_FILES ../include/box3d/base.h ../include/box3d/box3d.h ../include/box3d/collision.h + ../include/box3d/config.h ../include/box3d/constants.h ../include/box3d/id.h ../include/box3d/math_functions.h @@ -104,7 +105,7 @@ set(BOX3D_INCLUDE_FILES set(CMAKE_C_VISIBILITY_PRESET hidden) set(CMAKE_VISIBILITY_INLINES_HIDDEN 1) -add_library(box3d STATIC ${BOX3D_SOURCE_FILES} ${BOX3D_INCLUDE_FILES}) +add_library(box3d ${BOX3D_SOURCE_FILES} ${BOX3D_INCLUDE_FILES}) # target_link_libraries(box3d PRIVATE eastl) diff --git a/src/body.c b/src/body.c index d31fa18..aa4e91e 100644 --- a/src/body.c +++ b/src/body.c @@ -22,7 +22,7 @@ #include #include -_Static_assert( B3_NAME_LENGTH >= 0, "minimum name length" ); +_Static_assert( B3_BODY_NAME_LENGTH >= 0, "minimum name length" ); // Get a validated body from a world using an id. b3Body* b3GetBodyFullId( b3World* world, b3BodyId bodyId ) @@ -274,10 +274,10 @@ b3BodyId b3CreateBody( b3WorldId worldId, const b3BodyDef* def ) if ( def->name ) { #if defined( _MSC_VER ) - strncpy_s( body->name, B3_NAME_LENGTH + 1, def->name, B3_NAME_LENGTH ); + strncpy_s( body->name, B3_BODY_NAME_LENGTH + 1, def->name, B3_BODY_NAME_LENGTH ); #else - strncpy( body->name, def->name, B3_NAME_LENGTH ); - body->name[B3_NAME_LENGTH] = 0; + strncpy( body->name, def->name, B3_BODY_NAME_LENGTH ); + body->name[B3_BODY_NAME_LENGTH] = 0; #endif } else @@ -1733,10 +1733,10 @@ void b3Body_SetName( b3BodyId bodyId, const char* name ) if ( name ) { #if defined( _MSC_VER ) - strncpy_s( body->name, B3_NAME_LENGTH + 1, name, B3_NAME_LENGTH ); + strncpy_s( body->name, B3_BODY_NAME_LENGTH + 1, name, B3_BODY_NAME_LENGTH ); #else - strncpy( body->name, name, B3_NAME_LENGTH ); - body->name[B3_NAME_LENGTH] = 0; + strncpy( body->name, name, B3_BODY_NAME_LENGTH ); + body->name[B3_BODY_NAME_LENGTH] = 0; #endif } else diff --git a/src/body.h b/src/body.h index 87041ca..bcba5b7 100644 --- a/src/body.h +++ b/src/body.h @@ -123,7 +123,7 @@ typedef struct b3Body // Used to check for invalid b3BodyId uint16_t generation; - char name[B3_NAME_LENGTH + 1]; + char name[B3_BODY_NAME_LENGTH + 1]; } b3Body; // Body State diff --git a/src/ctz.h b/src/ctz.h index 26216b9..483ce4b 100644 --- a/src/ctz.h +++ b/src/ctz.h @@ -24,7 +24,7 @@ static inline uint32_t b3CTZ32( uint32_t block ) // This function doesn't need to be fast, so using the Ivy Bridge fallback. static inline uint32_t b3CLZ32( uint32_t value ) { -#if 0 +#if 1 // Use BSR (Bit Scan Reverse) which is available on Ivy Bridge unsigned long index; diff --git a/src/joint.c b/src/joint.c index 83bd301..5875f55 100644 --- a/src/joint.c +++ b/src/joint.c @@ -581,9 +581,6 @@ b3JointId b3CreatePrismaticJoint( b3WorldId worldId, const b3PrismaticJointDef* b3JointId b3CreateRevoluteJoint( b3WorldId worldId, const b3RevoluteJointDef* def ) { B3_CHECK_JOINT_DEF( def ); - B3_ASSERT( def->lowerAngle <= def->upperAngle ); - B3_ASSERT( def->lowerAngle >= -0.99f * B3_PI ); - B3_ASSERT( def->upperAngle <= 0.99f * B3_PI ); b3World* world = b3GetUnlockedWorldFromId( worldId ); if (world == NULL) @@ -599,10 +596,12 @@ b3JointId b3CreateRevoluteJoint( b3WorldId worldId, const b3RevoluteJointDef* de joint->revoluteJoint.hertz = def->hertz; joint->revoluteJoint.dampingRatio = def->dampingRatio; joint->revoluteJoint.targetAngle = b3ClampFloat( def->targetAngle, -B3_PI, B3_PI ); - joint->revoluteJoint.lowerAngle = b3MinFloat( def->lowerAngle, def->upperAngle ); - joint->revoluteJoint.upperAngle = b3MaxFloat( def->lowerAngle, def->upperAngle ); - joint->revoluteJoint.lowerAngle = b3ClampFloat( joint->revoluteJoint.lowerAngle, -B3_PI, B3_PI ); - joint->revoluteJoint.upperAngle = b3ClampFloat( joint->revoluteJoint.upperAngle, -B3_PI, B3_PI ); + + float lowerAngle = b3MinFloat( def->lowerAngle, def->upperAngle ); + float upperAngle = b3MaxFloat( def->lowerAngle, def->upperAngle ); + joint->revoluteJoint.lowerAngle = b3ClampFloat( lowerAngle, -0.99f * B3_PI, 0.99f * B3_PI ); + joint->revoluteJoint.upperAngle = b3ClampFloat( upperAngle, -0.99f * B3_PI, 0.99f * B3_PI ); + joint->revoluteJoint.maxMotorTorque = def->maxMotorTorque; joint->revoluteJoint.motorSpeed = def->motorSpeed; joint->revoluteJoint.enableSpring = def->enableSpring; @@ -617,9 +616,6 @@ b3JointId b3CreateRevoluteJoint( b3WorldId worldId, const b3RevoluteJointDef* de b3JointId b3CreateSphericalJoint( b3WorldId worldId, const b3SphericalJointDef* def ) { B3_CHECK_JOINT_DEF( def ); - B3_ASSERT( def->lowerTwistAngle <= def->upperTwistAngle ); - B3_ASSERT( def->lowerTwistAngle >= -0.99f * B3_PI ); - B3_ASSERT( def->upperTwistAngle <= 0.99f * B3_PI ); B3_ASSERT( 0.0f <= def->coneAngle && def->coneAngle <= 0.99f * B3_PI ); B3_ASSERT( b3IsValidQuat( def->targetRotation ) ); @@ -638,10 +634,12 @@ b3JointId b3CreateSphericalJoint( b3WorldId worldId, const b3SphericalJointDef* joint->sphericalJoint.dampingRatio = def->dampingRatio; joint->sphericalJoint.targetRotation = def->targetRotation; joint->sphericalJoint.coneAngle = b3ClampFloat( def->coneAngle, 0.0f, 0.5f * B3_PI ); - joint->sphericalJoint.lowerTwistAngle = b3MinFloat( def->lowerTwistAngle, def->upperTwistAngle ); - joint->sphericalJoint.upperTwistAngle = b3MaxFloat( def->lowerTwistAngle, def->upperTwistAngle ); - joint->sphericalJoint.lowerTwistAngle = b3ClampFloat( joint->sphericalJoint.lowerTwistAngle, -B3_PI, B3_PI ); - joint->sphericalJoint.upperTwistAngle = b3ClampFloat( joint->sphericalJoint.upperTwistAngle, -B3_PI, B3_PI ); + + float lowerAngle = b3MinFloat( def->lowerTwistAngle, def->upperTwistAngle ); + float upperAngle = b3MaxFloat( def->lowerTwistAngle, def->upperTwistAngle ); + joint->sphericalJoint.lowerTwistAngle = b3ClampFloat( lowerAngle, -0.99f * B3_PI, 0.99f * B3_PI ); + joint->sphericalJoint.upperTwistAngle = b3ClampFloat( upperAngle, -0.99f * B3_PI, 0.99f * B3_PI ); + joint->sphericalJoint.maxMotorTorque = def->maxMotorTorque; joint->sphericalJoint.motorVelocity = def->motorVelocity; joint->sphericalJoint.enableSpring = def->enableSpring; @@ -1156,6 +1154,9 @@ static b3Vec3 b3GetJointConstraintTorque( b3World* world, b3Joint* joint ) switch ( joint->type ) { + case b3_parallelJoint: + return b3GetParallelJointTorque( world, base ); + case b3_distanceJoint: return b3Vec3_zero; diff --git a/src/parallel_for.h b/src/parallel_for.h index a668fd0..4a6d285 100644 --- a/src/parallel_for.h +++ b/src/parallel_for.h @@ -5,7 +5,7 @@ typedef struct b3World b3World; -// Callback invoked by b2ParallelFor to process a range of items. May be called +// Callback invoked by b3ParallelFor to process a range of items. May be called // multiple times per worker: work is divided into blocks that workers claim // atomically, so a worker that finishes early picks up the next unclaimed // block instead of sitting idle. workerIndex is the worker identity and is diff --git a/src/physics_world.c b/src/physics_world.c index 15ff550..7f5630b 100644 --- a/src/physics_world.c +++ b/src/physics_world.c @@ -2203,6 +2203,28 @@ void* b3World_GetUserData( b3WorldId worldId ) return world->userData; } +void b3World_SetFrictionCallback( b3WorldId worldId, b3FrictionCallback* callback ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + world->frictionCallback = callback != NULL ? callback : b3DefaultFrictionCallback; +} + +void b3World_SetRestitutionCallback( b3WorldId worldId, b3RestitutionCallback* callback ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + world->restitutionCallback = callback != NULL ? callback : b3DefaultRestitutionCallback; +} + void b3World_SetWorkerCount( b3WorldId worldId, int count ) { b3World* world = b3GetUnlockedWorldFromId( worldId ); diff --git a/src/platform.h b/src/platform.h index cc5fd5e..49d63a8 100644 --- a/src/platform.h +++ b/src/platform.h @@ -8,12 +8,16 @@ #include #include -// Software prefetch hint. _MM_HINT_T0 brings the line into all cache levels. -// MSVC exposes _mm_prefetch via ; clang/gcc accept it via -// on x86 and provide __builtin_prefetch elsewhere. +// Software prefetch hint. T0 brings the line into all cache levels. +// On x86 MSVC exposes _mm_prefetch, ARM MSVC uses __prefetch instead. +// clang/gcc provide __builtin_prefetch on every target. #if defined( B3_COMPILER_MSVC ) #include +#if defined( B3_CPU_X86_X64 ) #define b3Prefetch( addr ) _mm_prefetch( (const char*)( addr ), _MM_HINT_T0 ) +#else +#define b3Prefetch( addr ) __prefetch( (const void*)( addr ) ) +#endif #elif defined( B3_COMPILER_CLANG ) || defined( B3_COMPILER_GCC ) #define b3Prefetch( addr ) __builtin_prefetch( (const void*)( addr ), 0, 3 ) #else diff --git a/src/prismatic_joint.c b/src/prismatic_joint.c index 74f91c3..c96e6d6 100644 --- a/src/prismatic_joint.c +++ b/src/prismatic_joint.c @@ -223,6 +223,47 @@ float b3PrismaticJoint_GetMaxMotorForce( b3JointId jointId ) return base->prismaticJoint.maxMotorForce; } +float b3PrismaticJoint_GetMotorForce( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + return world->inv_h * base->prismaticJoint.motorImpulse; +} + +float b3PrismaticJoint_GetSpeed( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + + b3Body* bodyA = b3Array_Get( world->bodies, base->bodyIdA ); + b3Body* bodyB = b3Array_Get( world->bodies, base->bodyIdB ); + b3BodySim* bodySimA = b3GetBodySim( world, bodyA ); + b3BodySim* bodySimB = b3GetBodySim( world, bodyB ); + b3BodyState* stateA = b3GetBodyState( world, bodyA ); + b3BodyState* stateB = b3GetBodyState( world, bodyB ); + + b3Quat qA = bodySimA->transform.q; + b3Quat qB = bodySimB->transform.q; + + b3Vec3 axisA = b3RotateVector( qA, b3RotateVector( base->localFrameA.q, b3Vec3_axisX ) ); + b3Vec3 rA = b3RotateVector( qA, b3Sub( base->localFrameA.p, bodySimA->localCenter ) ); + b3Vec3 rB = b3RotateVector( qB, b3Sub( base->localFrameB.p, bodySimB->localCenter ) ); + + // Difference the centers in double so the speed stays exact far from the origin. + b3Vec3 d = b3Add( b3SubPos( bodySimB->center, bodySimA->center ), b3Sub( rB, rA ) ); + + b3Vec3 vA = stateA ? stateA->linearVelocity : b3Vec3_zero; + b3Vec3 vB = stateB ? stateB->linearVelocity : b3Vec3_zero; + b3Vec3 wA = stateA ? stateA->angularVelocity : b3Vec3_zero; + b3Vec3 wB = stateB ? stateB->angularVelocity : b3Vec3_zero; + + b3Vec3 vRel = b3Sub( b3Add( vB, b3Cross( wB, rB ) ), b3Add( vA, b3Cross( wA, rA ) ) ); + + // The axis moves with body A, so account for its rotation. + float speed = b3Dot( d, b3Cross( wA, axisA ) ) + b3Dot( axisA, vRel ); + return speed; +} + b3Vec3 b3GetPrismaticJointForce( b3World* world, b3JointSim* base ) { b3WorldTransform transformA = b3GetBodyTransform( world, base->bodyIdA ); diff --git a/src/recording.c b/src/recording.c index 3c61069..933449f 100644 --- a/src/recording.c +++ b/src/recording.c @@ -938,7 +938,7 @@ void b3RecInternTag( b3Recording* rec, uint64_t key, uint64_t id, const char* na tag->key = key; tag->id = id; int n = 0; - while ( name != NULL && name[n] != '\0' && n < B3_NAME_LENGTH ) + while ( name != NULL && name[n] != '\0' && n < B3_BODY_NAME_LENGTH ) { tag->name[n] = name[n]; n++; diff --git a/src/recording.h b/src/recording.h index 014b446..9c8750c 100644 --- a/src/recording.h +++ b/src/recording.h @@ -120,7 +120,7 @@ typedef struct b3RecTag { uint64_t key; // hash of (id, name) uint64_t id; // entity/actor id - char name[B3_NAME_LENGTH + 1]; // query label + char name[B3_BODY_NAME_LENGTH + 1]; // query label } b3RecTag; // User-owned recording buffer. The world appends into it while active; the host saves and @@ -356,7 +356,7 @@ void b3RecWriteRegistry( b3Recording* rec ); uint64_t b3HashQueryTag( uint64_t id, const char* name ); // Record a key->(id, name) mapping once, deduped by key (a repeated key keeps its first id/name). -// The name is clamped to B3_NAME_LENGTH. +// The name is clamped to B3_BODY_NAME_LENGTH. void b3RecInternTag( b3Recording* rec, uint64_t key, uint64_t id, const char* name ); // Intern each large geometry kind and return a stable u32 id for use in create ops. diff --git a/src/recording_replay.c b/src/recording_replay.c index 511c825..f0537e0 100644 --- a/src/recording_replay.c +++ b/src/recording_replay.c @@ -385,9 +385,9 @@ const char* b3RecR_STR( b3RecReader* rdr ) } int n = (int)len; - if ( n > B3_NAME_LENGTH ) + if ( n > B3_BODY_NAME_LENGTH ) { - n = B3_NAME_LENGTH; + n = B3_BODY_NAME_LENGTH; } b3RecRdrCheck( rdr, (int)len ); if ( rdr->ok && n > 0 ) @@ -2332,7 +2332,7 @@ static void b3RecLoadTags( b3RecReader* rdr, const uint8_t* rp, const uint8_t* d { break; } - int n = len > B3_NAME_LENGTH ? B3_NAME_LENGTH : (int)len; + int n = len > B3_BODY_NAME_LENGTH ? B3_BODY_NAME_LENGTH : (int)len; tags[loaded].key = key; tags[loaded].id = id; if ( n > 0 ) diff --git a/src/recording_replay.h b/src/recording_replay.h index 7d3f4b0..e343d2b 100644 --- a/src/recording_replay.h +++ b/src/recording_replay.h @@ -91,7 +91,7 @@ typedef struct b3RecReader int matScratchCap; // Scratch for string reads: rotating slots, valid until the next 4 STR reads - char strBufs[4][B3_NAME_LENGTH + 1]; + char strBufs[4][B3_BODY_NAME_LENGTH + 1]; int strNext; // Preloaded geometry registry diff --git a/src/revolute_joint.c b/src/revolute_joint.c index 2cad93c..7856a83 100644 --- a/src/revolute_joint.c +++ b/src/revolute_joint.c @@ -73,18 +73,16 @@ float b3RevoluteJoint_GetUpperLimit( b3JointId jointId ) void b3RevoluteJoint_SetLimits( b3JointId jointId, float lowerLimitRadians, float upperLimitRadians ) { - B3_ASSERT( lowerLimitRadians <= upperLimitRadians ); B3_ASSERT( b3IsValidFloat( lowerLimitRadians ) && b3IsValidFloat( upperLimitRadians ) ); b3World* world = b3GetWorld( jointId.world0 ); B3_REC( world, RevoluteJointSetLimits, jointId, lowerLimitRadians, upperLimitRadians ); - float lowerAngle = b3ClampFloat( lowerLimitRadians, -B3_PI, B3_PI ); - float upperAngle = b3ClampFloat( upperLimitRadians, -B3_PI, B3_PI ); + + float lowerAngle = b3MinFloat( lowerLimitRadians, upperLimitRadians ); + float upperAngle = b3MaxFloat( lowerLimitRadians, upperLimitRadians ); b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); - base->revoluteJoint.lowerAngle = lowerAngle; - base->revoluteJoint.upperAngle = upperAngle; - base->revoluteJoint.lowerImpulse = 0.0f; - base->revoluteJoint.upperImpulse = 0.0f; + base->revoluteJoint.lowerAngle = b3ClampFloat( lowerAngle, -0.99f * B3_PI, 0.99f * B3_PI ); + base->revoluteJoint.upperAngle = b3ClampFloat( upperAngle, -0.99f * B3_PI, 0.99f * B3_PI ); } float b3RevoluteJoint_GetAngle( b3JointId jointId ) @@ -219,6 +217,13 @@ float b3RevoluteJoint_GetMaxMotorTorque( b3JointId jointId ) return base->revoluteJoint.maxMotorTorque; } +float b3RevoluteJoint_GetMotorTorque( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + return world->inv_h * base->revoluteJoint.motorImpulse; +} + b3Vec3 b3GetRevoluteJointForce( b3World* world, b3JointSim* base ) { b3Vec3 force = b3MulSV( world->inv_h, base->revoluteJoint.linearImpulse ); diff --git a/src/solver.c b/src/solver.c index f842a67..4c5c114 100644 --- a/src/solver.c +++ b/src/solver.c @@ -1821,7 +1821,7 @@ void b3Solve( b3World* world, b3StepContext* stepContext ) } } - // The calling thread of b2World_Step also enters b2SolverTask as worker 0 and races for the + // The calling thread of b3World_Step also enters b3SolverTask as worker 0 and races for the // orchestrator slot via the CAS inside. This guarantees progress even when the user's task // system can't run the queued worker 0 promptly: it might schedule out of order, have fewer // threads than workerCount, or invert priority by parking the calling thread in finishTaskFcn. diff --git a/src/solver.h b/src/solver.h index c0e2c74..7c8a1c7 100644 --- a/src/solver.h +++ b/src/solver.h @@ -249,7 +249,7 @@ typedef struct b3StepContext char padding2[64]; // Race flag claimed by whichever runner reaches b3SolverTask with workerIndex 0 first. - // The calling thread of b2World_Step also races for this slot so the orchestrator can + // The calling thread of b3World_Step also races for this slot so the orchestrator can // always make progress, regardless of how the user's task system schedules tasks (out // of order, fewer threads than workers, or synchronously inside enqueueTaskFcn). The // loser of the race no-ops as workerIndex 0. diff --git a/src/spherical_joint.c b/src/spherical_joint.c index 3634a57..3f699ac 100644 --- a/src/spherical_joint.c +++ b/src/spherical_joint.c @@ -103,14 +103,13 @@ void b3SphericalJoint_SetTwistLimits( b3JointId jointId, float lowerLimitRadians B3_ASSERT( b3IsValidFloat( lowerLimitRadians ) && b3IsValidFloat( upperLimitRadians ) ); b3World* world = b3GetWorld( jointId.world0 ); B3_REC( world, SphericalJointSetTwistLimits, jointId, lowerLimitRadians, upperLimitRadians ); - float lowerTwistAngle = b3MinFloat( lowerLimitRadians, upperLimitRadians ); - float upperTwistAngle = b3MaxFloat( lowerLimitRadians, upperLimitRadians ); - lowerTwistAngle = b3ClampFloat( lowerTwistAngle, -B3_PI, B3_PI ); - upperTwistAngle = b3ClampFloat( upperTwistAngle, -B3_PI, B3_PI ); + + float lowerAngle = b3MinFloat( lowerLimitRadians, upperLimitRadians ); + float upperAngle = b3MaxFloat( lowerLimitRadians, upperLimitRadians ); b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); - base->sphericalJoint.lowerTwistAngle = lowerTwistAngle; - base->sphericalJoint.upperTwistAngle = upperTwistAngle; + base->sphericalJoint.lowerTwistAngle = b3ClampFloat( lowerAngle, -0.99f * B3_PI, 0.99f * B3_PI ); + base->sphericalJoint.upperTwistAngle = b3ClampFloat( upperAngle, -0.99f * B3_PI, 0.99f * B3_PI ); } float b3SphericalJoint_GetTwistAngle( b3JointId jointId ) @@ -245,6 +244,13 @@ float b3SphericalJoint_GetMaxMotorTorque( b3JointId jointId ) return base->sphericalJoint.maxMotorTorque; } +b3Vec3 b3SphericalJoint_GetMotorTorque( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + return b3MulSV( world->inv_h, base->sphericalJoint.motorImpulse ); +} + b3Vec3 b3GetSphericalJointForce( b3World* world, b3JointSim* base ) { b3Vec3 force = b3MulSV( world->inv_h, base->sphericalJoint.linearImpulse ); diff --git a/src/types.c b/src/types.c index de4a2e0..8b3f38e 100644 --- a/src/types.c +++ b/src/types.c @@ -140,6 +140,13 @@ b3DebugDraw b3DefaultDebugDraw( void ) draw.DrawBoxFcn = b3EmptyDrawBox; draw.DrawStringFcn = b3EmptyDrawString; + // Not too small, not too big. + float h = 100.0f * b3GetLengthUnitsPerMeter(); + draw.drawingBounds = (b3AABB){ + .lowerBound = { -h, -h, -h }, + .upperBound = { h, h, h }, + }; + draw.jointScale = 1.0f; draw.forceScale = 1.0f; diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index a07a66b..1635ca7 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -14,6 +14,7 @@ set(BOX3D_TEST_FILES test_height_field.c test_hull.c test_id.c + test_joint.c test_large_world.c test_macros.h test_math.c diff --git a/test/main.c b/test/main.c index 930f771..fb8fc20 100644 --- a/test/main.c +++ b/test/main.c @@ -37,6 +37,7 @@ extern int DistanceTest( void ); extern int HeightFieldTest( void ); extern int HullTest( void ); extern int IdTest( void ); +extern int JointTest( void ); extern int LargeWorldTest( void ); extern int MathTest( void ); extern int MoverTest( void ); @@ -106,6 +107,7 @@ int main( int argc, char** argv ) MAYBE_RUN_TEST( HeightFieldTest ); MAYBE_RUN_TEST( HullTest ); MAYBE_RUN_TEST( IdTest ); + MAYBE_RUN_TEST( JointTest ); MAYBE_RUN_TEST( LargeWorldTest ); MAYBE_RUN_TEST( MathTest ); MAYBE_RUN_TEST( MoverTest ); diff --git a/test/test_joint.c b/test/test_joint.c new file mode 100644 index 0000000..582e68c --- /dev/null +++ b/test/test_joint.c @@ -0,0 +1,581 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#include "test_macros.h" + +#include "box3d/box3d.h" +#include "box3d/math_functions.h" + +// One sub-test per joint type. Each creates the joint, exercises the shared +// b3Joint_* API plus every type-specific accessor, then steps to make sure the +// joint solves without tripping a validation assert. + +typedef struct JointFixture +{ + b3WorldId worldId; + b3BodyId groundId; + b3BodyId bodyId; +} JointFixture; + +// Static ground plus a dynamic box, anchored so a point-coincident joint starts +// satisfied. Gravity is off so the body stays put across the handful of steps +// each sub-test takes. +static JointFixture CreateJointFixture( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.gravity = b3Vec3_zero; + + JointFixture f; + f.worldId = b3CreateWorld( &worldDef ); + + b3BodyDef groundDef = b3DefaultBodyDef(); + f.groundId = b3CreateBody( f.worldId, &groundDef ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ 0.0f, 4.0f, 0.0f }; + f.bodyId = b3CreateBody( f.worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 1.0f; + b3BoxHull box = b3MakeCubeHull( 0.5f ); + b3CreateHullShape( f.bodyId, &shapeDef, &box.base ); + + return f; +} + +// Place the joint anchor at the dynamic body so both local frames map to the +// same world point. +static void SetCommonFrames( b3JointDef* base, const JointFixture* f ) +{ + base->bodyIdA = f->groundId; + base->bodyIdB = f->bodyId; + base->localFrameA.p = (b3Vec3){ 0.0f, 4.0f, 0.0f }; + base->localFrameB.p = (b3Vec3){ 0.0f, 0.0f, 0.0f }; +} + +// Step a few times, destroy the joint, then the world. Destroying the joint +// explicitly also covers b3DestroyJoint and stale-handle detection. +static int FinishJoint( b3JointId jointId, b3WorldId worldId ) +{ + for ( int i = 0; i < 8; ++i ) + { + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + } + + b3DestroyJoint( jointId, true ); + ENSURE( b3Joint_IsValid( jointId ) == false ); + + b3DestroyWorld( worldId ); + return 0; +} + +// Exercise the API shared by every joint type. Frames are saved and restored so +// the caller's setup survives. +static int ExerciseJointBase( b3JointId jointId, b3WorldId worldId, b3BodyId bodyIdA, b3BodyId bodyIdB, b3JointType expectedType ) +{ + ENSURE( b3Joint_IsValid( jointId ) ); + ENSURE( b3Joint_GetType( jointId ) == expectedType ); + ENSURE( B3_ID_EQUALS( b3Joint_GetBodyA( jointId ), bodyIdA ) ); + ENSURE( B3_ID_EQUALS( b3Joint_GetBodyB( jointId ), bodyIdB ) ); + + // B3_ID_EQUALS does not work for world ids + b3WorldId gotWorld = b3Joint_GetWorld( jointId ); + ENSURE( gotWorld.index1 == worldId.index1 && gotWorld.generation == worldId.generation ); + + b3Transform originalA = b3Joint_GetLocalFrameA( jointId ); + b3Transform originalB = b3Joint_GetLocalFrameB( jointId ); + + b3Transform frameA = { { 0.1f, 0.2f, 0.3f }, b3Quat_identity }; + b3Joint_SetLocalFrameA( jointId, frameA ); + b3Transform gotA = b3Joint_GetLocalFrameA( jointId ); + ENSURE( gotA.p.x == frameA.p.x && gotA.p.y == frameA.p.y && gotA.p.z == frameA.p.z ); + + b3Transform frameB = { { -0.4f, 0.5f, -0.6f }, b3Quat_identity }; + b3Joint_SetLocalFrameB( jointId, frameB ); + b3Transform gotB = b3Joint_GetLocalFrameB( jointId ); + ENSURE( gotB.p.x == frameB.p.x && gotB.p.y == frameB.p.y && gotB.p.z == frameB.p.z ); + + b3Joint_SetCollideConnected( jointId, true ); + ENSURE( b3Joint_GetCollideConnected( jointId ) == true ); + b3Joint_SetCollideConnected( jointId, false ); + ENSURE( b3Joint_GetCollideConnected( jointId ) == false ); + + int userData = 0; + b3Joint_SetUserData( jointId, &userData ); + ENSURE( b3Joint_GetUserData( jointId ) == &userData ); + + b3Joint_SetConstraintTuning( jointId, 90.0f, 3.0f ); + float hertz = 0.0f; + float dampingRatio = 0.0f; + b3Joint_GetConstraintTuning( jointId, &hertz, &dampingRatio ); + ENSURE( hertz == 90.0f ); + ENSURE( dampingRatio == 3.0f ); + + b3Joint_SetForceThreshold( jointId, 100.0f ); + ENSURE( b3Joint_GetForceThreshold( jointId ) == 100.0f ); + + b3Joint_SetTorqueThreshold( jointId, 200.0f ); + ENSURE( b3Joint_GetTorqueThreshold( jointId ) == 200.0f ); + + b3Joint_WakeBodies( jointId ); + + // No stable value to assert before the first step, call for coverage + b3Vec3 force = b3Joint_GetConstraintForce( jointId ); + b3Vec3 torque = b3Joint_GetConstraintTorque( jointId ); + float linearSeparation = b3Joint_GetLinearSeparation( jointId ); + MAYBE_UNUSED( force ); + MAYBE_UNUSED( torque ); + MAYBE_UNUSED( linearSeparation ); + + // Wheel joint angular separation is an unimplemented todo in joint.c that + // asserts. Every other type computes it. + if ( expectedType != b3_wheelJoint ) + { + float angularSeparation = b3Joint_GetAngularSeparation( jointId ); + MAYBE_UNUSED( angularSeparation ); + } + + b3Joint_SetLocalFrameA( jointId, originalA ); + b3Joint_SetLocalFrameB( jointId, originalB ); + + return 0; +} + +static int TestParallelJoint( void ) +{ + JointFixture f = CreateJointFixture(); + + b3ParallelJointDef def = b3DefaultParallelJointDef(); + SetCommonFrames( &def.base, &f ); + def.hertz = 2.0f; + def.dampingRatio = 0.5f; + def.maxTorque = 100.0f; + b3JointId jointId = b3CreateParallelJoint( f.worldId, &def ); + + if ( ExerciseJointBase( jointId, f.worldId, f.groundId, f.bodyId, b3_parallelJoint ) != 0 ) + { + return 1; + } + + b3ParallelJoint_SetSpringHertz( jointId, 5.0f ); + ENSURE( b3ParallelJoint_GetSpringHertz( jointId ) == 5.0f ); + + b3ParallelJoint_SetSpringDampingRatio( jointId, 0.7f ); + ENSURE( b3ParallelJoint_GetSpringDampingRatio( jointId ) == 0.7f ); + + b3ParallelJoint_SetMaxTorque( jointId, 250.0f ); + ENSURE( b3ParallelJoint_GetMaxTorque( jointId ) == 250.0f ); + + return FinishJoint( jointId, f.worldId ); +} + +static int TestDistanceJoint( void ) +{ + JointFixture f = CreateJointFixture(); + + b3DistanceJointDef def = b3DefaultDistanceJointDef(); + SetCommonFrames( &def.base, &f ); + def.length = 2.0f; + b3JointId jointId = b3CreateDistanceJoint( f.worldId, &def ); + + if ( ExerciseJointBase( jointId, f.worldId, f.groundId, f.bodyId, b3_distanceJoint ) != 0 ) + { + return 1; + } + + b3DistanceJoint_SetLength( jointId, 3.0f ); + ENSURE( b3DistanceJoint_GetLength( jointId ) == 3.0f ); + + b3DistanceJoint_EnableSpring( jointId, true ); + ENSURE( b3DistanceJoint_IsSpringEnabled( jointId ) == true ); + + b3DistanceJoint_SetSpringForceRange( jointId, -50.0f, 75.0f ); + float lowerForce = 0.0f; + float upperForce = 0.0f; + b3DistanceJoint_GetSpringForceRange( jointId, &lowerForce, &upperForce ); + ENSURE( lowerForce == -50.0f && upperForce == 75.0f ); + + b3DistanceJoint_SetSpringHertz( jointId, 4.0f ); + ENSURE( b3DistanceJoint_GetSpringHertz( jointId ) == 4.0f ); + + b3DistanceJoint_SetSpringDampingRatio( jointId, 0.6f ); + ENSURE( b3DistanceJoint_GetSpringDampingRatio( jointId ) == 0.6f ); + + b3DistanceJoint_EnableLimit( jointId, true ); + ENSURE( b3DistanceJoint_IsLimitEnabled( jointId ) == true ); + + b3DistanceJoint_SetLengthRange( jointId, 1.0f, 5.0f ); + ENSURE( b3DistanceJoint_GetMinLength( jointId ) == 1.0f ); + ENSURE( b3DistanceJoint_GetMaxLength( jointId ) == 5.0f ); + + float currentLength = b3DistanceJoint_GetCurrentLength( jointId ); + MAYBE_UNUSED( currentLength ); + + b3DistanceJoint_EnableMotor( jointId, true ); + ENSURE( b3DistanceJoint_IsMotorEnabled( jointId ) == true ); + + b3DistanceJoint_SetMotorSpeed( jointId, 1.5f ); + ENSURE( b3DistanceJoint_GetMotorSpeed( jointId ) == 1.5f ); + + b3DistanceJoint_SetMaxMotorForce( jointId, 25.0f ); + ENSURE( b3DistanceJoint_GetMaxMotorForce( jointId ) == 25.0f ); + + float motorForce = b3DistanceJoint_GetMotorForce( jointId ); + MAYBE_UNUSED( motorForce ); + + return FinishJoint( jointId, f.worldId ); +} + +static int TestFilterJoint( void ) +{ + JointFixture f = CreateJointFixture(); + + // The filter joint has no type-specific API. It only disables collision and + // keeps both bodies in the same island. + b3FilterJointDef def = b3DefaultFilterJointDef(); + def.base.bodyIdA = f.groundId; + def.base.bodyIdB = f.bodyId; + b3JointId jointId = b3CreateFilterJoint( f.worldId, &def ); + + if ( ExerciseJointBase( jointId, f.worldId, f.groundId, f.bodyId, b3_filterJoint ) != 0 ) + { + return 1; + } + + return FinishJoint( jointId, f.worldId ); +} + +static int TestMotorJoint( void ) +{ + JointFixture f = CreateJointFixture(); + + b3MotorJointDef def = b3DefaultMotorJointDef(); + SetCommonFrames( &def.base, &f ); + b3JointId jointId = b3CreateMotorJoint( f.worldId, &def ); + + if ( ExerciseJointBase( jointId, f.worldId, f.groundId, f.bodyId, b3_motorJoint ) != 0 ) + { + return 1; + } + + b3Vec3 linearVelocity = { 1.0f, 2.0f, 3.0f }; + b3MotorJoint_SetLinearVelocity( jointId, linearVelocity ); + b3Vec3 gotLinear = b3MotorJoint_GetLinearVelocity( jointId ); + ENSURE( gotLinear.x == 1.0f && gotLinear.y == 2.0f && gotLinear.z == 3.0f ); + + b3Vec3 angularVelocity = { 0.1f, 0.2f, 0.3f }; + b3MotorJoint_SetAngularVelocity( jointId, angularVelocity ); + b3Vec3 gotAngular = b3MotorJoint_GetAngularVelocity( jointId ); + ENSURE( gotAngular.x == 0.1f && gotAngular.y == 0.2f && gotAngular.z == 0.3f ); + + b3MotorJoint_SetMaxVelocityForce( jointId, 500.0f ); + ENSURE( b3MotorJoint_GetMaxVelocityForce( jointId ) == 500.0f ); + + b3MotorJoint_SetMaxVelocityTorque( jointId, 600.0f ); + ENSURE( b3MotorJoint_GetMaxVelocityTorque( jointId ) == 600.0f ); + + b3MotorJoint_SetLinearHertz( jointId, 3.0f ); + ENSURE( b3MotorJoint_GetLinearHertz( jointId ) == 3.0f ); + + b3MotorJoint_SetLinearDampingRatio( jointId, 0.8f ); + ENSURE( b3MotorJoint_GetLinearDampingRatio( jointId ) == 0.8f ); + + b3MotorJoint_SetAngularHertz( jointId, 4.0f ); + ENSURE( b3MotorJoint_GetAngularHertz( jointId ) == 4.0f ); + + b3MotorJoint_SetAngularDampingRatio( jointId, 0.9f ); + ENSURE( b3MotorJoint_GetAngularDampingRatio( jointId ) == 0.9f ); + + b3MotorJoint_SetMaxSpringForce( jointId, 700.0f ); + ENSURE( b3MotorJoint_GetMaxSpringForce( jointId ) == 700.0f ); + + b3MotorJoint_SetMaxSpringTorque( jointId, 800.0f ); + ENSURE( b3MotorJoint_GetMaxSpringTorque( jointId ) == 800.0f ); + + return FinishJoint( jointId, f.worldId ); +} + +static int TestPrismaticJoint( void ) +{ + JointFixture f = CreateJointFixture(); + + b3PrismaticJointDef def = b3DefaultPrismaticJointDef(); + SetCommonFrames( &def.base, &f ); + b3JointId jointId = b3CreatePrismaticJoint( f.worldId, &def ); + + if ( ExerciseJointBase( jointId, f.worldId, f.groundId, f.bodyId, b3_prismaticJoint ) != 0 ) + { + return 1; + } + + b3PrismaticJoint_EnableSpring( jointId, true ); + ENSURE( b3PrismaticJoint_IsSpringEnabled( jointId ) == true ); + + b3PrismaticJoint_SetSpringHertz( jointId, 5.0f ); + ENSURE( b3PrismaticJoint_GetSpringHertz( jointId ) == 5.0f ); + + b3PrismaticJoint_SetSpringDampingRatio( jointId, 0.5f ); + ENSURE( b3PrismaticJoint_GetSpringDampingRatio( jointId ) == 0.5f ); + + b3PrismaticJoint_SetTargetTranslation( jointId, 1.0f ); + ENSURE( b3PrismaticJoint_GetTargetTranslation( jointId ) == 1.0f ); + + b3PrismaticJoint_EnableLimit( jointId, true ); + ENSURE( b3PrismaticJoint_IsLimitEnabled( jointId ) == true ); + + b3PrismaticJoint_SetLimits( jointId, -2.0f, 2.0f ); + ENSURE( b3PrismaticJoint_GetLowerLimit( jointId ) == -2.0f ); + ENSURE( b3PrismaticJoint_GetUpperLimit( jointId ) == 2.0f ); + + b3PrismaticJoint_EnableMotor( jointId, true ); + ENSURE( b3PrismaticJoint_IsMotorEnabled( jointId ) == true ); + + b3PrismaticJoint_SetMotorSpeed( jointId, 1.5f ); + ENSURE( b3PrismaticJoint_GetMotorSpeed( jointId ) == 1.5f ); + + b3PrismaticJoint_SetMaxMotorForce( jointId, 30.0f ); + ENSURE( b3PrismaticJoint_GetMaxMotorForce( jointId ) == 30.0f ); + + float motorForce = b3PrismaticJoint_GetMotorForce( jointId ); + float translation = b3PrismaticJoint_GetTranslation( jointId ); + float speed = b3PrismaticJoint_GetSpeed( jointId ); + MAYBE_UNUSED( motorForce ); + MAYBE_UNUSED( translation ); + MAYBE_UNUSED( speed ); + + return FinishJoint( jointId, f.worldId ); +} + +static int TestRevoluteJoint( void ) +{ + JointFixture f = CreateJointFixture(); + + b3RevoluteJointDef def = b3DefaultRevoluteJointDef(); + SetCommonFrames( &def.base, &f ); + b3JointId jointId = b3CreateRevoluteJoint( f.worldId, &def ); + + if ( ExerciseJointBase( jointId, f.worldId, f.groundId, f.bodyId, b3_revoluteJoint ) != 0 ) + { + return 1; + } + + b3RevoluteJoint_EnableSpring( jointId, true ); + ENSURE( b3RevoluteJoint_IsSpringEnabled( jointId ) == true ); + + b3RevoluteJoint_SetSpringHertz( jointId, 5.0f ); + ENSURE( b3RevoluteJoint_GetSpringHertz( jointId ) == 5.0f ); + + b3RevoluteJoint_SetSpringDampingRatio( jointId, 0.5f ); + ENSURE( b3RevoluteJoint_GetSpringDampingRatio( jointId ) == 0.5f ); + + b3RevoluteJoint_SetTargetAngle( jointId, 0.5f ); + ENSURE( b3RevoluteJoint_GetTargetAngle( jointId ) == 0.5f ); + + float angle = b3RevoluteJoint_GetAngle( jointId ); + MAYBE_UNUSED( angle ); + + b3RevoluteJoint_EnableLimit( jointId, true ); + ENSURE( b3RevoluteJoint_IsLimitEnabled( jointId ) == true ); + + b3RevoluteJoint_SetLimits( jointId, -1.0f, 1.0f ); + ENSURE( b3RevoluteJoint_GetLowerLimit( jointId ) == -1.0f ); + ENSURE( b3RevoluteJoint_GetUpperLimit( jointId ) == 1.0f ); + + b3RevoluteJoint_EnableMotor( jointId, true ); + ENSURE( b3RevoluteJoint_IsMotorEnabled( jointId ) == true ); + + b3RevoluteJoint_SetMotorSpeed( jointId, 2.0f ); + ENSURE( b3RevoluteJoint_GetMotorSpeed( jointId ) == 2.0f ); + + b3RevoluteJoint_SetMaxMotorTorque( jointId, 40.0f ); + ENSURE( b3RevoluteJoint_GetMaxMotorTorque( jointId ) == 40.0f ); + + float motorTorque = b3RevoluteJoint_GetMotorTorque( jointId ); + MAYBE_UNUSED( motorTorque ); + + return FinishJoint( jointId, f.worldId ); +} + +static int TestSphericalJoint( void ) +{ + JointFixture f = CreateJointFixture(); + + b3SphericalJointDef def = b3DefaultSphericalJointDef(); + SetCommonFrames( &def.base, &f ); + b3JointId jointId = b3CreateSphericalJoint( f.worldId, &def ); + + if ( ExerciseJointBase( jointId, f.worldId, f.groundId, f.bodyId, b3_sphericalJoint ) != 0 ) + { + return 1; + } + + b3SphericalJoint_EnableConeLimit( jointId, true ); + ENSURE( b3SphericalJoint_IsConeLimitEnabled( jointId ) == true ); + + b3SphericalJoint_SetConeLimit( jointId, 0.5f ); + ENSURE( b3SphericalJoint_GetConeLimit( jointId ) == 0.5f ); + + float coneAngle = b3SphericalJoint_GetConeAngle( jointId ); + MAYBE_UNUSED( coneAngle ); + + b3SphericalJoint_EnableTwistLimit( jointId, true ); + ENSURE( b3SphericalJoint_IsTwistLimitEnabled( jointId ) == true ); + + b3SphericalJoint_SetTwistLimits( jointId, -0.5f, 0.5f ); + ENSURE( b3SphericalJoint_GetLowerTwistLimit( jointId ) == -0.5f ); + ENSURE( b3SphericalJoint_GetUpperTwistLimit( jointId ) == 0.5f ); + + float twistAngle = b3SphericalJoint_GetTwistAngle( jointId ); + MAYBE_UNUSED( twistAngle ); + + b3SphericalJoint_EnableSpring( jointId, true ); + ENSURE( b3SphericalJoint_IsSpringEnabled( jointId ) == true ); + + b3SphericalJoint_SetSpringHertz( jointId, 5.0f ); + ENSURE( b3SphericalJoint_GetSpringHertz( jointId ) == 5.0f ); + + b3SphericalJoint_SetSpringDampingRatio( jointId, 0.5f ); + ENSURE( b3SphericalJoint_GetSpringDampingRatio( jointId ) == 0.5f ); + + // 90 degrees about z, a unit quaternion that round-trips through storage + b3Quat targetRotation = { { 0.0f, 0.0f, 0.7071068f }, 0.7071068f }; + b3SphericalJoint_SetTargetRotation( jointId, targetRotation ); + b3Quat gotRotation = b3SphericalJoint_GetTargetRotation( jointId ); + ENSURE_SMALL( gotRotation.v.x - targetRotation.v.x, 1.0e-5f ); + ENSURE_SMALL( gotRotation.v.y - targetRotation.v.y, 1.0e-5f ); + ENSURE_SMALL( gotRotation.v.z - targetRotation.v.z, 1.0e-5f ); + ENSURE_SMALL( gotRotation.s - targetRotation.s, 1.0e-5f ); + + b3SphericalJoint_EnableMotor( jointId, true ); + ENSURE( b3SphericalJoint_IsMotorEnabled( jointId ) == true ); + + b3Vec3 motorVelocity = { 0.1f, 0.2f, 0.3f }; + b3SphericalJoint_SetMotorVelocity( jointId, motorVelocity ); + b3Vec3 gotMotorVelocity = b3SphericalJoint_GetMotorVelocity( jointId ); + ENSURE( gotMotorVelocity.x == 0.1f && gotMotorVelocity.y == 0.2f && gotMotorVelocity.z == 0.3f ); + + b3SphericalJoint_SetMaxMotorTorque( jointId, 50.0f ); + ENSURE( b3SphericalJoint_GetMaxMotorTorque( jointId ) == 50.0f ); + + b3Vec3 motorTorque = b3SphericalJoint_GetMotorTorque( jointId ); + MAYBE_UNUSED( motorTorque ); + + return FinishJoint( jointId, f.worldId ); +} + +static int TestWeldJoint( void ) +{ + JointFixture f = CreateJointFixture(); + + b3WeldJointDef def = b3DefaultWeldJointDef(); + SetCommonFrames( &def.base, &f ); + b3JointId jointId = b3CreateWeldJoint( f.worldId, &def ); + + if ( ExerciseJointBase( jointId, f.worldId, f.groundId, f.bodyId, b3_weldJoint ) != 0 ) + { + return 1; + } + + b3WeldJoint_SetLinearHertz( jointId, 3.0f ); + ENSURE( b3WeldJoint_GetLinearHertz( jointId ) == 3.0f ); + + b3WeldJoint_SetLinearDampingRatio( jointId, 0.5f ); + ENSURE( b3WeldJoint_GetLinearDampingRatio( jointId ) == 0.5f ); + + b3WeldJoint_SetAngularHertz( jointId, 4.0f ); + ENSURE( b3WeldJoint_GetAngularHertz( jointId ) == 4.0f ); + + b3WeldJoint_SetAngularDampingRatio( jointId, 0.7f ); + ENSURE( b3WeldJoint_GetAngularDampingRatio( jointId ) == 0.7f ); + + return FinishJoint( jointId, f.worldId ); +} + +static int TestWheelJoint( void ) +{ + JointFixture f = CreateJointFixture(); + + b3WheelJointDef def = b3DefaultWheelJointDef(); + SetCommonFrames( &def.base, &f ); + b3JointId jointId = b3CreateWheelJoint( f.worldId, &def ); + + if ( ExerciseJointBase( jointId, f.worldId, f.groundId, f.bodyId, b3_wheelJoint ) != 0 ) + { + return 1; + } + + b3WheelJoint_EnableSuspension( jointId, true ); + ENSURE( b3WheelJoint_IsSuspensionEnabled( jointId ) == true ); + + b3WheelJoint_SetSuspensionHertz( jointId, 5.0f ); + ENSURE( b3WheelJoint_GetSuspensionHertz( jointId ) == 5.0f ); + + b3WheelJoint_SetSuspensionDampingRatio( jointId, 0.5f ); + ENSURE( b3WheelJoint_GetSuspensionDampingRatio( jointId ) == 0.5f ); + + b3WheelJoint_EnableSuspensionLimit( jointId, true ); + ENSURE( b3WheelJoint_IsSuspensionLimitEnabled( jointId ) == true ); + + b3WheelJoint_SetSuspensionLimits( jointId, -1.0f, 1.0f ); + ENSURE( b3WheelJoint_GetLowerSuspensionLimit( jointId ) == -1.0f ); + ENSURE( b3WheelJoint_GetUpperSuspensionLimit( jointId ) == 1.0f ); + + b3WheelJoint_EnableSpinMotor( jointId, true ); + ENSURE( b3WheelJoint_IsSpinMotorEnabled( jointId ) == true ); + + b3WheelJoint_SetSpinMotorSpeed( jointId, 6.0f ); + ENSURE( b3WheelJoint_GetSpinMotorSpeed( jointId ) == 6.0f ); + + b3WheelJoint_SetMaxSpinTorque( jointId, 35.0f ); + ENSURE( b3WheelJoint_GetMaxSpinTorque( jointId ) == 35.0f ); + + float spinSpeed = b3WheelJoint_GetSpinSpeed( jointId ); + float spinTorque = b3WheelJoint_GetSpinTorque( jointId ); + MAYBE_UNUSED( spinSpeed ); + MAYBE_UNUSED( spinTorque ); + + b3WheelJoint_EnableSteering( jointId, true ); + ENSURE( b3WheelJoint_IsSteeringEnabled( jointId ) == true ); + + b3WheelJoint_SetSteeringHertz( jointId, 7.0f ); + ENSURE( b3WheelJoint_GetSteeringHertz( jointId ) == 7.0f ); + + b3WheelJoint_SetSteeringDampingRatio( jointId, 0.8f ); + ENSURE( b3WheelJoint_GetSteeringDampingRatio( jointId ) == 0.8f ); + + b3WheelJoint_SetMaxSteeringTorque( jointId, 45.0f ); + ENSURE( b3WheelJoint_GetMaxSteeringTorque( jointId ) == 45.0f ); + + b3WheelJoint_EnableSteeringLimit( jointId, true ); + ENSURE( b3WheelJoint_IsSteeringLimitEnabled( jointId ) == true ); + + b3WheelJoint_SetSteeringLimits( jointId, -0.6f, 0.6f ); + ENSURE( b3WheelJoint_GetLowerSteeringLimit( jointId ) == -0.6f ); + ENSURE( b3WheelJoint_GetUpperSteeringLimit( jointId ) == 0.6f ); + + b3WheelJoint_SetTargetSteeringAngle( jointId, 0.25f ); + ENSURE( b3WheelJoint_GetTargetSteeringAngle( jointId ) == 0.25f ); + + float steeringAngle = b3WheelJoint_GetSteeringAngle( jointId ); + float steeringTorque = b3WheelJoint_GetSteeringTorque( jointId ); + MAYBE_UNUSED( steeringAngle ); + MAYBE_UNUSED( steeringTorque ); + + return FinishJoint( jointId, f.worldId ); +} + +int JointTest( void ) +{ + RUN_SUBTEST( TestParallelJoint ); + RUN_SUBTEST( TestDistanceJoint ); + RUN_SUBTEST( TestFilterJoint ); + RUN_SUBTEST( TestMotorJoint ); + RUN_SUBTEST( TestPrismaticJoint ); + RUN_SUBTEST( TestRevoluteJoint ); + RUN_SUBTEST( TestSphericalJoint ); + RUN_SUBTEST( TestWeldJoint ); + RUN_SUBTEST( TestWheelJoint ); + + return 0; +} diff --git a/test/test_recording.c b/test/test_recording.c index c61cb40..ba068e5 100644 --- a/test/test_recording.c +++ b/test/test_recording.c @@ -1020,13 +1020,6 @@ static int EmptyWorldRoundTrip( void ) // Exercise every recorded op in a single session, then validate replay at two worker // counts, round-trip through a file, and drive the incremental player. Mirrors the // comprehensive RecordingTest in Box2D's test suite (box2d/test/test_recording.c). -static int RecTestAssertDbg( const char* cond, const char* file, int line ) -{ - fprintf( stderr, "BOX3D ASSERTION: %s, %s:%d\n", cond, file, line ); - fflush( stderr ); - return 1; -} - static int AllOps( void ) { b3Recording* rec = b3CreateRecording( 0 ); @@ -1049,7 +1042,7 @@ static int AllOps( void ) b3ShapeId groundShapeId = b3CreateHullShape( groundId, &groundShapeDef, &groundBox.base ); ENSURE( b3Shape_IsValid( groundShapeId ) ); - // Dynamic body with a sphere shape. The name is intentionally longer than B3_NAME_LENGTH so + // Dynamic body with a sphere shape. The name is intentionally longer than B3_BODY_NAME_LENGTH so // replay exercises the over-length name path in the body def reader. b3BodyDef bodyDef = b3DefaultBodyDef(); bodyDef.type = b3_dynamicBody;