Repository: erincatto/box2d Branch: main Commit: 5778d748bb06 Files: 212 Total size: 2.7 MB Directory structure: gitextract___deiibx/ ├── .clang-format ├── .gitattributes ├── .github/ │ ├── FUNDING.yml │ ├── issue_template.md │ ├── pull_request_template.md │ └── workflows/ │ └── build.yml ├── .gitignore ├── CMakeLists.txt ├── LICENSE ├── README.md ├── benchmark/ │ ├── CMakeLists.txt │ ├── amd7950x_avx2/ │ │ ├── joint_grid.csv │ │ ├── large_pyramid.csv │ │ ├── many_pyramids.csv │ │ ├── rain.csv │ │ ├── smash.csv │ │ ├── spinner.csv │ │ └── tumbler.csv │ ├── amd7950x_float/ │ │ ├── joint_grid.csv │ │ ├── large_pyramid.csv │ │ ├── many_pyramids.csv │ │ ├── rain.csv │ │ ├── smash.csv │ │ ├── spinner.csv │ │ └── tumbler.csv │ ├── amd7950x_sse2/ │ │ ├── joint_grid.csv │ │ ├── large_pyramid.csv │ │ ├── many_pyramids.csv │ │ ├── rain.csv │ │ ├── smash.csv │ │ ├── spinner.csv │ │ ├── tumbler.csv │ │ └── washer.csv │ ├── m2air_float/ │ │ ├── joint_grid.csv │ │ ├── large_pyramid.csv │ │ ├── many_pyramids.csv │ │ ├── rain.csv │ │ ├── smash.csv │ │ ├── spinner.csv │ │ └── tumbler.csv │ ├── m2air_neon/ │ │ ├── joint_grid.csv │ │ ├── large_pyramid.csv │ │ ├── many_pyramids.csv │ │ ├── rain.csv │ │ ├── smash.csv │ │ ├── spinner.csv │ │ └── tumbler.csv │ ├── main.c │ └── n100_sse2/ │ ├── joint_grid.csv │ ├── large_pyramid.csv │ ├── many_pyramids.csv │ ├── rain.csv │ ├── smash.csv │ ├── spinner.csv │ └── tumbler.csv ├── build.sh ├── build_emscripten.sh ├── create_sln.bat ├── deploy_docs.sh ├── docs/ │ ├── CMakeLists.txt │ ├── FAQ.md │ ├── character.md │ ├── collision.md │ ├── extra.css │ ├── foundation.md │ ├── hello.md │ ├── layout.xml │ ├── loose_ends.md │ ├── migration.md │ ├── overview.md │ ├── reading.md │ ├── release_notes_v310.md │ ├── samples.md │ └── simulation.md ├── extern/ │ ├── glad/ │ │ ├── include/ │ │ │ ├── KHR/ │ │ │ │ └── khrplatform.h │ │ │ └── glad/ │ │ │ └── glad.h │ │ └── src/ │ │ └── glad.c │ └── jsmn/ │ └── jsmn.h ├── include/ │ └── box2d/ │ ├── base.h │ ├── box2d.h │ ├── collision.h │ ├── id.h │ ├── math_functions.h │ └── types.h ├── samples/ │ ├── CMakeLists.txt │ ├── car.cpp │ ├── car.h │ ├── container.c │ ├── container.h │ ├── data/ │ │ ├── background.fs │ │ ├── background.vs │ │ ├── circle.fs │ │ ├── circle.vs │ │ ├── font.fs │ │ ├── font.vs │ │ ├── line.fs │ │ ├── line.vs │ │ ├── point.fs │ │ ├── point.vs │ │ ├── solid_capsule.fs │ │ ├── solid_capsule.vs │ │ ├── solid_circle.fs │ │ ├── solid_circle.vs │ │ ├── solid_polygon.fs │ │ └── solid_polygon.vs │ ├── donut.cpp │ ├── donut.h │ ├── doohickey.cpp │ ├── doohickey.h │ ├── draw.c │ ├── draw.h │ ├── main.cpp │ ├── sample.cpp │ ├── sample.h │ ├── sample_benchmark.cpp │ ├── sample_bodies.cpp │ ├── sample_character.cpp │ ├── sample_collision.cpp │ ├── sample_continuous.cpp │ ├── sample_determinism.cpp │ ├── sample_events.cpp │ ├── sample_geometry.cpp │ ├── sample_issues.cpp │ ├── sample_joints.cpp │ ├── sample_robustness.cpp │ ├── sample_shapes.cpp │ ├── sample_stacking.cpp │ ├── sample_world.cpp │ ├── shader.c │ ├── shader.h │ ├── stb_image_write.h │ └── stb_truetype.h ├── shared/ │ ├── CMakeLists.txt │ ├── benchmarks.c │ ├── benchmarks.h │ ├── determinism.c │ ├── determinism.h │ ├── human.c │ ├── human.h │ ├── random.c │ └── random.h ├── src/ │ ├── CMakeLists.txt │ ├── aabb.c │ ├── aabb.h │ ├── arena_allocator.c │ ├── arena_allocator.h │ ├── array.c │ ├── array.h │ ├── atomic.h │ ├── bitset.c │ ├── bitset.h │ ├── body.c │ ├── body.h │ ├── box2d.natvis │ ├── broad_phase.c │ ├── broad_phase.h │ ├── constants.h │ ├── constraint_graph.c │ ├── constraint_graph.h │ ├── contact.c │ ├── contact.h │ ├── contact_solver.c │ ├── contact_solver.h │ ├── core.c │ ├── core.h │ ├── ctz.h │ ├── distance.c │ ├── distance_joint.c │ ├── dynamic_tree.c │ ├── geometry.c │ ├── hull.c │ ├── id_pool.c │ ├── id_pool.h │ ├── island.c │ ├── island.h │ ├── joint.c │ ├── joint.h │ ├── manifold.c │ ├── math_functions.c │ ├── motor_joint.c │ ├── mover.c │ ├── physics_world.c │ ├── physics_world.h │ ├── prismatic_joint.c │ ├── revolute_joint.c │ ├── sensor.c │ ├── sensor.h │ ├── shape.c │ ├── shape.h │ ├── solver.c │ ├── solver.h │ ├── solver_set.c │ ├── solver_set.h │ ├── table.c │ ├── table.h │ ├── timer.c │ ├── types.c │ ├── weld_joint.c │ └── wheel_joint.c └── test/ ├── CMakeLists.txt ├── main.c ├── test_bitset.c ├── test_collision.c ├── test_determinism.c ├── test_distance.c ├── test_dynamic_tree.c ├── test_id.c ├── test_macros.h ├── test_math.c ├── test_shape.c ├── test_table.c └── test_world.c ================================================ FILE CONTENTS ================================================ ================================================ FILE: .clang-format ================================================ # Reference: https://clang.llvm.org/docs/ClangFormatStyleOptions.html # VS 2026 uses 20.1.8 # https://releases.llvm.org/20.1.0/tools/clang/docs/ClangFormatStyleOptions.html # https://clang-format-configurator.site/ # default values: # https://github.com/llvm/llvm-project/blob/main/clang/lib/Format/Format.cpp --- Language: Cpp BasedOnStyle: Microsoft BreakBeforeBraces: Custom BraceWrapping: AfterCaseLabel: true AfterUnion: true BeforeWhile: true ColumnLimit: 130 PointerAlignment: Left UseTab: Always BreakConstructorInitializers: BeforeComma InsertNewlineAtEOF: true IncludeBlocks: Regroup IncludeCategories: - Regex: '^"(box2d\/)' Priority: 3 - Regex: '^<.*' Priority: 4 - Regex: '^"[^.]*\.h"' Priority: 1 - Regex: '^"[^.]*\.inl"' Priority: 2 IndentExternBlock: NoIndent IndentCaseLabels: true IndentAccessModifiers: false AccessModifierOffset: -4 SpacesInParens: Custom SpacesInParensOptions: ExceptDoubleParentheses: false InConditionalStatements: true InCStyleCasts: false InEmptyParentheses: true Other: true ================================================ FILE: .gitattributes ================================================ * text=auto *.c text *.cpp text *.h text *.md text *.txt text *.sh text eol=lf *.ttf binary ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: [erincatto] patreon: Box2D open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] ================================================ FILE: .github/issue_template.md ================================================ Make sure these boxes are checked before submitting your issue - thank you! - [ ] Ask for help on [discord](https://discord.gg/NKYgCBP) - [ ] Consider providing a dump file using b2World::Dump ================================================ FILE: .github/pull_request_template.md ================================================ Pull requests for core Box2D code are generally not accepted. Please consider filing an issue instead. ================================================ FILE: .github/workflows/build.yml ================================================ name: CI Build on: push: branches: [ main ] pull_request: branches: [ main ] env: BUILD_TYPE: Debug jobs: build-ubuntu-gcc: name: ubuntu-gcc runs-on: ubuntu-latest timeout-minutes: 4 steps: - uses: actions/checkout@v4 - name: Configure CMake run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX2D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DBOX2D_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 steps: - uses: actions/checkout@v4 - name: Configure CMake run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCMAKE_CXX_COMPILER=clang++-18 -DCMAKE_C_COMPILER=clang -DBOX2D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DBOX2D_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-macos: name: macos runs-on: macos-latest steps: - uses: actions/checkout@v4 - name: Configure CMake run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX2D_SAMPLES=OFF -DBOX2D_SANITIZE=ON -DBUILD_SHARED_LIBS=OFF -DBOX2D_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 steps: - uses: actions/checkout@v4 - name: Setup MSVC dev command prompt uses: TheMrMilchmann/setup-msvc-dev@v3 with: arch: x64 - name: Configure CMake run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX2D_SAMPLES=OFF -DBOX2D_SANITIZE=ON -DBUILD_SHARED_LIBS=OFF -DBOX2D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON # run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX2D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF - 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-static: name: samples-windows-static runs-on: windows-latest steps: - uses: actions/checkout@v4 - name: Setup MSVC dev command prompt uses: TheMrMilchmann/setup-msvc-dev@v3 with: arch: x64 - name: Configure CMake run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=Release -DBOX2D_SAMPLES=ON -DBUILD_SHARED_LIBS=OFF -DBOX2D_UNIT_TESTS=OFF - name: Build run: cmake --build ${{github.workspace}}/build --config Release samples-windows-dynamic: name: samples-windows-dynamic runs-on: windows-latest steps: - uses: actions/checkout@v4 - name: Setup MSVC dev command prompt uses: TheMrMilchmann/setup-msvc-dev@v3 with: arch: x64 - name: Configure CMake run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=Release -DBOX2D_SAMPLES=ON -DBUILD_SHARED_LIBS=ON -DBOX2D_UNIT_TESTS=OFF - name: Build run: cmake --build ${{github.workspace}}/build --config Release samples-macos-static: name: samples-macos-static runs-on: macos-latest steps: - uses: actions/checkout@v4 - name: Configure CMake run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=Release -DBOX2D_SAMPLES=ON -DBUILD_SHARED_LIBS=OFF -DBOX2D_UNIT_TESTS=OFF - name: Build run: cmake --build ${{github.workspace}}/build --config Release samples-macos-dynamic: name: samples-macos-dynamic runs-on: macos-latest steps: - uses: actions/checkout@v4 - name: Configure CMake run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=Release -DBOX2D_SAMPLES=ON -DBUILD_SHARED_LIBS=ON -DBOX2D_UNIT_TESTS=OFF - name: Build run: cmake --build ${{github.workspace}}/build --config Release samples-ubuntu-gcc-static: name: samples-ubuntu-gcc-static runs-on: ubuntu-latest timeout-minutes: 4 steps: - uses: actions/checkout@v4 - name: Install X11, Wayland & GL development libraries run: sudo apt-get update && sudo apt-get install -y libx11-dev wayland-protocols libwayland-dev libxkbcommon-dev libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl-dev - name: Configure CMake run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=Release -DBOX2D_SAMPLES=ON -DBUILD_SHARED_LIBS=OFF -DBOX2D_UNIT_TESTS=OFF - name: Build run: cmake --build ${{github.workspace}}/build --config Release ================================================ FILE: .gitignore ================================================ build/ imgui.ini settings.ini .vscode/ .vs/ .cap .DS_Store CMakeUserPresets.json .cache/ .idea/ ================================================ FILE: CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.22) include(FetchContent) include(CMakeDependentOption) project(box2d VERSION 3.2.0 DESCRIPTION "A 2D physics engine for games" HOMEPAGE_URL "https://box2d.org" LANGUAGES C CXX ) # stuff to help debug cmake # message(STATUS "cmake tool chain: ${CMAKE_TOOLCHAIN_FILE}") # message(STATUS "cmake source dir: ${CMAKE_SOURCE_DIR}") # message(STATUS "library postfix: ${CMAKE_DEBUG_POSTFIX}") message(STATUS "CMake C compiler: ${CMAKE_C_COMPILER_ID}") message(STATUS "CMake C++ compiler: ${CMAKE_CXX_COMPILER_ID}") message(STATUS "CMake system name: ${CMAKE_SYSTEM_NAME}") message(STATUS "CMake host system processor: ${CMAKE_HOST_SYSTEM_PROCESSOR}") # static link to make leak checking easier (_crtBreakAlloc) # set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") if (MSVC OR APPLE) option(BOX2D_SANITIZE "Enable sanitizers for some builds" OFF) if(BOX2D_SANITIZE) message(STATUS "Box2D Sanitize") # sanitizers need to apply to all compiled libraries to work well if(MSVC) # address sanitizer only in the debug build add_compile_options("$<$:/fsanitize=address>") add_link_options("$<$:/INCREMENTAL:NO>") elseif(APPLE) add_compile_options(-fsanitize=address -fsanitize-address-use-after-scope -fsanitize=undefined) add_link_options(-fsanitize=address -fsanitize-address-use-after-scope -fsanitize=undefined) endif() else() if(MSVC AND CMAKE_CXX_COMPILER_ID STREQUAL "MSVC" AND PROJECT_IS_TOP_LEVEL) # enable hot reloading add_compile_options("$<$:/ZI>") add_link_options("$<$:/INCREMENTAL>") endif() endif() endif() # Deterministic math # https://box2d.org/posts/2024/08/determinism/ if (MINGW OR APPLE OR UNIX) add_compile_options(-ffp-contract=off) endif() option(BOX2D_DISABLE_SIMD "Disable SIMD math (slower)" OFF) option(BOX2D_COMPILE_WARNING_AS_ERROR "Compile warnings as errors" OFF) if(CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64") cmake_dependent_option(BOX2D_AVX2 "Enable AVX2" OFF "NOT BOX2D_DISABLE_SIMD" OFF) endif() set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set_property(GLOBAL PROPERTY USE_FOLDERS ON) set(CMAKE_VERBOSE_MAKEFILE ON) # Needed for samples.exe to find box2d.dll set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/bin") set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/bin") add_subdirectory(src) # This hides samples, test, and doxygen from apps that use box2d via FetchContent if(PROJECT_IS_TOP_LEVEL) option(BOX2D_SAMPLES "Build the Box2D samples" ON) option(BOX2D_BENCHMARKS "Build the Box2D benchmarks" OFF) option(BOX2D_DOCS "Build the Box2D documentation" OFF) option(BOX2D_PROFILE "Enable profiling with Tracy" OFF) option(BOX2D_VALIDATE "Enable heavy validation" ON) option(BOX2D_UNIT_TESTS "Build the Box2D unit tests" ON) if(BOX2D_UNIT_TESTS OR BOX2D_SAMPLES OR BOX2D_BENCHMARKS) # Emscripten pthread support for enkiTS if(EMSCRIPTEN) set(EMSCRIPTEN_PTHREADS_COMPILER_FLAGS "-pthread -s USE_PTHREADS=1") set(EMSCRIPTEN_PTHREADS_LINKER_FLAGS "${EMSCRIPTEN_PTHREADS_COMPILER_FLAGS} -s ALLOW_MEMORY_GROWTH") string(APPEND CMAKE_C_FLAGS " ${EMSCRIPTEN_PTHREADS_COMPILER_FLAGS}") string(APPEND CMAKE_CXX_FLAGS " ${EMSCRIPTEN_PTHREADS_COMPILER_FLAGS}") string(APPEND CMAKE_EXE_LINKER_FLAGS " ${EMSCRIPTEN_PTHREADS_LINKER_FLAGS}") endif() # Task system used in tests and samples set(ENKITS_BUILD_EXAMPLES OFF CACHE BOOL "Build enkiTS examples") FetchContent_Declare( enkits GIT_REPOSITORY https://github.com/dougbinks/enkiTS.git GIT_TAG master GIT_SHALLOW TRUE GIT_PROGRESS TRUE ) FetchContent_MakeAvailable(enkits) add_subdirectory(shared) endif() # Tests need static linkage because they test internal Box2D functions if(NOT BUILD_SHARED_LIBS AND BOX2D_UNIT_TESTS) message(STATUS "Adding Box2D unit tests") add_subdirectory(test) set_target_properties(test PROPERTIES XCODE_GENERATE_SCHEME TRUE) else() message(STATUS "Skipping Box2D unit tests") endif() if(BOX2D_SAMPLES) add_subdirectory(samples) # default startup project for Visual Studio if(MSVC) set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT samples) set_property(TARGET samples PROPERTY VS_DEBUGGER_WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") endif() if(APPLE) set_target_properties(samples PROPERTIES XCODE_GENERATE_SCHEME TRUE XCODE_SCHEME_WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") endif() endif() if(BOX2D_BENCHMARKS) add_subdirectory(benchmark) set_target_properties(benchmark PROPERTIES XCODE_GENERATE_SCHEME TRUE) endif() if(BOX2D_DOCS) add_subdirectory(docs) endif() endif() # # Building on clang in windows # cmake -S .. -B . -G "Visual Studio 17 2022" -A x64 -T ClangCL # https://clang.llvm.org/docs/UsersManual.html#clang-cl ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2022 Erin Catto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ ![Box2D Logo](https://box2d.org/images/logo.svg) # Build Status [![Build Status](https://github.com/erincatto/box2d/actions/workflows/build.yml/badge.svg)](https://github.com/erincatto/box2d/actions) # Box2D Box2D is a 2D physics engine for games. [![Box2D Version 3.0 Release Demo](https://img.youtube.com/vi/dAoM-xjOWtA/0.jpg)](https://www.youtube.com/watch?v=dAoM-xjOWtA) ## Features ### Collision - Continuous collision detection - Contact events - Convex polygons, capsules, circles, rounded polygons, segments, and chains - Multiple shapes per body - Collision filtering - Ray casts, shape casts, and overlap queries - Sensor system ### Physics - Robust _Soft Step_ rigid body solver - Continuous physics for fast translations and rotations - Island based sleep - Revolute, prismatic, distance, mouse joint, weld, and wheel joints - Joint limits, motors, springs, and friction - Joint and contact forces - Body movement events and sleep notification ### System - Data-oriented design - Written in portable C17 - Extensive multithreading and SIMD - Optimized for large piles of bodies ### Samples - OpenGL with GLFW and enkiTS - Graphical user interface with imgui - Many samples to demonstrate features and performance ## Building for Visual Studio - Install [CMake](https://cmake.org/) - Ensure CMake is in the user `PATH` - Run `create_sln.bat` - Open and build `build/box2d.sln` ## Building for Linux - Run `build.sh` from a bash shell - Results are in the build sub-folder ## Building for Xcode - Install [CMake](https://cmake.org) - Add Cmake to the path in .zprofile (the default Terminal shell is zsh) - export PATH="/Applications/CMake.app/Contents/bin:$PATH" - mkdir build - cd build - cmake -G Xcode .. - Open `box2d.xcodeproj` - Select the samples scheme - Build and run the samples ## Building and installing - mkdir build - cd build - cmake .. - cmake --build . --config Release - cmake --install . (might need sudo) ## Compatibility The Box2D library and samples build and run on Windows, Linux, and Mac. You will need a compiler that supports C17 to build the Box2D library. You will need a compiler that supports C++20 to build the samples. Box2D uses SSE2 and Neon SIMD math to improve performance. This can be disabled by defining `BOX2D_DISABLE_SIMD`. ## Documentation - [Manual](https://box2d.org/documentation/) - [Migration Guide](https://github.com/erincatto/box2d/blob/main/docs/migration.md) ## Community - [Discord](https://discord.gg/NKYgCBP) ## Contributing Please do not submit pull requests. Instead, please file an issue for bugs or feature requests. For support, please visit the Discord server. # Giving Feedback Please file an issue or start a chat on discord. You can also use [GitHub Discussions](https://github.com/erincatto/box2d/discussions). ## License Box2D is developed by Erin Catto and uses the [MIT license](https://en.wikipedia.org/wiki/MIT_License). ## Sponsorship Support development of Box2D through [Github Sponsors](https://github.com/sponsors/erincatto). Please consider starring this repository and subscribing to my [YouTube channel](https://www.youtube.com/@erin_catto). ## External ports, wrappers, and bindings (unsupported) - Beef bindings - https://github.com/EnokViking/Box2DBeef - C++ bindings - https://github.com/HolyBlackCat/box2cpp - WASM - https://github.com/Birch-san/box2d3-wasm ================================================ FILE: benchmark/CMakeLists.txt ================================================ # Box2D benchmark app set(BOX2D_BENCHMARK_FILES main.c ) add_executable(benchmark ${BOX2D_BENCHMARK_FILES}) set_target_properties(benchmark PROPERTIES C_STANDARD 17 C_STANDARD_REQUIRED YES C_EXTENSIONS NO ) if (BOX2D_COMPILE_WARNING_AS_ERROR) set_target_properties(benchmark PROPERTIES COMPILE_WARNING_AS_ERROR ON) endif() target_link_libraries(benchmark PRIVATE box2d shared enkiTS) source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} PREFIX "" FILES ${BOX2D_BENCHMARK_FILES}) ================================================ FILE: benchmark/amd7950x_avx2/joint_grid.csv ================================================ threads,ms 1,3174.52 2,1795.2 3,1217.45 4,996.27 5,857.203 6,763.975 7,696.29 8,648.49 ================================================ FILE: benchmark/amd7950x_avx2/large_pyramid.csv ================================================ threads,ms 1,1951.88 2,1026.26 3,721.553 4,563.934 5,473.542 6,415.048 7,367.646 8,362.217 ================================================ FILE: benchmark/amd7950x_avx2/many_pyramids.csv ================================================ threads,ms 1,3312.37 2,1674.87 3,1116.48 4,859.268 5,691.412 6,594.236 7,513.412 8,462.289 ================================================ FILE: benchmark/amd7950x_avx2/rain.csv ================================================ threads,ms 1,8415.32 2,4830.51 3,3684.98 4,3008.05 5,2568.19 6,2275.1 7,2054.01 8,1896.27 ================================================ FILE: benchmark/amd7950x_avx2/smash.csv ================================================ threads,ms 1,1946.15 2,1212.81 3,937.648 4,786.533 5,699.338 6,636.796 7,597.153 8,564.691 ================================================ FILE: benchmark/amd7950x_avx2/spinner.csv ================================================ threads,ms 1,5145.33 2,3090.7 3,2362.34 4,1890.21 5,1643.82 6,1473.02 7,1339.32 8,1256.21 ================================================ FILE: benchmark/amd7950x_avx2/tumbler.csv ================================================ threads,ms 1,2035.14 2,1273.93 3,961.824 4,790.221 5,679.686 6,609.556 7,561.948 8,531.353 ================================================ FILE: benchmark/amd7950x_float/joint_grid.csv ================================================ threads,ms 1,3070.3 2,1743.41 3,1190.54 4,973.725 5,839.892 6,749.347 7,684.411 8,639.372 ================================================ FILE: benchmark/amd7950x_float/large_pyramid.csv ================================================ threads,ms 1,4324.94 2,2218.25 3,1489.84 4,1132.51 5,935.469 6,818.171 7,722.364 8,658.744 ================================================ FILE: benchmark/amd7950x_float/many_pyramids.csv ================================================ threads,ms 1,6803.92 2,3421.51 3,2310.75 4,1766.54 5,1424.53 6,1213.28 7,1043.65 8,915.268 ================================================ FILE: benchmark/amd7950x_float/rain.csv ================================================ threads,ms 1,10023.3 2,5685.88 3,4189.81 4,3390.77 5,2873.75 6,2522.69 7,2275.75 8,2098.4 ================================================ FILE: benchmark/amd7950x_float/smash.csv ================================================ threads,ms 1,2660.24 2,1604.04 3,1208.81 4,997.755 5,871.282 6,791.138 7,731.148 8,687.379 ================================================ FILE: benchmark/amd7950x_float/spinner.csv ================================================ threads,ms 1,8296.22 2,4821.7 3,3555.21 4,2816.7 5,2427.56 6,2162.31 7,2007.07 8,1896.91 ================================================ FILE: benchmark/amd7950x_float/tumbler.csv ================================================ threads,ms 1,3327.12 2,1933.37 3,1436.84 4,1169.7 5,1014.31 6,907.688 7,840.671 8,786.672 ================================================ FILE: benchmark/amd7950x_sse2/joint_grid.csv ================================================ threads,ms 1,2901.74 2,1679.24 3,1138.81 4,930.556 5,802.79 6,719.061 7,653.555 8,609.054 ================================================ FILE: benchmark/amd7950x_sse2/large_pyramid.csv ================================================ threads,ms 1,2234.69 2,1198.39 3,821.019 4,636.813 5,533.46 6,476.708 7,422.339 8,384.637 ================================================ FILE: benchmark/amd7950x_sse2/many_pyramids.csv ================================================ threads,ms 1,3718.08 2,1861.18 3,1279.77 4,968.623 5,781.502 6,667.149 7,572.954 8,511.755 ================================================ FILE: benchmark/amd7950x_sse2/rain.csv ================================================ threads,ms 1,10450.7 2,6050.77 3,4647.11 4,3631.8 5,3096.74 6,2735.92 7,2460.2 8,2256.3 ================================================ FILE: benchmark/amd7950x_sse2/smash.csv ================================================ threads,ms 1,1998.87 2,1206.23 3,894.774 4,732.413 5,636.455 6,571.134 7,527.128 8,493.411 ================================================ FILE: benchmark/amd7950x_sse2/spinner.csv ================================================ threads,ms 1,5416.19 2,3229.11 3,2377.87 4,1903.65 5,1630.79 6,1448.68 7,1324.58 8,1237.05 ================================================ FILE: benchmark/amd7950x_sse2/tumbler.csv ================================================ threads,ms 1,2338.19 2,1413.12 3,1081.55 4,883.9 5,769.756 6,696.251 7,647.607 8,612.832 ================================================ FILE: benchmark/amd7950x_sse2/washer.csv ================================================ threads,ms 1,7934.7 2,4531.48 3,3218.58 4,2523.46 5,2100.84 6,1842.67 7,1638.05 8,1529.17 ================================================ FILE: benchmark/m2air_float/joint_grid.csv ================================================ threads,ms 1,2367.43 2,1449.57 3,999.678 4,838.636 ================================================ FILE: benchmark/m2air_float/large_pyramid.csv ================================================ threads,ms 1,2317.53 2,1252.4 3,891.763 4,694.968 ================================================ FILE: benchmark/m2air_float/many_pyramids.csv ================================================ threads,ms 1,3559.49 2,1888.42 3,1357.7 4,1085.2 ================================================ FILE: benchmark/m2air_float/rain.csv ================================================ threads,ms 1,7119.67 2,4144.16 3,3192.93 4,2623.99 ================================================ FILE: benchmark/m2air_float/smash.csv ================================================ threads,ms 1,1757.78 2,1079.8 3,849.502 4,709.022 ================================================ FILE: benchmark/m2air_float/spinner.csv ================================================ threads,ms 1,5434.23 2,3244.67 3,2462.03 4,1998.78 ================================================ FILE: benchmark/m2air_float/tumbler.csv ================================================ threads,ms 1,2094.15 2,1270.1 3,1020.63 4,835.34 ================================================ FILE: benchmark/m2air_neon/joint_grid.csv ================================================ threads,ms 1,2377.18 2,1444.78 3,998.22 4,837.361 ================================================ FILE: benchmark/m2air_neon/large_pyramid.csv ================================================ threads,ms 1,1600.72 2,880.846 3,632.579 4,502.146 ================================================ FILE: benchmark/m2air_neon/many_pyramids.csv ================================================ threads,ms 1,2455.91 2,1329.33 3,984.499 4,820.902 ================================================ FILE: benchmark/m2air_neon/rain.csv ================================================ threads,ms 1,6834.98 2,4020.86 3,3123.64 4,2574.69 ================================================ FILE: benchmark/m2air_neon/smash.csv ================================================ threads,ms 1,1595.13 2,1005.41 3,798.89 4,670.542 ================================================ FILE: benchmark/m2air_neon/spinner.csv ================================================ threads,ms 1,4715.34 2,2939.07 3,2264.93 4,1855.98 ================================================ FILE: benchmark/m2air_neon/tumbler.csv ================================================ threads,ms 1,1804.16 2,1150.51 3,945.004 4,777.227 ================================================ FILE: benchmark/main.c ================================================ // SPDX-FileCopyrightText: 2024 Erin Catto // SPDX-License-Identifier: MIT #if defined( _MSC_VER ) && !defined( _CRT_SECURE_NO_WARNINGS ) #define _CRT_SECURE_NO_WARNINGS #endif #include "TaskScheduler_c.h" #include "benchmarks.h" #include "box2d/box2d.h" #include "box2d/math_functions.h" #include #include #include #include #include #if defined( _WIN64 ) #include #elif defined( __APPLE__ ) #include #elif defined( __linux__ ) #include #endif #define ARRAY_COUNT( A ) (int)( sizeof( A ) / sizeof( A[0] ) ) #define MAYBE_UNUSED( x ) ( (void)( x ) ) typedef void CreateFcn( b2WorldId worldId ); typedef float StepFcn( b2WorldId worldId, int stepCount ); typedef struct Benchmark { const char* name; CreateFcn* createFcn; StepFcn* stepFcn; int totalStepCount; } Benchmark; #define MAX_TASKS 128 #define THREAD_LIMIT 32 typedef struct TaskData { b2TaskCallback* box2dTask; void* box2dContext; } TaskData; enkiTaskScheduler* scheduler; enkiTaskSet* tasks[MAX_TASKS]; TaskData taskData[MAX_TASKS]; int taskCount; int GetNumberOfCores() { #if defined( _WIN64 ) SYSTEM_INFO sysinfo; GetSystemInfo( &sysinfo ); return sysinfo.dwNumberOfProcessors; #elif defined( __APPLE__ ) return (int)sysconf( _SC_NPROCESSORS_ONLN ); #elif defined( __linux__ ) return (int)sysconf( _SC_NPROCESSORS_ONLN ); #elif defined( __EMSCRIPTEN__ ) return (int)sysconf( _SC_NPROCESSORS_ONLN ); #else return 1; #endif } void ExecuteRangeTask( uint32_t start, uint32_t end, uint32_t threadIndex, void* context ) { TaskData* data = context; data->box2dTask( start, end, threadIndex, data->box2dContext ); } static void* EnqueueTask( b2TaskCallback* box2dTask, int itemCount, int minRange, void* box2dContext, void* userContext ) { MAYBE_UNUSED( userContext ); if ( taskCount < MAX_TASKS ) { enkiTaskSet* task = tasks[taskCount]; TaskData* data = taskData + taskCount; data->box2dTask = box2dTask; data->box2dContext = box2dContext; struct enkiParamsTaskSet params; params.minRange = minRange; params.setSize = itemCount; params.pArgs = data; params.priority = 0; enkiSetParamsTaskSet( task, params ); enkiAddTaskSet( scheduler, task ); ++taskCount; return task; } else { printf( "MAX_TASKS exceeded!!!\n" ); box2dTask( 0, itemCount, 0, box2dContext ); return NULL; } } static void FinishTask( void* userTask, void* userContext ) { MAYBE_UNUSED( userContext ); enkiTaskSet* task = userTask; enkiWaitForTaskSet( scheduler, task ); } static void MinProfile( b2Profile* p1, const b2Profile* p2 ) { p1->step = b2MinFloat( p1->step, p2->step ); p1->pairs = b2MinFloat( p1->pairs, p2->pairs ); p1->collide = b2MinFloat( p1->collide, p2->collide ); p1->solveConstraints = b2MinFloat( p1->solveConstraints, p2->solveConstraints ); p1->transforms = b2MinFloat( p1->transforms, p2->transforms ); p1->refit = b2MinFloat( p1->refit, p2->refit ); p1->sleepIslands = b2MinFloat( p1->sleepIslands, p2->sleepIslands ); } // Box2D benchmark application. On Windows it is important to use affinity avoid cross CCD // usage or efficiency cores. Also on Windows create a power plan with Processor power management // Min/Max of 99%. This prevents boosting and makes the benchmarks more repeatable. // Affinity [0x01 0x02 0x04 0x08 0x10 0x20 0x40 0x80] // Run all benchmarks with 1 to 8 threads. // start /affinity 0x5555 .\build\bin\Release\benchmark.exe -t=8 // Run all benchmarks with 4 workers only. // start /affinity 0x5555 .\build\bin\Release\benchmark.exe -t=4 -w=4 // Run benchmark 3 with 4 workers and repeat 20 times. Record the step times. // start /affinity 0x5555 .\build\bin\Release\benchmark.exe -t=4 -w=4 -b=3 -r=20 -s // start /affinity 0x5555 .\build\bin\Release\benchmark.exe -t=8 -b=7 // Run benchmark 3 with 4 workers and run once. Disable continuous collision. Record the step times. // start /affinity 0x5555 .\build\bin\Release\benchmark.exe -t=4 -w=4 -b=3 -r=1 -nc -s int main( int argc, char** argv ) { Benchmark benchmarks[] = { { "joint_grid", CreateJointGrid, NULL, 500 }, { "large_pyramid", CreateLargePyramid, NULL, 500 }, { "many_pyramids", CreateManyPyramids, NULL, 200 }, { "rain", CreateRain, StepRain, 1000 }, { "smash", CreateSmash, NULL, 300 }, { "spinner", CreateSpinner, StepSpinner, 500 }, { "tumbler", CreateTumbler, NULL, 750 }, { "washer", CreateWasher, NULL, 500 }, }; int benchmarkCount = ARRAY_COUNT( benchmarks ); int maxSteps = benchmarks[0].totalStepCount; for ( int i = 1; i < benchmarkCount; ++i ) { maxSteps = b2MaxInt( maxSteps, benchmarks[i].totalStepCount ); } b2Profile maxProfile = { .step = FLT_MAX, .pairs = FLT_MAX, .collide = FLT_MAX, .solve = FLT_MAX, .prepareStages = FLT_MAX, .solveConstraints = FLT_MAX, .prepareConstraints = FLT_MAX, .integrateVelocities = FLT_MAX, .warmStart = FLT_MAX, .solveImpulses = FLT_MAX, .integratePositions = FLT_MAX, .relaxImpulses = FLT_MAX, .applyRestitution = FLT_MAX, .storeImpulses = FLT_MAX, .splitIslands = FLT_MAX, .transforms = FLT_MAX, .hitEvents = FLT_MAX, .refit = FLT_MAX, .bullets = FLT_MAX, .sleepIslands = FLT_MAX, }; b2Profile* profiles = malloc( maxSteps * sizeof( b2Profile ) ); for ( int i = 0; i < maxSteps; ++i ) { profiles[i] = maxProfile; } float* stepResults = malloc( maxSteps * sizeof( float ) ); memset( stepResults, 0, maxSteps * sizeof( float ) ); int maxThreadCount = GetNumberOfCores(); int runCount = 4; int singleBenchmark = -1; int singleWorkerCount = -1; b2Counters counters = { 0 }; bool enableContinuous = true; bool recordStepTimes = false; assert( maxThreadCount <= THREAD_LIMIT ); for ( int i = 1; i < argc; ++i ) { const char* arg = argv[i]; if ( strncmp( arg, "-t=", 3 ) == 0 ) { int threadCount = atoi( arg + 3 ); maxThreadCount = b2ClampInt( threadCount, 1, maxThreadCount ); } else if ( strncmp( arg, "-b=", 3 ) == 0 ) { singleBenchmark = atoi( arg + 3 ); singleBenchmark = b2ClampInt( singleBenchmark, 0, benchmarkCount - 1 ); } else if ( strncmp( arg, "-w=", 3 ) == 0 ) { singleWorkerCount = atoi( arg + 3 ); } else if ( strncmp( arg, "-r=", 3 ) == 0 ) { runCount = b2ClampInt( atoi( arg + 3 ), 1, 1000 ); } else if ( strncmp( arg, "-nc", 3 ) == 0 ) { enableContinuous = false; printf( "Continuous disabled\n" ); } else if ( strncmp( arg, "-s", 3 ) == 0 ) { recordStepTimes = true; } else if ( strcmp( arg, "-h" ) == 0 ) { printf( "Usage\n" "-t=: the maximum number of threads to use\n" "-b=: run a single benchmark\n" "-w=: run a single worker count\n" "-r=: number of repeats (default is 4)\n" "-s: record step times\n" ); exit( 0 ); } } if ( singleWorkerCount != -1 ) { singleWorkerCount = b2ClampInt( singleWorkerCount, 1, maxThreadCount ); } printf( "Starting Box2D benchmarks\n" ); printf( "======================================\n" ); for ( int benchmarkIndex = 0; benchmarkIndex < benchmarkCount; ++benchmarkIndex ) { if ( singleBenchmark != -1 && benchmarkIndex != singleBenchmark ) { continue; } #ifdef NDEBUG int stepCount = benchmarks[benchmarkIndex].totalStepCount; #else int stepCount = 10; #endif Benchmark* benchmark = benchmarks + benchmarkIndex; bool countersAcquired = false; printf( "benchmark: %s, steps = %d\n", benchmarks[benchmarkIndex].name, stepCount ); float minTime[THREAD_LIMIT] = { 0 }; for ( int threadCount = 1; threadCount <= maxThreadCount; ++threadCount ) { if ( singleWorkerCount != -1 && singleWorkerCount != threadCount ) { continue; } printf( "thread count: %d\n", threadCount ); for ( int runIndex = 0; runIndex < runCount; ++runIndex ) { scheduler = enkiNewTaskScheduler(); struct enkiTaskSchedulerConfig config = enkiGetTaskSchedulerConfig( scheduler ); config.numTaskThreadsToCreate = threadCount - 1; enkiInitTaskSchedulerWithConfig( scheduler, config ); for ( int taskIndex = 0; taskIndex < MAX_TASKS; ++taskIndex ) { tasks[taskIndex] = enkiCreateTaskSet( scheduler, ExecuteRangeTask ); } b2WorldDef worldDef = b2DefaultWorldDef(); worldDef.enableContinuous = enableContinuous; worldDef.enqueueTask = EnqueueTask; worldDef.finishTask = FinishTask; worldDef.workerCount = threadCount; b2WorldId worldId = b2CreateWorld( &worldDef ); benchmark->createFcn( worldId ); float timeStep = 1.0f / 60.0f; int subStepCount = 4; // Initial step can be expensive and skew benchmark if ( benchmark->stepFcn != NULL ) { stepResults[0] = benchmark->stepFcn( worldId, 0 ); } assert( stepCount <= maxSteps ); b2World_Step( worldId, timeStep, subStepCount ); b2Profile profile = b2World_GetProfile( worldId ); MinProfile( profiles + 0, &profile ); taskCount = 0; uint64_t ticks = b2GetTicks(); for ( int stepIndex = 1; stepIndex < stepCount; ++stepIndex ) { if ( benchmark->stepFcn != NULL ) { stepResults[stepIndex] = benchmark->stepFcn( worldId, stepIndex ); } b2World_Step( worldId, timeStep, subStepCount ); taskCount = 0; profile = b2World_GetProfile( worldId ); MinProfile( profiles + stepIndex, &profile ); } float ms = b2GetMilliseconds( ticks ); printf( "run %d : %g (ms)\n", runIndex, ms ); if (runIndex == 0) { minTime[threadCount - 1] = ms ; } else { minTime[threadCount - 1] = b2MinFloat( minTime[threadCount - 1], ms ); } if ( countersAcquired == false ) { counters = b2World_GetCounters( worldId ); countersAcquired = true; } b2DestroyWorld( worldId ); for ( int taskIndex = 0; taskIndex < MAX_TASKS; ++taskIndex ) { enkiDeleteTaskSet( scheduler, tasks[taskIndex] ); tasks[taskIndex] = NULL; taskData[taskIndex] = ( TaskData ){ 0 }; } enkiDeleteTaskScheduler( scheduler ); scheduler = NULL; } if ( recordStepTimes ) { char fileName[64] = { 0 }; snprintf( fileName, 64, "%s_t%d.dat", benchmarks[benchmarkIndex].name, threadCount ); FILE* file = fopen( fileName, "w" ); if ( file == NULL ) { continue; } for ( int stepIndex = 0; stepIndex < stepCount; ++stepIndex ) { b2Profile p = profiles[stepIndex]; fprintf( file, "%g %g %g %g %g %g %g\n", p.step, p.pairs, p.collide, p.solveConstraints, p.transforms, p.refit, p.sleepIslands ); } fclose( file ); } } printf( "body %d / shape %d / contact %d / joint %d / stack %d\n\n", counters.bodyCount, counters.shapeCount, counters.contactCount, counters.jointCount, counters.stackUsed ); char fileName[64] = { 0 }; snprintf( fileName, 64, "%s.csv", benchmarks[benchmarkIndex].name ); FILE* file = fopen( fileName, "w" ); if ( file == NULL ) { continue; } fprintf( file, "threads,ms\n" ); for ( int threadIndex = 1; threadIndex <= maxThreadCount; ++threadIndex ) { fprintf( file, "%d,%g\n", threadIndex, minTime[threadIndex - 1] ); } fclose( file ); } printf( "======================================\n" ); printf( "All Box2D benchmarks complete!\n" ); free( profiles ); free( stepResults ); return 0; } ================================================ FILE: benchmark/n100_sse2/joint_grid.csv ================================================ threads,fps 1,75.5947 2,123.228 3,160.379 4,181.545 ================================================ FILE: benchmark/n100_sse2/large_pyramid.csv ================================================ threads,fps 1,127.236 2,226.291 3,297.628 4,345.526 ================================================ FILE: benchmark/n100_sse2/many_pyramids.csv ================================================ threads,fps 1,30.8828 2,55.0462 3,69.5406 4,77.7339 ================================================ FILE: benchmark/n100_sse2/rain.csv ================================================ threads,fps 1,72.2901 2,118.753 3,142.61 4,162.35 ================================================ FILE: benchmark/n100_sse2/smash.csv ================================================ threads,fps 1,86.2381 2,132.306 3,160.725 4,181.842 ================================================ FILE: benchmark/n100_sse2/spinner.csv ================================================ threads,fps 1,156.855 2,258.638 3,303.717 4,358.492 ================================================ FILE: benchmark/n100_sse2/tumbler.csv ================================================ threads,fps 1,199.492 2,313.012 3,381.983 4,441.825 ================================================ FILE: build.sh ================================================ #!/usr/bin/env bash # Use this to build box2d on any system with a bash shell rm -rf build mkdir build cd build # I haven't been able to get Wayland working on WSL but X11 works. # https://www.glfw.org/docs/latest/compile.html cmake -DBOX2D_BUILD_DOCS=OFF -DGLFW_BUILD_WAYLAND=OFF .. cmake --build . ================================================ FILE: build_emscripten.sh ================================================ #!/usr/bin/env bash # source emsdk_env.sh # Use this to build box2d on any system with a bash shell rm -rf build mkdir build cd build emcmake cmake -DBOX2D_VALIDATE=OFF -DBOX2D_UNIT_TESTS=ON -DBOX2D_SAMPLES=OFF -DCMAKE_BUILD_TYPE=Debug .. cmake --build . ================================================ FILE: create_sln.bat ================================================ rem Use this batch file to build box2d for Visual Studio rmdir /s /q build mkdir build cd build cmake .. ================================================ FILE: deploy_docs.sh ================================================ #!/usr/bin/env bash # Copies documentation to blog cp -R build/docs/html/. ../box2d_blog/public/documentation/ ================================================ FILE: docs/CMakeLists.txt ================================================ find_package(Doxygen REQUIRED dot) set(DOXYGEN_PROJECT_NAME "Box2D") set(DOXYGEN_GENERATE_HTML YES) set(DOXYGEN_USE_MATHJAX YES) set(DOXYGEN_MATHJAX_VERSION MathJax_3) set(DOXYGEN_MATHJAX_FORMAT SVG) set(DOXYGEN_EXTRACT_ALL NO) set(DOXYGEN_FILE_PATTERNS *.h) set(DOXYGEN_ENABLE_PREPROCESSING YES) set(DOXYGEN_MACRO_EXPANSION YES) set(DOXYGEN_EXPAND_ONLY_PREDEF YES) set(DOXYGEN_PREDEFINED B2_API= B2_INLINE=) set(DOXYGEN_WARN_IF_UNDOCUMENTED YES) # In multiline comments, this takes the first line/sentence as a brief description to use in the table of functions. # So I don't need to use @brief tags to separate the short description from the full description. set(DOXYGEN_JAVADOC_AUTOBRIEF YES) set(DOXYGEN_IMAGE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/images") set(DOXYGEN_HTML_EXTRA_STYLESHEET "${CMAKE_CURRENT_SOURCE_DIR}/extra.css") set(DOXYGEN_USE_MDFILE_AS_MAINPAGE "${CMAKE_CURRENT_SOURCE_DIR}/overview.md") set(DOXYGEN_PROJECT_LOGO "${CMAKE_CURRENT_SOURCE_DIR}/images/logo.svg") set(DOXYGEN_LAYOUT_FILE "${CMAKE_CURRENT_SOURCE_DIR}/layout.xml") set(DOXYGEN_INLINE_SIMPLE_STRUCTS YES) set(DOXYGEN_TYPEDEF_HIDES_STRUCT YES) # set(DOXYGEN_DISABLE_INDEX YES) set(DOXYGEN_GENERATE_TREEVIEW YES) set(DOXYGEN_FULL_SIDEBAR NO) # force dark mode to work with extra.css set(DOXYGEN_HTML_COLORSTYLE DARK) # this tells doxygen to label structs as structs instead of classes set(DOXYGEN_OPTIMIZE_OUTPUT_FOR_C YES) set(DOXYGEN_WARN_IF_INCOMPLETE_DOC NO) doxygen_add_docs(doc "${CMAKE_SOURCE_DIR}/include/box2d" "overview.md" "hello.md" "samples.md" "foundation.md" "collision.md" "simulation.md" "loose_ends.md" "character.md" "reading.md" "faq.md" "migration.md" "release_notes_v310.md" ALL COMMENT "Generate HTML documentation") ================================================ FILE: docs/FAQ.md ================================================ # FAQ ## What is Box2D? Box2D is a feature rich 2D rigid body physics engine, written in C17 by Erin Catto. It has been used in many games and in many game engines. Box2D uses the [MIT license](https://en.wikipedia.org/wiki/MIT_License) license and can be used free of charge. Credit should be included if possible. Support is [appreciated](https://github.com/sponsors/erincatto). You may use the Box2D [logo](https://box2d.org/images/logo.svg). ## What platforms does Box2D support? Box2D is developed using C. Ports and bindings are likely available for most languages and platforms. Erin Catto maintains the C version, but provides no support for other languages. Other languages are supported by the community and possibly by the authors of those ports. ## Who makes it? Erin Catto is the creator and sole contributor of the C version of Box2D, with various others supporting the ports. Box2D is an open source project, and accepts community feedback. ## How do I get help? You should read the documentation and the rest of this FAQ first. Also, you should study the examples included in the source distribution. Then you can visit the [Discord](https://discord.gg/aM4mRKxW) to ask any remaining questions. Please to not message or email Erin Catto directly for support. It is best to ask questions on the Discord server so that everyone can benefit from the discussion. ## Documentation ### Why isn't a feature documented? If you grab the latest code from the git main branch you will likely find features that are not documented in the manual. New features are added to the manual after they are mature and a new point release is imminent. However, all major features added to Box2D are accompanied by example code in the samples application to test the feature and show the intended usage. ## Prerequisites ### Programming You should have a working knowledge of C before you use Box2D. You should understand functions, structures, and pointers. There are plenty of resources on the web for learning C. You should also understand your development environment: compilation, linking, and debugging. ### Math and Physics You should have a basic knowledge of rigid bodies, force, torque, and impulses. If you come across a math or physics concept you don't understand, please read about it on Wikipedia. Visit this [page](http://box2d.org/publications/) if you want a deeper knowledge of the algorithms used in Box2D. ## API ### What units does Box2D use? Box2D is tuned for meters-kilograms-seconds (MKS). This is recommend as the units for your game. However, you may use different units if you are careful. ### How do I convert pixels to meters? Suppose you have a sprite for a character that is 100x100 pixels. You decide to use a scaling factor that is 0.01. This will make the character physics box 1m x 1m. So go make a physics box that is 1x1. Now suppose the character starts out at pixel coordinate (345,679). So position the physics box at (3.45,6.79). Now simulate the physics world. Suppose the character physics box moves to (2.31,4.98), so move your character sprite to pixel coordinates (231,498). Now the only tricky part is choosing a scaling factor. This really depends on your game. You should try to get your moving objects in the range 0.1 - 10 meters, with 1 meter being the sweet spot. This [repo](https://github.com/erincatto/box2d-raylib) shows how to convert meters to pixels. ### Why don't you use this awesome language? Box2D is designed to be portable and easy to wrap with other languages, so I decided to use C17. I used C17 to get support for atomics. ### Can I use Box2D in a DLL? Yes. See the CMake option `BUILD_SHARED_LIBS`. ### Is Box2D thread-safe? No. Box2D will likely never be thread-safe. Box2D has a large API and trying to make such an API thread-safe would have a large performance and complexity impact. However, you can call read only functions from multiple threads. For example, all the [spatial query](#spatial) functions are read only. ## Build Issues ### Why doesn't my code compile and/or link? There are many reasons why a build can go bad. Here are a few that have come up: * Using old Box2D headers with new code * Not linking the Box2D library with your application * Using old project files that don't include some new source files ## Rendering ### What are Box2D's rendering capabilities? Box2D is only a physics engine. How you draw stuff is up to you. ### But the samples application draws stuff Visualization is very important for debugging collision and physics. I wrote the samples application to help me test Box2D and give you examples of how to use Box2D. The samples are not part of the Box2D library. ### How do I draw shapes? Implement the `b2DebugDraw` interface and call `b2World_Draw()`. ## Accuracy Box2D uses approximate methods for a few reasons. * Performance * Some differential equations don't have known solutions * Some constraints cannot be determined uniquely What this means is that constraints are not perfectly rigid and sometimes you will see some bounce even when the restitution is zero. Box2D uses [Gauss-Seidel](https://en.wikipedia.org/wiki/Gauss%E2%80%93Seidel_method) to approximately solve constraints. Box2D also uses [Semi-implicit Euler](https://en.wikipedia.org/wiki/Semi-implicit_Euler_method) to approximately solve the differential equations. Box2D also does not have exact collision. There is no continuous collision between dynamic shapes. Slow moving shapes may have small overlap for a few time steps. In extreme stacking scenarios, shapes may have sustained overlap. ## Making Games ### Worms Clones Making a worms clone requires arbitrarily destructible terrain. This is beyond the scope of Box2D, so you will have to figure out how to do this on your own. ### Tile Based Environment Using many boxes for your terrain may not work well because box-like characters can get snagged on internal corners. Box2D provides chain shapes for smooth collision, see `b2ChainDef`. In general you should avoid using a rectangular character because collision tolerances will still lead to undesirable snagging. Box2D provides capsules and rounded polygons that may work better for characters. ### Asteroid Type Coordinate Systems Box2D does not have any support for coordinate frame wrapping. You would likely need to customize Box2D for this purpose. You may need to use a different broad-phase for this to work. ## Determinism ### Is Box2D deterministic? For the same input, and same binary, Box2D will reproduce any simulation. Box2D does not use any random numbers nor base any computation on random events (such as timers, etc). Box2D is also deterministic under multithreading. A simulation using two threads will give the same result as eight threads. Box2D has cross-platform determinism as of version 3.1. However, Box2D does not have rollback determinism. ### But I really want determinism This naturally leads to the question of fixed-point math. Box2D does not support fixed-point math. In the past Box2D was ported to the NDS in fixed-point and apparently it worked okay. Fixed-point math is slower and more tedious to develop, so I have chosen not to use fixed-point for the development of Box2D. ## What are the common mistakes made by new users? * Using pixels for length instead of meters * Expecting Box2D to give pixel perfect results * Testing their code in release mode * Not learning C before using Box2D ================================================ FILE: docs/character.md ================================================ # Character mover > **Caution**: > The character mover feature is new to version 3.1 and should be considered experimental. Box2D provides a few structures and functions you can use to build a character mover. These features support a `geometric` character mover. This is like a `kinematic` mover except the character mover is not a rigid body and does not exist in the simulation world. This is done to achieve features that would be difficult with a kinematic body. This type of mover may not be suitable for your game. It is less physical than a rigid body, but it gives you more control over the movement. It is the type of mover you might find in a first-person shooter or a game with platforming elements. The mover is assumed to be a capsule. Using a capsule helps keep movement smooth. The capsule should have a significant radius. It does not have to be a vertical capsule, but that is likely to be the easiest setup. There is no explicit handling of rotation. But slow rotation can work with this system. Let's review the features. First there are a couple world query functions. `b2World_CastMover()` is a custom shape cast that tries to avoid getting stuck when shapes start out touching. The feature is called _encroachment_. Since the capsule has a significant radius it can move closer to a surface it is touching without the inner line segment generating an overlap, which would cause the shape cast to fail. Due to the internal use of GJK, encroachment has little cost. The idea with encroachment is that the mover is trying to slide along a surface and we don't want to stop that even if there is some small movement into the surface. `b2World_CollideMover()` complements the cast function. This function generates collision planes for touching and/or overlapped surfaces. The character mover is assumed to have a fixed rotation, so it doesn't need contact manifolds or contact points. It just needs collision planes. Each plane is returned with the `b2Plane` and a `b2ShapeId` for each shape the mover is touching. Once you have some collision planes from `b2World_CollideMover()`, you can process and filter them to generate an array of `b2CollisionPlane`. These collision planes can then be sent to `b2SolvePlanes()` to generate a new position for the mover that attempts to find the optimal new position given the current position. These collision planes support *soft collision* using a `pushLimit`. This push limit is a distance value. A rigid surface will have a push limit of `FLT_MAX`. However, you may want some surfaces to have a limited effect on the character. For example, you may want the mover to push through other players or enemies yet still resolve the collision so they are not overlapped. Another example is a door or elevator that could otherwise push the mover through the floor. Finally after calling `b2SolverPlanes()` you can call `b2ClipVector()` to clip your velocity vector so the mover will not keep trying to push into a wall, which could lead to a huge velocity accumulation otherwise. The `Mover` sample shows all these functions being used together. It also includes other common character features such as acceleration and friction, jumping, and a pogo stick. ![Character Mover](images/mover.png) ================================================ FILE: docs/collision.md ================================================ # Collision Box2D provides geometric types and functions. These include: - primitives: circles, capsules, segments, and convex polygons - convex hull and related helper functions - mass and bounding box computation - local ray and shape casts - contact manifolds - shape distance - time of impact - dynamic bounding volume tree - character movement solver The collision interface is designed to be usable outside of rigid body simulation. For example, you can use the dynamic tree for other aspects of your game besides physics. However, the main purpose of Box2D is to be a rigid body physics engine. So the collision interface only contains features that are also useful in the physics simulation. ## Shape Primitives Shape primitives describe collision geometry and may be used independently of physics simulation. At a minimum, you should understand how to create primitives that can be later attached to rigid bodies. Box2D shape primitives support several operations: - Test a point for overlap with the primitive - Perform a ray cast against the primitive - Compute the primitive's bounding box - Compute the mass properties of the primitive ### Circles Circles have a center and radius. Circles are solid. ![Circle](images/circle.svg) ```c b2Circle circle; circle.center = (b2Vec2){2.0f, 3.0f}; circle.radius = 0.5f; ``` You can also initialize a circle and other structures inline. This is an equivalent circle: ```c b2Circle circle = {{2.0f, 3.0f}, 0.5f}; ``` ### Capsules Capsules have two center points and a radius. The center points are the centers of two semicircles that are connected by a rectangle. ![Capsule](images/capsule.svg) ```c b2Capsule capsule; capsule.center1 = (b2Vec2){1.0f, 1.0f}; capsule.center2 = (b2Vec2){2.0f, 3.0f}; capsule.radius = 0.25f; ``` ### Polygons Box2D polygons are solid convex polygons. A polygon is convex when all line segments connecting two points in the interior do not cross any edge of the polygon. Polygons are solid and never hollow. A polygon must have 3 or more vertices. ![Convex and Concave Polygons](images/convex_concave.svg) Polygons vertices are stored with a counter clockwise winding (CCW). We must be careful because the notion of CCW is with respect to a right-handed coordinate system with the z-axis pointing out of the plane. This might turn out to be clockwise on your screen, depending on your coordinate system conventions. ![Polygon Winding Order](images/winding.svg) The polygon members are public, but you should use initialization functions to create a polygon. The initialization functions create normal vectors and perform validation. Polygons in Box2D have a maximum of 8 vertices, as controlled by #B2_MAX_POLYGON_VERTICES. If you have more complex shapes, I recommend to use multiple polygons. There are a few ways to create polygons. You can attempt to create them manually, but this is not recommended. Instead there are several functions provided to create them. For example if you need a square or box you can use these functions: ```c b2Polygon square = b2MakeSquare(0.5f); b2Polygon box = b2MakeBox(0.5f, 1.0f); ``` The values provided to these functions are *extents*, which are half-widths or half-heights. This corresponds with circles and capsules using radii instead of diameters. Box2D also supports rounded polygons. These are convex polygons with a thick rounded skin. ```c float radius = 0.25f; b2Polygon roundedBox = b2MakeRoundedBox(0.5f, 1.0f, radius); ``` If you want a box that is not centered on the body origin, you can use an offset box. ```c b2Vec2 center = {1.0f, 0.0f}; float angle = b2_pi / 4.0f; b2Rot rotation = b2MakeRot(angle); b2Polygon offsetBox = b2MakeOffsetBox(0.5f, 1.0f, center, rotation); ``` If you want a more general convex polygon, you can compute the hull using `b2ComputeHull()`. Then you can create a polygon from the hull. You can make this rounded as well. ```c b2Vec2 points[] = {{-1.0f, 0.0f}, {1.0f, 0.0f}, {0.0f, 1.0f}}; b2Hull hull = b2ComputeHull(points, 3); float radius = 0.1f; b2Polygon roundedTriangle = b2MakePolygon(&hull, radius); ``` If you have an automatic process for generating convex polygons, you may feed a degenerate set of points to `b2ComputeHull()`. You should check that the hull was created successfully before creating the polygon or you will get an assertion. ```c b2Hull questionableHull = b2ComputeHull(randomPoints, 8); if (questionableHull.count == 0) { // handle failure } ``` Degenerate points may be coincident and/or collinear. For the hull to be viable, the enclosed area must be sufficiently positive. ### Segments Segments are line segments. Segment shapes can collide with circles, capsules, and polygons but not with other line segments. The collision algorithms used by Box2D require that at least one of two colliding shapes has sufficiently positive area. Segment shapes have no area, so segment-segment collision is not possible. ```c b2Segment segment1; segment1.point1 = (b2Vec2){0.0f, 0.0f}; segment2.point2 = (b2Vec2){1.0f, 0.0f}; // equivalent b2Segment segment2 = {{0.0f, 0.0f}, {1.0f, 0.0f}}; ``` ### Ghost Collisions In many cases a game environment is constructed by connecting several segment shapes end-to-end. This can give rise to an unexpected artifact when a polygon slides along the chain of segments. In the figure below there is a box colliding with an internal vertex. These *ghost* collisions are caused when the polygon collides with an internal vertex generating an internal collision normal. ![Ghost Collision](images/ghost_collision.svg){html: width=30%} If edge1 did not exist this collision would seem fine. With edge1 present, the internal collision seems like a bug. But normally when Box2D collides two shapes, it views them in isolation. `b2ChainSegment` provides a mechanism for eliminating ghost collisions by storing the adjacent *ghost* vertices. Box2D uses these ghost vertices to prevent internal collisions. ![Ghost Vertices](images/ghost_vertices.svg){html: width=30%} The Box2D algorithm for dealing with ghost collisions only supports one-sided collision. The front face is to the right when looking from the first vertex towards the second vertex. This matches the counter-clockwise winding order used by polygons. ### Chain segment Chain segments use a concept called *ghost vertices* that Box2D can use to eliminate ghost collisions. ```c b2ChainSegment chainSegment = {0}; chainSegment.ghost1 = (b2Vec2){1.7f, 0.0f}; chainSegment.segment = (b2Segment){{1.0f, 0.25f}, {0.0f, 0.0f}}; chainSegment.ghost2 = (b2Vec2){-1.7f, 0.4f}; ``` These ghost vertices must align with vertices of neighboring chain segments, making them tedious and error-prone to setup. Chain segments are not created directly. Instead, you can create chains of line segments. See `b2ChainDef` and `b2CreateChain()`. ## Geometric Queries You can perform a geometric queries on a single shape. ### Shape Point Test You can test a point for overlap with a shape. You provide a transform for the shape and a world point. ```c b2Vec2 point = {5.0f, 2.0f}; bool hit = b2PointInCapsule(point, &myCapsule); ``` See also `b2PointInCircle()` and `b2PointInPolygon()`. ### Ray Cast You can cast a ray at a shape to get the point of first intersection and normal vector. > **Caution**: > No hit will register if the ray starts inside a convex shape like a circle or polygon. This is > consistent with Box2D treating convex shapes as solid. ```c b2RayCastInput input = {0}; input.origin = (b2Vec2){0.0f, 0.0f}; input.translation = (b2Vec2){1.0f, 0.0f}; input.maxFraction = 1.0f; b2CastOutput output = b2RayCastPolygon(&input, &myPolygon); if (output.hit == true) { // do something } ``` ### Shape Cast You can also cast a shape at another shape. This uses an abstract way of describing the moving shape. It is represented as a point cloud with a radius. This implies a convex shape even if the input data is not convex. The internal algorithm (GJK) will essentially only use the convex portion. ```c b2ShapeCastInput input = {0}; input.points[0] = (b2Vec2){1.0f, 0.0f}; input.points[1] = (b2Vec2){2.0f, -3.0f}; input.radius = 0.2f; input.translation = (b2Vec2){1.0f, 0.0f}; input.maxFraction = 1.0f; b2CastOutput output = b2ShapeCastPolygon(&input, &myPolygon); if (output.hit == true) { // do something } ``` Even more generic, you can use `b2ShapeCast()` to linearly cast one point cloud at another point cloud. All shape cast functions use this internally. ### Distance `b2ShapeDistance()` function can be used to compute the distance between two shapes. The distance function needs both shapes to be converted into a `b2DistanceProxy` (which are point clouds with radii). There is also some caching used to warm start the distance function for repeated calls. This can improve performance when the shapes move by small amounts. ![Distance Function](images/distance.svg) ### Time of Impact If two shapes are moving fast, they may *tunnel* through each other in a single time step. ![Tunneling](images/tunneling2.svg){html: width=30%} The `b2TimeOfImpact()` function is used to determine the time when two moving shapes collide. This is called the *time of impact* (TOI). The main purpose of `b2TimeOfImpact()` is for tunnel prevention. Box2D uses this internally to prevent moving objects from tunneling through static shapes. The `b2TimeOfImpact()` identifies an initial separating axis and ensures the shapes do not cross on that axis. This process is repeated as shapes are moved closer together, until they touch or pass by each other. The TOI function might miss collisions that are clear at the final positions. Nevertheless, it is very fast and adequate for tunnel prevention. ![Captured Collision](images/captured_toi.svg){html: width=30%} ![Missed Collision](images/missed_toi.svg){html: width=30%} It is difficult to put a restriction on the rotation magnitude. There may be cases where collisions are missed for small rotations. Normally, these missed rotational collisions should not harm game play. They tend to be glancing collisions. The function requires two shapes (converted to `b2DistanceProxy`) and two `b2Sweep` structures. The sweep structure defines the initial and final transforms of the shapes. You can use fixed rotations to perform a *shape cast*. In this case, the time of impact function will not miss any collisions. ### Contact Manifolds Box2D has functions to compute contact points for overlapping shapes. If we consider circle-circle or circle-polygon, we can only get one contact point and normal. In the case of polygon-polygon we can get two points. These points share the same normal vector so Box2D groups them into a manifold structure. The contact solver takes advantage of this to improve stacking stability. ![Contact Manifold](images/manifolds.svg) Normally you don't need to compute contact manifolds directly, however you will likely use the results produced in the simulation. The `b2Manifold` structure holds a normal vector and up to two contact points. The contact points store the normal and tangential (friction) impulses computed in the rigid body simulation. ## Dynamic Tree `b2DynamicTree` is used by Box2D to organize large numbers of shapes efficiently. The object does not know directly about shapes. Instead it operates on axis-aligned bounding boxes (`b2AABB`) with user data integers. The dynamic tree is a hierarchical AABB tree. Each internal node in the tree has two children. A leaf node is a single user AABB. The tree uses rotations to keep the tree balanced, even in the case of degenerate input. The tree structure allows for efficient ray casts and region queries. For example, you may have hundreds of shapes in your scene. You could perform a ray cast against the scene in a brute force manner by ray casting each shape. This would be inefficient because it does not take advantage of shapes being spread out. Instead, you can maintain a dynamic tree and perform ray casts against the tree. This traverses the ray through the tree skipping large numbers of shapes. A region query uses the tree to find all leaf AABBs that overlap a query AABB. This is faster than a brute force approach because many shapes can be skipped. ![Ray-cast](images/raycast.svg){html: width=30%} ![Overlap Test](images/overlap_test.svg){html: width=30%} Normally you will not use the dynamic tree directly. Rather you will go through the `b2World` functions for ray casts and region queries. If you plan to instantiate your own dynamic tree, you can learn how to use it by looking at how Box2D uses it. Also see the `DynamicTree` sample. ================================================ FILE: docs/extra.css ================================================ /* Doxygen CSS overrides Adapted from: https://github.com/MaJerle/doxygen-dark-theme blog-light: #fafafa blog-dark: #252627 Dark background: #353629; New light dark background #32363d Light background: #dfe5f2; */ body { background: #292a2d; background-image: none; color: #D8D8D8; } #titlearea { border-bottom: 1px solid #32363d; background-color: #292a2d; } div.contents { max-width: 1000px; } /* this works with doxygen /image */ .image { background-color: #CCCCCC; border: 10px solid #CCCCCC; } /* this kind of works with doxygen markdown */ img.inline { background-color: #CCCCCC; border: 10px solid #CCCCCC; margin: 0px; } .caption { padding-top: 10px; color: black; } div.fragment, pre.fragment { margin: 20px 0px; padding: 10px; } blockquote.doxtable { border: 1px solid #000000; background: #32363d; background-color: #bf5f82; background-color: #456114; margin: 10px 24px 10px 4px; } div.toc { margin: 0 !important; border-radius: 4px !important; } div.toc h3 { font-size: 150%; color: inherit; } .contents table.doxtable { margin: 0 auto; } .fieldtable { box-shadow: none !important; -webkit-box-shadow: none; -moz-box-shadow: none; } .memitem, .memproto, .memdoc { box-shadow: none; -webkit-box-shadow: none; -moz-box-shadow: none; background-image: none; } .tablist a:hover, .tablist li.current a { text-shadow: none; -moz-text-shadow: none; -webkit-text-shadow: none; } .textblock h1 { border-bottom: 1px solid #32363d; border-left: 3px solid #32363d; margin: 40px 0px 10px 0px; padding-bottom: 10px; padding-top: 10px; padding-left: 5px; } .textblock h1:first-child { margin-top: 10px; } dl.note, dl.warning, dl.todo, dl.deprecated, dl.reflist { border: 0; padding: 0px; margin: 4px 0px 4px 0px; border-radius: 4px; } dl.note dt, dl.warning dt, dl.todo dt, dl.deprecated dt, dl.reflist dt { margin: 0; font-size: 14px; padding: 2px 4px; border: none; border-top-left-radius: 0px; border-top-right-radius:0px; font-weight: bold; text-transform: uppercase; color: #FFFFFF !important; box-shadow: none; -webkit-box-shadow: none; -moz-box-shadow: none; text-shadow: none; } dl.note dd, dl.warning dd, dl.todo dd, dl.deprecated dd, dl.reflist dd { margin: 0; padding: 4px; background: none; color: #222222; border: 1px solid; border-bottom-left-radius: 0px; border-bottom-right-radius: 0px; border-top: none; box-shadow: none; -webkit-box-shadow: none; -moz-box-shadow: none; text-shadow: none; } dl.reflist dd { margin-bottom: 15px; } dl.note dt { background-color: #cbc693; } dl.warning dt { background-color: #bf5f82; } dl.todo dt { background-color: #82b3c9; } dl.deprecated dt { background-color: #af8eb5; } dl.reflist dt { background-color: #cbae82; } dl.note dd { background-color: #fff9c4; border-color: #cbc693; } dl.warning dd { background-color: #f48fb1; border-color: #bf5f82; } dl.todo dd { background-color: #b3e5fc; border-color: #82b3c9; } dl.deprecated dd { background-color: #e1bee7; border-color: #af8eb5; } dl.reflist dd { background-color: #ffe0b2; border-color: #cbae82; } #docs_list { padding: 0 10px; } #docs_list ul { margin: 0; padding: 0; list-style: none; } #docs_list ul li { display: inline-block; border-right: 1px solid #BFBFBF; } #docs_list ul li:last-child { border-right: none; } #docs_list ul li a { display: block; padding: 8px 13px; font-weight: bold; font-size: 15px; } #docs_list ul li a:hover, #docs_list ul li a.docs_current { text-decoration: underline; } .ui-resizable-e { width: 3px; } .download_url { font-weight: bold; font-size: 150%; line-height: 150%; } span.lineno a { text-decoration: none; } .directory .arrow { height: initial; } .directory td.entry { padding: 3px 6px; } .memproto table td { font-family: monospace, fixed !important; } td.memItemLeft, td.memItemRight { font-family: monospace, fixed; } .paramname, .paramname em { font-style: italic; } .memdoc { text-shadow: none; } .memItem { font-family: monospace, fixed; } .memItem table { font-family: inherit; } img.footer { height: 22px; } .sm-dox { background: #dfe5f2 !important; } .sm-dox a { background: none; } div.fragment, pre.fragment { border: 1px solid #000000; background: #32363d; } a, a:link, a:visited { color: #67d8ef !important; } .highlighted { background: none !important; } a.highlighted { background: none !important; } #main-nav { border-bottom: 1px solid #32363d; } #main-nav .sm-dox { background: transparent !important; } .sm-dox a { text-shadow: none !important; background: transparent !important; } .sm-dox a:hover { background: #282923 !important; } .sm-dox { text-shadow: none !important; box-shadow: none !important; } .sm-dox ul { border: 1px solid #000000; background: #32363d; } .directory tr.even { background: #36383d; } .directory tr.odd { background: #292a2d; } #MSearchSelectWindow { border: 1px solid #000000; background: #32363d; } a.selectItem { padding: 3px; } a.SelectItem:hover { background: #282923 !important; } #MSearchResultsWindow { border: 1px solid #000000; background: #32363d; color: #67d8ef !important;; } #nav-tree { background: transparent; } #nav-tree .selected { background-image: none; background: #32363d; } div.toc { background: #32363d; border: 1px solid #000000; } div.toc h3 { font-size: 150%; color: inherit; } table.doxtable tr:nth-child(even) td { background: #32363d; } div.header { background: transparent; border-bottom: 1px solid #32363d; } .fieldtable th { background: #282923; color: inherit; } .memdoc { border: 1px solid #A8B8D9; } .tabs, .tabs2, .tabs3 { background: #DDDDDD; } .tablist li { background: transparent !important; } .tablist a { background-image: none; border-right: 1px solid #999999; color: #32363d; } .tablist a:hover, .tablist li.current a { text-decoration: none; color: #000000; background: #CCCCCC; background-image: none; } #docs_list { background: #32363d; } #docs_list ul li { border-right: 1px solid #BFBFBF; } #docs_list ul li a { color: #1b1e21; } #docs_list ul li a:hover, #docs_list ul li a.docs_current { background: #282923; } .ui-resizable-e { background: #32363d; } div.line { background: transparent; color: inherit; } div.line a { text-decoration: underline; color: inherit; } span.keyword { color: #f92472; font-style: italic; } span.keywordtype { color: #67cfc1; font-style: italic; } span.keywordflow { color: #f92472; font-style: italic; } span.comment { color: #74705a; } span.preprocessor { color: #a6e22b; } span.stringliteral { color: #e7db74; } span.charliteral { color: #e7db74; } span.vhdldigit { color: #ff00ff; } span.vhdlchar { color: #000000; } span.vhdlkeyword { color: #700070; } span.vhdllogic { color: #ff0000; } span.lineno { background: transparent; } span.lineno a { background: transparent; } .mdescLeft, .mdescRight, .memItemLeft, .memItemRight, .memTemplItemLeft, .memTemplItemRight, .memTemplParams { background: #32363d; color: inherit; } .memSeparator { border: none; background: transparent; } h2.groupheader { color: #67d8ef; } .memtitle { background: #32363d !important; border-color: #000000; } .memitem { background: #32363d !important; color: inherit; text-shadow: none; } .memproto { background: inherit; border-color: #000000; color: inherit; text-shadow: none; } .memproto table td { font-family: monospace, fixed !important; } td.memItemLeft, td.memItemRight { font-family: monospace, fixed; } .paramname, .paramname em { color: #bf5f82; } .memdoc { background: inherit; border-color: #000000; } #nav-path { background: transparent; } #nav-path ul { background: transparent; color: inherit; border: none; border-top: 1px solid #32363d; } .navpath li.footer { color: inherit; } .navpath li.navelem a { text-shadow: none; } ::-webkit-scrollbar { width: 10px; } ::-webkit-scrollbar-track { border-radius: 10px; } ::-webkit-scrollbar-thumb { background: #234567; border: none; } ::-webkit-scrollbar-thumb:hover { background: #32363d; } h1.glow, h2.glow, h3.glow, h4.glow, h5.glow, h6.glow { text-shadow: 0 0 15px #67d8ef; } ================================================ FILE: docs/foundation.md ================================================ # Foundations Box2D provides minimal base functionality for allocation hooks and vector math. The C interface allows most runtime data and types to be defined internally in the `src` folder. ## Assertions Box2D will assert on bad input. This includes things like sending in NaN or infinity for values. It will assert if you use negative values for things that should only be positive, such as density. Box2D will also assert if an internal bug is detected. For this reason, it is advisable to build Box2D from source. The Box2D library compiles in about a second on my computer. You may wish to capture assertions in your application. In this case you can use `b2SetAssertFcn()`. This allows you to override the debugger break and/or perform your own error handling. ## Allocation Box2D uses memory efficiently and minimizes per frame allocations by pooling memory. The engine quickly adapts to the simulation size. After the first step or two of simulation, there should be no further per frame allocations. As bodies, shapes, and joints are created and destroyed, their memory will be recycled. Internally all this data is stored in contiguous arrays. When an object is destroyed, the array element will be marked as empty. And when an object is created it will use empty slots in the array using an efficient free list. Once the internal memory pools are initially filled, the only allocations should be for sleeping islands since their data is copied out of the main simulation. Generally, these allocations should be infrequent. You can provide a custom allocator using `b2SetAllocator()` and you can get the number of bytes allocated using `b2GetByteCount()`. ## Version The b2Version structure holds the current version so you can query this at run-time using `b2GetVersion()`. ```c b2Version version = b2GetVersion(); printf("Box2D version %d.%d.%d\n", version.major, version.minor, version.revision); ``` ## Vector Math Box2D includes a small vector math library including types `b2Vec2`, `b2Rot`, `b2Transform`, and `b2AABB`. This has been designed to suit the internal needs of Box2D and the interface. All the members are exposed, so you may use them freely in your application. The math library is kept simple to make Box2D easy to port and maintain. ## Multithreading {#multi} Box2D has been highly optimized for multithreading. Multithreading is not required and by default Box2D will run single-threaded. If performance is important for your application, you should consider using the multithreading interface. Box2D multithreading has been designed to work with your application's task system. Box2D does not create threads. The Samples application shows how to do this using the open source tasks system [enkiTS](https://github.com/dougbinks/enkiTS). Multithreading is established for each Box2D world you create and must be hooked up to the world definition. See `b2TaskCallback()`, `b2EnqueueTaskCallback()`, and `b2FinishTaskCallback()` for more details. Also see `b2WorldDef::workerCount`, `b2WorldDef::enqueueTask`, and `b2WorldDef::finishTask`. The multithreading design for Box2D is focused on [data parallelism](https://en.wikipedia.org/wiki/Data_parallelism). The idea is to use multiple cores to complete the world simulation as fast as possible. Box2D multithreading is not designed for [task parallelism](https://en.wikipedia.org/wiki/Task_parallelism). Often in games you may have a render thread and an audio thread that do work in isolation from the main thread. Those are examples of task parallelism. So when you design your game loop, you should let Box2D *go wide* and use multiple cores to finish its work quickly, without other threads trying to interact with the Box2D world. In a multithreaded environment you must be careful to avoid [race conditions](https://en.wikipedia.org/wiki/Race_condition). Modifying the world while it is simulating will lead to unpredictable behavior and this is never safe. It is also not safe to read data from a Box2D world while it is simulating. Box2D may move data structures to improve cache performance. So it is very likely that you will read garbage data. > **Caution**: > Do not perform read or write operations on a Box2D world during `b2World_Step()` > **Caution**: > Do not write to the Box2D world from multiple threads It *is safe* to do ray-casts, shape-casts, and overlap tests from multiple threads outside of `b2World_Step()`. Generally, any read-only operation is safe to do multithreaded outside of `b2World_Step()`. This can be very useful if you have multithreaded game logic. ## Multithreading Multiple Worlds Some applications may wish to create multiple Box2D worlds and simulate them on different threads. This works fine because Box2D has very limited use of globals. There are a few caveats: - You will get a race condition if you create or destroy Box2D worlds from multiple threads. You should use a mutex to guard this. - If you will simulate multiple Box2D worlds simultaneously, then they should probably not use a task system. Otherwise you're likely to get preemption. - Any callbacks you hook up to Box2D must be thread-safe, such as memory allocators. - All of the limitations for single world simulation still apply. ================================================ FILE: docs/hello.md ================================================ # Hello Box2D {#hello} In the distribution of Box2D is a Hello World unit test written in C. The test creates a large ground box and a small dynamic box. This code does not contain any graphics. All you will see is text output in the console of the box's position over time. This is a good example of how to get up and running with Box2D. ## Creating a World Every Box2D program begins with the creation of a world object. The world is the physics hub that manages memory, objects, and simulation. The world is represented by an opaque handle called `b2WorldId`. It is easy to create a Box2D world. First, I create the world definition: ```c b2WorldDef worldDef = b2DefaultWorldDef(); ``` The world definition is a temporary object that you can create on the stack. The function `b2DefaultWorldDef()` populates the world definition with default values. This is necessary because C does not have constructors and zero initialization is not appropriate for `b2WorldDef`. Now I configure the world gravity vector. Note that Box2D has no concept of *up* and you may point gravity in any direction you like. Box2D example code uses the positive y-axis as the up direction. ```c worldDef.gravity = (b2Vec2){0.0f, -10.0f}; ``` Now I create the world object. ```c b2WorldId worldId = b2CreateWorld(&worldDef); ``` The world creation copies all the data it needs out of the world definition, so the world definition is no longer needed. So now we have our physics world, let's start adding some stuff to it. ## Creating a Ground Box Bodies are built using the following steps: 1. Define a body with position, damping, etc. 2. Use the world id to create the body. 3. Define shapes with friction, density, etc. 4. Create shapes on the body. For step 1 I create the ground body. For this I need a body definition. With the body definition I specify the initial position of the ground body. ```c b2BodyDef groundBodyDef = b2DefaultBodyDef(); groundBodyDef.position = (b2Vec2){0.0f, -10.0f}; ``` For step 2 the body definition and the world id are used to create the ground body. Again, the definition is fully copied and may leave scope after the body is created. Bodies are static by default. Static bodies don't collide with other static bodies and are immovable by the simulation. ```c b2BodyId groundId = b2CreateBody(worldId, &groundBodyDef); ``` Notice that `worldId` is passed by value. Ids are small structures that should be passed by value. For step 3 I create a ground polygon. I use the `b2MakeBox()` helper function to form the ground polygon into a box shape, with the box centered on the origin of the parent body. ```c b2Polygon groundBox = b2MakeBox(50.0f, 10.0f); ``` The `b2MakeBox()` function takes the **half-width** and **half-height** (extents). So in this case the ground box is 100 units wide (x-axis) and 20 units tall (y-axis). Box2D is tuned for meters, kilograms, and seconds. So you can consider the extents to be in meters. Box2D generally works best when objects are the size of typical real world objects. For example, a barrel is about 1 meter tall. Due to the limitations of floating point arithmetic, using Box2D to model the movement of glaciers or dust particles might not work well. I'll finish the ground body in step 4 by creating the shape. For this step I need to create a shape definition which works fine with the default value. ```c b2ShapeDef groundShapeDef = b2DefaultShapeDef(); b2CreatePolygonShape(groundId, &groundShapeDef, &groundBox); ``` Box2D does not keep a reference to the shape data. It copies the data into the internal data structures. Note that every shape must have a parent body, even shapes that are static. You may attach multiple shapes to a single parent body. When you attach a shape, the shape's coordinates become local to the body. So when the body moves, so does the shape. A shape's world transform is inherited from the parent body. A shape does not have a transform independent of the body. So we don't move a shape around on the body. Moving or modifying a shape that is on a body is possible with certain functions, but it should not be part of normal simulation. The reason is simple: a body with morphing shapes is not a rigid body, but Box2D is a rigid body engine. Many of the algorithms in Box2D are based on the rigid body model and optimized with that in mind. If this is violated you may get unexpected behavior. ## Creating a Dynamic Body I can use the same technique to create a dynamic body. The main difference, besides dimensions, is that I must establish the dynamic body's mass properties. First I create the body using CreateBody. By default bodies are static, so I should set the `b2BodyType` at creation time to make the body dynamic. I should also use the body definition to put the body at the intended position for simulation. Creating a body then moving it afterwards is very inefficient and may cause lag spikes, especially if many bodies are created at the origin. ```c b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = (b2Vec2){0.0f, 4.0f}; b2BodyId bodyId = b2CreateBody(worldId, &bodyDef); ``` > **Caution**: > You must set the body type to `b2_dynamicBody` if you want the body to > move in response to forces (such as gravity). Next I create and attach a polygon shape using a shape definition. First I create another box shape: ```c b2Polygon dynamicBox = b2MakeBox(1.0f, 1.0f); ``` Next I create a shape definition for the box. Notice that I set density to 1. The default density is 1, so this is unnecessary. Also, the friction on the surface material is set to 0.3. ```c b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.material.friction = 0.3f; ``` > **Caution**: > A dynamic body should have at least one shape with a non-zero density. > Otherwise you will get strange behavior. Using the shape definition I can now create the shape. This automatically updates the mass of the body. You can add as many shapes as you like to a body. Each one contributes to the total mass. ```c b2CreatePolygonShape(bodyId, &shapeDef, &dynamicBox); ``` That's it for initialization. We are now ready to begin simulating. ## Simulating the World I have initialized the ground box and a dynamic box. Now we are ready to set Newton loose to do his thing. I just have a couple more issues to consider. Box2D uses a computational algorithm called an integrator. Integrators simulate the physics equations at discrete points of time. This goes along with the traditional game loop where we essentially have a flip book of movement on the screen. So we need to pick a time step for Box2D. Generally physics engines for games like a time step at least as fast as 60Hz or 1/60 seconds. You can get away with larger time steps, but you will have to be more careful about setting up your simulation. It is also not good for the time step to vary from frame to frame. A variable time step produces variable results, which makes it difficult to debug. So don't tie the time step to your frame rate. Without further ado, here is the time step. ```c float timeStep = 1.0f / 60.0f; ``` In addition to the integrator, Box2D also uses a larger bit of code called a constraint solver. The constraint solver solves all the constraints in the simulation, one at a time. A single constraint can be solved perfectly. However, when Box2D solves one constraint, it slightly disrupts other constraints. To get a good solution, Box2D needs to iterate over all constraints a number of times. Box2D uses sub-stepping as a means of constraint iteration. It lets the simulation move forward in time by small amounts and each constraint gets a chance to react to the changes. The suggested sub-step count for Box2D is 4. You can tune this number to your liking, just keep in mind that this has a trade-off between performance and accuracy. Using fewer sub-steps increases performance but accuracy suffers. Likewise, using more sub-steps decreases performance but improves the quality of your simulation. For this example, I will use 4 sub-steps. ```c int subStepCount = 4; ``` Note that the time step and the sub-step count are related. As the time step decreases, the size of the sub-steps also decreases. For example, at 60Hz time step and 4 sub-steps, the sub-steps operate at 240Hz. With 8 sub-steps the sub-step is 480Hz. We are now ready to begin the simulation loop. In your game the simulation loop can be merged with your game loop. In each pass through your game loop you call `b2World_Step()`. Just one call is usually enough, depending on your frame rate and your physics time step. I recommend this article [Fix Your Timestep!](https://gafferongames.com/post/fix_your_timestep/) to run your game simulation at a fixed rate. The Hello World test was designed to be simple, so it has no graphical output. The code prints out the position and rotation of the dynamic body. Here is the simulation loop that simulates 90 time steps for a total of 1.5 seconds of simulated time. ```c for (int i = 0; i < 90; ++i) { b2World_Step(worldId, timeStep, subStepCount); b2Vec2 position = b2Body_GetPosition(bodyId); b2Rot rotation = b2Body_GetRotation(bodyId); printf("%4.2f %4.2f %4.2f\n", position.x, position.y, b2Rot_GetAngle(rotation)); } ``` Notice that the rotation of the body is returned in a `b2Rot` struct (short for rotation). This struct holds the rotation in a format that is fast for simulation. You may use `b2Rot_GetAngle` to get the rotation in radians. The output shows the box falling and landing on the ground box. Your output should look like this: ``` 0.00 4.00 0.00 0.00 3.99 0.00 0.00 3.98 0.00 ... 0.00 1.25 0.00 0.00 1.13 0.00 0.00 1.01 0.00 ``` ## Cleanup When you are done with the simulation, you should destroy the world. ```c b2DestroyWorld(worldId); ``` This efficiently destroys all bodies, shapes, and joints in the simulation. ================================================ FILE: docs/layout.xml ================================================ ================================================ FILE: docs/loose_ends.md ================================================ # Loose Ends ## User Data Bodies, shapes, and joints allow you to attach user data as a `void*`. This is handy when you are examining Box2D data structures and you want to determine how they relate to the objects in your game engine. For example, it is typical to attach an entity pointer to the rigid body on that entity. This sets up a circular reference. If you have the entity, you can get the body. If you have the body, you can get the entity. ```c GameEntity* entity = GameCreateEntity(); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.userData = entity; entity->bodyId = b2CreateBody(myWorldId, &bodyDef); ``` Here are some examples of cases where you would need the user data: - Applying damage to an entity using a collision result. - Playing a scripted event if the player is inside an axis-aligned box. - Accessing a game structure when Box2D notifies you that a joint is going to be destroyed. Keep in mind that user data is optional and you can put anything in it. However, you should be consistent. For example, if you want to store an entity pointer on one body, you should keep an entity pointer on all bodies. Don't store a `GameEntity` pointer on one body, and a `ParticleSystem` pointer on another body. Casting a `GameEntity` to a `ParticleSystem` pointer may lead to a crash. ## Pixels and Coordinate Systems I recommend using MKS (meters, kilograms, and seconds) units and radians for angles. You may have trouble working with meters because your game is expressed in terms of pixels. To deal with this in the sample I have the whole *game* world in meters and just use an OpenGL viewport transformation to scale the world into screen space. You use code like this to scale your graphics. ```c float lowerX = -25.0f, upperX = 25.0f, lowerY = -5.0f, upperY = 25.0f; gluOrtho2D(lowerX, upperX, lowerY, upperY); ``` If your game must work in pixel units then you could convert your length units from pixels to meters when passing values from Box2D. Likewise you should convert the values received from Box2D from meters to pixels. This will improve the stability of the physics simulation. You have to come up with a reasonable conversion factor. I suggest making this choice based on the size of your characters. Suppose you have determined to use 50 pixels per meter (because your character is 75 pixels tall). Then you can convert from pixels to meters using these formulas: ```cpp xMeters = 0.02f * xPixels; yMeters = 0.02f * yPixels; ``` In reverse: ```cpp xPixels = 50.0f * xMeters; yPixels = 50.0f * yMeters; ``` You should consider using MKS units in your game code and just convert to pixels when you render. This will simplify your game logic and reduce the chance for errors since the rendering conversion can be isolated to a small amount of code. If you use a conversion factor, you should try tweaking it globally to make sure nothing breaks. You can also try adjusting it to improve stability. If this conversion is not possible, you can set the length units used by Box2D using `b2SetLengthUnitsPerMeter()`. This is experimental and not well tested. ## Debug Drawing You can implement the function pointers in `b2DebugDraw` struct to get detailed drawing of the Box2D world. Debug draw provides: - shapes - joints - broad-phase axis-aligned bounding boxes (AABBs) - center of mass - contact points This is the preferred method of drawing the Box2D simulation, rather than accessing the data directly. The reason is that much of the necessary data is internal and subject to change. The samples application draws the Box2D world using the `b2DebugDraw`. ## Limitations Box2D uses several approximations to simulate rigid body physics efficiently. This brings some limitations. Here are the current limitations: 1. Extreme mass ratios may cause joint stretching and collision overlap. 2. Box2D uses soft constraints to improve robustness. This can lead to joint and contact flexing. 3. Continuous collision does not handle all situations. For example, general dynamic versus dynamic continuous collision is not handled. [Bullets](#bullets) handle this in a limited way. This is done for performance reasons. 4. Continuous collision does not handle joints. So you may see joint stretching on fast moving objects. Usually the joints recover after a few time steps. 5. Box2D uses the [semi-implicit Euler method](https://en.wikipedia.org/wiki/Semi-implicit_Euler_method) to solve the [equations of motion](https://en.wikipedia.org/wiki/Equations_of_motion). It does not reproduce exactly the parabolic motion of projectiles and has only first-order accuracy. However it is fast and has good stability. 6. Box2D uses the [Gauss-Seidel method](https://en.wikipedia.org/wiki/Gauss%E2%80%93Seidel_method) to solve constraints and achieve real-time performance. You will not get precisely rigid collisions or pixel perfect accuracy. Increasing the sub-step count will improve accuracy. ================================================ FILE: docs/migration.md ================================================ # Migration Guide > **Caution**: > This guide only covers the transition from 2.4 to 3.0. Please see the release notes for future version changes. ## Version 2.4 to Version 3.0 Box2D version 3.0 is a full rewrite. You can read some background information [here](https://box2d.org/posts/2023/01/starting-box2d-3.0/). Here are the highlights that affect the API: - moved from C++ to C - identifiers (handles) instead of pointers - multithreading support - fewer callbacks - more features (such as capsules and shape casts) - new sub-stepping solver (*Soft Step*) - gear and pulley joint removed (temporarily) However, the scope of what Box2D does has not changed much. It is still a 2D rigid body engine. It is just faster and more robust (hopefully). And hopefully it is easier to work with and port/wrap for other languages/platforms. I'm going to describe migration by comparing code snippets between 2.4 and 3.0. These should give you and idea of the sort of transformations you need to make to your code to migrate to v3.0. These snippets are written in C and may need some small adjustments to work with C++. I'm not going to cover all the details of v3.0 in this guide. That is the job of the manual, the doxygen reference, and the samples. The surface area of the Box2D is smaller in v3.0 because C++ is not good at hiding details. So hopefully you find the new API easier to work with. ### Should I upgrade to Version 3? Since the behavior changed from version 2 to version 3, I recommend to only use version 3 for new projects. Version 2 no longer receives updates, but it is already battle tested. Version 3 is good for projects that need high performance. ### Creating a world Version 2.4: ```cpp #include "box2d/box2d.h" b2Vec2 gravity(0.0f, -10.0f); b2World world(gravity); ``` Version 3.0: ```c #include "box2d/box2d.h" b2Vec2 gravity = {0.0f, -10.0f}; b2WorldDef worldDef = b2DefaultWorldDef(); worldDef.gravity = gravity; b2WorldId worldId = b2CreateWorld(&worldDef); ``` There is now a required world definition. C does not have constructors, so you need to initialize **ALL** structures that you pass to Box2D. Box2D provides an initialization helper for almost all structures. For example `b2DefaultWorldDef()` is used here to initialize `b2WorldDef`. `b2WorldDef` provides many options, but the defaults are good enough to get going. In Version 3.0, Box2D objects are generally hidden and you only have an identifier. This keeps the API small. So when you create a world you just get a `b2WorldId` which you should treat as an atomic object, like `int` or `float`. It is small and should be passed by value. In Version 3.0 there are also no destructors, so you must destroy the world. ```c b2DestroyWorld(worldId); worldId = b2_nullWorldId; ``` This destroys all bodies, shapes, and joints as well. This is quicker than destroying them individually. Just like pointers, it is good practice to nullify identifiers. Box2D provides null values for all identifiers and also macros such as `B2_IS_NULL` to test if an identifier is null. ### Creating a body Version 2.4: ```cpp b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(0.0f, 4.0f); b2Body* body = world.CreateBody(&bodyDef); ``` Version 3.0: ```c b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = (b2Vec2){0.0f, 4.0f}; b2BodyId bodyId = b2CreateBody(worldId, &bodyDef); ``` Body creation is very similar in v3.0. In this case there is a definition initialization function `b2DefaultBodyDef()`. This can help save a bit of typing in some cases. In v3.0 I recommend getting comfortable with curly brace initialization for initializing vectors. There are no member functions in C. Notice that the body is created using a loose function and providing the `b2WorldId` as an argument. Basically what you would expect going from C++ to C. Destroying a body is also similar. Version 2.4: ```cpp world.DestroyBody(body); body = nullptr; ``` Version 3.0: ```c b2DestroyBody(bodyId); bodyId = b2_nullBodyId; ``` Notice there is a little magic here in Version 3.0. `b2BodyId` knows what world it comes from. So you do not need to provide `worldId` when destroying the body. Version 3.0 supports up to 128 worlds. This may be increased or be overridden in the future. Shapes and joints are still destroyed automatically. However, `b2DestructionListener` is gone. This holds to the theme of fewer callbacks. However, you can now use `b2Shape_IsValid()` and `b2Joint_IsValid()`. ### Creating a shape Shape creation has been streamlined in Version 3.0. `b2Fixture` is gone. I feel like it was a confusing concept so I hope you don't miss it. Version 2.4: ```cpp b2PolygonShape box; box.SetAsBox(1.0f, 1.0f); b2FixtureDef fixtureDef; fixtureDef.shape = &box; fixtureDef.density = 1.0f; fixtureDef.friction = 0.3f; b2Fixture* fixture = body->CreateFixture(&fixtureDef); ``` Version 3.0: ```c b2Polygon box = b2MakeBox(1.0f, 1.0f); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.friction = 0.3f; b2ShapeId shapeId = b2CreatePolygonShape(bodyId, &shapeDef, &box); ``` So basically v2.4 shapes are no longer shapes, they are *primitives* or *geometry* with no inheritance (of course). This freed the term _shape_ to be used where _fixture_ was used before. In v3.0 the shape definition is generic and there are different functions for creating each shape type, such as `b2CreateCircleShape` or `b2CreateSegmentShape`. Again notice the structure initialization with `b2DefaultShapeDef()`. Unfortunately we cannot have meaningful definitions with zero initialization. You must initialize your structures. Another important change for shapes is that the default density in the shape definition is now 1 instead of 0. Static and kinematic bodies will ignore the density. You can now make an entire game without touching the density. Destroying shapes is straight forward. Version 2.4: ```cpp body->DestroyFixture(fixture); fixture = nullptr; ``` Version 3.0: ```c b2DestroyShape(shapeId); shapeId = b2_nullShapeId; ``` ### Chains In Version 2.4 chains are a type of shape. In Version 3.0 they are a separate concept. This leads to significant simplifications internally. In Version 2.4 all shapes had to support the notion of child shapes. This is gone. Version 2.4: ```cpp b2Vec2 points[5]; points[0].Set(-8.0f, 6.0f); points[1].Set(-8.0f, 20.0f); points[2].Set(8.0f, 20.0f); points[3].Set(8.0f, 6.0f); points[4].Set(0.0f, -2.0f); b2ChainShape chain; chain.CreateLoop(points, 5); b2FixtureDef fixtureDef; fixtureDef.shape = &chain; b2Fixture* chainFixture = body->CreateFixture(&fixtureDef); ``` Version 3.0: ```c b2Vec2 points[5] = { {-8.0f, 6.0f}, {-8.0f, 20.0f}, {8.0f, 20.0f}, {8.0f, 6.0f}, {0.0f, -2.0f} }; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = 5; chainDef.loop = true; b2ChainId chainId = b2CreateChain(bodyId, &chainDef); ``` Since chains are their own concept now, they get their own identifier, `b2ChainId`. You can view chains as macro objects, they create many `b2ChainSegment` shapes internally. Normally you don't interact with these. However they are returned from queries. You can use `b2Shape_GetParentChain()` to get the `b2ChainId` for a chain segment that you get from a query. > DO NOT destroy or modify a `b2ChainSegment` that belongs to a chain shape directly ### Creating a joint Joints are very similar in v3.0. The lack of C member functions changes initialization. Version 2.4: ```cpp b2RevoluteJointDef jointDef; jointDef.Initialize(ground, body, b2Vec2(-10.0f, 20.5f)); jointDef.motorSpeed = 1.0f; jointDef.maxMotorTorque = 100.0f; jointDef.enableMotor = true; jointDef.lowerAngle = -0.25f * b2_pi; jointDef.upperAngle = 0.5f * b2_pi; jointDef.enableLimit = true;: b2RevolutionJoint* joint = (b2RevoluteJoint*)world->CreateJoint(&jointDef); ``` Version 3.0: ```c b2Vec2 pivot = {-10.0f, 20.5f}; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = groundId; jointDef.bodyIdB = bodyId; jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); jointDef.motorSpeed = 1.0f; jointDef.maxMotorTorque = 100.0f; jointDef.enableMotor = true; jointDef.lowerAngle = -0.25f * b2_pi; jointDef.upperAngle = 0.5f * b2_pi; jointDef.enableLimit = true; b2JointId jointId = b2CreateRevoluteJoint(worldId, &jointDef); ``` Some of the joints have more options now. Check the code comments and samples for details. The friction joint has been removed since it is a subset of the motor joint. The pulley and gear joints have been removed. I'm not satisfied with how they work in 2.4 and plan to implement improved versions in the future. ### New solver There is a new solver that uses sub-stepping called *Soft Step*. Instead of specifying velocity iterations or position iterations, you now specify the number of sub-steps. ```c void b2World_Step(b2WorldId worldId, float timeStep, int32_t subStepCount); ``` It is recommended to start with 4 sub-steps and adjust as needed. The sub-stepping only computes contact points once per full time step, so contact events are for the full time step. With a sub-stepping solver you need to think differently about how you interact with bodies. Externally applied impulses or velocity adjustments no longer exist after the first sub-step. So if you try to control the movement of a body by setting the velocity every time step then you may get unexpected results. You will get more predictable results by applying a force and/or torque. Forces and torques are spread across all time steps. If you want full control over the movement of a body, considering setting the body type to `b2_kinematicBody`. Preferably this is done in the `b2BodyDef`: ```c b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_kinematicBody; ``` ### Contact data In v2.4 `b2ContactListener` provided `BeginContact`, `EndContact`, `PreSolve`, and `PostSolve`. You could also iterate over the contacts associated with a body using `b2Body::GetContactList`. The latter was rarely used due to how continuous collision worked in v2.4 meant that you could miss some contacts using `GetContactList`. In v3.0 there is a strong emphasis on multithreading. Callbacks in multithreading are problematic for a few reasons: * chance of race conditions in user code * user code becomes non-deterministic * uncertain performance impact Therefore all callbacks except `PreSolve` have been removed. Instead you can now access all events and contact data after the time step. Version 3.0 no longer uses collision sub-stepping for continuous collision. This means all contacts data are valid at the end of the time step. Just keep in mind that Box2D computes contact points at the beginning of the time step, so the contact points apply to the previous position of the body. Here is how you access contact data in v3.0: ```c b2ContactEvents contactEvents = b2World_GetContactEvents(worldId); ``` The contact events structure has begin and end events: ```c typedef struct b2ContactEvents { b2ContactBeginTouchEvent* beginEvents; b2ContactEndTouchEvent* endEvents; b2ContactHitEvent* hitEvents; int beginCount; int endCount; int hitCount; } b2ContactEvents; ``` You can loop through these events after the time step. These events are in deterministic order, even with multithreading. See the `sample_events.cpp` file for examples. You may not want Box2D to save all contact events, so you can disable them for a given shape using `enableContactEvents` on `b2ShapeDef`. If you want to access persistent contacts, you can get the data from bodies or shapes. ```c b2ContactData contactData[10]; int count = b2Body_GetContactData(bodyId, contactData, 10); ``` ```c b2ContactData contactData[10]; int count = b2Shape_GetContactData(shapeId, contactData, 10); ``` This includes contact data for contacts reported in begin events. This data is also in deterministic order. Pre-solve contact modification is available using a callback. ```c typedef bool b2PreSolveFcn(b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Manifold* manifold, void* context); void b2World_SetPreSolveCallback(b2WorldId worldId, b2PreSolveFcn* fcn, void* context); ``` You can define a pre-solve callback and register that with the world. You can also provide a context variable that will be passed back to your callback. This is **not** enough to get a pre-solve callback. You also need to enable it on your shape using `enablePreSolveEvents` in `b2ShapeDef`. This is false by default. > Pre-solve callbacks are dangerous. You must avoid race conditions and you must understand that behavior may not be deterministic. This is especially true if you have multiple pre-solve callbacks that are sensitive to order. ### Sensors In v2.4 sensor events were mixed in with contact events. I have split them up to make user code simpler. ```c b2SensorEvents sensorEvents = b2World_GetSensorEvents(b2WorldId worldId); ``` Note that contact data on bodies and shapes have no information about sensors. That data only has touching contacts. Sensor events are available to all shapes on dynamic bodies except chains. You can disable them using `enableSensorEvents` on `b2ShapeDef`. ### Queries Version 2.4 has `b2World::QueryAABB` and `b2World::RayCast`. This functionality is largely the same in v3.0, but more features have been added such as precise overlap tests and shape casts. Another new feature is `b2QueryFilter` which allows you to filter raycast results before they reach your callback. This query filter is tested against `b2Filter` on shapes that the query encounters. Ray casts now take an origin and translation rather than start and end points. This convention works better with the added shape cast functions. ### World iteration Iterating over all bodies/shapes/joints/contacts in a world is very inefficient and has been removed from Version 3.0. Instead, you should be using `b2BodyEvents` and `b2ContactEvents`. Events are efficient and data-oriented. ### Library configuration Version 3.0 offers more library configuration. You can override the allocator and you can intercept assertions by registering global callbacks. These are for expert users and they must be thread safe. ```c void b2SetAllocator(b2AllocFcn* allocFcn, b2FreeFcn* freeFcn); void b2SetAssertFcn(b2AssertFcn* assertFcn); ``` ================================================ FILE: docs/overview.md ================================================ # Overview Box2D is a 2D rigid body simulation library for games. Programmers can use it in their games to make objects move in realistic ways and make the game world more interactive. From the game engine's point of view, a physics engine is a system for procedural animation. Box2D also provides many collision routines that can be used even when rigid body simulation is not used. There are functions for overlap and cast queries. There is also a bounding volume hierarchy (dynamic tree) that can be used for game specific spatial sorting needs. Box2D is written in portable C17. Most of the types defined in the engine begin with the b2 prefix. Hopefully this is sufficient to avoid name clashing with your application. ## Prerequisites In this manual I'll assume you are familiar with basic physics concepts, such as mass, force, torque, and impulses. If not, please first consult Google search and Wikipedia. Box2D was created as part of a physics tutorial at the Game Developer Conference. You can get these tutorials from the publications section of [box2d.org](https://box2d.org/publications/). Since Box2D is written in C, you are expected to be experienced in C programming. Box2D should not be your first C programming project. You should be comfortable with compiling, linking, and debugging. > **Caution**: > Box2D should not be your first C project. Please learn C > programming, compiling, linking, and debugging before working with > Box2D. There are many resources for this online. ## Scope This manual covers the majority of the Box2D API. However, not every aspect is covered. Please look at the Reference section and samples application included with Box2D to learn more. This manual is only updated with new releases. The latest version of Box2D may be out of sync with this manual. > **Caution**: > This manual applies to the associated release and not necessarily the > latest version on the main branch. ## Feedback and Bugs Please file bugs and feature requests here: [Box2D Issues](https://github.com/erincatto/box2d/issues) You can help to ensure your issue gets fixed if you provide sufficient detail. A testbed example that reproduces the problem is ideal. You can read about the testbed later in this document. There is also a [Discord server](https://discord.gg/NKYgCBP) and a [subreddit](https://reddit.com/r/box2d) for Box2D. You may also use [GitHub Discussions](https://github.com/erincatto/box2d/discussions). ## Core Concepts Box2D works with several fundamental concepts and objects. I briefly define these objects here and more details are given later in this document. ### rigid body A chunk of matter that is so strong that the distance between any two bits of matter on the chunk is constant. They are hard like a diamond. In the following discussion I use *body* interchangeably with rigid body. ### shape A shape binds collision geometry to a body and adds material properties such as density, friction, and restitution. A shape puts collision geometry into the collision system (broad-phase) so that it can collide with other shapes. ### constraint A constraint is a physical connection that removes degrees of freedom from bodies. A 2D body has 3 degrees of freedom (two translation coordinates and one rotation coordinate). If I take a body and pin it to the wall (like a pendulum) I have constrained the body to the wall. At this point the body can only rotate about the pin, so the constraint has removed 2 degrees of freedom. ### contact constraint A special constraint designed to prevent penetration of rigid bodies and to simulate friction and restitution. You do not create contact constraints; they are created automatically by Box2D. ### joint constraint This is a constraint used to hold two or more bodies together. Box2D supports several joint types: revolute, prismatic, distance, and more. Joints may have limits, motors, and/or springs. ### joint limit A joint limit restricts the range of motion of a joint. For example, the human elbow only allows a certain range of angles. ### joint motor A joint motor drives the motion of the connected bodies according to the joint's degrees of freedom. For example, you can use a motor to drive the rotation of an elbow. Motors have a target speed and a maximum force or torque. The simulation will apply the force or torque required to achieve the desired speed. ### joint spring A joint spring has a stiffness and damping. In Box2D spring stiffness is expressed in terms or Hertz or cycles per second. This lets you configure how quickly a spring reacts regardless of the body masses. Joint springs also have a damping ratio to let you specify how quickly the spring will come to rest. ### world A physics world is a collection of bodies, shapes, joints, and contacts that interact together. Box2D supports the creation of multiple worlds which are completely independent. ### solver The physics world has a solver that is used to advance time and to resolve contact and joint constraints. The Box2D solver is a high performance sequential solver that operates in order N time, where N is the number of constraints. ### continuous collision The solver advances bodies in time using discrete time steps. Without intervention this can lead to tunneling. ![Tunneling Effect](images/tunneling1.svg) Box2D contains specialized algorithms to deal with tunneling. First, the collision algorithms can interpolate the motion of two bodies to find the first time of impact (TOI). Second, speculative collision is used to create contact constraints between bodies before they touch. ### events World simulation leads to the creation of events that are available at the end of the time step: - body movement events - contact begin and end events - sensor begin and end events - contact hit events These events allow your application to react to changes in the simulation. ## Modules Box2D's primary purpose is to provide rigid body simulation. However, there are math and collision features that may be useful apart from the rigid body simulation. These are provided in the `include` directory. Anything in the `include` directory is considered public, while everything in the `src` directory is consider internal. Public features are supported and you can get help with these on the Discord server. Using internal code directly is not supported. However, feel free to study the code and ask questions. I'm happy to share all the details of how Box2D works internally. ## Units Box2D works with floating point numbers and tolerances have to be used to make Box2D perform well. These tolerances have been tuned to work well with meters-kilogram-second (MKS) units. In particular, Box2D has been tuned to work well with moving shapes between 0.1 and 10 meters. So this means objects between soup cans and buses in size should work well. Static shapes may be up to 50 meters long without trouble. If you have a large world, you should split it up into multiple static bodies. This will improve precision and simulation behavior. Being a 2D physics engine, it is tempting to use pixels as your units. Unfortunately this will lead to a poor simulation and possibly weird behavior. An object of length 200 pixels would be seen by Box2D as the size of a 45 story building. > **Caution**: > Box2D is tuned for MKS units. Keep the size of moving objects larger than 1cm. > You'll need to use some scaling system when > you render your environment and actors. The Box2D samples application > does this by using an OpenGL viewport transform. Do not use pixel units > unless you understand the implications. It is best to think of Box2D bodies as moving billboards upon which you attach your artwork. The billboard may move in a unit system of meters, but you can convert that to pixel coordinates with a simple scaling factor. You can then use those pixel coordinates to place your sprites, etc. You can also account for flipped coordinate axes. Another limitation to consider is overall world size. If your world units become larger than 12 kilometers or so, then the lost precision can affect stability. > **Caution**: > Box2D works best with world sizes less than 12 kilometers. If you are > careful with your simulation tuning, this can be pushed up to around 24 > kilometers, which is much larger than most game worlds. Box2D uses radians for angles. The body rotation is stored a complex number, so when you access the angle of a body, it will be between \f$-\pi\f$ and \f$\pi\f$ radians. > **Caution**: > Box2D uses radians, not degrees. ## Changing the length units Advanced users may change the length unit by calling `b2SetLengthUnitsPerMeter()` at application startup. If you keep Box2D in a shared library, you will need to call this if the shared library is reloaded. If you change the length units to pixels you will need to decide how many pixels represent a meter. You will also need to figure out reasonable values for gravity, density, force, and torque. One of the benefits of using MKS units for physics simulation is that you can use real world values to get reasonable results. It is also harder to get support for using Box2D if you change the unit system, because values are harder to communicate and may become non-intuitive. ## Ids and Definitions Fast memory management plays a central role in the design of the Box2D interface. When you create a world, body, shape or joint, you will receive a handle called an *id*. These ids are opaque and are passed to various functions to access the underlying data. These ids provide some safety. If you use an id after it has been freed you will usually get an assertion. All ids support 64k generations of safety. All ids also have a corresponding function you can call to check if it is valid. When you create a world, body, shape, or joint, you need to provide a definition structure. These definitions contain all the information needed to build the Box2D object. By using this approach I can prevent construction errors, keep the number of function parameters small, provide sensible defaults, and reduce the number of accessors. Here is an example of body creation: ```c b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = (b2Vec2){10.0f, 5.0f}; b2BodyId myBodyId = b2CreateBody(myWorldId, &bodyDef); ``` Notice the body definition is initialized by calling `b2DefaultBodyDef()`. This is needed because C does not have constructors and zero initialization is generally not suitable for the definitions used in Box2D. Also notice that the body definition is a temporary object that is fully copied into the internal body data structures. Definitions should usually be created on the stack as temporaries. This is how a body is destroyed: ```c b2DestroyBody(myBodyId); myBodyId = b2_nullBodyId; ``` Notice that the body id is set to null using the constant `b2_nullBodyId`. You should treat ids as opaque data, however you may zero initialize all Box2D ids and they will be considered *null*. Shapes are created in a similar way. For example, here is how a box shape is created: ```c b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.42f; b2Polygon box = b2MakeBox(0.5f, 0.25f); b2ShapeId myShapeId = b2CreatePolygonShape(myBodyId, &shapeDef, &box); ``` And the shape may be destroyed as follows: ```c b2DestroyShape(myShapeId); myShapeId = b2_nullShapeId; ``` For convenience, Box2D will destroy all shapes on a body when the body is destroyed. You don't need to store the shape id. There are some macros to assist using ids in logical operations. ```c bool isNull = B2_IS_NULL(myBodyId); bool isNonNull = B2_IS_NON_NULL(myJointId); bool areEqual = B2_ID_EQUALS(myShapeIdA, myShapeIdB); ``` ================================================ FILE: docs/reading.md ================================================ # Further Reading - [Erin Catto's Publications](https://box2d.org/publications/) - [Erin Catto's Blog Posts](https://box2d.org/posts/) - Collision Detection in Interactive 3D Environments, Gino van den Bergen, 2004 - Real-Time Collision Detection, Christer Ericson, 2005 ================================================ FILE: docs/release_notes_v310.md ================================================ # v3.1 Release Notes ## API Changes - 64-bit filter categories and masks - 64-bit dynamic tree user data - Renamed `b2SmoothSegment` to `b2ChainSegment` - Cast and overlap functions modified for argument consistency - Contact begin events now provide the manifold - More consistent functions to make polygons - Contact events are now disabled by default - Replaced `b2Timer` with `uint64_t` - Shape material properties now use `b2SurfaceMaterial` ## New Features - New character mover features and sample - Revised sensor system is now independent of body type and sleep - Rolling resistance and tangent speed - Friction and restitution mixing callbacks - World explosions - World access to the maximum linear speed - More control over body mass updates - Filter joint to disable collision between specific bodies - Bodies can now have names for debugging - Added `b2Body_SetTargetTransform` for kinematic bodies ## Improvements - Cross-platform determinism - Custom SSE2 and Neon for significantly improved performance - SSE2 is the default instead of AVX2 - Removed SIMDE library dependency - Faster ray and shape casts - Faster continuous collision - Each segment of a chain shape may have a different surface material - Reduced overhead of restitution when not used - Implemented atomic platform wrappers eliminating the `experimental:c11atomics` flag ## Bugs Fixes - Many bug fixes based on user testing - Fixed missing hit events - Capsule and polygon manifold fixes - Fixed missing contact end events - PreSolve is now called in continuous collision - Reduced clipping into chain shapes by fast bodies - Friction and restitution are now remixed in the contact solver every time step - Body move events are now correctly adjusted for time of impact ## Infrastructure - Unit test for API coverage - macOS and Windows samples built in GitHub actions - CMake install - imgui and glfw versions are now pinned in FetchContent - Initial Emscripten support ================================================ FILE: docs/samples.md ================================================ # Samples {#samples} Once you have conquered the HelloWorld example, you should start looking at Box2D's samples application. The samples application is a testing framework and demo environment. Here are some of the features: - Camera with pan and zoom - Mouse dragging of dynamic bodies - Many samples in a tree view - GUI for selecting samples, parameter tuning, and debug drawing options - Pause and single step simulation - Multithreading and performance data ![Box2D Samples](images/samples.png) The samples application has many examples of Box2D usage in the test cases and the framework itself. I encourage you to explore and tinker with the samples as you learn Box2D. Note: the sample application is written using [GLFW](https://www.glfw.org), [imgui](https://github.com/ocornut/imgui), and [enkiTS](https://github.com/dougbinks/enkiTS). The samples app is not part of the Box2D library. The Box2D library is agnostic about rendering. As shown by the HelloWorld example, you don't need a renderer to use Box2D. ================================================ FILE: docs/simulation.md ================================================ # Simulation Rigid body simulation is the primary feature of Box2D. It is the most complex part of Box2D and is the part you will likely interact with the most. Simulation sits on top of the foundation and collision layers, so you should be somewhat familiar with those by now. Rigid body simulation contains: - worlds - bodies - shapes - contacts - joints - events There are many dependencies between these objects so it is difficult to describe one without referring to another. In the following, you may see some references to objects that have not been described yet. Therefore, you may want to quickly skim this section before reading it closely. ## Ids Box2D has a C interface. Typically in a C/C++ library when you create an object with a long lifetime you will keep a pointer (or smart pointer) to the object. Box2D works differently. Instead of pointers, you are given an *id* when you create an object. This *id* acts as a [handle](https://en.wikipedia.org/wiki/Handle_(computing)) which helps avoid problems with [dangling pointers](https://en.wikipedia.org/wiki/Dangling_pointer). This also allows Box2D to use [data-oriented design](https://en.wikipedia.org/wiki/Data-oriented_design) internally. This helps to reduce cache misses drastically and also allows for [SIMD](https://en.wikipedia.org/wiki/Single_instruction,_multiple_data) optimizations. So you will be dealing with `b2WorldId`, `b2BodyId`, etc. These are small opaque structures that you will pass around by value, just like pointers. Box2D creation functions return an id. Functions that operate on Box2D objects take ids. ```c b2BodyId myBodyId = b2CreateBody(myWorldId, &myBodyDef); ``` There are functions to check if an id is valid. Box2D functions will assert if you use an invalid id. This makes debugging easier than using dangling pointers. ```c if (b2Body_IsValid(myBodyId) == false) { // oops } ``` Null ids can be established in a couple ways. You can use predefined constants or zero initialization. ```c b2BodyId myNullBodyId = b2_nullBodyId; b2BodyId otherNullBodyId = {0}; ``` You can test if an id is null using some helper macros: ```c if (B2_IS_NULL(myBodyId)) { // do something } ``` ```c if (B2_IS_NON_NULL(myShapeId)) { // do something } ``` ## World The Box2D world contains the bodies and joints. It manages all aspects of the simulation and allows for asynchronous queries (like AABB queries and ray-casts). Much of your interactions with Box2D will be with a world object, using `b2WorldId`. ### World Definition Worlds are created using a *definition* structure. This is temporary structure that you can use to configure options for world creation. You **must** initialize the world definition using `b2DefaultWorldDef()`. ```c b2WorldDef worldDef = b2DefaultWorldDef(); ``` The world definition has lots of options, but for most you will use the defaults. You may want to set the gravity: ```c worldDef.gravity = (b2Vec2){0.0f, -10.0f}; ``` If your game doesn't need sleep, you can get a performance boost by completely disabling sleep: ```c worldDef.enableSleep = false; ``` You can also configure multithreading to improve performance: ```c worldDef.workerCount = 4; worldDef.enqueueTask = myAddTaskFunction; worldDef.finishTask = myFinishTaskFunction; worldDef.userTaskContext = &myTaskSystem; ``` Multithreading is not required but it can improve performance substantially. Read more [here](#multi). ### World Lifetime Creating a world is done using a world definition. ```c b2WorldId myWorldId = b2CreateWorld(&worldDef); // ... do stuff ... b2DestroyWorld(myWorldId); // Nullify id for safety myWorldId = b2_nullWorldId; ``` You can create up to 128 worlds. These worlds do not interact and may be simulated in parallel. When you destroy a world, every body, shape, and joint is also destroyed. This is much faster than destroying individual objects. ### Simulation The world is used to drive the simulation. You specify a time step and a sub-step count. For example: ```c float timeStep = 1.0f / 60.f; int32_t subSteps = 4; b2World_Step(myWorldId, timeStep, subSteps); ``` After the time step you can examine your bodies and joints for information. Most likely you will grab the position off the bodies so that you can update your game objects and render them. Or more optimally, you will use `b2World_GetBodyEvents()`. You can perform the time step anywhere in your game loop, but you should be aware of the order of things. For example, you must create bodies before the time step if you want to get collision results for the new bodies in that frame. As I discussed in the [HelloWorld tutorial](#hello), you should use a fixed time step. By using a larger time step you can improve performance in low frame rate scenarios. But generally you should use a time steps 1/30 seconds (30Hz) or smaller. A time step of 1/60 seconds (60Hz) will usually deliver a high quality simulation. The sub-step count is used to increase accuracy. By sub-stepping the solver divides up time into small increments and the bodies move by a small amount. This allows joints and contacts to respond with finer detail. The recommended sub-step count is 4. However, increasing the sub-step count may improve accuracy. For example, long joint chains will stretch less with more sub-steps. The scissor lift sample shown [here](#samples) works better with more sub-steps and is configured to use 8 sub-steps. With a primary time step of 1/60 seconds, the scissor lift is taking sub-steps at 480Hz! ## Rigid Bodies Rigid bodies, or just *bodies* have position and velocity. You can apply forces, torques, and impulses to bodies. Bodies can be static, kinematic, or dynamic. Here are the body type definitions: ### Body types #b2_staticBody: A static body does not move under simulation and behaves as if it has infinite mass. Internally, Box2D stores zero for the mass and the inverse mass. A static body has zero velocity. Static bodies do not collide with other static or kinematic bodies. #b2_kinematicBody: A kinematic body moves under simulation according to its velocity. Kinematic bodies do not respond to forces. A kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass, however, Box2D stores zero for the mass and the inverse mass. Kinematic bodies do not collide with other kinematic or static bodies. Generally you should use a kinematic body if you want a shape to be animated and not affected by forces or collisions. #b2_dynamicBody: A dynamic body is fully simulated and moves according to forces and torques. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass. > **Caution**: > Generally you should not set the transform on bodies after creation. > Box2D treats this as a teleport and may result in undesirable behavior and/or performance problems. Bodies carry shapes and moves them around in the world. Bodies are always rigid bodies in Box2D. That means that two shapes attached to the same rigid body never move relative to each other and shapes attached to the same body don't collide. Shapes have collision geometry and density. Normally, bodies acquire their mass properties from the shapes. However, you can override the mass properties after a body is constructed. You usually keep ids to all the bodies you create. This way you can query the body positions to update the positions of your graphical entities. You should also keep body ids so you can destroy them when you are done with them. ### Body Definition Before a body is created you must create a body definition (`b2BodyDef`). The body definition holds the data needed to create and initialize a body correctly. Because Box2D uses a C API, a function is provided to create a default body definition. ```c b2BodyDef myBodyDef = b2DefaultBodyDef(); ``` This ensures the body definition is valid and this initialization is **mandatory**. Box2D copies the data out of the body definition; it does not keep a pointer to the body definition. This means you can recycle a body definition to create multiple bodies. Let's go over some of the key members of the body definition. ### Body Type As discussed previously, there are three different body types: static, kinematic, and dynamic. b2_staticBody is the default. You should establish the body type at creation because changing the body type later is expensive. ```c b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; ``` ### Position and Angle You can initialize the body position and angle in the body definition. This has far better performance than creating the body at the world origin and then moving the body. > **Caution**: > Do not create a body at the origin and then move it. If you create > several bodies at the origin, then performance will suffer. A body has two main points of interest. The first point is the body's origin. Shapes and joints are attached relative to the body's origin. The second point of interest is the center of mass. The center of mass is determined from the mass distribution of the attached shapes or is explicitly set using `b2MassData`. Much of Box2D's internal computations use the center of mass position. For example the body stores the linear velocity for the center of mass, not the body origin. ![Body Origin and Center of Mass](images/center_of_mass.svg) When you are building the body definition, you may not know where the center of mass is located. Therefore you specify the position of the body's origin. You may also specify the body's angle in radians. If you later change the mass properties of the body, then the center of mass may move on the body, but the origin position and body angle does not change and the attached shapes and joints do not move. ```c b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = (b2Vec2){0.0f, 2.0f}; bodyDef.angle = 0.25f * b2_pi; ``` A rigid body is a frame of reference. You can define shapes and joints in that frame. Those shapes and joint anchors never move in the local frame of the body. ### Damping Damping is used to reduce the world velocity of bodies. Damping is different than friction because friction only occurs with contact. Damping is not a replacement for friction and the two effects are used together. Damping parameter are non-negative. Normally you will use a damping value between 0 and 1. I generally do not use linear damping because it makes bodies look like they are floating. ```c bodyDef.linearDamping = 0.0f; bodyDef.angularDamping = 0.1f; ``` Damping is approximated to improve performance. At small damping values the damping effect is mostly independent of the time step. At larger damping values, the damping effect will vary with the time step. This is not an issue if you use a fixed time step (recommended). Here's some math for the curious. A first-order differential equation for velocity damping is: \f[ \frac{dv}{dt} + c v = 0 \f] The solution with initial velocity \f$v_0\f$ is \f[ v = v_0 e^{-c t} \f] Across a single time step \f$h\f$ the velocity evolves like so \f[ v(t + h) = v_0 e^{-c (t + h)} = v_0 e^{-c t} e^{-c h} = v(t) e^{-c h} \f] Using the [Pade approximation](https://en.wikipedia.org/wiki/Pad%C3%A9_table) for the exponential function gives the update formula: \f[ v(t + h) \approx \frac{1}{1 + c h} v(t) \f] This is the formula used in the Box2D solver. ### Gravity Scale You can use the gravity scale to adjust the gravity on a single body. Be careful though, a large gravity magnitude can decrease stability. ```c // Set the gravity scale to zero so this body will float bodyDef.gravityScale = 0.0f; ``` ### Sleep Parameters What does sleep mean? Well it is expensive to simulate bodies, so the less we have to simulate the better. When a body comes to rest we would like to stop simulating it. When Box2D determines that a body (or group of bodies) has come to rest, the body enters a sleep state which has very little CPU overhead. If a body is awake and collides with a sleeping body, then the sleeping body wakes up. Bodies will also wake up if a joint or contact attached to them is destroyed. You can also wake a body manually. The body definition lets you specify whether a body can sleep and whether a body is created sleeping. ```c bodyDef.enableSleep = true; bodyDef.isAwake = true; ``` The `isAwake` flag is ignored if `enableSleep` is false. ### Fixed Rotation You may want a rigid body, such as a character, to have a fixed rotation. Such a body does not rotate, even under load. You can use the fixed rotation setting to achieve this: ```c bodyDef.fixedRotation = true; ``` The fixed rotation flag causes the rotational inertia and its inverse to be set to zero. ### Bullets {#bullets} Game simulation usually generates a sequence of transforms that are played at some frame rate. This is called discrete simulation. In discrete simulation, rigid bodies can move by a large amount in one time step. If a physics engine doesn't account for the large motion, you may see some objects incorrectly pass through each other. This effect is called *tunneling*. By default, Box2D uses continuous collision detection (CCD) to prevent dynamic bodies from tunneling through static bodies. This is done by sweeping shapes from their old position to their new positions. The engine looks for new collisions during the sweep and computes the time of impact (TOI) for these collisions. Bodies are moved to their first TOI at the end of the time step. Normally CCD is not used between dynamic bodies. This is done to keep performance reasonable. In some game scenarios you need dynamic bodies to use CCD. For example, you may want to shoot a high speed bullet at a stack of dynamic bricks. Without CCD, the bullet might tunnel through the bricks. Fast moving objects in Box2D can be configured as *bullets*. Bullets will perform CCD with all body types, but **not** other bullets. You should decide what bodies should be bullets based on your game design. If you decide a body should be treated as a bullet, use the following setting. ```c bodyDef.isBullet = true; ``` The bullet flag only affects dynamic bodies. I recommend using bullets sparingly. ### Disabling You may wish a body to be created but not participate in collision or simulation. This state is similar to sleeping except the body will not be woken by other bodies and the body's shapes will not collide with anything. This means the body will not participate in collisions, ray casts, etc. You can create a body as disabled and later enable it. ```c bodyDef.isEnabled = false; // Later ... b2Body_Enable(myBodyId); ``` Joints may be connected to disabled bodies. These joints will not be simulated. You should be careful when you enable a body that its joints are not distorted. Note that enabling a body is almost as expensive as creating the body from scratch. So you should not use body disabling for streaming worlds. Instead, use creation/destruction for streaming worlds to save memory. Body disabling is a convenience and is generally not good for performance. ### User Data User data is a void pointer. This gives you a hook to link your application objects to bodies. You should be consistent to use the same object type for all body user data. ```c bodyDef.userData = &myGameObject; ``` This is useful when you receive results from a query such as a ray-cast or event and you want to get back to your game object. You can acquire the use data from a body using `b2Body_GetUserData()`. ### Body Lifetime Bodies are created and destroyed using a world id. This lets the world create the body with an efficient allocator and add the body to the world data structure. ```c b2BodyId myBodyId = b2CreateBody(myWorldId, &bodyDef); // ... do stuff ... b2DestroyBody(myBodyId); // Nullify body id for safety myBodyId = b2_nullBodyId; ``` Box2D does not keep a reference to the body definition or any of the data it holds (except user data pointers). So you can create temporary body definitions and reuse the same body definitions. Box2D allows you to avoid destroying bodies by destroying the world directly using `b2DestroyWorld()`, which does all the cleanup work for you. However, you should be mindful to nullify body ids that you keep in your application. When you destroy a body, the attached shapes and joints are automatically destroyed. This has important implications for how you manage shape and joint ids. You should nullify these ids after destroying a body. ### Using a Body After creating a body, there are many operations you can perform on the body. These include setting mass properties, accessing position and velocity, applying forces, and transforming points and vectors. ### Mass Data A body has mass (scalar), center of mass (2-vector), and rotational inertia (scalar). For static bodies, the mass and rotational inertia are set to zero. When a body has fixed rotation, its rotational inertia is zero. Normally the mass properties of a body are established automatically when shapes are added to the body. You can also adjust the mass of a body at run-time. This is usually done when you have special game scenarios that require altering the mass. ```c b2MassData myMassData; myMassData.mass = 10.0f; myMassData.center = (b2Vec2){0.0f, 0.0f}; myMassData.rotationalInertia = 100.0f; b2Body_SetMassData(myBodyId, myMassData); ``` After setting a body's mass directly, you may wish to revert to the mass determined by the shapes. You can do this with: ```c b2Body_ApplyMassFromShapes(myBodyId); ``` The body's mass data is available through the following functions: ```c float mass = b2Body_GetMass(myBodyId); float inertia = b2Body_GetRotationalInertia(myBodyId); b2Vec2 localCenter b2Body_GetLocalCenterOfMass(myBodyId); b2MassData massData = b2Body_GetMassData(myBodyId); ``` ### State Information There are many aspects to the body's state. You can access this state data through the following functions: ```c b2Body_SetType(myBodyId, b2_kinematicBody); b2BodyType bodyType = b2Body_GetType(myBodyId); b2Body_SetBullet(myBodyId, true); bool isBullet = b2Body_IsBullet(myBodyId); b2Body_EnableSleep(myBodyId, false); bool isSleepEnabled = b2Body_IsSleepingEnabled(myBodyId); b2Body_SetAwake(myBodyId, true); bool isAwake = b2Body_IsAwake(myBodyId); b2Body_Disable(myBodyId); b2Body_Enable(myBodyId); bool isEnabled = b2Body_IsEnabled(myBodyId); b2Body_SetFixedRotation(myBodyId, true); bool isFixedRotation = b2Body_IsFixedRotation(myBodyId); ``` Please see the comments on these functions for more details. ### Position and Velocity You can access the position and rotation of a body. This is common when rendering your associated game object. You can also set the position and angle, although this is less common since you will normally use Box2D to simulate movement. Keep in mind that the Box2D interface uses *radians*. ```c b2Body_SetTransform(myBodyId, position, rotation); b2Transform transform = b2Body_GetTransform(myBodyId); b2Vec2 position = b2Body_GetPosition(myBodyId); b2Rot rotation = b2Body_GetRotation(myBodyId); float angleInRadians = b2Rot_GetAngle(rotation); ``` You can access the center of mass position in local and world coordinates. Much of the internal simulation in Box2D uses the center of mass. However, you should normally not need to access it. Instead you will usually work with the body transform. For example, you may have a body that is square. The body origin might be a corner of the square, while the center of mass is located at the center of the square. ```c b2Vec2 worldCenter = b2Body_GetWorldCenterOfMass(myBodyId); b2Vec2 localCenter = b2Body_GetLocalCenterOfMass(myBodyId); ``` You can access the linear and angular velocity. The linear velocity is for the center of mass. Therefore, the linear velocity may change if the mass properties change. Since Box2D uses radians, the angular velocity is in radians per second. ```c b2Vec2 linearVelocity = b2Body_GetLinearVelocity(myBodyId); float angularVelocity = b2Body_GetAngularVelocity(myBodyId); ``` You can drive a body to a specific transform. This is useful for kinematic bodies. ```c b2Vec2 targetPosition = {42.0f, -100.0f}; b2Rot targetRotation = b2MakeRot(B2_PI); b2Transform target = {targetPosition, targetRotation}; float timeStep = 1.0f / 60.0f; b2Body_SetTargetTransform(myBodyId, target, timeStep); ``` ### Forces and Impulses You can apply forces, torques, and impulses to a body. When you apply a force or an impulse, you can provide a world point where the load is applied. This often results in a torque about the center of mass. ```c b2Body_ApplyForce(myBodyId, force, worldPoint, wake); b2Body_ApplyTorque(myBodyId, torque, wake); b2Body_ApplyLinearImpulse(myBodyId, linearImpulse, worldPoint, wake); b2Body_ApplyAngularImpulse(myBodyId, angularImpulse, wake); ``` Applying a force, torque, or impulse optionally wakes the body. If you don't wake the body and it is asleep, then the force or impulse will be ignored. You can also apply a force and linear impulse to the center of mass to avoid rotation. ```c b2Body_ApplyForceToCenter(myBodyId, force, wake); b2Body_ApplyLinearImpulseToCenter(myBodyId, linearImpulse, wake); ``` > **Caution**: > Since Box2D uses sub-stepping, you should not apply a steady impulse > for several frames. Instead you should apply a force which Box2D will > spread out evenly across the sub-steps, resulting in smoother movement. ### Coordinate Transformations The body has some utility functions to help you transform points and vectors between local and world space. If you don't understand these concepts, I recommend reading \"Essential Mathematics for Games and Interactive Applications\" by Jim Van Verth and Lars Bishop. ```c b2Vec2 worldPoint = b2Body_GetWorldPoint(myBodyId, localPoint); b2Vec2 worldVector = b2Body_GetWorldVector(myBodyId, localVector); b2Vec2 localPoint = b2Body_GetLocalPoint(myBodyId, worldPoint); b2Vec2 localVector = b2Body_GetLocalVector(myBodyId, worldVector); ``` ### Accessing Shapes and Joints You can access the shapes on a body. You can get the number of shapes first. ```c int shapeCount = b2Body_GetShapeCount(myBodyId); ``` If you have bodies with many shapes, you can allocate an array or if you know the number is limited you can use a fixed size array. ```c b2ShapeId shapeIds[10]; int returnCount = b2Body_GetShapes(myBodyId, shapeIds, 10); for (int i = 0; i < returnCount; ++i) { b2ShapeId shapeId = shapeIds[i]; // do something with shapeId } ``` You can similarly get an array of the joints on a body. ### Body Events While you can gather transforms from all your bodies after every time step, this is inefficient. Many bodies may not have moved because they are sleeping. Also iterating across many bodies will have lots of cache misses. Box2D provides `b2BodyEvents` that you can access after every call to `b2World_Step()` to get an array of body movement events. Since this data is contiguous, it is cache friendly. ```c b2BodyEvents events = b2World_GetBodyEvents(m_worldId); for (int i = 0; i < events.moveCount; ++i) { const b2BodyMoveEvent* event = events.moveEvents + i; MyGameObject* gameObject = event->userData; MoveGameObject(gameObject, event->transform); if (event->fellAsleep) { SleepGameObject(gameObject); } } ``` The body event also indicates if the body fell asleep this time step. This might be useful to optimize your application. ## Shapes A body may have zero or more shapes. A body with multiple shapes is sometimes called a *compound body.* Shapes hold the following: - a shape primitive - density, friction, and restitution - collision filtering flags - parent body id - user data - sensor flag These are described in the following sections. ### Shape Lifetime Shapes are created by initializing a shape definition and a shape primitive. These are passed to a creation function specific to each shape type. ```c b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 10.0f; shapeDef.material.friction = 0.7f; b2Polygon box = b2MakeBox(0.5f, 1.0f); b2ShapeId myShapeId = b2CreatePolygonShape(myBodyId, &shapeDef, &box); ``` This creates a polygon and attaches it to the body. You do not need to store the shape id since the shape will automatically be destroyed when the parent body is destroyed. However, you may wish to store the shape id if you plan to change properties on it later. You can create multiple shapes on a single body. They all can contribute to the mass of the body. These shapes never collide with each other and may overlap. You can destroy a shape on the parent body. You may do this to model a breakable object. Otherwise you can just leave the shape alone and let the body destruction take care of destroying the attached shapes. ```c b2DestroyShape(myShapeId); ``` Material properties such as density, friction, and restitution are associated with shapes instead of bodies. Since you can attach multiple shapes to a body, this allows for more possible setups. For example, you can make a car that is heavier in the back. ### Density The shape density is used to compute the mass properties of the parent body. The density can be zero or positive. You should generally use similar densities for all your shapes. This will improve stacking stability. The mass of a body is not adjusted when you set the density. You must call `b2Body_ApplyMassFromShapes()` for this to occur. Generally you should establish the shape density in `b2ShapeDef` and avoid modifying it later because this can be expensive, especially on a compound body. ```c b2Shape_SetDensity(myShapeId, 5.0f); b2Body_ApplyMassFromShapes(myBodyId); ``` ### Friction Friction is used to make objects slide along each other realistically. Box2D supports static and dynamic friction, but uses the same parameter for both. Box2D attempts to simulate friction accurately and the friction strength is proportional to the normal force. This is called [Coulomb friction](https://en.wikipedia.org/wiki/Friction). The friction parameter is usually set between 0 and 1, but can be any non-negative value. A friction value of 0 turns off friction and a value of 1 makes the friction strong. When the friction force is computed between two shapes, Box2D must combine the friction parameters of the two parent shapes. This is done with the [geometric mean](https://en.wikipedia.org/wiki/Geometric_mean): ```c float mixedFriction = sqrtf(b2Shape_GetFriction(shapeIdA) * b2Shape_GetFriction(shapeIdB)); ``` If one shape has zero friction then the mixed friction will be zero. ### Restitution [Restitution](https://en.wikipedia.org/wiki/Coefficient_of_restitution) is used to make objects bounce. The restitution value is usually set to be between 0 and 1. Consider dropping a ball on a table. A value of zero means the ball won't bounce. This is called an *inelastic* collision. A value of one means the ball's velocity will be exactly reflected. This is called a *perfectly elastic* collision. Restitution is combined using the following formula. ```c float mixedRestitution = b2MaxFloat(b2Shape_GetRestitution(shapeIdA), b2Shape_GetRestitution(shapeIdB)); ``` Restitution is combined this way so that you can have a bouncy super ball without having a bouncy floor. When a shape develops multiple contacts, restitution is simulated approximately. This is because Box2D uses a sequential solver. Box2D also uses inelastic collisions when the collision velocity is small. This is done to prevent jitter. See `b2WorldDef::restitutionThreshold`. ### Friction and restitution callbacks Advanced users can override friction and restitution mixing using b2FrictionCallback and b2RestitutionCallback. These should be very light weight functions because they are called frequently. See the API reference for details. ```c float MyFrictionCallback(float frictionA, int userMaterialIdA, float frictionB, int userMaterialIdB) { if (userMaterialIdA > userMaterialIdB) { return frictionA; } return frictionB; } b2WorldDef worldDef = b2DefaultWorldDef(); worldDef.frictionCallback = MyFrictionCallback; ``` ### Filtering {#filtering} Collision filtering allows you to efficiently prevent collision between shapes. For example, say you make a character that rides a bicycle. You want the bicycle to collide with the terrain and the character to collide with the terrain, but you don't want the character to collide with the bicycle (because they must overlap). Box2D supports such collision filtering using categories, masks, and groups. Box2D supports 64 collision categories. For each shape you can specify which category it belongs to. You can also specify what other categories this shape can collide with. For example, you could specify in a multiplayer game that players don't collide with each other. Rather than identifying all the situations where things should not collide, I recommend identifying all the situations where things should collide. This way you don't get into situations where you are using [double negatives](https://en.wikipedia.org/wiki/Double_negative). You can specify which things can collide using mask bits. For example: ```c enum MyCategories { PLAYER = 0x00000002, MONSTER = 0x00000004, }; b2ShapeDef playerShapeDef = b2DefaultShapeDef(); b2ShapeDef monsterShapeDef = b2DefaultShapeDef(); playerShapeDef.filter.categoryBits = PLAYER; monsterShapeDef.filter.categoryBits = MONSTER; // Players collide with monsters, but not with other players playerShapeDef.filter.maskBits = MONSTER; // Monsters collide with players and other monsters monsterShapeDef.filter.maskBits = PLAYER | MONSTER; ``` Here is the rule for a collision to occur: ```c uint64_t catA = shapeA.filter.categoryBits; uint64_t maskA = shapeA.filter.maskBits; uint64_t catB = shapeB.filter.categoryBits; uint64_t maskB = shapeB.filter.maskBits; if ((catA & maskB) != 0 && (catB & maskA) != 0) { // shapes can collide } ``` Another filtering feature is *collision group*. Collision groups let you specify a group index. You can have all shapes with the same group index always collide (positive index) or never collide (negative index). Group indices are usually used for things that are somehow related, like the parts of a bicycle. In the following example, shape1 and shape2 always collide, but shape3 and shape4 never collide. ```c shape1Def.filter.groupIndex = 2; shape2Def.filter.groupIndex = 2; shape3Def.filter.groupIndex = -8; shape4Def.filter.groupIndex = -8; ``` Collisions between shapes of different group indices are filtered according the category and mask bits. If two shapes have the same non-zero group index, then this overrides the category and mask. Collision groups have a higher priority than categories and masks. Note that additional collision filtering occurs automatically in Box2D. Here is a list: - A shape on a static body can only collide with a dynamic body. - A shape on a kinematic body can only collide with a dynamic body. - Shapes on the same body never collide with each other. - You can optionally enable/disable collision between bodies connected by a joint. Sometimes you might need to change collision filtering after a shape has already been created. You can get and set the `b2Filter` structure on an existing shape using `b2Shape_GetFilter()` and `b2Shape_SetFilter()`. Changing the filter is expensive because it causes contacts to be destroyed. ### Chain Shapes The chain shape provides an efficient way to connect many line segments together to construct your static game worlds. Chain shapes automatically eliminate ghost collisions and provide one-sided collision. If you don't care about ghost collisions, you can create a bunch of two-sided segment shapes. The performance is similar. The simplest way to use chain shapes is to create loops. Simply provide an array of vertices. ```c b2Vec2 points[4] = { {1.7f, 0.0f}, {1.0f, 0.25f}, {0.0f, 0.0f}, {-1.7f, 0.4f}}; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = 4; b2ChainId myChainId = b2CreateChain(myBodyId, &chainDef); // Later ... b2DestroyChain(myChainId); // Nullify id for safety myChainId = b2_nullChainId; ``` The segment normal depends on the winding order. A counter-clockwise winding order orients the normal outwards and a clockwise winding order orients the normal inwards. ![Chain Shape Outwards Loop](images/chain_loop_outwards.svg) ![Chain Shape Inwards Loop](images/chain_loop_inwards.svg) You may have a scrolling game world and would like to connect several chains together. You can connect chains together using ghost vertices. To do this you must have the first three or last three points of each chain overlap. See the sample `ChainLink` for details. ![Chain Shape](images/chain_shape.svg) Self-intersection of chain shapes is not supported. It might work, it might not. The code that prevents ghost collisions assumes there are no self-intersections of the chain. Also, very close vertices can cause problems. Make sure all your points are more than than about a centimeter apart. ![Self Intersection is Bad](images/self_intersect.svg) Each segment in the chain is created as a `b2ChainSegment` shape on the body. If you have the shape id for a chain segment shape, you can get the owning chain id. This will return `b2_nullChainId` if the shape is not a chain segment. ```c b2ChainId chainId = b2SHape_GetParentChain(myShapeId); ``` You cannot create a chain segment shape directly. ### Sensors Sometimes game logic needs to know when two shapes overlap yet there should be no collision response. This is done by using sensors. A sensor is a shape that detects overlap but does not produce a response. You can flag any shape as being a sensor. Sensors may be static, kinematic, or dynamic. Remember that you may have multiple shapes per body and you can have any mix of sensors and solid shapes. Sensors can also detect other sensors. ```c b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.isSensor = true; ``` For both sensors and non-sensors, sensor events must also be enabled. There is a performance cost to generate sensor events, so they are disabled by default. ```c shapeDef.enableSensorEvents = true; ``` Sensors are processed at the end of the world step and generate begin and end events without delay. User operations may cause overlaps to begin or end. These are processed the next time step. Such operations include: - destroying a body or shape - changing a shape filter - disabling or enabling a body - setting a body transform - disabling or enabling sensor events on a shape Sensors do not detect objects that pass through the sensor shape within one time step. So sensors do not have continuous collision detection. If you have fast moving object and/or small sensors then you should use a ray or shape cast to detect these events. You can access the current sensor overlaps. Be careful because some shape ids may be invalid due to a shape being destroyed. Use `b2Shape_IsValid` to ensure an overlapping shape is still valid. ```cpp // First determine the required array capacity to hold all the overlapping shape ids. int capacity = b2Shape_GetSensorCapacity( sensorShapeId ); std::vector overlaps; overlaps.resize( capacity ); // Now get all overlaps and record the actual count int count = b2Shape_GetSensorOverlaps( sensorShapeId, overlaps.data(), capacity ); overlaps.resize( count ); for ( int i = 0; i < count; ++i ) { b2ShapeId visitorId = overlaps[i]; // Ensure the visitorId is valid if ( b2Shape_IsValid( visitorId ) == false ) { continue; } // process overlap using game logic } ``` Sensor overlap can also be determined using events, which are described below. ### Sensor Events Sensor events are available after every call to `b2World_Step()`. Sensor events are the best way to get information about sensors overlaps. There are events for when a shape begins to overlap with a sensor. ```c b2SensorEvents sensorEvents = b2World_GetSensorEvents(myWorldId); for (int i = 0; i < sensorEvents.beginCount; ++i) { b2SensorBeginTouchEvent* beginTouch = sensorEvents.beginEvents + i; void* myUserData = b2Shape_GetUserData(beginTouch->visitorShapeId); // process begin event } ``` And there are events when a shape stops overlapping with a sensor. Be careful with end touch events because they may be generated when shapes are destroyed. Test the shape ids with `b2Shape_IsValid`. ```c for (int i = 0; i < sensorEvents.endCount; ++i) { b2SensorEndTouchEvent* endTouch = sensorEvents.endEvents + i; if (b2Shape_IsValid(endTouch->visitorShapeId)) { void* myUserData = b2Shape_GetUserData(endTouch->visitorShapeId); // process end event } } ``` Sensor events should be processed after the world step and before other game logic. This should help you avoid processing stale data. Sensor events are only enabled for shapes and sensors if b2ShapeDef::enableSensorEvents is set to true. > **Note**: > A shape cannot start or stop being a sensor. Such a feature would break > sensor events, potentially causing bugs in game logic. ## Contacts Contacts are internal objects created by Box2D to manage collision between pairs of shapes. They are fundamental to rigid body simulation in games. ### Terminology Contacts have a fair bit of terminology that are important to review. #### contact point A contact point is a point where two shapes touch. Box2D approximates contact with a small number of points. Specifically, contact between two shapes has 0, 1, or 2 points. This is possible because Box2D uses convex shapes. #### contact normal A contact normal is a unit vector that points from one shape to another. By convention, the normal points from shapeA to shapeB. #### contact separation Separation is the opposite of penetration. Separation is negative when shapes overlap. #### contact manifold Contact between two convex polygons may generate up to 2 contact points. Both of these points use the same normal, so they are grouped into a contact manifold, which is an approximation of a continuous region of contact. #### normal impulse The normal force is the force applied at a contact point to prevent the shapes from penetrating. For convenience, Box2D uses impulses. The normal impulse is just the normal force multiplied by the time step. Since Box2D uses sub-stepping, this is the sub-step time step. #### tangent impulse The tangent force is generated at a contact point to simulate friction. For convenience, this is stored as an impulse. #### contact point id Box2D tries to re-use the contact impulse results from a time step as the initial guess for the next time step. Box2D uses contact point ids to match contact points across time steps. The ids contain geometric feature indices that help to distinguish one contact point from another. #### speculative contact When two shapes are close together, Box2D will create up to two contact points even if the shapes are not touching. This lets Box2D anticipate collision to improve behavior. Speculative contact points have positive separation. ### Contact Lifetime Contacts are created when two shape's AABBs (bounding boxes) begin to overlap. Sometimes collision filtering will prevent the creation of contacts. Contacts are destroyed with the AABBs cease to overlap. So you might gather that there may be contacts created for shapes that are not touching (just their AABBs). Well, this is correct. It's a \"chicken or egg\" problem. We don't know if we need a contact object until one is created to analyze the collision. We could delete the contact right away if the shapes are not touching, or we can just wait until the AABBs stop overlapping. Box2D takes the latter approach because it lets the system cache information to improve performance. ### Contact Data As mentioned before, the contact is created and destroyed by Box2D automatically. Contact data is not created by the user. However, you are able to access the contact data. You can get contact data from shapes or bodies. The contact data on a shape is a sub-set of the contact data on a body. The contact data is only returned for touching contacts. Contacts that are not touching provide no meaningful information for an application. Contact data is returned in arrays. So first you can ask a shape or body how much space you'll need in your array. This number is conservative and the actual number of contacts you'll receive may be less than this number, but never more. ```c int shapeContactCapacity = b2Shape_GetContactCapacity(myShapeId); int bodyContactCapacity = b2Body_GetContactCapacity(myBodyId); ``` You could allocate array space to get all the contact data in all cases, or you could use a fixed size array and get a limited number of results. ```c b2ContactData contactData[10]; int shapeContactCount = b2Shape_GetContactData(myShapeId, contactData, 10); int bodyContactCount = b2Body_GetContactData(myBodyId, contactData, 10); ``` `b2ContactData` contains the two shape ids and the manifold. ```c for (int i = 0; i < bodyContactCount; ++i) { b2ContactData* data = contactData + i; printf("point count = %d\n", data->manifold.pointCount); } ``` Getting contact data off shapes and bodies is not the most efficient way to handle contact data. Instead you should use contact events. ### Contact Events Contact events are available after each world step. Like sensor events these should be retrieved and processed before performing other game logic. Otherwise you may be accessing orphaned/invalid data. You can access all contact events in a single data structure. This is much more efficient than using functions like `b2Body_GetContactData()`. ```c b2ContactEvents contactEvents = b2World_GetContactEvents(myWorldId); ``` None of this data applies to sensors because they are handled separately. All events involve at least one dynamic body. There are three kinds of contact events: 1. Begin touch events 2. End touch events 3. Hit events #### Contact Touch Event `b2ContactBeginTouchEvent` is recorded when two shapes begin touching. These only contain the two shape ids. ```c for (int i = 0; i < contactEvents.beginCount; ++i) { b2ContactBeginTouchEvent* beginEvent = contactEvents.beginEvents + i; ShapesStartTouching(beginEvent->shapeIdA, beginEvent->shapeIdB); } ``` `b2ContactEndTouchEvent` is recorded when two shapes stop touching. These only contain the two shape ids. ```c for (int i = 0; i < contactEvents.endCount; ++i) { b2ContactEndTouchEvent* endEvent = contactEvents.endEvents + i; // Use b2Shape_IsValid because a shape may have been destroyed if (b2Shape_IsValid(endEvent->shapeIdA) && b2Shape_IsValid(endEvent->shapeIdB)) { ShapesStopTouching(endEvent->shapeIdA, endEvent->shapeIdB); } } ``` Similar to `b2SensorEndTouchEvent`, `b2ContactEndTouchEvent` may be generated due to a user operation, such as destroying a body or shape. These events are included with simulation events after the next `b2World_Step`. Shapes only generate begin and end touch events if `b2ShapeDef::enableContactEvents` is true. #### Hit Events Typically in games you are mainly concerned about getting contact events for when two shapes collide at a significant speed so you can play a sound and/or particle effect. Hit events are the answer for this. ```c for (int i = 0; i < contactEvents.hitCount; ++i) { b2ContactHitEvent* hitEvent = contactEvents.hitEvents + i; if (hitEvent->approachSpeed > 10.0f) { // play sound } } ``` Shapes only generate hit events if `b2ShapeDef::enableHitEvents` is true. I recommend you only enable this for shapes that need hit events because it creates some overhead. Box2D also only reports hit events that have an approach speed larger than `b2WorldDef::hitEventThreshold`. ### Contact Filtering Often in a game you don't want all objects to collide. For example, you may want to create a door that only certain characters can pass through. This is called contact filtering, because some interactions are filtered out. Contact filtering is setup on shapes and is covered [here](#filtering). ### Advanced Contact Handling #### Custom Filtering Callback For the best performance, use the contact filtering provided by `b2Filter`. However, in some cases you may need custom filtering. You can do this by registering a custom filter callback that implements `b2CustomFilterFcn()`. ```c bool MyCustomFilter(b2ShapeId shapeIdA, b2ShapeId shapeIdB, void* context) { MyGame* myGame = context; return myGame->WantsCollision(shapeIdA, shapeIdB); } // Elsewhere b2World_SetCustomFilterCallback(myWorldId, MyCustomFilter, myGame); ``` This function must be [thread-safe](https://en.wikipedia.org/wiki/Thread_safety) and must not read from or write to the Box2D world. Otherwise you will get a [race condition](https://en.wikipedia.org/wiki/Race_condition). #### Pre-Solve Callback This is called after collision detection, but before collision resolution. This gives you a chance to disable the contact based on the contact geometry. For example, you can implement a one-sided platform using this callback. The contact will be re-enabled each time through collision processing, so you will need to disable the contact every time-step. This function must be thread-safe and must not read from or write to the Box2D world. ```c bool MyPreSolve(b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Manifold* manifold, void* context) { MyGame* myGame = context; if (myGame->IsHittingBelowPlatform(shapeIdA, shapeIdB, manifold)) { return false; } return true; } // Elsewhere b2World_SetPreSolveCallback(myWorldId, MyPreSolve, myGame); ``` Note this currently does not work with high speed collisions, so you may see a pause in those situations. See the `Platformer` sample for more details. ## Joints Joints are used to constrain bodies to the world or to each other. Typical examples in games include ragdolls, teeters, and pulleys. Joints can be combined in many different ways to create interesting motions. Some joints provide limits so you can control the range of motion. Some joints provide motors which can be used to drive the joint at a prescribed speed until a prescribed force/torque is exceeded. And some joints provide springs with damping. Joint motors can be used in many ways. You can use motors to control position by specifying a joint velocity that is proportional to the difference between the actual and desired position. You can also use motors to simulate joint friction: set the joint velocity to zero and provide a small, but significant maximum motor force/torque. Then the motor will attempt to keep the joint from moving until the load becomes too strong. ### Joint Definition Each joint type has an associated joint definition. All joints are connected between two different bodies. One body may be static. Joints between static and/or kinematic bodies are allowed, but have no effect and use some processing time. If a joint is connected to a disabled body, that joint is effectively disabled. When the both bodies on a joint become enabled, the joint will automatically be enabled as well. In other words, you do not need to explicitly enable or disable a joint. You can specify user data for any joint type and you can provide a flag to prevent the attached bodies from colliding with each other. This is the default behavior and you must set the `collideConnected` Boolean to allow collision between two connected bodies. Many joint definitions require that you provide some geometric data. Often a joint will be defined by anchor points. These are points fixed in the attached bodies. Box2D requires these points to be specified in local coordinates. This way the joint can be specified even when the current body transforms violate the joint constraint. Additionally, some joint definitions need a reference angle between the bodies. This may be necessary to constrain rotation correctly. The rest of the joint definition data depends on the joint type. I cover these below. ### Joint Lifetime Joints are created using creation functions supplied for each joint type. They are destroyed with a shared function. All joint types share a single id type `b2JointId`. Here's an example of the lifetime of a revolute joint: ```c b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = myBodyA; jointDef.bodyIdB = myBodyB; jointDef.localAnchorA = (b2Vec2){0.0f, 0.0f}; jointDef.localAnchorB = (b2Vec2){1.0f, 2.0f}; b2JointId myJointId = b2CreateRevoluteJoint(myWorldId, &jointDef); // ... do stuff ... b2DestroyJoint(myJointId); myJointId = b2_nullJointId; ``` It is always good to nullify your ids after they are destroyed. Joint lifetime is related to body lifetime. Joints cannot exist detached from a body. So when a body is destroyed, all joints attached to that body are automatically destroyed. This means you need to be careful to avoid using joint ids when the attached body was destroyed. Box2D will assert if you use a dangling joint id. > **Caution**: > Joints are destroyed when an attached body is destroyed. Fortunately you can check if your joint id is valid. ```c if (b2Joint_IsValid(myJointId) == false) { myJointId = b2_nullJointId; } ``` This is certainly useful, but should not be overused because if you are creating and destroying many joints, this may eventually alias to a different joint. All ids have a limit of 64k generations. ### Using Joints Many simulations create the joints and don't access them again until they are destroyed. However, there is a lot of useful data contained in joints that you can use to create a rich simulation. First of all, you can get the type, bodies, anchor points, and user data from a joint. ```c b2JointType jointType = b2Joint_GetType(myJointId); b2BodyId bodyIdA = b2Joint_GetBodyA(myJointId); b2BodyId bodyIdB = b2Joint_GetBodyB(myJointId); b2Vec2 localAnchorA = b2Joint_GetLocalAnchorA(myJointId); b2Vec2 localAnchorB = b2Joint_GetLocalAnchorB(myJointId); void* myUserData = b2Joint_GetUserData(myJointId); ``` All joints have a reaction force and torque. Reaction forces are related to the [free body diagram](https://en.wikipedia.org/wiki/Free_body_diagram). The Box2D convention is that the reaction force is applied to body B at the anchor point. You can use reaction forces to break joints or trigger other game events. These functions may do some computations, so don't call them if you don't need the result. ```c b2Vec2 force = b2Joint_GetConstraintForce(myJointId); float torque = b2Joint_GetConstraintTorque(myJointId); ``` See the sample `BreakableJoint` for more details. ### Distance Joint One of the simplest joints is a distance joint which says that the distance between two points on two bodies must be constant. When you specify a distance joint the two bodies should already be in place. Then you specify the two anchor points in local coordinates. The first anchor point is connected to body A, and the second anchor point is connected to body B. These points imply the length of the distance constraint. ![Distance Joint](images/distance_joint.svg) Here is an example of a distance joint definition. In this case I decided to allow the bodies to collide. ```c b2DistanceJointDef jointDef = b2DefaultDistanceJointDef(); jointDef.bodyIdA = myBodyIdA; jointDef.bodyIdB = myBodyIdB; jointDef.localAnchorA = (b2Vec2){1.0f, -3.0f}; jointDef.localAnchorB = (b2Vec2){0.0f, 0.5f}; b2Vec2 anchorA = b2Body_GetWorldPoint(myBodyIdA, jointDef.localAnchorA); b2Vec2 anchorB = b2Body_GetWorldPoint(myBodyIdB, jointDef.localAnchorB); jointDef.length = b2Distance(anchorA, anchorB); jointDef.collideConnected = true; b2JointId myJointId = b2CreateDistanceJoint(myWorldId, &jointDef); ``` The distance joint can also be made soft, like a spring-damper connection. Softness is achieved by enabling the spring and tuning two values in the definition: Hertz and damping ratio. ```c jointDef.enableSpring = true; jointDef.hertz = 2.0f; jointDef.dampingRatio = 0.5f; ``` The hertz is the frequency of a [harmonic oscillator](https://en.wikipedia.org/wiki/Harmonic_oscillator) (like a guitar string). Typically the frequency should be less than a half the frequency of the time step. So if you are using a 60Hz time step, the frequency of the distance joint should be less than 30Hz. The reason is related to the [Nyquist frequency](https://en.wikipedia.org/wiki/Nyquist_frequency). The damping ratio controls how fast the oscillations dissipate. A damping ratio of one is [critical damping](https://en.wikipedia.org/wiki/Damping) and prevents oscillation. It is also possible to define a minimum and maximum length for the distance joint. You can even motorize the distance joint to adjust its length dynamically. See `b2DistanceJointDef` and the `DistanceJoint` sample for details. ### Revolute Joint A revolute joint forces two bodies to share a common anchor point, often called a hinge point or pivot. The revolute joint has a single degree of freedom: the relative rotation of the two bodies. This is called the joint angle. ![Revolute Joint](images/revolute_joint.svg) Like all joints, the anchor points are specified in local coordinates. However, you can use the body utility functions to simplify this. ```c b2Vec2 worldPivot = {10.0f, -4.0f}; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = myBodyIdA; jointDef.bodyIdB = myBodyIdB; jointDef.localAnchorA = b2Body_GetLocalPoint(myBodyIdA, worldPivot); jointDef.localAnchorB = b2Body_GetLocalPoint(myBodyIdB, worldPivot); b2JointId myJointId = b2CreateRevoluteJoint(myWorldId, &jointDef); ``` The revolute joint angle is positive when bodyB rotates counter-clockwise about the anchor point. Like all angles in Box2D, the revolute angle is measured in radians. By convention the revolute joint angle is zero when the two bodies have equal angles. You can offset this using `b2RevoluteJointDef::referenceAngle`. In some cases you might wish to control the joint angle. For this, the revolute joint can simulate a joint limit and/or a motor. A joint limit forces the joint angle to remain between a lower and upper angle. The limit will apply as much torque as needed to make this happen. The limit range should include zero, otherwise the joint will lurch when the simulation begins. The lower and upper limit are relative to the reference angle. A joint motor allows you to specify the joint speed. The speed can be negative or positive. A motor can have infinite force, but this is usually not desirable. Recall the eternal question: > *What happens when an irresistible force meets an immovable object?* I can tell you it's not pretty. So you can provide a maximum torque for the joint motor. The joint motor will maintain the specified speed unless the required torque exceeds the specified maximum. When the maximum torque is exceeded, the joint will slow down and can even reverse. You can use a joint motor to simulate joint friction. Just set the joint speed to zero, and set the maximum torque to some small, but significant value. The motor will try to prevent the joint from rotating, but will yield to a significant load. Here's a revision of the revolute joint definition above; this time the joint has a limit and a motor enabled. The motor is setup to simulate joint friction. ```c b2Vec2 worldPivot = {10.0f, -4.0f}; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = myBodyIdA; jointDef.bodyIdB = myBodyIdB; jointDef.localAnchorA = b2Body_GetLocalPoint(myBodyIdA, worldPivot); jointDef.localAnchorB = b2Body_GetLocalPoint(myBodyIdB, worldPivot); jointDef.lowerAngle = -0.5f * b2_pi; // -90 degrees jointDef.upperAngle = 0.25f * b2_pi; // 45 degrees jointDef.enableLimit = true; jointDef.maxMotorTorque = 10.0f; jointDef.motorSpeed = 0.0f; jointDef.enableMotor = true; ``` You can access a revolute joint's angle, speed, and motor torque. ```c float angleInRadians = b2RevoluteJoint_GetAngle(myJointId); float speed = b2RevoluteJoint_GetMotorSpeed(myJointId); float currentTorque = b2RevoluteJoint_GetMotorTorque(myJointId); ``` You also update the motor parameters each step. ```c b2RevoluteJoint_SetMotorSpeed(myJointId, 20.0f); b2RevoluteJoint_SetMaxMotorTorque(myJointId, 100.0f); ``` Joint motors have some interesting abilities. You can update the joint speed every time step so you can make the joint move back-and-forth like a sine-wave or according to whatever function you want. ```c // ... Game Loop Begin ... b2RevoluteJoint_SetMotorSpeed(myJointId, cosf(0.5f * time)); // ... Game Loop End ... ``` You can also use joint motors to track a desired joint angle. For example: ```c // ... Game Loop Begin ... float angleError = b2RevoluteJoint_GetAngle(myJointId) - angleTarget; float gain = 0.1f; b2RevoluteJoint_SetMotorSpeed(myJointId, -gain * angleError); // ... Game Loop End ... ``` Generally your gain parameter should not be too large. Otherwise your joint may become unstable. ### Prismatic Joint A prismatic joint allows for relative translation of two bodies along a local axis. A prismatic joint prevents relative rotation. Therefore, a prismatic joint has a single degree of freedom. ![Prismatic Joint](images/prismatic_joint.svg) The prismatic joint definition is similar to the revolute joint description; just substitute translation for angle and force for torque. Using this analogy provides an example prismatic joint definition with a joint limit and a friction motor: ```c b2Vec2 worldPivot = {10.0f, -4.0f}; b2Vec2 worldAxis = {1.0f, 0.0f}; b2PrismaticJointDef jointDef = b2DefaultPrismaticJointDef(); jointDef.bodyIdA = myBodyIdA; jointDef.bodyIdB = myBodyIdB; jointDef.localAnchorA = b2Body_GetLocalPoint(myBodyIdA, worldPivot); jointDef.localAnchorB = b2Body_GetLocalPoint(myBodyIdB, worldPivot); jointDef.localAxisA = b2Body_GetLocalVector(myBodyIdA, worldAxis); jointDef.lowerTranslation = -5.0f; jointDef.upperTranslation = 2.5f; jointDef.enableLimit = true; jointDef.maxMotorForce = 1.0f; jointDef.motorSpeed = 0.0f; jointDef.enableMotor = true; ``` The revolute joint has an implicit axis coming out of the screen. The prismatic joint needs an explicit axis parallel to the screen. This axis is fixed in body A. The prismatic joint translation is zero when the anchor points overlap. I recommend to have the prismatic anchor points close to the center of mass of the two bodies. This will improve joint stiffness. Using a prismatic joint is similar to using a revolute joint. Here are the relevant member functions: ```c float PrismaticJoint::GetJointTranslation() const; float PrismaticJoint::GetJointSpeed() const; float PrismaticJoint::GetMotorForce() const; void PrismaticJoint::SetMotorSpeed(float speed); void PrismaticJoint::SetMotorForce(float force); ``` ### Mouse Joint The mouse joint is used in the samples to manipulate bodies with the mouse. It attempts to drive a point on a body towards the current position of the cursor. There is no restriction on rotation. The mouse joint definition has a target point, maximum force, Hertz, and damping ratio. The target point initially coincides with the body's anchor point. The maximum force is used to prevent violent reactions when multiple dynamic bodies interact. You can make this as large as you like. The frequency and damping ratio are used to create a spring/damper effect similar to the distance joint. ### Weld Joint The weld joint attempts to constrain all relative motion between two bodies. See the `Cantilever` sample to see how the weld joint behaves. It is tempting to use the weld joint to define breakable structures. However, the Box2D solver is approximate so the joints can be soft in some cases regardless of the joint settings. So chains of bodies connected by weld joints may flex. See the `ContactEvent` sample for an example of how to merge and split bodies without using the weld joint. ### Motor Joint A motor joint lets you control the motion of a body by specifying target position and rotation offsets. You can set the maximum motor force and torque that will be applied to reach the target position and rotation. If the body is blocked, it will stop and the contact forces will be proportional the maximum motor force and torque. See `b2MotorJointDef` and the `MotorJoint` sample for details. ### Wheel Joint The wheel joint restricts a point on bodyB to a line on bodyA. The wheel joint also provides a suspension spring and a motor. See the `Driving` sample for details. ![Wheel Joint](images/wheel_joint.svg) The wheel joint is designed specifically for vehicles. It provides a translation and rotation. The translation has a spring and damper to simulate the vehicle suspension. The rotation allows the wheel to rotate. You can specify an rotational motor to drive the wheel and to apply braking. See `b2WheelJointDef` and the `Drive` sample for details. You may also use the wheel joint where you want free rotation and translation along an axis. See the `ScissorLift` sample for details. ## Spatial Queries {#spatial} Spatial queries allow you to inspect the world geometrically. There are overlap queries, ray-casts, and shape-casts. These allow you to do things like: - find a treasure chest near the player - shoot a laser beam and destroy all asteroids in the path - throw a grenade that is represented as a circle moving along a parabolic path ### Overlap Queries Sometimes you want to determine all the shapes in a region. The world has a fast log(N) method for this using the broad-phase data structure. Box2D provides these overlap tests: - axis-aligned bound box (AABB) overlap - shape proxy overlap #### Query Filtering A basic understanding of query filtering is needed before considering the specific queries. Shape versus shape filtering was discussed [here](#filtering). A similar setup is used for queries. This lets your queries only consider certain categories of shapes, it also lets your shapes ignore certain queries. Just like shapes, queries themselves can have a category. For example, you can have a `CAMERA` or `PROJECTILE` category. ```c enum MyCategories { STATIC = 0x00000001, PLAYER = 0x00000002, MONSTER = 0x00000004, WINDOW = 0x00000008, CAMERA = 0x00000010, PROJECTILE = 0x00000020, }; // Grenades collide with the static world, monsters, and windows but // not players or other projectiles. b2QueryFilter grenadeFilter; grenadeFilter.categoryBits = PROJECTILE; grenadeFilter.maskBits = STATIC | MONSTER | WINDOW; // The view collides with the static world, monsters, and players. b2QueryFilter viewFilter; viewFilter.categoryBits = CAMERA; viewFilter.maskBits = STATIC | PLAYER | MONSTER; ``` If you want to query everything you can use `b2DefaultQueryFilter()`; #### AABB Overlap You provide an AABB in world coordinates and an implementation of `b2OverlapResultFcn()`. The world calls your function with each shape whose AABB overlaps the query AABB. Return true to continue the query, otherwise return false. For example, the following code finds all the shapes that potentially intersect a specified AABB and wakes up all of the associated bodies. ```c bool MyOverlapCallback(b2ShapeId shapeId, void* context) { b2BodyId bodyId = b2Shape_GetBody(shapeId); b2Body_SetAwake(bodyId, true); // Return true to continue the query. return true; } // Elsewhere ... MyOverlapCallback callback; b2AABB aabb; aabb.lowerBound = (b2Vec2){-1.0f, -1.0f}; aabb.upperBound = (b2Vec2){1.0f, 1.0f}; b2QueryFilter filter = b2DefaultQueryFilter(); b2World_OverlapAABB(myWorldId, aabb, filter, MyOverlapCallback, &myGame); ``` Do not make any assumptions about the order of the callback. The order shapes are returned to your callback may seem arbitrary. #### Shape Overlap The AABB overlap is very fast but not very accurate because it only considers the shape bounding box. If you want an accurate overlap test, you can use a shape overlap query. The overlap function uses a `b2ShapeProxy` which is an abstract shape consisting of some points and a radius. You can think of it as a cloud of circles that has been _shrink wrapped_. This can represent a point, a circle, a line segment, a capsule, a polygon, a rounded rectangle, and so on. The helper function `b2MakeProxy` takes an array of points and a radius. In this example, I'm creating a shape proxy from a circle and then calling `b2World_OverlapShape()`. This takes a `b2OverlapResultFcn()` to receive results and control the search progress. ```c b2Circle circle = {b2Vec2_zero, 0.2f}; b2ShapeProxy proxy = b2MakeProxy(&circle.center, 1, circle.radius); b2World_OverlapShape(myWorldId, &proxy, grenadeFilter, MyOverlapCallback, &myGame); ``` ### Ray-casts You can use ray-casts to do line-of-sight checks, fire guns, etc. You perform a ray-cast by implementing the `b2CastResultFcn()` callback function and providing the origin point and translation. The world calls your function with each shape hit by the ray. Your callback is provided with the shape, the point of intersection, the unit normal vector, and the fractional distance along the ray. You cannot make any assumptions about the order of the points sent to the callback. The callback may receive points that are further away before receiving points that are closer. You control the continuation of the ray-cast by returning a fraction. Returning a fraction of zero indicates the ray-cast should be terminated. A fraction of one indicates the ray-cast should continue as if no hit occurred. If you return the fraction from the argument list, the ray will be clipped to the current intersection point. So you can ray-cast any shape, ray-cast all shapes, or ray-cast the closest shape by returning the appropriate fraction. You may also return of fraction of -1 to filter the shape. Then the ray-cast will proceed as if the shape does not exist. Here is an example: ```c // This struct captures the closest hit shape struct MyRayCastContext { b2ShapeId shapeId; b2Vec2 point; b2Vec2 normal; float fraction; }; float MyCastCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context) { MyRayCastContext* myContext = context; myContext->shape = shape; myContext->point = point; myContext->normal = normal; myContext->fraction = fraction; return fraction; } // Elsewhere ... MyRayCastContext context = {0}; b2Vec2 origin = {-1.0f, 0.0f}; b2Vec2 end(3.0f, 1.0f); b2Vec2 translation = b2Sub(end, origin); b2World_CastRay(myWorldId, origin, translation, viewFilter, MyCastCallback, &context); ``` Ray-cast results may be delivered in an arbitrary order. This doesn't affect the result for closest point ray-casts (except in ties). When you are collecting multiple hits along the ray, you may want to sort them according to the hit fraction. See the `CastWorld` sample for details. ### Shape-casts Shape-casts are similar to ray-casts. You can view a ray-cast as tracing a point along a line. A shape-cast allows you to trace a shape along a line. Like the shape overlap query, the shape cast uses a `b2ShapeProxy` to represent an arbitrary shape. ```c // This struct captures the closest hit shape struct MyRayCastContext { b2ShapeId shapeId; b2Vec2 point; b2Vec2 normal; float fraction; }; float MyCastCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context) { MyRayCastContext* myContext = context; myContext->shape = shape; myContext->point = point; myContext->normal = normal; myContext->fraction = fraction; return fraction; } // Elsewhere ... MyRayCastContext context = {0}; b2Circle circle = {{-1.0f, 0.0f}, 0.05f}; b2ShapeProxy proxy = b2MakeProxy(&circle.center, 1, circle.radius); b2Vec2 translation = {10.0f, -5.0f}; b2World_CastCircle(myWorldId, &proxy, translation, grenadeFilter, MyCastCallback, &context); ``` Otherwise, shape-casts are setup similarly to ray-casts. You can expect shape-casts to generally be slower than ray-casts. So only use a shape-cast if a ray-cast won't do. Just like ray-casts, shape-casts results may be sent to the callback in any order. If you need multiple sorted results, you will need to write some code to collect and sort the results. ## Simulation Loop ![Simulation Loop](images/simulation_loop.svg) The Box2D simulation loop can be useful to understand when you process results. Multithreading is represented in the diagram. - rectangles are parallel-for work - rounded rectangles are single-threaded work, but may be in parallel with other work Let's review each of these stages. ### time step The game starts the simulation by calling `b2World_Step` supplying the time step. ### find pairs Box2D maintains a record of every shape that has moved. For each of these shapes the broad-phase (BVH) is queried for overlaps. New overlaps are recorded for processing in the next step. I avoid reporting existing overlaps by using a hash table that records all existing shape pairs. This operation is a parallel-for. ### create contacts This takes the pair results and creates the internal contact pair structure (`b2Contact`). This structure is persistent across time steps. It is used for the island graph and holding contact manifolds. This operation is single-threaded but most of the work is done in `find pairs`. ### rebuild BVH After the new shape pairs are known the BVH is not considered until later in the time step. Therefore the BVH for dynamic and kinematic shapes may be optimized. This involves identifying the part of the collision tree that is stale from refitting and then performing a rebuild of that sub-tree. This is a single-single threaded operation that is done concurrently with other work. ### narrow phase This is where the contact manifolds and points are computed. Each active contact pair is confirmed as touching or non-touching. If the touching state changes then contact begin and end events are generated. This is a parallel-for operation. Notice that contact points are computed at the beginning of the time step, before bodies have moved and before impulses are known. This is necessary for obtaining good simulation results efficiently. If contacts were computed at the end of the time step then new contact points would not be known to the constraint solver and shapes would sink into each other. The `b2PreSolveFcn` is called within the parallel-for so it should be efficient and thread-safe. This is only called for shapes that have `enablePreSolveEvents == true`. ### merge islands Simulation islands are merged when shapes begin touching. Existing islands that have shapes that stop touching are flagged as candidates for splitting. This stage is single-threaded. ### split island A split island task may be generated if: - there is an island that has shapes that stopped touching - this island has a body that is moving slow enough to sleep Splitting an island may result in several new islands being created. Only a single island will be split per time step because it is expensive. Delaying the split may delay some bodies from sleeping. This is a single-single threaded operation that is done concurrently with other work. ### solve constraints This solves contact and joint constraints and applies restitution. This a parallel-for with multiple internal stages. ### update transforms This stage does several tasks: - updates body transforms - updates the body sleeping status - generates body move events - generates island splitting candidates - resets forces and torques - updates shape bounding boxes - performs continuous collision between dynamic and static bodies This stage is parallel-for. Note that continuous collision does not generate events. Instead they are generated the next time step. However, continuous collision will issue a `b2PreSolveFcn` callback. ### hit events Active contacts are scanned for fast approach velocities and added to a buffer. This considers contact points that have an impulse. This includes touching contacts and speculative contacts that generated an impulse (they are confirmed). So you may get hit events for contact points that have a positive separation. This is a single-threaded operation. ### refit BVH This updates the BVH for shapes that have moved significantly. This is done by enlarging the shapes bounding box and all ancestor bounding boxes in the BVH. This is a single-threaded operation. This can result in an inefficient BVH. This is the reason for the `rebuild BVH` stage. Refitting is faster than rebuilding the BVH but is necessary to ensure the BVH is valid for subsequent queries, such as ray casts. ### bullets This is where bullets are processed. Not that this comes after hit events because continuous collision in Box2D does not generate events until the next time step. ### island sleep When an island goes to sleep the simulation data associated with that island is moved to separate stored. This keeps the active simulation data contiguous and cache friendly. ### sensors Sensor overlaps are checked in the final stage. The overlap state reflects the final body transform. Sensors do not consider sleep so they may react to the user setting a body transform or creating a sleeping body. This is a parallel-for operation. The cost is roughly proportional to the number of sensors. ## Determinism Box2D is designed to be deterministic across thread counts and platforms. I believe this is important for debugging and game design. Multithreaded determinism is achieved by basing simulation order on creation order. This includes bodies, shapes, and joint creation order. Determinism includes results reported to users (events). These events must be in deterministic order. Cross-platform determinism is achieved on 64-bit platforms by using compiler flags and by avoiding non-deterministic library functions. - precise math is used on MSVC - floating point contraction is disabled on clang and GCC - Box2D has custom implementations of atan2, cosine, and sine. Determinism is on by default and there is no explicit option to disable it. However, you can break determinism by choosing different compiler flags. Box2D was designed to provide determinism with minimal cost. So there is no advantage to attempting to disable determinism. I maintain a unit test for determinism that is run for every pull request. Determinism is easy to break, so it is important to have regular validation. > **Caution**: > Box2D determinism does not mean your application will be deterministic. Consider using similar strategies to make your > application deterministic as I have used for Box2D. ================================================ FILE: extern/glad/include/KHR/khrplatform.h ================================================ #ifndef __khrplatform_h_ #define __khrplatform_h_ /* ** Copyright (c) 2008-2018 The Khronos Group Inc. ** ** Permission is hereby granted, free of charge, to any person obtaining a ** copy of this software and/or associated documentation files (the ** "Materials"), to deal in the Materials without restriction, including ** without limitation the rights to use, copy, modify, merge, publish, ** distribute, sublicense, and/or sell copies of the Materials, and to ** permit persons to whom the Materials are furnished to do so, subject to ** the following conditions: ** ** The above copyright notice and this permission notice shall be included ** in all copies or substantial portions of the Materials. ** ** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. */ /* Khronos platform-specific types and definitions. * * The master copy of khrplatform.h is maintained in the Khronos EGL * Registry repository at https://github.com/KhronosGroup/EGL-Registry * The last semantic modification to khrplatform.h was at commit ID: * 67a3e0864c2d75ea5287b9f3d2eb74a745936692 * * Adopters may modify this file to suit their platform. Adopters are * encouraged to submit platform specific modifications to the Khronos * group so that they can be included in future versions of this file. * Please submit changes by filing pull requests or issues on * the EGL Registry repository linked above. * * * See the Implementer's Guidelines for information about where this file * should be located on your system and for more details of its use: * http://www.khronos.org/registry/implementers_guide.pdf * * This file should be included as * #include * by Khronos client API header files that use its types and defines. * * The types in khrplatform.h should only be used to define API-specific types. * * Types defined in khrplatform.h: * khronos_int8_t signed 8 bit * khronos_uint8_t unsigned 8 bit * khronos_int16_t signed 16 bit * khronos_uint16_t unsigned 16 bit * khronos_int32_t signed 32 bit * khronos_uint32_t unsigned 32 bit * khronos_int64_t signed 64 bit * khronos_uint64_t unsigned 64 bit * khronos_intptr_t signed same number of bits as a pointer * khronos_uintptr_t unsigned same number of bits as a pointer * khronos_ssize_t signed size * khronos_usize_t unsigned size * khronos_float_t signed 32 bit floating point * khronos_time_ns_t unsigned 64 bit time in nanoseconds * khronos_utime_nanoseconds_t unsigned time interval or absolute time in * nanoseconds * khronos_stime_nanoseconds_t signed time interval in nanoseconds * khronos_boolean_enum_t enumerated boolean type. This should * only be used as a base type when a client API's boolean type is * an enum. Client APIs which use an integer or other type for * booleans cannot use this as the base type for their boolean. * * Tokens defined in khrplatform.h: * * KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values. * * KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0. * KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0. * * Calling convention macros defined in this file: * KHRONOS_APICALL * KHRONOS_APIENTRY * KHRONOS_APIATTRIBUTES * * These may be used in function prototypes as: * * KHRONOS_APICALL void KHRONOS_APIENTRY funcname( * int arg1, * int arg2) KHRONOS_APIATTRIBUTES; */ #if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC) # define KHRONOS_STATIC 1 #endif /*------------------------------------------------------------------------- * Definition of KHRONOS_APICALL *------------------------------------------------------------------------- * This precedes the return type of the function in the function prototype. */ #if defined(KHRONOS_STATIC) /* If the preprocessor constant KHRONOS_STATIC is defined, make the * header compatible with static linking. */ # define KHRONOS_APICALL #elif defined(_WIN32) # define KHRONOS_APICALL __declspec(dllimport) #elif defined (__SYMBIAN32__) # define KHRONOS_APICALL IMPORT_C #elif defined(__ANDROID__) # define KHRONOS_APICALL __attribute__((visibility("default"))) #else # define KHRONOS_APICALL #endif /*------------------------------------------------------------------------- * Definition of KHRONOS_APIENTRY *------------------------------------------------------------------------- * This follows the return type of the function and precedes the function * name in the function prototype. */ #if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__) /* Win32 but not WinCE */ # define KHRONOS_APIENTRY __stdcall #else # define KHRONOS_APIENTRY #endif /*------------------------------------------------------------------------- * Definition of KHRONOS_APIATTRIBUTES *------------------------------------------------------------------------- * This follows the closing parenthesis of the function prototype arguments. */ #if defined (__ARMCC_2__) #define KHRONOS_APIATTRIBUTES __softfp #else #define KHRONOS_APIATTRIBUTES #endif /*------------------------------------------------------------------------- * basic type definitions *-----------------------------------------------------------------------*/ #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__) /* * Using */ #include typedef int32_t khronos_int32_t; typedef uint32_t khronos_uint32_t; typedef int64_t khronos_int64_t; typedef uint64_t khronos_uint64_t; #define KHRONOS_SUPPORT_INT64 1 #define KHRONOS_SUPPORT_FLOAT 1 /* * To support platform where unsigned long cannot be used interchangeably with * inptr_t (e.g. CHERI-extended ISAs), we can use the stdint.h intptr_t. * Ideally, we could just use (u)intptr_t everywhere, but this could result in * ABI breakage if khronos_uintptr_t is changed from unsigned long to * unsigned long long or similar (this results in different C++ name mangling). * To avoid changes for existing platforms, we restrict usage of intptr_t to * platforms where the size of a pointer is larger than the size of long. */ #if defined(__SIZEOF_LONG__) && defined(__SIZEOF_POINTER__) #if __SIZEOF_POINTER__ > __SIZEOF_LONG__ #define KHRONOS_USE_INTPTR_T #endif #endif #elif defined(__VMS ) || defined(__sgi) /* * Using */ #include typedef int32_t khronos_int32_t; typedef uint32_t khronos_uint32_t; typedef int64_t khronos_int64_t; typedef uint64_t khronos_uint64_t; #define KHRONOS_SUPPORT_INT64 1 #define KHRONOS_SUPPORT_FLOAT 1 #elif defined(_WIN32) && !defined(__SCITECH_SNAP__) /* * Win32 */ typedef __int32 khronos_int32_t; typedef unsigned __int32 khronos_uint32_t; typedef __int64 khronos_int64_t; typedef unsigned __int64 khronos_uint64_t; #define KHRONOS_SUPPORT_INT64 1 #define KHRONOS_SUPPORT_FLOAT 1 #elif defined(__sun__) || defined(__digital__) /* * Sun or Digital */ typedef int khronos_int32_t; typedef unsigned int khronos_uint32_t; #if defined(__arch64__) || defined(_LP64) typedef long int khronos_int64_t; typedef unsigned long int khronos_uint64_t; #else typedef long long int khronos_int64_t; typedef unsigned long long int khronos_uint64_t; #endif /* __arch64__ */ #define KHRONOS_SUPPORT_INT64 1 #define KHRONOS_SUPPORT_FLOAT 1 #elif 0 /* * Hypothetical platform with no float or int64 support */ typedef int khronos_int32_t; typedef unsigned int khronos_uint32_t; #define KHRONOS_SUPPORT_INT64 0 #define KHRONOS_SUPPORT_FLOAT 0 #else /* * Generic fallback */ #include typedef int32_t khronos_int32_t; typedef uint32_t khronos_uint32_t; typedef int64_t khronos_int64_t; typedef uint64_t khronos_uint64_t; #define KHRONOS_SUPPORT_INT64 1 #define KHRONOS_SUPPORT_FLOAT 1 #endif /* * Types that are (so far) the same on all platforms */ typedef signed char khronos_int8_t; typedef unsigned char khronos_uint8_t; typedef signed short int khronos_int16_t; typedef unsigned short int khronos_uint16_t; /* * Types that differ between LLP64 and LP64 architectures - in LLP64, * pointers are 64 bits, but 'long' is still 32 bits. Win64 appears * to be the only LLP64 architecture in current use. */ #ifdef KHRONOS_USE_INTPTR_T typedef intptr_t khronos_intptr_t; typedef uintptr_t khronos_uintptr_t; #elif defined(_WIN64) typedef signed long long int khronos_intptr_t; typedef unsigned long long int khronos_uintptr_t; #else typedef signed long int khronos_intptr_t; typedef unsigned long int khronos_uintptr_t; #endif #if defined(_WIN64) typedef signed long long int khronos_ssize_t; typedef unsigned long long int khronos_usize_t; #else typedef signed long int khronos_ssize_t; typedef unsigned long int khronos_usize_t; #endif #if KHRONOS_SUPPORT_FLOAT /* * Float type */ typedef float khronos_float_t; #endif #if KHRONOS_SUPPORT_INT64 /* Time types * * These types can be used to represent a time interval in nanoseconds or * an absolute Unadjusted System Time. Unadjusted System Time is the number * of nanoseconds since some arbitrary system event (e.g. since the last * time the system booted). The Unadjusted System Time is an unsigned * 64 bit value that wraps back to 0 every 584 years. Time intervals * may be either signed or unsigned. */ typedef khronos_uint64_t khronos_utime_nanoseconds_t; typedef khronos_int64_t khronos_stime_nanoseconds_t; #endif /* * Dummy value used to pad enum types to 32 bits. */ #ifndef KHRONOS_MAX_ENUM #define KHRONOS_MAX_ENUM 0x7FFFFFFF #endif /* * Enumerated boolean type * * Values other than zero should be considered to be true. Therefore * comparisons should not be made against KHRONOS_TRUE. */ typedef enum { KHRONOS_FALSE = 0, KHRONOS_TRUE = 1, KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM } khronos_boolean_enum_t; #endif /* __khrplatform_h_ */ ================================================ FILE: extern/glad/include/glad/glad.h ================================================ /* OpenGL loader generated by glad 0.1.34 on Sat Jul 8 18:48:45 2023. Language/Generator: C/C++ Specification: gl APIs: gl=4.6 Profile: compatibility Extensions: Loader: True Local files: False Omit khrplatform: False Reproducible: False Commandline: --profile="compatibility" --api="gl=4.6" --generator="c" --spec="gl" --extensions="" Online: https://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&loader=on&api=gl%3D4.6 */ #ifndef __glad_h_ #define __glad_h_ #ifdef __gl_h_ #error OpenGL header already included, remove this include, glad already provides it #endif #define __gl_h_ #if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) #define APIENTRY __stdcall #endif #ifndef APIENTRY #define APIENTRY #endif #ifndef APIENTRYP #define APIENTRYP APIENTRY * #endif #ifndef GLAPIENTRY #define GLAPIENTRY APIENTRY #endif #ifdef __cplusplus extern "C" { #endif struct gladGLversionStruct { int major; int minor; }; typedef void* (* GLADloadproc)(const char *name); #ifndef GLAPI # if defined(GLAD_GLAPI_EXPORT) # if defined(_WIN32) || defined(__CYGWIN__) # if defined(GLAD_GLAPI_EXPORT_BUILD) # if defined(__GNUC__) # define GLAPI __attribute__ ((dllexport)) extern # else # define GLAPI __declspec(dllexport) extern # endif # else # if defined(__GNUC__) # define GLAPI __attribute__ ((dllimport)) extern # else # define GLAPI __declspec(dllimport) extern # endif # endif # elif defined(__GNUC__) && defined(GLAD_GLAPI_EXPORT_BUILD) # define GLAPI __attribute__ ((visibility ("default"))) extern # else # define GLAPI extern # endif # else # define GLAPI extern # endif #endif GLAPI struct gladGLversionStruct GLVersion; GLAPI int gladLoadGL(void); GLAPI int gladLoadGLLoader(GLADloadproc); #include typedef unsigned int GLenum; typedef unsigned char GLboolean; typedef unsigned int GLbitfield; typedef void GLvoid; typedef khronos_int8_t GLbyte; typedef khronos_uint8_t GLubyte; typedef khronos_int16_t GLshort; typedef khronos_uint16_t GLushort; typedef int GLint; typedef unsigned int GLuint; typedef khronos_int32_t GLclampx; typedef int GLsizei; typedef khronos_float_t GLfloat; typedef khronos_float_t GLclampf; typedef double GLdouble; typedef double GLclampd; typedef void *GLeglClientBufferEXT; typedef void *GLeglImageOES; typedef char GLchar; typedef char GLcharARB; #ifdef __APPLE__ typedef void *GLhandleARB; #else typedef unsigned int GLhandleARB; #endif typedef khronos_uint16_t GLhalf; typedef khronos_uint16_t GLhalfARB; typedef khronos_int32_t GLfixed; typedef khronos_intptr_t GLintptr; typedef khronos_intptr_t GLintptrARB; typedef khronos_ssize_t GLsizeiptr; typedef khronos_ssize_t GLsizeiptrARB; typedef khronos_int64_t GLint64; typedef khronos_int64_t GLint64EXT; typedef khronos_uint64_t GLuint64; typedef khronos_uint64_t GLuint64EXT; typedef struct __GLsync *GLsync; struct _cl_context; struct _cl_event; typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); typedef void (APIENTRY *GLDEBUGPROCKHR)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); typedef void (APIENTRY *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,void *userParam); typedef unsigned short GLhalfNV; typedef GLintptr GLvdpauSurfaceNV; typedef void (APIENTRY *GLVULKANPROCNV)(void); #define GL_DEPTH_BUFFER_BIT 0x00000100 #define GL_STENCIL_BUFFER_BIT 0x00000400 #define GL_COLOR_BUFFER_BIT 0x00004000 #define GL_FALSE 0 #define GL_TRUE 1 #define GL_POINTS 0x0000 #define GL_LINES 0x0001 #define GL_LINE_LOOP 0x0002 #define GL_LINE_STRIP 0x0003 #define GL_TRIANGLES 0x0004 #define GL_TRIANGLE_STRIP 0x0005 #define GL_TRIANGLE_FAN 0x0006 #define GL_QUADS 0x0007 #define GL_NEVER 0x0200 #define GL_LESS 0x0201 #define GL_EQUAL 0x0202 #define GL_LEQUAL 0x0203 #define GL_GREATER 0x0204 #define GL_NOTEQUAL 0x0205 #define GL_GEQUAL 0x0206 #define GL_ALWAYS 0x0207 #define GL_ZERO 0 #define GL_ONE 1 #define GL_SRC_COLOR 0x0300 #define GL_ONE_MINUS_SRC_COLOR 0x0301 #define GL_SRC_ALPHA 0x0302 #define GL_ONE_MINUS_SRC_ALPHA 0x0303 #define GL_DST_ALPHA 0x0304 #define GL_ONE_MINUS_DST_ALPHA 0x0305 #define GL_DST_COLOR 0x0306 #define GL_ONE_MINUS_DST_COLOR 0x0307 #define GL_SRC_ALPHA_SATURATE 0x0308 #define GL_NONE 0 #define GL_FRONT_LEFT 0x0400 #define GL_FRONT_RIGHT 0x0401 #define GL_BACK_LEFT 0x0402 #define GL_BACK_RIGHT 0x0403 #define GL_FRONT 0x0404 #define GL_BACK 0x0405 #define GL_LEFT 0x0406 #define GL_RIGHT 0x0407 #define GL_FRONT_AND_BACK 0x0408 #define GL_NO_ERROR 0 #define GL_INVALID_ENUM 0x0500 #define GL_INVALID_VALUE 0x0501 #define GL_INVALID_OPERATION 0x0502 #define GL_OUT_OF_MEMORY 0x0505 #define GL_CW 0x0900 #define GL_CCW 0x0901 #define GL_POINT_SIZE 0x0B11 #define GL_POINT_SIZE_RANGE 0x0B12 #define GL_POINT_SIZE_GRANULARITY 0x0B13 #define GL_LINE_SMOOTH 0x0B20 #define GL_LINE_WIDTH 0x0B21 #define GL_LINE_WIDTH_RANGE 0x0B22 #define GL_LINE_WIDTH_GRANULARITY 0x0B23 #define GL_POLYGON_MODE 0x0B40 #define GL_POLYGON_SMOOTH 0x0B41 #define GL_CULL_FACE 0x0B44 #define GL_CULL_FACE_MODE 0x0B45 #define GL_FRONT_FACE 0x0B46 #define GL_DEPTH_RANGE 0x0B70 #define GL_DEPTH_TEST 0x0B71 #define GL_DEPTH_WRITEMASK 0x0B72 #define GL_DEPTH_CLEAR_VALUE 0x0B73 #define GL_DEPTH_FUNC 0x0B74 #define GL_STENCIL_TEST 0x0B90 #define GL_STENCIL_CLEAR_VALUE 0x0B91 #define GL_STENCIL_FUNC 0x0B92 #define GL_STENCIL_VALUE_MASK 0x0B93 #define GL_STENCIL_FAIL 0x0B94 #define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 #define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 #define GL_STENCIL_REF 0x0B97 #define GL_STENCIL_WRITEMASK 0x0B98 #define GL_VIEWPORT 0x0BA2 #define GL_DITHER 0x0BD0 #define GL_BLEND_DST 0x0BE0 #define GL_BLEND_SRC 0x0BE1 #define GL_BLEND 0x0BE2 #define GL_LOGIC_OP_MODE 0x0BF0 #define GL_DRAW_BUFFER 0x0C01 #define GL_READ_BUFFER 0x0C02 #define GL_SCISSOR_BOX 0x0C10 #define GL_SCISSOR_TEST 0x0C11 #define GL_COLOR_CLEAR_VALUE 0x0C22 #define GL_COLOR_WRITEMASK 0x0C23 #define GL_DOUBLEBUFFER 0x0C32 #define GL_STEREO 0x0C33 #define GL_LINE_SMOOTH_HINT 0x0C52 #define GL_POLYGON_SMOOTH_HINT 0x0C53 #define GL_UNPACK_SWAP_BYTES 0x0CF0 #define GL_UNPACK_LSB_FIRST 0x0CF1 #define GL_UNPACK_ROW_LENGTH 0x0CF2 #define GL_UNPACK_SKIP_ROWS 0x0CF3 #define GL_UNPACK_SKIP_PIXELS 0x0CF4 #define GL_UNPACK_ALIGNMENT 0x0CF5 #define GL_PACK_SWAP_BYTES 0x0D00 #define GL_PACK_LSB_FIRST 0x0D01 #define GL_PACK_ROW_LENGTH 0x0D02 #define GL_PACK_SKIP_ROWS 0x0D03 #define GL_PACK_SKIP_PIXELS 0x0D04 #define GL_PACK_ALIGNMENT 0x0D05 #define GL_MAX_TEXTURE_SIZE 0x0D33 #define GL_MAX_VIEWPORT_DIMS 0x0D3A #define GL_SUBPIXEL_BITS 0x0D50 #define GL_TEXTURE_1D 0x0DE0 #define GL_TEXTURE_2D 0x0DE1 #define GL_TEXTURE_WIDTH 0x1000 #define GL_TEXTURE_HEIGHT 0x1001 #define GL_TEXTURE_BORDER_COLOR 0x1004 #define GL_DONT_CARE 0x1100 #define GL_FASTEST 0x1101 #define GL_NICEST 0x1102 #define GL_BYTE 0x1400 #define GL_UNSIGNED_BYTE 0x1401 #define GL_SHORT 0x1402 #define GL_UNSIGNED_SHORT 0x1403 #define GL_INT 0x1404 #define GL_UNSIGNED_INT 0x1405 #define GL_FLOAT 0x1406 #define GL_STACK_OVERFLOW 0x0503 #define GL_STACK_UNDERFLOW 0x0504 #define GL_CLEAR 0x1500 #define GL_AND 0x1501 #define GL_AND_REVERSE 0x1502 #define GL_COPY 0x1503 #define GL_AND_INVERTED 0x1504 #define GL_NOOP 0x1505 #define GL_XOR 0x1506 #define GL_OR 0x1507 #define GL_NOR 0x1508 #define GL_EQUIV 0x1509 #define GL_INVERT 0x150A #define GL_OR_REVERSE 0x150B #define GL_COPY_INVERTED 0x150C #define GL_OR_INVERTED 0x150D #define GL_NAND 0x150E #define GL_SET 0x150F #define GL_TEXTURE 0x1702 #define GL_COLOR 0x1800 #define GL_DEPTH 0x1801 #define GL_STENCIL 0x1802 #define GL_STENCIL_INDEX 0x1901 #define GL_DEPTH_COMPONENT 0x1902 #define GL_RED 0x1903 #define GL_GREEN 0x1904 #define GL_BLUE 0x1905 #define GL_ALPHA 0x1906 #define GL_RGB 0x1907 #define GL_RGBA 0x1908 #define GL_POINT 0x1B00 #define GL_LINE 0x1B01 #define GL_FILL 0x1B02 #define GL_KEEP 0x1E00 #define GL_REPLACE 0x1E01 #define GL_INCR 0x1E02 #define GL_DECR 0x1E03 #define GL_VENDOR 0x1F00 #define GL_RENDERER 0x1F01 #define GL_VERSION 0x1F02 #define GL_EXTENSIONS 0x1F03 #define GL_NEAREST 0x2600 #define GL_LINEAR 0x2601 #define GL_NEAREST_MIPMAP_NEAREST 0x2700 #define GL_LINEAR_MIPMAP_NEAREST 0x2701 #define GL_NEAREST_MIPMAP_LINEAR 0x2702 #define GL_LINEAR_MIPMAP_LINEAR 0x2703 #define GL_TEXTURE_MAG_FILTER 0x2800 #define GL_TEXTURE_MIN_FILTER 0x2801 #define GL_TEXTURE_WRAP_S 0x2802 #define GL_TEXTURE_WRAP_T 0x2803 #define GL_REPEAT 0x2901 #define GL_CURRENT_BIT 0x00000001 #define GL_POINT_BIT 0x00000002 #define GL_LINE_BIT 0x00000004 #define GL_POLYGON_BIT 0x00000008 #define GL_POLYGON_STIPPLE_BIT 0x00000010 #define GL_PIXEL_MODE_BIT 0x00000020 #define GL_LIGHTING_BIT 0x00000040 #define GL_FOG_BIT 0x00000080 #define GL_ACCUM_BUFFER_BIT 0x00000200 #define GL_VIEWPORT_BIT 0x00000800 #define GL_TRANSFORM_BIT 0x00001000 #define GL_ENABLE_BIT 0x00002000 #define GL_HINT_BIT 0x00008000 #define GL_EVAL_BIT 0x00010000 #define GL_LIST_BIT 0x00020000 #define GL_TEXTURE_BIT 0x00040000 #define GL_SCISSOR_BIT 0x00080000 #define GL_ALL_ATTRIB_BITS 0xFFFFFFFF #define GL_QUAD_STRIP 0x0008 #define GL_POLYGON 0x0009 #define GL_ACCUM 0x0100 #define GL_LOAD 0x0101 #define GL_RETURN 0x0102 #define GL_MULT 0x0103 #define GL_ADD 0x0104 #define GL_AUX0 0x0409 #define GL_AUX1 0x040A #define GL_AUX2 0x040B #define GL_AUX3 0x040C #define GL_2D 0x0600 #define GL_3D 0x0601 #define GL_3D_COLOR 0x0602 #define GL_3D_COLOR_TEXTURE 0x0603 #define GL_4D_COLOR_TEXTURE 0x0604 #define GL_PASS_THROUGH_TOKEN 0x0700 #define GL_POINT_TOKEN 0x0701 #define GL_LINE_TOKEN 0x0702 #define GL_POLYGON_TOKEN 0x0703 #define GL_BITMAP_TOKEN 0x0704 #define GL_DRAW_PIXEL_TOKEN 0x0705 #define GL_COPY_PIXEL_TOKEN 0x0706 #define GL_LINE_RESET_TOKEN 0x0707 #define GL_EXP 0x0800 #define GL_EXP2 0x0801 #define GL_COEFF 0x0A00 #define GL_ORDER 0x0A01 #define GL_DOMAIN 0x0A02 #define GL_PIXEL_MAP_I_TO_I 0x0C70 #define GL_PIXEL_MAP_S_TO_S 0x0C71 #define GL_PIXEL_MAP_I_TO_R 0x0C72 #define GL_PIXEL_MAP_I_TO_G 0x0C73 #define GL_PIXEL_MAP_I_TO_B 0x0C74 #define GL_PIXEL_MAP_I_TO_A 0x0C75 #define GL_PIXEL_MAP_R_TO_R 0x0C76 #define GL_PIXEL_MAP_G_TO_G 0x0C77 #define GL_PIXEL_MAP_B_TO_B 0x0C78 #define GL_PIXEL_MAP_A_TO_A 0x0C79 #define GL_CURRENT_COLOR 0x0B00 #define GL_CURRENT_INDEX 0x0B01 #define GL_CURRENT_NORMAL 0x0B02 #define GL_CURRENT_TEXTURE_COORDS 0x0B03 #define GL_CURRENT_RASTER_COLOR 0x0B04 #define GL_CURRENT_RASTER_INDEX 0x0B05 #define GL_CURRENT_RASTER_TEXTURE_COORDS 0x0B06 #define GL_CURRENT_RASTER_POSITION 0x0B07 #define GL_CURRENT_RASTER_POSITION_VALID 0x0B08 #define GL_CURRENT_RASTER_DISTANCE 0x0B09 #define GL_POINT_SMOOTH 0x0B10 #define GL_LINE_STIPPLE 0x0B24 #define GL_LINE_STIPPLE_PATTERN 0x0B25 #define GL_LINE_STIPPLE_REPEAT 0x0B26 #define GL_LIST_MODE 0x0B30 #define GL_MAX_LIST_NESTING 0x0B31 #define GL_LIST_BASE 0x0B32 #define GL_LIST_INDEX 0x0B33 #define GL_POLYGON_STIPPLE 0x0B42 #define GL_EDGE_FLAG 0x0B43 #define GL_LIGHTING 0x0B50 #define GL_LIGHT_MODEL_LOCAL_VIEWER 0x0B51 #define GL_LIGHT_MODEL_TWO_SIDE 0x0B52 #define GL_LIGHT_MODEL_AMBIENT 0x0B53 #define GL_SHADE_MODEL 0x0B54 #define GL_COLOR_MATERIAL_FACE 0x0B55 #define GL_COLOR_MATERIAL_PARAMETER 0x0B56 #define GL_COLOR_MATERIAL 0x0B57 #define GL_FOG 0x0B60 #define GL_FOG_INDEX 0x0B61 #define GL_FOG_DENSITY 0x0B62 #define GL_FOG_START 0x0B63 #define GL_FOG_END 0x0B64 #define GL_FOG_MODE 0x0B65 #define GL_FOG_COLOR 0x0B66 #define GL_ACCUM_CLEAR_VALUE 0x0B80 #define GL_MATRIX_MODE 0x0BA0 #define GL_NORMALIZE 0x0BA1 #define GL_MODELVIEW_STACK_DEPTH 0x0BA3 #define GL_PROJECTION_STACK_DEPTH 0x0BA4 #define GL_TEXTURE_STACK_DEPTH 0x0BA5 #define GL_MODELVIEW_MATRIX 0x0BA6 #define GL_PROJECTION_MATRIX 0x0BA7 #define GL_TEXTURE_MATRIX 0x0BA8 #define GL_ATTRIB_STACK_DEPTH 0x0BB0 #define GL_ALPHA_TEST 0x0BC0 #define GL_ALPHA_TEST_FUNC 0x0BC1 #define GL_ALPHA_TEST_REF 0x0BC2 #define GL_LOGIC_OP 0x0BF1 #define GL_AUX_BUFFERS 0x0C00 #define GL_INDEX_CLEAR_VALUE 0x0C20 #define GL_INDEX_WRITEMASK 0x0C21 #define GL_INDEX_MODE 0x0C30 #define GL_RGBA_MODE 0x0C31 #define GL_RENDER_MODE 0x0C40 #define GL_PERSPECTIVE_CORRECTION_HINT 0x0C50 #define GL_POINT_SMOOTH_HINT 0x0C51 #define GL_FOG_HINT 0x0C54 #define GL_TEXTURE_GEN_S 0x0C60 #define GL_TEXTURE_GEN_T 0x0C61 #define GL_TEXTURE_GEN_R 0x0C62 #define GL_TEXTURE_GEN_Q 0x0C63 #define GL_PIXEL_MAP_I_TO_I_SIZE 0x0CB0 #define GL_PIXEL_MAP_S_TO_S_SIZE 0x0CB1 #define GL_PIXEL_MAP_I_TO_R_SIZE 0x0CB2 #define GL_PIXEL_MAP_I_TO_G_SIZE 0x0CB3 #define GL_PIXEL_MAP_I_TO_B_SIZE 0x0CB4 #define GL_PIXEL_MAP_I_TO_A_SIZE 0x0CB5 #define GL_PIXEL_MAP_R_TO_R_SIZE 0x0CB6 #define GL_PIXEL_MAP_G_TO_G_SIZE 0x0CB7 #define GL_PIXEL_MAP_B_TO_B_SIZE 0x0CB8 #define GL_PIXEL_MAP_A_TO_A_SIZE 0x0CB9 #define GL_MAP_COLOR 0x0D10 #define GL_MAP_STENCIL 0x0D11 #define GL_INDEX_SHIFT 0x0D12 #define GL_INDEX_OFFSET 0x0D13 #define GL_RED_SCALE 0x0D14 #define GL_RED_BIAS 0x0D15 #define GL_ZOOM_X 0x0D16 #define GL_ZOOM_Y 0x0D17 #define GL_GREEN_SCALE 0x0D18 #define GL_GREEN_BIAS 0x0D19 #define GL_BLUE_SCALE 0x0D1A #define GL_BLUE_BIAS 0x0D1B #define GL_ALPHA_SCALE 0x0D1C #define GL_ALPHA_BIAS 0x0D1D #define GL_DEPTH_SCALE 0x0D1E #define GL_DEPTH_BIAS 0x0D1F #define GL_MAX_EVAL_ORDER 0x0D30 #define GL_MAX_LIGHTS 0x0D31 #define GL_MAX_CLIP_PLANES 0x0D32 #define GL_MAX_PIXEL_MAP_TABLE 0x0D34 #define GL_MAX_ATTRIB_STACK_DEPTH 0x0D35 #define GL_MAX_MODELVIEW_STACK_DEPTH 0x0D36 #define GL_MAX_NAME_STACK_DEPTH 0x0D37 #define GL_MAX_PROJECTION_STACK_DEPTH 0x0D38 #define GL_MAX_TEXTURE_STACK_DEPTH 0x0D39 #define GL_INDEX_BITS 0x0D51 #define GL_RED_BITS 0x0D52 #define GL_GREEN_BITS 0x0D53 #define GL_BLUE_BITS 0x0D54 #define GL_ALPHA_BITS 0x0D55 #define GL_DEPTH_BITS 0x0D56 #define GL_STENCIL_BITS 0x0D57 #define GL_ACCUM_RED_BITS 0x0D58 #define GL_ACCUM_GREEN_BITS 0x0D59 #define GL_ACCUM_BLUE_BITS 0x0D5A #define GL_ACCUM_ALPHA_BITS 0x0D5B #define GL_NAME_STACK_DEPTH 0x0D70 #define GL_AUTO_NORMAL 0x0D80 #define GL_MAP1_COLOR_4 0x0D90 #define GL_MAP1_INDEX 0x0D91 #define GL_MAP1_NORMAL 0x0D92 #define GL_MAP1_TEXTURE_COORD_1 0x0D93 #define GL_MAP1_TEXTURE_COORD_2 0x0D94 #define GL_MAP1_TEXTURE_COORD_3 0x0D95 #define GL_MAP1_TEXTURE_COORD_4 0x0D96 #define GL_MAP1_VERTEX_3 0x0D97 #define GL_MAP1_VERTEX_4 0x0D98 #define GL_MAP2_COLOR_4 0x0DB0 #define GL_MAP2_INDEX 0x0DB1 #define GL_MAP2_NORMAL 0x0DB2 #define GL_MAP2_TEXTURE_COORD_1 0x0DB3 #define GL_MAP2_TEXTURE_COORD_2 0x0DB4 #define GL_MAP2_TEXTURE_COORD_3 0x0DB5 #define GL_MAP2_TEXTURE_COORD_4 0x0DB6 #define GL_MAP2_VERTEX_3 0x0DB7 #define GL_MAP2_VERTEX_4 0x0DB8 #define GL_MAP1_GRID_DOMAIN 0x0DD0 #define GL_MAP1_GRID_SEGMENTS 0x0DD1 #define GL_MAP2_GRID_DOMAIN 0x0DD2 #define GL_MAP2_GRID_SEGMENTS 0x0DD3 #define GL_TEXTURE_COMPONENTS 0x1003 #define GL_TEXTURE_BORDER 0x1005 #define GL_AMBIENT 0x1200 #define GL_DIFFUSE 0x1201 #define GL_SPECULAR 0x1202 #define GL_POSITION 0x1203 #define GL_SPOT_DIRECTION 0x1204 #define GL_SPOT_EXPONENT 0x1205 #define GL_SPOT_CUTOFF 0x1206 #define GL_CONSTANT_ATTENUATION 0x1207 #define GL_LINEAR_ATTENUATION 0x1208 #define GL_QUADRATIC_ATTENUATION 0x1209 #define GL_COMPILE 0x1300 #define GL_COMPILE_AND_EXECUTE 0x1301 #define GL_2_BYTES 0x1407 #define GL_3_BYTES 0x1408 #define GL_4_BYTES 0x1409 #define GL_EMISSION 0x1600 #define GL_SHININESS 0x1601 #define GL_AMBIENT_AND_DIFFUSE 0x1602 #define GL_COLOR_INDEXES 0x1603 #define GL_MODELVIEW 0x1700 #define GL_PROJECTION 0x1701 #define GL_COLOR_INDEX 0x1900 #define GL_LUMINANCE 0x1909 #define GL_LUMINANCE_ALPHA 0x190A #define GL_BITMAP 0x1A00 #define GL_RENDER 0x1C00 #define GL_FEEDBACK 0x1C01 #define GL_SELECT 0x1C02 #define GL_FLAT 0x1D00 #define GL_SMOOTH 0x1D01 #define GL_S 0x2000 #define GL_T 0x2001 #define GL_R 0x2002 #define GL_Q 0x2003 #define GL_MODULATE 0x2100 #define GL_DECAL 0x2101 #define GL_TEXTURE_ENV_MODE 0x2200 #define GL_TEXTURE_ENV_COLOR 0x2201 #define GL_TEXTURE_ENV 0x2300 #define GL_EYE_LINEAR 0x2400 #define GL_OBJECT_LINEAR 0x2401 #define GL_SPHERE_MAP 0x2402 #define GL_TEXTURE_GEN_MODE 0x2500 #define GL_OBJECT_PLANE 0x2501 #define GL_EYE_PLANE 0x2502 #define GL_CLAMP 0x2900 #define GL_CLIP_PLANE0 0x3000 #define GL_CLIP_PLANE1 0x3001 #define GL_CLIP_PLANE2 0x3002 #define GL_CLIP_PLANE3 0x3003 #define GL_CLIP_PLANE4 0x3004 #define GL_CLIP_PLANE5 0x3005 #define GL_LIGHT0 0x4000 #define GL_LIGHT1 0x4001 #define GL_LIGHT2 0x4002 #define GL_LIGHT3 0x4003 #define GL_LIGHT4 0x4004 #define GL_LIGHT5 0x4005 #define GL_LIGHT6 0x4006 #define GL_LIGHT7 0x4007 #define GL_COLOR_LOGIC_OP 0x0BF2 #define GL_POLYGON_OFFSET_UNITS 0x2A00 #define GL_POLYGON_OFFSET_POINT 0x2A01 #define GL_POLYGON_OFFSET_LINE 0x2A02 #define GL_POLYGON_OFFSET_FILL 0x8037 #define GL_POLYGON_OFFSET_FACTOR 0x8038 #define GL_TEXTURE_BINDING_1D 0x8068 #define GL_TEXTURE_BINDING_2D 0x8069 #define GL_TEXTURE_INTERNAL_FORMAT 0x1003 #define GL_TEXTURE_RED_SIZE 0x805C #define GL_TEXTURE_GREEN_SIZE 0x805D #define GL_TEXTURE_BLUE_SIZE 0x805E #define GL_TEXTURE_ALPHA_SIZE 0x805F #define GL_DOUBLE 0x140A #define GL_PROXY_TEXTURE_1D 0x8063 #define GL_PROXY_TEXTURE_2D 0x8064 #define GL_R3_G3_B2 0x2A10 #define GL_RGB4 0x804F #define GL_RGB5 0x8050 #define GL_RGB8 0x8051 #define GL_RGB10 0x8052 #define GL_RGB12 0x8053 #define GL_RGB16 0x8054 #define GL_RGBA2 0x8055 #define GL_RGBA4 0x8056 #define GL_RGB5_A1 0x8057 #define GL_RGBA8 0x8058 #define GL_RGB10_A2 0x8059 #define GL_RGBA12 0x805A #define GL_RGBA16 0x805B #define GL_CLIENT_PIXEL_STORE_BIT 0x00000001 #define GL_CLIENT_VERTEX_ARRAY_BIT 0x00000002 #define GL_CLIENT_ALL_ATTRIB_BITS 0xFFFFFFFF #define GL_VERTEX_ARRAY_POINTER 0x808E #define GL_NORMAL_ARRAY_POINTER 0x808F #define GL_COLOR_ARRAY_POINTER 0x8090 #define GL_INDEX_ARRAY_POINTER 0x8091 #define GL_TEXTURE_COORD_ARRAY_POINTER 0x8092 #define GL_EDGE_FLAG_ARRAY_POINTER 0x8093 #define GL_FEEDBACK_BUFFER_POINTER 0x0DF0 #define GL_SELECTION_BUFFER_POINTER 0x0DF3 #define GL_CLIENT_ATTRIB_STACK_DEPTH 0x0BB1 #define GL_INDEX_LOGIC_OP 0x0BF1 #define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH 0x0D3B #define GL_FEEDBACK_BUFFER_SIZE 0x0DF1 #define GL_FEEDBACK_BUFFER_TYPE 0x0DF2 #define GL_SELECTION_BUFFER_SIZE 0x0DF4 #define GL_VERTEX_ARRAY 0x8074 #define GL_NORMAL_ARRAY 0x8075 #define GL_COLOR_ARRAY 0x8076 #define GL_INDEX_ARRAY 0x8077 #define GL_TEXTURE_COORD_ARRAY 0x8078 #define GL_EDGE_FLAG_ARRAY 0x8079 #define GL_VERTEX_ARRAY_SIZE 0x807A #define GL_VERTEX_ARRAY_TYPE 0x807B #define GL_VERTEX_ARRAY_STRIDE 0x807C #define GL_NORMAL_ARRAY_TYPE 0x807E #define GL_NORMAL_ARRAY_STRIDE 0x807F #define GL_COLOR_ARRAY_SIZE 0x8081 #define GL_COLOR_ARRAY_TYPE 0x8082 #define GL_COLOR_ARRAY_STRIDE 0x8083 #define GL_INDEX_ARRAY_TYPE 0x8085 #define GL_INDEX_ARRAY_STRIDE 0x8086 #define GL_TEXTURE_COORD_ARRAY_SIZE 0x8088 #define GL_TEXTURE_COORD_ARRAY_TYPE 0x8089 #define GL_TEXTURE_COORD_ARRAY_STRIDE 0x808A #define GL_EDGE_FLAG_ARRAY_STRIDE 0x808C #define GL_TEXTURE_LUMINANCE_SIZE 0x8060 #define GL_TEXTURE_INTENSITY_SIZE 0x8061 #define GL_TEXTURE_PRIORITY 0x8066 #define GL_TEXTURE_RESIDENT 0x8067 #define GL_ALPHA4 0x803B #define GL_ALPHA8 0x803C #define GL_ALPHA12 0x803D #define GL_ALPHA16 0x803E #define GL_LUMINANCE4 0x803F #define GL_LUMINANCE8 0x8040 #define GL_LUMINANCE12 0x8041 #define GL_LUMINANCE16 0x8042 #define GL_LUMINANCE4_ALPHA4 0x8043 #define GL_LUMINANCE6_ALPHA2 0x8044 #define GL_LUMINANCE8_ALPHA8 0x8045 #define GL_LUMINANCE12_ALPHA4 0x8046 #define GL_LUMINANCE12_ALPHA12 0x8047 #define GL_LUMINANCE16_ALPHA16 0x8048 #define GL_INTENSITY 0x8049 #define GL_INTENSITY4 0x804A #define GL_INTENSITY8 0x804B #define GL_INTENSITY12 0x804C #define GL_INTENSITY16 0x804D #define GL_V2F 0x2A20 #define GL_V3F 0x2A21 #define GL_C4UB_V2F 0x2A22 #define GL_C4UB_V3F 0x2A23 #define GL_C3F_V3F 0x2A24 #define GL_N3F_V3F 0x2A25 #define GL_C4F_N3F_V3F 0x2A26 #define GL_T2F_V3F 0x2A27 #define GL_T4F_V4F 0x2A28 #define GL_T2F_C4UB_V3F 0x2A29 #define GL_T2F_C3F_V3F 0x2A2A #define GL_T2F_N3F_V3F 0x2A2B #define GL_T2F_C4F_N3F_V3F 0x2A2C #define GL_T4F_C4F_N3F_V4F 0x2A2D #define GL_UNSIGNED_BYTE_3_3_2 0x8032 #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 #define GL_UNSIGNED_INT_8_8_8_8 0x8035 #define GL_UNSIGNED_INT_10_10_10_2 0x8036 #define GL_TEXTURE_BINDING_3D 0x806A #define GL_PACK_SKIP_IMAGES 0x806B #define GL_PACK_IMAGE_HEIGHT 0x806C #define GL_UNPACK_SKIP_IMAGES 0x806D #define GL_UNPACK_IMAGE_HEIGHT 0x806E #define GL_TEXTURE_3D 0x806F #define GL_PROXY_TEXTURE_3D 0x8070 #define GL_TEXTURE_DEPTH 0x8071 #define GL_TEXTURE_WRAP_R 0x8072 #define GL_MAX_3D_TEXTURE_SIZE 0x8073 #define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 #define GL_UNSIGNED_SHORT_5_6_5 0x8363 #define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 #define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 #define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 #define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 #define GL_BGR 0x80E0 #define GL_BGRA 0x80E1 #define GL_MAX_ELEMENTS_VERTICES 0x80E8 #define GL_MAX_ELEMENTS_INDICES 0x80E9 #define GL_CLAMP_TO_EDGE 0x812F #define GL_TEXTURE_MIN_LOD 0x813A #define GL_TEXTURE_MAX_LOD 0x813B #define GL_TEXTURE_BASE_LEVEL 0x813C #define GL_TEXTURE_MAX_LEVEL 0x813D #define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 #define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 #define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 #define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 #define GL_ALIASED_LINE_WIDTH_RANGE 0x846E #define GL_RESCALE_NORMAL 0x803A #define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 #define GL_SINGLE_COLOR 0x81F9 #define GL_SEPARATE_SPECULAR_COLOR 0x81FA #define GL_ALIASED_POINT_SIZE_RANGE 0x846D #define GL_TEXTURE0 0x84C0 #define GL_TEXTURE1 0x84C1 #define GL_TEXTURE2 0x84C2 #define GL_TEXTURE3 0x84C3 #define GL_TEXTURE4 0x84C4 #define GL_TEXTURE5 0x84C5 #define GL_TEXTURE6 0x84C6 #define GL_TEXTURE7 0x84C7 #define GL_TEXTURE8 0x84C8 #define GL_TEXTURE9 0x84C9 #define GL_TEXTURE10 0x84CA #define GL_TEXTURE11 0x84CB #define GL_TEXTURE12 0x84CC #define GL_TEXTURE13 0x84CD #define GL_TEXTURE14 0x84CE #define GL_TEXTURE15 0x84CF #define GL_TEXTURE16 0x84D0 #define GL_TEXTURE17 0x84D1 #define GL_TEXTURE18 0x84D2 #define GL_TEXTURE19 0x84D3 #define GL_TEXTURE20 0x84D4 #define GL_TEXTURE21 0x84D5 #define GL_TEXTURE22 0x84D6 #define GL_TEXTURE23 0x84D7 #define GL_TEXTURE24 0x84D8 #define GL_TEXTURE25 0x84D9 #define GL_TEXTURE26 0x84DA #define GL_TEXTURE27 0x84DB #define GL_TEXTURE28 0x84DC #define GL_TEXTURE29 0x84DD #define GL_TEXTURE30 0x84DE #define GL_TEXTURE31 0x84DF #define GL_ACTIVE_TEXTURE 0x84E0 #define GL_MULTISAMPLE 0x809D #define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E #define GL_SAMPLE_ALPHA_TO_ONE 0x809F #define GL_SAMPLE_COVERAGE 0x80A0 #define GL_SAMPLE_BUFFERS 0x80A8 #define GL_SAMPLES 0x80A9 #define GL_SAMPLE_COVERAGE_VALUE 0x80AA #define GL_SAMPLE_COVERAGE_INVERT 0x80AB #define GL_TEXTURE_CUBE_MAP 0x8513 #define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 #define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 #define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 #define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A #define GL_PROXY_TEXTURE_CUBE_MAP 0x851B #define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C #define GL_COMPRESSED_RGB 0x84ED #define GL_COMPRESSED_RGBA 0x84EE #define GL_TEXTURE_COMPRESSION_HINT 0x84EF #define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 #define GL_TEXTURE_COMPRESSED 0x86A1 #define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 #define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 #define GL_CLAMP_TO_BORDER 0x812D #define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 #define GL_MAX_TEXTURE_UNITS 0x84E2 #define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3 #define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4 #define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5 #define GL_TRANSPOSE_COLOR_MATRIX 0x84E6 #define GL_MULTISAMPLE_BIT 0x20000000 #define GL_NORMAL_MAP 0x8511 #define GL_REFLECTION_MAP 0x8512 #define GL_COMPRESSED_ALPHA 0x84E9 #define GL_COMPRESSED_LUMINANCE 0x84EA #define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB #define GL_COMPRESSED_INTENSITY 0x84EC #define GL_COMBINE 0x8570 #define GL_COMBINE_RGB 0x8571 #define GL_COMBINE_ALPHA 0x8572 #define GL_SOURCE0_RGB 0x8580 #define GL_SOURCE1_RGB 0x8581 #define GL_SOURCE2_RGB 0x8582 #define GL_SOURCE0_ALPHA 0x8588 #define GL_SOURCE1_ALPHA 0x8589 #define GL_SOURCE2_ALPHA 0x858A #define GL_OPERAND0_RGB 0x8590 #define GL_OPERAND1_RGB 0x8591 #define GL_OPERAND2_RGB 0x8592 #define GL_OPERAND0_ALPHA 0x8598 #define GL_OPERAND1_ALPHA 0x8599 #define GL_OPERAND2_ALPHA 0x859A #define GL_RGB_SCALE 0x8573 #define GL_ADD_SIGNED 0x8574 #define GL_INTERPOLATE 0x8575 #define GL_SUBTRACT 0x84E7 #define GL_CONSTANT 0x8576 #define GL_PRIMARY_COLOR 0x8577 #define GL_PREVIOUS 0x8578 #define GL_DOT3_RGB 0x86AE #define GL_DOT3_RGBA 0x86AF #define GL_BLEND_DST_RGB 0x80C8 #define GL_BLEND_SRC_RGB 0x80C9 #define GL_BLEND_DST_ALPHA 0x80CA #define GL_BLEND_SRC_ALPHA 0x80CB #define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 #define GL_DEPTH_COMPONENT16 0x81A5 #define GL_DEPTH_COMPONENT24 0x81A6 #define GL_DEPTH_COMPONENT32 0x81A7 #define GL_MIRRORED_REPEAT 0x8370 #define GL_MAX_TEXTURE_LOD_BIAS 0x84FD #define GL_TEXTURE_LOD_BIAS 0x8501 #define GL_INCR_WRAP 0x8507 #define GL_DECR_WRAP 0x8508 #define GL_TEXTURE_DEPTH_SIZE 0x884A #define GL_TEXTURE_COMPARE_MODE 0x884C #define GL_TEXTURE_COMPARE_FUNC 0x884D #define GL_POINT_SIZE_MIN 0x8126 #define GL_POINT_SIZE_MAX 0x8127 #define GL_POINT_DISTANCE_ATTENUATION 0x8129 #define GL_GENERATE_MIPMAP 0x8191 #define GL_GENERATE_MIPMAP_HINT 0x8192 #define GL_FOG_COORDINATE_SOURCE 0x8450 #define GL_FOG_COORDINATE 0x8451 #define GL_FRAGMENT_DEPTH 0x8452 #define GL_CURRENT_FOG_COORDINATE 0x8453 #define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 #define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 #define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 #define GL_FOG_COORDINATE_ARRAY 0x8457 #define GL_COLOR_SUM 0x8458 #define GL_CURRENT_SECONDARY_COLOR 0x8459 #define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A #define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B #define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C #define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D #define GL_SECONDARY_COLOR_ARRAY 0x845E #define GL_TEXTURE_FILTER_CONTROL 0x8500 #define GL_DEPTH_TEXTURE_MODE 0x884B #define GL_COMPARE_R_TO_TEXTURE 0x884E #define GL_BLEND_COLOR 0x8005 #define GL_BLEND_EQUATION 0x8009 #define GL_CONSTANT_COLOR 0x8001 #define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 #define GL_CONSTANT_ALPHA 0x8003 #define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 #define GL_FUNC_ADD 0x8006 #define GL_FUNC_REVERSE_SUBTRACT 0x800B #define GL_FUNC_SUBTRACT 0x800A #define GL_MIN 0x8007 #define GL_MAX 0x8008 #define GL_BUFFER_SIZE 0x8764 #define GL_BUFFER_USAGE 0x8765 #define GL_QUERY_COUNTER_BITS 0x8864 #define GL_CURRENT_QUERY 0x8865 #define GL_QUERY_RESULT 0x8866 #define GL_QUERY_RESULT_AVAILABLE 0x8867 #define GL_ARRAY_BUFFER 0x8892 #define GL_ELEMENT_ARRAY_BUFFER 0x8893 #define GL_ARRAY_BUFFER_BINDING 0x8894 #define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 #define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F #define GL_READ_ONLY 0x88B8 #define GL_WRITE_ONLY 0x88B9 #define GL_READ_WRITE 0x88BA #define GL_BUFFER_ACCESS 0x88BB #define GL_BUFFER_MAPPED 0x88BC #define GL_BUFFER_MAP_POINTER 0x88BD #define GL_STREAM_DRAW 0x88E0 #define GL_STREAM_READ 0x88E1 #define GL_STREAM_COPY 0x88E2 #define GL_STATIC_DRAW 0x88E4 #define GL_STATIC_READ 0x88E5 #define GL_STATIC_COPY 0x88E6 #define GL_DYNAMIC_DRAW 0x88E8 #define GL_DYNAMIC_READ 0x88E9 #define GL_DYNAMIC_COPY 0x88EA #define GL_SAMPLES_PASSED 0x8914 #define GL_SRC1_ALPHA 0x8589 #define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 #define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 #define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 #define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899 #define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A #define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B #define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C #define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D #define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E #define GL_FOG_COORD_SRC 0x8450 #define GL_FOG_COORD 0x8451 #define GL_CURRENT_FOG_COORD 0x8453 #define GL_FOG_COORD_ARRAY_TYPE 0x8454 #define GL_FOG_COORD_ARRAY_STRIDE 0x8455 #define GL_FOG_COORD_ARRAY_POINTER 0x8456 #define GL_FOG_COORD_ARRAY 0x8457 #define GL_FOG_COORD_ARRAY_BUFFER_BINDING 0x889D #define GL_SRC0_RGB 0x8580 #define GL_SRC1_RGB 0x8581 #define GL_SRC2_RGB 0x8582 #define GL_SRC0_ALPHA 0x8588 #define GL_SRC2_ALPHA 0x858A #define GL_BLEND_EQUATION_RGB 0x8009 #define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 #define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 #define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 #define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 #define GL_CURRENT_VERTEX_ATTRIB 0x8626 #define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 #define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 #define GL_STENCIL_BACK_FUNC 0x8800 #define GL_STENCIL_BACK_FAIL 0x8801 #define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 #define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 #define GL_MAX_DRAW_BUFFERS 0x8824 #define GL_DRAW_BUFFER0 0x8825 #define GL_DRAW_BUFFER1 0x8826 #define GL_DRAW_BUFFER2 0x8827 #define GL_DRAW_BUFFER3 0x8828 #define GL_DRAW_BUFFER4 0x8829 #define GL_DRAW_BUFFER5 0x882A #define GL_DRAW_BUFFER6 0x882B #define GL_DRAW_BUFFER7 0x882C #define GL_DRAW_BUFFER8 0x882D #define GL_DRAW_BUFFER9 0x882E #define GL_DRAW_BUFFER10 0x882F #define GL_DRAW_BUFFER11 0x8830 #define GL_DRAW_BUFFER12 0x8831 #define GL_DRAW_BUFFER13 0x8832 #define GL_DRAW_BUFFER14 0x8833 #define GL_DRAW_BUFFER15 0x8834 #define GL_BLEND_EQUATION_ALPHA 0x883D #define GL_MAX_VERTEX_ATTRIBS 0x8869 #define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A #define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 #define GL_FRAGMENT_SHADER 0x8B30 #define GL_VERTEX_SHADER 0x8B31 #define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 #define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A #define GL_MAX_VARYING_FLOATS 0x8B4B #define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C #define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D #define GL_SHADER_TYPE 0x8B4F #define GL_FLOAT_VEC2 0x8B50 #define GL_FLOAT_VEC3 0x8B51 #define GL_FLOAT_VEC4 0x8B52 #define GL_INT_VEC2 0x8B53 #define GL_INT_VEC3 0x8B54 #define GL_INT_VEC4 0x8B55 #define GL_BOOL 0x8B56 #define GL_BOOL_VEC2 0x8B57 #define GL_BOOL_VEC3 0x8B58 #define GL_BOOL_VEC4 0x8B59 #define GL_FLOAT_MAT2 0x8B5A #define GL_FLOAT_MAT3 0x8B5B #define GL_FLOAT_MAT4 0x8B5C #define GL_SAMPLER_1D 0x8B5D #define GL_SAMPLER_2D 0x8B5E #define GL_SAMPLER_3D 0x8B5F #define GL_SAMPLER_CUBE 0x8B60 #define GL_SAMPLER_1D_SHADOW 0x8B61 #define GL_SAMPLER_2D_SHADOW 0x8B62 #define GL_DELETE_STATUS 0x8B80 #define GL_COMPILE_STATUS 0x8B81 #define GL_LINK_STATUS 0x8B82 #define GL_VALIDATE_STATUS 0x8B83 #define GL_INFO_LOG_LENGTH 0x8B84 #define GL_ATTACHED_SHADERS 0x8B85 #define GL_ACTIVE_UNIFORMS 0x8B86 #define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 #define GL_SHADER_SOURCE_LENGTH 0x8B88 #define GL_ACTIVE_ATTRIBUTES 0x8B89 #define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A #define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B #define GL_SHADING_LANGUAGE_VERSION 0x8B8C #define GL_CURRENT_PROGRAM 0x8B8D #define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 #define GL_LOWER_LEFT 0x8CA1 #define GL_UPPER_LEFT 0x8CA2 #define GL_STENCIL_BACK_REF 0x8CA3 #define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 #define GL_STENCIL_BACK_WRITEMASK 0x8CA5 #define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643 #define GL_POINT_SPRITE 0x8861 #define GL_COORD_REPLACE 0x8862 #define GL_MAX_TEXTURE_COORDS 0x8871 #define GL_PIXEL_PACK_BUFFER 0x88EB #define GL_PIXEL_UNPACK_BUFFER 0x88EC #define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED #define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF #define GL_FLOAT_MAT2x3 0x8B65 #define GL_FLOAT_MAT2x4 0x8B66 #define GL_FLOAT_MAT3x2 0x8B67 #define GL_FLOAT_MAT3x4 0x8B68 #define GL_FLOAT_MAT4x2 0x8B69 #define GL_FLOAT_MAT4x3 0x8B6A #define GL_SRGB 0x8C40 #define GL_SRGB8 0x8C41 #define GL_SRGB_ALPHA 0x8C42 #define GL_SRGB8_ALPHA8 0x8C43 #define GL_COMPRESSED_SRGB 0x8C48 #define GL_COMPRESSED_SRGB_ALPHA 0x8C49 #define GL_CURRENT_RASTER_SECONDARY_COLOR 0x845F #define GL_SLUMINANCE_ALPHA 0x8C44 #define GL_SLUMINANCE8_ALPHA8 0x8C45 #define GL_SLUMINANCE 0x8C46 #define GL_SLUMINANCE8 0x8C47 #define GL_COMPRESSED_SLUMINANCE 0x8C4A #define GL_COMPRESSED_SLUMINANCE_ALPHA 0x8C4B #define GL_COMPARE_REF_TO_TEXTURE 0x884E #define GL_CLIP_DISTANCE0 0x3000 #define GL_CLIP_DISTANCE1 0x3001 #define GL_CLIP_DISTANCE2 0x3002 #define GL_CLIP_DISTANCE3 0x3003 #define GL_CLIP_DISTANCE4 0x3004 #define GL_CLIP_DISTANCE5 0x3005 #define GL_CLIP_DISTANCE6 0x3006 #define GL_CLIP_DISTANCE7 0x3007 #define GL_MAX_CLIP_DISTANCES 0x0D32 #define GL_MAJOR_VERSION 0x821B #define GL_MINOR_VERSION 0x821C #define GL_NUM_EXTENSIONS 0x821D #define GL_CONTEXT_FLAGS 0x821E #define GL_COMPRESSED_RED 0x8225 #define GL_COMPRESSED_RG 0x8226 #define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x00000001 #define GL_RGBA32F 0x8814 #define GL_RGB32F 0x8815 #define GL_RGBA16F 0x881A #define GL_RGB16F 0x881B #define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD #define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF #define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 #define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 #define GL_CLAMP_READ_COLOR 0x891C #define GL_FIXED_ONLY 0x891D #define GL_MAX_VARYING_COMPONENTS 0x8B4B #define GL_TEXTURE_1D_ARRAY 0x8C18 #define GL_PROXY_TEXTURE_1D_ARRAY 0x8C19 #define GL_TEXTURE_2D_ARRAY 0x8C1A #define GL_PROXY_TEXTURE_2D_ARRAY 0x8C1B #define GL_TEXTURE_BINDING_1D_ARRAY 0x8C1C #define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D #define GL_R11F_G11F_B10F 0x8C3A #define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B #define GL_RGB9_E5 0x8C3D #define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E #define GL_TEXTURE_SHARED_SIZE 0x8C3F #define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 #define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F #define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 #define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 #define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 #define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 #define GL_PRIMITIVES_GENERATED 0x8C87 #define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 #define GL_RASTERIZER_DISCARD 0x8C89 #define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A #define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B #define GL_INTERLEAVED_ATTRIBS 0x8C8C #define GL_SEPARATE_ATTRIBS 0x8C8D #define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E #define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F #define GL_RGBA32UI 0x8D70 #define GL_RGB32UI 0x8D71 #define GL_RGBA16UI 0x8D76 #define GL_RGB16UI 0x8D77 #define GL_RGBA8UI 0x8D7C #define GL_RGB8UI 0x8D7D #define GL_RGBA32I 0x8D82 #define GL_RGB32I 0x8D83 #define GL_RGBA16I 0x8D88 #define GL_RGB16I 0x8D89 #define GL_RGBA8I 0x8D8E #define GL_RGB8I 0x8D8F #define GL_RED_INTEGER 0x8D94 #define GL_GREEN_INTEGER 0x8D95 #define GL_BLUE_INTEGER 0x8D96 #define GL_RGB_INTEGER 0x8D98 #define GL_RGBA_INTEGER 0x8D99 #define GL_BGR_INTEGER 0x8D9A #define GL_BGRA_INTEGER 0x8D9B #define GL_SAMPLER_1D_ARRAY 0x8DC0 #define GL_SAMPLER_2D_ARRAY 0x8DC1 #define GL_SAMPLER_1D_ARRAY_SHADOW 0x8DC3 #define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 #define GL_SAMPLER_CUBE_SHADOW 0x8DC5 #define GL_UNSIGNED_INT_VEC2 0x8DC6 #define GL_UNSIGNED_INT_VEC3 0x8DC7 #define GL_UNSIGNED_INT_VEC4 0x8DC8 #define GL_INT_SAMPLER_1D 0x8DC9 #define GL_INT_SAMPLER_2D 0x8DCA #define GL_INT_SAMPLER_3D 0x8DCB #define GL_INT_SAMPLER_CUBE 0x8DCC #define GL_INT_SAMPLER_1D_ARRAY 0x8DCE #define GL_INT_SAMPLER_2D_ARRAY 0x8DCF #define GL_UNSIGNED_INT_SAMPLER_1D 0x8DD1 #define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 #define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 #define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 #define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY 0x8DD6 #define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 #define GL_QUERY_WAIT 0x8E13 #define GL_QUERY_NO_WAIT 0x8E14 #define GL_QUERY_BY_REGION_WAIT 0x8E15 #define GL_QUERY_BY_REGION_NO_WAIT 0x8E16 #define GL_BUFFER_ACCESS_FLAGS 0x911F #define GL_BUFFER_MAP_LENGTH 0x9120 #define GL_BUFFER_MAP_OFFSET 0x9121 #define GL_DEPTH_COMPONENT32F 0x8CAC #define GL_DEPTH32F_STENCIL8 0x8CAD #define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD #define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 #define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 #define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 #define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 #define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 #define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 #define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 #define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 #define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 #define GL_FRAMEBUFFER_DEFAULT 0x8218 #define GL_FRAMEBUFFER_UNDEFINED 0x8219 #define GL_DEPTH_STENCIL_ATTACHMENT 0x821A #define GL_MAX_RENDERBUFFER_SIZE 0x84E8 #define GL_DEPTH_STENCIL 0x84F9 #define GL_UNSIGNED_INT_24_8 0x84FA #define GL_DEPTH24_STENCIL8 0x88F0 #define GL_TEXTURE_STENCIL_SIZE 0x88F1 #define GL_TEXTURE_RED_TYPE 0x8C10 #define GL_TEXTURE_GREEN_TYPE 0x8C11 #define GL_TEXTURE_BLUE_TYPE 0x8C12 #define GL_TEXTURE_ALPHA_TYPE 0x8C13 #define GL_TEXTURE_DEPTH_TYPE 0x8C16 #define GL_UNSIGNED_NORMALIZED 0x8C17 #define GL_FRAMEBUFFER_BINDING 0x8CA6 #define GL_DRAW_FRAMEBUFFER_BINDING 0x8CA6 #define GL_RENDERBUFFER_BINDING 0x8CA7 #define GL_READ_FRAMEBUFFER 0x8CA8 #define GL_DRAW_FRAMEBUFFER 0x8CA9 #define GL_READ_FRAMEBUFFER_BINDING 0x8CAA #define GL_RENDERBUFFER_SAMPLES 0x8CAB #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 #define GL_FRAMEBUFFER_COMPLETE 0x8CD5 #define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 #define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 #define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB #define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC #define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD #define GL_MAX_COLOR_ATTACHMENTS 0x8CDF #define GL_COLOR_ATTACHMENT0 0x8CE0 #define GL_COLOR_ATTACHMENT1 0x8CE1 #define GL_COLOR_ATTACHMENT2 0x8CE2 #define GL_COLOR_ATTACHMENT3 0x8CE3 #define GL_COLOR_ATTACHMENT4 0x8CE4 #define GL_COLOR_ATTACHMENT5 0x8CE5 #define GL_COLOR_ATTACHMENT6 0x8CE6 #define GL_COLOR_ATTACHMENT7 0x8CE7 #define GL_COLOR_ATTACHMENT8 0x8CE8 #define GL_COLOR_ATTACHMENT9 0x8CE9 #define GL_COLOR_ATTACHMENT10 0x8CEA #define GL_COLOR_ATTACHMENT11 0x8CEB #define GL_COLOR_ATTACHMENT12 0x8CEC #define GL_COLOR_ATTACHMENT13 0x8CED #define GL_COLOR_ATTACHMENT14 0x8CEE #define GL_COLOR_ATTACHMENT15 0x8CEF #define GL_COLOR_ATTACHMENT16 0x8CF0 #define GL_COLOR_ATTACHMENT17 0x8CF1 #define GL_COLOR_ATTACHMENT18 0x8CF2 #define GL_COLOR_ATTACHMENT19 0x8CF3 #define GL_COLOR_ATTACHMENT20 0x8CF4 #define GL_COLOR_ATTACHMENT21 0x8CF5 #define GL_COLOR_ATTACHMENT22 0x8CF6 #define GL_COLOR_ATTACHMENT23 0x8CF7 #define GL_COLOR_ATTACHMENT24 0x8CF8 #define GL_COLOR_ATTACHMENT25 0x8CF9 #define GL_COLOR_ATTACHMENT26 0x8CFA #define GL_COLOR_ATTACHMENT27 0x8CFB #define GL_COLOR_ATTACHMENT28 0x8CFC #define GL_COLOR_ATTACHMENT29 0x8CFD #define GL_COLOR_ATTACHMENT30 0x8CFE #define GL_COLOR_ATTACHMENT31 0x8CFF #define GL_DEPTH_ATTACHMENT 0x8D00 #define GL_STENCIL_ATTACHMENT 0x8D20 #define GL_FRAMEBUFFER 0x8D40 #define GL_RENDERBUFFER 0x8D41 #define GL_RENDERBUFFER_WIDTH 0x8D42 #define GL_RENDERBUFFER_HEIGHT 0x8D43 #define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 #define GL_STENCIL_INDEX1 0x8D46 #define GL_STENCIL_INDEX4 0x8D47 #define GL_STENCIL_INDEX8 0x8D48 #define GL_STENCIL_INDEX16 0x8D49 #define GL_RENDERBUFFER_RED_SIZE 0x8D50 #define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 #define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 #define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 #define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 #define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 #define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 #define GL_MAX_SAMPLES 0x8D57 #define GL_INDEX 0x8222 #define GL_TEXTURE_LUMINANCE_TYPE 0x8C14 #define GL_TEXTURE_INTENSITY_TYPE 0x8C15 #define GL_FRAMEBUFFER_SRGB 0x8DB9 #define GL_HALF_FLOAT 0x140B #define GL_MAP_READ_BIT 0x0001 #define GL_MAP_WRITE_BIT 0x0002 #define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 #define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 #define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 #define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 #define GL_COMPRESSED_RED_RGTC1 0x8DBB #define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC #define GL_COMPRESSED_RG_RGTC2 0x8DBD #define GL_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE #define GL_RG 0x8227 #define GL_RG_INTEGER 0x8228 #define GL_R8 0x8229 #define GL_R16 0x822A #define GL_RG8 0x822B #define GL_RG16 0x822C #define GL_R16F 0x822D #define GL_R32F 0x822E #define GL_RG16F 0x822F #define GL_RG32F 0x8230 #define GL_R8I 0x8231 #define GL_R8UI 0x8232 #define GL_R16I 0x8233 #define GL_R16UI 0x8234 #define GL_R32I 0x8235 #define GL_R32UI 0x8236 #define GL_RG8I 0x8237 #define GL_RG8UI 0x8238 #define GL_RG16I 0x8239 #define GL_RG16UI 0x823A #define GL_RG32I 0x823B #define GL_RG32UI 0x823C #define GL_VERTEX_ARRAY_BINDING 0x85B5 #define GL_CLAMP_VERTEX_COLOR 0x891A #define GL_CLAMP_FRAGMENT_COLOR 0x891B #define GL_ALPHA_INTEGER 0x8D97 #define GL_SAMPLER_2D_RECT 0x8B63 #define GL_SAMPLER_2D_RECT_SHADOW 0x8B64 #define GL_SAMPLER_BUFFER 0x8DC2 #define GL_INT_SAMPLER_2D_RECT 0x8DCD #define GL_INT_SAMPLER_BUFFER 0x8DD0 #define GL_UNSIGNED_INT_SAMPLER_2D_RECT 0x8DD5 #define GL_UNSIGNED_INT_SAMPLER_BUFFER 0x8DD8 #define GL_TEXTURE_BUFFER 0x8C2A #define GL_MAX_TEXTURE_BUFFER_SIZE 0x8C2B #define GL_TEXTURE_BINDING_BUFFER 0x8C2C #define GL_TEXTURE_BUFFER_DATA_STORE_BINDING 0x8C2D #define GL_TEXTURE_RECTANGLE 0x84F5 #define GL_TEXTURE_BINDING_RECTANGLE 0x84F6 #define GL_PROXY_TEXTURE_RECTANGLE 0x84F7 #define GL_MAX_RECTANGLE_TEXTURE_SIZE 0x84F8 #define GL_R8_SNORM 0x8F94 #define GL_RG8_SNORM 0x8F95 #define GL_RGB8_SNORM 0x8F96 #define GL_RGBA8_SNORM 0x8F97 #define GL_R16_SNORM 0x8F98 #define GL_RG16_SNORM 0x8F99 #define GL_RGB16_SNORM 0x8F9A #define GL_RGBA16_SNORM 0x8F9B #define GL_SIGNED_NORMALIZED 0x8F9C #define GL_PRIMITIVE_RESTART 0x8F9D #define GL_PRIMITIVE_RESTART_INDEX 0x8F9E #define GL_COPY_READ_BUFFER 0x8F36 #define GL_COPY_WRITE_BUFFER 0x8F37 #define GL_UNIFORM_BUFFER 0x8A11 #define GL_UNIFORM_BUFFER_BINDING 0x8A28 #define GL_UNIFORM_BUFFER_START 0x8A29 #define GL_UNIFORM_BUFFER_SIZE 0x8A2A #define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B #define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C #define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D #define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E #define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F #define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 #define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 #define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32 #define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 #define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 #define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 #define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 #define GL_UNIFORM_TYPE 0x8A37 #define GL_UNIFORM_SIZE 0x8A38 #define GL_UNIFORM_NAME_LENGTH 0x8A39 #define GL_UNIFORM_BLOCK_INDEX 0x8A3A #define GL_UNIFORM_OFFSET 0x8A3B #define GL_UNIFORM_ARRAY_STRIDE 0x8A3C #define GL_UNIFORM_MATRIX_STRIDE 0x8A3D #define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E #define GL_UNIFORM_BLOCK_BINDING 0x8A3F #define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 #define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 #define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 #define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 #define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 #define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45 #define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 #define GL_INVALID_INDEX 0xFFFFFFFF #define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001 #define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 #define GL_LINES_ADJACENCY 0x000A #define GL_LINE_STRIP_ADJACENCY 0x000B #define GL_TRIANGLES_ADJACENCY 0x000C #define GL_TRIANGLE_STRIP_ADJACENCY 0x000D #define GL_PROGRAM_POINT_SIZE 0x8642 #define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS 0x8C29 #define GL_FRAMEBUFFER_ATTACHMENT_LAYERED 0x8DA7 #define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS 0x8DA8 #define GL_GEOMETRY_SHADER 0x8DD9 #define GL_GEOMETRY_VERTICES_OUT 0x8916 #define GL_GEOMETRY_INPUT_TYPE 0x8917 #define GL_GEOMETRY_OUTPUT_TYPE 0x8918 #define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS 0x8DDF #define GL_MAX_GEOMETRY_OUTPUT_VERTICES 0x8DE0 #define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS 0x8DE1 #define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 #define GL_MAX_GEOMETRY_INPUT_COMPONENTS 0x9123 #define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS 0x9124 #define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 #define GL_CONTEXT_PROFILE_MASK 0x9126 #define GL_DEPTH_CLAMP 0x864F #define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION 0x8E4C #define GL_FIRST_VERTEX_CONVENTION 0x8E4D #define GL_LAST_VERTEX_CONVENTION 0x8E4E #define GL_PROVOKING_VERTEX 0x8E4F #define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F #define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 #define GL_OBJECT_TYPE 0x9112 #define GL_SYNC_CONDITION 0x9113 #define GL_SYNC_STATUS 0x9114 #define GL_SYNC_FLAGS 0x9115 #define GL_SYNC_FENCE 0x9116 #define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 #define GL_UNSIGNALED 0x9118 #define GL_SIGNALED 0x9119 #define GL_ALREADY_SIGNALED 0x911A #define GL_TIMEOUT_EXPIRED 0x911B #define GL_CONDITION_SATISFIED 0x911C #define GL_WAIT_FAILED 0x911D #define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFF #define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 #define GL_SAMPLE_POSITION 0x8E50 #define GL_SAMPLE_MASK 0x8E51 #define GL_SAMPLE_MASK_VALUE 0x8E52 #define GL_MAX_SAMPLE_MASK_WORDS 0x8E59 #define GL_TEXTURE_2D_MULTISAMPLE 0x9100 #define GL_PROXY_TEXTURE_2D_MULTISAMPLE 0x9101 #define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102 #define GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9103 #define GL_TEXTURE_BINDING_2D_MULTISAMPLE 0x9104 #define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY 0x9105 #define GL_TEXTURE_SAMPLES 0x9106 #define GL_TEXTURE_FIXED_SAMPLE_LOCATIONS 0x9107 #define GL_SAMPLER_2D_MULTISAMPLE 0x9108 #define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 #define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A #define GL_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910B #define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C #define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D #define GL_MAX_COLOR_TEXTURE_SAMPLES 0x910E #define GL_MAX_DEPTH_TEXTURE_SAMPLES 0x910F #define GL_MAX_INTEGER_SAMPLES 0x9110 #define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE #define GL_SRC1_COLOR 0x88F9 #define GL_ONE_MINUS_SRC1_COLOR 0x88FA #define GL_ONE_MINUS_SRC1_ALPHA 0x88FB #define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS 0x88FC #define GL_ANY_SAMPLES_PASSED 0x8C2F #define GL_SAMPLER_BINDING 0x8919 #define GL_RGB10_A2UI 0x906F #define GL_TEXTURE_SWIZZLE_R 0x8E42 #define GL_TEXTURE_SWIZZLE_G 0x8E43 #define GL_TEXTURE_SWIZZLE_B 0x8E44 #define GL_TEXTURE_SWIZZLE_A 0x8E45 #define GL_TEXTURE_SWIZZLE_RGBA 0x8E46 #define GL_TIME_ELAPSED 0x88BF #define GL_TIMESTAMP 0x8E28 #define GL_INT_2_10_10_10_REV 0x8D9F #define GL_SAMPLE_SHADING 0x8C36 #define GL_MIN_SAMPLE_SHADING_VALUE 0x8C37 #define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5E #define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5F #define GL_TEXTURE_CUBE_MAP_ARRAY 0x9009 #define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY 0x900A #define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY 0x900B #define GL_SAMPLER_CUBE_MAP_ARRAY 0x900C #define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW 0x900D #define GL_INT_SAMPLER_CUBE_MAP_ARRAY 0x900E #define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY 0x900F #define GL_DRAW_INDIRECT_BUFFER 0x8F3F #define GL_DRAW_INDIRECT_BUFFER_BINDING 0x8F43 #define GL_GEOMETRY_SHADER_INVOCATIONS 0x887F #define GL_MAX_GEOMETRY_SHADER_INVOCATIONS 0x8E5A #define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET 0x8E5B #define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET 0x8E5C #define GL_FRAGMENT_INTERPOLATION_OFFSET_BITS 0x8E5D #define GL_MAX_VERTEX_STREAMS 0x8E71 #define GL_DOUBLE_VEC2 0x8FFC #define GL_DOUBLE_VEC3 0x8FFD #define GL_DOUBLE_VEC4 0x8FFE #define GL_DOUBLE_MAT2 0x8F46 #define GL_DOUBLE_MAT3 0x8F47 #define GL_DOUBLE_MAT4 0x8F48 #define GL_DOUBLE_MAT2x3 0x8F49 #define GL_DOUBLE_MAT2x4 0x8F4A #define GL_DOUBLE_MAT3x2 0x8F4B #define GL_DOUBLE_MAT3x4 0x8F4C #define GL_DOUBLE_MAT4x2 0x8F4D #define GL_DOUBLE_MAT4x3 0x8F4E #define GL_ACTIVE_SUBROUTINES 0x8DE5 #define GL_ACTIVE_SUBROUTINE_UNIFORMS 0x8DE6 #define GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS 0x8E47 #define GL_ACTIVE_SUBROUTINE_MAX_LENGTH 0x8E48 #define GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH 0x8E49 #define GL_MAX_SUBROUTINES 0x8DE7 #define GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS 0x8DE8 #define GL_NUM_COMPATIBLE_SUBROUTINES 0x8E4A #define GL_COMPATIBLE_SUBROUTINES 0x8E4B #define GL_PATCHES 0x000E #define GL_PATCH_VERTICES 0x8E72 #define GL_PATCH_DEFAULT_INNER_LEVEL 0x8E73 #define GL_PATCH_DEFAULT_OUTER_LEVEL 0x8E74 #define GL_TESS_CONTROL_OUTPUT_VERTICES 0x8E75 #define GL_TESS_GEN_MODE 0x8E76 #define GL_TESS_GEN_SPACING 0x8E77 #define GL_TESS_GEN_VERTEX_ORDER 0x8E78 #define GL_TESS_GEN_POINT_MODE 0x8E79 #define GL_ISOLINES 0x8E7A #define GL_FRACTIONAL_ODD 0x8E7B #define GL_FRACTIONAL_EVEN 0x8E7C #define GL_MAX_PATCH_VERTICES 0x8E7D #define GL_MAX_TESS_GEN_LEVEL 0x8E7E #define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E7F #define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E80 #define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS 0x8E81 #define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS 0x8E82 #define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS 0x8E83 #define GL_MAX_TESS_PATCH_COMPONENTS 0x8E84 #define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS 0x8E85 #define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS 0x8E86 #define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS 0x8E89 #define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS 0x8E8A #define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS 0x886C #define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS 0x886D #define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E1E #define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E1F #define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER 0x84F0 #define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER 0x84F1 #define GL_TESS_EVALUATION_SHADER 0x8E87 #define GL_TESS_CONTROL_SHADER 0x8E88 #define GL_TRANSFORM_FEEDBACK 0x8E22 #define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED 0x8E23 #define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE 0x8E24 #define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25 #define GL_MAX_TRANSFORM_FEEDBACK_BUFFERS 0x8E70 #define GL_FIXED 0x140C #define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A #define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B #define GL_LOW_FLOAT 0x8DF0 #define GL_MEDIUM_FLOAT 0x8DF1 #define GL_HIGH_FLOAT 0x8DF2 #define GL_LOW_INT 0x8DF3 #define GL_MEDIUM_INT 0x8DF4 #define GL_HIGH_INT 0x8DF5 #define GL_SHADER_COMPILER 0x8DFA #define GL_SHADER_BINARY_FORMATS 0x8DF8 #define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 #define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB #define GL_MAX_VARYING_VECTORS 0x8DFC #define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD #define GL_RGB565 0x8D62 #define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257 #define GL_PROGRAM_BINARY_LENGTH 0x8741 #define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE #define GL_PROGRAM_BINARY_FORMATS 0x87FF #define GL_VERTEX_SHADER_BIT 0x00000001 #define GL_FRAGMENT_SHADER_BIT 0x00000002 #define GL_GEOMETRY_SHADER_BIT 0x00000004 #define GL_TESS_CONTROL_SHADER_BIT 0x00000008 #define GL_TESS_EVALUATION_SHADER_BIT 0x00000010 #define GL_ALL_SHADER_BITS 0xFFFFFFFF #define GL_PROGRAM_SEPARABLE 0x8258 #define GL_ACTIVE_PROGRAM 0x8259 #define GL_PROGRAM_PIPELINE_BINDING 0x825A #define GL_MAX_VIEWPORTS 0x825B #define GL_VIEWPORT_SUBPIXEL_BITS 0x825C #define GL_VIEWPORT_BOUNDS_RANGE 0x825D #define GL_LAYER_PROVOKING_VERTEX 0x825E #define GL_VIEWPORT_INDEX_PROVOKING_VERTEX 0x825F #define GL_UNDEFINED_VERTEX 0x8260 #define GL_COPY_READ_BUFFER_BINDING 0x8F36 #define GL_COPY_WRITE_BUFFER_BINDING 0x8F37 #define GL_TRANSFORM_FEEDBACK_ACTIVE 0x8E24 #define GL_TRANSFORM_FEEDBACK_PAUSED 0x8E23 #define GL_UNPACK_COMPRESSED_BLOCK_WIDTH 0x9127 #define GL_UNPACK_COMPRESSED_BLOCK_HEIGHT 0x9128 #define GL_UNPACK_COMPRESSED_BLOCK_DEPTH 0x9129 #define GL_UNPACK_COMPRESSED_BLOCK_SIZE 0x912A #define GL_PACK_COMPRESSED_BLOCK_WIDTH 0x912B #define GL_PACK_COMPRESSED_BLOCK_HEIGHT 0x912C #define GL_PACK_COMPRESSED_BLOCK_DEPTH 0x912D #define GL_PACK_COMPRESSED_BLOCK_SIZE 0x912E #define GL_NUM_SAMPLE_COUNTS 0x9380 #define GL_MIN_MAP_BUFFER_ALIGNMENT 0x90BC #define GL_ATOMIC_COUNTER_BUFFER 0x92C0 #define GL_ATOMIC_COUNTER_BUFFER_BINDING 0x92C1 #define GL_ATOMIC_COUNTER_BUFFER_START 0x92C2 #define GL_ATOMIC_COUNTER_BUFFER_SIZE 0x92C3 #define GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE 0x92C4 #define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS 0x92C5 #define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES 0x92C6 #define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER 0x92C7 #define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER 0x92C8 #define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER 0x92C9 #define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER 0x92CA #define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER 0x92CB #define GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS 0x92CC #define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS 0x92CD #define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS 0x92CE #define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS 0x92CF #define GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS 0x92D0 #define GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS 0x92D1 #define GL_MAX_VERTEX_ATOMIC_COUNTERS 0x92D2 #define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS 0x92D3 #define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS 0x92D4 #define GL_MAX_GEOMETRY_ATOMIC_COUNTERS 0x92D5 #define GL_MAX_FRAGMENT_ATOMIC_COUNTERS 0x92D6 #define GL_MAX_COMBINED_ATOMIC_COUNTERS 0x92D7 #define GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE 0x92D8 #define GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS 0x92DC #define GL_ACTIVE_ATOMIC_COUNTER_BUFFERS 0x92D9 #define GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX 0x92DA #define GL_UNSIGNED_INT_ATOMIC_COUNTER 0x92DB #define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001 #define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002 #define GL_UNIFORM_BARRIER_BIT 0x00000004 #define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008 #define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020 #define GL_COMMAND_BARRIER_BIT 0x00000040 #define GL_PIXEL_BUFFER_BARRIER_BIT 0x00000080 #define GL_TEXTURE_UPDATE_BARRIER_BIT 0x00000100 #define GL_BUFFER_UPDATE_BARRIER_BIT 0x00000200 #define GL_FRAMEBUFFER_BARRIER_BIT 0x00000400 #define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800 #define GL_ATOMIC_COUNTER_BARRIER_BIT 0x00001000 #define GL_ALL_BARRIER_BITS 0xFFFFFFFF #define GL_MAX_IMAGE_UNITS 0x8F38 #define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS 0x8F39 #define GL_IMAGE_BINDING_NAME 0x8F3A #define GL_IMAGE_BINDING_LEVEL 0x8F3B #define GL_IMAGE_BINDING_LAYERED 0x8F3C #define GL_IMAGE_BINDING_LAYER 0x8F3D #define GL_IMAGE_BINDING_ACCESS 0x8F3E #define GL_IMAGE_1D 0x904C #define GL_IMAGE_2D 0x904D #define GL_IMAGE_3D 0x904E #define GL_IMAGE_2D_RECT 0x904F #define GL_IMAGE_CUBE 0x9050 #define GL_IMAGE_BUFFER 0x9051 #define GL_IMAGE_1D_ARRAY 0x9052 #define GL_IMAGE_2D_ARRAY 0x9053 #define GL_IMAGE_CUBE_MAP_ARRAY 0x9054 #define GL_IMAGE_2D_MULTISAMPLE 0x9055 #define GL_IMAGE_2D_MULTISAMPLE_ARRAY 0x9056 #define GL_INT_IMAGE_1D 0x9057 #define GL_INT_IMAGE_2D 0x9058 #define GL_INT_IMAGE_3D 0x9059 #define GL_INT_IMAGE_2D_RECT 0x905A #define GL_INT_IMAGE_CUBE 0x905B #define GL_INT_IMAGE_BUFFER 0x905C #define GL_INT_IMAGE_1D_ARRAY 0x905D #define GL_INT_IMAGE_2D_ARRAY 0x905E #define GL_INT_IMAGE_CUBE_MAP_ARRAY 0x905F #define GL_INT_IMAGE_2D_MULTISAMPLE 0x9060 #define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x9061 #define GL_UNSIGNED_INT_IMAGE_1D 0x9062 #define GL_UNSIGNED_INT_IMAGE_2D 0x9063 #define GL_UNSIGNED_INT_IMAGE_3D 0x9064 #define GL_UNSIGNED_INT_IMAGE_2D_RECT 0x9065 #define GL_UNSIGNED_INT_IMAGE_CUBE 0x9066 #define GL_UNSIGNED_INT_IMAGE_BUFFER 0x9067 #define GL_UNSIGNED_INT_IMAGE_1D_ARRAY 0x9068 #define GL_UNSIGNED_INT_IMAGE_2D_ARRAY 0x9069 #define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A #define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE 0x906B #define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x906C #define GL_MAX_IMAGE_SAMPLES 0x906D #define GL_IMAGE_BINDING_FORMAT 0x906E #define GL_IMAGE_FORMAT_COMPATIBILITY_TYPE 0x90C7 #define GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE 0x90C8 #define GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS 0x90C9 #define GL_MAX_VERTEX_IMAGE_UNIFORMS 0x90CA #define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS 0x90CB #define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS 0x90CC #define GL_MAX_GEOMETRY_IMAGE_UNIFORMS 0x90CD #define GL_MAX_FRAGMENT_IMAGE_UNIFORMS 0x90CE #define GL_MAX_COMBINED_IMAGE_UNIFORMS 0x90CF #define GL_COMPRESSED_RGBA_BPTC_UNORM 0x8E8C #define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM 0x8E8D #define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT 0x8E8E #define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT 0x8E8F #define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F #define GL_NUM_SHADING_LANGUAGE_VERSIONS 0x82E9 #define GL_VERTEX_ATTRIB_ARRAY_LONG 0x874E #define GL_COMPRESSED_RGB8_ETC2 0x9274 #define GL_COMPRESSED_SRGB8_ETC2 0x9275 #define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276 #define GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277 #define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 #define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279 #define GL_COMPRESSED_R11_EAC 0x9270 #define GL_COMPRESSED_SIGNED_R11_EAC 0x9271 #define GL_COMPRESSED_RG11_EAC 0x9272 #define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273 #define GL_PRIMITIVE_RESTART_FIXED_INDEX 0x8D69 #define GL_ANY_SAMPLES_PASSED_CONSERVATIVE 0x8D6A #define GL_MAX_ELEMENT_INDEX 0x8D6B #define GL_COMPUTE_SHADER 0x91B9 #define GL_MAX_COMPUTE_UNIFORM_BLOCKS 0x91BB #define GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS 0x91BC #define GL_MAX_COMPUTE_IMAGE_UNIFORMS 0x91BD #define GL_MAX_COMPUTE_SHARED_MEMORY_SIZE 0x8262 #define GL_MAX_COMPUTE_UNIFORM_COMPONENTS 0x8263 #define GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS 0x8264 #define GL_MAX_COMPUTE_ATOMIC_COUNTERS 0x8265 #define GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS 0x8266 #define GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS 0x90EB #define GL_MAX_COMPUTE_WORK_GROUP_COUNT 0x91BE #define GL_MAX_COMPUTE_WORK_GROUP_SIZE 0x91BF #define GL_COMPUTE_WORK_GROUP_SIZE 0x8267 #define GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER 0x90EC #define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER 0x90ED #define GL_DISPATCH_INDIRECT_BUFFER 0x90EE #define GL_DISPATCH_INDIRECT_BUFFER_BINDING 0x90EF #define GL_COMPUTE_SHADER_BIT 0x00000020 #define GL_DEBUG_OUTPUT_SYNCHRONOUS 0x8242 #define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH 0x8243 #define GL_DEBUG_CALLBACK_FUNCTION 0x8244 #define GL_DEBUG_CALLBACK_USER_PARAM 0x8245 #define GL_DEBUG_SOURCE_API 0x8246 #define GL_DEBUG_SOURCE_WINDOW_SYSTEM 0x8247 #define GL_DEBUG_SOURCE_SHADER_COMPILER 0x8248 #define GL_DEBUG_SOURCE_THIRD_PARTY 0x8249 #define GL_DEBUG_SOURCE_APPLICATION 0x824A #define GL_DEBUG_SOURCE_OTHER 0x824B #define GL_DEBUG_TYPE_ERROR 0x824C #define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR 0x824D #define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR 0x824E #define GL_DEBUG_TYPE_PORTABILITY 0x824F #define GL_DEBUG_TYPE_PERFORMANCE 0x8250 #define GL_DEBUG_TYPE_OTHER 0x8251 #define GL_MAX_DEBUG_MESSAGE_LENGTH 0x9143 #define GL_MAX_DEBUG_LOGGED_MESSAGES 0x9144 #define GL_DEBUG_LOGGED_MESSAGES 0x9145 #define GL_DEBUG_SEVERITY_HIGH 0x9146 #define GL_DEBUG_SEVERITY_MEDIUM 0x9147 #define GL_DEBUG_SEVERITY_LOW 0x9148 #define GL_DEBUG_TYPE_MARKER 0x8268 #define GL_DEBUG_TYPE_PUSH_GROUP 0x8269 #define GL_DEBUG_TYPE_POP_GROUP 0x826A #define GL_DEBUG_SEVERITY_NOTIFICATION 0x826B #define GL_MAX_DEBUG_GROUP_STACK_DEPTH 0x826C #define GL_DEBUG_GROUP_STACK_DEPTH 0x826D #define GL_BUFFER 0x82E0 #define GL_SHADER 0x82E1 #define GL_PROGRAM 0x82E2 #define GL_QUERY 0x82E3 #define GL_PROGRAM_PIPELINE 0x82E4 #define GL_SAMPLER 0x82E6 #define GL_MAX_LABEL_LENGTH 0x82E8 #define GL_DEBUG_OUTPUT 0x92E0 #define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 #define GL_MAX_UNIFORM_LOCATIONS 0x826E #define GL_FRAMEBUFFER_DEFAULT_WIDTH 0x9310 #define GL_FRAMEBUFFER_DEFAULT_HEIGHT 0x9311 #define GL_FRAMEBUFFER_DEFAULT_LAYERS 0x9312 #define GL_FRAMEBUFFER_DEFAULT_SAMPLES 0x9313 #define GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS 0x9314 #define GL_MAX_FRAMEBUFFER_WIDTH 0x9315 #define GL_MAX_FRAMEBUFFER_HEIGHT 0x9316 #define GL_MAX_FRAMEBUFFER_LAYERS 0x9317 #define GL_MAX_FRAMEBUFFER_SAMPLES 0x9318 #define GL_INTERNALFORMAT_SUPPORTED 0x826F #define GL_INTERNALFORMAT_PREFERRED 0x8270 #define GL_INTERNALFORMAT_RED_SIZE 0x8271 #define GL_INTERNALFORMAT_GREEN_SIZE 0x8272 #define GL_INTERNALFORMAT_BLUE_SIZE 0x8273 #define GL_INTERNALFORMAT_ALPHA_SIZE 0x8274 #define GL_INTERNALFORMAT_DEPTH_SIZE 0x8275 #define GL_INTERNALFORMAT_STENCIL_SIZE 0x8276 #define GL_INTERNALFORMAT_SHARED_SIZE 0x8277 #define GL_INTERNALFORMAT_RED_TYPE 0x8278 #define GL_INTERNALFORMAT_GREEN_TYPE 0x8279 #define GL_INTERNALFORMAT_BLUE_TYPE 0x827A #define GL_INTERNALFORMAT_ALPHA_TYPE 0x827B #define GL_INTERNALFORMAT_DEPTH_TYPE 0x827C #define GL_INTERNALFORMAT_STENCIL_TYPE 0x827D #define GL_MAX_WIDTH 0x827E #define GL_MAX_HEIGHT 0x827F #define GL_MAX_DEPTH 0x8280 #define GL_MAX_LAYERS 0x8281 #define GL_MAX_COMBINED_DIMENSIONS 0x8282 #define GL_COLOR_COMPONENTS 0x8283 #define GL_DEPTH_COMPONENTS 0x8284 #define GL_STENCIL_COMPONENTS 0x8285 #define GL_COLOR_RENDERABLE 0x8286 #define GL_DEPTH_RENDERABLE 0x8287 #define GL_STENCIL_RENDERABLE 0x8288 #define GL_FRAMEBUFFER_RENDERABLE 0x8289 #define GL_FRAMEBUFFER_RENDERABLE_LAYERED 0x828A #define GL_FRAMEBUFFER_BLEND 0x828B #define GL_READ_PIXELS 0x828C #define GL_READ_PIXELS_FORMAT 0x828D #define GL_READ_PIXELS_TYPE 0x828E #define GL_TEXTURE_IMAGE_FORMAT 0x828F #define GL_TEXTURE_IMAGE_TYPE 0x8290 #define GL_GET_TEXTURE_IMAGE_FORMAT 0x8291 #define GL_GET_TEXTURE_IMAGE_TYPE 0x8292 #define GL_MIPMAP 0x8293 #define GL_MANUAL_GENERATE_MIPMAP 0x8294 #define GL_AUTO_GENERATE_MIPMAP 0x8295 #define GL_COLOR_ENCODING 0x8296 #define GL_SRGB_READ 0x8297 #define GL_SRGB_WRITE 0x8298 #define GL_FILTER 0x829A #define GL_VERTEX_TEXTURE 0x829B #define GL_TESS_CONTROL_TEXTURE 0x829C #define GL_TESS_EVALUATION_TEXTURE 0x829D #define GL_GEOMETRY_TEXTURE 0x829E #define GL_FRAGMENT_TEXTURE 0x829F #define GL_COMPUTE_TEXTURE 0x82A0 #define GL_TEXTURE_SHADOW 0x82A1 #define GL_TEXTURE_GATHER 0x82A2 #define GL_TEXTURE_GATHER_SHADOW 0x82A3 #define GL_SHADER_IMAGE_LOAD 0x82A4 #define GL_SHADER_IMAGE_STORE 0x82A5 #define GL_SHADER_IMAGE_ATOMIC 0x82A6 #define GL_IMAGE_TEXEL_SIZE 0x82A7 #define GL_IMAGE_COMPATIBILITY_CLASS 0x82A8 #define GL_IMAGE_PIXEL_FORMAT 0x82A9 #define GL_IMAGE_PIXEL_TYPE 0x82AA #define GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST 0x82AC #define GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST 0x82AD #define GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE 0x82AE #define GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE 0x82AF #define GL_TEXTURE_COMPRESSED_BLOCK_WIDTH 0x82B1 #define GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT 0x82B2 #define GL_TEXTURE_COMPRESSED_BLOCK_SIZE 0x82B3 #define GL_CLEAR_BUFFER 0x82B4 #define GL_TEXTURE_VIEW 0x82B5 #define GL_VIEW_COMPATIBILITY_CLASS 0x82B6 #define GL_FULL_SUPPORT 0x82B7 #define GL_CAVEAT_SUPPORT 0x82B8 #define GL_IMAGE_CLASS_4_X_32 0x82B9 #define GL_IMAGE_CLASS_2_X_32 0x82BA #define GL_IMAGE_CLASS_1_X_32 0x82BB #define GL_IMAGE_CLASS_4_X_16 0x82BC #define GL_IMAGE_CLASS_2_X_16 0x82BD #define GL_IMAGE_CLASS_1_X_16 0x82BE #define GL_IMAGE_CLASS_4_X_8 0x82BF #define GL_IMAGE_CLASS_2_X_8 0x82C0 #define GL_IMAGE_CLASS_1_X_8 0x82C1 #define GL_IMAGE_CLASS_11_11_10 0x82C2 #define GL_IMAGE_CLASS_10_10_10_2 0x82C3 #define GL_VIEW_CLASS_128_BITS 0x82C4 #define GL_VIEW_CLASS_96_BITS 0x82C5 #define GL_VIEW_CLASS_64_BITS 0x82C6 #define GL_VIEW_CLASS_48_BITS 0x82C7 #define GL_VIEW_CLASS_32_BITS 0x82C8 #define GL_VIEW_CLASS_24_BITS 0x82C9 #define GL_VIEW_CLASS_16_BITS 0x82CA #define GL_VIEW_CLASS_8_BITS 0x82CB #define GL_VIEW_CLASS_S3TC_DXT1_RGB 0x82CC #define GL_VIEW_CLASS_S3TC_DXT1_RGBA 0x82CD #define GL_VIEW_CLASS_S3TC_DXT3_RGBA 0x82CE #define GL_VIEW_CLASS_S3TC_DXT5_RGBA 0x82CF #define GL_VIEW_CLASS_RGTC1_RED 0x82D0 #define GL_VIEW_CLASS_RGTC2_RG 0x82D1 #define GL_VIEW_CLASS_BPTC_UNORM 0x82D2 #define GL_VIEW_CLASS_BPTC_FLOAT 0x82D3 #define GL_UNIFORM 0x92E1 #define GL_UNIFORM_BLOCK 0x92E2 #define GL_PROGRAM_INPUT 0x92E3 #define GL_PROGRAM_OUTPUT 0x92E4 #define GL_BUFFER_VARIABLE 0x92E5 #define GL_SHADER_STORAGE_BLOCK 0x92E6 #define GL_VERTEX_SUBROUTINE 0x92E8 #define GL_TESS_CONTROL_SUBROUTINE 0x92E9 #define GL_TESS_EVALUATION_SUBROUTINE 0x92EA #define GL_GEOMETRY_SUBROUTINE 0x92EB #define GL_FRAGMENT_SUBROUTINE 0x92EC #define GL_COMPUTE_SUBROUTINE 0x92ED #define GL_VERTEX_SUBROUTINE_UNIFORM 0x92EE #define GL_TESS_CONTROL_SUBROUTINE_UNIFORM 0x92EF #define GL_TESS_EVALUATION_SUBROUTINE_UNIFORM 0x92F0 #define GL_GEOMETRY_SUBROUTINE_UNIFORM 0x92F1 #define GL_FRAGMENT_SUBROUTINE_UNIFORM 0x92F2 #define GL_COMPUTE_SUBROUTINE_UNIFORM 0x92F3 #define GL_TRANSFORM_FEEDBACK_VARYING 0x92F4 #define GL_ACTIVE_RESOURCES 0x92F5 #define GL_MAX_NAME_LENGTH 0x92F6 #define GL_MAX_NUM_ACTIVE_VARIABLES 0x92F7 #define GL_MAX_NUM_COMPATIBLE_SUBROUTINES 0x92F8 #define GL_NAME_LENGTH 0x92F9 #define GL_TYPE 0x92FA #define GL_ARRAY_SIZE 0x92FB #define GL_OFFSET 0x92FC #define GL_BLOCK_INDEX 0x92FD #define GL_ARRAY_STRIDE 0x92FE #define GL_MATRIX_STRIDE 0x92FF #define GL_IS_ROW_MAJOR 0x9300 #define GL_ATOMIC_COUNTER_BUFFER_INDEX 0x9301 #define GL_BUFFER_BINDING 0x9302 #define GL_BUFFER_DATA_SIZE 0x9303 #define GL_NUM_ACTIVE_VARIABLES 0x9304 #define GL_ACTIVE_VARIABLES 0x9305 #define GL_REFERENCED_BY_VERTEX_SHADER 0x9306 #define GL_REFERENCED_BY_TESS_CONTROL_SHADER 0x9307 #define GL_REFERENCED_BY_TESS_EVALUATION_SHADER 0x9308 #define GL_REFERENCED_BY_GEOMETRY_SHADER 0x9309 #define GL_REFERENCED_BY_FRAGMENT_SHADER 0x930A #define GL_REFERENCED_BY_COMPUTE_SHADER 0x930B #define GL_TOP_LEVEL_ARRAY_SIZE 0x930C #define GL_TOP_LEVEL_ARRAY_STRIDE 0x930D #define GL_LOCATION 0x930E #define GL_LOCATION_INDEX 0x930F #define GL_IS_PER_PATCH 0x92E7 #define GL_SHADER_STORAGE_BUFFER 0x90D2 #define GL_SHADER_STORAGE_BUFFER_BINDING 0x90D3 #define GL_SHADER_STORAGE_BUFFER_START 0x90D4 #define GL_SHADER_STORAGE_BUFFER_SIZE 0x90D5 #define GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS 0x90D6 #define GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS 0x90D7 #define GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS 0x90D8 #define GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS 0x90D9 #define GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS 0x90DA #define GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS 0x90DB #define GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS 0x90DC #define GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS 0x90DD #define GL_MAX_SHADER_STORAGE_BLOCK_SIZE 0x90DE #define GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT 0x90DF #define GL_SHADER_STORAGE_BARRIER_BIT 0x00002000 #define GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES 0x8F39 #define GL_DEPTH_STENCIL_TEXTURE_MODE 0x90EA #define GL_TEXTURE_BUFFER_OFFSET 0x919D #define GL_TEXTURE_BUFFER_SIZE 0x919E #define GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT 0x919F #define GL_TEXTURE_VIEW_MIN_LEVEL 0x82DB #define GL_TEXTURE_VIEW_NUM_LEVELS 0x82DC #define GL_TEXTURE_VIEW_MIN_LAYER 0x82DD #define GL_TEXTURE_VIEW_NUM_LAYERS 0x82DE #define GL_TEXTURE_IMMUTABLE_LEVELS 0x82DF #define GL_VERTEX_ATTRIB_BINDING 0x82D4 #define GL_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D5 #define GL_VERTEX_BINDING_DIVISOR 0x82D6 #define GL_VERTEX_BINDING_OFFSET 0x82D7 #define GL_VERTEX_BINDING_STRIDE 0x82D8 #define GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D9 #define GL_MAX_VERTEX_ATTRIB_BINDINGS 0x82DA #define GL_VERTEX_BINDING_BUFFER 0x8F4F #define GL_DISPLAY_LIST 0x82E7 #define GL_MAX_VERTEX_ATTRIB_STRIDE 0x82E5 #define GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED 0x8221 #define GL_TEXTURE_BUFFER_BINDING 0x8C2A #define GL_MAP_PERSISTENT_BIT 0x0040 #define GL_MAP_COHERENT_BIT 0x0080 #define GL_DYNAMIC_STORAGE_BIT 0x0100 #define GL_CLIENT_STORAGE_BIT 0x0200 #define GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT 0x00004000 #define GL_BUFFER_IMMUTABLE_STORAGE 0x821F #define GL_BUFFER_STORAGE_FLAGS 0x8220 #define GL_CLEAR_TEXTURE 0x9365 #define GL_LOCATION_COMPONENT 0x934A #define GL_TRANSFORM_FEEDBACK_BUFFER_INDEX 0x934B #define GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE 0x934C #define GL_QUERY_BUFFER 0x9192 #define GL_QUERY_BUFFER_BARRIER_BIT 0x00008000 #define GL_QUERY_BUFFER_BINDING 0x9193 #define GL_QUERY_RESULT_NO_WAIT 0x9194 #define GL_MIRROR_CLAMP_TO_EDGE 0x8743 #define GL_CONTEXT_LOST 0x0507 #define GL_NEGATIVE_ONE_TO_ONE 0x935E #define GL_ZERO_TO_ONE 0x935F #define GL_CLIP_ORIGIN 0x935C #define GL_CLIP_DEPTH_MODE 0x935D #define GL_QUERY_WAIT_INVERTED 0x8E17 #define GL_QUERY_NO_WAIT_INVERTED 0x8E18 #define GL_QUERY_BY_REGION_WAIT_INVERTED 0x8E19 #define GL_QUERY_BY_REGION_NO_WAIT_INVERTED 0x8E1A #define GL_MAX_CULL_DISTANCES 0x82F9 #define GL_MAX_COMBINED_CLIP_AND_CULL_DISTANCES 0x82FA #define GL_TEXTURE_TARGET 0x1006 #define GL_QUERY_TARGET 0x82EA #define GL_GUILTY_CONTEXT_RESET 0x8253 #define GL_INNOCENT_CONTEXT_RESET 0x8254 #define GL_UNKNOWN_CONTEXT_RESET 0x8255 #define GL_RESET_NOTIFICATION_STRATEGY 0x8256 #define GL_LOSE_CONTEXT_ON_RESET 0x8252 #define GL_NO_RESET_NOTIFICATION 0x8261 #define GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT 0x00000004 #define GL_COLOR_TABLE 0x80D0 #define GL_POST_CONVOLUTION_COLOR_TABLE 0x80D1 #define GL_POST_COLOR_MATRIX_COLOR_TABLE 0x80D2 #define GL_PROXY_COLOR_TABLE 0x80D3 #define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE 0x80D4 #define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE 0x80D5 #define GL_CONVOLUTION_1D 0x8010 #define GL_CONVOLUTION_2D 0x8011 #define GL_SEPARABLE_2D 0x8012 #define GL_HISTOGRAM 0x8024 #define GL_PROXY_HISTOGRAM 0x8025 #define GL_MINMAX 0x802E #define GL_CONTEXT_RELEASE_BEHAVIOR 0x82FB #define GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH 0x82FC #define GL_SHADER_BINARY_FORMAT_SPIR_V 0x9551 #define GL_SPIR_V_BINARY 0x9552 #define GL_PARAMETER_BUFFER 0x80EE #define GL_PARAMETER_BUFFER_BINDING 0x80EF #define GL_CONTEXT_FLAG_NO_ERROR_BIT 0x00000008 #define GL_VERTICES_SUBMITTED 0x82EE #define GL_PRIMITIVES_SUBMITTED 0x82EF #define GL_VERTEX_SHADER_INVOCATIONS 0x82F0 #define GL_TESS_CONTROL_SHADER_PATCHES 0x82F1 #define GL_TESS_EVALUATION_SHADER_INVOCATIONS 0x82F2 #define GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED 0x82F3 #define GL_FRAGMENT_SHADER_INVOCATIONS 0x82F4 #define GL_COMPUTE_SHADER_INVOCATIONS 0x82F5 #define GL_CLIPPING_INPUT_PRIMITIVES 0x82F6 #define GL_CLIPPING_OUTPUT_PRIMITIVES 0x82F7 #define GL_POLYGON_OFFSET_CLAMP 0x8E1B #define GL_SPIR_V_EXTENSIONS 0x9553 #define GL_NUM_SPIR_V_EXTENSIONS 0x9554 #define GL_TEXTURE_MAX_ANISOTROPY 0x84FE #define GL_MAX_TEXTURE_MAX_ANISOTROPY 0x84FF #define GL_TRANSFORM_FEEDBACK_OVERFLOW 0x82EC #define GL_TRANSFORM_FEEDBACK_STREAM_OVERFLOW 0x82ED #ifndef GL_VERSION_1_0 #define GL_VERSION_1_0 1 GLAPI int GLAD_GL_VERSION_1_0; typedef void (APIENTRYP PFNGLCULLFACEPROC)(GLenum mode); GLAPI PFNGLCULLFACEPROC glad_glCullFace; #define glCullFace glad_glCullFace typedef void (APIENTRYP PFNGLFRONTFACEPROC)(GLenum mode); GLAPI PFNGLFRONTFACEPROC glad_glFrontFace; #define glFrontFace glad_glFrontFace typedef void (APIENTRYP PFNGLHINTPROC)(GLenum target, GLenum mode); GLAPI PFNGLHINTPROC glad_glHint; #define glHint glad_glHint typedef void (APIENTRYP PFNGLLINEWIDTHPROC)(GLfloat width); GLAPI PFNGLLINEWIDTHPROC glad_glLineWidth; #define glLineWidth glad_glLineWidth typedef void (APIENTRYP PFNGLPOINTSIZEPROC)(GLfloat size); GLAPI PFNGLPOINTSIZEPROC glad_glPointSize; #define glPointSize glad_glPointSize typedef void (APIENTRYP PFNGLPOLYGONMODEPROC)(GLenum face, GLenum mode); GLAPI PFNGLPOLYGONMODEPROC glad_glPolygonMode; #define glPolygonMode glad_glPolygonMode typedef void (APIENTRYP PFNGLSCISSORPROC)(GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLSCISSORPROC glad_glScissor; #define glScissor glad_glScissor typedef void (APIENTRYP PFNGLTEXPARAMETERFPROC)(GLenum target, GLenum pname, GLfloat param); GLAPI PFNGLTEXPARAMETERFPROC glad_glTexParameterf; #define glTexParameterf glad_glTexParameterf typedef void (APIENTRYP PFNGLTEXPARAMETERFVPROC)(GLenum target, GLenum pname, const GLfloat *params); GLAPI PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv; #define glTexParameterfv glad_glTexParameterfv typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC)(GLenum target, GLenum pname, GLint param); GLAPI PFNGLTEXPARAMETERIPROC glad_glTexParameteri; #define glTexParameteri glad_glTexParameteri typedef void (APIENTRYP PFNGLTEXPARAMETERIVPROC)(GLenum target, GLenum pname, const GLint *params); GLAPI PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv; #define glTexParameteriv glad_glTexParameteriv typedef void (APIENTRYP PFNGLTEXIMAGE1DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXIMAGE1DPROC glad_glTexImage1D; #define glTexImage1D glad_glTexImage1D typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXIMAGE2DPROC glad_glTexImage2D; #define glTexImage2D glad_glTexImage2D typedef void (APIENTRYP PFNGLDRAWBUFFERPROC)(GLenum buf); GLAPI PFNGLDRAWBUFFERPROC glad_glDrawBuffer; #define glDrawBuffer glad_glDrawBuffer typedef void (APIENTRYP PFNGLCLEARPROC)(GLbitfield mask); GLAPI PFNGLCLEARPROC glad_glClear; #define glClear glad_glClear typedef void (APIENTRYP PFNGLCLEARCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); GLAPI PFNGLCLEARCOLORPROC glad_glClearColor; #define glClearColor glad_glClearColor typedef void (APIENTRYP PFNGLCLEARSTENCILPROC)(GLint s); GLAPI PFNGLCLEARSTENCILPROC glad_glClearStencil; #define glClearStencil glad_glClearStencil typedef void (APIENTRYP PFNGLCLEARDEPTHPROC)(GLdouble depth); GLAPI PFNGLCLEARDEPTHPROC glad_glClearDepth; #define glClearDepth glad_glClearDepth typedef void (APIENTRYP PFNGLSTENCILMASKPROC)(GLuint mask); GLAPI PFNGLSTENCILMASKPROC glad_glStencilMask; #define glStencilMask glad_glStencilMask typedef void (APIENTRYP PFNGLCOLORMASKPROC)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); GLAPI PFNGLCOLORMASKPROC glad_glColorMask; #define glColorMask glad_glColorMask typedef void (APIENTRYP PFNGLDEPTHMASKPROC)(GLboolean flag); GLAPI PFNGLDEPTHMASKPROC glad_glDepthMask; #define glDepthMask glad_glDepthMask typedef void (APIENTRYP PFNGLDISABLEPROC)(GLenum cap); GLAPI PFNGLDISABLEPROC glad_glDisable; #define glDisable glad_glDisable typedef void (APIENTRYP PFNGLENABLEPROC)(GLenum cap); GLAPI PFNGLENABLEPROC glad_glEnable; #define glEnable glad_glEnable typedef void (APIENTRYP PFNGLFINISHPROC)(void); GLAPI PFNGLFINISHPROC glad_glFinish; #define glFinish glad_glFinish typedef void (APIENTRYP PFNGLFLUSHPROC)(void); GLAPI PFNGLFLUSHPROC glad_glFlush; #define glFlush glad_glFlush typedef void (APIENTRYP PFNGLBLENDFUNCPROC)(GLenum sfactor, GLenum dfactor); GLAPI PFNGLBLENDFUNCPROC glad_glBlendFunc; #define glBlendFunc glad_glBlendFunc typedef void (APIENTRYP PFNGLLOGICOPPROC)(GLenum opcode); GLAPI PFNGLLOGICOPPROC glad_glLogicOp; #define glLogicOp glad_glLogicOp typedef void (APIENTRYP PFNGLSTENCILFUNCPROC)(GLenum func, GLint ref, GLuint mask); GLAPI PFNGLSTENCILFUNCPROC glad_glStencilFunc; #define glStencilFunc glad_glStencilFunc typedef void (APIENTRYP PFNGLSTENCILOPPROC)(GLenum fail, GLenum zfail, GLenum zpass); GLAPI PFNGLSTENCILOPPROC glad_glStencilOp; #define glStencilOp glad_glStencilOp typedef void (APIENTRYP PFNGLDEPTHFUNCPROC)(GLenum func); GLAPI PFNGLDEPTHFUNCPROC glad_glDepthFunc; #define glDepthFunc glad_glDepthFunc typedef void (APIENTRYP PFNGLPIXELSTOREFPROC)(GLenum pname, GLfloat param); GLAPI PFNGLPIXELSTOREFPROC glad_glPixelStoref; #define glPixelStoref glad_glPixelStoref typedef void (APIENTRYP PFNGLPIXELSTOREIPROC)(GLenum pname, GLint param); GLAPI PFNGLPIXELSTOREIPROC glad_glPixelStorei; #define glPixelStorei glad_glPixelStorei typedef void (APIENTRYP PFNGLREADBUFFERPROC)(GLenum src); GLAPI PFNGLREADBUFFERPROC glad_glReadBuffer; #define glReadBuffer glad_glReadBuffer typedef void (APIENTRYP PFNGLREADPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); GLAPI PFNGLREADPIXELSPROC glad_glReadPixels; #define glReadPixels glad_glReadPixels typedef void (APIENTRYP PFNGLGETBOOLEANVPROC)(GLenum pname, GLboolean *data); GLAPI PFNGLGETBOOLEANVPROC glad_glGetBooleanv; #define glGetBooleanv glad_glGetBooleanv typedef void (APIENTRYP PFNGLGETDOUBLEVPROC)(GLenum pname, GLdouble *data); GLAPI PFNGLGETDOUBLEVPROC glad_glGetDoublev; #define glGetDoublev glad_glGetDoublev typedef GLenum (APIENTRYP PFNGLGETERRORPROC)(void); GLAPI PFNGLGETERRORPROC glad_glGetError; #define glGetError glad_glGetError typedef void (APIENTRYP PFNGLGETFLOATVPROC)(GLenum pname, GLfloat *data); GLAPI PFNGLGETFLOATVPROC glad_glGetFloatv; #define glGetFloatv glad_glGetFloatv typedef void (APIENTRYP PFNGLGETINTEGERVPROC)(GLenum pname, GLint *data); GLAPI PFNGLGETINTEGERVPROC glad_glGetIntegerv; #define glGetIntegerv glad_glGetIntegerv typedef const GLubyte * (APIENTRYP PFNGLGETSTRINGPROC)(GLenum name); GLAPI PFNGLGETSTRINGPROC glad_glGetString; #define glGetString glad_glGetString typedef void (APIENTRYP PFNGLGETTEXIMAGEPROC)(GLenum target, GLint level, GLenum format, GLenum type, void *pixels); GLAPI PFNGLGETTEXIMAGEPROC glad_glGetTexImage; #define glGetTexImage glad_glGetTexImage typedef void (APIENTRYP PFNGLGETTEXPARAMETERFVPROC)(GLenum target, GLenum pname, GLfloat *params); GLAPI PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv; #define glGetTexParameterfv glad_glGetTexParameterfv typedef void (APIENTRYP PFNGLGETTEXPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); GLAPI PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv; #define glGetTexParameteriv glad_glGetTexParameteriv typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERFVPROC)(GLenum target, GLint level, GLenum pname, GLfloat *params); GLAPI PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv; #define glGetTexLevelParameterfv glad_glGetTexLevelParameterfv typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERIVPROC)(GLenum target, GLint level, GLenum pname, GLint *params); GLAPI PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv; #define glGetTexLevelParameteriv glad_glGetTexLevelParameteriv typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC)(GLenum cap); GLAPI PFNGLISENABLEDPROC glad_glIsEnabled; #define glIsEnabled glad_glIsEnabled typedef void (APIENTRYP PFNGLDEPTHRANGEPROC)(GLdouble n, GLdouble f); GLAPI PFNGLDEPTHRANGEPROC glad_glDepthRange; #define glDepthRange glad_glDepthRange typedef void (APIENTRYP PFNGLVIEWPORTPROC)(GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLVIEWPORTPROC glad_glViewport; #define glViewport glad_glViewport typedef void (APIENTRYP PFNGLNEWLISTPROC)(GLuint list, GLenum mode); GLAPI PFNGLNEWLISTPROC glad_glNewList; #define glNewList glad_glNewList typedef void (APIENTRYP PFNGLENDLISTPROC)(void); GLAPI PFNGLENDLISTPROC glad_glEndList; #define glEndList glad_glEndList typedef void (APIENTRYP PFNGLCALLLISTPROC)(GLuint list); GLAPI PFNGLCALLLISTPROC glad_glCallList; #define glCallList glad_glCallList typedef void (APIENTRYP PFNGLCALLLISTSPROC)(GLsizei n, GLenum type, const void *lists); GLAPI PFNGLCALLLISTSPROC glad_glCallLists; #define glCallLists glad_glCallLists typedef void (APIENTRYP PFNGLDELETELISTSPROC)(GLuint list, GLsizei range); GLAPI PFNGLDELETELISTSPROC glad_glDeleteLists; #define glDeleteLists glad_glDeleteLists typedef GLuint (APIENTRYP PFNGLGENLISTSPROC)(GLsizei range); GLAPI PFNGLGENLISTSPROC glad_glGenLists; #define glGenLists glad_glGenLists typedef void (APIENTRYP PFNGLLISTBASEPROC)(GLuint base); GLAPI PFNGLLISTBASEPROC glad_glListBase; #define glListBase glad_glListBase typedef void (APIENTRYP PFNGLBEGINPROC)(GLenum mode); GLAPI PFNGLBEGINPROC glad_glBegin; #define glBegin glad_glBegin typedef void (APIENTRYP PFNGLBITMAPPROC)(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap); GLAPI PFNGLBITMAPPROC glad_glBitmap; #define glBitmap glad_glBitmap typedef void (APIENTRYP PFNGLCOLOR3BPROC)(GLbyte red, GLbyte green, GLbyte blue); GLAPI PFNGLCOLOR3BPROC glad_glColor3b; #define glColor3b glad_glColor3b typedef void (APIENTRYP PFNGLCOLOR3BVPROC)(const GLbyte *v); GLAPI PFNGLCOLOR3BVPROC glad_glColor3bv; #define glColor3bv glad_glColor3bv typedef void (APIENTRYP PFNGLCOLOR3DPROC)(GLdouble red, GLdouble green, GLdouble blue); GLAPI PFNGLCOLOR3DPROC glad_glColor3d; #define glColor3d glad_glColor3d typedef void (APIENTRYP PFNGLCOLOR3DVPROC)(const GLdouble *v); GLAPI PFNGLCOLOR3DVPROC glad_glColor3dv; #define glColor3dv glad_glColor3dv typedef void (APIENTRYP PFNGLCOLOR3FPROC)(GLfloat red, GLfloat green, GLfloat blue); GLAPI PFNGLCOLOR3FPROC glad_glColor3f; #define glColor3f glad_glColor3f typedef void (APIENTRYP PFNGLCOLOR3FVPROC)(const GLfloat *v); GLAPI PFNGLCOLOR3FVPROC glad_glColor3fv; #define glColor3fv glad_glColor3fv typedef void (APIENTRYP PFNGLCOLOR3IPROC)(GLint red, GLint green, GLint blue); GLAPI PFNGLCOLOR3IPROC glad_glColor3i; #define glColor3i glad_glColor3i typedef void (APIENTRYP PFNGLCOLOR3IVPROC)(const GLint *v); GLAPI PFNGLCOLOR3IVPROC glad_glColor3iv; #define glColor3iv glad_glColor3iv typedef void (APIENTRYP PFNGLCOLOR3SPROC)(GLshort red, GLshort green, GLshort blue); GLAPI PFNGLCOLOR3SPROC glad_glColor3s; #define glColor3s glad_glColor3s typedef void (APIENTRYP PFNGLCOLOR3SVPROC)(const GLshort *v); GLAPI PFNGLCOLOR3SVPROC glad_glColor3sv; #define glColor3sv glad_glColor3sv typedef void (APIENTRYP PFNGLCOLOR3UBPROC)(GLubyte red, GLubyte green, GLubyte blue); GLAPI PFNGLCOLOR3UBPROC glad_glColor3ub; #define glColor3ub glad_glColor3ub typedef void (APIENTRYP PFNGLCOLOR3UBVPROC)(const GLubyte *v); GLAPI PFNGLCOLOR3UBVPROC glad_glColor3ubv; #define glColor3ubv glad_glColor3ubv typedef void (APIENTRYP PFNGLCOLOR3UIPROC)(GLuint red, GLuint green, GLuint blue); GLAPI PFNGLCOLOR3UIPROC glad_glColor3ui; #define glColor3ui glad_glColor3ui typedef void (APIENTRYP PFNGLCOLOR3UIVPROC)(const GLuint *v); GLAPI PFNGLCOLOR3UIVPROC glad_glColor3uiv; #define glColor3uiv glad_glColor3uiv typedef void (APIENTRYP PFNGLCOLOR3USPROC)(GLushort red, GLushort green, GLushort blue); GLAPI PFNGLCOLOR3USPROC glad_glColor3us; #define glColor3us glad_glColor3us typedef void (APIENTRYP PFNGLCOLOR3USVPROC)(const GLushort *v); GLAPI PFNGLCOLOR3USVPROC glad_glColor3usv; #define glColor3usv glad_glColor3usv typedef void (APIENTRYP PFNGLCOLOR4BPROC)(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha); GLAPI PFNGLCOLOR4BPROC glad_glColor4b; #define glColor4b glad_glColor4b typedef void (APIENTRYP PFNGLCOLOR4BVPROC)(const GLbyte *v); GLAPI PFNGLCOLOR4BVPROC glad_glColor4bv; #define glColor4bv glad_glColor4bv typedef void (APIENTRYP PFNGLCOLOR4DPROC)(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha); GLAPI PFNGLCOLOR4DPROC glad_glColor4d; #define glColor4d glad_glColor4d typedef void (APIENTRYP PFNGLCOLOR4DVPROC)(const GLdouble *v); GLAPI PFNGLCOLOR4DVPROC glad_glColor4dv; #define glColor4dv glad_glColor4dv typedef void (APIENTRYP PFNGLCOLOR4FPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); GLAPI PFNGLCOLOR4FPROC glad_glColor4f; #define glColor4f glad_glColor4f typedef void (APIENTRYP PFNGLCOLOR4FVPROC)(const GLfloat *v); GLAPI PFNGLCOLOR4FVPROC glad_glColor4fv; #define glColor4fv glad_glColor4fv typedef void (APIENTRYP PFNGLCOLOR4IPROC)(GLint red, GLint green, GLint blue, GLint alpha); GLAPI PFNGLCOLOR4IPROC glad_glColor4i; #define glColor4i glad_glColor4i typedef void (APIENTRYP PFNGLCOLOR4IVPROC)(const GLint *v); GLAPI PFNGLCOLOR4IVPROC glad_glColor4iv; #define glColor4iv glad_glColor4iv typedef void (APIENTRYP PFNGLCOLOR4SPROC)(GLshort red, GLshort green, GLshort blue, GLshort alpha); GLAPI PFNGLCOLOR4SPROC glad_glColor4s; #define glColor4s glad_glColor4s typedef void (APIENTRYP PFNGLCOLOR4SVPROC)(const GLshort *v); GLAPI PFNGLCOLOR4SVPROC glad_glColor4sv; #define glColor4sv glad_glColor4sv typedef void (APIENTRYP PFNGLCOLOR4UBPROC)(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha); GLAPI PFNGLCOLOR4UBPROC glad_glColor4ub; #define glColor4ub glad_glColor4ub typedef void (APIENTRYP PFNGLCOLOR4UBVPROC)(const GLubyte *v); GLAPI PFNGLCOLOR4UBVPROC glad_glColor4ubv; #define glColor4ubv glad_glColor4ubv typedef void (APIENTRYP PFNGLCOLOR4UIPROC)(GLuint red, GLuint green, GLuint blue, GLuint alpha); GLAPI PFNGLCOLOR4UIPROC glad_glColor4ui; #define glColor4ui glad_glColor4ui typedef void (APIENTRYP PFNGLCOLOR4UIVPROC)(const GLuint *v); GLAPI PFNGLCOLOR4UIVPROC glad_glColor4uiv; #define glColor4uiv glad_glColor4uiv typedef void (APIENTRYP PFNGLCOLOR4USPROC)(GLushort red, GLushort green, GLushort blue, GLushort alpha); GLAPI PFNGLCOLOR4USPROC glad_glColor4us; #define glColor4us glad_glColor4us typedef void (APIENTRYP PFNGLCOLOR4USVPROC)(const GLushort *v); GLAPI PFNGLCOLOR4USVPROC glad_glColor4usv; #define glColor4usv glad_glColor4usv typedef void (APIENTRYP PFNGLEDGEFLAGPROC)(GLboolean flag); GLAPI PFNGLEDGEFLAGPROC glad_glEdgeFlag; #define glEdgeFlag glad_glEdgeFlag typedef void (APIENTRYP PFNGLEDGEFLAGVPROC)(const GLboolean *flag); GLAPI PFNGLEDGEFLAGVPROC glad_glEdgeFlagv; #define glEdgeFlagv glad_glEdgeFlagv typedef void (APIENTRYP PFNGLENDPROC)(void); GLAPI PFNGLENDPROC glad_glEnd; #define glEnd glad_glEnd typedef void (APIENTRYP PFNGLINDEXDPROC)(GLdouble c); GLAPI PFNGLINDEXDPROC glad_glIndexd; #define glIndexd glad_glIndexd typedef void (APIENTRYP PFNGLINDEXDVPROC)(const GLdouble *c); GLAPI PFNGLINDEXDVPROC glad_glIndexdv; #define glIndexdv glad_glIndexdv typedef void (APIENTRYP PFNGLINDEXFPROC)(GLfloat c); GLAPI PFNGLINDEXFPROC glad_glIndexf; #define glIndexf glad_glIndexf typedef void (APIENTRYP PFNGLINDEXFVPROC)(const GLfloat *c); GLAPI PFNGLINDEXFVPROC glad_glIndexfv; #define glIndexfv glad_glIndexfv typedef void (APIENTRYP PFNGLINDEXIPROC)(GLint c); GLAPI PFNGLINDEXIPROC glad_glIndexi; #define glIndexi glad_glIndexi typedef void (APIENTRYP PFNGLINDEXIVPROC)(const GLint *c); GLAPI PFNGLINDEXIVPROC glad_glIndexiv; #define glIndexiv glad_glIndexiv typedef void (APIENTRYP PFNGLINDEXSPROC)(GLshort c); GLAPI PFNGLINDEXSPROC glad_glIndexs; #define glIndexs glad_glIndexs typedef void (APIENTRYP PFNGLINDEXSVPROC)(const GLshort *c); GLAPI PFNGLINDEXSVPROC glad_glIndexsv; #define glIndexsv glad_glIndexsv typedef void (APIENTRYP PFNGLNORMAL3BPROC)(GLbyte nx, GLbyte ny, GLbyte nz); GLAPI PFNGLNORMAL3BPROC glad_glNormal3b; #define glNormal3b glad_glNormal3b typedef void (APIENTRYP PFNGLNORMAL3BVPROC)(const GLbyte *v); GLAPI PFNGLNORMAL3BVPROC glad_glNormal3bv; #define glNormal3bv glad_glNormal3bv typedef void (APIENTRYP PFNGLNORMAL3DPROC)(GLdouble nx, GLdouble ny, GLdouble nz); GLAPI PFNGLNORMAL3DPROC glad_glNormal3d; #define glNormal3d glad_glNormal3d typedef void (APIENTRYP PFNGLNORMAL3DVPROC)(const GLdouble *v); GLAPI PFNGLNORMAL3DVPROC glad_glNormal3dv; #define glNormal3dv glad_glNormal3dv typedef void (APIENTRYP PFNGLNORMAL3FPROC)(GLfloat nx, GLfloat ny, GLfloat nz); GLAPI PFNGLNORMAL3FPROC glad_glNormal3f; #define glNormal3f glad_glNormal3f typedef void (APIENTRYP PFNGLNORMAL3FVPROC)(const GLfloat *v); GLAPI PFNGLNORMAL3FVPROC glad_glNormal3fv; #define glNormal3fv glad_glNormal3fv typedef void (APIENTRYP PFNGLNORMAL3IPROC)(GLint nx, GLint ny, GLint nz); GLAPI PFNGLNORMAL3IPROC glad_glNormal3i; #define glNormal3i glad_glNormal3i typedef void (APIENTRYP PFNGLNORMAL3IVPROC)(const GLint *v); GLAPI PFNGLNORMAL3IVPROC glad_glNormal3iv; #define glNormal3iv glad_glNormal3iv typedef void (APIENTRYP PFNGLNORMAL3SPROC)(GLshort nx, GLshort ny, GLshort nz); GLAPI PFNGLNORMAL3SPROC glad_glNormal3s; #define glNormal3s glad_glNormal3s typedef void (APIENTRYP PFNGLNORMAL3SVPROC)(const GLshort *v); GLAPI PFNGLNORMAL3SVPROC glad_glNormal3sv; #define glNormal3sv glad_glNormal3sv typedef void (APIENTRYP PFNGLRASTERPOS2DPROC)(GLdouble x, GLdouble y); GLAPI PFNGLRASTERPOS2DPROC glad_glRasterPos2d; #define glRasterPos2d glad_glRasterPos2d typedef void (APIENTRYP PFNGLRASTERPOS2DVPROC)(const GLdouble *v); GLAPI PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv; #define glRasterPos2dv glad_glRasterPos2dv typedef void (APIENTRYP PFNGLRASTERPOS2FPROC)(GLfloat x, GLfloat y); GLAPI PFNGLRASTERPOS2FPROC glad_glRasterPos2f; #define glRasterPos2f glad_glRasterPos2f typedef void (APIENTRYP PFNGLRASTERPOS2FVPROC)(const GLfloat *v); GLAPI PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv; #define glRasterPos2fv glad_glRasterPos2fv typedef void (APIENTRYP PFNGLRASTERPOS2IPROC)(GLint x, GLint y); GLAPI PFNGLRASTERPOS2IPROC glad_glRasterPos2i; #define glRasterPos2i glad_glRasterPos2i typedef void (APIENTRYP PFNGLRASTERPOS2IVPROC)(const GLint *v); GLAPI PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv; #define glRasterPos2iv glad_glRasterPos2iv typedef void (APIENTRYP PFNGLRASTERPOS2SPROC)(GLshort x, GLshort y); GLAPI PFNGLRASTERPOS2SPROC glad_glRasterPos2s; #define glRasterPos2s glad_glRasterPos2s typedef void (APIENTRYP PFNGLRASTERPOS2SVPROC)(const GLshort *v); GLAPI PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv; #define glRasterPos2sv glad_glRasterPos2sv typedef void (APIENTRYP PFNGLRASTERPOS3DPROC)(GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLRASTERPOS3DPROC glad_glRasterPos3d; #define glRasterPos3d glad_glRasterPos3d typedef void (APIENTRYP PFNGLRASTERPOS3DVPROC)(const GLdouble *v); GLAPI PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv; #define glRasterPos3dv glad_glRasterPos3dv typedef void (APIENTRYP PFNGLRASTERPOS3FPROC)(GLfloat x, GLfloat y, GLfloat z); GLAPI PFNGLRASTERPOS3FPROC glad_glRasterPos3f; #define glRasterPos3f glad_glRasterPos3f typedef void (APIENTRYP PFNGLRASTERPOS3FVPROC)(const GLfloat *v); GLAPI PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv; #define glRasterPos3fv glad_glRasterPos3fv typedef void (APIENTRYP PFNGLRASTERPOS3IPROC)(GLint x, GLint y, GLint z); GLAPI PFNGLRASTERPOS3IPROC glad_glRasterPos3i; #define glRasterPos3i glad_glRasterPos3i typedef void (APIENTRYP PFNGLRASTERPOS3IVPROC)(const GLint *v); GLAPI PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv; #define glRasterPos3iv glad_glRasterPos3iv typedef void (APIENTRYP PFNGLRASTERPOS3SPROC)(GLshort x, GLshort y, GLshort z); GLAPI PFNGLRASTERPOS3SPROC glad_glRasterPos3s; #define glRasterPos3s glad_glRasterPos3s typedef void (APIENTRYP PFNGLRASTERPOS3SVPROC)(const GLshort *v); GLAPI PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv; #define glRasterPos3sv glad_glRasterPos3sv typedef void (APIENTRYP PFNGLRASTERPOS4DPROC)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); GLAPI PFNGLRASTERPOS4DPROC glad_glRasterPos4d; #define glRasterPos4d glad_glRasterPos4d typedef void (APIENTRYP PFNGLRASTERPOS4DVPROC)(const GLdouble *v); GLAPI PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv; #define glRasterPos4dv glad_glRasterPos4dv typedef void (APIENTRYP PFNGLRASTERPOS4FPROC)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); GLAPI PFNGLRASTERPOS4FPROC glad_glRasterPos4f; #define glRasterPos4f glad_glRasterPos4f typedef void (APIENTRYP PFNGLRASTERPOS4FVPROC)(const GLfloat *v); GLAPI PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv; #define glRasterPos4fv glad_glRasterPos4fv typedef void (APIENTRYP PFNGLRASTERPOS4IPROC)(GLint x, GLint y, GLint z, GLint w); GLAPI PFNGLRASTERPOS4IPROC glad_glRasterPos4i; #define glRasterPos4i glad_glRasterPos4i typedef void (APIENTRYP PFNGLRASTERPOS4IVPROC)(const GLint *v); GLAPI PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv; #define glRasterPos4iv glad_glRasterPos4iv typedef void (APIENTRYP PFNGLRASTERPOS4SPROC)(GLshort x, GLshort y, GLshort z, GLshort w); GLAPI PFNGLRASTERPOS4SPROC glad_glRasterPos4s; #define glRasterPos4s glad_glRasterPos4s typedef void (APIENTRYP PFNGLRASTERPOS4SVPROC)(const GLshort *v); GLAPI PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv; #define glRasterPos4sv glad_glRasterPos4sv typedef void (APIENTRYP PFNGLRECTDPROC)(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2); GLAPI PFNGLRECTDPROC glad_glRectd; #define glRectd glad_glRectd typedef void (APIENTRYP PFNGLRECTDVPROC)(const GLdouble *v1, const GLdouble *v2); GLAPI PFNGLRECTDVPROC glad_glRectdv; #define glRectdv glad_glRectdv typedef void (APIENTRYP PFNGLRECTFPROC)(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2); GLAPI PFNGLRECTFPROC glad_glRectf; #define glRectf glad_glRectf typedef void (APIENTRYP PFNGLRECTFVPROC)(const GLfloat *v1, const GLfloat *v2); GLAPI PFNGLRECTFVPROC glad_glRectfv; #define glRectfv glad_glRectfv typedef void (APIENTRYP PFNGLRECTIPROC)(GLint x1, GLint y1, GLint x2, GLint y2); GLAPI PFNGLRECTIPROC glad_glRecti; #define glRecti glad_glRecti typedef void (APIENTRYP PFNGLRECTIVPROC)(const GLint *v1, const GLint *v2); GLAPI PFNGLRECTIVPROC glad_glRectiv; #define glRectiv glad_glRectiv typedef void (APIENTRYP PFNGLRECTSPROC)(GLshort x1, GLshort y1, GLshort x2, GLshort y2); GLAPI PFNGLRECTSPROC glad_glRects; #define glRects glad_glRects typedef void (APIENTRYP PFNGLRECTSVPROC)(const GLshort *v1, const GLshort *v2); GLAPI PFNGLRECTSVPROC glad_glRectsv; #define glRectsv glad_glRectsv typedef void (APIENTRYP PFNGLTEXCOORD1DPROC)(GLdouble s); GLAPI PFNGLTEXCOORD1DPROC glad_glTexCoord1d; #define glTexCoord1d glad_glTexCoord1d typedef void (APIENTRYP PFNGLTEXCOORD1DVPROC)(const GLdouble *v); GLAPI PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv; #define glTexCoord1dv glad_glTexCoord1dv typedef void (APIENTRYP PFNGLTEXCOORD1FPROC)(GLfloat s); GLAPI PFNGLTEXCOORD1FPROC glad_glTexCoord1f; #define glTexCoord1f glad_glTexCoord1f typedef void (APIENTRYP PFNGLTEXCOORD1FVPROC)(const GLfloat *v); GLAPI PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv; #define glTexCoord1fv glad_glTexCoord1fv typedef void (APIENTRYP PFNGLTEXCOORD1IPROC)(GLint s); GLAPI PFNGLTEXCOORD1IPROC glad_glTexCoord1i; #define glTexCoord1i glad_glTexCoord1i typedef void (APIENTRYP PFNGLTEXCOORD1IVPROC)(const GLint *v); GLAPI PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv; #define glTexCoord1iv glad_glTexCoord1iv typedef void (APIENTRYP PFNGLTEXCOORD1SPROC)(GLshort s); GLAPI PFNGLTEXCOORD1SPROC glad_glTexCoord1s; #define glTexCoord1s glad_glTexCoord1s typedef void (APIENTRYP PFNGLTEXCOORD1SVPROC)(const GLshort *v); GLAPI PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv; #define glTexCoord1sv glad_glTexCoord1sv typedef void (APIENTRYP PFNGLTEXCOORD2DPROC)(GLdouble s, GLdouble t); GLAPI PFNGLTEXCOORD2DPROC glad_glTexCoord2d; #define glTexCoord2d glad_glTexCoord2d typedef void (APIENTRYP PFNGLTEXCOORD2DVPROC)(const GLdouble *v); GLAPI PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv; #define glTexCoord2dv glad_glTexCoord2dv typedef void (APIENTRYP PFNGLTEXCOORD2FPROC)(GLfloat s, GLfloat t); GLAPI PFNGLTEXCOORD2FPROC glad_glTexCoord2f; #define glTexCoord2f glad_glTexCoord2f typedef void (APIENTRYP PFNGLTEXCOORD2FVPROC)(const GLfloat *v); GLAPI PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv; #define glTexCoord2fv glad_glTexCoord2fv typedef void (APIENTRYP PFNGLTEXCOORD2IPROC)(GLint s, GLint t); GLAPI PFNGLTEXCOORD2IPROC glad_glTexCoord2i; #define glTexCoord2i glad_glTexCoord2i typedef void (APIENTRYP PFNGLTEXCOORD2IVPROC)(const GLint *v); GLAPI PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv; #define glTexCoord2iv glad_glTexCoord2iv typedef void (APIENTRYP PFNGLTEXCOORD2SPROC)(GLshort s, GLshort t); GLAPI PFNGLTEXCOORD2SPROC glad_glTexCoord2s; #define glTexCoord2s glad_glTexCoord2s typedef void (APIENTRYP PFNGLTEXCOORD2SVPROC)(const GLshort *v); GLAPI PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv; #define glTexCoord2sv glad_glTexCoord2sv typedef void (APIENTRYP PFNGLTEXCOORD3DPROC)(GLdouble s, GLdouble t, GLdouble r); GLAPI PFNGLTEXCOORD3DPROC glad_glTexCoord3d; #define glTexCoord3d glad_glTexCoord3d typedef void (APIENTRYP PFNGLTEXCOORD3DVPROC)(const GLdouble *v); GLAPI PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv; #define glTexCoord3dv glad_glTexCoord3dv typedef void (APIENTRYP PFNGLTEXCOORD3FPROC)(GLfloat s, GLfloat t, GLfloat r); GLAPI PFNGLTEXCOORD3FPROC glad_glTexCoord3f; #define glTexCoord3f glad_glTexCoord3f typedef void (APIENTRYP PFNGLTEXCOORD3FVPROC)(const GLfloat *v); GLAPI PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv; #define glTexCoord3fv glad_glTexCoord3fv typedef void (APIENTRYP PFNGLTEXCOORD3IPROC)(GLint s, GLint t, GLint r); GLAPI PFNGLTEXCOORD3IPROC glad_glTexCoord3i; #define glTexCoord3i glad_glTexCoord3i typedef void (APIENTRYP PFNGLTEXCOORD3IVPROC)(const GLint *v); GLAPI PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv; #define glTexCoord3iv glad_glTexCoord3iv typedef void (APIENTRYP PFNGLTEXCOORD3SPROC)(GLshort s, GLshort t, GLshort r); GLAPI PFNGLTEXCOORD3SPROC glad_glTexCoord3s; #define glTexCoord3s glad_glTexCoord3s typedef void (APIENTRYP PFNGLTEXCOORD3SVPROC)(const GLshort *v); GLAPI PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv; #define glTexCoord3sv glad_glTexCoord3sv typedef void (APIENTRYP PFNGLTEXCOORD4DPROC)(GLdouble s, GLdouble t, GLdouble r, GLdouble q); GLAPI PFNGLTEXCOORD4DPROC glad_glTexCoord4d; #define glTexCoord4d glad_glTexCoord4d typedef void (APIENTRYP PFNGLTEXCOORD4DVPROC)(const GLdouble *v); GLAPI PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv; #define glTexCoord4dv glad_glTexCoord4dv typedef void (APIENTRYP PFNGLTEXCOORD4FPROC)(GLfloat s, GLfloat t, GLfloat r, GLfloat q); GLAPI PFNGLTEXCOORD4FPROC glad_glTexCoord4f; #define glTexCoord4f glad_glTexCoord4f typedef void (APIENTRYP PFNGLTEXCOORD4FVPROC)(const GLfloat *v); GLAPI PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv; #define glTexCoord4fv glad_glTexCoord4fv typedef void (APIENTRYP PFNGLTEXCOORD4IPROC)(GLint s, GLint t, GLint r, GLint q); GLAPI PFNGLTEXCOORD4IPROC glad_glTexCoord4i; #define glTexCoord4i glad_glTexCoord4i typedef void (APIENTRYP PFNGLTEXCOORD4IVPROC)(const GLint *v); GLAPI PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv; #define glTexCoord4iv glad_glTexCoord4iv typedef void (APIENTRYP PFNGLTEXCOORD4SPROC)(GLshort s, GLshort t, GLshort r, GLshort q); GLAPI PFNGLTEXCOORD4SPROC glad_glTexCoord4s; #define glTexCoord4s glad_glTexCoord4s typedef void (APIENTRYP PFNGLTEXCOORD4SVPROC)(const GLshort *v); GLAPI PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv; #define glTexCoord4sv glad_glTexCoord4sv typedef void (APIENTRYP PFNGLVERTEX2DPROC)(GLdouble x, GLdouble y); GLAPI PFNGLVERTEX2DPROC glad_glVertex2d; #define glVertex2d glad_glVertex2d typedef void (APIENTRYP PFNGLVERTEX2DVPROC)(const GLdouble *v); GLAPI PFNGLVERTEX2DVPROC glad_glVertex2dv; #define glVertex2dv glad_glVertex2dv typedef void (APIENTRYP PFNGLVERTEX2FPROC)(GLfloat x, GLfloat y); GLAPI PFNGLVERTEX2FPROC glad_glVertex2f; #define glVertex2f glad_glVertex2f typedef void (APIENTRYP PFNGLVERTEX2FVPROC)(const GLfloat *v); GLAPI PFNGLVERTEX2FVPROC glad_glVertex2fv; #define glVertex2fv glad_glVertex2fv typedef void (APIENTRYP PFNGLVERTEX2IPROC)(GLint x, GLint y); GLAPI PFNGLVERTEX2IPROC glad_glVertex2i; #define glVertex2i glad_glVertex2i typedef void (APIENTRYP PFNGLVERTEX2IVPROC)(const GLint *v); GLAPI PFNGLVERTEX2IVPROC glad_glVertex2iv; #define glVertex2iv glad_glVertex2iv typedef void (APIENTRYP PFNGLVERTEX2SPROC)(GLshort x, GLshort y); GLAPI PFNGLVERTEX2SPROC glad_glVertex2s; #define glVertex2s glad_glVertex2s typedef void (APIENTRYP PFNGLVERTEX2SVPROC)(const GLshort *v); GLAPI PFNGLVERTEX2SVPROC glad_glVertex2sv; #define glVertex2sv glad_glVertex2sv typedef void (APIENTRYP PFNGLVERTEX3DPROC)(GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLVERTEX3DPROC glad_glVertex3d; #define glVertex3d glad_glVertex3d typedef void (APIENTRYP PFNGLVERTEX3DVPROC)(const GLdouble *v); GLAPI PFNGLVERTEX3DVPROC glad_glVertex3dv; #define glVertex3dv glad_glVertex3dv typedef void (APIENTRYP PFNGLVERTEX3FPROC)(GLfloat x, GLfloat y, GLfloat z); GLAPI PFNGLVERTEX3FPROC glad_glVertex3f; #define glVertex3f glad_glVertex3f typedef void (APIENTRYP PFNGLVERTEX3FVPROC)(const GLfloat *v); GLAPI PFNGLVERTEX3FVPROC glad_glVertex3fv; #define glVertex3fv glad_glVertex3fv typedef void (APIENTRYP PFNGLVERTEX3IPROC)(GLint x, GLint y, GLint z); GLAPI PFNGLVERTEX3IPROC glad_glVertex3i; #define glVertex3i glad_glVertex3i typedef void (APIENTRYP PFNGLVERTEX3IVPROC)(const GLint *v); GLAPI PFNGLVERTEX3IVPROC glad_glVertex3iv; #define glVertex3iv glad_glVertex3iv typedef void (APIENTRYP PFNGLVERTEX3SPROC)(GLshort x, GLshort y, GLshort z); GLAPI PFNGLVERTEX3SPROC glad_glVertex3s; #define glVertex3s glad_glVertex3s typedef void (APIENTRYP PFNGLVERTEX3SVPROC)(const GLshort *v); GLAPI PFNGLVERTEX3SVPROC glad_glVertex3sv; #define glVertex3sv glad_glVertex3sv typedef void (APIENTRYP PFNGLVERTEX4DPROC)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); GLAPI PFNGLVERTEX4DPROC glad_glVertex4d; #define glVertex4d glad_glVertex4d typedef void (APIENTRYP PFNGLVERTEX4DVPROC)(const GLdouble *v); GLAPI PFNGLVERTEX4DVPROC glad_glVertex4dv; #define glVertex4dv glad_glVertex4dv typedef void (APIENTRYP PFNGLVERTEX4FPROC)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); GLAPI PFNGLVERTEX4FPROC glad_glVertex4f; #define glVertex4f glad_glVertex4f typedef void (APIENTRYP PFNGLVERTEX4FVPROC)(const GLfloat *v); GLAPI PFNGLVERTEX4FVPROC glad_glVertex4fv; #define glVertex4fv glad_glVertex4fv typedef void (APIENTRYP PFNGLVERTEX4IPROC)(GLint x, GLint y, GLint z, GLint w); GLAPI PFNGLVERTEX4IPROC glad_glVertex4i; #define glVertex4i glad_glVertex4i typedef void (APIENTRYP PFNGLVERTEX4IVPROC)(const GLint *v); GLAPI PFNGLVERTEX4IVPROC glad_glVertex4iv; #define glVertex4iv glad_glVertex4iv typedef void (APIENTRYP PFNGLVERTEX4SPROC)(GLshort x, GLshort y, GLshort z, GLshort w); GLAPI PFNGLVERTEX4SPROC glad_glVertex4s; #define glVertex4s glad_glVertex4s typedef void (APIENTRYP PFNGLVERTEX4SVPROC)(const GLshort *v); GLAPI PFNGLVERTEX4SVPROC glad_glVertex4sv; #define glVertex4sv glad_glVertex4sv typedef void (APIENTRYP PFNGLCLIPPLANEPROC)(GLenum plane, const GLdouble *equation); GLAPI PFNGLCLIPPLANEPROC glad_glClipPlane; #define glClipPlane glad_glClipPlane typedef void (APIENTRYP PFNGLCOLORMATERIALPROC)(GLenum face, GLenum mode); GLAPI PFNGLCOLORMATERIALPROC glad_glColorMaterial; #define glColorMaterial glad_glColorMaterial typedef void (APIENTRYP PFNGLFOGFPROC)(GLenum pname, GLfloat param); GLAPI PFNGLFOGFPROC glad_glFogf; #define glFogf glad_glFogf typedef void (APIENTRYP PFNGLFOGFVPROC)(GLenum pname, const GLfloat *params); GLAPI PFNGLFOGFVPROC glad_glFogfv; #define glFogfv glad_glFogfv typedef void (APIENTRYP PFNGLFOGIPROC)(GLenum pname, GLint param); GLAPI PFNGLFOGIPROC glad_glFogi; #define glFogi glad_glFogi typedef void (APIENTRYP PFNGLFOGIVPROC)(GLenum pname, const GLint *params); GLAPI PFNGLFOGIVPROC glad_glFogiv; #define glFogiv glad_glFogiv typedef void (APIENTRYP PFNGLLIGHTFPROC)(GLenum light, GLenum pname, GLfloat param); GLAPI PFNGLLIGHTFPROC glad_glLightf; #define glLightf glad_glLightf typedef void (APIENTRYP PFNGLLIGHTFVPROC)(GLenum light, GLenum pname, const GLfloat *params); GLAPI PFNGLLIGHTFVPROC glad_glLightfv; #define glLightfv glad_glLightfv typedef void (APIENTRYP PFNGLLIGHTIPROC)(GLenum light, GLenum pname, GLint param); GLAPI PFNGLLIGHTIPROC glad_glLighti; #define glLighti glad_glLighti typedef void (APIENTRYP PFNGLLIGHTIVPROC)(GLenum light, GLenum pname, const GLint *params); GLAPI PFNGLLIGHTIVPROC glad_glLightiv; #define glLightiv glad_glLightiv typedef void (APIENTRYP PFNGLLIGHTMODELFPROC)(GLenum pname, GLfloat param); GLAPI PFNGLLIGHTMODELFPROC glad_glLightModelf; #define glLightModelf glad_glLightModelf typedef void (APIENTRYP PFNGLLIGHTMODELFVPROC)(GLenum pname, const GLfloat *params); GLAPI PFNGLLIGHTMODELFVPROC glad_glLightModelfv; #define glLightModelfv glad_glLightModelfv typedef void (APIENTRYP PFNGLLIGHTMODELIPROC)(GLenum pname, GLint param); GLAPI PFNGLLIGHTMODELIPROC glad_glLightModeli; #define glLightModeli glad_glLightModeli typedef void (APIENTRYP PFNGLLIGHTMODELIVPROC)(GLenum pname, const GLint *params); GLAPI PFNGLLIGHTMODELIVPROC glad_glLightModeliv; #define glLightModeliv glad_glLightModeliv typedef void (APIENTRYP PFNGLLINESTIPPLEPROC)(GLint factor, GLushort pattern); GLAPI PFNGLLINESTIPPLEPROC glad_glLineStipple; #define glLineStipple glad_glLineStipple typedef void (APIENTRYP PFNGLMATERIALFPROC)(GLenum face, GLenum pname, GLfloat param); GLAPI PFNGLMATERIALFPROC glad_glMaterialf; #define glMaterialf glad_glMaterialf typedef void (APIENTRYP PFNGLMATERIALFVPROC)(GLenum face, GLenum pname, const GLfloat *params); GLAPI PFNGLMATERIALFVPROC glad_glMaterialfv; #define glMaterialfv glad_glMaterialfv typedef void (APIENTRYP PFNGLMATERIALIPROC)(GLenum face, GLenum pname, GLint param); GLAPI PFNGLMATERIALIPROC glad_glMateriali; #define glMateriali glad_glMateriali typedef void (APIENTRYP PFNGLMATERIALIVPROC)(GLenum face, GLenum pname, const GLint *params); GLAPI PFNGLMATERIALIVPROC glad_glMaterialiv; #define glMaterialiv glad_glMaterialiv typedef void (APIENTRYP PFNGLPOLYGONSTIPPLEPROC)(const GLubyte *mask); GLAPI PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple; #define glPolygonStipple glad_glPolygonStipple typedef void (APIENTRYP PFNGLSHADEMODELPROC)(GLenum mode); GLAPI PFNGLSHADEMODELPROC glad_glShadeModel; #define glShadeModel glad_glShadeModel typedef void (APIENTRYP PFNGLTEXENVFPROC)(GLenum target, GLenum pname, GLfloat param); GLAPI PFNGLTEXENVFPROC glad_glTexEnvf; #define glTexEnvf glad_glTexEnvf typedef void (APIENTRYP PFNGLTEXENVFVPROC)(GLenum target, GLenum pname, const GLfloat *params); GLAPI PFNGLTEXENVFVPROC glad_glTexEnvfv; #define glTexEnvfv glad_glTexEnvfv typedef void (APIENTRYP PFNGLTEXENVIPROC)(GLenum target, GLenum pname, GLint param); GLAPI PFNGLTEXENVIPROC glad_glTexEnvi; #define glTexEnvi glad_glTexEnvi typedef void (APIENTRYP PFNGLTEXENVIVPROC)(GLenum target, GLenum pname, const GLint *params); GLAPI PFNGLTEXENVIVPROC glad_glTexEnviv; #define glTexEnviv glad_glTexEnviv typedef void (APIENTRYP PFNGLTEXGENDPROC)(GLenum coord, GLenum pname, GLdouble param); GLAPI PFNGLTEXGENDPROC glad_glTexGend; #define glTexGend glad_glTexGend typedef void (APIENTRYP PFNGLTEXGENDVPROC)(GLenum coord, GLenum pname, const GLdouble *params); GLAPI PFNGLTEXGENDVPROC glad_glTexGendv; #define glTexGendv glad_glTexGendv typedef void (APIENTRYP PFNGLTEXGENFPROC)(GLenum coord, GLenum pname, GLfloat param); GLAPI PFNGLTEXGENFPROC glad_glTexGenf; #define glTexGenf glad_glTexGenf typedef void (APIENTRYP PFNGLTEXGENFVPROC)(GLenum coord, GLenum pname, const GLfloat *params); GLAPI PFNGLTEXGENFVPROC glad_glTexGenfv; #define glTexGenfv glad_glTexGenfv typedef void (APIENTRYP PFNGLTEXGENIPROC)(GLenum coord, GLenum pname, GLint param); GLAPI PFNGLTEXGENIPROC glad_glTexGeni; #define glTexGeni glad_glTexGeni typedef void (APIENTRYP PFNGLTEXGENIVPROC)(GLenum coord, GLenum pname, const GLint *params); GLAPI PFNGLTEXGENIVPROC glad_glTexGeniv; #define glTexGeniv glad_glTexGeniv typedef void (APIENTRYP PFNGLFEEDBACKBUFFERPROC)(GLsizei size, GLenum type, GLfloat *buffer); GLAPI PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer; #define glFeedbackBuffer glad_glFeedbackBuffer typedef void (APIENTRYP PFNGLSELECTBUFFERPROC)(GLsizei size, GLuint *buffer); GLAPI PFNGLSELECTBUFFERPROC glad_glSelectBuffer; #define glSelectBuffer glad_glSelectBuffer typedef GLint (APIENTRYP PFNGLRENDERMODEPROC)(GLenum mode); GLAPI PFNGLRENDERMODEPROC glad_glRenderMode; #define glRenderMode glad_glRenderMode typedef void (APIENTRYP PFNGLINITNAMESPROC)(void); GLAPI PFNGLINITNAMESPROC glad_glInitNames; #define glInitNames glad_glInitNames typedef void (APIENTRYP PFNGLLOADNAMEPROC)(GLuint name); GLAPI PFNGLLOADNAMEPROC glad_glLoadName; #define glLoadName glad_glLoadName typedef void (APIENTRYP PFNGLPASSTHROUGHPROC)(GLfloat token); GLAPI PFNGLPASSTHROUGHPROC glad_glPassThrough; #define glPassThrough glad_glPassThrough typedef void (APIENTRYP PFNGLPOPNAMEPROC)(void); GLAPI PFNGLPOPNAMEPROC glad_glPopName; #define glPopName glad_glPopName typedef void (APIENTRYP PFNGLPUSHNAMEPROC)(GLuint name); GLAPI PFNGLPUSHNAMEPROC glad_glPushName; #define glPushName glad_glPushName typedef void (APIENTRYP PFNGLCLEARACCUMPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); GLAPI PFNGLCLEARACCUMPROC glad_glClearAccum; #define glClearAccum glad_glClearAccum typedef void (APIENTRYP PFNGLCLEARINDEXPROC)(GLfloat c); GLAPI PFNGLCLEARINDEXPROC glad_glClearIndex; #define glClearIndex glad_glClearIndex typedef void (APIENTRYP PFNGLINDEXMASKPROC)(GLuint mask); GLAPI PFNGLINDEXMASKPROC glad_glIndexMask; #define glIndexMask glad_glIndexMask typedef void (APIENTRYP PFNGLACCUMPROC)(GLenum op, GLfloat value); GLAPI PFNGLACCUMPROC glad_glAccum; #define glAccum glad_glAccum typedef void (APIENTRYP PFNGLPOPATTRIBPROC)(void); GLAPI PFNGLPOPATTRIBPROC glad_glPopAttrib; #define glPopAttrib glad_glPopAttrib typedef void (APIENTRYP PFNGLPUSHATTRIBPROC)(GLbitfield mask); GLAPI PFNGLPUSHATTRIBPROC glad_glPushAttrib; #define glPushAttrib glad_glPushAttrib typedef void (APIENTRYP PFNGLMAP1DPROC)(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points); GLAPI PFNGLMAP1DPROC glad_glMap1d; #define glMap1d glad_glMap1d typedef void (APIENTRYP PFNGLMAP1FPROC)(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points); GLAPI PFNGLMAP1FPROC glad_glMap1f; #define glMap1f glad_glMap1f typedef void (APIENTRYP PFNGLMAP2DPROC)(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points); GLAPI PFNGLMAP2DPROC glad_glMap2d; #define glMap2d glad_glMap2d typedef void (APIENTRYP PFNGLMAP2FPROC)(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points); GLAPI PFNGLMAP2FPROC glad_glMap2f; #define glMap2f glad_glMap2f typedef void (APIENTRYP PFNGLMAPGRID1DPROC)(GLint un, GLdouble u1, GLdouble u2); GLAPI PFNGLMAPGRID1DPROC glad_glMapGrid1d; #define glMapGrid1d glad_glMapGrid1d typedef void (APIENTRYP PFNGLMAPGRID1FPROC)(GLint un, GLfloat u1, GLfloat u2); GLAPI PFNGLMAPGRID1FPROC glad_glMapGrid1f; #define glMapGrid1f glad_glMapGrid1f typedef void (APIENTRYP PFNGLMAPGRID2DPROC)(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2); GLAPI PFNGLMAPGRID2DPROC glad_glMapGrid2d; #define glMapGrid2d glad_glMapGrid2d typedef void (APIENTRYP PFNGLMAPGRID2FPROC)(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2); GLAPI PFNGLMAPGRID2FPROC glad_glMapGrid2f; #define glMapGrid2f glad_glMapGrid2f typedef void (APIENTRYP PFNGLEVALCOORD1DPROC)(GLdouble u); GLAPI PFNGLEVALCOORD1DPROC glad_glEvalCoord1d; #define glEvalCoord1d glad_glEvalCoord1d typedef void (APIENTRYP PFNGLEVALCOORD1DVPROC)(const GLdouble *u); GLAPI PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv; #define glEvalCoord1dv glad_glEvalCoord1dv typedef void (APIENTRYP PFNGLEVALCOORD1FPROC)(GLfloat u); GLAPI PFNGLEVALCOORD1FPROC glad_glEvalCoord1f; #define glEvalCoord1f glad_glEvalCoord1f typedef void (APIENTRYP PFNGLEVALCOORD1FVPROC)(const GLfloat *u); GLAPI PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv; #define glEvalCoord1fv glad_glEvalCoord1fv typedef void (APIENTRYP PFNGLEVALCOORD2DPROC)(GLdouble u, GLdouble v); GLAPI PFNGLEVALCOORD2DPROC glad_glEvalCoord2d; #define glEvalCoord2d glad_glEvalCoord2d typedef void (APIENTRYP PFNGLEVALCOORD2DVPROC)(const GLdouble *u); GLAPI PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv; #define glEvalCoord2dv glad_glEvalCoord2dv typedef void (APIENTRYP PFNGLEVALCOORD2FPROC)(GLfloat u, GLfloat v); GLAPI PFNGLEVALCOORD2FPROC glad_glEvalCoord2f; #define glEvalCoord2f glad_glEvalCoord2f typedef void (APIENTRYP PFNGLEVALCOORD2FVPROC)(const GLfloat *u); GLAPI PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv; #define glEvalCoord2fv glad_glEvalCoord2fv typedef void (APIENTRYP PFNGLEVALMESH1PROC)(GLenum mode, GLint i1, GLint i2); GLAPI PFNGLEVALMESH1PROC glad_glEvalMesh1; #define glEvalMesh1 glad_glEvalMesh1 typedef void (APIENTRYP PFNGLEVALPOINT1PROC)(GLint i); GLAPI PFNGLEVALPOINT1PROC glad_glEvalPoint1; #define glEvalPoint1 glad_glEvalPoint1 typedef void (APIENTRYP PFNGLEVALMESH2PROC)(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2); GLAPI PFNGLEVALMESH2PROC glad_glEvalMesh2; #define glEvalMesh2 glad_glEvalMesh2 typedef void (APIENTRYP PFNGLEVALPOINT2PROC)(GLint i, GLint j); GLAPI PFNGLEVALPOINT2PROC glad_glEvalPoint2; #define glEvalPoint2 glad_glEvalPoint2 typedef void (APIENTRYP PFNGLALPHAFUNCPROC)(GLenum func, GLfloat ref); GLAPI PFNGLALPHAFUNCPROC glad_glAlphaFunc; #define glAlphaFunc glad_glAlphaFunc typedef void (APIENTRYP PFNGLPIXELZOOMPROC)(GLfloat xfactor, GLfloat yfactor); GLAPI PFNGLPIXELZOOMPROC glad_glPixelZoom; #define glPixelZoom glad_glPixelZoom typedef void (APIENTRYP PFNGLPIXELTRANSFERFPROC)(GLenum pname, GLfloat param); GLAPI PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf; #define glPixelTransferf glad_glPixelTransferf typedef void (APIENTRYP PFNGLPIXELTRANSFERIPROC)(GLenum pname, GLint param); GLAPI PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi; #define glPixelTransferi glad_glPixelTransferi typedef void (APIENTRYP PFNGLPIXELMAPFVPROC)(GLenum map, GLsizei mapsize, const GLfloat *values); GLAPI PFNGLPIXELMAPFVPROC glad_glPixelMapfv; #define glPixelMapfv glad_glPixelMapfv typedef void (APIENTRYP PFNGLPIXELMAPUIVPROC)(GLenum map, GLsizei mapsize, const GLuint *values); GLAPI PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv; #define glPixelMapuiv glad_glPixelMapuiv typedef void (APIENTRYP PFNGLPIXELMAPUSVPROC)(GLenum map, GLsizei mapsize, const GLushort *values); GLAPI PFNGLPIXELMAPUSVPROC glad_glPixelMapusv; #define glPixelMapusv glad_glPixelMapusv typedef void (APIENTRYP PFNGLCOPYPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type); GLAPI PFNGLCOPYPIXELSPROC glad_glCopyPixels; #define glCopyPixels glad_glCopyPixels typedef void (APIENTRYP PFNGLDRAWPIXELSPROC)(GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLDRAWPIXELSPROC glad_glDrawPixels; #define glDrawPixels glad_glDrawPixels typedef void (APIENTRYP PFNGLGETCLIPPLANEPROC)(GLenum plane, GLdouble *equation); GLAPI PFNGLGETCLIPPLANEPROC glad_glGetClipPlane; #define glGetClipPlane glad_glGetClipPlane typedef void (APIENTRYP PFNGLGETLIGHTFVPROC)(GLenum light, GLenum pname, GLfloat *params); GLAPI PFNGLGETLIGHTFVPROC glad_glGetLightfv; #define glGetLightfv glad_glGetLightfv typedef void (APIENTRYP PFNGLGETLIGHTIVPROC)(GLenum light, GLenum pname, GLint *params); GLAPI PFNGLGETLIGHTIVPROC glad_glGetLightiv; #define glGetLightiv glad_glGetLightiv typedef void (APIENTRYP PFNGLGETMAPDVPROC)(GLenum target, GLenum query, GLdouble *v); GLAPI PFNGLGETMAPDVPROC glad_glGetMapdv; #define glGetMapdv glad_glGetMapdv typedef void (APIENTRYP PFNGLGETMAPFVPROC)(GLenum target, GLenum query, GLfloat *v); GLAPI PFNGLGETMAPFVPROC glad_glGetMapfv; #define glGetMapfv glad_glGetMapfv typedef void (APIENTRYP PFNGLGETMAPIVPROC)(GLenum target, GLenum query, GLint *v); GLAPI PFNGLGETMAPIVPROC glad_glGetMapiv; #define glGetMapiv glad_glGetMapiv typedef void (APIENTRYP PFNGLGETMATERIALFVPROC)(GLenum face, GLenum pname, GLfloat *params); GLAPI PFNGLGETMATERIALFVPROC glad_glGetMaterialfv; #define glGetMaterialfv glad_glGetMaterialfv typedef void (APIENTRYP PFNGLGETMATERIALIVPROC)(GLenum face, GLenum pname, GLint *params); GLAPI PFNGLGETMATERIALIVPROC glad_glGetMaterialiv; #define glGetMaterialiv glad_glGetMaterialiv typedef void (APIENTRYP PFNGLGETPIXELMAPFVPROC)(GLenum map, GLfloat *values); GLAPI PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv; #define glGetPixelMapfv glad_glGetPixelMapfv typedef void (APIENTRYP PFNGLGETPIXELMAPUIVPROC)(GLenum map, GLuint *values); GLAPI PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv; #define glGetPixelMapuiv glad_glGetPixelMapuiv typedef void (APIENTRYP PFNGLGETPIXELMAPUSVPROC)(GLenum map, GLushort *values); GLAPI PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv; #define glGetPixelMapusv glad_glGetPixelMapusv typedef void (APIENTRYP PFNGLGETPOLYGONSTIPPLEPROC)(GLubyte *mask); GLAPI PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple; #define glGetPolygonStipple glad_glGetPolygonStipple typedef void (APIENTRYP PFNGLGETTEXENVFVPROC)(GLenum target, GLenum pname, GLfloat *params); GLAPI PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv; #define glGetTexEnvfv glad_glGetTexEnvfv typedef void (APIENTRYP PFNGLGETTEXENVIVPROC)(GLenum target, GLenum pname, GLint *params); GLAPI PFNGLGETTEXENVIVPROC glad_glGetTexEnviv; #define glGetTexEnviv glad_glGetTexEnviv typedef void (APIENTRYP PFNGLGETTEXGENDVPROC)(GLenum coord, GLenum pname, GLdouble *params); GLAPI PFNGLGETTEXGENDVPROC glad_glGetTexGendv; #define glGetTexGendv glad_glGetTexGendv typedef void (APIENTRYP PFNGLGETTEXGENFVPROC)(GLenum coord, GLenum pname, GLfloat *params); GLAPI PFNGLGETTEXGENFVPROC glad_glGetTexGenfv; #define glGetTexGenfv glad_glGetTexGenfv typedef void (APIENTRYP PFNGLGETTEXGENIVPROC)(GLenum coord, GLenum pname, GLint *params); GLAPI PFNGLGETTEXGENIVPROC glad_glGetTexGeniv; #define glGetTexGeniv glad_glGetTexGeniv typedef GLboolean (APIENTRYP PFNGLISLISTPROC)(GLuint list); GLAPI PFNGLISLISTPROC glad_glIsList; #define glIsList glad_glIsList typedef void (APIENTRYP PFNGLFRUSTUMPROC)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); GLAPI PFNGLFRUSTUMPROC glad_glFrustum; #define glFrustum glad_glFrustum typedef void (APIENTRYP PFNGLLOADIDENTITYPROC)(void); GLAPI PFNGLLOADIDENTITYPROC glad_glLoadIdentity; #define glLoadIdentity glad_glLoadIdentity typedef void (APIENTRYP PFNGLLOADMATRIXFPROC)(const GLfloat *m); GLAPI PFNGLLOADMATRIXFPROC glad_glLoadMatrixf; #define glLoadMatrixf glad_glLoadMatrixf typedef void (APIENTRYP PFNGLLOADMATRIXDPROC)(const GLdouble *m); GLAPI PFNGLLOADMATRIXDPROC glad_glLoadMatrixd; #define glLoadMatrixd glad_glLoadMatrixd typedef void (APIENTRYP PFNGLMATRIXMODEPROC)(GLenum mode); GLAPI PFNGLMATRIXMODEPROC glad_glMatrixMode; #define glMatrixMode glad_glMatrixMode typedef void (APIENTRYP PFNGLMULTMATRIXFPROC)(const GLfloat *m); GLAPI PFNGLMULTMATRIXFPROC glad_glMultMatrixf; #define glMultMatrixf glad_glMultMatrixf typedef void (APIENTRYP PFNGLMULTMATRIXDPROC)(const GLdouble *m); GLAPI PFNGLMULTMATRIXDPROC glad_glMultMatrixd; #define glMultMatrixd glad_glMultMatrixd typedef void (APIENTRYP PFNGLORTHOPROC)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); GLAPI PFNGLORTHOPROC glad_glOrtho; #define glOrtho glad_glOrtho typedef void (APIENTRYP PFNGLPOPMATRIXPROC)(void); GLAPI PFNGLPOPMATRIXPROC glad_glPopMatrix; #define glPopMatrix glad_glPopMatrix typedef void (APIENTRYP PFNGLPUSHMATRIXPROC)(void); GLAPI PFNGLPUSHMATRIXPROC glad_glPushMatrix; #define glPushMatrix glad_glPushMatrix typedef void (APIENTRYP PFNGLROTATEDPROC)(GLdouble angle, GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLROTATEDPROC glad_glRotated; #define glRotated glad_glRotated typedef void (APIENTRYP PFNGLROTATEFPROC)(GLfloat angle, GLfloat x, GLfloat y, GLfloat z); GLAPI PFNGLROTATEFPROC glad_glRotatef; #define glRotatef glad_glRotatef typedef void (APIENTRYP PFNGLSCALEDPROC)(GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLSCALEDPROC glad_glScaled; #define glScaled glad_glScaled typedef void (APIENTRYP PFNGLSCALEFPROC)(GLfloat x, GLfloat y, GLfloat z); GLAPI PFNGLSCALEFPROC glad_glScalef; #define glScalef glad_glScalef typedef void (APIENTRYP PFNGLTRANSLATEDPROC)(GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLTRANSLATEDPROC glad_glTranslated; #define glTranslated glad_glTranslated typedef void (APIENTRYP PFNGLTRANSLATEFPROC)(GLfloat x, GLfloat y, GLfloat z); GLAPI PFNGLTRANSLATEFPROC glad_glTranslatef; #define glTranslatef glad_glTranslatef #endif #ifndef GL_VERSION_1_1 #define GL_VERSION_1_1 1 GLAPI int GLAD_GL_VERSION_1_1; typedef void (APIENTRYP PFNGLDRAWARRAYSPROC)(GLenum mode, GLint first, GLsizei count); GLAPI PFNGLDRAWARRAYSPROC glad_glDrawArrays; #define glDrawArrays glad_glDrawArrays typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices); GLAPI PFNGLDRAWELEMENTSPROC glad_glDrawElements; #define glDrawElements glad_glDrawElements typedef void (APIENTRYP PFNGLGETPOINTERVPROC)(GLenum pname, void **params); GLAPI PFNGLGETPOINTERVPROC glad_glGetPointerv; #define glGetPointerv glad_glGetPointerv typedef void (APIENTRYP PFNGLPOLYGONOFFSETPROC)(GLfloat factor, GLfloat units); GLAPI PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset; #define glPolygonOffset glad_glPolygonOffset typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); GLAPI PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D; #define glCopyTexImage1D glad_glCopyTexImage1D typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); GLAPI PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D; #define glCopyTexImage2D glad_glCopyTexImage2D typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); GLAPI PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D; #define glCopyTexSubImage1D glad_glCopyTexSubImage1D typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D; #define glCopyTexSubImage2D glad_glCopyTexSubImage2D typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D; #define glTexSubImage1D glad_glTexSubImage1D typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D; #define glTexSubImage2D glad_glTexSubImage2D typedef void (APIENTRYP PFNGLBINDTEXTUREPROC)(GLenum target, GLuint texture); GLAPI PFNGLBINDTEXTUREPROC glad_glBindTexture; #define glBindTexture glad_glBindTexture typedef void (APIENTRYP PFNGLDELETETEXTURESPROC)(GLsizei n, const GLuint *textures); GLAPI PFNGLDELETETEXTURESPROC glad_glDeleteTextures; #define glDeleteTextures glad_glDeleteTextures typedef void (APIENTRYP PFNGLGENTEXTURESPROC)(GLsizei n, GLuint *textures); GLAPI PFNGLGENTEXTURESPROC glad_glGenTextures; #define glGenTextures glad_glGenTextures typedef GLboolean (APIENTRYP PFNGLISTEXTUREPROC)(GLuint texture); GLAPI PFNGLISTEXTUREPROC glad_glIsTexture; #define glIsTexture glad_glIsTexture typedef void (APIENTRYP PFNGLARRAYELEMENTPROC)(GLint i); GLAPI PFNGLARRAYELEMENTPROC glad_glArrayElement; #define glArrayElement glad_glArrayElement typedef void (APIENTRYP PFNGLCOLORPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLCOLORPOINTERPROC glad_glColorPointer; #define glColorPointer glad_glColorPointer typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEPROC)(GLenum array); GLAPI PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState; #define glDisableClientState glad_glDisableClientState typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERPROC)(GLsizei stride, const void *pointer); GLAPI PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer; #define glEdgeFlagPointer glad_glEdgeFlagPointer typedef void (APIENTRYP PFNGLENABLECLIENTSTATEPROC)(GLenum array); GLAPI PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState; #define glEnableClientState glad_glEnableClientState typedef void (APIENTRYP PFNGLINDEXPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLINDEXPOINTERPROC glad_glIndexPointer; #define glIndexPointer glad_glIndexPointer typedef void (APIENTRYP PFNGLINTERLEAVEDARRAYSPROC)(GLenum format, GLsizei stride, const void *pointer); GLAPI PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays; #define glInterleavedArrays glad_glInterleavedArrays typedef void (APIENTRYP PFNGLNORMALPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLNORMALPOINTERPROC glad_glNormalPointer; #define glNormalPointer glad_glNormalPointer typedef void (APIENTRYP PFNGLTEXCOORDPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer; #define glTexCoordPointer glad_glTexCoordPointer typedef void (APIENTRYP PFNGLVERTEXPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLVERTEXPOINTERPROC glad_glVertexPointer; #define glVertexPointer glad_glVertexPointer typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTPROC)(GLsizei n, const GLuint *textures, GLboolean *residences); GLAPI PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident; #define glAreTexturesResident glad_glAreTexturesResident typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESPROC)(GLsizei n, const GLuint *textures, const GLfloat *priorities); GLAPI PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures; #define glPrioritizeTextures glad_glPrioritizeTextures typedef void (APIENTRYP PFNGLINDEXUBPROC)(GLubyte c); GLAPI PFNGLINDEXUBPROC glad_glIndexub; #define glIndexub glad_glIndexub typedef void (APIENTRYP PFNGLINDEXUBVPROC)(const GLubyte *c); GLAPI PFNGLINDEXUBVPROC glad_glIndexubv; #define glIndexubv glad_glIndexubv typedef void (APIENTRYP PFNGLPOPCLIENTATTRIBPROC)(void); GLAPI PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib; #define glPopClientAttrib glad_glPopClientAttrib typedef void (APIENTRYP PFNGLPUSHCLIENTATTRIBPROC)(GLbitfield mask); GLAPI PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib; #define glPushClientAttrib glad_glPushClientAttrib #endif #ifndef GL_VERSION_1_2 #define GL_VERSION_1_2 1 GLAPI int GLAD_GL_VERSION_1_2; typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); GLAPI PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements; #define glDrawRangeElements glad_glDrawRangeElements typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXIMAGE3DPROC glad_glTexImage3D; #define glTexImage3D glad_glTexImage3D typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D; #define glTexSubImage3D glad_glTexSubImage3D typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D; #define glCopyTexSubImage3D glad_glCopyTexSubImage3D #endif #ifndef GL_VERSION_1_3 #define GL_VERSION_1_3 1 GLAPI int GLAD_GL_VERSION_1_3; typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC)(GLenum texture); GLAPI PFNGLACTIVETEXTUREPROC glad_glActiveTexture; #define glActiveTexture glad_glActiveTexture typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC)(GLfloat value, GLboolean invert); GLAPI PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage; #define glSampleCoverage glad_glSampleCoverage typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D; #define glCompressedTexImage3D glad_glCompressedTexImage3D typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D; #define glCompressedTexImage2D glad_glCompressedTexImage2D typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D; #define glCompressedTexImage1D glad_glCompressedTexImage1D typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D; #define glCompressedTexSubImage3D glad_glCompressedTexSubImage3D typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D; #define glCompressedTexSubImage2D glad_glCompressedTexSubImage2D typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D; #define glCompressedTexSubImage1D glad_glCompressedTexSubImage1D typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC)(GLenum target, GLint level, void *img); GLAPI PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage; #define glGetCompressedTexImage glad_glGetCompressedTexImage typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC)(GLenum texture); GLAPI PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture; #define glClientActiveTexture glad_glClientActiveTexture typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC)(GLenum target, GLdouble s); GLAPI PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d; #define glMultiTexCoord1d glad_glMultiTexCoord1d typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC)(GLenum target, const GLdouble *v); GLAPI PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv; #define glMultiTexCoord1dv glad_glMultiTexCoord1dv typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC)(GLenum target, GLfloat s); GLAPI PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f; #define glMultiTexCoord1f glad_glMultiTexCoord1f typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC)(GLenum target, const GLfloat *v); GLAPI PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv; #define glMultiTexCoord1fv glad_glMultiTexCoord1fv typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC)(GLenum target, GLint s); GLAPI PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i; #define glMultiTexCoord1i glad_glMultiTexCoord1i typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC)(GLenum target, const GLint *v); GLAPI PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv; #define glMultiTexCoord1iv glad_glMultiTexCoord1iv typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC)(GLenum target, GLshort s); GLAPI PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s; #define glMultiTexCoord1s glad_glMultiTexCoord1s typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC)(GLenum target, const GLshort *v); GLAPI PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv; #define glMultiTexCoord1sv glad_glMultiTexCoord1sv typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC)(GLenum target, GLdouble s, GLdouble t); GLAPI PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d; #define glMultiTexCoord2d glad_glMultiTexCoord2d typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC)(GLenum target, const GLdouble *v); GLAPI PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv; #define glMultiTexCoord2dv glad_glMultiTexCoord2dv typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC)(GLenum target, GLfloat s, GLfloat t); GLAPI PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f; #define glMultiTexCoord2f glad_glMultiTexCoord2f typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC)(GLenum target, const GLfloat *v); GLAPI PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv; #define glMultiTexCoord2fv glad_glMultiTexCoord2fv typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC)(GLenum target, GLint s, GLint t); GLAPI PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i; #define glMultiTexCoord2i glad_glMultiTexCoord2i typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC)(GLenum target, const GLint *v); GLAPI PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv; #define glMultiTexCoord2iv glad_glMultiTexCoord2iv typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC)(GLenum target, GLshort s, GLshort t); GLAPI PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s; #define glMultiTexCoord2s glad_glMultiTexCoord2s typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC)(GLenum target, const GLshort *v); GLAPI PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv; #define glMultiTexCoord2sv glad_glMultiTexCoord2sv typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r); GLAPI PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d; #define glMultiTexCoord3d glad_glMultiTexCoord3d typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC)(GLenum target, const GLdouble *v); GLAPI PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv; #define glMultiTexCoord3dv glad_glMultiTexCoord3dv typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r); GLAPI PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f; #define glMultiTexCoord3f glad_glMultiTexCoord3f typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC)(GLenum target, const GLfloat *v); GLAPI PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv; #define glMultiTexCoord3fv glad_glMultiTexCoord3fv typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC)(GLenum target, GLint s, GLint t, GLint r); GLAPI PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i; #define glMultiTexCoord3i glad_glMultiTexCoord3i typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC)(GLenum target, const GLint *v); GLAPI PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv; #define glMultiTexCoord3iv glad_glMultiTexCoord3iv typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC)(GLenum target, GLshort s, GLshort t, GLshort r); GLAPI PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s; #define glMultiTexCoord3s glad_glMultiTexCoord3s typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC)(GLenum target, const GLshort *v); GLAPI PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv; #define glMultiTexCoord3sv glad_glMultiTexCoord3sv typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); GLAPI PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d; #define glMultiTexCoord4d glad_glMultiTexCoord4d typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC)(GLenum target, const GLdouble *v); GLAPI PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv; #define glMultiTexCoord4dv glad_glMultiTexCoord4dv typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); GLAPI PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f; #define glMultiTexCoord4f glad_glMultiTexCoord4f typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC)(GLenum target, const GLfloat *v); GLAPI PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv; #define glMultiTexCoord4fv glad_glMultiTexCoord4fv typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC)(GLenum target, GLint s, GLint t, GLint r, GLint q); GLAPI PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i; #define glMultiTexCoord4i glad_glMultiTexCoord4i typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC)(GLenum target, const GLint *v); GLAPI PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv; #define glMultiTexCoord4iv glad_glMultiTexCoord4iv typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC)(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); GLAPI PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s; #define glMultiTexCoord4s glad_glMultiTexCoord4s typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC)(GLenum target, const GLshort *v); GLAPI PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv; #define glMultiTexCoord4sv glad_glMultiTexCoord4sv typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC)(const GLfloat *m); GLAPI PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf; #define glLoadTransposeMatrixf glad_glLoadTransposeMatrixf typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC)(const GLdouble *m); GLAPI PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd; #define glLoadTransposeMatrixd glad_glLoadTransposeMatrixd typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC)(const GLfloat *m); GLAPI PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf; #define glMultTransposeMatrixf glad_glMultTransposeMatrixf typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC)(const GLdouble *m); GLAPI PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd; #define glMultTransposeMatrixd glad_glMultTransposeMatrixd #endif #ifndef GL_VERSION_1_4 #define GL_VERSION_1_4 1 GLAPI int GLAD_GL_VERSION_1_4; typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); GLAPI PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate; #define glBlendFuncSeparate glad_glBlendFuncSeparate typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC)(GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount); GLAPI PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays; #define glMultiDrawArrays glad_glMultiDrawArrays typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC)(GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount); GLAPI PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements; #define glMultiDrawElements glad_glMultiDrawElements typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC)(GLenum pname, GLfloat param); GLAPI PFNGLPOINTPARAMETERFPROC glad_glPointParameterf; #define glPointParameterf glad_glPointParameterf typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC)(GLenum pname, const GLfloat *params); GLAPI PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv; #define glPointParameterfv glad_glPointParameterfv typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC)(GLenum pname, GLint param); GLAPI PFNGLPOINTPARAMETERIPROC glad_glPointParameteri; #define glPointParameteri glad_glPointParameteri typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC)(GLenum pname, const GLint *params); GLAPI PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv; #define glPointParameteriv glad_glPointParameteriv typedef void (APIENTRYP PFNGLFOGCOORDFPROC)(GLfloat coord); GLAPI PFNGLFOGCOORDFPROC glad_glFogCoordf; #define glFogCoordf glad_glFogCoordf typedef void (APIENTRYP PFNGLFOGCOORDFVPROC)(const GLfloat *coord); GLAPI PFNGLFOGCOORDFVPROC glad_glFogCoordfv; #define glFogCoordfv glad_glFogCoordfv typedef void (APIENTRYP PFNGLFOGCOORDDPROC)(GLdouble coord); GLAPI PFNGLFOGCOORDDPROC glad_glFogCoordd; #define glFogCoordd glad_glFogCoordd typedef void (APIENTRYP PFNGLFOGCOORDDVPROC)(const GLdouble *coord); GLAPI PFNGLFOGCOORDDVPROC glad_glFogCoorddv; #define glFogCoorddv glad_glFogCoorddv typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer; #define glFogCoordPointer glad_glFogCoordPointer typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC)(GLbyte red, GLbyte green, GLbyte blue); GLAPI PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b; #define glSecondaryColor3b glad_glSecondaryColor3b typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC)(const GLbyte *v); GLAPI PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv; #define glSecondaryColor3bv glad_glSecondaryColor3bv typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC)(GLdouble red, GLdouble green, GLdouble blue); GLAPI PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d; #define glSecondaryColor3d glad_glSecondaryColor3d typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC)(const GLdouble *v); GLAPI PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv; #define glSecondaryColor3dv glad_glSecondaryColor3dv typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC)(GLfloat red, GLfloat green, GLfloat blue); GLAPI PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f; #define glSecondaryColor3f glad_glSecondaryColor3f typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC)(const GLfloat *v); GLAPI PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv; #define glSecondaryColor3fv glad_glSecondaryColor3fv typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC)(GLint red, GLint green, GLint blue); GLAPI PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i; #define glSecondaryColor3i glad_glSecondaryColor3i typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC)(const GLint *v); GLAPI PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv; #define glSecondaryColor3iv glad_glSecondaryColor3iv typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC)(GLshort red, GLshort green, GLshort blue); GLAPI PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s; #define glSecondaryColor3s glad_glSecondaryColor3s typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC)(const GLshort *v); GLAPI PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv; #define glSecondaryColor3sv glad_glSecondaryColor3sv typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC)(GLubyte red, GLubyte green, GLubyte blue); GLAPI PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub; #define glSecondaryColor3ub glad_glSecondaryColor3ub typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC)(const GLubyte *v); GLAPI PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv; #define glSecondaryColor3ubv glad_glSecondaryColor3ubv typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC)(GLuint red, GLuint green, GLuint blue); GLAPI PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui; #define glSecondaryColor3ui glad_glSecondaryColor3ui typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC)(const GLuint *v); GLAPI PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv; #define glSecondaryColor3uiv glad_glSecondaryColor3uiv typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC)(GLushort red, GLushort green, GLushort blue); GLAPI PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us; #define glSecondaryColor3us glad_glSecondaryColor3us typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC)(const GLushort *v); GLAPI PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv; #define glSecondaryColor3usv glad_glSecondaryColor3usv typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer; #define glSecondaryColorPointer glad_glSecondaryColorPointer typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC)(GLdouble x, GLdouble y); GLAPI PFNGLWINDOWPOS2DPROC glad_glWindowPos2d; #define glWindowPos2d glad_glWindowPos2d typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC)(const GLdouble *v); GLAPI PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv; #define glWindowPos2dv glad_glWindowPos2dv typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC)(GLfloat x, GLfloat y); GLAPI PFNGLWINDOWPOS2FPROC glad_glWindowPos2f; #define glWindowPos2f glad_glWindowPos2f typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC)(const GLfloat *v); GLAPI PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv; #define glWindowPos2fv glad_glWindowPos2fv typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC)(GLint x, GLint y); GLAPI PFNGLWINDOWPOS2IPROC glad_glWindowPos2i; #define glWindowPos2i glad_glWindowPos2i typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC)(const GLint *v); GLAPI PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv; #define glWindowPos2iv glad_glWindowPos2iv typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC)(GLshort x, GLshort y); GLAPI PFNGLWINDOWPOS2SPROC glad_glWindowPos2s; #define glWindowPos2s glad_glWindowPos2s typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC)(const GLshort *v); GLAPI PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv; #define glWindowPos2sv glad_glWindowPos2sv typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC)(GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLWINDOWPOS3DPROC glad_glWindowPos3d; #define glWindowPos3d glad_glWindowPos3d typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC)(const GLdouble *v); GLAPI PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv; #define glWindowPos3dv glad_glWindowPos3dv typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC)(GLfloat x, GLfloat y, GLfloat z); GLAPI PFNGLWINDOWPOS3FPROC glad_glWindowPos3f; #define glWindowPos3f glad_glWindowPos3f typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC)(const GLfloat *v); GLAPI PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv; #define glWindowPos3fv glad_glWindowPos3fv typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC)(GLint x, GLint y, GLint z); GLAPI PFNGLWINDOWPOS3IPROC glad_glWindowPos3i; #define glWindowPos3i glad_glWindowPos3i typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC)(const GLint *v); GLAPI PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv; #define glWindowPos3iv glad_glWindowPos3iv typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC)(GLshort x, GLshort y, GLshort z); GLAPI PFNGLWINDOWPOS3SPROC glad_glWindowPos3s; #define glWindowPos3s glad_glWindowPos3s typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC)(const GLshort *v); GLAPI PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv; #define glWindowPos3sv glad_glWindowPos3sv typedef void (APIENTRYP PFNGLBLENDCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); GLAPI PFNGLBLENDCOLORPROC glad_glBlendColor; #define glBlendColor glad_glBlendColor typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC)(GLenum mode); GLAPI PFNGLBLENDEQUATIONPROC glad_glBlendEquation; #define glBlendEquation glad_glBlendEquation #endif #ifndef GL_VERSION_1_5 #define GL_VERSION_1_5 1 GLAPI int GLAD_GL_VERSION_1_5; typedef void (APIENTRYP PFNGLGENQUERIESPROC)(GLsizei n, GLuint *ids); GLAPI PFNGLGENQUERIESPROC glad_glGenQueries; #define glGenQueries glad_glGenQueries typedef void (APIENTRYP PFNGLDELETEQUERIESPROC)(GLsizei n, const GLuint *ids); GLAPI PFNGLDELETEQUERIESPROC glad_glDeleteQueries; #define glDeleteQueries glad_glDeleteQueries typedef GLboolean (APIENTRYP PFNGLISQUERYPROC)(GLuint id); GLAPI PFNGLISQUERYPROC glad_glIsQuery; #define glIsQuery glad_glIsQuery typedef void (APIENTRYP PFNGLBEGINQUERYPROC)(GLenum target, GLuint id); GLAPI PFNGLBEGINQUERYPROC glad_glBeginQuery; #define glBeginQuery glad_glBeginQuery typedef void (APIENTRYP PFNGLENDQUERYPROC)(GLenum target); GLAPI PFNGLENDQUERYPROC glad_glEndQuery; #define glEndQuery glad_glEndQuery typedef void (APIENTRYP PFNGLGETQUERYIVPROC)(GLenum target, GLenum pname, GLint *params); GLAPI PFNGLGETQUERYIVPROC glad_glGetQueryiv; #define glGetQueryiv glad_glGetQueryiv typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC)(GLuint id, GLenum pname, GLint *params); GLAPI PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv; #define glGetQueryObjectiv glad_glGetQueryObjectiv typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC)(GLuint id, GLenum pname, GLuint *params); GLAPI PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv; #define glGetQueryObjectuiv glad_glGetQueryObjectuiv typedef void (APIENTRYP PFNGLBINDBUFFERPROC)(GLenum target, GLuint buffer); GLAPI PFNGLBINDBUFFERPROC glad_glBindBuffer; #define glBindBuffer glad_glBindBuffer typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC)(GLsizei n, const GLuint *buffers); GLAPI PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers; #define glDeleteBuffers glad_glDeleteBuffers typedef void (APIENTRYP PFNGLGENBUFFERSPROC)(GLsizei n, GLuint *buffers); GLAPI PFNGLGENBUFFERSPROC glad_glGenBuffers; #define glGenBuffers glad_glGenBuffers typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC)(GLuint buffer); GLAPI PFNGLISBUFFERPROC glad_glIsBuffer; #define glIsBuffer glad_glIsBuffer typedef void (APIENTRYP PFNGLBUFFERDATAPROC)(GLenum target, GLsizeiptr size, const void *data, GLenum usage); GLAPI PFNGLBUFFERDATAPROC glad_glBufferData; #define glBufferData glad_glBufferData typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC)(GLenum target, GLintptr offset, GLsizeiptr size, const void *data); GLAPI PFNGLBUFFERSUBDATAPROC glad_glBufferSubData; #define glBufferSubData glad_glBufferSubData typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC)(GLenum target, GLintptr offset, GLsizeiptr size, void *data); GLAPI PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData; #define glGetBufferSubData glad_glGetBufferSubData typedef void * (APIENTRYP PFNGLMAPBUFFERPROC)(GLenum target, GLenum access); GLAPI PFNGLMAPBUFFERPROC glad_glMapBuffer; #define glMapBuffer glad_glMapBuffer typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC)(GLenum target); GLAPI PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer; #define glUnmapBuffer glad_glUnmapBuffer typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); GLAPI PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv; #define glGetBufferParameteriv glad_glGetBufferParameteriv typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC)(GLenum target, GLenum pname, void **params); GLAPI PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv; #define glGetBufferPointerv glad_glGetBufferPointerv #endif #ifndef GL_VERSION_2_0 #define GL_VERSION_2_0 1 GLAPI int GLAD_GL_VERSION_2_0; typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC)(GLenum modeRGB, GLenum modeAlpha); GLAPI PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate; #define glBlendEquationSeparate glad_glBlendEquationSeparate typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC)(GLsizei n, const GLenum *bufs); GLAPI PFNGLDRAWBUFFERSPROC glad_glDrawBuffers; #define glDrawBuffers glad_glDrawBuffers typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC)(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); GLAPI PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate; #define glStencilOpSeparate glad_glStencilOpSeparate typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC)(GLenum face, GLenum func, GLint ref, GLuint mask); GLAPI PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate; #define glStencilFuncSeparate glad_glStencilFuncSeparate typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC)(GLenum face, GLuint mask); GLAPI PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate; #define glStencilMaskSeparate glad_glStencilMaskSeparate typedef void (APIENTRYP PFNGLATTACHSHADERPROC)(GLuint program, GLuint shader); GLAPI PFNGLATTACHSHADERPROC glad_glAttachShader; #define glAttachShader glad_glAttachShader typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC)(GLuint program, GLuint index, const GLchar *name); GLAPI PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation; #define glBindAttribLocation glad_glBindAttribLocation typedef void (APIENTRYP PFNGLCOMPILESHADERPROC)(GLuint shader); GLAPI PFNGLCOMPILESHADERPROC glad_glCompileShader; #define glCompileShader glad_glCompileShader typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC)(void); GLAPI PFNGLCREATEPROGRAMPROC glad_glCreateProgram; #define glCreateProgram glad_glCreateProgram typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC)(GLenum type); GLAPI PFNGLCREATESHADERPROC glad_glCreateShader; #define glCreateShader glad_glCreateShader typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC)(GLuint program); GLAPI PFNGLDELETEPROGRAMPROC glad_glDeleteProgram; #define glDeleteProgram glad_glDeleteProgram typedef void (APIENTRYP PFNGLDELETESHADERPROC)(GLuint shader); GLAPI PFNGLDELETESHADERPROC glad_glDeleteShader; #define glDeleteShader glad_glDeleteShader typedef void (APIENTRYP PFNGLDETACHSHADERPROC)(GLuint program, GLuint shader); GLAPI PFNGLDETACHSHADERPROC glad_glDetachShader; #define glDetachShader glad_glDetachShader typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC)(GLuint index); GLAPI PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray; #define glDisableVertexAttribArray glad_glDisableVertexAttribArray typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC)(GLuint index); GLAPI PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray; #define glEnableVertexAttribArray glad_glEnableVertexAttribArray typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); GLAPI PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib; #define glGetActiveAttrib glad_glGetActiveAttrib typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); GLAPI PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform; #define glGetActiveUniform glad_glGetActiveUniform typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC)(GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); GLAPI PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders; #define glGetAttachedShaders glad_glGetAttachedShaders typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC)(GLuint program, const GLchar *name); GLAPI PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation; #define glGetAttribLocation glad_glGetAttribLocation typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC)(GLuint program, GLenum pname, GLint *params); GLAPI PFNGLGETPROGRAMIVPROC glad_glGetProgramiv; #define glGetProgramiv glad_glGetProgramiv typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC)(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); GLAPI PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog; #define glGetProgramInfoLog glad_glGetProgramInfoLog typedef void (APIENTRYP PFNGLGETSHADERIVPROC)(GLuint shader, GLenum pname, GLint *params); GLAPI PFNGLGETSHADERIVPROC glad_glGetShaderiv; #define glGetShaderiv glad_glGetShaderiv typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); GLAPI PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog; #define glGetShaderInfoLog glad_glGetShaderInfoLog typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); GLAPI PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource; #define glGetShaderSource glad_glGetShaderSource typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC)(GLuint program, const GLchar *name); GLAPI PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation; #define glGetUniformLocation glad_glGetUniformLocation typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC)(GLuint program, GLint location, GLfloat *params); GLAPI PFNGLGETUNIFORMFVPROC glad_glGetUniformfv; #define glGetUniformfv glad_glGetUniformfv typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC)(GLuint program, GLint location, GLint *params); GLAPI PFNGLGETUNIFORMIVPROC glad_glGetUniformiv; #define glGetUniformiv glad_glGetUniformiv typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC)(GLuint index, GLenum pname, GLdouble *params); GLAPI PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv; #define glGetVertexAttribdv glad_glGetVertexAttribdv typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC)(GLuint index, GLenum pname, GLfloat *params); GLAPI PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv; #define glGetVertexAttribfv glad_glGetVertexAttribfv typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC)(GLuint index, GLenum pname, GLint *params); GLAPI PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv; #define glGetVertexAttribiv glad_glGetVertexAttribiv typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC)(GLuint index, GLenum pname, void **pointer); GLAPI PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv; #define glGetVertexAttribPointerv glad_glGetVertexAttribPointerv typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC)(GLuint program); GLAPI PFNGLISPROGRAMPROC glad_glIsProgram; #define glIsProgram glad_glIsProgram typedef GLboolean (APIENTRYP PFNGLISSHADERPROC)(GLuint shader); GLAPI PFNGLISSHADERPROC glad_glIsShader; #define glIsShader glad_glIsShader typedef void (APIENTRYP PFNGLLINKPROGRAMPROC)(GLuint program); GLAPI PFNGLLINKPROGRAMPROC glad_glLinkProgram; #define glLinkProgram glad_glLinkProgram typedef void (APIENTRYP PFNGLSHADERSOURCEPROC)(GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); GLAPI PFNGLSHADERSOURCEPROC glad_glShaderSource; #define glShaderSource glad_glShaderSource typedef void (APIENTRYP PFNGLUSEPROGRAMPROC)(GLuint program); GLAPI PFNGLUSEPROGRAMPROC glad_glUseProgram; #define glUseProgram glad_glUseProgram typedef void (APIENTRYP PFNGLUNIFORM1FPROC)(GLint location, GLfloat v0); GLAPI PFNGLUNIFORM1FPROC glad_glUniform1f; #define glUniform1f glad_glUniform1f typedef void (APIENTRYP PFNGLUNIFORM2FPROC)(GLint location, GLfloat v0, GLfloat v1); GLAPI PFNGLUNIFORM2FPROC glad_glUniform2f; #define glUniform2f glad_glUniform2f typedef void (APIENTRYP PFNGLUNIFORM3FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2); GLAPI PFNGLUNIFORM3FPROC glad_glUniform3f; #define glUniform3f glad_glUniform3f typedef void (APIENTRYP PFNGLUNIFORM4FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); GLAPI PFNGLUNIFORM4FPROC glad_glUniform4f; #define glUniform4f glad_glUniform4f typedef void (APIENTRYP PFNGLUNIFORM1IPROC)(GLint location, GLint v0); GLAPI PFNGLUNIFORM1IPROC glad_glUniform1i; #define glUniform1i glad_glUniform1i typedef void (APIENTRYP PFNGLUNIFORM2IPROC)(GLint location, GLint v0, GLint v1); GLAPI PFNGLUNIFORM2IPROC glad_glUniform2i; #define glUniform2i glad_glUniform2i typedef void (APIENTRYP PFNGLUNIFORM3IPROC)(GLint location, GLint v0, GLint v1, GLint v2); GLAPI PFNGLUNIFORM3IPROC glad_glUniform3i; #define glUniform3i glad_glUniform3i typedef void (APIENTRYP PFNGLUNIFORM4IPROC)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3); GLAPI PFNGLUNIFORM4IPROC glad_glUniform4i; #define glUniform4i glad_glUniform4i typedef void (APIENTRYP PFNGLUNIFORM1FVPROC)(GLint location, GLsizei count, const GLfloat *value); GLAPI PFNGLUNIFORM1FVPROC glad_glUniform1fv; #define glUniform1fv glad_glUniform1fv typedef void (APIENTRYP PFNGLUNIFORM2FVPROC)(GLint location, GLsizei count, const GLfloat *value); GLAPI PFNGLUNIFORM2FVPROC glad_glUniform2fv; #define glUniform2fv glad_glUniform2fv typedef void (APIENTRYP PFNGLUNIFORM3FVPROC)(GLint location, GLsizei count, const GLfloat *value); GLAPI PFNGLUNIFORM3FVPROC glad_glUniform3fv; #define glUniform3fv glad_glUniform3fv typedef void (APIENTRYP PFNGLUNIFORM4FVPROC)(GLint location, GLsizei count, const GLfloat *value); GLAPI PFNGLUNIFORM4FVPROC glad_glUniform4fv; #define glUniform4fv glad_glUniform4fv typedef void (APIENTRYP PFNGLUNIFORM1IVPROC)(GLint location, GLsizei count, const GLint *value); GLAPI PFNGLUNIFORM1IVPROC glad_glUniform1iv; #define glUniform1iv glad_glUniform1iv typedef void (APIENTRYP PFNGLUNIFORM2IVPROC)(GLint location, GLsizei count, const GLint *value); GLAPI PFNGLUNIFORM2IVPROC glad_glUniform2iv; #define glUniform2iv glad_glUniform2iv typedef void (APIENTRYP PFNGLUNIFORM3IVPROC)(GLint location, GLsizei count, const GLint *value); GLAPI PFNGLUNIFORM3IVPROC glad_glUniform3iv; #define glUniform3iv glad_glUniform3iv typedef void (APIENTRYP PFNGLUNIFORM4IVPROC)(GLint location, GLsizei count, const GLint *value); GLAPI PFNGLUNIFORM4IVPROC glad_glUniform4iv; #define glUniform4iv glad_glUniform4iv typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv; #define glUniformMatrix2fv glad_glUniformMatrix2fv typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv; #define glUniformMatrix3fv glad_glUniformMatrix3fv typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv; #define glUniformMatrix4fv glad_glUniformMatrix4fv typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC)(GLuint program); GLAPI PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram; #define glValidateProgram glad_glValidateProgram typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC)(GLuint index, GLdouble x); GLAPI PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d; #define glVertexAttrib1d glad_glVertexAttrib1d typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC)(GLuint index, const GLdouble *v); GLAPI PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv; #define glVertexAttrib1dv glad_glVertexAttrib1dv typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC)(GLuint index, GLfloat x); GLAPI PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f; #define glVertexAttrib1f glad_glVertexAttrib1f typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC)(GLuint index, const GLfloat *v); GLAPI PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv; #define glVertexAttrib1fv glad_glVertexAttrib1fv typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC)(GLuint index, GLshort x); GLAPI PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s; #define glVertexAttrib1s glad_glVertexAttrib1s typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC)(GLuint index, const GLshort *v); GLAPI PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv; #define glVertexAttrib1sv glad_glVertexAttrib1sv typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC)(GLuint index, GLdouble x, GLdouble y); GLAPI PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d; #define glVertexAttrib2d glad_glVertexAttrib2d typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC)(GLuint index, const GLdouble *v); GLAPI PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv; #define glVertexAttrib2dv glad_glVertexAttrib2dv typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC)(GLuint index, GLfloat x, GLfloat y); GLAPI PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f; #define glVertexAttrib2f glad_glVertexAttrib2f typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC)(GLuint index, const GLfloat *v); GLAPI PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv; #define glVertexAttrib2fv glad_glVertexAttrib2fv typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC)(GLuint index, GLshort x, GLshort y); GLAPI PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s; #define glVertexAttrib2s glad_glVertexAttrib2s typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC)(GLuint index, const GLshort *v); GLAPI PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv; #define glVertexAttrib2sv glad_glVertexAttrib2sv typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d; #define glVertexAttrib3d glad_glVertexAttrib3d typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC)(GLuint index, const GLdouble *v); GLAPI PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv; #define glVertexAttrib3dv glad_glVertexAttrib3dv typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z); GLAPI PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f; #define glVertexAttrib3f glad_glVertexAttrib3f typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC)(GLuint index, const GLfloat *v); GLAPI PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv; #define glVertexAttrib3fv glad_glVertexAttrib3fv typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC)(GLuint index, GLshort x, GLshort y, GLshort z); GLAPI PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s; #define glVertexAttrib3s glad_glVertexAttrib3s typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC)(GLuint index, const GLshort *v); GLAPI PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv; #define glVertexAttrib3sv glad_glVertexAttrib3sv typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC)(GLuint index, const GLbyte *v); GLAPI PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv; #define glVertexAttrib4Nbv glad_glVertexAttrib4Nbv typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC)(GLuint index, const GLint *v); GLAPI PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv; #define glVertexAttrib4Niv glad_glVertexAttrib4Niv typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC)(GLuint index, const GLshort *v); GLAPI PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv; #define glVertexAttrib4Nsv glad_glVertexAttrib4Nsv typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); GLAPI PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub; #define glVertexAttrib4Nub glad_glVertexAttrib4Nub typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC)(GLuint index, const GLubyte *v); GLAPI PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv; #define glVertexAttrib4Nubv glad_glVertexAttrib4Nubv typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC)(GLuint index, const GLuint *v); GLAPI PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv; #define glVertexAttrib4Nuiv glad_glVertexAttrib4Nuiv typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC)(GLuint index, const GLushort *v); GLAPI PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv; #define glVertexAttrib4Nusv glad_glVertexAttrib4Nusv typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC)(GLuint index, const GLbyte *v); GLAPI PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv; #define glVertexAttrib4bv glad_glVertexAttrib4bv typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); GLAPI PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d; #define glVertexAttrib4d glad_glVertexAttrib4d typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC)(GLuint index, const GLdouble *v); GLAPI PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv; #define glVertexAttrib4dv glad_glVertexAttrib4dv typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); GLAPI PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f; #define glVertexAttrib4f glad_glVertexAttrib4f typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC)(GLuint index, const GLfloat *v); GLAPI PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv; #define glVertexAttrib4fv glad_glVertexAttrib4fv typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC)(GLuint index, const GLint *v); GLAPI PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv; #define glVertexAttrib4iv glad_glVertexAttrib4iv typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); GLAPI PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s; #define glVertexAttrib4s glad_glVertexAttrib4s typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC)(GLuint index, const GLshort *v); GLAPI PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv; #define glVertexAttrib4sv glad_glVertexAttrib4sv typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC)(GLuint index, const GLubyte *v); GLAPI PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv; #define glVertexAttrib4ubv glad_glVertexAttrib4ubv typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC)(GLuint index, const GLuint *v); GLAPI PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv; #define glVertexAttrib4uiv glad_glVertexAttrib4uiv typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC)(GLuint index, const GLushort *v); GLAPI PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv; #define glVertexAttrib4usv glad_glVertexAttrib4usv typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); GLAPI PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer; #define glVertexAttribPointer glad_glVertexAttribPointer #endif #ifndef GL_VERSION_2_1 #define GL_VERSION_2_1 1 GLAPI int GLAD_GL_VERSION_2_1; typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv; #define glUniformMatrix2x3fv glad_glUniformMatrix2x3fv typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv; #define glUniformMatrix3x2fv glad_glUniformMatrix3x2fv typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv; #define glUniformMatrix2x4fv glad_glUniformMatrix2x4fv typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv; #define glUniformMatrix4x2fv glad_glUniformMatrix4x2fv typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv; #define glUniformMatrix3x4fv glad_glUniformMatrix3x4fv typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv; #define glUniformMatrix4x3fv glad_glUniformMatrix4x3fv #endif #ifndef GL_VERSION_3_0 #define GL_VERSION_3_0 1 GLAPI int GLAD_GL_VERSION_3_0; typedef void (APIENTRYP PFNGLCOLORMASKIPROC)(GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); GLAPI PFNGLCOLORMASKIPROC glad_glColorMaski; #define glColorMaski glad_glColorMaski typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC)(GLenum target, GLuint index, GLboolean *data); GLAPI PFNGLGETBOOLEANI_VPROC glad_glGetBooleani_v; #define glGetBooleani_v glad_glGetBooleani_v typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC)(GLenum target, GLuint index, GLint *data); GLAPI PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v; #define glGetIntegeri_v glad_glGetIntegeri_v typedef void (APIENTRYP PFNGLENABLEIPROC)(GLenum target, GLuint index); GLAPI PFNGLENABLEIPROC glad_glEnablei; #define glEnablei glad_glEnablei typedef void (APIENTRYP PFNGLDISABLEIPROC)(GLenum target, GLuint index); GLAPI PFNGLDISABLEIPROC glad_glDisablei; #define glDisablei glad_glDisablei typedef GLboolean (APIENTRYP PFNGLISENABLEDIPROC)(GLenum target, GLuint index); GLAPI PFNGLISENABLEDIPROC glad_glIsEnabledi; #define glIsEnabledi glad_glIsEnabledi typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKPROC)(GLenum primitiveMode); GLAPI PFNGLBEGINTRANSFORMFEEDBACKPROC glad_glBeginTransformFeedback; #define glBeginTransformFeedback glad_glBeginTransformFeedback typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKPROC)(void); GLAPI PFNGLENDTRANSFORMFEEDBACKPROC glad_glEndTransformFeedback; #define glEndTransformFeedback glad_glEndTransformFeedback typedef void (APIENTRYP PFNGLBINDBUFFERRANGEPROC)(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); GLAPI PFNGLBINDBUFFERRANGEPROC glad_glBindBufferRange; #define glBindBufferRange glad_glBindBufferRange typedef void (APIENTRYP PFNGLBINDBUFFERBASEPROC)(GLenum target, GLuint index, GLuint buffer); GLAPI PFNGLBINDBUFFERBASEPROC glad_glBindBufferBase; #define glBindBufferBase glad_glBindBufferBase typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSPROC)(GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); GLAPI PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings; #define glTransformFeedbackVaryings glad_glTransformFeedbackVaryings typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); GLAPI PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying; #define glGetTransformFeedbackVarying glad_glGetTransformFeedbackVarying typedef void (APIENTRYP PFNGLCLAMPCOLORPROC)(GLenum target, GLenum clamp); GLAPI PFNGLCLAMPCOLORPROC glad_glClampColor; #define glClampColor glad_glClampColor typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERPROC)(GLuint id, GLenum mode); GLAPI PFNGLBEGINCONDITIONALRENDERPROC glad_glBeginConditionalRender; #define glBeginConditionalRender glad_glBeginConditionalRender typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERPROC)(void); GLAPI PFNGLENDCONDITIONALRENDERPROC glad_glEndConditionalRender; #define glEndConditionalRender glad_glEndConditionalRender typedef void (APIENTRYP PFNGLVERTEXATTRIBIPOINTERPROC)(GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLVERTEXATTRIBIPOINTERPROC glad_glVertexAttribIPointer; #define glVertexAttribIPointer glad_glVertexAttribIPointer typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVPROC)(GLuint index, GLenum pname, GLint *params); GLAPI PFNGLGETVERTEXATTRIBIIVPROC glad_glGetVertexAttribIiv; #define glGetVertexAttribIiv glad_glGetVertexAttribIiv typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVPROC)(GLuint index, GLenum pname, GLuint *params); GLAPI PFNGLGETVERTEXATTRIBIUIVPROC glad_glGetVertexAttribIuiv; #define glGetVertexAttribIuiv glad_glGetVertexAttribIuiv typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IPROC)(GLuint index, GLint x); GLAPI PFNGLVERTEXATTRIBI1IPROC glad_glVertexAttribI1i; #define glVertexAttribI1i glad_glVertexAttribI1i typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IPROC)(GLuint index, GLint x, GLint y); GLAPI PFNGLVERTEXATTRIBI2IPROC glad_glVertexAttribI2i; #define glVertexAttribI2i glad_glVertexAttribI2i typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IPROC)(GLuint index, GLint x, GLint y, GLint z); GLAPI PFNGLVERTEXATTRIBI3IPROC glad_glVertexAttribI3i; #define glVertexAttribI3i glad_glVertexAttribI3i typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IPROC)(GLuint index, GLint x, GLint y, GLint z, GLint w); GLAPI PFNGLVERTEXATTRIBI4IPROC glad_glVertexAttribI4i; #define glVertexAttribI4i glad_glVertexAttribI4i typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIPROC)(GLuint index, GLuint x); GLAPI PFNGLVERTEXATTRIBI1UIPROC glad_glVertexAttribI1ui; #define glVertexAttribI1ui glad_glVertexAttribI1ui typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIPROC)(GLuint index, GLuint x, GLuint y); GLAPI PFNGLVERTEXATTRIBI2UIPROC glad_glVertexAttribI2ui; #define glVertexAttribI2ui glad_glVertexAttribI2ui typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIPROC)(GLuint index, GLuint x, GLuint y, GLuint z); GLAPI PFNGLVERTEXATTRIBI3UIPROC glad_glVertexAttribI3ui; #define glVertexAttribI3ui glad_glVertexAttribI3ui typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIPROC)(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); GLAPI PFNGLVERTEXATTRIBI4UIPROC glad_glVertexAttribI4ui; #define glVertexAttribI4ui glad_glVertexAttribI4ui typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IVPROC)(GLuint index, const GLint *v); GLAPI PFNGLVERTEXATTRIBI1IVPROC glad_glVertexAttribI1iv; #define glVertexAttribI1iv glad_glVertexAttribI1iv typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IVPROC)(GLuint index, const GLint *v); GLAPI PFNGLVERTEXATTRIBI2IVPROC glad_glVertexAttribI2iv; #define glVertexAttribI2iv glad_glVertexAttribI2iv typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IVPROC)(GLuint index, const GLint *v); GLAPI PFNGLVERTEXATTRIBI3IVPROC glad_glVertexAttribI3iv; #define glVertexAttribI3iv glad_glVertexAttribI3iv typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IVPROC)(GLuint index, const GLint *v); GLAPI PFNGLVERTEXATTRIBI4IVPROC glad_glVertexAttribI4iv; #define glVertexAttribI4iv glad_glVertexAttribI4iv typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIVPROC)(GLuint index, const GLuint *v); GLAPI PFNGLVERTEXATTRIBI1UIVPROC glad_glVertexAttribI1uiv; #define glVertexAttribI1uiv glad_glVertexAttribI1uiv typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIVPROC)(GLuint index, const GLuint *v); GLAPI PFNGLVERTEXATTRIBI2UIVPROC glad_glVertexAttribI2uiv; #define glVertexAttribI2uiv glad_glVertexAttribI2uiv typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIVPROC)(GLuint index, const GLuint *v); GLAPI PFNGLVERTEXATTRIBI3UIVPROC glad_glVertexAttribI3uiv; #define glVertexAttribI3uiv glad_glVertexAttribI3uiv typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIVPROC)(GLuint index, const GLuint *v); GLAPI PFNGLVERTEXATTRIBI4UIVPROC glad_glVertexAttribI4uiv; #define glVertexAttribI4uiv glad_glVertexAttribI4uiv typedef void (APIENTRYP PFNGLVERTEXATTRIBI4BVPROC)(GLuint index, const GLbyte *v); GLAPI PFNGLVERTEXATTRIBI4BVPROC glad_glVertexAttribI4bv; #define glVertexAttribI4bv glad_glVertexAttribI4bv typedef void (APIENTRYP PFNGLVERTEXATTRIBI4SVPROC)(GLuint index, const GLshort *v); GLAPI PFNGLVERTEXATTRIBI4SVPROC glad_glVertexAttribI4sv; #define glVertexAttribI4sv glad_glVertexAttribI4sv typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UBVPROC)(GLuint index, const GLubyte *v); GLAPI PFNGLVERTEXATTRIBI4UBVPROC glad_glVertexAttribI4ubv; #define glVertexAttribI4ubv glad_glVertexAttribI4ubv typedef void (APIENTRYP PFNGLVERTEXATTRIBI4USVPROC)(GLuint index, const GLushort *v); GLAPI PFNGLVERTEXATTRIBI4USVPROC glad_glVertexAttribI4usv; #define glVertexAttribI4usv glad_glVertexAttribI4usv typedef void (APIENTRYP PFNGLGETUNIFORMUIVPROC)(GLuint program, GLint location, GLuint *params); GLAPI PFNGLGETUNIFORMUIVPROC glad_glGetUniformuiv; #define glGetUniformuiv glad_glGetUniformuiv typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONPROC)(GLuint program, GLuint color, const GLchar *name); GLAPI PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation; #define glBindFragDataLocation glad_glBindFragDataLocation typedef GLint (APIENTRYP PFNGLGETFRAGDATALOCATIONPROC)(GLuint program, const GLchar *name); GLAPI PFNGLGETFRAGDATALOCATIONPROC glad_glGetFragDataLocation; #define glGetFragDataLocation glad_glGetFragDataLocation typedef void (APIENTRYP PFNGLUNIFORM1UIPROC)(GLint location, GLuint v0); GLAPI PFNGLUNIFORM1UIPROC glad_glUniform1ui; #define glUniform1ui glad_glUniform1ui typedef void (APIENTRYP PFNGLUNIFORM2UIPROC)(GLint location, GLuint v0, GLuint v1); GLAPI PFNGLUNIFORM2UIPROC glad_glUniform2ui; #define glUniform2ui glad_glUniform2ui typedef void (APIENTRYP PFNGLUNIFORM3UIPROC)(GLint location, GLuint v0, GLuint v1, GLuint v2); GLAPI PFNGLUNIFORM3UIPROC glad_glUniform3ui; #define glUniform3ui glad_glUniform3ui typedef void (APIENTRYP PFNGLUNIFORM4UIPROC)(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); GLAPI PFNGLUNIFORM4UIPROC glad_glUniform4ui; #define glUniform4ui glad_glUniform4ui typedef void (APIENTRYP PFNGLUNIFORM1UIVPROC)(GLint location, GLsizei count, const GLuint *value); GLAPI PFNGLUNIFORM1UIVPROC glad_glUniform1uiv; #define glUniform1uiv glad_glUniform1uiv typedef void (APIENTRYP PFNGLUNIFORM2UIVPROC)(GLint location, GLsizei count, const GLuint *value); GLAPI PFNGLUNIFORM2UIVPROC glad_glUniform2uiv; #define glUniform2uiv glad_glUniform2uiv typedef void (APIENTRYP PFNGLUNIFORM3UIVPROC)(GLint location, GLsizei count, const GLuint *value); GLAPI PFNGLUNIFORM3UIVPROC glad_glUniform3uiv; #define glUniform3uiv glad_glUniform3uiv typedef void (APIENTRYP PFNGLUNIFORM4UIVPROC)(GLint location, GLsizei count, const GLuint *value); GLAPI PFNGLUNIFORM4UIVPROC glad_glUniform4uiv; #define glUniform4uiv glad_glUniform4uiv typedef void (APIENTRYP PFNGLTEXPARAMETERIIVPROC)(GLenum target, GLenum pname, const GLint *params); GLAPI PFNGLTEXPARAMETERIIVPROC glad_glTexParameterIiv; #define glTexParameterIiv glad_glTexParameterIiv typedef void (APIENTRYP PFNGLTEXPARAMETERIUIVPROC)(GLenum target, GLenum pname, const GLuint *params); GLAPI PFNGLTEXPARAMETERIUIVPROC glad_glTexParameterIuiv; #define glTexParameterIuiv glad_glTexParameterIuiv typedef void (APIENTRYP PFNGLGETTEXPARAMETERIIVPROC)(GLenum target, GLenum pname, GLint *params); GLAPI PFNGLGETTEXPARAMETERIIVPROC glad_glGetTexParameterIiv; #define glGetTexParameterIiv glad_glGetTexParameterIiv typedef void (APIENTRYP PFNGLGETTEXPARAMETERIUIVPROC)(GLenum target, GLenum pname, GLuint *params); GLAPI PFNGLGETTEXPARAMETERIUIVPROC glad_glGetTexParameterIuiv; #define glGetTexParameterIuiv glad_glGetTexParameterIuiv typedef void (APIENTRYP PFNGLCLEARBUFFERIVPROC)(GLenum buffer, GLint drawbuffer, const GLint *value); GLAPI PFNGLCLEARBUFFERIVPROC glad_glClearBufferiv; #define glClearBufferiv glad_glClearBufferiv typedef void (APIENTRYP PFNGLCLEARBUFFERUIVPROC)(GLenum buffer, GLint drawbuffer, const GLuint *value); GLAPI PFNGLCLEARBUFFERUIVPROC glad_glClearBufferuiv; #define glClearBufferuiv glad_glClearBufferuiv typedef void (APIENTRYP PFNGLCLEARBUFFERFVPROC)(GLenum buffer, GLint drawbuffer, const GLfloat *value); GLAPI PFNGLCLEARBUFFERFVPROC glad_glClearBufferfv; #define glClearBufferfv glad_glClearBufferfv typedef void (APIENTRYP PFNGLCLEARBUFFERFIPROC)(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); GLAPI PFNGLCLEARBUFFERFIPROC glad_glClearBufferfi; #define glClearBufferfi glad_glClearBufferfi typedef const GLubyte * (APIENTRYP PFNGLGETSTRINGIPROC)(GLenum name, GLuint index); GLAPI PFNGLGETSTRINGIPROC glad_glGetStringi; #define glGetStringi glad_glGetStringi typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFERPROC)(GLuint renderbuffer); GLAPI PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer; #define glIsRenderbuffer glad_glIsRenderbuffer typedef void (APIENTRYP PFNGLBINDRENDERBUFFERPROC)(GLenum target, GLuint renderbuffer); GLAPI PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer; #define glBindRenderbuffer glad_glBindRenderbuffer typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSPROC)(GLsizei n, const GLuint *renderbuffers); GLAPI PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers; #define glDeleteRenderbuffers glad_glDeleteRenderbuffers typedef void (APIENTRYP PFNGLGENRENDERBUFFERSPROC)(GLsizei n, GLuint *renderbuffers); GLAPI PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers; #define glGenRenderbuffers glad_glGenRenderbuffers typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height); GLAPI PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage; #define glRenderbufferStorage glad_glRenderbufferStorage typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); GLAPI PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv; #define glGetRenderbufferParameteriv glad_glGetRenderbufferParameteriv typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFERPROC)(GLuint framebuffer); GLAPI PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer; #define glIsFramebuffer glad_glIsFramebuffer typedef void (APIENTRYP PFNGLBINDFRAMEBUFFERPROC)(GLenum target, GLuint framebuffer); GLAPI PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer; #define glBindFramebuffer glad_glBindFramebuffer typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC)(GLsizei n, const GLuint *framebuffers); GLAPI PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers; #define glDeleteFramebuffers glad_glDeleteFramebuffers typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSPROC)(GLsizei n, GLuint *framebuffers); GLAPI PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers; #define glGenFramebuffers glad_glGenFramebuffers typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC)(GLenum target); GLAPI PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus; #define glCheckFramebufferStatus glad_glCheckFramebufferStatus typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); GLAPI PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D; #define glFramebufferTexture1D glad_glFramebufferTexture1D typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); GLAPI PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D; #define glFramebufferTexture2D glad_glFramebufferTexture2D typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); GLAPI PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D; #define glFramebufferTexture3D glad_glFramebufferTexture3D typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); GLAPI PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer; #define glFramebufferRenderbuffer glad_glFramebufferRenderbuffer typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)(GLenum target, GLenum attachment, GLenum pname, GLint *params); GLAPI PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv; #define glGetFramebufferAttachmentParameteriv glad_glGetFramebufferAttachmentParameteriv typedef void (APIENTRYP PFNGLGENERATEMIPMAPPROC)(GLenum target); GLAPI PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap; #define glGenerateMipmap glad_glGenerateMipmap typedef void (APIENTRYP PFNGLBLITFRAMEBUFFERPROC)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); GLAPI PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer; #define glBlitFramebuffer glad_glBlitFramebuffer typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); GLAPI PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample; #define glRenderbufferStorageMultisample glad_glRenderbufferStorageMultisample typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); GLAPI PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer; #define glFramebufferTextureLayer glad_glFramebufferTextureLayer typedef void * (APIENTRYP PFNGLMAPBUFFERRANGEPROC)(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); GLAPI PFNGLMAPBUFFERRANGEPROC glad_glMapBufferRange; #define glMapBufferRange glad_glMapBufferRange typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEPROC)(GLenum target, GLintptr offset, GLsizeiptr length); GLAPI PFNGLFLUSHMAPPEDBUFFERRANGEPROC glad_glFlushMappedBufferRange; #define glFlushMappedBufferRange glad_glFlushMappedBufferRange typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC)(GLuint array); GLAPI PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray; #define glBindVertexArray glad_glBindVertexArray typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC)(GLsizei n, const GLuint *arrays); GLAPI PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays; #define glDeleteVertexArrays glad_glDeleteVertexArrays typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC)(GLsizei n, GLuint *arrays); GLAPI PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays; #define glGenVertexArrays glad_glGenVertexArrays typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYPROC)(GLuint array); GLAPI PFNGLISVERTEXARRAYPROC glad_glIsVertexArray; #define glIsVertexArray glad_glIsVertexArray #endif #ifndef GL_VERSION_3_1 #define GL_VERSION_3_1 1 GLAPI int GLAD_GL_VERSION_3_1; typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDPROC)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount); GLAPI PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced; #define glDrawArraysInstanced glad_glDrawArraysInstanced typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); GLAPI PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced; #define glDrawElementsInstanced glad_glDrawElementsInstanced typedef void (APIENTRYP PFNGLTEXBUFFERPROC)(GLenum target, GLenum internalformat, GLuint buffer); GLAPI PFNGLTEXBUFFERPROC glad_glTexBuffer; #define glTexBuffer glad_glTexBuffer typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXPROC)(GLuint index); GLAPI PFNGLPRIMITIVERESTARTINDEXPROC glad_glPrimitiveRestartIndex; #define glPrimitiveRestartIndex glad_glPrimitiveRestartIndex typedef void (APIENTRYP PFNGLCOPYBUFFERSUBDATAPROC)(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); GLAPI PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData; #define glCopyBufferSubData glad_glCopyBufferSubData typedef void (APIENTRYP PFNGLGETUNIFORMINDICESPROC)(GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); GLAPI PFNGLGETUNIFORMINDICESPROC glad_glGetUniformIndices; #define glGetUniformIndices glad_glGetUniformIndices typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMSIVPROC)(GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); GLAPI PFNGLGETACTIVEUNIFORMSIVPROC glad_glGetActiveUniformsiv; #define glGetActiveUniformsiv glad_glGetActiveUniformsiv typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMNAMEPROC)(GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName); GLAPI PFNGLGETACTIVEUNIFORMNAMEPROC glad_glGetActiveUniformName; #define glGetActiveUniformName glad_glGetActiveUniformName typedef GLuint (APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC)(GLuint program, const GLchar *uniformBlockName); GLAPI PFNGLGETUNIFORMBLOCKINDEXPROC glad_glGetUniformBlockIndex; #define glGetUniformBlockIndex glad_glGetUniformBlockIndex typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC)(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); GLAPI PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv; #define glGetActiveUniformBlockiv glad_glGetActiveUniformBlockiv typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); GLAPI PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName; #define glGetActiveUniformBlockName glad_glGetActiveUniformBlockName typedef void (APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC)(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); GLAPI PFNGLUNIFORMBLOCKBINDINGPROC glad_glUniformBlockBinding; #define glUniformBlockBinding glad_glUniformBlockBinding #endif #ifndef GL_VERSION_3_2 #define GL_VERSION_3_2 1 GLAPI int GLAD_GL_VERSION_3_2; typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); GLAPI PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex; #define glDrawElementsBaseVertex glad_glDrawElementsBaseVertex typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); GLAPI PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex; #define glDrawRangeElementsBaseVertex glad_glDrawRangeElementsBaseVertex typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); GLAPI PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex; #define glDrawElementsInstancedBaseVertex glad_glDrawElementsInstancedBaseVertex typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)(GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex); GLAPI PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex; #define glMultiDrawElementsBaseVertex glad_glMultiDrawElementsBaseVertex typedef void (APIENTRYP PFNGLPROVOKINGVERTEXPROC)(GLenum mode); GLAPI PFNGLPROVOKINGVERTEXPROC glad_glProvokingVertex; #define glProvokingVertex glad_glProvokingVertex typedef GLsync (APIENTRYP PFNGLFENCESYNCPROC)(GLenum condition, GLbitfield flags); GLAPI PFNGLFENCESYNCPROC glad_glFenceSync; #define glFenceSync glad_glFenceSync typedef GLboolean (APIENTRYP PFNGLISSYNCPROC)(GLsync sync); GLAPI PFNGLISSYNCPROC glad_glIsSync; #define glIsSync glad_glIsSync typedef void (APIENTRYP PFNGLDELETESYNCPROC)(GLsync sync); GLAPI PFNGLDELETESYNCPROC glad_glDeleteSync; #define glDeleteSync glad_glDeleteSync typedef GLenum (APIENTRYP PFNGLCLIENTWAITSYNCPROC)(GLsync sync, GLbitfield flags, GLuint64 timeout); GLAPI PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync; #define glClientWaitSync glad_glClientWaitSync typedef void (APIENTRYP PFNGLWAITSYNCPROC)(GLsync sync, GLbitfield flags, GLuint64 timeout); GLAPI PFNGLWAITSYNCPROC glad_glWaitSync; #define glWaitSync glad_glWaitSync typedef void (APIENTRYP PFNGLGETINTEGER64VPROC)(GLenum pname, GLint64 *data); GLAPI PFNGLGETINTEGER64VPROC glad_glGetInteger64v; #define glGetInteger64v glad_glGetInteger64v typedef void (APIENTRYP PFNGLGETSYNCIVPROC)(GLsync sync, GLenum pname, GLsizei count, GLsizei *length, GLint *values); GLAPI PFNGLGETSYNCIVPROC glad_glGetSynciv; #define glGetSynciv glad_glGetSynciv typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC)(GLenum target, GLuint index, GLint64 *data); GLAPI PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v; #define glGetInteger64i_v glad_glGetInteger64i_v typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERI64VPROC)(GLenum target, GLenum pname, GLint64 *params); GLAPI PFNGLGETBUFFERPARAMETERI64VPROC glad_glGetBufferParameteri64v; #define glGetBufferParameteri64v glad_glGetBufferParameteri64v typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level); GLAPI PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture; #define glFramebufferTexture glad_glFramebufferTexture typedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); GLAPI PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample; #define glTexImage2DMultisample glad_glTexImage2DMultisample typedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); GLAPI PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample; #define glTexImage3DMultisample glad_glTexImage3DMultisample typedef void (APIENTRYP PFNGLGETMULTISAMPLEFVPROC)(GLenum pname, GLuint index, GLfloat *val); GLAPI PFNGLGETMULTISAMPLEFVPROC glad_glGetMultisamplefv; #define glGetMultisamplefv glad_glGetMultisamplefv typedef void (APIENTRYP PFNGLSAMPLEMASKIPROC)(GLuint maskNumber, GLbitfield mask); GLAPI PFNGLSAMPLEMASKIPROC glad_glSampleMaski; #define glSampleMaski glad_glSampleMaski #endif #ifndef GL_VERSION_3_3 #define GL_VERSION_3_3 1 GLAPI int GLAD_GL_VERSION_3_3; typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONINDEXEDPROC)(GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); GLAPI PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glad_glBindFragDataLocationIndexed; #define glBindFragDataLocationIndexed glad_glBindFragDataLocationIndexed typedef GLint (APIENTRYP PFNGLGETFRAGDATAINDEXPROC)(GLuint program, const GLchar *name); GLAPI PFNGLGETFRAGDATAINDEXPROC glad_glGetFragDataIndex; #define glGetFragDataIndex glad_glGetFragDataIndex typedef void (APIENTRYP PFNGLGENSAMPLERSPROC)(GLsizei count, GLuint *samplers); GLAPI PFNGLGENSAMPLERSPROC glad_glGenSamplers; #define glGenSamplers glad_glGenSamplers typedef void (APIENTRYP PFNGLDELETESAMPLERSPROC)(GLsizei count, const GLuint *samplers); GLAPI PFNGLDELETESAMPLERSPROC glad_glDeleteSamplers; #define glDeleteSamplers glad_glDeleteSamplers typedef GLboolean (APIENTRYP PFNGLISSAMPLERPROC)(GLuint sampler); GLAPI PFNGLISSAMPLERPROC glad_glIsSampler; #define glIsSampler glad_glIsSampler typedef void (APIENTRYP PFNGLBINDSAMPLERPROC)(GLuint unit, GLuint sampler); GLAPI PFNGLBINDSAMPLERPROC glad_glBindSampler; #define glBindSampler glad_glBindSampler typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIPROC)(GLuint sampler, GLenum pname, GLint param); GLAPI PFNGLSAMPLERPARAMETERIPROC glad_glSamplerParameteri; #define glSamplerParameteri glad_glSamplerParameteri typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIVPROC)(GLuint sampler, GLenum pname, const GLint *param); GLAPI PFNGLSAMPLERPARAMETERIVPROC glad_glSamplerParameteriv; #define glSamplerParameteriv glad_glSamplerParameteriv typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFPROC)(GLuint sampler, GLenum pname, GLfloat param); GLAPI PFNGLSAMPLERPARAMETERFPROC glad_glSamplerParameterf; #define glSamplerParameterf glad_glSamplerParameterf typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFVPROC)(GLuint sampler, GLenum pname, const GLfloat *param); GLAPI PFNGLSAMPLERPARAMETERFVPROC glad_glSamplerParameterfv; #define glSamplerParameterfv glad_glSamplerParameterfv typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIIVPROC)(GLuint sampler, GLenum pname, const GLint *param); GLAPI PFNGLSAMPLERPARAMETERIIVPROC glad_glSamplerParameterIiv; #define glSamplerParameterIiv glad_glSamplerParameterIiv typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIUIVPROC)(GLuint sampler, GLenum pname, const GLuint *param); GLAPI PFNGLSAMPLERPARAMETERIUIVPROC glad_glSamplerParameterIuiv; #define glSamplerParameterIuiv glad_glSamplerParameterIuiv typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIVPROC)(GLuint sampler, GLenum pname, GLint *params); GLAPI PFNGLGETSAMPLERPARAMETERIVPROC glad_glGetSamplerParameteriv; #define glGetSamplerParameteriv glad_glGetSamplerParameteriv typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIIVPROC)(GLuint sampler, GLenum pname, GLint *params); GLAPI PFNGLGETSAMPLERPARAMETERIIVPROC glad_glGetSamplerParameterIiv; #define glGetSamplerParameterIiv glad_glGetSamplerParameterIiv typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERFVPROC)(GLuint sampler, GLenum pname, GLfloat *params); GLAPI PFNGLGETSAMPLERPARAMETERFVPROC glad_glGetSamplerParameterfv; #define glGetSamplerParameterfv glad_glGetSamplerParameterfv typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVPROC)(GLuint sampler, GLenum pname, GLuint *params); GLAPI PFNGLGETSAMPLERPARAMETERIUIVPROC glad_glGetSamplerParameterIuiv; #define glGetSamplerParameterIuiv glad_glGetSamplerParameterIuiv typedef void (APIENTRYP PFNGLQUERYCOUNTERPROC)(GLuint id, GLenum target); GLAPI PFNGLQUERYCOUNTERPROC glad_glQueryCounter; #define glQueryCounter glad_glQueryCounter typedef void (APIENTRYP PFNGLGETQUERYOBJECTI64VPROC)(GLuint id, GLenum pname, GLint64 *params); GLAPI PFNGLGETQUERYOBJECTI64VPROC glad_glGetQueryObjecti64v; #define glGetQueryObjecti64v glad_glGetQueryObjecti64v typedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VPROC)(GLuint id, GLenum pname, GLuint64 *params); GLAPI PFNGLGETQUERYOBJECTUI64VPROC glad_glGetQueryObjectui64v; #define glGetQueryObjectui64v glad_glGetQueryObjectui64v typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC)(GLuint index, GLuint divisor); GLAPI PFNGLVERTEXATTRIBDIVISORPROC glad_glVertexAttribDivisor; #define glVertexAttribDivisor glad_glVertexAttribDivisor typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); GLAPI PFNGLVERTEXATTRIBP1UIPROC glad_glVertexAttribP1ui; #define glVertexAttribP1ui glad_glVertexAttribP1ui typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint *value); GLAPI PFNGLVERTEXATTRIBP1UIVPROC glad_glVertexAttribP1uiv; #define glVertexAttribP1uiv glad_glVertexAttribP1uiv typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); GLAPI PFNGLVERTEXATTRIBP2UIPROC glad_glVertexAttribP2ui; #define glVertexAttribP2ui glad_glVertexAttribP2ui typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint *value); GLAPI PFNGLVERTEXATTRIBP2UIVPROC glad_glVertexAttribP2uiv; #define glVertexAttribP2uiv glad_glVertexAttribP2uiv typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); GLAPI PFNGLVERTEXATTRIBP3UIPROC glad_glVertexAttribP3ui; #define glVertexAttribP3ui glad_glVertexAttribP3ui typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint *value); GLAPI PFNGLVERTEXATTRIBP3UIVPROC glad_glVertexAttribP3uiv; #define glVertexAttribP3uiv glad_glVertexAttribP3uiv typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); GLAPI PFNGLVERTEXATTRIBP4UIPROC glad_glVertexAttribP4ui; #define glVertexAttribP4ui glad_glVertexAttribP4ui typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint *value); GLAPI PFNGLVERTEXATTRIBP4UIVPROC glad_glVertexAttribP4uiv; #define glVertexAttribP4uiv glad_glVertexAttribP4uiv typedef void (APIENTRYP PFNGLVERTEXP2UIPROC)(GLenum type, GLuint value); GLAPI PFNGLVERTEXP2UIPROC glad_glVertexP2ui; #define glVertexP2ui glad_glVertexP2ui typedef void (APIENTRYP PFNGLVERTEXP2UIVPROC)(GLenum type, const GLuint *value); GLAPI PFNGLVERTEXP2UIVPROC glad_glVertexP2uiv; #define glVertexP2uiv glad_glVertexP2uiv typedef void (APIENTRYP PFNGLVERTEXP3UIPROC)(GLenum type, GLuint value); GLAPI PFNGLVERTEXP3UIPROC glad_glVertexP3ui; #define glVertexP3ui glad_glVertexP3ui typedef void (APIENTRYP PFNGLVERTEXP3UIVPROC)(GLenum type, const GLuint *value); GLAPI PFNGLVERTEXP3UIVPROC glad_glVertexP3uiv; #define glVertexP3uiv glad_glVertexP3uiv typedef void (APIENTRYP PFNGLVERTEXP4UIPROC)(GLenum type, GLuint value); GLAPI PFNGLVERTEXP4UIPROC glad_glVertexP4ui; #define glVertexP4ui glad_glVertexP4ui typedef void (APIENTRYP PFNGLVERTEXP4UIVPROC)(GLenum type, const GLuint *value); GLAPI PFNGLVERTEXP4UIVPROC glad_glVertexP4uiv; #define glVertexP4uiv glad_glVertexP4uiv typedef void (APIENTRYP PFNGLTEXCOORDP1UIPROC)(GLenum type, GLuint coords); GLAPI PFNGLTEXCOORDP1UIPROC glad_glTexCoordP1ui; #define glTexCoordP1ui glad_glTexCoordP1ui typedef void (APIENTRYP PFNGLTEXCOORDP1UIVPROC)(GLenum type, const GLuint *coords); GLAPI PFNGLTEXCOORDP1UIVPROC glad_glTexCoordP1uiv; #define glTexCoordP1uiv glad_glTexCoordP1uiv typedef void (APIENTRYP PFNGLTEXCOORDP2UIPROC)(GLenum type, GLuint coords); GLAPI PFNGLTEXCOORDP2UIPROC glad_glTexCoordP2ui; #define glTexCoordP2ui glad_glTexCoordP2ui typedef void (APIENTRYP PFNGLTEXCOORDP2UIVPROC)(GLenum type, const GLuint *coords); GLAPI PFNGLTEXCOORDP2UIVPROC glad_glTexCoordP2uiv; #define glTexCoordP2uiv glad_glTexCoordP2uiv typedef void (APIENTRYP PFNGLTEXCOORDP3UIPROC)(GLenum type, GLuint coords); GLAPI PFNGLTEXCOORDP3UIPROC glad_glTexCoordP3ui; #define glTexCoordP3ui glad_glTexCoordP3ui typedef void (APIENTRYP PFNGLTEXCOORDP3UIVPROC)(GLenum type, const GLuint *coords); GLAPI PFNGLTEXCOORDP3UIVPROC glad_glTexCoordP3uiv; #define glTexCoordP3uiv glad_glTexCoordP3uiv typedef void (APIENTRYP PFNGLTEXCOORDP4UIPROC)(GLenum type, GLuint coords); GLAPI PFNGLTEXCOORDP4UIPROC glad_glTexCoordP4ui; #define glTexCoordP4ui glad_glTexCoordP4ui typedef void (APIENTRYP PFNGLTEXCOORDP4UIVPROC)(GLenum type, const GLuint *coords); GLAPI PFNGLTEXCOORDP4UIVPROC glad_glTexCoordP4uiv; #define glTexCoordP4uiv glad_glTexCoordP4uiv typedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIPROC)(GLenum texture, GLenum type, GLuint coords); GLAPI PFNGLMULTITEXCOORDP1UIPROC glad_glMultiTexCoordP1ui; #define glMultiTexCoordP1ui glad_glMultiTexCoordP1ui typedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIVPROC)(GLenum texture, GLenum type, const GLuint *coords); GLAPI PFNGLMULTITEXCOORDP1UIVPROC glad_glMultiTexCoordP1uiv; #define glMultiTexCoordP1uiv glad_glMultiTexCoordP1uiv typedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIPROC)(GLenum texture, GLenum type, GLuint coords); GLAPI PFNGLMULTITEXCOORDP2UIPROC glad_glMultiTexCoordP2ui; #define glMultiTexCoordP2ui glad_glMultiTexCoordP2ui typedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIVPROC)(GLenum texture, GLenum type, const GLuint *coords); GLAPI PFNGLMULTITEXCOORDP2UIVPROC glad_glMultiTexCoordP2uiv; #define glMultiTexCoordP2uiv glad_glMultiTexCoordP2uiv typedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIPROC)(GLenum texture, GLenum type, GLuint coords); GLAPI PFNGLMULTITEXCOORDP3UIPROC glad_glMultiTexCoordP3ui; #define glMultiTexCoordP3ui glad_glMultiTexCoordP3ui typedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIVPROC)(GLenum texture, GLenum type, const GLuint *coords); GLAPI PFNGLMULTITEXCOORDP3UIVPROC glad_glMultiTexCoordP3uiv; #define glMultiTexCoordP3uiv glad_glMultiTexCoordP3uiv typedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIPROC)(GLenum texture, GLenum type, GLuint coords); GLAPI PFNGLMULTITEXCOORDP4UIPROC glad_glMultiTexCoordP4ui; #define glMultiTexCoordP4ui glad_glMultiTexCoordP4ui typedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIVPROC)(GLenum texture, GLenum type, const GLuint *coords); GLAPI PFNGLMULTITEXCOORDP4UIVPROC glad_glMultiTexCoordP4uiv; #define glMultiTexCoordP4uiv glad_glMultiTexCoordP4uiv typedef void (APIENTRYP PFNGLNORMALP3UIPROC)(GLenum type, GLuint coords); GLAPI PFNGLNORMALP3UIPROC glad_glNormalP3ui; #define glNormalP3ui glad_glNormalP3ui typedef void (APIENTRYP PFNGLNORMALP3UIVPROC)(GLenum type, const GLuint *coords); GLAPI PFNGLNORMALP3UIVPROC glad_glNormalP3uiv; #define glNormalP3uiv glad_glNormalP3uiv typedef void (APIENTRYP PFNGLCOLORP3UIPROC)(GLenum type, GLuint color); GLAPI PFNGLCOLORP3UIPROC glad_glColorP3ui; #define glColorP3ui glad_glColorP3ui typedef void (APIENTRYP PFNGLCOLORP3UIVPROC)(GLenum type, const GLuint *color); GLAPI PFNGLCOLORP3UIVPROC glad_glColorP3uiv; #define glColorP3uiv glad_glColorP3uiv typedef void (APIENTRYP PFNGLCOLORP4UIPROC)(GLenum type, GLuint color); GLAPI PFNGLCOLORP4UIPROC glad_glColorP4ui; #define glColorP4ui glad_glColorP4ui typedef void (APIENTRYP PFNGLCOLORP4UIVPROC)(GLenum type, const GLuint *color); GLAPI PFNGLCOLORP4UIVPROC glad_glColorP4uiv; #define glColorP4uiv glad_glColorP4uiv typedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIPROC)(GLenum type, GLuint color); GLAPI PFNGLSECONDARYCOLORP3UIPROC glad_glSecondaryColorP3ui; #define glSecondaryColorP3ui glad_glSecondaryColorP3ui typedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIVPROC)(GLenum type, const GLuint *color); GLAPI PFNGLSECONDARYCOLORP3UIVPROC glad_glSecondaryColorP3uiv; #define glSecondaryColorP3uiv glad_glSecondaryColorP3uiv #endif #ifndef GL_VERSION_4_0 #define GL_VERSION_4_0 1 GLAPI int GLAD_GL_VERSION_4_0; typedef void (APIENTRYP PFNGLMINSAMPLESHADINGPROC)(GLfloat value); GLAPI PFNGLMINSAMPLESHADINGPROC glad_glMinSampleShading; #define glMinSampleShading glad_glMinSampleShading typedef void (APIENTRYP PFNGLBLENDEQUATIONIPROC)(GLuint buf, GLenum mode); GLAPI PFNGLBLENDEQUATIONIPROC glad_glBlendEquationi; #define glBlendEquationi glad_glBlendEquationi typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEIPROC)(GLuint buf, GLenum modeRGB, GLenum modeAlpha); GLAPI PFNGLBLENDEQUATIONSEPARATEIPROC glad_glBlendEquationSeparatei; #define glBlendEquationSeparatei glad_glBlendEquationSeparatei typedef void (APIENTRYP PFNGLBLENDFUNCIPROC)(GLuint buf, GLenum src, GLenum dst); GLAPI PFNGLBLENDFUNCIPROC glad_glBlendFunci; #define glBlendFunci glad_glBlendFunci typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEIPROC)(GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); GLAPI PFNGLBLENDFUNCSEPARATEIPROC glad_glBlendFuncSeparatei; #define glBlendFuncSeparatei glad_glBlendFuncSeparatei typedef void (APIENTRYP PFNGLDRAWARRAYSINDIRECTPROC)(GLenum mode, const void *indirect); GLAPI PFNGLDRAWARRAYSINDIRECTPROC glad_glDrawArraysIndirect; #define glDrawArraysIndirect glad_glDrawArraysIndirect typedef void (APIENTRYP PFNGLDRAWELEMENTSINDIRECTPROC)(GLenum mode, GLenum type, const void *indirect); GLAPI PFNGLDRAWELEMENTSINDIRECTPROC glad_glDrawElementsIndirect; #define glDrawElementsIndirect glad_glDrawElementsIndirect typedef void (APIENTRYP PFNGLUNIFORM1DPROC)(GLint location, GLdouble x); GLAPI PFNGLUNIFORM1DPROC glad_glUniform1d; #define glUniform1d glad_glUniform1d typedef void (APIENTRYP PFNGLUNIFORM2DPROC)(GLint location, GLdouble x, GLdouble y); GLAPI PFNGLUNIFORM2DPROC glad_glUniform2d; #define glUniform2d glad_glUniform2d typedef void (APIENTRYP PFNGLUNIFORM3DPROC)(GLint location, GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLUNIFORM3DPROC glad_glUniform3d; #define glUniform3d glad_glUniform3d typedef void (APIENTRYP PFNGLUNIFORM4DPROC)(GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); GLAPI PFNGLUNIFORM4DPROC glad_glUniform4d; #define glUniform4d glad_glUniform4d typedef void (APIENTRYP PFNGLUNIFORM1DVPROC)(GLint location, GLsizei count, const GLdouble *value); GLAPI PFNGLUNIFORM1DVPROC glad_glUniform1dv; #define glUniform1dv glad_glUniform1dv typedef void (APIENTRYP PFNGLUNIFORM2DVPROC)(GLint location, GLsizei count, const GLdouble *value); GLAPI PFNGLUNIFORM2DVPROC glad_glUniform2dv; #define glUniform2dv glad_glUniform2dv typedef void (APIENTRYP PFNGLUNIFORM3DVPROC)(GLint location, GLsizei count, const GLdouble *value); GLAPI PFNGLUNIFORM3DVPROC glad_glUniform3dv; #define glUniform3dv glad_glUniform3dv typedef void (APIENTRYP PFNGLUNIFORM4DVPROC)(GLint location, GLsizei count, const GLdouble *value); GLAPI PFNGLUNIFORM4DVPROC glad_glUniform4dv; #define glUniform4dv glad_glUniform4dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX2DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX2DVPROC glad_glUniformMatrix2dv; #define glUniformMatrix2dv glad_glUniformMatrix2dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX3DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX3DVPROC glad_glUniformMatrix3dv; #define glUniformMatrix3dv glad_glUniformMatrix3dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX4DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX4DVPROC glad_glUniformMatrix4dv; #define glUniformMatrix4dv glad_glUniformMatrix4dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX2X3DVPROC glad_glUniformMatrix2x3dv; #define glUniformMatrix2x3dv glad_glUniformMatrix2x3dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX2X4DVPROC glad_glUniformMatrix2x4dv; #define glUniformMatrix2x4dv glad_glUniformMatrix2x4dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX3X2DVPROC glad_glUniformMatrix3x2dv; #define glUniformMatrix3x2dv glad_glUniformMatrix3x2dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX3X4DVPROC glad_glUniformMatrix3x4dv; #define glUniformMatrix3x4dv glad_glUniformMatrix3x4dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX4X2DVPROC glad_glUniformMatrix4x2dv; #define glUniformMatrix4x2dv glad_glUniformMatrix4x2dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX4X3DVPROC glad_glUniformMatrix4x3dv; #define glUniformMatrix4x3dv glad_glUniformMatrix4x3dv typedef void (APIENTRYP PFNGLGETUNIFORMDVPROC)(GLuint program, GLint location, GLdouble *params); GLAPI PFNGLGETUNIFORMDVPROC glad_glGetUniformdv; #define glGetUniformdv glad_glGetUniformdv typedef GLint (APIENTRYP PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC)(GLuint program, GLenum shadertype, const GLchar *name); GLAPI PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC glad_glGetSubroutineUniformLocation; #define glGetSubroutineUniformLocation glad_glGetSubroutineUniformLocation typedef GLuint (APIENTRYP PFNGLGETSUBROUTINEINDEXPROC)(GLuint program, GLenum shadertype, const GLchar *name); GLAPI PFNGLGETSUBROUTINEINDEXPROC glad_glGetSubroutineIndex; #define glGetSubroutineIndex glad_glGetSubroutineIndex typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC)(GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint *values); GLAPI PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC glad_glGetActiveSubroutineUniformiv; #define glGetActiveSubroutineUniformiv glad_glGetActiveSubroutineUniformiv typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC)(GLuint program, GLenum shadertype, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); GLAPI PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC glad_glGetActiveSubroutineUniformName; #define glGetActiveSubroutineUniformName glad_glGetActiveSubroutineUniformName typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINENAMEPROC)(GLuint program, GLenum shadertype, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); GLAPI PFNGLGETACTIVESUBROUTINENAMEPROC glad_glGetActiveSubroutineName; #define glGetActiveSubroutineName glad_glGetActiveSubroutineName typedef void (APIENTRYP PFNGLUNIFORMSUBROUTINESUIVPROC)(GLenum shadertype, GLsizei count, const GLuint *indices); GLAPI PFNGLUNIFORMSUBROUTINESUIVPROC glad_glUniformSubroutinesuiv; #define glUniformSubroutinesuiv glad_glUniformSubroutinesuiv typedef void (APIENTRYP PFNGLGETUNIFORMSUBROUTINEUIVPROC)(GLenum shadertype, GLint location, GLuint *params); GLAPI PFNGLGETUNIFORMSUBROUTINEUIVPROC glad_glGetUniformSubroutineuiv; #define glGetUniformSubroutineuiv glad_glGetUniformSubroutineuiv typedef void (APIENTRYP PFNGLGETPROGRAMSTAGEIVPROC)(GLuint program, GLenum shadertype, GLenum pname, GLint *values); GLAPI PFNGLGETPROGRAMSTAGEIVPROC glad_glGetProgramStageiv; #define glGetProgramStageiv glad_glGetProgramStageiv typedef void (APIENTRYP PFNGLPATCHPARAMETERIPROC)(GLenum pname, GLint value); GLAPI PFNGLPATCHPARAMETERIPROC glad_glPatchParameteri; #define glPatchParameteri glad_glPatchParameteri typedef void (APIENTRYP PFNGLPATCHPARAMETERFVPROC)(GLenum pname, const GLfloat *values); GLAPI PFNGLPATCHPARAMETERFVPROC glad_glPatchParameterfv; #define glPatchParameterfv glad_glPatchParameterfv typedef void (APIENTRYP PFNGLBINDTRANSFORMFEEDBACKPROC)(GLenum target, GLuint id); GLAPI PFNGLBINDTRANSFORMFEEDBACKPROC glad_glBindTransformFeedback; #define glBindTransformFeedback glad_glBindTransformFeedback typedef void (APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSPROC)(GLsizei n, const GLuint *ids); GLAPI PFNGLDELETETRANSFORMFEEDBACKSPROC glad_glDeleteTransformFeedbacks; #define glDeleteTransformFeedbacks glad_glDeleteTransformFeedbacks typedef void (APIENTRYP PFNGLGENTRANSFORMFEEDBACKSPROC)(GLsizei n, GLuint *ids); GLAPI PFNGLGENTRANSFORMFEEDBACKSPROC glad_glGenTransformFeedbacks; #define glGenTransformFeedbacks glad_glGenTransformFeedbacks typedef GLboolean (APIENTRYP PFNGLISTRANSFORMFEEDBACKPROC)(GLuint id); GLAPI PFNGLISTRANSFORMFEEDBACKPROC glad_glIsTransformFeedback; #define glIsTransformFeedback glad_glIsTransformFeedback typedef void (APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKPROC)(void); GLAPI PFNGLPAUSETRANSFORMFEEDBACKPROC glad_glPauseTransformFeedback; #define glPauseTransformFeedback glad_glPauseTransformFeedback typedef void (APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKPROC)(void); GLAPI PFNGLRESUMETRANSFORMFEEDBACKPROC glad_glResumeTransformFeedback; #define glResumeTransformFeedback glad_glResumeTransformFeedback typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKPROC)(GLenum mode, GLuint id); GLAPI PFNGLDRAWTRANSFORMFEEDBACKPROC glad_glDrawTransformFeedback; #define glDrawTransformFeedback glad_glDrawTransformFeedback typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC)(GLenum mode, GLuint id, GLuint stream); GLAPI PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC glad_glDrawTransformFeedbackStream; #define glDrawTransformFeedbackStream glad_glDrawTransformFeedbackStream typedef void (APIENTRYP PFNGLBEGINQUERYINDEXEDPROC)(GLenum target, GLuint index, GLuint id); GLAPI PFNGLBEGINQUERYINDEXEDPROC glad_glBeginQueryIndexed; #define glBeginQueryIndexed glad_glBeginQueryIndexed typedef void (APIENTRYP PFNGLENDQUERYINDEXEDPROC)(GLenum target, GLuint index); GLAPI PFNGLENDQUERYINDEXEDPROC glad_glEndQueryIndexed; #define glEndQueryIndexed glad_glEndQueryIndexed typedef void (APIENTRYP PFNGLGETQUERYINDEXEDIVPROC)(GLenum target, GLuint index, GLenum pname, GLint *params); GLAPI PFNGLGETQUERYINDEXEDIVPROC glad_glGetQueryIndexediv; #define glGetQueryIndexediv glad_glGetQueryIndexediv #endif #ifndef GL_VERSION_4_1 #define GL_VERSION_4_1 1 GLAPI int GLAD_GL_VERSION_4_1; typedef void (APIENTRYP PFNGLRELEASESHADERCOMPILERPROC)(void); GLAPI PFNGLRELEASESHADERCOMPILERPROC glad_glReleaseShaderCompiler; #define glReleaseShaderCompiler glad_glReleaseShaderCompiler typedef void (APIENTRYP PFNGLSHADERBINARYPROC)(GLsizei count, const GLuint *shaders, GLenum binaryFormat, const void *binary, GLsizei length); GLAPI PFNGLSHADERBINARYPROC glad_glShaderBinary; #define glShaderBinary glad_glShaderBinary typedef void (APIENTRYP PFNGLGETSHADERPRECISIONFORMATPROC)(GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); GLAPI PFNGLGETSHADERPRECISIONFORMATPROC glad_glGetShaderPrecisionFormat; #define glGetShaderPrecisionFormat glad_glGetShaderPrecisionFormat typedef void (APIENTRYP PFNGLDEPTHRANGEFPROC)(GLfloat n, GLfloat f); GLAPI PFNGLDEPTHRANGEFPROC glad_glDepthRangef; #define glDepthRangef glad_glDepthRangef typedef void (APIENTRYP PFNGLCLEARDEPTHFPROC)(GLfloat d); GLAPI PFNGLCLEARDEPTHFPROC glad_glClearDepthf; #define glClearDepthf glad_glClearDepthf typedef void (APIENTRYP PFNGLGETPROGRAMBINARYPROC)(GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); GLAPI PFNGLGETPROGRAMBINARYPROC glad_glGetProgramBinary; #define glGetProgramBinary glad_glGetProgramBinary typedef void (APIENTRYP PFNGLPROGRAMBINARYPROC)(GLuint program, GLenum binaryFormat, const void *binary, GLsizei length); GLAPI PFNGLPROGRAMBINARYPROC glad_glProgramBinary; #define glProgramBinary glad_glProgramBinary typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIPROC)(GLuint program, GLenum pname, GLint value); GLAPI PFNGLPROGRAMPARAMETERIPROC glad_glProgramParameteri; #define glProgramParameteri glad_glProgramParameteri typedef void (APIENTRYP PFNGLUSEPROGRAMSTAGESPROC)(GLuint pipeline, GLbitfield stages, GLuint program); GLAPI PFNGLUSEPROGRAMSTAGESPROC glad_glUseProgramStages; #define glUseProgramStages glad_glUseProgramStages typedef void (APIENTRYP PFNGLACTIVESHADERPROGRAMPROC)(GLuint pipeline, GLuint program); GLAPI PFNGLACTIVESHADERPROGRAMPROC glad_glActiveShaderProgram; #define glActiveShaderProgram glad_glActiveShaderProgram typedef GLuint (APIENTRYP PFNGLCREATESHADERPROGRAMVPROC)(GLenum type, GLsizei count, const GLchar *const*strings); GLAPI PFNGLCREATESHADERPROGRAMVPROC glad_glCreateShaderProgramv; #define glCreateShaderProgramv glad_glCreateShaderProgramv typedef void (APIENTRYP PFNGLBINDPROGRAMPIPELINEPROC)(GLuint pipeline); GLAPI PFNGLBINDPROGRAMPIPELINEPROC glad_glBindProgramPipeline; #define glBindProgramPipeline glad_glBindProgramPipeline typedef void (APIENTRYP PFNGLDELETEPROGRAMPIPELINESPROC)(GLsizei n, const GLuint *pipelines); GLAPI PFNGLDELETEPROGRAMPIPELINESPROC glad_glDeleteProgramPipelines; #define glDeleteProgramPipelines glad_glDeleteProgramPipelines typedef void (APIENTRYP PFNGLGENPROGRAMPIPELINESPROC)(GLsizei n, GLuint *pipelines); GLAPI PFNGLGENPROGRAMPIPELINESPROC glad_glGenProgramPipelines; #define glGenProgramPipelines glad_glGenProgramPipelines typedef GLboolean (APIENTRYP PFNGLISPROGRAMPIPELINEPROC)(GLuint pipeline); GLAPI PFNGLISPROGRAMPIPELINEPROC glad_glIsProgramPipeline; #define glIsProgramPipeline glad_glIsProgramPipeline typedef void (APIENTRYP PFNGLGETPROGRAMPIPELINEIVPROC)(GLuint pipeline, GLenum pname, GLint *params); GLAPI PFNGLGETPROGRAMPIPELINEIVPROC glad_glGetProgramPipelineiv; #define glGetProgramPipelineiv glad_glGetProgramPipelineiv typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IPROC)(GLuint program, GLint location, GLint v0); GLAPI PFNGLPROGRAMUNIFORM1IPROC glad_glProgramUniform1i; #define glProgramUniform1i glad_glProgramUniform1i typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IVPROC)(GLuint program, GLint location, GLsizei count, const GLint *value); GLAPI PFNGLPROGRAMUNIFORM1IVPROC glad_glProgramUniform1iv; #define glProgramUniform1iv glad_glProgramUniform1iv typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FPROC)(GLuint program, GLint location, GLfloat v0); GLAPI PFNGLPROGRAMUNIFORM1FPROC glad_glProgramUniform1f; #define glProgramUniform1f glad_glProgramUniform1f typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FVPROC)(GLuint program, GLint location, GLsizei count, const GLfloat *value); GLAPI PFNGLPROGRAMUNIFORM1FVPROC glad_glProgramUniform1fv; #define glProgramUniform1fv glad_glProgramUniform1fv typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DPROC)(GLuint program, GLint location, GLdouble v0); GLAPI PFNGLPROGRAMUNIFORM1DPROC glad_glProgramUniform1d; #define glProgramUniform1d glad_glProgramUniform1d typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DVPROC)(GLuint program, GLint location, GLsizei count, const GLdouble *value); GLAPI PFNGLPROGRAMUNIFORM1DVPROC glad_glProgramUniform1dv; #define glProgramUniform1dv glad_glProgramUniform1dv typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIPROC)(GLuint program, GLint location, GLuint v0); GLAPI PFNGLPROGRAMUNIFORM1UIPROC glad_glProgramUniform1ui; #define glProgramUniform1ui glad_glProgramUniform1ui typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIVPROC)(GLuint program, GLint location, GLsizei count, const GLuint *value); GLAPI PFNGLPROGRAMUNIFORM1UIVPROC glad_glProgramUniform1uiv; #define glProgramUniform1uiv glad_glProgramUniform1uiv typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IPROC)(GLuint program, GLint location, GLint v0, GLint v1); GLAPI PFNGLPROGRAMUNIFORM2IPROC glad_glProgramUniform2i; #define glProgramUniform2i glad_glProgramUniform2i typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IVPROC)(GLuint program, GLint location, GLsizei count, const GLint *value); GLAPI PFNGLPROGRAMUNIFORM2IVPROC glad_glProgramUniform2iv; #define glProgramUniform2iv glad_glProgramUniform2iv typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FPROC)(GLuint program, GLint location, GLfloat v0, GLfloat v1); GLAPI PFNGLPROGRAMUNIFORM2FPROC glad_glProgramUniform2f; #define glProgramUniform2f glad_glProgramUniform2f typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FVPROC)(GLuint program, GLint location, GLsizei count, const GLfloat *value); GLAPI PFNGLPROGRAMUNIFORM2FVPROC glad_glProgramUniform2fv; #define glProgramUniform2fv glad_glProgramUniform2fv typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DPROC)(GLuint program, GLint location, GLdouble v0, GLdouble v1); GLAPI PFNGLPROGRAMUNIFORM2DPROC glad_glProgramUniform2d; #define glProgramUniform2d glad_glProgramUniform2d typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DVPROC)(GLuint program, GLint location, GLsizei count, const GLdouble *value); GLAPI PFNGLPROGRAMUNIFORM2DVPROC glad_glProgramUniform2dv; #define glProgramUniform2dv glad_glProgramUniform2dv typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIPROC)(GLuint program, GLint location, GLuint v0, GLuint v1); GLAPI PFNGLPROGRAMUNIFORM2UIPROC glad_glProgramUniform2ui; #define glProgramUniform2ui glad_glProgramUniform2ui typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIVPROC)(GLuint program, GLint location, GLsizei count, const GLuint *value); GLAPI PFNGLPROGRAMUNIFORM2UIVPROC glad_glProgramUniform2uiv; #define glProgramUniform2uiv glad_glProgramUniform2uiv typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IPROC)(GLuint program, GLint location, GLint v0, GLint v1, GLint v2); GLAPI PFNGLPROGRAMUNIFORM3IPROC glad_glProgramUniform3i; #define glProgramUniform3i glad_glProgramUniform3i typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IVPROC)(GLuint program, GLint location, GLsizei count, const GLint *value); GLAPI PFNGLPROGRAMUNIFORM3IVPROC glad_glProgramUniform3iv; #define glProgramUniform3iv glad_glProgramUniform3iv typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FPROC)(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); GLAPI PFNGLPROGRAMUNIFORM3FPROC glad_glProgramUniform3f; #define glProgramUniform3f glad_glProgramUniform3f typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FVPROC)(GLuint program, GLint location, GLsizei count, const GLfloat *value); GLAPI PFNGLPROGRAMUNIFORM3FVPROC glad_glProgramUniform3fv; #define glProgramUniform3fv glad_glProgramUniform3fv typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DPROC)(GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2); GLAPI PFNGLPROGRAMUNIFORM3DPROC glad_glProgramUniform3d; #define glProgramUniform3d glad_glProgramUniform3d typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DVPROC)(GLuint program, GLint location, GLsizei count, const GLdouble *value); GLAPI PFNGLPROGRAMUNIFORM3DVPROC glad_glProgramUniform3dv; #define glProgramUniform3dv glad_glProgramUniform3dv typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIPROC)(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); GLAPI PFNGLPROGRAMUNIFORM3UIPROC glad_glProgramUniform3ui; #define glProgramUniform3ui glad_glProgramUniform3ui typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIVPROC)(GLuint program, GLint location, GLsizei count, const GLuint *value); GLAPI PFNGLPROGRAMUNIFORM3UIVPROC glad_glProgramUniform3uiv; #define glProgramUniform3uiv glad_glProgramUniform3uiv typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IPROC)(GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); GLAPI PFNGLPROGRAMUNIFORM4IPROC glad_glProgramUniform4i; #define glProgramUniform4i glad_glProgramUniform4i typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IVPROC)(GLuint program, GLint location, GLsizei count, const GLint *value); GLAPI PFNGLPROGRAMUNIFORM4IVPROC glad_glProgramUniform4iv; #define glProgramUniform4iv glad_glProgramUniform4iv typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FPROC)(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); GLAPI PFNGLPROGRAMUNIFORM4FPROC glad_glProgramUniform4f; #define glProgramUniform4f glad_glProgramUniform4f typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FVPROC)(GLuint program, GLint location, GLsizei count, const GLfloat *value); GLAPI PFNGLPROGRAMUNIFORM4FVPROC glad_glProgramUniform4fv; #define glProgramUniform4fv glad_glProgramUniform4fv typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DPROC)(GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3); GLAPI PFNGLPROGRAMUNIFORM4DPROC glad_glProgramUniform4d; #define glProgramUniform4d glad_glProgramUniform4d typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DVPROC)(GLuint program, GLint location, GLsizei count, const GLdouble *value); GLAPI PFNGLPROGRAMUNIFORM4DVPROC glad_glProgramUniform4dv; #define glProgramUniform4dv glad_glProgramUniform4dv typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIPROC)(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); GLAPI PFNGLPROGRAMUNIFORM4UIPROC glad_glProgramUniform4ui; #define glProgramUniform4ui glad_glProgramUniform4ui typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIVPROC)(GLuint program, GLint location, GLsizei count, const GLuint *value); GLAPI PFNGLPROGRAMUNIFORM4UIVPROC glad_glProgramUniform4uiv; #define glProgramUniform4uiv glad_glProgramUniform4uiv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX2FVPROC glad_glProgramUniformMatrix2fv; #define glProgramUniformMatrix2fv glad_glProgramUniformMatrix2fv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX3FVPROC glad_glProgramUniformMatrix3fv; #define glProgramUniformMatrix3fv glad_glProgramUniformMatrix3fv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX4FVPROC glad_glProgramUniformMatrix4fv; #define glProgramUniformMatrix4fv glad_glProgramUniformMatrix4fv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX2DVPROC glad_glProgramUniformMatrix2dv; #define glProgramUniformMatrix2dv glad_glProgramUniformMatrix2dv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX3DVPROC glad_glProgramUniformMatrix3dv; #define glProgramUniformMatrix3dv glad_glProgramUniformMatrix3dv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX4DVPROC glad_glProgramUniformMatrix4dv; #define glProgramUniformMatrix4dv glad_glProgramUniformMatrix4dv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC glad_glProgramUniformMatrix2x3fv; #define glProgramUniformMatrix2x3fv glad_glProgramUniformMatrix2x3fv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC glad_glProgramUniformMatrix3x2fv; #define glProgramUniformMatrix3x2fv glad_glProgramUniformMatrix3x2fv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC glad_glProgramUniformMatrix2x4fv; #define glProgramUniformMatrix2x4fv glad_glProgramUniformMatrix2x4fv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC glad_glProgramUniformMatrix4x2fv; #define glProgramUniformMatrix4x2fv glad_glProgramUniformMatrix4x2fv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC glad_glProgramUniformMatrix3x4fv; #define glProgramUniformMatrix3x4fv glad_glProgramUniformMatrix3x4fv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC glad_glProgramUniformMatrix4x3fv; #define glProgramUniformMatrix4x3fv glad_glProgramUniformMatrix4x3fv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC glad_glProgramUniformMatrix2x3dv; #define glProgramUniformMatrix2x3dv glad_glProgramUniformMatrix2x3dv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC glad_glProgramUniformMatrix3x2dv; #define glProgramUniformMatrix3x2dv glad_glProgramUniformMatrix3x2dv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC glad_glProgramUniformMatrix2x4dv; #define glProgramUniformMatrix2x4dv glad_glProgramUniformMatrix2x4dv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC glad_glProgramUniformMatrix4x2dv; #define glProgramUniformMatrix4x2dv glad_glProgramUniformMatrix4x2dv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC glad_glProgramUniformMatrix3x4dv; #define glProgramUniformMatrix3x4dv glad_glProgramUniformMatrix3x4dv typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC glad_glProgramUniformMatrix4x3dv; #define glProgramUniformMatrix4x3dv glad_glProgramUniformMatrix4x3dv typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPIPELINEPROC)(GLuint pipeline); GLAPI PFNGLVALIDATEPROGRAMPIPELINEPROC glad_glValidateProgramPipeline; #define glValidateProgramPipeline glad_glValidateProgramPipeline typedef void (APIENTRYP PFNGLGETPROGRAMPIPELINEINFOLOGPROC)(GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog); GLAPI PFNGLGETPROGRAMPIPELINEINFOLOGPROC glad_glGetProgramPipelineInfoLog; #define glGetProgramPipelineInfoLog glad_glGetProgramPipelineInfoLog typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DPROC)(GLuint index, GLdouble x); GLAPI PFNGLVERTEXATTRIBL1DPROC glad_glVertexAttribL1d; #define glVertexAttribL1d glad_glVertexAttribL1d typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DPROC)(GLuint index, GLdouble x, GLdouble y); GLAPI PFNGLVERTEXATTRIBL2DPROC glad_glVertexAttribL2d; #define glVertexAttribL2d glad_glVertexAttribL2d typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLVERTEXATTRIBL3DPROC glad_glVertexAttribL3d; #define glVertexAttribL3d glad_glVertexAttribL3d typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); GLAPI PFNGLVERTEXATTRIBL4DPROC glad_glVertexAttribL4d; #define glVertexAttribL4d glad_glVertexAttribL4d typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DVPROC)(GLuint index, const GLdouble *v); GLAPI PFNGLVERTEXATTRIBL1DVPROC glad_glVertexAttribL1dv; #define glVertexAttribL1dv glad_glVertexAttribL1dv typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DVPROC)(GLuint index, const GLdouble *v); GLAPI PFNGLVERTEXATTRIBL2DVPROC glad_glVertexAttribL2dv; #define glVertexAttribL2dv glad_glVertexAttribL2dv typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DVPROC)(GLuint index, const GLdouble *v); GLAPI PFNGLVERTEXATTRIBL3DVPROC glad_glVertexAttribL3dv; #define glVertexAttribL3dv glad_glVertexAttribL3dv typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DVPROC)(GLuint index, const GLdouble *v); GLAPI PFNGLVERTEXATTRIBL4DVPROC glad_glVertexAttribL4dv; #define glVertexAttribL4dv glad_glVertexAttribL4dv typedef void (APIENTRYP PFNGLVERTEXATTRIBLPOINTERPROC)(GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLVERTEXATTRIBLPOINTERPROC glad_glVertexAttribLPointer; #define glVertexAttribLPointer glad_glVertexAttribLPointer typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLDVPROC)(GLuint index, GLenum pname, GLdouble *params); GLAPI PFNGLGETVERTEXATTRIBLDVPROC glad_glGetVertexAttribLdv; #define glGetVertexAttribLdv glad_glGetVertexAttribLdv typedef void (APIENTRYP PFNGLVIEWPORTARRAYVPROC)(GLuint first, GLsizei count, const GLfloat *v); GLAPI PFNGLVIEWPORTARRAYVPROC glad_glViewportArrayv; #define glViewportArrayv glad_glViewportArrayv typedef void (APIENTRYP PFNGLVIEWPORTINDEXEDFPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); GLAPI PFNGLVIEWPORTINDEXEDFPROC glad_glViewportIndexedf; #define glViewportIndexedf glad_glViewportIndexedf typedef void (APIENTRYP PFNGLVIEWPORTINDEXEDFVPROC)(GLuint index, const GLfloat *v); GLAPI PFNGLVIEWPORTINDEXEDFVPROC glad_glViewportIndexedfv; #define glViewportIndexedfv glad_glViewportIndexedfv typedef void (APIENTRYP PFNGLSCISSORARRAYVPROC)(GLuint first, GLsizei count, const GLint *v); GLAPI PFNGLSCISSORARRAYVPROC glad_glScissorArrayv; #define glScissorArrayv glad_glScissorArrayv typedef void (APIENTRYP PFNGLSCISSORINDEXEDPROC)(GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); GLAPI PFNGLSCISSORINDEXEDPROC glad_glScissorIndexed; #define glScissorIndexed glad_glScissorIndexed typedef void (APIENTRYP PFNGLSCISSORINDEXEDVPROC)(GLuint index, const GLint *v); GLAPI PFNGLSCISSORINDEXEDVPROC glad_glScissorIndexedv; #define glScissorIndexedv glad_glScissorIndexedv typedef void (APIENTRYP PFNGLDEPTHRANGEARRAYVPROC)(GLuint first, GLsizei count, const GLdouble *v); GLAPI PFNGLDEPTHRANGEARRAYVPROC glad_glDepthRangeArrayv; #define glDepthRangeArrayv glad_glDepthRangeArrayv typedef void (APIENTRYP PFNGLDEPTHRANGEINDEXEDPROC)(GLuint index, GLdouble n, GLdouble f); GLAPI PFNGLDEPTHRANGEINDEXEDPROC glad_glDepthRangeIndexed; #define glDepthRangeIndexed glad_glDepthRangeIndexed typedef void (APIENTRYP PFNGLGETFLOATI_VPROC)(GLenum target, GLuint index, GLfloat *data); GLAPI PFNGLGETFLOATI_VPROC glad_glGetFloati_v; #define glGetFloati_v glad_glGetFloati_v typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC)(GLenum target, GLuint index, GLdouble *data); GLAPI PFNGLGETDOUBLEI_VPROC glad_glGetDoublei_v; #define glGetDoublei_v glad_glGetDoublei_v #endif #ifndef GL_VERSION_4_2 #define GL_VERSION_4_2 1 GLAPI int GLAD_GL_VERSION_4_2; typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); GLAPI PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC glad_glDrawArraysInstancedBaseInstance; #define glDrawArraysInstancedBaseInstance glad_glDrawArraysInstancedBaseInstance typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance); GLAPI PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC glad_glDrawElementsInstancedBaseInstance; #define glDrawElementsInstancedBaseInstance glad_glDrawElementsInstancedBaseInstance typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); GLAPI PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC glad_glDrawElementsInstancedBaseVertexBaseInstance; #define glDrawElementsInstancedBaseVertexBaseInstance glad_glDrawElementsInstancedBaseVertexBaseInstance typedef void (APIENTRYP PFNGLGETINTERNALFORMATIVPROC)(GLenum target, GLenum internalformat, GLenum pname, GLsizei count, GLint *params); GLAPI PFNGLGETINTERNALFORMATIVPROC glad_glGetInternalformativ; #define glGetInternalformativ glad_glGetInternalformativ typedef void (APIENTRYP PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC)(GLuint program, GLuint bufferIndex, GLenum pname, GLint *params); GLAPI PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC glad_glGetActiveAtomicCounterBufferiv; #define glGetActiveAtomicCounterBufferiv glad_glGetActiveAtomicCounterBufferiv typedef void (APIENTRYP PFNGLBINDIMAGETEXTUREPROC)(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); GLAPI PFNGLBINDIMAGETEXTUREPROC glad_glBindImageTexture; #define glBindImageTexture glad_glBindImageTexture typedef void (APIENTRYP PFNGLMEMORYBARRIERPROC)(GLbitfield barriers); GLAPI PFNGLMEMORYBARRIERPROC glad_glMemoryBarrier; #define glMemoryBarrier glad_glMemoryBarrier typedef void (APIENTRYP PFNGLTEXSTORAGE1DPROC)(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); GLAPI PFNGLTEXSTORAGE1DPROC glad_glTexStorage1D; #define glTexStorage1D glad_glTexStorage1D typedef void (APIENTRYP PFNGLTEXSTORAGE2DPROC)(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); GLAPI PFNGLTEXSTORAGE2DPROC glad_glTexStorage2D; #define glTexStorage2D glad_glTexStorage2D typedef void (APIENTRYP PFNGLTEXSTORAGE3DPROC)(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); GLAPI PFNGLTEXSTORAGE3DPROC glad_glTexStorage3D; #define glTexStorage3D glad_glTexStorage3D typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC)(GLenum mode, GLuint id, GLsizei instancecount); GLAPI PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC glad_glDrawTransformFeedbackInstanced; #define glDrawTransformFeedbackInstanced glad_glDrawTransformFeedbackInstanced typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC)(GLenum mode, GLuint id, GLuint stream, GLsizei instancecount); GLAPI PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC glad_glDrawTransformFeedbackStreamInstanced; #define glDrawTransformFeedbackStreamInstanced glad_glDrawTransformFeedbackStreamInstanced #endif #ifndef GL_VERSION_4_3 #define GL_VERSION_4_3 1 GLAPI int GLAD_GL_VERSION_4_3; typedef void (APIENTRYP PFNGLCLEARBUFFERDATAPROC)(GLenum target, GLenum internalformat, GLenum format, GLenum type, const void *data); GLAPI PFNGLCLEARBUFFERDATAPROC glad_glClearBufferData; #define glClearBufferData glad_glClearBufferData typedef void (APIENTRYP PFNGLCLEARBUFFERSUBDATAPROC)(GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); GLAPI PFNGLCLEARBUFFERSUBDATAPROC glad_glClearBufferSubData; #define glClearBufferSubData glad_glClearBufferSubData typedef void (APIENTRYP PFNGLDISPATCHCOMPUTEPROC)(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z); GLAPI PFNGLDISPATCHCOMPUTEPROC glad_glDispatchCompute; #define glDispatchCompute glad_glDispatchCompute typedef void (APIENTRYP PFNGLDISPATCHCOMPUTEINDIRECTPROC)(GLintptr indirect); GLAPI PFNGLDISPATCHCOMPUTEINDIRECTPROC glad_glDispatchComputeIndirect; #define glDispatchComputeIndirect glad_glDispatchComputeIndirect typedef void (APIENTRYP PFNGLCOPYIMAGESUBDATAPROC)(GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); GLAPI PFNGLCOPYIMAGESUBDATAPROC glad_glCopyImageSubData; #define glCopyImageSubData glad_glCopyImageSubData typedef void (APIENTRYP PFNGLFRAMEBUFFERPARAMETERIPROC)(GLenum target, GLenum pname, GLint param); GLAPI PFNGLFRAMEBUFFERPARAMETERIPROC glad_glFramebufferParameteri; #define glFramebufferParameteri glad_glFramebufferParameteri typedef void (APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); GLAPI PFNGLGETFRAMEBUFFERPARAMETERIVPROC glad_glGetFramebufferParameteriv; #define glGetFramebufferParameteriv glad_glGetFramebufferParameteriv typedef void (APIENTRYP PFNGLGETINTERNALFORMATI64VPROC)(GLenum target, GLenum internalformat, GLenum pname, GLsizei count, GLint64 *params); GLAPI PFNGLGETINTERNALFORMATI64VPROC glad_glGetInternalformati64v; #define glGetInternalformati64v glad_glGetInternalformati64v typedef void (APIENTRYP PFNGLINVALIDATETEXSUBIMAGEPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth); GLAPI PFNGLINVALIDATETEXSUBIMAGEPROC glad_glInvalidateTexSubImage; #define glInvalidateTexSubImage glad_glInvalidateTexSubImage typedef void (APIENTRYP PFNGLINVALIDATETEXIMAGEPROC)(GLuint texture, GLint level); GLAPI PFNGLINVALIDATETEXIMAGEPROC glad_glInvalidateTexImage; #define glInvalidateTexImage glad_glInvalidateTexImage typedef void (APIENTRYP PFNGLINVALIDATEBUFFERSUBDATAPROC)(GLuint buffer, GLintptr offset, GLsizeiptr length); GLAPI PFNGLINVALIDATEBUFFERSUBDATAPROC glad_glInvalidateBufferSubData; #define glInvalidateBufferSubData glad_glInvalidateBufferSubData typedef void (APIENTRYP PFNGLINVALIDATEBUFFERDATAPROC)(GLuint buffer); GLAPI PFNGLINVALIDATEBUFFERDATAPROC glad_glInvalidateBufferData; #define glInvalidateBufferData glad_glInvalidateBufferData typedef void (APIENTRYP PFNGLINVALIDATEFRAMEBUFFERPROC)(GLenum target, GLsizei numAttachments, const GLenum *attachments); GLAPI PFNGLINVALIDATEFRAMEBUFFERPROC glad_glInvalidateFramebuffer; #define glInvalidateFramebuffer glad_glInvalidateFramebuffer typedef void (APIENTRYP PFNGLINVALIDATESUBFRAMEBUFFERPROC)(GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLINVALIDATESUBFRAMEBUFFERPROC glad_glInvalidateSubFramebuffer; #define glInvalidateSubFramebuffer glad_glInvalidateSubFramebuffer typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTPROC)(GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride); GLAPI PFNGLMULTIDRAWARRAYSINDIRECTPROC glad_glMultiDrawArraysIndirect; #define glMultiDrawArraysIndirect glad_glMultiDrawArraysIndirect typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTPROC)(GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride); GLAPI PFNGLMULTIDRAWELEMENTSINDIRECTPROC glad_glMultiDrawElementsIndirect; #define glMultiDrawElementsIndirect glad_glMultiDrawElementsIndirect typedef void (APIENTRYP PFNGLGETPROGRAMINTERFACEIVPROC)(GLuint program, GLenum programInterface, GLenum pname, GLint *params); GLAPI PFNGLGETPROGRAMINTERFACEIVPROC glad_glGetProgramInterfaceiv; #define glGetProgramInterfaceiv glad_glGetProgramInterfaceiv typedef GLuint (APIENTRYP PFNGLGETPROGRAMRESOURCEINDEXPROC)(GLuint program, GLenum programInterface, const GLchar *name); GLAPI PFNGLGETPROGRAMRESOURCEINDEXPROC glad_glGetProgramResourceIndex; #define glGetProgramResourceIndex glad_glGetProgramResourceIndex typedef void (APIENTRYP PFNGLGETPROGRAMRESOURCENAMEPROC)(GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); GLAPI PFNGLGETPROGRAMRESOURCENAMEPROC glad_glGetProgramResourceName; #define glGetProgramResourceName glad_glGetProgramResourceName typedef void (APIENTRYP PFNGLGETPROGRAMRESOURCEIVPROC)(GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei count, GLsizei *length, GLint *params); GLAPI PFNGLGETPROGRAMRESOURCEIVPROC glad_glGetProgramResourceiv; #define glGetProgramResourceiv glad_glGetProgramResourceiv typedef GLint (APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONPROC)(GLuint program, GLenum programInterface, const GLchar *name); GLAPI PFNGLGETPROGRAMRESOURCELOCATIONPROC glad_glGetProgramResourceLocation; #define glGetProgramResourceLocation glad_glGetProgramResourceLocation typedef GLint (APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC)(GLuint program, GLenum programInterface, const GLchar *name); GLAPI PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC glad_glGetProgramResourceLocationIndex; #define glGetProgramResourceLocationIndex glad_glGetProgramResourceLocationIndex typedef void (APIENTRYP PFNGLSHADERSTORAGEBLOCKBINDINGPROC)(GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding); GLAPI PFNGLSHADERSTORAGEBLOCKBINDINGPROC glad_glShaderStorageBlockBinding; #define glShaderStorageBlockBinding glad_glShaderStorageBlockBinding typedef void (APIENTRYP PFNGLTEXBUFFERRANGEPROC)(GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); GLAPI PFNGLTEXBUFFERRANGEPROC glad_glTexBufferRange; #define glTexBufferRange glad_glTexBufferRange typedef void (APIENTRYP PFNGLTEXSTORAGE2DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); GLAPI PFNGLTEXSTORAGE2DMULTISAMPLEPROC glad_glTexStorage2DMultisample; #define glTexStorage2DMultisample glad_glTexStorage2DMultisample typedef void (APIENTRYP PFNGLTEXSTORAGE3DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); GLAPI PFNGLTEXSTORAGE3DMULTISAMPLEPROC glad_glTexStorage3DMultisample; #define glTexStorage3DMultisample glad_glTexStorage3DMultisample typedef void (APIENTRYP PFNGLTEXTUREVIEWPROC)(GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); GLAPI PFNGLTEXTUREVIEWPROC glad_glTextureView; #define glTextureView glad_glTextureView typedef void (APIENTRYP PFNGLBINDVERTEXBUFFERPROC)(GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); GLAPI PFNGLBINDVERTEXBUFFERPROC glad_glBindVertexBuffer; #define glBindVertexBuffer glad_glBindVertexBuffer typedef void (APIENTRYP PFNGLVERTEXATTRIBFORMATPROC)(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); GLAPI PFNGLVERTEXATTRIBFORMATPROC glad_glVertexAttribFormat; #define glVertexAttribFormat glad_glVertexAttribFormat typedef void (APIENTRYP PFNGLVERTEXATTRIBIFORMATPROC)(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); GLAPI PFNGLVERTEXATTRIBIFORMATPROC glad_glVertexAttribIFormat; #define glVertexAttribIFormat glad_glVertexAttribIFormat typedef void (APIENTRYP PFNGLVERTEXATTRIBLFORMATPROC)(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); GLAPI PFNGLVERTEXATTRIBLFORMATPROC glad_glVertexAttribLFormat; #define glVertexAttribLFormat glad_glVertexAttribLFormat typedef void (APIENTRYP PFNGLVERTEXATTRIBBINDINGPROC)(GLuint attribindex, GLuint bindingindex); GLAPI PFNGLVERTEXATTRIBBINDINGPROC glad_glVertexAttribBinding; #define glVertexAttribBinding glad_glVertexAttribBinding typedef void (APIENTRYP PFNGLVERTEXBINDINGDIVISORPROC)(GLuint bindingindex, GLuint divisor); GLAPI PFNGLVERTEXBINDINGDIVISORPROC glad_glVertexBindingDivisor; #define glVertexBindingDivisor glad_glVertexBindingDivisor typedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLPROC)(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); GLAPI PFNGLDEBUGMESSAGECONTROLPROC glad_glDebugMessageControl; #define glDebugMessageControl glad_glDebugMessageControl typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTPROC)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); GLAPI PFNGLDEBUGMESSAGEINSERTPROC glad_glDebugMessageInsert; #define glDebugMessageInsert glad_glDebugMessageInsert typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKPROC)(GLDEBUGPROC callback, const void *userParam); GLAPI PFNGLDEBUGMESSAGECALLBACKPROC glad_glDebugMessageCallback; #define glDebugMessageCallback glad_glDebugMessageCallback typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGPROC)(GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); GLAPI PFNGLGETDEBUGMESSAGELOGPROC glad_glGetDebugMessageLog; #define glGetDebugMessageLog glad_glGetDebugMessageLog typedef void (APIENTRYP PFNGLPUSHDEBUGGROUPPROC)(GLenum source, GLuint id, GLsizei length, const GLchar *message); GLAPI PFNGLPUSHDEBUGGROUPPROC glad_glPushDebugGroup; #define glPushDebugGroup glad_glPushDebugGroup typedef void (APIENTRYP PFNGLPOPDEBUGGROUPPROC)(void); GLAPI PFNGLPOPDEBUGGROUPPROC glad_glPopDebugGroup; #define glPopDebugGroup glad_glPopDebugGroup typedef void (APIENTRYP PFNGLOBJECTLABELPROC)(GLenum identifier, GLuint name, GLsizei length, const GLchar *label); GLAPI PFNGLOBJECTLABELPROC glad_glObjectLabel; #define glObjectLabel glad_glObjectLabel typedef void (APIENTRYP PFNGLGETOBJECTLABELPROC)(GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); GLAPI PFNGLGETOBJECTLABELPROC glad_glGetObjectLabel; #define glGetObjectLabel glad_glGetObjectLabel typedef void (APIENTRYP PFNGLOBJECTPTRLABELPROC)(const void *ptr, GLsizei length, const GLchar *label); GLAPI PFNGLOBJECTPTRLABELPROC glad_glObjectPtrLabel; #define glObjectPtrLabel glad_glObjectPtrLabel typedef void (APIENTRYP PFNGLGETOBJECTPTRLABELPROC)(const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); GLAPI PFNGLGETOBJECTPTRLABELPROC glad_glGetObjectPtrLabel; #define glGetObjectPtrLabel glad_glGetObjectPtrLabel #endif #ifndef GL_VERSION_4_4 #define GL_VERSION_4_4 1 GLAPI int GLAD_GL_VERSION_4_4; typedef void (APIENTRYP PFNGLBUFFERSTORAGEPROC)(GLenum target, GLsizeiptr size, const void *data, GLbitfield flags); GLAPI PFNGLBUFFERSTORAGEPROC glad_glBufferStorage; #define glBufferStorage glad_glBufferStorage typedef void (APIENTRYP PFNGLCLEARTEXIMAGEPROC)(GLuint texture, GLint level, GLenum format, GLenum type, const void *data); GLAPI PFNGLCLEARTEXIMAGEPROC glad_glClearTexImage; #define glClearTexImage glad_glClearTexImage typedef void (APIENTRYP PFNGLCLEARTEXSUBIMAGEPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data); GLAPI PFNGLCLEARTEXSUBIMAGEPROC glad_glClearTexSubImage; #define glClearTexSubImage glad_glClearTexSubImage typedef void (APIENTRYP PFNGLBINDBUFFERSBASEPROC)(GLenum target, GLuint first, GLsizei count, const GLuint *buffers); GLAPI PFNGLBINDBUFFERSBASEPROC glad_glBindBuffersBase; #define glBindBuffersBase glad_glBindBuffersBase typedef void (APIENTRYP PFNGLBINDBUFFERSRANGEPROC)(GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizeiptr *sizes); GLAPI PFNGLBINDBUFFERSRANGEPROC glad_glBindBuffersRange; #define glBindBuffersRange glad_glBindBuffersRange typedef void (APIENTRYP PFNGLBINDTEXTURESPROC)(GLuint first, GLsizei count, const GLuint *textures); GLAPI PFNGLBINDTEXTURESPROC glad_glBindTextures; #define glBindTextures glad_glBindTextures typedef void (APIENTRYP PFNGLBINDSAMPLERSPROC)(GLuint first, GLsizei count, const GLuint *samplers); GLAPI PFNGLBINDSAMPLERSPROC glad_glBindSamplers; #define glBindSamplers glad_glBindSamplers typedef void (APIENTRYP PFNGLBINDIMAGETEXTURESPROC)(GLuint first, GLsizei count, const GLuint *textures); GLAPI PFNGLBINDIMAGETEXTURESPROC glad_glBindImageTextures; #define glBindImageTextures glad_glBindImageTextures typedef void (APIENTRYP PFNGLBINDVERTEXBUFFERSPROC)(GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); GLAPI PFNGLBINDVERTEXBUFFERSPROC glad_glBindVertexBuffers; #define glBindVertexBuffers glad_glBindVertexBuffers #endif #ifndef GL_VERSION_4_5 #define GL_VERSION_4_5 1 GLAPI int GLAD_GL_VERSION_4_5; typedef void (APIENTRYP PFNGLCLIPCONTROLPROC)(GLenum origin, GLenum depth); GLAPI PFNGLCLIPCONTROLPROC glad_glClipControl; #define glClipControl glad_glClipControl typedef void (APIENTRYP PFNGLCREATETRANSFORMFEEDBACKSPROC)(GLsizei n, GLuint *ids); GLAPI PFNGLCREATETRANSFORMFEEDBACKSPROC glad_glCreateTransformFeedbacks; #define glCreateTransformFeedbacks glad_glCreateTransformFeedbacks typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC)(GLuint xfb, GLuint index, GLuint buffer); GLAPI PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC glad_glTransformFeedbackBufferBase; #define glTransformFeedbackBufferBase glad_glTransformFeedbackBufferBase typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC)(GLuint xfb, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); GLAPI PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC glad_glTransformFeedbackBufferRange; #define glTransformFeedbackBufferRange glad_glTransformFeedbackBufferRange typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKIVPROC)(GLuint xfb, GLenum pname, GLint *param); GLAPI PFNGLGETTRANSFORMFEEDBACKIVPROC glad_glGetTransformFeedbackiv; #define glGetTransformFeedbackiv glad_glGetTransformFeedbackiv typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI_VPROC)(GLuint xfb, GLenum pname, GLuint index, GLint *param); GLAPI PFNGLGETTRANSFORMFEEDBACKI_VPROC glad_glGetTransformFeedbacki_v; #define glGetTransformFeedbacki_v glad_glGetTransformFeedbacki_v typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI64_VPROC)(GLuint xfb, GLenum pname, GLuint index, GLint64 *param); GLAPI PFNGLGETTRANSFORMFEEDBACKI64_VPROC glad_glGetTransformFeedbacki64_v; #define glGetTransformFeedbacki64_v glad_glGetTransformFeedbacki64_v typedef void (APIENTRYP PFNGLCREATEBUFFERSPROC)(GLsizei n, GLuint *buffers); GLAPI PFNGLCREATEBUFFERSPROC glad_glCreateBuffers; #define glCreateBuffers glad_glCreateBuffers typedef void (APIENTRYP PFNGLNAMEDBUFFERSTORAGEPROC)(GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); GLAPI PFNGLNAMEDBUFFERSTORAGEPROC glad_glNamedBufferStorage; #define glNamedBufferStorage glad_glNamedBufferStorage typedef void (APIENTRYP PFNGLNAMEDBUFFERDATAPROC)(GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); GLAPI PFNGLNAMEDBUFFERDATAPROC glad_glNamedBufferData; #define glNamedBufferData glad_glNamedBufferData typedef void (APIENTRYP PFNGLNAMEDBUFFERSUBDATAPROC)(GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); GLAPI PFNGLNAMEDBUFFERSUBDATAPROC glad_glNamedBufferSubData; #define glNamedBufferSubData glad_glNamedBufferSubData typedef void (APIENTRYP PFNGLCOPYNAMEDBUFFERSUBDATAPROC)(GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); GLAPI PFNGLCOPYNAMEDBUFFERSUBDATAPROC glad_glCopyNamedBufferSubData; #define glCopyNamedBufferSubData glad_glCopyNamedBufferSubData typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERDATAPROC)(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); GLAPI PFNGLCLEARNAMEDBUFFERDATAPROC glad_glClearNamedBufferData; #define glClearNamedBufferData glad_glClearNamedBufferData typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERSUBDATAPROC)(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); GLAPI PFNGLCLEARNAMEDBUFFERSUBDATAPROC glad_glClearNamedBufferSubData; #define glClearNamedBufferSubData glad_glClearNamedBufferSubData typedef void * (APIENTRYP PFNGLMAPNAMEDBUFFERPROC)(GLuint buffer, GLenum access); GLAPI PFNGLMAPNAMEDBUFFERPROC glad_glMapNamedBuffer; #define glMapNamedBuffer glad_glMapNamedBuffer typedef void * (APIENTRYP PFNGLMAPNAMEDBUFFERRANGEPROC)(GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); GLAPI PFNGLMAPNAMEDBUFFERRANGEPROC glad_glMapNamedBufferRange; #define glMapNamedBufferRange glad_glMapNamedBufferRange typedef GLboolean (APIENTRYP PFNGLUNMAPNAMEDBUFFERPROC)(GLuint buffer); GLAPI PFNGLUNMAPNAMEDBUFFERPROC glad_glUnmapNamedBuffer; #define glUnmapNamedBuffer glad_glUnmapNamedBuffer typedef void (APIENTRYP PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC)(GLuint buffer, GLintptr offset, GLsizeiptr length); GLAPI PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC glad_glFlushMappedNamedBufferRange; #define glFlushMappedNamedBufferRange glad_glFlushMappedNamedBufferRange typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERIVPROC)(GLuint buffer, GLenum pname, GLint *params); GLAPI PFNGLGETNAMEDBUFFERPARAMETERIVPROC glad_glGetNamedBufferParameteriv; #define glGetNamedBufferParameteriv glad_glGetNamedBufferParameteriv typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERI64VPROC)(GLuint buffer, GLenum pname, GLint64 *params); GLAPI PFNGLGETNAMEDBUFFERPARAMETERI64VPROC glad_glGetNamedBufferParameteri64v; #define glGetNamedBufferParameteri64v glad_glGetNamedBufferParameteri64v typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPOINTERVPROC)(GLuint buffer, GLenum pname, void **params); GLAPI PFNGLGETNAMEDBUFFERPOINTERVPROC glad_glGetNamedBufferPointerv; #define glGetNamedBufferPointerv glad_glGetNamedBufferPointerv typedef void (APIENTRYP PFNGLGETNAMEDBUFFERSUBDATAPROC)(GLuint buffer, GLintptr offset, GLsizeiptr size, void *data); GLAPI PFNGLGETNAMEDBUFFERSUBDATAPROC glad_glGetNamedBufferSubData; #define glGetNamedBufferSubData glad_glGetNamedBufferSubData typedef void (APIENTRYP PFNGLCREATEFRAMEBUFFERSPROC)(GLsizei n, GLuint *framebuffers); GLAPI PFNGLCREATEFRAMEBUFFERSPROC glad_glCreateFramebuffers; #define glCreateFramebuffers glad_glCreateFramebuffers typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC)(GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); GLAPI PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC glad_glNamedFramebufferRenderbuffer; #define glNamedFramebufferRenderbuffer glad_glNamedFramebufferRenderbuffer typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC)(GLuint framebuffer, GLenum pname, GLint param); GLAPI PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC glad_glNamedFramebufferParameteri; #define glNamedFramebufferParameteri glad_glNamedFramebufferParameteri typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREPROC)(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); GLAPI PFNGLNAMEDFRAMEBUFFERTEXTUREPROC glad_glNamedFramebufferTexture; #define glNamedFramebufferTexture glad_glNamedFramebufferTexture typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC)(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); GLAPI PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC glad_glNamedFramebufferTextureLayer; #define glNamedFramebufferTextureLayer glad_glNamedFramebufferTextureLayer typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC)(GLuint framebuffer, GLenum buf); GLAPI PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC glad_glNamedFramebufferDrawBuffer; #define glNamedFramebufferDrawBuffer glad_glNamedFramebufferDrawBuffer typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC)(GLuint framebuffer, GLsizei n, const GLenum *bufs); GLAPI PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC glad_glNamedFramebufferDrawBuffers; #define glNamedFramebufferDrawBuffers glad_glNamedFramebufferDrawBuffers typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC)(GLuint framebuffer, GLenum src); GLAPI PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC glad_glNamedFramebufferReadBuffer; #define glNamedFramebufferReadBuffer glad_glNamedFramebufferReadBuffer typedef void (APIENTRYP PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC)(GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments); GLAPI PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC glad_glInvalidateNamedFramebufferData; #define glInvalidateNamedFramebufferData glad_glInvalidateNamedFramebufferData typedef void (APIENTRYP PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC)(GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC glad_glInvalidateNamedFramebufferSubData; #define glInvalidateNamedFramebufferSubData glad_glInvalidateNamedFramebufferSubData typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERIVPROC)(GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLint *value); GLAPI PFNGLCLEARNAMEDFRAMEBUFFERIVPROC glad_glClearNamedFramebufferiv; #define glClearNamedFramebufferiv glad_glClearNamedFramebufferiv typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC)(GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLuint *value); GLAPI PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC glad_glClearNamedFramebufferuiv; #define glClearNamedFramebufferuiv glad_glClearNamedFramebufferuiv typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERFVPROC)(GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLfloat *value); GLAPI PFNGLCLEARNAMEDFRAMEBUFFERFVPROC glad_glClearNamedFramebufferfv; #define glClearNamedFramebufferfv glad_glClearNamedFramebufferfv typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERFIPROC)(GLuint framebuffer, GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); GLAPI PFNGLCLEARNAMEDFRAMEBUFFERFIPROC glad_glClearNamedFramebufferfi; #define glClearNamedFramebufferfi glad_glClearNamedFramebufferfi typedef void (APIENTRYP PFNGLBLITNAMEDFRAMEBUFFERPROC)(GLuint readFramebuffer, GLuint drawFramebuffer, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); GLAPI PFNGLBLITNAMEDFRAMEBUFFERPROC glad_glBlitNamedFramebuffer; #define glBlitNamedFramebuffer glad_glBlitNamedFramebuffer typedef GLenum (APIENTRYP PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC)(GLuint framebuffer, GLenum target); GLAPI PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC glad_glCheckNamedFramebufferStatus; #define glCheckNamedFramebufferStatus glad_glCheckNamedFramebufferStatus typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC)(GLuint framebuffer, GLenum pname, GLint *param); GLAPI PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC glad_glGetNamedFramebufferParameteriv; #define glGetNamedFramebufferParameteriv glad_glGetNamedFramebufferParameteriv typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC)(GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); GLAPI PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetNamedFramebufferAttachmentParameteriv; #define glGetNamedFramebufferAttachmentParameteriv glad_glGetNamedFramebufferAttachmentParameteriv typedef void (APIENTRYP PFNGLCREATERENDERBUFFERSPROC)(GLsizei n, GLuint *renderbuffers); GLAPI PFNGLCREATERENDERBUFFERSPROC glad_glCreateRenderbuffers; #define glCreateRenderbuffers glad_glCreateRenderbuffers typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEPROC)(GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); GLAPI PFNGLNAMEDRENDERBUFFERSTORAGEPROC glad_glNamedRenderbufferStorage; #define glNamedRenderbufferStorage glad_glNamedRenderbufferStorage typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC)(GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); GLAPI PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glNamedRenderbufferStorageMultisample; #define glNamedRenderbufferStorageMultisample glad_glNamedRenderbufferStorageMultisample typedef void (APIENTRYP PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC)(GLuint renderbuffer, GLenum pname, GLint *params); GLAPI PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC glad_glGetNamedRenderbufferParameteriv; #define glGetNamedRenderbufferParameteriv glad_glGetNamedRenderbufferParameteriv typedef void (APIENTRYP PFNGLCREATETEXTURESPROC)(GLenum target, GLsizei n, GLuint *textures); GLAPI PFNGLCREATETEXTURESPROC glad_glCreateTextures; #define glCreateTextures glad_glCreateTextures typedef void (APIENTRYP PFNGLTEXTUREBUFFERPROC)(GLuint texture, GLenum internalformat, GLuint buffer); GLAPI PFNGLTEXTUREBUFFERPROC glad_glTextureBuffer; #define glTextureBuffer glad_glTextureBuffer typedef void (APIENTRYP PFNGLTEXTUREBUFFERRANGEPROC)(GLuint texture, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); GLAPI PFNGLTEXTUREBUFFERRANGEPROC glad_glTextureBufferRange; #define glTextureBufferRange glad_glTextureBufferRange typedef void (APIENTRYP PFNGLTEXTURESTORAGE1DPROC)(GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width); GLAPI PFNGLTEXTURESTORAGE1DPROC glad_glTextureStorage1D; #define glTextureStorage1D glad_glTextureStorage1D typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DPROC)(GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); GLAPI PFNGLTEXTURESTORAGE2DPROC glad_glTextureStorage2D; #define glTextureStorage2D glad_glTextureStorage2D typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DPROC)(GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); GLAPI PFNGLTEXTURESTORAGE3DPROC glad_glTextureStorage3D; #define glTextureStorage3D glad_glTextureStorage3D typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC)(GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); GLAPI PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC glad_glTextureStorage2DMultisample; #define glTextureStorage2DMultisample glad_glTextureStorage2DMultisample typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC)(GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); GLAPI PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC glad_glTextureStorage3DMultisample; #define glTextureStorage3DMultisample glad_glTextureStorage3DMultisample typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE1DPROC)(GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXTURESUBIMAGE1DPROC glad_glTextureSubImage1D; #define glTextureSubImage1D glad_glTextureSubImage1D typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE2DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXTURESUBIMAGE2DPROC glad_glTextureSubImage2D; #define glTextureSubImage2D glad_glTextureSubImage2D typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE3DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXTURESUBIMAGE3DPROC glad_glTextureSubImage3D; #define glTextureSubImage3D glad_glTextureSubImage3D typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC)(GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC glad_glCompressedTextureSubImage1D; #define glCompressedTextureSubImage1D glad_glCompressedTextureSubImage1D typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC glad_glCompressedTextureSubImage2D; #define glCompressedTextureSubImage2D glad_glCompressedTextureSubImage2D typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC glad_glCompressedTextureSubImage3D; #define glCompressedTextureSubImage3D glad_glCompressedTextureSubImage3D typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE1DPROC)(GLuint texture, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); GLAPI PFNGLCOPYTEXTURESUBIMAGE1DPROC glad_glCopyTextureSubImage1D; #define glCopyTextureSubImage1D glad_glCopyTextureSubImage1D typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE2DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLCOPYTEXTURESUBIMAGE2DPROC glad_glCopyTextureSubImage2D; #define glCopyTextureSubImage2D glad_glCopyTextureSubImage2D typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE3DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLCOPYTEXTURESUBIMAGE3DPROC glad_glCopyTextureSubImage3D; #define glCopyTextureSubImage3D glad_glCopyTextureSubImage3D typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFPROC)(GLuint texture, GLenum pname, GLfloat param); GLAPI PFNGLTEXTUREPARAMETERFPROC glad_glTextureParameterf; #define glTextureParameterf glad_glTextureParameterf typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFVPROC)(GLuint texture, GLenum pname, const GLfloat *param); GLAPI PFNGLTEXTUREPARAMETERFVPROC glad_glTextureParameterfv; #define glTextureParameterfv glad_glTextureParameterfv typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIPROC)(GLuint texture, GLenum pname, GLint param); GLAPI PFNGLTEXTUREPARAMETERIPROC glad_glTextureParameteri; #define glTextureParameteri glad_glTextureParameteri typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIIVPROC)(GLuint texture, GLenum pname, const GLint *params); GLAPI PFNGLTEXTUREPARAMETERIIVPROC glad_glTextureParameterIiv; #define glTextureParameterIiv glad_glTextureParameterIiv typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIUIVPROC)(GLuint texture, GLenum pname, const GLuint *params); GLAPI PFNGLTEXTUREPARAMETERIUIVPROC glad_glTextureParameterIuiv; #define glTextureParameterIuiv glad_glTextureParameterIuiv typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIVPROC)(GLuint texture, GLenum pname, const GLint *param); GLAPI PFNGLTEXTUREPARAMETERIVPROC glad_glTextureParameteriv; #define glTextureParameteriv glad_glTextureParameteriv typedef void (APIENTRYP PFNGLGENERATETEXTUREMIPMAPPROC)(GLuint texture); GLAPI PFNGLGENERATETEXTUREMIPMAPPROC glad_glGenerateTextureMipmap; #define glGenerateTextureMipmap glad_glGenerateTextureMipmap typedef void (APIENTRYP PFNGLBINDTEXTUREUNITPROC)(GLuint unit, GLuint texture); GLAPI PFNGLBINDTEXTUREUNITPROC glad_glBindTextureUnit; #define glBindTextureUnit glad_glBindTextureUnit typedef void (APIENTRYP PFNGLGETTEXTUREIMAGEPROC)(GLuint texture, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); GLAPI PFNGLGETTEXTUREIMAGEPROC glad_glGetTextureImage; #define glGetTextureImage glad_glGetTextureImage typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC)(GLuint texture, GLint level, GLsizei bufSize, void *pixels); GLAPI PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC glad_glGetCompressedTextureImage; #define glGetCompressedTextureImage glad_glGetCompressedTextureImage typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERFVPROC)(GLuint texture, GLint level, GLenum pname, GLfloat *params); GLAPI PFNGLGETTEXTURELEVELPARAMETERFVPROC glad_glGetTextureLevelParameterfv; #define glGetTextureLevelParameterfv glad_glGetTextureLevelParameterfv typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERIVPROC)(GLuint texture, GLint level, GLenum pname, GLint *params); GLAPI PFNGLGETTEXTURELEVELPARAMETERIVPROC glad_glGetTextureLevelParameteriv; #define glGetTextureLevelParameteriv glad_glGetTextureLevelParameteriv typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERFVPROC)(GLuint texture, GLenum pname, GLfloat *params); GLAPI PFNGLGETTEXTUREPARAMETERFVPROC glad_glGetTextureParameterfv; #define glGetTextureParameterfv glad_glGetTextureParameterfv typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIIVPROC)(GLuint texture, GLenum pname, GLint *params); GLAPI PFNGLGETTEXTUREPARAMETERIIVPROC glad_glGetTextureParameterIiv; #define glGetTextureParameterIiv glad_glGetTextureParameterIiv typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIUIVPROC)(GLuint texture, GLenum pname, GLuint *params); GLAPI PFNGLGETTEXTUREPARAMETERIUIVPROC glad_glGetTextureParameterIuiv; #define glGetTextureParameterIuiv glad_glGetTextureParameterIuiv typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIVPROC)(GLuint texture, GLenum pname, GLint *params); GLAPI PFNGLGETTEXTUREPARAMETERIVPROC glad_glGetTextureParameteriv; #define glGetTextureParameteriv glad_glGetTextureParameteriv typedef void (APIENTRYP PFNGLCREATEVERTEXARRAYSPROC)(GLsizei n, GLuint *arrays); GLAPI PFNGLCREATEVERTEXARRAYSPROC glad_glCreateVertexArrays; #define glCreateVertexArrays glad_glCreateVertexArrays typedef void (APIENTRYP PFNGLDISABLEVERTEXARRAYATTRIBPROC)(GLuint vaobj, GLuint index); GLAPI PFNGLDISABLEVERTEXARRAYATTRIBPROC glad_glDisableVertexArrayAttrib; #define glDisableVertexArrayAttrib glad_glDisableVertexArrayAttrib typedef void (APIENTRYP PFNGLENABLEVERTEXARRAYATTRIBPROC)(GLuint vaobj, GLuint index); GLAPI PFNGLENABLEVERTEXARRAYATTRIBPROC glad_glEnableVertexArrayAttrib; #define glEnableVertexArrayAttrib glad_glEnableVertexArrayAttrib typedef void (APIENTRYP PFNGLVERTEXARRAYELEMENTBUFFERPROC)(GLuint vaobj, GLuint buffer); GLAPI PFNGLVERTEXARRAYELEMENTBUFFERPROC glad_glVertexArrayElementBuffer; #define glVertexArrayElementBuffer glad_glVertexArrayElementBuffer typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBUFFERPROC)(GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); GLAPI PFNGLVERTEXARRAYVERTEXBUFFERPROC glad_glVertexArrayVertexBuffer; #define glVertexArrayVertexBuffer glad_glVertexArrayVertexBuffer typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBUFFERSPROC)(GLuint vaobj, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); GLAPI PFNGLVERTEXARRAYVERTEXBUFFERSPROC glad_glVertexArrayVertexBuffers; #define glVertexArrayVertexBuffers glad_glVertexArrayVertexBuffers typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBBINDINGPROC)(GLuint vaobj, GLuint attribindex, GLuint bindingindex); GLAPI PFNGLVERTEXARRAYATTRIBBINDINGPROC glad_glVertexArrayAttribBinding; #define glVertexArrayAttribBinding glad_glVertexArrayAttribBinding typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBFORMATPROC)(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); GLAPI PFNGLVERTEXARRAYATTRIBFORMATPROC glad_glVertexArrayAttribFormat; #define glVertexArrayAttribFormat glad_glVertexArrayAttribFormat typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBIFORMATPROC)(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); GLAPI PFNGLVERTEXARRAYATTRIBIFORMATPROC glad_glVertexArrayAttribIFormat; #define glVertexArrayAttribIFormat glad_glVertexArrayAttribIFormat typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBLFORMATPROC)(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); GLAPI PFNGLVERTEXARRAYATTRIBLFORMATPROC glad_glVertexArrayAttribLFormat; #define glVertexArrayAttribLFormat glad_glVertexArrayAttribLFormat typedef void (APIENTRYP PFNGLVERTEXARRAYBINDINGDIVISORPROC)(GLuint vaobj, GLuint bindingindex, GLuint divisor); GLAPI PFNGLVERTEXARRAYBINDINGDIVISORPROC glad_glVertexArrayBindingDivisor; #define glVertexArrayBindingDivisor glad_glVertexArrayBindingDivisor typedef void (APIENTRYP PFNGLGETVERTEXARRAYIVPROC)(GLuint vaobj, GLenum pname, GLint *param); GLAPI PFNGLGETVERTEXARRAYIVPROC glad_glGetVertexArrayiv; #define glGetVertexArrayiv glad_glGetVertexArrayiv typedef void (APIENTRYP PFNGLGETVERTEXARRAYINDEXEDIVPROC)(GLuint vaobj, GLuint index, GLenum pname, GLint *param); GLAPI PFNGLGETVERTEXARRAYINDEXEDIVPROC glad_glGetVertexArrayIndexediv; #define glGetVertexArrayIndexediv glad_glGetVertexArrayIndexediv typedef void (APIENTRYP PFNGLGETVERTEXARRAYINDEXED64IVPROC)(GLuint vaobj, GLuint index, GLenum pname, GLint64 *param); GLAPI PFNGLGETVERTEXARRAYINDEXED64IVPROC glad_glGetVertexArrayIndexed64iv; #define glGetVertexArrayIndexed64iv glad_glGetVertexArrayIndexed64iv typedef void (APIENTRYP PFNGLCREATESAMPLERSPROC)(GLsizei n, GLuint *samplers); GLAPI PFNGLCREATESAMPLERSPROC glad_glCreateSamplers; #define glCreateSamplers glad_glCreateSamplers typedef void (APIENTRYP PFNGLCREATEPROGRAMPIPELINESPROC)(GLsizei n, GLuint *pipelines); GLAPI PFNGLCREATEPROGRAMPIPELINESPROC glad_glCreateProgramPipelines; #define glCreateProgramPipelines glad_glCreateProgramPipelines typedef void (APIENTRYP PFNGLCREATEQUERIESPROC)(GLenum target, GLsizei n, GLuint *ids); GLAPI PFNGLCREATEQUERIESPROC glad_glCreateQueries; #define glCreateQueries glad_glCreateQueries typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTI64VPROC)(GLuint id, GLuint buffer, GLenum pname, GLintptr offset); GLAPI PFNGLGETQUERYBUFFEROBJECTI64VPROC glad_glGetQueryBufferObjecti64v; #define glGetQueryBufferObjecti64v glad_glGetQueryBufferObjecti64v typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTIVPROC)(GLuint id, GLuint buffer, GLenum pname, GLintptr offset); GLAPI PFNGLGETQUERYBUFFEROBJECTIVPROC glad_glGetQueryBufferObjectiv; #define glGetQueryBufferObjectiv glad_glGetQueryBufferObjectiv typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTUI64VPROC)(GLuint id, GLuint buffer, GLenum pname, GLintptr offset); GLAPI PFNGLGETQUERYBUFFEROBJECTUI64VPROC glad_glGetQueryBufferObjectui64v; #define glGetQueryBufferObjectui64v glad_glGetQueryBufferObjectui64v typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTUIVPROC)(GLuint id, GLuint buffer, GLenum pname, GLintptr offset); GLAPI PFNGLGETQUERYBUFFEROBJECTUIVPROC glad_glGetQueryBufferObjectuiv; #define glGetQueryBufferObjectuiv glad_glGetQueryBufferObjectuiv typedef void (APIENTRYP PFNGLMEMORYBARRIERBYREGIONPROC)(GLbitfield barriers); GLAPI PFNGLMEMORYBARRIERBYREGIONPROC glad_glMemoryBarrierByRegion; #define glMemoryBarrierByRegion glad_glMemoryBarrierByRegion typedef void (APIENTRYP PFNGLGETTEXTURESUBIMAGEPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLsizei bufSize, void *pixels); GLAPI PFNGLGETTEXTURESUBIMAGEPROC glad_glGetTextureSubImage; #define glGetTextureSubImage glad_glGetTextureSubImage typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei bufSize, void *pixels); GLAPI PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC glad_glGetCompressedTextureSubImage; #define glGetCompressedTextureSubImage glad_glGetCompressedTextureSubImage typedef GLenum (APIENTRYP PFNGLGETGRAPHICSRESETSTATUSPROC)(void); GLAPI PFNGLGETGRAPHICSRESETSTATUSPROC glad_glGetGraphicsResetStatus; #define glGetGraphicsResetStatus glad_glGetGraphicsResetStatus typedef void (APIENTRYP PFNGLGETNCOMPRESSEDTEXIMAGEPROC)(GLenum target, GLint lod, GLsizei bufSize, void *pixels); GLAPI PFNGLGETNCOMPRESSEDTEXIMAGEPROC glad_glGetnCompressedTexImage; #define glGetnCompressedTexImage glad_glGetnCompressedTexImage typedef void (APIENTRYP PFNGLGETNTEXIMAGEPROC)(GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); GLAPI PFNGLGETNTEXIMAGEPROC glad_glGetnTexImage; #define glGetnTexImage glad_glGetnTexImage typedef void (APIENTRYP PFNGLGETNUNIFORMDVPROC)(GLuint program, GLint location, GLsizei bufSize, GLdouble *params); GLAPI PFNGLGETNUNIFORMDVPROC glad_glGetnUniformdv; #define glGetnUniformdv glad_glGetnUniformdv typedef void (APIENTRYP PFNGLGETNUNIFORMFVPROC)(GLuint program, GLint location, GLsizei bufSize, GLfloat *params); GLAPI PFNGLGETNUNIFORMFVPROC glad_glGetnUniformfv; #define glGetnUniformfv glad_glGetnUniformfv typedef void (APIENTRYP PFNGLGETNUNIFORMIVPROC)(GLuint program, GLint location, GLsizei bufSize, GLint *params); GLAPI PFNGLGETNUNIFORMIVPROC glad_glGetnUniformiv; #define glGetnUniformiv glad_glGetnUniformiv typedef void (APIENTRYP PFNGLGETNUNIFORMUIVPROC)(GLuint program, GLint location, GLsizei bufSize, GLuint *params); GLAPI PFNGLGETNUNIFORMUIVPROC glad_glGetnUniformuiv; #define glGetnUniformuiv glad_glGetnUniformuiv typedef void (APIENTRYP PFNGLREADNPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); GLAPI PFNGLREADNPIXELSPROC glad_glReadnPixels; #define glReadnPixels glad_glReadnPixels typedef void (APIENTRYP PFNGLGETNMAPDVPROC)(GLenum target, GLenum query, GLsizei bufSize, GLdouble *v); GLAPI PFNGLGETNMAPDVPROC glad_glGetnMapdv; #define glGetnMapdv glad_glGetnMapdv typedef void (APIENTRYP PFNGLGETNMAPFVPROC)(GLenum target, GLenum query, GLsizei bufSize, GLfloat *v); GLAPI PFNGLGETNMAPFVPROC glad_glGetnMapfv; #define glGetnMapfv glad_glGetnMapfv typedef void (APIENTRYP PFNGLGETNMAPIVPROC)(GLenum target, GLenum query, GLsizei bufSize, GLint *v); GLAPI PFNGLGETNMAPIVPROC glad_glGetnMapiv; #define glGetnMapiv glad_glGetnMapiv typedef void (APIENTRYP PFNGLGETNPIXELMAPFVPROC)(GLenum map, GLsizei bufSize, GLfloat *values); GLAPI PFNGLGETNPIXELMAPFVPROC glad_glGetnPixelMapfv; #define glGetnPixelMapfv glad_glGetnPixelMapfv typedef void (APIENTRYP PFNGLGETNPIXELMAPUIVPROC)(GLenum map, GLsizei bufSize, GLuint *values); GLAPI PFNGLGETNPIXELMAPUIVPROC glad_glGetnPixelMapuiv; #define glGetnPixelMapuiv glad_glGetnPixelMapuiv typedef void (APIENTRYP PFNGLGETNPIXELMAPUSVPROC)(GLenum map, GLsizei bufSize, GLushort *values); GLAPI PFNGLGETNPIXELMAPUSVPROC glad_glGetnPixelMapusv; #define glGetnPixelMapusv glad_glGetnPixelMapusv typedef void (APIENTRYP PFNGLGETNPOLYGONSTIPPLEPROC)(GLsizei bufSize, GLubyte *pattern); GLAPI PFNGLGETNPOLYGONSTIPPLEPROC glad_glGetnPolygonStipple; #define glGetnPolygonStipple glad_glGetnPolygonStipple typedef void (APIENTRYP PFNGLGETNCOLORTABLEPROC)(GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table); GLAPI PFNGLGETNCOLORTABLEPROC glad_glGetnColorTable; #define glGetnColorTable glad_glGetnColorTable typedef void (APIENTRYP PFNGLGETNCONVOLUTIONFILTERPROC)(GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image); GLAPI PFNGLGETNCONVOLUTIONFILTERPROC glad_glGetnConvolutionFilter; #define glGetnConvolutionFilter glad_glGetnConvolutionFilter typedef void (APIENTRYP PFNGLGETNSEPARABLEFILTERPROC)(GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); GLAPI PFNGLGETNSEPARABLEFILTERPROC glad_glGetnSeparableFilter; #define glGetnSeparableFilter glad_glGetnSeparableFilter typedef void (APIENTRYP PFNGLGETNHISTOGRAMPROC)(GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); GLAPI PFNGLGETNHISTOGRAMPROC glad_glGetnHistogram; #define glGetnHistogram glad_glGetnHistogram typedef void (APIENTRYP PFNGLGETNMINMAXPROC)(GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); GLAPI PFNGLGETNMINMAXPROC glad_glGetnMinmax; #define glGetnMinmax glad_glGetnMinmax typedef void (APIENTRYP PFNGLTEXTUREBARRIERPROC)(void); GLAPI PFNGLTEXTUREBARRIERPROC glad_glTextureBarrier; #define glTextureBarrier glad_glTextureBarrier #endif #ifndef GL_VERSION_4_6 #define GL_VERSION_4_6 1 GLAPI int GLAD_GL_VERSION_4_6; typedef void (APIENTRYP PFNGLSPECIALIZESHADERPROC)(GLuint shader, const GLchar *pEntryPoint, GLuint numSpecializationConstants, const GLuint *pConstantIndex, const GLuint *pConstantValue); GLAPI PFNGLSPECIALIZESHADERPROC glad_glSpecializeShader; #define glSpecializeShader glad_glSpecializeShader typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTCOUNTPROC)(GLenum mode, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); GLAPI PFNGLMULTIDRAWARRAYSINDIRECTCOUNTPROC glad_glMultiDrawArraysIndirectCount; #define glMultiDrawArraysIndirectCount glad_glMultiDrawArraysIndirectCount typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTPROC)(GLenum mode, GLenum type, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); GLAPI PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTPROC glad_glMultiDrawElementsIndirectCount; #define glMultiDrawElementsIndirectCount glad_glMultiDrawElementsIndirectCount typedef void (APIENTRYP PFNGLPOLYGONOFFSETCLAMPPROC)(GLfloat factor, GLfloat units, GLfloat clamp); GLAPI PFNGLPOLYGONOFFSETCLAMPPROC glad_glPolygonOffsetClamp; #define glPolygonOffsetClamp glad_glPolygonOffsetClamp #endif #ifdef __cplusplus } #endif #endif ================================================ FILE: extern/glad/src/glad.c ================================================ /* OpenGL loader generated by glad 0.1.34 on Sat Jul 8 18:48:45 2023. Language/Generator: C/C++ Specification: gl APIs: gl=4.6 Profile: compatibility Extensions: Loader: True Local files: False Omit khrplatform: False Reproducible: False Commandline: --profile="compatibility" --api="gl=4.6" --generator="c" --spec="gl" --extensions="" Online: https://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&loader=on&api=gl%3D4.6 */ #include #include #include #include static void* get_proc(const char *namez); #if defined(_WIN32) || defined(__CYGWIN__) #ifndef _WINDOWS_ #undef APIENTRY #endif #include static HMODULE libGL; typedef void* (APIENTRYP PFNWGLGETPROCADDRESSPROC_PRIVATE)(const char*); static PFNWGLGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr; #ifdef _MSC_VER #ifdef __has_include #if __has_include() #define HAVE_WINAPIFAMILY 1 #endif #elif _MSC_VER >= 1700 && !_USING_V110_SDK71_ #define HAVE_WINAPIFAMILY 1 #endif #endif #ifdef HAVE_WINAPIFAMILY #include #if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) #define IS_UWP 1 #endif #endif static int open_gl(void) { #ifndef IS_UWP libGL = LoadLibraryW(L"opengl32.dll"); if(libGL != NULL) { void (* tmp)(void); tmp = (void(*)(void)) GetProcAddress(libGL, "wglGetProcAddress"); gladGetProcAddressPtr = (PFNWGLGETPROCADDRESSPROC_PRIVATE) tmp; return gladGetProcAddressPtr != NULL; } #endif return 0; } static void close_gl(void) { if(libGL != NULL) { FreeLibrary((HMODULE) libGL); libGL = NULL; } } #else #include static void* libGL; #if !defined(__APPLE__) && !defined(__HAIKU__) typedef void* (APIENTRYP PFNGLXGETPROCADDRESSPROC_PRIVATE)(const char*); static PFNGLXGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr; #endif static int open_gl(void) { #ifdef __APPLE__ static const char *NAMES[] = { "../Frameworks/OpenGL.framework/OpenGL", "/Library/Frameworks/OpenGL.framework/OpenGL", "/System/Library/Frameworks/OpenGL.framework/OpenGL", "/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL" }; #else static const char *NAMES[] = {"libGL.so.1", "libGL.so"}; #endif unsigned int index = 0; for(index = 0; index < (sizeof(NAMES) / sizeof(NAMES[0])); index++) { libGL = dlopen(NAMES[index], RTLD_NOW | RTLD_GLOBAL); if(libGL != NULL) { #if defined(__APPLE__) || defined(__HAIKU__) return 1; #else gladGetProcAddressPtr = (PFNGLXGETPROCADDRESSPROC_PRIVATE)dlsym(libGL, "glXGetProcAddressARB"); return gladGetProcAddressPtr != NULL; #endif } } return 0; } static void close_gl(void) { if(libGL != NULL) { dlclose(libGL); libGL = NULL; } } #endif static void* get_proc(const char *namez) { void* result = NULL; if(libGL == NULL) return NULL; #if !defined(__APPLE__) && !defined(__HAIKU__) if(gladGetProcAddressPtr != NULL) { result = gladGetProcAddressPtr(namez); } #endif if(result == NULL) { #if defined(_WIN32) || defined(__CYGWIN__) result = (void*)GetProcAddress((HMODULE) libGL, namez); #else result = dlsym(libGL, namez); #endif } return result; } int gladLoadGL(void) { int status = 0; if(open_gl()) { status = gladLoadGLLoader(&get_proc); close_gl(); } return status; } struct gladGLversionStruct GLVersion = { 0, 0 }; #if defined(GL_ES_VERSION_3_0) || defined(GL_VERSION_3_0) #define _GLAD_IS_SOME_NEW_VERSION 1 #endif static int max_loaded_major; static int max_loaded_minor; static const char *exts = NULL; static int num_exts_i = 0; static char **exts_i = NULL; static int get_exts(void) { #ifdef _GLAD_IS_SOME_NEW_VERSION if(max_loaded_major < 3) { #endif exts = (const char *)glGetString(GL_EXTENSIONS); #ifdef _GLAD_IS_SOME_NEW_VERSION } else { unsigned int index; num_exts_i = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts_i); if (num_exts_i > 0) { exts_i = (char **)malloc((size_t)num_exts_i * (sizeof *exts_i)); } if (exts_i == NULL) { return 0; } for(index = 0; index < (unsigned)num_exts_i; index++) { const char *gl_str_tmp = (const char*)glGetStringi(GL_EXTENSIONS, index); size_t len = strlen(gl_str_tmp); char *local_str = (char*)malloc((len+1) * sizeof(char)); if(local_str != NULL) { memcpy(local_str, gl_str_tmp, (len+1) * sizeof(char)); } exts_i[index] = local_str; } } #endif return 1; } static void free_exts(void) { if (exts_i != NULL) { int index; for(index = 0; index < num_exts_i; index++) { free((char *)exts_i[index]); } free((void *)exts_i); exts_i = NULL; } } static int has_ext(const char *ext) { #ifdef _GLAD_IS_SOME_NEW_VERSION if(max_loaded_major < 3) { #endif const char *extensions; const char *loc; const char *terminator; extensions = exts; if(extensions == NULL || ext == NULL) { return 0; } while(1) { loc = strstr(extensions, ext); if(loc == NULL) { return 0; } terminator = loc + strlen(ext); if((loc == extensions || *(loc - 1) == ' ') && (*terminator == ' ' || *terminator == '\0')) { return 1; } extensions = terminator; } #ifdef _GLAD_IS_SOME_NEW_VERSION } else { int index; if(exts_i == NULL) return 0; for(index = 0; index < num_exts_i; index++) { const char *e = exts_i[index]; if(exts_i[index] != NULL && strcmp(e, ext) == 0) { return 1; } } } #endif return 0; } int GLAD_GL_VERSION_1_0 = 0; int GLAD_GL_VERSION_1_1 = 0; int GLAD_GL_VERSION_1_2 = 0; int GLAD_GL_VERSION_1_3 = 0; int GLAD_GL_VERSION_1_4 = 0; int GLAD_GL_VERSION_1_5 = 0; int GLAD_GL_VERSION_2_0 = 0; int GLAD_GL_VERSION_2_1 = 0; int GLAD_GL_VERSION_3_0 = 0; int GLAD_GL_VERSION_3_1 = 0; int GLAD_GL_VERSION_3_2 = 0; int GLAD_GL_VERSION_3_3 = 0; int GLAD_GL_VERSION_4_0 = 0; int GLAD_GL_VERSION_4_1 = 0; int GLAD_GL_VERSION_4_2 = 0; int GLAD_GL_VERSION_4_3 = 0; int GLAD_GL_VERSION_4_4 = 0; int GLAD_GL_VERSION_4_5 = 0; int GLAD_GL_VERSION_4_6 = 0; PFNGLACCUMPROC glad_glAccum = NULL; PFNGLACTIVESHADERPROGRAMPROC glad_glActiveShaderProgram = NULL; PFNGLACTIVETEXTUREPROC glad_glActiveTexture = NULL; PFNGLALPHAFUNCPROC glad_glAlphaFunc = NULL; PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident = NULL; PFNGLARRAYELEMENTPROC glad_glArrayElement = NULL; PFNGLATTACHSHADERPROC glad_glAttachShader = NULL; PFNGLBEGINPROC glad_glBegin = NULL; PFNGLBEGINCONDITIONALRENDERPROC glad_glBeginConditionalRender = NULL; PFNGLBEGINQUERYPROC glad_glBeginQuery = NULL; PFNGLBEGINQUERYINDEXEDPROC glad_glBeginQueryIndexed = NULL; PFNGLBEGINTRANSFORMFEEDBACKPROC glad_glBeginTransformFeedback = NULL; PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation = NULL; PFNGLBINDBUFFERPROC glad_glBindBuffer = NULL; PFNGLBINDBUFFERBASEPROC glad_glBindBufferBase = NULL; PFNGLBINDBUFFERRANGEPROC glad_glBindBufferRange = NULL; PFNGLBINDBUFFERSBASEPROC glad_glBindBuffersBase = NULL; PFNGLBINDBUFFERSRANGEPROC glad_glBindBuffersRange = NULL; PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation = NULL; PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glad_glBindFragDataLocationIndexed = NULL; PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer = NULL; PFNGLBINDIMAGETEXTUREPROC glad_glBindImageTexture = NULL; PFNGLBINDIMAGETEXTURESPROC glad_glBindImageTextures = NULL; PFNGLBINDPROGRAMPIPELINEPROC glad_glBindProgramPipeline = NULL; PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer = NULL; PFNGLBINDSAMPLERPROC glad_glBindSampler = NULL; PFNGLBINDSAMPLERSPROC glad_glBindSamplers = NULL; PFNGLBINDTEXTUREPROC glad_glBindTexture = NULL; PFNGLBINDTEXTUREUNITPROC glad_glBindTextureUnit = NULL; PFNGLBINDTEXTURESPROC glad_glBindTextures = NULL; PFNGLBINDTRANSFORMFEEDBACKPROC glad_glBindTransformFeedback = NULL; PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray = NULL; PFNGLBINDVERTEXBUFFERPROC glad_glBindVertexBuffer = NULL; PFNGLBINDVERTEXBUFFERSPROC glad_glBindVertexBuffers = NULL; PFNGLBITMAPPROC glad_glBitmap = NULL; PFNGLBLENDCOLORPROC glad_glBlendColor = NULL; PFNGLBLENDEQUATIONPROC glad_glBlendEquation = NULL; PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate = NULL; PFNGLBLENDEQUATIONSEPARATEIPROC glad_glBlendEquationSeparatei = NULL; PFNGLBLENDEQUATIONIPROC glad_glBlendEquationi = NULL; PFNGLBLENDFUNCPROC glad_glBlendFunc = NULL; PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate = NULL; PFNGLBLENDFUNCSEPARATEIPROC glad_glBlendFuncSeparatei = NULL; PFNGLBLENDFUNCIPROC glad_glBlendFunci = NULL; PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer = NULL; PFNGLBLITNAMEDFRAMEBUFFERPROC glad_glBlitNamedFramebuffer = NULL; PFNGLBUFFERDATAPROC glad_glBufferData = NULL; PFNGLBUFFERSTORAGEPROC glad_glBufferStorage = NULL; PFNGLBUFFERSUBDATAPROC glad_glBufferSubData = NULL; PFNGLCALLLISTPROC glad_glCallList = NULL; PFNGLCALLLISTSPROC glad_glCallLists = NULL; PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus = NULL; PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC glad_glCheckNamedFramebufferStatus = NULL; PFNGLCLAMPCOLORPROC glad_glClampColor = NULL; PFNGLCLEARPROC glad_glClear = NULL; PFNGLCLEARACCUMPROC glad_glClearAccum = NULL; PFNGLCLEARBUFFERDATAPROC glad_glClearBufferData = NULL; PFNGLCLEARBUFFERSUBDATAPROC glad_glClearBufferSubData = NULL; PFNGLCLEARBUFFERFIPROC glad_glClearBufferfi = NULL; PFNGLCLEARBUFFERFVPROC glad_glClearBufferfv = NULL; PFNGLCLEARBUFFERIVPROC glad_glClearBufferiv = NULL; PFNGLCLEARBUFFERUIVPROC glad_glClearBufferuiv = NULL; PFNGLCLEARCOLORPROC glad_glClearColor = NULL; PFNGLCLEARDEPTHPROC glad_glClearDepth = NULL; PFNGLCLEARDEPTHFPROC glad_glClearDepthf = NULL; PFNGLCLEARINDEXPROC glad_glClearIndex = NULL; PFNGLCLEARNAMEDBUFFERDATAPROC glad_glClearNamedBufferData = NULL; PFNGLCLEARNAMEDBUFFERSUBDATAPROC glad_glClearNamedBufferSubData = NULL; PFNGLCLEARNAMEDFRAMEBUFFERFIPROC glad_glClearNamedFramebufferfi = NULL; PFNGLCLEARNAMEDFRAMEBUFFERFVPROC glad_glClearNamedFramebufferfv = NULL; PFNGLCLEARNAMEDFRAMEBUFFERIVPROC glad_glClearNamedFramebufferiv = NULL; PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC glad_glClearNamedFramebufferuiv = NULL; PFNGLCLEARSTENCILPROC glad_glClearStencil = NULL; PFNGLCLEARTEXIMAGEPROC glad_glClearTexImage = NULL; PFNGLCLEARTEXSUBIMAGEPROC glad_glClearTexSubImage = NULL; PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture = NULL; PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync = NULL; PFNGLCLIPCONTROLPROC glad_glClipControl = NULL; PFNGLCLIPPLANEPROC glad_glClipPlane = NULL; PFNGLCOLOR3BPROC glad_glColor3b = NULL; PFNGLCOLOR3BVPROC glad_glColor3bv = NULL; PFNGLCOLOR3DPROC glad_glColor3d = NULL; PFNGLCOLOR3DVPROC glad_glColor3dv = NULL; PFNGLCOLOR3FPROC glad_glColor3f = NULL; PFNGLCOLOR3FVPROC glad_glColor3fv = NULL; PFNGLCOLOR3IPROC glad_glColor3i = NULL; PFNGLCOLOR3IVPROC glad_glColor3iv = NULL; PFNGLCOLOR3SPROC glad_glColor3s = NULL; PFNGLCOLOR3SVPROC glad_glColor3sv = NULL; PFNGLCOLOR3UBPROC glad_glColor3ub = NULL; PFNGLCOLOR3UBVPROC glad_glColor3ubv = NULL; PFNGLCOLOR3UIPROC glad_glColor3ui = NULL; PFNGLCOLOR3UIVPROC glad_glColor3uiv = NULL; PFNGLCOLOR3USPROC glad_glColor3us = NULL; PFNGLCOLOR3USVPROC glad_glColor3usv = NULL; PFNGLCOLOR4BPROC glad_glColor4b = NULL; PFNGLCOLOR4BVPROC glad_glColor4bv = NULL; PFNGLCOLOR4DPROC glad_glColor4d = NULL; PFNGLCOLOR4DVPROC glad_glColor4dv = NULL; PFNGLCOLOR4FPROC glad_glColor4f = NULL; PFNGLCOLOR4FVPROC glad_glColor4fv = NULL; PFNGLCOLOR4IPROC glad_glColor4i = NULL; PFNGLCOLOR4IVPROC glad_glColor4iv = NULL; PFNGLCOLOR4SPROC glad_glColor4s = NULL; PFNGLCOLOR4SVPROC glad_glColor4sv = NULL; PFNGLCOLOR4UBPROC glad_glColor4ub = NULL; PFNGLCOLOR4UBVPROC glad_glColor4ubv = NULL; PFNGLCOLOR4UIPROC glad_glColor4ui = NULL; PFNGLCOLOR4UIVPROC glad_glColor4uiv = NULL; PFNGLCOLOR4USPROC glad_glColor4us = NULL; PFNGLCOLOR4USVPROC glad_glColor4usv = NULL; PFNGLCOLORMASKPROC glad_glColorMask = NULL; PFNGLCOLORMASKIPROC glad_glColorMaski = NULL; PFNGLCOLORMATERIALPROC glad_glColorMaterial = NULL; PFNGLCOLORP3UIPROC glad_glColorP3ui = NULL; PFNGLCOLORP3UIVPROC glad_glColorP3uiv = NULL; PFNGLCOLORP4UIPROC glad_glColorP4ui = NULL; PFNGLCOLORP4UIVPROC glad_glColorP4uiv = NULL; PFNGLCOLORPOINTERPROC glad_glColorPointer = NULL; PFNGLCOMPILESHADERPROC glad_glCompileShader = NULL; PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D = NULL; PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D = NULL; PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D = NULL; PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D = NULL; PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D = NULL; PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D = NULL; PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC glad_glCompressedTextureSubImage1D = NULL; PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC glad_glCompressedTextureSubImage2D = NULL; PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC glad_glCompressedTextureSubImage3D = NULL; PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData = NULL; PFNGLCOPYIMAGESUBDATAPROC glad_glCopyImageSubData = NULL; PFNGLCOPYNAMEDBUFFERSUBDATAPROC glad_glCopyNamedBufferSubData = NULL; PFNGLCOPYPIXELSPROC glad_glCopyPixels = NULL; PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D = NULL; PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D = NULL; PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D = NULL; PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D = NULL; PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D = NULL; PFNGLCOPYTEXTURESUBIMAGE1DPROC glad_glCopyTextureSubImage1D = NULL; PFNGLCOPYTEXTURESUBIMAGE2DPROC glad_glCopyTextureSubImage2D = NULL; PFNGLCOPYTEXTURESUBIMAGE3DPROC glad_glCopyTextureSubImage3D = NULL; PFNGLCREATEBUFFERSPROC glad_glCreateBuffers = NULL; PFNGLCREATEFRAMEBUFFERSPROC glad_glCreateFramebuffers = NULL; PFNGLCREATEPROGRAMPROC glad_glCreateProgram = NULL; PFNGLCREATEPROGRAMPIPELINESPROC glad_glCreateProgramPipelines = NULL; PFNGLCREATEQUERIESPROC glad_glCreateQueries = NULL; PFNGLCREATERENDERBUFFERSPROC glad_glCreateRenderbuffers = NULL; PFNGLCREATESAMPLERSPROC glad_glCreateSamplers = NULL; PFNGLCREATESHADERPROC glad_glCreateShader = NULL; PFNGLCREATESHADERPROGRAMVPROC glad_glCreateShaderProgramv = NULL; PFNGLCREATETEXTURESPROC glad_glCreateTextures = NULL; PFNGLCREATETRANSFORMFEEDBACKSPROC glad_glCreateTransformFeedbacks = NULL; PFNGLCREATEVERTEXARRAYSPROC glad_glCreateVertexArrays = NULL; PFNGLCULLFACEPROC glad_glCullFace = NULL; PFNGLDEBUGMESSAGECALLBACKPROC glad_glDebugMessageCallback = NULL; PFNGLDEBUGMESSAGECONTROLPROC glad_glDebugMessageControl = NULL; PFNGLDEBUGMESSAGEINSERTPROC glad_glDebugMessageInsert = NULL; PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers = NULL; PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers = NULL; PFNGLDELETELISTSPROC glad_glDeleteLists = NULL; PFNGLDELETEPROGRAMPROC glad_glDeleteProgram = NULL; PFNGLDELETEPROGRAMPIPELINESPROC glad_glDeleteProgramPipelines = NULL; PFNGLDELETEQUERIESPROC glad_glDeleteQueries = NULL; PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers = NULL; PFNGLDELETESAMPLERSPROC glad_glDeleteSamplers = NULL; PFNGLDELETESHADERPROC glad_glDeleteShader = NULL; PFNGLDELETESYNCPROC glad_glDeleteSync = NULL; PFNGLDELETETEXTURESPROC glad_glDeleteTextures = NULL; PFNGLDELETETRANSFORMFEEDBACKSPROC glad_glDeleteTransformFeedbacks = NULL; PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays = NULL; PFNGLDEPTHFUNCPROC glad_glDepthFunc = NULL; PFNGLDEPTHMASKPROC glad_glDepthMask = NULL; PFNGLDEPTHRANGEPROC glad_glDepthRange = NULL; PFNGLDEPTHRANGEARRAYVPROC glad_glDepthRangeArrayv = NULL; PFNGLDEPTHRANGEINDEXEDPROC glad_glDepthRangeIndexed = NULL; PFNGLDEPTHRANGEFPROC glad_glDepthRangef = NULL; PFNGLDETACHSHADERPROC glad_glDetachShader = NULL; PFNGLDISABLEPROC glad_glDisable = NULL; PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState = NULL; PFNGLDISABLEVERTEXARRAYATTRIBPROC glad_glDisableVertexArrayAttrib = NULL; PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray = NULL; PFNGLDISABLEIPROC glad_glDisablei = NULL; PFNGLDISPATCHCOMPUTEPROC glad_glDispatchCompute = NULL; PFNGLDISPATCHCOMPUTEINDIRECTPROC glad_glDispatchComputeIndirect = NULL; PFNGLDRAWARRAYSPROC glad_glDrawArrays = NULL; PFNGLDRAWARRAYSINDIRECTPROC glad_glDrawArraysIndirect = NULL; PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced = NULL; PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC glad_glDrawArraysInstancedBaseInstance = NULL; PFNGLDRAWBUFFERPROC glad_glDrawBuffer = NULL; PFNGLDRAWBUFFERSPROC glad_glDrawBuffers = NULL; PFNGLDRAWELEMENTSPROC glad_glDrawElements = NULL; PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex = NULL; PFNGLDRAWELEMENTSINDIRECTPROC glad_glDrawElementsIndirect = NULL; PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced = NULL; PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC glad_glDrawElementsInstancedBaseInstance = NULL; PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex = NULL; PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC glad_glDrawElementsInstancedBaseVertexBaseInstance = NULL; PFNGLDRAWPIXELSPROC glad_glDrawPixels = NULL; PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements = NULL; PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex = NULL; PFNGLDRAWTRANSFORMFEEDBACKPROC glad_glDrawTransformFeedback = NULL; PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC glad_glDrawTransformFeedbackInstanced = NULL; PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC glad_glDrawTransformFeedbackStream = NULL; PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC glad_glDrawTransformFeedbackStreamInstanced = NULL; PFNGLEDGEFLAGPROC glad_glEdgeFlag = NULL; PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer = NULL; PFNGLEDGEFLAGVPROC glad_glEdgeFlagv = NULL; PFNGLENABLEPROC glad_glEnable = NULL; PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState = NULL; PFNGLENABLEVERTEXARRAYATTRIBPROC glad_glEnableVertexArrayAttrib = NULL; PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray = NULL; PFNGLENABLEIPROC glad_glEnablei = NULL; PFNGLENDPROC glad_glEnd = NULL; PFNGLENDCONDITIONALRENDERPROC glad_glEndConditionalRender = NULL; PFNGLENDLISTPROC glad_glEndList = NULL; PFNGLENDQUERYPROC glad_glEndQuery = NULL; PFNGLENDQUERYINDEXEDPROC glad_glEndQueryIndexed = NULL; PFNGLENDTRANSFORMFEEDBACKPROC glad_glEndTransformFeedback = NULL; PFNGLEVALCOORD1DPROC glad_glEvalCoord1d = NULL; PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv = NULL; PFNGLEVALCOORD1FPROC glad_glEvalCoord1f = NULL; PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv = NULL; PFNGLEVALCOORD2DPROC glad_glEvalCoord2d = NULL; PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv = NULL; PFNGLEVALCOORD2FPROC glad_glEvalCoord2f = NULL; PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv = NULL; PFNGLEVALMESH1PROC glad_glEvalMesh1 = NULL; PFNGLEVALMESH2PROC glad_glEvalMesh2 = NULL; PFNGLEVALPOINT1PROC glad_glEvalPoint1 = NULL; PFNGLEVALPOINT2PROC glad_glEvalPoint2 = NULL; PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer = NULL; PFNGLFENCESYNCPROC glad_glFenceSync = NULL; PFNGLFINISHPROC glad_glFinish = NULL; PFNGLFLUSHPROC glad_glFlush = NULL; PFNGLFLUSHMAPPEDBUFFERRANGEPROC glad_glFlushMappedBufferRange = NULL; PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC glad_glFlushMappedNamedBufferRange = NULL; PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer = NULL; PFNGLFOGCOORDDPROC glad_glFogCoordd = NULL; PFNGLFOGCOORDDVPROC glad_glFogCoorddv = NULL; PFNGLFOGCOORDFPROC glad_glFogCoordf = NULL; PFNGLFOGCOORDFVPROC glad_glFogCoordfv = NULL; PFNGLFOGFPROC glad_glFogf = NULL; PFNGLFOGFVPROC glad_glFogfv = NULL; PFNGLFOGIPROC glad_glFogi = NULL; PFNGLFOGIVPROC glad_glFogiv = NULL; PFNGLFRAMEBUFFERPARAMETERIPROC glad_glFramebufferParameteri = NULL; PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer = NULL; PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture = NULL; PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D = NULL; PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D = NULL; PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D = NULL; PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer = NULL; PFNGLFRONTFACEPROC glad_glFrontFace = NULL; PFNGLFRUSTUMPROC glad_glFrustum = NULL; PFNGLGENBUFFERSPROC glad_glGenBuffers = NULL; PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers = NULL; PFNGLGENLISTSPROC glad_glGenLists = NULL; PFNGLGENPROGRAMPIPELINESPROC glad_glGenProgramPipelines = NULL; PFNGLGENQUERIESPROC glad_glGenQueries = NULL; PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers = NULL; PFNGLGENSAMPLERSPROC glad_glGenSamplers = NULL; PFNGLGENTEXTURESPROC glad_glGenTextures = NULL; PFNGLGENTRANSFORMFEEDBACKSPROC glad_glGenTransformFeedbacks = NULL; PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays = NULL; PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap = NULL; PFNGLGENERATETEXTUREMIPMAPPROC glad_glGenerateTextureMipmap = NULL; PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC glad_glGetActiveAtomicCounterBufferiv = NULL; PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib = NULL; PFNGLGETACTIVESUBROUTINENAMEPROC glad_glGetActiveSubroutineName = NULL; PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC glad_glGetActiveSubroutineUniformName = NULL; PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC glad_glGetActiveSubroutineUniformiv = NULL; PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform = NULL; PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName = NULL; PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv = NULL; PFNGLGETACTIVEUNIFORMNAMEPROC glad_glGetActiveUniformName = NULL; PFNGLGETACTIVEUNIFORMSIVPROC glad_glGetActiveUniformsiv = NULL; PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders = NULL; PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation = NULL; PFNGLGETBOOLEANI_VPROC glad_glGetBooleani_v = NULL; PFNGLGETBOOLEANVPROC glad_glGetBooleanv = NULL; PFNGLGETBUFFERPARAMETERI64VPROC glad_glGetBufferParameteri64v = NULL; PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv = NULL; PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv = NULL; PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData = NULL; PFNGLGETCLIPPLANEPROC glad_glGetClipPlane = NULL; PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage = NULL; PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC glad_glGetCompressedTextureImage = NULL; PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC glad_glGetCompressedTextureSubImage = NULL; PFNGLGETDEBUGMESSAGELOGPROC glad_glGetDebugMessageLog = NULL; PFNGLGETDOUBLEI_VPROC glad_glGetDoublei_v = NULL; PFNGLGETDOUBLEVPROC glad_glGetDoublev = NULL; PFNGLGETERRORPROC glad_glGetError = NULL; PFNGLGETFLOATI_VPROC glad_glGetFloati_v = NULL; PFNGLGETFLOATVPROC glad_glGetFloatv = NULL; PFNGLGETFRAGDATAINDEXPROC glad_glGetFragDataIndex = NULL; PFNGLGETFRAGDATALOCATIONPROC glad_glGetFragDataLocation = NULL; PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv = NULL; PFNGLGETFRAMEBUFFERPARAMETERIVPROC glad_glGetFramebufferParameteriv = NULL; PFNGLGETGRAPHICSRESETSTATUSPROC glad_glGetGraphicsResetStatus = NULL; PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v = NULL; PFNGLGETINTEGER64VPROC glad_glGetInteger64v = NULL; PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v = NULL; PFNGLGETINTEGERVPROC glad_glGetIntegerv = NULL; PFNGLGETINTERNALFORMATI64VPROC glad_glGetInternalformati64v = NULL; PFNGLGETINTERNALFORMATIVPROC glad_glGetInternalformativ = NULL; PFNGLGETLIGHTFVPROC glad_glGetLightfv = NULL; PFNGLGETLIGHTIVPROC glad_glGetLightiv = NULL; PFNGLGETMAPDVPROC glad_glGetMapdv = NULL; PFNGLGETMAPFVPROC glad_glGetMapfv = NULL; PFNGLGETMAPIVPROC glad_glGetMapiv = NULL; PFNGLGETMATERIALFVPROC glad_glGetMaterialfv = NULL; PFNGLGETMATERIALIVPROC glad_glGetMaterialiv = NULL; PFNGLGETMULTISAMPLEFVPROC glad_glGetMultisamplefv = NULL; PFNGLGETNAMEDBUFFERPARAMETERI64VPROC glad_glGetNamedBufferParameteri64v = NULL; PFNGLGETNAMEDBUFFERPARAMETERIVPROC glad_glGetNamedBufferParameteriv = NULL; PFNGLGETNAMEDBUFFERPOINTERVPROC glad_glGetNamedBufferPointerv = NULL; PFNGLGETNAMEDBUFFERSUBDATAPROC glad_glGetNamedBufferSubData = NULL; PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetNamedFramebufferAttachmentParameteriv = NULL; PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC glad_glGetNamedFramebufferParameteriv = NULL; PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC glad_glGetNamedRenderbufferParameteriv = NULL; PFNGLGETOBJECTLABELPROC glad_glGetObjectLabel = NULL; PFNGLGETOBJECTPTRLABELPROC glad_glGetObjectPtrLabel = NULL; PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv = NULL; PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv = NULL; PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv = NULL; PFNGLGETPOINTERVPROC glad_glGetPointerv = NULL; PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple = NULL; PFNGLGETPROGRAMBINARYPROC glad_glGetProgramBinary = NULL; PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog = NULL; PFNGLGETPROGRAMINTERFACEIVPROC glad_glGetProgramInterfaceiv = NULL; PFNGLGETPROGRAMPIPELINEINFOLOGPROC glad_glGetProgramPipelineInfoLog = NULL; PFNGLGETPROGRAMPIPELINEIVPROC glad_glGetProgramPipelineiv = NULL; PFNGLGETPROGRAMRESOURCEINDEXPROC glad_glGetProgramResourceIndex = NULL; PFNGLGETPROGRAMRESOURCELOCATIONPROC glad_glGetProgramResourceLocation = NULL; PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC glad_glGetProgramResourceLocationIndex = NULL; PFNGLGETPROGRAMRESOURCENAMEPROC glad_glGetProgramResourceName = NULL; PFNGLGETPROGRAMRESOURCEIVPROC glad_glGetProgramResourceiv = NULL; PFNGLGETPROGRAMSTAGEIVPROC glad_glGetProgramStageiv = NULL; PFNGLGETPROGRAMIVPROC glad_glGetProgramiv = NULL; PFNGLGETQUERYBUFFEROBJECTI64VPROC glad_glGetQueryBufferObjecti64v = NULL; PFNGLGETQUERYBUFFEROBJECTIVPROC glad_glGetQueryBufferObjectiv = NULL; PFNGLGETQUERYBUFFEROBJECTUI64VPROC glad_glGetQueryBufferObjectui64v = NULL; PFNGLGETQUERYBUFFEROBJECTUIVPROC glad_glGetQueryBufferObjectuiv = NULL; PFNGLGETQUERYINDEXEDIVPROC glad_glGetQueryIndexediv = NULL; PFNGLGETQUERYOBJECTI64VPROC glad_glGetQueryObjecti64v = NULL; PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv = NULL; PFNGLGETQUERYOBJECTUI64VPROC glad_glGetQueryObjectui64v = NULL; PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv = NULL; PFNGLGETQUERYIVPROC glad_glGetQueryiv = NULL; PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv = NULL; PFNGLGETSAMPLERPARAMETERIIVPROC glad_glGetSamplerParameterIiv = NULL; PFNGLGETSAMPLERPARAMETERIUIVPROC glad_glGetSamplerParameterIuiv = NULL; PFNGLGETSAMPLERPARAMETERFVPROC glad_glGetSamplerParameterfv = NULL; PFNGLGETSAMPLERPARAMETERIVPROC glad_glGetSamplerParameteriv = NULL; PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog = NULL; PFNGLGETSHADERPRECISIONFORMATPROC glad_glGetShaderPrecisionFormat = NULL; PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource = NULL; PFNGLGETSHADERIVPROC glad_glGetShaderiv = NULL; PFNGLGETSTRINGPROC glad_glGetString = NULL; PFNGLGETSTRINGIPROC glad_glGetStringi = NULL; PFNGLGETSUBROUTINEINDEXPROC glad_glGetSubroutineIndex = NULL; PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC glad_glGetSubroutineUniformLocation = NULL; PFNGLGETSYNCIVPROC glad_glGetSynciv = NULL; PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv = NULL; PFNGLGETTEXENVIVPROC glad_glGetTexEnviv = NULL; PFNGLGETTEXGENDVPROC glad_glGetTexGendv = NULL; PFNGLGETTEXGENFVPROC glad_glGetTexGenfv = NULL; PFNGLGETTEXGENIVPROC glad_glGetTexGeniv = NULL; PFNGLGETTEXIMAGEPROC glad_glGetTexImage = NULL; PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv = NULL; PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv = NULL; PFNGLGETTEXPARAMETERIIVPROC glad_glGetTexParameterIiv = NULL; PFNGLGETTEXPARAMETERIUIVPROC glad_glGetTexParameterIuiv = NULL; PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv = NULL; PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv = NULL; PFNGLGETTEXTUREIMAGEPROC glad_glGetTextureImage = NULL; PFNGLGETTEXTURELEVELPARAMETERFVPROC glad_glGetTextureLevelParameterfv = NULL; PFNGLGETTEXTURELEVELPARAMETERIVPROC glad_glGetTextureLevelParameteriv = NULL; PFNGLGETTEXTUREPARAMETERIIVPROC glad_glGetTextureParameterIiv = NULL; PFNGLGETTEXTUREPARAMETERIUIVPROC glad_glGetTextureParameterIuiv = NULL; PFNGLGETTEXTUREPARAMETERFVPROC glad_glGetTextureParameterfv = NULL; PFNGLGETTEXTUREPARAMETERIVPROC glad_glGetTextureParameteriv = NULL; PFNGLGETTEXTURESUBIMAGEPROC glad_glGetTextureSubImage = NULL; PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying = NULL; PFNGLGETTRANSFORMFEEDBACKI64_VPROC glad_glGetTransformFeedbacki64_v = NULL; PFNGLGETTRANSFORMFEEDBACKI_VPROC glad_glGetTransformFeedbacki_v = NULL; PFNGLGETTRANSFORMFEEDBACKIVPROC glad_glGetTransformFeedbackiv = NULL; PFNGLGETUNIFORMBLOCKINDEXPROC glad_glGetUniformBlockIndex = NULL; PFNGLGETUNIFORMINDICESPROC glad_glGetUniformIndices = NULL; PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation = NULL; PFNGLGETUNIFORMSUBROUTINEUIVPROC glad_glGetUniformSubroutineuiv = NULL; PFNGLGETUNIFORMDVPROC glad_glGetUniformdv = NULL; PFNGLGETUNIFORMFVPROC glad_glGetUniformfv = NULL; PFNGLGETUNIFORMIVPROC glad_glGetUniformiv = NULL; PFNGLGETUNIFORMUIVPROC glad_glGetUniformuiv = NULL; PFNGLGETVERTEXARRAYINDEXED64IVPROC glad_glGetVertexArrayIndexed64iv = NULL; PFNGLGETVERTEXARRAYINDEXEDIVPROC glad_glGetVertexArrayIndexediv = NULL; PFNGLGETVERTEXARRAYIVPROC glad_glGetVertexArrayiv = NULL; PFNGLGETVERTEXATTRIBIIVPROC glad_glGetVertexAttribIiv = NULL; PFNGLGETVERTEXATTRIBIUIVPROC glad_glGetVertexAttribIuiv = NULL; PFNGLGETVERTEXATTRIBLDVPROC glad_glGetVertexAttribLdv = NULL; PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv = NULL; PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv = NULL; PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv = NULL; PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv = NULL; PFNGLGETNCOLORTABLEPROC glad_glGetnColorTable = NULL; PFNGLGETNCOMPRESSEDTEXIMAGEPROC glad_glGetnCompressedTexImage = NULL; PFNGLGETNCONVOLUTIONFILTERPROC glad_glGetnConvolutionFilter = NULL; PFNGLGETNHISTOGRAMPROC glad_glGetnHistogram = NULL; PFNGLGETNMAPDVPROC glad_glGetnMapdv = NULL; PFNGLGETNMAPFVPROC glad_glGetnMapfv = NULL; PFNGLGETNMAPIVPROC glad_glGetnMapiv = NULL; PFNGLGETNMINMAXPROC glad_glGetnMinmax = NULL; PFNGLGETNPIXELMAPFVPROC glad_glGetnPixelMapfv = NULL; PFNGLGETNPIXELMAPUIVPROC glad_glGetnPixelMapuiv = NULL; PFNGLGETNPIXELMAPUSVPROC glad_glGetnPixelMapusv = NULL; PFNGLGETNPOLYGONSTIPPLEPROC glad_glGetnPolygonStipple = NULL; PFNGLGETNSEPARABLEFILTERPROC glad_glGetnSeparableFilter = NULL; PFNGLGETNTEXIMAGEPROC glad_glGetnTexImage = NULL; PFNGLGETNUNIFORMDVPROC glad_glGetnUniformdv = NULL; PFNGLGETNUNIFORMFVPROC glad_glGetnUniformfv = NULL; PFNGLGETNUNIFORMIVPROC glad_glGetnUniformiv = NULL; PFNGLGETNUNIFORMUIVPROC glad_glGetnUniformuiv = NULL; PFNGLHINTPROC glad_glHint = NULL; PFNGLINDEXMASKPROC glad_glIndexMask = NULL; PFNGLINDEXPOINTERPROC glad_glIndexPointer = NULL; PFNGLINDEXDPROC glad_glIndexd = NULL; PFNGLINDEXDVPROC glad_glIndexdv = NULL; PFNGLINDEXFPROC glad_glIndexf = NULL; PFNGLINDEXFVPROC glad_glIndexfv = NULL; PFNGLINDEXIPROC glad_glIndexi = NULL; PFNGLINDEXIVPROC glad_glIndexiv = NULL; PFNGLINDEXSPROC glad_glIndexs = NULL; PFNGLINDEXSVPROC glad_glIndexsv = NULL; PFNGLINDEXUBPROC glad_glIndexub = NULL; PFNGLINDEXUBVPROC glad_glIndexubv = NULL; PFNGLINITNAMESPROC glad_glInitNames = NULL; PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays = NULL; PFNGLINVALIDATEBUFFERDATAPROC glad_glInvalidateBufferData = NULL; PFNGLINVALIDATEBUFFERSUBDATAPROC glad_glInvalidateBufferSubData = NULL; PFNGLINVALIDATEFRAMEBUFFERPROC glad_glInvalidateFramebuffer = NULL; PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC glad_glInvalidateNamedFramebufferData = NULL; PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC glad_glInvalidateNamedFramebufferSubData = NULL; PFNGLINVALIDATESUBFRAMEBUFFERPROC glad_glInvalidateSubFramebuffer = NULL; PFNGLINVALIDATETEXIMAGEPROC glad_glInvalidateTexImage = NULL; PFNGLINVALIDATETEXSUBIMAGEPROC glad_glInvalidateTexSubImage = NULL; PFNGLISBUFFERPROC glad_glIsBuffer = NULL; PFNGLISENABLEDPROC glad_glIsEnabled = NULL; PFNGLISENABLEDIPROC glad_glIsEnabledi = NULL; PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer = NULL; PFNGLISLISTPROC glad_glIsList = NULL; PFNGLISPROGRAMPROC glad_glIsProgram = NULL; PFNGLISPROGRAMPIPELINEPROC glad_glIsProgramPipeline = NULL; PFNGLISQUERYPROC glad_glIsQuery = NULL; PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer = NULL; PFNGLISSAMPLERPROC glad_glIsSampler = NULL; PFNGLISSHADERPROC glad_glIsShader = NULL; PFNGLISSYNCPROC glad_glIsSync = NULL; PFNGLISTEXTUREPROC glad_glIsTexture = NULL; PFNGLISTRANSFORMFEEDBACKPROC glad_glIsTransformFeedback = NULL; PFNGLISVERTEXARRAYPROC glad_glIsVertexArray = NULL; PFNGLLIGHTMODELFPROC glad_glLightModelf = NULL; PFNGLLIGHTMODELFVPROC glad_glLightModelfv = NULL; PFNGLLIGHTMODELIPROC glad_glLightModeli = NULL; PFNGLLIGHTMODELIVPROC glad_glLightModeliv = NULL; PFNGLLIGHTFPROC glad_glLightf = NULL; PFNGLLIGHTFVPROC glad_glLightfv = NULL; PFNGLLIGHTIPROC glad_glLighti = NULL; PFNGLLIGHTIVPROC glad_glLightiv = NULL; PFNGLLINESTIPPLEPROC glad_glLineStipple = NULL; PFNGLLINEWIDTHPROC glad_glLineWidth = NULL; PFNGLLINKPROGRAMPROC glad_glLinkProgram = NULL; PFNGLLISTBASEPROC glad_glListBase = NULL; PFNGLLOADIDENTITYPROC glad_glLoadIdentity = NULL; PFNGLLOADMATRIXDPROC glad_glLoadMatrixd = NULL; PFNGLLOADMATRIXFPROC glad_glLoadMatrixf = NULL; PFNGLLOADNAMEPROC glad_glLoadName = NULL; PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd = NULL; PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf = NULL; PFNGLLOGICOPPROC glad_glLogicOp = NULL; PFNGLMAP1DPROC glad_glMap1d = NULL; PFNGLMAP1FPROC glad_glMap1f = NULL; PFNGLMAP2DPROC glad_glMap2d = NULL; PFNGLMAP2FPROC glad_glMap2f = NULL; PFNGLMAPBUFFERPROC glad_glMapBuffer = NULL; PFNGLMAPBUFFERRANGEPROC glad_glMapBufferRange = NULL; PFNGLMAPGRID1DPROC glad_glMapGrid1d = NULL; PFNGLMAPGRID1FPROC glad_glMapGrid1f = NULL; PFNGLMAPGRID2DPROC glad_glMapGrid2d = NULL; PFNGLMAPGRID2FPROC glad_glMapGrid2f = NULL; PFNGLMAPNAMEDBUFFERPROC glad_glMapNamedBuffer = NULL; PFNGLMAPNAMEDBUFFERRANGEPROC glad_glMapNamedBufferRange = NULL; PFNGLMATERIALFPROC glad_glMaterialf = NULL; PFNGLMATERIALFVPROC glad_glMaterialfv = NULL; PFNGLMATERIALIPROC glad_glMateriali = NULL; PFNGLMATERIALIVPROC glad_glMaterialiv = NULL; PFNGLMATRIXMODEPROC glad_glMatrixMode = NULL; PFNGLMEMORYBARRIERPROC glad_glMemoryBarrier = NULL; PFNGLMEMORYBARRIERBYREGIONPROC glad_glMemoryBarrierByRegion = NULL; PFNGLMINSAMPLESHADINGPROC glad_glMinSampleShading = NULL; PFNGLMULTMATRIXDPROC glad_glMultMatrixd = NULL; PFNGLMULTMATRIXFPROC glad_glMultMatrixf = NULL; PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd = NULL; PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf = NULL; PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays = NULL; PFNGLMULTIDRAWARRAYSINDIRECTPROC glad_glMultiDrawArraysIndirect = NULL; PFNGLMULTIDRAWARRAYSINDIRECTCOUNTPROC glad_glMultiDrawArraysIndirectCount = NULL; PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements = NULL; PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex = NULL; PFNGLMULTIDRAWELEMENTSINDIRECTPROC glad_glMultiDrawElementsIndirect = NULL; PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTPROC glad_glMultiDrawElementsIndirectCount = NULL; PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d = NULL; PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv = NULL; PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f = NULL; PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv = NULL; PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i = NULL; PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv = NULL; PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s = NULL; PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv = NULL; PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d = NULL; PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv = NULL; PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f = NULL; PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv = NULL; PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i = NULL; PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv = NULL; PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s = NULL; PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv = NULL; PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d = NULL; PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv = NULL; PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f = NULL; PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv = NULL; PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i = NULL; PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv = NULL; PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s = NULL; PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv = NULL; PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d = NULL; PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv = NULL; PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f = NULL; PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv = NULL; PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i = NULL; PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv = NULL; PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s = NULL; PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv = NULL; PFNGLMULTITEXCOORDP1UIPROC glad_glMultiTexCoordP1ui = NULL; PFNGLMULTITEXCOORDP1UIVPROC glad_glMultiTexCoordP1uiv = NULL; PFNGLMULTITEXCOORDP2UIPROC glad_glMultiTexCoordP2ui = NULL; PFNGLMULTITEXCOORDP2UIVPROC glad_glMultiTexCoordP2uiv = NULL; PFNGLMULTITEXCOORDP3UIPROC glad_glMultiTexCoordP3ui = NULL; PFNGLMULTITEXCOORDP3UIVPROC glad_glMultiTexCoordP3uiv = NULL; PFNGLMULTITEXCOORDP4UIPROC glad_glMultiTexCoordP4ui = NULL; PFNGLMULTITEXCOORDP4UIVPROC glad_glMultiTexCoordP4uiv = NULL; PFNGLNAMEDBUFFERDATAPROC glad_glNamedBufferData = NULL; PFNGLNAMEDBUFFERSTORAGEPROC glad_glNamedBufferStorage = NULL; PFNGLNAMEDBUFFERSUBDATAPROC glad_glNamedBufferSubData = NULL; PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC glad_glNamedFramebufferDrawBuffer = NULL; PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC glad_glNamedFramebufferDrawBuffers = NULL; PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC glad_glNamedFramebufferParameteri = NULL; PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC glad_glNamedFramebufferReadBuffer = NULL; PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC glad_glNamedFramebufferRenderbuffer = NULL; PFNGLNAMEDFRAMEBUFFERTEXTUREPROC glad_glNamedFramebufferTexture = NULL; PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC glad_glNamedFramebufferTextureLayer = NULL; PFNGLNAMEDRENDERBUFFERSTORAGEPROC glad_glNamedRenderbufferStorage = NULL; PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glNamedRenderbufferStorageMultisample = NULL; PFNGLNEWLISTPROC glad_glNewList = NULL; PFNGLNORMAL3BPROC glad_glNormal3b = NULL; PFNGLNORMAL3BVPROC glad_glNormal3bv = NULL; PFNGLNORMAL3DPROC glad_glNormal3d = NULL; PFNGLNORMAL3DVPROC glad_glNormal3dv = NULL; PFNGLNORMAL3FPROC glad_glNormal3f = NULL; PFNGLNORMAL3FVPROC glad_glNormal3fv = NULL; PFNGLNORMAL3IPROC glad_glNormal3i = NULL; PFNGLNORMAL3IVPROC glad_glNormal3iv = NULL; PFNGLNORMAL3SPROC glad_glNormal3s = NULL; PFNGLNORMAL3SVPROC glad_glNormal3sv = NULL; PFNGLNORMALP3UIPROC glad_glNormalP3ui = NULL; PFNGLNORMALP3UIVPROC glad_glNormalP3uiv = NULL; PFNGLNORMALPOINTERPROC glad_glNormalPointer = NULL; PFNGLOBJECTLABELPROC glad_glObjectLabel = NULL; PFNGLOBJECTPTRLABELPROC glad_glObjectPtrLabel = NULL; PFNGLORTHOPROC glad_glOrtho = NULL; PFNGLPASSTHROUGHPROC glad_glPassThrough = NULL; PFNGLPATCHPARAMETERFVPROC glad_glPatchParameterfv = NULL; PFNGLPATCHPARAMETERIPROC glad_glPatchParameteri = NULL; PFNGLPAUSETRANSFORMFEEDBACKPROC glad_glPauseTransformFeedback = NULL; PFNGLPIXELMAPFVPROC glad_glPixelMapfv = NULL; PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv = NULL; PFNGLPIXELMAPUSVPROC glad_glPixelMapusv = NULL; PFNGLPIXELSTOREFPROC glad_glPixelStoref = NULL; PFNGLPIXELSTOREIPROC glad_glPixelStorei = NULL; PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf = NULL; PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi = NULL; PFNGLPIXELZOOMPROC glad_glPixelZoom = NULL; PFNGLPOINTPARAMETERFPROC glad_glPointParameterf = NULL; PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv = NULL; PFNGLPOINTPARAMETERIPROC glad_glPointParameteri = NULL; PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv = NULL; PFNGLPOINTSIZEPROC glad_glPointSize = NULL; PFNGLPOLYGONMODEPROC glad_glPolygonMode = NULL; PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset = NULL; PFNGLPOLYGONOFFSETCLAMPPROC glad_glPolygonOffsetClamp = NULL; PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple = NULL; PFNGLPOPATTRIBPROC glad_glPopAttrib = NULL; PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib = NULL; PFNGLPOPDEBUGGROUPPROC glad_glPopDebugGroup = NULL; PFNGLPOPMATRIXPROC glad_glPopMatrix = NULL; PFNGLPOPNAMEPROC glad_glPopName = NULL; PFNGLPRIMITIVERESTARTINDEXPROC glad_glPrimitiveRestartIndex = NULL; PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures = NULL; PFNGLPROGRAMBINARYPROC glad_glProgramBinary = NULL; PFNGLPROGRAMPARAMETERIPROC glad_glProgramParameteri = NULL; PFNGLPROGRAMUNIFORM1DPROC glad_glProgramUniform1d = NULL; PFNGLPROGRAMUNIFORM1DVPROC glad_glProgramUniform1dv = NULL; PFNGLPROGRAMUNIFORM1FPROC glad_glProgramUniform1f = NULL; PFNGLPROGRAMUNIFORM1FVPROC glad_glProgramUniform1fv = NULL; PFNGLPROGRAMUNIFORM1IPROC glad_glProgramUniform1i = NULL; PFNGLPROGRAMUNIFORM1IVPROC glad_glProgramUniform1iv = NULL; PFNGLPROGRAMUNIFORM1UIPROC glad_glProgramUniform1ui = NULL; PFNGLPROGRAMUNIFORM1UIVPROC glad_glProgramUniform1uiv = NULL; PFNGLPROGRAMUNIFORM2DPROC glad_glProgramUniform2d = NULL; PFNGLPROGRAMUNIFORM2DVPROC glad_glProgramUniform2dv = NULL; PFNGLPROGRAMUNIFORM2FPROC glad_glProgramUniform2f = NULL; PFNGLPROGRAMUNIFORM2FVPROC glad_glProgramUniform2fv = NULL; PFNGLPROGRAMUNIFORM2IPROC glad_glProgramUniform2i = NULL; PFNGLPROGRAMUNIFORM2IVPROC glad_glProgramUniform2iv = NULL; PFNGLPROGRAMUNIFORM2UIPROC glad_glProgramUniform2ui = NULL; PFNGLPROGRAMUNIFORM2UIVPROC glad_glProgramUniform2uiv = NULL; PFNGLPROGRAMUNIFORM3DPROC glad_glProgramUniform3d = NULL; PFNGLPROGRAMUNIFORM3DVPROC glad_glProgramUniform3dv = NULL; PFNGLPROGRAMUNIFORM3FPROC glad_glProgramUniform3f = NULL; PFNGLPROGRAMUNIFORM3FVPROC glad_glProgramUniform3fv = NULL; PFNGLPROGRAMUNIFORM3IPROC glad_glProgramUniform3i = NULL; PFNGLPROGRAMUNIFORM3IVPROC glad_glProgramUniform3iv = NULL; PFNGLPROGRAMUNIFORM3UIPROC glad_glProgramUniform3ui = NULL; PFNGLPROGRAMUNIFORM3UIVPROC glad_glProgramUniform3uiv = NULL; PFNGLPROGRAMUNIFORM4DPROC glad_glProgramUniform4d = NULL; PFNGLPROGRAMUNIFORM4DVPROC glad_glProgramUniform4dv = NULL; PFNGLPROGRAMUNIFORM4FPROC glad_glProgramUniform4f = NULL; PFNGLPROGRAMUNIFORM4FVPROC glad_glProgramUniform4fv = NULL; PFNGLPROGRAMUNIFORM4IPROC glad_glProgramUniform4i = NULL; PFNGLPROGRAMUNIFORM4IVPROC glad_glProgramUniform4iv = NULL; PFNGLPROGRAMUNIFORM4UIPROC glad_glProgramUniform4ui = NULL; PFNGLPROGRAMUNIFORM4UIVPROC glad_glProgramUniform4uiv = NULL; PFNGLPROGRAMUNIFORMMATRIX2DVPROC glad_glProgramUniformMatrix2dv = NULL; PFNGLPROGRAMUNIFORMMATRIX2FVPROC glad_glProgramUniformMatrix2fv = NULL; PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC glad_glProgramUniformMatrix2x3dv = NULL; PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC glad_glProgramUniformMatrix2x3fv = NULL; PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC glad_glProgramUniformMatrix2x4dv = NULL; PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC glad_glProgramUniformMatrix2x4fv = NULL; PFNGLPROGRAMUNIFORMMATRIX3DVPROC glad_glProgramUniformMatrix3dv = NULL; PFNGLPROGRAMUNIFORMMATRIX3FVPROC glad_glProgramUniformMatrix3fv = NULL; PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC glad_glProgramUniformMatrix3x2dv = NULL; PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC glad_glProgramUniformMatrix3x2fv = NULL; PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC glad_glProgramUniformMatrix3x4dv = NULL; PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC glad_glProgramUniformMatrix3x4fv = NULL; PFNGLPROGRAMUNIFORMMATRIX4DVPROC glad_glProgramUniformMatrix4dv = NULL; PFNGLPROGRAMUNIFORMMATRIX4FVPROC glad_glProgramUniformMatrix4fv = NULL; PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC glad_glProgramUniformMatrix4x2dv = NULL; PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC glad_glProgramUniformMatrix4x2fv = NULL; PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC glad_glProgramUniformMatrix4x3dv = NULL; PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC glad_glProgramUniformMatrix4x3fv = NULL; PFNGLPROVOKINGVERTEXPROC glad_glProvokingVertex = NULL; PFNGLPUSHATTRIBPROC glad_glPushAttrib = NULL; PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib = NULL; PFNGLPUSHDEBUGGROUPPROC glad_glPushDebugGroup = NULL; PFNGLPUSHMATRIXPROC glad_glPushMatrix = NULL; PFNGLPUSHNAMEPROC glad_glPushName = NULL; PFNGLQUERYCOUNTERPROC glad_glQueryCounter = NULL; PFNGLRASTERPOS2DPROC glad_glRasterPos2d = NULL; PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv = NULL; PFNGLRASTERPOS2FPROC glad_glRasterPos2f = NULL; PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv = NULL; PFNGLRASTERPOS2IPROC glad_glRasterPos2i = NULL; PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv = NULL; PFNGLRASTERPOS2SPROC glad_glRasterPos2s = NULL; PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv = NULL; PFNGLRASTERPOS3DPROC glad_glRasterPos3d = NULL; PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv = NULL; PFNGLRASTERPOS3FPROC glad_glRasterPos3f = NULL; PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv = NULL; PFNGLRASTERPOS3IPROC glad_glRasterPos3i = NULL; PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv = NULL; PFNGLRASTERPOS3SPROC glad_glRasterPos3s = NULL; PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv = NULL; PFNGLRASTERPOS4DPROC glad_glRasterPos4d = NULL; PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv = NULL; PFNGLRASTERPOS4FPROC glad_glRasterPos4f = NULL; PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv = NULL; PFNGLRASTERPOS4IPROC glad_glRasterPos4i = NULL; PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv = NULL; PFNGLRASTERPOS4SPROC glad_glRasterPos4s = NULL; PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv = NULL; PFNGLREADBUFFERPROC glad_glReadBuffer = NULL; PFNGLREADPIXELSPROC glad_glReadPixels = NULL; PFNGLREADNPIXELSPROC glad_glReadnPixels = NULL; PFNGLRECTDPROC glad_glRectd = NULL; PFNGLRECTDVPROC glad_glRectdv = NULL; PFNGLRECTFPROC glad_glRectf = NULL; PFNGLRECTFVPROC glad_glRectfv = NULL; PFNGLRECTIPROC glad_glRecti = NULL; PFNGLRECTIVPROC glad_glRectiv = NULL; PFNGLRECTSPROC glad_glRects = NULL; PFNGLRECTSVPROC glad_glRectsv = NULL; PFNGLRELEASESHADERCOMPILERPROC glad_glReleaseShaderCompiler = NULL; PFNGLRENDERMODEPROC glad_glRenderMode = NULL; PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage = NULL; PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample = NULL; PFNGLRESUMETRANSFORMFEEDBACKPROC glad_glResumeTransformFeedback = NULL; PFNGLROTATEDPROC glad_glRotated = NULL; PFNGLROTATEFPROC glad_glRotatef = NULL; PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage = NULL; PFNGLSAMPLEMASKIPROC glad_glSampleMaski = NULL; PFNGLSAMPLERPARAMETERIIVPROC glad_glSamplerParameterIiv = NULL; PFNGLSAMPLERPARAMETERIUIVPROC glad_glSamplerParameterIuiv = NULL; PFNGLSAMPLERPARAMETERFPROC glad_glSamplerParameterf = NULL; PFNGLSAMPLERPARAMETERFVPROC glad_glSamplerParameterfv = NULL; PFNGLSAMPLERPARAMETERIPROC glad_glSamplerParameteri = NULL; PFNGLSAMPLERPARAMETERIVPROC glad_glSamplerParameteriv = NULL; PFNGLSCALEDPROC glad_glScaled = NULL; PFNGLSCALEFPROC glad_glScalef = NULL; PFNGLSCISSORPROC glad_glScissor = NULL; PFNGLSCISSORARRAYVPROC glad_glScissorArrayv = NULL; PFNGLSCISSORINDEXEDPROC glad_glScissorIndexed = NULL; PFNGLSCISSORINDEXEDVPROC glad_glScissorIndexedv = NULL; PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b = NULL; PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv = NULL; PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d = NULL; PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv = NULL; PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f = NULL; PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv = NULL; PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i = NULL; PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv = NULL; PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s = NULL; PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv = NULL; PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub = NULL; PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv = NULL; PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui = NULL; PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv = NULL; PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us = NULL; PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv = NULL; PFNGLSECONDARYCOLORP3UIPROC glad_glSecondaryColorP3ui = NULL; PFNGLSECONDARYCOLORP3UIVPROC glad_glSecondaryColorP3uiv = NULL; PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer = NULL; PFNGLSELECTBUFFERPROC glad_glSelectBuffer = NULL; PFNGLSHADEMODELPROC glad_glShadeModel = NULL; PFNGLSHADERBINARYPROC glad_glShaderBinary = NULL; PFNGLSHADERSOURCEPROC glad_glShaderSource = NULL; PFNGLSHADERSTORAGEBLOCKBINDINGPROC glad_glShaderStorageBlockBinding = NULL; PFNGLSPECIALIZESHADERPROC glad_glSpecializeShader = NULL; PFNGLSTENCILFUNCPROC glad_glStencilFunc = NULL; PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate = NULL; PFNGLSTENCILMASKPROC glad_glStencilMask = NULL; PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate = NULL; PFNGLSTENCILOPPROC glad_glStencilOp = NULL; PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate = NULL; PFNGLTEXBUFFERPROC glad_glTexBuffer = NULL; PFNGLTEXBUFFERRANGEPROC glad_glTexBufferRange = NULL; PFNGLTEXCOORD1DPROC glad_glTexCoord1d = NULL; PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv = NULL; PFNGLTEXCOORD1FPROC glad_glTexCoord1f = NULL; PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv = NULL; PFNGLTEXCOORD1IPROC glad_glTexCoord1i = NULL; PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv = NULL; PFNGLTEXCOORD1SPROC glad_glTexCoord1s = NULL; PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv = NULL; PFNGLTEXCOORD2DPROC glad_glTexCoord2d = NULL; PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv = NULL; PFNGLTEXCOORD2FPROC glad_glTexCoord2f = NULL; PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv = NULL; PFNGLTEXCOORD2IPROC glad_glTexCoord2i = NULL; PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv = NULL; PFNGLTEXCOORD2SPROC glad_glTexCoord2s = NULL; PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv = NULL; PFNGLTEXCOORD3DPROC glad_glTexCoord3d = NULL; PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv = NULL; PFNGLTEXCOORD3FPROC glad_glTexCoord3f = NULL; PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv = NULL; PFNGLTEXCOORD3IPROC glad_glTexCoord3i = NULL; PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv = NULL; PFNGLTEXCOORD3SPROC glad_glTexCoord3s = NULL; PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv = NULL; PFNGLTEXCOORD4DPROC glad_glTexCoord4d = NULL; PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv = NULL; PFNGLTEXCOORD4FPROC glad_glTexCoord4f = NULL; PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv = NULL; PFNGLTEXCOORD4IPROC glad_glTexCoord4i = NULL; PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv = NULL; PFNGLTEXCOORD4SPROC glad_glTexCoord4s = NULL; PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv = NULL; PFNGLTEXCOORDP1UIPROC glad_glTexCoordP1ui = NULL; PFNGLTEXCOORDP1UIVPROC glad_glTexCoordP1uiv = NULL; PFNGLTEXCOORDP2UIPROC glad_glTexCoordP2ui = NULL; PFNGLTEXCOORDP2UIVPROC glad_glTexCoordP2uiv = NULL; PFNGLTEXCOORDP3UIPROC glad_glTexCoordP3ui = NULL; PFNGLTEXCOORDP3UIVPROC glad_glTexCoordP3uiv = NULL; PFNGLTEXCOORDP4UIPROC glad_glTexCoordP4ui = NULL; PFNGLTEXCOORDP4UIVPROC glad_glTexCoordP4uiv = NULL; PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer = NULL; PFNGLTEXENVFPROC glad_glTexEnvf = NULL; PFNGLTEXENVFVPROC glad_glTexEnvfv = NULL; PFNGLTEXENVIPROC glad_glTexEnvi = NULL; PFNGLTEXENVIVPROC glad_glTexEnviv = NULL; PFNGLTEXGENDPROC glad_glTexGend = NULL; PFNGLTEXGENDVPROC glad_glTexGendv = NULL; PFNGLTEXGENFPROC glad_glTexGenf = NULL; PFNGLTEXGENFVPROC glad_glTexGenfv = NULL; PFNGLTEXGENIPROC glad_glTexGeni = NULL; PFNGLTEXGENIVPROC glad_glTexGeniv = NULL; PFNGLTEXIMAGE1DPROC glad_glTexImage1D = NULL; PFNGLTEXIMAGE2DPROC glad_glTexImage2D = NULL; PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample = NULL; PFNGLTEXIMAGE3DPROC glad_glTexImage3D = NULL; PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample = NULL; PFNGLTEXPARAMETERIIVPROC glad_glTexParameterIiv = NULL; PFNGLTEXPARAMETERIUIVPROC glad_glTexParameterIuiv = NULL; PFNGLTEXPARAMETERFPROC glad_glTexParameterf = NULL; PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv = NULL; PFNGLTEXPARAMETERIPROC glad_glTexParameteri = NULL; PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv = NULL; PFNGLTEXSTORAGE1DPROC glad_glTexStorage1D = NULL; PFNGLTEXSTORAGE2DPROC glad_glTexStorage2D = NULL; PFNGLTEXSTORAGE2DMULTISAMPLEPROC glad_glTexStorage2DMultisample = NULL; PFNGLTEXSTORAGE3DPROC glad_glTexStorage3D = NULL; PFNGLTEXSTORAGE3DMULTISAMPLEPROC glad_glTexStorage3DMultisample = NULL; PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D = NULL; PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D = NULL; PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D = NULL; PFNGLTEXTUREBARRIERPROC glad_glTextureBarrier = NULL; PFNGLTEXTUREBUFFERPROC glad_glTextureBuffer = NULL; PFNGLTEXTUREBUFFERRANGEPROC glad_glTextureBufferRange = NULL; PFNGLTEXTUREPARAMETERIIVPROC glad_glTextureParameterIiv = NULL; PFNGLTEXTUREPARAMETERIUIVPROC glad_glTextureParameterIuiv = NULL; PFNGLTEXTUREPARAMETERFPROC glad_glTextureParameterf = NULL; PFNGLTEXTUREPARAMETERFVPROC glad_glTextureParameterfv = NULL; PFNGLTEXTUREPARAMETERIPROC glad_glTextureParameteri = NULL; PFNGLTEXTUREPARAMETERIVPROC glad_glTextureParameteriv = NULL; PFNGLTEXTURESTORAGE1DPROC glad_glTextureStorage1D = NULL; PFNGLTEXTURESTORAGE2DPROC glad_glTextureStorage2D = NULL; PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC glad_glTextureStorage2DMultisample = NULL; PFNGLTEXTURESTORAGE3DPROC glad_glTextureStorage3D = NULL; PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC glad_glTextureStorage3DMultisample = NULL; PFNGLTEXTURESUBIMAGE1DPROC glad_glTextureSubImage1D = NULL; PFNGLTEXTURESUBIMAGE2DPROC glad_glTextureSubImage2D = NULL; PFNGLTEXTURESUBIMAGE3DPROC glad_glTextureSubImage3D = NULL; PFNGLTEXTUREVIEWPROC glad_glTextureView = NULL; PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC glad_glTransformFeedbackBufferBase = NULL; PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC glad_glTransformFeedbackBufferRange = NULL; PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings = NULL; PFNGLTRANSLATEDPROC glad_glTranslated = NULL; PFNGLTRANSLATEFPROC glad_glTranslatef = NULL; PFNGLUNIFORM1DPROC glad_glUniform1d = NULL; PFNGLUNIFORM1DVPROC glad_glUniform1dv = NULL; PFNGLUNIFORM1FPROC glad_glUniform1f = NULL; PFNGLUNIFORM1FVPROC glad_glUniform1fv = NULL; PFNGLUNIFORM1IPROC glad_glUniform1i = NULL; PFNGLUNIFORM1IVPROC glad_glUniform1iv = NULL; PFNGLUNIFORM1UIPROC glad_glUniform1ui = NULL; PFNGLUNIFORM1UIVPROC glad_glUniform1uiv = NULL; PFNGLUNIFORM2DPROC glad_glUniform2d = NULL; PFNGLUNIFORM2DVPROC glad_glUniform2dv = NULL; PFNGLUNIFORM2FPROC glad_glUniform2f = NULL; PFNGLUNIFORM2FVPROC glad_glUniform2fv = NULL; PFNGLUNIFORM2IPROC glad_glUniform2i = NULL; PFNGLUNIFORM2IVPROC glad_glUniform2iv = NULL; PFNGLUNIFORM2UIPROC glad_glUniform2ui = NULL; PFNGLUNIFORM2UIVPROC glad_glUniform2uiv = NULL; PFNGLUNIFORM3DPROC glad_glUniform3d = NULL; PFNGLUNIFORM3DVPROC glad_glUniform3dv = NULL; PFNGLUNIFORM3FPROC glad_glUniform3f = NULL; PFNGLUNIFORM3FVPROC glad_glUniform3fv = NULL; PFNGLUNIFORM3IPROC glad_glUniform3i = NULL; PFNGLUNIFORM3IVPROC glad_glUniform3iv = NULL; PFNGLUNIFORM3UIPROC glad_glUniform3ui = NULL; PFNGLUNIFORM3UIVPROC glad_glUniform3uiv = NULL; PFNGLUNIFORM4DPROC glad_glUniform4d = NULL; PFNGLUNIFORM4DVPROC glad_glUniform4dv = NULL; PFNGLUNIFORM4FPROC glad_glUniform4f = NULL; PFNGLUNIFORM4FVPROC glad_glUniform4fv = NULL; PFNGLUNIFORM4IPROC glad_glUniform4i = NULL; PFNGLUNIFORM4IVPROC glad_glUniform4iv = NULL; PFNGLUNIFORM4UIPROC glad_glUniform4ui = NULL; PFNGLUNIFORM4UIVPROC glad_glUniform4uiv = NULL; PFNGLUNIFORMBLOCKBINDINGPROC glad_glUniformBlockBinding = NULL; PFNGLUNIFORMMATRIX2DVPROC glad_glUniformMatrix2dv = NULL; PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv = NULL; PFNGLUNIFORMMATRIX2X3DVPROC glad_glUniformMatrix2x3dv = NULL; PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv = NULL; PFNGLUNIFORMMATRIX2X4DVPROC glad_glUniformMatrix2x4dv = NULL; PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv = NULL; PFNGLUNIFORMMATRIX3DVPROC glad_glUniformMatrix3dv = NULL; PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv = NULL; PFNGLUNIFORMMATRIX3X2DVPROC glad_glUniformMatrix3x2dv = NULL; PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv = NULL; PFNGLUNIFORMMATRIX3X4DVPROC glad_glUniformMatrix3x4dv = NULL; PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv = NULL; PFNGLUNIFORMMATRIX4DVPROC glad_glUniformMatrix4dv = NULL; PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv = NULL; PFNGLUNIFORMMATRIX4X2DVPROC glad_glUniformMatrix4x2dv = NULL; PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv = NULL; PFNGLUNIFORMMATRIX4X3DVPROC glad_glUniformMatrix4x3dv = NULL; PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv = NULL; PFNGLUNIFORMSUBROUTINESUIVPROC glad_glUniformSubroutinesuiv = NULL; PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer = NULL; PFNGLUNMAPNAMEDBUFFERPROC glad_glUnmapNamedBuffer = NULL; PFNGLUSEPROGRAMPROC glad_glUseProgram = NULL; PFNGLUSEPROGRAMSTAGESPROC glad_glUseProgramStages = NULL; PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram = NULL; PFNGLVALIDATEPROGRAMPIPELINEPROC glad_glValidateProgramPipeline = NULL; PFNGLVERTEX2DPROC glad_glVertex2d = NULL; PFNGLVERTEX2DVPROC glad_glVertex2dv = NULL; PFNGLVERTEX2FPROC glad_glVertex2f = NULL; PFNGLVERTEX2FVPROC glad_glVertex2fv = NULL; PFNGLVERTEX2IPROC glad_glVertex2i = NULL; PFNGLVERTEX2IVPROC glad_glVertex2iv = NULL; PFNGLVERTEX2SPROC glad_glVertex2s = NULL; PFNGLVERTEX2SVPROC glad_glVertex2sv = NULL; PFNGLVERTEX3DPROC glad_glVertex3d = NULL; PFNGLVERTEX3DVPROC glad_glVertex3dv = NULL; PFNGLVERTEX3FPROC glad_glVertex3f = NULL; PFNGLVERTEX3FVPROC glad_glVertex3fv = NULL; PFNGLVERTEX3IPROC glad_glVertex3i = NULL; PFNGLVERTEX3IVPROC glad_glVertex3iv = NULL; PFNGLVERTEX3SPROC glad_glVertex3s = NULL; PFNGLVERTEX3SVPROC glad_glVertex3sv = NULL; PFNGLVERTEX4DPROC glad_glVertex4d = NULL; PFNGLVERTEX4DVPROC glad_glVertex4dv = NULL; PFNGLVERTEX4FPROC glad_glVertex4f = NULL; PFNGLVERTEX4FVPROC glad_glVertex4fv = NULL; PFNGLVERTEX4IPROC glad_glVertex4i = NULL; PFNGLVERTEX4IVPROC glad_glVertex4iv = NULL; PFNGLVERTEX4SPROC glad_glVertex4s = NULL; PFNGLVERTEX4SVPROC glad_glVertex4sv = NULL; PFNGLVERTEXARRAYATTRIBBINDINGPROC glad_glVertexArrayAttribBinding = NULL; PFNGLVERTEXARRAYATTRIBFORMATPROC glad_glVertexArrayAttribFormat = NULL; PFNGLVERTEXARRAYATTRIBIFORMATPROC glad_glVertexArrayAttribIFormat = NULL; PFNGLVERTEXARRAYATTRIBLFORMATPROC glad_glVertexArrayAttribLFormat = NULL; PFNGLVERTEXARRAYBINDINGDIVISORPROC glad_glVertexArrayBindingDivisor = NULL; PFNGLVERTEXARRAYELEMENTBUFFERPROC glad_glVertexArrayElementBuffer = NULL; PFNGLVERTEXARRAYVERTEXBUFFERPROC glad_glVertexArrayVertexBuffer = NULL; PFNGLVERTEXARRAYVERTEXBUFFERSPROC glad_glVertexArrayVertexBuffers = NULL; PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d = NULL; PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv = NULL; PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f = NULL; PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv = NULL; PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s = NULL; PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv = NULL; PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d = NULL; PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv = NULL; PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f = NULL; PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv = NULL; PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s = NULL; PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv = NULL; PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d = NULL; PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv = NULL; PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f = NULL; PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv = NULL; PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s = NULL; PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv = NULL; PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv = NULL; PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv = NULL; PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv = NULL; PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub = NULL; PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv = NULL; PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv = NULL; PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv = NULL; PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv = NULL; PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d = NULL; PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv = NULL; PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f = NULL; PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv = NULL; PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv = NULL; PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s = NULL; PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv = NULL; PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv = NULL; PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv = NULL; PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv = NULL; PFNGLVERTEXATTRIBBINDINGPROC glad_glVertexAttribBinding = NULL; PFNGLVERTEXATTRIBDIVISORPROC glad_glVertexAttribDivisor = NULL; PFNGLVERTEXATTRIBFORMATPROC glad_glVertexAttribFormat = NULL; PFNGLVERTEXATTRIBI1IPROC glad_glVertexAttribI1i = NULL; PFNGLVERTEXATTRIBI1IVPROC glad_glVertexAttribI1iv = NULL; PFNGLVERTEXATTRIBI1UIPROC glad_glVertexAttribI1ui = NULL; PFNGLVERTEXATTRIBI1UIVPROC glad_glVertexAttribI1uiv = NULL; PFNGLVERTEXATTRIBI2IPROC glad_glVertexAttribI2i = NULL; PFNGLVERTEXATTRIBI2IVPROC glad_glVertexAttribI2iv = NULL; PFNGLVERTEXATTRIBI2UIPROC glad_glVertexAttribI2ui = NULL; PFNGLVERTEXATTRIBI2UIVPROC glad_glVertexAttribI2uiv = NULL; PFNGLVERTEXATTRIBI3IPROC glad_glVertexAttribI3i = NULL; PFNGLVERTEXATTRIBI3IVPROC glad_glVertexAttribI3iv = NULL; PFNGLVERTEXATTRIBI3UIPROC glad_glVertexAttribI3ui = NULL; PFNGLVERTEXATTRIBI3UIVPROC glad_glVertexAttribI3uiv = NULL; PFNGLVERTEXATTRIBI4BVPROC glad_glVertexAttribI4bv = NULL; PFNGLVERTEXATTRIBI4IPROC glad_glVertexAttribI4i = NULL; PFNGLVERTEXATTRIBI4IVPROC glad_glVertexAttribI4iv = NULL; PFNGLVERTEXATTRIBI4SVPROC glad_glVertexAttribI4sv = NULL; PFNGLVERTEXATTRIBI4UBVPROC glad_glVertexAttribI4ubv = NULL; PFNGLVERTEXATTRIBI4UIPROC glad_glVertexAttribI4ui = NULL; PFNGLVERTEXATTRIBI4UIVPROC glad_glVertexAttribI4uiv = NULL; PFNGLVERTEXATTRIBI4USVPROC glad_glVertexAttribI4usv = NULL; PFNGLVERTEXATTRIBIFORMATPROC glad_glVertexAttribIFormat = NULL; PFNGLVERTEXATTRIBIPOINTERPROC glad_glVertexAttribIPointer = NULL; PFNGLVERTEXATTRIBL1DPROC glad_glVertexAttribL1d = NULL; PFNGLVERTEXATTRIBL1DVPROC glad_glVertexAttribL1dv = NULL; PFNGLVERTEXATTRIBL2DPROC glad_glVertexAttribL2d = NULL; PFNGLVERTEXATTRIBL2DVPROC glad_glVertexAttribL2dv = NULL; PFNGLVERTEXATTRIBL3DPROC glad_glVertexAttribL3d = NULL; PFNGLVERTEXATTRIBL3DVPROC glad_glVertexAttribL3dv = NULL; PFNGLVERTEXATTRIBL4DPROC glad_glVertexAttribL4d = NULL; PFNGLVERTEXATTRIBL4DVPROC glad_glVertexAttribL4dv = NULL; PFNGLVERTEXATTRIBLFORMATPROC glad_glVertexAttribLFormat = NULL; PFNGLVERTEXATTRIBLPOINTERPROC glad_glVertexAttribLPointer = NULL; PFNGLVERTEXATTRIBP1UIPROC glad_glVertexAttribP1ui = NULL; PFNGLVERTEXATTRIBP1UIVPROC glad_glVertexAttribP1uiv = NULL; PFNGLVERTEXATTRIBP2UIPROC glad_glVertexAttribP2ui = NULL; PFNGLVERTEXATTRIBP2UIVPROC glad_glVertexAttribP2uiv = NULL; PFNGLVERTEXATTRIBP3UIPROC glad_glVertexAttribP3ui = NULL; PFNGLVERTEXATTRIBP3UIVPROC glad_glVertexAttribP3uiv = NULL; PFNGLVERTEXATTRIBP4UIPROC glad_glVertexAttribP4ui = NULL; PFNGLVERTEXATTRIBP4UIVPROC glad_glVertexAttribP4uiv = NULL; PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer = NULL; PFNGLVERTEXBINDINGDIVISORPROC glad_glVertexBindingDivisor = NULL; PFNGLVERTEXP2UIPROC glad_glVertexP2ui = NULL; PFNGLVERTEXP2UIVPROC glad_glVertexP2uiv = NULL; PFNGLVERTEXP3UIPROC glad_glVertexP3ui = NULL; PFNGLVERTEXP3UIVPROC glad_glVertexP3uiv = NULL; PFNGLVERTEXP4UIPROC glad_glVertexP4ui = NULL; PFNGLVERTEXP4UIVPROC glad_glVertexP4uiv = NULL; PFNGLVERTEXPOINTERPROC glad_glVertexPointer = NULL; PFNGLVIEWPORTPROC glad_glViewport = NULL; PFNGLVIEWPORTARRAYVPROC glad_glViewportArrayv = NULL; PFNGLVIEWPORTINDEXEDFPROC glad_glViewportIndexedf = NULL; PFNGLVIEWPORTINDEXEDFVPROC glad_glViewportIndexedfv = NULL; PFNGLWAITSYNCPROC glad_glWaitSync = NULL; PFNGLWINDOWPOS2DPROC glad_glWindowPos2d = NULL; PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv = NULL; PFNGLWINDOWPOS2FPROC glad_glWindowPos2f = NULL; PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv = NULL; PFNGLWINDOWPOS2IPROC glad_glWindowPos2i = NULL; PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv = NULL; PFNGLWINDOWPOS2SPROC glad_glWindowPos2s = NULL; PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv = NULL; PFNGLWINDOWPOS3DPROC glad_glWindowPos3d = NULL; PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv = NULL; PFNGLWINDOWPOS3FPROC glad_glWindowPos3f = NULL; PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv = NULL; PFNGLWINDOWPOS3IPROC glad_glWindowPos3i = NULL; PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv = NULL; PFNGLWINDOWPOS3SPROC glad_glWindowPos3s = NULL; PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv = NULL; static void load_GL_VERSION_1_0(GLADloadproc load) { if(!GLAD_GL_VERSION_1_0) return; glad_glCullFace = (PFNGLCULLFACEPROC)load("glCullFace"); glad_glFrontFace = (PFNGLFRONTFACEPROC)load("glFrontFace"); glad_glHint = (PFNGLHINTPROC)load("glHint"); glad_glLineWidth = (PFNGLLINEWIDTHPROC)load("glLineWidth"); glad_glPointSize = (PFNGLPOINTSIZEPROC)load("glPointSize"); glad_glPolygonMode = (PFNGLPOLYGONMODEPROC)load("glPolygonMode"); glad_glScissor = (PFNGLSCISSORPROC)load("glScissor"); glad_glTexParameterf = (PFNGLTEXPARAMETERFPROC)load("glTexParameterf"); glad_glTexParameterfv = (PFNGLTEXPARAMETERFVPROC)load("glTexParameterfv"); glad_glTexParameteri = (PFNGLTEXPARAMETERIPROC)load("glTexParameteri"); glad_glTexParameteriv = (PFNGLTEXPARAMETERIVPROC)load("glTexParameteriv"); glad_glTexImage1D = (PFNGLTEXIMAGE1DPROC)load("glTexImage1D"); glad_glTexImage2D = (PFNGLTEXIMAGE2DPROC)load("glTexImage2D"); glad_glDrawBuffer = (PFNGLDRAWBUFFERPROC)load("glDrawBuffer"); glad_glClear = (PFNGLCLEARPROC)load("glClear"); glad_glClearColor = (PFNGLCLEARCOLORPROC)load("glClearColor"); glad_glClearStencil = (PFNGLCLEARSTENCILPROC)load("glClearStencil"); glad_glClearDepth = (PFNGLCLEARDEPTHPROC)load("glClearDepth"); glad_glStencilMask = (PFNGLSTENCILMASKPROC)load("glStencilMask"); glad_glColorMask = (PFNGLCOLORMASKPROC)load("glColorMask"); glad_glDepthMask = (PFNGLDEPTHMASKPROC)load("glDepthMask"); glad_glDisable = (PFNGLDISABLEPROC)load("glDisable"); glad_glEnable = (PFNGLENABLEPROC)load("glEnable"); glad_glFinish = (PFNGLFINISHPROC)load("glFinish"); glad_glFlush = (PFNGLFLUSHPROC)load("glFlush"); glad_glBlendFunc = (PFNGLBLENDFUNCPROC)load("glBlendFunc"); glad_glLogicOp = (PFNGLLOGICOPPROC)load("glLogicOp"); glad_glStencilFunc = (PFNGLSTENCILFUNCPROC)load("glStencilFunc"); glad_glStencilOp = (PFNGLSTENCILOPPROC)load("glStencilOp"); glad_glDepthFunc = (PFNGLDEPTHFUNCPROC)load("glDepthFunc"); glad_glPixelStoref = (PFNGLPIXELSTOREFPROC)load("glPixelStoref"); glad_glPixelStorei = (PFNGLPIXELSTOREIPROC)load("glPixelStorei"); glad_glReadBuffer = (PFNGLREADBUFFERPROC)load("glReadBuffer"); glad_glReadPixels = (PFNGLREADPIXELSPROC)load("glReadPixels"); glad_glGetBooleanv = (PFNGLGETBOOLEANVPROC)load("glGetBooleanv"); glad_glGetDoublev = (PFNGLGETDOUBLEVPROC)load("glGetDoublev"); glad_glGetError = (PFNGLGETERRORPROC)load("glGetError"); glad_glGetFloatv = (PFNGLGETFLOATVPROC)load("glGetFloatv"); glad_glGetIntegerv = (PFNGLGETINTEGERVPROC)load("glGetIntegerv"); glad_glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); glad_glGetTexImage = (PFNGLGETTEXIMAGEPROC)load("glGetTexImage"); glad_glGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)load("glGetTexParameterfv"); glad_glGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)load("glGetTexParameteriv"); glad_glGetTexLevelParameterfv = (PFNGLGETTEXLEVELPARAMETERFVPROC)load("glGetTexLevelParameterfv"); glad_glGetTexLevelParameteriv = (PFNGLGETTEXLEVELPARAMETERIVPROC)load("glGetTexLevelParameteriv"); glad_glIsEnabled = (PFNGLISENABLEDPROC)load("glIsEnabled"); glad_glDepthRange = (PFNGLDEPTHRANGEPROC)load("glDepthRange"); glad_glViewport = (PFNGLVIEWPORTPROC)load("glViewport"); glad_glNewList = (PFNGLNEWLISTPROC)load("glNewList"); glad_glEndList = (PFNGLENDLISTPROC)load("glEndList"); glad_glCallList = (PFNGLCALLLISTPROC)load("glCallList"); glad_glCallLists = (PFNGLCALLLISTSPROC)load("glCallLists"); glad_glDeleteLists = (PFNGLDELETELISTSPROC)load("glDeleteLists"); glad_glGenLists = (PFNGLGENLISTSPROC)load("glGenLists"); glad_glListBase = (PFNGLLISTBASEPROC)load("glListBase"); glad_glBegin = (PFNGLBEGINPROC)load("glBegin"); glad_glBitmap = (PFNGLBITMAPPROC)load("glBitmap"); glad_glColor3b = (PFNGLCOLOR3BPROC)load("glColor3b"); glad_glColor3bv = (PFNGLCOLOR3BVPROC)load("glColor3bv"); glad_glColor3d = (PFNGLCOLOR3DPROC)load("glColor3d"); glad_glColor3dv = (PFNGLCOLOR3DVPROC)load("glColor3dv"); glad_glColor3f = (PFNGLCOLOR3FPROC)load("glColor3f"); glad_glColor3fv = (PFNGLCOLOR3FVPROC)load("glColor3fv"); glad_glColor3i = (PFNGLCOLOR3IPROC)load("glColor3i"); glad_glColor3iv = (PFNGLCOLOR3IVPROC)load("glColor3iv"); glad_glColor3s = (PFNGLCOLOR3SPROC)load("glColor3s"); glad_glColor3sv = (PFNGLCOLOR3SVPROC)load("glColor3sv"); glad_glColor3ub = (PFNGLCOLOR3UBPROC)load("glColor3ub"); glad_glColor3ubv = (PFNGLCOLOR3UBVPROC)load("glColor3ubv"); glad_glColor3ui = (PFNGLCOLOR3UIPROC)load("glColor3ui"); glad_glColor3uiv = (PFNGLCOLOR3UIVPROC)load("glColor3uiv"); glad_glColor3us = (PFNGLCOLOR3USPROC)load("glColor3us"); glad_glColor3usv = (PFNGLCOLOR3USVPROC)load("glColor3usv"); glad_glColor4b = (PFNGLCOLOR4BPROC)load("glColor4b"); glad_glColor4bv = (PFNGLCOLOR4BVPROC)load("glColor4bv"); glad_glColor4d = (PFNGLCOLOR4DPROC)load("glColor4d"); glad_glColor4dv = (PFNGLCOLOR4DVPROC)load("glColor4dv"); glad_glColor4f = (PFNGLCOLOR4FPROC)load("glColor4f"); glad_glColor4fv = (PFNGLCOLOR4FVPROC)load("glColor4fv"); glad_glColor4i = (PFNGLCOLOR4IPROC)load("glColor4i"); glad_glColor4iv = (PFNGLCOLOR4IVPROC)load("glColor4iv"); glad_glColor4s = (PFNGLCOLOR4SPROC)load("glColor4s"); glad_glColor4sv = (PFNGLCOLOR4SVPROC)load("glColor4sv"); glad_glColor4ub = (PFNGLCOLOR4UBPROC)load("glColor4ub"); glad_glColor4ubv = (PFNGLCOLOR4UBVPROC)load("glColor4ubv"); glad_glColor4ui = (PFNGLCOLOR4UIPROC)load("glColor4ui"); glad_glColor4uiv = (PFNGLCOLOR4UIVPROC)load("glColor4uiv"); glad_glColor4us = (PFNGLCOLOR4USPROC)load("glColor4us"); glad_glColor4usv = (PFNGLCOLOR4USVPROC)load("glColor4usv"); glad_glEdgeFlag = (PFNGLEDGEFLAGPROC)load("glEdgeFlag"); glad_glEdgeFlagv = (PFNGLEDGEFLAGVPROC)load("glEdgeFlagv"); glad_glEnd = (PFNGLENDPROC)load("glEnd"); glad_glIndexd = (PFNGLINDEXDPROC)load("glIndexd"); glad_glIndexdv = (PFNGLINDEXDVPROC)load("glIndexdv"); glad_glIndexf = (PFNGLINDEXFPROC)load("glIndexf"); glad_glIndexfv = (PFNGLINDEXFVPROC)load("glIndexfv"); glad_glIndexi = (PFNGLINDEXIPROC)load("glIndexi"); glad_glIndexiv = (PFNGLINDEXIVPROC)load("glIndexiv"); glad_glIndexs = (PFNGLINDEXSPROC)load("glIndexs"); glad_glIndexsv = (PFNGLINDEXSVPROC)load("glIndexsv"); glad_glNormal3b = (PFNGLNORMAL3BPROC)load("glNormal3b"); glad_glNormal3bv = (PFNGLNORMAL3BVPROC)load("glNormal3bv"); glad_glNormal3d = (PFNGLNORMAL3DPROC)load("glNormal3d"); glad_glNormal3dv = (PFNGLNORMAL3DVPROC)load("glNormal3dv"); glad_glNormal3f = (PFNGLNORMAL3FPROC)load("glNormal3f"); glad_glNormal3fv = (PFNGLNORMAL3FVPROC)load("glNormal3fv"); glad_glNormal3i = (PFNGLNORMAL3IPROC)load("glNormal3i"); glad_glNormal3iv = (PFNGLNORMAL3IVPROC)load("glNormal3iv"); glad_glNormal3s = (PFNGLNORMAL3SPROC)load("glNormal3s"); glad_glNormal3sv = (PFNGLNORMAL3SVPROC)load("glNormal3sv"); glad_glRasterPos2d = (PFNGLRASTERPOS2DPROC)load("glRasterPos2d"); glad_glRasterPos2dv = (PFNGLRASTERPOS2DVPROC)load("glRasterPos2dv"); glad_glRasterPos2f = (PFNGLRASTERPOS2FPROC)load("glRasterPos2f"); glad_glRasterPos2fv = (PFNGLRASTERPOS2FVPROC)load("glRasterPos2fv"); glad_glRasterPos2i = (PFNGLRASTERPOS2IPROC)load("glRasterPos2i"); glad_glRasterPos2iv = (PFNGLRASTERPOS2IVPROC)load("glRasterPos2iv"); glad_glRasterPos2s = (PFNGLRASTERPOS2SPROC)load("glRasterPos2s"); glad_glRasterPos2sv = (PFNGLRASTERPOS2SVPROC)load("glRasterPos2sv"); glad_glRasterPos3d = (PFNGLRASTERPOS3DPROC)load("glRasterPos3d"); glad_glRasterPos3dv = (PFNGLRASTERPOS3DVPROC)load("glRasterPos3dv"); glad_glRasterPos3f = (PFNGLRASTERPOS3FPROC)load("glRasterPos3f"); glad_glRasterPos3fv = (PFNGLRASTERPOS3FVPROC)load("glRasterPos3fv"); glad_glRasterPos3i = (PFNGLRASTERPOS3IPROC)load("glRasterPos3i"); glad_glRasterPos3iv = (PFNGLRASTERPOS3IVPROC)load("glRasterPos3iv"); glad_glRasterPos3s = (PFNGLRASTERPOS3SPROC)load("glRasterPos3s"); glad_glRasterPos3sv = (PFNGLRASTERPOS3SVPROC)load("glRasterPos3sv"); glad_glRasterPos4d = (PFNGLRASTERPOS4DPROC)load("glRasterPos4d"); glad_glRasterPos4dv = (PFNGLRASTERPOS4DVPROC)load("glRasterPos4dv"); glad_glRasterPos4f = (PFNGLRASTERPOS4FPROC)load("glRasterPos4f"); glad_glRasterPos4fv = (PFNGLRASTERPOS4FVPROC)load("glRasterPos4fv"); glad_glRasterPos4i = (PFNGLRASTERPOS4IPROC)load("glRasterPos4i"); glad_glRasterPos4iv = (PFNGLRASTERPOS4IVPROC)load("glRasterPos4iv"); glad_glRasterPos4s = (PFNGLRASTERPOS4SPROC)load("glRasterPos4s"); glad_glRasterPos4sv = (PFNGLRASTERPOS4SVPROC)load("glRasterPos4sv"); glad_glRectd = (PFNGLRECTDPROC)load("glRectd"); glad_glRectdv = (PFNGLRECTDVPROC)load("glRectdv"); glad_glRectf = (PFNGLRECTFPROC)load("glRectf"); glad_glRectfv = (PFNGLRECTFVPROC)load("glRectfv"); glad_glRecti = (PFNGLRECTIPROC)load("glRecti"); glad_glRectiv = (PFNGLRECTIVPROC)load("glRectiv"); glad_glRects = (PFNGLRECTSPROC)load("glRects"); glad_glRectsv = (PFNGLRECTSVPROC)load("glRectsv"); glad_glTexCoord1d = (PFNGLTEXCOORD1DPROC)load("glTexCoord1d"); glad_glTexCoord1dv = (PFNGLTEXCOORD1DVPROC)load("glTexCoord1dv"); glad_glTexCoord1f = (PFNGLTEXCOORD1FPROC)load("glTexCoord1f"); glad_glTexCoord1fv = (PFNGLTEXCOORD1FVPROC)load("glTexCoord1fv"); glad_glTexCoord1i = (PFNGLTEXCOORD1IPROC)load("glTexCoord1i"); glad_glTexCoord1iv = (PFNGLTEXCOORD1IVPROC)load("glTexCoord1iv"); glad_glTexCoord1s = (PFNGLTEXCOORD1SPROC)load("glTexCoord1s"); glad_glTexCoord1sv = (PFNGLTEXCOORD1SVPROC)load("glTexCoord1sv"); glad_glTexCoord2d = (PFNGLTEXCOORD2DPROC)load("glTexCoord2d"); glad_glTexCoord2dv = (PFNGLTEXCOORD2DVPROC)load("glTexCoord2dv"); glad_glTexCoord2f = (PFNGLTEXCOORD2FPROC)load("glTexCoord2f"); glad_glTexCoord2fv = (PFNGLTEXCOORD2FVPROC)load("glTexCoord2fv"); glad_glTexCoord2i = (PFNGLTEXCOORD2IPROC)load("glTexCoord2i"); glad_glTexCoord2iv = (PFNGLTEXCOORD2IVPROC)load("glTexCoord2iv"); glad_glTexCoord2s = (PFNGLTEXCOORD2SPROC)load("glTexCoord2s"); glad_glTexCoord2sv = (PFNGLTEXCOORD2SVPROC)load("glTexCoord2sv"); glad_glTexCoord3d = (PFNGLTEXCOORD3DPROC)load("glTexCoord3d"); glad_glTexCoord3dv = (PFNGLTEXCOORD3DVPROC)load("glTexCoord3dv"); glad_glTexCoord3f = (PFNGLTEXCOORD3FPROC)load("glTexCoord3f"); glad_glTexCoord3fv = (PFNGLTEXCOORD3FVPROC)load("glTexCoord3fv"); glad_glTexCoord3i = (PFNGLTEXCOORD3IPROC)load("glTexCoord3i"); glad_glTexCoord3iv = (PFNGLTEXCOORD3IVPROC)load("glTexCoord3iv"); glad_glTexCoord3s = (PFNGLTEXCOORD3SPROC)load("glTexCoord3s"); glad_glTexCoord3sv = (PFNGLTEXCOORD3SVPROC)load("glTexCoord3sv"); glad_glTexCoord4d = (PFNGLTEXCOORD4DPROC)load("glTexCoord4d"); glad_glTexCoord4dv = (PFNGLTEXCOORD4DVPROC)load("glTexCoord4dv"); glad_glTexCoord4f = (PFNGLTEXCOORD4FPROC)load("glTexCoord4f"); glad_glTexCoord4fv = (PFNGLTEXCOORD4FVPROC)load("glTexCoord4fv"); glad_glTexCoord4i = (PFNGLTEXCOORD4IPROC)load("glTexCoord4i"); glad_glTexCoord4iv = (PFNGLTEXCOORD4IVPROC)load("glTexCoord4iv"); glad_glTexCoord4s = (PFNGLTEXCOORD4SPROC)load("glTexCoord4s"); glad_glTexCoord4sv = (PFNGLTEXCOORD4SVPROC)load("glTexCoord4sv"); glad_glVertex2d = (PFNGLVERTEX2DPROC)load("glVertex2d"); glad_glVertex2dv = (PFNGLVERTEX2DVPROC)load("glVertex2dv"); glad_glVertex2f = (PFNGLVERTEX2FPROC)load("glVertex2f"); glad_glVertex2fv = (PFNGLVERTEX2FVPROC)load("glVertex2fv"); glad_glVertex2i = (PFNGLVERTEX2IPROC)load("glVertex2i"); glad_glVertex2iv = (PFNGLVERTEX2IVPROC)load("glVertex2iv"); glad_glVertex2s = (PFNGLVERTEX2SPROC)load("glVertex2s"); glad_glVertex2sv = (PFNGLVERTEX2SVPROC)load("glVertex2sv"); glad_glVertex3d = (PFNGLVERTEX3DPROC)load("glVertex3d"); glad_glVertex3dv = (PFNGLVERTEX3DVPROC)load("glVertex3dv"); glad_glVertex3f = (PFNGLVERTEX3FPROC)load("glVertex3f"); glad_glVertex3fv = (PFNGLVERTEX3FVPROC)load("glVertex3fv"); glad_glVertex3i = (PFNGLVERTEX3IPROC)load("glVertex3i"); glad_glVertex3iv = (PFNGLVERTEX3IVPROC)load("glVertex3iv"); glad_glVertex3s = (PFNGLVERTEX3SPROC)load("glVertex3s"); glad_glVertex3sv = (PFNGLVERTEX3SVPROC)load("glVertex3sv"); glad_glVertex4d = (PFNGLVERTEX4DPROC)load("glVertex4d"); glad_glVertex4dv = (PFNGLVERTEX4DVPROC)load("glVertex4dv"); glad_glVertex4f = (PFNGLVERTEX4FPROC)load("glVertex4f"); glad_glVertex4fv = (PFNGLVERTEX4FVPROC)load("glVertex4fv"); glad_glVertex4i = (PFNGLVERTEX4IPROC)load("glVertex4i"); glad_glVertex4iv = (PFNGLVERTEX4IVPROC)load("glVertex4iv"); glad_glVertex4s = (PFNGLVERTEX4SPROC)load("glVertex4s"); glad_glVertex4sv = (PFNGLVERTEX4SVPROC)load("glVertex4sv"); glad_glClipPlane = (PFNGLCLIPPLANEPROC)load("glClipPlane"); glad_glColorMaterial = (PFNGLCOLORMATERIALPROC)load("glColorMaterial"); glad_glFogf = (PFNGLFOGFPROC)load("glFogf"); glad_glFogfv = (PFNGLFOGFVPROC)load("glFogfv"); glad_glFogi = (PFNGLFOGIPROC)load("glFogi"); glad_glFogiv = (PFNGLFOGIVPROC)load("glFogiv"); glad_glLightf = (PFNGLLIGHTFPROC)load("glLightf"); glad_glLightfv = (PFNGLLIGHTFVPROC)load("glLightfv"); glad_glLighti = (PFNGLLIGHTIPROC)load("glLighti"); glad_glLightiv = (PFNGLLIGHTIVPROC)load("glLightiv"); glad_glLightModelf = (PFNGLLIGHTMODELFPROC)load("glLightModelf"); glad_glLightModelfv = (PFNGLLIGHTMODELFVPROC)load("glLightModelfv"); glad_glLightModeli = (PFNGLLIGHTMODELIPROC)load("glLightModeli"); glad_glLightModeliv = (PFNGLLIGHTMODELIVPROC)load("glLightModeliv"); glad_glLineStipple = (PFNGLLINESTIPPLEPROC)load("glLineStipple"); glad_glMaterialf = (PFNGLMATERIALFPROC)load("glMaterialf"); glad_glMaterialfv = (PFNGLMATERIALFVPROC)load("glMaterialfv"); glad_glMateriali = (PFNGLMATERIALIPROC)load("glMateriali"); glad_glMaterialiv = (PFNGLMATERIALIVPROC)load("glMaterialiv"); glad_glPolygonStipple = (PFNGLPOLYGONSTIPPLEPROC)load("glPolygonStipple"); glad_glShadeModel = (PFNGLSHADEMODELPROC)load("glShadeModel"); glad_glTexEnvf = (PFNGLTEXENVFPROC)load("glTexEnvf"); glad_glTexEnvfv = (PFNGLTEXENVFVPROC)load("glTexEnvfv"); glad_glTexEnvi = (PFNGLTEXENVIPROC)load("glTexEnvi"); glad_glTexEnviv = (PFNGLTEXENVIVPROC)load("glTexEnviv"); glad_glTexGend = (PFNGLTEXGENDPROC)load("glTexGend"); glad_glTexGendv = (PFNGLTEXGENDVPROC)load("glTexGendv"); glad_glTexGenf = (PFNGLTEXGENFPROC)load("glTexGenf"); glad_glTexGenfv = (PFNGLTEXGENFVPROC)load("glTexGenfv"); glad_glTexGeni = (PFNGLTEXGENIPROC)load("glTexGeni"); glad_glTexGeniv = (PFNGLTEXGENIVPROC)load("glTexGeniv"); glad_glFeedbackBuffer = (PFNGLFEEDBACKBUFFERPROC)load("glFeedbackBuffer"); glad_glSelectBuffer = (PFNGLSELECTBUFFERPROC)load("glSelectBuffer"); glad_glRenderMode = (PFNGLRENDERMODEPROC)load("glRenderMode"); glad_glInitNames = (PFNGLINITNAMESPROC)load("glInitNames"); glad_glLoadName = (PFNGLLOADNAMEPROC)load("glLoadName"); glad_glPassThrough = (PFNGLPASSTHROUGHPROC)load("glPassThrough"); glad_glPopName = (PFNGLPOPNAMEPROC)load("glPopName"); glad_glPushName = (PFNGLPUSHNAMEPROC)load("glPushName"); glad_glClearAccum = (PFNGLCLEARACCUMPROC)load("glClearAccum"); glad_glClearIndex = (PFNGLCLEARINDEXPROC)load("glClearIndex"); glad_glIndexMask = (PFNGLINDEXMASKPROC)load("glIndexMask"); glad_glAccum = (PFNGLACCUMPROC)load("glAccum"); glad_glPopAttrib = (PFNGLPOPATTRIBPROC)load("glPopAttrib"); glad_glPushAttrib = (PFNGLPUSHATTRIBPROC)load("glPushAttrib"); glad_glMap1d = (PFNGLMAP1DPROC)load("glMap1d"); glad_glMap1f = (PFNGLMAP1FPROC)load("glMap1f"); glad_glMap2d = (PFNGLMAP2DPROC)load("glMap2d"); glad_glMap2f = (PFNGLMAP2FPROC)load("glMap2f"); glad_glMapGrid1d = (PFNGLMAPGRID1DPROC)load("glMapGrid1d"); glad_glMapGrid1f = (PFNGLMAPGRID1FPROC)load("glMapGrid1f"); glad_glMapGrid2d = (PFNGLMAPGRID2DPROC)load("glMapGrid2d"); glad_glMapGrid2f = (PFNGLMAPGRID2FPROC)load("glMapGrid2f"); glad_glEvalCoord1d = (PFNGLEVALCOORD1DPROC)load("glEvalCoord1d"); glad_glEvalCoord1dv = (PFNGLEVALCOORD1DVPROC)load("glEvalCoord1dv"); glad_glEvalCoord1f = (PFNGLEVALCOORD1FPROC)load("glEvalCoord1f"); glad_glEvalCoord1fv = (PFNGLEVALCOORD1FVPROC)load("glEvalCoord1fv"); glad_glEvalCoord2d = (PFNGLEVALCOORD2DPROC)load("glEvalCoord2d"); glad_glEvalCoord2dv = (PFNGLEVALCOORD2DVPROC)load("glEvalCoord2dv"); glad_glEvalCoord2f = (PFNGLEVALCOORD2FPROC)load("glEvalCoord2f"); glad_glEvalCoord2fv = (PFNGLEVALCOORD2FVPROC)load("glEvalCoord2fv"); glad_glEvalMesh1 = (PFNGLEVALMESH1PROC)load("glEvalMesh1"); glad_glEvalPoint1 = (PFNGLEVALPOINT1PROC)load("glEvalPoint1"); glad_glEvalMesh2 = (PFNGLEVALMESH2PROC)load("glEvalMesh2"); glad_glEvalPoint2 = (PFNGLEVALPOINT2PROC)load("glEvalPoint2"); glad_glAlphaFunc = (PFNGLALPHAFUNCPROC)load("glAlphaFunc"); glad_glPixelZoom = (PFNGLPIXELZOOMPROC)load("glPixelZoom"); glad_glPixelTransferf = (PFNGLPIXELTRANSFERFPROC)load("glPixelTransferf"); glad_glPixelTransferi = (PFNGLPIXELTRANSFERIPROC)load("glPixelTransferi"); glad_glPixelMapfv = (PFNGLPIXELMAPFVPROC)load("glPixelMapfv"); glad_glPixelMapuiv = (PFNGLPIXELMAPUIVPROC)load("glPixelMapuiv"); glad_glPixelMapusv = (PFNGLPIXELMAPUSVPROC)load("glPixelMapusv"); glad_glCopyPixels = (PFNGLCOPYPIXELSPROC)load("glCopyPixels"); glad_glDrawPixels = (PFNGLDRAWPIXELSPROC)load("glDrawPixels"); glad_glGetClipPlane = (PFNGLGETCLIPPLANEPROC)load("glGetClipPlane"); glad_glGetLightfv = (PFNGLGETLIGHTFVPROC)load("glGetLightfv"); glad_glGetLightiv = (PFNGLGETLIGHTIVPROC)load("glGetLightiv"); glad_glGetMapdv = (PFNGLGETMAPDVPROC)load("glGetMapdv"); glad_glGetMapfv = (PFNGLGETMAPFVPROC)load("glGetMapfv"); glad_glGetMapiv = (PFNGLGETMAPIVPROC)load("glGetMapiv"); glad_glGetMaterialfv = (PFNGLGETMATERIALFVPROC)load("glGetMaterialfv"); glad_glGetMaterialiv = (PFNGLGETMATERIALIVPROC)load("glGetMaterialiv"); glad_glGetPixelMapfv = (PFNGLGETPIXELMAPFVPROC)load("glGetPixelMapfv"); glad_glGetPixelMapuiv = (PFNGLGETPIXELMAPUIVPROC)load("glGetPixelMapuiv"); glad_glGetPixelMapusv = (PFNGLGETPIXELMAPUSVPROC)load("glGetPixelMapusv"); glad_glGetPolygonStipple = (PFNGLGETPOLYGONSTIPPLEPROC)load("glGetPolygonStipple"); glad_glGetTexEnvfv = (PFNGLGETTEXENVFVPROC)load("glGetTexEnvfv"); glad_glGetTexEnviv = (PFNGLGETTEXENVIVPROC)load("glGetTexEnviv"); glad_glGetTexGendv = (PFNGLGETTEXGENDVPROC)load("glGetTexGendv"); glad_glGetTexGenfv = (PFNGLGETTEXGENFVPROC)load("glGetTexGenfv"); glad_glGetTexGeniv = (PFNGLGETTEXGENIVPROC)load("glGetTexGeniv"); glad_glIsList = (PFNGLISLISTPROC)load("glIsList"); glad_glFrustum = (PFNGLFRUSTUMPROC)load("glFrustum"); glad_glLoadIdentity = (PFNGLLOADIDENTITYPROC)load("glLoadIdentity"); glad_glLoadMatrixf = (PFNGLLOADMATRIXFPROC)load("glLoadMatrixf"); glad_glLoadMatrixd = (PFNGLLOADMATRIXDPROC)load("glLoadMatrixd"); glad_glMatrixMode = (PFNGLMATRIXMODEPROC)load("glMatrixMode"); glad_glMultMatrixf = (PFNGLMULTMATRIXFPROC)load("glMultMatrixf"); glad_glMultMatrixd = (PFNGLMULTMATRIXDPROC)load("glMultMatrixd"); glad_glOrtho = (PFNGLORTHOPROC)load("glOrtho"); glad_glPopMatrix = (PFNGLPOPMATRIXPROC)load("glPopMatrix"); glad_glPushMatrix = (PFNGLPUSHMATRIXPROC)load("glPushMatrix"); glad_glRotated = (PFNGLROTATEDPROC)load("glRotated"); glad_glRotatef = (PFNGLROTATEFPROC)load("glRotatef"); glad_glScaled = (PFNGLSCALEDPROC)load("glScaled"); glad_glScalef = (PFNGLSCALEFPROC)load("glScalef"); glad_glTranslated = (PFNGLTRANSLATEDPROC)load("glTranslated"); glad_glTranslatef = (PFNGLTRANSLATEFPROC)load("glTranslatef"); } static void load_GL_VERSION_1_1(GLADloadproc load) { if(!GLAD_GL_VERSION_1_1) return; glad_glDrawArrays = (PFNGLDRAWARRAYSPROC)load("glDrawArrays"); glad_glDrawElements = (PFNGLDRAWELEMENTSPROC)load("glDrawElements"); glad_glGetPointerv = (PFNGLGETPOINTERVPROC)load("glGetPointerv"); glad_glPolygonOffset = (PFNGLPOLYGONOFFSETPROC)load("glPolygonOffset"); glad_glCopyTexImage1D = (PFNGLCOPYTEXIMAGE1DPROC)load("glCopyTexImage1D"); glad_glCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)load("glCopyTexImage2D"); glad_glCopyTexSubImage1D = (PFNGLCOPYTEXSUBIMAGE1DPROC)load("glCopyTexSubImage1D"); glad_glCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)load("glCopyTexSubImage2D"); glad_glTexSubImage1D = (PFNGLTEXSUBIMAGE1DPROC)load("glTexSubImage1D"); glad_glTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)load("glTexSubImage2D"); glad_glBindTexture = (PFNGLBINDTEXTUREPROC)load("glBindTexture"); glad_glDeleteTextures = (PFNGLDELETETEXTURESPROC)load("glDeleteTextures"); glad_glGenTextures = (PFNGLGENTEXTURESPROC)load("glGenTextures"); glad_glIsTexture = (PFNGLISTEXTUREPROC)load("glIsTexture"); glad_glArrayElement = (PFNGLARRAYELEMENTPROC)load("glArrayElement"); glad_glColorPointer = (PFNGLCOLORPOINTERPROC)load("glColorPointer"); glad_glDisableClientState = (PFNGLDISABLECLIENTSTATEPROC)load("glDisableClientState"); glad_glEdgeFlagPointer = (PFNGLEDGEFLAGPOINTERPROC)load("glEdgeFlagPointer"); glad_glEnableClientState = (PFNGLENABLECLIENTSTATEPROC)load("glEnableClientState"); glad_glIndexPointer = (PFNGLINDEXPOINTERPROC)load("glIndexPointer"); glad_glInterleavedArrays = (PFNGLINTERLEAVEDARRAYSPROC)load("glInterleavedArrays"); glad_glNormalPointer = (PFNGLNORMALPOINTERPROC)load("glNormalPointer"); glad_glTexCoordPointer = (PFNGLTEXCOORDPOINTERPROC)load("glTexCoordPointer"); glad_glVertexPointer = (PFNGLVERTEXPOINTERPROC)load("glVertexPointer"); glad_glAreTexturesResident = (PFNGLARETEXTURESRESIDENTPROC)load("glAreTexturesResident"); glad_glPrioritizeTextures = (PFNGLPRIORITIZETEXTURESPROC)load("glPrioritizeTextures"); glad_glIndexub = (PFNGLINDEXUBPROC)load("glIndexub"); glad_glIndexubv = (PFNGLINDEXUBVPROC)load("glIndexubv"); glad_glPopClientAttrib = (PFNGLPOPCLIENTATTRIBPROC)load("glPopClientAttrib"); glad_glPushClientAttrib = (PFNGLPUSHCLIENTATTRIBPROC)load("glPushClientAttrib"); } static void load_GL_VERSION_1_2(GLADloadproc load) { if(!GLAD_GL_VERSION_1_2) return; glad_glDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)load("glDrawRangeElements"); glad_glTexImage3D = (PFNGLTEXIMAGE3DPROC)load("glTexImage3D"); glad_glTexSubImage3D = (PFNGLTEXSUBIMAGE3DPROC)load("glTexSubImage3D"); glad_glCopyTexSubImage3D = (PFNGLCOPYTEXSUBIMAGE3DPROC)load("glCopyTexSubImage3D"); } static void load_GL_VERSION_1_3(GLADloadproc load) { if(!GLAD_GL_VERSION_1_3) return; glad_glActiveTexture = (PFNGLACTIVETEXTUREPROC)load("glActiveTexture"); glad_glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)load("glSampleCoverage"); glad_glCompressedTexImage3D = (PFNGLCOMPRESSEDTEXIMAGE3DPROC)load("glCompressedTexImage3D"); glad_glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)load("glCompressedTexImage2D"); glad_glCompressedTexImage1D = (PFNGLCOMPRESSEDTEXIMAGE1DPROC)load("glCompressedTexImage1D"); glad_glCompressedTexSubImage3D = (PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)load("glCompressedTexSubImage3D"); glad_glCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)load("glCompressedTexSubImage2D"); glad_glCompressedTexSubImage1D = (PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)load("glCompressedTexSubImage1D"); glad_glGetCompressedTexImage = (PFNGLGETCOMPRESSEDTEXIMAGEPROC)load("glGetCompressedTexImage"); glad_glClientActiveTexture = (PFNGLCLIENTACTIVETEXTUREPROC)load("glClientActiveTexture"); glad_glMultiTexCoord1d = (PFNGLMULTITEXCOORD1DPROC)load("glMultiTexCoord1d"); glad_glMultiTexCoord1dv = (PFNGLMULTITEXCOORD1DVPROC)load("glMultiTexCoord1dv"); glad_glMultiTexCoord1f = (PFNGLMULTITEXCOORD1FPROC)load("glMultiTexCoord1f"); glad_glMultiTexCoord1fv = (PFNGLMULTITEXCOORD1FVPROC)load("glMultiTexCoord1fv"); glad_glMultiTexCoord1i = (PFNGLMULTITEXCOORD1IPROC)load("glMultiTexCoord1i"); glad_glMultiTexCoord1iv = (PFNGLMULTITEXCOORD1IVPROC)load("glMultiTexCoord1iv"); glad_glMultiTexCoord1s = (PFNGLMULTITEXCOORD1SPROC)load("glMultiTexCoord1s"); glad_glMultiTexCoord1sv = (PFNGLMULTITEXCOORD1SVPROC)load("glMultiTexCoord1sv"); glad_glMultiTexCoord2d = (PFNGLMULTITEXCOORD2DPROC)load("glMultiTexCoord2d"); glad_glMultiTexCoord2dv = (PFNGLMULTITEXCOORD2DVPROC)load("glMultiTexCoord2dv"); glad_glMultiTexCoord2f = (PFNGLMULTITEXCOORD2FPROC)load("glMultiTexCoord2f"); glad_glMultiTexCoord2fv = (PFNGLMULTITEXCOORD2FVPROC)load("glMultiTexCoord2fv"); glad_glMultiTexCoord2i = (PFNGLMULTITEXCOORD2IPROC)load("glMultiTexCoord2i"); glad_glMultiTexCoord2iv = (PFNGLMULTITEXCOORD2IVPROC)load("glMultiTexCoord2iv"); glad_glMultiTexCoord2s = (PFNGLMULTITEXCOORD2SPROC)load("glMultiTexCoord2s"); glad_glMultiTexCoord2sv = (PFNGLMULTITEXCOORD2SVPROC)load("glMultiTexCoord2sv"); glad_glMultiTexCoord3d = (PFNGLMULTITEXCOORD3DPROC)load("glMultiTexCoord3d"); glad_glMultiTexCoord3dv = (PFNGLMULTITEXCOORD3DVPROC)load("glMultiTexCoord3dv"); glad_glMultiTexCoord3f = (PFNGLMULTITEXCOORD3FPROC)load("glMultiTexCoord3f"); glad_glMultiTexCoord3fv = (PFNGLMULTITEXCOORD3FVPROC)load("glMultiTexCoord3fv"); glad_glMultiTexCoord3i = (PFNGLMULTITEXCOORD3IPROC)load("glMultiTexCoord3i"); glad_glMultiTexCoord3iv = (PFNGLMULTITEXCOORD3IVPROC)load("glMultiTexCoord3iv"); glad_glMultiTexCoord3s = (PFNGLMULTITEXCOORD3SPROC)load("glMultiTexCoord3s"); glad_glMultiTexCoord3sv = (PFNGLMULTITEXCOORD3SVPROC)load("glMultiTexCoord3sv"); glad_glMultiTexCoord4d = (PFNGLMULTITEXCOORD4DPROC)load("glMultiTexCoord4d"); glad_glMultiTexCoord4dv = (PFNGLMULTITEXCOORD4DVPROC)load("glMultiTexCoord4dv"); glad_glMultiTexCoord4f = (PFNGLMULTITEXCOORD4FPROC)load("glMultiTexCoord4f"); glad_glMultiTexCoord4fv = (PFNGLMULTITEXCOORD4FVPROC)load("glMultiTexCoord4fv"); glad_glMultiTexCoord4i = (PFNGLMULTITEXCOORD4IPROC)load("glMultiTexCoord4i"); glad_glMultiTexCoord4iv = (PFNGLMULTITEXCOORD4IVPROC)load("glMultiTexCoord4iv"); glad_glMultiTexCoord4s = (PFNGLMULTITEXCOORD4SPROC)load("glMultiTexCoord4s"); glad_glMultiTexCoord4sv = (PFNGLMULTITEXCOORD4SVPROC)load("glMultiTexCoord4sv"); glad_glLoadTransposeMatrixf = (PFNGLLOADTRANSPOSEMATRIXFPROC)load("glLoadTransposeMatrixf"); glad_glLoadTransposeMatrixd = (PFNGLLOADTRANSPOSEMATRIXDPROC)load("glLoadTransposeMatrixd"); glad_glMultTransposeMatrixf = (PFNGLMULTTRANSPOSEMATRIXFPROC)load("glMultTransposeMatrixf"); glad_glMultTransposeMatrixd = (PFNGLMULTTRANSPOSEMATRIXDPROC)load("glMultTransposeMatrixd"); } static void load_GL_VERSION_1_4(GLADloadproc load) { if(!GLAD_GL_VERSION_1_4) return; glad_glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)load("glBlendFuncSeparate"); glad_glMultiDrawArrays = (PFNGLMULTIDRAWARRAYSPROC)load("glMultiDrawArrays"); glad_glMultiDrawElements = (PFNGLMULTIDRAWELEMENTSPROC)load("glMultiDrawElements"); glad_glPointParameterf = (PFNGLPOINTPARAMETERFPROC)load("glPointParameterf"); glad_glPointParameterfv = (PFNGLPOINTPARAMETERFVPROC)load("glPointParameterfv"); glad_glPointParameteri = (PFNGLPOINTPARAMETERIPROC)load("glPointParameteri"); glad_glPointParameteriv = (PFNGLPOINTPARAMETERIVPROC)load("glPointParameteriv"); glad_glFogCoordf = (PFNGLFOGCOORDFPROC)load("glFogCoordf"); glad_glFogCoordfv = (PFNGLFOGCOORDFVPROC)load("glFogCoordfv"); glad_glFogCoordd = (PFNGLFOGCOORDDPROC)load("glFogCoordd"); glad_glFogCoorddv = (PFNGLFOGCOORDDVPROC)load("glFogCoorddv"); glad_glFogCoordPointer = (PFNGLFOGCOORDPOINTERPROC)load("glFogCoordPointer"); glad_glSecondaryColor3b = (PFNGLSECONDARYCOLOR3BPROC)load("glSecondaryColor3b"); glad_glSecondaryColor3bv = (PFNGLSECONDARYCOLOR3BVPROC)load("glSecondaryColor3bv"); glad_glSecondaryColor3d = (PFNGLSECONDARYCOLOR3DPROC)load("glSecondaryColor3d"); glad_glSecondaryColor3dv = (PFNGLSECONDARYCOLOR3DVPROC)load("glSecondaryColor3dv"); glad_glSecondaryColor3f = (PFNGLSECONDARYCOLOR3FPROC)load("glSecondaryColor3f"); glad_glSecondaryColor3fv = (PFNGLSECONDARYCOLOR3FVPROC)load("glSecondaryColor3fv"); glad_glSecondaryColor3i = (PFNGLSECONDARYCOLOR3IPROC)load("glSecondaryColor3i"); glad_glSecondaryColor3iv = (PFNGLSECONDARYCOLOR3IVPROC)load("glSecondaryColor3iv"); glad_glSecondaryColor3s = (PFNGLSECONDARYCOLOR3SPROC)load("glSecondaryColor3s"); glad_glSecondaryColor3sv = (PFNGLSECONDARYCOLOR3SVPROC)load("glSecondaryColor3sv"); glad_glSecondaryColor3ub = (PFNGLSECONDARYCOLOR3UBPROC)load("glSecondaryColor3ub"); glad_glSecondaryColor3ubv = (PFNGLSECONDARYCOLOR3UBVPROC)load("glSecondaryColor3ubv"); glad_glSecondaryColor3ui = (PFNGLSECONDARYCOLOR3UIPROC)load("glSecondaryColor3ui"); glad_glSecondaryColor3uiv = (PFNGLSECONDARYCOLOR3UIVPROC)load("glSecondaryColor3uiv"); glad_glSecondaryColor3us = (PFNGLSECONDARYCOLOR3USPROC)load("glSecondaryColor3us"); glad_glSecondaryColor3usv = (PFNGLSECONDARYCOLOR3USVPROC)load("glSecondaryColor3usv"); glad_glSecondaryColorPointer = (PFNGLSECONDARYCOLORPOINTERPROC)load("glSecondaryColorPointer"); glad_glWindowPos2d = (PFNGLWINDOWPOS2DPROC)load("glWindowPos2d"); glad_glWindowPos2dv = (PFNGLWINDOWPOS2DVPROC)load("glWindowPos2dv"); glad_glWindowPos2f = (PFNGLWINDOWPOS2FPROC)load("glWindowPos2f"); glad_glWindowPos2fv = (PFNGLWINDOWPOS2FVPROC)load("glWindowPos2fv"); glad_glWindowPos2i = (PFNGLWINDOWPOS2IPROC)load("glWindowPos2i"); glad_glWindowPos2iv = (PFNGLWINDOWPOS2IVPROC)load("glWindowPos2iv"); glad_glWindowPos2s = (PFNGLWINDOWPOS2SPROC)load("glWindowPos2s"); glad_glWindowPos2sv = (PFNGLWINDOWPOS2SVPROC)load("glWindowPos2sv"); glad_glWindowPos3d = (PFNGLWINDOWPOS3DPROC)load("glWindowPos3d"); glad_glWindowPos3dv = (PFNGLWINDOWPOS3DVPROC)load("glWindowPos3dv"); glad_glWindowPos3f = (PFNGLWINDOWPOS3FPROC)load("glWindowPos3f"); glad_glWindowPos3fv = (PFNGLWINDOWPOS3FVPROC)load("glWindowPos3fv"); glad_glWindowPos3i = (PFNGLWINDOWPOS3IPROC)load("glWindowPos3i"); glad_glWindowPos3iv = (PFNGLWINDOWPOS3IVPROC)load("glWindowPos3iv"); glad_glWindowPos3s = (PFNGLWINDOWPOS3SPROC)load("glWindowPos3s"); glad_glWindowPos3sv = (PFNGLWINDOWPOS3SVPROC)load("glWindowPos3sv"); glad_glBlendColor = (PFNGLBLENDCOLORPROC)load("glBlendColor"); glad_glBlendEquation = (PFNGLBLENDEQUATIONPROC)load("glBlendEquation"); } static void load_GL_VERSION_1_5(GLADloadproc load) { if(!GLAD_GL_VERSION_1_5) return; glad_glGenQueries = (PFNGLGENQUERIESPROC)load("glGenQueries"); glad_glDeleteQueries = (PFNGLDELETEQUERIESPROC)load("glDeleteQueries"); glad_glIsQuery = (PFNGLISQUERYPROC)load("glIsQuery"); glad_glBeginQuery = (PFNGLBEGINQUERYPROC)load("glBeginQuery"); glad_glEndQuery = (PFNGLENDQUERYPROC)load("glEndQuery"); glad_glGetQueryiv = (PFNGLGETQUERYIVPROC)load("glGetQueryiv"); glad_glGetQueryObjectiv = (PFNGLGETQUERYOBJECTIVPROC)load("glGetQueryObjectiv"); glad_glGetQueryObjectuiv = (PFNGLGETQUERYOBJECTUIVPROC)load("glGetQueryObjectuiv"); glad_glBindBuffer = (PFNGLBINDBUFFERPROC)load("glBindBuffer"); glad_glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)load("glDeleteBuffers"); glad_glGenBuffers = (PFNGLGENBUFFERSPROC)load("glGenBuffers"); glad_glIsBuffer = (PFNGLISBUFFERPROC)load("glIsBuffer"); glad_glBufferData = (PFNGLBUFFERDATAPROC)load("glBufferData"); glad_glBufferSubData = (PFNGLBUFFERSUBDATAPROC)load("glBufferSubData"); glad_glGetBufferSubData = (PFNGLGETBUFFERSUBDATAPROC)load("glGetBufferSubData"); glad_glMapBuffer = (PFNGLMAPBUFFERPROC)load("glMapBuffer"); glad_glUnmapBuffer = (PFNGLUNMAPBUFFERPROC)load("glUnmapBuffer"); glad_glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)load("glGetBufferParameteriv"); glad_glGetBufferPointerv = (PFNGLGETBUFFERPOINTERVPROC)load("glGetBufferPointerv"); } static void load_GL_VERSION_2_0(GLADloadproc load) { if(!GLAD_GL_VERSION_2_0) return; glad_glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)load("glBlendEquationSeparate"); glad_glDrawBuffers = (PFNGLDRAWBUFFERSPROC)load("glDrawBuffers"); glad_glStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)load("glStencilOpSeparate"); glad_glStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)load("glStencilFuncSeparate"); glad_glStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)load("glStencilMaskSeparate"); glad_glAttachShader = (PFNGLATTACHSHADERPROC)load("glAttachShader"); glad_glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)load("glBindAttribLocation"); glad_glCompileShader = (PFNGLCOMPILESHADERPROC)load("glCompileShader"); glad_glCreateProgram = (PFNGLCREATEPROGRAMPROC)load("glCreateProgram"); glad_glCreateShader = (PFNGLCREATESHADERPROC)load("glCreateShader"); glad_glDeleteProgram = (PFNGLDELETEPROGRAMPROC)load("glDeleteProgram"); glad_glDeleteShader = (PFNGLDELETESHADERPROC)load("glDeleteShader"); glad_glDetachShader = (PFNGLDETACHSHADERPROC)load("glDetachShader"); glad_glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)load("glDisableVertexAttribArray"); glad_glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)load("glEnableVertexAttribArray"); glad_glGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)load("glGetActiveAttrib"); glad_glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)load("glGetActiveUniform"); glad_glGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)load("glGetAttachedShaders"); glad_glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)load("glGetAttribLocation"); glad_glGetProgramiv = (PFNGLGETPROGRAMIVPROC)load("glGetProgramiv"); glad_glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)load("glGetProgramInfoLog"); glad_glGetShaderiv = (PFNGLGETSHADERIVPROC)load("glGetShaderiv"); glad_glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)load("glGetShaderInfoLog"); glad_glGetShaderSource = (PFNGLGETSHADERSOURCEPROC)load("glGetShaderSource"); glad_glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)load("glGetUniformLocation"); glad_glGetUniformfv = (PFNGLGETUNIFORMFVPROC)load("glGetUniformfv"); glad_glGetUniformiv = (PFNGLGETUNIFORMIVPROC)load("glGetUniformiv"); glad_glGetVertexAttribdv = (PFNGLGETVERTEXATTRIBDVPROC)load("glGetVertexAttribdv"); glad_glGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)load("glGetVertexAttribfv"); glad_glGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)load("glGetVertexAttribiv"); glad_glGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)load("glGetVertexAttribPointerv"); glad_glIsProgram = (PFNGLISPROGRAMPROC)load("glIsProgram"); glad_glIsShader = (PFNGLISSHADERPROC)load("glIsShader"); glad_glLinkProgram = (PFNGLLINKPROGRAMPROC)load("glLinkProgram"); glad_glShaderSource = (PFNGLSHADERSOURCEPROC)load("glShaderSource"); glad_glUseProgram = (PFNGLUSEPROGRAMPROC)load("glUseProgram"); glad_glUniform1f = (PFNGLUNIFORM1FPROC)load("glUniform1f"); glad_glUniform2f = (PFNGLUNIFORM2FPROC)load("glUniform2f"); glad_glUniform3f = (PFNGLUNIFORM3FPROC)load("glUniform3f"); glad_glUniform4f = (PFNGLUNIFORM4FPROC)load("glUniform4f"); glad_glUniform1i = (PFNGLUNIFORM1IPROC)load("glUniform1i"); glad_glUniform2i = (PFNGLUNIFORM2IPROC)load("glUniform2i"); glad_glUniform3i = (PFNGLUNIFORM3IPROC)load("glUniform3i"); glad_glUniform4i = (PFNGLUNIFORM4IPROC)load("glUniform4i"); glad_glUniform1fv = (PFNGLUNIFORM1FVPROC)load("glUniform1fv"); glad_glUniform2fv = (PFNGLUNIFORM2FVPROC)load("glUniform2fv"); glad_glUniform3fv = (PFNGLUNIFORM3FVPROC)load("glUniform3fv"); glad_glUniform4fv = (PFNGLUNIFORM4FVPROC)load("glUniform4fv"); glad_glUniform1iv = (PFNGLUNIFORM1IVPROC)load("glUniform1iv"); glad_glUniform2iv = (PFNGLUNIFORM2IVPROC)load("glUniform2iv"); glad_glUniform3iv = (PFNGLUNIFORM3IVPROC)load("glUniform3iv"); glad_glUniform4iv = (PFNGLUNIFORM4IVPROC)load("glUniform4iv"); glad_glUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)load("glUniformMatrix2fv"); glad_glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)load("glUniformMatrix3fv"); glad_glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)load("glUniformMatrix4fv"); glad_glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)load("glValidateProgram"); glad_glVertexAttrib1d = (PFNGLVERTEXATTRIB1DPROC)load("glVertexAttrib1d"); glad_glVertexAttrib1dv = (PFNGLVERTEXATTRIB1DVPROC)load("glVertexAttrib1dv"); glad_glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)load("glVertexAttrib1f"); glad_glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)load("glVertexAttrib1fv"); glad_glVertexAttrib1s = (PFNGLVERTEXATTRIB1SPROC)load("glVertexAttrib1s"); glad_glVertexAttrib1sv = (PFNGLVERTEXATTRIB1SVPROC)load("glVertexAttrib1sv"); glad_glVertexAttrib2d = (PFNGLVERTEXATTRIB2DPROC)load("glVertexAttrib2d"); glad_glVertexAttrib2dv = (PFNGLVERTEXATTRIB2DVPROC)load("glVertexAttrib2dv"); glad_glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)load("glVertexAttrib2f"); glad_glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)load("glVertexAttrib2fv"); glad_glVertexAttrib2s = (PFNGLVERTEXATTRIB2SPROC)load("glVertexAttrib2s"); glad_glVertexAttrib2sv = (PFNGLVERTEXATTRIB2SVPROC)load("glVertexAttrib2sv"); glad_glVertexAttrib3d = (PFNGLVERTEXATTRIB3DPROC)load("glVertexAttrib3d"); glad_glVertexAttrib3dv = (PFNGLVERTEXATTRIB3DVPROC)load("glVertexAttrib3dv"); glad_glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)load("glVertexAttrib3f"); glad_glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)load("glVertexAttrib3fv"); glad_glVertexAttrib3s = (PFNGLVERTEXATTRIB3SPROC)load("glVertexAttrib3s"); glad_glVertexAttrib3sv = (PFNGLVERTEXATTRIB3SVPROC)load("glVertexAttrib3sv"); glad_glVertexAttrib4Nbv = (PFNGLVERTEXATTRIB4NBVPROC)load("glVertexAttrib4Nbv"); glad_glVertexAttrib4Niv = (PFNGLVERTEXATTRIB4NIVPROC)load("glVertexAttrib4Niv"); glad_glVertexAttrib4Nsv = (PFNGLVERTEXATTRIB4NSVPROC)load("glVertexAttrib4Nsv"); glad_glVertexAttrib4Nub = (PFNGLVERTEXATTRIB4NUBPROC)load("glVertexAttrib4Nub"); glad_glVertexAttrib4Nubv = (PFNGLVERTEXATTRIB4NUBVPROC)load("glVertexAttrib4Nubv"); glad_glVertexAttrib4Nuiv = (PFNGLVERTEXATTRIB4NUIVPROC)load("glVertexAttrib4Nuiv"); glad_glVertexAttrib4Nusv = (PFNGLVERTEXATTRIB4NUSVPROC)load("glVertexAttrib4Nusv"); glad_glVertexAttrib4bv = (PFNGLVERTEXATTRIB4BVPROC)load("glVertexAttrib4bv"); glad_glVertexAttrib4d = (PFNGLVERTEXATTRIB4DPROC)load("glVertexAttrib4d"); glad_glVertexAttrib4dv = (PFNGLVERTEXATTRIB4DVPROC)load("glVertexAttrib4dv"); glad_glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)load("glVertexAttrib4f"); glad_glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)load("glVertexAttrib4fv"); glad_glVertexAttrib4iv = (PFNGLVERTEXATTRIB4IVPROC)load("glVertexAttrib4iv"); glad_glVertexAttrib4s = (PFNGLVERTEXATTRIB4SPROC)load("glVertexAttrib4s"); glad_glVertexAttrib4sv = (PFNGLVERTEXATTRIB4SVPROC)load("glVertexAttrib4sv"); glad_glVertexAttrib4ubv = (PFNGLVERTEXATTRIB4UBVPROC)load("glVertexAttrib4ubv"); glad_glVertexAttrib4uiv = (PFNGLVERTEXATTRIB4UIVPROC)load("glVertexAttrib4uiv"); glad_glVertexAttrib4usv = (PFNGLVERTEXATTRIB4USVPROC)load("glVertexAttrib4usv"); glad_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)load("glVertexAttribPointer"); } static void load_GL_VERSION_2_1(GLADloadproc load) { if(!GLAD_GL_VERSION_2_1) return; glad_glUniformMatrix2x3fv = (PFNGLUNIFORMMATRIX2X3FVPROC)load("glUniformMatrix2x3fv"); glad_glUniformMatrix3x2fv = (PFNGLUNIFORMMATRIX3X2FVPROC)load("glUniformMatrix3x2fv"); glad_glUniformMatrix2x4fv = (PFNGLUNIFORMMATRIX2X4FVPROC)load("glUniformMatrix2x4fv"); glad_glUniformMatrix4x2fv = (PFNGLUNIFORMMATRIX4X2FVPROC)load("glUniformMatrix4x2fv"); glad_glUniformMatrix3x4fv = (PFNGLUNIFORMMATRIX3X4FVPROC)load("glUniformMatrix3x4fv"); glad_glUniformMatrix4x3fv = (PFNGLUNIFORMMATRIX4X3FVPROC)load("glUniformMatrix4x3fv"); } static void load_GL_VERSION_3_0(GLADloadproc load) { if(!GLAD_GL_VERSION_3_0) return; glad_glColorMaski = (PFNGLCOLORMASKIPROC)load("glColorMaski"); glad_glGetBooleani_v = (PFNGLGETBOOLEANI_VPROC)load("glGetBooleani_v"); glad_glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)load("glGetIntegeri_v"); glad_glEnablei = (PFNGLENABLEIPROC)load("glEnablei"); glad_glDisablei = (PFNGLDISABLEIPROC)load("glDisablei"); glad_glIsEnabledi = (PFNGLISENABLEDIPROC)load("glIsEnabledi"); glad_glBeginTransformFeedback = (PFNGLBEGINTRANSFORMFEEDBACKPROC)load("glBeginTransformFeedback"); glad_glEndTransformFeedback = (PFNGLENDTRANSFORMFEEDBACKPROC)load("glEndTransformFeedback"); glad_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)load("glBindBufferRange"); glad_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)load("glBindBufferBase"); glad_glTransformFeedbackVaryings = (PFNGLTRANSFORMFEEDBACKVARYINGSPROC)load("glTransformFeedbackVaryings"); glad_glGetTransformFeedbackVarying = (PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)load("glGetTransformFeedbackVarying"); glad_glClampColor = (PFNGLCLAMPCOLORPROC)load("glClampColor"); glad_glBeginConditionalRender = (PFNGLBEGINCONDITIONALRENDERPROC)load("glBeginConditionalRender"); glad_glEndConditionalRender = (PFNGLENDCONDITIONALRENDERPROC)load("glEndConditionalRender"); glad_glVertexAttribIPointer = (PFNGLVERTEXATTRIBIPOINTERPROC)load("glVertexAttribIPointer"); glad_glGetVertexAttribIiv = (PFNGLGETVERTEXATTRIBIIVPROC)load("glGetVertexAttribIiv"); glad_glGetVertexAttribIuiv = (PFNGLGETVERTEXATTRIBIUIVPROC)load("glGetVertexAttribIuiv"); glad_glVertexAttribI1i = (PFNGLVERTEXATTRIBI1IPROC)load("glVertexAttribI1i"); glad_glVertexAttribI2i = (PFNGLVERTEXATTRIBI2IPROC)load("glVertexAttribI2i"); glad_glVertexAttribI3i = (PFNGLVERTEXATTRIBI3IPROC)load("glVertexAttribI3i"); glad_glVertexAttribI4i = (PFNGLVERTEXATTRIBI4IPROC)load("glVertexAttribI4i"); glad_glVertexAttribI1ui = (PFNGLVERTEXATTRIBI1UIPROC)load("glVertexAttribI1ui"); glad_glVertexAttribI2ui = (PFNGLVERTEXATTRIBI2UIPROC)load("glVertexAttribI2ui"); glad_glVertexAttribI3ui = (PFNGLVERTEXATTRIBI3UIPROC)load("glVertexAttribI3ui"); glad_glVertexAttribI4ui = (PFNGLVERTEXATTRIBI4UIPROC)load("glVertexAttribI4ui"); glad_glVertexAttribI1iv = (PFNGLVERTEXATTRIBI1IVPROC)load("glVertexAttribI1iv"); glad_glVertexAttribI2iv = (PFNGLVERTEXATTRIBI2IVPROC)load("glVertexAttribI2iv"); glad_glVertexAttribI3iv = (PFNGLVERTEXATTRIBI3IVPROC)load("glVertexAttribI3iv"); glad_glVertexAttribI4iv = (PFNGLVERTEXATTRIBI4IVPROC)load("glVertexAttribI4iv"); glad_glVertexAttribI1uiv = (PFNGLVERTEXATTRIBI1UIVPROC)load("glVertexAttribI1uiv"); glad_glVertexAttribI2uiv = (PFNGLVERTEXATTRIBI2UIVPROC)load("glVertexAttribI2uiv"); glad_glVertexAttribI3uiv = (PFNGLVERTEXATTRIBI3UIVPROC)load("glVertexAttribI3uiv"); glad_glVertexAttribI4uiv = (PFNGLVERTEXATTRIBI4UIVPROC)load("glVertexAttribI4uiv"); glad_glVertexAttribI4bv = (PFNGLVERTEXATTRIBI4BVPROC)load("glVertexAttribI4bv"); glad_glVertexAttribI4sv = (PFNGLVERTEXATTRIBI4SVPROC)load("glVertexAttribI4sv"); glad_glVertexAttribI4ubv = (PFNGLVERTEXATTRIBI4UBVPROC)load("glVertexAttribI4ubv"); glad_glVertexAttribI4usv = (PFNGLVERTEXATTRIBI4USVPROC)load("glVertexAttribI4usv"); glad_glGetUniformuiv = (PFNGLGETUNIFORMUIVPROC)load("glGetUniformuiv"); glad_glBindFragDataLocation = (PFNGLBINDFRAGDATALOCATIONPROC)load("glBindFragDataLocation"); glad_glGetFragDataLocation = (PFNGLGETFRAGDATALOCATIONPROC)load("glGetFragDataLocation"); glad_glUniform1ui = (PFNGLUNIFORM1UIPROC)load("glUniform1ui"); glad_glUniform2ui = (PFNGLUNIFORM2UIPROC)load("glUniform2ui"); glad_glUniform3ui = (PFNGLUNIFORM3UIPROC)load("glUniform3ui"); glad_glUniform4ui = (PFNGLUNIFORM4UIPROC)load("glUniform4ui"); glad_glUniform1uiv = (PFNGLUNIFORM1UIVPROC)load("glUniform1uiv"); glad_glUniform2uiv = (PFNGLUNIFORM2UIVPROC)load("glUniform2uiv"); glad_glUniform3uiv = (PFNGLUNIFORM3UIVPROC)load("glUniform3uiv"); glad_glUniform4uiv = (PFNGLUNIFORM4UIVPROC)load("glUniform4uiv"); glad_glTexParameterIiv = (PFNGLTEXPARAMETERIIVPROC)load("glTexParameterIiv"); glad_glTexParameterIuiv = (PFNGLTEXPARAMETERIUIVPROC)load("glTexParameterIuiv"); glad_glGetTexParameterIiv = (PFNGLGETTEXPARAMETERIIVPROC)load("glGetTexParameterIiv"); glad_glGetTexParameterIuiv = (PFNGLGETTEXPARAMETERIUIVPROC)load("glGetTexParameterIuiv"); glad_glClearBufferiv = (PFNGLCLEARBUFFERIVPROC)load("glClearBufferiv"); glad_glClearBufferuiv = (PFNGLCLEARBUFFERUIVPROC)load("glClearBufferuiv"); glad_glClearBufferfv = (PFNGLCLEARBUFFERFVPROC)load("glClearBufferfv"); glad_glClearBufferfi = (PFNGLCLEARBUFFERFIPROC)load("glClearBufferfi"); glad_glGetStringi = (PFNGLGETSTRINGIPROC)load("glGetStringi"); glad_glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)load("glIsRenderbuffer"); glad_glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)load("glBindRenderbuffer"); glad_glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)load("glDeleteRenderbuffers"); glad_glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)load("glGenRenderbuffers"); glad_glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)load("glRenderbufferStorage"); glad_glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)load("glGetRenderbufferParameteriv"); glad_glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)load("glIsFramebuffer"); glad_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)load("glBindFramebuffer"); glad_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)load("glDeleteFramebuffers"); glad_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)load("glGenFramebuffers"); glad_glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)load("glCheckFramebufferStatus"); glad_glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)load("glFramebufferTexture1D"); glad_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)load("glFramebufferTexture2D"); glad_glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)load("glFramebufferTexture3D"); glad_glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)load("glFramebufferRenderbuffer"); glad_glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)load("glGetFramebufferAttachmentParameteriv"); glad_glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)load("glGenerateMipmap"); glad_glBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)load("glBlitFramebuffer"); glad_glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)load("glRenderbufferStorageMultisample"); glad_glFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC)load("glFramebufferTextureLayer"); glad_glMapBufferRange = (PFNGLMAPBUFFERRANGEPROC)load("glMapBufferRange"); glad_glFlushMappedBufferRange = (PFNGLFLUSHMAPPEDBUFFERRANGEPROC)load("glFlushMappedBufferRange"); glad_glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)load("glBindVertexArray"); glad_glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)load("glDeleteVertexArrays"); glad_glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)load("glGenVertexArrays"); glad_glIsVertexArray = (PFNGLISVERTEXARRAYPROC)load("glIsVertexArray"); } static void load_GL_VERSION_3_1(GLADloadproc load) { if(!GLAD_GL_VERSION_3_1) return; glad_glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDPROC)load("glDrawArraysInstanced"); glad_glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDPROC)load("glDrawElementsInstanced"); glad_glTexBuffer = (PFNGLTEXBUFFERPROC)load("glTexBuffer"); glad_glPrimitiveRestartIndex = (PFNGLPRIMITIVERESTARTINDEXPROC)load("glPrimitiveRestartIndex"); glad_glCopyBufferSubData = (PFNGLCOPYBUFFERSUBDATAPROC)load("glCopyBufferSubData"); glad_glGetUniformIndices = (PFNGLGETUNIFORMINDICESPROC)load("glGetUniformIndices"); glad_glGetActiveUniformsiv = (PFNGLGETACTIVEUNIFORMSIVPROC)load("glGetActiveUniformsiv"); glad_glGetActiveUniformName = (PFNGLGETACTIVEUNIFORMNAMEPROC)load("glGetActiveUniformName"); glad_glGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC)load("glGetUniformBlockIndex"); glad_glGetActiveUniformBlockiv = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC)load("glGetActiveUniformBlockiv"); glad_glGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)load("glGetActiveUniformBlockName"); glad_glUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC)load("glUniformBlockBinding"); glad_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)load("glBindBufferRange"); glad_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)load("glBindBufferBase"); glad_glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)load("glGetIntegeri_v"); } static void load_GL_VERSION_3_2(GLADloadproc load) { if(!GLAD_GL_VERSION_3_2) return; glad_glDrawElementsBaseVertex = (PFNGLDRAWELEMENTSBASEVERTEXPROC)load("glDrawElementsBaseVertex"); glad_glDrawRangeElementsBaseVertex = (PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)load("glDrawRangeElementsBaseVertex"); glad_glDrawElementsInstancedBaseVertex = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)load("glDrawElementsInstancedBaseVertex"); glad_glMultiDrawElementsBaseVertex = (PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)load("glMultiDrawElementsBaseVertex"); glad_glProvokingVertex = (PFNGLPROVOKINGVERTEXPROC)load("glProvokingVertex"); glad_glFenceSync = (PFNGLFENCESYNCPROC)load("glFenceSync"); glad_glIsSync = (PFNGLISSYNCPROC)load("glIsSync"); glad_glDeleteSync = (PFNGLDELETESYNCPROC)load("glDeleteSync"); glad_glClientWaitSync = (PFNGLCLIENTWAITSYNCPROC)load("glClientWaitSync"); glad_glWaitSync = (PFNGLWAITSYNCPROC)load("glWaitSync"); glad_glGetInteger64v = (PFNGLGETINTEGER64VPROC)load("glGetInteger64v"); glad_glGetSynciv = (PFNGLGETSYNCIVPROC)load("glGetSynciv"); glad_glGetInteger64i_v = (PFNGLGETINTEGER64I_VPROC)load("glGetInteger64i_v"); glad_glGetBufferParameteri64v = (PFNGLGETBUFFERPARAMETERI64VPROC)load("glGetBufferParameteri64v"); glad_glFramebufferTexture = (PFNGLFRAMEBUFFERTEXTUREPROC)load("glFramebufferTexture"); glad_glTexImage2DMultisample = (PFNGLTEXIMAGE2DMULTISAMPLEPROC)load("glTexImage2DMultisample"); glad_glTexImage3DMultisample = (PFNGLTEXIMAGE3DMULTISAMPLEPROC)load("glTexImage3DMultisample"); glad_glGetMultisamplefv = (PFNGLGETMULTISAMPLEFVPROC)load("glGetMultisamplefv"); glad_glSampleMaski = (PFNGLSAMPLEMASKIPROC)load("glSampleMaski"); } static void load_GL_VERSION_3_3(GLADloadproc load) { if(!GLAD_GL_VERSION_3_3) return; glad_glBindFragDataLocationIndexed = (PFNGLBINDFRAGDATALOCATIONINDEXEDPROC)load("glBindFragDataLocationIndexed"); glad_glGetFragDataIndex = (PFNGLGETFRAGDATAINDEXPROC)load("glGetFragDataIndex"); glad_glGenSamplers = (PFNGLGENSAMPLERSPROC)load("glGenSamplers"); glad_glDeleteSamplers = (PFNGLDELETESAMPLERSPROC)load("glDeleteSamplers"); glad_glIsSampler = (PFNGLISSAMPLERPROC)load("glIsSampler"); glad_glBindSampler = (PFNGLBINDSAMPLERPROC)load("glBindSampler"); glad_glSamplerParameteri = (PFNGLSAMPLERPARAMETERIPROC)load("glSamplerParameteri"); glad_glSamplerParameteriv = (PFNGLSAMPLERPARAMETERIVPROC)load("glSamplerParameteriv"); glad_glSamplerParameterf = (PFNGLSAMPLERPARAMETERFPROC)load("glSamplerParameterf"); glad_glSamplerParameterfv = (PFNGLSAMPLERPARAMETERFVPROC)load("glSamplerParameterfv"); glad_glSamplerParameterIiv = (PFNGLSAMPLERPARAMETERIIVPROC)load("glSamplerParameterIiv"); glad_glSamplerParameterIuiv = (PFNGLSAMPLERPARAMETERIUIVPROC)load("glSamplerParameterIuiv"); glad_glGetSamplerParameteriv = (PFNGLGETSAMPLERPARAMETERIVPROC)load("glGetSamplerParameteriv"); glad_glGetSamplerParameterIiv = (PFNGLGETSAMPLERPARAMETERIIVPROC)load("glGetSamplerParameterIiv"); glad_glGetSamplerParameterfv = (PFNGLGETSAMPLERPARAMETERFVPROC)load("glGetSamplerParameterfv"); glad_glGetSamplerParameterIuiv = (PFNGLGETSAMPLERPARAMETERIUIVPROC)load("glGetSamplerParameterIuiv"); glad_glQueryCounter = (PFNGLQUERYCOUNTERPROC)load("glQueryCounter"); glad_glGetQueryObjecti64v = (PFNGLGETQUERYOBJECTI64VPROC)load("glGetQueryObjecti64v"); glad_glGetQueryObjectui64v = (PFNGLGETQUERYOBJECTUI64VPROC)load("glGetQueryObjectui64v"); glad_glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISORPROC)load("glVertexAttribDivisor"); glad_glVertexAttribP1ui = (PFNGLVERTEXATTRIBP1UIPROC)load("glVertexAttribP1ui"); glad_glVertexAttribP1uiv = (PFNGLVERTEXATTRIBP1UIVPROC)load("glVertexAttribP1uiv"); glad_glVertexAttribP2ui = (PFNGLVERTEXATTRIBP2UIPROC)load("glVertexAttribP2ui"); glad_glVertexAttribP2uiv = (PFNGLVERTEXATTRIBP2UIVPROC)load("glVertexAttribP2uiv"); glad_glVertexAttribP3ui = (PFNGLVERTEXATTRIBP3UIPROC)load("glVertexAttribP3ui"); glad_glVertexAttribP3uiv = (PFNGLVERTEXATTRIBP3UIVPROC)load("glVertexAttribP3uiv"); glad_glVertexAttribP4ui = (PFNGLVERTEXATTRIBP4UIPROC)load("glVertexAttribP4ui"); glad_glVertexAttribP4uiv = (PFNGLVERTEXATTRIBP4UIVPROC)load("glVertexAttribP4uiv"); glad_glVertexP2ui = (PFNGLVERTEXP2UIPROC)load("glVertexP2ui"); glad_glVertexP2uiv = (PFNGLVERTEXP2UIVPROC)load("glVertexP2uiv"); glad_glVertexP3ui = (PFNGLVERTEXP3UIPROC)load("glVertexP3ui"); glad_glVertexP3uiv = (PFNGLVERTEXP3UIVPROC)load("glVertexP3uiv"); glad_glVertexP4ui = (PFNGLVERTEXP4UIPROC)load("glVertexP4ui"); glad_glVertexP4uiv = (PFNGLVERTEXP4UIVPROC)load("glVertexP4uiv"); glad_glTexCoordP1ui = (PFNGLTEXCOORDP1UIPROC)load("glTexCoordP1ui"); glad_glTexCoordP1uiv = (PFNGLTEXCOORDP1UIVPROC)load("glTexCoordP1uiv"); glad_glTexCoordP2ui = (PFNGLTEXCOORDP2UIPROC)load("glTexCoordP2ui"); glad_glTexCoordP2uiv = (PFNGLTEXCOORDP2UIVPROC)load("glTexCoordP2uiv"); glad_glTexCoordP3ui = (PFNGLTEXCOORDP3UIPROC)load("glTexCoordP3ui"); glad_glTexCoordP3uiv = (PFNGLTEXCOORDP3UIVPROC)load("glTexCoordP3uiv"); glad_glTexCoordP4ui = (PFNGLTEXCOORDP4UIPROC)load("glTexCoordP4ui"); glad_glTexCoordP4uiv = (PFNGLTEXCOORDP4UIVPROC)load("glTexCoordP4uiv"); glad_glMultiTexCoordP1ui = (PFNGLMULTITEXCOORDP1UIPROC)load("glMultiTexCoordP1ui"); glad_glMultiTexCoordP1uiv = (PFNGLMULTITEXCOORDP1UIVPROC)load("glMultiTexCoordP1uiv"); glad_glMultiTexCoordP2ui = (PFNGLMULTITEXCOORDP2UIPROC)load("glMultiTexCoordP2ui"); glad_glMultiTexCoordP2uiv = (PFNGLMULTITEXCOORDP2UIVPROC)load("glMultiTexCoordP2uiv"); glad_glMultiTexCoordP3ui = (PFNGLMULTITEXCOORDP3UIPROC)load("glMultiTexCoordP3ui"); glad_glMultiTexCoordP3uiv = (PFNGLMULTITEXCOORDP3UIVPROC)load("glMultiTexCoordP3uiv"); glad_glMultiTexCoordP4ui = (PFNGLMULTITEXCOORDP4UIPROC)load("glMultiTexCoordP4ui"); glad_glMultiTexCoordP4uiv = (PFNGLMULTITEXCOORDP4UIVPROC)load("glMultiTexCoordP4uiv"); glad_glNormalP3ui = (PFNGLNORMALP3UIPROC)load("glNormalP3ui"); glad_glNormalP3uiv = (PFNGLNORMALP3UIVPROC)load("glNormalP3uiv"); glad_glColorP3ui = (PFNGLCOLORP3UIPROC)load("glColorP3ui"); glad_glColorP3uiv = (PFNGLCOLORP3UIVPROC)load("glColorP3uiv"); glad_glColorP4ui = (PFNGLCOLORP4UIPROC)load("glColorP4ui"); glad_glColorP4uiv = (PFNGLCOLORP4UIVPROC)load("glColorP4uiv"); glad_glSecondaryColorP3ui = (PFNGLSECONDARYCOLORP3UIPROC)load("glSecondaryColorP3ui"); glad_glSecondaryColorP3uiv = (PFNGLSECONDARYCOLORP3UIVPROC)load("glSecondaryColorP3uiv"); } static void load_GL_VERSION_4_0(GLADloadproc load) { if(!GLAD_GL_VERSION_4_0) return; glad_glMinSampleShading = (PFNGLMINSAMPLESHADINGPROC)load("glMinSampleShading"); glad_glBlendEquationi = (PFNGLBLENDEQUATIONIPROC)load("glBlendEquationi"); glad_glBlendEquationSeparatei = (PFNGLBLENDEQUATIONSEPARATEIPROC)load("glBlendEquationSeparatei"); glad_glBlendFunci = (PFNGLBLENDFUNCIPROC)load("glBlendFunci"); glad_glBlendFuncSeparatei = (PFNGLBLENDFUNCSEPARATEIPROC)load("glBlendFuncSeparatei"); glad_glDrawArraysIndirect = (PFNGLDRAWARRAYSINDIRECTPROC)load("glDrawArraysIndirect"); glad_glDrawElementsIndirect = (PFNGLDRAWELEMENTSINDIRECTPROC)load("glDrawElementsIndirect"); glad_glUniform1d = (PFNGLUNIFORM1DPROC)load("glUniform1d"); glad_glUniform2d = (PFNGLUNIFORM2DPROC)load("glUniform2d"); glad_glUniform3d = (PFNGLUNIFORM3DPROC)load("glUniform3d"); glad_glUniform4d = (PFNGLUNIFORM4DPROC)load("glUniform4d"); glad_glUniform1dv = (PFNGLUNIFORM1DVPROC)load("glUniform1dv"); glad_glUniform2dv = (PFNGLUNIFORM2DVPROC)load("glUniform2dv"); glad_glUniform3dv = (PFNGLUNIFORM3DVPROC)load("glUniform3dv"); glad_glUniform4dv = (PFNGLUNIFORM4DVPROC)load("glUniform4dv"); glad_glUniformMatrix2dv = (PFNGLUNIFORMMATRIX2DVPROC)load("glUniformMatrix2dv"); glad_glUniformMatrix3dv = (PFNGLUNIFORMMATRIX3DVPROC)load("glUniformMatrix3dv"); glad_glUniformMatrix4dv = (PFNGLUNIFORMMATRIX4DVPROC)load("glUniformMatrix4dv"); glad_glUniformMatrix2x3dv = (PFNGLUNIFORMMATRIX2X3DVPROC)load("glUniformMatrix2x3dv"); glad_glUniformMatrix2x4dv = (PFNGLUNIFORMMATRIX2X4DVPROC)load("glUniformMatrix2x4dv"); glad_glUniformMatrix3x2dv = (PFNGLUNIFORMMATRIX3X2DVPROC)load("glUniformMatrix3x2dv"); glad_glUniformMatrix3x4dv = (PFNGLUNIFORMMATRIX3X4DVPROC)load("glUniformMatrix3x4dv"); glad_glUniformMatrix4x2dv = (PFNGLUNIFORMMATRIX4X2DVPROC)load("glUniformMatrix4x2dv"); glad_glUniformMatrix4x3dv = (PFNGLUNIFORMMATRIX4X3DVPROC)load("glUniformMatrix4x3dv"); glad_glGetUniformdv = (PFNGLGETUNIFORMDVPROC)load("glGetUniformdv"); glad_glGetSubroutineUniformLocation = (PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC)load("glGetSubroutineUniformLocation"); glad_glGetSubroutineIndex = (PFNGLGETSUBROUTINEINDEXPROC)load("glGetSubroutineIndex"); glad_glGetActiveSubroutineUniformiv = (PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC)load("glGetActiveSubroutineUniformiv"); glad_glGetActiveSubroutineUniformName = (PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC)load("glGetActiveSubroutineUniformName"); glad_glGetActiveSubroutineName = (PFNGLGETACTIVESUBROUTINENAMEPROC)load("glGetActiveSubroutineName"); glad_glUniformSubroutinesuiv = (PFNGLUNIFORMSUBROUTINESUIVPROC)load("glUniformSubroutinesuiv"); glad_glGetUniformSubroutineuiv = (PFNGLGETUNIFORMSUBROUTINEUIVPROC)load("glGetUniformSubroutineuiv"); glad_glGetProgramStageiv = (PFNGLGETPROGRAMSTAGEIVPROC)load("glGetProgramStageiv"); glad_glPatchParameteri = (PFNGLPATCHPARAMETERIPROC)load("glPatchParameteri"); glad_glPatchParameterfv = (PFNGLPATCHPARAMETERFVPROC)load("glPatchParameterfv"); glad_glBindTransformFeedback = (PFNGLBINDTRANSFORMFEEDBACKPROC)load("glBindTransformFeedback"); glad_glDeleteTransformFeedbacks = (PFNGLDELETETRANSFORMFEEDBACKSPROC)load("glDeleteTransformFeedbacks"); glad_glGenTransformFeedbacks = (PFNGLGENTRANSFORMFEEDBACKSPROC)load("glGenTransformFeedbacks"); glad_glIsTransformFeedback = (PFNGLISTRANSFORMFEEDBACKPROC)load("glIsTransformFeedback"); glad_glPauseTransformFeedback = (PFNGLPAUSETRANSFORMFEEDBACKPROC)load("glPauseTransformFeedback"); glad_glResumeTransformFeedback = (PFNGLRESUMETRANSFORMFEEDBACKPROC)load("glResumeTransformFeedback"); glad_glDrawTransformFeedback = (PFNGLDRAWTRANSFORMFEEDBACKPROC)load("glDrawTransformFeedback"); glad_glDrawTransformFeedbackStream = (PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC)load("glDrawTransformFeedbackStream"); glad_glBeginQueryIndexed = (PFNGLBEGINQUERYINDEXEDPROC)load("glBeginQueryIndexed"); glad_glEndQueryIndexed = (PFNGLENDQUERYINDEXEDPROC)load("glEndQueryIndexed"); glad_glGetQueryIndexediv = (PFNGLGETQUERYINDEXEDIVPROC)load("glGetQueryIndexediv"); } static void load_GL_VERSION_4_1(GLADloadproc load) { if(!GLAD_GL_VERSION_4_1) return; glad_glReleaseShaderCompiler = (PFNGLRELEASESHADERCOMPILERPROC)load("glReleaseShaderCompiler"); glad_glShaderBinary = (PFNGLSHADERBINARYPROC)load("glShaderBinary"); glad_glGetShaderPrecisionFormat = (PFNGLGETSHADERPRECISIONFORMATPROC)load("glGetShaderPrecisionFormat"); glad_glDepthRangef = (PFNGLDEPTHRANGEFPROC)load("glDepthRangef"); glad_glClearDepthf = (PFNGLCLEARDEPTHFPROC)load("glClearDepthf"); glad_glGetProgramBinary = (PFNGLGETPROGRAMBINARYPROC)load("glGetProgramBinary"); glad_glProgramBinary = (PFNGLPROGRAMBINARYPROC)load("glProgramBinary"); glad_glProgramParameteri = (PFNGLPROGRAMPARAMETERIPROC)load("glProgramParameteri"); glad_glUseProgramStages = (PFNGLUSEPROGRAMSTAGESPROC)load("glUseProgramStages"); glad_glActiveShaderProgram = (PFNGLACTIVESHADERPROGRAMPROC)load("glActiveShaderProgram"); glad_glCreateShaderProgramv = (PFNGLCREATESHADERPROGRAMVPROC)load("glCreateShaderProgramv"); glad_glBindProgramPipeline = (PFNGLBINDPROGRAMPIPELINEPROC)load("glBindProgramPipeline"); glad_glDeleteProgramPipelines = (PFNGLDELETEPROGRAMPIPELINESPROC)load("glDeleteProgramPipelines"); glad_glGenProgramPipelines = (PFNGLGENPROGRAMPIPELINESPROC)load("glGenProgramPipelines"); glad_glIsProgramPipeline = (PFNGLISPROGRAMPIPELINEPROC)load("glIsProgramPipeline"); glad_glGetProgramPipelineiv = (PFNGLGETPROGRAMPIPELINEIVPROC)load("glGetProgramPipelineiv"); glad_glProgramParameteri = (PFNGLPROGRAMPARAMETERIPROC)load("glProgramParameteri"); glad_glProgramUniform1i = (PFNGLPROGRAMUNIFORM1IPROC)load("glProgramUniform1i"); glad_glProgramUniform1iv = (PFNGLPROGRAMUNIFORM1IVPROC)load("glProgramUniform1iv"); glad_glProgramUniform1f = (PFNGLPROGRAMUNIFORM1FPROC)load("glProgramUniform1f"); glad_glProgramUniform1fv = (PFNGLPROGRAMUNIFORM1FVPROC)load("glProgramUniform1fv"); glad_glProgramUniform1d = (PFNGLPROGRAMUNIFORM1DPROC)load("glProgramUniform1d"); glad_glProgramUniform1dv = (PFNGLPROGRAMUNIFORM1DVPROC)load("glProgramUniform1dv"); glad_glProgramUniform1ui = (PFNGLPROGRAMUNIFORM1UIPROC)load("glProgramUniform1ui"); glad_glProgramUniform1uiv = (PFNGLPROGRAMUNIFORM1UIVPROC)load("glProgramUniform1uiv"); glad_glProgramUniform2i = (PFNGLPROGRAMUNIFORM2IPROC)load("glProgramUniform2i"); glad_glProgramUniform2iv = (PFNGLPROGRAMUNIFORM2IVPROC)load("glProgramUniform2iv"); glad_glProgramUniform2f = (PFNGLPROGRAMUNIFORM2FPROC)load("glProgramUniform2f"); glad_glProgramUniform2fv = (PFNGLPROGRAMUNIFORM2FVPROC)load("glProgramUniform2fv"); glad_glProgramUniform2d = (PFNGLPROGRAMUNIFORM2DPROC)load("glProgramUniform2d"); glad_glProgramUniform2dv = (PFNGLPROGRAMUNIFORM2DVPROC)load("glProgramUniform2dv"); glad_glProgramUniform2ui = (PFNGLPROGRAMUNIFORM2UIPROC)load("glProgramUniform2ui"); glad_glProgramUniform2uiv = (PFNGLPROGRAMUNIFORM2UIVPROC)load("glProgramUniform2uiv"); glad_glProgramUniform3i = (PFNGLPROGRAMUNIFORM3IPROC)load("glProgramUniform3i"); glad_glProgramUniform3iv = (PFNGLPROGRAMUNIFORM3IVPROC)load("glProgramUniform3iv"); glad_glProgramUniform3f = (PFNGLPROGRAMUNIFORM3FPROC)load("glProgramUniform3f"); glad_glProgramUniform3fv = (PFNGLPROGRAMUNIFORM3FVPROC)load("glProgramUniform3fv"); glad_glProgramUniform3d = (PFNGLPROGRAMUNIFORM3DPROC)load("glProgramUniform3d"); glad_glProgramUniform3dv = (PFNGLPROGRAMUNIFORM3DVPROC)load("glProgramUniform3dv"); glad_glProgramUniform3ui = (PFNGLPROGRAMUNIFORM3UIPROC)load("glProgramUniform3ui"); glad_glProgramUniform3uiv = (PFNGLPROGRAMUNIFORM3UIVPROC)load("glProgramUniform3uiv"); glad_glProgramUniform4i = (PFNGLPROGRAMUNIFORM4IPROC)load("glProgramUniform4i"); glad_glProgramUniform4iv = (PFNGLPROGRAMUNIFORM4IVPROC)load("glProgramUniform4iv"); glad_glProgramUniform4f = (PFNGLPROGRAMUNIFORM4FPROC)load("glProgramUniform4f"); glad_glProgramUniform4fv = (PFNGLPROGRAMUNIFORM4FVPROC)load("glProgramUniform4fv"); glad_glProgramUniform4d = (PFNGLPROGRAMUNIFORM4DPROC)load("glProgramUniform4d"); glad_glProgramUniform4dv = (PFNGLPROGRAMUNIFORM4DVPROC)load("glProgramUniform4dv"); glad_glProgramUniform4ui = (PFNGLPROGRAMUNIFORM4UIPROC)load("glProgramUniform4ui"); glad_glProgramUniform4uiv = (PFNGLPROGRAMUNIFORM4UIVPROC)load("glProgramUniform4uiv"); glad_glProgramUniformMatrix2fv = (PFNGLPROGRAMUNIFORMMATRIX2FVPROC)load("glProgramUniformMatrix2fv"); glad_glProgramUniformMatrix3fv = (PFNGLPROGRAMUNIFORMMATRIX3FVPROC)load("glProgramUniformMatrix3fv"); glad_glProgramUniformMatrix4fv = (PFNGLPROGRAMUNIFORMMATRIX4FVPROC)load("glProgramUniformMatrix4fv"); glad_glProgramUniformMatrix2dv = (PFNGLPROGRAMUNIFORMMATRIX2DVPROC)load("glProgramUniformMatrix2dv"); glad_glProgramUniformMatrix3dv = (PFNGLPROGRAMUNIFORMMATRIX3DVPROC)load("glProgramUniformMatrix3dv"); glad_glProgramUniformMatrix4dv = (PFNGLPROGRAMUNIFORMMATRIX4DVPROC)load("glProgramUniformMatrix4dv"); glad_glProgramUniformMatrix2x3fv = (PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC)load("glProgramUniformMatrix2x3fv"); glad_glProgramUniformMatrix3x2fv = (PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC)load("glProgramUniformMatrix3x2fv"); glad_glProgramUniformMatrix2x4fv = (PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC)load("glProgramUniformMatrix2x4fv"); glad_glProgramUniformMatrix4x2fv = (PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC)load("glProgramUniformMatrix4x2fv"); glad_glProgramUniformMatrix3x4fv = (PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC)load("glProgramUniformMatrix3x4fv"); glad_glProgramUniformMatrix4x3fv = (PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC)load("glProgramUniformMatrix4x3fv"); glad_glProgramUniformMatrix2x3dv = (PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC)load("glProgramUniformMatrix2x3dv"); glad_glProgramUniformMatrix3x2dv = (PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC)load("glProgramUniformMatrix3x2dv"); glad_glProgramUniformMatrix2x4dv = (PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC)load("glProgramUniformMatrix2x4dv"); glad_glProgramUniformMatrix4x2dv = (PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC)load("glProgramUniformMatrix4x2dv"); glad_glProgramUniformMatrix3x4dv = (PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC)load("glProgramUniformMatrix3x4dv"); glad_glProgramUniformMatrix4x3dv = (PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC)load("glProgramUniformMatrix4x3dv"); glad_glValidateProgramPipeline = (PFNGLVALIDATEPROGRAMPIPELINEPROC)load("glValidateProgramPipeline"); glad_glGetProgramPipelineInfoLog = (PFNGLGETPROGRAMPIPELINEINFOLOGPROC)load("glGetProgramPipelineInfoLog"); glad_glVertexAttribL1d = (PFNGLVERTEXATTRIBL1DPROC)load("glVertexAttribL1d"); glad_glVertexAttribL2d = (PFNGLVERTEXATTRIBL2DPROC)load("glVertexAttribL2d"); glad_glVertexAttribL3d = (PFNGLVERTEXATTRIBL3DPROC)load("glVertexAttribL3d"); glad_glVertexAttribL4d = (PFNGLVERTEXATTRIBL4DPROC)load("glVertexAttribL4d"); glad_glVertexAttribL1dv = (PFNGLVERTEXATTRIBL1DVPROC)load("glVertexAttribL1dv"); glad_glVertexAttribL2dv = (PFNGLVERTEXATTRIBL2DVPROC)load("glVertexAttribL2dv"); glad_glVertexAttribL3dv = (PFNGLVERTEXATTRIBL3DVPROC)load("glVertexAttribL3dv"); glad_glVertexAttribL4dv = (PFNGLVERTEXATTRIBL4DVPROC)load("glVertexAttribL4dv"); glad_glVertexAttribLPointer = (PFNGLVERTEXATTRIBLPOINTERPROC)load("glVertexAttribLPointer"); glad_glGetVertexAttribLdv = (PFNGLGETVERTEXATTRIBLDVPROC)load("glGetVertexAttribLdv"); glad_glViewportArrayv = (PFNGLVIEWPORTARRAYVPROC)load("glViewportArrayv"); glad_glViewportIndexedf = (PFNGLVIEWPORTINDEXEDFPROC)load("glViewportIndexedf"); glad_glViewportIndexedfv = (PFNGLVIEWPORTINDEXEDFVPROC)load("glViewportIndexedfv"); glad_glScissorArrayv = (PFNGLSCISSORARRAYVPROC)load("glScissorArrayv"); glad_glScissorIndexed = (PFNGLSCISSORINDEXEDPROC)load("glScissorIndexed"); glad_glScissorIndexedv = (PFNGLSCISSORINDEXEDVPROC)load("glScissorIndexedv"); glad_glDepthRangeArrayv = (PFNGLDEPTHRANGEARRAYVPROC)load("glDepthRangeArrayv"); glad_glDepthRangeIndexed = (PFNGLDEPTHRANGEINDEXEDPROC)load("glDepthRangeIndexed"); glad_glGetFloati_v = (PFNGLGETFLOATI_VPROC)load("glGetFloati_v"); glad_glGetDoublei_v = (PFNGLGETDOUBLEI_VPROC)load("glGetDoublei_v"); } static void load_GL_VERSION_4_2(GLADloadproc load) { if(!GLAD_GL_VERSION_4_2) return; glad_glDrawArraysInstancedBaseInstance = (PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC)load("glDrawArraysInstancedBaseInstance"); glad_glDrawElementsInstancedBaseInstance = (PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC)load("glDrawElementsInstancedBaseInstance"); glad_glDrawElementsInstancedBaseVertexBaseInstance = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC)load("glDrawElementsInstancedBaseVertexBaseInstance"); glad_glGetInternalformativ = (PFNGLGETINTERNALFORMATIVPROC)load("glGetInternalformativ"); glad_glGetActiveAtomicCounterBufferiv = (PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC)load("glGetActiveAtomicCounterBufferiv"); glad_glBindImageTexture = (PFNGLBINDIMAGETEXTUREPROC)load("glBindImageTexture"); glad_glMemoryBarrier = (PFNGLMEMORYBARRIERPROC)load("glMemoryBarrier"); glad_glTexStorage1D = (PFNGLTEXSTORAGE1DPROC)load("glTexStorage1D"); glad_glTexStorage2D = (PFNGLTEXSTORAGE2DPROC)load("glTexStorage2D"); glad_glTexStorage3D = (PFNGLTEXSTORAGE3DPROC)load("glTexStorage3D"); glad_glDrawTransformFeedbackInstanced = (PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC)load("glDrawTransformFeedbackInstanced"); glad_glDrawTransformFeedbackStreamInstanced = (PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC)load("glDrawTransformFeedbackStreamInstanced"); } static void load_GL_VERSION_4_3(GLADloadproc load) { if(!GLAD_GL_VERSION_4_3) return; glad_glClearBufferData = (PFNGLCLEARBUFFERDATAPROC)load("glClearBufferData"); glad_glClearBufferSubData = (PFNGLCLEARBUFFERSUBDATAPROC)load("glClearBufferSubData"); glad_glDispatchCompute = (PFNGLDISPATCHCOMPUTEPROC)load("glDispatchCompute"); glad_glDispatchComputeIndirect = (PFNGLDISPATCHCOMPUTEINDIRECTPROC)load("glDispatchComputeIndirect"); glad_glCopyImageSubData = (PFNGLCOPYIMAGESUBDATAPROC)load("glCopyImageSubData"); glad_glFramebufferParameteri = (PFNGLFRAMEBUFFERPARAMETERIPROC)load("glFramebufferParameteri"); glad_glGetFramebufferParameteriv = (PFNGLGETFRAMEBUFFERPARAMETERIVPROC)load("glGetFramebufferParameteriv"); glad_glGetInternalformati64v = (PFNGLGETINTERNALFORMATI64VPROC)load("glGetInternalformati64v"); glad_glInvalidateTexSubImage = (PFNGLINVALIDATETEXSUBIMAGEPROC)load("glInvalidateTexSubImage"); glad_glInvalidateTexImage = (PFNGLINVALIDATETEXIMAGEPROC)load("glInvalidateTexImage"); glad_glInvalidateBufferSubData = (PFNGLINVALIDATEBUFFERSUBDATAPROC)load("glInvalidateBufferSubData"); glad_glInvalidateBufferData = (PFNGLINVALIDATEBUFFERDATAPROC)load("glInvalidateBufferData"); glad_glInvalidateFramebuffer = (PFNGLINVALIDATEFRAMEBUFFERPROC)load("glInvalidateFramebuffer"); glad_glInvalidateSubFramebuffer = (PFNGLINVALIDATESUBFRAMEBUFFERPROC)load("glInvalidateSubFramebuffer"); glad_glMultiDrawArraysIndirect = (PFNGLMULTIDRAWARRAYSINDIRECTPROC)load("glMultiDrawArraysIndirect"); glad_glMultiDrawElementsIndirect = (PFNGLMULTIDRAWELEMENTSINDIRECTPROC)load("glMultiDrawElementsIndirect"); glad_glGetProgramInterfaceiv = (PFNGLGETPROGRAMINTERFACEIVPROC)load("glGetProgramInterfaceiv"); glad_glGetProgramResourceIndex = (PFNGLGETPROGRAMRESOURCEINDEXPROC)load("glGetProgramResourceIndex"); glad_glGetProgramResourceName = (PFNGLGETPROGRAMRESOURCENAMEPROC)load("glGetProgramResourceName"); glad_glGetProgramResourceiv = (PFNGLGETPROGRAMRESOURCEIVPROC)load("glGetProgramResourceiv"); glad_glGetProgramResourceLocation = (PFNGLGETPROGRAMRESOURCELOCATIONPROC)load("glGetProgramResourceLocation"); glad_glGetProgramResourceLocationIndex = (PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC)load("glGetProgramResourceLocationIndex"); glad_glShaderStorageBlockBinding = (PFNGLSHADERSTORAGEBLOCKBINDINGPROC)load("glShaderStorageBlockBinding"); glad_glTexBufferRange = (PFNGLTEXBUFFERRANGEPROC)load("glTexBufferRange"); glad_glTexStorage2DMultisample = (PFNGLTEXSTORAGE2DMULTISAMPLEPROC)load("glTexStorage2DMultisample"); glad_glTexStorage3DMultisample = (PFNGLTEXSTORAGE3DMULTISAMPLEPROC)load("glTexStorage3DMultisample"); glad_glTextureView = (PFNGLTEXTUREVIEWPROC)load("glTextureView"); glad_glBindVertexBuffer = (PFNGLBINDVERTEXBUFFERPROC)load("glBindVertexBuffer"); glad_glVertexAttribFormat = (PFNGLVERTEXATTRIBFORMATPROC)load("glVertexAttribFormat"); glad_glVertexAttribIFormat = (PFNGLVERTEXATTRIBIFORMATPROC)load("glVertexAttribIFormat"); glad_glVertexAttribLFormat = (PFNGLVERTEXATTRIBLFORMATPROC)load("glVertexAttribLFormat"); glad_glVertexAttribBinding = (PFNGLVERTEXATTRIBBINDINGPROC)load("glVertexAttribBinding"); glad_glVertexBindingDivisor = (PFNGLVERTEXBINDINGDIVISORPROC)load("glVertexBindingDivisor"); glad_glDebugMessageControl = (PFNGLDEBUGMESSAGECONTROLPROC)load("glDebugMessageControl"); glad_glDebugMessageInsert = (PFNGLDEBUGMESSAGEINSERTPROC)load("glDebugMessageInsert"); glad_glDebugMessageCallback = (PFNGLDEBUGMESSAGECALLBACKPROC)load("glDebugMessageCallback"); glad_glGetDebugMessageLog = (PFNGLGETDEBUGMESSAGELOGPROC)load("glGetDebugMessageLog"); glad_glPushDebugGroup = (PFNGLPUSHDEBUGGROUPPROC)load("glPushDebugGroup"); glad_glPopDebugGroup = (PFNGLPOPDEBUGGROUPPROC)load("glPopDebugGroup"); glad_glObjectLabel = (PFNGLOBJECTLABELPROC)load("glObjectLabel"); glad_glGetObjectLabel = (PFNGLGETOBJECTLABELPROC)load("glGetObjectLabel"); glad_glObjectPtrLabel = (PFNGLOBJECTPTRLABELPROC)load("glObjectPtrLabel"); glad_glGetObjectPtrLabel = (PFNGLGETOBJECTPTRLABELPROC)load("glGetObjectPtrLabel"); glad_glGetPointerv = (PFNGLGETPOINTERVPROC)load("glGetPointerv"); } static void load_GL_VERSION_4_4(GLADloadproc load) { if(!GLAD_GL_VERSION_4_4) return; glad_glBufferStorage = (PFNGLBUFFERSTORAGEPROC)load("glBufferStorage"); glad_glClearTexImage = (PFNGLCLEARTEXIMAGEPROC)load("glClearTexImage"); glad_glClearTexSubImage = (PFNGLCLEARTEXSUBIMAGEPROC)load("glClearTexSubImage"); glad_glBindBuffersBase = (PFNGLBINDBUFFERSBASEPROC)load("glBindBuffersBase"); glad_glBindBuffersRange = (PFNGLBINDBUFFERSRANGEPROC)load("glBindBuffersRange"); glad_glBindTextures = (PFNGLBINDTEXTURESPROC)load("glBindTextures"); glad_glBindSamplers = (PFNGLBINDSAMPLERSPROC)load("glBindSamplers"); glad_glBindImageTextures = (PFNGLBINDIMAGETEXTURESPROC)load("glBindImageTextures"); glad_glBindVertexBuffers = (PFNGLBINDVERTEXBUFFERSPROC)load("glBindVertexBuffers"); } static void load_GL_VERSION_4_5(GLADloadproc load) { if(!GLAD_GL_VERSION_4_5) return; glad_glClipControl = (PFNGLCLIPCONTROLPROC)load("glClipControl"); glad_glCreateTransformFeedbacks = (PFNGLCREATETRANSFORMFEEDBACKSPROC)load("glCreateTransformFeedbacks"); glad_glTransformFeedbackBufferBase = (PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC)load("glTransformFeedbackBufferBase"); glad_glTransformFeedbackBufferRange = (PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC)load("glTransformFeedbackBufferRange"); glad_glGetTransformFeedbackiv = (PFNGLGETTRANSFORMFEEDBACKIVPROC)load("glGetTransformFeedbackiv"); glad_glGetTransformFeedbacki_v = (PFNGLGETTRANSFORMFEEDBACKI_VPROC)load("glGetTransformFeedbacki_v"); glad_glGetTransformFeedbacki64_v = (PFNGLGETTRANSFORMFEEDBACKI64_VPROC)load("glGetTransformFeedbacki64_v"); glad_glCreateBuffers = (PFNGLCREATEBUFFERSPROC)load("glCreateBuffers"); glad_glNamedBufferStorage = (PFNGLNAMEDBUFFERSTORAGEPROC)load("glNamedBufferStorage"); glad_glNamedBufferData = (PFNGLNAMEDBUFFERDATAPROC)load("glNamedBufferData"); glad_glNamedBufferSubData = (PFNGLNAMEDBUFFERSUBDATAPROC)load("glNamedBufferSubData"); glad_glCopyNamedBufferSubData = (PFNGLCOPYNAMEDBUFFERSUBDATAPROC)load("glCopyNamedBufferSubData"); glad_glClearNamedBufferData = (PFNGLCLEARNAMEDBUFFERDATAPROC)load("glClearNamedBufferData"); glad_glClearNamedBufferSubData = (PFNGLCLEARNAMEDBUFFERSUBDATAPROC)load("glClearNamedBufferSubData"); glad_glMapNamedBuffer = (PFNGLMAPNAMEDBUFFERPROC)load("glMapNamedBuffer"); glad_glMapNamedBufferRange = (PFNGLMAPNAMEDBUFFERRANGEPROC)load("glMapNamedBufferRange"); glad_glUnmapNamedBuffer = (PFNGLUNMAPNAMEDBUFFERPROC)load("glUnmapNamedBuffer"); glad_glFlushMappedNamedBufferRange = (PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC)load("glFlushMappedNamedBufferRange"); glad_glGetNamedBufferParameteriv = (PFNGLGETNAMEDBUFFERPARAMETERIVPROC)load("glGetNamedBufferParameteriv"); glad_glGetNamedBufferParameteri64v = (PFNGLGETNAMEDBUFFERPARAMETERI64VPROC)load("glGetNamedBufferParameteri64v"); glad_glGetNamedBufferPointerv = (PFNGLGETNAMEDBUFFERPOINTERVPROC)load("glGetNamedBufferPointerv"); glad_glGetNamedBufferSubData = (PFNGLGETNAMEDBUFFERSUBDATAPROC)load("glGetNamedBufferSubData"); glad_glCreateFramebuffers = (PFNGLCREATEFRAMEBUFFERSPROC)load("glCreateFramebuffers"); glad_glNamedFramebufferRenderbuffer = (PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC)load("glNamedFramebufferRenderbuffer"); glad_glNamedFramebufferParameteri = (PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC)load("glNamedFramebufferParameteri"); glad_glNamedFramebufferTexture = (PFNGLNAMEDFRAMEBUFFERTEXTUREPROC)load("glNamedFramebufferTexture"); glad_glNamedFramebufferTextureLayer = (PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC)load("glNamedFramebufferTextureLayer"); glad_glNamedFramebufferDrawBuffer = (PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC)load("glNamedFramebufferDrawBuffer"); glad_glNamedFramebufferDrawBuffers = (PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC)load("glNamedFramebufferDrawBuffers"); glad_glNamedFramebufferReadBuffer = (PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC)load("glNamedFramebufferReadBuffer"); glad_glInvalidateNamedFramebufferData = (PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC)load("glInvalidateNamedFramebufferData"); glad_glInvalidateNamedFramebufferSubData = (PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC)load("glInvalidateNamedFramebufferSubData"); glad_glClearNamedFramebufferiv = (PFNGLCLEARNAMEDFRAMEBUFFERIVPROC)load("glClearNamedFramebufferiv"); glad_glClearNamedFramebufferuiv = (PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC)load("glClearNamedFramebufferuiv"); glad_glClearNamedFramebufferfv = (PFNGLCLEARNAMEDFRAMEBUFFERFVPROC)load("glClearNamedFramebufferfv"); glad_glClearNamedFramebufferfi = (PFNGLCLEARNAMEDFRAMEBUFFERFIPROC)load("glClearNamedFramebufferfi"); glad_glBlitNamedFramebuffer = (PFNGLBLITNAMEDFRAMEBUFFERPROC)load("glBlitNamedFramebuffer"); glad_glCheckNamedFramebufferStatus = (PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC)load("glCheckNamedFramebufferStatus"); glad_glGetNamedFramebufferParameteriv = (PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC)load("glGetNamedFramebufferParameteriv"); glad_glGetNamedFramebufferAttachmentParameteriv = (PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC)load("glGetNamedFramebufferAttachmentParameteriv"); glad_glCreateRenderbuffers = (PFNGLCREATERENDERBUFFERSPROC)load("glCreateRenderbuffers"); glad_glNamedRenderbufferStorage = (PFNGLNAMEDRENDERBUFFERSTORAGEPROC)load("glNamedRenderbufferStorage"); glad_glNamedRenderbufferStorageMultisample = (PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC)load("glNamedRenderbufferStorageMultisample"); glad_glGetNamedRenderbufferParameteriv = (PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC)load("glGetNamedRenderbufferParameteriv"); glad_glCreateTextures = (PFNGLCREATETEXTURESPROC)load("glCreateTextures"); glad_glTextureBuffer = (PFNGLTEXTUREBUFFERPROC)load("glTextureBuffer"); glad_glTextureBufferRange = (PFNGLTEXTUREBUFFERRANGEPROC)load("glTextureBufferRange"); glad_glTextureStorage1D = (PFNGLTEXTURESTORAGE1DPROC)load("glTextureStorage1D"); glad_glTextureStorage2D = (PFNGLTEXTURESTORAGE2DPROC)load("glTextureStorage2D"); glad_glTextureStorage3D = (PFNGLTEXTURESTORAGE3DPROC)load("glTextureStorage3D"); glad_glTextureStorage2DMultisample = (PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC)load("glTextureStorage2DMultisample"); glad_glTextureStorage3DMultisample = (PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC)load("glTextureStorage3DMultisample"); glad_glTextureSubImage1D = (PFNGLTEXTURESUBIMAGE1DPROC)load("glTextureSubImage1D"); glad_glTextureSubImage2D = (PFNGLTEXTURESUBIMAGE2DPROC)load("glTextureSubImage2D"); glad_glTextureSubImage3D = (PFNGLTEXTURESUBIMAGE3DPROC)load("glTextureSubImage3D"); glad_glCompressedTextureSubImage1D = (PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC)load("glCompressedTextureSubImage1D"); glad_glCompressedTextureSubImage2D = (PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC)load("glCompressedTextureSubImage2D"); glad_glCompressedTextureSubImage3D = (PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC)load("glCompressedTextureSubImage3D"); glad_glCopyTextureSubImage1D = (PFNGLCOPYTEXTURESUBIMAGE1DPROC)load("glCopyTextureSubImage1D"); glad_glCopyTextureSubImage2D = (PFNGLCOPYTEXTURESUBIMAGE2DPROC)load("glCopyTextureSubImage2D"); glad_glCopyTextureSubImage3D = (PFNGLCOPYTEXTURESUBIMAGE3DPROC)load("glCopyTextureSubImage3D"); glad_glTextureParameterf = (PFNGLTEXTUREPARAMETERFPROC)load("glTextureParameterf"); glad_glTextureParameterfv = (PFNGLTEXTUREPARAMETERFVPROC)load("glTextureParameterfv"); glad_glTextureParameteri = (PFNGLTEXTUREPARAMETERIPROC)load("glTextureParameteri"); glad_glTextureParameterIiv = (PFNGLTEXTUREPARAMETERIIVPROC)load("glTextureParameterIiv"); glad_glTextureParameterIuiv = (PFNGLTEXTUREPARAMETERIUIVPROC)load("glTextureParameterIuiv"); glad_glTextureParameteriv = (PFNGLTEXTUREPARAMETERIVPROC)load("glTextureParameteriv"); glad_glGenerateTextureMipmap = (PFNGLGENERATETEXTUREMIPMAPPROC)load("glGenerateTextureMipmap"); glad_glBindTextureUnit = (PFNGLBINDTEXTUREUNITPROC)load("glBindTextureUnit"); glad_glGetTextureImage = (PFNGLGETTEXTUREIMAGEPROC)load("glGetTextureImage"); glad_glGetCompressedTextureImage = (PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC)load("glGetCompressedTextureImage"); glad_glGetTextureLevelParameterfv = (PFNGLGETTEXTURELEVELPARAMETERFVPROC)load("glGetTextureLevelParameterfv"); glad_glGetTextureLevelParameteriv = (PFNGLGETTEXTURELEVELPARAMETERIVPROC)load("glGetTextureLevelParameteriv"); glad_glGetTextureParameterfv = (PFNGLGETTEXTUREPARAMETERFVPROC)load("glGetTextureParameterfv"); glad_glGetTextureParameterIiv = (PFNGLGETTEXTUREPARAMETERIIVPROC)load("glGetTextureParameterIiv"); glad_glGetTextureParameterIuiv = (PFNGLGETTEXTUREPARAMETERIUIVPROC)load("glGetTextureParameterIuiv"); glad_glGetTextureParameteriv = (PFNGLGETTEXTUREPARAMETERIVPROC)load("glGetTextureParameteriv"); glad_glCreateVertexArrays = (PFNGLCREATEVERTEXARRAYSPROC)load("glCreateVertexArrays"); glad_glDisableVertexArrayAttrib = (PFNGLDISABLEVERTEXARRAYATTRIBPROC)load("glDisableVertexArrayAttrib"); glad_glEnableVertexArrayAttrib = (PFNGLENABLEVERTEXARRAYATTRIBPROC)load("glEnableVertexArrayAttrib"); glad_glVertexArrayElementBuffer = (PFNGLVERTEXARRAYELEMENTBUFFERPROC)load("glVertexArrayElementBuffer"); glad_glVertexArrayVertexBuffer = (PFNGLVERTEXARRAYVERTEXBUFFERPROC)load("glVertexArrayVertexBuffer"); glad_glVertexArrayVertexBuffers = (PFNGLVERTEXARRAYVERTEXBUFFERSPROC)load("glVertexArrayVertexBuffers"); glad_glVertexArrayAttribBinding = (PFNGLVERTEXARRAYATTRIBBINDINGPROC)load("glVertexArrayAttribBinding"); glad_glVertexArrayAttribFormat = (PFNGLVERTEXARRAYATTRIBFORMATPROC)load("glVertexArrayAttribFormat"); glad_glVertexArrayAttribIFormat = (PFNGLVERTEXARRAYATTRIBIFORMATPROC)load("glVertexArrayAttribIFormat"); glad_glVertexArrayAttribLFormat = (PFNGLVERTEXARRAYATTRIBLFORMATPROC)load("glVertexArrayAttribLFormat"); glad_glVertexArrayBindingDivisor = (PFNGLVERTEXARRAYBINDINGDIVISORPROC)load("glVertexArrayBindingDivisor"); glad_glGetVertexArrayiv = (PFNGLGETVERTEXARRAYIVPROC)load("glGetVertexArrayiv"); glad_glGetVertexArrayIndexediv = (PFNGLGETVERTEXARRAYINDEXEDIVPROC)load("glGetVertexArrayIndexediv"); glad_glGetVertexArrayIndexed64iv = (PFNGLGETVERTEXARRAYINDEXED64IVPROC)load("glGetVertexArrayIndexed64iv"); glad_glCreateSamplers = (PFNGLCREATESAMPLERSPROC)load("glCreateSamplers"); glad_glCreateProgramPipelines = (PFNGLCREATEPROGRAMPIPELINESPROC)load("glCreateProgramPipelines"); glad_glCreateQueries = (PFNGLCREATEQUERIESPROC)load("glCreateQueries"); glad_glGetQueryBufferObjecti64v = (PFNGLGETQUERYBUFFEROBJECTI64VPROC)load("glGetQueryBufferObjecti64v"); glad_glGetQueryBufferObjectiv = (PFNGLGETQUERYBUFFEROBJECTIVPROC)load("glGetQueryBufferObjectiv"); glad_glGetQueryBufferObjectui64v = (PFNGLGETQUERYBUFFEROBJECTUI64VPROC)load("glGetQueryBufferObjectui64v"); glad_glGetQueryBufferObjectuiv = (PFNGLGETQUERYBUFFEROBJECTUIVPROC)load("glGetQueryBufferObjectuiv"); glad_glMemoryBarrierByRegion = (PFNGLMEMORYBARRIERBYREGIONPROC)load("glMemoryBarrierByRegion"); glad_glGetTextureSubImage = (PFNGLGETTEXTURESUBIMAGEPROC)load("glGetTextureSubImage"); glad_glGetCompressedTextureSubImage = (PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC)load("glGetCompressedTextureSubImage"); glad_glGetGraphicsResetStatus = (PFNGLGETGRAPHICSRESETSTATUSPROC)load("glGetGraphicsResetStatus"); glad_glGetnCompressedTexImage = (PFNGLGETNCOMPRESSEDTEXIMAGEPROC)load("glGetnCompressedTexImage"); glad_glGetnTexImage = (PFNGLGETNTEXIMAGEPROC)load("glGetnTexImage"); glad_glGetnUniformdv = (PFNGLGETNUNIFORMDVPROC)load("glGetnUniformdv"); glad_glGetnUniformfv = (PFNGLGETNUNIFORMFVPROC)load("glGetnUniformfv"); glad_glGetnUniformiv = (PFNGLGETNUNIFORMIVPROC)load("glGetnUniformiv"); glad_glGetnUniformuiv = (PFNGLGETNUNIFORMUIVPROC)load("glGetnUniformuiv"); glad_glReadnPixels = (PFNGLREADNPIXELSPROC)load("glReadnPixels"); glad_glGetnMapdv = (PFNGLGETNMAPDVPROC)load("glGetnMapdv"); glad_glGetnMapfv = (PFNGLGETNMAPFVPROC)load("glGetnMapfv"); glad_glGetnMapiv = (PFNGLGETNMAPIVPROC)load("glGetnMapiv"); glad_glGetnPixelMapfv = (PFNGLGETNPIXELMAPFVPROC)load("glGetnPixelMapfv"); glad_glGetnPixelMapuiv = (PFNGLGETNPIXELMAPUIVPROC)load("glGetnPixelMapuiv"); glad_glGetnPixelMapusv = (PFNGLGETNPIXELMAPUSVPROC)load("glGetnPixelMapusv"); glad_glGetnPolygonStipple = (PFNGLGETNPOLYGONSTIPPLEPROC)load("glGetnPolygonStipple"); glad_glGetnColorTable = (PFNGLGETNCOLORTABLEPROC)load("glGetnColorTable"); glad_glGetnConvolutionFilter = (PFNGLGETNCONVOLUTIONFILTERPROC)load("glGetnConvolutionFilter"); glad_glGetnSeparableFilter = (PFNGLGETNSEPARABLEFILTERPROC)load("glGetnSeparableFilter"); glad_glGetnHistogram = (PFNGLGETNHISTOGRAMPROC)load("glGetnHistogram"); glad_glGetnMinmax = (PFNGLGETNMINMAXPROC)load("glGetnMinmax"); glad_glTextureBarrier = (PFNGLTEXTUREBARRIERPROC)load("glTextureBarrier"); } static void load_GL_VERSION_4_6(GLADloadproc load) { if(!GLAD_GL_VERSION_4_6) return; glad_glSpecializeShader = (PFNGLSPECIALIZESHADERPROC)load("glSpecializeShader"); glad_glMultiDrawArraysIndirectCount = (PFNGLMULTIDRAWARRAYSINDIRECTCOUNTPROC)load("glMultiDrawArraysIndirectCount"); glad_glMultiDrawElementsIndirectCount = (PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTPROC)load("glMultiDrawElementsIndirectCount"); glad_glPolygonOffsetClamp = (PFNGLPOLYGONOFFSETCLAMPPROC)load("glPolygonOffsetClamp"); } static int find_extensionsGL(void) { if (!get_exts()) return 0; (void)&has_ext; free_exts(); return 1; } static void find_coreGL(void) { /* Thank you @elmindreda * https://github.com/elmindreda/greg/blob/master/templates/greg.c.in#L176 * https://github.com/glfw/glfw/blob/master/src/context.c#L36 */ int i, major, minor; const char* version; const char* prefixes[] = { "OpenGL ES-CM ", "OpenGL ES-CL ", "OpenGL ES ", NULL }; version = (const char*) glGetString(GL_VERSION); if (!version) return; for (i = 0; prefixes[i]; i++) { const size_t length = strlen(prefixes[i]); if (strncmp(version, prefixes[i], length) == 0) { version += length; break; } } /* PR #18 */ #ifdef _MSC_VER sscanf_s(version, "%d.%d", &major, &minor); #else sscanf(version, "%d.%d", &major, &minor); #endif GLVersion.major = major; GLVersion.minor = minor; max_loaded_major = major; max_loaded_minor = minor; GLAD_GL_VERSION_1_0 = (major == 1 && minor >= 0) || major > 1; GLAD_GL_VERSION_1_1 = (major == 1 && minor >= 1) || major > 1; GLAD_GL_VERSION_1_2 = (major == 1 && minor >= 2) || major > 1; GLAD_GL_VERSION_1_3 = (major == 1 && minor >= 3) || major > 1; GLAD_GL_VERSION_1_4 = (major == 1 && minor >= 4) || major > 1; GLAD_GL_VERSION_1_5 = (major == 1 && minor >= 5) || major > 1; GLAD_GL_VERSION_2_0 = (major == 2 && minor >= 0) || major > 2; GLAD_GL_VERSION_2_1 = (major == 2 && minor >= 1) || major > 2; GLAD_GL_VERSION_3_0 = (major == 3 && minor >= 0) || major > 3; GLAD_GL_VERSION_3_1 = (major == 3 && minor >= 1) || major > 3; GLAD_GL_VERSION_3_2 = (major == 3 && minor >= 2) || major > 3; GLAD_GL_VERSION_3_3 = (major == 3 && minor >= 3) || major > 3; GLAD_GL_VERSION_4_0 = (major == 4 && minor >= 0) || major > 4; GLAD_GL_VERSION_4_1 = (major == 4 && minor >= 1) || major > 4; GLAD_GL_VERSION_4_2 = (major == 4 && minor >= 2) || major > 4; GLAD_GL_VERSION_4_3 = (major == 4 && minor >= 3) || major > 4; GLAD_GL_VERSION_4_4 = (major == 4 && minor >= 4) || major > 4; GLAD_GL_VERSION_4_5 = (major == 4 && minor >= 5) || major > 4; GLAD_GL_VERSION_4_6 = (major == 4 && minor >= 6) || major > 4; if (GLVersion.major > 4 || (GLVersion.major >= 4 && GLVersion.minor >= 6)) { max_loaded_major = 4; max_loaded_minor = 6; } } int gladLoadGLLoader(GLADloadproc load) { GLVersion.major = 0; GLVersion.minor = 0; glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); if(glGetString == NULL) return 0; if(glGetString(GL_VERSION) == NULL) return 0; find_coreGL(); load_GL_VERSION_1_0(load); load_GL_VERSION_1_1(load); load_GL_VERSION_1_2(load); load_GL_VERSION_1_3(load); load_GL_VERSION_1_4(load); load_GL_VERSION_1_5(load); load_GL_VERSION_2_0(load); load_GL_VERSION_2_1(load); load_GL_VERSION_3_0(load); load_GL_VERSION_3_1(load); load_GL_VERSION_3_2(load); load_GL_VERSION_3_3(load); load_GL_VERSION_4_0(load); load_GL_VERSION_4_1(load); load_GL_VERSION_4_2(load); load_GL_VERSION_4_3(load); load_GL_VERSION_4_4(load); load_GL_VERSION_4_5(load); load_GL_VERSION_4_6(load); if (!find_extensionsGL()) return 0; return GLVersion.major != 0 || GLVersion.minor != 0; } ================================================ FILE: extern/jsmn/jsmn.h ================================================ /* * MIT License * * Copyright (c) 2010 Serge Zaitsev * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef JSMN_H #define JSMN_H #include #ifdef __cplusplus extern "C" { #endif #ifdef JSMN_STATIC #define JSMN_API static #else #define JSMN_API extern #endif /** * JSON type identifier. Basic types are: * o Object * o Array * o String * o Other primitive: number, boolean (true/false) or null */ typedef enum { JSMN_UNDEFINED = 0, JSMN_OBJECT = 1 << 0, JSMN_ARRAY = 1 << 1, JSMN_STRING = 1 << 2, JSMN_PRIMITIVE = 1 << 3 } jsmntype_t; enum jsmnerr { /* Not enough tokens were provided */ JSMN_ERROR_NOMEM = -1, /* Invalid character inside JSON string */ JSMN_ERROR_INVAL = -2, /* The string is not a full JSON packet, more bytes expected */ JSMN_ERROR_PART = -3 }; /** * JSON token description. * type type (object, array, string etc.) * start start position in JSON data string * end end position in JSON data string */ typedef struct jsmntok { jsmntype_t type; int start; int end; int size; #ifdef JSMN_PARENT_LINKS int parent; #endif } jsmntok_t; /** * JSON parser. Contains an array of token blocks available. Also stores * the string being parsed now and current position in that string. */ typedef struct jsmn_parser { unsigned int pos; /* offset in the JSON string */ unsigned int toknext; /* next token to allocate */ int toksuper; /* superior token node, e.g. parent object or array */ } jsmn_parser; /** * Create JSON parser over an array of tokens */ JSMN_API void jsmn_init(jsmn_parser *parser); /** * Run JSON parser. It parses a JSON data string into and array of tokens, each * describing * a single JSON object. */ JSMN_API int jsmn_parse(jsmn_parser *parser, const char *js, const size_t len, jsmntok_t *tokens, const unsigned int num_tokens); #ifndef JSMN_HEADER /** * Allocates a fresh unused token from the token pool. */ static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser, jsmntok_t *tokens, const size_t num_tokens) { jsmntok_t *tok; if (parser->toknext >= num_tokens) { return NULL; } tok = &tokens[parser->toknext++]; tok->start = tok->end = -1; tok->size = 0; #ifdef JSMN_PARENT_LINKS tok->parent = -1; #endif return tok; } /** * Fills token type and boundaries. */ static void jsmn_fill_token(jsmntok_t *token, const jsmntype_t type, const int start, const int end) { token->type = type; token->start = start; token->end = end; token->size = 0; } /** * Fills next available token with JSON primitive. */ static int jsmn_parse_primitive(jsmn_parser *parser, const char *js, const size_t len, jsmntok_t *tokens, const size_t num_tokens) { jsmntok_t *token; int start; start = parser->pos; for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { switch (js[parser->pos]) { #ifndef JSMN_STRICT /* In strict mode primitive must be followed by "," or "}" or "]" */ case ':': #endif case '\t': case '\r': case '\n': case ' ': case ',': case ']': case '}': goto found; default: /* to quiet a warning from gcc*/ break; } if (js[parser->pos] < 32 || js[parser->pos] >= 127) { parser->pos = start; return JSMN_ERROR_INVAL; } } #ifdef JSMN_STRICT /* In strict mode primitive must be followed by a comma/object/array */ parser->pos = start; return JSMN_ERROR_PART; #endif found: if (tokens == NULL) { parser->pos--; return 0; } token = jsmn_alloc_token(parser, tokens, num_tokens); if (token == NULL) { parser->pos = start; return JSMN_ERROR_NOMEM; } jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos); #ifdef JSMN_PARENT_LINKS token->parent = parser->toksuper; #endif parser->pos--; return 0; } /** * Fills next token with JSON string. */ static int jsmn_parse_string(jsmn_parser *parser, const char *js, const size_t len, jsmntok_t *tokens, const size_t num_tokens) { jsmntok_t *token; int start = parser->pos; /* Skip starting quote */ parser->pos++; for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { char c = js[parser->pos]; /* Quote: end of string */ if (c == '\"') { if (tokens == NULL) { return 0; } token = jsmn_alloc_token(parser, tokens, num_tokens); if (token == NULL) { parser->pos = start; return JSMN_ERROR_NOMEM; } jsmn_fill_token(token, JSMN_STRING, start + 1, parser->pos); #ifdef JSMN_PARENT_LINKS token->parent = parser->toksuper; #endif return 0; } /* Backslash: Quoted symbol expected */ if (c == '\\' && parser->pos + 1 < len) { int i; parser->pos++; switch (js[parser->pos]) { /* Allowed escaped symbols */ case '\"': case '/': case '\\': case 'b': case 'f': case 'r': case 'n': case 't': break; /* Allows escaped symbol \uXXXX */ case 'u': parser->pos++; for (i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; i++) { /* If it isn't a hex character we have an error */ if (!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */ (js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */ (js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */ parser->pos = start; return JSMN_ERROR_INVAL; } parser->pos++; } parser->pos--; break; /* Unexpected symbol */ default: parser->pos = start; return JSMN_ERROR_INVAL; } } } parser->pos = start; return JSMN_ERROR_PART; } /** * Parse JSON string and fill tokens. */ JSMN_API int jsmn_parse(jsmn_parser *parser, const char *js, const size_t len, jsmntok_t *tokens, const unsigned int num_tokens) { int r; int i; jsmntok_t *token; int count = parser->toknext; for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { char c; jsmntype_t type; c = js[parser->pos]; switch (c) { case '{': case '[': count++; if (tokens == NULL) { break; } token = jsmn_alloc_token(parser, tokens, num_tokens); if (token == NULL) { return JSMN_ERROR_NOMEM; } if (parser->toksuper != -1) { jsmntok_t *t = &tokens[parser->toksuper]; #ifdef JSMN_STRICT /* In strict mode an object or array can't become a key */ if (t->type == JSMN_OBJECT) { return JSMN_ERROR_INVAL; } #endif t->size++; #ifdef JSMN_PARENT_LINKS token->parent = parser->toksuper; #endif } token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY); token->start = parser->pos; parser->toksuper = parser->toknext - 1; break; case '}': case ']': if (tokens == NULL) { break; } type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY); #ifdef JSMN_PARENT_LINKS if (parser->toknext < 1) { return JSMN_ERROR_INVAL; } token = &tokens[parser->toknext - 1]; for (;;) { if (token->start != -1 && token->end == -1) { if (token->type != type) { return JSMN_ERROR_INVAL; } token->end = parser->pos + 1; parser->toksuper = token->parent; break; } if (token->parent == -1) { if (token->type != type || parser->toksuper == -1) { return JSMN_ERROR_INVAL; } break; } token = &tokens[token->parent]; } #else for (i = parser->toknext - 1; i >= 0; i--) { token = &tokens[i]; if (token->start != -1 && token->end == -1) { if (token->type != type) { return JSMN_ERROR_INVAL; } parser->toksuper = -1; token->end = parser->pos + 1; break; } } /* Error if unmatched closing bracket */ if (i == -1) { return JSMN_ERROR_INVAL; } for (; i >= 0; i--) { token = &tokens[i]; if (token->start != -1 && token->end == -1) { parser->toksuper = i; break; } } #endif break; case '\"': r = jsmn_parse_string(parser, js, len, tokens, num_tokens); if (r < 0) { return r; } count++; if (parser->toksuper != -1 && tokens != NULL) { tokens[parser->toksuper].size++; } break; case '\t': case '\r': case '\n': case ' ': break; case ':': parser->toksuper = parser->toknext - 1; break; case ',': if (tokens != NULL && parser->toksuper != -1 && tokens[parser->toksuper].type != JSMN_ARRAY && tokens[parser->toksuper].type != JSMN_OBJECT) { #ifdef JSMN_PARENT_LINKS parser->toksuper = tokens[parser->toksuper].parent; #else for (i = parser->toknext - 1; i >= 0; i--) { if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT) { if (tokens[i].start != -1 && tokens[i].end == -1) { parser->toksuper = i; break; } } } #endif } break; #ifdef JSMN_STRICT /* In strict mode primitives are: numbers and booleans */ case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 't': case 'f': case 'n': /* And they must not be keys of the object */ if (tokens != NULL && parser->toksuper != -1) { const jsmntok_t *t = &tokens[parser->toksuper]; if (t->type == JSMN_OBJECT || (t->type == JSMN_STRING && t->size != 0)) { return JSMN_ERROR_INVAL; } } #else /* In non-strict mode every unquoted value is a primitive */ default: #endif r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens); if (r < 0) { return r; } count++; if (parser->toksuper != -1 && tokens != NULL) { tokens[parser->toksuper].size++; } break; #ifdef JSMN_STRICT /* Unexpected char in strict mode */ default: return JSMN_ERROR_INVAL; #endif } } if (tokens != NULL) { for (i = parser->toknext - 1; i >= 0; i--) { /* Unmatched opened object or array */ if (tokens[i].start != -1 && tokens[i].end == -1) { return JSMN_ERROR_PART; } } } return count; } /** * Creates a new parser based over a given buffer with an array of tokens * available. */ JSMN_API void jsmn_init(jsmn_parser *parser) { parser->pos = 0; parser->toknext = 0; parser->toksuper = -1; } #endif /* JSMN_HEADER */ #ifdef __cplusplus } #endif #endif /* JSMN_H */ ================================================ FILE: include/box2d/base.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include // clang-format off // // Shared library macros #if defined( _MSC_VER ) && defined( box2d_EXPORTS ) // build the Windows DLL #define BOX2D_EXPORT __declspec( dllexport ) #elif defined( _MSC_VER ) && defined( BOX2D_DLL ) // using the Windows DLL #define BOX2D_EXPORT __declspec( dllimport ) #elif defined( box2d_EXPORTS ) // building or using the shared library #define BOX2D_EXPORT __attribute__( ( visibility( "default" ) ) ) #else // static library #define BOX2D_EXPORT #endif // C++ macros #ifdef __cplusplus #define B2_API extern "C" BOX2D_EXPORT #define B2_INLINE inline #define B2_LITERAL(T) T #define B2_ZERO_INIT {} #else #define B2_API BOX2D_EXPORT #define B2_INLINE static inline /// Used for C literals like (b2Vec2){1.0f, 2.0f} where C++ requires b2Vec2{1.0f, 2.0f} #define B2_LITERAL(T) (T) #define B2_ZERO_INIT {0} #endif // clang-format on /** * @defgroup base Base * Base functionality * @{ */ /// Prototype for user allocation function /// @param size the allocation size in bytes /// @param alignment the required alignment, guaranteed to be a power of 2 typedef void* b2AllocFcn( unsigned int size, int alignment ); /// Prototype for user free function /// @param mem the memory previously allocated through `b2AllocFcn` /// @param size the allocation size in bytes typedef void b2FreeFcn( void* mem, unsigned int size ); /// Prototype for the user assert callback. Return 0 to skip the debugger break. typedef int b2AssertFcn( const char* condition, const char* fileName, int lineNumber ); /// Prototype for user log callback. Used to log warnings. typedef void b2LogFcn( const char* message ); /// This allows the user to override the allocation functions. These should be /// set during application startup. B2_API void b2SetAllocator( b2AllocFcn* allocFcn, b2FreeFcn* freeFcn ); /// @return the total bytes allocated by Box2D B2_API int b2GetByteCount( void ); /// Override the default assert function /// @param assertFcn a non-null assert callback B2_API void b2SetAssertFcn( b2AssertFcn* assertFcn ); /// Override the default log function /// @param logFcn a non-null log callback B2_API void b2SetLogFcn( b2LogFcn* logFcn ); /// Version numbering scheme. /// See https://semver.org/ typedef struct b2Version { /// Significant changes int major; /// Incremental changes int minor; /// Bug fixes int revision; } b2Version; /// Get the current version of Box2D B2_API b2Version b2GetVersion( void ); /**@}*/ //! @cond // see https://github.com/scottt/debugbreak #if defined( _MSC_VER ) #define B2_BREAKPOINT __debugbreak() #elif defined( __GNUC__ ) || defined( __clang__ ) #define B2_BREAKPOINT __builtin_trap() #else // Unknown compiler #include #define B2_BREAKPOINT assert( 0 ) #endif #if !defined( NDEBUG ) || defined( B2_ENABLE_ASSERT ) B2_API int b2InternalAssertFcn( const char* condition, const char* fileName, int lineNumber ); #define B2_ASSERT( condition ) \ do \ { \ if ( !( condition ) && b2InternalAssertFcn( #condition, __FILE__, (int)__LINE__ ) ) \ B2_BREAKPOINT; \ } \ while ( 0 ) #else #define B2_ASSERT( ... ) ( (void)0 ) #endif /// Get the absolute number of system ticks. The value is platform specific. B2_API uint64_t b2GetTicks( void ); /// Get the milliseconds passed from an initial tick value. B2_API float b2GetMilliseconds( uint64_t ticks ); /// Get the milliseconds passed from an initial tick value. Resets the passed in /// value to the current tick value. B2_API float b2GetMillisecondsAndReset( uint64_t* ticks ); /// Yield to be used in a busy loop. B2_API void b2Yield( void ); /// Simple djb2 hash function for determinism testing #define B2_HASH_INIT 5381 B2_API uint32_t b2Hash( uint32_t hash, const uint8_t* data, int count ); //! @endcond ================================================ FILE: include/box2d/box2d.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "base.h" #include "collision.h" #include "id.h" #include "types.h" #include /** * @defgroup world World * These functions allow you to create a simulation world. * * You can add rigid bodies and joint constraints to the world and run the simulation. You can get contact * information to get contact points and normals as well as events. You can query to world, checking for overlaps and casting rays * or shapes. There is also debugging information such as debug draw, timing information, and counters. You can find documentation * here: https://box2d.org/ * @{ */ /// Create a world for rigid body simulation. A world contains bodies, shapes, and constraints. You make create /// up to 128 worlds. Each world is completely independent and may be simulated in parallel. /// @return the world id. B2_API b2WorldId b2CreateWorld( const b2WorldDef* def ); /// Destroy a world B2_API void b2DestroyWorld( b2WorldId worldId ); /// World id validation. Provides validation for up to 64K allocations. B2_API bool b2World_IsValid( b2WorldId id ); /// Simulate a world for one time step. This performs collision detection, integration, and constraint solution. /// @param worldId The world to simulate /// @param timeStep The amount of time to simulate, this should be a fixed number. Usually 1/60. /// @param subStepCount The number of sub-steps, increasing the sub-step count can increase accuracy. Usually 4. B2_API void b2World_Step( b2WorldId worldId, float timeStep, int subStepCount ); /// Call this to draw shapes and other debug draw data B2_API void b2World_Draw( b2WorldId worldId, b2DebugDraw* draw ); /// Get the body events for the current time step. The event data is transient. Do not store a reference to this data. B2_API b2BodyEvents b2World_GetBodyEvents( b2WorldId worldId ); /// Get sensor events for the current time step. The event data is transient. Do not store a reference to this data. B2_API b2SensorEvents b2World_GetSensorEvents( b2WorldId worldId ); /// Get contact events for this current time step. The event data is transient. Do not store a reference to this data. B2_API b2ContactEvents b2World_GetContactEvents( b2WorldId worldId ); /// Get the joint events for the current time step. The event data is transient. Do not store a reference to this data. B2_API b2JointEvents b2World_GetJointEvents( b2WorldId worldId ); /// Overlap test for all shapes that *potentially* overlap the provided AABB B2_API b2TreeStats b2World_OverlapAABB( b2WorldId worldId, b2AABB aabb, b2QueryFilter filter, b2OverlapResultFcn* fcn, void* context ); /// Overlap test for all shapes that overlap the provided shape proxy. B2_API b2TreeStats b2World_OverlapShape( b2WorldId worldId, const b2ShapeProxy* proxy, b2QueryFilter filter, b2OverlapResultFcn* fcn, void* context ); /// Cast a ray into the world to collect shapes in the path of the ray. /// Your callback function controls whether you get the closest point, any point, or n-points. /// @note The callback function may receive shapes in any order /// @param worldId The world to cast the ray against /// @param origin The start point of the ray /// @param translation The translation of the ray from the start point to the end point /// @param filter Contains bit flags to filter unwanted shapes from the results /// @param fcn A user implemented callback function /// @param context A user context that is passed along to the callback function /// @return traversal performance counters B2_API b2TreeStats b2World_CastRay( b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter, b2CastResultFcn* fcn, void* context ); /// Cast a ray into the world to collect the closest hit. This is a convenience function. Ignores initial overlap. /// This is less general than b2World_CastRay() and does not allow for custom filtering. B2_API b2RayResult b2World_CastRayClosest( b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter ); /// Cast a shape through the world. Similar to a cast ray except that a shape is cast instead of a point. /// @see b2World_CastRay B2_API b2TreeStats b2World_CastShape( b2WorldId worldId, const b2ShapeProxy* proxy, b2Vec2 translation, b2QueryFilter filter, b2CastResultFcn* fcn, void* context ); /// Cast a capsule mover through the world. This is a special shape cast that handles sliding along other shapes while reducing /// clipping. B2_API float b2World_CastMover( b2WorldId worldId, const b2Capsule* mover, b2Vec2 translation, b2QueryFilter filter ); /// Collide a capsule mover with the world, gathering collision planes that can be fed to b2SolvePlanes. Useful for /// kinematic character movement. B2_API void b2World_CollideMover( b2WorldId worldId, const b2Capsule* mover, b2QueryFilter filter, b2PlaneResultFcn* fcn, void* context ); /// Enable/disable sleep. If your application does not need sleeping, you can gain some performance /// by disabling sleep completely at the world level. /// @see b2WorldDef B2_API void b2World_EnableSleeping( b2WorldId worldId, bool flag ); /// Is body sleeping enabled? B2_API bool b2World_IsSleepingEnabled( b2WorldId worldId ); /// Enable/disable continuous collision between dynamic and static bodies. Generally you should keep continuous /// collision enabled to prevent fast moving objects from going through static objects. The performance gain from /// disabling continuous collision is minor. /// @see b2WorldDef B2_API void b2World_EnableContinuous( b2WorldId worldId, bool flag ); /// Is continuous collision enabled? B2_API bool b2World_IsContinuousEnabled( b2WorldId worldId ); /// Adjust the restitution threshold. It is recommended not to make this value very small /// because it will prevent bodies from sleeping. Usually in meters per second. /// @see b2WorldDef B2_API void b2World_SetRestitutionThreshold( b2WorldId worldId, float value ); /// Get the the restitution speed threshold. Usually in meters per second. B2_API float b2World_GetRestitutionThreshold( b2WorldId worldId ); /// Adjust the hit event threshold. This controls the collision speed needed to generate a b2ContactHitEvent. /// Usually in meters per second. /// @see b2WorldDef::hitEventThreshold B2_API void b2World_SetHitEventThreshold( b2WorldId worldId, float value ); /// Get the the hit event speed threshold. Usually in meters per second. B2_API float b2World_GetHitEventThreshold( b2WorldId worldId ); /// Register the custom filter callback. This is optional. B2_API void b2World_SetCustomFilterCallback( b2WorldId worldId, b2CustomFilterFcn* fcn, void* context ); /// Register the pre-solve callback. This is optional. B2_API void b2World_SetPreSolveCallback( b2WorldId worldId, b2PreSolveFcn* fcn, void* context ); /// Set the gravity vector for the entire world. Box2D has no concept of an up direction and this /// is left as a decision for the application. Usually in m/s^2. /// @see b2WorldDef B2_API void b2World_SetGravity( b2WorldId worldId, b2Vec2 gravity ); /// Get the gravity vector B2_API b2Vec2 b2World_GetGravity( b2WorldId worldId ); /// Apply a radial explosion /// @param worldId The world id /// @param explosionDef The explosion definition B2_API void b2World_Explode( b2WorldId worldId, const b2ExplosionDef* explosionDef ); /// Adjust contact tuning parameters /// @param worldId The world id /// @param hertz The contact stiffness (cycles per second) /// @param dampingRatio The contact bounciness with 1 being critical damping (non-dimensional) /// @param pushSpeed The maximum contact constraint push out speed (meters per second) /// @note Advanced feature B2_API void b2World_SetContactTuning( b2WorldId worldId, float hertz, float dampingRatio, float pushSpeed ); /// Set the maximum linear speed. Usually in m/s. B2_API void b2World_SetMaximumLinearSpeed( b2WorldId worldId, float maximumLinearSpeed ); /// Get the maximum linear speed. Usually in m/s. B2_API float b2World_GetMaximumLinearSpeed( b2WorldId worldId ); /// Enable/disable constraint warm starting. Advanced feature for testing. Disabling /// warm starting greatly reduces stability and provides no performance gain. B2_API void b2World_EnableWarmStarting( b2WorldId worldId, bool flag ); /// Is constraint warm starting enabled? B2_API bool b2World_IsWarmStartingEnabled( b2WorldId worldId ); /// Get the number of awake bodies. B2_API int b2World_GetAwakeBodyCount( b2WorldId worldId ); /// Get the current world performance profile B2_API b2Profile b2World_GetProfile( b2WorldId worldId ); /// Get world counters and sizes B2_API b2Counters b2World_GetCounters( b2WorldId worldId ); /// Set the user data pointer. B2_API void b2World_SetUserData( b2WorldId worldId, void* userData ); /// Get the user data pointer. B2_API void* b2World_GetUserData( b2WorldId worldId ); /// Set the friction callback. Passing NULL resets to default. B2_API void b2World_SetFrictionCallback( b2WorldId worldId, b2FrictionCallback* callback ); /// Set the restitution callback. Passing NULL resets to default. B2_API void b2World_SetRestitutionCallback( b2WorldId worldId, b2RestitutionCallback* callback ); /// Dump memory stats to box2d_memory.txt B2_API void b2World_DumpMemoryStats( b2WorldId worldId ); /// This is for internal testing B2_API void b2World_RebuildStaticTree( b2WorldId worldId ); /// This is for internal testing B2_API void b2World_EnableSpeculative( b2WorldId worldId, bool flag ); /** @} */ /** * @defgroup body Body * This is the body API. * @{ */ /// Create a rigid body given a definition. No reference to the definition is retained. So you can create the definition /// on the stack and pass it as a pointer. /// @code{.c} /// b2BodyDef bodyDef = b2DefaultBodyDef(); /// b2BodyId myBodyId = b2CreateBody(myWorldId, &bodyDef); /// @endcode /// @warning This function is locked during callbacks. B2_API b2BodyId b2CreateBody( b2WorldId worldId, const b2BodyDef* def ); /// Destroy a rigid body given an id. This destroys all shapes and joints attached to the body. /// Do not keep references to the associated shapes and joints. B2_API void b2DestroyBody( b2BodyId bodyId ); /// Body identifier validation. A valid body exists in a world and is non-null. /// This can be used to detect orphaned ids. Provides validation for up to 64K allocations. B2_API bool b2Body_IsValid( b2BodyId id ); /// Get the body type: static, kinematic, or dynamic B2_API b2BodyType b2Body_GetType( b2BodyId bodyId ); /// Change the body type. This is an expensive operation. This automatically updates the mass /// properties regardless of the automatic mass setting. B2_API void b2Body_SetType( b2BodyId bodyId, b2BodyType type ); /// Set the body name. Up to 31 characters excluding 0 termination. B2_API void b2Body_SetName( b2BodyId bodyId, const char* name ); /// Get the body name. B2_API const char* b2Body_GetName( b2BodyId bodyId ); /// Set the user data for a body B2_API void b2Body_SetUserData( b2BodyId bodyId, void* userData ); /// Get the user data stored in a body B2_API void* b2Body_GetUserData( b2BodyId bodyId ); /// Get the world position of a body. This is the location of the body origin. B2_API b2Vec2 b2Body_GetPosition( b2BodyId bodyId ); /// Get the world rotation of a body as a cosine/sine pair (complex number) B2_API b2Rot b2Body_GetRotation( b2BodyId bodyId ); /// Get the world transform of a body. B2_API b2Transform b2Body_GetTransform( b2BodyId bodyId ); /// Set the world transform of a body. This acts as a teleport and is fairly expensive. /// @note Generally you should create a body with then intended transform. /// @see b2BodyDef::position and b2BodyDef::rotation B2_API void b2Body_SetTransform( b2BodyId bodyId, b2Vec2 position, b2Rot rotation ); /// Get a local point on a body given a world point B2_API b2Vec2 b2Body_GetLocalPoint( b2BodyId bodyId, b2Vec2 worldPoint ); /// Get a world point on a body given a local point B2_API b2Vec2 b2Body_GetWorldPoint( b2BodyId bodyId, b2Vec2 localPoint ); /// Get a local vector on a body given a world vector B2_API b2Vec2 b2Body_GetLocalVector( b2BodyId bodyId, b2Vec2 worldVector ); /// Get a world vector on a body given a local vector B2_API b2Vec2 b2Body_GetWorldVector( b2BodyId bodyId, b2Vec2 localVector ); /// Get the linear velocity of a body's center of mass. Usually in meters per second. B2_API b2Vec2 b2Body_GetLinearVelocity( b2BodyId bodyId ); /// Get the angular velocity of a body in radians per second B2_API float b2Body_GetAngularVelocity( b2BodyId bodyId ); /// Set the linear velocity of a body. Usually in meters per second. B2_API void b2Body_SetLinearVelocity( b2BodyId bodyId, b2Vec2 linearVelocity ); /// Set the angular velocity of a body in radians per second B2_API void b2Body_SetAngularVelocity( b2BodyId bodyId, float angularVelocity ); /// Set the velocity to reach the given transform after a given time step. /// The result will be close but maybe not exact. This is meant for kinematic bodies. /// The target is not applied if the velocity would be below the sleep threshold and /// the body is currently asleep. /// @param bodyId The body id /// @param target The target transform for the body /// @param timeStep The time step of the next call to b2World_Step /// @param wake Option to wake the body or not B2_API void b2Body_SetTargetTransform( b2BodyId bodyId, b2Transform target, float timeStep, bool wake ); /// Get the linear velocity of a local point attached to a body. Usually in meters per second. B2_API b2Vec2 b2Body_GetLocalPointVelocity( b2BodyId bodyId, b2Vec2 localPoint ); /// Get the linear velocity of a world point attached to a body. Usually in meters per second. B2_API b2Vec2 b2Body_GetWorldPointVelocity( b2BodyId bodyId, b2Vec2 worldPoint ); /// Apply a force at a world point. If the force is not applied at the center of mass, /// it will generate a torque and affect the angular velocity. This optionally wakes up the body. /// The force is ignored if the body is not awake. /// @param bodyId The body id /// @param force The world force vector, usually in newtons (N) /// @param point The world position of the point of application /// @param wake Option to wake up the body B2_API void b2Body_ApplyForce( b2BodyId bodyId, b2Vec2 force, b2Vec2 point, bool wake ); /// Apply a force to the center of mass. This optionally wakes up the body. /// The force is ignored if the body is not awake. /// @param bodyId The body id /// @param force the world force vector, usually in newtons (N). /// @param wake also wake up the body B2_API void b2Body_ApplyForceToCenter( b2BodyId bodyId, b2Vec2 force, bool wake ); /// Apply a torque. This affects the angular velocity without affecting the linear velocity. /// This optionally wakes the body. The torque is ignored if the body is not awake. /// @param bodyId The body id /// @param torque about the z-axis (out of the screen), usually in N*m. /// @param wake also wake up the body B2_API void b2Body_ApplyTorque( b2BodyId bodyId, float torque, bool wake ); /// Clear the force and torque on this body. Forces and torques are automatically cleared after each world /// step. So this only needs to be called if the application wants to remove the effect of previous /// calls to apply forces and torques before the world step is called. /// @param bodyId The body id B2_API void b2Body_ClearForces( b2BodyId bodyId ); /// Apply an impulse at a point. This immediately modifies the velocity. /// It also modifies the angular velocity if the point of application /// is not at the center of mass. This optionally wakes the body. /// The impulse is ignored if the body is not awake. /// @param bodyId The body id /// @param impulse the world impulse vector, usually in N*s or kg*m/s. /// @param point the world position of the point of application. /// @param wake also wake up the body /// @warning This should be used for one-shot impulses. If you need a steady force, /// use a force instead, which will work better with the sub-stepping solver. B2_API void b2Body_ApplyLinearImpulse( b2BodyId bodyId, b2Vec2 impulse, b2Vec2 point, bool wake ); /// Apply an impulse to the center of mass. This immediately modifies the velocity. /// The impulse is ignored if the body is not awake. This optionally wakes the body. /// @param bodyId The body id /// @param impulse the world impulse vector, usually in N*s or kg*m/s. /// @param wake also wake up the body /// @warning This should be used for one-shot impulses. If you need a steady force, /// use a force instead, which will work better with the sub-stepping solver. B2_API void b2Body_ApplyLinearImpulseToCenter( b2BodyId bodyId, b2Vec2 impulse, bool wake ); /// Apply an angular impulse. The impulse is ignored if the body is not awake. /// This optionally wakes the body. /// @param bodyId The body id /// @param impulse the angular impulse, usually in units of kg*m*m/s /// @param wake also wake up the body /// @warning This should be used for one-shot impulses. If you need a steady torque, /// use a torque instead, which will work better with the sub-stepping solver. B2_API void b2Body_ApplyAngularImpulse( b2BodyId bodyId, float impulse, bool wake ); /// Get the mass of the body, usually in kilograms B2_API float b2Body_GetMass( b2BodyId bodyId ); /// Get the rotational inertia of the body, usually in kg*m^2 B2_API float b2Body_GetRotationalInertia( b2BodyId bodyId ); /// Get the center of mass position of the body in local space B2_API b2Vec2 b2Body_GetLocalCenterOfMass( b2BodyId bodyId ); /// Get the center of mass position of the body in world space B2_API b2Vec2 b2Body_GetWorldCenterOfMass( b2BodyId bodyId ); /// Override the body's mass properties. Normally this is computed automatically using the /// shape geometry and density. This information is lost if a shape is added or removed or if the /// body type changes. B2_API void b2Body_SetMassData( b2BodyId bodyId, b2MassData massData ); /// Get the mass data for a body B2_API b2MassData b2Body_GetMassData( b2BodyId bodyId ); /// This updates the mass properties to the sum of the mass properties of the shapes. /// This normally does not need to be called unless you called SetMassData to override /// the mass and you later want to reset the mass. /// You may also use this when automatic mass computation has been disabled. /// You should call this regardless of body type. /// Note that sensor shapes may have mass. B2_API void b2Body_ApplyMassFromShapes( b2BodyId bodyId ); /// Adjust the linear damping. Normally this is set in b2BodyDef before creation. B2_API void b2Body_SetLinearDamping( b2BodyId bodyId, float linearDamping ); /// Get the current linear damping. B2_API float b2Body_GetLinearDamping( b2BodyId bodyId ); /// Adjust the angular damping. Normally this is set in b2BodyDef before creation. B2_API void b2Body_SetAngularDamping( b2BodyId bodyId, float angularDamping ); /// Get the current angular damping. B2_API float b2Body_GetAngularDamping( b2BodyId bodyId ); /// Adjust the gravity scale. Normally this is set in b2BodyDef before creation. /// @see b2BodyDef::gravityScale B2_API void b2Body_SetGravityScale( b2BodyId bodyId, float gravityScale ); /// Get the current gravity scale B2_API float b2Body_GetGravityScale( b2BodyId bodyId ); /// @return true if this body is awake B2_API bool b2Body_IsAwake( b2BodyId bodyId ); /// Wake a body from sleep. This wakes the entire island the body is touching. /// @warning Putting a body to sleep will put the entire island of bodies touching this body to sleep, /// which can be expensive and possibly unintuitive. B2_API void b2Body_SetAwake( b2BodyId bodyId, bool awake ); /// Wake bodies touching this body. Works for static bodies. B2_API void b2Body_WakeTouching( b2BodyId bodyId ); /// Enable or disable sleeping for this body. If sleeping is disabled the body will wake. B2_API void b2Body_EnableSleep( b2BodyId bodyId, bool enableSleep ); /// Returns true if sleeping is enabled for this body B2_API bool b2Body_IsSleepEnabled( b2BodyId bodyId ); /// Set the sleep threshold, usually in meters per second B2_API void b2Body_SetSleepThreshold( b2BodyId bodyId, float sleepThreshold ); /// Get the sleep threshold, usually in meters per second. B2_API float b2Body_GetSleepThreshold( b2BodyId bodyId ); /// Returns true if this body is enabled B2_API bool b2Body_IsEnabled( b2BodyId bodyId ); /// Disable a body by removing it completely from the simulation. This is expensive. B2_API void b2Body_Disable( b2BodyId bodyId ); /// Enable a body by adding it to the simulation. This is expensive. B2_API void b2Body_Enable( b2BodyId bodyId ); /// Set the motion locks on this body. B2_API void b2Body_SetMotionLocks( b2BodyId bodyId, b2MotionLocks locks ); /// Get the motion locks for this body. B2_API b2MotionLocks b2Body_GetMotionLocks( b2BodyId bodyId ); /// Set this body to be a bullet. A bullet does continuous collision detection /// against dynamic bodies (but not other bullets). B2_API void b2Body_SetBullet( b2BodyId bodyId, bool flag ); /// Is this body a bullet? B2_API bool b2Body_IsBullet( b2BodyId bodyId ); /// Enable/disable contact events on all shapes. /// @see b2ShapeDef::enableContactEvents /// @warning changing this at runtime may cause mismatched begin/end touch events B2_API void b2Body_EnableContactEvents( b2BodyId bodyId, bool flag ); /// Enable/disable hit events on all shapes /// @see b2ShapeDef::enableHitEvents B2_API void b2Body_EnableHitEvents( b2BodyId bodyId, bool flag ); /// Get the world that owns this body B2_API b2WorldId b2Body_GetWorld( b2BodyId bodyId ); /// Get the number of shapes on this body B2_API int b2Body_GetShapeCount( b2BodyId bodyId ); /// Get the shape ids for all shapes on this body, up to the provided capacity. /// @returns the number of shape ids stored in the user array B2_API int b2Body_GetShapes( b2BodyId bodyId, b2ShapeId* shapeArray, int capacity ); /// Get the number of joints on this body B2_API int b2Body_GetJointCount( b2BodyId bodyId ); /// Get the joint ids for all joints on this body, up to the provided capacity /// @returns the number of joint ids stored in the user array B2_API int b2Body_GetJoints( b2BodyId bodyId, b2JointId* jointArray, int capacity ); /// Get the maximum capacity required for retrieving all the touching contacts on a body B2_API int b2Body_GetContactCapacity( b2BodyId bodyId ); /// Get the touching contact data for a body. /// @note Box2D uses speculative collision so some contact points may be separated. /// @returns the number of elements filled in the provided array /// @warning do not ignore the return value, it specifies the valid number of elements B2_API int b2Body_GetContactData( b2BodyId bodyId, b2ContactData* contactData, int capacity ); /// Get the current world AABB that contains all the attached shapes. Note that this may not encompass the body origin. /// If there are no shapes attached then the returned AABB is empty and centered on the body origin. B2_API b2AABB b2Body_ComputeAABB( b2BodyId bodyId ); /** @} */ /** * @defgroup shape Shape * Functions to create, destroy, and access. * Shapes bind raw geometry to bodies and hold material properties including friction and restitution. * @{ */ /// Create a circle shape and attach it to a body. The shape definition and geometry are fully cloned. /// Contacts are not created until the next time step. /// @return the shape id for accessing the shape B2_API b2ShapeId b2CreateCircleShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Circle* circle ); /// Create a line segment shape and attach it to a body. The shape definition and geometry are fully cloned. /// Contacts are not created until the next time step. /// @return the shape id for accessing the shape B2_API b2ShapeId b2CreateSegmentShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Segment* segment ); /// Create a capsule shape and attach it to a body. The shape definition and geometry are fully cloned. /// Contacts are not created until the next time step. /// @return the shape id for accessing the shape, this will be b2_nullShapeId if the length is too small. B2_API b2ShapeId b2CreateCapsuleShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Capsule* capsule ); /// Create a polygon shape and attach it to a body. The shape definition and geometry are fully cloned. /// Contacts are not created until the next time step. /// @return the shape id for accessing the shape B2_API b2ShapeId b2CreatePolygonShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Polygon* polygon ); /// Destroy a shape. You may defer the body mass update which can improve performance if several shapes on a /// body are destroyed at once. /// @see b2Body_ApplyMassFromShapes B2_API void b2DestroyShape( b2ShapeId shapeId, bool updateBodyMass ); /// Shape identifier validation. Provides validation for up to 64K allocations. B2_API bool b2Shape_IsValid( b2ShapeId id ); /// Get the type of a shape B2_API b2ShapeType b2Shape_GetType( b2ShapeId shapeId ); /// Get the id of the body that a shape is attached to B2_API b2BodyId b2Shape_GetBody( b2ShapeId shapeId ); /// Get the world that owns this shape B2_API b2WorldId b2Shape_GetWorld( b2ShapeId shapeId ); /// Returns true if the shape is a sensor. It is not possible to change a shape /// from sensor to solid dynamically because this breaks the contract for /// sensor events. B2_API bool b2Shape_IsSensor( b2ShapeId shapeId ); /// Set the user data for a shape B2_API void b2Shape_SetUserData( b2ShapeId shapeId, void* userData ); /// Get the user data for a shape. This is useful when you get a shape id /// from an event or query. B2_API void* b2Shape_GetUserData( b2ShapeId shapeId ); /// Set the mass density of a shape, usually in kg/m^2. /// This will optionally update the mass properties on the parent body. /// @see b2ShapeDef::density, b2Body_ApplyMassFromShapes B2_API void b2Shape_SetDensity( b2ShapeId shapeId, float density, bool updateBodyMass ); /// Get the density of a shape, usually in kg/m^2 B2_API float b2Shape_GetDensity( b2ShapeId shapeId ); /// Set the friction on a shape B2_API void b2Shape_SetFriction( b2ShapeId shapeId, float friction ); /// Get the friction of a shape B2_API float b2Shape_GetFriction( b2ShapeId shapeId ); /// Set the shape restitution (bounciness) B2_API void b2Shape_SetRestitution( b2ShapeId shapeId, float restitution ); /// Get the shape restitution B2_API float b2Shape_GetRestitution( b2ShapeId shapeId ); /// Set the user material identifier B2_API void b2Shape_SetUserMaterial( b2ShapeId shapeId, uint64_t material ); /// Get the user material identifier B2_API uint64_t b2Shape_GetUserMaterial( b2ShapeId shapeId ); /// Set the shape surface material B2_API void b2Shape_SetSurfaceMaterial( b2ShapeId shapeId, const b2SurfaceMaterial* surfaceMaterial ); /// Get the shape surface material B2_API b2SurfaceMaterial b2Shape_GetSurfaceMaterial( b2ShapeId shapeId ); /// Get the shape filter B2_API b2Filter b2Shape_GetFilter( b2ShapeId shapeId ); /// Set the current filter. This is almost as expensive as recreating the shape. This may cause /// contacts to be immediately destroyed. However contacts are not created until the next world step. /// Sensor overlap state is also not updated until the next world step. /// @see b2ShapeDef::filter B2_API void b2Shape_SetFilter( b2ShapeId shapeId, b2Filter filter ); /// Enable sensor events for this shape. /// @see b2ShapeDef::enableSensorEvents B2_API void b2Shape_EnableSensorEvents( b2ShapeId shapeId, bool flag ); /// Returns true if sensor events are enabled. B2_API bool b2Shape_AreSensorEventsEnabled( b2ShapeId shapeId ); /// Enable contact events for this shape. Only applies to kinematic and dynamic bodies. Ignored for sensors. /// @see b2ShapeDef::enableContactEvents /// @warning changing this at run-time may lead to lost begin/end events B2_API void b2Shape_EnableContactEvents( b2ShapeId shapeId, bool flag ); /// Returns true if contact events are enabled B2_API bool b2Shape_AreContactEventsEnabled( b2ShapeId shapeId ); /// Enable pre-solve contact events for this shape. Only applies to dynamic bodies. These are expensive /// and must be carefully handled due to multithreading. Ignored for sensors. /// @see b2PreSolveFcn B2_API void b2Shape_EnablePreSolveEvents( b2ShapeId shapeId, bool flag ); /// Returns true if pre-solve events are enabled B2_API bool b2Shape_ArePreSolveEventsEnabled( b2ShapeId shapeId ); /// Enable contact hit events for this shape. Ignored for sensors. /// @see b2WorldDef.hitEventThreshold B2_API void b2Shape_EnableHitEvents( b2ShapeId shapeId, bool flag ); /// Returns true if hit events are enabled B2_API bool b2Shape_AreHitEventsEnabled( b2ShapeId shapeId ); /// Test a point for overlap with a shape B2_API bool b2Shape_TestPoint( b2ShapeId shapeId, b2Vec2 point ); /// Ray cast a shape directly B2_API b2CastOutput b2Shape_RayCast( b2ShapeId shapeId, const b2RayCastInput* input ); /// Get a copy of the shape's circle. Asserts the type is correct. B2_API b2Circle b2Shape_GetCircle( b2ShapeId shapeId ); /// Get a copy of the shape's line segment. Asserts the type is correct. B2_API b2Segment b2Shape_GetSegment( b2ShapeId shapeId ); /// Get a copy of the shape's chain segment. These come from chain shapes. /// Asserts the type is correct. B2_API b2ChainSegment b2Shape_GetChainSegment( b2ShapeId shapeId ); /// Get a copy of the shape's capsule. Asserts the type is correct. B2_API b2Capsule b2Shape_GetCapsule( b2ShapeId shapeId ); /// Get a copy of the shape's convex polygon. Asserts the type is correct. B2_API b2Polygon b2Shape_GetPolygon( b2ShapeId shapeId ); /// Allows you to change a shape to be a circle or update the current circle. /// This does not modify the mass properties. /// @see b2Body_ApplyMassFromShapes B2_API void b2Shape_SetCircle( b2ShapeId shapeId, const b2Circle* circle ); /// Allows you to change a shape to be a capsule or update the current capsule. /// This does not modify the mass properties. /// @see b2Body_ApplyMassFromShapes B2_API void b2Shape_SetCapsule( b2ShapeId shapeId, const b2Capsule* capsule ); /// Allows you to change a shape to be a segment or update the current segment. B2_API void b2Shape_SetSegment( b2ShapeId shapeId, const b2Segment* segment ); /// Allows you to change a shape to be a polygon or update the current polygon. /// This does not modify the mass properties. /// @see b2Body_ApplyMassFromShapes B2_API void b2Shape_SetPolygon( b2ShapeId shapeId, const b2Polygon* polygon ); /// Get the parent chain id if the shape type is a chain segment, otherwise /// returns b2_nullChainId. B2_API b2ChainId b2Shape_GetParentChain( b2ShapeId shapeId ); /// Get the maximum capacity required for retrieving all the touching contacts on a shape B2_API int b2Shape_GetContactCapacity( b2ShapeId shapeId ); /// Get the touching contact data for a shape. The provided shapeId will be either shapeIdA or shapeIdB on the contact data. /// @note Box2D uses speculative collision so some contact points may be separated. /// @returns the number of elements filled in the provided array /// @warning do not ignore the return value, it specifies the valid number of elements B2_API int b2Shape_GetContactData( b2ShapeId shapeId, b2ContactData* contactData, int capacity ); /// Get the maximum capacity required for retrieving all the overlapped shapes on a sensor shape. /// This returns 0 if the provided shape is not a sensor. /// @param shapeId the id of a sensor shape /// @returns the required capacity to get all the overlaps in b2Shape_GetSensorOverlaps B2_API int b2Shape_GetSensorCapacity( b2ShapeId shapeId ); /// Get the overlap data for a sensor shape. /// @param shapeId the id of a sensor shape /// @param visitorIds a user allocated array that is filled with the overlapping shapes (visitors) /// @param capacity the capacity of overlappedShapes /// @returns the number of elements filled in the provided array /// @warning do not ignore the return value, it specifies the valid number of elements /// @warning overlaps may contain destroyed shapes so use b2Shape_IsValid to confirm each overlap B2_API int b2Shape_GetSensorData( b2ShapeId shapeId, b2ShapeId* visitorIds, int capacity ); /// Get the current world AABB B2_API b2AABB b2Shape_GetAABB( b2ShapeId shapeId ); /// Compute the mass data for a shape B2_API b2MassData b2Shape_ComputeMassData( b2ShapeId shapeId ); /// Get the closest point on a shape to a target point. Target and result are in world space. /// todo need sample B2_API b2Vec2 b2Shape_GetClosestPoint( b2ShapeId shapeId, b2Vec2 target ); /// Apply a wind force to the body for this shape using the density of air. This considers /// the projected area of the shape in the wind direction. This also considers /// the relative velocity of the shape. /// @param shapeId the shape id /// @param wind the wind velocity in world space /// @param drag the drag coefficient, the force that opposes the relative velocity /// @param lift the lift coefficient, the force that is perpendicular to the relative velocity /// @param wake should this wake the body B2_API void b2Shape_ApplyWind( b2ShapeId shapeId, b2Vec2 wind, float drag, float lift, bool wake ); /// Chain Shape /// Create a chain shape /// @see b2ChainDef for details B2_API b2ChainId b2CreateChain( b2BodyId bodyId, const b2ChainDef* def ); /// Destroy a chain shape B2_API void b2DestroyChain( b2ChainId chainId ); /// Get the world that owns this chain shape B2_API b2WorldId b2Chain_GetWorld( b2ChainId chainId ); /// Get the number of segments on this chain B2_API int b2Chain_GetSegmentCount( b2ChainId chainId ); /// Fill a user array with chain segment shape ids up to the specified capacity. Returns /// the actual number of segments returned. B2_API int b2Chain_GetSegments( b2ChainId chainId, b2ShapeId* segmentArray, int capacity ); /// Get the number of materials used on this chain. Must be 1 or the number of segments. B2_API int b2Chain_GetSurfaceMaterialCount( b2ChainId chainId ); /// Set a chain material. If the chain has only one material, this material is applied to all /// segments. Otherwise it is applied to a single segment. B2_API void b2Chain_SetSurfaceMaterial( b2ChainId chainId, const b2SurfaceMaterial* material, int materialIndex ); /// Get a chain material by index. B2_API b2SurfaceMaterial b2Chain_GetSurfaceMaterial( b2ChainId chainId, int materialIndex ); /// Chain identifier validation. Provides validation for up to 64K allocations. B2_API bool b2Chain_IsValid( b2ChainId id ); /** @} */ /** * @defgroup joint Joint * @brief Joints allow you to connect rigid bodies together while allowing various forms of relative motions. * @{ */ /// Destroy a joint. Optionally wake attached bodies. B2_API void b2DestroyJoint( b2JointId jointId, bool wakeAttached ); /// Joint identifier validation. Provides validation for up to 64K allocations. B2_API bool b2Joint_IsValid( b2JointId id ); /// Get the joint type B2_API b2JointType b2Joint_GetType( b2JointId jointId ); /// Get body A id on a joint B2_API b2BodyId b2Joint_GetBodyA( b2JointId jointId ); /// Get body B id on a joint B2_API b2BodyId b2Joint_GetBodyB( b2JointId jointId ); /// Get the world that owns this joint B2_API b2WorldId b2Joint_GetWorld( b2JointId jointId ); /// Set the local frame on bodyA B2_API void b2Joint_SetLocalFrameA( b2JointId jointId, b2Transform localFrame ); /// Get the local frame on bodyA B2_API b2Transform b2Joint_GetLocalFrameA( b2JointId jointId ); /// Set the local frame on bodyB B2_API void b2Joint_SetLocalFrameB( b2JointId jointId, b2Transform localFrame ); /// Get the local frame on bodyB B2_API b2Transform b2Joint_GetLocalFrameB( b2JointId jointId ); /// Toggle collision between connected bodies B2_API void b2Joint_SetCollideConnected( b2JointId jointId, bool shouldCollide ); /// Is collision allowed between connected bodies? B2_API bool b2Joint_GetCollideConnected( b2JointId jointId ); /// Set the user data on a joint B2_API void b2Joint_SetUserData( b2JointId jointId, void* userData ); /// Get the user data on a joint B2_API void* b2Joint_GetUserData( b2JointId jointId ); /// Wake the bodies connect to this joint B2_API void b2Joint_WakeBodies( b2JointId jointId ); /// Get the current constraint force for this joint. Usually in Newtons. B2_API b2Vec2 b2Joint_GetConstraintForce( b2JointId jointId ); /// Get the current constraint torque for this joint. Usually in Newton * meters. B2_API float b2Joint_GetConstraintTorque( b2JointId jointId ); /// Get the current linear separation error for this joint. Does not consider admissible movement. Usually in meters. B2_API float b2Joint_GetLinearSeparation( b2JointId jointId ); /// Get the current angular separation error for this joint. Does not consider admissible movement. Usually in meters. B2_API float b2Joint_GetAngularSeparation( b2JointId jointId ); /// Set the joint constraint tuning. Advanced feature. /// @param jointId the joint /// @param hertz the stiffness in Hertz (cycles per second) /// @param dampingRatio the non-dimensional damping ratio (one for critical damping) B2_API void b2Joint_SetConstraintTuning( b2JointId jointId, float hertz, float dampingRatio ); /// Get the joint constraint tuning. Advanced feature. B2_API void b2Joint_GetConstraintTuning( b2JointId jointId, float* hertz, float* dampingRatio ); /// Set the force threshold for joint events (Newtons) B2_API void b2Joint_SetForceThreshold( b2JointId jointId, float threshold ); /// Get the force threshold for joint events (Newtons) B2_API float b2Joint_GetForceThreshold( b2JointId jointId ); /// Set the torque threshold for joint events (N-m) B2_API void b2Joint_SetTorqueThreshold( b2JointId jointId, float threshold ); /// Get the torque threshold for joint events (N-m) B2_API float b2Joint_GetTorqueThreshold( b2JointId jointId ); /** * @defgroup distance_joint Distance Joint * @brief Functions for the distance joint. * @{ */ /// Create a distance joint /// @see b2DistanceJointDef for details B2_API b2JointId b2CreateDistanceJoint( b2WorldId worldId, const b2DistanceJointDef* def ); /// Set the rest length of a distance joint /// @param jointId The id for a distance joint /// @param length The new distance joint length B2_API void b2DistanceJoint_SetLength( b2JointId jointId, float length ); /// Get the rest length of a distance joint B2_API float b2DistanceJoint_GetLength( b2JointId jointId ); /// Enable/disable the distance joint spring. When disabled the distance joint is rigid. B2_API void b2DistanceJoint_EnableSpring( b2JointId jointId, bool enableSpring ); /// Is the distance joint spring enabled? B2_API bool b2DistanceJoint_IsSpringEnabled( b2JointId jointId ); /// Set the force range for the spring. B2_API void b2DistanceJoint_SetSpringForceRange( b2JointId jointId, float lowerForce, float upperForce ); /// Get the force range for the spring. B2_API void b2DistanceJoint_GetSpringForceRange( b2JointId jointId, float* lowerForce, float* upperForce ); /// Set the spring stiffness in Hertz B2_API void b2DistanceJoint_SetSpringHertz( b2JointId jointId, float hertz ); /// Set the spring damping ratio, non-dimensional B2_API void b2DistanceJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ); /// Get the spring Hertz B2_API float b2DistanceJoint_GetSpringHertz( b2JointId jointId ); /// Get the spring damping ratio B2_API float b2DistanceJoint_GetSpringDampingRatio( b2JointId jointId ); /// Enable joint limit. The limit only works if the joint spring is enabled. Otherwise the joint is rigid /// and the limit has no effect. B2_API void b2DistanceJoint_EnableLimit( b2JointId jointId, bool enableLimit ); /// Is the distance joint limit enabled? B2_API bool b2DistanceJoint_IsLimitEnabled( b2JointId jointId ); /// Set the minimum and maximum length parameters of a distance joint B2_API void b2DistanceJoint_SetLengthRange( b2JointId jointId, float minLength, float maxLength ); /// Get the distance joint minimum length B2_API float b2DistanceJoint_GetMinLength( b2JointId jointId ); /// Get the distance joint maximum length B2_API float b2DistanceJoint_GetMaxLength( b2JointId jointId ); /// Get the current length of a distance joint B2_API float b2DistanceJoint_GetCurrentLength( b2JointId jointId ); /// Enable/disable the distance joint motor B2_API void b2DistanceJoint_EnableMotor( b2JointId jointId, bool enableMotor ); /// Is the distance joint motor enabled? B2_API bool b2DistanceJoint_IsMotorEnabled( b2JointId jointId ); /// Set the distance joint motor speed, usually in meters per second B2_API void b2DistanceJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed ); /// Get the distance joint motor speed, usually in meters per second B2_API float b2DistanceJoint_GetMotorSpeed( b2JointId jointId ); /// Set the distance joint maximum motor force, usually in newtons B2_API void b2DistanceJoint_SetMaxMotorForce( b2JointId jointId, float force ); /// Get the distance joint maximum motor force, usually in newtons B2_API float b2DistanceJoint_GetMaxMotorForce( b2JointId jointId ); /// Get the distance joint current motor force, usually in newtons B2_API float b2DistanceJoint_GetMotorForce( b2JointId jointId ); /** @} */ /** * @defgroup motor_joint Motor Joint * @brief Functions for the motor joint. * * The motor joint is designed to control the movement of a body while still being * responsive to collisions. A spring controls the position and rotation. A velocity motor * can be used to control velocity and allows for friction in top-down games. Both types * of control can be combined. For example, you can have a spring with friction. * Position and velocity control have force and torque limits. * @{ */ /// Create a motor joint /// @see b2MotorJointDef for details B2_API b2JointId b2CreateMotorJoint( b2WorldId worldId, const b2MotorJointDef* def ); /// Set the desired relative linear velocity in meters per second B2_API void b2MotorJoint_SetLinearVelocity( b2JointId jointId, b2Vec2 velocity ); /// Get the desired relative linear velocity in meters per second B2_API b2Vec2 b2MotorJoint_GetLinearVelocity( b2JointId jointId ); /// Set the desired relative angular velocity in radians per second B2_API void b2MotorJoint_SetAngularVelocity( b2JointId jointId, float velocity ); /// Get the desired relative angular velocity in radians per second B2_API float b2MotorJoint_GetAngularVelocity( b2JointId jointId ); /// Set the motor joint maximum force, usually in newtons B2_API void b2MotorJoint_SetMaxVelocityForce( b2JointId jointId, float maxForce ); /// Get the motor joint maximum force, usually in newtons B2_API float b2MotorJoint_GetMaxVelocityForce( b2JointId jointId ); /// Set the motor joint maximum torque, usually in newton-meters B2_API void b2MotorJoint_SetMaxVelocityTorque( b2JointId jointId, float maxTorque ); /// Get the motor joint maximum torque, usually in newton-meters B2_API float b2MotorJoint_GetMaxVelocityTorque( b2JointId jointId ); /// Set the spring linear hertz stiffness B2_API void b2MotorJoint_SetLinearHertz( b2JointId jointId, float hertz ); /// Get the spring linear hertz stiffness B2_API float b2MotorJoint_GetLinearHertz( b2JointId jointId ); /// Set the spring linear damping ratio. Use 1.0 for critical damping. B2_API void b2MotorJoint_SetLinearDampingRatio( b2JointId jointId, float damping ); /// Get the spring linear damping ratio. B2_API float b2MotorJoint_GetLinearDampingRatio( b2JointId jointId ); /// Set the spring angular hertz stiffness B2_API void b2MotorJoint_SetAngularHertz( b2JointId jointId, float hertz ); /// Get the spring angular hertz stiffness B2_API float b2MotorJoint_GetAngularHertz( b2JointId jointId ); /// Set the spring angular damping ratio. Use 1.0 for critical damping. B2_API void b2MotorJoint_SetAngularDampingRatio( b2JointId jointId, float damping ); /// Get the spring angular damping ratio. B2_API float b2MotorJoint_GetAngularDampingRatio( b2JointId jointId ); /// Set the maximum spring force in newtons. B2_API void b2MotorJoint_SetMaxSpringForce( b2JointId jointId, float maxForce ); /// Get the maximum spring force in newtons. B2_API float b2MotorJoint_GetMaxSpringForce( b2JointId jointId ); /// Set the maximum spring torque in newtons * meters B2_API void b2MotorJoint_SetMaxSpringTorque( b2JointId jointId, float maxTorque ); /// Get the maximum spring torque in newtons * meters B2_API float b2MotorJoint_GetMaxSpringTorque( b2JointId jointId ); /**@}*/ /** * @defgroup filter_joint Filter Joint * @brief Functions for the filter joint. * * The filter joint is used to disable collision between two bodies. As a side effect of being a joint, it also * keeps the two bodies in the same simulation island. * @{ */ /// Create a filter joint. /// @see b2FilterJointDef for details B2_API b2JointId b2CreateFilterJoint( b2WorldId worldId, const b2FilterJointDef* def ); /**@}*/ /** * @defgroup prismatic_joint Prismatic Joint * @brief A prismatic joint allows for translation along a single axis with no rotation. * * The prismatic joint is useful for things like pistons and moving platforms, where you want a body to translate * along an axis and have no rotation. Also called a *slider* joint. * @{ */ /// Create a prismatic (slider) joint. /// @see b2PrismaticJointDef for details B2_API b2JointId b2CreatePrismaticJoint( b2WorldId worldId, const b2PrismaticJointDef* def ); /// Enable/disable the joint spring. B2_API void b2PrismaticJoint_EnableSpring( b2JointId jointId, bool enableSpring ); /// Is the prismatic joint spring enabled or not? B2_API bool b2PrismaticJoint_IsSpringEnabled( b2JointId jointId ); /// Set the prismatic joint stiffness in Hertz. /// This should usually be less than a quarter of the simulation rate. For example, if the simulation /// runs at 60Hz then the joint stiffness should be 15Hz or less. B2_API void b2PrismaticJoint_SetSpringHertz( b2JointId jointId, float hertz ); /// Get the prismatic joint stiffness in Hertz B2_API float b2PrismaticJoint_GetSpringHertz( b2JointId jointId ); /// Set the prismatic joint damping ratio (non-dimensional) B2_API void b2PrismaticJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ); /// Get the prismatic spring damping ratio (non-dimensional) B2_API float b2PrismaticJoint_GetSpringDampingRatio( b2JointId jointId ); /// Set the prismatic joint spring target angle, usually in meters B2_API void b2PrismaticJoint_SetTargetTranslation( b2JointId jointId, float translation ); /// Get the prismatic joint spring target translation, usually in meters B2_API float b2PrismaticJoint_GetTargetTranslation( b2JointId jointId ); /// Enable/disable a prismatic joint limit B2_API void b2PrismaticJoint_EnableLimit( b2JointId jointId, bool enableLimit ); /// Is the prismatic joint limit enabled? B2_API bool b2PrismaticJoint_IsLimitEnabled( b2JointId jointId ); /// Get the prismatic joint lower limit B2_API float b2PrismaticJoint_GetLowerLimit( b2JointId jointId ); /// Get the prismatic joint upper limit B2_API float b2PrismaticJoint_GetUpperLimit( b2JointId jointId ); /// Set the prismatic joint limits B2_API void b2PrismaticJoint_SetLimits( b2JointId jointId, float lower, float upper ); /// Enable/disable a prismatic joint motor B2_API void b2PrismaticJoint_EnableMotor( b2JointId jointId, bool enableMotor ); /// Is the prismatic joint motor enabled? B2_API bool b2PrismaticJoint_IsMotorEnabled( b2JointId jointId ); /// Set the prismatic joint motor speed, usually in meters per second B2_API void b2PrismaticJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed ); /// Get the prismatic joint motor speed, usually in meters per second B2_API float b2PrismaticJoint_GetMotorSpeed( b2JointId jointId ); /// Set the prismatic joint maximum motor force, usually in newtons B2_API void b2PrismaticJoint_SetMaxMotorForce( b2JointId jointId, float force ); /// Get the prismatic joint maximum motor force, usually in newtons B2_API float b2PrismaticJoint_GetMaxMotorForce( b2JointId jointId ); /// Get the prismatic joint current motor force, usually in newtons B2_API float b2PrismaticJoint_GetMotorForce( b2JointId jointId ); /// Get the current joint translation, usually in meters. B2_API float b2PrismaticJoint_GetTranslation( b2JointId jointId ); /// Get the current joint translation speed, usually in meters per second. B2_API float b2PrismaticJoint_GetSpeed( b2JointId jointId ); /** @} */ /** * @defgroup revolute_joint Revolute Joint * @brief A revolute joint allows for relative rotation in the 2D plane 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. * @{ */ /// Create a revolute joint /// @see b2RevoluteJointDef for details B2_API b2JointId b2CreateRevoluteJoint( b2WorldId worldId, const b2RevoluteJointDef* def ); /// Enable/disable the revolute joint spring B2_API void b2RevoluteJoint_EnableSpring( b2JointId jointId, bool enableSpring ); /// It the revolute angular spring enabled? B2_API bool b2RevoluteJoint_IsSpringEnabled( b2JointId jointId ); /// Set the revolute joint spring stiffness in Hertz B2_API void b2RevoluteJoint_SetSpringHertz( b2JointId jointId, float hertz ); /// Get the revolute joint spring stiffness in Hertz B2_API float b2RevoluteJoint_GetSpringHertz( b2JointId jointId ); /// Set the revolute joint spring damping ratio, non-dimensional B2_API void b2RevoluteJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ); /// Get the revolute joint spring damping ratio, non-dimensional B2_API float b2RevoluteJoint_GetSpringDampingRatio( b2JointId jointId ); /// Set the revolute joint spring target angle, radians B2_API void b2RevoluteJoint_SetTargetAngle( b2JointId jointId, float angle ); /// Get the revolute joint spring target angle, radians B2_API float b2RevoluteJoint_GetTargetAngle( b2JointId jointId ); /// Get the revolute joint current angle in radians relative to the reference angle /// @see b2RevoluteJointDef::referenceAngle B2_API float b2RevoluteJoint_GetAngle( b2JointId jointId ); /// Enable/disable the revolute joint limit B2_API void b2RevoluteJoint_EnableLimit( b2JointId jointId, bool enableLimit ); /// Is the revolute joint limit enabled? B2_API bool b2RevoluteJoint_IsLimitEnabled( b2JointId jointId ); /// Get the revolute joint lower limit in radians B2_API float b2RevoluteJoint_GetLowerLimit( b2JointId jointId ); /// Get the revolute joint upper limit in radians B2_API float b2RevoluteJoint_GetUpperLimit( b2JointId jointId ); /// Set the revolute joint limits in radians. It is expected that lower <= upper /// and that -0.99 * B2_PI <= lower && upper <= -0.99 * B2_PI. B2_API void b2RevoluteJoint_SetLimits( b2JointId jointId, float lower, float upper ); /// Enable/disable a revolute joint motor B2_API void b2RevoluteJoint_EnableMotor( b2JointId jointId, bool enableMotor ); /// Is the revolute joint motor enabled? B2_API bool b2RevoluteJoint_IsMotorEnabled( b2JointId jointId ); /// Set the revolute joint motor speed in radians per second B2_API void b2RevoluteJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed ); /// Get the revolute joint motor speed in radians per second B2_API float b2RevoluteJoint_GetMotorSpeed( b2JointId jointId ); /// Get the revolute joint current motor torque, usually in newton-meters B2_API float b2RevoluteJoint_GetMotorTorque( b2JointId jointId ); /// Set the revolute joint maximum motor torque, usually in newton-meters B2_API void b2RevoluteJoint_SetMaxMotorTorque( b2JointId jointId, float torque ); /// Get the revolute joint maximum motor torque, usually in newton-meters B2_API float b2RevoluteJoint_GetMaxMotorTorque( b2JointId jointId ); /**@}*/ /** * @defgroup weld_joint Weld Joint * @brief A weld joint fully constrains the relative transform between two bodies while allowing for springiness * * A weld joint constrains the relative rotation and translation between two bodies. Both rotation and translation * can have damped springs. * * @note The accuracy of weld joint is limited by the accuracy of the solver. Long chains of weld joints may flex. * @{ */ /// Create a weld joint /// @see b2WeldJointDef for details B2_API b2JointId b2CreateWeldJoint( b2WorldId worldId, const b2WeldJointDef* def ); /// Set the weld joint linear stiffness in Hertz. 0 is rigid. B2_API void b2WeldJoint_SetLinearHertz( b2JointId jointId, float hertz ); /// Get the weld joint linear stiffness in Hertz B2_API float b2WeldJoint_GetLinearHertz( b2JointId jointId ); /// Set the weld joint linear damping ratio (non-dimensional) B2_API void b2WeldJoint_SetLinearDampingRatio( b2JointId jointId, float dampingRatio ); /// Get the weld joint linear damping ratio (non-dimensional) B2_API float b2WeldJoint_GetLinearDampingRatio( b2JointId jointId ); /// Set the weld joint angular stiffness in Hertz. 0 is rigid. B2_API void b2WeldJoint_SetAngularHertz( b2JointId jointId, float hertz ); /// Get the weld joint angular stiffness in Hertz B2_API float b2WeldJoint_GetAngularHertz( b2JointId jointId ); /// Set weld joint angular damping ratio, non-dimensional B2_API void b2WeldJoint_SetAngularDampingRatio( b2JointId jointId, float dampingRatio ); /// Get the weld joint angular damping ratio, non-dimensional B2_API float b2WeldJoint_GetAngularDampingRatio( b2JointId jointId ); /** @} */ /** * @defgroup wheel_joint Wheel Joint * The wheel joint can be used to simulate wheels on vehicles. * * The wheel joint restricts body B to move along a local axis in body A. Body B is free to * rotate. Supports a linear spring, linear limits, and a rotational motor. * * @{ */ /// Create a wheel joint /// @see b2WheelJointDef for details B2_API b2JointId b2CreateWheelJoint( b2WorldId worldId, const b2WheelJointDef* def ); /// Enable/disable the wheel joint spring B2_API void b2WheelJoint_EnableSpring( b2JointId jointId, bool enableSpring ); /// Is the wheel joint spring enabled? B2_API bool b2WheelJoint_IsSpringEnabled( b2JointId jointId ); /// Set the wheel joint stiffness in Hertz B2_API void b2WheelJoint_SetSpringHertz( b2JointId jointId, float hertz ); /// Get the wheel joint stiffness in Hertz B2_API float b2WheelJoint_GetSpringHertz( b2JointId jointId ); /// Set the wheel joint damping ratio, non-dimensional B2_API void b2WheelJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ); /// Get the wheel joint damping ratio, non-dimensional B2_API float b2WheelJoint_GetSpringDampingRatio( b2JointId jointId ); /// Enable/disable the wheel joint limit B2_API void b2WheelJoint_EnableLimit( b2JointId jointId, bool enableLimit ); /// Is the wheel joint limit enabled? B2_API bool b2WheelJoint_IsLimitEnabled( b2JointId jointId ); /// Get the wheel joint lower limit B2_API float b2WheelJoint_GetLowerLimit( b2JointId jointId ); /// Get the wheel joint upper limit B2_API float b2WheelJoint_GetUpperLimit( b2JointId jointId ); /// Set the wheel joint limits B2_API void b2WheelJoint_SetLimits( b2JointId jointId, float lower, float upper ); /// Enable/disable the wheel joint motor B2_API void b2WheelJoint_EnableMotor( b2JointId jointId, bool enableMotor ); /// Is the wheel joint motor enabled? B2_API bool b2WheelJoint_IsMotorEnabled( b2JointId jointId ); /// Set the wheel joint motor speed in radians per second B2_API void b2WheelJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed ); /// Get the wheel joint motor speed in radians per second B2_API float b2WheelJoint_GetMotorSpeed( b2JointId jointId ); /// Set the wheel joint maximum motor torque, usually in newton-meters B2_API void b2WheelJoint_SetMaxMotorTorque( b2JointId jointId, float torque ); /// Get the wheel joint maximum motor torque, usually in newton-meters B2_API float b2WheelJoint_GetMaxMotorTorque( b2JointId jointId ); /// Get the wheel joint current motor torque, usually in newton-meters B2_API float b2WheelJoint_GetMotorTorque( b2JointId jointId ); /**@}*/ /**@}*/ /** * @defgroup contact Contact * Access to contacts * @{ */ /// Contact identifier validation. Provides validation for up to 2^32 allocations. B2_API bool b2Contact_IsValid( b2ContactId id ); /// Get the data for a contact. The manifold may have no points if the contact is not touching. B2_API b2ContactData b2Contact_GetData( b2ContactId contactId ); /**@}*/ ================================================ FILE: include/box2d/collision.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "base.h" #include "math_functions.h" #include typedef struct b2SimplexCache b2SimplexCache; typedef struct b2Hull b2Hull; /** * @defgroup geometry Geometry * @brief Geometry types and algorithms * * Definitions of circles, capsules, segments, and polygons. Various algorithms to compute hulls, mass properties, and so on. * Functions should take the shape as the first argument to assist editor auto-complete. * @{ */ /// The maximum number of vertices on a convex polygon. Changing this affects performance even if you /// don't use more vertices. #define B2_MAX_POLYGON_VERTICES 8 /// Low level ray cast input data typedef struct b2RayCastInput { /// Start point of the ray cast b2Vec2 origin; /// Translation of the ray cast b2Vec2 translation; /// The maximum fraction of the translation to consider, typically 1 float maxFraction; } b2RayCastInput; /// A distance proxy is used by the GJK algorithm. It encapsulates any shape. /// You can provide between 1 and B2_MAX_POLYGON_VERTICES and a radius. typedef struct b2ShapeProxy { /// The point cloud b2Vec2 points[B2_MAX_POLYGON_VERTICES]; /// The number of points. Must be greater than 0. int count; /// The external radius of the point cloud. May be zero. float radius; } b2ShapeProxy; /// Low level shape cast input in generic form. This allows casting an arbitrary point /// cloud wrap with a radius. For example, a circle is a single point with a non-zero radius. /// A capsule is two points with a non-zero radius. A box is four points with a zero radius. typedef struct b2ShapeCastInput { /// A generic shape b2ShapeProxy proxy; /// The translation of the shape cast b2Vec2 translation; /// The maximum fraction of the translation to consider, typically 1 float maxFraction; /// Allow shape cast to encroach when initially touching. This only works if the radius is greater than zero. bool canEncroach; } b2ShapeCastInput; /// Low level ray cast or shape-cast output data. Returns a zero fraction and normal in the case of initial overlap. typedef struct b2CastOutput { /// The surface normal at the hit point b2Vec2 normal; /// The surface hit point b2Vec2 point; /// The fraction of the input translation at collision float fraction; /// The number of iterations used int iterations; /// Did the cast hit? bool hit; } b2CastOutput; /// This holds the mass data computed for a shape. typedef struct b2MassData { /// The mass of the shape, usually in kilograms. float mass; /// The position of the shape's centroid relative to the shape's origin. b2Vec2 center; /// The rotational inertia of the shape about the shape center. float rotationalInertia; } b2MassData; /// A solid circle typedef struct b2Circle { /// The local center b2Vec2 center; /// The radius float radius; } b2Circle; /// A solid capsule can be viewed as two semicircles connected /// by a rectangle. typedef struct b2Capsule { /// Local center of the first semicircle b2Vec2 center1; /// Local center of the second semicircle b2Vec2 center2; /// The radius of the semicircles float radius; } b2Capsule; /// A solid convex polygon. It is assumed that the interior of the polygon is to /// the left of each edge. /// Polygons have a maximum number of vertices equal to B2_MAX_POLYGON_VERTICES. /// In most cases you should not need many vertices for a convex polygon. /// @warning DO NOT fill this out manually, instead use a helper function like /// b2MakePolygon or b2MakeBox. typedef struct b2Polygon { /// The polygon vertices b2Vec2 vertices[B2_MAX_POLYGON_VERTICES]; /// The outward normal vectors of the polygon sides b2Vec2 normals[B2_MAX_POLYGON_VERTICES]; /// The centroid of the polygon b2Vec2 centroid; /// The external radius for rounded polygons float radius; /// The number of polygon vertices int count; } b2Polygon; /// A line segment with two-sided collision. typedef struct b2Segment { /// The first point b2Vec2 point1; /// The second point b2Vec2 point2; } b2Segment; /// A line segment with one-sided collision. Only collides on the right side. /// Several of these are generated for a chain shape. /// ghost1 -> point1 -> point2 -> ghost2 typedef struct b2ChainSegment { /// The tail ghost vertex b2Vec2 ghost1; /// The line segment b2Segment segment; /// The head ghost vertex b2Vec2 ghost2; /// The owning chain shape index (internal usage only) int chainId; } b2ChainSegment; /// Validate ray cast input data (NaN, etc) B2_API bool b2IsValidRay( const b2RayCastInput* input ); /// Make a convex polygon from a convex hull. This will assert if the hull is not valid. /// @warning Do not manually fill in the hull data, it must come directly from b2ComputeHull B2_API b2Polygon b2MakePolygon( const b2Hull* hull, float radius ); /// Make an offset convex polygon from a convex hull. This will assert if the hull is not valid. /// @warning Do not manually fill in the hull data, it must come directly from b2ComputeHull B2_API b2Polygon b2MakeOffsetPolygon( const b2Hull* hull, b2Vec2 position, b2Rot rotation ); /// Make an offset convex polygon from a convex hull. This will assert if the hull is not valid. /// @warning Do not manually fill in the hull data, it must come directly from b2ComputeHull B2_API b2Polygon b2MakeOffsetRoundedPolygon( const b2Hull* hull, b2Vec2 position, b2Rot rotation, float radius ); /// Make a square polygon, bypassing the need for a convex hull. /// @param halfWidth the half-width B2_API b2Polygon b2MakeSquare( float halfWidth ); /// Make a box (rectangle) polygon, bypassing the need for a convex hull. /// @param halfWidth the half-width (x-axis) /// @param halfHeight the half-height (y-axis) B2_API b2Polygon b2MakeBox( float halfWidth, float halfHeight ); /// Make a rounded box, bypassing the need for a convex hull. /// @param halfWidth the half-width (x-axis) /// @param halfHeight the half-height (y-axis) /// @param radius the radius of the rounded extension B2_API b2Polygon b2MakeRoundedBox( float halfWidth, float halfHeight, float radius ); /// Make an offset box, bypassing the need for a convex hull. /// @param halfWidth the half-width (x-axis) /// @param halfHeight the half-height (y-axis) /// @param center the local center of the box /// @param rotation the local rotation of the box B2_API b2Polygon b2MakeOffsetBox( float halfWidth, float halfHeight, b2Vec2 center, b2Rot rotation ); /// Make an offset rounded box, bypassing the need for a convex hull. /// @param halfWidth the half-width (x-axis) /// @param halfHeight the half-height (y-axis) /// @param center the local center of the box /// @param rotation the local rotation of the box /// @param radius the radius of the rounded extension B2_API b2Polygon b2MakeOffsetRoundedBox( float halfWidth, float halfHeight, b2Vec2 center, b2Rot rotation, float radius ); /// Transform a polygon. This is useful for transferring a shape from one body to another. B2_API b2Polygon b2TransformPolygon( b2Transform transform, const b2Polygon* polygon ); /// Compute mass properties of a circle B2_API b2MassData b2ComputeCircleMass( const b2Circle* shape, float density ); /// Compute mass properties of a capsule B2_API b2MassData b2ComputeCapsuleMass( const b2Capsule* shape, float density ); /// Compute mass properties of a polygon B2_API b2MassData b2ComputePolygonMass( const b2Polygon* shape, float density ); /// Compute the bounding box of a transformed circle B2_API b2AABB b2ComputeCircleAABB( const b2Circle* shape, b2Transform transform ); /// Compute the bounding box of a transformed capsule B2_API b2AABB b2ComputeCapsuleAABB( const b2Capsule* shape, b2Transform transform ); /// Compute the bounding box of a transformed polygon B2_API b2AABB b2ComputePolygonAABB( const b2Polygon* shape, b2Transform transform ); /// Compute the bounding box of a transformed line segment B2_API b2AABB b2ComputeSegmentAABB( const b2Segment* shape, b2Transform transform ); /// Test a point for overlap with a circle in local space B2_API bool b2PointInCircle( const b2Circle* shape, b2Vec2 point ); /// Test a point for overlap with a capsule in local space B2_API bool b2PointInCapsule( const b2Capsule* shape, b2Vec2 point ); /// Test a point for overlap with a convex polygon in local space B2_API bool b2PointInPolygon( const b2Polygon* shape, b2Vec2 point ); /// Ray cast versus circle shape in local space. B2_API b2CastOutput b2RayCastCircle( const b2Circle* shape, const b2RayCastInput* input ); /// Ray cast versus capsule shape in local space. B2_API b2CastOutput b2RayCastCapsule( const b2Capsule* shape, const b2RayCastInput* input ); /// Ray cast versus segment shape in local space. Optionally treat the segment as one-sided with hits from /// the left side being treated as a miss. B2_API b2CastOutput b2RayCastSegment( const b2Segment* shape, const b2RayCastInput* input, bool oneSided ); /// Ray cast versus polygon shape in local space. B2_API b2CastOutput b2RayCastPolygon( const b2Polygon* shape, const b2RayCastInput* input ); /// Shape cast versus a circle. B2_API b2CastOutput b2ShapeCastCircle(const b2Circle* shape, const b2ShapeCastInput* input ); /// Shape cast versus a capsule. B2_API b2CastOutput b2ShapeCastCapsule( const b2Capsule* shape, const b2ShapeCastInput* input); /// Shape cast versus a line segment. B2_API b2CastOutput b2ShapeCastSegment( const b2Segment* shape, const b2ShapeCastInput* input ); /// Shape cast versus a convex polygon. B2_API b2CastOutput b2ShapeCastPolygon( const b2Polygon* shape, const b2ShapeCastInput* input ); /// A convex hull. Used to create convex polygons. /// @warning Do not modify these values directly, instead use b2ComputeHull() typedef struct b2Hull { /// The final points of the hull b2Vec2 points[B2_MAX_POLYGON_VERTICES]; /// The number of points int count; } b2Hull; /// Compute the convex hull of a set of points. Returns an empty hull if it fails. /// Some failure cases: /// - all points very close together /// - all points on a line /// - less than 3 points /// - more than B2_MAX_POLYGON_VERTICES points /// This welds close points and removes collinear points. /// @warning Do not modify a hull once it has been computed B2_API b2Hull b2ComputeHull( const b2Vec2* points, int count ); /// This determines if a hull is valid. Checks for: /// - convexity /// - collinear points /// This is expensive and should not be called at runtime. B2_API bool b2ValidateHull( const b2Hull* hull ); /**@}*/ /** * @defgroup distance Distance * Functions for computing the distance between shapes. * * These are advanced functions you can use to perform distance calculations. There * are functions for computing the closest points between shapes, doing linear shape casts, * and doing rotational shape casts. The latter is called time of impact (TOI). * @{ */ /// Result of computing the distance between two line segments typedef struct b2SegmentDistanceResult { /// The closest point on the first segment b2Vec2 closest1; /// The closest point on the second segment b2Vec2 closest2; /// The barycentric coordinate on the first segment float fraction1; /// The barycentric coordinate on the second segment float fraction2; /// The squared distance between the closest points float distanceSquared; } b2SegmentDistanceResult; /// Compute the distance between two line segments, clamping at the end points if needed. B2_API b2SegmentDistanceResult b2SegmentDistance( b2Vec2 p1, b2Vec2 q1, b2Vec2 p2, b2Vec2 q2 ); /// Used to warm start the GJK simplex. If you call this function multiple times with nearby /// transforms this might improve performance. Otherwise you can zero initialize this. /// The distance cache must be initialized to zero on the first call. /// Users should generally just zero initialize this structure for each call. typedef struct b2SimplexCache { /// The number of stored simplex points uint16_t count; /// The cached simplex indices on shape A uint8_t indexA[3]; /// The cached simplex indices on shape B uint8_t indexB[3]; } b2SimplexCache; static const b2SimplexCache b2_emptySimplexCache = B2_ZERO_INIT; /// Input for b2ShapeDistance typedef struct b2DistanceInput { /// The proxy for shape A b2ShapeProxy proxyA; /// The proxy for shape B b2ShapeProxy proxyB; /// The world transform for shape A b2Transform transformA; /// The world transform for shape B b2Transform transformB; /// Should the proxy radius be considered? bool useRadii; } b2DistanceInput; /// Output for b2ShapeDistance typedef struct b2DistanceOutput { b2Vec2 pointA; ///< Closest point on shapeA b2Vec2 pointB; ///< Closest point on shapeB b2Vec2 normal; ///< Normal vector that points from A to B. Invalid if distance is zero. float distance; ///< The final distance, zero if overlapped int iterations; ///< Number of GJK iterations used int simplexCount; ///< The number of simplexes stored in the simplex array } b2DistanceOutput; /// Simplex vertex for debugging the GJK algorithm typedef struct b2SimplexVertex { b2Vec2 wA; ///< support point in proxyA b2Vec2 wB; ///< support point in proxyB b2Vec2 w; ///< wB - wA float a; ///< barycentric coordinate for closest point int indexA; ///< wA index int indexB; ///< wB index } b2SimplexVertex; /// Simplex from the GJK algorithm typedef struct b2Simplex { b2SimplexVertex v1, v2, v3; ///< vertices int count; ///< number of valid vertices } b2Simplex; /// Compute the closest points between two shapes represented as point clouds. /// b2SimplexCache cache is input/output. On the first call set b2SimplexCache.count to zero. /// The underlying GJK algorithm may be debugged by passing in debug simplexes and capacity. You may pass in NULL and 0 for these. B2_API b2DistanceOutput b2ShapeDistance( const b2DistanceInput* input, b2SimplexCache* cache, b2Simplex* simplexes, int simplexCapacity ); /// Input parameters for b2ShapeCast typedef struct b2ShapeCastPairInput { b2ShapeProxy proxyA; ///< The proxy for shape A b2ShapeProxy proxyB; ///< The proxy for shape B b2Transform transformA; ///< The world transform for shape A b2Transform transformB; ///< The world transform for shape B b2Vec2 translationB; ///< The translation of shape B float maxFraction; ///< The fraction of the translation to consider, typically 1 bool canEncroach; ///< Allows shapes with a radius to move slightly closer if already touching } b2ShapeCastPairInput; /// Perform a linear shape cast of shape B moving and shape A fixed. Determines the hit point, normal, and translation fraction. /// Initially touching shapes are treated as a miss. B2_API b2CastOutput b2ShapeCast( const b2ShapeCastPairInput* input ); /// Make a proxy for use in overlap, shape cast, and related functions. This is a deep copy of the points. B2_API b2ShapeProxy b2MakeProxy( const b2Vec2* points, int count, float radius ); /// Make a proxy with a transform. This is a deep copy of the points. B2_API b2ShapeProxy b2MakeOffsetProxy( const b2Vec2* points, int count, float radius, b2Vec2 position, b2Rot rotation ); /// This describes the motion of a body/shape for TOI computation. Shapes are defined with respect to the body origin, /// which may not coincide with the center of mass. However, to support dynamics we must interpolate the center of mass /// position. typedef struct b2Sweep { b2Vec2 localCenter; ///< Local center of mass position b2Vec2 c1; ///< Starting center of mass world position b2Vec2 c2; ///< Ending center of mass world position b2Rot q1; ///< Starting world rotation b2Rot q2; ///< Ending world rotation } b2Sweep; /// Evaluate the transform sweep at a specific time. B2_API b2Transform b2GetSweepTransform( const b2Sweep* sweep, float time ); /// Time of impact input typedef struct b2TOIInput { b2ShapeProxy proxyA; ///< The proxy for shape A b2ShapeProxy proxyB; ///< The proxy for shape B b2Sweep sweepA; ///< The movement of shape A b2Sweep sweepB; ///< The movement of shape B float maxFraction; ///< Defines the sweep interval [0, maxFraction] } b2TOIInput; /// Describes the TOI output typedef enum b2TOIState { b2_toiStateUnknown, b2_toiStateFailed, b2_toiStateOverlapped, b2_toiStateHit, b2_toiStateSeparated } b2TOIState; /// Time of impact output typedef struct b2TOIOutput { /// The type of result b2TOIState state; /// The hit point b2Vec2 point; /// The hit normal b2Vec2 normal; /// The sweep time of the collision float fraction; } b2TOIOutput; /// Compute the upper bound on time before two shapes penetrate. Time is represented as /// a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate, /// non-tunneling collisions. If you change the time interval, you should call this function /// again. B2_API b2TOIOutput b2TimeOfImpact( const b2TOIInput* input ); /**@}*/ /** * @defgroup collision Collision * @brief Functions for colliding pairs of shapes * @{ */ /// A manifold point is a contact point belonging to a contact manifold. /// It holds details related to the geometry and dynamics of the contact points. /// Box2D uses speculative collision so some contact points may be separated. /// You may use the totalNormalImpulse to determine if there was an interaction during /// the time step. typedef struct b2ManifoldPoint { /// Location of the contact point in world space. Subject to precision loss at large coordinates. /// @note Should only be used for debugging. b2Vec2 point; /// Location of the contact point relative to shapeA's origin in world space /// @note When used internally to the Box2D solver, this is relative to the body center of mass. b2Vec2 anchorA; /// Location of the contact point relative to shapeB's origin in world space /// @note When used internally to the Box2D solver, this is relative to the body center of mass. b2Vec2 anchorB; /// The separation of the contact point, negative if penetrating float separation; /// The impulse along the manifold normal vector. float normalImpulse; /// The friction impulse float tangentImpulse; /// The total normal impulse applied across sub-stepping and restitution. This is important /// to identify speculative contact points that had an interaction in the time step. /// This includes the warm starting impulse, the sub-step delta impulse, and the restitution /// impulse. float totalNormalImpulse; /// Relative normal velocity pre-solve. Used for hit events. If the normal impulse is /// zero then there was no hit. Negative means shapes are approaching. float normalVelocity; /// Uniquely identifies a contact point between two shapes uint16_t id; /// Did this contact point exist the previous step? bool persisted; } b2ManifoldPoint; /// A contact manifold describes the contact points between colliding shapes. /// @note Box2D uses speculative collision so some contact points may be separated. typedef struct b2Manifold { /// The unit normal vector in world space, points from shape A to bodyB b2Vec2 normal; /// Angular impulse applied for rolling resistance. N * m * s = kg * m^2 / s float rollingImpulse; /// The manifold points, up to two are possible in 2D b2ManifoldPoint points[2]; /// The number of contacts points, will be 0, 1, or 2 int pointCount; } b2Manifold; /// Compute the contact manifold between two circles B2_API b2Manifold b2CollideCircles( const b2Circle* circleA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB ); /// Compute the contact manifold between a capsule and circle B2_API b2Manifold b2CollideCapsuleAndCircle( const b2Capsule* capsuleA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB ); /// Compute the contact manifold between an segment and a circle B2_API b2Manifold b2CollideSegmentAndCircle( const b2Segment* segmentA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB ); /// Compute the contact manifold between a polygon and a circle B2_API b2Manifold b2CollidePolygonAndCircle( const b2Polygon* polygonA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB ); /// Compute the contact manifold between a capsule and circle B2_API b2Manifold b2CollideCapsules( const b2Capsule* capsuleA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB ); /// Compute the contact manifold between an segment and a capsule B2_API b2Manifold b2CollideSegmentAndCapsule( const b2Segment* segmentA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB ); /// Compute the contact manifold between a polygon and capsule B2_API b2Manifold b2CollidePolygonAndCapsule( const b2Polygon* polygonA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB ); /// Compute the contact manifold between two polygons B2_API b2Manifold b2CollidePolygons( const b2Polygon* polygonA, b2Transform xfA, const b2Polygon* polygonB, b2Transform xfB ); /// Compute the contact manifold between an segment and a polygon B2_API b2Manifold b2CollideSegmentAndPolygon( const b2Segment* segmentA, b2Transform xfA, const b2Polygon* polygonB, b2Transform xfB ); /// Compute the contact manifold between a chain segment and a circle B2_API b2Manifold b2CollideChainSegmentAndCircle( const b2ChainSegment* segmentA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB ); /// Compute the contact manifold between a chain segment and a capsule B2_API b2Manifold b2CollideChainSegmentAndCapsule( const b2ChainSegment* segmentA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB, b2SimplexCache* cache ); /// Compute the contact manifold between a chain segment and a rounded polygon B2_API b2Manifold b2CollideChainSegmentAndPolygon( const b2ChainSegment* segmentA, b2Transform xfA, const b2Polygon* polygonB, b2Transform xfB, b2SimplexCache* cache ); /**@}*/ /** * @defgroup tree Dynamic Tree * The dynamic tree is a binary AABB tree to organize and query large numbers of geometric objects * * Box2D uses the dynamic tree internally to sort collision shapes into a binary bounding volume hierarchy. * This data structure may have uses in games for organizing other geometry data and may be used independently * of Box2D rigid body simulation. * * A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt. * A dynamic tree arranges data in a binary tree to accelerate * queries such as AABB queries and ray casts. Leaf nodes are proxies * with an AABB. These are used to hold a user collision object. * Nodes are pooled and relocatable, so I use node indices rather than pointers. * The dynamic tree is made available for advanced users that would like to use it to organize * spatial game data besides rigid bodies. * @{ */ /// The dynamic tree structure. This should be considered private data. /// It is placed here for performance reasons. typedef struct b2DynamicTree { /// The tree nodes struct b2TreeNode* nodes; /// The root index int32_t root; /// The number of nodes int32_t nodeCount; /// The allocated node space int32_t nodeCapacity; /// Node free list int32_t freeList; /// Number of proxies created int32_t proxyCount; /// Leaf indices for rebuild int32_t* leafIndices; /// Leaf bounding boxes for rebuild b2AABB* leafBoxes; /// Leaf bounding box centers for rebuild b2Vec2* leafCenters; /// Bins for sorting during rebuild int32_t* binIndices; /// Allocated space for rebuilding int32_t rebuildCapacity; } b2DynamicTree; /// These are performance results returned by dynamic tree queries. typedef struct b2TreeStats { /// Number of internal nodes visited during the query int nodeVisits; /// Number of leaf nodes visited during the query int leafVisits; } b2TreeStats; /// Constructing the tree initializes the node pool. B2_API b2DynamicTree b2DynamicTree_Create( void ); /// Destroy the tree, freeing the node pool. B2_API void b2DynamicTree_Destroy( b2DynamicTree* tree ); /// Create a proxy. Provide an AABB and a userData value. B2_API int b2DynamicTree_CreateProxy( b2DynamicTree* tree, b2AABB aabb, uint64_t categoryBits, uint64_t userData ); /// Destroy a proxy. This asserts if the id is invalid. B2_API void b2DynamicTree_DestroyProxy( b2DynamicTree* tree, int proxyId ); /// Move a proxy to a new AABB by removing and reinserting into the tree. B2_API void b2DynamicTree_MoveProxy( b2DynamicTree* tree, int proxyId, b2AABB aabb ); /// Enlarge a proxy and enlarge ancestors as necessary. B2_API void b2DynamicTree_EnlargeProxy( b2DynamicTree* tree, int proxyId, b2AABB aabb ); /// Modify the category bits on a proxy. This is an expensive operation. B2_API void b2DynamicTree_SetCategoryBits( b2DynamicTree* tree, int proxyId, uint64_t categoryBits ); /// Get the category bits on a proxy. B2_API uint64_t b2DynamicTree_GetCategoryBits( b2DynamicTree* tree, int proxyId ); /// This function receives proxies found in the AABB query. /// @return true if the query should continue typedef bool b2TreeQueryCallbackFcn( int proxyId, uint64_t userData, void* context ); /// Query an AABB for overlapping proxies. The callback class is called for each proxy that overlaps the supplied AABB. /// @return performance data B2_API b2TreeStats b2DynamicTree_Query( const b2DynamicTree* tree, b2AABB aabb, uint64_t maskBits, b2TreeQueryCallbackFcn* callback, void* context ); /// Query an AABB for overlapping proxies. The callback class is called for each proxy that overlaps the supplied AABB. /// No filtering is performed. /// @return performance data B2_API b2TreeStats b2DynamicTree_QueryAll( const b2DynamicTree* tree, b2AABB aabb, b2TreeQueryCallbackFcn* callback, void* context ); /// This function receives clipped ray cast input for a proxy. The function /// returns the new ray fraction. /// - return a value of 0 to terminate the ray cast /// - return a value less than input->maxFraction to clip the ray /// - return a value of input->maxFraction to continue the ray cast without clipping typedef float b2TreeRayCastCallbackFcn( const b2RayCastInput* input, int proxyId, uint64_t userData, void* context ); /// Ray cast against the proxies in the tree. This relies on the callback /// to perform a exact ray cast in the case were the proxy contains a shape. /// The callback also performs the any collision filtering. This has performance /// roughly equal to k * log(n), where k is the number of collisions and n is the /// number of proxies in the tree. /// Bit-wise filtering using mask bits can greatly improve performance in some scenarios. /// However, this filtering may be approximate, so the user should still apply filtering to results. /// @param tree the dynamic tree to ray cast /// @param input the ray cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1) /// @param maskBits mask bit hint: `bool accept = (maskBits & node->categoryBits) != 0;` /// @param callback a callback class that is called for each proxy that is hit by the ray /// @param context user context that is passed to the callback /// @return performance data B2_API b2TreeStats b2DynamicTree_RayCast( const b2DynamicTree* tree, const b2RayCastInput* input, uint64_t maskBits, b2TreeRayCastCallbackFcn* callback, void* context ); /// This function receives clipped ray cast input for a proxy. The function /// returns the new ray fraction. /// - return a value of 0 to terminate the ray cast /// - return a value less than input->maxFraction to clip the ray /// - return a value of input->maxFraction to continue the ray cast without clipping typedef float b2TreeShapeCastCallbackFcn( const b2ShapeCastInput* input, int proxyId, uint64_t userData, void* context ); /// Ray cast against the proxies in the tree. This relies on the callback /// to perform a exact ray cast in the case were the proxy contains a shape. /// The callback also performs the any collision filtering. This has performance /// roughly equal to k * log(n), where k is the number of collisions and n is the /// number of proxies in the tree. /// @param tree the dynamic tree to ray cast /// @param input the ray cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). /// @param maskBits filter bits: `bool accept = (maskBits & node->categoryBits) != 0;` /// @param callback a callback class that is called for each proxy that is hit by the shape /// @param context user context that is passed to the callback /// @return performance data B2_API b2TreeStats b2DynamicTree_ShapeCast( const b2DynamicTree* tree, const b2ShapeCastInput* input, uint64_t maskBits, b2TreeShapeCastCallbackFcn* callback, void* context ); /// Get the height of the binary tree. B2_API int b2DynamicTree_GetHeight( const b2DynamicTree* tree ); /// Get the ratio of the sum of the node areas to the root area. B2_API float b2DynamicTree_GetAreaRatio( const b2DynamicTree* tree ); /// Get the bounding box that contains the entire tree B2_API b2AABB b2DynamicTree_GetRootBounds( const b2DynamicTree* tree ); /// Get the number of proxies created B2_API int b2DynamicTree_GetProxyCount( const b2DynamicTree* tree ); /// Rebuild the tree while retaining subtrees that haven't changed. Returns the number of boxes sorted. B2_API int b2DynamicTree_Rebuild( b2DynamicTree* tree, bool fullBuild ); /// Get the number of bytes used by this tree B2_API int b2DynamicTree_GetByteCount( const b2DynamicTree* tree ); /// Get proxy user data B2_API uint64_t b2DynamicTree_GetUserData( const b2DynamicTree* tree, int proxyId ); /// Get the AABB of a proxy B2_API b2AABB b2DynamicTree_GetAABB( const b2DynamicTree* tree, int proxyId ); /// Validate this tree. For testing. B2_API void b2DynamicTree_Validate( const b2DynamicTree* tree ); /// Validate this tree has no enlarged AABBs. For testing. B2_API void b2DynamicTree_ValidateNoEnlarged( const b2DynamicTree* tree ); /**@}*/ /** * @defgroup character Character mover * Character movement solver * @{ */ /// These are the collision planes returned from b2World_CollideMover typedef struct b2PlaneResult { /// The collision plane between the mover and a convex shape b2Plane plane; // The collision point on the shape. b2Vec2 point; /// Did the collision register a hit? If not this plane should be ignored. bool hit; } b2PlaneResult; /// These are collision planes that can be fed to b2SolvePlanes. Normally /// this is assembled by the user from plane results in b2PlaneResult typedef struct b2CollisionPlane { /// The collision plane between the mover and some shape b2Plane plane; /// Setting this to FLT_MAX makes the plane as rigid as possible. Lower values can /// make the plane collision soft. Usually in meters. float pushLimit; /// The push on the mover determined by b2SolvePlanes. Usually in meters. float push; /// Indicates if b2ClipVector should clip against this plane. Should be false for soft collision. bool clipVelocity; } b2CollisionPlane; /// Result returned by b2SolvePlanes typedef struct b2PlaneSolverResult { /// The translation of the mover b2Vec2 translation; /// The number of iterations used by the plane solver. For diagnostics. int iterationCount; } b2PlaneSolverResult; /// Solves the position of a mover that satisfies the given collision planes. /// @param targetDelta the desired movement from the position used to generate the collision planes /// @param planes the collision planes /// @param count the number of collision planes B2_API b2PlaneSolverResult b2SolvePlanes( b2Vec2 targetDelta, b2CollisionPlane* planes, int count ); /// Clips the velocity against the given collision planes. Planes with zero push or clipVelocity /// set to false are skipped. B2_API b2Vec2 b2ClipVector( b2Vec2 vector, const b2CollisionPlane* planes, int count ); /**@}*/ ================================================ FILE: include/box2d/id.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include // Note: this file should be stand-alone /** * @defgroup id Ids * These ids serve as handles to internal Box2D objects. * These should be considered opaque data and passed by value. * Include this header if you need the id types and not the whole Box2D API. * All ids are considered null if initialized to zero. * * For example in C++: * * @code{.cxx} * b2WorldId worldId = {}; * @endcode * * Or in C: * * @code{.c} * b2WorldId worldId = {0}; * @endcode * * These are both considered null. * * @warning Do not use the internals of these ids. They are subject to change. Ids should be treated as opaque objects. * @warning You should use ids to access objects in Box2D. Do not access files within the src folder. Such usage is unsupported. * @{ */ /// World id references a world instance. This should be treated as an opaque handle. typedef struct b2WorldId { uint16_t index1; uint16_t generation; } b2WorldId; /// Body id references a body instance. This should be treated as an opaque handle. typedef struct b2BodyId { int32_t index1; uint16_t world0; uint16_t generation; } b2BodyId; /// Shape id references a shape instance. This should be treated as an opaque handle. typedef struct b2ShapeId { int32_t index1; uint16_t world0; uint16_t generation; } b2ShapeId; /// Chain id references a chain instances. This should be treated as an opaque handle. typedef struct b2ChainId { int32_t index1; uint16_t world0; uint16_t generation; } b2ChainId; /// Joint id references a joint instance. This should be treated as an opaque handle. typedef struct b2JointId { int32_t index1; uint16_t world0; uint16_t generation; } b2JointId; /// Contact id references a contact instance. This should be treated as an opaque handled. typedef struct b2ContactId { int32_t index1; uint16_t world0; int16_t padding; uint32_t generation; } b2ContactId; #ifdef __cplusplus #define B2_NULL_ID {} #define B2_ID_INLINE inline #else #define B2_NULL_ID { 0 } #define B2_ID_INLINE static inline #endif /// Use these to make your identifiers null. /// You may also use zero initialization to get null. static const b2WorldId b2_nullWorldId = B2_NULL_ID; static const b2BodyId b2_nullBodyId = B2_NULL_ID; static const b2ShapeId b2_nullShapeId = B2_NULL_ID; static const b2ChainId b2_nullChainId = B2_NULL_ID; static const b2JointId b2_nullJointId = B2_NULL_ID; static const b2ContactId b2_nullContactId = B2_NULL_ID; /// Macro to determine if any id is null. #define B2_IS_NULL( id ) ( (id).index1 == 0 ) /// Macro to determine if any id is non-null. #define B2_IS_NON_NULL( id ) ( (id).index1 != 0 ) /// Compare two ids for equality. Doesn't work for b2WorldId. Don't mix types. #define B2_ID_EQUALS( id1, id2 ) ( (id1).index1 == (id2).index1 && (id1).world0 == (id2).world0 && (id1).generation == (id2).generation ) /// Store a world id into a uint32_t. B2_ID_INLINE uint32_t b2StoreWorldId( b2WorldId id ) { return ( (uint32_t)id.index1 << 16 ) | (uint32_t)id.generation; } /// Load a uint32_t into a world id. B2_ID_INLINE b2WorldId b2LoadWorldId( uint32_t x ) { b2WorldId id = { (uint16_t)( x >> 16 ), (uint16_t)( x ) }; return id; } /// Store a body id into a uint64_t. B2_ID_INLINE uint64_t b2StoreBodyId( b2BodyId id ) { return ( (uint64_t)id.index1 << 32 ) | ( (uint64_t)id.world0 ) << 16 | (uint64_t)id.generation; } /// Load a uint64_t into a body id. B2_ID_INLINE b2BodyId b2LoadBodyId( uint64_t x ) { b2BodyId id = { (int32_t)( x >> 32 ), (uint16_t)( x >> 16 ), (uint16_t)( x ) }; return id; } /// Store a shape id into a uint64_t. B2_ID_INLINE uint64_t b2StoreShapeId( b2ShapeId id ) { return ( (uint64_t)id.index1 << 32 ) | ( (uint64_t)id.world0 ) << 16 | (uint64_t)id.generation; } /// Load a uint64_t into a shape id. B2_ID_INLINE b2ShapeId b2LoadShapeId( uint64_t x ) { b2ShapeId id = { (int32_t)( x >> 32 ), (uint16_t)( x >> 16 ), (uint16_t)( x ) }; return id; } /// Store a chain id into a uint64_t. B2_ID_INLINE uint64_t b2StoreChainId( b2ChainId id ) { return ( (uint64_t)id.index1 << 32 ) | ( (uint64_t)id.world0 ) << 16 | (uint64_t)id.generation; } /// Load a uint64_t into a chain id. B2_ID_INLINE b2ChainId b2LoadChainId( uint64_t x ) { b2ChainId id = { (int32_t)( x >> 32 ), (uint16_t)( x >> 16 ), (uint16_t)( x ) }; return id; } /// Store a joint id into a uint64_t. B2_ID_INLINE uint64_t b2StoreJointId( b2JointId id ) { return ( (uint64_t)id.index1 << 32 ) | ( (uint64_t)id.world0 ) << 16 | (uint64_t)id.generation; } /// Load a uint64_t into a joint id. B2_ID_INLINE b2JointId b2LoadJointId( uint64_t x ) { b2JointId id = { (int32_t)( x >> 32 ), (uint16_t)( x >> 16 ), (uint16_t)( x ) }; return id; } /// Store a contact id into 16 bytes B2_ID_INLINE void b2StoreContactId( b2ContactId id, uint32_t values[3] ) { values[0] = (uint32_t)id.index1; values[1] = (uint32_t)id.world0; values[2] = (uint32_t)id.generation; } /// Load a two uint64_t into a contact id. B2_ID_INLINE b2ContactId b2LoadContactId( uint32_t values[3] ) { b2ContactId id; id.index1 = (int32_t)values[0]; id.world0 = (uint16_t)values[1]; id.padding = 0; id.generation = (uint32_t)values[2]; return id; } /**@}*/ ================================================ FILE: include/box2d/math_functions.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "base.h" #include #include #include /** * @defgroup math Math * @brief Vector math types and functions * @{ */ /// 2D vector /// This can be used to represent a point or free vector typedef struct b2Vec2 { /// coordinates float x, y; } b2Vec2; /// Cosine and sine pair /// This uses a custom implementation designed for cross-platform determinism typedef struct b2CosSin { /// cosine and sine float cosine; float sine; } b2CosSin; /// 2D rotation /// This is similar to using a complex number for rotation typedef struct b2Rot { /// cosine and sine float c, s; } b2Rot; /// A 2D rigid transform typedef struct b2Transform { b2Vec2 p; b2Rot q; } b2Transform; /// A 2-by-2 Matrix typedef struct b2Mat22 { /// columns b2Vec2 cx, cy; } b2Mat22; /// Axis-aligned bounding box typedef struct b2AABB { b2Vec2 lowerBound; b2Vec2 upperBound; } b2AABB; /// separation = dot(normal, point) - offset typedef struct b2Plane { b2Vec2 normal; float offset; } b2Plane; /**@}*/ /** * @addtogroup math * @{ */ /// https://en.wikipedia.org/wiki/Pi #define B2_PI 3.14159265359f static const b2Vec2 b2Vec2_zero = { 0.0f, 0.0f }; static const b2Rot b2Rot_identity = { 1.0f, 0.0f }; static const b2Transform b2Transform_identity = { { 0.0f, 0.0f }, { 1.0f, 0.0f } }; static const b2Mat22 b2Mat22_zero = { { 0.0f, 0.0f }, { 0.0f, 0.0f } }; /// Is this a valid number? Not NaN or infinity. B2_API bool b2IsValidFloat( float a ); /// Is this a valid vector? Not NaN or infinity. B2_API bool b2IsValidVec2( b2Vec2 v ); /// Is this a valid rotation? Not NaN or infinity. Is normalized. B2_API bool b2IsValidRotation( b2Rot q ); /// Is this a valid transform? Not NaN or infinity. Rotation is normalized. B2_API bool b2IsValidTransform( b2Transform t ); /// Is this a valid bounding box? Not Nan or infinity. Upper bound greater than or equal to lower bound. B2_API bool b2IsValidAABB( b2AABB aabb ); /// Is this a valid plane? Normal is a unit vector. Not Nan or infinity. B2_API bool b2IsValidPlane( b2Plane a ); /// @return the minimum of two integers B2_INLINE int b2MinInt( int a, int b ) { return a < b ? a : b; } /// @return the maximum of two integers B2_INLINE int b2MaxInt( int a, int b ) { return a > b ? a : b; } /// @return the absolute value of an integer B2_INLINE int b2AbsInt( int a ) { return a < 0 ? -a : a; } /// @return an integer clamped between a lower and upper bound B2_INLINE int b2ClampInt( int a, int lower, int upper ) { return a < lower ? lower : ( a > upper ? upper : a ); } /// @return the minimum of two floats B2_INLINE float b2MinFloat( float a, float b ) { return a < b ? a : b; } /// @return the maximum of two floats B2_INLINE float b2MaxFloat( float a, float b ) { return a > b ? a : b; } /// @return the absolute value of a float B2_INLINE float b2AbsFloat( float a ) { return a < 0 ? -a : a; } /// @return a float clamped between a lower and upper bound B2_INLINE float b2ClampFloat( float a, float lower, float upper ) { return a < lower ? lower : ( a > upper ? upper : a ); } /// Compute an approximate arctangent in the range [-pi, pi] /// This is hand coded for cross-platform determinism. The atan2f /// function in the standard library is not cross-platform deterministic. /// Accurate to around 0.0023 degrees B2_API float b2Atan2( float y, float x ); /// Compute the cosine and sine of an angle in radians. Implemented /// for cross-platform determinism. B2_API b2CosSin b2ComputeCosSin( float radians ); /// Vector dot product B2_INLINE float b2Dot( b2Vec2 a, b2Vec2 b ) { return a.x * b.x + a.y * b.y; } /// Vector cross product. In 2D this yields a scalar. B2_INLINE float b2Cross( b2Vec2 a, b2Vec2 b ) { return a.x * b.y - a.y * b.x; } /// Perform the cross product on a vector and a scalar. In 2D this produces a vector. B2_INLINE b2Vec2 b2CrossVS( b2Vec2 v, float s ) { return B2_LITERAL( b2Vec2 ){ s * v.y, -s * v.x }; } /// Perform the cross product on a scalar and a vector. In 2D this produces a vector. B2_INLINE b2Vec2 b2CrossSV( float s, b2Vec2 v ) { return B2_LITERAL( b2Vec2 ){ -s * v.y, s * v.x }; } /// Get a left pointing perpendicular vector. Equivalent to b2CrossSV(1.0f, v) B2_INLINE b2Vec2 b2LeftPerp( b2Vec2 v ) { return B2_LITERAL( b2Vec2 ){ -v.y, v.x }; } /// Get a right pointing perpendicular vector. Equivalent to b2CrossVS(v, 1.0f) B2_INLINE b2Vec2 b2RightPerp( b2Vec2 v ) { return B2_LITERAL( b2Vec2 ){ v.y, -v.x }; } /// Vector addition B2_INLINE b2Vec2 b2Add( b2Vec2 a, b2Vec2 b ) { return B2_LITERAL( b2Vec2 ){ a.x + b.x, a.y + b.y }; } /// Vector subtraction B2_INLINE b2Vec2 b2Sub( b2Vec2 a, b2Vec2 b ) { return B2_LITERAL( b2Vec2 ){ a.x - b.x, a.y - b.y }; } /// Vector negation B2_INLINE b2Vec2 b2Neg( b2Vec2 a ) { return B2_LITERAL( b2Vec2 ){ -a.x, -a.y }; } /// Vector linear interpolation /// https://fgiesen.wordpress.com/2012/08/15/linear-interpolation-past-present-and-future/ B2_INLINE b2Vec2 b2Lerp( b2Vec2 a, b2Vec2 b, float t ) { return B2_LITERAL( b2Vec2 ){ ( 1.0f - t ) * a.x + t * b.x, ( 1.0f - t ) * a.y + t * b.y }; } /// Component-wise multiplication B2_INLINE b2Vec2 b2Mul( b2Vec2 a, b2Vec2 b ) { return B2_LITERAL( b2Vec2 ){ a.x * b.x, a.y * b.y }; } /// Multiply a scalar and vector B2_INLINE b2Vec2 b2MulSV( float s, b2Vec2 v ) { return B2_LITERAL( b2Vec2 ){ s * v.x, s * v.y }; } /// a + s * b B2_INLINE b2Vec2 b2MulAdd( b2Vec2 a, float s, b2Vec2 b ) { return B2_LITERAL( b2Vec2 ){ a.x + s * b.x, a.y + s * b.y }; } /// a - s * b B2_INLINE b2Vec2 b2MulSub( b2Vec2 a, float s, b2Vec2 b ) { return B2_LITERAL( b2Vec2 ){ a.x - s * b.x, a.y - s * b.y }; } /// Component-wise absolute vector B2_INLINE b2Vec2 b2Abs( b2Vec2 a ) { b2Vec2 b; b.x = b2AbsFloat( a.x ); b.y = b2AbsFloat( a.y ); return b; } /// Component-wise minimum vector B2_INLINE b2Vec2 b2Min( b2Vec2 a, b2Vec2 b ) { b2Vec2 c; c.x = b2MinFloat( a.x, b.x ); c.y = b2MinFloat( a.y, b.y ); return c; } /// Component-wise maximum vector B2_INLINE b2Vec2 b2Max( b2Vec2 a, b2Vec2 b ) { b2Vec2 c; c.x = b2MaxFloat( a.x, b.x ); c.y = b2MaxFloat( a.y, b.y ); return c; } /// Component-wise clamp vector v into the range [a, b] B2_INLINE b2Vec2 b2Clamp( b2Vec2 v, b2Vec2 a, b2Vec2 b ) { b2Vec2 c; c.x = b2ClampFloat( v.x, a.x, b.x ); c.y = b2ClampFloat( v.y, a.y, b.y ); return c; } /// Get the length of this vector (the norm) B2_INLINE float b2Length( b2Vec2 v ) { return sqrtf( v.x * v.x + v.y * v.y ); } /// Get the distance between two points B2_INLINE float b2Distance( b2Vec2 a, b2Vec2 b ) { float dx = b.x - a.x; float dy = b.y - a.y; return sqrtf( dx * dx + dy * dy ); } /// Convert a vector into a unit vector if possible, otherwise returns the zero vector. /// todo MSVC is not inlining this function in several places per warning 4710 B2_INLINE b2Vec2 b2Normalize( b2Vec2 v ) { float length = sqrtf( v.x * v.x + v.y * v.y ); if ( length < FLT_EPSILON ) { return B2_LITERAL( b2Vec2 ){ 0.0f, 0.0f }; } float invLength = 1.0f / length; b2Vec2 n = { invLength * v.x, invLength * v.y }; return n; } /// Determines if the provided vector is normalized (norm(a) == 1). B2_INLINE bool b2IsNormalized( b2Vec2 a ) { float aa = b2Dot( a, a ); return b2AbsFloat( 1.0f - aa ) < 100.0f * FLT_EPSILON; } /// Convert a vector into a unit vector if possible, otherwise returns the zero vector. Also /// outputs the length. B2_INLINE b2Vec2 b2GetLengthAndNormalize( float* length, b2Vec2 v ) { *length = sqrtf( v.x * v.x + v.y * v.y ); if ( *length < FLT_EPSILON ) { return B2_LITERAL( b2Vec2 ){ 0.0f, 0.0f }; } float invLength = 1.0f / *length; b2Vec2 n = { invLength * v.x, invLength * v.y }; return n; } /// Normalize rotation B2_INLINE b2Rot b2NormalizeRot( b2Rot q ) { float mag = sqrtf( q.s * q.s + q.c * q.c ); float invMag = mag > 0.0f ? 1.0f / mag : 0.0f; b2Rot qn = { q.c * invMag, q.s * invMag }; return qn; } /// Integrate rotation from angular velocity /// @param q1 initial rotation /// @param deltaAngle the angular displacement in radians B2_INLINE b2Rot b2IntegrateRotation( b2Rot q1, float deltaAngle ) { // dc/dt = -omega * sin(t) // ds/dt = omega * cos(t) // c2 = c1 - omega * h * s1 // s2 = s1 + omega * h * c1 b2Rot q2 = { q1.c - deltaAngle * q1.s, q1.s + deltaAngle * q1.c }; float mag = sqrtf( q2.s * q2.s + q2.c * q2.c ); float invMag = mag > 0.0f ? 1.0f / mag : 0.0f; b2Rot qn = { q2.c * invMag, q2.s * invMag }; return qn; } /// Get the length squared of this vector B2_INLINE float b2LengthSquared( b2Vec2 v ) { return v.x * v.x + v.y * v.y; } /// Get the distance squared between points B2_INLINE float b2DistanceSquared( b2Vec2 a, b2Vec2 b ) { b2Vec2 c = { b.x - a.x, b.y - a.y }; return c.x * c.x + c.y * c.y; } /// Make a rotation using an angle in radians B2_INLINE b2Rot b2MakeRot( float radians ) { b2CosSin cs = b2ComputeCosSin( radians ); return B2_LITERAL( b2Rot ){ cs.cosine, cs.sine }; } /// Make a rotation using a unit vector B2_INLINE b2Rot b2MakeRotFromUnitVector( b2Vec2 unitVector ) { B2_ASSERT( b2IsNormalized( unitVector ) ); return B2_LITERAL( b2Rot ){ unitVector.x, unitVector.y }; } /// Compute the rotation between two unit vectors B2_API b2Rot b2ComputeRotationBetweenUnitVectors( b2Vec2 v1, b2Vec2 v2 ); /// Is this rotation normalized? B2_INLINE bool b2IsNormalizedRot( b2Rot q ) { // larger tolerance due to failure on mingw 32-bit float qq = q.s * q.s + q.c * q.c; return 1.0f - 0.0006f < qq && qq < 1.0f + 0.0006f; } /// Get the inverse of a rotation B2_INLINE b2Rot b2InvertRot( b2Rot a ) { return B2_LITERAL( b2Rot ){ .c = a.c, .s = -a.s, }; } /// Normalized linear interpolation /// https://fgiesen.wordpress.com/2012/08/15/linear-interpolation-past-present-and-future/ /// https://web.archive.org/web/20170825184056/http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/ B2_INLINE b2Rot b2NLerp( b2Rot q1, b2Rot q2, float t ) { float omt = 1.0f - t; b2Rot q = { omt * q1.c + t * q2.c, omt * q1.s + t * q2.s, }; float mag = sqrtf( q.s * q.s + q.c * q.c ); float invMag = mag > 0.0f ? 1.0f / mag : 0.0f; b2Rot qn = { q.c * invMag, q.s * invMag }; return qn; } /// Compute the angular velocity necessary to rotate between two rotations over a give time /// @param q1 initial rotation /// @param q2 final rotation /// @param inv_h inverse time step B2_INLINE float b2ComputeAngularVelocity( b2Rot q1, b2Rot q2, float inv_h ) { // ds/dt = omega * cos(t) // dc/dt = -omega * sin(t) // s2 = s1 + omega * h * c1 // c2 = c1 - omega * h * s1 // omega * h * s1 = c1 - c2 // omega * h * c1 = s2 - s1 // omega * h = (c1 - c2) * s1 + (s2 - s1) * c1; // omega * h = s1 * c1 - c2 * s1 + s2 * c1 - s1 * c1 // omega * h = s2 * c1 - c2 * s1 = sin(a2 - a1) ~= a2 - a1 for small delta float omega = inv_h * ( q2.s * q1.c - q2.c * q1.s ); return omega; } /// Get the angle in radians in the range [-pi, pi] B2_INLINE float b2Rot_GetAngle( b2Rot q ) { return b2Atan2( q.s, q.c ); } /// Get the x-axis B2_INLINE b2Vec2 b2Rot_GetXAxis( b2Rot q ) { b2Vec2 v = { q.c, q.s }; return v; } /// Get the y-axis B2_INLINE b2Vec2 b2Rot_GetYAxis( b2Rot q ) { b2Vec2 v = { -q.s, q.c }; return v; } /// Multiply two rotations: q * r B2_INLINE b2Rot b2MulRot( b2Rot q, b2Rot r ) { // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] // s(q + r) = qs * rc + qc * rs // c(q + r) = qc * rc - qs * rs b2Rot qr; qr.s = q.s * r.c + q.c * r.s; qr.c = q.c * r.c - q.s * r.s; return qr; } /// Transpose multiply two rotations: inv(a) * b /// This rotates a vector local in frame b into a vector local in frame a B2_INLINE b2Rot b2InvMulRot( b2Rot a, b2Rot b ) { // [ ac as] * [bc -bs] = [ac*bc+qs*bs -ac*bs+as*bc] // [-as ac] [bs bc] [-as*bc+ac*bs as*bs+ac*bc] // s(a - b) = ac * bs - as * bc // c(a - b) = ac * bc + as * bs b2Rot r; r.s = a.c * b.s - a.s * b.c; r.c = a.c * b.c + a.s * b.s; return r; } /// Relative angle between a and b B2_INLINE float b2RelativeAngle( b2Rot a, b2Rot b ) { // sin(b - a) = bs * ac - bc * as // cos(b - a) = bc * ac + bs * as float s = a.c * b.s - a.s * b.c; float c = a.c * b.c + a.s * b.s; return b2Atan2( s, c ); } /// Convert any angle into the range [-pi, pi] B2_INLINE float b2UnwindAngle( float radians ) { // Assuming this is deterministic return remainderf( radians, 2.0f * B2_PI ); } /// Rotate a vector B2_INLINE b2Vec2 b2RotateVector( b2Rot q, b2Vec2 v ) { return B2_LITERAL( b2Vec2 ){ q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y }; } /// Inverse rotate a vector B2_INLINE b2Vec2 b2InvRotateVector( b2Rot q, b2Vec2 v ) { return B2_LITERAL( b2Vec2 ){ q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y }; } /// Transform a point (e.g. local space to world space) B2_INLINE b2Vec2 b2TransformPoint( b2Transform t, const b2Vec2 p ) { float x = ( t.q.c * p.x - t.q.s * p.y ) + t.p.x; float y = ( t.q.s * p.x + t.q.c * p.y ) + t.p.y; return B2_LITERAL( b2Vec2 ){ x, y }; } /// Inverse transform a point (e.g. world space to local space) B2_INLINE b2Vec2 b2InvTransformPoint( b2Transform t, const b2Vec2 p ) { float vx = p.x - t.p.x; float vy = p.y - t.p.y; return B2_LITERAL( b2Vec2 ){ t.q.c * vx + t.q.s * vy, -t.q.s * vx + t.q.c * vy }; } /// Multiply two transforms. If the result is applied to a point p local to frame B, /// the transform would first convert p to a point local to frame A, then into a point /// in the world frame. /// v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p /// = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p B2_INLINE b2Transform b2MulTransforms( b2Transform A, b2Transform B ) { b2Transform C; C.q = b2MulRot( A.q, B.q ); C.p = b2Add( b2RotateVector( A.q, B.p ), A.p ); return C; } /// Creates a transform that converts a local point in frame B to a local point in frame A. /// v2 = A.q' * (B.q * v1 + B.p - A.p) /// = A.q' * B.q * v1 + A.q' * (B.p - A.p) B2_INLINE b2Transform b2InvMulTransforms( b2Transform A, b2Transform B ) { b2Transform C; C.q = b2InvMulRot( A.q, B.q ); C.p = b2InvRotateVector( A.q, b2Sub( B.p, A.p ) ); return C; } /// Multiply a 2-by-2 matrix times a 2D vector B2_INLINE b2Vec2 b2MulMV( b2Mat22 A, b2Vec2 v ) { b2Vec2 u = { A.cx.x * v.x + A.cy.x * v.y, A.cx.y * v.x + A.cy.y * v.y, }; return u; } /// Get the inverse of a 2-by-2 matrix B2_INLINE b2Mat22 b2GetInverse22( b2Mat22 A ) { float a = A.cx.x, b = A.cy.x, c = A.cx.y, d = A.cy.y; float det = a * d - b * c; if ( det != 0.0f ) { det = 1.0f / det; } b2Mat22 B = { { det * d, -det * c }, { -det * b, det * a }, }; return B; } /// Solve A * x = b, where b is a column vector. This is more efficient /// than computing the inverse in one-shot cases. B2_INLINE b2Vec2 b2Solve22( b2Mat22 A, b2Vec2 b ) { float a11 = A.cx.x, a12 = A.cy.x, a21 = A.cx.y, a22 = A.cy.y; float det = a11 * a22 - a12 * a21; if ( det != 0.0f ) { det = 1.0f / det; } b2Vec2 x = { det * ( a22 * b.x - a12 * b.y ), det * ( a11 * b.y - a21 * b.x ) }; return x; } /// Does a fully contain b B2_INLINE bool b2AABB_Contains( b2AABB a, b2AABB b ) { bool s = true; s = s && a.lowerBound.x <= b.lowerBound.x; s = s && a.lowerBound.y <= b.lowerBound.y; s = s && b.upperBound.x <= a.upperBound.x; s = s && b.upperBound.y <= a.upperBound.y; return s; } /// Get the center of the AABB. B2_INLINE b2Vec2 b2AABB_Center( b2AABB a ) { b2Vec2 b = { 0.5f * ( a.lowerBound.x + a.upperBound.x ), 0.5f * ( a.lowerBound.y + a.upperBound.y ) }; return b; } /// Get the extents of the AABB (half-widths). B2_INLINE b2Vec2 b2AABB_Extents( b2AABB a ) { b2Vec2 b = { 0.5f * ( a.upperBound.x - a.lowerBound.x ), 0.5f * ( a.upperBound.y - a.lowerBound.y ) }; return b; } /// Union of two AABBs B2_INLINE b2AABB b2AABB_Union( b2AABB a, b2AABB b ) { b2AABB c; c.lowerBound.x = b2MinFloat( a.lowerBound.x, b.lowerBound.x ); c.lowerBound.y = b2MinFloat( a.lowerBound.y, b.lowerBound.y ); c.upperBound.x = b2MaxFloat( a.upperBound.x, b.upperBound.x ); c.upperBound.y = b2MaxFloat( a.upperBound.y, b.upperBound.y ); return c; } /// Do a and b overlap B2_INLINE bool b2AABB_Overlaps( b2AABB a, b2AABB b ) { return !( b.lowerBound.x > a.upperBound.x || b.lowerBound.y > a.upperBound.y || a.lowerBound.x > b.upperBound.x || a.lowerBound.y > b.upperBound.y ); } /// Compute the bounding box of an array of circles B2_INLINE b2AABB b2MakeAABB( const b2Vec2* points, int count, float radius ) { B2_ASSERT( count > 0 ); b2AABB a = { points[0], points[0] }; for ( int i = 1; i < count; ++i ) { a.lowerBound = b2Min( a.lowerBound, points[i] ); a.upperBound = b2Max( a.upperBound, points[i] ); } b2Vec2 r = { radius, radius }; a.lowerBound = b2Sub( a.lowerBound, r ); a.upperBound = b2Add( a.upperBound, r ); return a; } /// Signed separation of a point from a plane B2_INLINE float b2PlaneSeparation( b2Plane plane, b2Vec2 point ) { return b2Dot( plane.normal, point ) - plane.offset; } /// One-dimensional mass-spring-damper simulation. Returns the new velocity given the position and time step. /// You can then compute the new position using: /// position += timeStep * newVelocity /// This drives towards a zero position. By using implicit integration we get a stable solution /// that doesn't require transcendental functions. B2_INLINE float b2SpringDamper( float hertz, float dampingRatio, float position, float velocity, float timeStep ) { float omega = 2.0f * B2_PI * hertz; float omegaH = omega * timeStep; return ( velocity - omega * omegaH * position ) / ( 1.0f + 2.0f * dampingRatio * omegaH + omegaH * omegaH ); } /// Box2D bases all length units on meters, but you may need different units for your game. /// You can set this value to use different units. This should be done at application startup /// and only modified once. Default value is 1. /// For example, if your game uses pixels for units you can use pixels for all length values /// sent to Box2D. There should be no extra cost. However, Box2D has some internal tolerances /// and thresholds that have been tuned for meters. By calling this function, Box2D is able /// to adjust those tolerances and thresholds to improve accuracy. /// A good rule of thumb is to pass the height of your player character to this function. So /// if your player character is 32 pixels high, then pass 32 to this function. Then you may /// confidently use pixels for all the length values sent to Box2D. All length values returned /// from Box2D will also be pixels because Box2D does not do any scaling internally. /// However, you are now on the hook for coming up with good values for gravity, density, and /// forces. /// @warning This must be modified before any calls to Box2D B2_API void b2SetLengthUnitsPerMeter( float lengthUnits ); /// Get the current length units per meter. B2_API float b2GetLengthUnitsPerMeter( void ); /**@}*/ /** * @defgroup math_cpp C++ Math * @brief Math operator overloads for C++ * * See math_functions.h for details. * @{ */ #ifdef __cplusplus /// Unary add one vector to another inline void operator+=( b2Vec2& a, b2Vec2 b ) { a.x += b.x; a.y += b.y; } /// Unary subtract one vector from another inline void operator-=( b2Vec2& a, b2Vec2 b ) { a.x -= b.x; a.y -= b.y; } /// Unary multiply a vector by a scalar inline void operator*=( b2Vec2& a, float b ) { a.x *= b; a.y *= b; } /// Unary negate a vector inline b2Vec2 operator-( b2Vec2 a ) { return { -a.x, -a.y }; } /// Binary vector addition inline b2Vec2 operator+( b2Vec2 a, b2Vec2 b ) { return { a.x + b.x, a.y + b.y }; } /// Binary vector subtraction inline b2Vec2 operator-( b2Vec2 a, b2Vec2 b ) { return { a.x - b.x, a.y - b.y }; } /// Binary scalar and vector multiplication inline b2Vec2 operator*( float a, b2Vec2 b ) { return { a * b.x, a * b.y }; } /// Binary scalar and vector multiplication inline b2Vec2 operator*( b2Vec2 a, float b ) { return { a.x * b, a.y * b }; } /// Binary vector equality inline bool operator==( b2Vec2 a, b2Vec2 b ) { return a.x == b.x && a.y == b.y; } /// Binary vector inequality inline bool operator!=( b2Vec2 a, b2Vec2 b ) { return a.x != b.x || a.y != b.y; } #endif /**@}*/ ================================================ FILE: include/box2d/types.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "base.h" #include "collision.h" #include "id.h" #include "math_functions.h" #include #include #define B2_DEFAULT_CATEGORY_BITS 1 #define B2_DEFAULT_MASK_BITS UINT64_MAX /// Task interface /// This is prototype for a Box2D task. Your task system is expected to invoke the Box2D task with these arguments. /// The task spans a range of the parallel-for: [startIndex, endIndex) /// The worker index must correctly identify each worker in the user thread pool, expected in [0, workerCount). /// A worker must only exist on only one thread at a time and is analogous to the thread index. /// The task context is the context pointer sent from Box2D when it is enqueued. /// The startIndex and endIndex are expected in the range [0, itemCount) where itemCount is the argument to b2EnqueueTaskCallback /// below. Box2D expects startIndex < endIndex and will execute a loop like this: /// /// @code{.c} /// for (int i = startIndex; i < endIndex; ++i) /// { /// DoWork(); /// } /// @endcode /// @ingroup world typedef void b2TaskCallback( int startIndex, int endIndex, uint32_t workerIndex, void* taskContext ); /// These functions can be provided to Box2D to invoke a task system. These are designed to work well with enkiTS. /// Returns a pointer to the user's task object. May be nullptr. A nullptr indicates to Box2D that the work was executed /// serially within the callback and there is no need to call b2FinishTaskCallback. /// The itemCount is the number of Box2D work items that are to be partitioned among workers by the user's task system. /// This is essentially a parallel-for. The minRange parameter is a suggestion of the minimum number of items to assign /// per worker to reduce overhead. For example, suppose the task is small and that itemCount is 16. A minRange of 8 suggests /// that your task system should split the work items among just two workers, even if you have more available. /// In general the range [startIndex, endIndex) send to b2TaskCallback should obey: /// endIndex - startIndex >= minRange /// The exception of course is when itemCount < minRange. /// @ingroup world typedef void* b2EnqueueTaskCallback( b2TaskCallback* task, int itemCount, int minRange, void* taskContext, void* userContext ); /// Finishes a user task object that wraps a Box2D task. /// @ingroup world typedef void b2FinishTaskCallback( void* userTask, void* userContext ); /// Optional friction mixing callback. This intentionally provides no context objects because this is called /// from a worker thread. /// @warning This function should not attempt to modify Box2D state or user application state. /// @ingroup world typedef float b2FrictionCallback( float frictionA, uint64_t userMaterialIdA, float frictionB, uint64_t userMaterialIdB ); /// Optional restitution mixing callback. This intentionally provides no context objects because this is called /// from a worker thread. /// @warning This function should not attempt to modify Box2D state or user application state. /// @ingroup world typedef float b2RestitutionCallback( float restitutionA, uint64_t userMaterialIdA, float restitutionB, uint64_t userMaterialIdB ); /// Result from b2World_RayCastClosest /// If there is initial overlap the fraction and normal will be zero while the point is an arbitrary point in the overlap region. /// @ingroup world typedef struct b2RayResult { b2ShapeId shapeId; b2Vec2 point; b2Vec2 normal; float fraction; int nodeVisits; int leafVisits; bool hit; } b2RayResult; /// World definition used to create a simulation world. /// Must be initialized using b2DefaultWorldDef(). /// @ingroup world typedef struct b2WorldDef { /// Gravity vector. Box2D has no up-vector defined. b2Vec2 gravity; /// Restitution speed threshold, usually in m/s. Collisions above this /// speed have restitution applied (will bounce). float restitutionThreshold; /// Threshold speed for hit events. Usually meters per second. float hitEventThreshold; /// Contact stiffness. Cycles per second. Increasing this increases the speed of overlap recovery, but can introduce jitter. float contactHertz; /// Contact bounciness. Non-dimensional. You can speed up overlap recovery by decreasing this with /// the trade-off that overlap resolution becomes more energetic. float contactDampingRatio; /// This parameter controls how fast overlap is resolved and usually has units of meters per second. This only /// puts a cap on the resolution speed. The resolution speed is increased by increasing the hertz and/or /// decreasing the damping ratio. float contactSpeed; /// Maximum linear speed. Usually meters per second. float maximumLinearSpeed; /// Optional mixing callback for friction. The default uses sqrt(frictionA * frictionB). b2FrictionCallback* frictionCallback; /// Optional mixing callback for restitution. The default uses max(restitutionA, restitutionB). b2RestitutionCallback* restitutionCallback; /// Can bodies go to sleep to improve performance bool enableSleep; /// Enable continuous collision bool enableContinuous; /// Contact softening when mass ratios are large. Experimental. bool enableContactSoftening; /// Number of workers to use with the provided task system. Box2D 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 Box2D does not create threads. This is the number of threads your applications has created /// that you are allocating to b2World_Step. /// @warning Do not modify the default value unless you are also providing a task system and providing /// task callbacks (enqueueTask and finishTask). int workerCount; /// Function to spawn tasks b2EnqueueTaskCallback* enqueueTask; /// Function to finish a task b2FinishTaskCallback* finishTask; /// User context that is provided to enqueueTask and finishTask void* userTaskContext; /// User data void* userData; /// Used internally to detect a valid definition. DO NOT SET. int internalValue; } b2WorldDef; /// Use this to initialize your world definition /// @ingroup world B2_API b2WorldDef b2DefaultWorldDef( void ); /// The body simulation type. /// Each body is one of these three types. The type determines how the body behaves in the simulation. /// @ingroup body typedef enum b2BodyType { /// zero mass, zero velocity, may be manually moved b2_staticBody = 0, /// zero mass, velocity set by user, moved by solver b2_kinematicBody = 1, /// positive mass, velocity determined by forces, moved by solver b2_dynamicBody = 2, /// number of body types b2_bodyTypeCount, } b2BodyType; /// Motion locks to restrict the body movement typedef struct b2MotionLocks { /// Prevent translation along the x-axis bool linearX; /// Prevent translation along the y-axis bool linearY; /// Prevent rotation around the z-axis bool angularZ; } b2MotionLocks; /// A body definition holds all the data needed to construct a rigid body. /// You can safely re-use body definitions. Shapes are added to a body after construction. /// Body definitions are temporary objects used to bundle creation parameters. /// Must be initialized using b2DefaultBodyDef(). /// @ingroup body typedef struct b2BodyDef { /// The body type: static, kinematic, or dynamic. b2BodyType type; /// The initial world position of the body. Bodies should be created with the desired position. /// @note Creating bodies at the origin and then moving them nearly doubles the cost of body creation, especially /// if the body is moved after shapes have been added. b2Vec2 position; /// The initial world rotation of the body. Use b2MakeRot() if you have an angle. b2Rot rotation; /// The initial linear velocity of the body's origin. Usually in meters per second. b2Vec2 linearVelocity; /// The initial angular velocity of the body. Radians per second. float angularVelocity; /// Linear damping is used to reduce the linear velocity. The damping parameter /// can be larger than 1 but the damping effect becomes sensitive to the /// time step when the damping parameter is large. /// Generally linear damping is undesirable because it makes objects move slowly /// as if they are floating. float linearDamping; /// Angular damping is used to reduce the angular velocity. The damping parameter /// can be larger than 1.0f but the damping effect becomes sensitive to the /// time step when the damping parameter is large. /// Angular damping can be use slow down rotating bodies. float angularDamping; /// Scale the gravity applied to this body. Non-dimensional. float gravityScale; /// Sleep speed threshold, default is 0.05 meters per second float sleepThreshold; /// Optional body name for debugging. Up to 31 characters (excluding null termination) const char* name; /// Use this to store application specific body data. void* userData; /// Motions locks to restrict linear and angular movement. /// Caution: may lead to softer constraints along the locked direction b2MotionLocks motionLocks; /// Set this flag to false if this body should never fall asleep. bool enableSleep; /// Is this body initially awake or sleeping? bool isAwake; /// Treat this body as a high speed object that performs continuous collision detection /// against dynamic and kinematic bodies, but not other bullet bodies. /// @warning Bullets should be used sparingly. They are not a solution for general dynamic-versus-dynamic /// continuous collision. They do not guarantee accurate collision if both bodies are fast moving because /// the bullet does a continuous check after all non-bullet bodies have moved. You could get unlucky and have /// the bullet body end a time step very close to a non-bullet body and the non-bullet body then moves over /// the bullet body. In continuous collision, initial overlap is ignored to avoid freezing bodies in place. /// I do not recommend using them for game projectiles if precise collision timing is needed. Instead consider /// using a ray or shape cast. You can use a marching ray or shape cast for projectile that moves over time. /// If you want a fast moving projectile to collide with a fast moving target, you need to consider the relative /// movement in your ray or shape cast. This is out of the scope of Box2D. /// So what are good use cases for bullets? Pinball games or games with dynamic containers that hold other objects. /// It should be a use case where it doesn't break the game if there is a collision missed, but the having them /// captured improves the quality of the game. bool isBullet; /// Used to disable a body. A disabled body does not move or collide. bool isEnabled; /// This allows this body to bypass rotational speed limits. Should only be used /// for circular objects, like wheels. bool allowFastRotation; /// Used internally to detect a valid definition. DO NOT SET. int internalValue; } b2BodyDef; /// Use this to initialize your body definition /// @ingroup body B2_API b2BodyDef b2DefaultBodyDef( void ); /// This is used to filter collision on shapes. It affects shape-vs-shape collision /// and shape-versus-query collision (such as b2World_CastRay). /// @ingroup shape typedef struct b2Filter { /// The collision category bits. Normally you would just set one bit. The category bits should /// represent your application object types. For example: /// @code{.cpp} /// enum MyCategories /// { /// Static = 0x00000001, /// Dynamic = 0x00000002, /// Debris = 0x00000004, /// Player = 0x00000008, /// // etc /// }; /// @endcode uint64_t categoryBits; /// The collision mask bits. This states the categories that this /// shape would accept for collision. /// For example, you may want your player to only collide with static objects /// and other players. /// @code{.c} /// maskBits = Static | Player; /// @endcode uint64_t maskBits; /// Collision groups allow a certain group of objects to never collide (negative) /// or always collide (positive). A group index of zero has no effect. Non-zero group filtering /// always wins against the mask bits. /// For example, you may want ragdolls to collide with other ragdolls but you don't want /// ragdoll self-collision. In this case you would give each ragdoll a unique negative group index /// and apply that group index to all shapes on the ragdoll. int groupIndex; } b2Filter; /// Use this to initialize your filter /// @ingroup shape B2_API b2Filter b2DefaultFilter( void ); /// The query filter is used to filter collisions between queries and shapes. For example, /// you may want a ray-cast representing a projectile to hit players and the static environment /// but not debris. /// @ingroup shape typedef struct b2QueryFilter { /// The collision category bits of this query. Normally you would just set one bit. uint64_t categoryBits; /// The collision mask bits. This states the shape categories that this /// query would accept for collision. uint64_t maskBits; } b2QueryFilter; /// Use this to initialize your query filter /// @ingroup shape B2_API b2QueryFilter b2DefaultQueryFilter( void ); /// Shape type /// @ingroup shape typedef enum b2ShapeType { /// A circle with an offset b2_circleShape, /// A capsule is an extruded circle b2_capsuleShape, /// A line segment b2_segmentShape, /// A convex polygon b2_polygonShape, /// A line segment owned by a chain shape b2_chainSegmentShape, /// The number of shape types b2_shapeTypeCount } b2ShapeType; /// Surface materials allow chain shapes to have per segment surface properties. /// @ingroup shape typedef struct b2SurfaceMaterial { /// The Coulomb (dry) friction coefficient, usually in the range [0,1]. float friction; /// The coefficient of restitution (bounce) usually in the range [0,1]. /// https://en.wikipedia.org/wiki/Coefficient_of_restitution float restitution; /// The rolling resistance usually in the range [0,1]. float rollingResistance; /// The tangent speed for conveyor belts float tangentSpeed; /// User material identifier. This is passed with query results and to friction and restitution /// combining functions. It is not used internally. uint64_t userMaterialId; /// Custom debug draw color. uint32_t customColor; } b2SurfaceMaterial; /// Use this to initialize your surface material /// @ingroup shape B2_API b2SurfaceMaterial b2DefaultSurfaceMaterial( void ); /// Used to create a shape. /// This is a temporary object used to bundle shape creation parameters. You may use /// the same shape definition to create multiple shapes. /// Must be initialized using b2DefaultShapeDef(). /// @ingroup shape typedef struct b2ShapeDef { /// Use this to store application specific shape data. void* userData; /// The surface material for this shape. b2SurfaceMaterial material; /// The density, usually in kg/m^2. /// This is not part of the surface material because this is for the interior, which may have /// other considerations, such as being hollow. For example a wood barrel may be hollow or full of water. float density; /// Collision filtering data. b2Filter filter; /// Enable custom filtering. Only one of the two shapes needs to enable custom filtering. See b2WorldDef. bool enableCustomFiltering; /// A sensor shape generates overlap events but never generates a collision response. /// Sensors do not have continuous collision. Instead, use a ray or shape cast for those scenarios. /// Sensors still contribute to the body mass if they have non-zero density. /// @note Sensor events are disabled by default. /// @see enableSensorEvents bool isSensor; /// Enable sensor events for this shape. This applies to sensors and non-sensors. False by default, even for sensors. bool enableSensorEvents; /// Enable contact events for this shape. Only applies to kinematic and dynamic bodies. Ignored for sensors. False by default. bool enableContactEvents; /// Enable hit events for this shape. Only applies to kinematic and dynamic bodies. Ignored for sensors. False by default. bool enableHitEvents; /// Enable pre-solve contact events for this shape. Only applies to dynamic bodies. These are expensive /// and must be carefully handled due to multithreading. Ignored for sensors. bool enablePreSolveEvents; /// When shapes are created they will scan the environment for collision the next time step. This can significantly slow down /// static body creation when there are many static shapes. /// This is flag is ignored for dynamic and kinematic shapes which always invoke contact creation. bool invokeContactCreation; /// Should the body update the mass properties when this shape is created. Default is true. /// Warning: if this is true, you MUST call b2Body_ApplyMassFromShapes before simulating the world. bool updateBodyMass; /// Used internally to detect a valid definition. DO NOT SET. int internalValue; } b2ShapeDef; /// Use this to initialize your shape definition /// @ingroup shape B2_API b2ShapeDef b2DefaultShapeDef( void ); /// Used to create a chain of line segments. This is designed to eliminate ghost collisions with some limitations. /// - chains are one-sided /// - chains have no mass and should be used on static bodies /// - chains have a counter-clockwise winding order (normal points right of segment direction) /// - chains are either a loop or open /// - a chain must have at least 4 points /// - the distance between any two points must be greater than B2_LINEAR_SLOP /// - a chain shape should not self intersect (this is not validated) /// - an open chain shape has NO COLLISION on the first and final edge /// - you may overlap two open chains on their first three and/or last three points to get smooth collision /// - a chain shape creates multiple line segment shapes on the body /// https://en.wikipedia.org/wiki/Polygonal_chain /// Must be initialized using b2DefaultChainDef(). /// @warning Do not use chain shapes unless you understand the limitations. This is an advanced feature. /// @ingroup shape typedef struct b2ChainDef { /// Use this to store application specific shape data. void* userData; /// An array of at least 4 points. These are cloned and may be temporary. const b2Vec2* points; /// The point count, must be 4 or more. int count; /// Surface materials for each segment. These are cloned. const b2SurfaceMaterial* materials; /// The material count. Must be 1 or count. This allows you to provide one /// material for all segments or a unique material per segment. For open /// chains, the material on the ghost segments are place holders. int materialCount; /// Contact filtering data. b2Filter filter; /// Indicates a closed chain formed by connecting the first and last points bool isLoop; /// Enable sensors to detect this chain. False by default. bool enableSensorEvents; /// Used internally to detect a valid definition. DO NOT SET. int internalValue; } b2ChainDef; /// Use this to initialize your chain definition /// @ingroup shape B2_API b2ChainDef b2DefaultChainDef( void ); //! @cond /// Profiling data. Times are in milliseconds. typedef struct b2Profile { float step; float pairs; float collide; float solve; float prepareStages; float solveConstraints; float prepareConstraints; float integrateVelocities; float warmStart; float solveImpulses; float integratePositions; float relaxImpulses; float applyRestitution; float storeImpulses; float splitIslands; float transforms; float sensorHits; float jointEvents; float hitEvents; float refit; float bullets; float sleepIslands; float sensors; } b2Profile; /// Counters that give details of the simulation size. typedef struct b2Counters { int bodyCount; int shapeCount; int contactCount; int jointCount; int islandCount; int stackUsed; int staticTreeHeight; int treeHeight; int byteCount; int taskCount; int colorCounts[24]; } b2Counters; //! @endcond /// Joint type enumeration /// /// This is useful because all joint types use b2JointId and sometimes you /// want to get the type of a joint. /// @ingroup joint typedef enum b2JointType { b2_distanceJoint, b2_filterJoint, b2_motorJoint, b2_prismaticJoint, b2_revoluteJoint, b2_weldJoint, b2_wheelJoint, } b2JointType; /// Base joint definition used by all joint types. /// The local frames are measured from the body's origin rather than the center of mass because: /// 1. you might not know where the center of mass will be /// 2. if you add/remove shapes from a body and recompute the mass, the joints will be broken typedef struct b2JointDef { /// User data pointer void* userData; /// The first attached body b2BodyId bodyIdA; /// The second attached body b2BodyId bodyIdB; /// The first local joint frame b2Transform localFrameA; /// The second local joint frame b2Transform localFrameB; /// Force threshold for joint events float forceThreshold; /// Torque threshold for joint events float torqueThreshold; /// Constraint hertz (advanced feature) float constraintHertz; /// Constraint damping ratio (advanced feature) float constraintDampingRatio; /// Debug draw scale float drawScale; /// Set this flag to true if the attached bodies should collide bool collideConnected; } b2JointDef; /// Distance joint definition /// Connects a point on body A with a point on body B by a segment. /// Useful for ropes and springs. /// @ingroup distance_joint typedef struct b2DistanceJointDef { /// Base joint definition b2JointDef base; /// The rest length of this joint. Clamped to a stable minimum value. float length; /// Enable the distance constraint to behave like a spring. If false /// then the distance joint will be rigid, overriding the limit and motor. bool enableSpring; /// The lower spring force controls how much tension it can sustain float lowerSpringForce; /// The upper spring force controls how much compression it an sustain float upperSpringForce; /// The spring linear stiffness Hertz, cycles per second float hertz; /// The spring linear damping ratio, non-dimensional float dampingRatio; /// Enable/disable the joint limit bool enableLimit; /// Minimum length for limit. Clamped to a stable minimum value. float minLength; /// Maximum length for limit. Must be greater than or equal to the minimum length. float maxLength; /// Enable/disable the joint motor bool enableMotor; /// The maximum motor force, usually in newtons float maxMotorForce; /// The desired motor speed, usually in meters per second float motorSpeed; /// Used internally to detect a valid definition. DO NOT SET. int internalValue; } b2DistanceJointDef; /// Use this to initialize your joint definition /// @ingroup distance_joint B2_API b2DistanceJointDef b2DefaultDistanceJointDef( void ); /// A motor joint is used to control the relative velocity and or transform between two bodies. /// With a velocity of zero this acts like top-down friction. /// @ingroup motor_joint typedef struct b2MotorJointDef { /// Base joint definition b2JointDef base; /// The desired linear velocity b2Vec2 linearVelocity; /// The maximum motor force in newtons float maxVelocityForce; /// The desired angular velocity float angularVelocity; /// The maximum motor torque in newton-meters float maxVelocityTorque; /// Linear spring hertz for position control float linearHertz; /// Linear spring damping ratio float linearDampingRatio; /// Maximum spring force in newtons float maxSpringForce; /// Angular spring hertz for position control float angularHertz; /// Angular spring damping ratio float angularDampingRatio; /// Maximum spring torque in newton-meters float maxSpringTorque; /// Used internally to detect a valid definition. DO NOT SET. int internalValue; } b2MotorJointDef; /// Use this to initialize your joint definition /// @ingroup motor_joint B2_API b2MotorJointDef b2DefaultMotorJointDef( void ); /// A filter joint is used to disable collision between two specific bodies. /// /// @ingroup filter_joint typedef struct b2FilterJointDef { /// Base joint definition b2JointDef base; /// Used internally to detect a valid definition. DO NOT SET. int internalValue; } b2FilterJointDef; /// Use this to initialize your joint definition /// @ingroup filter_joint B2_API b2FilterJointDef b2DefaultFilterJointDef( void ); /// Prismatic joint definition /// Body B may slide along the x-axis in local frame A. Body B cannot rotate relative to body A. /// The joint translation is zero when the local frame origins coincide in world space. /// @ingroup prismatic_joint typedef struct b2PrismaticJointDef { /// Base joint definition b2JointDef base; /// Enable a linear spring along the prismatic joint axis bool enableSpring; /// The spring stiffness Hertz, cycles per second float hertz; /// The spring damping ratio, non-dimensional float dampingRatio; /// The target translation for the joint in meters. The spring-damper will drive /// to this translation. float targetTranslation; /// Enable/disable the joint limit bool enableLimit; /// The lower translation limit float lowerTranslation; /// The upper translation limit float upperTranslation; /// Enable/disable the joint motor bool enableMotor; /// The maximum motor force, typically in newtons float maxMotorForce; /// The desired motor speed, typically in meters per second float motorSpeed; /// Used internally to detect a valid definition. DO NOT SET. int internalValue; } b2PrismaticJointDef; /// Use this to initialize your joint definition /// @ingroup prismatic_joint B2_API b2PrismaticJointDef b2DefaultPrismaticJointDef( void ); /// Revolute joint definition /// A point on body B is fixed to a point on body A. Allows relative rotation. /// @ingroup revolute_joint typedef struct b2RevoluteJointDef { /// Base joint definition b2JointDef base; /// The target angle for the joint in radians. The spring-damper will drive /// to this angle. float targetAngle; /// Enable a rotational spring on the revolute hinge axis bool enableSpring; /// The spring stiffness Hertz, cycles per second float hertz; /// The spring damping ratio, non-dimensional float dampingRatio; /// A flag to enable joint limits bool enableLimit; /// 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. Maximum of 0.99*pi radians. float upperAngle; /// A flag to enable the joint motor bool enableMotor; /// The maximum motor torque, typically in newton-meters float maxMotorTorque; /// The desired motor speed in radians per second float motorSpeed; /// Used internally to detect a valid definition. DO NOT SET. int internalValue; } b2RevoluteJointDef; /// Use this to initialize your joint definition. /// @ingroup revolute_joint B2_API b2RevoluteJointDef b2DefaultRevoluteJointDef( void ); /// Weld joint definition /// Connects two bodies together rigidly. This constraint provides springs to mimic /// soft-body simulation. /// @note The approximate solver in Box2D cannot hold many bodies together rigidly /// @ingroup weld_joint typedef struct b2WeldJointDef { /// Base joint definition b2JointDef base; /// Linear stiffness expressed as Hertz (cycles per second). Use zero for maximum stiffness. float linearHertz; /// Angular stiffness as Hertz (cycles per second). Use zero for maximum stiffness. float angularHertz; /// Linear damping ratio, non-dimensional. Use 1 for critical damping. float linearDampingRatio; /// Linear damping ratio, non-dimensional. Use 1 for critical damping. float angularDampingRatio; /// Used internally to detect a valid definition. DO NOT SET. int internalValue; } b2WeldJointDef; /// Use this to initialize your joint definition /// @ingroup weld_joint B2_API b2WeldJointDef b2DefaultWeldJointDef( void ); /// Wheel joint definition /// Body B is a wheel that may rotate freely and slide along the local x-axis in frame A. /// The joint translation is zero when the local frame origins coincide in world space. /// @ingroup wheel_joint typedef struct b2WheelJointDef { /// Base joint definition b2JointDef base; /// Enable a linear spring along the local axis bool enableSpring; /// Spring stiffness in Hertz float hertz; /// Spring damping ratio, non-dimensional float dampingRatio; /// Enable/disable the joint linear limit bool enableLimit; /// The lower translation limit float lowerTranslation; /// The upper translation limit float upperTranslation; /// Enable/disable the joint rotational motor bool enableMotor; /// The maximum motor torque, typically in newton-meters float maxMotorTorque; /// The desired motor speed in radians per second float motorSpeed; /// Used internally to detect a valid definition. DO NOT SET. int internalValue; } b2WheelJointDef; /// Use this to initialize your joint definition /// @ingroup wheel_joint B2_API b2WheelJointDef b2DefaultWheelJointDef( void ); /// The explosion definition is used to configure options for explosions. Explosions /// consider shape geometry when computing the impulse. /// @ingroup world typedef struct b2ExplosionDef { /// Mask bits to filter shapes uint64_t maskBits; /// The center of the explosion in world space b2Vec2 position; /// The radius of the explosion float radius; /// The falloff distance beyond the radius. Impulse is reduced to zero at this distance. float falloff; /// Impulse per unit length. This applies an impulse according to the shape perimeter that /// is facing the explosion. Explosions only apply to circles, capsules, and polygons. This /// may be negative for implosions. float impulsePerLength; } b2ExplosionDef; /// Use this to initialize your explosion definition /// @ingroup world B2_API b2ExplosionDef b2DefaultExplosionDef( void ); /** * @defgroup events Events * World event types. * * Events are used to collect events that occur during the world time step. These events * are then available to query after the time step is complete. This is preferable to callbacks * because Box2D uses multithreaded simulation. * * Also when events occur in the simulation step it may be problematic to modify the world, which is * often what applications want to do when events occur. * * With event arrays, you can scan the events in a loop and modify the world. However, you need to be careful * that some event data may become invalid. There are several samples that show how to do this safely. * * @{ */ /// A begin touch event is generated when a shape starts to overlap a sensor shape. typedef struct b2SensorBeginTouchEvent { /// The id of the sensor shape b2ShapeId sensorShapeId; /// The id of the shape that began touching the sensor shape b2ShapeId visitorShapeId; } b2SensorBeginTouchEvent; /// An end touch event is generated when a shape stops overlapping a sensor shape. /// These include things like setting the transform, destroying a body or shape, or changing /// a filter. You will also get an end event if the sensor or visitor are destroyed. /// Therefore you should always confirm the shape id is valid using b2Shape_IsValid. typedef struct b2SensorEndTouchEvent { /// The id of the sensor shape /// @warning this shape may have been destroyed /// @see b2Shape_IsValid b2ShapeId sensorShapeId; /// The id of the shape that stopped touching the sensor shape /// @warning this shape may have been destroyed /// @see b2Shape_IsValid b2ShapeId visitorShapeId; } b2SensorEndTouchEvent; /// Sensor events are buffered in the world and are available /// as begin/end overlap event arrays after the time step is complete. /// Note: these may become invalid if bodies and/or shapes are destroyed typedef struct b2SensorEvents { /// Array of sensor begin touch events b2SensorBeginTouchEvent* beginEvents; /// Array of sensor end touch events b2SensorEndTouchEvent* endEvents; /// The number of begin touch events int beginCount; /// The number of end touch events int endCount; } b2SensorEvents; /// A begin touch event is generated when two shapes begin touching. typedef struct b2ContactBeginTouchEvent { /// Id of the first shape b2ShapeId shapeIdA; /// Id of the second shape b2ShapeId shapeIdB; /// The transient contact id. This contact maybe destroyed automatically when the world is modified or simulated. /// Used b2Contact_IsValid before using this id. b2ContactId contactId; } b2ContactBeginTouchEvent; /// An end touch event is generated when two shapes stop touching. /// You will get an end event if you do anything that destroys contacts previous to the last /// world step. These include things like setting the transform, destroying a body /// or shape, or changing a filter or body type. typedef struct b2ContactEndTouchEvent { /// Id of the first shape /// @warning this shape may have been destroyed /// @see b2Shape_IsValid b2ShapeId shapeIdA; /// Id of the second shape /// @warning this shape may have been destroyed /// @see b2Shape_IsValid b2ShapeId shapeIdB; /// Id of the contact. /// @warning this contact may have been destroyed /// @see b2Contact_IsValid b2ContactId contactId; } b2ContactEndTouchEvent; /// A hit touch event is generated when two shapes collide with a speed faster than the hit speed threshold. /// This may be reported for speculative contacts that have a confirmed impulse. typedef struct b2ContactHitEvent { /// Id of the first shape b2ShapeId shapeIdA; /// Id of the second shape b2ShapeId shapeIdB; /// Id of the contact. /// @warning this contact may have been destroyed /// @see b2Contact_IsValid b2ContactId contactId; /// Point where the shapes hit at the beginning of the time step. /// This is a mid-point between the two surfaces. It could be at speculative /// point where the two shapes were not touching at the beginning of the time step. b2Vec2 point; /// Normal vector pointing from shape A to shape B b2Vec2 normal; /// The speed the shapes are approaching. Always positive. Typically in meters per second. float approachSpeed; } b2ContactHitEvent; /// Contact events are buffered in the Box2D world and are available /// as event arrays after the time step is complete. /// Note: these may become invalid if bodies and/or shapes are destroyed typedef struct b2ContactEvents { /// Array of begin touch events b2ContactBeginTouchEvent* beginEvents; /// Array of end touch events b2ContactEndTouchEvent* endEvents; /// Array of hit events b2ContactHitEvent* hitEvents; /// Number of begin touch events int beginCount; /// Number of end touch events int endCount; /// Number of hit events int hitCount; } b2ContactEvents; /// Body move events triggered when a body moves. /// Triggered when a body moves due to simulation. Not reported for bodies moved by the user. /// This also has a flag to indicate that the body went to sleep so the application can also /// sleep that actor/entity/object associated with the body. /// On the other hand if the flag does not indicate the body went to sleep then the application /// can treat the actor/entity/object associated with the body as awake. /// This is an efficient way for an application to update game object transforms rather than /// calling functions such as b2Body_GetTransform() because this data is delivered as a contiguous array /// and it is only populated with bodies that have moved. /// @note If sleeping is disabled all dynamic and kinematic bodies will trigger move events. typedef struct b2BodyMoveEvent { void* userData; b2Transform transform; b2BodyId bodyId; bool fellAsleep; } b2BodyMoveEvent; /// Body events are buffered in the Box2D world and are available /// as event arrays after the time step is complete. /// Note: this data becomes invalid if bodies are destroyed typedef struct b2BodyEvents { /// Array of move events b2BodyMoveEvent* moveEvents; /// Number of move events int moveCount; } b2BodyEvents; /// Joint events report joints that are awake and have a force and/or torque exceeding the threshold /// The observed forces and torques are not returned for efficiency reasons. typedef struct b2JointEvent { /// The joint id b2JointId jointId; /// The user data from the joint for convenience void* userData; } b2JointEvent; /// Joint events are buffered in the world and are available /// as event arrays after the time step is complete. /// Note: this data becomes invalid if joints are destroyed typedef struct b2JointEvents { /// Array of events b2JointEvent* jointEvents; /// Number of events int count; } b2JointEvents; /// The contact data for two shapes. By convention the manifold normal points /// from shape A to shape B. /// @see b2Shape_GetContactData() and b2Body_GetContactData() typedef struct b2ContactData { b2ContactId contactId; b2ShapeId shapeIdA; b2ShapeId shapeIdB; b2Manifold manifold; } b2ContactData; /**@}*/ /// Prototype for a contact filter callback. /// This is called when a contact pair is considered for collision. This allows you to /// perform custom logic to prevent collision between shapes. This is only called if /// one of the two shapes has custom filtering enabled. /// Notes: /// - this function must be thread-safe /// - this is only called if one of the two shapes has enabled custom filtering /// - this may be called for awake dynamic bodies and sensors /// Return false if you want to disable the collision /// @see b2ShapeDef /// @warning Do not attempt to modify the world inside this callback /// @ingroup world typedef bool b2CustomFilterFcn( b2ShapeId shapeIdA, b2ShapeId shapeIdB, void* context ); /// Prototype for a pre-solve callback. /// This is called after a contact is updated. This allows you to inspect a /// contact before it goes to the solver. If you are careful, you can modify the /// contact manifold (e.g. modify the normal). /// Notes: /// - this function must be thread-safe /// - this is only called if the shape has enabled pre-solve events /// - this is called only for awake dynamic bodies /// - this is not called for sensors /// - the supplied manifold has impulse values from the previous step /// Return false if you want to disable the contact this step /// @warning Do not attempt to modify the world inside this callback /// @ingroup world typedef bool b2PreSolveFcn( b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Vec2 point, b2Vec2 normal, void* context ); /// Prototype callback for overlap queries. /// Called for each shape found in the query. /// @see b2World_OverlapABB /// @return false to terminate the query. /// @ingroup world typedef bool b2OverlapResultFcn( b2ShapeId shapeId, void* context ); /// Prototype callback for ray and shape casts. /// Called for each shape found in the query. You control how the ray cast /// proceeds by returning a float: /// return -1: ignore this shape and continue /// return 0: terminate the ray cast /// return fraction: clip the ray to this point /// return 1: don't clip the ray and continue /// A cast with initial overlap will return a zero fraction and a zero normal. /// @param shapeId the shape hit by the ray /// @param point the point of initial intersection /// @param normal the normal vector at the point of intersection, zero for a shape cast with initial overlap /// @param fraction the fraction along the ray at the point of intersection, zero for a shape cast with initial overlap /// @param context the user context /// @return -1 to filter, 0 to terminate, fraction to clip the ray for closest hit, 1 to continue /// @see b2World_CastRay /// @ingroup world typedef float b2CastResultFcn( b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context ); // Used to collect collision planes for character movers. // Return true to continue gathering planes. typedef bool b2PlaneResultFcn( b2ShapeId shapeId, const b2PlaneResult* plane, void* context ); /// These colors are used for debug draw and mostly match the named SVG colors. /// See https://www.rapidtables.com/web/color/index.html /// https://johndecember.com/html/spec/colorsvg.html /// https://upload.wikimedia.org/wikipedia/commons/2/2b/SVG_Recognized_color_keyword_names.svg typedef enum b2HexColor { b2_colorAliceBlue = 0xF0F8FF, b2_colorAntiqueWhite = 0xFAEBD7, b2_colorAqua = 0x00FFFF, b2_colorAquamarine = 0x7FFFD4, b2_colorAzure = 0xF0FFFF, b2_colorBeige = 0xF5F5DC, b2_colorBisque = 0xFFE4C4, b2_colorBlack = 0x000000, b2_colorBlanchedAlmond = 0xFFEBCD, b2_colorBlue = 0x0000FF, b2_colorBlueViolet = 0x8A2BE2, b2_colorBrown = 0xA52A2A, b2_colorBurlywood = 0xDEB887, b2_colorCadetBlue = 0x5F9EA0, b2_colorChartreuse = 0x7FFF00, b2_colorChocolate = 0xD2691E, b2_colorCoral = 0xFF7F50, b2_colorCornflowerBlue = 0x6495ED, b2_colorCornsilk = 0xFFF8DC, b2_colorCrimson = 0xDC143C, b2_colorCyan = 0x00FFFF, b2_colorDarkBlue = 0x00008B, b2_colorDarkCyan = 0x008B8B, b2_colorDarkGoldenRod = 0xB8860B, b2_colorDarkGray = 0xA9A9A9, b2_colorDarkGreen = 0x006400, b2_colorDarkKhaki = 0xBDB76B, b2_colorDarkMagenta = 0x8B008B, b2_colorDarkOliveGreen = 0x556B2F, b2_colorDarkOrange = 0xFF8C00, b2_colorDarkOrchid = 0x9932CC, b2_colorDarkRed = 0x8B0000, b2_colorDarkSalmon = 0xE9967A, b2_colorDarkSeaGreen = 0x8FBC8F, b2_colorDarkSlateBlue = 0x483D8B, b2_colorDarkSlateGray = 0x2F4F4F, b2_colorDarkTurquoise = 0x00CED1, b2_colorDarkViolet = 0x9400D3, b2_colorDeepPink = 0xFF1493, b2_colorDeepSkyBlue = 0x00BFFF, b2_colorDimGray = 0x696969, b2_colorDodgerBlue = 0x1E90FF, b2_colorFireBrick = 0xB22222, b2_colorFloralWhite = 0xFFFAF0, b2_colorForestGreen = 0x228B22, b2_colorFuchsia = 0xFF00FF, b2_colorGainsboro = 0xDCDCDC, b2_colorGhostWhite = 0xF8F8FF, b2_colorGold = 0xFFD700, b2_colorGoldenRod = 0xDAA520, b2_colorGray = 0x808080, b2_colorGreen = 0x008000, b2_colorGreenYellow = 0xADFF2F, b2_colorHoneyDew = 0xF0FFF0, b2_colorHotPink = 0xFF69B4, b2_colorIndianRed = 0xCD5C5C, b2_colorIndigo = 0x4B0082, b2_colorIvory = 0xFFFFF0, b2_colorKhaki = 0xF0E68C, b2_colorLavender = 0xE6E6FA, b2_colorLavenderBlush = 0xFFF0F5, b2_colorLawnGreen = 0x7CFC00, b2_colorLemonChiffon = 0xFFFACD, b2_colorLightBlue = 0xADD8E6, b2_colorLightCoral = 0xF08080, b2_colorLightCyan = 0xE0FFFF, b2_colorLightGoldenRodYellow = 0xFAFAD2, b2_colorLightGray = 0xD3D3D3, b2_colorLightGreen = 0x90EE90, b2_colorLightPink = 0xFFB6C1, b2_colorLightSalmon = 0xFFA07A, b2_colorLightSeaGreen = 0x20B2AA, b2_colorLightSkyBlue = 0x87CEFA, b2_colorLightSlateGray = 0x778899, b2_colorLightSteelBlue = 0xB0C4DE, b2_colorLightYellow = 0xFFFFE0, b2_colorLime = 0x00FF00, b2_colorLimeGreen = 0x32CD32, b2_colorLinen = 0xFAF0E6, b2_colorMagenta = 0xFF00FF, b2_colorMaroon = 0x800000, b2_colorMediumAquaMarine = 0x66CDAA, b2_colorMediumBlue = 0x0000CD, b2_colorMediumOrchid = 0xBA55D3, b2_colorMediumPurple = 0x9370DB, b2_colorMediumSeaGreen = 0x3CB371, b2_colorMediumSlateBlue = 0x7B68EE, b2_colorMediumSpringGreen = 0x00FA9A, b2_colorMediumTurquoise = 0x48D1CC, b2_colorMediumVioletRed = 0xC71585, b2_colorMidnightBlue = 0x191970, b2_colorMintCream = 0xF5FFFA, b2_colorMistyRose = 0xFFE4E1, b2_colorMoccasin = 0xFFE4B5, b2_colorNavajoWhite = 0xFFDEAD, b2_colorNavy = 0x000080, b2_colorOldLace = 0xFDF5E6, b2_colorOlive = 0x808000, b2_colorOliveDrab = 0x6B8E23, b2_colorOrange = 0xFFA500, b2_colorOrangeRed = 0xFF4500, b2_colorOrchid = 0xDA70D6, b2_colorPaleGoldenRod = 0xEEE8AA, b2_colorPaleGreen = 0x98FB98, b2_colorPaleTurquoise = 0xAFEEEE, b2_colorPaleVioletRed = 0xDB7093, b2_colorPapayaWhip = 0xFFEFD5, b2_colorPeachPuff = 0xFFDAB9, b2_colorPeru = 0xCD853F, b2_colorPink = 0xFFC0CB, b2_colorPlum = 0xDDA0DD, b2_colorPowderBlue = 0xB0E0E6, b2_colorPurple = 0x800080, b2_colorRebeccaPurple = 0x663399, b2_colorRed = 0xFF0000, b2_colorRosyBrown = 0xBC8F8F, b2_colorRoyalBlue = 0x4169E1, b2_colorSaddleBrown = 0x8B4513, b2_colorSalmon = 0xFA8072, b2_colorSandyBrown = 0xF4A460, b2_colorSeaGreen = 0x2E8B57, b2_colorSeaShell = 0xFFF5EE, b2_colorSienna = 0xA0522D, b2_colorSilver = 0xC0C0C0, b2_colorSkyBlue = 0x87CEEB, b2_colorSlateBlue = 0x6A5ACD, b2_colorSlateGray = 0x708090, b2_colorSnow = 0xFFFAFA, b2_colorSpringGreen = 0x00FF7F, b2_colorSteelBlue = 0x4682B4, b2_colorTan = 0xD2B48C, b2_colorTeal = 0x008080, b2_colorThistle = 0xD8BFD8, b2_colorTomato = 0xFF6347, b2_colorTurquoise = 0x40E0D0, b2_colorViolet = 0xEE82EE, b2_colorWheat = 0xF5DEB3, b2_colorWhite = 0xFFFFFF, b2_colorWhiteSmoke = 0xF5F5F5, b2_colorYellow = 0xFFFF00, b2_colorYellowGreen = 0x9ACD32, b2_colorBox2DRed = 0xDC3132, b2_colorBox2DBlue = 0x30AEBF, b2_colorBox2DGreen = 0x8CC924, b2_colorBox2DYellow = 0xFFEE8C } b2HexColor; /// This struct holds callbacks you can implement to draw a Box2D world. /// This structure should be zero initialized. /// @ingroup world typedef struct b2DebugDraw { /// Draw a closed polygon provided in CCW order. void ( *DrawPolygonFcn )( const b2Vec2* vertices, int vertexCount, b2HexColor color, void* context ); /// Draw a solid closed polygon provided in CCW order. void ( *DrawSolidPolygonFcn )( b2Transform transform, const b2Vec2* vertices, int vertexCount, float radius, b2HexColor color, void* context ); /// Draw a circle. void ( *DrawCircleFcn )( b2Vec2 center, float radius, b2HexColor color, void* context ); /// Draw a solid circle. void ( *DrawSolidCircleFcn )( b2Transform transform, float radius, b2HexColor color, void* context ); /// Draw a solid capsule. void ( *DrawSolidCapsuleFcn )( b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color, void* context ); /// Draw a line segment. void ( *DrawLineFcn )( b2Vec2 p1, b2Vec2 p2, b2HexColor color, void* context ); /// Draw a transform. Choose your own length scale. void ( *DrawTransformFcn )( b2Transform transform, void* context ); /// Draw a point. void ( *DrawPointFcn )( b2Vec2 p, float size, b2HexColor color, void* context ); /// Draw a string in world space void ( *DrawStringFcn )( b2Vec2 p, const char* s, b2HexColor color, void* context ); /// World bounds to use for debug draw b2AABB drawingBounds; /// Scale to use when drawing forces float forceScale; /// Global scaling for joint drawing float jointScale; /// Option to draw shapes bool drawShapes; /// Option to draw joints bool drawJoints; /// Option to draw additional information for joints bool drawJointExtras; /// Option to draw the bounding boxes for shapes bool drawBounds; /// Option to draw the mass and center of mass of dynamic bodies bool drawMass; /// Option to draw body names bool drawBodyNames; /// Option to draw contact points bool drawContactPoints; /// Option to visualize the graph coloring used for contacts and joints bool drawGraphColors; /// Option to draw contact feature ids bool drawContactFeatures; /// Option to draw contact normals bool drawContactNormals; /// Option to draw contact normal forces bool drawContactForces; /// Option to draw contact friction forces bool drawFrictionForces; /// Option to draw islands as bounding boxes bool drawIslands; /// User context that is passed as an argument to drawing callback functions void* context; } b2DebugDraw; /// Use this to initialize your drawing interface. This allows you to implement a sub-set /// of the drawing functions. B2_API b2DebugDraw b2DefaultDebugDraw( void ); ================================================ FILE: samples/CMakeLists.txt ================================================ # Box2D samples app # glad for OpenGL API set(GLAD_DIR ${CMAKE_SOURCE_DIR}/extern/glad) add_library( glad STATIC ${GLAD_DIR}/src/glad.c ${GLAD_DIR}/include/glad/glad.h ${GLAD_DIR}/include/KHR/khrplatform.h ) target_include_directories(glad PUBLIC ${GLAD_DIR}/include) # glfw for windowing and input set(GLFW_BUILD_DOCS OFF CACHE BOOL "GLFW Docs") set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "GLFW Examples") set(GLFW_BUILD_TESTS OFF CACHE BOOL "GLFW Tests") set(GLFW_INSTALL OFF CACHE BOOL "GLFW Install") FetchContent_Declare( glfw GIT_REPOSITORY https://github.com/glfw/glfw.git GIT_TAG 3.4 GIT_SHALLOW TRUE GIT_PROGRESS TRUE ) FetchContent_MakeAvailable(glfw) # imgui and glfw backend for GUI # https://gist.github.com/jeffamstutz/992723dfabac4e3ffff265eb71a24cd9 # Modified to pin to a specific imgui release FetchContent_Populate(imgui URL https://github.com/ocornut/imgui/archive/refs/tags/v1.91.3.zip SOURCE_DIR ${CMAKE_SOURCE_DIR}/build/imgui ) set(IMGUI_DIR ${CMAKE_SOURCE_DIR}/build/imgui) add_library(imgui STATIC ${IMGUI_DIR}/imconfig.h ${IMGUI_DIR}/imgui.h ${IMGUI_DIR}/imgui.cpp ${IMGUI_DIR}/imgui_draw.cpp ${IMGUI_DIR}/imgui_demo.cpp ${IMGUI_DIR}/imgui_tables.cpp ${IMGUI_DIR}/imgui_widgets.cpp ${IMGUI_DIR}/backends/imgui_impl_glfw.cpp ${IMGUI_DIR}/backends/imgui_impl_opengl3.cpp ) target_link_libraries(imgui PUBLIC glfw glad) target_include_directories(imgui PUBLIC ${IMGUI_DIR} ${IMGUI_DIR}/backends) target_compile_definitions(imgui PUBLIC IMGUI_DISABLE_OBSOLETE_FUNCTIONS) # The sample app also uses stb_truetype and this keeps the symbols separate target_compile_definitions(imgui PRIVATE IMGUI_STB_NAMESPACE=imgui_stb) set_target_properties(imgui PROPERTIES CXX_STANDARD 20 CXX_STANDARD_REQUIRED YES CXX_EXTENSIONS NO ) # jsmn for json set(JSMN_DIR ${CMAKE_SOURCE_DIR}/extern/jsmn) add_library(jsmn INTERFACE ${JSMN_DIR}/jsmn.h) target_include_directories(jsmn INTERFACE ${JSMN_DIR}) set(BOX2D_SAMPLE_FILES car.cpp car.h container.c container.h donut.cpp donut.h doohickey.cpp doohickey.h draw.c draw.h main.cpp sample.cpp sample.h sample_benchmark.cpp sample_bodies.cpp sample_character.cpp sample_collision.cpp sample_continuous.cpp sample_determinism.cpp sample_events.cpp sample_geometry.cpp sample_issues.cpp sample_joints.cpp sample_robustness.cpp sample_shapes.cpp sample_stacking.cpp sample_world.cpp shader.c shader.h stb_image_write.h stb_truetype.h ) add_executable(samples ${BOX2D_SAMPLE_FILES}) set_target_properties(samples PROPERTIES CXX_STANDARD 20 CXX_STANDARD_REQUIRED YES CXX_EXTENSIONS NO ) if (BOX2D_COMPILE_WARNING_AS_ERROR) set_target_properties(samples PROPERTIES COMPILE_WARNING_AS_ERROR ON) endif() target_include_directories(samples PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ${JSMN_DIR}) target_link_libraries(samples PUBLIC box2d shared imgui glfw glad enkiTS) # target_compile_definitions(samples PRIVATE "$<$:SAMPLES_DEBUG>") # message(STATUS "runtime = ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}") # message(STATUS "binary = ${CMAKE_CURRENT_BINARY_DIR}") # Copy font files, etc add_custom_command( TARGET samples POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/data/ ${CMAKE_CURRENT_BINARY_DIR}/data/) source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${BOX2D_SAMPLE_FILES}) ================================================ FILE: samples/car.cpp ================================================ // SPDX-FileCopyrightText: 2022 Erin Catto // SPDX-License-Identifier: MIT #include "car.h" #include "box2d/box2d.h" #include "box2d/math_functions.h" #include Car::Car() { m_chassisId = {}; m_rearWheelId = {}; m_frontWheelId = {}; m_rearAxleId = {}; m_frontAxleId = {}; m_isSpawned = false; } void Car::Spawn( b2WorldId worldId, b2Vec2 position, float scale, float hertz, float dampingRatio, float torque, void* userData ) { assert( m_isSpawned == false ); assert( B2_IS_NULL( m_chassisId ) ); assert( B2_IS_NULL( m_frontWheelId ) ); assert( B2_IS_NULL( m_rearWheelId ) ); b2Vec2 vertices[6] = { { -1.5f, -0.5f }, { 1.5f, -0.5f }, { 1.5f, 0.0f }, { 0.0f, 0.9f }, { -1.15f, 0.9f }, { -1.5f, 0.2f }, }; for ( int i = 0; i < 6; ++i ) { vertices[i].x *= 0.85f * scale; vertices[i].y *= 0.85f * scale; } b2Hull hull = b2ComputeHull( vertices, 6 ); b2Polygon chassis = b2MakePolygon( &hull, 0.15f * scale ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f / scale; shapeDef.material.friction = 0.2f; b2Circle circle = { { 0.0f, 0.0f }, 0.4f * scale }; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = b2Add( { 0.0f, 1.0f * scale }, position ); m_chassisId = b2CreateBody( worldId, &bodyDef ); b2CreatePolygonShape( m_chassisId, &shapeDef, &chassis ); shapeDef.density = 2.0f / scale; shapeDef.material.friction = 1.5f; shapeDef.material.rollingResistance = 0.1f; bodyDef.position = b2Add( { -1.0f * scale, 0.35f * scale }, position ); bodyDef.allowFastRotation = true; m_rearWheelId = b2CreateBody( worldId, &bodyDef ); b2CreateCircleShape( m_rearWheelId, &shapeDef, &circle ); bodyDef.position = b2Add( { 1.0f * scale, 0.4f * scale }, position ); bodyDef.allowFastRotation = true; m_frontWheelId = b2CreateBody( worldId, &bodyDef ); b2CreateCircleShape( m_frontWheelId, &shapeDef, &circle ); b2Vec2 axis = { 0.0f, 1.0f }; b2Vec2 pivot = b2Body_GetPosition( m_rearWheelId ); // float throttle = 0.0f; // float speed = 35.0f; // float torque = 2.5f * scale; // float hertz = 5.0f; // float dampingRatio = 0.7f; b2WheelJointDef jointDef = b2DefaultWheelJointDef(); jointDef.base.bodyIdA = m_chassisId; jointDef.base.bodyIdB = m_rearWheelId; jointDef.base.localFrameA.q = b2MakeRot( 0.5f * B2_PI ); jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.motorSpeed = 0.0f; jointDef.maxMotorTorque = torque; jointDef.enableMotor = true; jointDef.hertz = hertz; jointDef.dampingRatio = dampingRatio; jointDef.lowerTranslation = -0.25f * scale; jointDef.upperTranslation = 0.25f * scale; jointDef.enableLimit = true; m_rearAxleId = b2CreateWheelJoint( worldId, &jointDef ); pivot = b2Body_GetPosition( m_frontWheelId ); jointDef.base.bodyIdA = m_chassisId; jointDef.base.bodyIdB = m_frontWheelId; jointDef.base.localFrameA.q = b2MakeRot( 0.5f * B2_PI ); jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.motorSpeed = 0.0f; jointDef.maxMotorTorque = torque; jointDef.enableMotor = true; jointDef.hertz = hertz; jointDef.dampingRatio = dampingRatio; jointDef.lowerTranslation = -0.25f * scale; jointDef.upperTranslation = 0.25f * scale; jointDef.enableLimit = true; m_frontAxleId = b2CreateWheelJoint( worldId, &jointDef ); } void Car::Despawn() { assert( m_isSpawned == true ); b2DestroyJoint( m_rearAxleId, false ); b2DestroyJoint( m_frontAxleId, false ); b2DestroyBody( m_rearWheelId ); b2DestroyBody( m_frontWheelId ); b2DestroyBody( m_chassisId ); m_isSpawned = false; } void Car::SetSpeed( float speed ) { b2WheelJoint_SetMotorSpeed( m_rearAxleId, speed ); b2WheelJoint_SetMotorSpeed( m_frontAxleId, speed ); b2Joint_WakeBodies( m_rearAxleId ); } void Car::SetTorque( float torque ) { b2WheelJoint_SetMaxMotorTorque( m_rearAxleId, torque ); b2WheelJoint_SetMaxMotorTorque( m_frontAxleId, torque ); } void Car::SetHertz( float hertz ) { b2WheelJoint_SetSpringHertz( m_rearAxleId, hertz ); b2WheelJoint_SetSpringHertz( m_frontAxleId, hertz ); } void Car::SetDampingRadio( float dampingRatio ) { b2WheelJoint_SetSpringDampingRatio( m_rearAxleId, dampingRatio ); b2WheelJoint_SetSpringDampingRatio( m_frontAxleId, dampingRatio ); } Truck::Truck() { m_chassisId = {}; m_rearWheelId = {}; m_frontWheelId = {}; m_rearAxleId = {}; m_frontAxleId = {}; m_isSpawned = false; } void Truck::Spawn( b2WorldId worldId, b2Vec2 position, float scale, float hertz, float dampingRatio, float torque, float density, void* userData ) { assert( m_isSpawned == false ); assert( B2_IS_NULL( m_chassisId ) ); assert( B2_IS_NULL( m_frontWheelId ) ); assert( B2_IS_NULL( m_rearWheelId ) ); // b2Vec2 vertices[6] = { // { -1.5f, -0.5f }, { 1.5f, -0.5f }, { 1.5f, 0.0f }, { 0.0f, 0.9f }, { -1.15f, 0.9f }, { -1.5f, 0.2f }, // }; b2Vec2 vertices[5] = { { -0.65f, -0.4f }, { 1.5f, -0.4f }, { 1.5f, 0.0f }, { 0.0f, 0.9f }, { -0.65f, 0.9f }, }; for ( int i = 0; i < 5; ++i ) { vertices[i].x *= 0.85f * scale; vertices[i].y *= 0.85f * scale; } b2Hull hull = b2ComputeHull( vertices, 5 ); b2Polygon chassis = b2MakePolygon( &hull, 0.15f * scale ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = density; shapeDef.material.friction = 0.2f; shapeDef.material.customColor = b2_colorHotPink; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = b2Add( { 0.0f, 1.0f * scale }, position ); m_chassisId = b2CreateBody( worldId, &bodyDef ); b2CreatePolygonShape( m_chassisId, &shapeDef, &chassis ); b2Polygon box = b2MakeOffsetBox( 1.25f * scale, 0.1f * scale, { -2.05f * scale, -0.275f * scale }, b2Rot_identity ); box.radius = 0.1f * scale; b2CreatePolygonShape( m_chassisId, &shapeDef, &box ); box = b2MakeOffsetBox( 0.05f * scale, 0.35f * scale, { -3.25f * scale, 0.375f * scale }, b2Rot_identity ); box.radius = 0.1f * scale; b2CreatePolygonShape( m_chassisId, &shapeDef, &box ); shapeDef.density = 2.0f * density; shapeDef.material.friction = 2.5f; shapeDef.material.customColor = b2_colorSilver; b2Circle circle = { { 0.0f, 0.0f }, 0.4f * scale }; bodyDef.position = b2Add( { -2.75f * scale, 0.3f * scale }, position ); m_rearWheelId = b2CreateBody( worldId, &bodyDef ); b2CreateCircleShape( m_rearWheelId, &shapeDef, &circle ); bodyDef.position = b2Add( { 0.8f * scale, 0.3f * scale }, position ); m_frontWheelId = b2CreateBody( worldId, &bodyDef ); b2CreateCircleShape( m_frontWheelId, &shapeDef, &circle ); b2Vec2 axis = { 0.0f, 1.0f }; b2Vec2 pivot = b2Body_GetPosition( m_rearWheelId ); // float throttle = 0.0f; // float speed = 35.0f; // float torque = 2.5f * scale; // float hertz = 5.0f; // float dampingRatio = 0.7f; b2WheelJointDef jointDef = b2DefaultWheelJointDef(); jointDef.base.bodyIdA = m_chassisId; jointDef.base.bodyIdB = m_rearWheelId; jointDef.base.localFrameA.q = b2MakeRot( 0.5f * B2_PI ); jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.motorSpeed = 0.0f; jointDef.maxMotorTorque = torque; jointDef.enableMotor = true; jointDef.hertz = hertz; jointDef.dampingRatio = dampingRatio; jointDef.lowerTranslation = -0.25f * scale; jointDef.upperTranslation = 0.25f * scale; jointDef.enableLimit = true; m_rearAxleId = b2CreateWheelJoint( worldId, &jointDef ); pivot = b2Body_GetPosition( m_frontWheelId ); jointDef.base.bodyIdA = m_chassisId; jointDef.base.bodyIdB = m_frontWheelId; jointDef.base.localFrameA.q = b2MakeRot( 0.5f * B2_PI ); jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.motorSpeed = 0.0f; jointDef.maxMotorTorque = torque; jointDef.enableMotor = true; jointDef.hertz = hertz; jointDef.dampingRatio = dampingRatio; jointDef.lowerTranslation = -0.25f * scale; jointDef.upperTranslation = 0.25f * scale; jointDef.enableLimit = true; m_frontAxleId = b2CreateWheelJoint( worldId, &jointDef ); } void Truck::Despawn() { assert( m_isSpawned == true ); b2DestroyJoint( m_rearAxleId, false ); b2DestroyJoint( m_frontAxleId, false ); b2DestroyBody( m_rearWheelId ); b2DestroyBody( m_frontWheelId ); b2DestroyBody( m_chassisId ); m_isSpawned = false; } void Truck::SetSpeed( float speed ) { b2WheelJoint_SetMotorSpeed( m_rearAxleId, speed ); b2WheelJoint_SetMotorSpeed( m_frontAxleId, speed ); b2Joint_WakeBodies( m_rearAxleId ); } void Truck::SetTorque( float torque ) { b2WheelJoint_SetMaxMotorTorque( m_rearAxleId, torque ); b2WheelJoint_SetMaxMotorTorque( m_frontAxleId, torque ); } void Truck::SetHertz( float hertz ) { b2WheelJoint_SetSpringHertz( m_rearAxleId, hertz ); b2WheelJoint_SetSpringHertz( m_frontAxleId, hertz ); } void Truck::SetDampingRadio( float dampingRatio ) { b2WheelJoint_SetSpringDampingRatio( m_rearAxleId, dampingRatio ); b2WheelJoint_SetSpringDampingRatio( m_frontAxleId, dampingRatio ); } ================================================ FILE: samples/car.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "box2d/types.h" class Car { public: Car(); void Spawn( b2WorldId worldId, b2Vec2 position, float scale, float hertz, float dampingRatio, float torque, void* userData ); void Despawn(); void SetSpeed( float speed ); void SetTorque( float torque ); void SetHertz( float hertz ); void SetDampingRadio( float dampingRatio ); b2BodyId m_chassisId; b2BodyId m_rearWheelId; b2BodyId m_frontWheelId; b2JointId m_rearAxleId; b2JointId m_frontAxleId; bool m_isSpawned; }; class Truck { public: Truck(); void Spawn( b2WorldId worldId, b2Vec2 position, float scale, float hertz, float dampingRatio, float torque, float density, void* userData ); void Despawn(); void SetSpeed( float speed ); void SetTorque( float torque ); void SetHertz( float hertz ); void SetDampingRadio( float dampingRatio ); b2BodyId m_chassisId; b2BodyId m_rearWheelId; b2BodyId m_frontWheelId; b2JointId m_rearAxleId; b2JointId m_frontAxleId; bool m_isSpawned; }; ================================================ FILE: samples/container.c ================================================ // SPDX-FileCopyrightText: 2025 Erin Catto // SPDX-License-Identifier: MIT #if defined( _MSC_VER ) && !defined( _CRT_SECURE_NO_WARNINGS ) #define _CRT_SECURE_NO_WARNINGS #endif #include "container.h" #include #include #include void* GrowAlloc( void* oldMem, int oldSize, int newSize ) { assert( newSize > oldSize ); void* newMem = malloc( newSize ); if ( oldSize > 0 ) { memcpy( newMem, oldMem, oldSize ); free( oldMem ); } return newMem; } ================================================ FILE: samples/container.h ================================================ // SPDX-FileCopyrightText: 2025 Erin Catto // SPDX-License-Identifier: MIT #pragma once #define NULL_INDEX -1 // Array declaration. Works with forward declaration of TYPE. #define ARRAY_DECLARE( TYPE ) \ typedef struct \ { \ TYPE* data; \ int count; \ int capacity; \ } TYPE##Array; \ TYPE##Array TYPE##Array_Create( int capacity ); \ void TYPE##Array_Reserve( TYPE##Array* a, int newCapacity ); \ void TYPE##Array_Destroy( TYPE##Array* a ) // Inline array functions that need the TYPE to be defined. #define ARRAY_INLINE( TYPE ) \ static inline void TYPE##Array_Resize( TYPE##Array* a, int count ) \ { \ TYPE##Array_Reserve( a, count ); \ a->count = count; \ } \ static inline TYPE* TYPE##Array_Get( TYPE##Array* a, int index ) \ { \ assert( 0 <= index && index < a->count ); \ return a->data + index; \ } \ static inline TYPE* TYPE##Array_Add( TYPE##Array* a ) \ { \ if ( a->count == a->capacity ) \ { \ int newCapacity = a->capacity < 2 ? 2 : a->capacity + ( a->capacity >> 1 ); \ TYPE##Array_Reserve( a, newCapacity ); \ } \ a->count += 1; \ return a->data + ( a->count - 1 ); \ } \ static inline void TYPE##Array_Push( TYPE##Array* a, TYPE value ) \ { \ if ( a->count == a->capacity ) \ { \ int newCapacity = a->capacity < 2 ? 2 : a->capacity + ( a->capacity >> 1 ); \ TYPE##Array_Reserve( a, newCapacity ); \ } \ a->data[a->count] = value; \ a->count += 1; \ } \ static inline void TYPE##Array_Set( TYPE##Array* a, int index, TYPE value ) \ { \ assert( 0 <= index && index < a->count ); \ a->data[index] = value; \ } \ static inline int TYPE##Array_RemoveSwap( TYPE##Array* a, int index ) \ { \ assert( 0 <= index && index < a->count ); \ int movedIndex = NULL_INDEX; \ if ( index != a->count - 1 ) \ { \ movedIndex = a->count - 1; \ a->data[index] = a->data[movedIndex]; \ } \ a->count -= 1; \ return movedIndex; \ } \ static inline TYPE TYPE##Array_Pop( TYPE##Array* a ) \ { \ assert( a->count > 0 ); \ TYPE value = a->data[a->count - 1]; \ a->count -= 1; \ return value; \ } \ // These functions go in the source file #define ARRAY_SOURCE( TYPE ) \ TYPE##Array TYPE##Array_Create( int capacity ) \ { \ TYPE##Array a = { 0 }; \ if ( capacity > 0 ) \ { \ a.data = malloc( capacity * sizeof( TYPE ) ); \ a.capacity = capacity; \ } \ return a; \ } \ void TYPE##Array_Reserve( TYPE##Array* a, int newCapacity ) \ { \ if ( newCapacity <= a->capacity ) \ { \ return; \ } \ a->data = GrowAlloc( a->data, a->capacity * sizeof( TYPE ), newCapacity * sizeof( TYPE ) ); \ a->capacity = newCapacity; \ } \ void TYPE##Array_Destroy( TYPE##Array* a ) \ { \ free( a->data ); \ a->data = NULL; \ a->count = 0; \ a->capacity = 0; \ } void* GrowAlloc( void* oldMem, int oldSize, int newSize ); ================================================ FILE: samples/data/background.fs ================================================ // SPDX-FileCopyrightText: 2024 Erin Catto // SPDX-License-Identifier: MIT #version 330 out vec4 FragColor; uniform float time; uniform vec2 resolution; uniform vec3 baseColor; // A simple pseudo-random function float random(vec2 st) { return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453123); } void main() { vec2 uv = gl_FragCoord.xy / resolution.xy; // Create some noise float noise = random(uv + time * 0.1); // Adjust these values to control the intensity and color of the grain float grainIntensity = 0.01; // Mix the base color with the noise vec3 color = baseColor + vec3(noise * grainIntensity); FragColor = vec4(color, 1.0); } ================================================ FILE: samples/data/background.vs ================================================ // SPDX-FileCopyrightText: 2024 Erin Catto // SPDX-License-Identifier: MIT #version 330 layout(location = 0) in vec2 v_position; void main(void) { gl_Position = vec4(v_position, 0.0f, 1.0f); } ================================================ FILE: samples/data/circle.fs ================================================ // SPDX-FileCopyrightText: 2024 Erin Catto // SPDX-License-Identifier: MIT #version 330 in vec2 f_position; in vec4 f_color; in float f_thickness; out vec4 fragColor; void main() { // radius in unit quad float radius = 1.0; // distance to circle vec2 w = f_position; float dw = length(w); float d = abs(dw - radius); fragColor = vec4(f_color.rgb, smoothstep(f_thickness, 0.0, d)); } ================================================ FILE: samples/data/circle.vs ================================================ // SPDX-FileCopyrightText: 2024 Erin Catto // SPDX-License-Identifier: MIT #version 330 uniform mat4 projectionMatrix; uniform float pixelScale; layout(location = 0) in vec2 v_localPosition; layout(location = 1) in vec2 v_instancePosition; layout(location = 2) in float v_instanceRadius; layout(location = 3) in vec4 v_instanceColor; out vec2 f_position; out vec4 f_color; out float f_thickness; void main() { f_position = v_localPosition; f_color = v_instanceColor; float radius = v_instanceRadius; // resolution.y = pixelScale * radius f_thickness = 3.0f / (pixelScale * radius); vec2 p = vec2(radius * v_localPosition.x, radius * v_localPosition.y) + v_instancePosition; gl_Position = projectionMatrix * vec4(p, 0.0f, 1.0f); } ================================================ FILE: samples/data/font.fs ================================================ // SPDX-FileCopyrightText: 2025 Erin Catto // SPDX-License-Identifier: MIT #version 330 core in vec4 color; in vec2 uv; uniform sampler2D FontAtlas; out vec4 fragColor; void main() { fragColor = vec4(color.rgb, color.a * texture(FontAtlas, uv).r); } ================================================ FILE: samples/data/font.vs ================================================ // SPDX-FileCopyrightText: 2025 Erin Catto // SPDX-License-Identifier: MIT #version 330 core layout (location = 0) in vec2 aPosition; layout (location = 1) in vec2 aUV; layout (location = 2) in vec4 aColor; out vec4 color; out vec2 uv; uniform mat4 ProjectionMatrix; void main() { gl_Position = ProjectionMatrix * vec4(aPosition, 0.0, 1.0); color = aColor; uv = aUV; } ================================================ FILE: samples/data/line.fs ================================================ // SPDX-FileCopyrightText: 2025 Erin Catto // SPDX-License-Identifier: MIT #version 330 in vec4 f_color; out vec4 color; void main(void) { color = f_color; } ================================================ FILE: samples/data/line.vs ================================================ // SPDX-FileCopyrightText: 2024 Erin Catto // SPDX-License-Identifier: MIT #version 330 uniform mat4 projectionMatrix; layout(location = 0) in vec2 v_position; layout(location = 1) in vec4 v_color; out vec4 f_color; void main(void) { f_color = v_color; gl_Position = projectionMatrix * vec4(v_position, 0.0f, 1.0f); } ================================================ FILE: samples/data/point.fs ================================================ // SPDX-FileCopyrightText: 2025 Erin Catto // SPDX-License-Identifier: MIT #version 330 in vec4 f_color; out vec4 color; void main(void) { color = f_color; } ================================================ FILE: samples/data/point.vs ================================================ // SPDX-FileCopyrightText: 2024 Erin Catto // SPDX-License-Identifier: MIT #version 330 uniform mat4 projectionMatrix; layout(location = 0) in vec2 v_position; layout(location = 1) in float v_size; layout(location = 2) in vec4 v_color; out vec4 f_color; void main(void) { f_color = v_color; gl_Position = projectionMatrix * vec4(v_position, 0.0f, 1.0f); gl_PointSize = v_size; } ================================================ FILE: samples/data/solid_capsule.fs ================================================ // SPDX-FileCopyrightText: 2024 Erin Catto // SPDX-License-Identifier: MIT #version 330 in vec2 f_position; in vec4 f_color; in float f_length; in float f_thickness; out vec4 color; // Thanks to baz and kolyan3040 for help on this shader // todo this can be optimized a bit, keeping some terms for clarity // https://en.wikipedia.org/wiki/Alpha_compositing vec4 blend_colors(vec4 front,vec4 back) { vec3 cSrc = front.rgb; float alphaSrc = front.a; vec3 cDst = back.rgb; float alphaDst = back.a; vec3 cOut = cSrc * alphaSrc + cDst * alphaDst * (1.0 - alphaSrc); float alphaOut = alphaSrc + alphaDst * (1.0 - alphaSrc); // remove alpha from rgb cOut = cOut / alphaOut; return vec4(cOut, alphaOut); } void main() { // radius in unit quad float radius = 0.5 * (2.0 - f_length); vec4 borderColor = f_color; vec4 fillColor = 0.6f * borderColor; vec2 v1 = vec2(-0.5 * f_length, 0); vec2 v2 = vec2(0.5 * f_length, 0); // distance to line segment vec2 e = v2 - v1; vec2 w = f_position - v1; float we = dot(w, e); vec2 b = w - e * clamp(we / dot(e, e), 0.0, 1.0); float dw = length(b); // SDF union of capsule and line segment float d = min(dw, abs(dw - radius)); // roll the fill alpha down at the border vec4 back = vec4(fillColor.rgb, fillColor.a * smoothstep(radius + f_thickness, radius, dw)); // roll the border alpha down from 1 to 0 across the border thickness vec4 front = vec4(borderColor.rgb, smoothstep(f_thickness, 0.0f, d)); color = blend_colors(front, back); } ================================================ FILE: samples/data/solid_capsule.vs ================================================ // SPDX-FileCopyrightText: 2024 Erin Catto // SPDX-License-Identifier: MIT #version 330 uniform mat4 projectionMatrix; uniform float pixelScale; layout(location=0) in vec2 v_localPosition; layout(location=1) in vec4 v_instanceTransform; layout(location=2) in float v_instanceRadius; layout(location=3) in float v_instanceLength; layout(location=4) in vec4 v_instanceColor; out vec2 f_position; out vec4 f_color; out float f_length; out float f_thickness; void main() { f_position = v_localPosition; f_color = v_instanceColor; float radius = v_instanceRadius; float length = v_instanceLength; // scale quad large enough to hold capsule float scale = radius + 0.5 * length; // quad range of [-1, 1] implies normalize radius and length f_length = length / scale; // resolution.y = pixelScale * scale f_thickness = 3.0f / (pixelScale * scale); float x = v_instanceTransform.x; float y = v_instanceTransform.y; float c = v_instanceTransform.z; float s = v_instanceTransform.w; vec2 p = vec2(scale * v_localPosition.x, scale * v_localPosition.y); p = vec2((c * p.x - s * p.y) + x, (s * p.x + c * p.y) + y); gl_Position = projectionMatrix * vec4(p, 0.0, 1.0); } ================================================ FILE: samples/data/solid_circle.fs ================================================ // SPDX-FileCopyrightText: 2024 Erin Catto // SPDX-License-Identifier: MIT #version 330 in vec2 f_position; in vec4 f_color; in float f_thickness; out vec4 fragColor; // https://en.wikipedia.org/wiki/Alpha_compositing vec4 blend_colors(vec4 front, vec4 back) { vec3 cSrc = front.rgb; float alphaSrc = front.a; vec3 cDst = back.rgb; float alphaDst = back.a; vec3 cOut = cSrc * alphaSrc + cDst * alphaDst * (1.0 - alphaSrc); float alphaOut = alphaSrc + alphaDst * (1.0 - alphaSrc); cOut = cOut / alphaOut; return vec4(cOut, alphaOut); } void main() { // radius in unit quad float radius = 1.0; // distance to axis line segment vec2 e = vec2(radius, 0); vec2 w = f_position; float we = dot(w, e); vec2 b = w - e * clamp(we / dot(e, e), 0.0, 1.0); float da = length(b); // distance to circle float dw = length(w); float dc = abs(dw - radius); // union of circle and axis float d = min(da, dc); vec4 borderColor = f_color; vec4 fillColor = 0.6f * borderColor; // roll the fill alpha down at the border vec4 back = vec4(fillColor.rgb, fillColor.a * smoothstep(radius + f_thickness, radius, dw)); // roll the border alpha down from 1 to 0 across the border thickness vec4 front = vec4(borderColor.rgb, smoothstep(f_thickness, 0.0f, d)); fragColor = blend_colors(front, back); } ================================================ FILE: samples/data/solid_circle.vs ================================================ // SPDX-FileCopyrightText: 2024 Erin Catto // SPDX-License-Identifier: MIT #version 330 uniform mat4 projectionMatrix; uniform float pixelScale; layout(location = 0) in vec2 v_localPosition; layout(location = 1) in vec4 v_instanceTransform; layout(location = 2) in float v_instanceRadius; layout(location = 3) in vec4 v_instanceColor; out vec2 f_position; out vec4 f_color; out float f_thickness; void main() { f_position = v_localPosition; f_color = v_instanceColor; float radius = v_instanceRadius; // resolution.y = pixelScale * radius f_thickness = 3.0f / (pixelScale * radius); float x = v_instanceTransform.x; float y = v_instanceTransform.y; float c = v_instanceTransform.z; float s = v_instanceTransform.w; vec2 p = vec2(radius * v_localPosition.x, radius * v_localPosition.y); p = vec2((c * p.x - s * p.y) + x, (s * p.x + c * p.y) + y); gl_Position = projectionMatrix * vec4(p, 0.0f, 1.0f); } ================================================ FILE: samples/data/solid_polygon.fs ================================================ // SPDX-FileCopyrightText: 2024 Erin Catto // SPDX-License-Identifier: MIT #version 330 in vec2 f_position; in vec2 f_points[8]; flat in int f_count; in float f_radius; in vec4 f_color; in float f_thickness; out vec4 fragColor; // https://en.wikipedia.org/wiki/Alpha_compositing vec4 blend_colors(vec4 front, vec4 back) { vec3 cSrc = front.rgb; float alphaSrc = front.a; vec3 cDst = back.rgb; float alphaDst = back.a; vec3 cOut = cSrc * alphaSrc + cDst * alphaDst * (1.0 - alphaSrc); float alphaOut = alphaSrc + alphaDst * (1.0 - alphaSrc); // remove alpha from rgb cOut = cOut / alphaOut; return vec4(cOut, alphaOut); } float cross2d(in vec2 v1, in vec2 v2) { return v1.x * v2.y - v1.y * v2.x; } // Signed distance function for convex polygon float sdConvexPolygon(in vec2 p, in vec2[8] v, in int count) { // Initial squared distance float d = dot(p - v[0], p - v[0]); // Consider query point inside to start float side = -1.0; int j = count - 1; for (int i = 0; i < count; ++i) { // Distance to a polygon edge vec2 e = v[i] - v[j]; vec2 w = p - v[j]; float we = dot(w, e); vec2 b = w - e * clamp(we / dot(e, e), 0.0, 1.0); float bb = dot(b, b); // Track smallest distance if (bb < d) { d = bb; } // If the query point is outside any edge then it is outside the entire polygon. // This depends on the CCW winding order of points. float s = cross2d(w, e); if (s >= 0.0) { side = 1.0; } j = i; } return side * sqrt(d); } void main() { vec4 borderColor = f_color; vec4 fillColor = 0.6f * borderColor; float dw = sdConvexPolygon(f_position, f_points, f_count); float d = abs(dw - f_radius); // roll the fill alpha down at the border vec4 back = vec4(fillColor.rgb, fillColor.a * smoothstep(f_radius + f_thickness, f_radius, dw)); // roll the border alpha down from 1 to 0 across the border thickness vec4 front = vec4(borderColor.rgb, smoothstep(f_thickness, 0.0f, d)); fragColor = blend_colors(front, back); // todo debugging // float resy = 3.0f / f_thickness; // if (resy < 539.9f) // { // fragColor = vec4(1, 0, 0, 1); // } // else if (resy > 540.1f) // { // fragColor = vec4(0, 1, 0, 1); // } // else // { // fragColor = vec4(0, 0, 1, 1); // } } ================================================ FILE: samples/data/solid_polygon.vs ================================================ // SPDX-FileCopyrightText: 2024 Erin Catto // SPDX-License-Identifier: MIT #version 330 uniform mat4 projectionMatrix; uniform float pixelScale; layout(location = 0) in vec2 v_localPosition; layout(location = 1) in vec4 v_instanceTransform; layout(location = 2) in vec4 v_instancePoints12; layout(location = 3) in vec4 v_instancePoints34; layout(location = 4) in vec4 v_instancePoints56; layout(location = 5) in vec4 v_instancePoints78; layout(location = 6) in int v_instanceCount; layout(location = 7) in float v_instanceRadius; layout(location = 8) in vec4 v_instanceColor; out vec2 f_position; out vec4 f_color; out vec2 f_points[8]; flat out int f_count; out float f_radius; out float f_thickness; void main() { f_position = v_localPosition; f_color = v_instanceColor; f_radius = v_instanceRadius; f_count = v_instanceCount; f_points[0] = v_instancePoints12.xy; f_points[1] = v_instancePoints12.zw; f_points[2] = v_instancePoints34.xy; f_points[3] = v_instancePoints34.zw; f_points[4] = v_instancePoints56.xy; f_points[5] = v_instancePoints56.zw; f_points[6] = v_instancePoints78.xy; f_points[7] = v_instancePoints78.zw; // Compute polygon AABB vec2 lower = f_points[0]; vec2 upper = f_points[0]; for (int i = 1; i < v_instanceCount; ++i) { lower = min(lower, f_points[i]); upper = max(upper, f_points[i]); } vec2 center = 0.5 * (lower + upper); vec2 width = upper - lower; float maxWidth = max(width.x, width.y); float scale = f_radius + 0.5 * maxWidth; float invScale = 1.0 / scale; // Shift and scale polygon points so they fit in 2x2 quad for (int i = 0; i < f_count; ++i) { f_points[i] = invScale * (f_points[i] - center); } // Scale radius as well f_radius = invScale * f_radius; // resolution.y = pixelScale * scale f_thickness = 3.0f / (pixelScale * scale); // scale up and transform quad to fit polygon float x = v_instanceTransform.x; float y = v_instanceTransform.y; float c = v_instanceTransform.z; float s = v_instanceTransform.w; vec2 p = vec2(scale * v_localPosition.x, scale * v_localPosition.y) + center; p = vec2((c * p.x - s * p.y) + x, (s * p.x + c * p.y) + y); gl_Position = projectionMatrix * vec4(p, 0.0f, 1.0f); } ================================================ FILE: samples/donut.cpp ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "donut.h" #include "box2d/box2d.h" #include "box2d/math_functions.h" #include Donut::Donut() { for ( int i = 0; i < m_sides; ++i ) { m_bodyIds[i] = b2_nullBodyId; m_jointIds[i] = b2_nullJointId; } m_isSpawned = false; } void Donut::Create( b2WorldId worldId, b2Vec2 position, float scale, int groupIndex, bool enableSensorEvents, void* userData ) { assert( m_isSpawned == false ); for ( int i = 0; i < m_sides; ++i ) { assert( B2_IS_NULL( m_bodyIds[i] ) ); assert( B2_IS_NULL( m_jointIds[i] ) ); } float radius = 1.0f * scale; float deltaAngle = 2.0f * B2_PI / m_sides; float length = 2.0f * B2_PI * radius / m_sides; b2Capsule capsule = { { 0.0f, -0.5f * length }, { 0.0f, 0.5f * length }, 0.25f * scale }; b2Vec2 center = position; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.userData = userData; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.enableSensorEvents = enableSensorEvents; shapeDef.filter.groupIndex = -groupIndex; shapeDef.material.friction = 0.3f; // Create bodies float angle = 0.0f; for ( int i = 0; i < m_sides; ++i ) { bodyDef.position = { radius * cosf( angle ) + center.x, radius * sinf( angle ) + center.y }; bodyDef.rotation = b2MakeRot( angle ); m_bodyIds[i] = b2CreateBody( worldId, &bodyDef ); b2CreateCapsuleShape( m_bodyIds[i], &shapeDef, &capsule ); angle += deltaAngle; } // Create joints b2WeldJointDef weldDef = b2DefaultWeldJointDef(); weldDef.angularHertz = 5.0f; weldDef.angularDampingRatio = 0.0f; weldDef.base.localFrameA.p = { 0.0f, 0.5f * length }; weldDef.base.localFrameB.p = { 0.0f, -0.5f * length }; weldDef.base.drawScale = 0.5f * scale; b2BodyId prevBodyId = m_bodyIds[m_sides - 1]; for ( int i = 0; i < m_sides; ++i ) { weldDef.base.bodyIdA = prevBodyId; weldDef.base.bodyIdB = m_bodyIds[i]; b2Rot qA = b2Body_GetRotation( prevBodyId ); b2Rot qB = b2Body_GetRotation( m_bodyIds[i] ); weldDef.base.localFrameA.q = b2InvMulRot( qA, qB ); m_jointIds[i] = b2CreateWeldJoint( worldId, &weldDef ); prevBodyId = weldDef.base.bodyIdB; } m_isSpawned = true; } void Donut::Destroy() { assert( m_isSpawned == true ); for ( int i = 0; i < m_sides; ++i ) { b2DestroyBody( m_bodyIds[i] ); m_bodyIds[i] = b2_nullBodyId; m_jointIds[i] = b2_nullJointId; } m_isSpawned = false; } ================================================ FILE: samples/donut.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "box2d/types.h" class Donut { public: Donut(); void Create( b2WorldId worldId, b2Vec2 position, float scale, int groupIndex, bool enableSensorEvents, void* userData ); void Destroy(); static constexpr int m_sides = 7; b2BodyId m_bodyIds[m_sides]; b2JointId m_jointIds[m_sides]; bool m_isSpawned; }; ================================================ FILE: samples/doohickey.cpp ================================================ // SPDX-FileCopyrightText: 2025 Erin Catto // SPDX-License-Identifier: MIT #include "doohickey.h" #include "box2d/box2d.h" #include "box2d/math_functions.h" #include Doohickey::Doohickey() { m_wheelId1 = {}; m_wheelId2 = {}; m_barId1 = {}; m_barId2 = {}; m_axleId1 = {}; m_axleId2 = {}; m_sliderId = {}; m_isSpawned = false; } void Doohickey::Spawn( b2WorldId worldId, b2Vec2 position, float scale ) { assert( m_isSpawned == false ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.rollingResistance = 0.1f; b2Circle circle = { { 0.0f, 0.0f }, 1.0f * scale }; b2Capsule capsule = { { -3.5f * scale, 0.0f }, { 3.5f * scale, 0.0f }, 0.15f * scale }; bodyDef.position = b2MulAdd( position, scale, { -5.0f, 3.0f } ); m_wheelId1 = b2CreateBody( worldId, &bodyDef ); b2CreateCircleShape( m_wheelId1, &shapeDef, &circle ); bodyDef.position = b2MulAdd( position, scale, { 5.0f, 3.0f } ); m_wheelId2 = b2CreateBody( worldId, &bodyDef ); b2CreateCircleShape( m_wheelId2, &shapeDef, &circle ); bodyDef.position = b2MulAdd( position, scale, { -1.5f, 3.0f } ); m_barId1 = b2CreateBody( worldId, &bodyDef ); b2CreateCapsuleShape( m_barId1, &shapeDef, &capsule ); bodyDef.position = b2MulAdd( position, scale, { 1.5f, 3.0f } ); m_barId2 = b2CreateBody( worldId, &bodyDef ); b2CreateCapsuleShape( m_barId2, &shapeDef, &capsule ); b2RevoluteJointDef revoluteDef = b2DefaultRevoluteJointDef(); revoluteDef.base.bodyIdA = m_wheelId1; revoluteDef.base.bodyIdB = m_barId1; revoluteDef.base.localFrameA.p = { 0.0f, 0.0f }; revoluteDef.base.localFrameB.p = { -3.5f * scale, 0.0f }; revoluteDef.enableMotor = true; revoluteDef.maxMotorTorque = 2.0f * scale; b2CreateRevoluteJoint( worldId, &revoluteDef ); revoluteDef.base.bodyIdA = m_wheelId2; revoluteDef.base.bodyIdB = m_barId2; revoluteDef.base.localFrameA.p = { 0.0f, 0.0f }; revoluteDef.base.localFrameB.p = { 3.5f * scale, 0.0f }; revoluteDef.enableMotor = true; revoluteDef.maxMotorTorque = 2.0f * scale; b2CreateRevoluteJoint( worldId, &revoluteDef ); b2PrismaticJointDef prismaticDef = b2DefaultPrismaticJointDef(); prismaticDef.base.bodyIdA = m_barId1; prismaticDef.base.bodyIdB = m_barId2; prismaticDef.base.localFrameA.p = { 2.0f * scale, 0.0f }; prismaticDef.base.localFrameB.p = { -2.0f * scale, 0.0f }; prismaticDef.lowerTranslation = -2.0f * scale; prismaticDef.upperTranslation = 2.0f * scale; prismaticDef.enableLimit = true; prismaticDef.enableMotor = true; prismaticDef.maxMotorForce = 2.0f * scale; prismaticDef.enableSpring = true; prismaticDef.hertz = 1.0f; prismaticDef.dampingRatio = 0.5; b2CreatePrismaticJoint( worldId, &prismaticDef ); } void Doohickey::Despawn() { assert( m_isSpawned == true ); b2DestroyJoint( m_axleId1, false ); b2DestroyJoint( m_axleId2, false ); b2DestroyJoint( m_sliderId, false ); b2DestroyBody( m_wheelId1 ); b2DestroyBody( m_wheelId2 ); b2DestroyBody( m_barId1 ); b2DestroyBody( m_barId2 ); m_isSpawned = false; } ================================================ FILE: samples/doohickey.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "box2d/types.h" class Doohickey { public: Doohickey(); void Spawn( b2WorldId worldId, b2Vec2 position, float scale ); void Despawn(); b2BodyId m_wheelId1; b2BodyId m_wheelId2; b2BodyId m_barId1; b2BodyId m_barId2; b2JointId m_axleId1; b2JointId m_axleId2; b2JointId m_sliderId; bool m_isSpawned; }; ================================================ FILE: samples/draw.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #if defined( _MSC_VER ) && !defined( _CRT_SECURE_NO_WARNINGS ) #define _CRT_SECURE_NO_WARNINGS #endif #include "draw.h" #include "container.h" #include "shader.h" #include "box2d/math_functions.h" #include #include #include #if defined( _MSC_VER ) #define _CRTDBG_MAP_ALLOC #include #include #else #include #endif // clang-format off #include #include // clang-format on #define STBTT_STATIC #define STB_TRUETYPE_IMPLEMENTATION #include "stb_truetype.h" //#define STB_IMAGE_WRITE_IMPLEMENTATION //#include "stb_image_write.h" #define BUFFER_OFFSET( x ) ( (const void*)( x ) ) #define SHADER_TEXT( x ) "#version 330\n" #x typedef struct { uint8_t r, g, b, a; } RGBA8; static inline RGBA8 MakeRGBA8( b2HexColor c, float alpha ) { return (RGBA8){ (uint8_t)( ( c >> 16 ) & 0xFF ), (uint8_t)( ( c >> 8 ) & 0xFF ), (uint8_t)( c & 0xFF ), (uint8_t)( 0xFF * alpha ), }; } Camera GetDefaultCamera( void ) { return (Camera){ .center = { 0.0f, 20.0f }, .zoom = 1.0f, .width = 1920.0f, .height = 1080.0f, }; } void ResetView( Camera* camera ) { camera->center = (b2Vec2){ 0.0f, 20.0f }; camera->zoom = 1.0f; } b2Vec2 ConvertScreenToWorld( Camera* camera, b2Vec2 screenPoint ) { float w = camera->width; float h = camera->height; float u = screenPoint.x / w; float v = ( h - screenPoint.y ) / h; float ratio = w / h; b2Vec2 extents = { camera->zoom * ratio, camera->zoom }; b2Vec2 lower = b2Sub( camera->center, extents ); b2Vec2 upper = b2Add( camera->center, extents ); b2Vec2 pw = { ( 1.0f - u ) * lower.x + u * upper.x, ( 1.0f - v ) * lower.y + v * upper.y }; return pw; } b2Vec2 ConvertWorldToScreen( Camera* camera, b2Vec2 worldPoint ) { float w = camera->width; float h = camera->height; float ratio = w / h; b2Vec2 extents = { camera->zoom * ratio, camera->zoom }; b2Vec2 lower = b2Sub( camera->center, extents ); b2Vec2 upper = b2Add( camera->center, extents ); float u = ( worldPoint.x - lower.x ) / ( upper.x - lower.x ); float v = ( worldPoint.y - lower.y ) / ( upper.y - lower.y ); b2Vec2 ps = { u * w, ( 1.0f - v ) * h }; return ps; } // Convert from world coordinates to normalized device coordinates. // http://www.songho.ca/opengl/gl_projectionmatrix.html // This also includes the view transform static void BuildProjectionMatrix( Camera* camera, float* m, float zBias ) { float ratio = camera->width / camera->height; b2Vec2 extents = { camera->zoom * ratio, camera->zoom }; b2Vec2 lower = b2Sub( camera->center, extents ); b2Vec2 upper = b2Add( camera->center, extents ); float w = upper.x - lower.x; float h = upper.y - lower.y; m[0] = 2.0f / w; m[1] = 0.0f; m[2] = 0.0f; m[3] = 0.0f; m[4] = 0.0f; m[5] = 2.0f / h; m[6] = 0.0f; m[7] = 0.0f; m[8] = 0.0f; m[9] = 0.0f; m[10] = -1.0f; m[11] = 0.0f; m[12] = -2.0f * camera->center.x / w; m[13] = -2.0f * camera->center.y / h; m[14] = zBias; m[15] = 1.0f; } static void MakeOrthographicMatrix( float* m, float left, float right, float bottom, float top, float near, float far ) { m[0] = 2.0f / ( right - left ); m[1] = 0.0f; m[2] = 0.0f; m[3] = 0.0f; m[4] = 0.0f; m[5] = 2.0f / ( top - bottom ); m[6] = 0.0f; m[7] = 0.0f; m[8] = 0.0f; m[9] = 0.0f; m[10] = -2.0f / ( far - near ); m[11] = 0.0f; m[12] = -( right + left ) / ( right - left ); m[13] = -( top + bottom ) / ( top - bottom ); m[14] = -( far + near ) / ( far - near ); m[15] = 1.0f; } b2AABB GetViewBounds( Camera* camera ) { if ( camera->height == 0.0f || camera->width == 0.0f ) { b2AABB bounds = { .lowerBound = b2Vec2_zero, .upperBound = b2Vec2_zero }; return bounds; } b2AABB bounds; bounds.lowerBound = ConvertScreenToWorld( camera, (b2Vec2){ 0.0f, camera->height } ); bounds.upperBound = ConvertScreenToWorld( camera, (b2Vec2){ camera->width, 0.0f } ); return bounds; } typedef struct { b2Vec2 position; b2Vec2 uv; RGBA8 color; } FontVertex; ARRAY_DECLARE( FontVertex ); ARRAY_INLINE( FontVertex ); ARRAY_SOURCE( FontVertex ); #define FONT_FIRST_CHARACTER 32 #define FONT_CHARACTER_COUNT 96 #define FONT_ATLAS_WIDTH 512 #define FONT_ATLAS_HEIGHT 512 // The number of vertices the vbo can hold. Must be a multiple of 6. #define FONT_BATCH_SIZE ( 6 * 10000 ) typedef struct { float fontSize; FontVertexArray vertices; stbtt_bakedchar* characters; unsigned int textureId; uint32_t vaoId; uint32_t vboId; uint32_t programId; } Font; Font CreateFont( const char* trueTypeFile, float fontSize ) { Font font = { 0 }; FILE* file = fopen( trueTypeFile, "rb" ); if ( file == NULL ) { assert( false ); return font; } font.vertices = FontVertexArray_Create( FONT_BATCH_SIZE ); font.fontSize = fontSize; font.characters = malloc( FONT_CHARACTER_COUNT * sizeof( stbtt_bakedchar ) ); int fileBufferCapacity = 1 << 20; unsigned char* fileBuffer = (unsigned char*)malloc( fileBufferCapacity * sizeof( unsigned char ) ); fread( fileBuffer, 1, fileBufferCapacity, file ); int pw = FONT_ATLAS_WIDTH; int ph = FONT_ATLAS_HEIGHT; unsigned char* tempBitmap = (unsigned char*)malloc( pw * ph * sizeof( unsigned char ) ); stbtt_BakeFontBitmap( fileBuffer, 0, font.fontSize, tempBitmap, pw, ph, FONT_FIRST_CHARACTER, FONT_CHARACTER_COUNT, font.characters ); glGenTextures( 1, &font.textureId ); glBindTexture( GL_TEXTURE_2D, font.textureId ); glTexImage2D( GL_TEXTURE_2D, 0, GL_R8, pw, ph, 0, GL_RED, GL_UNSIGNED_BYTE, tempBitmap ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); // for debugging // stbi_write_png( "build/fontAtlas.png", pw, ph, 1, tempBitmap, pw ); fclose( file ); free( fileBuffer ); free( tempBitmap ); fileBuffer = NULL; tempBitmap = NULL; font.programId = CreateProgramFromFiles( "samples/data/font.vs", "samples/data/font.fs" ); if ( font.programId == 0 ) { return font; } // Setting up the VAO and VBO glGenBuffers( 1, &font.vboId ); glBindBuffer( GL_ARRAY_BUFFER, font.vboId ); glBufferData( GL_ARRAY_BUFFER, FONT_BATCH_SIZE * sizeof( FontVertex ), NULL, GL_DYNAMIC_DRAW ); glGenVertexArrays( 1, &font.vaoId ); glBindVertexArray( font.vaoId ); // position attribute glVertexAttribPointer( 0, 2, GL_FLOAT, GL_FALSE, sizeof( FontVertex ), (void*)offsetof( FontVertex, position ) ); glEnableVertexAttribArray( 0 ); // uv attribute glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, sizeof( FontVertex ), (void*)offsetof( FontVertex, uv ) ); glEnableVertexAttribArray( 1 ); // color attribute will be expanded to floats using normalization glVertexAttribPointer( 2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( FontVertex ), (void*)offsetof( FontVertex, color ) ); glEnableVertexAttribArray( 2 ); glBindVertexArray( 0 ); CheckOpenGL(); return font; } void DestroyFont( Font* font ) { if ( font->programId != 0 ) { glDeleteProgram( font->programId ); } glDeleteBuffers( 1, &font->vboId ); glDeleteVertexArrays( 1, &font->vaoId ); if ( font->textureId != 0 ) { glDeleteTextures( 1, &font->textureId ); } free( font->characters ); FontVertexArray_Destroy( &font->vertices ); } void AddText( Font* font, float x, float y, b2HexColor color, const char* text ) { if ( text == NULL ) { return; } b2Vec2 position = { x, y }; RGBA8 c = MakeRGBA8( color, 1.0f ); int pw = FONT_ATLAS_WIDTH; int ph = FONT_ATLAS_HEIGHT; int i = 0; while ( text[i] != 0 ) { int index = (int)text[i] - FONT_FIRST_CHARACTER; if ( 0 <= index && index < FONT_CHARACTER_COUNT ) { // 1=opengl stbtt_aligned_quad q; stbtt_GetBakedQuad( font->characters, pw, ph, index, &position.x, &position.y, &q, 1 ); FontVertex v1 = { { q.x0, q.y0 }, { q.s0, q.t0 }, c }; FontVertex v2 = { { q.x1, q.y0 }, { q.s1, q.t0 }, c }; FontVertex v3 = { { q.x1, q.y1 }, { q.s1, q.t1 }, c }; FontVertex v4 = { { q.x0, q.y1 }, { q.s0, q.t1 }, c }; FontVertexArray_Push( &font->vertices, v1 ); FontVertexArray_Push( &font->vertices, v3 ); FontVertexArray_Push( &font->vertices, v2 ); FontVertexArray_Push( &font->vertices, v1 ); FontVertexArray_Push( &font->vertices, v4 ); FontVertexArray_Push( &font->vertices, v3 ); } i += 1; } } void FlushText( Font* font, Camera* camera ) { float projectionMatrix[16]; MakeOrthographicMatrix( projectionMatrix, 0.0f, camera->width, camera->height, 0.0f, -1.0f, 1.0f ); glUseProgram( font->programId ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); int slot = 0; glActiveTexture( GL_TEXTURE0 + slot ); glBindTexture( GL_TEXTURE_2D, font->textureId ); glBindVertexArray( font->vaoId ); glBindBuffer( GL_ARRAY_BUFFER, font->vboId ); int textureUniform = glGetUniformLocation( font->programId, "FontAtlas" ); glUniform1i( textureUniform, slot ); int matrixUniform = glGetUniformLocation( font->programId, "ProjectionMatrix" ); glUniformMatrix4fv( matrixUniform, 1, GL_FALSE, projectionMatrix ); int totalVertexCount = font->vertices.count; int drawCallCount = ( totalVertexCount / FONT_BATCH_SIZE ) + 1; for ( int i = 0; i < drawCallCount; i++ ) { const FontVertex* data = font->vertices.data + i * FONT_BATCH_SIZE; int vertexCount; if ( i == drawCallCount - 1 ) { vertexCount = totalVertexCount % FONT_BATCH_SIZE; } else { vertexCount = FONT_BATCH_SIZE; } glBufferSubData( GL_ARRAY_BUFFER, 0, vertexCount * sizeof( FontVertex ), data ); glDrawArrays( GL_TRIANGLES, 0, vertexCount ); } glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); glBindTexture( GL_TEXTURE_2D, 0 ); glDisable( GL_BLEND ); CheckOpenGL(); font->vertices.count = 0; } typedef struct { GLuint vaoId; GLuint vboId; GLuint programId; GLint timeUniform; GLint resolutionUniform; GLint baseColorUniform; } Background; Background CreateBackground() { Background background = { 0 }; background.programId = CreateProgramFromFiles( "samples/data/background.vs", "samples/data/background.fs" ); background.timeUniform = glGetUniformLocation( background.programId, "time" ); background.resolutionUniform = glGetUniformLocation( background.programId, "resolution" ); background.baseColorUniform = glGetUniformLocation( background.programId, "baseColor" ); int vertexAttribute = 0; // Generate glGenVertexArrays( 1, &background.vaoId ); glGenBuffers( 1, &background.vboId ); glBindVertexArray( background.vaoId ); glEnableVertexAttribArray( vertexAttribute ); // Single quad b2Vec2 vertices[] = { { -1.0f, 1.0f }, { -1.0f, -1.0f }, { 1.0f, 1.0f }, { 1.0f, -1.0f } }; glBindBuffer( GL_ARRAY_BUFFER, background.vboId ); glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW ); glVertexAttribPointer( vertexAttribute, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET( 0 ) ); CheckOpenGL(); // Cleanup glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); return background; } void DestroyBackground( Background* background ) { if ( background->vaoId ) { glDeleteVertexArrays( 1, &background->vaoId ); glDeleteBuffers( 1, &background->vboId ); background->vaoId = 0; background->vboId = 0; } if ( background->programId ) { glDeleteProgram( background->programId ); background->programId = 0; } } void RenderBackground( Background* background, Camera* camera ) { glUseProgram( background->programId ); float time = (float)glfwGetTime(); time = fmodf( time, 100.0f ); glUniform1f( background->timeUniform, time ); glUniform2f( background->resolutionUniform, (float)camera->width, (float)camera->height ); // struct RGBA8 c8 = MakeRGBA8( b2_colorGray2, 1.0f ); // glUniform3f(baseColorUniform, c8.r/255.0f, c8.g/255.0f, c8.b/255.0f); glUniform3f( background->baseColorUniform, 0.2f, 0.2f, 0.2f ); glBindVertexArray( background->vaoId ); glBindBuffer( GL_ARRAY_BUFFER, background->vboId ); glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); glUseProgram( 0 ); } #define POINT_BATCH_SIZE 2048 typedef struct { b2Vec2 position; float size; RGBA8 rgba; } PointData; ARRAY_DECLARE( PointData ); ARRAY_INLINE( PointData ); ARRAY_SOURCE( PointData ); typedef struct { PointDataArray points; GLuint vaoId; GLuint vboId; GLuint programId; GLint projectionUniform; } PointRender; PointRender CreatePointDrawData() { PointRender render = { 0 }; render.points = PointDataArray_Create( POINT_BATCH_SIZE ); render.programId = CreateProgramFromFiles( "samples/data/point.vs", "samples/data/point.fs" ); render.projectionUniform = glGetUniformLocation( render.programId, "projectionMatrix" ); int vertexAttribute = 0; int sizeAttribute = 1; int colorAttribute = 2; // Generate glGenVertexArrays( 1, &render.vaoId ); glGenBuffers( 1, &render.vboId ); glBindVertexArray( render.vaoId ); glEnableVertexAttribArray( vertexAttribute ); glEnableVertexAttribArray( sizeAttribute ); glEnableVertexAttribArray( colorAttribute ); // Vertex buffer glBindBuffer( GL_ARRAY_BUFFER, render.vboId ); glBufferData( GL_ARRAY_BUFFER, POINT_BATCH_SIZE * sizeof( PointData ), NULL, GL_DYNAMIC_DRAW ); glVertexAttribPointer( vertexAttribute, 2, GL_FLOAT, GL_FALSE, sizeof( PointData ), (void*)offsetof( PointData, position ) ); glVertexAttribPointer( sizeAttribute, 1, GL_FLOAT, GL_FALSE, sizeof( PointData ), (void*)offsetof( PointData, size ) ); // save bandwidth by expanding color to floats in the shader glVertexAttribPointer( colorAttribute, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( PointData ), (void*)offsetof( PointData, rgba ) ); CheckOpenGL(); // Cleanup glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); return render; } void DestroyPointDrawData( PointRender* render ) { if ( render->vaoId ) { glDeleteVertexArrays( 1, &render->vaoId ); glDeleteBuffers( 1, &render->vboId ); } if ( render->programId ) { glDeleteProgram( render->programId ); } PointDataArray_Destroy( &render->points ); *render = (PointRender){ 0 }; } void AddPoint( PointRender* render, b2Vec2 v, float size, b2HexColor c ) { RGBA8 rgba = MakeRGBA8( c, 1.0f ); PointDataArray_Push( &render->points, (PointData){ v, size, rgba } ); } void FlushPoints( PointRender* render, Camera* camera ) { int count = render->points.count; if ( count == 0 ) { return; } glUseProgram( render->programId ); float proj[16] = { 0.0f }; BuildProjectionMatrix( camera, proj, 0.0f ); glUniformMatrix4fv( render->projectionUniform, 1, GL_FALSE, proj ); glBindVertexArray( render->vaoId ); glBindBuffer( GL_ARRAY_BUFFER, render->vboId ); glEnable( GL_PROGRAM_POINT_SIZE ); int base = 0; while ( count > 0 ) { int batchCount = b2MinInt( count, POINT_BATCH_SIZE ); glBufferSubData( GL_ARRAY_BUFFER, 0, batchCount * sizeof( PointData ), render->points.data + base ); glDrawArrays( GL_POINTS, 0, batchCount ); CheckOpenGL(); count -= POINT_BATCH_SIZE; base += POINT_BATCH_SIZE; } glDisable( GL_PROGRAM_POINT_SIZE ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); glUseProgram( 0 ); render->points.count = 0; } #define LINE_BATCH_SIZE ( 2 * 2048 ) typedef struct { b2Vec2 position; RGBA8 rgba; } VertexData; ARRAY_DECLARE( VertexData ); ARRAY_INLINE( VertexData ); ARRAY_SOURCE( VertexData ); typedef struct { VertexDataArray points; GLuint vaoId; GLuint vboId; GLuint programId; GLint projectionUniform; } LineRender; LineRender CreateLineRender() { LineRender render = { 0 }; render.points = VertexDataArray_Create( LINE_BATCH_SIZE ); render.programId = CreateProgramFromFiles( "samples/data/line.vs", "samples/data/line.fs" ); render.projectionUniform = glGetUniformLocation( render.programId, "projectionMatrix" ); int vertexAttribute = 0; int colorAttribute = 1; // Generate glGenVertexArrays( 1, &render.vaoId ); glGenBuffers( 1, &render.vboId ); glBindVertexArray( render.vaoId ); glEnableVertexAttribArray( vertexAttribute ); glEnableVertexAttribArray( colorAttribute ); // Vertex buffer glBindBuffer( GL_ARRAY_BUFFER, render.vboId ); glBufferData( GL_ARRAY_BUFFER, LINE_BATCH_SIZE * sizeof( VertexData ), NULL, GL_DYNAMIC_DRAW ); glVertexAttribPointer( vertexAttribute, 2, GL_FLOAT, GL_FALSE, sizeof( VertexData ), (void*)offsetof( VertexData, position ) ); // save bandwidth by expanding color to floats in the shader glVertexAttribPointer( colorAttribute, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( VertexData ), (void*)offsetof( VertexData, rgba ) ); CheckOpenGL(); // Cleanup glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); return render; } void DestroyLineRender( LineRender* render ) { if ( render->vaoId ) { glDeleteVertexArrays( 1, &render->vaoId ); glDeleteBuffers( 1, &render->vboId ); } if ( render->programId ) { glDeleteProgram( render->programId ); } VertexDataArray_Destroy( &render->points ); *render = (LineRender){ 0 }; } void AddLine( LineRender* render, b2Vec2 p1, b2Vec2 p2, b2HexColor c ) { RGBA8 rgba = MakeRGBA8( c, 1.0f ); VertexDataArray_Push( &render->points, (VertexData){ p1, rgba } ); VertexDataArray_Push( &render->points, (VertexData){ p2, rgba } ); } void FlushLines( LineRender* render, Camera* camera ) { int count = render->points.count; if ( count == 0 ) { return; } assert( count % 2 == 0 ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glUseProgram( render->programId ); float proj[16] = { 0 }; BuildProjectionMatrix( camera, proj, 0.1f ); glUniformMatrix4fv( render->projectionUniform, 1, GL_FALSE, proj ); glBindVertexArray( render->vaoId ); glBindBuffer( GL_ARRAY_BUFFER, render->vboId ); int base = 0; while ( count > 0 ) { int batchCount = b2MinInt( count, LINE_BATCH_SIZE ); glBufferSubData( GL_ARRAY_BUFFER, 0, batchCount * sizeof( VertexData ), render->points.data + base ); glDrawArrays( GL_LINES, 0, batchCount ); CheckOpenGL(); count -= LINE_BATCH_SIZE; base += LINE_BATCH_SIZE; } glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); glUseProgram( 0 ); glDisable( GL_BLEND ); render->points.count = 0; } #define CIRCLE_BATCH_SIZE 2048 typedef struct { b2Vec2 position; float radius; RGBA8 rgba; } CircleData; ARRAY_DECLARE( CircleData ); ARRAY_INLINE( CircleData ); ARRAY_SOURCE( CircleData ); typedef struct { CircleDataArray circles; GLuint vaoId; GLuint vboIds[2]; GLuint programId; GLint projectionUniform; GLint pixelScaleUniform; } CircleRender; CircleRender CreateCircles() { CircleRender render = { 0 }; render.circles = CircleDataArray_Create( CIRCLE_BATCH_SIZE ); render.programId = CreateProgramFromFiles( "samples/data/circle.vs", "samples/data/circle.fs" ); render.projectionUniform = glGetUniformLocation( render.programId, "projectionMatrix" ); render.pixelScaleUniform = glGetUniformLocation( render.programId, "pixelScale" ); int vertexAttribute = 0; int positionInstance = 1; int radiusInstance = 2; int colorInstance = 3; // Generate glGenVertexArrays( 1, &render.vaoId ); glGenBuffers( 2, render.vboIds ); glBindVertexArray( render.vaoId ); glEnableVertexAttribArray( vertexAttribute ); glEnableVertexAttribArray( positionInstance ); glEnableVertexAttribArray( radiusInstance ); glEnableVertexAttribArray( colorInstance ); // Vertex buffer for single quad float a = 1.1f; b2Vec2 vertices[] = { { -a, -a }, { a, -a }, { -a, a }, { a, -a }, { a, a }, { -a, a } }; glBindBuffer( GL_ARRAY_BUFFER, render.vboIds[0] ); glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW ); glVertexAttribPointer( vertexAttribute, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET( 0 ) ); // Circle buffer glBindBuffer( GL_ARRAY_BUFFER, render.vboIds[1] ); glBufferData( GL_ARRAY_BUFFER, CIRCLE_BATCH_SIZE * sizeof( CircleData ), NULL, GL_DYNAMIC_DRAW ); glVertexAttribPointer( positionInstance, 2, GL_FLOAT, GL_FALSE, sizeof( CircleData ), (void*)offsetof( CircleData, position ) ); glVertexAttribPointer( radiusInstance, 1, GL_FLOAT, GL_FALSE, sizeof( CircleData ), (void*)offsetof( CircleData, radius ) ); glVertexAttribPointer( colorInstance, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( CircleData ), (void*)offsetof( CircleData, rgba ) ); glVertexAttribDivisor( positionInstance, 1 ); glVertexAttribDivisor( radiusInstance, 1 ); glVertexAttribDivisor( colorInstance, 1 ); CheckOpenGL(); // Cleanup glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); return render; } void DestroyCircles( CircleRender* render ) { if ( render->vaoId ) { glDeleteVertexArrays( 1, &render->vaoId ); glDeleteBuffers( 2, render->vboIds ); } if ( render->programId ) { glDeleteProgram( render->programId ); } CircleDataArray_Destroy( &render->circles ); *render = (CircleRender){ 0 }; } void AddCircle( CircleRender* render, b2Vec2 center, float radius, b2HexColor color ) { RGBA8 rgba = MakeRGBA8( color, 1.0f ); CircleDataArray_Push( &render->circles, (CircleData){ center, radius, rgba } ); } void FlushCircles( CircleRender* render, Camera* camera ) { int count = render->circles.count; if ( count == 0 ) { return; } glUseProgram( render->programId ); float proj[16] = { 0.0f }; BuildProjectionMatrix( camera, proj, 0.2f ); glUniformMatrix4fv( render->projectionUniform, 1, GL_FALSE, proj ); glUniform1f( render->pixelScaleUniform, camera->height / camera->zoom ); glBindVertexArray( render->vaoId ); glBindBuffer( GL_ARRAY_BUFFER, render->vboIds[1] ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); int base = 0; while ( count > 0 ) { int batchCount = b2MinInt( count, CIRCLE_BATCH_SIZE ); glBufferSubData( GL_ARRAY_BUFFER, 0, batchCount * sizeof( CircleData ), render->circles.data + base ); glDrawArraysInstanced( GL_TRIANGLES, 0, 6, batchCount ); CheckOpenGL(); count -= CIRCLE_BATCH_SIZE; base += CIRCLE_BATCH_SIZE; } glDisable( GL_BLEND ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); glUseProgram( 0 ); render->circles.count = 0; } typedef struct { b2Transform transform; float radius; RGBA8 rgba; } SolidCircle; ARRAY_DECLARE( SolidCircle ); ARRAY_INLINE( SolidCircle ); ARRAY_SOURCE( SolidCircle ); #define SOLID_CIRCLE_BATCH_SIZE 2048 // Draws SDF circles using quad instancing. Apparently instancing of quads can be slow on older GPUs. // https://www.reddit.com/r/opengl/comments/q7yikr/how_to_draw_several_quads_through_instancing/ // https://www.g-truc.net/post-0666.html typedef struct { SolidCircleArray circles; GLuint vaoId; GLuint vboIds[2]; GLuint programId; GLint projectionUniform; GLint pixelScaleUniform; } SolidCircles; SolidCircles CreateSolidCircles() { SolidCircles render = { 0 }; render.circles = SolidCircleArray_Create( SOLID_CIRCLE_BATCH_SIZE ); render.programId = CreateProgramFromFiles( "samples/data/solid_circle.vs", "samples/data/solid_circle.fs" ); render.projectionUniform = glGetUniformLocation( render.programId, "projectionMatrix" ); render.pixelScaleUniform = glGetUniformLocation( render.programId, "pixelScale" ); // Generate glGenVertexArrays( 1, &render.vaoId ); glGenBuffers( 2, render.vboIds ); glBindVertexArray( render.vaoId ); int vertexAttribute = 0; int transformInstance = 1; int radiusInstance = 2; int colorInstance = 3; glEnableVertexAttribArray( vertexAttribute ); glEnableVertexAttribArray( transformInstance ); glEnableVertexAttribArray( radiusInstance ); glEnableVertexAttribArray( colorInstance ); // Vertex buffer for single quad float a = 1.1f; b2Vec2 vertices[] = { { -a, -a }, { a, -a }, { -a, a }, { a, -a }, { a, a }, { -a, a } }; glBindBuffer( GL_ARRAY_BUFFER, render.vboIds[0] ); glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW ); glVertexAttribPointer( vertexAttribute, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET( 0 ) ); // Circle buffer glBindBuffer( GL_ARRAY_BUFFER, render.vboIds[1] ); glBufferData( GL_ARRAY_BUFFER, SOLID_CIRCLE_BATCH_SIZE * sizeof( SolidCircle ), NULL, GL_DYNAMIC_DRAW ); glVertexAttribPointer( transformInstance, 4, GL_FLOAT, GL_FALSE, sizeof( SolidCircle ), (void*)offsetof( SolidCircle, transform ) ); glVertexAttribPointer( radiusInstance, 1, GL_FLOAT, GL_FALSE, sizeof( SolidCircle ), (void*)offsetof( SolidCircle, radius ) ); glVertexAttribPointer( colorInstance, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( SolidCircle ), (void*)offsetof( SolidCircle, rgba ) ); glVertexAttribDivisor( transformInstance, 1 ); glVertexAttribDivisor( radiusInstance, 1 ); glVertexAttribDivisor( colorInstance, 1 ); CheckOpenGL(); // Cleanup glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); return render; } void DestroySolidCircles( SolidCircles* render ) { if ( render->vaoId ) { glDeleteVertexArrays( 1, &render->vaoId ); glDeleteBuffers( 2, render->vboIds ); } if ( render->programId ) { glDeleteProgram( render->programId ); } SolidCircleArray_Destroy( &render->circles ); *render = (SolidCircles){ 0 }; } void AddSolidCircle( SolidCircles* render, b2Transform transform, float radius, b2HexColor color ) { RGBA8 rgba = MakeRGBA8( color, 1.0f ); SolidCircleArray_Push( &render->circles, (SolidCircle){ transform, radius, rgba } ); } void FlushSolidCircles( SolidCircles* render, Camera* camera ) { int count = render->circles.count; if ( count == 0 ) { return; } glUseProgram( render->programId ); float proj[16] = { 0.0f }; BuildProjectionMatrix( camera, proj, 0.2f ); glUniformMatrix4fv( render->projectionUniform, 1, GL_FALSE, proj ); glUniform1f( render->pixelScaleUniform, camera->height / camera->zoom ); glBindVertexArray( render->vaoId ); glBindBuffer( GL_ARRAY_BUFFER, render->vboIds[1] ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); int base = 0; while ( count > 0 ) { int batchCount = b2MinInt( count, SOLID_CIRCLE_BATCH_SIZE ); glBufferSubData( GL_ARRAY_BUFFER, 0, batchCount * sizeof( SolidCircle ), render->circles.data + base ); glDrawArraysInstanced( GL_TRIANGLES, 0, 6, batchCount ); CheckOpenGL(); count -= SOLID_CIRCLE_BATCH_SIZE; base += SOLID_CIRCLE_BATCH_SIZE; } glDisable( GL_BLEND ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); glUseProgram( 0 ); render->circles.count = 0; } typedef struct { b2Transform transform; float radius; float length; RGBA8 rgba; } Capsule; ARRAY_DECLARE( Capsule ); ARRAY_INLINE( Capsule ); ARRAY_SOURCE( Capsule ); #define CAPSULE_BATCH_SIZE 2048 // Draw capsules using SDF-based shader typedef struct { CapsuleArray capsules; GLuint vaoId; GLuint vboIds[2]; GLuint programId; GLint projectionUniform; GLint pixelScaleUniform; } Capsules; Capsules CreateCapsules() { Capsules render = { 0 }; render.capsules = CapsuleArray_Create( CAPSULE_BATCH_SIZE ); render.programId = CreateProgramFromFiles( "samples/data/solid_capsule.vs", "samples/data/solid_capsule.fs" ); render.projectionUniform = glGetUniformLocation( render.programId, "projectionMatrix" ); render.pixelScaleUniform = glGetUniformLocation( render.programId, "pixelScale" ); int vertexAttribute = 0; int transformInstance = 1; int radiusInstance = 2; int lengthInstance = 3; int colorInstance = 4; // Generate glGenVertexArrays( 1, &render.vaoId ); glGenBuffers( 2, render.vboIds ); glBindVertexArray( render.vaoId ); glEnableVertexAttribArray( vertexAttribute ); glEnableVertexAttribArray( transformInstance ); glEnableVertexAttribArray( radiusInstance ); glEnableVertexAttribArray( lengthInstance ); glEnableVertexAttribArray( colorInstance ); // Vertex buffer for single quad float a = 1.1f; b2Vec2 vertices[] = { { -a, -a }, { a, -a }, { -a, a }, { a, -a }, { a, a }, { -a, a } }; glBindBuffer( GL_ARRAY_BUFFER, render.vboIds[0] ); glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW ); glVertexAttribPointer( vertexAttribute, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET( 0 ) ); // Capsule buffer glBindBuffer( GL_ARRAY_BUFFER, render.vboIds[1] ); glBufferData( GL_ARRAY_BUFFER, CAPSULE_BATCH_SIZE * sizeof( Capsule ), NULL, GL_DYNAMIC_DRAW ); glVertexAttribPointer( transformInstance, 4, GL_FLOAT, GL_FALSE, sizeof( Capsule ), (void*)offsetof( Capsule, transform ) ); glVertexAttribPointer( radiusInstance, 1, GL_FLOAT, GL_FALSE, sizeof( Capsule ), (void*)offsetof( Capsule, radius ) ); glVertexAttribPointer( lengthInstance, 1, GL_FLOAT, GL_FALSE, sizeof( Capsule ), (void*)offsetof( Capsule, length ) ); glVertexAttribPointer( colorInstance, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( Capsule ), (void*)offsetof( Capsule, rgba ) ); glVertexAttribDivisor( transformInstance, 1 ); glVertexAttribDivisor( radiusInstance, 1 ); glVertexAttribDivisor( lengthInstance, 1 ); glVertexAttribDivisor( colorInstance, 1 ); CheckOpenGL(); // Cleanup glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); return render; } void DestroyCapsules( Capsules* render ) { if ( render->vaoId ) { glDeleteVertexArrays( 1, &render->vaoId ); glDeleteBuffers( 2, render->vboIds ); } if ( render->programId ) { glDeleteProgram( render->programId ); } CapsuleArray_Destroy( &render->capsules ); *render = (Capsules){ 0 }; } void AddCapsule( Capsules* render, b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor c ) { b2Vec2 d = b2Sub( p2, p1 ); float length = b2Length( d ); if ( length < 0.001f ) { printf( "WARNING: sample app: capsule too short!\n" ); return; } b2Vec2 axis = { d.x / length, d.y / length }; b2Transform transform; transform.p = b2Lerp( p1, p2, 0.5f ); transform.q.c = axis.x; transform.q.s = axis.y; RGBA8 rgba = MakeRGBA8( c, 1.0f ); CapsuleArray_Push( &render->capsules, (Capsule){ transform, radius, length, rgba } ); } void FlushCapsules( Capsules* render, Camera* camera ) { int count = render->capsules.count; if ( count == 0 ) { return; } glUseProgram( render->programId ); float proj[16] = { 0.0f }; BuildProjectionMatrix( camera, proj, 0.2f ); glUniformMatrix4fv( render->projectionUniform, 1, GL_FALSE, proj ); glUniform1f( render->pixelScaleUniform, camera->height / camera->zoom ); glBindVertexArray( render->vaoId ); glBindBuffer( GL_ARRAY_BUFFER, render->vboIds[1] ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); int base = 0; while ( count > 0 ) { int batchCount = b2MinInt( count, CAPSULE_BATCH_SIZE ); glBufferSubData( GL_ARRAY_BUFFER, 0, batchCount * sizeof( Capsule ), render->capsules.data + base ); glDrawArraysInstanced( GL_TRIANGLES, 0, 6, batchCount ); CheckOpenGL(); count -= CAPSULE_BATCH_SIZE; base += CAPSULE_BATCH_SIZE; } glDisable( GL_BLEND ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); glUseProgram( 0 ); render->capsules.count = 0; } typedef struct { b2Transform transform; b2Vec2 p1, p2, p3, p4, p5, p6, p7, p8; int count; float radius; // keep color small RGBA8 color; } Polygon; ARRAY_DECLARE( Polygon ); ARRAY_INLINE( Polygon ); ARRAY_SOURCE( Polygon ); #define POLYGON_BATCH_SIZE 2048 // Rounded and non-rounded convex polygons using an SDF-based shader. typedef struct { PolygonArray polygons; GLuint vaoId; GLuint vboIds[2]; GLuint programId; GLint projectionUniform; GLint pixelScaleUniform; } Polygons; Polygons CreatePolygons() { Polygons render = { 0 }; render.polygons = PolygonArray_Create( POLYGON_BATCH_SIZE ); render.programId = CreateProgramFromFiles( "samples/data/solid_polygon.vs", "samples/data/solid_polygon.fs" ); render.projectionUniform = glGetUniformLocation( render.programId, "projectionMatrix" ); render.pixelScaleUniform = glGetUniformLocation( render.programId, "pixelScale" ); int vertexAttribute = 0; int instanceTransform = 1; int instancePoint12 = 2; int instancePoint34 = 3; int instancePoint56 = 4; int instancePoint78 = 5; int instancePointCount = 6; int instanceRadius = 7; int instanceColor = 8; // Generate glGenVertexArrays( 1, &render.vaoId ); glGenBuffers( 2, render.vboIds ); glBindVertexArray( render.vaoId ); glEnableVertexAttribArray( vertexAttribute ); glEnableVertexAttribArray( instanceTransform ); glEnableVertexAttribArray( instancePoint12 ); glEnableVertexAttribArray( instancePoint34 ); glEnableVertexAttribArray( instancePoint56 ); glEnableVertexAttribArray( instancePoint78 ); glEnableVertexAttribArray( instancePointCount ); glEnableVertexAttribArray( instanceRadius ); glEnableVertexAttribArray( instanceColor ); // Vertex buffer for single quad float a = 1.1f; b2Vec2 vertices[] = { { -a, -a }, { a, -a }, { -a, a }, { a, -a }, { a, a }, { -a, a } }; glBindBuffer( GL_ARRAY_BUFFER, render.vboIds[0] ); glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW ); glVertexAttribPointer( vertexAttribute, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET( 0 ) ); // Polygon buffer glBindBuffer( GL_ARRAY_BUFFER, render.vboIds[1] ); glBufferData( GL_ARRAY_BUFFER, POLYGON_BATCH_SIZE * sizeof( Polygon ), NULL, GL_DYNAMIC_DRAW ); glVertexAttribPointer( instanceTransform, 4, GL_FLOAT, GL_FALSE, sizeof( Polygon ), (void*)offsetof( Polygon, transform ) ); glVertexAttribPointer( instancePoint12, 4, GL_FLOAT, GL_FALSE, sizeof( Polygon ), (void*)offsetof( Polygon, p1 ) ); glVertexAttribPointer( instancePoint34, 4, GL_FLOAT, GL_FALSE, sizeof( Polygon ), (void*)offsetof( Polygon, p3 ) ); glVertexAttribPointer( instancePoint56, 4, GL_FLOAT, GL_FALSE, sizeof( Polygon ), (void*)offsetof( Polygon, p5 ) ); glVertexAttribPointer( instancePoint78, 4, GL_FLOAT, GL_FALSE, sizeof( Polygon ), (void*)offsetof( Polygon, p7 ) ); glVertexAttribIPointer( instancePointCount, 1, GL_INT, sizeof( Polygon ), (void*)offsetof( Polygon, count ) ); glVertexAttribPointer( instanceRadius, 1, GL_FLOAT, GL_FALSE, sizeof( Polygon ), (void*)offsetof( Polygon, radius ) ); // color will get automatically expanded to floats in the shader glVertexAttribPointer( instanceColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( Polygon ), (void*)offsetof( Polygon, color ) ); // These divisors tell glsl how to distribute per instance data glVertexAttribDivisor( instanceTransform, 1 ); glVertexAttribDivisor( instancePoint12, 1 ); glVertexAttribDivisor( instancePoint34, 1 ); glVertexAttribDivisor( instancePoint56, 1 ); glVertexAttribDivisor( instancePoint78, 1 ); glVertexAttribDivisor( instancePointCount, 1 ); glVertexAttribDivisor( instanceRadius, 1 ); glVertexAttribDivisor( instanceColor, 1 ); CheckOpenGL(); // Cleanup glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); return render; } void DestroyPolygons( Polygons* render ) { if ( render->vaoId ) { glDeleteVertexArrays( 1, &render->vaoId ); glDeleteBuffers( 2, render->vboIds ); } if ( render->programId ) { glDeleteProgram( render->programId ); } PolygonArray_Destroy( &render->polygons ); *render = (Polygons){ 0 }; } void AddPolygon( Polygons* render, b2Transform transform, const b2Vec2* points, int count, float radius, b2HexColor color ) { Polygon data = {}; data.transform = transform; int n = count < 8 ? count : 8; b2Vec2* ps = &data.p1; for ( int i = 0; i < n; ++i ) { ps[i] = points[i]; } data.count = n; data.radius = radius; data.color = MakeRGBA8( color, 1.0f ); PolygonArray_Push( &render->polygons, data ); } void FlushPolygons( Polygons* render, Camera* camera ) { int count = render->polygons.count; if ( count == 0 ) { return; } glUseProgram( render->programId ); float proj[16] = { 0.0f }; BuildProjectionMatrix( camera, proj, 0.2f ); glUniformMatrix4fv( render->projectionUniform, 1, GL_FALSE, proj ); glUniform1f( render->pixelScaleUniform, camera->height / camera->zoom ); glBindVertexArray( render->vaoId ); glBindBuffer( GL_ARRAY_BUFFER, render->vboIds[1] ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); int base = 0; while ( count > 0 ) { int batchCount = b2MinInt( count, POLYGON_BATCH_SIZE ); glBufferSubData( GL_ARRAY_BUFFER, 0, batchCount * sizeof( Polygon ), render->polygons.data + base ); glDrawArraysInstanced( GL_TRIANGLES, 0, 6, batchCount ); CheckOpenGL(); count -= POLYGON_BATCH_SIZE; base += POLYGON_BATCH_SIZE; } glDisable( GL_BLEND ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); glUseProgram( 0 ); render->polygons.count = 0; } typedef struct Draw { Background background; PointRender points; LineRender lines; CircleRender hollowCircles; SolidCircles circles; Capsules capsules; Polygons polygons; Font font; } Draw; Draw* CreateDraw( void ) { Draw* draw = malloc( sizeof( Draw ) ); *draw = (Draw){ 0 }; draw->background = CreateBackground(); draw->points = CreatePointDrawData(); draw->lines = CreateLineRender(); draw->hollowCircles = CreateCircles(); draw->circles = CreateSolidCircles(); draw->capsules = CreateCapsules(); draw->polygons = CreatePolygons(); draw->font = CreateFont( "samples/data/droid_sans.ttf", 18.0f ); return draw; } void DestroyDraw( Draw* draw ) { DestroyBackground( &draw->background ); DestroyPointDrawData( &draw->points ); DestroyLineRender( &draw->lines ); DestroyCircles( &draw->hollowCircles ); DestroySolidCircles( &draw->circles ); DestroyCapsules( &draw->capsules ); DestroyPolygons( &draw->polygons ); DestroyFont( &draw->font ); free( draw ); } void DrawPoint( Draw* draw, b2Vec2 p, float size, b2HexColor color ) { AddPoint( &draw->points, p, size, color ); } void DrawLine( Draw* draw, b2Vec2 p1, b2Vec2 p2, b2HexColor color ) { AddLine( &draw->lines, p1, p2, color ); } void DrawCircle( Draw* draw, b2Vec2 center, float radius, b2HexColor color ) { AddCircle( &draw->hollowCircles, center, radius, color ); } void DrawSolidCircle( Draw* draw, b2Transform transform, float radius, b2HexColor color ) { AddSolidCircle( &draw->circles, transform, radius, color ); } void DrawSolidCapsule( Draw* draw, b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color ) { AddCapsule( &draw->capsules, p1, p2, radius, color ); } void DrawPolygon( Draw* draw, const b2Vec2* vertices, int vertexCount, b2HexColor color ) { b2Vec2 p1 = vertices[vertexCount - 1]; for ( int i = 0; i < vertexCount; ++i ) { b2Vec2 p2 = vertices[i]; AddLine( &draw->lines, p1, p2, color ); p1 = p2; } } void DrawSolidPolygon( Draw* draw, b2Transform transform, const b2Vec2* vertices, int vertexCount, float radius, b2HexColor color ) { AddPolygon( &draw->polygons, transform, vertices, vertexCount, radius, color ); } void DrawTransform( Draw* draw, b2Transform transform, float scale ) { b2Vec2 p1 = transform.p; b2Vec2 p2 = b2MulAdd( p1, scale, b2Rot_GetXAxis( transform.q ) ); AddLine( &draw->lines, p1, p2, b2_colorRed ); p2 = b2MulAdd( p1, scale, b2Rot_GetYAxis( transform.q ) ); AddLine( &draw->lines, p1, p2, b2_colorGreen ); } void DrawBounds( Draw* draw, b2AABB aabb, b2HexColor color ) { b2Vec2 p1 = aabb.lowerBound; b2Vec2 p2 = { aabb.upperBound.x, aabb.lowerBound.y }; b2Vec2 p3 = aabb.upperBound; b2Vec2 p4 = { aabb.lowerBound.x, aabb.upperBound.y }; AddLine( &draw->lines, p1, p2, color ); AddLine( &draw->lines, p2, p3, color ); AddLine( &draw->lines, p3, p4, color ); AddLine( &draw->lines, p4, p1, color ); } void DrawScreenString( Draw* draw, float x, float y, b2HexColor color, const char* string, ... ) { char buffer[256]; va_list arg; va_start( arg, string ); vsnprintf( buffer, 256, string, arg ); va_end( arg ); buffer[255] = 0; AddText( &draw->font, x, y, color, buffer ); } void DrawWorldString( Draw* draw, Camera* camera, b2Vec2 p, b2HexColor color, const char* string, ... ) { b2Vec2 ps = ConvertWorldToScreen( camera, p ); char buffer[256]; va_list arg; va_start( arg, string ); vsnprintf( buffer, 256, string, arg ); va_end( arg ); buffer[255] = 0; AddText( &draw->font, ps.x, ps.y, color, buffer ); } void FlushDraw( Draw* draw, Camera* camera ) { // order matters FlushSolidCircles( &draw->circles, camera ); FlushCapsules( &draw->capsules, camera ); FlushPolygons( &draw->polygons, camera ); FlushCircles( &draw->hollowCircles, camera ); FlushLines( &draw->lines, camera ); FlushPoints( &draw->points, camera ); FlushText( &draw->font, camera ); CheckOpenGL(); } void DrawBackground( Draw* draw, Camera* camera ) { RenderBackground( &draw->background, camera ); } ================================================ FILE: samples/draw.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "box2d/types.h" typedef struct Camera { b2Vec2 center; float zoom; float width; float height; } Camera; typedef struct Draw Draw; #ifdef __cplusplus extern "C" { #endif Camera GetDefaultCamera( void ); void ResetView( Camera* camera ); b2Vec2 ConvertScreenToWorld( Camera* camera, b2Vec2 screenPoint ); b2Vec2 ConvertWorldToScreen( Camera* camera, b2Vec2 worldPoint ); b2AABB GetViewBounds( Camera* camera ); Draw* CreateDraw( void ); void DestroyDraw( Draw* draw ); void DrawPoint( Draw* draw, b2Vec2 p, float size, b2HexColor color ); void DrawLine( Draw* draw, b2Vec2 p1, b2Vec2 p2, b2HexColor color ); void DrawCircle( Draw* draw, b2Vec2 center, float radius, b2HexColor color ); void DrawSolidCircle( Draw* draw, b2Transform transform, float radius, b2HexColor color ); void DrawSolidCapsule( Draw* draw, b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color ); void DrawPolygon( Draw* draw, const b2Vec2* vertices, int vertexCount, b2HexColor color ); void DrawSolidPolygon( Draw* draw, b2Transform transform, const b2Vec2* vertices, int vertexCount, float radius, b2HexColor color ); void DrawTransform( Draw* draw, b2Transform transform, float scale ); void DrawBounds( Draw* draw, b2AABB aabb, b2HexColor color ); void DrawScreenString( Draw* draw, float x, float y, b2HexColor color, const char* string, ... ); void DrawWorldString( Draw* draw, Camera* camera, b2Vec2 p, b2HexColor color, const char* string, ... ); void FlushDraw( Draw* draw, Camera* camera ); void DrawBackground( Draw* draw, Camera* camera ); #ifdef __cplusplus } #endif ================================================ FILE: samples/main.cpp ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #if defined( _MSC_VER ) #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif #define _CRTDBG_MAP_ALLOC #endif #define IMGUI_DISABLE_OBSOLETE_FUNCTIONS 1 #include "TaskScheduler.h" #include "draw.h" #include "sample.h" #include "box2d/base.h" #include "box2d/box2d.h" #include "box2d/math_functions.h" // clang-format off #include "glad/glad.h" #include "GLFW/glfw3.h" // clang-format on #include "imgui.h" #include "imgui_impl_glfw.h" #include "imgui_impl_opengl3.h" #include #include #ifdef BOX2D_PROFILE #include #else #define FrameMark #endif #if defined( _MSC_VER ) && 0 #include static int MyAllocHook( int allocType, void* userData, size_t size, int blockType, long requestNumber, const unsigned char* filename, int lineNumber ) { // This hook can help find leaks if ( size == 143 ) { size += 0; } return 1; } #endif static SampleContext s_context; static int32_t s_selection = 0; static Sample* s_sample = nullptr; static bool s_rightMouseDown = false; static b2Vec2 s_clickPointWS = b2Vec2_zero; static float s_framebufferScale = 1.0f; inline bool IsPowerOfTwo( int32_t x ) { return ( x != 0 ) && ( ( x & ( x - 1 ) ) == 0 ); } void* AllocFcn( unsigned int size, int32_t alignment ) { // Allocation must be a multiple of alignment or risk a seg fault // https://en.cppreference.com/w/c/memory/aligned_alloc assert( IsPowerOfTwo( alignment ) ); size_t sizeAligned = ( ( size - 1 ) | ( alignment - 1 ) ) + 1; assert( ( sizeAligned & ( alignment - 1 ) ) == 0 ); #if defined( _MSC_VER ) || defined( __MINGW32__ ) || defined( __MINGW64__ ) void* ptr = _aligned_malloc( sizeAligned, alignment ); #else void* ptr = aligned_alloc( alignment, sizeAligned ); #endif assert( ptr != nullptr ); return ptr; } void FreeFcn( void* mem, unsigned int size ) { (void)size; #if defined( _MSC_VER ) || defined( __MINGW32__ ) || defined( __MINGW64__ ) _aligned_free( mem ); #else free( mem ); #endif } int AssertFcn( const char* condition, const char* fileName, int lineNumber ) { printf( "SAMPLE ASSERTION: %s, %s, line %d\n", condition, fileName, lineNumber ); return 1; } void glfwErrorCallback( int error, const char* description ) { fprintf( stderr, "GLFW error occurred. Code: %d. Description: %s\n", error, description ); } static int CompareSamples( const void* a, const void* b ) { SampleEntry* sa = (SampleEntry*)a; SampleEntry* sb = (SampleEntry*)b; int result = strcmp( sa->category, sb->category ); if ( result == 0 ) { result = strcmp( sa->name, sb->name ); } return result; } static void SortSamples() { qsort( g_sampleEntries, g_sampleCount, sizeof( SampleEntry ), CompareSamples ); } static void RestartSample() { delete s_sample; s_sample = nullptr; s_context.restart = true; s_sample = g_sampleEntries[s_context.sampleIndex].createFcn( &s_context ); s_context.restart = false; } static void CreateUI( GLFWwindow* window, const char* glslVersion ) { IMGUI_CHECKVERSION(); ImGui::CreateContext(); bool success = ImGui_ImplGlfw_InitForOpenGL( window, false ); if ( success == false ) { printf( "ImGui_ImplGlfw_InitForOpenGL failed\n" ); assert( false ); } success = ImGui_ImplOpenGL3_Init( glslVersion ); if ( success == false ) { printf( "ImGui_ImplOpenGL3_Init failed\n" ); assert( false ); } ImGui::GetStyle().ScaleAllSizes( s_context.uiScale ); const char* fontPath = "samples/data/droid_sans.ttf"; FILE* file = fopen( fontPath, "rb" ); if ( file != nullptr ) { ImFontConfig fontConfig; fontConfig.RasterizerMultiply = s_context.uiScale * s_framebufferScale; float regularSize = floorf( 13.0f * s_context.uiScale ); float mediumSize = floorf( 40.0f * s_context.uiScale ); float largeSize = floorf( 64.0f * s_context.uiScale ); ImGuiIO& io = ImGui::GetIO(); s_context.regularFont = io.Fonts->AddFontFromFileTTF( fontPath, regularSize, &fontConfig ); s_context.mediumFont = io.Fonts->AddFontFromFileTTF( fontPath, mediumSize, &fontConfig ); s_context.largeFont = io.Fonts->AddFontFromFileTTF( fontPath, largeSize, &fontConfig ); ImGui::GetIO().FontDefault = s_context.regularFont; } else { printf( "\n\nERROR: the Box2D samples working directory must be the top level Box2D directory (same as README.md)\n\n" ); exit( EXIT_FAILURE ); } } static void DestroyUI() { ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); } static void ResizeWindowCallback( GLFWwindow*, int width, int height ) { s_context.camera.width = float( width ); s_context.camera.height = float( height ); } static void KeyCallback( GLFWwindow* window, int key, int scancode, int action, int mods ) { ImGui_ImplGlfw_KeyCallback( window, key, scancode, action, mods ); if ( ImGui::GetIO().WantCaptureKeyboard ) { return; } if ( action == GLFW_PRESS ) { switch ( key ) { case GLFW_KEY_ESCAPE: // Quit glfwSetWindowShouldClose( s_context.window, GL_TRUE ); break; case GLFW_KEY_LEFT: // Pan left if ( mods == GLFW_MOD_CONTROL ) { b2Vec2 newOrigin = { 2.0f, 0.0f }; s_sample->ShiftOrigin( newOrigin ); } else { s_context.camera.center.x -= 0.5f; } break; case GLFW_KEY_RIGHT: // Pan right if ( mods == GLFW_MOD_CONTROL ) { b2Vec2 newOrigin = { -2.0f, 0.0f }; s_sample->ShiftOrigin( newOrigin ); } else { s_context.camera.center.x += 0.5f; } break; case GLFW_KEY_DOWN: // Pan down if ( mods == GLFW_MOD_CONTROL ) { b2Vec2 newOrigin = { 0.0f, 2.0f }; s_sample->ShiftOrigin( newOrigin ); } else { s_context.camera.center.y -= 0.5f; } break; case GLFW_KEY_UP: // Pan up if ( mods == GLFW_MOD_CONTROL ) { b2Vec2 newOrigin = { 0.0f, -2.0f }; s_sample->ShiftOrigin( newOrigin ); } else { s_context.camera.center.y += 0.5f; } break; case GLFW_KEY_HOME: ResetView( &s_context.camera ); break; case GLFW_KEY_R: RestartSample(); break; case GLFW_KEY_O: s_context.singleStep = true; break; case GLFW_KEY_P: s_context.pause = !s_context.pause; break; case GLFW_KEY_LEFT_BRACKET: // Switch to previous test --s_selection; if ( s_selection < 0 ) { s_selection = g_sampleCount - 1; } break; case GLFW_KEY_RIGHT_BRACKET: // Switch to next test ++s_selection; if ( s_selection == g_sampleCount ) { s_selection = 0; } break; case GLFW_KEY_TAB: s_context.showUI = !s_context.showUI; break; default: if ( s_sample ) { s_sample->Keyboard( key ); } } } } static void CharCallback( GLFWwindow* window, unsigned int c ) { ImGui_ImplGlfw_CharCallback( window, c ); } static void MouseButtonCallback( GLFWwindow* window, int button, int action, int modifiers ) { ImGui_ImplGlfw_MouseButtonCallback( window, button, action, modifiers ); if ( ImGui::GetIO().WantCaptureMouse ) { return; } double xd, yd; glfwGetCursorPos( window, &xd, &yd ); b2Vec2 ps = { float( xd ), float( yd ) }; // Use the mouse to move things around. if ( button == GLFW_MOUSE_BUTTON_1 ) { b2Vec2 pw = ConvertScreenToWorld( &s_context.camera, ps ); if ( action == GLFW_PRESS ) { s_sample->MouseDown( pw, button, modifiers ); } if ( action == GLFW_RELEASE ) { s_sample->MouseUp( pw, button ); } } else if ( button == GLFW_MOUSE_BUTTON_2 ) { if ( action == GLFW_PRESS ) { s_clickPointWS = ConvertScreenToWorld( &s_context.camera, ps ); s_rightMouseDown = true; } if ( action == GLFW_RELEASE ) { s_rightMouseDown = false; } } } static void MouseMotionCallback( GLFWwindow* window, double xd, double yd ) { b2Vec2 ps = { float( xd ), float( yd ) }; ImGui_ImplGlfw_CursorPosCallback( window, ps.x, ps.y ); b2Vec2 pw = ConvertScreenToWorld( &s_context.camera, ps ); s_sample->MouseMove( pw ); if ( s_rightMouseDown ) { b2Vec2 diff = b2Sub( pw, s_clickPointWS ); s_context.camera.center.x -= diff.x; s_context.camera.center.y -= diff.y; s_clickPointWS = ConvertScreenToWorld( &s_context.camera, ps ); } } static void ScrollCallback( GLFWwindow* window, double dx, double dy ) { ImGui_ImplGlfw_ScrollCallback( window, dx, dy ); if ( ImGui::GetIO().WantCaptureMouse ) { return; } if ( dy > 0 ) { s_context.camera.zoom /= 1.1f; } else { s_context.camera.zoom *= 1.1f; } } static void UpdateUI() { int maxWorkers = enki::GetNumHardwareThreads(); float fontSize = ImGui::GetFontSize(); float menuWidth = 13.0f * fontSize; if ( s_context.showUI ) { ImGui::SetNextWindowPos( { s_context.camera.width - menuWidth - 0.5f * fontSize, 0.5f * fontSize } ); ImGui::SetNextWindowSize( { menuWidth, s_context.camera.height - fontSize } ); ImGui::Begin( "Tools", &s_context.showUI, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse ); if ( ImGui::BeginTabBar( "ControlTabs", ImGuiTabBarFlags_None ) ) { if ( ImGui::BeginTabItem( "Controls" ) ) { ImGui::PushItemWidth( 100.0f ); ImGui::SliderInt( "Sub-steps", &s_context.subStepCount, 1, 32 ); ImGui::SliderFloat( "Hertz", &s_context.hertz, 5.0f, 240.0f, "%.0f hz" ); if ( ImGui::SliderInt( "Workers", &s_context.workerCount, 1, maxWorkers ) ) { s_context.workerCount = b2ClampInt( s_context.workerCount, 1, maxWorkers ); RestartSample(); } ImGui::PopItemWidth(); ImGui::Separator(); ImGui::Checkbox( "Sleep", &s_context.enableSleep ); ImGui::Checkbox( "Warm Starting", &s_context.enableWarmStarting ); ImGui::Checkbox( "Continuous", &s_context.enableContinuous ); ImGui::Separator(); ImGui::Checkbox( "Shapes", &s_context.debugDraw.drawShapes ); ImGui::Checkbox( "Joints", &s_context.debugDraw.drawJoints ); ImGui::Checkbox( "Joint Extras", &s_context.debugDraw.drawJointExtras ); ImGui::Checkbox( "Bounds", &s_context.debugDraw.drawBounds ); ImGui::Checkbox( "Contact Points", &s_context.debugDraw.drawContactPoints ); ImGui::Checkbox( "Contact Normals", &s_context.debugDraw.drawContactNormals ); ImGui::Checkbox( "Contact Features", &s_context.debugDraw.drawContactFeatures ); ImGui::Checkbox( "Contact Forces", &s_context.debugDraw.drawContactForces ); ImGui::Checkbox( "Friction Forces", &s_context.debugDraw.drawFrictionForces ); ImGui::Checkbox( "Mass", &s_context.debugDraw.drawMass ); ImGui::Checkbox( "Body Names", &s_context.debugDraw.drawBodyNames ); ImGui::Checkbox( "Graph Colors", &s_context.debugDraw.drawGraphColors ); ImGui::Checkbox( "Islands", &s_context.debugDraw.drawIslands ); ImGui::Checkbox( "Counters", &s_context.drawCounters ); ImGui::Checkbox( "Profile", &s_context.drawProfile ); ImGui::PushItemWidth( 80.0f ); ImGui::InputFloat( "Joint Scale", &s_context.debugDraw.jointScale ); ImGui::InputFloat( "Force Scale", &s_context.debugDraw.forceScale ); ImGui::PopItemWidth(); ImVec2 button_sz = ImVec2( -1, 0 ); if ( ImGui::Button( "Pause (P)", button_sz ) ) { s_context.pause = !s_context.pause; } if ( ImGui::Button( "Single Step (O)", button_sz ) ) { s_context.singleStep = !s_context.singleStep; } if ( ImGui::Button( "Dump Mem Stats", button_sz ) ) { b2World_DumpMemoryStats( s_sample->m_worldId ); } if ( ImGui::Button( "Reset Profile", button_sz ) ) { s_sample->ResetProfile(); } if ( ImGui::Button( "Restart (R)", button_sz ) ) { RestartSample(); } if ( ImGui::Button( "Quit", button_sz ) ) { glfwSetWindowShouldClose( s_context.window, GL_TRUE ); } ImGui::EndTabItem(); } ImGuiTreeNodeFlags leafNodeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; leafNodeFlags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; if ( ImGui::BeginTabItem( "Samples" ) ) { int categoryIndex = 0; const char* category = g_sampleEntries[categoryIndex].category; int i = 0; while ( i < g_sampleCount ) { bool categorySelected = strcmp( category, g_sampleEntries[s_context.sampleIndex].category ) == 0; ImGuiTreeNodeFlags nodeSelectionFlags = categorySelected ? ImGuiTreeNodeFlags_Selected : 0; bool nodeOpen = ImGui::TreeNodeEx( category, nodeFlags | nodeSelectionFlags ); if ( nodeOpen ) { while ( i < g_sampleCount && strcmp( category, g_sampleEntries[i].category ) == 0 ) { ImGuiTreeNodeFlags selectionFlags = 0; if ( s_context.sampleIndex == i ) { selectionFlags = ImGuiTreeNodeFlags_Selected; } ImGui::TreeNodeEx( (void*)(intptr_t)i, leafNodeFlags | selectionFlags, "%s", g_sampleEntries[i].name ); if ( ImGui::IsItemClicked() ) { s_selection = i; } ++i; } ImGui::TreePop(); } else { while ( i < g_sampleCount && strcmp( category, g_sampleEntries[i].category ) == 0 ) { ++i; } } if ( i < g_sampleCount ) { category = g_sampleEntries[i].category; categoryIndex = i; } } ImGui::EndTabItem(); } ImGui::EndTabBar(); } ImGui::End(); s_sample->UpdateGui(); } } int main( int, char** ) { #if defined( _MSC_VER ) // Enable memory-leak reports _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT ); //_CrtSetAllocHook(MyAllocHook); // How to break at the leaking allocation, in the watch window enter this variable // and set it to the allocation number in {}. Do this at the first line in main. // {,,ucrtbased.dll}_crtBreakAlloc = #endif // Install memory hooks b2SetAllocator( AllocFcn, FreeFcn ); b2SetAssertFcn( AssertFcn ); char buffer[128]; s_context.Load(); s_context.workerCount = b2MinInt( 8, (int)enki::GetNumHardwareThreads() / 2 ); SortSamples(); glfwSetErrorCallback( glfwErrorCallback ); if ( glfwInit() == 0 ) { fprintf( stderr, "Failed to initialize GLFW\n" ); return -1; } #if __APPLE__ const char* glslVersion = "#version 150"; #else const char* glslVersion = nullptr; #endif glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 3 ); glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 3 ); glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE ); glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE ); // MSAA glfwWindowHint( GLFW_SAMPLES, 4 ); b2Version version = b2GetVersion(); snprintf( buffer, 128, "Box2D Version %d.%d.%d", version.major, version.minor, version.revision ); if ( GLFWmonitor* primaryMonitor = glfwGetPrimaryMonitor() ) { #ifdef __APPLE__ glfwGetMonitorContentScale( primaryMonitor, &s_framebufferScale, &s_framebufferScale ); #else float uiScale = 1.0f; glfwGetMonitorContentScale( primaryMonitor, &uiScale, &uiScale ); s_context.uiScale = uiScale; #endif } bool fullscreen = false; if ( fullscreen ) { s_context.window = glfwCreateWindow( 1920, 1080, buffer, glfwGetPrimaryMonitor(), nullptr ); } else { s_context.window = glfwCreateWindow( int( s_context.camera.width ), int( s_context.camera.height ), buffer, nullptr, nullptr ); } if ( s_context.window == nullptr ) { fprintf( stderr, "Failed to open GLFW window.\n" ); glfwTerminate(); return -1; } glfwMakeContextCurrent( s_context.window ); // Load OpenGL functions using glad if ( !gladLoadGL() ) { fprintf( stderr, "Failed to initialize glad\n" ); glfwTerminate(); return -1; } { const char* glVersionString = (const char*)glGetString( GL_VERSION ); const char* glslVersionString = (const char*)glGetString( GL_SHADING_LANGUAGE_VERSION ); printf( "OpenGL %s, GLSL %s\n", glVersionString, glslVersionString ); } glfwSetWindowSizeCallback( s_context.window, ResizeWindowCallback ); glfwSetKeyCallback( s_context.window, KeyCallback ); glfwSetCharCallback( s_context.window, CharCallback ); glfwSetMouseButtonCallback( s_context.window, MouseButtonCallback ); glfwSetCursorPosCallback( s_context.window, MouseMotionCallback ); glfwSetScrollCallback( s_context.window, ScrollCallback ); CreateUI( s_context.window, glslVersion ); s_context.draw = CreateDraw(); s_context.sampleIndex = b2ClampInt( s_context.sampleIndex, 0, g_sampleCount - 1 ); s_selection = s_context.sampleIndex; glClearColor( 0.2f, 0.2f, 0.2f, 1.0f ); float frameTime = 0.0; while ( !glfwWindowShouldClose( s_context.window ) ) { double time1 = glfwGetTime(); if ( glfwGetKey( s_context.window, GLFW_KEY_Z ) == GLFW_PRESS ) { // Zoom out s_context.camera.zoom = b2MinFloat( 1.005f * s_context.camera.zoom, 100.0f ); } else if ( glfwGetKey( s_context.window, GLFW_KEY_X ) == GLFW_PRESS ) { // Zoom in s_context.camera.zoom = b2MaxFloat( 0.995f * s_context.camera.zoom, 0.5f ); } int width, height; glfwGetWindowSize( s_context.window, &width, &height ); s_context.camera.width = width; s_context.camera.height = height; int bufferWidth, bufferHeight; glfwGetFramebufferSize( s_context.window, &bufferWidth, &bufferHeight ); glViewport( 0, 0, bufferWidth, bufferHeight ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // s_context.draw.DrawBackground(); // double cursorPosX = 0, cursorPosY = 0; // glfwGetCursorPos( s_context.window, &cursorPosX, &cursorPosY ); // ImGui_ImplGlfw_CursorPosCallback( s_context.window, cursorPosX / s_windowScale, cursorPosY / s_windowScale ); ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); // ImGui_ImplGlfw_CursorPosCallback( s_context.window, cursorPosX / s_windowScale, cursorPosY / s_windowScale ); ImGuiIO& io = ImGui::GetIO(); io.DisplaySize.x = s_context.camera.width; io.DisplaySize.y = s_context.camera.height; io.DisplayFramebufferScale.x = bufferWidth / s_context.camera.width; io.DisplayFramebufferScale.y = bufferHeight / s_context.camera.height; ImGui::NewFrame(); if ( s_sample == nullptr ) { // delayed creation because imgui doesn't create fonts until NewFrame() is called s_sample = g_sampleEntries[s_context.sampleIndex].createFcn( &s_context ); } s_sample->ResetText(); const SampleEntry& entry = g_sampleEntries[s_context.sampleIndex]; s_sample->DrawColoredTextLine(b2_colorYellow, "%s : %s", entry.category, entry.name ); s_sample->Step(); DrawScreenString( s_context.draw, 5.0f, s_context.camera.height - 10.0f, b2_colorSeaGreen, "%.1f ms - step %d - camera (%g, %g, %g)", 1000.0f * frameTime, s_sample->m_stepCount, s_context.camera.center.x, s_context.camera.center.y, s_context.camera.zoom ); FlushDraw( s_context.draw, &s_context.camera ); UpdateUI(); // ImGui::ShowDemoWindow(); ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData( ImGui::GetDrawData() ); glfwSwapBuffers( s_context.window ); // For the Tracy profiler FrameMark; if ( s_selection != s_context.sampleIndex ) { ResetView( &s_context.camera ); s_context.sampleIndex = s_selection; s_context.subStepCount = 4; s_context.debugDraw.drawJoints = true; delete s_sample; s_sample = nullptr; s_sample = g_sampleEntries[s_context.sampleIndex].createFcn( &s_context ); } glfwPollEvents(); // Limit frame rate to 60Hz double time2 = glfwGetTime(); double targetTime = time1 + 1.0 / 60.0; while ( time2 < targetTime ) { b2Yield(); time2 = glfwGetTime(); } frameTime = float( time2 - time1 ); } delete s_sample; s_sample = nullptr; DestroyDraw( s_context.draw ); DestroyUI(); glfwTerminate(); s_context.Save(); #if defined( _MSC_VER ) _CrtDumpMemoryLeaks(); #endif return 0; } ================================================ FILE: samples/sample.cpp ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #if defined( _MSC_VER ) && !defined( _CRT_SECURE_NO_WARNINGS ) #define _CRT_SECURE_NO_WARNINGS #endif #include "sample.h" #include "TaskScheduler.h" #include "draw.h" #include "imgui.h" #include "random.h" // consider using https://github.com/skeeto/pdjson #include "jsmn.h" #include "box2d/box2d.h" #include "box2d/math_functions.h" #include #include #include static const char* fileName = "settings.ini"; // Load a file. You must free the character array. static bool ReadFile( char*& data, int& size, const char* filename ) { FILE* file = fopen( filename, "rb" ); if ( file == nullptr ) { return false; } fseek( file, 0, SEEK_END ); size = (int)ftell( file ); fseek( file, 0, SEEK_SET ); if ( size == 0 ) { return false; } data = (char*)malloc( size + 1 ); size_t count = fread( data, size, 1, file ); (void)count; fclose( file ); data[size] = 0; return true; } void SampleContext::Save() { FILE* file = fopen( fileName, "w" ); fprintf( file, "{\n" ); fprintf( file, " \"sampleIndex\": %d,\n", sampleIndex ); fprintf( file, " \"drawShapes\": %s,\n", debugDraw.drawShapes ? "true" : "false" ); fprintf( file, " \"drawJoints\": %s,\n", debugDraw.drawJoints ? "true" : "false" ); fprintf( file, "}\n" ); fclose( file ); } static int jsoneq( const char* json, jsmntok_t* tok, const char* s ) { if ( tok->type == JSMN_STRING && (int)strlen( s ) == tok->end - tok->start && strncmp( json + tok->start, s, tok->end - tok->start ) == 0 ) { return 0; } return -1; } void DrawPolygonFcn( const b2Vec2* vertices, int vertexCount, b2HexColor color, void* context ) { SampleContext* sampleContext = static_cast( context ); DrawPolygon( sampleContext->draw, vertices, vertexCount, color ); } void DrawSolidPolygonFcn( b2Transform transform, const b2Vec2* vertices, int vertexCount, float radius, b2HexColor color, void* context ) { SampleContext* sampleContext = static_cast( context ); DrawSolidPolygon( sampleContext->draw, transform, vertices, vertexCount, radius, color ); } void DrawCircleFcn( b2Vec2 center, float radius, b2HexColor color, void* context ) { SampleContext* sampleContext = static_cast( context ); DrawCircle( sampleContext->draw, center, radius, color ); } void DrawSolidCircleFcn( b2Transform transform, float radius, b2HexColor color, void* context ) { SampleContext* sampleContext = static_cast( context ); DrawSolidCircle( sampleContext->draw, transform, radius, color ); } void DrawSolidCapsuleFcn( b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color, void* context ) { SampleContext* sampleContext = static_cast( context ); DrawSolidCapsule( sampleContext->draw, p1, p2, radius, color ); } void DrawLineFcn( b2Vec2 p1, b2Vec2 p2, b2HexColor color, void* context ) { SampleContext* sampleContext = static_cast( context ); DrawLine( sampleContext->draw, p1, p2, color ); } void DrawTransformFcn( b2Transform transform, void* context ) { SampleContext* sampleContext = static_cast( context ); DrawTransform( sampleContext->draw, transform, 1.0f ); } void DrawPointFcn( b2Vec2 p, float size, b2HexColor color, void* context ) { SampleContext* sampleContext = static_cast( context ); DrawPoint( sampleContext->draw, p, size, color ); } void DrawStringFcn( b2Vec2 p, const char* s, b2HexColor color, void* context ) { SampleContext* sampleContext = static_cast( context ); DrawWorldString( sampleContext->draw, &sampleContext->camera, p, color, s ); } #define MAX_TOKENS 32 void SampleContext::Load() { camera = GetDefaultCamera(); debugDraw = b2DefaultDebugDraw(); debugDraw.DrawPolygonFcn = DrawPolygonFcn; debugDraw.DrawSolidPolygonFcn = DrawSolidPolygonFcn; debugDraw.DrawCircleFcn = DrawCircleFcn; debugDraw.DrawSolidCircleFcn = DrawSolidCircleFcn; debugDraw.DrawSolidCapsuleFcn = DrawSolidCapsuleFcn; debugDraw.DrawLineFcn = DrawLineFcn; debugDraw.DrawTransformFcn = DrawTransformFcn; debugDraw.DrawPointFcn = DrawPointFcn; debugDraw.DrawStringFcn = DrawStringFcn; debugDraw.context = this; char* data = nullptr; int size = 0; bool found = ReadFile( data, size, fileName ); if ( found == false ) { return; } jsmn_parser parser; jsmntok_t tokens[MAX_TOKENS]; jsmn_init( &parser ); // js - pointer to JSON string // tokens - an array of tokens available // 10 - number of tokens available int tokenCount = jsmn_parse( &parser, data, size, tokens, MAX_TOKENS ); char buffer[32]; for ( int i = 0; i < tokenCount; ++i ) { if ( jsoneq( data, &tokens[i], "sampleIndex" ) == 0 ) { int count = tokens[i + 1].end - tokens[i + 1].start; assert( count < 32 ); const char* s = data + tokens[i + 1].start; strncpy( buffer, s, count ); buffer[count] = 0; char* dummy; sampleIndex = (int)strtol( buffer, &dummy, 10 ); } else if ( jsoneq( data, &tokens[i], "drawShapes" ) == 0 ) { const char* s = data + tokens[i + 1].start; if ( strncmp( s, "true", 4 ) == 0 ) { debugDraw.drawShapes = true; } else if ( strncmp( s, "false", 5 ) == 0 ) { debugDraw.drawShapes = false; } } else if ( jsoneq( data, &tokens[i], "drawJoints" ) == 0 ) { const char* s = data + tokens[i + 1].start; if ( strncmp( s, "true", 4 ) == 0 ) { debugDraw.drawJoints = true; } else if ( strncmp( s, "false", 5 ) == 0 ) { debugDraw.drawJoints = false; } } } free( data ); } class SampleTask : public enki::ITaskSet { public: SampleTask() = default; void ExecuteRange( enki::TaskSetPartition range, uint32_t threadIndex ) override { m_task( range.start, range.end, threadIndex, m_taskContext ); } b2TaskCallback* m_task = nullptr; void* m_taskContext = nullptr; }; static void* EnqueueTask( b2TaskCallback* task, int32_t itemCount, int32_t minRange, void* taskContext, void* userContext ) { Sample* sample = static_cast( userContext ); if ( sample->m_taskCount < Sample::m_maxTasks ) { SampleTask& sampleTask = sample->m_tasks[sample->m_taskCount]; sampleTask.m_SetSize = itemCount; sampleTask.m_MinRange = minRange; sampleTask.m_task = task; sampleTask.m_taskContext = taskContext; sample->m_scheduler->AddTaskSetToPipe( &sampleTask ); ++sample->m_taskCount; return &sampleTask; } else { // This is not fatal but the maxTasks should be increased assert( false ); task( 0, itemCount, 0, taskContext ); return nullptr; } } static void FinishTask( void* taskPtr, void* userContext ) { if ( taskPtr != nullptr ) { SampleTask* sampleTask = static_cast( taskPtr ); Sample* sample = static_cast( userContext ); sample->m_scheduler->WaitforTask( sampleTask ); } } static void TestMathCpp() { b2Vec2 a = { 1.0f, 2.0f }; b2Vec2 b = { 3.0f, 4.0f }; b2Vec2 c = a; c += b; c -= b; c *= 2.0f; c = -a; c = c + b; c = c - a; c = 2.0f * a; c = a * 2.0f; if ( b == a ) { c = a; } if ( b != a ) { c = b; } c += c; } Sample::Sample( SampleContext* context ) { m_context = context; m_camera = &context->camera; m_draw = context->draw; m_scheduler = new enki::TaskScheduler; m_scheduler->Initialize( m_context->workerCount ); m_tasks = new SampleTask[m_maxTasks]; m_taskCount = 0; m_threadCount = 1 + m_context->workerCount; m_worldId = b2_nullWorldId; m_textIncrement = 26; m_textLine = m_textIncrement; m_mouseJointId = b2_nullJointId; m_stepCount = 0; m_mouseBodyId = b2_nullBodyId; m_mousePoint = {}; m_mouseForceScale = 100.0f; m_maxProfile = {}; m_totalProfile = {}; g_randomSeed = RAND_SEED; CreateWorld(); TestMathCpp(); } Sample::~Sample() { // By deleting the world, we delete the bomb, mouse joint, etc. b2DestroyWorld( m_worldId ); delete m_scheduler; delete[] m_tasks; } void Sample::CreateWorld() { if ( B2_IS_NON_NULL( m_worldId ) ) { b2DestroyWorld( m_worldId ); m_worldId = b2_nullWorldId; } b2WorldDef worldDef = b2DefaultWorldDef(); worldDef.workerCount = m_context->workerCount; worldDef.enqueueTask = EnqueueTask; worldDef.finishTask = FinishTask; worldDef.userTaskContext = this; worldDef.enableSleep = m_context->enableSleep; // todo experimental // worldDef.enableContactSoftening = true; m_worldId = b2CreateWorld( &worldDef ); } void Sample::ResetText() { m_textLine = m_textIncrement; } struct QueryContext { b2Vec2 point; b2BodyId bodyId = b2_nullBodyId; }; bool QueryCallback( b2ShapeId shapeId, void* context ) { QueryContext* queryContext = static_cast( context ); b2BodyId bodyId = b2Shape_GetBody( shapeId ); b2BodyType bodyType = b2Body_GetType( bodyId ); if ( bodyType != b2_dynamicBody ) { // continue query return true; } bool overlap = b2Shape_TestPoint( shapeId, queryContext->point ); if ( overlap ) { // found shape queryContext->bodyId = bodyId; return false; } return true; } void Sample::MouseDown( b2Vec2 p, int button, int mod ) { if ( B2_IS_NON_NULL( m_mouseJointId ) ) { return; } if ( button == GLFW_MOUSE_BUTTON_1 ) { // Make a small box. b2AABB box; b2Vec2 d = { 0.001f, 0.001f }; box.lowerBound = b2Sub( p, d ); box.upperBound = b2Add( p, d ); m_mousePoint = p; // Query the world for overlapping shapes. QueryContext queryContext = { p, b2_nullBodyId }; b2World_OverlapAABB( m_worldId, box, b2DefaultQueryFilter(), QueryCallback, &queryContext ); if ( B2_IS_NON_NULL( queryContext.bodyId ) ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_kinematicBody; bodyDef.position = m_mousePoint; bodyDef.enableSleep = false; m_mouseBodyId = b2CreateBody( m_worldId, &bodyDef ); b2MotorJointDef jointDef = b2DefaultMotorJointDef(); jointDef.base.bodyIdA = m_mouseBodyId; jointDef.base.bodyIdB = queryContext.bodyId; jointDef.base.localFrameB.p = b2Body_GetLocalPoint( queryContext.bodyId, p ); jointDef.linearHertz = 7.5f; jointDef.linearDampingRatio = 1.0f; b2MassData massData = b2Body_GetMassData( queryContext.bodyId ); float g = b2Length( b2World_GetGravity( m_worldId ) ); float mg = massData.mass * g; jointDef.maxSpringForce = m_mouseForceScale * mg; if ( massData.mass > 0.0f ) { // This acts like angular friction float lever = sqrtf( massData.rotationalInertia / massData.mass ); jointDef.maxVelocityTorque = 0.25f * lever * mg; } m_mouseJointId = b2CreateMotorJoint( m_worldId, &jointDef ); } } } void Sample::MouseUp( b2Vec2 p, int button ) { if ( B2_IS_NON_NULL( m_mouseJointId ) && button == GLFW_MOUSE_BUTTON_1 ) { b2DestroyJoint( m_mouseJointId, true ); m_mouseJointId = b2_nullJointId; b2DestroyBody( m_mouseBodyId ); m_mouseBodyId = b2_nullBodyId; } } void Sample::MouseMove( b2Vec2 p ) { if ( b2Joint_IsValid( m_mouseJointId ) == false ) { // The world or attached body was destroyed. m_mouseJointId = b2_nullJointId; } m_mousePoint = p; } void Sample::DrawColoredTextLine( b2HexColor color, const char* text,... ) { if (m_context->showUI == false) { return; } char buffer[256]; va_list arg; va_start( arg, text ); vsnprintf( buffer, 256, text, arg ); va_end( arg ); buffer[255] = 0; DrawScreenString( m_draw, 5, m_textLine, color, buffer ); m_textLine += m_textIncrement; } void Sample::DrawTextLine( const char* text, ... ) { if (m_context->showUI == false) { return; } char buffer[256]; va_list arg; va_start( arg, text ); vsnprintf( buffer, 256, text, arg ); va_end( arg ); buffer[255] = 0; DrawScreenString( m_draw, 5, m_textLine, b2_colorWhite, buffer ); m_textLine += m_textIncrement; } void Sample::ResetProfile() { m_totalProfile = {}; m_maxProfile = {}; m_stepCount = 0; } void Sample::Step() { float timeStep = m_context->hertz > 0.0f ? 1.0f / m_context->hertz : 0.0f; if ( m_context->pause ) { if ( m_context->singleStep ) { m_context->singleStep = false; } else { timeStep = 0.0f; } if ( m_context->showUI ) { DrawTextLine( "****PAUSED****" ); m_textLine += m_textIncrement; } } if ( B2_IS_NON_NULL( m_mouseJointId ) && b2Joint_IsValid( m_mouseJointId ) == false ) { // The world or attached body was destroyed. m_mouseJointId = b2_nullJointId; if ( B2_IS_NON_NULL( m_mouseBodyId ) ) { b2DestroyBody( m_mouseBodyId ); m_mouseBodyId = b2_nullBodyId; } } if ( B2_IS_NON_NULL( m_mouseBodyId ) && timeStep > 0.0f ) { bool wake = true; b2Body_SetTargetTransform( m_mouseBodyId, { m_mousePoint, b2Rot_identity }, timeStep, wake ); } m_context->debugDraw.drawingBounds = GetViewBounds( &m_context->camera ); b2World_EnableSleeping( m_worldId, m_context->enableSleep ); b2World_EnableWarmStarting( m_worldId, m_context->enableWarmStarting ); b2World_EnableContinuous( m_worldId, m_context->enableContinuous ); for ( int i = 0; i < 1; ++i ) { b2World_Step( m_worldId, timeStep, m_context->subStepCount ); m_taskCount = 0; } b2World_Draw( m_worldId, &m_context->debugDraw ); if ( timeStep > 0.0f ) { ++m_stepCount; } if ( m_context->drawCounters ) { b2Counters s = b2World_GetCounters( m_worldId ); DrawTextLine( "bodies/shapes/contacts/joints = %d/%d/%d/%d", s.bodyCount, s.shapeCount, s.contactCount, s.jointCount ); DrawTextLine( "islands/tasks = %d/%d", s.islandCount, s.taskCount ); DrawTextLine( "tree height static/movable = %d/%d", s.staticTreeHeight, s.treeHeight ); int totalCount = 0; char buffer[256] = { 0 }; int colorCount = sizeof( s.colorCounts ) / sizeof( s.colorCounts[0] ); // todo fix this int offset = snprintf( buffer, 256, "colors: " ); for ( int i = 0; i < colorCount; ++i ) { offset += snprintf( buffer + offset, 256 - offset, "%d/", s.colorCounts[i] ); totalCount += s.colorCounts[i]; } snprintf( buffer + offset, 256 - offset, "[%d]", totalCount ); DrawTextLine( buffer ); DrawTextLine( "stack allocator size = %d K", s.stackUsed / 1024 ); DrawTextLine( "total allocation = %d K", s.byteCount / 1024 ); } // Track maximum profile times { b2Profile p = b2World_GetProfile( m_worldId ); m_maxProfile.step = b2MaxFloat( m_maxProfile.step, p.step ); m_maxProfile.pairs = b2MaxFloat( m_maxProfile.pairs, p.pairs ); m_maxProfile.collide = b2MaxFloat( m_maxProfile.collide, p.collide ); m_maxProfile.solve = b2MaxFloat( m_maxProfile.solve, p.solve ); m_maxProfile.prepareStages = b2MaxFloat( m_maxProfile.prepareStages, p.prepareStages ); m_maxProfile.solveConstraints = b2MaxFloat( m_maxProfile.solveConstraints, p.solveConstraints ); m_maxProfile.prepareConstraints = b2MaxFloat( m_maxProfile.prepareConstraints, p.prepareConstraints ); m_maxProfile.integrateVelocities = b2MaxFloat( m_maxProfile.integrateVelocities, p.integrateVelocities ); m_maxProfile.warmStart = b2MaxFloat( m_maxProfile.warmStart, p.warmStart ); m_maxProfile.solveImpulses = b2MaxFloat( m_maxProfile.solveImpulses, p.solveImpulses ); m_maxProfile.integratePositions = b2MaxFloat( m_maxProfile.integratePositions, p.integratePositions ); m_maxProfile.relaxImpulses = b2MaxFloat( m_maxProfile.relaxImpulses, p.relaxImpulses ); m_maxProfile.applyRestitution = b2MaxFloat( m_maxProfile.applyRestitution, p.applyRestitution ); m_maxProfile.storeImpulses = b2MaxFloat( m_maxProfile.storeImpulses, p.storeImpulses ); m_maxProfile.transforms = b2MaxFloat( m_maxProfile.transforms, p.transforms ); m_maxProfile.splitIslands = b2MaxFloat( m_maxProfile.splitIslands, p.splitIslands ); m_maxProfile.jointEvents = b2MaxFloat( m_maxProfile.jointEvents, p.jointEvents ); m_maxProfile.hitEvents = b2MaxFloat( m_maxProfile.hitEvents, p.hitEvents ); m_maxProfile.refit = b2MaxFloat( m_maxProfile.refit, p.refit ); m_maxProfile.bullets = b2MaxFloat( m_maxProfile.bullets, p.bullets ); m_maxProfile.sleepIslands = b2MaxFloat( m_maxProfile.sleepIslands, p.sleepIslands ); m_maxProfile.sensors = b2MaxFloat( m_maxProfile.sensors, p.sensors ); m_totalProfile.step += p.step; m_totalProfile.pairs += p.pairs; m_totalProfile.collide += p.collide; m_totalProfile.solve += p.solve; m_totalProfile.prepareStages += p.prepareStages; m_totalProfile.solveConstraints += p.solveConstraints; m_totalProfile.prepareConstraints += p.prepareConstraints; m_totalProfile.integrateVelocities += p.integrateVelocities; m_totalProfile.warmStart += p.warmStart; m_totalProfile.solveImpulses += p.solveImpulses; m_totalProfile.integratePositions += p.integratePositions; m_totalProfile.relaxImpulses += p.relaxImpulses; m_totalProfile.applyRestitution += p.applyRestitution; m_totalProfile.storeImpulses += p.storeImpulses; m_totalProfile.transforms += p.transforms; m_totalProfile.splitIslands += p.splitIslands; m_totalProfile.jointEvents += p.jointEvents; m_totalProfile.hitEvents += p.hitEvents; m_totalProfile.refit += p.refit; m_totalProfile.bullets += p.bullets; m_totalProfile.sleepIslands += p.sleepIslands; m_totalProfile.sensors += p.sensors; } if ( m_context->drawProfile ) { b2Profile p = b2World_GetProfile( m_worldId ); b2Profile aveProfile = {}; if ( m_stepCount > 0 ) { float scale = 1.0f / m_stepCount; aveProfile.step = scale * m_totalProfile.step; aveProfile.pairs = scale * m_totalProfile.pairs; aveProfile.collide = scale * m_totalProfile.collide; aveProfile.solve = scale * m_totalProfile.solve; aveProfile.prepareStages = scale * m_totalProfile.prepareStages; aveProfile.solveConstraints = scale * m_totalProfile.solveConstraints; aveProfile.prepareConstraints = scale * m_totalProfile.prepareConstraints; aveProfile.integrateVelocities = scale * m_totalProfile.integrateVelocities; aveProfile.warmStart = scale * m_totalProfile.warmStart; aveProfile.solveImpulses = scale * m_totalProfile.solveImpulses; aveProfile.integratePositions = scale * m_totalProfile.integratePositions; aveProfile.relaxImpulses = scale * m_totalProfile.relaxImpulses; aveProfile.applyRestitution = scale * m_totalProfile.applyRestitution; aveProfile.storeImpulses = scale * m_totalProfile.storeImpulses; aveProfile.transforms = scale * m_totalProfile.transforms; aveProfile.splitIslands = scale * m_totalProfile.splitIslands; aveProfile.jointEvents = scale * m_totalProfile.jointEvents; aveProfile.hitEvents = scale * m_totalProfile.hitEvents; aveProfile.refit = scale * m_totalProfile.refit; aveProfile.bullets = scale * m_totalProfile.bullets; aveProfile.sleepIslands = scale * m_totalProfile.sleepIslands; aveProfile.sensors = scale * m_totalProfile.sensors; } DrawTextLine( "step [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.step, aveProfile.step, m_maxProfile.step ); DrawTextLine( "pairs [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.pairs, aveProfile.pairs, m_maxProfile.pairs ); DrawTextLine( "collide [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.collide, aveProfile.collide, m_maxProfile.collide ); DrawTextLine( "solve [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solve, aveProfile.solve, m_maxProfile.solve ); DrawTextLine( "> prepare tasks [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.prepareStages, aveProfile.prepareStages, m_maxProfile.prepareStages ); DrawTextLine( "> solve constraints [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveConstraints, aveProfile.solveConstraints, m_maxProfile.solveConstraints ); DrawTextLine( ">> prepare constraints [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.prepareConstraints, aveProfile.prepareConstraints, m_maxProfile.prepareConstraints ); DrawTextLine( ">> integrate velocities [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.integrateVelocities, aveProfile.integrateVelocities, m_maxProfile.integrateVelocities ); DrawTextLine( ">> warm start [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.warmStart, aveProfile.warmStart, m_maxProfile.warmStart ); DrawTextLine( ">> solve impulses [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveImpulses, aveProfile.solveImpulses, m_maxProfile.solveImpulses ); DrawTextLine( ">> integrate positions [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.integratePositions, aveProfile.integratePositions, m_maxProfile.integratePositions ); DrawTextLine( ">> relax impulses [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.relaxImpulses, aveProfile.relaxImpulses, m_maxProfile.relaxImpulses ); DrawTextLine( ">> apply restitution [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.applyRestitution, aveProfile.applyRestitution, m_maxProfile.applyRestitution ); DrawTextLine( ">> store impulses [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.storeImpulses, aveProfile.storeImpulses, m_maxProfile.storeImpulses ); DrawTextLine( ">> split islands [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.splitIslands, aveProfile.splitIslands, m_maxProfile.splitIslands ); DrawTextLine( "> update transforms [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.transforms, aveProfile.transforms, m_maxProfile.transforms ); DrawTextLine( "> joint events [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.jointEvents, aveProfile.jointEvents, m_maxProfile.jointEvents ); DrawTextLine( "> hit events [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.hitEvents, aveProfile.hitEvents, m_maxProfile.hitEvents ); DrawTextLine( "> refit BVH [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.refit, aveProfile.refit, m_maxProfile.refit ); DrawTextLine( "> sleep islands [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.sleepIslands, aveProfile.sleepIslands, m_maxProfile.sleepIslands ); DrawTextLine( "> bullets [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.bullets, aveProfile.bullets, m_maxProfile.bullets ); DrawTextLine( "sensors [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.sensors, aveProfile.sensors, m_maxProfile.sensors ); } } void Sample::ShiftOrigin( b2Vec2 newOrigin ) { // m_world->ShiftOrigin(newOrigin); } // Parse an SVG path element with only straight lines. Example: // "M 47.625004,185.20833 H 161.39585 l 29.10417,-2.64583 26.45834,-7.9375 26.45833,-13.22917 23.81251,-21.16666 h " // "13.22916 v 44.97916 H 592.66669 V 0 h 21.16671 v 206.375 l -566.208398,-1e-5 z" int Sample::ParsePath( const char* svgPath, b2Vec2 offset, b2Vec2* points, int capacity, float scale, bool reverseOrder ) { int pointCount = 0; b2Vec2 currentPoint = {}; const char* ptr = svgPath; char command = *ptr; while ( *ptr != '\0' ) { if ( isdigit( *ptr ) == 0 && *ptr != '-' ) { // note: command can be implicitly repeated command = *ptr; if ( command == 'M' || command == 'L' || command == 'H' || command == 'V' || command == 'm' || command == 'l' || command == 'h' || command == 'v' ) { ptr += 2; // Skip the command character and space } if ( command == 'z' ) { break; } } assert( isdigit( *ptr ) != 0 || *ptr == '-' ); float x = 0.0f, y = 0.0f; switch ( command ) { case 'M': case 'L': if ( sscanf( ptr, "%f,%f", &x, &y ) == 2 ) { currentPoint.x = x; currentPoint.y = y; } else { assert( false ); } break; case 'H': if ( sscanf( ptr, "%f", &x ) == 1 ) { currentPoint.x = x; } else { assert( false ); } break; case 'V': if ( sscanf( ptr, "%f", &y ) == 1 ) { currentPoint.y = y; } else { assert( false ); } break; case 'm': case 'l': if ( sscanf( ptr, "%f,%f", &x, &y ) == 2 ) { currentPoint.x += x; currentPoint.y += y; } else { assert( false ); } break; case 'h': if ( sscanf( ptr, "%f", &x ) == 1 ) { currentPoint.x += x; } else { assert( false ); } break; case 'v': if ( sscanf( ptr, "%f", &y ) == 1 ) { currentPoint.y += y; } else { assert( false ); } break; default: assert( false ); break; } points[pointCount] = { scale * ( currentPoint.x + offset.x ), -scale * ( currentPoint.y + offset.y ) }; pointCount += 1; if ( pointCount == capacity ) { break; } // Move to the next space or end of string while ( *ptr != '\0' && isspace( *ptr ) == 0 ) { ptr++; } // Skip contiguous spaces while ( isspace( *ptr ) ) { ptr++; } ptr += 0; } if ( pointCount == 0 ) { return 0; } if ( reverseOrder ) { } return pointCount; } SampleEntry g_sampleEntries[MAX_SAMPLES] = {}; int g_sampleCount = 0; int RegisterSample( const char* category, const char* name, SampleCreateFcn* fcn ) { int index = g_sampleCount; if ( index < MAX_SAMPLES ) { g_sampleEntries[index] = { category, name, fcn }; ++g_sampleCount; return index; } return -1; } ================================================ FILE: samples/sample.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "box2d/id.h" #include "box2d/types.h" #include "draw.h" #define ARRAY_COUNT( A ) (int)( sizeof( A ) / sizeof( A[0] ) ) namespace enki { class TaskScheduler; }; struct ImFont; struct SampleContext { void Save(); void Load(); struct GLFWwindow* window = nullptr; Camera camera; Draw* draw; float uiScale = 1.0f; float hertz = 60.0f; int subStepCount = 4; int workerCount = 1; bool restart = false; bool pause = false; bool singleStep = false; bool drawCounters = false; bool drawProfile = false; bool enableWarmStarting = true; bool enableContinuous = true; bool enableSleep = true; bool showUI = true; // These are persisted int sampleIndex = 0; b2DebugDraw debugDraw; ImFont* regularFont; ImFont* mediumFont; ImFont* largeFont; }; class Sample { public: explicit Sample( SampleContext* context ); virtual ~Sample(); void CreateWorld( ); void ResetText(); virtual void Step( ); virtual void UpdateGui() { } virtual void Keyboard( int ) { } virtual void MouseDown( b2Vec2 p, int button, int mod ); virtual void MouseUp( b2Vec2 p, int button ); virtual void MouseMove( b2Vec2 p ); void DrawTextLine( const char* text, ... ); void DrawColoredTextLine( b2HexColor color, const char* text, ... ); void ResetProfile(); void ShiftOrigin( b2Vec2 newOrigin ); static int ParsePath( const char* svgPath, b2Vec2 offset, b2Vec2* points, int capacity, float scale, bool reverseOrder ); friend class DestructionListener; friend class BoundaryListener; friend class ContactListener; static constexpr int m_maxTasks = 64; static constexpr int m_maxThreads = 64; #ifdef NDEBUG static constexpr bool m_isDebug = false; #else static constexpr bool m_isDebug = true; #endif SampleContext* m_context; Camera* m_camera; Draw* m_draw; enki::TaskScheduler* m_scheduler; class SampleTask* m_tasks; int m_taskCount; int m_threadCount; b2BodyId m_mouseBodyId; b2WorldId m_worldId; b2JointId m_mouseJointId; b2Vec2 m_mousePoint; float m_mouseForceScale; int m_stepCount; b2Profile m_maxProfile; b2Profile m_totalProfile; private: int m_textLine; int m_textIncrement; }; typedef Sample* SampleCreateFcn( SampleContext* context ); int RegisterSample( const char* category, const char* name, SampleCreateFcn* fcn ); struct SampleEntry { const char* category; const char* name; SampleCreateFcn* createFcn; }; #define MAX_SAMPLES 256 extern SampleEntry g_sampleEntries[MAX_SAMPLES]; extern int g_sampleCount; ================================================ FILE: samples/sample_benchmark.cpp ================================================ // SPDX-FileCopyrightText: 2022 Erin Catto // SPDX-License-Identifier: MIT #include "benchmarks.h" #include "draw.h" #include "human.h" #include "random.h" #include "sample.h" #include "box2d/box2d.h" #include "box2d/math_functions.h" #include #include #include #include #include #if defined( _MSC_VER ) #include #define GET_CYCLES __rdtsc() #else #define GET_CYCLES b2GetTicks() #endif inline bool operator<( b2BodyId a, b2BodyId b ) { uint64_t ua = b2StoreBodyId( a ); uint64_t ub = b2StoreBodyId( b ); return ua < ub; } // these are not accessible in some build types // extern "C" int b2_toiCalls; // extern "C" int b2_toiHitCount; // Note: resetting the scene is non-deterministic because the world uses freelists class BenchmarkBarrel : public Sample { public: enum ShapeType { e_circleShape = 0, e_capsuleShape, e_mixShape, e_compoundShape, e_humanShape, }; enum { e_maxColumns = 26, e_maxRows = 150, }; explicit BenchmarkBarrel( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 8.0f, 53.0f }; m_context->camera.zoom = 25.0f * 2.35f; } m_context->debugDraw.drawJoints = false; { float gridSize = 1.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); float y = 0.0f; float x = -40.0f * gridSize; for ( int i = 0; i < 81; ++i ) { b2Polygon box = b2MakeOffsetBox( 0.5f * gridSize, 0.5f * gridSize, { x, y }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); x += gridSize; } y = gridSize; x = -40.0f * gridSize; for ( int i = 0; i < 100; ++i ) { b2Polygon box = b2MakeOffsetBox( 0.5f * gridSize, 0.5f * gridSize, { x, y }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); y += gridSize; } y = gridSize; x = 40.0f * gridSize; for ( int i = 0; i < 100; ++i ) { b2Polygon box = b2MakeOffsetBox( 0.5f * gridSize, 0.5f * gridSize, { x, y }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); y += gridSize; } b2Segment segment = { { -800.0f, -80.0f }, { 800.0f, -80.f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } for ( int i = 0; i < e_maxRows * e_maxColumns; ++i ) { m_bodies[i] = b2_nullBodyId; } memset( m_humans, 0, sizeof( m_humans ) ); m_shapeType = e_compoundShape; CreateScene(); } void CreateScene() { g_randomSeed = 42; for ( int i = 0; i < e_maxRows * e_maxColumns; ++i ) { if ( B2_IS_NON_NULL( m_bodies[i] ) ) { b2DestroyBody( m_bodies[i] ); m_bodies[i] = b2_nullBodyId; } if ( m_humans[i].isSpawned ) { DestroyHuman( m_humans + i ); } } m_columnCount = m_isDebug ? 10 : e_maxColumns; m_rowCount = m_isDebug ? 40 : e_maxRows; if ( m_shapeType == e_compoundShape ) { if constexpr ( m_isDebug == false ) { m_columnCount = 20; } } else if ( m_shapeType == e_humanShape ) { if constexpr ( m_isDebug ) { m_rowCount = 5; m_columnCount = 10; } else { m_rowCount = 30; } } float rad = 0.5f; float shift = 1.15f; float centerx = shift * m_columnCount / 2.0f; float centery = shift / 2.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; // todo eliminate this once rolling resistance is added if ( m_shapeType == e_mixShape ) { bodyDef.angularDamping = 0.3f; } b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.material.friction = 0.5f; b2Capsule capsule = { { 0.0f, -0.25f }, { 0.0f, 0.25f }, rad }; b2Circle circle = { { 0.0f, 0.0f }, rad }; b2Vec2 points[3] = { { -0.1f, -0.5f }, { 0.1f, -0.5f }, { 0.0f, 0.5f } }; b2Hull wedgeHull = b2ComputeHull( points, 3 ); b2Polygon wedge = b2MakePolygon( &wedgeHull, 0.0f ); b2Vec2 vertices[3]; vertices[0] = { -1.0f, 0.0f }; vertices[1] = { 0.5f, 1.0f }; vertices[2] = { 0.0f, 2.0f }; b2Hull hull = b2ComputeHull( vertices, 3 ); b2Polygon left = b2MakePolygon( &hull, 0.0f ); vertices[0] = { 1.0f, 0.0f }; vertices[1] = { -0.5f, 1.0f }; vertices[2] = { 0.0f, 2.0f }; hull = b2ComputeHull( vertices, 3 ); b2Polygon right = b2MakePolygon( &hull, 0.0f ); // b2Polygon top = b2MakeOffsetBox(0.8f, 0.2f, {0.0f, 0.8f}, 0.0f); // b2Polygon leftLeg = b2MakeOffsetBox(0.2f, 0.5f, {-0.6f, 0.5f}, 0.0f); // b2Polygon rightLeg = b2MakeOffsetBox(0.2f, 0.5f, {0.6f, 0.5f}, 0.0f); float side = -0.1f; float extray = 0.5f; if ( m_shapeType == e_compoundShape ) { extray = 0.25f; side = 0.25f; shift = 2.0f; centerx = shift * m_columnCount / 2.0f - 1.0f; } else if ( m_shapeType == e_humanShape ) { extray = 0.5f; side = 0.55f; shift = 2.5f; centerx = shift * m_columnCount / 2.0f; } int index = 0; float yStart = m_shapeType == e_humanShape ? 2.0f : 100.0f; for ( int i = 0; i < m_columnCount; ++i ) { float x = i * shift - centerx; for ( int j = 0; j < m_rowCount; ++j ) { float y = j * ( shift + extray ) + centery + yStart; bodyDef.position = { x + side, y }; side = -side; if ( m_shapeType == e_circleShape ) { m_bodies[index] = b2CreateBody( m_worldId, &bodyDef ); circle.radius = RandomFloatRange( 0.25f, 0.75f ); shapeDef.material.rollingResistance = 0.2f; b2CreateCircleShape( m_bodies[index], &shapeDef, &circle ); } else if ( m_shapeType == e_capsuleShape ) { m_bodies[index] = b2CreateBody( m_worldId, &bodyDef ); capsule.radius = RandomFloatRange( 0.25f, 0.5f ); float length = RandomFloatRange( 0.25f, 1.0f ); capsule.center1 = { 0.0f, -0.5f * length }; capsule.center2 = { 0.0f, 0.5f * length }; shapeDef.material.rollingResistance = 0.2f; b2CreateCapsuleShape( m_bodies[index], &shapeDef, &capsule ); } else if ( m_shapeType == e_mixShape ) { m_bodies[index] = b2CreateBody( m_worldId, &bodyDef ); int mod = index % 3; if ( mod == 0 ) { circle.radius = RandomFloatRange( 0.25f, 0.75f ); b2CreateCircleShape( m_bodies[index], &shapeDef, &circle ); } else if ( mod == 1 ) { capsule.radius = RandomFloatRange( 0.25f, 0.5f ); float length = RandomFloatRange( 0.25f, 1.0f ); capsule.center1 = { 0.0f, -0.5f * length }; capsule.center2 = { 0.0f, 0.5f * length }; b2CreateCapsuleShape( m_bodies[index], &shapeDef, &capsule ); } else if ( mod == 2 ) { float width = RandomFloatRange( 0.1f, 0.5f ); float height = RandomFloatRange( 0.5f, 0.75f ); b2Polygon box = b2MakeBox( width, height ); // Don't put a function call into a macro. float value = RandomFloatRange( -1.0f, 1.0f ); box.radius = 0.25f * b2MaxFloat( 0.0f, value ); b2CreatePolygonShape( m_bodies[index], &shapeDef, &box ); } else { wedge.radius = RandomFloatRange( 0.1f, 0.25f ); b2CreatePolygonShape( m_bodies[index], &shapeDef, &wedge ); } } else if ( m_shapeType == e_compoundShape ) { m_bodies[index] = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( m_bodies[index], &shapeDef, &left ); b2CreatePolygonShape( m_bodies[index], &shapeDef, &right ); // b2CreatePolygonShape(m_bodies[index], &shapeDef, &top); // b2CreatePolygonShape(m_bodies[index], &shapeDef, &leftLeg); // b2CreatePolygonShape(m_bodies[index], &shapeDef, &rightLeg); } else if ( m_shapeType == e_humanShape ) { float scale = 3.5f; float jointFriction = 0.05f; float jointHertz = 5.0f; float jointDamping = 0.5f; CreateHuman( m_humans + index, m_worldId, bodyDef.position, scale, jointFriction, jointHertz, jointDamping, index + 1, nullptr, false ); } index += 1; } } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 6.0f * fontSize; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 15.0f * fontSize, height ) ); ImGui::Begin( "Benchmark: Barrel", nullptr, ImGuiWindowFlags_NoResize ); bool changed = false; const char* shapeTypes[] = { "Circle", "Capsule", "Mix", "Compound", "Human" }; int shapeType = int( m_shapeType ); changed = changed || ImGui::Combo( "Shape", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ); m_shapeType = ShapeType( shapeType ); changed = changed || ImGui::Button( "Reset Scene" ); if ( changed ) { CreateScene(); } ImGui::End(); } static Sample* Create( SampleContext* context ) { return new BenchmarkBarrel( context ); } b2BodyId m_bodies[e_maxRows * e_maxColumns]; Human m_humans[e_maxRows * e_maxColumns]; int m_columnCount; int m_rowCount; ShapeType m_shapeType; }; static int benchmarkBarrel = RegisterSample( "Benchmark", "Barrel", BenchmarkBarrel::Create ); // This is used to compare performance with Box2D v2.4 class BenchmarkBarrel24 : public Sample { public: explicit BenchmarkBarrel24( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 8.0f, 53.0f }; m_context->camera.zoom = 25.0f * 2.35f; } float groundSize = 25.0f; { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( groundSize, 1.2f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( groundId, &shapeDef, &box ); bodyDef.rotation = b2MakeRot( 0.5f * B2_PI ); bodyDef.position = { groundSize, 2.0f * groundSize }; groundId = b2CreateBody( m_worldId, &bodyDef ); box = b2MakeBox( 2.0f * groundSize, 1.2f ); b2CreatePolygonShape( groundId, &shapeDef, &box ); bodyDef.position = { -groundSize, 2.0f * groundSize }; groundId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } int32_t num = 26; float rad = 0.5f; float shift = rad * 2.0f; float centerx = shift * num / 2.0f; float centery = shift / 2.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.material.friction = 0.5f; b2Polygon cuboid = b2MakeSquare( 0.5f ); // b2Polygon top = b2MakeOffsetBox(0.8f, 0.2f, {0.0f, 0.8f}, 0.0f); // b2Polygon leftLeg = b2MakeOffsetBox(0.2f, 0.5f, {-0.6f, 0.5f}, 0.0f); // b2Polygon rightLeg = b2MakeOffsetBox(0.2f, 0.5f, {0.6f, 0.5f}, 0.0f); #ifdef _DEBUG int numj = 5; #else int numj = 5 * num; #endif for ( int i = 0; i < num; ++i ) { float x = i * shift - centerx; for ( int j = 0; j < numj; ++j ) { float y = j * shift + centery + 2.0f; bodyDef.position = { x, y }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &cuboid ); } } } static Sample* Create( SampleContext* context ) { return new BenchmarkBarrel24( context ); } }; static int benchmarkBarrel24 = RegisterSample( "Benchmark", "Barrel 2.4", BenchmarkBarrel24::Create ); class BenchmarkTumbler : public Sample { public: explicit BenchmarkTumbler( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 1.5f, 10.0f }; m_context->camera.zoom = 15.0f; } CreateTumbler( m_worldId ); } static Sample* Create( SampleContext* context ) { return new BenchmarkTumbler( context ); } }; static int benchmarkTumbler = RegisterSample( "Benchmark", "Tumbler", BenchmarkTumbler::Create ); class BenchmarkWasher : public Sample { public: explicit BenchmarkWasher( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 1.5f, 10.0f }; m_context->camera.zoom = 20.0f; } CreateWasher( m_worldId ); } static Sample* Create( SampleContext* context ) { return new BenchmarkWasher( context ); } }; static int benchmarkWasher = RegisterSample( "Benchmark", "Washer", BenchmarkWasher::Create ); // todo try removing kinematics from graph coloring class BenchmarkManyTumblers : public Sample { public: explicit BenchmarkManyTumblers( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 1.0f, -5.5 }; m_context->camera.zoom = 25.0f * 3.4f; m_context->debugDraw.drawJoints = false; } b2BodyDef bodyDef = b2DefaultBodyDef(); m_groundId = b2CreateBody( m_worldId, &bodyDef ); m_rowCount = m_isDebug ? 2 : 19; m_columnCount = m_isDebug ? 2 : 19; m_tumblerIds = nullptr; m_positions = nullptr; m_tumblerCount = 0; m_bodyIds = nullptr; m_bodyCount = 0; m_bodyIndex = 0; m_angularSpeed = 25.0f; CreateScene(); } ~BenchmarkManyTumblers() override { free( m_tumblerIds ); free( m_positions ); free( m_bodyIds ); } void CreateTumbler( b2Vec2 position, int index ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_kinematicBody; bodyDef.position = { position.x, position.y }; bodyDef.angularVelocity = ( B2_PI / 180.0f ) * m_angularSpeed; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); m_tumblerIds[index] = bodyId; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 50.0f; b2Polygon polygon; polygon = b2MakeOffsetBox( 0.25f, 2.0f, { 2.0f, 0.0f }, b2Rot_identity ); b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); polygon = b2MakeOffsetBox( 0.25f, 2.0f, { -2.0f, 0.0f }, b2Rot_identity ); b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); polygon = b2MakeOffsetBox( 2.0f, 0.25f, { 0.0f, 2.0f }, b2Rot_identity ); b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); polygon = b2MakeOffsetBox( 2.0f, 0.25f, { 0.0f, -2.0f }, b2Rot_identity ); b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); } void CreateScene() { for ( int i = 0; i < m_bodyCount; ++i ) { if ( B2_IS_NON_NULL( m_bodyIds[i] ) ) { b2DestroyBody( m_bodyIds[i] ); } } for ( int i = 0; i < m_tumblerCount; ++i ) { b2DestroyBody( m_tumblerIds[i] ); } free( m_tumblerIds ); free( m_positions ); m_tumblerCount = m_rowCount * m_columnCount; m_tumblerIds = static_cast( malloc( m_tumblerCount * sizeof( b2BodyId ) ) ); m_positions = static_cast( malloc( m_tumblerCount * sizeof( b2Vec2 ) ) ); int index = 0; float x = -4.0f * m_rowCount; for ( int i = 0; i < m_rowCount; ++i ) { float y = -4.0f * m_columnCount; for ( int j = 0; j < m_columnCount; ++j ) { m_positions[index] = { x, y }; CreateTumbler( m_positions[index], index ); ++index; y += 8.0f; } x += 8.0f; } free( m_bodyIds ); int bodiesPerTumbler = m_isDebug ? 8 : 50; m_bodyCount = bodiesPerTumbler * m_tumblerCount; m_bodyIds = static_cast( malloc( m_bodyCount * sizeof( b2BodyId ) ) ); memset( m_bodyIds, 0, m_bodyCount * sizeof( b2BodyId ) ); m_bodyIndex = 0; } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 8.5f * fontSize; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 15.5f * fontSize, height ) ); ImGui::Begin( "Benchmark: Many Tumblers", nullptr, ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 8.0f * fontSize ); bool changed = false; changed = changed || ImGui::SliderInt( "Row Count", &m_rowCount, 1, 32 ); changed = changed || ImGui::SliderInt( "Column Count", &m_columnCount, 1, 32 ); if ( changed ) { CreateScene(); } if ( ImGui::SliderFloat( "Speed", &m_angularSpeed, 0.0f, 100.0f, "%.f" ) ) { for ( int i = 0; i < m_tumblerCount; ++i ) { b2Body_SetAngularVelocity( m_tumblerIds[i], ( B2_PI / 180.0f ) * m_angularSpeed ); b2Body_SetAwake( m_tumblerIds[i], true ); } } ImGui::PopItemWidth(); ImGui::End(); } void Step() override { Sample::Step(); if ( m_bodyIndex < m_bodyCount && ( m_stepCount & 0x7 ) == 0 ) { b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Capsule capsule = { { -0.1f, 0.0f }, { 0.1f, 0.0f }, 0.075f }; for ( int i = 0; i < m_tumblerCount; ++i ) { assert( m_bodyIndex < m_bodyCount ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = m_positions[i]; m_bodyIds[m_bodyIndex] = b2CreateBody( m_worldId, &bodyDef ); b2CreateCapsuleShape( m_bodyIds[m_bodyIndex], &shapeDef, &capsule ); m_bodyIndex += 1; } } } static Sample* Create( SampleContext* context ) { return new BenchmarkManyTumblers( context ); } b2BodyId m_groundId; int m_rowCount; int m_columnCount; b2BodyId* m_tumblerIds; b2Vec2* m_positions; int m_tumblerCount; b2BodyId* m_bodyIds; int m_bodyCount; int m_bodyIndex; float m_angularSpeed; }; static int benchmarkManyTumblers = RegisterSample( "Benchmark", "Many Tumblers", BenchmarkManyTumblers::Create ); class BenchmarkLargePyramid : public Sample { public: explicit BenchmarkLargePyramid( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 50.0f }; m_context->camera.zoom = 25.0f * 2.2f; m_context->enableSleep = false; } CreateLargePyramid( m_worldId ); } static Sample* Create( SampleContext* context ) { return new BenchmarkLargePyramid( context ); } }; static int benchmarkLargePyramid = RegisterSample( "Benchmark", "Large Pyramid", BenchmarkLargePyramid::Create ); class BenchmarkManyPyramids : public Sample { public: explicit BenchmarkManyPyramids( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 16.0f, 110.0f }; m_context->camera.zoom = 25.0f * 5.0f; m_context->enableSleep = false; } CreateManyPyramids( m_worldId ); } static Sample* Create( SampleContext* context ) { return new BenchmarkManyPyramids( context ); } }; static int benchmarkManyPyramids = RegisterSample( "Benchmark", "Many Pyramids", BenchmarkManyPyramids::Create ); class BenchmarkCreateDestroy : public Sample { public: enum { e_maxBaseCount = 100, e_maxBodyCount = e_maxBaseCount * ( e_maxBaseCount + 1 ) / 2 }; explicit BenchmarkCreateDestroy( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 50.0f }; m_context->camera.zoom = 25.0f * 2.2f; } float groundSize = 100.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( groundSize, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( groundId, &shapeDef, &box ); for ( int i = 0; i < e_maxBodyCount; ++i ) { m_bodies[i] = b2_nullBodyId; } m_createTime = 0.0f; m_destroyTime = 0.0f; m_baseCount = m_isDebug ? 40 : 100; m_iterations = m_isDebug ? 1 : 10; m_bodyCount = 0; } void CreateScene() { uint64_t ticks = b2GetTicks(); for ( int i = 0; i < e_maxBodyCount; ++i ) { if ( B2_IS_NON_NULL( m_bodies[i] ) ) { b2DestroyBody( m_bodies[i] ); m_bodies[i] = b2_nullBodyId; } } m_destroyTime += b2GetMillisecondsAndReset( &ticks ); int count = m_baseCount; float rad = 0.5f; float shift = rad * 2.0f; float centerx = shift * count / 2.0f; float centery = shift / 2.0f + 1.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.material.friction = 0.5f; float h = 0.5f; b2Polygon box = b2MakeRoundedBox( h, h, 0.0f ); int index = 0; for ( int i = 0; i < count; ++i ) { float y = i * shift + centery; for ( int j = i; j < count; ++j ) { float x = 0.5f * i * shift + ( j - i ) * shift - centerx; bodyDef.position = { x, y }; assert( index < e_maxBodyCount ); m_bodies[index] = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( m_bodies[index], &shapeDef, &box ); index += 1; } } m_createTime += b2GetMilliseconds( ticks ); m_bodyCount = index; b2World_Step( m_worldId, 1.0f / 60.0f, 4 ); } void Step() override { m_createTime = 0.0f; m_destroyTime = 0.0f; for ( int i = 0; i < m_iterations; ++i ) { CreateScene(); } DrawTextLine( "total: create = %g ms, destroy = %g ms", m_createTime, m_destroyTime ); float createPerBody = 1000.0f * m_createTime / m_iterations / m_bodyCount; float destroyPerBody = 1000.0f * m_destroyTime / m_iterations / m_bodyCount; DrawTextLine( "body: create = %g us, destroy = %g us", createPerBody, destroyPerBody ); Sample::Step(); } static Sample* Create( SampleContext* context ) { return new BenchmarkCreateDestroy( context ); } float m_createTime; float m_destroyTime; b2BodyId m_bodies[e_maxBodyCount]; int m_bodyCount; int m_baseCount; int m_iterations; }; static int benchmarkCreateDestroy = RegisterSample( "Benchmark", "CreateDestroy", BenchmarkCreateDestroy::Create ); class BenchmarkSleep : public Sample { public: enum { e_maxBaseCount = 100, e_maxBodyCount = e_maxBaseCount * ( e_maxBaseCount + 1 ) / 2 }; explicit BenchmarkSleep( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 50.0f }; m_context->camera.zoom = 25.0f * 2.2f; } { float groundSize = 100.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( groundSize, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( groundId, &shapeDef, &box ); } m_baseCount = m_isDebug ? 40 : 100; m_bodyCount = 0; int count = m_baseCount; float rad = 0.5f; float shift = rad * 2.0f; float centerx = shift * count / 2.0f; float centery = shift / 2.0f + 1.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.material.friction = 0.5f; float h = 0.5f; b2Polygon box = b2MakeRoundedBox( h, h, 0.0f ); int index = 0; for ( int i = 0; i < count; ++i ) { float y = i * shift + centery; for ( int j = i; j < count; ++j ) { float x = 0.5f * i * shift + ( j - i ) * shift - centerx; bodyDef.position = { x, y }; assert( index < e_maxBodyCount ); m_bodies[index] = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( m_bodies[index], &shapeDef, &box ); index += 1; } } m_bodyCount = index; m_wakeTotal = 0.0f; m_sleepTotal = 0.0f; } void Step() override { // These operations don't show up in b2Profile if ( m_stepCount > 20 ) { // Creating and destroying a joint will engage the island splitter. b2FilterJointDef jointDef = b2DefaultFilterJointDef(); jointDef.base.bodyIdA = m_bodies[0]; jointDef.base.bodyIdB = m_bodies[1]; b2JointId jointId = b2CreateFilterJoint( m_worldId, &jointDef ); uint64_t ticks = b2GetTicks(); // This will wake the island b2DestroyJoint( jointId, true ); m_wakeTotal += b2GetMillisecondsAndReset( &ticks ); // Put the island back to sleep. It must be split because a constraint was removed. b2Body_SetAwake( m_bodies[0], false ); m_sleepTotal += b2GetMillisecondsAndReset( &ticks ); int count = m_stepCount - 20; DrawTextLine( "wake ave = %g ms", m_wakeTotal / count ); DrawTextLine( "sleep ave = %g ms", m_sleepTotal / count ); } Sample::Step(); } static Sample* Create( SampleContext* context ) { return new BenchmarkSleep( context ); } b2BodyId m_bodies[e_maxBodyCount]; int m_bodyCount; int m_baseCount; float m_wakeTotal; float m_sleepTotal; bool m_awake; }; static int benchmarkSleep = RegisterSample( "Benchmark", "Sleep", BenchmarkSleep::Create ); class BenchmarkJointGrid : public Sample { public: explicit BenchmarkJointGrid( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 60.0f, -57.0f }; m_context->camera.zoom = 25.0f * 2.5f; m_context->enableSleep = false; } CreateJointGrid( m_worldId ); } static Sample* Create( SampleContext* context ) { return new BenchmarkJointGrid( context ); } }; static int benchmarkJointGridIndex = RegisterSample( "Benchmark", "Joint Grid", BenchmarkJointGrid::Create ); class BenchmarkSmash : public Sample { public: explicit BenchmarkSmash( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 60.0f, 6.0f }; m_context->camera.zoom = 25.0f * 1.6f; } CreateSmash( m_worldId ); } static Sample* Create( SampleContext* context ) { return new BenchmarkSmash( context ); } }; static int sampleSmash = RegisterSample( "Benchmark", "Smash", BenchmarkSmash::Create ); class BenchmarkCompound : public Sample { public: explicit BenchmarkCompound( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 18.0f, 115.0f }; m_context->camera.zoom = 25.0f * 5.5f; } float grid = 1.0f; #ifdef NDEBUG int height = 200; int width = 200; #else int height = 100; int width = 100; #endif { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); for ( int i = 0; i < height; ++i ) { float y = grid * i; for ( int j = i; j < width; ++j ) { float x = grid * j; b2Polygon square = b2MakeOffsetBox( 0.5f * grid, 0.5f * grid, { x, y }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &square ); } } for ( int i = 0; i < height; ++i ) { float y = grid * i; for ( int j = i; j < width; ++j ) { float x = -grid * j; b2Polygon square = b2MakeOffsetBox( 0.5f * grid, 0.5f * grid, { x, y }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &square ); } } } { #ifdef NDEBUG int span = 20; int count = 5; #else int span = 5; int count = 5; #endif b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; // defer mass properties to avoid n-squared mass computations b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.updateBodyMass = false; for ( int m = 0; m < count; ++m ) { float ybody = ( 100.0f + m * span ) * grid; for ( int n = 0; n < count; ++n ) { float xbody = -0.5f * grid * count * span + n * span * grid; bodyDef.position = { xbody, ybody }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); for ( int i = 0; i < span; ++i ) { float y = i * grid; for ( int j = 0; j < span; ++j ) { float x = j * grid; b2Polygon square = b2MakeOffsetBox( 0.5f * grid, 0.5f * grid, { x, y }, b2Rot_identity ); b2CreatePolygonShape( bodyId, &shapeDef, &square ); } } // All shapes have been added so I can efficiently compute the mass properties. b2Body_ApplyMassFromShapes( bodyId ); } } } } static Sample* Create( SampleContext* context ) { return new BenchmarkCompound( context ); } }; static int sampleCompound = RegisterSample( "Benchmark", "Compound", BenchmarkCompound::Create ); class BenchmarkKinematic : public Sample { public: explicit BenchmarkKinematic( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 0.0f }; m_context->camera.zoom = 150.0f; } float grid = 1.0f; #ifdef NDEBUG int span = 100; #else int span = 20; #endif b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_kinematicBody; bodyDef.angularVelocity = 1.0f; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.filter.categoryBits = 1; shapeDef.filter.maskBits = 2; // defer mass properties to avoid n-squared mass computations shapeDef.updateBodyMass = false; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); for ( int i = -span; i < span; ++i ) { float y = i * grid; for ( int j = -span; j < span; ++j ) { float x = j * grid; b2Polygon square = b2MakeOffsetBox( 0.5f * grid, 0.5f * grid, { x, y }, b2Rot_identity ); b2CreatePolygonShape( bodyId, &shapeDef, &square ); } } // All shapes have been added so I can efficiently compute the mass properties. b2Body_ApplyMassFromShapes( bodyId ); } static Sample* Create( SampleContext* context ) { return new BenchmarkKinematic( context ); } }; static int sampleKinematic = RegisterSample( "Benchmark", "Kinematic", BenchmarkKinematic::Create ); enum QueryType { e_rayCast, e_circleCast, e_overlap, }; class BenchmarkCast : public Sample { public: explicit BenchmarkCast( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 500.0f, 500.0f }; m_context->camera.zoom = 25.0f * 21.0f; // settings.drawShapes = m_isDebug; } m_queryType = e_circleCast; m_ratio = 5.0f; m_grid = 1.0f; m_fill = 0.1f; m_rowCount = m_isDebug ? 100 : 1000; m_columnCount = m_isDebug ? 100 : 1000; m_minTime = 1e6f; m_drawIndex = 0; m_topDown = false; m_buildTime = 0.0f; m_radius = 0.1f; g_randomSeed = 1234; int sampleCount = m_isDebug ? 100 : 10000; m_origins.resize( sampleCount ); m_translations.resize( sampleCount ); float extent = m_rowCount * m_grid; // Pre-compute rays to avoid randomizer overhead for ( int i = 0; i < sampleCount; ++i ) { b2Vec2 rayStart = RandomVec2( 0.0f, extent ); b2Vec2 rayEnd = RandomVec2( 0.0f, extent ); m_origins[i] = rayStart; m_translations[i] = rayEnd - rayStart; } BuildScene(); } void BuildScene() { g_randomSeed = 1234; b2DestroyWorld( m_worldId ); b2WorldDef worldDef = b2DefaultWorldDef(); m_worldId = b2CreateWorld( &worldDef ); uint64_t ticks = b2GetTicks(); b2BodyDef bodyDef = b2DefaultBodyDef(); b2ShapeDef shapeDef = b2DefaultShapeDef(); float y = 0.0f; for ( int i = 0; i < m_rowCount; ++i ) { float x = 0.0f; for ( int j = 0; j < m_columnCount; ++j ) { float fillTest = RandomFloatRange( 0.0f, 1.0f ); if ( fillTest <= m_fill ) { bodyDef.position = { x, y }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); float ratio = RandomFloatRange( 1.0f, m_ratio ); float halfWidth = RandomFloatRange( 0.05f, 0.25f ); b2Polygon box; if ( RandomFloat() > 0.0f ) { box = b2MakeBox( ratio * halfWidth, halfWidth ); } else { box = b2MakeBox( halfWidth, ratio * halfWidth ); } int category = RandomIntRange( 0, 2 ); shapeDef.filter.categoryBits = 1 << category; if ( category == 0 ) { shapeDef.material.customColor = b2_colorBox2DBlue; } else if ( category == 1 ) { shapeDef.material.customColor = b2_colorBox2DYellow; } else { shapeDef.material.customColor = b2_colorBox2DGreen; } b2CreatePolygonShape( bodyId, &shapeDef, &box ); } x += m_grid; } y += m_grid; } if ( m_topDown ) { b2World_RebuildStaticTree( m_worldId ); } m_buildTime = b2GetMilliseconds( ticks ); m_minTime = 1e6f; } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 17.0f * fontSize; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 13.0f * fontSize, height ) ); ImGui::Begin( "Cast", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 7.5f * fontSize ); bool changed = false; const char* queryTypes[] = { "Ray", "Circle", "Overlap" }; int queryType = int( m_queryType ); if ( ImGui::Combo( "Query", &queryType, queryTypes, IM_ARRAYSIZE( queryTypes ) ) ) { m_queryType = QueryType( queryType ); if ( m_queryType == e_overlap ) { m_radius = 5.0f; } else { m_radius = 0.1f; } changed = true; } if ( ImGui::SliderInt( "rows", &m_rowCount, 0, 1000, "%d" ) ) { changed = true; } if ( ImGui::SliderInt( "columns", &m_columnCount, 0, 1000, "%d" ) ) { changed = true; } if ( ImGui::SliderFloat( "fill", &m_fill, 0.0f, 1.0f, "%.2f" ) ) { changed = true; } if ( ImGui::SliderFloat( "grid", &m_grid, 0.5f, 2.0f, "%.2f" ) ) { changed = true; } if ( ImGui::SliderFloat( "ratio", &m_ratio, 1.0f, 10.0f, "%.2f" ) ) { changed = true; } if ( ImGui::Checkbox( "top down", &m_topDown ) ) { changed = true; } if ( ImGui::Button( "Draw Next" ) ) { m_drawIndex = ( m_drawIndex + 1 ) % m_origins.size(); } ImGui::PopItemWidth(); ImGui::End(); if ( changed ) { BuildScene(); } } struct CastResult { b2Vec2 point; float fraction; bool hit; }; static float CastCallback( b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context ) { CastResult* result = (CastResult*)context; result->point = point; result->fraction = fraction; result->hit = true; return fraction; } struct OverlapResult { b2Vec2 points[32]; int count; }; static bool OverlapCallback( b2ShapeId shapeId, void* context ) { OverlapResult* result = (OverlapResult*)context; if ( result->count < 32 ) { b2AABB aabb = b2Shape_GetAABB( shapeId ); result->points[result->count] = b2AABB_Center( aabb ); result->count += 1; } return true; } void Step() override { Sample::Step(); b2QueryFilter filter = b2DefaultQueryFilter(); filter.maskBits = 1; int hitCount = 0; int nodeVisits = 0; int leafVisits = 0; float ms = 0.0f; int sampleCount = (int)m_origins.size(); if ( m_queryType == e_rayCast ) { uint64_t ticks = b2GetTicks(); b2RayResult drawResult = {}; for ( int i = 0; i < sampleCount; ++i ) { b2Vec2 origin = m_origins[i]; b2Vec2 translation = m_translations[i]; b2RayResult result = b2World_CastRayClosest( m_worldId, origin, translation, filter ); if ( i == m_drawIndex ) { drawResult = result; } nodeVisits += result.nodeVisits; leafVisits += result.leafVisits; hitCount += result.hit ? 1 : 0; } ms = b2GetMilliseconds( ticks ); m_minTime = b2MinFloat( m_minTime, ms ); b2Vec2 p1 = m_origins[m_drawIndex]; b2Vec2 p2 = p1 + m_translations[m_drawIndex]; DrawLine( m_context->draw, p1, p2, b2_colorWhite ); DrawPoint( m_context->draw, p1, 5.0f, b2_colorGreen ); DrawPoint( m_context->draw, p2, 5.0f, b2_colorRed ); if ( drawResult.hit ) { DrawPoint( m_context->draw, drawResult.point, 5.0f, b2_colorWhite ); } } else if ( m_queryType == e_circleCast ) { uint64_t ticks = b2GetTicks(); CastResult drawResult = {}; for ( int i = 0; i < sampleCount; ++i ) { b2ShapeProxy proxy = b2MakeProxy( &m_origins[i], 1, m_radius ); b2Vec2 translation = m_translations[i]; CastResult result; b2TreeStats traversalResult = b2World_CastShape( m_worldId, &proxy, translation, filter, CastCallback, &result ); if ( i == m_drawIndex ) { drawResult = result; } nodeVisits += traversalResult.nodeVisits; leafVisits += traversalResult.leafVisits; hitCount += result.hit ? 1 : 0; } ms = b2GetMilliseconds( ticks ); m_minTime = b2MinFloat( m_minTime, ms ); b2Vec2 p1 = m_origins[m_drawIndex]; b2Vec2 p2 = p1 + m_translations[m_drawIndex]; DrawLine( m_context->draw, p1, p2, b2_colorWhite ); DrawPoint( m_context->draw, p1, 5.0f, b2_colorGreen ); DrawPoint( m_context->draw, p2, 5.0f, b2_colorRed ); if ( drawResult.hit ) { b2Vec2 t = b2Lerp( p1, p2, drawResult.fraction ); DrawCircle( m_context->draw, t, m_radius, b2_colorWhite ); DrawPoint( m_context->draw, drawResult.point, 5.0f, b2_colorWhite ); } } else if ( m_queryType == e_overlap ) { uint64_t ticks = b2GetTicks(); OverlapResult drawResult = {}; b2Vec2 extent = { m_radius, m_radius }; OverlapResult result = {}; for ( int i = 0; i < sampleCount; ++i ) { b2Vec2 origin = m_origins[i]; b2AABB aabb = { origin - extent, origin + extent }; result.count = 0; b2TreeStats traversalResult = b2World_OverlapAABB( m_worldId, aabb, filter, OverlapCallback, &result ); if ( i == m_drawIndex ) { drawResult = result; } nodeVisits += traversalResult.nodeVisits; leafVisits += traversalResult.leafVisits; hitCount += result.count; } ms = b2GetMilliseconds( ticks ); m_minTime = b2MinFloat( m_minTime, ms ); b2Vec2 origin = m_origins[m_drawIndex]; b2AABB aabb = { origin - extent, origin + extent }; DrawBounds( m_context->draw, aabb, b2_colorWhite ); for ( int i = 0; i < drawResult.count; ++i ) { DrawPoint( m_context->draw, drawResult.points[i], 5.0f, b2_colorHotPink ); } } DrawTextLine( "build time ms = %g", m_buildTime ); DrawTextLine( "hit count = %d, node visits = %d, leaf visits = %d", hitCount, nodeVisits, leafVisits ); DrawTextLine( "total ms = %.3f", ms ); DrawTextLine( "min total ms = %.3f", m_minTime ); float aveRayCost = 1000.0f * m_minTime / float( sampleCount ); DrawTextLine( "average us = %.2f", aveRayCost ); } static Sample* Create( SampleContext* context ) { return new BenchmarkCast( context ); } QueryType m_queryType; std::vector m_origins; std::vector m_translations; float m_minTime; float m_buildTime; int m_rowCount, m_columnCount; int m_updateType; int m_drawIndex; float m_radius; float m_fill; float m_ratio; float m_grid; bool m_topDown; }; static int sampleCast = RegisterSample( "Benchmark", "Cast", BenchmarkCast::Create ); class BenchmarkSpinner : public Sample { public: explicit BenchmarkSpinner( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 32.0f }; m_context->camera.zoom = 42.0f; } // b2_toiCalls = 0; // b2_toiHitCount = 0; CreateSpinner( m_worldId ); } void Step() override { Sample::Step(); if ( m_stepCount == 1000 && false ) { // 0.1 : 46544, 25752 // 0.25 : 5745, 1947 // 0.5 : 2197, 660 m_context->pause = true; } // DrawTextLine( "toi calls, hits = %d, %d", b2_toiCalls, b2_toiHitCount ); } static Sample* Create( SampleContext* context ) { return new BenchmarkSpinner( context ); } }; static int sampleSpinner = RegisterSample( "Benchmark", "Spinner", BenchmarkSpinner::Create ); class BenchmarkRain : public Sample { public: explicit BenchmarkRain( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 110.0f }; m_context->camera.zoom = 125.0f; m_context->enableSleep = true; } m_context->debugDraw.drawJoints = false; CreateRain( m_worldId ); } void Step() override { if ( m_context->pause == false || m_context->singleStep == true ) { StepRain( m_worldId, m_stepCount ); } Sample::Step(); if ( m_stepCount % 1000 == 0 ) { m_stepCount += 0; } } static Sample* Create( SampleContext* context ) { return new BenchmarkRain( context ); } }; static int benchmarkRain = RegisterSample( "Benchmark", "Rain", BenchmarkRain::Create ); class BenchmarkShapeDistance : public Sample { public: explicit BenchmarkShapeDistance( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 0.0f }; m_context->camera.zoom = 3.0f; } { b2Vec2 points[8] = {}; b2Rot q = b2MakeRot( 2.0f * B2_PI / 8.0f ); b2Vec2 p = { 0.5f, 0.0f }; points[0] = p; for ( int i = 1; i < 8; ++i ) { points[i] = b2RotateVector( q, points[i - 1] ); } b2Hull hull = b2ComputeHull( points, 8 ); m_polygonA = b2MakePolygon( &hull, 0.0f ); } { b2Vec2 points[8] = {}; b2Rot q = b2MakeRot( 2.0f * B2_PI / 8.0f ); b2Vec2 p = { 0.5f, 0.0f }; points[0] = p; for ( int i = 1; i < 8; ++i ) { points[i] = b2RotateVector( q, points[i - 1] ); } b2Hull hull = b2ComputeHull( points, 8 ); m_polygonB = b2MakePolygon( &hull, 0.1f ); } // todo arena m_transformAs = (b2Transform*)malloc( m_count * sizeof( b2Transform ) ); m_transformBs = (b2Transform*)malloc( m_count * sizeof( b2Transform ) ); m_outputs = (b2DistanceOutput*)calloc( m_count, sizeof( b2DistanceOutput ) ); g_randomSeed = 42; for ( int i = 0; i < m_count; ++i ) { m_transformAs[i] = { RandomVec2( -0.1f, 0.1f ), RandomRot() }; m_transformBs[i] = { RandomVec2( 0.25f, 2.0f ), RandomRot() }; } m_drawIndex = 0; m_minCycles = INT_MAX; m_minMilliseconds = FLT_MAX; } ~BenchmarkShapeDistance() override { free( m_transformAs ); free( m_transformBs ); free( m_outputs ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 5.0f * fontSize; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 17.0f * fontSize, height ) ); ImGui::Begin( "Benchmark: Shape Distance", nullptr, ImGuiWindowFlags_NoResize ); ImGui::SliderInt( "draw index", &m_drawIndex, 0, m_count - 1 ); ImGui::End(); } void Step() override { if ( m_context->pause == false || m_context->singleStep == true ) { b2DistanceInput input = {}; input.proxyA = b2MakeProxy( m_polygonA.vertices, m_polygonA.count, m_polygonA.radius ); input.proxyB = b2MakeProxy( m_polygonB.vertices, m_polygonB.count, m_polygonB.radius ); input.useRadii = true; int totalIterations = 0; uint64_t start = b2GetTicks(); uint64_t startCycles = GET_CYCLES; for ( int i = 0; i < m_count; ++i ) { b2SimplexCache cache = {}; input.transformA = m_transformAs[i]; input.transformB = m_transformBs[i]; m_outputs[i] = b2ShapeDistance( &input, &cache, nullptr, 0 ); totalIterations += m_outputs[i].iterations; } uint64_t endCycles = GET_CYCLES; float ms = b2GetMilliseconds( start ); m_minCycles = b2MinInt( m_minCycles, int( endCycles - startCycles ) ); m_minMilliseconds = b2MinFloat( m_minMilliseconds, ms ); DrawTextLine( "count = %d", m_count ); DrawTextLine( "min cycles = %d", m_minCycles ); DrawTextLine( "ave cycles = %g", float( m_minCycles ) / float( m_count ) ); DrawTextLine( "min ms = %g, ave us = %g", m_minMilliseconds, 1000.0f * m_minMilliseconds / float( m_count ) ); DrawTextLine( "average iterations = %g", totalIterations / float( m_count ) ); } b2Transform xfA = m_transformAs[m_drawIndex]; b2Transform xfB = m_transformBs[m_drawIndex]; b2DistanceOutput output = m_outputs[m_drawIndex]; DrawSolidPolygon( m_context->draw, xfA, m_polygonA.vertices, m_polygonA.count, m_polygonA.radius, b2_colorBox2DGreen ); DrawSolidPolygon( m_context->draw, xfB, m_polygonB.vertices, m_polygonB.count, m_polygonB.radius, b2_colorBox2DBlue ); DrawLine( m_context->draw, output.pointA, output.pointB, b2_colorDimGray ); DrawPoint( m_context->draw, output.pointA, 10.0f, b2_colorWhite ); DrawPoint( m_context->draw, output.pointB, 10.0f, b2_colorWhite ); DrawLine( m_context->draw, output.pointA, output.pointA + 0.5f * output.normal, b2_colorYellow ); DrawTextLine( "distance = %g", output.distance ); Sample::Step(); } static Sample* Create( SampleContext* context ) { return new BenchmarkShapeDistance( context ); } static constexpr int m_count = m_isDebug ? 100 : 10000; b2Transform* m_transformAs; b2Transform* m_transformBs; b2DistanceOutput* m_outputs; b2Polygon m_polygonA; b2Polygon m_polygonB; float m_minMilliseconds; int m_drawIndex; int m_minCycles; }; static int benchmarkShapeDistance = RegisterSample( "Benchmark", "Shape Distance", BenchmarkShapeDistance::Create ); struct ShapeUserData { int row; bool active; }; class BenchmarkSensor : public Sample { public: explicit BenchmarkSensor( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 105.0f }; m_context->camera.zoom = 125.0f; } b2World_SetCustomFilterCallback( m_worldId, FilterFcn, this ); m_activeSensor.row = 0; m_activeSensor.active = true; b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); { float gridSize = 3.0f; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.isSensor = true; shapeDef.enableSensorEvents = true; shapeDef.userData = &m_activeSensor; float y = 0.0f; float x = -40.0f * gridSize; for ( int i = 0; i < 81; ++i ) { b2Polygon box = b2MakeOffsetBox( 0.5f * gridSize, 0.5f * gridSize, { x, y }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); x += gridSize; } } g_randomSeed = 42; float shift = 5.0f; float xCenter = 0.5f * shift * m_columnCount; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.isSensor = true; shapeDef.enableSensorEvents = true; float yStart = 10.0f; m_filterRow = m_rowCount >> 1; for ( int j = 0; j < m_rowCount; ++j ) { m_passiveSensors[j].row = j; m_passiveSensors[j].active = false; shapeDef.userData = m_passiveSensors + j; if ( j == m_filterRow ) { shapeDef.enableCustomFiltering = true; shapeDef.material.customColor = b2_colorFuchsia; } else { shapeDef.enableCustomFiltering = false; shapeDef.material.customColor = 0; } float y = j * shift + yStart; for ( int i = 0; i < m_columnCount; ++i ) { float x = i * shift - xCenter; b2Polygon box = b2MakeOffsetRoundedBox( 0.5f, 0.5f, { x, y }, b2Rot_identity, 0.1f ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } } m_maxBeginCount = 0; m_maxEndCount = 0; m_lastStepCount = 0; } void CreateRow( float y ) { float shift = 5.0f; float xCenter = 0.5f * shift * m_columnCount; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.gravityScale = 0.0f; bodyDef.linearVelocity = { 0.0f, -5.0f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.enableSensorEvents = true; b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; for ( int i = 0; i < m_columnCount; ++i ) { // stagger bodies to avoid bunching up events into a single update float yOffset = RandomFloatRange( -1.0f, 1.0f ); bodyDef.position = { shift * i - xCenter, y + yOffset }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreateCircleShape( bodyId, &shapeDef, &circle ); } } void Step() override { Sample::Step(); if ( m_stepCount == m_lastStepCount ) { return; } std::set zombies; b2SensorEvents events = b2World_GetSensorEvents( m_worldId ); for ( int i = 0; i < events.beginCount; ++i ) { b2SensorBeginTouchEvent* event = events.beginEvents + i; // shapes on begin touch are always valid ShapeUserData* userData = static_cast( b2Shape_GetUserData( event->sensorShapeId ) ); if ( userData->active ) { zombies.emplace( b2Shape_GetBody( event->visitorShapeId ) ); } else { // Check custom filter correctness assert( userData->row != m_filterRow ); // Modify color while overlapped with a sensor b2SurfaceMaterial surfaceMaterial = b2Shape_GetSurfaceMaterial( event->visitorShapeId ); surfaceMaterial.customColor = b2_colorLime; b2Shape_SetSurfaceMaterial( event->visitorShapeId, &surfaceMaterial ); } } for ( int i = 0; i < events.endCount; ++i ) { b2SensorEndTouchEvent* event = events.endEvents + i; if ( b2Shape_IsValid( event->visitorShapeId ) == false ) { continue; } // Restore color to default b2SurfaceMaterial surfaceMaterial = b2Shape_GetSurfaceMaterial( event->visitorShapeId ); surfaceMaterial.customColor = 0; b2Shape_SetSurfaceMaterial( event->visitorShapeId, &surfaceMaterial ); } for ( b2BodyId bodyId : zombies ) { b2DestroyBody( bodyId ); } int delay = 0x1F; if ( ( m_stepCount & delay ) == 0 ) { CreateRow( 10.0f + m_rowCount * 5.0f ); } m_lastStepCount = m_stepCount; m_maxBeginCount = b2MaxInt( events.beginCount, m_maxBeginCount ); m_maxEndCount = b2MaxInt( events.endCount, m_maxEndCount ); DrawTextLine( "max begin touch events = %d", m_maxBeginCount ); DrawTextLine( "max end touch events = %d", m_maxEndCount ); } bool Filter( b2ShapeId idA, b2ShapeId idB ) { ShapeUserData* userData = nullptr; if ( b2Shape_IsSensor( idA ) ) { userData = (ShapeUserData*)b2Shape_GetUserData( idA ); } else if ( b2Shape_IsSensor( idB ) ) { userData = (ShapeUserData*)b2Shape_GetUserData( idB ); } if ( userData != nullptr ) { return userData->active == true || userData->row != m_filterRow; } return true; } static bool FilterFcn( b2ShapeId idA, b2ShapeId idB, void* context ) { BenchmarkSensor* self = (BenchmarkSensor*)context; return self->Filter( idA, idB ); } static Sample* Create( SampleContext* context ) { return new BenchmarkSensor( context ); } static constexpr int m_columnCount = 40; static constexpr int m_rowCount = 40; int m_maxBeginCount; int m_maxEndCount; ShapeUserData m_passiveSensors[m_rowCount]; ShapeUserData m_activeSensor; int m_lastStepCount; int m_filterRow; }; static int benchmarkSensor = RegisterSample( "Benchmark", "Sensor", BenchmarkSensor::Create ); // This benchmark pushes Box2D to the limit for a large pile. It terminates once simulation is deemed to be slow. // The higher the body count achieved, the better. // Note: this benchmark stresses the sleep system more than any other benchmark. Better results are achieved if sleeping // is disabled. class BenchmarkCapacity : public Sample { public: explicit BenchmarkCapacity( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 150.0f }; m_context->camera.zoom = 200.0f; } m_context->enableSleep = false; { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position.y = -5.0f; b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 800.0f, 5.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( groundId, &shapeDef, &box ); } m_square = b2MakeSquare( 0.5f ); m_done = false; m_reachCount = 0; } void Step() override { Sample::Step(); float millisecondLimit = 20.0f; b2Profile profile = b2World_GetProfile( m_worldId ); if ( profile.step > millisecondLimit ) { m_reachCount += 1; if ( m_reachCount > 60 ) { // Hit the millisecond limit 60 times in a row m_done = true; } } else { m_reachCount = 0; } if ( m_done == true ) { return; } if ( ( m_stepCount & 0x1F ) != 0x1F ) { return; } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position.y = 200.0f; b2ShapeDef shapeDef = b2DefaultShapeDef(); int count = 200; float x = -1.0f * count; for ( int i = 0; i < count; ++i ) { bodyDef.position.x = x; bodyDef.position.y += 0.5f; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &m_square ); x += 2.0f; } } static Sample* Create( SampleContext* context ) { return new BenchmarkCapacity( context ); } b2Polygon m_square; int m_reachCount; bool m_done; }; static int benchmarkCapacity = RegisterSample( "Benchmark", "Capacity", BenchmarkCapacity::Create ); ================================================ FILE: samples/sample_bodies.cpp ================================================ // SPDX-FileCopyrightText: 2022 Erin Catto // SPDX-License-Identifier: MIT #include "draw.h" #include "sample.h" #include "box2d/box2d.h" #include class BodyType : public Sample { public: explicit BodyType( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.8f, 6.4f }; m_context->camera.zoom = 25.0f * 0.4f; } m_type = b2_staticBody; m_isEnabled = true; b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.name = "ground"; groundId = b2CreateBody( m_worldId, &bodyDef ); b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Define attachment { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -2.0f, 3.0f }; bodyDef.name = "attach1"; m_attachmentId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 0.5f, 2.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; b2CreatePolygonShape( m_attachmentId, &shapeDef, &box ); } // Define second attachment { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = m_type; bodyDef.isEnabled = m_isEnabled; bodyDef.position = { 3.0f, 3.0f }; bodyDef.name = "attach2"; m_secondAttachmentId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 0.5f, 2.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; b2CreatePolygonShape( m_secondAttachmentId, &shapeDef, &box ); } // Define platform { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = m_type; bodyDef.isEnabled = m_isEnabled; bodyDef.position = { -4.0f, 5.0f }; bodyDef.name = "platform"; m_platformId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeOffsetBox( 0.5f, 4.0f, { 4.0f, 0.0f }, b2MakeRot( 0.5f * B2_PI ) ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 2.0f; b2CreatePolygonShape( m_platformId, &shapeDef, &box ); b2RevoluteJointDef revoluteDef = b2DefaultRevoluteJointDef(); b2Vec2 pivot = { -2.0f, 5.0f }; revoluteDef.base.bodyIdA = m_attachmentId; revoluteDef.base.bodyIdB = m_platformId; revoluteDef.base.localFrameA.p = b2Body_GetLocalPoint( m_attachmentId, pivot ); revoluteDef.base.localFrameB.p = b2Body_GetLocalPoint( m_platformId, pivot ); revoluteDef.maxMotorTorque = 50.0f; revoluteDef.enableMotor = true; b2CreateRevoluteJoint( m_worldId, &revoluteDef ); pivot = { 3.0f, 5.0f }; revoluteDef.base.bodyIdA = m_secondAttachmentId; revoluteDef.base.bodyIdB = m_platformId; revoluteDef.base.localFrameA.p = b2Body_GetLocalPoint( m_secondAttachmentId, pivot ); revoluteDef.base.localFrameB.p = b2Body_GetLocalPoint( m_platformId, pivot ); revoluteDef.maxMotorTorque = 50.0f; revoluteDef.enableMotor = true; b2CreateRevoluteJoint( m_worldId, &revoluteDef ); b2PrismaticJointDef prismaticDef = b2DefaultPrismaticJointDef(); b2Vec2 anchor = { 0.0f, 5.0f }; prismaticDef.base.bodyIdA = groundId; prismaticDef.base.bodyIdB = m_platformId; prismaticDef.base.localFrameA.p = b2Body_GetLocalPoint( groundId, anchor ); prismaticDef.base.localFrameB.p = b2Body_GetLocalPoint( m_platformId, anchor ); prismaticDef.maxMotorForce = 1000.0f; prismaticDef.motorSpeed = 0.0f; prismaticDef.enableMotor = true; prismaticDef.lowerTranslation = -10.0f; prismaticDef.upperTranslation = 10.0f; prismaticDef.enableLimit = true; b2CreatePrismaticJoint( m_worldId, &prismaticDef ); m_speed = 3.0f; } // Create a payload { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -3.0f, 8.0f }; bodyDef.name = "crate1"; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 0.75f, 0.75f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 2.0f; b2CreatePolygonShape( bodyId, &shapeDef, &box ); } // Create a second payload { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = m_type; bodyDef.isEnabled = m_isEnabled; bodyDef.position = { 2.0f, 8.0f }; bodyDef.name = "crate2"; m_secondPayloadId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 0.75f, 0.75f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 2.0f; b2CreatePolygonShape( m_secondPayloadId, &shapeDef, &box ); } // Create a separate body on the ground { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = m_type; bodyDef.isEnabled = m_isEnabled; bodyDef.position = { 8.0f, 0.2f }; bodyDef.name = "debris"; m_touchingBodyId = b2CreateBody( m_worldId, &bodyDef ); b2Capsule capsule = { { 0.0f, 0.0f }, { 1.0f, 0.0f }, 0.25f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 2.0f; b2CreateCapsuleShape( m_touchingBodyId, &shapeDef, &capsule ); } // Create a separate body on the ground { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_staticBody; bodyDef.isEnabled = m_isEnabled; bodyDef.position = { 8.5f, 0.2f }; bodyDef.name = "debris"; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Capsule capsule = { { 0.0f, 0.0f }, { 1.0f, 0.0f }, 0.5f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); } // Create a separate floating body { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = m_type; bodyDef.isEnabled = m_isEnabled; bodyDef.position = { -8.0f, 12.0f }; bodyDef.gravityScale = 0.0f; bodyDef.name = "floater"; m_floatingBodyId = b2CreateBody( m_worldId, &bodyDef ); b2Circle circle = { { 0.0f, 0.5f }, 0.25f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 2.0f; b2CreateCircleShape( m_floatingBodyId, &shapeDef, &circle ); } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 11.0f * fontSize; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 9.0f * fontSize, height ) ); ImGui::Begin( "Body Type", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); if ( ImGui::RadioButton( "Static", m_type == b2_staticBody ) ) { m_type = b2_staticBody; b2Body_SetType( m_platformId, b2_staticBody ); b2Body_SetType( m_secondAttachmentId, b2_staticBody ); b2Body_SetType( m_secondPayloadId, b2_staticBody ); b2Body_SetType( m_touchingBodyId, b2_staticBody ); b2Body_SetType( m_floatingBodyId, b2_staticBody ); } if ( ImGui::RadioButton( "Kinematic", m_type == b2_kinematicBody ) ) { m_type = b2_kinematicBody; b2Body_SetType( m_platformId, b2_kinematicBody ); b2Body_SetLinearVelocity( m_platformId, { -m_speed, 0.0f } ); b2Body_SetAngularVelocity( m_platformId, 0.0f ); b2Body_SetType( m_secondAttachmentId, b2_kinematicBody ); b2Body_SetLinearVelocity(m_secondAttachmentId, b2Vec2_zero); b2Body_SetAngularVelocity(m_secondAttachmentId, 0.0f); b2Body_SetType( m_secondPayloadId, b2_kinematicBody ); b2Body_SetType( m_touchingBodyId, b2_kinematicBody ); b2Body_SetType( m_floatingBodyId, b2_kinematicBody ); } if ( ImGui::RadioButton( "Dynamic", m_type == b2_dynamicBody ) ) { m_type = b2_dynamicBody; b2Body_SetType( m_platformId, b2_dynamicBody ); b2Body_SetType( m_secondAttachmentId, b2_dynamicBody ); b2Body_SetType( m_secondPayloadId, b2_dynamicBody ); b2Body_SetType( m_touchingBodyId, b2_dynamicBody ); b2Body_SetType( m_floatingBodyId, b2_dynamicBody ); } if ( ImGui::Checkbox( "Enable", &m_isEnabled ) ) { if ( m_isEnabled ) { b2Body_Enable( m_attachmentId ); b2Body_Enable( m_secondPayloadId ); b2Body_Enable( m_floatingBodyId ); } else { b2Body_Disable( m_attachmentId ); b2Body_Disable( m_secondPayloadId ); b2Body_Disable( m_floatingBodyId ); } } ImGui::End(); } void Step() override { // Drive the kinematic body. if ( m_type == b2_kinematicBody ) { b2Vec2 p = b2Body_GetPosition( m_platformId ); b2Vec2 v = b2Body_GetLinearVelocity( m_platformId ); if ( ( p.x < -14.0f && v.x < 0.0f ) || ( p.x > 6.0f && v.x > 0.0f ) ) { v.x = -v.x; b2Body_SetLinearVelocity( m_platformId, v ); } } Sample::Step(); } static Sample* Create( SampleContext* context ) { return new BodyType( context ); } b2BodyId m_attachmentId; b2BodyId m_secondAttachmentId; b2BodyId m_platformId; b2BodyId m_secondPayloadId; b2BodyId m_touchingBodyId; b2BodyId m_floatingBodyId; b2BodyType m_type; float m_speed; bool m_isEnabled; }; static int sampleBodyType = RegisterSample( "Bodies", "Body Type", BodyType::Create ); float FrictionCallback( float, uint64_t, float, uint64_t ) { return 0.1f; } float RestitutionCallback( float, uint64_t, float, uint64_t ) { return 1.0f; } class Weeble : public Sample { public: explicit Weeble( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 2.3f, 10.0f }; m_context->camera.zoom = 25.0f * 0.5f; } // Test friction and restitution callbacks b2World_SetFrictionCallback( m_worldId, FrictionCallback ); b2World_SetRestitutionCallback( m_worldId, RestitutionCallback ); b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Build weeble { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 0.0f, 3.0f }; bodyDef.rotation = b2MakeRot( 0.25f * B2_PI ); m_weebleId = b2CreateBody( m_worldId, &bodyDef ); b2Capsule capsule = { { 0.0f, -1.0f }, { 0.0f, 1.0f }, 1.0f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreateCapsuleShape( m_weebleId, &shapeDef, &capsule ); float mass = b2Body_GetMass( m_weebleId ); float inertiaTensor = b2Body_GetRotationalInertia( m_weebleId ); float offset = 1.5f; // See: https://en.wikipedia.org/wiki/Parallel_axis_theorem inertiaTensor += mass * offset * offset; b2MassData massData = { mass, { 0.0f, -offset }, inertiaTensor }; b2Body_SetMassData( m_weebleId, massData ); } m_explosionPosition = { 0.0f, 0.0f }; m_explosionRadius = 2.0f; m_explosionMagnitude = 8.0f; } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 120.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); ImGui::Begin( "Weeble", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); if ( ImGui::Button( "Teleport" ) ) { b2Body_SetTransform( m_weebleId, { 0.0f, 5.0f }, b2MakeRot( 0.95 * B2_PI ) ); } if ( ImGui::Button( "Explode" ) ) { b2ExplosionDef def = b2DefaultExplosionDef(); def.position = m_explosionPosition; def.radius = m_explosionRadius; def.falloff = 0.1f; def.impulsePerLength = m_explosionMagnitude; b2World_Explode( m_worldId, &def ); } ImGui::PushItemWidth( 100.0f ); ImGui::SliderFloat( "Magnitude", &m_explosionMagnitude, -100.0f, 100.0f, "%.1f" ); ImGui::PopItemWidth(); ImGui::End(); } void Step() override { Sample::Step(); DrawCircle( m_context->draw, m_explosionPosition, m_explosionRadius, b2_colorAzure ); // This shows how to get the velocity of a point on a body b2Vec2 localPoint = { 0.0f, 2.0f }; b2Vec2 worldPoint = b2Body_GetWorldPoint( m_weebleId, localPoint ); b2Vec2 v1 = b2Body_GetLocalPointVelocity( m_weebleId, localPoint ); b2Vec2 v2 = b2Body_GetWorldPointVelocity( m_weebleId, worldPoint ); b2Vec2 offset = { 0.05f, 0.0f }; DrawLine(m_context->draw, worldPoint, worldPoint + v1, b2_colorRed ); DrawLine(m_context->draw, worldPoint + offset, worldPoint + v2 + offset, b2_colorGreen ); } static Sample* Create( SampleContext* context ) { return new Weeble( context ); } b2BodyId m_weebleId; b2Vec2 m_explosionPosition; float m_explosionRadius; float m_explosionMagnitude; }; static int sampleWeeble = RegisterSample( "Bodies", "Weeble", Weeble::Create ); class Sleep : public Sample { public: explicit Sleep( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 3.0f, 50.0f }; m_context->camera.zoom = 25.0f * 2.2f; } b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); b2Segment segment = { { -40.0f, 0.0f }, { 40.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.enableSensorEvents = true; m_groundShapeId = b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Sleeping body with sensors for ( int i = 0; i < 2; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -4.0f, 3.0f + 2.0f * i }; bodyDef.isAwake = false; bodyDef.enableSleep = true; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Capsule capsule = { { 0.0f, 1.0f }, { 1.0f, 1.0f }, 0.75f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); shapeDef.isSensor = true; shapeDef.enableSensorEvents = true; capsule.radius = 1.0f; m_sensorIds[i] = b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); m_sensorTouching[i] = false; } // Sleeping body but sleep is disabled { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 0.0f, 3.0f }; bodyDef.isAwake = false; bodyDef.enableSleep = false; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Circle circle = { { 1.0f, 1.0f }, 1.0f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreateCircleShape( bodyId, &shapeDef, &circle ); } // Awake body and sleep is disabled { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 5.0f, 3.0f }; bodyDef.isAwake = true; bodyDef.enableSleep = false; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeOffsetBox( 1.0f, 1.0f, { 0.0f, 1.0f }, b2MakeRot( 0.25f * B2_PI ) ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } // A sleeping body to test waking on collision { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 5.0f, 1.0f }; bodyDef.isAwake = false; bodyDef.enableSleep = true; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeSquare( 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } // A long pendulum { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 0.0f, 100.0f }; bodyDef.angularDamping = 0.5f; bodyDef.sleepThreshold = 0.05f; m_pendulumId = b2CreateBody( m_worldId, &bodyDef ); b2Capsule capsule = { { 0.0f, 0.0f }, { 90.0f, 0.0f }, 0.25f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreateCapsuleShape( m_pendulumId, &shapeDef, &capsule ); b2Vec2 pivot = bodyDef.position; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = m_pendulumId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); b2CreateRevoluteJoint( m_worldId, &jointDef ); } // A sleeping body to test waking on contact destroyed { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -10.0f, 1.0f }; bodyDef.isAwake = false; bodyDef.enableSleep = true; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeSquare( 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } m_staticBodyId = b2_nullBodyId; } void ToggleInvoker() { if ( B2_IS_NULL( m_staticBodyId ) ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { -10.5f, 3.0f }; m_staticBodyId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeOffsetBox( 2.0f, 0.1f, { 0.0f, 0.0f }, b2MakeRot( 0.25f * B2_PI ) ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.invokeContactCreation = true; b2CreatePolygonShape( m_staticBodyId, &shapeDef, &box ); } else { b2DestroyBody( m_staticBodyId ); m_staticBodyId = b2_nullBodyId; } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 160.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Sleep", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 120.0f ); ImGui::Text( "Pendulum Tuning" ); float sleepVelocity = b2Body_GetSleepThreshold( m_pendulumId ); if ( ImGui::SliderFloat( "sleep velocity", &sleepVelocity, 0.0f, 1.0f, "%.2f" ) ) { b2Body_SetSleepThreshold( m_pendulumId, sleepVelocity ); b2Body_SetAwake( m_pendulumId, true ); } float angularDamping = b2Body_GetAngularDamping( m_pendulumId ); if ( ImGui::SliderFloat( "angular damping", &angularDamping, 0.0f, 2.0f, "%.2f" ) ) { b2Body_SetAngularDamping( m_pendulumId, angularDamping ); } ImGui::PopItemWidth(); ImGui::Separator(); if ( B2_IS_NULL( m_staticBodyId ) ) { if ( ImGui::Button( "Create" ) ) { ToggleInvoker(); } } else { if ( ImGui::Button( "Destroy" ) ) { ToggleInvoker(); } } ImGui::End(); } void Step() override { Sample::Step(); // Detect sensors touching the ground b2SensorEvents sensorEvents = b2World_GetSensorEvents( m_worldId ); for ( int i = 0; i < sensorEvents.beginCount; ++i ) { b2SensorBeginTouchEvent* event = sensorEvents.beginEvents + i; if ( B2_ID_EQUALS( event->visitorShapeId, m_groundShapeId ) ) { if ( B2_ID_EQUALS( event->sensorShapeId, m_sensorIds[0] ) ) { m_sensorTouching[0] = true; } else if ( B2_ID_EQUALS( event->sensorShapeId, m_sensorIds[1] ) ) { m_sensorTouching[1] = true; } } } for ( int i = 0; i < sensorEvents.endCount; ++i ) { b2SensorEndTouchEvent* event = sensorEvents.endEvents + i; if ( B2_ID_EQUALS( event->visitorShapeId, m_groundShapeId ) ) { if ( B2_ID_EQUALS( event->sensorShapeId, m_sensorIds[0] ) ) { m_sensorTouching[0] = false; } else if ( B2_ID_EQUALS( event->sensorShapeId, m_sensorIds[1] ) ) { m_sensorTouching[1] = false; } } } for ( int i = 0; i < 2; ++i ) { DrawTextLine( "sensor touch %d = %s", i, m_sensorTouching[i] ? "true" : "false" ); } } static Sample* Create( SampleContext* context ) { return new Sleep( context ); } b2BodyId m_pendulumId; b2BodyId m_staticBodyId; b2ShapeId m_groundShapeId; b2ShapeId m_sensorIds[2]; bool m_sensorTouching[2]; }; static int sampleSleep = RegisterSample( "Bodies", "Sleep", Sleep::Create ); class BadBody : public Sample { public: explicit BadBody( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 2.3f, 10.0f }; m_context->camera.zoom = 25.0f * 0.5f; } b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Build a bad body { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 0.0f, 3.0f }; bodyDef.angularVelocity = 0.5f; bodyDef.rotation = b2MakeRot( 0.25f * B2_PI ); m_badBodyId = b2CreateBody( m_worldId, &bodyDef ); b2Capsule capsule = { { 0.0f, -1.0f }, { 0.0f, 1.0f }, 1.0f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); // density set to zero intentionally to create a bad body shapeDef.density = 0.0f; b2CreateCapsuleShape( m_badBodyId, &shapeDef, &capsule ); } // Build a normal body { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 2.0f, 3.0f }; bodyDef.rotation = b2MakeRot( 0.25f * B2_PI ); b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Capsule capsule = { { 0.0f, -1.0f }, { 0.0f, 1.0f }, 1.0f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); } } void Step() override { Sample::Step(); DrawTextLine("A bad body is a dynamic body with no mass and behaves like a kinematic body." ); DrawTextLine( "Bad bodies are considered invalid and a user bug. Behavior is not guaranteed." ); // For science b2Body_ApplyForceToCenter( m_badBodyId, { 0.0f, 10.0f }, true ); } static Sample* Create( SampleContext* context ) { return new BadBody( context ); } b2BodyId m_badBodyId; }; static int sampleBadBody = RegisterSample( "Bodies", "Bad", BadBody::Create ); // This shows how to set the initial angular velocity to get a specific movement. class Pivot : public Sample { public: explicit Pivot( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.8f, 6.4f }; m_context->camera.zoom = 25.0f * 0.4f; } b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Create a separate body on the ground { b2Vec2 v = { 5.0f, 0.0f }; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 0.0f, 3.0f }; bodyDef.gravityScale = 1.0f; bodyDef.linearVelocity = v; m_bodyId = b2CreateBody( m_worldId, &bodyDef ); m_lever = 3.0f; b2Vec2 r = { 0.0f, -m_lever }; float omega = b2Cross( v, r ) / b2Dot( r, r ); b2Body_SetAngularVelocity( m_bodyId, omega ); b2Polygon box = b2MakeBox( 0.1f, m_lever ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( m_bodyId, &shapeDef, &box ); } } void Step() override { Sample::Step(); b2Vec2 v = b2Body_GetLinearVelocity( m_bodyId ); float omega = b2Body_GetAngularVelocity( m_bodyId ); b2Vec2 r = b2Body_GetWorldVector( m_bodyId, { 0.0f, -m_lever } ); b2Vec2 vp = v + b2CrossSV( omega, r ); DrawTextLine( "pivot velocity = (%g, %g)", vp.x, vp.y ); } static Sample* Create( SampleContext* context ) { return new Pivot( context ); } b2BodyId m_bodyId; float m_lever; }; static int samplePivot = RegisterSample( "Bodies", "Pivot", Pivot::Create ); // This shows how to drive a kinematic body to reach a target class Kinematic : public Sample { public: explicit Kinematic( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 0.0f }; m_context->camera.zoom = 4.0f; } m_amplitude = 2.0f; { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_kinematicBody; bodyDef.position.x = 2.0f * m_amplitude; m_bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 0.1f, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( m_bodyId, &shapeDef, &box ); } m_time = 0.0f; } void Step() override { float timeStep = m_context->hertz > 0.0f ? 1.0f / m_context->hertz : 0.0f; if ( m_context->pause && m_context->singleStep == false ) { timeStep = 0.0f; } if ( timeStep > 0.0f ) { b2Vec2 point = { .x = 2.0f * m_amplitude * cosf( m_time ), .y = m_amplitude * sinf( 2.0f * m_time ), }; b2Rot rotation = b2MakeRot( 2.0f * m_time ); b2Vec2 axis = b2RotateVector( rotation, { 0.0f, 1.0f } ); DrawLine( m_context->draw, point - 0.5f * axis, point + 0.5f * axis, b2_colorPlum ); DrawPoint( m_context->draw, point, 10.0f, b2_colorPlum ); bool wake = true; b2Body_SetTargetTransform( m_bodyId, { point, rotation }, timeStep, wake ); } Sample::Step(); m_time += timeStep; } static Sample* Create( SampleContext* context ) { return new Kinematic( context ); } b2BodyId m_bodyId; float m_amplitude; float m_time; }; static int sampleKinematic = RegisterSample( "Bodies", "Kinematic", Kinematic::Create ); // Motion locking can be a bit squishy class MixedLocks : public Sample { public: explicit MixedLocks( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 2.5f }; m_context->camera.zoom = 3.5f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -40.0, 0.0f }, { 40.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } b2Polygon box = b2MakeSquare( 0.5f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 2.0f, 1.0f }; bodyDef.name = "static"; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 1.0f, 1.0f }; bodyDef.name = "free"; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 1.0f, 3.0f }; bodyDef.name = "free"; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -1.0f, 1.0f }; bodyDef.motionLocks.angularZ = true; bodyDef.name = "angular z"; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -2.0f, 2.0f }; bodyDef.motionLocks.linearX = true; bodyDef.name = "linear x"; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -1.0f, 2.5f }; bodyDef.motionLocks.linearY = true; bodyDef.motionLocks.angularZ = true; bodyDef.name = "lin y ang z"; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 0.0f, 1.0f }; bodyDef.motionLocks.linearX = true; bodyDef.motionLocks.linearY = true; bodyDef.motionLocks.angularZ = true; bodyDef.name = "full"; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } static Sample* Create( SampleContext* context ) { return new MixedLocks( context ); } }; static int sampleMixedLocks = RegisterSample( "Bodies", "Mixed Locks", MixedLocks::Create ); class SetVelocity : public Sample { public: explicit SetVelocity( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 2.5f }; m_context->camera.zoom = 3.5f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, -0.25f }; b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeBox( 20.0f, 0.25f ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeSquare( 0.5f ); bodyDef.position = { 0.0f, 0.5f }; m_bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( m_bodyId, &shapeDef, &box ); } } void Step() override { Sample::Step(); b2Body_SetLinearVelocity( m_bodyId, { 0.0f, -20.0f } ); b2Vec2 position = b2Body_GetPosition( m_bodyId ); DrawTextLine( "(x, y) = (%.2g, %.2g)", position.x, position.y ); } static Sample* Create( SampleContext* context ) { return new SetVelocity( context ); } b2BodyId m_bodyId; }; static int sampleSetVelocity = RegisterSample( "Bodies", "Set Velocity", SetVelocity::Create ); class WakeTouching : public Sample { public: explicit WakeTouching( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 4.0f }; m_context->camera.zoom = 8.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); m_groundId = b2CreateBody( m_worldId, &bodyDef ); b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreateSegmentShape( m_groundId, &shapeDef, &segment ); } b2Polygon box = b2MakeBox( 0.5f, 0.5f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; float x = -1.0f * ( m_count - 1 ); for ( int i = 0; i < m_count; ++i ) { bodyDef.position = { x, 4.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); x += 2.0f; } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 5.0f * fontSize; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 10.0f * fontSize, height ) ); ImGui::Begin( "Wake Touching", nullptr, ImGuiWindowFlags_NoResize ); if ( ImGui::Button( "Wake Touching" ) ) { b2Body_WakeTouching( m_groundId ); } ImGui::End(); } static Sample* Create( SampleContext* context ) { return new WakeTouching( context ); } static constexpr int m_count = 10; b2BodyId m_groundId; }; static int sampleWakeTouching = RegisterSample( "Bodies", "Wake Touching", WakeTouching::Create ); ================================================ FILE: samples/sample_character.cpp ================================================ // SPDX-FileCopyrightText: 2022 Erin Catto // SPDX-License-Identifier: MIT #include "draw.h" #include "sample.h" #include "box2d/box2d.h" #include "box2d/math_functions.h" #include #include struct ShapeUserData { float maxPush; bool clipVelocity; }; enum CollisionBits : uint64_t { StaticBit = 0x0001, MoverBit = 0x0002, DynamicBit = 0x0004, DebrisBit = 0x0008, AllBits = ~0u, }; enum PogoShape { PogoPoint, PogoCircle, PogoSegment }; struct CastResult { b2Vec2 point; b2Vec2 normal; b2BodyId bodyId; float fraction; bool hit; }; static float CastCallback( b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context ) { CastResult* result = (CastResult*)context; result->point = point; result->normal = normal; result->bodyId = b2Shape_GetBody( shapeId ); result->fraction = fraction; result->hit = true; return fraction; } class Mover : public Sample { public: explicit Mover( SampleContext* context ) : Sample( context ) { if ( context->restart == false ) { m_camera->center = { 20.0f, 9.0f }; m_camera->zoom = 10.0f; } context->debugDraw.drawJoints = false; m_transform = { { 2.0f, 8.0f }, b2Rot_identity }; m_velocity = { 0.0f, 0.0f }; m_capsule = { { 0.0f, -0.5f }, { 0.0f, 0.5f }, 0.3f }; b2BodyId groundId1; { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, 0.0f }; groundId1 = b2CreateBody( m_worldId, &bodyDef ); const char* path = "M 2.6458333,201.08333 H 293.68751 v -47.625 h -2.64584 l -10.58333,7.9375 -13.22916,7.9375 -13.24648,5.29167 " "-31.73269,7.9375 -21.16667,2.64583 -23.8125,10.58333 H 142.875 v -5.29167 h -5.29166 v 5.29167 H 119.0625 v " "-2.64583 h -2.64583 v -2.64584 h -2.64584 v -2.64583 H 111.125 v -2.64583 H 84.666668 v -2.64583 h -5.291666 v " "-2.64584 h -5.291667 v -2.64583 H 68.791668 V 174.625 h -5.291666 v -2.64584 H 52.916669 L 39.6875,177.27083 H " "34.395833 L 23.8125,185.20833 H 15.875 L 5.2916669,187.85416 V 153.45833 H 2.6458333 v 47.625"; b2Vec2 points[64]; b2Vec2 offset = { -50.0f, -200.0f }; float scale = 0.2f; int count = ParsePath( path, offset, points, 64, scale, false ); b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = count; chainDef.isLoop = true; b2CreateChain( groundId1, &chainDef ); } b2BodyId groundId2; { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 98.0f, 0.0f }; groundId2 = b2CreateBody( m_worldId, &bodyDef ); const char* path = "M 2.6458333,201.08333 H 293.68751 l 0,-23.8125 h -23.8125 l 21.16667,21.16667 h -23.8125 l -39.68751,-13.22917 " "-26.45833,7.9375 -23.8125,2.64583 h -13.22917 l -0.0575,2.64584 h -5.29166 v -2.64583 l -7.86855,-1e-5 " "-0.0114,-2.64583 h -2.64583 l -2.64583,2.64584 h -7.9375 l -2.64584,2.64583 -2.58891,-2.64584 h -13.28609 v " "-2.64583 h -2.64583 v -2.64584 l -5.29167,1e-5 v -2.64583 h -2.64583 v -2.64583 l -5.29167,-1e-5 v -2.64583 h " "-2.64583 v -2.64584 h -5.291667 v -2.64583 H 92.60417 V 174.625 h -5.291667 v -2.64584 l -34.395835,1e-5 " "-7.9375,-2.64584 -7.9375,-2.64583 -5.291667,-5.29167 H 21.166667 L 13.229167,158.75 5.2916668,153.45833 H " "2.6458334 l -10e-8,47.625"; b2Vec2 points[64]; b2Vec2 offset = { 0.0f, -200.0f }; float scale = 0.2f; int count = ParsePath( path, offset, points, 64, scale, false ); b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = count; chainDef.isLoop = true; b2CreateChain( groundId2, &chainDef ); } { b2Polygon box = b2MakeBox( 0.5f, 0.125f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.maxMotorTorque = 10.0f; jointDef.enableMotor = true; jointDef.hertz = 3.0f; jointDef.dampingRatio = 0.8f; jointDef.enableSpring = true; float xBase = 48.7f; float yBase = 9.2f; int count = 50; b2BodyId prevBodyId = groundId1; for ( int i = 0; i < count; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { xBase + 0.5f + 1.0f * i, yBase }; bodyDef.angularDamping = 0.2f; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2Vec2 pivot = { xBase + 1.0f * i, yBase }; jointDef.base.bodyIdA = prevBodyId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); b2CreateRevoluteJoint( m_worldId, &jointDef ); prevBodyId = bodyId; } b2Vec2 pivot = { xBase + 1.0f * count, yBase }; jointDef.base.bodyIdA = prevBodyId; jointDef.base.bodyIdB = groundId2; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); b2CreateRevoluteJoint( m_worldId, &jointDef ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 32.0f, 4.5f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); m_friendlyShape.maxPush = 0.025f; m_friendlyShape.clipVelocity = false; shapeDef.filter = { MoverBit, AllBits, 0 }; shapeDef.userData = &m_friendlyShape; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreateCapsuleShape( bodyId, &shapeDef, &m_capsule ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 7.0f, 7.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.filter = { DebrisBit, AllBits, 0 }; shapeDef.material.restitution = 0.7f; shapeDef.material.rollingResistance = 0.2f; b2Circle circle = { b2Vec2_zero, 0.3f }; m_ballId = b2CreateCircleShape( bodyId, &shapeDef, &circle ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_kinematicBody; bodyDef.position = { m_elevatorBase.x, m_elevatorBase.y - m_elevatorAmplitude }; m_elevatorId = b2CreateBody( m_worldId, &bodyDef ); m_elevatorShape = { .maxPush = 0.1f, .clipVelocity = true, }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.filter = { DynamicBit, AllBits, 0 }; shapeDef.userData = &m_elevatorShape; b2Polygon box = b2MakeBox( 2.0f, 0.1f ); b2CreatePolygonShape( m_elevatorId, &shapeDef, &box ); } m_totalIterations = 0; m_pogoVelocity = 0.0f; m_onGround = false; m_jumpReleased = true; m_lockCamera = true; m_planeCount = 0; m_time = 0.0f; } // https://github.com/id-Software/Quake/blob/master/QW/client/pmove.c#L390 void SolveMove( float timeStep, float throttle ) { // Friction float speed = b2Length( m_velocity ); if ( speed < m_minSpeed ) { m_velocity.x = 0.0f; m_velocity.y = 0.0f; } else if ( m_onGround ) { // Linear damping above stopSpeed and fixed reduction below stopSpeed float control = speed < m_stopSpeed ? m_stopSpeed : speed; // friction has units of 1/time float drop = control * m_friction * timeStep; float newSpeed = b2MaxFloat( 0.0f, speed - drop ); m_velocity *= newSpeed / speed; } b2Vec2 desiredVelocity = { m_maxSpeed * throttle, 0.0f }; float desiredSpeed; b2Vec2 desiredDirection = b2GetLengthAndNormalize( &desiredSpeed, desiredVelocity ); if ( desiredSpeed > m_maxSpeed ) { desiredSpeed = m_maxSpeed; } if ( m_onGround ) { m_velocity.y = 0.0f; } // Accelerate float currentSpeed = b2Dot( m_velocity, desiredDirection ); float addSpeed = desiredSpeed - currentSpeed; if ( addSpeed > 0.0f ) { float steer = m_onGround ? 1.0f : m_airSteer; float accelSpeed = steer * m_accelerate * m_maxSpeed * timeStep; if ( accelSpeed > addSpeed ) { accelSpeed = addSpeed; } m_velocity += accelSpeed * desiredDirection; } m_velocity.y -= m_gravity * timeStep; float pogoRestLength = 3.0f * m_capsule.radius; float rayLength = pogoRestLength + m_capsule.radius; b2Vec2 origin = b2TransformPoint( m_transform, m_capsule.center1 ); b2Circle circle = { origin, 0.5f * m_capsule.radius }; b2Vec2 segmentOffset = { 0.75f * m_capsule.radius, 0.0f }; b2Segment segment = { .point1 = origin - segmentOffset, .point2 = origin + segmentOffset, }; b2ShapeProxy proxy = {}; b2Vec2 translation; b2QueryFilter pogoFilter = { MoverBit, StaticBit | DynamicBit }; CastResult castResult = {}; if ( m_pogoShape == PogoPoint ) { proxy = b2MakeProxy( &origin, 1, 0.0f ); translation = { 0.0f, -rayLength }; } else if ( m_pogoShape == PogoCircle ) { proxy = b2MakeProxy( &origin, 1, circle.radius ); translation = { 0.0f, -rayLength + circle.radius }; } else { proxy = b2MakeProxy( &segment.point1, 2, 0.0f ); translation = { 0.0f, -rayLength }; } b2World_CastShape( m_worldId, &proxy, translation, pogoFilter, CastCallback, &castResult ); // Avoid snapping to ground if still going up if ( m_onGround == false ) { m_onGround = castResult.hit && m_velocity.y <= 0.01f; } else { m_onGround = castResult.hit; } if ( castResult.hit == false ) { m_pogoVelocity = 0.0f; b2Vec2 delta = translation; DrawLine( m_draw, origin, origin + delta, b2_colorGray ); if ( m_pogoShape == PogoPoint ) { DrawPoint( m_draw, origin + delta, 10.0f, b2_colorGray ); } else if ( m_pogoShape == PogoCircle ) { DrawCircle( m_draw, origin + delta, circle.radius, b2_colorGray ); } else { DrawLine( m_draw, segment.point1 + delta, segment.point2 + delta, b2_colorGray ); } } else { float pogoCurrentLength = castResult.fraction * rayLength; float offset = pogoCurrentLength - pogoRestLength; m_pogoVelocity = b2SpringDamper( m_pogoHertz, m_pogoDampingRatio, offset, m_pogoVelocity, timeStep ); b2Vec2 delta = castResult.fraction * translation; DrawLine( m_draw, origin, origin + delta, b2_colorGray ); if ( m_pogoShape == PogoPoint ) { DrawPoint( m_draw, origin + delta, 10.0f, b2_colorPlum ); } else if ( m_pogoShape == PogoCircle ) { DrawCircle( m_draw, origin + delta, circle.radius, b2_colorPlum ); } else { DrawLine( m_draw, segment.point1 + delta, segment.point2 + delta, b2_colorPlum ); } b2Body_ApplyForce( castResult.bodyId, { 0.0f, -50.0f }, castResult.point, true ); } b2Vec2 target = m_transform.p + timeStep * m_velocity + timeStep * m_pogoVelocity * b2Vec2{ 0.0f, 1.0f }; // Mover overlap filter b2QueryFilter collideFilter = { MoverBit, StaticBit | DynamicBit | MoverBit }; // Movers don't sweep against other movers, allows for soft collision b2QueryFilter castFilter = { MoverBit, StaticBit | DynamicBit }; m_totalIterations = 0; float tolerance = 0.01f; for ( int iteration = 0; iteration < 5; ++iteration ) { m_planeCount = 0; b2Capsule mover; mover.center1 = b2TransformPoint( m_transform, m_capsule.center1 ); mover.center2 = b2TransformPoint( m_transform, m_capsule.center2 ); mover.radius = m_capsule.radius; b2World_CollideMover( m_worldId, &mover, collideFilter, PlaneResultFcn, this ); b2PlaneSolverResult result = b2SolvePlanes( target - m_transform.p, m_planes, m_planeCount ); m_totalIterations += result.iterationCount; float fraction = b2World_CastMover( m_worldId, &mover, result.translation, castFilter ); b2Vec2 delta = fraction * result.translation; m_transform.p += delta; if ( b2LengthSquared( delta ) < tolerance * tolerance ) { break; } } m_velocity = b2ClipVector( m_velocity, m_planes, m_planeCount ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 350.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 25.0f ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 340.0f, height ) ); ImGui::Begin( "Mover", nullptr, 0 ); ImGui::PushItemWidth( 240.0f ); ImGui::SliderFloat( "Jump Speed", &m_jumpSpeed, 0.0f, 40.0f, "%.0f" ); ImGui::SliderFloat( "Min Speed", &m_minSpeed, 0.0f, 1.0f, "%.2f" ); ImGui::SliderFloat( "Max Speed", &m_maxSpeed, 0.0f, 20.0f, "%.0f" ); ImGui::SliderFloat( "Stop Speed", &m_stopSpeed, 0.0f, 10.0f, "%.1f" ); ImGui::SliderFloat( "Accelerate", &m_accelerate, 0.0f, 100.0f, "%.0f" ); ImGui::SliderFloat( "Friction", &m_friction, 0.0f, 10.0f, "%.1f" ); ImGui::SliderFloat( "Gravity", &m_gravity, 0.0f, 100.0f, "%.1f" ); ImGui::SliderFloat( "Air Steer", &m_airSteer, 0.0f, 1.0f, "%.2f" ); ImGui::SliderFloat( "Pogo Hertz", &m_pogoHertz, 0.0f, 30.0f, "%.0f" ); ImGui::SliderFloat( "Pogo Damping", &m_pogoDampingRatio, 0.0f, 4.0f, "%.1f" ); ImGui::PopItemWidth(); ImGui::Separator(); ImGui::Text( "Pogo Shape" ); ImGui::RadioButton( "Point", &m_pogoShape, PogoPoint ); ImGui::SameLine(); ImGui::RadioButton( "Circle", &m_pogoShape, PogoCircle ); ImGui::SameLine(); ImGui::RadioButton( "Segment", &m_pogoShape, PogoSegment ); ImGui::Checkbox( "Lock Camera", &m_lockCamera ); ImGui::End(); } static bool PlaneResultFcn( b2ShapeId shapeId, const b2PlaneResult* planeResult, void* context ) { assert( planeResult->hit == true ); Mover* self = static_cast( context ); float maxPush = FLT_MAX; bool clipVelocity = true; ShapeUserData* userData = static_cast( (void*)b2Shape_GetUserData( shapeId ) ); if ( userData != nullptr ) { maxPush = userData->maxPush; clipVelocity = userData->clipVelocity; } if ( self->m_planeCount < m_planeCapacity ) { assert( b2IsValidPlane( planeResult->plane ) ); self->m_planes[self->m_planeCount] = { planeResult->plane, maxPush, 0.0f, clipVelocity }; self->m_planeCount += 1; } return true; } static bool Kick( b2ShapeId shapeId, void* context ) { Mover* self = (Mover*)context; b2BodyId bodyId = b2Shape_GetBody( shapeId ); b2BodyType type = b2Body_GetType( bodyId ); if ( type != b2_dynamicBody ) { return true; } b2Vec2 center = b2Body_GetWorldCenterOfMass( bodyId ); b2Vec2 direction = b2Normalize( center - self->m_transform.p ); b2Vec2 impulse = b2Vec2{ 2.0f * direction.x, 2.0f }; b2Body_ApplyLinearImpulseToCenter( bodyId, impulse, true ); return true; } void Keyboard( int key ) override { if ( key == 'K' ) { b2Vec2 point = b2TransformPoint( m_transform, { 0.0f, m_capsule.center1.y - 3.0f * m_capsule.radius } ); b2Circle circle = { point, 0.5f }; b2ShapeProxy proxy = b2MakeProxy( &circle.center, 1, circle.radius ); b2QueryFilter filter = { MoverBit, DebrisBit }; b2World_OverlapShape( m_worldId, &proxy, filter, Kick, this ); DrawCircle( m_draw, circle.center, circle.radius, b2_colorGoldenRod ); } Sample::Keyboard( key ); } void Step() override { bool pause = false; if ( m_context->pause ) { pause = m_context->singleStep != true; } float timeStep = m_context->hertz > 0.0f ? 1.0f / m_context->hertz : 0.0f; if ( pause ) { timeStep = 0.0f; } if ( timeStep > 0.0f ) { b2Vec2 point = { .x = m_elevatorBase.x, .y = m_elevatorAmplitude * cosf( 1.0f * m_time + B2_PI ) + m_elevatorBase.y, }; bool wake = true; b2Body_SetTargetTransform( m_elevatorId, { point, b2Rot_identity }, timeStep, wake ); } m_time += timeStep; Sample::Step(); if ( pause == false ) { float throttle = 0.0f; if ( glfwGetKey( m_context->window, GLFW_KEY_A ) ) { throttle -= 1.0f; } if ( glfwGetKey( m_context->window, GLFW_KEY_D ) ) { throttle += 1.0f; } if ( glfwGetKey( m_context->window, GLFW_KEY_SPACE ) ) { if ( m_onGround == true && m_jumpReleased ) { m_velocity.y = m_jumpSpeed; m_onGround = false; m_jumpReleased = false; } } else { m_jumpReleased = true; } SolveMove( timeStep, throttle ); } int count = m_planeCount; for ( int i = 0; i < count; ++i ) { b2Plane plane = m_planes[i].plane; b2Vec2 p1 = m_transform.p + ( plane.offset - m_capsule.radius ) * plane.normal; b2Vec2 p2 = p1 + 0.1f * plane.normal; DrawPoint( m_draw, p1, 5.0f, b2_colorYellow ); DrawLine( m_draw, p1, p2, b2_colorYellow ); } b2Vec2 p1 = b2TransformPoint( m_transform, m_capsule.center1 ); b2Vec2 p2 = b2TransformPoint( m_transform, m_capsule.center2 ); b2HexColor color = m_onGround ? b2_colorOrange : b2_colorAquamarine; DrawSolidCapsule( m_draw, p1, p2, m_capsule.radius, color ); DrawLine( m_draw, m_transform.p, m_transform.p + m_velocity, b2_colorPurple ); b2Vec2 p = m_transform.p; DrawTextLine( "position %.2f %.2f", p.x, p.y ); DrawTextLine( "velocity %.2f %.2f", m_velocity.x, m_velocity.y ); DrawTextLine( "iterations %d", m_totalIterations ); if ( m_lockCamera ) { m_camera->center.x = m_transform.p.x; } } static Sample* Create( SampleContext* context ) { return new Mover( context ); } static constexpr int m_planeCapacity = 8; static constexpr b2Vec2 m_elevatorBase = { 112.0f, 10.0f }; static constexpr float m_elevatorAmplitude = 4.0f; float m_jumpSpeed = 10.0f; float m_maxSpeed = 6.0f; float m_minSpeed = 0.1f; float m_stopSpeed = 3.0f; float m_accelerate = 20.0f; float m_airSteer = 0.2f; float m_friction = 8.0f; float m_gravity = 30.0f; float m_pogoHertz = 5.0f; float m_pogoDampingRatio = 0.8f; int m_pogoShape = PogoSegment; b2Transform m_transform; b2Vec2 m_velocity; b2Capsule m_capsule; b2BodyId m_elevatorId; b2ShapeId m_ballId; ShapeUserData m_friendlyShape; ShapeUserData m_elevatorShape; b2CollisionPlane m_planes[m_planeCapacity] = {}; int m_planeCount; int m_totalIterations; float m_pogoVelocity; float m_time; bool m_onGround; bool m_jumpReleased; bool m_lockCamera; }; static int sampleMover = RegisterSample( "Character", "Mover", Mover::Create ); // todo mover experiment wip #if 0 enum MoverMode { e_walkingMode, e_fallingMode, e_modeCount, }; class Mover2 : public Sample { public: explicit Mover( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 20.0f, 9.0f }; m_context->camera.zoom = 10.0f; } settings.drawJoints = false; m_transform = { { 2.0f, 8.0f }, b2Rot_identity }; m_velocity = { 0.0f, 0.0f }; m_capsule = { { 0.0f, -0.5f * m_capsuleInteriorLength }, { 0.0f, 0.5f * m_capsuleInteriorLength }, m_capsuleRadius }; b2BodyId groundId1; { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, 0.0f }; groundId1 = b2CreateBody( m_worldId, &bodyDef ); const char* path = "M -34.395834,201.08333 H 293.68751 v -47.625 h -2.64584 l -10.58333,7.9375 -13.22916,7.9375 -13.24648,5.29167 " "-31.73269,7.9375 -21.16667,2.64583 -23.8125,10.58333 H 142.875 v -5.29167 h -5.29166 v 5.29167 H 119.0625 v " "-2.64583 h -2.64583 v -2.64584 h -2.64584 v -2.64583 H 111.125 v -2.64583 H 84.666668 v -2.64583 h -5.291666 v " "-2.64584 h -5.291667 v -2.64583 H 68.791668 V 174.625 h -5.291666 v -2.64584 H 52.916669 L 39.6875,177.27083 h " "-5.291667 l -7.937499,5.29167 H 15.875001 l -47.625002,-50.27083 v -26.45834 h -2.645834 l 10e-7,95.25"; b2Vec2 points[64]; b2Vec2 offset = { -50.0f, -200.0f }; float scale = 0.2f; int count = ParsePath( path, offset, points, 64, scale, false ); b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = count; chainDef.isLoop = true; b2CreateChain( groundId1, &chainDef ); } b2BodyId groundId2; { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 98.0f, 0.0f }; groundId2 = b2CreateBody( m_worldId, &bodyDef ); const char* path = "M 2.6458333,201.08333 H 293.68751 l 0,-23.8125 h -23.8125 l 21.16667,21.16667 h -23.8125 l -39.68751,-13.22917 " "-26.45833,7.9375 -23.8125,2.64583 h -13.22917 l -0.0575,2.64584 h -5.29166 v -2.64583 l -7.86855,-1e-5 " "-0.0114,-2.64583 h -2.64583 l -2.64583,2.64584 h -7.9375 l -2.64584,2.64583 -2.58891,-2.64584 h -13.28609 v " "-2.64583 h -2.64583 v -2.64584 l -5.29167,1e-5 v -2.64583 h -2.64583 v -2.64583 l -5.29167,-1e-5 v -2.64583 h " "-2.64583 v -2.64584 h -5.291667 v -2.64583 H 92.60417 V 174.625 h -5.291667 v -2.64584 l -34.395835,1e-5 " "-7.9375,-2.64584 -7.9375,-2.64583 -5.291667,-5.29167 H 21.166667 L 13.229167,158.75 5.2916668,153.45833 H " "2.6458334 l -10e-8,47.625"; b2Vec2 points[64]; b2Vec2 offset = { 0.0f, -200.0f }; float scale = 0.2f; int count = ParsePath( path, offset, points, 64, scale, false ); b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = count; chainDef.isLoop = true; b2CreateChain( groundId2, &chainDef ); } { b2Polygon box = b2MakeBox( 0.5f, 0.125f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.maxMotorTorque = 10.0f; jointDef.enableMotor = true; jointDef.hertz = 3.0f; jointDef.dampingRatio = 0.8f; jointDef.enableSpring = true; float xBase = 48.7f; float yBase = 9.2f; int count = 50; b2BodyId prevBodyId = groundId1; for ( int i = 0; i < count; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { xBase + 0.5f + 1.0f * i, yBase }; bodyDef.angularDamping = 0.2f; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2Vec2 pivot = { xBase + 1.0f * i, yBase }; jointDef.base.bodyIdA = prevBodyId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); b2CreateRevoluteJoint( m_worldId, &jointDef ); prevBodyId = bodyId; } b2Vec2 pivot = { xBase + 1.0f * count, yBase }; jointDef.base.bodyIdA = prevBodyId; jointDef.base.bodyIdB = groundId2; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); b2CreateRevoluteJoint( m_worldId, &jointDef ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 32.0f, 4.5f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); m_friendlyShape.maxPush = 0.025f; m_friendlyShape.clipVelocity = false; shapeDef.filter = { MoverBit, AllBits, 0 }; shapeDef.userData = &m_friendlyShape; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreateCapsuleShape( bodyId, &shapeDef, &m_capsule ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 7.0f, 7.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.filter = { DebrisBit, AllBits, 0 }; shapeDef.material.restitution = 0.7f; shapeDef.material.rollingResistance = 0.2f; b2Circle circle = { b2Vec2_zero, 0.3f }; m_ballId = b2CreateCircleShape( bodyId, &shapeDef, &circle ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_kinematicBody; bodyDef.position = { m_elevatorBase.x, m_elevatorBase.y - m_elevatorAmplitude }; m_elevatorId = b2CreateBody( m_worldId, &bodyDef ); m_elevatorShape = { .maxPush = 0.1f, .clipVelocity = true, }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.filter = { DynamicBit, AllBits, 0 }; shapeDef.userData = &m_elevatorShape; b2Polygon box = b2MakeBox( 2.0f, 0.1f ); b2CreatePolygonShape( m_elevatorId, &shapeDef, &box ); } m_floorResult = {}; m_floorSeparation = 0.0f; m_mode = MoverMode::e_fallingMode; m_nonWalkablePosition = m_transform.p; m_noWalkTime = 0.0f; m_groundNormal = b2Vec2_zero; m_totalIterations = 0; m_pogoVelocity = 0.0f; m_canWalk = false; m_jumpReleased = true; m_lockCamera = true; m_planeCount = 0; m_time = 0.0f; } void UpdateFloorData(float timeStep) { // This cast extension keeps the character glued to the ground when walking down slopes and steps. float castExtension = m_stepDownHeight; // The extension increases with velocity while on ground. if (m_mode == MoverMode::e_walkingMode) { castExtension += b2Length( m_velocity ) * timeStep; } float castLength = m_pogoRestLength + m_capsule.radius + castExtension; DrawTextLine( "extension = %.3f", castExtension ); // Start cast from the center of the bottom capsule sphere. b2Vec2 origin = b2TransformPoint( m_transform, m_capsule.center1 ); b2Vec2 translation = { 0.0, -castLength }; b2QueryFilter pogoFilter = { MoverBit, StaticBit | DynamicBit }; m_floorResult = {}; b2World_CastRay( m_worldId, origin, translation, pogoFilter, CastCallback, &m_floorResult ); if ( m_floorResult.hit == false || m_floorResult.normal.y < m_walkableGroundY ) { m_floorResult = {}; // Try again with a circle cast b2ShapeProxy proxy = b2MakeProxy( &origin, 1, 0.9f * m_capsuleRadius ); b2World_CastShape( m_worldId, &proxy, translation, pogoFilter, CastCallback, &m_floorResult ); } if ( m_floorResult.hit == true) { float contactHeight = m_floorResult.point.y; float distanceToGround = m_transform.p.y - contactHeight; if (m_velocity.y > 0.0f) { // todo why bother trying to find the surface if we just reset it here? m_floorResult = {}; m_floorSeparation = 1.0f; m_canWalk = false; } else { m_floorSeparation = distanceToGround; m_canWalk = false; if (m_floorResult.hit && m_floorResult.normal.y >= m_walkableGroundY) { if (distanceToGround <= castExtension) { if (m_mode == MoverMode::e_walkingMode) { float currentPogoLength = m_pogoRestLength + m_pogoOffset; float bottomOfCapsule = m_transform.p.y + currentPogoLength; float bottomOfCapsuleAtRest = contactHeight + m_pogoRestLength; float prevOffset = m_pogoOffset; m_pogoOffset = bottomOfCapsule - bottomOfCapsuleAtRest; m_visualOffset += m_pogoOffset - prevOffset; } m_canWalk = true; } else { m_floorResult = {}; } } } } } void SetMode(MoverMode mode) { if (mode == m_mode) { return; } m_canJump = false; if (m_modePicked[mode] == true) { return; } if (mode == e_fallingMode) { m_timeInAir = 0.0f; } else if (mode == e_walkingMode) { if (m_mode == e_fallingMode) { m_landed = true; m_landingSpeed = -m_velocity.y; } m_velocity.y = 0.0f; } m_mode = mode; } void ComputeVelocity( float timeStep, bool keepNormalVelocity ) { #if 0 bool walkable = m_groundNormal.y > 0.71f; // Friction float speed = b2Length( m_velocity ); { // Linear damping above stopSpeed and fixed reduction below stopSpeed float control = speed < m_stopSpeed ? m_stopSpeed : speed; // friction has units of 1/time float drop = control * m_friction * timeStep; float newSpeed = b2MaxFloat( 0.0f, speed - drop ); m_velocity *= newSpeed / speed; } b2Vec2 desiredVelocity = { m_maxSpeed * throttle, 0.0f }; float desiredSpeed; b2Vec2 desiredDirection = b2GetLengthAndNormalize( &desiredSpeed, desiredVelocity ); if ( desiredSpeed > m_maxSpeed ) { desiredSpeed = m_maxSpeed; } float noWalkSteer = 0.0f; if ( m_onGround ) { if ( walkable ) { m_velocity.y = 0.0f; noWalkSteer = m_airSteer; m_noWalkTime = 0.0f; } else { if ( m_noWalkTime == 0.0f ) { m_nonWalkablePosition = m_transform.p; } m_velocity = m_velocity - b2Dot( m_velocity, m_groundNormal ) * m_groundNormal; // m_noWalkSpeed = m_airSteer * b2MaxFloat( 0.0f, 1.0f - 0.25f * speed / b2MaxFloat(m_stopSpeed, 1.0f) ); float noWalkDistance = b2Distance( m_transform.p, m_nonWalkablePosition ); noWalkSteer = m_airSteer; m_noWalkTime += timeStep; // if ( noWalkDistance / m_noWalkTime < 0.5f * m_airSteer * m_maxSpeed ) //{ // noWalkSteer = m_airSteer + 0.5f * m_noWalkTime * ( 1.0f - m_airSteer ); // noWalkSteer = b2ClampFloat( noWalkSteer, m_airSteer, 1.0f ); // } } } else { m_noWalkTime = 0.0f; } // Accelerate float currentSpeed = b2Dot( m_velocity, desiredDirection ); float addSpeed = desiredSpeed - currentSpeed; if ( addSpeed > 0.0f ) { float steer; if ( m_onGround ) { steer = walkable ? 1.0f : noWalkSteer; } else { steer = m_airSteer; } DrawTextLine( "steer = %.2f", steer ); float accelSpeed = steer * m_accelerate * m_maxSpeed * timeStep; if ( accelSpeed > addSpeed ) { accelSpeed = addSpeed; } m_velocity += accelSpeed * desiredDirection; } #else // todo keepNormalVelocity always true b2Vec2 v = m_velocity; float vy = v.y; v.y = 0.0f; // ConfigAccel = m_accelerate // ConfigDecelBase = // ConfigDecelPerSpeed // ConfigDecelStartAtSpeed bool inAir = m_mode == e_fallingMode; float acceleration = inAir ? m_airSteer * m_accelerate : m_accelerate; // m/s^2 float decelBase = inAir ? 0.0f : 2.0f; // todo // m/s^2 / m/s = 1/s // same as friction in quake? float decelPerSpeed = inAir ? 1.0f : 5.0f; // todo // m/s float decelStartAtSpeed = inAir ? 4.25f : 0.0f; // todo float speed = b2Length( v ); // m/s^2 float perSpeedDecel = decelPerSpeed * b2MaxFloat( speed - decelStartAtSpeed, 0.0f ); // m/s^2 float decelTotal = decelBase + perSpeedDecel; // m/s float decel = decelTotal * timeStep; // m/s float decelCapped = b2MinFloat( decel, speed ); float accel = acceleration * m_maxSpeed * timeStep; v -= decelCapped * b2Normalize( v ); b2Vec2 throttle = { m_throttle, 0.0f }; b2Vec2 control = m_maxSpeed * throttle; b2Vec2 toTarget = control - v; float toTargetDist = b2Length( toTarget ); if ( b2Length( control ) > b2Length(v)) { float accelFraction = b2ClampFloat( accel / toTargetDist, 0.0f, 1.0f ); v += accelFraction * toTarget; } #endif } void UpdateFalling(float timeStep) { float vy = m_velocity.y; ComputeVelocity(timeStep, true ); m_velocity.y = vy; m_velocity.y -= m_gravity * timeStep; m_timeInAir += timeStep; m_floorSeparation = 0.0f; if ( b2Dot(m_velocity, m_floorResult.normal) < 0.0f && m_floorResult.normal.y >= m_walkableGroundY) { float currentPogoLength = m_pogoRestLength + m_pogoOffset; float bottomOfCapsule = m_transform.p.y + currentPogoLength; float bottomOfCapsuleAtRest = m_floorResult.point.y + m_pogoRestLength; float prevOffset = m_pogoOffset; m_pogoOffset = bottomOfCapsule - bottomOfCapsuleAtRest; m_visualOffset += m_pogoOffset - prevOffset; SetMode( e_walkingMode ); } } void UpdateWalking( float timeStep ) { if (m_floorResult.hit == false || m_floorResult.normal.y < m_walkableGroundY) { SetMode( e_fallingMode ); return; } if (m_floorResult.normal.y >= m_walkableGroundY) { // todo unsafe teleport m_transform.p.y = m_floorResult.point.y; } ComputeVelocity(timeStep, true); m_velocity.y = 0.0f; if ( m_canJump && glfwGetKey( m_context->window, GLFW_KEY_SPACE ) ) { m_velocity.y = m_jumpSpeed; SetMode( e_fallingMode ); } } // https://github.com/id-Software/Quake/blob/master/QW/client/pmove.c#L390 void SolveMove( float timeStep, float throttle ) { bool walkable = m_groundNormal.y > 0.71f; // Friction float speed = b2Length( m_velocity ); if ( speed < m_minSpeed ) { m_velocity.x = 0.0f; m_velocity.y = 0.0f; } else if ( m_onGround && walkable ) { // Linear damping above stopSpeed and fixed reduction below stopSpeed float control = speed < m_stopSpeed ? m_stopSpeed : speed; // friction has units of 1/time float drop = control * m_friction * timeStep; float newSpeed = b2MaxFloat( 0.0f, speed - drop ); m_velocity *= newSpeed / speed; } b2Vec2 desiredVelocity = { m_maxSpeed * throttle, 0.0f }; float desiredSpeed; b2Vec2 desiredDirection = b2GetLengthAndNormalize( &desiredSpeed, desiredVelocity ); if ( desiredSpeed > m_maxSpeed ) { desiredSpeed = m_maxSpeed; } float noWalkSteer = 0.0f; if ( m_onGround ) { if ( walkable ) { m_velocity.y = 0.0f; noWalkSteer = m_airSteer; m_noWalkTime = 0.0f; } else { if (m_noWalkTime == 0.0f) { m_nonWalkablePosition = m_transform.p; } m_velocity = m_velocity - b2Dot( m_velocity, m_groundNormal ) * m_groundNormal; //m_noWalkSpeed = m_airSteer * b2MaxFloat( 0.0f, 1.0f - 0.25f * speed / b2MaxFloat(m_stopSpeed, 1.0f) ); float noWalkDistance = b2Distance( m_transform.p, m_nonWalkablePosition ); noWalkSteer = m_airSteer; m_noWalkTime += timeStep; //if ( noWalkDistance / m_noWalkTime < 0.5f * m_airSteer * m_maxSpeed ) //{ // noWalkSteer = m_airSteer + 0.5f * m_noWalkTime * ( 1.0f - m_airSteer ); // noWalkSteer = b2ClampFloat( noWalkSteer, m_airSteer, 1.0f ); //} } } else { m_noWalkTime = 0.0f; } // Accelerate float currentSpeed = b2Dot( m_velocity, desiredDirection ); float addSpeed = desiredSpeed - currentSpeed; if ( addSpeed > 0.0f ) { float steer; if ( m_onGround ) { steer = walkable ? 1.0f : noWalkSteer; } else { steer = m_airSteer; } DrawTextLine( "steer = %.2f", steer ); float accelSpeed = steer * m_accelerate * m_maxSpeed * timeStep; if ( accelSpeed > addSpeed ) { accelSpeed = addSpeed; } m_velocity += accelSpeed * desiredDirection; } m_velocity.y -= m_gravity * timeStep; // This ray extension keeps you glued to the ground when walking down slopes. // The extension increases with velocity. float rayExtension = m_stepDownHeight; rayExtension += m_onGround ? b2Length( m_velocity ) * timeStep : 0.0f; float rayLength = m_pogoRestLength + m_capsule.radius + rayExtension; DrawTextLine( "extension = %.3f", rayExtension ); b2Vec2 origin = b2TransformPoint( m_transform, m_capsule.center1 ); b2Circle circle = { origin, 0.9f * m_capsule.radius }; b2Vec2 segmentOffset = { 0.9f * m_capsule.radius, 0.0f }; b2Segment segment = { .point1 = origin - segmentOffset, .point2 = origin + segmentOffset, }; b2ShapeProxy proxy = {}; b2Vec2 translation; b2QueryFilter pogoFilter = { MoverBit, StaticBit | DynamicBit }; CastResult castResult = {}; if ( m_pogoShape == e_pogoPoint ) { proxy = b2MakeProxy( &origin, 1, 0.0f ); translation = { 0.0f, -rayLength }; } else if ( m_pogoShape == PogoCircle ) { proxy = b2MakeProxy( &origin, 1, circle.radius ); translation = { 0.0f, -rayLength + circle.radius }; } else { proxy = b2MakeProxy( &segment.point1, 2, 0.0f ); translation = { 0.0f, -rayLength }; } b2World_CastShape( m_worldId, &proxy, translation, pogoFilter, CastCallback, &castResult ); // Avoid snapping to ground if still going up if ( m_onGround == false ) { m_onGround = castResult.hit && m_velocity.y <= 0.01f; } else { m_onGround = castResult.hit; } if ( castResult.hit == false ) { m_pogoVelocity = 0.0f; m_groundNormal = b2Vec2_zero; b2Vec2 delta = translation; m_context->draw.DrawSegment( origin, origin + delta, b2_colorGray ); if ( m_pogoShape == e_pogoPoint ) { m_context->draw.DrawPoint( origin + delta, 10.0f, b2_colorGray ); } else if ( m_pogoShape == PogoCircle ) { m_context->draw.DrawCircle( origin + delta, circle.radius, b2_colorGray ); } else { m_context->draw.DrawSegment( segment.point1 + delta, segment.point2 + delta, b2_colorGray ); } } else { m_groundNormal = castResult.normal; float pogoCurrentLength = castResult.fraction * rayLength - m_capsuleRadius; float zeta = m_pogoDampingRatio; float hertz = m_pogoHertz; float omega = 2.0f * B2_PI * hertz; float omegaH = omega * timeStep; m_pogoVelocity = ( m_pogoVelocity - omega * omegaH * ( pogoCurrentLength - m_pogoRestLength ) ) / ( 1.0f + 2.0f * zeta * omegaH + omegaH * omegaH ); b2Vec2 delta = castResult.fraction * translation; m_context->draw.DrawSegment( origin, origin + delta, b2_colorGray ); if ( m_pogoShape == e_pogoPoint ) { m_context->draw.DrawPoint( origin + delta, 10.0f, b2_colorPlum ); } else if ( m_pogoShape == PogoCircle ) { m_context->draw.DrawCircle( origin + delta, circle.radius, b2_colorPlum ); } else { m_context->draw.DrawSegment( segment.point1 + delta, segment.point2 + delta, b2_colorPlum ); } b2Body_ApplyForce( castResult.bodyId, { 0.0f, -50.0f }, castResult.point, true ); } b2Vec2 target = m_transform.p + timeStep * m_velocity + timeStep * m_pogoVelocity * b2Vec2{ 0.0f, 1.0f }; // Mover overlap filter b2QueryFilter collideFilter = { MoverBit, StaticBit | DynamicBit | MoverBit }; // Movers don't sweep against other movers, allows for soft collision b2QueryFilter castFilter = { MoverBit, StaticBit | DynamicBit }; m_totalIterations = 0; float tolerance = 0.01f; for ( int iteration = 0; iteration < 5; ++iteration ) { m_planeCount = 0; b2Capsule mover; mover.center1 = b2TransformPoint( m_transform, m_capsule.center1 ); mover.center2 = b2TransformPoint( m_transform, m_capsule.center2 ); mover.radius = m_capsule.radius; b2World_CollideMover( m_worldId, &mover, collideFilter, PlaneResultFcn, this ); b2PlaneSolverResult result = b2SolvePlanes( target, m_planes, m_planeCount ); m_totalIterations += result.iterationCount; b2Vec2 moverTranslation = result.position - m_transform.p; float fraction = b2World_CastMover( m_worldId, &mover, moverTranslation, castFilter ); b2Vec2 delta = fraction * moverTranslation; m_transform.p += delta; if ( b2LengthSquared( delta ) < tolerance * tolerance ) { break; } } m_velocity = b2ClipVector( m_velocity, m_planes, m_planeCount ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 350.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->m_height - height - 25.0f ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 340.0f, height ) ); ImGui::Begin( "Mover", nullptr, 0 ); ImGui::PushItemWidth( 240.0f ); ImGui::SliderFloat( "Jump Speed", &m_jumpSpeed, 0.0f, 20.0f, "%.0f" ); ImGui::SliderFloat( "Min Speed", &m_minSpeed, 0.0f, 1.0f, "%.2f" ); ImGui::SliderFloat( "Max Speed", &m_maxSpeed, 0.0f, 20.0f, "%.0f" ); ImGui::SliderFloat( "Stop Speed", &m_stopSpeed, 0.0f, 10.0f, "%.1f" ); ImGui::SliderFloat( "Accelerate", &m_accelerate, 0.0f, 100.0f, "%.0f" ); ImGui::SliderFloat( "Friction", &m_friction, 0.0f, 10.0f, "%.1f" ); ImGui::SliderFloat( "Gravity", &m_gravity, 0.0f, 100.0f, "%.1f" ); ImGui::SliderFloat( "Air Steer", &m_airSteer, 0.0f, 1.0f, "%.2f" ); ImGui::SliderFloat( "Pogo Hertz", &m_pogoHertz, 0.0f, 30.0f, "%.0f" ); ImGui::SliderFloat( "Pogo Damping", &m_pogoDampingRatio, 0.0f, 4.0f, "%.1f" ); ImGui::PopItemWidth(); ImGui::Separator(); ImGui::Checkbox( "Lock Camera", &m_lockCamera ); ImGui::End(); } static bool PlaneResultFcn( b2ShapeId shapeId, const b2PlaneResult* planeResult, void* context ) { assert( planeResult->hit == true ); Mover* self = static_cast( context ); float maxPush = FLT_MAX; bool clipVelocity = true; ShapeUserData* userData = static_cast( (void*)b2Shape_GetUserData( shapeId ) ); if ( userData != nullptr ) { maxPush = userData->maxPush; clipVelocity = userData->clipVelocity; } if ( self->m_planeCount < m_planeCapacity ) { assert( b2IsValidPlane( planeResult->plane ) ); self->m_planes[self->m_planeCount] = { planeResult->plane, maxPush, 0.0f, clipVelocity }; self->m_planeCount += 1; } return true; } static bool Kick( b2ShapeId shapeId, void* context ) { Mover* self = (Mover*)context; b2BodyId bodyId = b2Shape_GetBody( shapeId ); b2BodyType type = b2Body_GetType( bodyId ); if ( type != b2_dynamicBody ) { return true; } b2Vec2 center = b2Body_GetWorldCenterOfMass( bodyId ); b2Vec2 direction = b2Normalize( center - self->m_transform.p ); b2Vec2 impulse = b2Vec2{ 2.0f * direction.x, 2.0f }; b2Body_ApplyLinearImpulseToCenter( bodyId, impulse, true ); return true; } void Keyboard( int key ) override { if ( key == 'K' ) { b2Vec2 point = b2TransformPoint( m_transform, { 0.0f, m_capsule.center1.y - m_capsuleRadius } ); b2Circle circle = { point, 0.5f }; b2ShapeProxy proxy = b2MakeProxy( &circle.center, 1, circle.radius ); b2QueryFilter filter = { MoverBit, DebrisBit }; b2World_OverlapShape( m_worldId, &proxy, filter, Kick, this ); m_context->draw.DrawCircle( circle.center, circle.radius, b2_colorGoldenRod ); } Sample::Keyboard( key ); } void Step() override { bool pause = false; if ( settings.pause ) { pause = settings.singleStep != true; } float timeStep = settings.hertz > 0.0f ? 1.0f / settings.hertz : 0.0f; if ( pause ) { timeStep = 0.0f; } if ( timeStep > 0.0f ) { b2Vec2 point = { .x = m_elevatorBase.x, .y = m_elevatorAmplitude * cosf( 1.0f * m_time + B2_PI ) + m_elevatorBase.y, }; b2Body_SetTargetTransform( m_elevatorId, { point, b2Rot_identity }, timeStep ); } m_time += timeStep; Sample::Step(); if ( pause == false ) { float throttle = 0.0f; if ( glfwGetKey( m_context->window, GLFW_KEY_A ) ) { throttle -= 1.0f; } if ( glfwGetKey( m_context->window, GLFW_KEY_D ) ) { throttle += 1.0f; } if ( glfwGetKey( m_context->window, GLFW_KEY_SPACE ) ) { bool walkable = m_groundNormal.y > 0.71f; if ( m_onGround == true && walkable && m_jumpReleased ) { m_velocity.y = m_jumpSpeed; m_onGround = false; m_jumpReleased = false; } } else { m_jumpReleased = true; } SolveMove( timeStep, throttle ); } int count = m_planeCount; for ( int i = 0; i < count; ++i ) { b2Plane plane = m_planes[i].plane; b2Vec2 p1 = m_transform.p + ( plane.offset - m_capsule.radius ) * plane.normal; b2Vec2 p2 = p1 + 0.1f * plane.normal; m_context->draw.DrawPoint( p1, 5.0f, b2_colorYellow ); m_context->draw.DrawSegment( p1, p2, b2_colorYellow ); } b2Vec2 p1 = b2TransformPoint( m_transform, m_capsule.center1 ); b2Vec2 p2 = b2TransformPoint( m_transform, m_capsule.center2 ); b2HexColor color = m_onGround ? b2_colorOrange : b2_colorAquamarine; m_context->draw.DrawSolidCapsule( p1, p2, m_capsule.radius, color ); m_context->draw.DrawSegment( m_transform.p, m_transform.p + m_velocity, b2_colorPurple ); b2Vec2 p = m_transform.p; DrawTextLine( "position %.2f %.2f", p.x, p.y ); DrawTextLine( "velocity %.2f %.2f", m_velocity.x, m_velocity.y ); DrawTextLine( "iterations %d", m_totalIterations ); if ( m_lockCamera ) { m_context->camera.m_center.x = m_transform.p.x; } } static Sample* Create( SampleContext* context ) { return new Mover( context ); } static constexpr int m_planeCapacity = 8; static constexpr b2Vec2 m_elevatorBase = { 112.0f, 10.0f }; static constexpr float m_elevatorAmplitude = 4.0f; static constexpr float m_walkableGroundY = 0.706f; float m_pogoRestLength = 0.5f; float m_capsuleRadius = 0.4f; float m_capsuleInteriorLength = 0.5f; float m_jumpSpeed = 5.0f; float m_maxSpeed = 6.0f; float m_stopSpeed = 2.0f; float m_accelerate = 11.0f; float m_airSteer = 0.2f; float m_friction = 8.0f; float m_gravity = 15.0f; float m_pogoHertz = 5.0f; float m_pogoDampingRatio = 0.8f; float m_stepDownHeight = 0.5f; CastResult m_floorResult; float m_floorSeparation; float m_pogoSpeed = 0.0f; float m_pogoOffset = 0.0f; float m_visualOffset = 0.0f; // The mover transform origin is at the bottom of the pogo stick. On the floor if walking. b2Transform m_transform; MoverMode m_mode; b2Vec2 m_velocity; b2Vec2 m_groundNormal; b2Vec2 m_nonWalkablePosition; b2Capsule m_capsule; b2BodyId m_elevatorId; b2ShapeId m_ballId; ShapeUserData m_friendlyShape; ShapeUserData m_elevatorShape; b2CollisionPlane m_planes[m_planeCapacity] = {}; bool m_modePicked[MoverMode::e_modeCount]; int m_planeCount; int m_totalIterations; float m_timeInAir; float m_throttle; bool m_canJump; bool m_landed; float m_landingSpeed; float m_pogoVelocity; float m_time; float m_noWalkTime; bool m_canWalk; bool m_jumpReleased; bool m_lockCamera; }; static int sampleMover = RegisterSample( "Character", "Mover", Mover2::Create ); #endif ================================================ FILE: samples/sample_collision.cpp ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "draw.h" #include "random.h" #include "sample.h" #include "box2d/box2d.h" #include "box2d/collision.h" #include "box2d/math_functions.h" #include #include #include //#include class ShapeDistance : public Sample { public: enum ShapeType { e_point, e_segment, e_triangle, e_box }; explicit ShapeDistance( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 0.0f }; m_context->camera.zoom = 3.0f; } m_point = b2Vec2_zero; m_segment = { { -0.5f, 0.0f }, { 0.5f, 0.0f } }; { b2Vec2 points[3] = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, { 0.0f, 1.0f } }; b2Hull hull = b2ComputeHull( points, 3 ); m_triangle = b2MakePolygon( &hull, 0.0f ); // m_triangle = b2MakeSquare( 0.4f ); } m_box = b2MakeSquare( 0.5f ); // m_transform = { { 1.5f, -1.5f }, b2Rot_identity }; m_transform = { { 0.0f, 0.0f }, b2Rot_identity }; m_angle = 0.0f; m_cache = b2_emptySimplexCache; m_simplexCount = 0; m_simplexIndex = 0; m_startPoint = { 0.0f, 0.0f }; m_basePosition = { 0.0f, 0.0f }; m_baseAngle = 0.0f; m_dragging = false; m_rotating = false; m_showIndices = false; m_useCache = false; m_drawSimplex = false; m_typeA = e_box; m_typeB = e_box; m_radiusA = 0.0f; m_radiusB = 0.0f; m_proxyA = MakeProxy( m_typeA, m_radiusA ); m_proxyB = MakeProxy( m_typeB, m_radiusB ); } b2ShapeProxy MakeProxy( ShapeType type, float radius ) { b2ShapeProxy proxy = {}; proxy.radius = radius; switch ( type ) { case e_point: proxy.points[0] = b2Vec2_zero; proxy.count = 1; break; case e_segment: proxy.points[0] = m_segment.point1; proxy.points[1] = m_segment.point2; proxy.count = 2; break; case e_triangle: for ( int i = 0; i < m_triangle.count; ++i ) { proxy.points[i] = m_triangle.vertices[i]; } proxy.count = m_triangle.count; break; case e_box: proxy.points[0] = m_box.vertices[0]; proxy.points[1] = m_box.vertices[1]; proxy.points[2] = m_box.vertices[2]; proxy.points[3] = m_box.vertices[3]; proxy.count = 4; break; default: assert( false ); } return proxy; } void DrawShape( ShapeType type, b2Transform transform, float radius, b2HexColor color ) { switch ( type ) { case e_point: { b2Vec2 p = b2TransformPoint( transform, m_point ); if ( radius > 0.0f ) { DrawSolidCircle( m_draw, { p, transform.q }, radius, color ); } else { DrawPoint( m_draw, p, 5.0f, color ); } } break; case e_segment: { b2Vec2 p1 = b2TransformPoint( transform, m_segment.point1 ); b2Vec2 p2 = b2TransformPoint( transform, m_segment.point2 ); if ( radius > 0.0f ) { DrawSolidCapsule( m_draw, p1, p2, radius, color ); } else { DrawLine( m_draw, p1, p2, color ); } } break; case e_triangle: DrawSolidPolygon( m_draw, transform, m_triangle.vertices, m_triangle.count, radius, color ); break; case e_box: DrawSolidPolygon( m_draw, transform, m_box.vertices, m_box.count, radius, color ); break; default: assert( false ); } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 21.0f * fontSize; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 19.0f * fontSize, height ) ); ImGui::Begin( "Shape Distance", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); const char* shapeTypes[] = { "point", "segment", "triangle", "box" }; int shapeType = int( m_typeA ); if ( ImGui::Combo( "shape A", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) ) { m_typeA = ShapeType( shapeType ); m_proxyA = MakeProxy( m_typeA, m_radiusA ); } if ( ImGui::SliderFloat( "radius A", &m_radiusA, 0.0f, 0.5f, "%.2f" ) ) { m_proxyA.radius = m_radiusA; } shapeType = int( m_typeB ); if ( ImGui::Combo( "shape B", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) ) { m_typeB = ShapeType( shapeType ); m_proxyB = MakeProxy( m_typeB, m_radiusB ); } if ( ImGui::SliderFloat( "radius B", &m_radiusB, 0.0f, 0.5f, "%.2f" ) ) { m_proxyB.radius = m_radiusB; } ImGui::Separator(); ImGui::SliderFloat( "x offset", &m_transform.p.x, -2.0f, 2.0f, "%.2f" ); ImGui::SliderFloat( "y offset", &m_transform.p.y, -2.0f, 2.0f, "%.2f" ); if ( ImGui::SliderFloat( "angle", &m_angle, -B2_PI, B2_PI, "%.2f" ) ) { m_transform.q = b2MakeRot( m_angle ); } ImGui::Separator(); ImGui::Checkbox( "show indices", &m_showIndices ); ImGui::Checkbox( "use cache", &m_useCache ); ImGui::Separator(); if ( ImGui::Checkbox( "draw simplex", &m_drawSimplex ) ) { m_simplexIndex = 0; } if ( m_drawSimplex && m_simplexCount > 0 ) { ImGui::SliderInt( "index", &m_simplexIndex, 0, m_simplexCount - 1 ); m_simplexIndex = b2ClampInt( m_simplexIndex, 0, m_simplexCount - 1 ); } ImGui::End(); } void MouseDown( b2Vec2 p, int button, int mods ) override { if ( button == GLFW_MOUSE_BUTTON_1 ) { if ( mods == 0 && m_rotating == false ) { m_dragging = true; m_startPoint = p; m_basePosition = m_transform.p; } else if ( mods == GLFW_MOD_SHIFT && m_dragging == false ) { m_rotating = true; m_startPoint = p; m_baseAngle = m_angle; } } } void MouseUp( b2Vec2, int button ) override { if ( button == GLFW_MOUSE_BUTTON_1 ) { m_dragging = false; m_rotating = false; } } void MouseMove( b2Vec2 p ) override { if ( m_dragging ) { m_transform.p = m_basePosition + 0.5f * ( p - m_startPoint ); } else if ( m_rotating ) { float dx = p.x - m_startPoint.x; m_angle = b2ClampFloat( m_baseAngle + 1.0f * dx, -B2_PI, B2_PI ); m_transform.q = b2MakeRot( m_angle ); } } static b2Vec2 Weight2( float a1, b2Vec2 w1, float a2, b2Vec2 w2 ) { return { a1 * w1.x + a2 * w2.x, a1 * w1.y + a2 * w2.y }; } static b2Vec2 Weight3( float a1, b2Vec2 w1, float a2, b2Vec2 w2, float a3, b2Vec2 w3 ) { return { a1 * w1.x + a2 * w2.x + a3 * w3.x, a1 * w1.y + a2 * w2.y + a3 * w3.y }; } void ComputeSimplexWitnessPoints( b2Vec2* a, b2Vec2* b, const b2Simplex* s ) { switch ( s->count ) { case 0: assert( false ); break; case 1: *a = s->v1.wA; *b = s->v1.wB; break; case 2: *a = Weight2( s->v1.a, s->v1.wA, s->v2.a, s->v2.wA ); *b = Weight2( s->v1.a, s->v1.wB, s->v2.a, s->v2.wB ); break; case 3: *a = Weight3( s->v1.a, s->v1.wA, s->v2.a, s->v2.wA, s->v3.a, s->v3.wA ); *b = *a; break; default: assert( false ); break; } } void Step() override { b2DistanceInput input; input.proxyA = m_proxyA; input.proxyB = m_proxyB; input.transformA = b2Transform_identity; input.transformB = m_transform; input.useRadii = m_radiusA > 0.0f || m_radiusB > 0.0f; if ( m_useCache == false ) { m_cache.count = 0; } b2DistanceOutput output = b2ShapeDistance( &input, &m_cache, m_simplexes, m_simplexCapacity ); m_simplexCount = output.simplexCount; DrawShape( m_typeA, b2Transform_identity, m_radiusA, b2_colorCyan ); DrawShape( m_typeB, m_transform, m_radiusB, b2_colorBisque ); if ( m_drawSimplex ) { b2Simplex* simplex = m_simplexes + m_simplexIndex; b2SimplexVertex* vertices[3] = { &simplex->v1, &simplex->v2, &simplex->v3 }; if ( m_simplexIndex > 0 ) { // The first recorded simplex does not have valid barycentric coordinates b2Vec2 pointA, pointB; ComputeSimplexWitnessPoints( &pointA, &pointB, simplex ); DrawLine( m_draw, pointA, pointB, b2_colorWhite ); DrawPoint( m_draw, pointA, 10.0f, b2_colorWhite ); DrawPoint( m_draw, pointB, 10.0f, b2_colorWhite ); } b2HexColor colors[3] = { b2_colorRed, b2_colorGreen, b2_colorBlue }; for ( int i = 0; i < simplex->count; ++i ) { b2SimplexVertex* vertex = vertices[i]; DrawPoint( m_draw, vertex->wA, 10.0f, colors[i] ); DrawPoint( m_draw, vertex->wB, 10.0f, colors[i] ); } } else { DrawLine( m_draw, output.pointA, output.pointB, b2_colorDimGray ); DrawPoint( m_draw, output.pointA, 10.0f, b2_colorWhite ); DrawPoint( m_draw, output.pointB, 10.0f, b2_colorWhite ); DrawLine( m_draw, output.pointA, output.pointA + 0.5f * output.normal, b2_colorYellow ); } if ( m_showIndices ) { for ( int i = 0; i < m_proxyA.count; ++i ) { b2Vec2 p = m_proxyA.points[i]; DrawWorldString( m_draw, m_camera, p, b2_colorWhite, " %d", i ); } for ( int i = 0; i < m_proxyB.count; ++i ) { b2Vec2 p = b2TransformPoint( m_transform, m_proxyB.points[i] ); DrawWorldString( m_draw, m_camera, p, b2_colorWhite, " %d", i ); } } DrawTextLine( "mouse button 1: drag" ); DrawTextLine( "mouse button 1 + shift: rotate" ); DrawTextLine( "distance = %.2f, iterations = %d", output.distance, output.iterations ); if ( m_cache.count == 1 ) { DrawTextLine( "cache = {%d}, {%d}", m_cache.indexA[0], m_cache.indexB[0] ); } else if ( m_cache.count == 2 ) { DrawTextLine( "cache = {%d, %d}, {%d, %d}", m_cache.indexA[0], m_cache.indexA[1], m_cache.indexB[0], m_cache.indexB[1] ); } else if ( m_cache.count == 3 ) { DrawTextLine( "cache = {%d, %d, %d}, {%d, %d, %d}", m_cache.indexA[0], m_cache.indexA[1], m_cache.indexA[2], m_cache.indexB[0], m_cache.indexB[1], m_cache.indexB[2] ); } } static Sample* Create( SampleContext* context ) { return new ShapeDistance( context ); } static constexpr int m_simplexCapacity = 20; b2Polygon m_box; b2Polygon m_triangle; b2Vec2 m_point; b2Segment m_segment; ShapeType m_typeA; ShapeType m_typeB; float m_radiusA; float m_radiusB; b2ShapeProxy m_proxyA; b2ShapeProxy m_proxyB; b2SimplexCache m_cache; b2Simplex m_simplexes[m_simplexCapacity]; int m_simplexCount; int m_simplexIndex; b2Transform m_transform; float m_angle; b2Vec2 m_basePosition; b2Vec2 m_startPoint; float m_baseAngle; bool m_dragging; bool m_rotating; bool m_showIndices; bool m_useCache; bool m_drawSimplex; }; static int sampleShapeDistance = RegisterSample( "Collision", "Shape Distance", ShapeDistance::Create ); enum UpdateType { Update_Incremental = 0, Update_FullRebuild = 1, Update_PartialRebuild = 2, }; struct Proxy { b2AABB box; b2AABB fatBox; b2Vec2 position; b2Vec2 width; int proxyId; int rayStamp; int queryStamp; bool moved; }; static bool QueryCallback( int32_t proxyId, uint64_t userData, void* context ); static float RayCallback( const b2RayCastInput* input, int32_t proxyId, uint64_t userData, void* context ); // Tests the Box2D bounding volume hierarchy (BVH). The dynamic tree // can be used independently as a spatial data structure. class DynamicTree : public Sample { public: explicit DynamicTree( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 500.0f, 500.0f }; m_context->camera.zoom = 25.0f * 21.0f; } m_fill = 0.25f; m_moveFraction = 0.05f; m_moveDelta = 0.1f; m_proxies = nullptr; m_proxyCount = 0; m_proxyCapacity = 0; m_ratio = 5.0f; m_grid = 1.0f; m_moveBuffer = nullptr; m_moveCount = 0; m_rowCount = m_isDebug ? 100 : 1000; m_columnCount = m_isDebug ? 100 : 1000; memset( &m_tree, 0, sizeof( m_tree ) ); BuildTree(); m_timeStamp = 0; m_updateType = Update_Incremental; m_startPoint = { 0.0f, 0.0f }; m_endPoint = { 0.0f, 0.0f }; m_queryDrag = false; m_rayDrag = false; m_validate = true; } ~DynamicTree() override { free( m_proxies ); free( m_moveBuffer ); b2DynamicTree_Destroy( &m_tree ); } void BuildTree() { b2DynamicTree_Destroy( &m_tree ); free( m_proxies ); free( m_moveBuffer ); m_proxyCapacity = m_rowCount * m_columnCount; m_proxies = static_cast( malloc( m_proxyCapacity * sizeof( Proxy ) ) ); m_proxyCount = 0; m_moveBuffer = static_cast( malloc( m_proxyCapacity * sizeof( int ) ) ); m_moveCount = 0; float y = -4.0f; m_tree = b2DynamicTree_Create(); const b2Vec2 aabbMargin = { 0.1f, 0.1f }; for ( int i = 0; i < m_rowCount; ++i ) { float x = -40.0f; for ( int j = 0; j < m_columnCount; ++j ) { float fillTest = RandomFloatRange( 0.0f, 1.0f ); if ( fillTest <= m_fill ) { assert( m_proxyCount <= m_proxyCapacity ); Proxy* p = m_proxies + m_proxyCount; p->position = { x, y }; float ratio = RandomFloatRange( 1.0f, m_ratio ); float width = RandomFloatRange( 0.1f, 0.5f ); if ( RandomFloat() > 0.0f ) { p->width.x = ratio * width; p->width.y = width; } else { p->width.x = width; p->width.y = ratio * width; } p->box.lowerBound = { x, y }; p->box.upperBound = { x + p->width.x, y + p->width.y }; p->fatBox.lowerBound = b2Sub( p->box.lowerBound, aabbMargin ); p->fatBox.upperBound = b2Add( p->box.upperBound, aabbMargin ); p->proxyId = b2DynamicTree_CreateProxy( &m_tree, p->fatBox, B2_DEFAULT_CATEGORY_BITS, m_proxyCount ); p->rayStamp = -1; p->queryStamp = -1; p->moved = false; ++m_proxyCount; } x += m_grid; } y += m_grid; } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 320.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); ImGui::Begin( "Dynamic Tree", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 100.0f ); bool changed = false; if ( ImGui::SliderInt( "rows", &m_rowCount, 0, 1000, "%d" ) ) { changed = true; } if ( ImGui::SliderInt( "columns", &m_columnCount, 0, 1000, "%d" ) ) { changed = true; } if ( ImGui::SliderFloat( "fill", &m_fill, 0.0f, 1.0f, "%.2f" ) ) { changed = true; } if ( ImGui::SliderFloat( "grid", &m_grid, 0.5f, 2.0f, "%.2f" ) ) { changed = true; } if ( ImGui::SliderFloat( "ratio", &m_ratio, 1.0f, 10.0f, "%.2f" ) ) { changed = true; } if ( ImGui::SliderFloat( "move", &m_moveFraction, 0.0f, 1.0f, "%.2f" ) ) { } if ( ImGui::SliderFloat( "delta", &m_moveDelta, 0.0f, 1.0f, "%.2f" ) ) { } if ( ImGui::RadioButton( "Incremental", m_updateType == Update_Incremental ) ) { m_updateType = Update_Incremental; changed = true; } if ( ImGui::RadioButton( "Full Rebuild", m_updateType == Update_FullRebuild ) ) { m_updateType = Update_FullRebuild; changed = true; } if ( ImGui::RadioButton( "Partial Rebuild", m_updateType == Update_PartialRebuild ) ) { m_updateType = Update_PartialRebuild; changed = true; } ImGui::Separator(); ImGui::Text( "mouse button 1: ray cast" ); ImGui::Text( "mouse button 1 + shift: query" ); ImGui::PopItemWidth(); ImGui::End(); if ( changed ) { BuildTree(); } } void MouseDown( b2Vec2 p, int button, int mods ) override { if ( button == GLFW_MOUSE_BUTTON_1 ) { if ( mods == 0 && m_queryDrag == false ) { m_rayDrag = true; m_startPoint = p; m_endPoint = p; } else if ( mods == GLFW_MOD_SHIFT && m_rayDrag == false ) { m_queryDrag = true; m_startPoint = p; m_endPoint = p; } } } void MouseUp( b2Vec2, int button ) override { if ( button == GLFW_MOUSE_BUTTON_1 ) { m_queryDrag = false; m_rayDrag = false; } } void MouseMove( b2Vec2 p ) override { m_endPoint = p; } void Step() override { if ( m_queryDrag ) { b2AABB box = { b2Min( m_startPoint, m_endPoint ), b2Max( m_startPoint, m_endPoint ) }; b2DynamicTree_Query( &m_tree, box, B2_DEFAULT_MASK_BITS, QueryCallback, this ); DrawBounds( m_draw, box, b2_colorWhite ); } // m_startPoint = {-1.0f, 0.5f}; // m_endPoint = {7.0f, 0.5f}; if ( m_rayDrag ) { b2RayCastInput input = { m_startPoint, b2Sub( m_endPoint, m_startPoint ), 1.0f }; b2TreeStats result = b2DynamicTree_RayCast( &m_tree, &input, B2_DEFAULT_MASK_BITS, RayCallback, this ); DrawLine( m_draw, m_startPoint, m_endPoint, b2_colorWhite ); DrawPoint( m_draw, m_startPoint, 5.0f, b2_colorGreen ); DrawPoint( m_draw, m_endPoint, 5.0f, b2_colorRed ); DrawTextLine( "node visits = %d, leaf visits = %d", result.nodeVisits, result.leafVisits ); } b2HexColor c = b2_colorBlue; b2HexColor qc = b2_colorGreen; const b2Vec2 aabbMargin = { 0.1f, 0.1f }; for ( int i = 0; i < m_proxyCount; ++i ) { Proxy* p = m_proxies + i; if ( p->queryStamp == m_timeStamp || p->rayStamp == m_timeStamp ) { DrawBounds( m_draw, p->box, qc ); } else { DrawBounds( m_draw, p->box, c ); } float moveTest = RandomFloatRange( 0.0f, 1.0f ); if ( m_moveFraction > moveTest ) { float dx = m_moveDelta * RandomFloat(); float dy = m_moveDelta * RandomFloat(); p->position.x += dx; p->position.y += dy; p->box.lowerBound.x = p->position.x + dx; p->box.lowerBound.y = p->position.y + dy; p->box.upperBound.x = p->position.x + dx + p->width.x; p->box.upperBound.y = p->position.y + dy + p->width.y; if ( b2AABB_Contains( p->fatBox, p->box ) == false ) { p->fatBox.lowerBound = b2Sub( p->box.lowerBound, aabbMargin ); p->fatBox.upperBound = b2Add( p->box.upperBound, aabbMargin ); p->moved = true; } else { p->moved = false; } } else { p->moved = false; } } switch ( m_updateType ) { case Update_Incremental: { uint64_t ticks = b2GetTicks(); for ( int i = 0; i < m_proxyCount; ++i ) { Proxy* p = m_proxies + i; if ( p->moved ) { b2DynamicTree_MoveProxy( &m_tree, p->proxyId, p->fatBox ); } } float ms = b2GetMilliseconds( ticks ); DrawTextLine( "incremental : %.3f ms", ms ); } break; case Update_FullRebuild: { for ( int i = 0; i < m_proxyCount; ++i ) { Proxy* p = m_proxies + i; if ( p->moved ) { b2DynamicTree_EnlargeProxy( &m_tree, p->proxyId, p->fatBox ); } } uint64_t ticks = b2GetTicks(); int boxCount = b2DynamicTree_Rebuild( &m_tree, true ); float ms = b2GetMilliseconds( ticks ); DrawTextLine( "full build %d : %.3f ms", boxCount, ms ); } break; case Update_PartialRebuild: { for ( int i = 0; i < m_proxyCount; ++i ) { Proxy* p = m_proxies + i; if ( p->moved ) { b2DynamicTree_EnlargeProxy( &m_tree, p->proxyId, p->fatBox ); } } uint64_t ticks = b2GetTicks(); int boxCount = b2DynamicTree_Rebuild( &m_tree, false ); float ms = b2GetMilliseconds( ticks ); DrawTextLine( "partial rebuild %d : %.3f ms", boxCount, ms ); } break; default: break; } int height = b2DynamicTree_GetHeight( &m_tree ); float areaRatio = b2DynamicTree_GetAreaRatio( &m_tree ); int hmin = (int)( ceilf( logf( (float)m_proxyCount ) / logf( 2.0f ) - 1.0f ) ); DrawTextLine( "proxies = %d, height = %d, hmin = %d, area ratio = %.1f", m_proxyCount, height, hmin, areaRatio ); b2DynamicTree_Validate( &m_tree ); m_timeStamp += 1; } static Sample* Create( SampleContext* context ) { return new DynamicTree( context ); } b2DynamicTree m_tree; int m_rowCount, m_columnCount; Proxy* m_proxies; int* m_moveBuffer; int m_moveCount; int m_proxyCapacity; int m_proxyCount; int m_timeStamp; int m_updateType; float m_fill; float m_moveFraction; float m_moveDelta; float m_ratio; float m_grid; b2Vec2 m_startPoint; b2Vec2 m_endPoint; bool m_rayDrag; bool m_queryDrag; bool m_validate; }; static bool QueryCallback( int proxyId, uint64_t userData, void* context ) { DynamicTree* sample = static_cast( context ); Proxy* proxy = sample->m_proxies + userData; assert( proxy->proxyId == proxyId ); proxy->queryStamp = sample->m_timeStamp; return true; } static float RayCallback( const b2RayCastInput* input, int proxyId, uint64_t userData, void* context ) { DynamicTree* sample = static_cast( context ); Proxy* proxy = sample->m_proxies + userData; assert( proxy->proxyId == proxyId ); proxy->rayStamp = sample->m_timeStamp; return input->maxFraction; } static int sampleDynamicTree = RegisterSample( "Collision", "Dynamic Tree", DynamicTree::Create ); class RayCast : public Sample { public: explicit RayCast( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 20.0f }; m_context->camera.zoom = 17.5f; } m_circle = { { 0.0f, 0.0f }, 2.0f }; m_capsule = { { -1.0f, 1.0f }, { 1.0f, -1.0f }, 1.5f }; m_box = b2MakeBox( 2.0f, 2.0f ); b2Vec2 vertices[3] = { { -2.0f, 0.0f }, { 2.0f, 0.0f }, { 2.0f, 3.0f } }; b2Hull hull = b2ComputeHull( vertices, 3 ); m_triangle = b2MakePolygon( &hull, 0.0f ); m_segment = { { -3.0f, 0.0f }, { 3.0f, 0.0f } }; m_transform = b2Transform_identity; m_angle = 0.0f; m_basePosition = { 0.0f, 0.0f }; m_baseAngle = 0.0f; m_startPosition = { 0.0f, 0.0f }; m_rayStart = { 0.0f, 30.0f }; m_rayEnd = { 0.0f, 0.0f }; m_rayDrag = false; m_translating = false; m_rotating = false; m_showFraction = false; } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 230.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); ImGui::Begin( "Ray-cast", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 100.0f ); ImGui::SliderFloat( "x offset", &m_transform.p.x, -2.0f, 2.0f, "%.2f" ); ImGui::SliderFloat( "y offset", &m_transform.p.y, -2.0f, 2.0f, "%.2f" ); if ( ImGui::SliderFloat( "angle", &m_angle, -B2_PI, B2_PI, "%.2f" ) ) { m_transform.q = b2MakeRot( m_angle ); } // if (ImGui::SliderFloat("ray radius", &m_rayRadius, 0.0f, 1.0f, "%.1f")) //{ // } ImGui::Checkbox( "show fraction", &m_showFraction ); if ( ImGui::Button( "Reset" ) ) { m_transform = b2Transform_identity; m_angle = 0.0f; } ImGui::Separator(); ImGui::Text( "mouse btn 1: ray cast" ); ImGui::Text( "mouse btn 1 + shft: translate" ); ImGui::Text( "mouse btn 1 + ctrl: rotate" ); ImGui::PopItemWidth(); ImGui::End(); } void MouseDown( b2Vec2 p, int button, int mods ) override { if ( button == GLFW_MOUSE_BUTTON_1 ) { m_startPosition = p; if ( mods == 0 ) { m_rayStart = p; m_rayDrag = true; } else if ( mods == GLFW_MOD_SHIFT ) { m_translating = true; m_basePosition = m_transform.p; } else if ( mods == GLFW_MOD_CONTROL ) { m_rotating = true; m_baseAngle = m_angle; } } } void MouseUp( b2Vec2, int button ) override { if ( button == GLFW_MOUSE_BUTTON_1 ) { m_rayDrag = false; m_rotating = false; m_translating = false; } } void MouseMove( b2Vec2 p ) override { if ( m_rayDrag ) { m_rayEnd = p; } else if ( m_translating ) { m_transform.p.x = m_basePosition.x + 0.5f * ( p.x - m_startPosition.x ); m_transform.p.y = m_basePosition.y + 0.5f * ( p.y - m_startPosition.y ); } else if ( m_rotating ) { float dx = p.x - m_startPosition.x; m_angle = b2ClampFloat( m_baseAngle + 0.5f * dx, -B2_PI, B2_PI ); m_transform.q = b2MakeRot( m_angle ); } } void DrawRay( const b2CastOutput* output ) { b2Vec2 p1 = m_rayStart; b2Vec2 p2 = m_rayEnd; b2Vec2 d = b2Sub( p2, p1 ); if ( output->hit ) { b2Vec2 p; if ( output->fraction == 0.0f ) { assert( output->normal.x == 0.0f && output->normal.y == 0.0f ); p = output->point; DrawPoint( m_draw, output->point, 5.0, b2_colorPeru ); } else { p = b2MulAdd( p1, output->fraction, d ); DrawLine( m_draw, p1, p, b2_colorWhite ); DrawPoint( m_draw, p1, 5.0f, b2_colorGreen ); DrawPoint( m_draw, output->point, 5.0f, b2_colorWhite ); b2Vec2 n = b2MulAdd( p, 1.0f, output->normal ); DrawLine( m_draw, p, n, b2_colorViolet ); } if ( m_showFraction ) { b2Vec2 ps = { p.x + 0.05f, p.y - 0.02f }; DrawWorldString( m_draw, m_camera, ps, b2_colorWhite, "%.2f", output->fraction ); } } else { DrawLine( m_draw, p1, p2, b2_colorWhite ); DrawPoint( m_draw, p1, 5.0f, b2_colorGreen ); DrawPoint( m_draw, p2, 5.0f, b2_colorRed ); } } void Step() override { b2Vec2 offset = { -20.0f, 20.0f }; b2Vec2 increment = { 10.0f, 0.0f }; b2HexColor color1 = b2_colorYellow; b2CastOutput output = {}; float maxFraction = 1.0f; // circle { b2Transform transform = { b2Add( m_transform.p, offset ), m_transform.q }; b2Vec2 center = b2TransformPoint( transform, m_circle.center ); DrawSolidCircle( m_draw, { center, transform.q }, m_circle.radius, color1 ); b2Vec2 start = b2InvTransformPoint( transform, m_rayStart ); b2Vec2 translation = b2InvRotateVector( transform.q, b2Sub( m_rayEnd, m_rayStart ) ); b2RayCastInput input = { start, translation, maxFraction }; b2CastOutput localOutput = b2RayCastCircle( &m_circle, &input ); if ( localOutput.hit ) { output = localOutput; output.point = b2TransformPoint( transform, localOutput.point ); output.normal = b2RotateVector( transform.q, localOutput.normal ); maxFraction = localOutput.fraction; } offset = b2Add( offset, increment ); } // capsule { b2Transform transform = { b2Add( m_transform.p, offset ), m_transform.q }; b2Vec2 v1 = b2TransformPoint( transform, m_capsule.center1 ); b2Vec2 v2 = b2TransformPoint( transform, m_capsule.center2 ); DrawSolidCapsule( m_draw, v1, v2, m_capsule.radius, color1 ); b2Vec2 start = b2InvTransformPoint( transform, m_rayStart ); b2Vec2 translation = b2InvRotateVector( transform.q, b2Sub( m_rayEnd, m_rayStart ) ); b2RayCastInput input = { start, translation, maxFraction }; b2CastOutput localOutput = b2RayCastCapsule( &m_capsule, &input ); if ( localOutput.hit ) { output = localOutput; output.point = b2TransformPoint( transform, localOutput.point ); output.normal = b2RotateVector( transform.q, localOutput.normal ); maxFraction = localOutput.fraction; } offset = b2Add( offset, increment ); } // box { b2Transform transform = { b2Add( m_transform.p, offset ), m_transform.q }; DrawSolidPolygon( m_draw, transform, m_box.vertices, m_box.count, 0.0f, color1 ); b2Vec2 start = b2InvTransformPoint( transform, m_rayStart ); b2Vec2 translation = b2InvRotateVector( transform.q, b2Sub( m_rayEnd, m_rayStart ) ); b2RayCastInput input = { start, translation, maxFraction }; b2CastOutput localOutput = b2RayCastPolygon( &m_box, &input ); if ( localOutput.hit ) { output = localOutput; output.point = b2TransformPoint( transform, localOutput.point ); output.normal = b2RotateVector( transform.q, localOutput.normal ); maxFraction = localOutput.fraction; } offset = b2Add( offset, increment ); } // triangle { b2Transform transform = { b2Add( m_transform.p, offset ), m_transform.q }; DrawSolidPolygon( m_draw, transform, m_triangle.vertices, m_triangle.count, 0.0f, color1 ); b2Vec2 start = b2InvTransformPoint( transform, m_rayStart ); b2Vec2 translation = b2InvRotateVector( transform.q, b2Sub( m_rayEnd, m_rayStart ) ); b2RayCastInput input = { start, translation, maxFraction }; b2CastOutput localOutput = b2RayCastPolygon( &m_triangle, &input ); if ( localOutput.hit ) { output = localOutput; output.point = b2TransformPoint( transform, localOutput.point ); output.normal = b2RotateVector( transform.q, localOutput.normal ); maxFraction = localOutput.fraction; } offset = b2Add( offset, increment ); } // segment { b2Transform transform = { b2Add( m_transform.p, offset ), m_transform.q }; b2Vec2 p1 = b2TransformPoint( transform, m_segment.point1 ); b2Vec2 p2 = b2TransformPoint( transform, m_segment.point2 ); DrawLine( m_draw, p1, p2, color1 ); b2Vec2 start = b2InvTransformPoint( transform, m_rayStart ); b2Vec2 translation = b2InvRotateVector( transform.q, b2Sub( m_rayEnd, m_rayStart ) ); b2RayCastInput input = { start, translation, maxFraction }; b2CastOutput localOutput = b2RayCastSegment( &m_segment, &input, false ); if ( localOutput.hit ) { output = localOutput; output.point = b2TransformPoint( transform, localOutput.point ); output.normal = b2RotateVector( transform.q, localOutput.normal ); maxFraction = localOutput.fraction; } offset = b2Add( offset, increment ); } DrawRay( &output ); } static Sample* Create( SampleContext* context ) { return new RayCast( context ); } b2Polygon m_box; b2Polygon m_triangle; b2Circle m_circle; b2Capsule m_capsule; b2Segment m_segment; b2Transform m_transform; float m_angle; b2Vec2 m_rayStart; b2Vec2 m_rayEnd; b2Vec2 m_basePosition; float m_baseAngle; b2Vec2 m_startPosition; bool m_rayDrag; bool m_translating; bool m_rotating; bool m_showFraction; }; static int sampleIndex = RegisterSample( "Collision", "Ray Cast", RayCast::Create ); // This shows how to filter a specific shape using using data. struct ShapeUserData { int index; bool ignore; }; // Context for ray cast callbacks. Do what you want with this. struct CastContext { b2Vec2 points[3]; b2Vec2 normals[3]; float fractions[3]; int count; }; // This callback finds the closest hit. This is the most common callback used in games. static float RayCastClosestCallback( b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context ) { CastContext* rayContext = (CastContext*)context; ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData( shapeId ); // Ignore a specific shape. Also ignore initial overlap. if ( ( userData != nullptr && userData->ignore ) || fraction == 0.0f ) { // By returning -1, we instruct the calling code to ignore this shape and // continue the ray-cast to the next shape. return -1.0f; } rayContext->points[0] = point; rayContext->normals[0] = normal; rayContext->fractions[0] = fraction; rayContext->count = 1; // By returning the current fraction, we instruct the calling code to clip the ray and // continue the ray-cast to the next shape. WARNING: do not assume that shapes // are reported in order. However, by clipping, we can always get the closest shape. return fraction; } // This callback finds any hit. For this type of query we are usually just checking for obstruction, // so the hit data is not relevant. // NOTE: shape hits are not ordered, so this may not return the closest hit static float RayCastAnyCallback( b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context ) { CastContext* rayContext = (CastContext*)context; ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData( shapeId ); // Ignore a specific shape. Also ignore initial overlap. if ( ( userData != nullptr && userData->ignore ) || fraction == 0.0f ) { // By returning -1, we instruct the calling code to ignore this shape and // continue the ray-cast to the next shape. return -1.0f; } rayContext->points[0] = point; rayContext->normals[0] = normal; rayContext->fractions[0] = fraction; rayContext->count = 1; // At this point we have a hit, so we know the ray is obstructed. // By returning 0, we instruct the calling code to terminate the ray-cast. return 0.0f; } // This ray cast collects multiple hits along the ray. // The shapes are not necessary reported in order, so we might not capture // the closest shape. // NOTE: shape hits are not ordered, so this may return hits in any order. This means that // if you limit the number of results, you may discard the closest hit. You can see this // behavior in the sample. static float RayCastMultipleCallback( b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context ) { CastContext* rayContext = (CastContext*)context; ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData( shapeId ); // Ignore a specific shape. Also ignore initial overlap. if ( ( userData != nullptr && userData->ignore ) || fraction == 0.0f ) { // By returning -1, we instruct the calling code to ignore this shape and // continue the ray-cast to the next shape. return -1.0f; } int count = rayContext->count; assert( count < 3 ); rayContext->points[count] = point; rayContext->normals[count] = normal; rayContext->fractions[count] = fraction; rayContext->count = count + 1; if ( rayContext->count == 3 ) { // At this point the buffer is full. // By returning 0, we instruct the calling code to terminate the ray-cast. return 0.0f; } // By returning 1, we instruct the caller to continue without clipping the ray. return 1.0f; } // This ray cast collects multiple hits along the ray and sorts them. static float RayCastSortedCallback( b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context ) { CastContext* rayContext = (CastContext*)context; ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData( shapeId ); // Ignore a specific shape. Also ignore initial overlap. if ( ( userData != nullptr && userData->ignore ) || fraction == 0.0f ) { // By returning -1, we instruct the calling code to ignore this shape and // continue the ray-cast to the next shape. return -1.0f; } int count = rayContext->count; assert( count <= 3 ); int index = 3; while ( fraction < rayContext->fractions[index - 1] ) { index -= 1; if ( index == 0 ) { break; } } if ( index == 3 ) { // not closer, continue but tell the caller not to consider fractions further than the largest fraction acquired // this only happens once the buffer is full assert( rayContext->count == 3 ); assert( rayContext->fractions[2] <= 1.0f ); return rayContext->fractions[2]; } for ( int j = 2; j > index; --j ) { rayContext->points[j] = rayContext->points[j - 1]; rayContext->normals[j] = rayContext->normals[j - 1]; rayContext->fractions[j] = rayContext->fractions[j - 1]; } rayContext->points[index] = point; rayContext->normals[index] = normal; rayContext->fractions[index] = fraction; rayContext->count = count < 3 ? count + 1 : 3; if ( rayContext->count == 3 ) { return rayContext->fractions[2]; } // By returning 1, we instruct the caller to continue without clipping the ray. return 1.0f; } // This sample shows how to use the ray and shape cast functions on a b2World. This // sample is configured to ignore initial overlap. class CastWorld : public Sample { public: enum Mode { e_any = 0, e_closest = 1, e_multiple = 2, e_sorted = 3 }; enum CastType { e_rayCast = 0, e_circleCast = 1, e_capsuleCast = 2, e_polygonCast = 3 }; enum { e_maxCount = 64 }; explicit CastWorld( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 2.0f, 14.0f }; m_context->camera.zoom = 25.0f * 0.75f; } // Ground body { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -40.0f, 0.0f }, { 40.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { b2Vec2 vertices[3] = { { -0.1f, 0.0f }, { 0.1f, 0.0f }, { 0.0f, 1.5f } }; b2Hull hull = b2ComputeHull( vertices, 3 ); m_polygons[0] = b2MakePolygon( &hull, 0.0f ); m_polygons[0].radius = 0.5f; } { float w = 1.0f; float b = w / ( 2.0f + sqrtf( 2.0f ) ); float s = sqrtf( 2.0f ) * b; b2Vec2 vertices[8] = { { 0.5f * s, 0.0f }, { 0.5f * w, b }, { 0.5f * w, b + s }, { 0.5f * s, w }, { -0.5f * s, w }, { -0.5f * w, b + s }, { -0.5f * w, b }, { -0.5f * s, 0.0f } }; b2Hull hull = b2ComputeHull( vertices, 8 ); m_polygons[1] = b2MakePolygon( &hull, 0.0f ); } m_box = b2MakeBox( 0.5f, 0.5f ); m_capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, 0.25f }; m_circle = { { 0.0f, 0.0f }, 0.5f }; m_segment = { { -1.0f, 0.0f }, { 1.0f, 0.0f } }; m_bodyIndex = 0; for ( int i = 0; i < e_maxCount; ++i ) { m_bodyIds[i] = b2_nullBodyId; } m_mode = e_closest; m_ignoreIndex = 7; m_castType = e_rayCast; m_castRadius = 0.5f; m_rayStart = { -20.0f, 10.0f }; m_rayEnd = { 20.0f, 10.0f }; m_dragging = false; m_angle = 0.0f; m_baseAngle = 0.0f; m_angleAnchor = { 0.0f, 0.0f }; m_rotating = false; m_simple = false; } void Create( int index ) { if ( B2_IS_NON_NULL( m_bodyIds[m_bodyIndex] ) ) { b2DestroyBody( m_bodyIds[m_bodyIndex] ); m_bodyIds[m_bodyIndex] = b2_nullBodyId; } float x = RandomFloatRange( -20.0f, 20.0f ); float y = RandomFloatRange( 0.0f, 20.0f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { x, y }; bodyDef.rotation = b2MakeRot( RandomFloatRange( -B2_PI, B2_PI ) ); int mod = m_bodyIndex % 3; if ( mod == 0 ) { bodyDef.type = b2_staticBody; } else if ( mod == 1 ) { bodyDef.type = b2_kinematicBody; } else if ( mod == 2 ) { bodyDef.type = b2_dynamicBody; bodyDef.gravityScale = 0.0f; } m_bodyIds[m_bodyIndex] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.userData = m_userData + m_bodyIndex; m_userData[m_bodyIndex].ignore = false; if ( m_bodyIndex == m_ignoreIndex ) { m_userData[m_bodyIndex].ignore = true; } if ( index == 0 ) { int polygonIndex = ( m_bodyIndex & 1 ); b2CreatePolygonShape( m_bodyIds[m_bodyIndex], &shapeDef, m_polygons + polygonIndex ); } else if ( index == 1 ) { b2CreatePolygonShape( m_bodyIds[m_bodyIndex], &shapeDef, &m_box ); } else if ( index == 2 ) { b2CreateCircleShape( m_bodyIds[m_bodyIndex], &shapeDef, &m_circle ); } else if ( index == 3 ) { b2CreateCapsuleShape( m_bodyIds[m_bodyIndex], &shapeDef, &m_capsule ); } else if ( index == 4 ) { b2CreateSegmentShape( m_bodyIds[m_bodyIndex], &shapeDef, &m_segment ); } else { b2Vec2 points[4] = { { 1.0f, 0.0f }, { -1.0f, 0.0f }, { -1.0f, -1.0f }, { 1.0f, -1.0f } }; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = 4; chainDef.isLoop = true; b2CreateChain( m_bodyIds[m_bodyIndex], &chainDef ); } m_bodyIndex = ( m_bodyIndex + 1 ) % e_maxCount; } void CreateN( int index, int count ) { for ( int i = 0; i < count; ++i ) { Create( index ); } } void DestroyBody() { for ( int i = 0; i < e_maxCount; ++i ) { if ( B2_IS_NON_NULL( m_bodyIds[i] ) ) { b2DestroyBody( m_bodyIds[i] ); m_bodyIds[i] = b2_nullBodyId; return; } } } void MouseDown( b2Vec2 p, int button, int mods ) override { if ( button == GLFW_MOUSE_BUTTON_1 ) { if ( mods == 0 && m_rotating == false ) { m_rayStart = p; m_rayEnd = p; m_dragging = true; } else if ( mods == GLFW_MOD_SHIFT && m_dragging == false ) { m_rotating = true; m_angleAnchor = p; m_baseAngle = m_angle; } } } void MouseUp( b2Vec2, int button ) override { if ( button == GLFW_MOUSE_BUTTON_1 ) { m_dragging = false; m_rotating = false; } } void MouseMove( b2Vec2 p ) override { if ( m_dragging ) { m_rayEnd = p; } else if ( m_rotating ) { float dx = p.x - m_angleAnchor.x; m_angle = m_baseAngle + 1.0f * dx; } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 320.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); ImGui::Begin( "Ray-cast World", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); ImGui::Checkbox( "Simple", &m_simple ); if ( m_simple == false ) { const char* castTypes[] = { "Ray", "Circle", "Capsule", "Polygon" }; int castType = int( m_castType ); if ( ImGui::Combo( "Type", &castType, castTypes, IM_ARRAYSIZE( castTypes ) ) ) { m_castType = CastType( castType ); } if ( m_castType != e_rayCast ) { ImGui::SliderFloat( "Radius", &m_castRadius, 0.0f, 2.0f, "%.1f" ); } const char* modes[] = { "Any", "Closest", "Multiple", "Sorted" }; int mode = int( m_mode ); if ( ImGui::Combo( "Mode", &mode, modes, IM_ARRAYSIZE( modes ) ) ) { m_mode = Mode( mode ); } } if ( ImGui::Button( "Polygon" ) ) Create( 0 ); ImGui::SameLine(); if ( ImGui::Button( "10x##Poly" ) ) CreateN( 0, 10 ); if ( ImGui::Button( "Box" ) ) Create( 1 ); ImGui::SameLine(); if ( ImGui::Button( "10x##Box" ) ) CreateN( 1, 10 ); if ( ImGui::Button( "Circle" ) ) Create( 2 ); ImGui::SameLine(); if ( ImGui::Button( "10x##Circle" ) ) CreateN( 2, 10 ); if ( ImGui::Button( "Capsule" ) ) Create( 3 ); ImGui::SameLine(); if ( ImGui::Button( "10x##Capsule" ) ) CreateN( 3, 10 ); if ( ImGui::Button( "Segment" ) ) Create( 4 ); ImGui::SameLine(); if ( ImGui::Button( "10x##Segment" ) ) CreateN( 4, 10 ); if ( ImGui::Button( "Chain" ) ) Create( 5 ); ImGui::SameLine(); if ( ImGui::Button( "10x##Chain" ) ) CreateN( 5, 10 ); if ( ImGui::Button( "Destroy Shape" ) ) { DestroyBody(); } ImGui::End(); } void Step() override { Sample::Step(); DrawTextLine( "Click left mouse button and drag to modify ray cast" ); DrawTextLine( "Shape 7 is intentionally ignored by the ray" ); b2HexColor color1 = b2_colorGreen; b2HexColor color2 = b2_colorLightGray; b2HexColor color3 = b2_colorMagenta; b2Vec2 rayTranslation = b2Sub( m_rayEnd, m_rayStart ); if ( m_simple ) { DrawTextLine( "Simple closest point ray cast" ); // This version doesn't have a callback, but it doesn't skip the ignored shape b2RayResult result = b2World_CastRayClosest( m_worldId, m_rayStart, rayTranslation, b2DefaultQueryFilter() ); if ( result.hit == true && result.fraction > 0.0f ) { b2Vec2 c = b2MulAdd( m_rayStart, result.fraction, rayTranslation ); DrawPoint( m_draw, result.point, 5.0f, color1 ); DrawLine( m_draw, m_rayStart, c, color2 ); b2Vec2 head = b2MulAdd( result.point, 0.5f, result.normal ); DrawLine( m_draw, result.point, head, color3 ); } else { DrawLine( m_draw, m_rayStart, m_rayEnd, color2 ); } } else { switch ( m_mode ) { case e_any: DrawTextLine( "Cast mode: any - check for obstruction - unsorted" ); break; case e_closest: DrawTextLine( "Cast mode: closest - find closest shape along the cast" ); break; case e_multiple: DrawTextLine( "Cast mode: multiple - gather up to 3 shapes - unsorted" ); break; case e_sorted: DrawTextLine( "Cast mode: sorted - gather up to 3 shapes sorted by closeness" ); break; default: assert( false ); break; } b2CastResultFcn* functions[] = { RayCastAnyCallback, RayCastClosestCallback, RayCastMultipleCallback, RayCastSortedCallback, }; b2CastResultFcn* modeFcn = functions[m_mode]; CastContext context = {}; // Must initialize fractions for sorting context.fractions[0] = FLT_MAX; context.fractions[1] = FLT_MAX; context.fractions[2] = FLT_MAX; b2Transform transform = { m_rayStart, b2MakeRot( m_angle ) }; b2Circle circle = { .center = m_rayStart, .radius = m_castRadius }; b2Capsule capsule = { b2TransformPoint( transform, { -0.25f, 0.0f } ), b2TransformPoint( transform, { 0.25f, 0.0f } ), m_castRadius }; b2Polygon box = b2MakeOffsetRoundedBox( 0.125f, 0.25f, transform.p, transform.q, m_castRadius ); b2ShapeProxy proxy = {}; if ( m_castType == e_rayCast ) { b2World_CastRay( m_worldId, m_rayStart, rayTranslation, b2DefaultQueryFilter(), modeFcn, &context ); } else { if ( m_castType == e_circleCast ) { proxy = b2MakeProxy( &circle.center, 1, circle.radius ); } else if ( m_castType == e_capsuleCast ) { proxy = b2MakeProxy( &capsule.center1, 2, capsule.radius ); } else { proxy = b2MakeProxy( box.vertices, box.count, box.radius ); } b2World_CastShape( m_worldId, &proxy, rayTranslation, b2DefaultQueryFilter(), modeFcn, &context ); } if ( context.count > 0 ) { assert( context.count <= 3 ); b2HexColor colors[3] = { b2_colorRed, b2_colorGreen, b2_colorBlue }; for ( int i = 0; i < context.count; ++i ) { b2Vec2 c = b2MulAdd( m_rayStart, context.fractions[i], rayTranslation ); b2Vec2 p = context.points[i]; b2Vec2 n = context.normals[i]; DrawPoint( m_draw, p, 5.0f, colors[i] ); DrawLine( m_draw, m_rayStart, c, color2 ); b2Vec2 head = b2MulAdd( p, 1.0f, n ); DrawLine( m_draw, p, head, color3 ); b2Vec2 t = b2MulSV( context.fractions[i], rayTranslation ); b2Transform shiftedTransform = { t, b2Rot_identity }; if ( m_castType == e_circleCast ) { b2Vec2 center = b2TransformPoint( shiftedTransform, circle.center ); DrawSolidCircle( m_draw, { center, shiftedTransform.q }, m_castRadius, b2_colorYellow ); } else if ( m_castType == e_capsuleCast ) { b2Vec2 p1 = capsule.center1 + t; b2Vec2 p2 = capsule.center2 + t; DrawSolidCapsule( m_draw, p1, p2, m_castRadius, b2_colorYellow ); } else if ( m_castType == e_polygonCast ) { DrawSolidPolygon( m_draw, shiftedTransform, box.vertices, box.count, box.radius, b2_colorYellow ); } } } else { DrawLine( m_draw, m_rayStart, m_rayEnd, color2 ); b2Transform shiftedTransform = { rayTranslation, b2Rot_identity }; if ( m_castType == e_circleCast ) { b2Vec2 center = b2TransformPoint( shiftedTransform, circle.center ); DrawSolidCircle( m_draw, { center, shiftedTransform.q }, m_castRadius, b2_colorGray ); } else if ( m_castType == e_capsuleCast ) { b2Vec2 p1 = capsule.center1 + rayTranslation; b2Vec2 p2 = capsule.center2 + rayTranslation; DrawSolidCapsule( m_draw, p1, p2, m_castRadius, b2_colorYellow ); } else if ( m_castType == e_polygonCast ) { DrawSolidPolygon( m_draw, shiftedTransform, box.vertices, box.count, box.radius, b2_colorYellow ); } } } DrawPoint( m_draw, m_rayStart, 5.0f, b2_colorGreen ); if ( B2_IS_NON_NULL( m_bodyIds[m_ignoreIndex] ) ) { b2Vec2 p = b2Body_GetPosition( m_bodyIds[m_ignoreIndex] ); p.x -= 0.2f; DrawWorldString( m_draw, m_camera, p, b2_colorWhite, "ign" ); } } static Sample* Create( SampleContext* context ) { return new CastWorld( context ); } int m_bodyIndex; b2BodyId m_bodyIds[e_maxCount] = {}; ShapeUserData m_userData[e_maxCount] = {}; b2Polygon m_polygons[2] = {}; b2Polygon m_box; b2Capsule m_capsule; b2Circle m_circle; b2Segment m_segment; bool m_simple; int m_mode; int m_ignoreIndex; CastType m_castType; float m_castRadius; b2Vec2 m_angleAnchor; float m_baseAngle; float m_angle; bool m_rotating; b2Vec2 m_rayStart; b2Vec2 m_rayEnd; bool m_dragging; }; static int sampleRayCastWorld = RegisterSample( "Collision", "Cast World", CastWorld::Create ); class OverlapWorld : public Sample { public: enum { e_circleShape = 0, e_capsuleShape = 1, e_boxShape = 2 }; enum { e_maxCount = 64, e_maxDoomed = 16, }; static bool OverlapResultFcn( b2ShapeId shapeId, void* context ) { ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData( shapeId ); if ( userData != nullptr && userData->ignore ) { // continue the query return true; } OverlapWorld* sample = (OverlapWorld*)context; if ( sample->m_doomCount < e_maxDoomed ) { int index = sample->m_doomCount; sample->m_doomIds[index] = shapeId; sample->m_doomCount += 1; } // continue the query return true; } explicit OverlapWorld( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 10.0f }; m_context->camera.zoom = 25.0f * 0.7f; } { b2Vec2 vertices[3] = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, { 0.0f, 1.5f } }; b2Hull hull = b2ComputeHull( vertices, 3 ); m_polygons[0] = b2MakePolygon( &hull, 0.0f ); } { b2Vec2 vertices[3] = { { -0.1f, 0.0f }, { 0.1f, 0.0f }, { 0.0f, 1.5f } }; b2Hull hull = b2ComputeHull( vertices, 3 ); m_polygons[1] = b2MakePolygon( &hull, 0.0f ); } { float w = 1.0f; float b = w / ( 2.0f + sqrtf( 2.0f ) ); float s = sqrtf( 2.0f ) * b; b2Vec2 vertices[8] = { { 0.5f * s, 0.0f }, { 0.5f * w, b }, { 0.5f * w, b + s }, { 0.5f * s, w }, { -0.5f * s, w }, { -0.5f * w, b + s }, { -0.5f * w, b }, { -0.5f * s, 0.0f } }; b2Hull hull = b2ComputeHull( vertices, 8 ); m_polygons[2] = b2MakePolygon( &hull, 0.0f ); } m_polygons[3] = b2MakeBox( 0.5f, 0.5f ); m_capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, 0.25f }; m_circle = { { 0.0f, 0.0f }, 0.5f }; m_segment = { { -1.0f, 0.0f }, { 1.0f, 0.0f } }; m_bodyIndex = 0; for ( int i = 0; i < e_maxCount; ++i ) { m_bodyIds[i] = b2_nullBodyId; } m_ignoreIndex = 7; m_shapeType = e_circleShape; m_position = { 0.0f, 10.0f }; m_angle = 0.0f; m_dragging = false; m_rotating = false; m_doomCount = 0; CreateN( 0, 10 ); } void Create( int index ) { if ( B2_IS_NON_NULL( m_bodyIds[m_bodyIndex] ) ) { b2DestroyBody( m_bodyIds[m_bodyIndex] ); m_bodyIds[m_bodyIndex] = b2_nullBodyId; } float x = RandomFloatRange( -20.0f, 20.0f ); float y = RandomFloatRange( 0.0f, 20.0f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { x, y }; bodyDef.rotation = b2MakeRot( RandomFloatRange( -B2_PI, B2_PI ) ); m_bodyIds[m_bodyIndex] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.userData = m_userData + m_bodyIndex; m_userData[m_bodyIndex].index = m_bodyIndex; m_userData[m_bodyIndex].ignore = false; if ( m_bodyIndex == m_ignoreIndex ) { m_userData[m_bodyIndex].ignore = true; } if ( index < 4 ) { b2CreatePolygonShape( m_bodyIds[m_bodyIndex], &shapeDef, m_polygons + index ); } else if ( index == 4 ) { b2CreateCircleShape( m_bodyIds[m_bodyIndex], &shapeDef, &m_circle ); } else if ( index == 5 ) { b2CreateCapsuleShape( m_bodyIds[m_bodyIndex], &shapeDef, &m_capsule ); } else { b2CreateSegmentShape( m_bodyIds[m_bodyIndex], &shapeDef, &m_segment ); } m_bodyIndex = ( m_bodyIndex + 1 ) % e_maxCount; } void CreateN( int index, int count ) { for ( int i = 0; i < count; ++i ) { Create( index ); } } void DestroyBody() { for ( int i = 0; i < e_maxCount; ++i ) { if ( B2_IS_NON_NULL( m_bodyIds[i] ) ) { b2DestroyBody( m_bodyIds[i] ); m_bodyIds[i] = b2_nullBodyId; return; } } } void MouseDown( b2Vec2 p, int button, int mods ) override { if ( button == GLFW_MOUSE_BUTTON_1 ) { if ( mods == 0 && m_rotating == false ) { m_dragging = true; m_position = p; } else if ( mods == GLFW_MOD_SHIFT && m_dragging == false ) { m_rotating = true; m_startPosition = p; m_baseAngle = m_angle; } } } void MouseUp( b2Vec2, int button ) override { if ( button == GLFW_MOUSE_BUTTON_1 ) { m_dragging = false; m_rotating = false; } } void MouseMove( b2Vec2 p ) override { if ( m_dragging ) { m_position = p; } else if ( m_rotating ) { float dx = p.x - m_startPosition.x; m_angle = m_baseAngle + 1.0f * dx; } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 330.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 140.0f, height ) ); ImGui::Begin( "Overlap World", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); if ( ImGui::Button( "Polygon 1" ) ) Create( 0 ); ImGui::SameLine(); if ( ImGui::Button( "10x##Poly1" ) ) CreateN( 0, 10 ); if ( ImGui::Button( "Polygon 2" ) ) Create( 1 ); ImGui::SameLine(); if ( ImGui::Button( "10x##Poly2" ) ) CreateN( 1, 10 ); if ( ImGui::Button( "Polygon 3" ) ) Create( 2 ); ImGui::SameLine(); if ( ImGui::Button( "10x##Poly3" ) ) CreateN( 2, 10 ); if ( ImGui::Button( "Box" ) ) Create( 3 ); ImGui::SameLine(); if ( ImGui::Button( "10x##Box" ) ) CreateN( 3, 10 ); if ( ImGui::Button( "Circle" ) ) Create( 4 ); ImGui::SameLine(); if ( ImGui::Button( "10x##Circle" ) ) CreateN( 4, 10 ); if ( ImGui::Button( "Capsule" ) ) Create( 5 ); ImGui::SameLine(); if ( ImGui::Button( "10x##Capsule" ) ) CreateN( 5, 10 ); if ( ImGui::Button( "Segment" ) ) Create( 6 ); ImGui::SameLine(); if ( ImGui::Button( "10x##Segment" ) ) CreateN( 6, 10 ); if ( ImGui::Button( "Destroy Shape" ) ) { DestroyBody(); } ImGui::Separator(); ImGui::Text( "Overlap Shape" ); ImGui::RadioButton( "Circle##Overlap", &m_shapeType, e_circleShape ); ImGui::RadioButton( "Capsule##Overlap", &m_shapeType, e_capsuleShape ); ImGui::RadioButton( "Box##Overlap", &m_shapeType, e_boxShape ); ImGui::End(); } void Step() override { Sample::Step(); DrawTextLine( "left mouse button: drag query shape" ); DrawTextLine( "left mouse button + shift: rotate query shape" ); m_doomCount = 0; b2Transform transform = { m_position, b2MakeRot( m_angle ) }; b2ShapeProxy proxy = {}; if ( m_shapeType == e_circleShape ) { b2Circle circle = { .center = transform.p, .radius = 1.0f, }; proxy = b2MakeProxy( &circle.center, 1, circle.radius ); DrawSolidCircle( m_draw, { circle.center, b2Rot_identity }, circle.radius, b2_colorWhite ); } else if ( m_shapeType == e_capsuleShape ) { b2Capsule capsule = { .center1 = b2TransformPoint( transform, { -1.0f, 0.0f } ), .center2 = b2TransformPoint( transform, { 1.0f, 0.0f } ), .radius = 0.5f, }; proxy = b2MakeProxy( &capsule.center1, 2, capsule.radius ); DrawSolidCapsule( m_draw, capsule.center1, capsule.center2, capsule.radius, b2_colorWhite ); } else if ( m_shapeType == e_boxShape ) { b2Polygon box = b2MakeOffsetBox( 2.0f, 0.5f, transform.p, transform.q ); proxy = b2MakeProxy( box.vertices, box.count, box.radius ); DrawPolygon( m_draw, box.vertices, box.count, b2_colorWhite ); } b2World_OverlapShape( m_worldId, &proxy, b2DefaultQueryFilter(), OverlapResultFcn, this ); if ( B2_IS_NON_NULL( m_bodyIds[m_ignoreIndex] ) ) { b2Vec2 p = b2Body_GetPosition( m_bodyIds[m_ignoreIndex] ); p.x -= 0.2f; DrawWorldString( m_draw, m_camera, p, b2_colorWhite, "skip" ); } for ( int i = 0; i < m_doomCount; ++i ) { b2ShapeId shapeId = m_doomIds[i]; ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData( shapeId ); if ( userData == nullptr ) { continue; } int index = userData->index; assert( 0 <= index && index < e_maxCount ); assert( B2_IS_NON_NULL( m_bodyIds[index] ) ); b2DestroyBody( m_bodyIds[index] ); m_bodyIds[index] = b2_nullBodyId; } } static Sample* Create( SampleContext* context ) { return new OverlapWorld( context ); } int m_bodyIndex; b2BodyId m_bodyIds[e_maxCount]; ShapeUserData m_userData[e_maxCount]; b2Polygon m_polygons[4]; b2Capsule m_capsule; b2Circle m_circle; b2Segment m_segment; int m_ignoreIndex; b2ShapeId m_doomIds[e_maxDoomed]; int m_doomCount; int m_shapeType; b2Transform m_transform; b2Vec2 m_startPosition; b2Vec2 m_position; b2Vec2 m_basePosition; float m_angle; float m_baseAngle; bool m_dragging; bool m_rotating; }; static int sampleOverlapWorld = RegisterSample( "Collision", "Overlap World", OverlapWorld::Create ); // Tests manifolds and contact points class Manifold : public Sample { public: explicit Manifold( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { // m_context->camera.m_center = {1.8f, 15.0f}; m_context->camera.center = { 1.8f, 0.0f }; m_context->camera.zoom = 25.0f * 0.45f; } m_smgroxCache1 = b2_emptySimplexCache; m_smgroxCache2 = b2_emptySimplexCache; m_smgcapCache1 = b2_emptySimplexCache; m_smgcapCache2 = b2_emptySimplexCache; m_transform = b2Transform_identity; m_transform.p.x = 0.17f; m_transform.p.y = 1.12f; // m_transform.q = b2MakeRot( 0.5f * b2_pi ); m_angle = 0.0f; m_round = 0.1f; m_startPoint = { 0.0f, 0.0f }; m_basePosition = { 0.0f, 0.0f }; m_baseAngle = 0.0f; m_dragging = false; m_rotating = false; m_showCount = false; m_showIds = false; m_showSeparation = false; m_showAnchors = false; m_enableCaching = true; b2Vec2 points[3] = { { -0.1f, -0.5f }, { 0.1f, -0.5f }, { 0.0f, 0.5f } }; m_wedge = b2ComputeHull( points, 3 ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 24.0f * fontSize; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 20.0f * fontSize, height ) ); ImGui::Begin( "Manifold", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 14.0f * fontSize ); ImGui::SliderFloat( "x offset", &m_transform.p.x, -2.0f, 2.0f, "%.2f" ); ImGui::SliderFloat( "y offset", &m_transform.p.y, -2.0f, 2.0f, "%.2f" ); if ( ImGui::SliderFloat( "angle", &m_angle, -B2_PI, B2_PI, "%.2f" ) ) { m_transform.q = b2MakeRot( m_angle ); } ImGui::SliderFloat( "round", &m_round, 0.0f, 0.4f, "%.1f" ); ImGui::PopItemWidth(); ImGui::Separator(); ImGui::Checkbox( "show count", &m_showCount ); ImGui::Checkbox( "show ids", &m_showIds ); ImGui::Checkbox( "show separation", &m_showSeparation ); ImGui::Checkbox( "show anchors", &m_showAnchors ); ImGui::Checkbox( "enable caching", &m_enableCaching ); if ( ImGui::Button( "Reset" ) ) { m_transform = b2Transform_identity; m_angle = 0.0f; } ImGui::Separator(); ImGui::Text( "mouse button 1: drag" ); ImGui::Text( "mouse button 1 + shift: rotate" ); ImGui::End(); } void MouseDown( b2Vec2 p, int button, int mods ) override { if ( button == GLFW_MOUSE_BUTTON_1 ) { if ( mods == 0 && m_rotating == false ) { m_dragging = true; m_startPoint = p; m_basePosition = m_transform.p; } else if ( mods == GLFW_MOD_SHIFT && m_dragging == false ) { m_rotating = true; m_startPoint = p; m_baseAngle = m_angle; } } } void MouseUp( b2Vec2, int button ) override { if ( button == GLFW_MOUSE_BUTTON_1 ) { m_dragging = false; m_rotating = false; } } void MouseMove( b2Vec2 p ) override { if ( m_dragging ) { m_transform.p.x = m_basePosition.x + 0.5f * ( p.x - m_startPoint.x ); m_transform.p.y = m_basePosition.y + 0.5f * ( p.y - m_startPoint.y ); } else if ( m_rotating ) { float dx = p.x - m_startPoint.x; m_angle = b2ClampFloat( m_baseAngle + 1.0f * dx, -B2_PI, B2_PI ); m_transform.q = b2MakeRot( m_angle ); } } void DrawManifold( const b2Manifold* manifold, b2Vec2 origin1, b2Vec2 origin2 ) { if ( m_showCount ) { b2Vec2 p = 0.5f * ( origin1 + origin2 ); DrawWorldString( m_draw, m_camera, p, b2_colorWhite, "%d", manifold->pointCount ); } for ( int i = 0; i < manifold->pointCount; ++i ) { const b2ManifoldPoint* mp = manifold->points + i; b2Vec2 p1 = mp->point; b2Vec2 p2 = b2MulAdd( p1, 0.5f, manifold->normal ); DrawLine( m_draw, p1, p2, b2_colorViolet ); if ( m_showAnchors ) { DrawPoint( m_draw, b2Add( origin1, mp->anchorA ), 5.0f, b2_colorRed ); DrawPoint( m_draw, b2Add( origin2, mp->anchorB ), 5.0f, b2_colorGreen ); } else { DrawPoint( m_draw, p1, 10.0f, b2_colorBlue ); } if ( m_showIds ) { // uint32_t indexA = mp->id >> 8; // uint32_t indexB = 0xFF & mp->id; b2Vec2 p = { p1.x + 0.05f, p1.y - 0.02f }; DrawWorldString( m_draw, m_camera, p, b2_colorWhite, "0x%04x", mp->id ); } if ( m_showSeparation ) { b2Vec2 p = { p1.x + 0.05f, p1.y + 0.03f }; DrawWorldString( m_draw, m_camera, p, b2_colorWhite, "%.3f", mp->separation ); } } } void Step() override { b2Vec2 offset = { -10.0f, -5.0f }; b2Vec2 increment = { 4.0f, 0.0f }; b2HexColor color1 = b2_colorAquamarine; b2HexColor color2 = b2_colorPaleGoldenRod; if ( m_enableCaching == false ) { m_smgroxCache1 = b2_emptySimplexCache; m_smgroxCache2 = b2_emptySimplexCache; m_smgcapCache1 = b2_emptySimplexCache; m_smgcapCache2 = b2_emptySimplexCache; } #if 1 // circle-circle { b2Circle circle1 = { { 0.0f, 0.0f }, 0.5f }; b2Circle circle2 = { { 0.0f, 0.0f }, 1.0f }; b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; b2Manifold m = b2CollideCircles( &circle1, transform1, &circle2, transform2 ); b2Vec2 center1 = b2TransformPoint( transform1, circle1.center ); DrawSolidCircle( m_draw, { center1, transform1.q }, circle1.radius, color1 ); b2Vec2 center2 = b2TransformPoint( transform2, circle2.center ); DrawSolidCircle( m_draw, { center2, transform2.q }, circle2.radius, color2 ); DrawManifold( &m, transform1.p, transform2.p ); offset = b2Add( offset, increment ); } // capsule-circle { b2Capsule capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, 0.25f }; b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; b2Manifold m = b2CollideCapsuleAndCircle( &capsule, transform1, &circle, transform2 ); b2Vec2 v1 = b2TransformPoint( transform1, capsule.center1 ); b2Vec2 v2 = b2TransformPoint( transform1, capsule.center2 ); DrawSolidCapsule( m_draw, v1, v2, capsule.radius, color1 ); b2Vec2 center = b2TransformPoint( transform2, circle.center ); DrawSolidCircle( m_draw, { center, transform2.q }, circle.radius, color2 ); DrawManifold( &m, transform1.p, transform2.p ); offset = b2Add( offset, increment ); } // segment-circle { b2Segment segment = { { -1.0f, 0.0f }, { 1.0f, 0.0f } }; b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; b2Manifold m = b2CollideSegmentAndCircle( &segment, transform1, &circle, transform2 ); b2Vec2 p1 = b2TransformPoint( transform1, segment.point1 ); b2Vec2 p2 = b2TransformPoint( transform1, segment.point2 ); DrawLine( m_draw, p1, p2, color1 ); b2Vec2 center = b2TransformPoint( transform2, circle.center ); DrawSolidCircle( m_draw, { center, transform2.q }, circle.radius, color2 ); DrawManifold( &m, transform1.p, transform2.p ); offset = b2Add( offset, increment ); } // box-circle { b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; b2Polygon box = b2MakeSquare( 0.5f ); box.radius = m_round; b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; b2Manifold m = b2CollidePolygonAndCircle( &box, transform1, &circle, transform2 ); DrawSolidPolygon( m_draw, transform1, box.vertices, box.count, m_round, color1 ); b2Vec2 center = b2TransformPoint( transform2, circle.center ); DrawSolidCircle( m_draw, { center, transform2.q }, circle.radius, color2 ); DrawManifold( &m, transform1.p, transform2.p ); offset = b2Add( offset, increment ); } // capsule-capsule { b2Capsule capsule1 = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, 0.25f }; b2Capsule capsule2 = { { 0.25f, 0.0f }, { 1.0f, 0.0f }, 0.1f }; b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; b2Manifold m = b2CollideCapsules( &capsule1, transform1, &capsule2, transform2 ); b2Vec2 v1 = b2TransformPoint( transform1, capsule1.center1 ); b2Vec2 v2 = b2TransformPoint( transform1, capsule1.center2 ); DrawSolidCapsule( m_draw, v1, v2, capsule1.radius, color1 ); v1 = b2TransformPoint( transform2, capsule2.center1 ); v2 = b2TransformPoint( transform2, capsule2.center2 ); DrawSolidCapsule( m_draw, v1, v2, capsule2.radius, color2 ); DrawManifold( &m, transform1.p, transform2.p ); offset = b2Add( offset, increment ); } // box-capsule { b2Capsule capsule = { { -0.4f, 0.0f }, { -0.1f, 0.0f }, 0.1f }; b2Polygon box = b2MakeOffsetBox( 0.25f, 1.0f, { 1.0f, -1.0f }, b2MakeRot( 0.25f * B2_PI ) ); b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; b2Manifold m = b2CollidePolygonAndCapsule( &box, transform1, &capsule, transform2 ); DrawSolidPolygon( m_draw, transform1, box.vertices, box.count, box.radius, color1 ); b2Vec2 v1 = b2TransformPoint( transform2, capsule.center1 ); b2Vec2 v2 = b2TransformPoint( transform2, capsule.center2 ); DrawSolidCapsule( m_draw, v1, v2, capsule.radius, color2 ); DrawManifold( &m, transform1.p, transform2.p ); offset = b2Add( offset, increment ); } // segment-capsule { b2Segment segment = { { -1.0f, 0.0f }, { 1.0f, 0.0f } }; b2Capsule capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, 0.25f }; b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; b2Manifold m = b2CollideSegmentAndCapsule( &segment, transform1, &capsule, transform2 ); b2Vec2 p1 = b2TransformPoint( transform1, segment.point1 ); b2Vec2 p2 = b2TransformPoint( transform1, segment.point2 ); DrawLine( m_draw, p1, p2, color1 ); p1 = b2TransformPoint( transform2, capsule.center1 ); p2 = b2TransformPoint( transform2, capsule.center2 ); DrawSolidCapsule( m_draw, p1, p2, capsule.radius, color2 ); DrawManifold( &m, transform1.p, transform2.p ); offset = b2Add( offset, increment ); } offset = { -10.0f, 0.0f }; #endif #if 1 // square-square { b2Polygon box1 = b2MakeSquare( 0.5f ); b2Polygon box = b2MakeSquare( 0.5f ); b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; b2Manifold m = b2CollidePolygons( &box1, transform1, &box, transform2 ); DrawSolidPolygon( m_draw, transform1, box1.vertices, box1.count, box1.radius, color1 ); DrawSolidPolygon( m_draw, transform2, box.vertices, box.count, box.radius, color2 ); DrawManifold( &m, transform1.p, transform2.p ); offset = b2Add( offset, increment ); } // box-box { b2Polygon box1 = b2MakeBox( 2.0f, 0.1f ); b2Polygon box = b2MakeSquare( 0.25f ); b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; // b2Transform transform2 = {b2Add({0.0f, -0.1f}, offset), {0.0f, 1.0f}}; b2Manifold m = b2CollidePolygons( &box1, transform1, &box, transform2 ); DrawSolidPolygon( m_draw, transform1, box1.vertices, box1.count, box1.radius, color1 ); DrawSolidPolygon( m_draw, transform2, box.vertices, box.count, box.radius, color2 ); DrawManifold( &m, transform1.p, transform2.p ); offset = b2Add( offset, increment ); } // box-rox { b2Polygon box = b2MakeSquare( 0.5f ); float h = 0.5f - m_round; b2Polygon rox = b2MakeRoundedBox( h, h, m_round ); b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; // b2Transform transform2 = {b2Add({0.0f, -0.1f}, offset), {0.0f, 1.0f}}; b2Manifold m = b2CollidePolygons( &box, transform1, &rox, transform2 ); DrawSolidPolygon( m_draw, transform1, box.vertices, box.count, box.radius, color1 ); DrawSolidPolygon( m_draw, transform2, rox.vertices, rox.count, rox.radius, color2 ); DrawManifold( &m, transform1.p, transform2.p ); offset = b2Add( offset, increment ); } // rox-rox { float h = 0.5f - m_round; b2Polygon rox = b2MakeRoundedBox( h, h, m_round ); b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; // b2Transform transform1 = {{6.48024225f, 2.07872653f}, {-0.938356698f, 0.345668465f}}; // b2Transform transform2 = {{5.52862263f, 2.51146317f}, {-0.859374702f, -0.511346340f}}; b2Manifold m = b2CollidePolygons( &rox, transform1, &rox, transform2 ); DrawSolidPolygon( m_draw, transform1, rox.vertices, rox.count, rox.radius, color1 ); DrawSolidPolygon( m_draw, transform2, rox.vertices, rox.count, rox.radius, color2 ); DrawManifold( &m, transform1.p, transform2.p ); offset = b2Add( offset, increment ); } // segment-rox { b2Segment segment = { { -1.0f, 0.0f }, { 1.0f, 0.0f } }; float h = 0.5f - m_round; b2Polygon rox = b2MakeRoundedBox( h, h, m_round ); b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; // b2Transform transform2 = {b2Add({-1.44583416f, 0.397352695f}, offset), m_transform.q}; b2Manifold m = b2CollideSegmentAndPolygon( &segment, transform1, &rox, transform2 ); b2Vec2 p1 = b2TransformPoint( transform1, segment.point1 ); b2Vec2 p2 = b2TransformPoint( transform1, segment.point2 ); DrawLine( m_draw, p1, p2, color1 ); DrawSolidPolygon( m_draw, transform2, rox.vertices, rox.count, rox.radius, color2 ); DrawManifold( &m, transform1.p, transform2.p ); offset = b2Add( offset, increment ); } #endif // wox-wox { b2Polygon wox = b2MakePolygon( &m_wedge, m_round ); b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; // b2Transform transform2 = {b2Add({0.0f, -0.1f}, offset), {0.0f, 1.0f}}; b2Manifold m = b2CollidePolygons( &wox, transform1, &wox, transform2 ); DrawSolidPolygon( m_draw, transform1, wox.vertices, wox.count, wox.radius, color1 ); DrawSolidPolygon( m_draw, transform1, wox.vertices, wox.count, 0.0f, color1 ); DrawSolidPolygon( m_draw, transform2, wox.vertices, wox.count, wox.radius, color2 ); DrawSolidPolygon( m_draw, transform2, wox.vertices, wox.count, 0.0f, color2 ); DrawManifold( &m, transform1.p, transform2.p ); offset = b2Add( offset, increment ); } #if 1 // wox-wox { b2Vec2 p1s[3] = { { 0.175740838, 0.224936664 }, { -0.301293969, 0.194021404 }, { -0.105151534, -0.432157338 } }; b2Vec2 p2s[3] = { { -0.427884758, -0.225028217 }, { 0.0566576123, -0.128772855 }, { 0.176625848, 0.338923335 } }; b2Hull h1 = b2ComputeHull( p1s, 3 ); b2Hull h2 = b2ComputeHull( p2s, 3 ); b2Polygon w1 = b2MakePolygon( &h1, 0.158798501 ); b2Polygon w2 = b2MakePolygon( &h2, 0.205900759 ); b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; // b2Transform transform2 = {b2Add({0.0f, -0.1f}, offset), {0.0f, 1.0f}}; b2Manifold m = b2CollidePolygons( &w1, transform1, &w2, transform2 ); DrawSolidPolygon( m_draw, transform1, w1.vertices, w1.count, w1.radius, color1 ); DrawSolidPolygon( m_draw, transform1, w1.vertices, w1.count, 0.0f, color1 ); DrawSolidPolygon( m_draw, transform2, w2.vertices, w2.count, w2.radius, color2 ); DrawSolidPolygon( m_draw, transform2, w2.vertices, w2.count, 0.0f, color2 ); DrawManifold( &m, transform1.p, transform2.p ); offset = b2Add( offset, increment ); } offset = { -10.0f, 5.0f }; // box-triangle { b2Polygon box = b2MakeBox( 1.0f, 1.0f ); b2Vec2 points[3] = { { -0.05f, 0.0f }, { 0.05f, 0.0f }, { 0.0f, 0.1f } }; b2Hull hull = b2ComputeHull( points, 3 ); b2Polygon tri = b2MakePolygon( &hull, 0.0f ); b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; // b2Transform transform2 = {b2Add({0.0f, -0.1f}, offset), {0.0f, 1.0f}}; b2Manifold m = b2CollidePolygons( &box, transform1, &tri, transform2 ); DrawSolidPolygon( m_draw, transform1, box.vertices, box.count, 0.0f, color1 ); DrawSolidPolygon( m_draw, transform2, tri.vertices, tri.count, 0.0f, color2 ); DrawManifold( &m, transform1.p, transform2.p ); offset = b2Add( offset, increment ); } // chain-segment vs circle { b2ChainSegment segment = { { 2.0f, 1.0f }, { { 1.0f, 1.0f }, { -1.0f, 0.0f } }, { -2.0f, 0.0f }, -1 }; b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; b2Manifold m = b2CollideChainSegmentAndCircle( &segment, transform1, &circle, transform2 ); b2Vec2 g1 = b2TransformPoint( transform1, segment.ghost1 ); b2Vec2 g2 = b2TransformPoint( transform1, segment.ghost2 ); b2Vec2 p1 = b2TransformPoint( transform1, segment.segment.point1 ); b2Vec2 p2 = b2TransformPoint( transform1, segment.segment.point2 ); DrawLine( m_draw, g1, p1, b2_colorLightGray ); DrawLine( m_draw, p1, p2, color1 ); DrawLine( m_draw, p2, g2, b2_colorLightGray ); b2Vec2 center = b2TransformPoint( transform2, circle.center ); DrawSolidCircle( m_draw, { center, transform2.q }, circle.radius, color2 ); DrawManifold( &m, transform1.p, transform2.p ); offset.x += 2.0f * increment.x; } // chain-segment vs rounded polygon { b2ChainSegment segment1 = { { 2.0f, 1.0f }, { { 1.0f, 1.0f }, { -1.0f, 0.0f } }, { -2.0f, 0.0f }, -1 }; b2ChainSegment segment2 = { { 3.0f, 1.0f }, { { 2.0f, 1.0f }, { 1.0f, 1.0f } }, { -1.0f, 0.0f }, -1 }; // b2ChainSegment segment1 = {{2.0f, 0.0f}, {{1.0f, 0.0f}, {-1.0f, 0.0f}}, {-2.0f, 0.0f}, -1}; // b2ChainSegment segment2 = {{3.0f, 0.0f}, {{2.0f, 0.0f}, {1.0f, 0.0f}}, {-1.0f, 0.0f}, -1}; // b2ChainSegment segment1 = {{0.5f, 1.0f}, {{0.0f, 2.0f}, {-0.5f, 1.0f}}, {-1.0f, 0.0f}, -1}; // b2ChainSegment segment2 = {{1.0f, 0.0f}, {{0.5f, 1.0f}, {0.0f, 2.0f}}, {-0.5f, 1.0f}, -1}; float h = 0.5f - m_round; b2Polygon rox = b2MakeRoundedBox( h, h, m_round ); b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; b2Manifold m1 = b2CollideChainSegmentAndPolygon( &segment1, transform1, &rox, transform2, &m_smgroxCache1 ); b2Manifold m2 = b2CollideChainSegmentAndPolygon( &segment2, transform1, &rox, transform2, &m_smgroxCache2 ); { b2Vec2 g2 = b2TransformPoint( transform1, segment1.ghost2 ); b2Vec2 p1 = b2TransformPoint( transform1, segment1.segment.point1 ); b2Vec2 p2 = b2TransformPoint( transform1, segment1.segment.point2 ); DrawLine( m_draw, p1, p2, color1 ); DrawPoint( m_draw, p1, 4.0f, color1 ); DrawPoint( m_draw, p2, 4.0f, color1 ); DrawLine( m_draw, p2, g2, b2_colorLightGray ); } { b2Vec2 g1 = b2TransformPoint( transform1, segment2.ghost1 ); b2Vec2 p1 = b2TransformPoint( transform1, segment2.segment.point1 ); b2Vec2 p2 = b2TransformPoint( transform1, segment2.segment.point2 ); DrawLine( m_draw, g1, p1, b2_colorLightGray ); DrawLine( m_draw, p1, p2, color1 ); DrawPoint( m_draw, p1, 4.0f, color1 ); DrawPoint( m_draw, p2, 4.0f, color1 ); } DrawSolidPolygon( m_draw, transform2, rox.vertices, rox.count, rox.radius, color2 ); DrawPoint( m_draw, b2TransformPoint( transform2, rox.centroid ), 5.0f, b2_colorGainsboro ); DrawManifold( &m1, transform1.p, transform2.p ); DrawManifold( &m2, transform1.p, transform2.p ); offset.x += 2.0f * increment.x; } // chain-segment vs capsule { b2ChainSegment segment1 = { { 2.0f, 1.0f }, { { 1.0f, 1.0f }, { -1.0f, 0.0f } }, { -2.0f, 0.0f }, -1 }; b2ChainSegment segment2 = { { 3.0f, 1.0f }, { { 2.0f, 1.0f }, { 1.0f, 1.0f } }, { -1.0f, 0.0f }, -1 }; b2Capsule capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, 0.25f }; b2Transform transform1 = { offset, b2Rot_identity }; b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; b2Manifold m1 = b2CollideChainSegmentAndCapsule( &segment1, transform1, &capsule, transform2, &m_smgcapCache1 ); b2Manifold m2 = b2CollideChainSegmentAndCapsule( &segment2, transform1, &capsule, transform2, &m_smgcapCache2 ); { b2Vec2 g2 = b2TransformPoint( transform1, segment1.ghost2 ); b2Vec2 p1 = b2TransformPoint( transform1, segment1.segment.point1 ); b2Vec2 p2 = b2TransformPoint( transform1, segment1.segment.point2 ); // DrawSegment(g1, p1, b2_colorLightGray); DrawLine( m_draw, p1, p2, color1 ); DrawPoint( m_draw, p1, 4.0f, color1 ); DrawPoint( m_draw, p2, 4.0f, color1 ); DrawLine( m_draw, p2, g2, b2_colorLightGray ); } { b2Vec2 g1 = b2TransformPoint( transform1, segment2.ghost1 ); b2Vec2 p1 = b2TransformPoint( transform1, segment2.segment.point1 ); b2Vec2 p2 = b2TransformPoint( transform1, segment2.segment.point2 ); DrawLine( m_draw, g1, p1, b2_colorLightGray ); DrawLine( m_draw, p1, p2, color1 ); DrawPoint( m_draw, p1, 4.0f, color1 ); DrawPoint( m_draw, p2, 4.0f, color1 ); // DrawSegment(p2, g2, b2_colorLightGray); } b2Vec2 p1 = b2TransformPoint( transform2, capsule.center1 ); b2Vec2 p2 = b2TransformPoint( transform2, capsule.center2 ); DrawSolidCapsule( m_draw, p1, p2, capsule.radius, color2 ); DrawPoint( m_draw, b2Lerp( p1, p2, 0.5f ), 5.0f, b2_colorGainsboro ); DrawManifold( &m1, transform1.p, transform2.p ); DrawManifold( &m2, transform1.p, transform2.p ); offset.x += 2.0f * increment.x; } #endif } static Sample* Create( SampleContext* context ) { return new Manifold( context ); } b2SimplexCache m_smgroxCache1; b2SimplexCache m_smgroxCache2; b2SimplexCache m_smgcapCache1; b2SimplexCache m_smgcapCache2; b2Hull m_wedge; b2Transform m_transform; float m_angle; float m_round; b2Vec2 m_basePosition; b2Vec2 m_startPoint; float m_baseAngle; bool m_dragging; bool m_rotating; bool m_showCount; bool m_showIds; bool m_showAnchors; bool m_showSeparation; bool m_enableCaching; }; static int sampleManifoldIndex = RegisterSample( "Collision", "Manifold", Manifold::Create ); class SmoothManifold : public Sample { public: enum ShapeType { e_circleShape = 0, e_boxShape }; explicit SmoothManifold( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 2.0f, 20.0f }; m_context->camera.zoom = 21.0f; } m_shapeType = e_boxShape; m_transform = { { 0.0f, 20.0f }, b2Rot_identity }; m_angle = 0.0f; m_round = 0.0f; m_startPoint = { 0.0f, 00.0f }; m_basePosition = { 0.0f, 0.0f }; m_baseAngle = 0.0f; m_dragging = false; m_rotating = false; m_showIds = false; m_showAnchors = false; m_showSeparation = false; // https://betravis.github.io/shape-tools/path-to-polygon/ m_count = 36; b2Vec2 points[36]; points[0] = { -20.58325, 14.54175 }; points[1] = { -21.90625, 15.8645 }; points[2] = { -24.552, 17.1875 }; points[3] = { -27.198, 11.89575 }; points[4] = { -29.84375, 15.8645 }; points[5] = { -29.84375, 21.15625 }; points[6] = { -25.875, 23.802 }; points[7] = { -20.58325, 25.125 }; points[8] = { -25.875, 29.09375 }; points[9] = { -20.58325, 31.7395 }; points[10] = { -11.0089998, 23.2290001 }; points[11] = { -8.67700005, 21.15625 }; points[12] = { -6.03125, 21.15625 }; points[13] = { -7.35424995, 29.09375 }; points[14] = { -3.38549995, 29.09375 }; points[15] = { 1.90625, 30.41675 }; points[16] = { 5.875, 17.1875 }; points[17] = { 11.16675, 25.125 }; points[18] = { 9.84375, 29.09375 }; points[19] = { 13.8125, 31.7395 }; points[20] = { 21.75, 30.41675 }; points[21] = { 28.3644981, 26.448 }; points[22] = { 25.71875, 18.5105 }; points[23] = { 24.3957481, 13.21875 }; points[24] = { 17.78125, 11.89575 }; points[25] = { 15.1355, 7.92700005 }; points[26] = { 5.875, 9.25 }; points[27] = { 1.90625, 11.89575 }; points[28] = { -3.25, 11.89575 }; points[29] = { -3.25, 9.9375 }; points[30] = { -4.70825005, 9.25 }; points[31] = { -8.67700005, 9.25 }; points[32] = { -11.323, 11.89575 }; points[33] = { -13.96875, 11.89575 }; points[34] = { -15.29175, 14.54175 }; points[35] = { -19.2605, 14.54175 }; m_segments = (b2ChainSegment*)malloc( m_count * sizeof( b2ChainSegment ) ); for ( int i = 0; i < m_count; ++i ) { int i0 = i > 0 ? i - 1 : m_count - 1; int i1 = i; int i2 = i1 < m_count - 1 ? i1 + 1 : 0; int i3 = i2 < m_count - 1 ? i2 + 1 : 0; b2Vec2 g1 = points[i0]; b2Vec2 p1 = points[i1]; b2Vec2 p2 = points[i2]; b2Vec2 g2 = points[i3]; m_segments[i] = { g1, { p1, p2 }, g2, -1 }; } } virtual ~SmoothManifold() override { free( m_segments ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 290.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 180.0f, height ) ); ImGui::Begin( "Smooth Manifold", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 100.0f ); { const char* shapeTypes[] = { "Circle", "Box" }; int shapeType = int( m_shapeType ); ImGui::Combo( "Shape", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ); m_shapeType = ShapeType( shapeType ); } ImGui::SliderFloat( "x Offset", &m_transform.p.x, -2.0f, 2.0f, "%.2f" ); ImGui::SliderFloat( "y Offset", &m_transform.p.y, -2.0f, 2.0f, "%.2f" ); if ( ImGui::SliderFloat( "Angle", &m_angle, -B2_PI, B2_PI, "%.2f" ) ) { m_transform.q = b2MakeRot( m_angle ); } ImGui::SliderFloat( "Round", &m_round, 0.0f, 0.4f, "%.1f" ); ImGui::Checkbox( "Show Ids", &m_showIds ); ImGui::Checkbox( "Show Separation", &m_showSeparation ); ImGui::Checkbox( "Show Anchors", &m_showAnchors ); if ( ImGui::Button( "Reset" ) ) { m_transform = b2Transform_identity; m_angle = 0.0f; } ImGui::Separator(); ImGui::Text( "mouse button 1: drag" ); ImGui::Text( "mouse button 1 + shift: rotate" ); ImGui::PopItemWidth(); ImGui::End(); } void MouseDown( b2Vec2 p, int button, int mods ) override { if ( button == GLFW_MOUSE_BUTTON_1 ) { if ( mods == 0 && m_rotating == false ) { m_dragging = true; m_startPoint = p; m_basePosition = m_transform.p; } else if ( mods == GLFW_MOD_SHIFT && m_dragging == false ) { m_rotating = true; m_startPoint = p; m_baseAngle = m_angle; } } } void MouseUp( b2Vec2, int button ) override { if ( button == GLFW_MOUSE_BUTTON_1 ) { m_dragging = false; m_rotating = false; } } void MouseMove( b2Vec2 p ) override { if ( m_dragging ) { m_transform.p.x = m_basePosition.x + ( p.x - m_startPoint.x ); m_transform.p.y = m_basePosition.y + ( p.y - m_startPoint.y ); } else if ( m_rotating ) { float dx = p.x - m_startPoint.x; m_angle = b2ClampFloat( m_baseAngle + 1.0f * dx, -B2_PI, B2_PI ); m_transform.q = b2MakeRot( m_angle ); } } void DrawManifold( const b2Manifold* manifold ) { for ( int i = 0; i < manifold->pointCount; ++i ) { const b2ManifoldPoint* mp = manifold->points + i; b2Vec2 p1 = mp->point; b2Vec2 p2 = b2MulAdd( p1, 0.5f, manifold->normal ); DrawLine( m_draw, p1, p2, b2_colorWhite ); if ( m_showAnchors ) { DrawPoint( m_draw, p1, 5.0f, b2_colorGreen ); } else { DrawPoint( m_draw, p1, 5.0f, b2_colorGreen ); } if ( m_showIds ) { // uint32_t indexA = mp->id >> 8; // uint32_t indexB = 0xFF & mp->id; b2Vec2 p = { p1.x + 0.05f, p1.y - 0.02f }; DrawWorldString( m_draw, m_camera, p, b2_colorWhite, "0x%04x", mp->id ); } if ( m_showSeparation ) { b2Vec2 p = { p1.x + 0.05f, p1.y + 0.03f }; DrawWorldString( m_draw, m_camera, p, b2_colorWhite, "%.3f", mp->separation ); } } } void Step() override { b2HexColor color1 = b2_colorYellow; b2HexColor color2 = b2_colorMagenta; b2Transform transform1 = b2Transform_identity; b2Transform transform2 = m_transform; for ( int i = 0; i < m_count; ++i ) { const b2ChainSegment* segment = m_segments + i; b2Vec2 p1 = b2TransformPoint( transform1, segment->segment.point1 ); b2Vec2 p2 = b2TransformPoint( transform1, segment->segment.point2 ); DrawLine( m_draw, p1, p2, color1 ); DrawPoint( m_draw, p1, 4.0f, color1 ); } // chain-segment vs circle if ( m_shapeType == e_circleShape ) { float radius = 0.5f; b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; DrawSolidCircle( m_draw, transform2, circle.radius, color2 ); for ( int i = 0; i < m_count; ++i ) { const b2ChainSegment* segment = m_segments + i; b2Manifold m = b2CollideChainSegmentAndCircle( segment, transform1, &circle, transform2 ); DrawManifold( &m ); } } else if ( m_shapeType == e_boxShape ) { float h = 0.5f - m_round; b2Polygon rox = b2MakeRoundedBox( h, h, m_round ); DrawSolidPolygon( m_draw, transform2, rox.vertices, rox.count, rox.radius, color2 ); for ( int i = 0; i < m_count; ++i ) { const b2ChainSegment* segment = m_segments + i; b2SimplexCache cache = {}; b2Manifold m = b2CollideChainSegmentAndPolygon( segment, transform1, &rox, transform2, &cache ); DrawManifold( &m ); } } } static Sample* Create( SampleContext* context ) { return new SmoothManifold( context ); } ShapeType m_shapeType; b2ChainSegment* m_segments; int m_count; b2Transform m_transform; float m_angle; float m_round; b2Vec2 m_basePosition; b2Vec2 m_startPoint; float m_baseAngle; bool m_dragging; bool m_rotating; bool m_showIds; bool m_showAnchors; bool m_showSeparation; }; static int sampleSmoothManifoldIndex = RegisterSample( "Collision", "Smooth Manifold", SmoothManifold::Create ); class ShapeCast : public Sample { public: enum ShapeType { e_point, e_segment, e_triangle, e_box }; explicit ShapeCast( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 0.25f }; m_context->camera.zoom = 3.0f; } m_point = b2Vec2_zero; m_segment = { { 0.0f, 0.0f }, { 0.5f, 0.0f } }; { b2Vec2 points[3] = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, { 0.0f, 1.0f } }; b2Hull hull = b2ComputeHull( points, 3 ); m_triangle = b2MakePolygon( &hull, 0.0f ); } #if 0 { b2Vec2 points[4] = {}; points[0].x = -0.599999964; points[0].y = -0.700000048; points[1].x = 0.449999988; points[1].y = -0.700000048; points[2].x = 0.449999988; points[2].y = 0.350000024; points[3].x = -0.599999964; points[3].y = 0.350000024; points[0] = { 3.0, -0.5 }; points[1] = { 3.0, 0.5 }; points[2] = { -3.0, 0.5 }; points[3] = { -3.0, -0.5 }; b2Hull hull = b2ComputeHull( points, 4 ); bool isValid = b2ValidateHull( &hull ); assert( isValid ); m_triangle = b2MakePolygon( &hull, 0.0f ); } #endif m_box = b2MakeOffsetBox( 0.5f, 0.5f, { 0.0f, 0.0f }, b2Rot_identity ); #if 0 { b2Vec2 points[4] = {}; points[0].x = 0.449999988; points[0].y = -0.100000001; points[1].x = 0.550000012; points[1].y = -0.100000001; points[2].x = 0.550000012; points[2].y = 0.100000001; points[3].x = 0.449999988; points[3].y = 0.100000001; b2Hull hull = b2ComputeHull( points, 4 ); m_box = b2MakePolygon( &hull, 0.0f ); } #endif m_transform = { { -0.6f, 0.0f }, b2Rot_identity }; m_translation = { 2.0f, 0.0f }; m_angle = 0.0f; m_startPoint = { 0.0f, 0.0f }; m_basePosition = { 0.0f, 0.0f }; m_baseAngle = 0.0f; m_dragging = false; m_sweeping = false; m_rotating = false; m_showIndices = false; m_drawSimplex = false; m_encroach = false; m_typeA = e_box; m_typeB = e_point; m_radiusA = 0.0f; m_radiusB = 0.2f; m_proxyA = MakeProxy( m_typeA, m_radiusA ); m_proxyB = MakeProxy( m_typeB, m_radiusB ); } b2ShapeProxy MakeProxy( ShapeType type, float radius ) const { b2ShapeProxy proxy = {}; proxy.radius = radius; switch ( type ) { case e_point: proxy.points[0] = b2Vec2_zero; proxy.count = 1; break; case e_segment: proxy.points[0] = m_segment.point1; proxy.points[1] = m_segment.point2; proxy.count = 2; break; case e_triangle: for ( int i = 0; i < m_triangle.count; ++i ) { proxy.points[i] = m_triangle.vertices[i]; } proxy.count = m_triangle.count; break; case e_box: proxy.points[0] = m_box.vertices[0]; proxy.points[1] = m_box.vertices[1]; proxy.points[2] = m_box.vertices[2]; proxy.points[3] = m_box.vertices[3]; proxy.count = 4; break; default: assert( false ); } return proxy; } void DrawShape( ShapeType type, b2Transform transform, float radius, b2HexColor color ) { switch ( type ) { case e_point: { b2Vec2 p = b2TransformPoint( transform, m_point ); if ( radius > 0.0f ) { DrawSolidCircle( m_draw, { p, transform.q }, radius, color ); } else { DrawPoint( m_draw, p, 5.0f, color ); } } break; case e_segment: { b2Vec2 p1 = b2TransformPoint( transform, m_segment.point1 ); b2Vec2 p2 = b2TransformPoint( transform, m_segment.point2 ); if ( radius > 0.0f ) { DrawSolidCapsule( m_draw, p1, p2, radius, color ); } else { DrawLine( m_draw, p1, p2, color ); } } break; case e_triangle: DrawSolidPolygon( m_draw, transform, m_triangle.vertices, m_triangle.count, radius, color ); break; case e_box: DrawSolidPolygon( m_draw, transform, m_box.vertices, m_box.count, radius, color ); break; default: assert( false ); } } void MouseDown( b2Vec2 p, int button, int mods ) override { if ( button == GLFW_MOUSE_BUTTON_1 ) { if ( mods == 0 ) { m_dragging = true; m_sweeping = false; m_rotating = false; m_startPoint = p; m_basePosition = m_transform.p; } else if ( mods == GLFW_MOD_SHIFT ) { m_dragging = false; m_sweeping = false; m_rotating = true; m_startPoint = p; m_baseAngle = m_angle; } else if ( mods == GLFW_MOD_CONTROL ) { m_dragging = false; m_sweeping = true; m_rotating = false; m_startPoint = p; m_basePosition = b2Vec2_zero; } } } void MouseUp( b2Vec2, int button ) override { if ( button == GLFW_MOUSE_BUTTON_1 ) { m_dragging = false; m_sweeping = false; m_rotating = false; } } void MouseMove( b2Vec2 p ) override { if ( m_dragging ) { m_transform.p = m_basePosition + 0.5f * ( p - m_startPoint ); } else if ( m_rotating ) { float dx = p.x - m_startPoint.x; m_angle = b2ClampFloat( m_baseAngle + 1.0f * dx, -B2_PI, B2_PI ); m_transform.q = b2MakeRot( m_angle ); } else if ( m_sweeping ) { m_translation = p - m_startPoint; } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 300.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Shape Distance", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); const char* shapeTypes[] = { "point", "segment", "triangle", "box" }; int shapeType = int( m_typeA ); if ( ImGui::Combo( "shape A", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) ) { m_typeA = ShapeType( shapeType ); m_proxyA = MakeProxy( m_typeA, m_radiusA ); } if ( ImGui::SliderFloat( "radius A", &m_radiusA, 0.0f, 0.5f, "%.2f" ) ) { m_proxyA.radius = m_radiusA; } shapeType = int( m_typeB ); if ( ImGui::Combo( "shape B", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) ) { m_typeB = ShapeType( shapeType ); m_proxyB = MakeProxy( m_typeB, m_radiusB ); } if ( ImGui::SliderFloat( "radius B", &m_radiusB, 0.0f, 0.5f, "%.2f" ) ) { m_proxyB.radius = m_radiusB; } ImGui::Separator(); ImGui::SliderFloat( "x offset", &m_transform.p.x, -2.0f, 2.0f, "%.2f" ); ImGui::SliderFloat( "y offset", &m_transform.p.y, -2.0f, 2.0f, "%.2f" ); if ( ImGui::SliderFloat( "angle", &m_angle, -B2_PI, B2_PI, "%.2f" ) ) { m_transform.q = b2MakeRot( m_angle ); } ImGui::Separator(); ImGui::Checkbox( "show indices", &m_showIndices ); ImGui::Checkbox( "encroach", &m_encroach ); ImGui::End(); } void Step() override { Sample::Step(); b2ShapeCastPairInput input = {}; input.proxyA = m_proxyA; input.proxyB = m_proxyB; input.transformA = b2Transform_identity; input.transformB = m_transform; input.translationB = m_translation; input.maxFraction = 1.0f; input.canEncroach = m_encroach; b2CastOutput output = b2ShapeCast( &input ); b2Transform transform; transform.q = m_transform.q; transform.p = b2MulAdd( m_transform.p, output.fraction, input.translationB ); b2DistanceInput distanceInput; distanceInput.proxyA = m_proxyA; distanceInput.proxyB = m_proxyB; distanceInput.transformA = b2Transform_identity; distanceInput.transformB = transform; distanceInput.useRadii = false; b2SimplexCache distanceCache; distanceCache.count = 0; b2DistanceOutput distanceOutput = b2ShapeDistance( &distanceInput, &distanceCache, nullptr, 0 ); DrawTextLine( "hit = %s, iterations = %d, fraction = %g, distance = %g", output.hit ? "true" : "false", output.iterations, output.fraction, distanceOutput.distance ); DrawShape( m_typeA, b2Transform_identity, m_radiusA, b2_colorCyan ); DrawShape( m_typeB, m_transform, m_radiusB, b2_colorLightGreen ); b2Transform transform2 = { m_transform.p + m_translation, m_transform.q }; DrawShape( m_typeB, transform2, m_radiusB, b2_colorIndianRed ); if ( output.hit ) { DrawShape( m_typeB, transform, m_radiusB, b2_colorPlum ); if ( output.fraction > 0.0f ) { DrawPoint( m_draw, output.point, 5.0f, b2_colorWhite ); DrawLine( m_draw, output.point, output.point + 0.5f * output.normal, b2_colorYellow ); } else { DrawPoint( m_draw, output.point, 5.0f, b2_colorPeru ); } } if ( m_showIndices ) { for ( int i = 0; i < m_proxyA.count; ++i ) { b2Vec2 p = m_proxyA.points[i]; DrawWorldString( m_draw, m_camera, p, b2_colorWhite, " %d", i ); } for ( int i = 0; i < m_proxyB.count; ++i ) { b2Vec2 p = b2TransformPoint( m_transform, m_proxyB.points[i] ); DrawWorldString( m_draw, m_camera, p, b2_colorWhite, " %d", i ); } } DrawTextLine( "mouse button 1: drag" ); DrawTextLine( "mouse button 1 + shift: rotate" ); DrawTextLine( "mouse button 1 + control: sweep" ); DrawTextLine( "distance = %.2f, iterations = %d", distanceOutput.distance, output.iterations ); } static Sample* Create( SampleContext* context ) { return new ShapeCast( context ); } b2Polygon m_box; b2Polygon m_triangle; b2Vec2 m_point; b2Segment m_segment; ShapeType m_typeA; ShapeType m_typeB; float m_radiusA; float m_radiusB; b2ShapeProxy m_proxyA; b2ShapeProxy m_proxyB; b2Transform m_transform; float m_angle; b2Vec2 m_translation; b2Vec2 m_basePosition; b2Vec2 m_startPoint; float m_baseAngle; bool m_dragging; bool m_sweeping; bool m_rotating; bool m_showIndices; bool m_drawSimplex; bool m_encroach; }; static int sampleShapeCast = RegisterSample( "Collision", "Shape Cast", ShapeCast::Create ); class TimeOfImpact : public Sample { public: explicit TimeOfImpact( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.6f, 2.0f }; m_context->camera.center = { -16, 45 }; m_context->camera.zoom = 5.0f; } } static Sample* Create( SampleContext* context ) { return new TimeOfImpact( context ); } void Step() override { Sample::Step(); b2Sweep sweepA = { b2Vec2_zero, { 0.0f, 0.0f }, { 0.0f, 0.0f }, b2Rot_identity, b2Rot_identity, }; b2Sweep sweepB = { b2Vec2_zero, { -15.8332710, 45.3520279 }, { -15.8324337, 45.3413048 }, { -0.540891349, 0.841092527 }, { -0.457797021, 0.889056742 }, }; b2TOIInput input; input.proxyA = b2MakeProxy( m_verticesA, m_countA, m_radiusA ); input.proxyB = b2MakeProxy( m_verticesB, m_countB, m_radiusB ); input.sweepA = sweepA; input.sweepB = sweepB; input.maxFraction = 1.0f; b2TOIOutput output = b2TimeOfImpact( &input ); DrawTextLine( "toi = %g", output.fraction ); // DrawString(5, m_textLine, "max toi iters = %d, max root iters = %d", b2_toiMaxIters, // b2_toiMaxRootIters); b2Vec2 vertices[B2_MAX_POLYGON_VERTICES]; // Draw A b2Transform transformA = b2GetSweepTransform( &sweepA, 0.0f ); for ( int i = 0; i < m_countA; ++i ) { vertices[i] = b2TransformPoint( transformA, m_verticesA[i] ); } DrawPolygon( m_draw, vertices, m_countA, b2_colorGray ); // Draw B at t = 0 b2Transform transformB = b2GetSweepTransform( &sweepB, 0.0f ); for ( int i = 0; i < m_countB; ++i ) { vertices[i] = b2TransformPoint( transformB, m_verticesB[i] ); } DrawSolidCapsule( m_draw, vertices[0], vertices[1], m_radiusB, b2_colorGreen ); // DrawPolygon( vertices, m_countB, b2_colorGreen ); // Draw B at t = hit_time transformB = b2GetSweepTransform( &sweepB, output.fraction ); for ( int i = 0; i < m_countB; ++i ) { vertices[i] = b2TransformPoint( transformB, m_verticesB[i] ); } DrawPolygon( m_draw, vertices, m_countB, b2_colorOrange ); // Draw B at t = 1 transformB = b2GetSweepTransform( &sweepB, 1.0f ); for ( int i = 0; i < m_countB; ++i ) { vertices[i] = b2TransformPoint( transformB, m_verticesB[i] ); } DrawSolidCapsule( m_draw, vertices[0], vertices[1], m_radiusB, b2_colorRed ); // DrawPolygon( vertices, m_countB, b2_colorRed ); if ( output.state == b2_toiStateHit ) { b2DistanceInput distanceInput; distanceInput.proxyA = input.proxyA; distanceInput.proxyB = input.proxyB; distanceInput.transformA = b2GetSweepTransform( &sweepA, output.fraction ); distanceInput.transformB = b2GetSweepTransform( &sweepB, output.fraction ); distanceInput.useRadii = false; b2SimplexCache cache = { 0 }; b2DistanceOutput distanceOutput = b2ShapeDistance( &distanceInput, &cache, nullptr, 0 ); DrawTextLine( "distance = %g", distanceOutput.distance ); } #if 0 for (float t = 0.0f; t < 1.0f; t += 0.1f) { transformB = b2GetSweepTransform(&sweepB, t); for (int i = 0; i < m_countB; ++i) { vertices[i] = b2TransformPoint(transformB, m_verticesB[i]); } DrawPolygon(vertices, m_countB, {0.3f, 0.3f, 0.3f}); } #endif } b2Vec2 m_verticesA[4] = { { -16.25, 44.75 }, { -15.75, 44.75 }, { -15.75, 45.25 }, { -16.25, 45.25 } }; b2Vec2 m_verticesB[2] = { { 0.0f, -0.125000000f }, { 0.0f, 0.125000000f } }; int m_countA = ARRAY_COUNT( m_verticesA ); int m_countB = ARRAY_COUNT( m_verticesB ); float m_radiusA = 0.0f; float m_radiusB = 0.0299999993f; }; static int sampleTimeOfImpact = RegisterSample( "Collision", "Time of Impact", TimeOfImpact::Create ); ================================================ FILE: samples/sample_continuous.cpp ================================================ // SPDX-FileCopyrightText: 2022 Erin Catto // SPDX-License-Identifier: MIT #include "draw.h" #include "human.h" #include "random.h" #include "sample.h" #include "box2d/box2d.h" #include "box2d/math_functions.h" #include #include #include // extern "C" int b2_toiHitCount; class BounceHouse : public Sample { public: enum ShapeType { e_circleShape = 0, e_capsuleShape, e_boxShape }; struct HitEvent { b2Vec2 point; float speed; int stepIndex; }; explicit BounceHouse( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 0.0f }; m_context->camera.zoom = 25.0f * 0.45f; } b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); { b2Segment segment = { { -10.0f, -10.0f }, { 10.0f, -10.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { b2Segment segment = { { 10.0f, -10.0f }, { 10.0f, 10.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { b2Segment segment = { { 10.0f, 10.0f }, { -10.0f, 10.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { b2Segment segment = { { -10.0f, 10.0f }, { -10.0f, -10.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } m_shapeType = e_circleShape; m_bodyId = b2_nullBodyId; m_enableHitEvents = true; memset( m_hitEvents, 0, sizeof( m_hitEvents ) ); Launch(); } void Launch() { if ( B2_IS_NON_NULL( m_bodyId ) ) { b2DestroyBody( m_bodyId ); } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.linearVelocity = { 10.0f, 20.0f }; bodyDef.position = { 0.0f, 0.0f }; bodyDef.gravityScale = 0.0f; bodyDef.isBullet = true; // Circle shapes centered on the body can spin fast without risk of tunnelling. bodyDef.allowFastRotation = m_shapeType == e_circleShape; m_bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.material.restitution = 1.0f; shapeDef.material.friction = 0.0f; shapeDef.enableHitEvents = m_enableHitEvents; if ( m_shapeType == e_circleShape ) { b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; b2CreateCircleShape( m_bodyId, &shapeDef, &circle ); } else if ( m_shapeType == e_capsuleShape ) { b2Capsule capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, 0.25f }; b2CreateCapsuleShape( m_bodyId, &shapeDef, &capsule ); } else { float h = 0.1f; b2Polygon box = b2MakeBox( 20.0f * h, h ); b2CreatePolygonShape( m_bodyId, &shapeDef, &box ); } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 100.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Bounce House", nullptr, ImGuiWindowFlags_NoResize ); const char* shapeTypes[] = { "Circle", "Capsule", "Box" }; int shapeType = int( m_shapeType ); if ( ImGui::Combo( "Shape", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) ) { m_shapeType = ShapeType( shapeType ); Launch(); } if ( ImGui::Checkbox( "hit events", &m_enableHitEvents ) ) { b2Body_EnableHitEvents( m_bodyId, m_enableHitEvents ); } ImGui::End(); } void Step() override { Sample::Step(); b2ContactEvents events = b2World_GetContactEvents( m_worldId ); for ( int i = 0; i < events.hitCount; ++i ) { b2ContactHitEvent* event = events.hitEvents + i; HitEvent* e = m_hitEvents + 0; for ( int j = 1; j < 4; ++j ) { if ( m_hitEvents[j].stepIndex < e->stepIndex ) { e = m_hitEvents + j; } } e->point = event->point; e->speed = event->approachSpeed; e->stepIndex = m_stepCount; } for ( int i = 0; i < 4; ++i ) { HitEvent* e = m_hitEvents + i; if ( e->stepIndex > 0 && m_stepCount <= e->stepIndex + 30 ) { DrawCircle(m_draw, e->point, 0.1f, b2_colorOrangeRed ); DrawWorldString( m_draw, m_camera, e->point, b2_colorWhite, "%.1f", e->speed ); } } if ( m_stepCount == 1000 ) { m_stepCount += 0; } } static Sample* Create( SampleContext* context ) { return new BounceHouse( context ); } HitEvent m_hitEvents[4]; b2BodyId m_bodyId; ShapeType m_shapeType; bool m_enableHitEvents; }; static int sampleBounceHouse = RegisterSample( "Continuous", "Bounce House", BounceHouse::Create ); class BounceHumans : public Sample { public: explicit BounceHumans( SampleContext* context ) : Sample( context ) { m_context->camera.center = { 0.0f, 0.0f }; m_context->camera.zoom = 12.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.restitution = 1.3f; shapeDef.material.friction = 0.1f; { b2Segment segment = { { -10.0f, -10.0f }, { 10.0f, -10.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { b2Segment segment = { { 10.0f, -10.0f }, { 10.0f, 10.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { b2Segment segment = { { 10.0f, 10.0f }, { -10.0f, 10.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { b2Segment segment = { { -10.0f, 10.0f }, { -10.0f, -10.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } b2Circle circle = { { 0.0f, 0.0f }, 2.0f }; shapeDef.material.restitution = 2.0f; b2CreateCircleShape( groundId, &shapeDef, &circle ); } void Step() override { if ( m_humanCount < 5 && m_countDown <= 0.0f ) { float jointFrictionTorque = 0.0f; float jointHertz = 1.0f; float jointDampingRatio = 0.1f; CreateHuman( m_humans + m_humanCount, m_worldId, { 0.0f, 5.0f }, 1.0f, jointFrictionTorque, jointHertz, jointDampingRatio, 1, nullptr, true ); // Human_SetVelocity( m_humans + m_humanCount, { 10.0f - 5.0f * m_humanCount, -20.0f + 5.0f * m_humanCount } ); m_countDown = 2.0f; m_humanCount += 1; } float timeStep = 1.0f / 60.0f; b2CosSin cs1 = b2ComputeCosSin( 0.5f * m_time ); b2CosSin cs2 = b2ComputeCosSin( m_time ); float gravity = 10.0f; b2Vec2 gravityVec = { gravity * cs1.sine, gravity * cs2.cosine }; DrawLine( m_draw, b2Vec2_zero, b2Vec2{ 3.0f * cs1.sine, 3.0f * cs2.cosine }, b2_colorWhite ); m_time += timeStep; m_countDown -= timeStep; b2World_SetGravity( m_worldId, gravityVec ); Sample::Step(); } static Sample* Create( SampleContext* context ) { return new BounceHumans( context ); } Human m_humans[5] = {}; int m_humanCount = 0; float m_countDown = 0.0f; float m_time = 0.0f; }; static int sampleBounceHumans = RegisterSample( "Continuous", "Bounce Humans", BounceHumans::Create ); class ChainDrop : public Sample { public: explicit ChainDrop( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 0.0f }; m_context->camera.zoom = 25.0f * 0.35f; } // // b2World_SetContactTuning( m_worldId, 30.0f, 1.0f, 100.0f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, -6.0f }; b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2Vec2 points[4] = { { -10.0f, -2.0f }, { 10.0f, -2.0f }, { 10.0f, 1.0f }, { -10.0f, 1.0f } }; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = 4; chainDef.isLoop = true; b2CreateChain( groundId, &chainDef ); m_bodyId = b2_nullBodyId; m_yOffset = -0.1f; m_speed = -42.0f; Launch(); } void Launch() { if ( B2_IS_NON_NULL( m_bodyId ) ) { b2DestroyBody( m_bodyId ); } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.linearVelocity = { 0.0f, m_speed }; bodyDef.position = { 0.0f, 10.0f + m_yOffset }; bodyDef.rotation = b2MakeRot( 0.5f * B2_PI ); bodyDef.motionLocks.angularZ = true; m_bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; m_shapeId = b2CreateCircleShape( m_bodyId, &shapeDef, &circle ); // b2Capsule capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, 0.25f }; // m_shapeId = b2CreateCapsuleShape( m_bodyId, &shapeDef, &capsule ); // float h = 0.5f; // b2Polygon box = b2MakeBox( h, h ); // m_shapeId = b2CreatePolygonShape( m_bodyId, &shapeDef, &box ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 140.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Chain Drop", nullptr, ImGuiWindowFlags_NoResize ); ImGui::SliderFloat( "Speed", &m_speed, -100.0f, 0.0f, "%.0f" ); ImGui::SliderFloat( "Y Offset", &m_yOffset, -1.0f, 1.0f, "%.1f" ); if ( ImGui::Button( "Launch" ) ) { Launch(); } ImGui::End(); } static Sample* Create( SampleContext* context ) { return new ChainDrop( context ); } b2BodyId m_bodyId; b2ShapeId m_shapeId; float m_yOffset; float m_speed; }; static int sampleChainDrop = RegisterSample( "Continuous", "Chain Drop", ChainDrop::Create ); class ChainSlide : public Sample { public: explicit ChainSlide( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 10.0f }; m_context->camera.zoom = 15.0f; } // b2_toiHitCount = 0; { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); constexpr int count = 80; b2Vec2 points[count]; float w = 2.0f; float h = 1.0f; float x = 20.0f, y = 0.0f; for ( int i = 0; i < 20; ++i ) { points[i] = { x, y }; x -= w; } for ( int i = 20; i < 40; ++i ) { points[i] = { x, y }; y += h; } for ( int i = 40; i < 60; ++i ) { points[i] = { x, y }; x += w; } for ( int i = 60; i < 80; ++i ) { points[i] = { x, y }; y -= h; } b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = count; chainDef.isLoop = true; b2CreateChain( groundId, &chainDef ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.linearVelocity = { 100.0f, 0.0f }; bodyDef.position = { -19.5f, 0.0f + 0.5f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.0f; b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; b2CreateCircleShape( bodyId, &shapeDef, &circle ); } } void Step() override { Sample::Step(); // DrawTextLine( "toi hits = %d", b2_toiHitCount ); } static Sample* Create( SampleContext* context ) { return new ChainSlide( context ); } }; static int sampleChainSlide = RegisterSample( "Continuous", "Chain Slide", ChainSlide::Create ); class SegmentSlide : public Sample { public: explicit SegmentSlide( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 10.0f }; m_context->camera.zoom = 15.0f; } // b2_toiHitCount = 0; { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -40.0f, 0.0f }, { 40.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); segment = { { 40.0f, 0.0f }, { 40.0f, 10.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.linearVelocity = { 100.0f, 0.0f }; bodyDef.position = { -20.0f, 0.7f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); // shapeDef.friction = 0.0f; b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; b2CreateCircleShape( bodyId, &shapeDef, &circle ); } } void Step() override { Sample::Step(); // DrawTextLine("toi hits = %d", b2_toiHitCount ); } static Sample* Create( SampleContext* context ) { return new SegmentSlide( context ); } }; static int sampleSegmentSlide = RegisterSample( "Continuous", "Segment Slide", SegmentSlide::Create ); class SkinnyBox : public Sample { public: explicit SkinnyBox( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 1.0f, 5.0f }; m_context->camera.zoom = 25.0f * 0.25f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2Segment segment = { { -10.0f, 0.0f }, { 10.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.9f; b2CreateSegmentShape( groundId, &shapeDef, &segment ); b2Polygon box = b2MakeOffsetBox( 0.1f, 1.0f, { 0.0f, 1.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } m_autoTest = false; m_bullet = false; m_capsule = false; m_bodyId = b2_nullBodyId; m_bulletId = b2_nullBodyId; Launch(); } void Launch() { if ( B2_IS_NON_NULL( m_bodyId ) ) { b2DestroyBody( m_bodyId ); } if ( B2_IS_NON_NULL( m_bulletId ) ) { b2DestroyBody( m_bulletId ); } m_angularVelocity = RandomFloatRange( -50.0f, 50.0f ); // m_angularVelocity = -30.6695766f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 0.0f, 8.0f }; bodyDef.angularVelocity = m_angularVelocity; bodyDef.linearVelocity = { 0.0f, -100.0f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.material.friction = 0.9f; m_bodyId = b2CreateBody( m_worldId, &bodyDef ); if ( m_capsule ) { b2Capsule capsule = { { 0.0f, -1.0f }, { 0.0f, 1.0f }, 0.1f }; b2CreateCapsuleShape( m_bodyId, &shapeDef, &capsule ); } else { b2Polygon polygon = b2MakeBox( 2.0f, 0.05f ); b2CreatePolygonShape( m_bodyId, &shapeDef, &polygon ); } if ( m_bullet ) { b2Polygon polygon = b2MakeBox( 0.25f, 0.25f ); m_x = RandomFloatRange( -1.0f, 1.0f ); bodyDef.position = { m_x, 10.0f }; bodyDef.linearVelocity = { 0.0f, -50.0f }; m_bulletId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( m_bulletId, &shapeDef, &polygon ); } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 110.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 140.0f, height ) ); ImGui::Begin( "Skinny Box", nullptr, ImGuiWindowFlags_NoResize ); ImGui::Checkbox( "Capsule", &m_capsule ); if ( ImGui::Button( "Launch" ) ) { Launch(); } ImGui::Checkbox( "Auto Test", &m_autoTest ); ImGui::End(); } void Step() override { Sample::Step(); if ( m_autoTest && m_stepCount % 60 == 0 ) { Launch(); } } static Sample* Create( SampleContext* context ) { return new SkinnyBox( context ); } b2BodyId m_bodyId, m_bulletId; float m_angularVelocity; float m_x; bool m_capsule; bool m_autoTest; bool m_bullet; }; static int sampleSkinnyBox = RegisterSample( "Continuous", "Skinny Box", SkinnyBox::Create ); // This sample shows ghost bumps class GhostBumps : public Sample { public: enum ShapeType { e_circleShape = 0, e_capsuleShape, e_boxShape }; explicit GhostBumps( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 1.5f, 16.0f }; m_context->camera.zoom = 25.0f * 0.8f; } m_groundId = b2_nullBodyId; m_bodyId = b2_nullBodyId; m_shapeId = b2_nullShapeId; m_shapeType = e_circleShape; m_round = 0.0f; m_friction = 0.2f; m_bevel = 0.0f; m_useChain = true; CreateScene(); Launch(); } void CreateScene() { if ( B2_IS_NON_NULL( m_groundId ) ) { b2DestroyBody( m_groundId ); } m_shapeId = b2_nullShapeId; b2BodyDef bodyDef = b2DefaultBodyDef(); m_groundId = b2CreateBody( m_worldId, &bodyDef ); float m = 1.0f / sqrt( 2.0f ); float mm = 2.0f * ( sqrt( 2.0f ) - 1.0f ); float hx = 4.0f, hy = 0.25f; if ( m_useChain ) { b2Vec2 points[20]; points[0] = { -3.0f * hx, hy }; points[1] = b2Add( points[0], { -2.0f * hx * m, 2.0f * hx * m } ); points[2] = b2Add( points[1], { -2.0f * hx * m, 2.0f * hx * m } ); points[3] = b2Add( points[2], { -2.0f * hx * m, 2.0f * hx * m } ); points[4] = b2Add( points[3], { -2.0f * hy * m, -2.0f * hy * m } ); points[5] = b2Add( points[4], { 2.0f * hx * m, -2.0f * hx * m } ); points[6] = b2Add( points[5], { 2.0f * hx * m, -2.0f * hx * m } ); points[7] = b2Add( points[6], { 2.0f * hx * m + 2.0f * hy * ( 1.0f - m ), -2.0f * hx * m - 2.0f * hy * ( 1.0f - m ) } ); points[8] = b2Add( points[7], { 2.0f * hx + hy * mm, 0.0f } ); points[9] = b2Add( points[8], { 2.0f * hx, 0.0f } ); points[10] = b2Add( points[9], { 2.0f * hx + hy * mm, 0.0f } ); points[11] = b2Add( points[10], { 2.0f * hx * m + 2.0f * hy * ( 1.0f - m ), 2.0f * hx * m + 2.0f * hy * ( 1.0f - m ) } ); points[12] = b2Add( points[11], { 2.0f * hx * m, 2.0f * hx * m } ); points[13] = b2Add( points[12], { 2.0f * hx * m, 2.0f * hx * m } ); points[14] = b2Add( points[13], { -2.0f * hy * m, 2.0f * hy * m } ); points[15] = b2Add( points[14], { -2.0f * hx * m, -2.0f * hx * m } ); points[16] = b2Add( points[15], { -2.0f * hx * m, -2.0f * hx * m } ); points[17] = b2Add( points[16], { -2.0f * hx * m, -2.0f * hx * m } ); points[18] = b2Add( points[17], { -2.0f * hx, 0.0f } ); points[19] = b2Add( points[18], { -2.0f * hx, 0.0f } ); b2SurfaceMaterial material = {}; material.friction = m_friction; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = 20; chainDef.isLoop = true; chainDef.materials = &material; chainDef.materialCount = 1; b2CreateChain( m_groundId, &chainDef ); } else { b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = m_friction; b2Hull hull = {}; if ( m_bevel > 0.0f ) { float hb = m_bevel; b2Vec2 vs[8] = { { hx + hb, hy - 0.05f }, { hx, hy }, { -hx, hy }, { -hx - hb, hy - 0.05f }, { -hx - hb, -hy + 0.05f }, { -hx, -hy }, { hx, -hy }, { hx + hb, -hy + 0.05f } }; hull = b2ComputeHull( vs, 8 ); } else { b2Vec2 vs[4] = { { hx, hy }, { -hx, hy }, { -hx, -hy }, { hx, -hy } }; hull = b2ComputeHull( vs, 4 ); } b2Transform transform; float x, y; // Left slope x = -3.0f * hx - m * hx - m * hy; y = hy + m * hx - m * hy; transform.q = b2MakeRot( -0.25f * B2_PI ); { transform.p = { x, y }; b2Polygon polygon = b2MakeOffsetPolygon( &hull, transform.p, transform.q ); b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x -= 2.0f * m * hx; y += 2.0f * m * hx; } { transform.p = { x, y }; b2Polygon polygon = b2MakeOffsetPolygon( &hull, transform.p, transform.q ); b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x -= 2.0f * m * hx; y += 2.0f * m * hx; } { transform.p = { x, y }; b2Polygon polygon = b2MakeOffsetPolygon( &hull, transform.p, transform.q ); b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x -= 2.0f * m * hx; y += 2.0f * m * hx; } x = -2.0f * hx; y = 0.0f; transform.q = b2MakeRot( 0.0f ); { transform.p = { x, y }; b2Polygon polygon = b2MakeOffsetPolygon( &hull, transform.p, transform.q ); b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x += 2.0f * hx; } { transform.p = { x, y }; b2Polygon polygon = b2MakeOffsetPolygon( &hull, transform.p, transform.q ); b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x += 2.0f * hx; } { transform.p = { x, y }; b2Polygon polygon = b2MakeOffsetPolygon( &hull, transform.p, transform.q ); b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x += 2.0f * hx; } x = 3.0f * hx + m * hx + m * hy; y = hy + m * hx - m * hy; transform.q = b2MakeRot( 0.25f * B2_PI ); { transform.p = { x, y }; b2Polygon polygon = b2MakeOffsetPolygon( &hull, transform.p, transform.q ); b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x += 2.0f * m * hx; y += 2.0f * m * hx; } { transform.p = { x, y }; b2Polygon polygon = b2MakeOffsetPolygon( &hull, transform.p, transform.q ); b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x += 2.0f * m * hx; y += 2.0f * m * hx; } { transform.p = { x, y }; b2Polygon polygon = b2MakeOffsetPolygon( &hull, transform.p, transform.q ); b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x += 2.0f * m * hx; y += 2.0f * m * hx; } } } void Launch() { if ( B2_IS_NON_NULL( m_bodyId ) ) { b2DestroyBody( m_bodyId ); m_shapeId = b2_nullShapeId; } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -28.0f, 18.0f }; bodyDef.linearVelocity = { 0.0f, 0.0f }; m_bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.material.friction = m_friction; if ( m_shapeType == e_circleShape ) { b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; m_shapeId = b2CreateCircleShape( m_bodyId, &shapeDef, &circle ); } else if ( m_shapeType == e_capsuleShape ) { b2Capsule capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, 0.25f }; m_shapeId = b2CreateCapsuleShape( m_bodyId, &shapeDef, &capsule ); } else { float h = 0.5f - m_round; b2Polygon box = b2MakeRoundedBox( h, 2.0f * h, m_round ); m_shapeId = b2CreatePolygonShape( m_bodyId, &shapeDef, &box ); } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 140.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 180.0f, height ) ); ImGui::Begin( "Ghost Bumps", nullptr, ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 100.0f ); if ( ImGui::Checkbox( "Chain", &m_useChain ) ) { CreateScene(); } if ( m_useChain == false ) { if ( ImGui::SliderFloat( "Bevel", &m_bevel, 0.0f, 1.0f, "%.2f" ) ) { CreateScene(); } } { const char* shapeTypes[] = { "Circle", "Capsule", "Box" }; int shapeType = int( m_shapeType ); ImGui::Combo( "Shape", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ); m_shapeType = ShapeType( shapeType ); } if ( m_shapeType == e_boxShape ) { ImGui::SliderFloat( "Round", &m_round, 0.0f, 0.4f, "%.1f" ); } if ( ImGui::SliderFloat( "Friction", &m_friction, 0.0f, 1.0f, "%.1f" ) ) { if ( B2_IS_NON_NULL( m_shapeId ) ) { b2Shape_SetFriction( m_shapeId, m_friction ); } CreateScene(); } if ( ImGui::Button( "Launch" ) ) { Launch(); } ImGui::PopItemWidth(); ImGui::End(); } static Sample* Create( SampleContext* context ) { return new GhostBumps( context ); } b2BodyId m_groundId; b2BodyId m_bodyId; b2ShapeId m_shapeId; ShapeType m_shapeType; float m_round; float m_friction; float m_bevel; bool m_useChain; }; static int sampleGhostCollision = RegisterSample( "Continuous", "Ghost Bumps", GhostBumps::Create ); // Speculative collision failure case suggested by Dirk Gregorius. This uses // a simple fallback scheme to prevent tunneling. class SpeculativeFallback : public Sample { public: explicit SpeculativeFallback( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 1.0f, 5.0f }; m_context->camera.zoom = 25.0f * 0.25f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -10.0f, 0.0f }, { 10.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); b2Vec2 points[5] = { { -2.0f, 4.0f }, { 2.0f, 4.0f }, { 2.0f, 4.1f }, { -0.5f, 4.2f }, { -2.0f, 4.2f } }; b2Hull hull = b2ComputeHull( points, 5 ); b2Polygon poly = b2MakePolygon( &hull, 0.0f ); b2CreatePolygonShape( groundId, &shapeDef, &poly ); } // Fast moving skinny box. Also testing a large shape offset. { float offset = 8.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { offset, 12.0f }; bodyDef.linearVelocity = { 0.0f, -100.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeOffsetBox( 2.0f, 0.05f, { -offset, 0.0f }, b2MakeRot( B2_PI ) ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } static Sample* Create( SampleContext* context ) { return new SpeculativeFallback( context ); } }; static int sampleSpeculativeFallback = RegisterSample( "Continuous", "Speculative Fallback", SpeculativeFallback::Create ); class SpeculativeSliver : public Sample { public: explicit SpeculativeSliver( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 1.75f }; m_context->camera.zoom = 2.5f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -10.0f, 0.0f }, { 10.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 0.0f, 12.0f }; bodyDef.linearVelocity = { 0.0f, -100.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Vec2 points[3] = { { -2.0f, 0.0f }, { -1.0f, 0.0f }, { 2.0f, 0.5f } }; b2Hull hull = b2ComputeHull( points, 3 ); b2Polygon poly = b2MakePolygon( &hull, 0.0f ); b2CreatePolygonShape( bodyId, &shapeDef, &poly ); } } static Sample* Create( SampleContext* context ) { return new SpeculativeSliver( context ); } }; static int sampleSpeculativeSliver = RegisterSample( "Continuous", "Speculative Sliver", SpeculativeSliver::Create ); // This shows that while Box2D uses speculative collision, it does not lead to speculative ghost collisions at small distances class SpeculativeGhost : public Sample { public: explicit SpeculativeGhost( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 1.75f }; m_context->camera.zoom = 2.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -10.0f, 0.0f }, { 10.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); b2Polygon box = b2MakeOffsetBox( 1.0f, 0.1f, { 0.0f, 0.9f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; // The speculative distance is 0.02 meters, so this avoid it bodyDef.position = { 0.015f, 2.515f }; bodyDef.linearVelocity = { 0.1f * 1.25f * m_context->hertz, -0.1f * 1.25f * m_context->hertz }; bodyDef.gravityScale = 0.0f; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeSquare( 0.25f ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } static Sample* Create( SampleContext* context ) { return new SpeculativeGhost( context ); } }; static int sampleSpeculativeGhost = RegisterSample( "Continuous", "Speculative Ghost", SpeculativeGhost::Create ); // This shows that Box2D does not have pixel perfect collision. class PixelImperfect : public Sample { public: explicit PixelImperfect( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 7.0f, 5.0f }; m_context->camera.zoom = 6.0f; } float pixelsPerMeter = 30.f; { b2BodyDef block4BodyDef = b2DefaultBodyDef(); block4BodyDef.type = b2_staticBody; block4BodyDef.position = { 175.f / pixelsPerMeter, 150.f / pixelsPerMeter }; b2BodyId block4BodyId = b2CreateBody( m_worldId, &block4BodyDef ); b2Polygon block4Shape = b2MakeBox( 20.f / pixelsPerMeter, 10.f / pixelsPerMeter ); b2ShapeDef block4ShapeDef = b2DefaultShapeDef(); block4ShapeDef.material.friction = 0.f; b2CreatePolygonShape( block4BodyId, &block4ShapeDef, &block4Shape ); } { b2BodyDef ballBodyDef = b2DefaultBodyDef(); ballBodyDef.type = b2_dynamicBody; ballBodyDef.position = { 200.0f / pixelsPerMeter, 275.f / pixelsPerMeter }; ballBodyDef.gravityScale = 0.0f; m_ballId = b2CreateBody( m_worldId, &ballBodyDef ); // Ball shape // b2Polygon ballShape = b2MakeBox( 5.f / pixelsPerMeter, 5.f / pixelsPerMeter ); b2Polygon ballShape = b2MakeRoundedBox( 4.0f / pixelsPerMeter, 4.0f / pixelsPerMeter, 0.9f / pixelsPerMeter ); b2ShapeDef ballShapeDef = b2DefaultShapeDef(); ballShapeDef.material.friction = 0.f; // ballShapeDef.restitution = 1.f; b2CreatePolygonShape( m_ballId, &ballShapeDef, &ballShape ); b2Body_SetLinearVelocity( m_ballId, { 0.f, -5.0f } ); b2Body_SetMotionLocks( m_ballId, { false, false, true } ); } } void Step() override { b2ContactData data; b2Body_GetContactData( m_ballId, &data, 1 ); b2Vec2 p = b2Body_GetPosition( m_ballId ); b2Vec2 v = b2Body_GetLinearVelocity( m_ballId ); DrawTextLine( "p.x = %.9f, v.y = %.9f", p.x, v.y ); Sample::Step(); } static Sample* Create( SampleContext* context ) { return new PixelImperfect( context ); } b2BodyId m_ballId; }; static int samplePixelImperfect = RegisterSample( "Continuous", "Pixel Imperfect", PixelImperfect::Create ); class RestitutionThreshold : public Sample { public: explicit RestitutionThreshold( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 7.0f, 5.0f }; m_context->camera.zoom = 6.0f; } float pixelsPerMeter = 30.f; // With the default threshold the ball will not bounce. b2World_SetRestitutionThreshold( m_worldId, 0.1f ); { b2BodyDef block0BodyDef = b2DefaultBodyDef(); block0BodyDef.type = b2_staticBody; block0BodyDef.position = { 205.f / pixelsPerMeter, 120.f / pixelsPerMeter }; block0BodyDef.rotation = b2MakeRot( 70.f * 3.14f / 180.f ); b2BodyId block0BodyId = b2CreateBody( m_worldId, &block0BodyDef ); b2Polygon block0Shape = b2MakeBox( 50.f / pixelsPerMeter, 5.f / pixelsPerMeter ); b2ShapeDef block0ShapeDef = b2DefaultShapeDef(); block0ShapeDef.material.friction = 0.f; b2CreatePolygonShape( block0BodyId, &block0ShapeDef, &block0Shape ); } { // Make a ball b2BodyDef ballBodyDef = b2DefaultBodyDef(); ballBodyDef.type = b2_dynamicBody; ballBodyDef.position = { 200.f / pixelsPerMeter, 250.f / pixelsPerMeter }; m_ballId = b2CreateBody( m_worldId, &ballBodyDef ); b2Circle ballShape = {}; ballShape.radius = 5.f / pixelsPerMeter; b2ShapeDef ballShapeDef = b2DefaultShapeDef(); ballShapeDef.material.friction = 0.f; ballShapeDef.material.restitution = 1.f; b2CreateCircleShape( m_ballId, &ballShapeDef, &ballShape ); b2Body_SetLinearVelocity( m_ballId, { 0.f, -2.9f } ); // Initial velocity b2Body_SetMotionLocks( m_ballId, { false, false, true } ); // Do not rotate a ball } } void Step() override { b2ContactData data; b2Body_GetContactData( m_ballId, &data, 1 ); b2Vec2 p = b2Body_GetPosition( m_ballId ); b2Vec2 v = b2Body_GetLinearVelocity( m_ballId ); DrawTextLine( "p.x = %.9f, v.y = %.9f", p.x, v.y ); Sample::Step(); } static Sample* Create( SampleContext* context ) { return new RestitutionThreshold( context ); } b2BodyId m_ballId; }; static int sampleRestitutionThreshold = RegisterSample( "Continuous", "Restitution Threshold", RestitutionThreshold::Create ); class Drop : public Sample { public: explicit Drop( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 1.5f }; m_context->camera.zoom = 3.0f; m_context->enableSleep = false; m_context->debugDraw.drawJoints = false; } #if 0 { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); float w = 0.25f; int count = 40; float x = -0.5f * count * w; float h = 0.05f; for ( int j = 0; j <= count; ++j ) { b2Polygon box = b2MakeOffsetBox( w, h, { x, -h }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); x += w; } } #endif m_human = {}; m_frameSkip = 0; m_frameCount = 0; m_continuous = true; m_speculative = true; Scene1(); } void Clear() { for ( int i = 0; i < m_bodyIds.size(); ++i ) { b2DestroyBody( m_bodyIds[i] ); } m_bodyIds.clear(); if ( m_human.isSpawned ) { DestroyHuman( &m_human ); } } void CreateGround1() { for ( int i = 0; i < m_groundIds.size(); ++i ) { b2DestroyBody( m_groundIds[i] ); } m_groundIds.clear(); b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); float w = 0.25f; int count = 40; b2Segment segment = { { -0.5f * count * w, 0.0f }, { 0.5f * count * w, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); m_groundIds.push_back( groundId ); } void CreateGround2() { for ( int i = 0; i < m_groundIds.size(); ++i ) { b2DestroyBody( m_groundIds[i] ); } m_groundIds.clear(); b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); float w = 0.25f; int count = 40; float x = -0.5f * count * w; float h = 0.05f; for ( int j = 0; j <= count; ++j ) { b2Polygon box = b2MakeOffsetBox( 0.5f * w, h, { x, 0.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); x += w; } m_groundIds.push_back( groundId ); } void CreateGround3() { for ( int i = 0; i < m_groundIds.size(); ++i ) { b2DestroyBody( m_groundIds[i] ); } m_groundIds.clear(); b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); float w = 0.25f; int count = 40; b2Segment segment = { { -0.5f * count * w, 0.0f }, { 0.5f * count * w, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); segment = { { 3.0f, 0.0f }, { 3.0f, 8.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); m_groundIds.push_back( groundId ); } // ball void Scene1() { Clear(); CreateGround2(); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 0.0f, 4.0f }; bodyDef.linearVelocity = { 0.0f, -100.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Circle circle = { { 0.0f, 0.0f }, 0.125f }; b2CreateCircleShape( bodyId, &shapeDef, &circle ); m_bodyIds.push_back( bodyId ); m_frameCount = 1; } // ruler void Scene2() { Clear(); CreateGround1(); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 0.0f, 4.0f }; bodyDef.rotation = b2MakeRot( 0.5f * B2_PI ); bodyDef.linearVelocity = { 0.0f, 0.0f }; bodyDef.angularVelocity = -0.5f; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeBox( 0.75f, 0.01f ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); m_bodyIds.push_back( bodyId ); m_frameCount = 1; } // ragdoll void Scene3() { Clear(); CreateGround2(); float jointFrictionTorque = 0.03f; float jointHertz = 1.0f; float jointDampingRatio = 0.5f; CreateHuman( &m_human, m_worldId, { 0.0f, 40.0f }, 1.0f, jointFrictionTorque, jointHertz, jointDampingRatio, 1, nullptr, true ); m_frameCount = 1; } void Scene4() { Clear(); CreateGround3(); float a = 0.25f; b2Polygon box = b2MakeSquare( a ); b2ShapeDef shapeDef = b2DefaultShapeDef(); float offset = 0.01f; for ( int i = 0; i < 5; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; float shift = ( i % 2 == 0 ? -offset : offset ); bodyDef.position = { 2.5f + shift, a + 2.0f * a * i }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); m_bodyIds.push_back( bodyId ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } b2Circle circle = { { 0.0f, 0.0f }, 0.125f }; shapeDef.density = 4.0f; { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -7.7f, 1.9f }; bodyDef.linearVelocity = { 200.0f, 0.0f }; bodyDef.isBullet = true; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreateCircleShape( bodyId, &shapeDef, &circle ); m_bodyIds.push_back( bodyId ); } m_frameCount = 1; } void Keyboard( int key ) override { switch ( key ) { case GLFW_KEY_1: Scene1(); break; case GLFW_KEY_2: Scene2(); break; case GLFW_KEY_3: Scene3(); break; case GLFW_KEY_4: Scene4(); break; case GLFW_KEY_C: Clear(); m_continuous = !m_continuous; break; case GLFW_KEY_V: Clear(); m_speculative = !m_speculative; b2World_EnableSpeculative( m_worldId, m_speculative ); break; case GLFW_KEY_S: m_frameSkip = m_frameSkip > 0 ? 0 : 60; break; default: Sample::Keyboard( key ); break; } } void Step() override { #if 0 ImGui::SetNextWindowPos( ImVec2( 0.0f, 0.0f ) ); ImGui::SetNextWindowSize( ImVec2( float( m_context->camera.width ), float( m_camera->height ) ) ); ImGui::SetNextWindowBgAlpha( 0.0f ); ImGui::Begin( "DropBackground", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoScrollbar ); ImDrawList* drawList = ImGui::GetWindowDrawList(); const char* ContinuousText = m_continuous && m_speculative ? "Continuous ON" : "Continuous OFF"; drawList->AddText( m_largeFont, m_largeFont->FontSize, { 40.0f, 40.0f }, IM_COL32_WHITE, ContinuousText ); if ( m_frameSkip > 0 ) { drawList->AddText( m_mediumFont, m_mediumFont->FontSize, { 40.0f, 40.0f + 64.0f + 20.0f }, IM_COL32( 200, 200, 200, 255 ), "Slow Time" ); } ImGui::End(); #endif // if (m_frameCount == 165) //{ // settings.pause = true; // m_frameSkip = 30; // } m_context->enableContinuous = m_continuous; if ( ( m_frameSkip == 0 || m_frameCount % m_frameSkip == 0 ) && m_context->pause == false ) { Sample::Step(); } else { bool pause = m_context->pause; m_context->pause = true; Sample::Step(); m_context->pause = pause; } m_frameCount += 1; } static Sample* Create( SampleContext* context ) { return new Drop( context ); } std::vector m_groundIds; std::vector m_bodyIds; Human m_human; int m_frameSkip; int m_frameCount; bool m_continuous; bool m_speculative; }; static int sampleDrop = RegisterSample( "Continuous", "Drop", Drop::Create ); // This shows a fast moving body that uses continuous collision versus static and dynamic bodies. // This is achieved by setting the ball body as a *bullet*. class Pinball : public Sample { public: explicit Pinball( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 9.0f }; m_context->camera.zoom = 25.0f * 0.5f; } m_context->debugDraw.drawJoints = false; // Ground body b2BodyId groundId = {}; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); b2Vec2 vs[5] = { { -8.0f, 6.0f }, { -8.0f, 20.0f }, { 8.0f, 20.0f }, { 8.0f, 6.0f }, { 0.0f, -2.0f } }; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = vs; chainDef.count = 5; chainDef.isLoop = true; b2CreateChain( groundId, &chainDef ); } // Flippers { b2Vec2 p1 = { -2.0f, 0.0f }, p2 = { 2.0f, 0.0f }; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.enableSleep = false; bodyDef.position = p1; b2BodyId leftFlipperId = b2CreateBody( m_worldId, &bodyDef ); bodyDef.position = p2; b2BodyId rightFlipperId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 1.75f, 0.2f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( leftFlipperId, &shapeDef, &box ); b2CreatePolygonShape( rightFlipperId, &shapeDef, &box ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.localFrameB.p = b2Vec2_zero; jointDef.enableMotor = true; jointDef.maxMotorTorque = 1000.0f; jointDef.enableLimit = true; jointDef.motorSpeed = 0.0f; jointDef.base.localFrameA.p = p1; jointDef.base.bodyIdB = leftFlipperId; jointDef.lowerAngle = -30.0f * B2_PI / 180.0f; jointDef.upperAngle = 5.0f * B2_PI / 180.0f; m_leftJointId = b2CreateRevoluteJoint( m_worldId, &jointDef ); jointDef.motorSpeed = 0.0f; jointDef.base.localFrameA.p = p2; jointDef.base.bodyIdB = rightFlipperId; jointDef.lowerAngle = -5.0f * B2_PI / 180.0f; jointDef.upperAngle = 30.0f * B2_PI / 180.0f; m_rightJointId = b2CreateRevoluteJoint( m_worldId, &jointDef ); } // Spinners { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -4.0f, 17.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box1 = b2MakeBox( 1.5f, 0.125f ); b2Polygon box2 = b2MakeBox( 0.125f, 1.5f ); b2CreatePolygonShape( bodyId, &shapeDef, &box1 ); b2CreatePolygonShape( bodyId, &shapeDef, &box2 ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = bodyDef.position; jointDef.base.localFrameB.p = b2Vec2_zero; jointDef.enableMotor = true; jointDef.maxMotorTorque = 0.1f; b2CreateRevoluteJoint( m_worldId, &jointDef ); bodyDef.position = { 4.0f, 8.0f }; bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box1 ); b2CreatePolygonShape( bodyId, &shapeDef, &box2 ); jointDef.base.localFrameA.p = bodyDef.position; jointDef.base.bodyIdB = bodyId; b2CreateRevoluteJoint( m_worldId, &jointDef ); } // Bumpers { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { -4.0f, 8.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.restitution = 1.5f; b2Circle circle = { { 0.0f, 0.0f }, 1.0f }; b2CreateCircleShape( bodyId, &shapeDef, &circle ); bodyDef.position = { 4.0f, 17.0f }; bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreateCircleShape( bodyId, &shapeDef, &circle ); } // Ball { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 1.0f, 15.0f }; bodyDef.type = b2_dynamicBody; bodyDef.isBullet = true; m_ballId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Circle circle = { { 0.0f, 0.0f }, 0.2f }; b2CreateCircleShape( m_ballId, &shapeDef, &circle ); } } void Step() override { Sample::Step(); if ( glfwGetKey( m_context->window, GLFW_KEY_SPACE ) == GLFW_PRESS ) { b2RevoluteJoint_SetMotorSpeed( m_leftJointId, 20.0f ); b2RevoluteJoint_SetMotorSpeed( m_rightJointId, -20.0f ); } else { b2RevoluteJoint_SetMotorSpeed( m_leftJointId, -10.0f ); b2RevoluteJoint_SetMotorSpeed( m_rightJointId, 10.0f ); } } static Sample* Create( SampleContext* context ) { return new Pinball( context ); } b2JointId m_leftJointId; b2JointId m_rightJointId; b2BodyId m_ballId; }; static int samplePinball = RegisterSample( "Continuous", "Pinball", Pinball::Create ); // This shows the importance of secondary collisions in continuous physics. // This also shows a difficult setup for the solver with an acute angle. class Wedge : public Sample { public: explicit Wedge( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 5.5f }; m_context->camera.zoom = 6.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -4.0f, 8.0f }, { 0.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); segment = { { 0.0f, 0.0f }, { 0.0f, 8.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -0.45f, 10.75f }; bodyDef.linearVelocity = { 0.0f, -200.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Circle circle = {}; circle.radius = 0.3f; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.2f; b2CreateCircleShape( bodyId, &shapeDef, &circle ); } } static Sample* Create( SampleContext* context ) { return new Wedge( context ); } }; static int sampleWedge = RegisterSample( "Continuous", "Wedge", Wedge::Create ); ================================================ FILE: samples/sample_determinism.cpp ================================================ // SPDX-FileCopyrightText: 2022 Erin Catto // SPDX-License-Identifier: MIT #include "determinism.h" #include "sample.h" #include "box2d/math_functions.h" // This sample provides a visual representation of the cross platform determinism unit test. // The scenario is designed to produce a chaotic result engaging: // - continuous collision // - joint limits (approximate atan2) // - b2MakeRot (approximate sin/cos) // Once all the bodies go to sleep the step counter and transform hash is emitted which // can then be transferred to the unit test and tested in GitHub build actions. // See CrossPlatformTest in the unit tests. class FallingHinges : public Sample { public: explicit FallingHinges( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 7.5f }; m_context->camera.zoom = 10.0f; } m_data = CreateFallingHinges( m_worldId ); m_done = false; } ~FallingHinges() override { DestroyFallingHinges( &m_data ); } void Step() override { Sample::Step(); if (m_context->pause == false && m_done == false) { m_done = UpdateFallingHinges( m_worldId, &m_data ); } else { DrawTextLine( "sleep step = %d, hash = 0x%08X", m_data.sleepStep, m_data.hash ); } } static Sample* Create( SampleContext* context ) { return new FallingHinges( context ); } FallingHingeData m_data; bool m_done; }; static int sampleFallingHinges = RegisterSample( "Determinism", "Falling Hinges", FallingHinges::Create ); ================================================ FILE: samples/sample_events.cpp ================================================ // SPDX-FileCopyrightText: 2022 Erin Catto // SPDX-License-Identifier: MIT #include "donut.h" #include "draw.h" #include "human.h" #include "random.h" #include "sample.h" #include "box2d/box2d.h" #include "box2d/math_functions.h" #include #include #include #include class SensorFunnel : public Sample { public: enum { e_donut = 1, e_human = 2, e_count = 32 }; explicit SensorFunnel( SampleContext* context ) : Sample( context ) { if (m_context->restart == false) { m_context->camera.center = { 0.0f, 0.0f }; m_context->camera.zoom = 25.0f * 1.333f; } m_context->debugDraw.drawJoints = false; { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); // b2Vec2 points[] = { //{42.333, 44.979}, {177.271, 44.979}, {177.271, 100.542}, {142.875, 121.708}, {177.271, 121.708}, //{177.271, 171.979}, {142.875, 193.146}, {177.271, 193.146}, {177.271, 222.250}, {124.354, 261.938}, //{124.354, 293.688}, {95.250, 293.688}, {95.250, 261.938}, {42.333, 222.250}, {42.333, 193.146}, //{76.729, 193.146}, {42.333, 171.979}, {42.333, 121.708}, {76.729, 121.708}, {42.333, 100.542}, //}; b2Vec2 points[] = { { -16.8672504, 31.088623 }, { 16.8672485, 31.088623 }, { 16.8672485, 17.1978741 }, { 8.26824951, 11.906374 }, { 16.8672485, 11.906374 }, { 16.8672485, -0.661376953 }, { 8.26824951, -5.953125 }, { 16.8672485, -5.953125 }, { 16.8672485, -13.229126 }, { 3.63799858, -23.151123 }, { 3.63799858, -31.088623 }, { -3.63800049, -31.088623 }, { -3.63800049, -23.151123 }, { -16.8672504, -13.229126 }, { -16.8672504, -5.953125 }, { -8.26825142, -5.953125 }, { -16.8672504, -0.661376953 }, { -16.8672504, 11.906374 }, { -8.26825142, 11.906374 }, { -16.8672504, 17.1978741 }, }; int count = std::size( points ); // float scale = 0.25f; // b2Vec2 lower = {FLT_MAX, FLT_MAX}; // b2Vec2 upper = {-FLT_MAX, -FLT_MAX}; // for (int i = 0; i < count; ++i) //{ // points[i].x = scale * points[i].x; // points[i].y = -scale * points[i].y; // lower = b2Min(lower, points[i]); // upper = b2Max(upper, points[i]); //} // b2Vec2 center = b2MulSV(0.5f, b2Add(lower, upper)); // for (int i = 0; i < count; ++i) //{ // points[i] = b2Sub(points[i], center); // } // for (int i = 0; i < count / 2; ++i) //{ // b2Vec2 temp = points[i]; // points[i] = points[count - 1 - i]; // points[count - 1 - i] = temp; // } // printf("{"); // for (int i = 0; i < count; ++i) //{ // printf("{%.9g, %.9g},", points[i].x, points[i].y); // } // printf("};\n"); b2SurfaceMaterial material = {}; material.friction = 0.2f; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = count; chainDef.isLoop = true; chainDef.materials = &material; chainDef.materialCount = 1; b2CreateChain( groundId, &chainDef ); float sign = 1.0f; float y = 14.0f; for (int i = 0; i < 3; ++i) { bodyDef.position = { 0.0f, y }; bodyDef.type = b2_dynamicBody; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 6.0f, 0.5f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.1f; shapeDef.material.restitution = 1.0f; shapeDef.density = 1.0f; b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2RevoluteJointDef revoluteDef = b2DefaultRevoluteJointDef(); revoluteDef.base.bodyIdA = groundId; revoluteDef.base.bodyIdB = bodyId; revoluteDef.base.localFrameA.p = bodyDef.position; revoluteDef.base.localFrameB.p = b2Vec2_zero; revoluteDef.maxMotorTorque = 200.0f; revoluteDef.motorSpeed = 2.0f * sign; revoluteDef.enableMotor = true; b2CreateRevoluteJoint( m_worldId, &revoluteDef ); y -= 14.0f; sign = -sign; } { b2Polygon box = b2MakeOffsetBox( 4.0f, 1.0f, { 0.0f, -30.5f }, b2Rot_identity ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.isSensor = true; shapeDef.enableSensorEvents = true; b2CreatePolygonShape( groundId, &shapeDef, &box ); } } m_wait = 0.5f; m_side = -15.0f; m_type = e_human; for (int i = 0; i < e_count; ++i) { m_isSpawned[i] = false; } memset( m_humans, 0, sizeof( m_humans ) ); CreateElement(); } void CreateElement() { int index = -1; for (int i = 0; i < e_count; ++i) { if (m_isSpawned[i] == false) { index = i; break; } } if (index == -1) { return; } b2Vec2 center = { m_side, 29.5f }; if (m_type == e_donut) { Donut* donut = m_donuts + index; donut->Create( m_worldId, center, 1.0f, 0, true, donut ); } else { Human* human = m_humans + index; float scale = 2.0f; float jointFriction = 0.05f; float jointHertz = 6.0f; float jointDamping = 0.5f; bool colorize = true; CreateHuman( human, m_worldId, center, scale, jointFriction, jointHertz, jointDamping, index + 1, human, colorize ); Human_EnableSensorEvents( human, true ); } m_isSpawned[index] = true; m_side = -m_side; } void DestroyElement( int index ) { if (m_type == e_donut) { Donut* donut = m_donuts + index; donut->Destroy(); } else { Human* human = m_humans + index; DestroyHuman( human ); } m_isSpawned[index] = false; } void Clear() { for (int i = 0; i < e_count; ++i) { if (m_isSpawned[i] == true) { if (m_type == e_donut) { m_donuts[i].Destroy(); } else { DestroyHuman( m_humans + i ); } m_isSpawned[i] = false; } } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 90.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 140.0f, height ) ); ImGui::Begin( "Sensor Event", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); if (ImGui::RadioButton( "donut", m_type == e_donut )) { Clear(); m_type = e_donut; } if (ImGui::RadioButton( "human", m_type == e_human )) { Clear(); m_type = e_human; } ImGui::End(); } void Step() override { if (m_stepCount == 832) { m_stepCount += 0; } Sample::Step(); // Discover rings that touch the bottom sensor bool deferredDestruction[e_count] = {}; b2SensorEvents sensorEvents = b2World_GetSensorEvents( m_worldId ); for (int i = 0; i < sensorEvents.beginCount; ++i) { b2SensorBeginTouchEvent event = sensorEvents.beginEvents[i]; b2ShapeId visitorId = event.visitorShapeId; b2BodyId bodyId = b2Shape_GetBody( visitorId ); if (m_type == e_donut) { Donut* donut = (Donut*)b2Body_GetUserData( bodyId ); if (donut != nullptr) { int index = (int)( donut - m_donuts ); assert( 0 <= index && index < e_count ); // Defer destruction to avoid double destruction and event invalidation (orphaned shape ids) deferredDestruction[index] = true; } } else { Human* human = (Human*)b2Body_GetUserData( bodyId ); if (human != nullptr) { int index = (int)( human - m_humans ); assert( 0 <= index && index < e_count ); // Defer destruction to avoid double destruction and event invalidation (orphaned shape ids) deferredDestruction[index] = true; } } } // todo destroy mouse joint if necessary // Safely destroy rings that hit the bottom sensor for (int i = 0; i < e_count; ++i) { if (deferredDestruction[i]) { DestroyElement( i ); } } if (m_context->hertz > 0.0f && m_context->pause == false) { m_wait -= 1.0f / m_context->hertz; if (m_wait < 0.0f) { CreateElement(); m_wait += 0.5f; } } } static Sample* Create( SampleContext* context ) { return new SensorFunnel( context ); } Human m_humans[e_count]; Donut m_donuts[e_count]; bool m_isSpawned[e_count]; int m_type; float m_wait; float m_side; }; static int sampleSensorBeginEvent = RegisterSample( "Events", "Sensor Funnel", SensorFunnel::Create ); class SensorBookend : public Sample { public: explicit SensorBookend( SampleContext* context ) : Sample( context ) { if (m_context->restart == false) { m_context->camera.center = { 0.0f, 6.0f }; m_context->camera.zoom = 7.5f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment groundSegment = { { -10.0f, 0.0f }, { 10.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &groundSegment ); groundSegment = { { -10.0f, 0.0f }, { -10.0f, 10.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &groundSegment ); groundSegment = { { 10.0f, 0.0f }, { 10.0f, 10.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &groundSegment ); m_isVisiting1 = false; m_isVisiting2 = false; m_sensorsOverlapCount = 0; } CreateSensor1(); CreateSensor2(); CreateVisitor(); } void CreateSensor1() { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { -2.0f, 1.0f }; m_sensorBodyId1 = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.isSensor = true; shapeDef.enableSensorEvents = true; b2Polygon box = b2MakeSquare( 1.0f ); m_sensorShapeId1 = b2CreatePolygonShape( m_sensorBodyId1, &shapeDef, &box ); } void CreateSensor2() { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 2.0f, 1.0f }; m_sensorBodyId2 = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.isSensor = true; shapeDef.enableSensorEvents = true; b2Polygon box = b2MakeRoundedBox( 0.5f, 0.5f, 0.5f ); m_sensorShapeId2 = b2CreatePolygonShape( m_sensorBodyId2, &shapeDef, &box ); // Solid middle shapeDef.isSensor = false; shapeDef.enableSensorEvents = false; box = b2MakeSquare( 0.5f ); b2CreatePolygonShape( m_sensorBodyId2, &shapeDef, &box ); } void CreateVisitor() { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { -4.0f, 1.0f }; bodyDef.type = b2_dynamicBody; m_visitorBodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.enableSensorEvents = true; b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; m_visitorShapeId = b2CreateCircleShape( m_visitorBodyId, &shapeDef, &circle ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 19.0f * fontSize; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 12.0f * fontSize, height ) ); ImGui::Begin( "Sensor Bookend", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); if (B2_IS_NULL( m_visitorBodyId )) { if (ImGui::Button( "create visitor" )) { CreateVisitor(); } } else { if (ImGui::Button( "destroy visitor" )) { b2DestroyBody( m_visitorBodyId ); m_visitorBodyId = b2_nullBodyId; // Retain m_visitorShapeId for end events. } else { bool enabledEvents = b2Shape_AreSensorEventsEnabled( m_visitorShapeId ); if (ImGui::Checkbox( "visitor events", &enabledEvents )) { b2Shape_EnableSensorEvents( m_visitorShapeId, enabledEvents ); } bool enabledBody = b2Body_IsEnabled( m_visitorBodyId ); if (ImGui::Checkbox( "enable visitor body", &enabledBody )) { if (enabledBody) { b2Body_Enable( m_visitorBodyId ); } else { b2Body_Disable( m_visitorBodyId ); } } } } ImGui::Separator(); if (B2_IS_NULL( m_sensorBodyId1 )) { if (ImGui::Button( "create sensor1" )) { CreateSensor1(); } } else { if (ImGui::Button( "destroy sensor1" )) { b2DestroyBody( m_sensorBodyId1 ); m_sensorBodyId1 = b2_nullBodyId; // Retain m_sensorShapeId1 for end events. } else { bool enabledEvents = b2Shape_AreSensorEventsEnabled( m_sensorShapeId1 ); if (ImGui::Checkbox( "sensor 1 events", &enabledEvents )) { b2Shape_EnableSensorEvents( m_sensorShapeId1, enabledEvents ); } bool enabledBody = b2Body_IsEnabled( m_sensorBodyId1 ); if (ImGui::Checkbox( "enable sensor1 body", &enabledBody )) { if (enabledBody) { b2Body_Enable( m_sensorBodyId1 ); } else { b2Body_Disable( m_sensorBodyId1 ); } } } } ImGui::Separator(); if (B2_IS_NULL( m_sensorBodyId2 )) { if (ImGui::Button( "create sensor2" )) { CreateSensor2(); } } else { if (ImGui::Button( "destroy sensor2" )) { b2DestroyBody( m_sensorBodyId2 ); m_sensorBodyId2 = b2_nullBodyId; // Retain m_sensorShapeId2 for end events. } else { bool enabledEvents = b2Shape_AreSensorEventsEnabled( m_sensorShapeId2 ); if (ImGui::Checkbox( "sensor2 events", &enabledEvents )) { b2Shape_EnableSensorEvents( m_sensorShapeId2, enabledEvents ); } bool enabledBody = b2Body_IsEnabled( m_sensorBodyId2 ); if (ImGui::Checkbox( "enable sensor2 body", &enabledBody )) { if (enabledBody) { b2Body_Enable( m_sensorBodyId2 ); } else { b2Body_Disable( m_sensorBodyId2 ); } } } } ImGui::End(); } void Step() override { Sample::Step(); b2SensorEvents sensorEvents = b2World_GetSensorEvents( m_worldId ); for (int i = 0; i < sensorEvents.beginCount; ++i) { b2SensorBeginTouchEvent event = sensorEvents.beginEvents[i]; if (B2_ID_EQUALS( event.sensorShapeId, m_sensorShapeId1 )) { if (B2_ID_EQUALS( event.visitorShapeId, m_visitorShapeId )) { assert( m_isVisiting1 == false ); m_isVisiting1 = true; } else { assert( B2_ID_EQUALS( event.visitorShapeId, m_sensorShapeId2 ) ); m_sensorsOverlapCount += 1; } } else { assert( B2_ID_EQUALS( event.sensorShapeId, m_sensorShapeId2 ) ); if (B2_ID_EQUALS( event.visitorShapeId, m_visitorShapeId )) { assert( m_isVisiting2 == false ); m_isVisiting2 = true; } else { assert( B2_ID_EQUALS( event.visitorShapeId, m_sensorShapeId1 ) ); m_sensorsOverlapCount += 1; } } } assert( m_sensorsOverlapCount == 0 || m_sensorsOverlapCount == 2 ); for (int i = 0; i < sensorEvents.endCount; ++i) { b2SensorEndTouchEvent event = sensorEvents.endEvents[i]; if (B2_ID_EQUALS( event.sensorShapeId, m_sensorShapeId1 )) { if (B2_ID_EQUALS( event.visitorShapeId, m_visitorShapeId )) { assert( m_isVisiting1 == true ); m_isVisiting1 = false; } else { assert( B2_ID_EQUALS( event.visitorShapeId, m_sensorShapeId2 ) ); m_sensorsOverlapCount -= 1; } } else { assert( B2_ID_EQUALS( event.sensorShapeId, m_sensorShapeId2 ) ); if (B2_ID_EQUALS( event.visitorShapeId, m_visitorShapeId )) { assert( m_isVisiting2 == true ); m_isVisiting2 = false; } else { assert( B2_ID_EQUALS( event.visitorShapeId, m_sensorShapeId1 ) ); m_sensorsOverlapCount -= 1; } } } assert( m_sensorsOverlapCount == 0 || m_sensorsOverlapCount == 2 ); // Nullify invalid shape ids after end events are processed. if (b2Shape_IsValid( m_visitorShapeId ) == false) { m_visitorShapeId = b2_nullShapeId; } if (b2Shape_IsValid( m_sensorShapeId1 ) == false) { m_sensorShapeId1 = b2_nullShapeId; } if (b2Shape_IsValid( m_sensorShapeId2 ) == false) { m_sensorShapeId2 = b2_nullShapeId; } DrawTextLine( "visiting 1 == %s", m_isVisiting1 ? "true" : "false" ); DrawTextLine( "visiting 2 == %s", m_isVisiting2 ? "true" : "false" ); DrawTextLine( "sensors overlap count == %d", m_sensorsOverlapCount ); } static Sample* Create( SampleContext* context ) { return new SensorBookend( context ); } b2BodyId m_sensorBodyId1; b2ShapeId m_sensorShapeId1; b2BodyId m_sensorBodyId2; b2ShapeId m_sensorShapeId2; b2BodyId m_visitorBodyId; b2ShapeId m_visitorShapeId; bool m_isVisiting1; bool m_isVisiting2; int m_sensorsOverlapCount; }; static int sampleSensorBookendEvent = RegisterSample( "Events", "Sensor Bookend", SensorBookend::Create ); class FootSensor : public Sample { public: enum CollisionBits { GROUND = 0x00000001, PLAYER = 0x00000002, FOOT = 0x00000004, ALL_BITS = ( ~0u ) }; explicit FootSensor( SampleContext* context ) : Sample( context ) { if (m_context->restart == false) { m_context->camera.center = { 0.0f, 6.0f }; m_context->camera.zoom = 7.5f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2Vec2 points[20]; float x = 10.0f; for (int i = 0; i < 20; ++i) { points[i] = { x, 0.0f }; x -= 1.0f; } b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = 20; chainDef.filter.categoryBits = GROUND; chainDef.filter.maskBits = FOOT | PLAYER; chainDef.isLoop = false; chainDef.enableSensorEvents = true; b2CreateChain( groundId, &chainDef ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.motionLocks.angularZ = true; bodyDef.position = { 0.0f, 1.0f }; m_playerId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.filter.categoryBits = PLAYER; shapeDef.filter.maskBits = GROUND; shapeDef.material.friction = 0.3f; b2Capsule capsule = { { 0.0f, -0.5f }, { 0.0f, 0.5f }, 0.5f }; b2CreateCapsuleShape( m_playerId, &shapeDef, &capsule ); b2Polygon box = b2MakeOffsetBox( 0.5f, 0.25f, { 0.0f, -1.0f }, b2Rot_identity ); shapeDef.filter.categoryBits = FOOT; shapeDef.filter.maskBits = GROUND; shapeDef.isSensor = true; shapeDef.enableSensorEvents = true; m_sensorId = b2CreatePolygonShape( m_playerId, &shapeDef, &box ); } m_overlapCount = 0; } void Step() override { if (glfwGetKey( m_context->window, GLFW_KEY_A ) == GLFW_PRESS) { b2Body_ApplyForceToCenter( m_playerId, { -50.0f, 0.0f }, true ); } if (glfwGetKey( m_context->window, GLFW_KEY_D ) == GLFW_PRESS) { b2Body_ApplyForceToCenter( m_playerId, { 50.0f, 0.0f }, true ); } Sample::Step(); b2SensorEvents sensorEvents = b2World_GetSensorEvents( m_worldId ); for (int i = 0; i < sensorEvents.beginCount; ++i) { b2SensorBeginTouchEvent event = sensorEvents.beginEvents[i]; assert( B2_ID_EQUALS( event.visitorShapeId, m_sensorId ) == false ); if (B2_ID_EQUALS( event.sensorShapeId, m_sensorId )) { m_overlapCount += 1; } } for (int i = 0; i < sensorEvents.endCount; ++i) { b2SensorEndTouchEvent event = sensorEvents.endEvents[i]; assert( B2_ID_EQUALS( event.visitorShapeId, m_sensorId ) == false ); if (B2_ID_EQUALS( event.sensorShapeId, m_sensorId )) { m_overlapCount -= 1; } } DrawTextLine( "count == %d", m_overlapCount ); int capacity = b2Shape_GetSensorCapacity( m_sensorId ); m_visitorIds.clear(); m_visitorIds.resize( capacity ); int count = b2Shape_GetSensorData( m_sensorId, m_visitorIds.data(), capacity ); for (int i = 0; i < count; ++i) { b2ShapeId shapeId = m_visitorIds[i]; b2AABB aabb = b2Shape_GetAABB( shapeId ); b2Vec2 point = b2AABB_Center( aabb ); DrawPoint( m_draw, point, 10.0f, b2_colorWhite ); } } static Sample* Create( SampleContext* context ) { return new FootSensor( context ); } b2BodyId m_playerId; b2ShapeId m_sensorId; std::vector m_visitorIds; int m_overlapCount; }; static int sampleFootSensor = RegisterSample( "Events", "Foot Sensor", FootSensor::Create ); struct BodyUserData { int index; }; class ContactEvent : public Sample { public: enum { e_count = 20 }; explicit ContactEvent( SampleContext* context ) : Sample( context ) { if (m_context->restart == false) { m_context->camera.center = { 0.0f, 0.0f }; m_context->camera.zoom = 25.0f * 1.75f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2Vec2 points[] = { { 40.0f, -40.0f }, { -40.0f, -40.0f }, { -40.0f, 40.0f }, { 40.0f, 40.0f } }; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.count = 4; chainDef.points = points; chainDef.isLoop = true; b2CreateChain( groundId, &chainDef ); } // Player { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.gravityScale = 0.0f; bodyDef.linearDamping = 0.5f; bodyDef.angularDamping = 0.5f; bodyDef.isBullet = true; m_playerId = b2CreateBody( m_worldId, &bodyDef ); b2Circle circle = { { 0.0f, 0.0f }, 1.0f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); // Enable contact events for the player shape shapeDef.enableContactEvents = true; m_coreShapeId = b2CreateCircleShape( m_playerId, &shapeDef, &circle ); } for (int i = 0; i < e_count; ++i) { m_debrisIds[i] = b2_nullBodyId; m_bodyUserData[i].index = i; } m_wait = 0.5f; m_force = 200.0f; } void SpawnDebris() { int index = -1; for (int i = 0; i < e_count; ++i) { if (B2_IS_NULL( m_debrisIds[i] )) { index = i; break; } } if (index == -1) { return; } // Debris b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { RandomFloatRange( -38.0f, 38.0f ), RandomFloatRange( -38.0f, 38.0f ) }; bodyDef.rotation = b2MakeRot( RandomFloatRange( -B2_PI, B2_PI ) ); bodyDef.linearVelocity = { RandomFloatRange( -5.0f, 5.0f ), RandomFloatRange( -5.0f, 5.0f ) }; bodyDef.angularVelocity = RandomFloatRange( -1.0f, 1.0f ); bodyDef.gravityScale = 0.0f; bodyDef.userData = m_bodyUserData + index; m_debrisIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.restitution = 0.8f; // No events when debris hits debris shapeDef.enableContactEvents = false; if (( index + 1 ) % 3 == 0) { b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; b2CreateCircleShape( m_debrisIds[index], &shapeDef, &circle ); } else if (( index + 1 ) % 2 == 0) { b2Capsule capsule = { { 0.0f, -0.25f }, { 0.0f, 0.25f }, 0.25f }; b2CreateCapsuleShape( m_debrisIds[index], &shapeDef, &capsule ); } else { b2Polygon box = b2MakeBox( 0.4f, 0.6f ); b2CreatePolygonShape( m_debrisIds[index], &shapeDef, &box ); } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 60.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Contact Event", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); ImGui::SliderFloat( "force", &m_force, 100.0f, 500.0f, "%.1f" ); ImGui::End(); } void Step() override { DrawTextLine( "move using WASD" ); b2Vec2 position = b2Body_GetPosition( m_playerId ); if (glfwGetKey( m_context->window, GLFW_KEY_A ) == GLFW_PRESS) { b2Body_ApplyForce( m_playerId, { -m_force, 0.0f }, position, true ); } if (glfwGetKey( m_context->window, GLFW_KEY_D ) == GLFW_PRESS) { b2Body_ApplyForce( m_playerId, { m_force, 0.0f }, position, true ); } if (glfwGetKey( m_context->window, GLFW_KEY_W ) == GLFW_PRESS) { b2Body_ApplyForce( m_playerId, { 0.0f, m_force }, position, true ); } if (glfwGetKey( m_context->window, GLFW_KEY_S ) == GLFW_PRESS) { b2Body_ApplyForce( m_playerId, { 0.0f, -m_force }, position, true ); } Sample::Step(); // Discover rings that touch the bottom sensor int debrisToAttach[e_count] = {}; b2ShapeId shapesToDestroy[e_count] = { b2_nullShapeId }; int attachCount = 0; int destroyCount = 0; std::vector contactData; // Process contact begin touch events. b2ContactEvents contactEvents = b2World_GetContactEvents( m_worldId ); for (int i = 0; i < contactEvents.beginCount; ++i) { b2ContactBeginTouchEvent event = contactEvents.beginEvents[i]; b2BodyId bodyIdA = b2Shape_GetBody( event.shapeIdA ); b2BodyId bodyIdB = b2Shape_GetBody( event.shapeIdB ); // The begin touch events have the contact manifolds, but the impulses are zero. This is because the manifolds // are gathered before the contact solver is run. // We can get the final contact data from the shapes. The manifold is shared by the two shapes, so we just need the // contact data from one of the shapes. Choose the one with the smallest number of contacts. int capacityA = b2Shape_GetContactCapacity( event.shapeIdA ); int capacityB = b2Shape_GetContactCapacity( event.shapeIdB ); if (capacityA < capacityB) { contactData.resize( capacityA ); // The count may be less than the capacity int countA = b2Shape_GetContactData( event.shapeIdA, contactData.data(), capacityA ); assert( countA >= 1 ); for (int j = 0; j < countA; ++j) { b2ShapeId idA = contactData[j].shapeIdA; b2ShapeId idB = contactData[j].shapeIdB; if (B2_ID_EQUALS( idA, event.shapeIdB ) || B2_ID_EQUALS( idB, event.shapeIdB )) { assert( B2_ID_EQUALS( idA, event.shapeIdA ) || B2_ID_EQUALS( idB, event.shapeIdA ) ); b2Manifold manifold = contactData[j].manifold; b2Vec2 normal = manifold.normal; assert( b2AbsFloat( b2Length( normal ) - 1.0f ) < 4.0f * FLT_EPSILON ); for (int k = 0; k < manifold.pointCount; ++k) { b2ManifoldPoint point = manifold.points[k]; DrawLine( m_draw, point.point, point.point + point.totalNormalImpulse * normal, b2_colorBlueViolet ); DrawPoint( m_draw, point.point, 10.0f, b2_colorWhite ); } } } } else { contactData.resize( capacityB ); // The count may be less than the capacity int countB = b2Shape_GetContactData( event.shapeIdB, contactData.data(), capacityB ); assert( countB >= 1 ); for (int j = 0; j < countB; ++j) { b2ShapeId idA = contactData[j].shapeIdA; b2ShapeId idB = contactData[j].shapeIdB; if (B2_ID_EQUALS( idA, event.shapeIdA ) || B2_ID_EQUALS( idB, event.shapeIdA )) { assert( B2_ID_EQUALS( idA, event.shapeIdB ) || B2_ID_EQUALS( idB, event.shapeIdB ) ); b2Manifold manifold = contactData[j].manifold; b2Vec2 normal = manifold.normal; assert( b2AbsFloat( b2Length( normal ) - 1.0f ) < 4.0f * FLT_EPSILON ); for (int k = 0; k < manifold.pointCount; ++k) { b2ManifoldPoint point = manifold.points[k]; DrawLine( m_draw, point.point, point.point + point.totalNormalImpulse * normal, b2_colorYellowGreen ); DrawPoint( m_draw, point.point, 10.0f, b2_colorWhite ); } } } } if (B2_ID_EQUALS( bodyIdA, m_playerId )) { BodyUserData* userDataB = static_cast( b2Body_GetUserData( bodyIdB ) ); if (userDataB == nullptr) { if (B2_ID_EQUALS( event.shapeIdA, m_coreShapeId ) == false && destroyCount < e_count) { // player non-core shape hit the wall bool found = false; for (int j = 0; j < destroyCount; ++j) { if (B2_ID_EQUALS( event.shapeIdA, shapesToDestroy[j] )) { found = true; break; } } // avoid double deletion if (found == false) { shapesToDestroy[destroyCount] = event.shapeIdA; destroyCount += 1; } } } else if (attachCount < e_count) { debrisToAttach[attachCount] = userDataB->index; attachCount += 1; } } else { // Only expect events for the player assert( B2_ID_EQUALS( bodyIdB, m_playerId ) ); BodyUserData* userDataA = static_cast( b2Body_GetUserData( bodyIdA ) ); if (userDataA == nullptr) { if (B2_ID_EQUALS( event.shapeIdB, m_coreShapeId ) == false && destroyCount < e_count) { // player non-core shape hit the wall bool found = false; for (int j = 0; j < destroyCount; ++j) { if (B2_ID_EQUALS( event.shapeIdB, shapesToDestroy[j] )) { found = true; break; } } // avoid double deletion if (found == false) { shapesToDestroy[destroyCount] = event.shapeIdB; destroyCount += 1; } } } else if (attachCount < e_count) { debrisToAttach[attachCount] = userDataA->index; attachCount += 1; } } } // Attach debris to player body for (int i = 0; i < attachCount; ++i) { int index = debrisToAttach[i]; b2BodyId debrisId = m_debrisIds[index]; if (B2_IS_NULL( debrisId )) { continue; } b2Transform playerTransform = b2Body_GetTransform( m_playerId ); b2Transform debrisTransform = b2Body_GetTransform( debrisId ); b2Transform relativeTransform = b2InvMulTransforms( playerTransform, debrisTransform ); int shapeCount = b2Body_GetShapeCount( debrisId ); if (shapeCount == 0) { continue; } b2ShapeId shapeId; b2Body_GetShapes( debrisId, &shapeId, 1 ); b2ShapeType type = b2Shape_GetType( shapeId ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.enableContactEvents = true; switch (type) { case b2_circleShape: { b2Circle circle = b2Shape_GetCircle( shapeId ); circle.center = b2TransformPoint( relativeTransform, circle.center ); b2CreateCircleShape( m_playerId, &shapeDef, &circle ); } break; case b2_capsuleShape: { b2Capsule capsule = b2Shape_GetCapsule( shapeId ); capsule.center1 = b2TransformPoint( relativeTransform, capsule.center1 ); capsule.center2 = b2TransformPoint( relativeTransform, capsule.center2 ); b2CreateCapsuleShape( m_playerId, &shapeDef, &capsule ); } break; case b2_polygonShape: { b2Polygon originalPolygon = b2Shape_GetPolygon( shapeId ); b2Polygon polygon = b2TransformPolygon( relativeTransform, &originalPolygon ); b2CreatePolygonShape( m_playerId, &shapeDef, &polygon ); } break; default: assert( false ); } b2DestroyBody( debrisId ); m_debrisIds[index] = b2_nullBodyId; } for (int i = 0; i < destroyCount; ++i) { bool updateMass = false; b2DestroyShape( shapesToDestroy[i], updateMass ); } if (destroyCount > 0) { // Update mass just once b2Body_ApplyMassFromShapes( m_playerId ); } if (m_context->hertz > 0.0f && m_context->pause == false) { m_wait -= 1.0f / m_context->hertz; if (m_wait < 0.0f) { SpawnDebris(); m_wait += 0.5f; } } } static Sample* Create( SampleContext* context ) { return new ContactEvent( context ); } b2BodyId m_playerId; b2ShapeId m_coreShapeId; b2BodyId m_debrisIds[e_count]; BodyUserData m_bodyUserData[e_count]; float m_force; float m_wait; }; static int sampleWeeble = RegisterSample( "Events", "Contact", ContactEvent::Create ); // Shows how to make a rigid body character mover and use the pre-solve callback. In this // case the platform should get the pre-solve event, not the player. class Platform : public Sample { public: explicit Platform( SampleContext* context ) : Sample( context ) { if (m_context->restart == false) { m_context->camera.center = { 0.5f, 7.5f }; m_context->camera.zoom = 25.0f * 0.4f; } b2World_SetPreSolveCallback( m_worldId, PreSolveStatic, this ); // Ground { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Static Platform // This tests pre-solve with continuous collision { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_staticBody; bodyDef.position = { -6.0f, 6.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); // Need to turn this on to get the callback shapeDef.enablePreSolveEvents = true; b2Polygon box = b2MakeBox( 2.0f, 0.5f ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } // Moving Platform { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_kinematicBody; bodyDef.position = { 0.0f, 6.0f }; bodyDef.linearVelocity = { 2.0f, 0.0f }; m_movingPlatformId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); // Need to turn this on to get the callback shapeDef.enablePreSolveEvents = true; b2Polygon box = b2MakeBox( 3.0f, 0.5f ); b2CreatePolygonShape( m_movingPlatformId, &shapeDef, &box ); } // Player { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.motionLocks.angularZ = true; bodyDef.linearDamping = 0.5f; bodyDef.position = { 0.0f, 1.0f }; m_playerId = b2CreateBody( m_worldId, &bodyDef ); m_radius = 0.5f; b2Capsule capsule = { { 0.0f, 0.0f }, { 0.0f, 1.0f }, m_radius }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.1f; m_playerShapeId = b2CreateCapsuleShape( m_playerId, &shapeDef, &capsule ); } m_force = 25.0f; m_impulse = 25.0f; m_jumpDelay = 0.25f; m_jumping = false; } static bool PreSolveStatic( b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Vec2 point, b2Vec2 normal, void* context ) { Platform* self = static_cast( context ); return self->PreSolve( shapeIdA, shapeIdB, point, normal ); } // This callback must be thread-safe. It may be called multiple times simultaneously. // Notice how this method is constant and doesn't change any data. It also // does not try to access any values in the world that may be changing, such as contact data. bool PreSolve( b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Vec2 point, b2Vec2 normal ) const { assert( b2Shape_IsValid( shapeIdA ) ); assert( b2Shape_IsValid( shapeIdB ) ); float sign = 0.0f; if (B2_ID_EQUALS( shapeIdA, m_playerShapeId )) { sign = -1.0f; } else if (B2_ID_EQUALS( shapeIdB, m_playerShapeId )) { sign = 1.0f; } else { // not colliding with the player, enable contact return true; } if (sign * normal.y > 0.95f) { return true; } // normal points down, disable contact return false; } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 100.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "One-Sided Platform", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); ImGui::SliderFloat( "force", &m_force, 0.0f, 50.0f, "%.1f" ); ImGui::SliderFloat( "impulse", &m_impulse, 0.0f, 50.0f, "%.1f" ); ImGui::End(); } void Step() override { bool canJump = false; b2Vec2 velocity = b2Body_GetLinearVelocity( m_playerId ); if (m_jumpDelay == 0.0f && m_jumping == false && velocity.y < 0.01f) { int capacity = b2Body_GetContactCapacity( m_playerId ); capacity = b2MinInt( capacity, 4 ); b2ContactData contactData[4]; int count = b2Body_GetContactData( m_playerId, contactData, capacity ); for (int i = 0; i < count; ++i) { b2BodyId bodyIdA = b2Shape_GetBody( contactData[i].shapeIdA ); float sign = 0.0f; if (B2_ID_EQUALS( bodyIdA, m_playerId )) { // normal points from A to B sign = -1.0f; } else { sign = 1.0f; } if (sign * contactData[i].manifold.normal.y > 0.9f) { canJump = true; break; } } } // A kinematic body is moved by setting its velocity. This // ensure friction works correctly. b2Vec2 platformPosition = b2Body_GetPosition( m_movingPlatformId ); if (platformPosition.x < -15.0f) { b2Body_SetLinearVelocity( m_movingPlatformId, { 2.0f, 0.0f } ); } else if (platformPosition.x > 15.0f) { b2Body_SetLinearVelocity( m_movingPlatformId, { -2.0f, 0.0f } ); } if (glfwGetKey( m_context->window, GLFW_KEY_A ) == GLFW_PRESS) { b2Body_ApplyForceToCenter( m_playerId, { -m_force, 0.0f }, true ); } if (glfwGetKey( m_context->window, GLFW_KEY_D ) == GLFW_PRESS) { b2Body_ApplyForceToCenter( m_playerId, { m_force, 0.0f }, true ); } int keyState = glfwGetKey( m_context->window, GLFW_KEY_SPACE ); if (keyState == GLFW_PRESS) { if (canJump) { b2Body_ApplyLinearImpulseToCenter( m_playerId, { 0.0f, m_impulse }, true ); m_jumpDelay = 0.5f; m_jumping = true; } } else { m_jumping = false; } Sample::Step(); b2ContactData contactData = {}; int contactCount = b2Body_GetContactData( m_movingPlatformId, &contactData, 1 ); DrawTextLine( "Platform contact count = %d, point count = %d", contactCount, contactData.manifold.pointCount ); DrawTextLine( "Movement: A/D/Space" ); DrawTextLine( "Can jump = %s", canJump ? "true" : "false" ); if (m_context->hertz > 0.0f) { m_jumpDelay = b2MaxFloat( 0.0f, m_jumpDelay - 1.0f / m_context->hertz ); } } static Sample* Create( SampleContext* context ) { return new Platform( context ); } bool m_jumping; float m_radius; float m_force; float m_impulse; float m_jumpDelay; b2BodyId m_playerId; b2ShapeId m_playerShapeId; b2BodyId m_movingPlatformId; }; static int samplePlatformer = RegisterSample( "Events", "Platformer", Platform::Create ); // This shows how to process body events. class BodyMove : public Sample { public: enum { e_count = 50 }; explicit BodyMove( SampleContext* context ) : Sample( context ) { if (m_context->restart == false) { m_context->camera.center = { 2.0f, 8.0f }; m_context->camera.zoom = 25.0f * 0.55f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.1f; b2Polygon box = b2MakeOffsetBox( 12.0f, 0.1f, { -10.0f, -0.1f }, b2MakeRot( -0.15f * B2_PI ) ); b2CreatePolygonShape( groundId, &shapeDef, &box ); box = b2MakeOffsetBox( 12.0f, 0.1f, { 10.0f, -0.1f }, b2MakeRot( 0.15f * B2_PI ) ); b2CreatePolygonShape( groundId, &shapeDef, &box ); shapeDef.material.restitution = 0.8f; box = b2MakeOffsetBox( 0.1f, 10.0f, { 19.9f, 10.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); box = b2MakeOffsetBox( 0.1f, 10.0f, { -19.9f, 10.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); box = b2MakeOffsetBox( 20.0f, 0.1f, { 0.0f, 20.1f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } m_sleepCount = 0; m_count = 0; m_explosionPosition = { 0.0f, -5.0f }; m_explosionRadius = 10.0f; m_explosionMagnitude = 10.0f; } void CreateBodies() { b2Capsule capsule = { { -0.25f, 0.0f }, { 0.25f, 0.0f }, 0.25f }; b2Circle circle = { { 0.0f, 0.0f }, 0.35f }; b2Polygon square = b2MakeSquare( 0.35f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); float x = -5.0f, y = 10.0f; for (int i = 0; i < 10 && m_count < e_count; ++i) { bodyDef.position = { x, y }; bodyDef.isBullet = ( m_count % 12 == 0 ); bodyDef.userData = m_bodyIds + m_count; m_bodyIds[m_count] = b2CreateBody( m_worldId, &bodyDef ); m_sleeping[m_count] = false; int remainder = m_count % 4; if (remainder == 0) { b2CreateCapsuleShape( m_bodyIds[m_count], &shapeDef, &capsule ); } else if (remainder == 1) { b2CreateCircleShape( m_bodyIds[m_count], &shapeDef, &circle ); } else if (remainder == 2) { b2CreatePolygonShape( m_bodyIds[m_count], &shapeDef, &square ); } else { b2Polygon poly = RandomPolygon( 0.75f ); poly.radius = 0.1f; b2CreatePolygonShape( m_bodyIds[m_count], &shapeDef, &poly ); } m_count += 1; x += 1.0f; } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 100.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Body Move", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); if (ImGui::Button( "Explode" )) { b2ExplosionDef def = b2DefaultExplosionDef(); def.position = m_explosionPosition; def.radius = m_explosionRadius; def.falloff = 0.1f; def.impulsePerLength = m_explosionMagnitude; b2World_Explode( m_worldId, &def ); } ImGui::SliderFloat( "Magnitude", &m_explosionMagnitude, -20.0f, 20.0f, "%.1f" ); ImGui::End(); } void Step() override { if (m_context->pause == false && ( m_stepCount & 15 ) == 15 && m_count < e_count) { CreateBodies(); } Sample::Step(); // Process body events b2BodyEvents events = b2World_GetBodyEvents( m_worldId ); for (int i = 0; i < events.moveCount; ++i) { const b2BodyMoveEvent* event = events.moveEvents + i; if (event->userData == nullptr) { // The mouse joint body has no user data continue; } // draw the transform of every body that moved (not sleeping) DrawTransform( m_draw, event->transform, 1.0f ); b2Transform transform = b2Body_GetTransform( event->bodyId ); B2_ASSERT( transform.p.x == event->transform.p.x ); B2_ASSERT( transform.p.y == event->transform.p.y ); B2_ASSERT( transform.q.c == event->transform.q.c ); B2_ASSERT( transform.q.s == event->transform.q.s ); // this shows a somewhat contrived way to track body sleeping b2BodyId* bodyId = static_cast( event->userData ); ptrdiff_t diff = bodyId - m_bodyIds; bool* sleeping = m_sleeping + diff; if (event->fellAsleep) { *sleeping = true; m_sleepCount += 1; } else { if (*sleeping) { *sleeping = false; m_sleepCount -= 1; } } } DrawCircle( m_draw, m_explosionPosition, m_explosionRadius, b2_colorAzure ); DrawTextLine( "sleep count: %d", m_sleepCount ); } static Sample* Create( SampleContext* context ) { return new BodyMove( context ); } b2BodyId m_bodyIds[e_count] = {}; bool m_sleeping[e_count] = {}; int m_count; int m_sleepCount; b2Vec2 m_explosionPosition; float m_explosionRadius; float m_explosionMagnitude; }; static int sampleBodyMove = RegisterSample( "Events", "Body Move", BodyMove::Create ); class SensorTypes : public Sample { public: enum CollisionBits { GROUND = 0x00000001, SENSOR = 0x00000002, DEFAULT = 0x00000004, ALL_BITS = ( ~0u ) }; explicit SensorTypes( SampleContext* context ) : Sample( context ) { if (m_context->restart == false) { m_context->camera.center = { 0.0f, 3.0f }; m_context->camera.zoom = 4.5f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.name = "ground"; b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); // Enable sensor events, but filter them out as a test shapeDef.filter.categoryBits = GROUND; shapeDef.filter.maskBits = DEFAULT; shapeDef.enableSensorEvents = true; b2Segment groundSegment = { { -6.0f, 0.0f }, { 6.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &groundSegment ); groundSegment = { { -6.0f, 0.0f }, { -6.0f, 4.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &groundSegment ); groundSegment = { { 6.0f, 0.0f }, { 6.0f, 4.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &groundSegment ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.name = "static sensor"; bodyDef.type = b2_staticBody; bodyDef.position = { -3.0f, 0.8f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.filter.categoryBits = SENSOR; shapeDef.isSensor = true; shapeDef.enableSensorEvents = true; b2Polygon box = b2MakeSquare( 1.0f ); m_staticSensorId = b2CreatePolygonShape( bodyId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.name = "kinematic sensor"; bodyDef.type = b2_kinematicBody; bodyDef.position = { 0.0f, 0.0f }; bodyDef.linearVelocity = { 0.0f, 1.0f }; m_kinematicBodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.filter.categoryBits = SENSOR; shapeDef.isSensor = true; shapeDef.enableSensorEvents = true; b2Polygon box = b2MakeSquare( 1.0f ); m_kinematicSensorId = b2CreatePolygonShape( m_kinematicBodyId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.name = "dynamic sensor"; bodyDef.type = b2_dynamicBody; bodyDef.position = { 3.0f, 1.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.filter.categoryBits = SENSOR; shapeDef.isSensor = true; shapeDef.enableSensorEvents = true; b2Polygon box = b2MakeSquare( 1.0f ); m_dynamicSensorId = b2CreatePolygonShape( bodyId, &shapeDef, &box ); // Add some real collision so the dynamic body is valid shapeDef.filter.categoryBits = DEFAULT; shapeDef.isSensor = false; shapeDef.enableSensorEvents = false; box = b2MakeSquare( 0.8f ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.name = "ball_01"; bodyDef.position = { -5.0f, 1.0f }; bodyDef.type = b2_dynamicBody; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.filter.categoryBits = DEFAULT; shapeDef.filter.maskBits = GROUND | DEFAULT | SENSOR; shapeDef.enableSensorEvents = true; b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; b2CreateCircleShape( bodyId, &shapeDef, &circle ); } } void PrintOverlaps( b2ShapeId sensorShapeId, const char* prefix ) { char buffer[256] = {}; // Determine the necessary capacity int capacity = b2Shape_GetSensorCapacity( sensorShapeId ); m_visitorIds.resize( capacity ); // Get all overlaps and record the actual count int count = b2Shape_GetSensorData( sensorShapeId, m_visitorIds.data(), capacity ); m_visitorIds.resize( count ); int start = snprintf( buffer, sizeof( buffer ), "%s: ", prefix ); for (int i = 0; i < count && start < sizeof( buffer ); ++i) { b2ShapeId visitorId = m_visitorIds[i]; if (b2Shape_IsValid( visitorId ) == false) { continue; } b2BodyId bodyId = b2Shape_GetBody( visitorId ); const char* name = b2Body_GetName( bodyId ); if (name == nullptr) { continue; } // todo fix this start += snprintf( buffer + start, sizeof( buffer ) - start, "%s, ", name ); } DrawTextLine( buffer ); } void Step() override { b2Vec2 position = b2Body_GetPosition( m_kinematicBodyId ); if (position.y < 0.0f) { b2Body_SetLinearVelocity( m_kinematicBodyId, { 0.0f, 1.0f } ); // b2Body_SetKinematicTarget( m_kinematicBodyId ); } else if (position.y > 3.0f) { b2Body_SetLinearVelocity( m_kinematicBodyId, { 0.0f, -1.0f } ); } Sample::Step(); PrintOverlaps( m_staticSensorId, "static" ); PrintOverlaps( m_kinematicSensorId, "kinematic" ); PrintOverlaps( m_dynamicSensorId, "dynamic" ); b2Vec2 origin = { 5.0f, 1.0f }; b2Vec2 translation = { -10.0f, 0.0f }; b2RayResult result = b2World_CastRayClosest( m_worldId, origin, translation, b2DefaultQueryFilter() ); DrawLine( m_draw, origin, origin + translation, b2_colorDimGray ); if (result.hit) { DrawPoint( m_draw, result.point, 10.0f, b2_colorCyan ); } } static Sample* Create( SampleContext* context ) { return new SensorTypes( context ); } b2ShapeId m_staticSensorId; b2ShapeId m_kinematicSensorId; b2ShapeId m_dynamicSensorId; b2BodyId m_kinematicBodyId; std::vector m_visitorIds; }; static int sampleSensorTypes = RegisterSample( "Events", "Sensor Types", SensorTypes::Create ); // This sample shows how to break joints when the internal reaction force becomes large. Instead of polling, this uses events. class JointEvent : public Sample { public: enum { e_count = 6 }; explicit JointEvent( SampleContext* context ) : Sample( context ) { if (m_context->restart == false) { m_context->camera.center = { 0.0f, 8.0f }; m_context->camera.zoom = 25.0f * 0.7f; } b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -40.0f, 0.0f }, { 40.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); for (int i = 0; i < e_count; ++i) { m_jointIds[i] = b2_nullJointId; } b2Vec2 position = { -12.5f, 10.0f }; bodyDef.type = b2_dynamicBody; bodyDef.enableSleep = false; b2Polygon box = b2MakeBox( 1.0f, 1.0f ); int index = 0; float forceThreshold = 20000.0f; float torqueThreshold = 10000.0f; // distance joint { assert( index < e_count ); bodyDef.position = position; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); float length = 2.0f; b2Vec2 pivot1 = { position.x, position.y + 1.0f + length }; b2Vec2 pivot2 = { position.x, position.y + 1.0f }; b2DistanceJointDef jointDef = b2DefaultDistanceJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot1 ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot2 ); jointDef.length = length; jointDef.base.forceThreshold = forceThreshold; jointDef.base.torqueThreshold = torqueThreshold; jointDef.base.collideConnected = true; jointDef.base.userData = (void*)(intptr_t)index; m_jointIds[index] = b2CreateDistanceJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; // motor joint { assert( index < e_count ); bodyDef.position = position; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2MotorJointDef jointDef = b2DefaultMotorJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = position; jointDef.maxVelocityForce = 1000.0f; jointDef.maxVelocityTorque = 20.0f; jointDef.base.forceThreshold = forceThreshold; jointDef.base.torqueThreshold = torqueThreshold; jointDef.base.collideConnected = true; jointDef.base.userData = (void*)(intptr_t)index; m_jointIds[index] = b2CreateMotorJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; // prismatic joint { assert( index < e_count ); bodyDef.position = position; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2Vec2 pivot = { position.x - 1.0f, position.y }; b2PrismaticJointDef jointDef = b2DefaultPrismaticJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.base.forceThreshold = forceThreshold; jointDef.base.torqueThreshold = torqueThreshold; jointDef.base.collideConnected = true; jointDef.base.userData = (void*)(intptr_t)index; m_jointIds[index] = b2CreatePrismaticJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; // revolute joint { assert( index < e_count ); bodyDef.position = position; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2Vec2 pivot = { position.x - 1.0f, position.y }; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.base.forceThreshold = forceThreshold; jointDef.base.torqueThreshold = torqueThreshold; jointDef.base.collideConnected = true; jointDef.base.userData = (void*)(intptr_t)index; m_jointIds[index] = b2CreateRevoluteJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; // weld joint { assert( index < e_count ); bodyDef.position = position; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2Vec2 pivot = { position.x - 1.0f, position.y }; b2WeldJointDef jointDef = b2DefaultWeldJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.angularHertz = 2.0f; jointDef.angularDampingRatio = 0.5f; jointDef.base.forceThreshold = forceThreshold; jointDef.base.torqueThreshold = torqueThreshold; jointDef.base.collideConnected = true; jointDef.base.userData = (void*)(intptr_t)index; m_jointIds[index] = b2CreateWeldJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; // wheel joint { assert( index < e_count ); bodyDef.position = position; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2Vec2 pivot = { position.x - 1.0f, position.y }; b2WheelJointDef jointDef = b2DefaultWheelJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.hertz = 1.0f; jointDef.dampingRatio = 0.7f; jointDef.lowerTranslation = -1.0f; jointDef.upperTranslation = 1.0f; jointDef.enableLimit = true; jointDef.enableMotor = true; jointDef.maxMotorTorque = 10.0f; jointDef.motorSpeed = 1.0f; jointDef.base.forceThreshold = forceThreshold; jointDef.base.torqueThreshold = torqueThreshold; jointDef.base.collideConnected = true; jointDef.base.userData = (void*)(intptr_t)index; m_jointIds[index] = b2CreateWheelJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; } void Step() override { Sample::Step(); // Process joint events b2JointEvents events = b2World_GetJointEvents( m_worldId ); for (int i = 0; i < events.count; ++i) { // Destroy the joint if it is still valid const b2JointEvent* event = events.jointEvents + i; if (b2Joint_IsValid( event->jointId )) { int index = (int)(intptr_t)event->userData; assert( 0 <= index && index < e_count ); b2DestroyJoint( event->jointId, true ); m_jointIds[index] = b2_nullJointId; } } } static Sample* Create( SampleContext* context ) { return new JointEvent( context ); } b2JointId m_jointIds[e_count]; }; static int sampleJointEvent = RegisterSample( "Events", "Joint", JointEvent::Create ); class PersistentContact : public Sample { public: explicit PersistentContact( SampleContext* context ) : Sample( context ) { if (m_context->restart == false) { m_context->camera.center = { 0.0f, 6.0f }; m_context->camera.zoom = 7.5f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2Vec2 points[22]; float x = 10.0f; for (int i = 0; i < 20; ++i) { points[i] = { x, 0.0f }; x -= 1.0f; } points[20] = { -9.0f, 10.0f }; points[21] = { 10.0f, 10.0f }; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = 22; chainDef.isLoop = true; b2CreateChain( groundId, &chainDef ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -8.0f, 1.0f }; bodyDef.linearVelocity = { 2.0f, 0.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.enableContactEvents = true; b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; b2CreateCircleShape( bodyId, &shapeDef, &circle ); } m_contactId = b2_nullContactId; } void Step() override { Sample::Step(); b2ContactEvents events = b2World_GetContactEvents( m_worldId ); for (int i = 0; i < events.beginCount && i < 1; ++i) { b2ContactBeginTouchEvent event = events.beginEvents[i]; m_contactId = events.beginEvents[i].contactId; } for (int i = 0; i < events.endCount; ++i) { if (B2_ID_EQUALS( m_contactId, events.endEvents[i].contactId )) { m_contactId = b2_nullContactId; break; } } if (B2_IS_NON_NULL( m_contactId ) && b2Contact_IsValid( m_contactId )) { b2ContactData data = b2Contact_GetData( m_contactId ); for (int i = 0; i < data.manifold.pointCount; ++i) { const b2ManifoldPoint* manifoldPoint = data.manifold.points + i; b2Vec2 p1 = manifoldPoint->point; b2Vec2 p2 = p1 + manifoldPoint->totalNormalImpulse * data.manifold.normal; DrawLine( m_draw, p1, p2, b2_colorCrimson ); DrawPoint( m_draw, p1, 6.0f, b2_colorCrimson ); DrawWorldString( m_draw, m_camera, p1, b2_colorWhite, "%.2f", manifoldPoint->totalNormalImpulse ); } } else { m_contactId = b2_nullContactId; } } static Sample* Create( SampleContext* context ) { return new PersistentContact( context ); } b2ContactId m_contactId; }; static int samplePersistentContact = RegisterSample( "Events", "Persistent Contact", PersistentContact::Create ); class SensorHits : public Sample { public: explicit SensorHits( SampleContext* context ) : Sample( context ) , m_transforms{} { if (m_context->restart == false) { m_context->camera.center = { 0.0f, 5.0f }; m_context->camera.zoom = 7.5f; } b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.name = "ground"; groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment groundSegment = { { -10.0f, 0.0f }, { 10.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &groundSegment ); groundSegment = { { 10.0f, 0.0f }, { 10.0f, 10.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &groundSegment ); } // Static sensor { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.name = "static sensor"; bodyDef.position = { -4.0f, 1.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.isSensor = true; shapeDef.enableSensorEvents = true; b2Segment segment = { { 0.0f, 0.0f }, { 0.0f, 10.0f } }; m_staticSensorId = b2CreateSegmentShape( bodyId, &shapeDef, &segment ); } // Kinematic sensor { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.name = "kinematic sensor"; bodyDef.type = b2_kinematicBody; bodyDef.position = { 0.0f, 1.0f }; bodyDef.linearVelocity = { 0.5f, 0.0f }; m_kinematicBodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.isSensor = true; shapeDef.enableSensorEvents = true; b2Segment segment = { { 0.0f, 0.0f }, { 0.0f, 10.0f } }; m_kinematicSensorId = b2CreateSegmentShape( m_kinematicBodyId, &shapeDef, &segment ); } // Dynamic sensor { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.name = "dynamic sensor"; bodyDef.type = b2_dynamicBody; bodyDef.position = { 4.0f, 1.0f }; m_dynamicBodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.isSensor = true; shapeDef.enableSensorEvents = true; b2Capsule capsule = { { 0.0f, 1.0f }, { 0.0f, 9.0f }, 0.1f }; m_dynamicSensorId = b2CreateCapsuleShape( m_dynamicBodyId, &shapeDef, &capsule ); b2Vec2 pivot = bodyDef.position + b2Vec2{ 0.0f, 6.0f }; b2Vec2 axis = { 1.0f, 0.0f }; b2PrismaticJointDef jointDef = b2DefaultPrismaticJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = m_dynamicBodyId; jointDef.base.localFrameA.q = b2MakeRotFromUnitVector( axis ); jointDef.base.localFrameA.p = b2Body_GetLocalPoint( groundId, pivot ); jointDef.base.localFrameB.q = b2MakeRotFromUnitVector( axis ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( m_dynamicBodyId, pivot ); jointDef.enableMotor = true; jointDef.maxMotorForce = 1000.0f; jointDef.motorSpeed = 0.5f; m_jointId = b2CreatePrismaticJoint( m_worldId, &jointDef ); } m_beginCount = 0; m_endCount = 0; m_bodyId = {}; m_shapeId = {}; m_transformCount = 0; m_isBullet = true; Launch(); } void Launch() { if (B2_IS_NON_NULL( m_bodyId )) { b2DestroyBody( m_bodyId ); } m_transformCount = 0; m_beginCount = 0; m_endCount = 0; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -26.7f, 6.0f }; float speed = RandomFloatRange( 200.0f, 300.0f ); bodyDef.linearVelocity = { speed, 0.0f }; bodyDef.isBullet = m_isBullet; m_bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.enableSensorEvents = true; shapeDef.material.friction = 0.8f; shapeDef.material.rollingResistance = 0.01f; b2Circle circle = { { 0.0f, 0.0f }, 0.25f }; m_shapeId = b2CreateCircleShape( m_bodyId, &shapeDef, &circle ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 120.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 120.0f, height ) ); ImGui::Begin( "Sensor Hit", nullptr, ImGuiWindowFlags_NoResize ); ImGui::Checkbox( "Bullet", &m_isBullet ); if (ImGui::Button( "Launch" ) || glfwGetKey( m_context->window, GLFW_KEY_B ) == GLFW_PRESS) { Launch(); } ImGui::End(); } void CollectTransforms( b2ShapeId sensorShapeId ) { constexpr int capacity = 5; b2ShapeId visitorIds[capacity]; int count = b2Shape_GetSensorData( sensorShapeId, visitorIds, capacity ); for (int i = 0; i < count && m_transformCount < m_transformCapacity; ++i) { b2BodyId sensorBodyId = b2Shape_GetBody( sensorShapeId ); m_transforms[m_transformCount] = b2Body_GetTransform( sensorBodyId ); m_transformCount += 1; } } void Step() override { b2Vec2 p = b2Body_GetPosition( m_kinematicBodyId ); if (p.x > 1.0f) { b2Body_SetLinearVelocity( m_kinematicBodyId, { -0.5f, 0.0f } ); } else if (p.x < -1.0f) { b2Body_SetLinearVelocity( m_kinematicBodyId, { 0.5f, 0.0f } ); } float x = b2PrismaticJoint_GetTranslation( m_jointId ); if (x > 1.0f) { b2PrismaticJoint_SetMotorSpeed( m_jointId, -0.5f ); } else if (x < -1.0f) { b2PrismaticJoint_SetMotorSpeed( m_jointId, 0.5f ); } Sample::Step(); for (int i = 0; i < m_transformCount; ++i) { DrawTransform( m_draw, m_transforms[i], 1.0f ); } b2SensorEvents sensorEvents = b2World_GetSensorEvents( m_worldId ); m_beginCount += sensorEvents.beginCount; m_endCount += sensorEvents.endCount; for (int i = 0; i < sensorEvents.beginCount; ++i) { const b2SensorBeginTouchEvent* event = sensorEvents.beginEvents + i; if (b2Shape_IsValid( event->sensorShapeId ) == true) { CollectTransforms( event->sensorShapeId ); } } DrawTextLine( "begin touch count = %d", m_beginCount ); DrawTextLine( "end touch count = %d", m_endCount ); } static Sample* Create( SampleContext* context ) { return new SensorHits( context ); } b2ShapeId m_staticSensorId; b2ShapeId m_kinematicSensorId; b2ShapeId m_dynamicSensorId; b2BodyId m_kinematicBodyId; b2BodyId m_dynamicBodyId; b2JointId m_jointId; b2BodyId m_bodyId; b2ShapeId m_shapeId; static constexpr int m_transformCapacity = 20; int m_transformCount; b2Transform m_transforms[m_transformCapacity]; bool m_isBullet; int m_beginCount; int m_endCount; }; static int sampleSensorHits = RegisterSample( "Events", "Sensor Hits", SensorHits::Create ); // This shows how to create a projectile that explodes on impact class ProjectileEvent : public Sample { public: explicit ProjectileEvent( SampleContext* context ) : Sample( context ) { if (m_context->restart == false) { m_context->camera.center = { -7.0f, 9.0f }; m_context->camera.zoom = 14.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, 0.0f }; b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.enableSensorEvents = true; b2Segment segment = { { 10.0f, 0.0f }, { 10.0f, 20.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); segment = { { -30.0f, 0.0f }, { 30.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } m_projectileId = {}; m_projectileShapeId = {}; m_dragging = false; m_point1 = b2Vec2_zero; m_point2 = b2Vec2_zero; b2Polygon box = b2MakeRoundedBox( 0.45f, 0.45f, 0.05f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.enableSensorEvents = true; float offset = 0.01f; float x = 8.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; for (int i = 0; i < 8; ++i) { float shift = ( i % 2 == 0 ? -offset : offset ); bodyDef.position = { x + shift, 0.5f + 1.0f * i }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } void FireProjectile() { if (B2_IS_NON_NULL( m_projectileId )) { b2DestroyBody( m_projectileId ); } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = m_point1; bodyDef.linearVelocity = 4.0f * ( m_point2 - m_point1 ); bodyDef.isBullet = true; m_projectileId = b2CreateBody( m_worldId, &bodyDef ); b2Circle circle = { { 0.0f, 0.0f }, 0.25f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.enableContactEvents = true; m_projectileShapeId = b2CreateCircleShape( m_projectileId, &shapeDef, &circle ); } void MouseDown( b2Vec2 p, int button, int mods ) override { if (button == GLFW_MOUSE_BUTTON_1) { if (mods == GLFW_MOD_CONTROL) { m_dragging = true; m_point1 = p; } } } void MouseUp( b2Vec2, int button ) override { if (button == GLFW_MOUSE_BUTTON_1) { if (m_dragging) { m_dragging = false; FireProjectile(); } } } void MouseMove( b2Vec2 p ) override { if (m_dragging) { m_point2 = p; } } void Step() override { DrawTextLine( "Use Ctrl + Left Mouse to drag and shoot a projectile" ); Sample::Step(); if (m_dragging) { DrawLine( m_draw, m_point1, m_point2, b2_colorWhite ); DrawPoint( m_draw, m_point1, 5.0f, b2_colorGreen ); DrawPoint( m_draw, m_point2, 5.0f, b2_colorRed ); } b2ContactEvents contactEvents = b2World_GetContactEvents( m_worldId ); for (int i = 0; i < contactEvents.beginCount; ++i) { const b2ContactBeginTouchEvent* event = contactEvents.beginEvents + i; if (B2_ID_EQUALS( event->shapeIdA, m_projectileShapeId ) || B2_ID_EQUALS( event->shapeIdB, m_projectileShapeId )) { if (b2Contact_IsValid( event->contactId )) { b2ContactData data = b2Contact_GetData( event->contactId ); if (data.manifold.pointCount > 0) { b2ExplosionDef explosionDef = b2DefaultExplosionDef(); explosionDef.position = data.manifold.points[0].point; explosionDef.radius = 1.0f; explosionDef.impulsePerLength = 20.0f; b2World_Explode( m_worldId, &explosionDef ); b2DestroyBody( m_projectileId ); m_projectileId = b2_nullBodyId; } } break; } } } static Sample* Create( SampleContext* context ) { return new ProjectileEvent( context ); } b2BodyId m_projectileId; b2ShapeId m_projectileShapeId; b2Vec2 m_point1; b2Vec2 m_point2; bool m_dragging; }; static int sampleProjectileEvent = RegisterSample( "Events", "Projectile Event", ProjectileEvent::Create ); class CircleImpulse : public Sample { public: struct Event { float impulse; float totalImpulse; float speed; }; explicit CircleImpulse( SampleContext* context ) : Sample( context ) { if (m_context->restart == false) { m_context->camera.center = { 0.0f, 2.7f }; m_context->camera.zoom = 3.4f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -10.0f, 0.0f }, { 10.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } m_gravity = 10.0f; m_restitution = 0.25f; m_useGravity = false; m_useRestitution = false; m_mass = 1.0f; m_bodyId = b2_nullBodyId; Spawn(); } void Spawn() { if (B2_IS_NON_NULL( m_bodyId )) { b2DestroyBody( m_bodyId ); m_bodyId = b2_nullBodyId; } m_events.clear(); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.gravityScale = m_useGravity ? 1.0f : 0.0f; bodyDef.linearVelocity.y = -25.0f; bodyDef.position.y = 5.5f; b2Circle circle = {}; circle.radius = 0.25f; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.enableHitEvents = true; shapeDef.material.friction = 0.0f; shapeDef.material.restitution = m_useRestitution ? m_restitution : 0.0f; m_bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreateCircleShape( m_bodyId, &shapeDef, &circle ); // Override mass b2MassData massData = b2Body_GetMassData( m_bodyId ); float ratio = m_mass / massData.mass; massData.mass = m_mass; massData.rotationalInertia *= ratio; b2Body_SetMassData( m_bodyId, massData ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 6.0f * fontSize; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 10.0f * fontSize, height ) ); ImGui::Begin( "Circle Impulse", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); if (ImGui::Checkbox( "gravity", &m_useGravity )) { Spawn(); } if (ImGui::Checkbox( "restitution", &m_useRestitution )) { Spawn(); } ImGui::End(); } void Step() override { Sample::Step(); b2ContactEvents events = b2World_GetContactEvents( m_worldId ); for (int i = 0; i < events.hitCount; ++i) { b2ContactHitEvent* event = events.hitEvents + i; DrawPoint( m_draw, event->point, 10.0f, b2_colorWhite ); b2ContactData data = b2Contact_GetData( event->contactId ); Event e = {}; e.speed = event->approachSpeed; if (data.manifold.pointCount > 0) { e.impulse = data.manifold.points[0].normalImpulse; e.totalImpulse = data.manifold.points[0].totalNormalImpulse; } m_events.push_back( e ); } DrawTextLine( "mass = %g, gravity = %g, restitution = %g", m_mass, m_useGravity ? 10.0f : 0.0f, m_useRestitution ? m_restitution : 0.0f ); int eventCount = (int)m_events.size(); for (int i = 0; i < eventCount; ++i) { const Event& e = m_events[i]; DrawTextLine( "hit speed = %g, hit momentum = %g, final impulse = %g, total impulse = %g", e.speed, m_mass * e.speed, e.impulse, e.totalImpulse ); } } static Sample* Create( SampleContext* context ) { return new CircleImpulse( context ); } float m_mass; std::vector m_events; b2BodyId m_bodyId; float m_gravity; float m_restitution; bool m_useGravity; bool m_useRestitution; }; static int sampleCircleImpulse = RegisterSample( "Stacking", "Circle Impulse", CircleImpulse::Create ); ================================================ FILE: samples/sample_geometry.cpp ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "draw.h" #include "random.h" #include "sample.h" #include "box2d/math_functions.h" #include class ConvexHull : public Sample { public: enum { e_count = B2_MAX_POLYGON_VERTICES }; explicit ConvexHull( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.5f, 0.0f }; m_context->camera.zoom = 25.0f * 0.3f; } m_generation = 0; m_auto = false; m_bulk = false; Generate(); } void Generate() { #if 0 m_points[0] = { 5.65314484f, 0.204832315f }; m_points[1] = {-5.65314484f, -0.204832315f }; m_points[2] = {2.34463644f, 1.15731204f }; m_points[3] = {0.0508846045f, 3.23230696f }; m_points[4] = {-5.65314484f, -0.204832315f }; m_points[5] = {-5.65314484f, -0.204832315f }; m_points[6] = {3.73758054f, -1.11098099f }; m_points[7] = {1.33504069f, -4.43795443f }; m_count = e_count; #elif 0 m_points[0] = { -0.328125, 0.179688 }; m_points[1] = { -0.203125, 0.304688 }; m_points[2] = { 0.171875, 0.304688 }; m_points[3] = { 0.359375, 0.117188 }; m_points[4] = { 0.359375, -0.195313 }; m_points[5] = { 0.234375, -0.320313 }; m_points[6] = { -0.265625, -0.257813 }; m_points[7] = { -0.328125, -0.132813 }; b2Hull hull = b2ComputeHull( m_points, 8 ); bool valid = b2ValidateHull( &hull ); if ( valid == false ) { assert( valid ); } m_count = e_count; #else float angle = B2_PI * RandomFloat(); b2Rot r = b2MakeRot( angle ); b2Vec2 lowerBound = { -4.0f, -4.0f }; b2Vec2 upperBound = { 4.0f, 4.0f }; for ( int i = 0; i < e_count; ++i ) { float x = 10.0f * RandomFloat(); float y = 10.0f * RandomFloat(); // Clamp onto a square to help create collinearities. // This will stress the convex hull algorithm. b2Vec2 v = b2Clamp( { x, y }, lowerBound, upperBound ); m_points[i] = b2RotateVector( r, v ); } m_count = e_count; #endif m_generation += 1; } void Keyboard( int key ) override { switch ( key ) { case GLFW_KEY_A: m_auto = !m_auto; break; case GLFW_KEY_B: m_bulk = !m_bulk; break; case GLFW_KEY_G: Generate(); break; default: break; } } void Step() override { Sample::Step(); DrawTextLine( "Options: generate(g), auto(a), bulk(b)" ); b2Hull hull; bool valid = false; float milliseconds = 0.0f; if ( m_bulk ) { #if 1 // defect hunting for ( int i = 0; i < 10000; ++i ) { Generate(); hull = b2ComputeHull( m_points, m_count ); if ( hull.count == 0 ) { // m_bulk = false; // break; continue; } valid = b2ValidateHull( &hull ); if ( valid == false || m_bulk == false ) { m_bulk = false; break; } } #else // performance Generate(); b2Timer timer; for ( int i = 0; i < 1000000; ++i ) { hull = b2ComputeHull( m_points, m_count ); } valid = hull.count > 0; milliseconds = timer.GetMilliseconds(); #endif } else { if ( m_auto ) { Generate(); } hull = b2ComputeHull( m_points, m_count ); if ( hull.count > 0 ) { valid = b2ValidateHull( &hull ); if ( valid == false ) { m_auto = false; } } } if ( valid == false ) { DrawTextLine( "generation = %d, FAILED", m_generation ); } else { DrawTextLine( "generation = %d, count = %d", m_generation, hull.count ); } if ( milliseconds > 0.0f ) { DrawTextLine( "milliseconds = %g", milliseconds ); } DrawPolygon( m_draw, hull.points, hull.count, b2_colorGray ); for ( int32_t i = 0; i < m_count; ++i ) { DrawPoint( m_draw, m_points[i], 5.0f, b2_colorBlue ); DrawWorldString( m_draw, m_camera, b2Add( m_points[i], { 0.1f, 0.1f } ), b2_colorWhite, "%d", i ); } for ( int32_t i = 0; i < hull.count; ++i ) { DrawPoint( m_draw, hull.points[i], 6.0f, b2_colorGreen ); } } static Sample* Create( SampleContext* context ) { return new ConvexHull( context ); } b2Vec2 m_points[B2_MAX_POLYGON_VERTICES]; int32_t m_count; int32_t m_generation; bool m_auto; bool m_bulk; }; static int sampleIndex = RegisterSample( "Geometry", "Convex Hull", ConvexHull::Create ); ================================================ FILE: samples/sample_issues.cpp ================================================ #include "GLFW/glfw3.h" #include "imgui.h" #include "sample.h" #include "box2d/box2d.h" struct PhysicsHitQueryResult2D { b2ShapeId shapeId = b2_nullShapeId; b2Vec2 point = b2Vec2_zero; b2Vec2 normal = b2Vec2_zero; b2Vec2 endPos = b2Vec2_zero; float fraction = 0.0f; bool startPenetrating = false; bool blockingHit = false; }; struct CastContext_Single { b2Vec2 startPos; b2Vec2 translation; PhysicsHitQueryResult2D result; bool hit = false; }; static float b2CastResult_Closest( b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* c ) { CastContext_Single* context = static_cast( c ); if ( b2Dot( context->translation, normal ) >= 0.0f ) return -1.0f; context->result.shapeId = shapeId; context->result.point = point; context->result.normal = normal; context->result.endPos = context->startPos + context->translation * fraction; context->result.fraction = fraction; context->result.blockingHit = true; context->hit = true; return fraction; } static b2ShapeProxy TransformShapeProxy( const b2Transform& t, const b2ShapeProxy& proxy ) { b2ShapeProxy ret; ret.count = proxy.count; ret.radius = proxy.radius; for ( int i = 0; i < proxy.count; ++i ) { ret.points[i] = b2TransformPoint( t, proxy.points[i] ); } return ret; } // This showed a problem with shape casts hitting the back-side of a chain shape class ShapeCastChain : public Sample { public: explicit ShapeCastChain( SampleContext* context ) : Sample( context ) { // World Body & Shape b2BodyDef worldBodyDef = b2DefaultBodyDef(); const b2BodyId groundId = b2CreateBody( m_worldId, &worldBodyDef ); b2Vec2 points[4] = { { 1.0f, 0.0f }, { -1.0f, 0.0f }, { -1.0f, -1.0f }, { 1.0f, -1.0f } }; b2ChainDef worldChainDef = b2DefaultChainDef(); worldChainDef.userData = nullptr; worldChainDef.points = points; worldChainDef.count = 4; worldChainDef.filter.categoryBits = 0x1; worldChainDef.filter.maskBits = 0x1; worldChainDef.filter.groupIndex = 0; worldChainDef.isLoop = true; worldChainDef.enableSensorEvents = false; b2CreateChain( groundId, &worldChainDef ); // "Character" Body & Shape b2BodyDef characterBodyDef = b2DefaultBodyDef(); characterBodyDef.position = { 0.0f, 0.103f }; characterBodyDef.rotation = b2MakeRot( 0.0f ); characterBodyDef.linearDamping = 0.0f; characterBodyDef.angularDamping = 0.0f; characterBodyDef.gravityScale = 1.0f; characterBodyDef.enableSleep = true; characterBodyDef.isAwake = false; characterBodyDef.motionLocks.angularZ = true; characterBodyDef.isEnabled = true; characterBodyDef.userData = nullptr; characterBodyDef.type = b2_kinematicBody; characterBodyId_ = b2CreateBody( m_worldId, &characterBodyDef ); b2ShapeDef characterShapeDef = b2DefaultShapeDef(); characterShapeDef.userData = nullptr; characterShapeDef.filter.categoryBits = 0x1; characterShapeDef.filter.maskBits = 0x1; characterShapeDef.filter.groupIndex = 0; characterShapeDef.isSensor = false; characterShapeDef.enableSensorEvents = false; characterShapeDef.enableContactEvents = false; characterShapeDef.enableHitEvents = false; characterShapeDef.enablePreSolveEvents = false; characterShapeDef.invokeContactCreation = false; characterShapeDef.updateBodyMass = false; characterBox_ = b2MakeBox( 0.1f, 0.1f ); b2CreatePolygonShape( characterBodyId_, &characterShapeDef, &characterBox_ ); context->camera.center = b2Vec2_zero; } void Step() override { const float timeStep = m_context->hertz > 0.0f ? 1.0f / m_context->hertz : 0.0f; bool noXInput = true; if ( glfwGetKey( m_context->window, GLFW_KEY_A ) ) { characterVelocity_.x -= timeStep * 5.0f; noXInput = false; } if ( glfwGetKey( m_context->window, GLFW_KEY_D ) ) { characterVelocity_.x += timeStep * 5.0f; noXInput = false; } bool noYInput = true; if ( glfwGetKey( m_context->window, GLFW_KEY_S ) ) { characterVelocity_.y -= timeStep * 5.0f; noYInput = false; } if ( glfwGetKey( m_context->window, GLFW_KEY_W ) ) { characterVelocity_.y += timeStep * 5.0f; noYInput = false; } if ( noXInput ) { if ( b2AbsFloat( characterVelocity_.x ) > 0.01f ) { const float decel = characterVelocity_.x > 0.0f ? 5.0f : -5.0f; if ( b2AbsFloat( decel ) < characterVelocity_.x ) { characterVelocity_.x -= decel; } else { characterVelocity_.x = 0.0f; } } else { characterVelocity_.x = 0.0f; } } if ( noYInput ) { if ( b2AbsFloat( characterVelocity_.y ) > 0.01f ) { const float decel = characterVelocity_.y > 0.0f ? 5.0f : -5.0f; if ( b2AbsFloat( decel ) < characterVelocity_.y ) { characterVelocity_.y -= decel; } else { characterVelocity_.y = 0.0f; } } else { characterVelocity_.y = 0.0f; } } b2Vec2 characterPos = b2Body_GetPosition( characterBodyId_ ); b2Vec2 newCharacterPos = characterPos; newCharacterPos.x += characterVelocity_.x * timeStep; newCharacterPos.y += characterVelocity_.y * timeStep; b2Body_SetTransform( characterBodyId_, newCharacterPos, b2Rot_identity ); PhysicsHitQueryResult2D hitResult; const b2ShapeProxy shapeProxy = b2MakeProxy( characterBox_.vertices, characterBox_.count, characterBox_.radius ); if ( ShapeCastSingle( hitResult, characterPos, newCharacterPos, 0.0f, shapeProxy ) ) { hitPos = hitResult.point; hitNormal = hitResult.normal; } DrawLine( m_draw, hitPos, { hitPos.x + hitNormal.x, hitPos.y + hitNormal.y }, b2_colorRed ); Sample::Step(); } bool ShapeCastSingle( PhysicsHitQueryResult2D& outResult, b2Vec2 start, b2Vec2 end, float rotation, const b2ShapeProxy& shape ) const { const b2Transform transform = { start, b2MakeRot( rotation ) }; const b2ShapeProxy transformedShape = TransformShapeProxy( transform, shape ); const b2Vec2 translation = { end.x - start.x, end.y - start.y }; const b2QueryFilter filter = { 0x1, 0x1 }; CastContext_Single context; context.startPos = start; context.translation = { translation.x, translation.y }; b2World_CastShape( m_worldId, &transformedShape, translation, filter, &b2CastResult_Closest, &context ); if ( context.hit ) { outResult = context.result; return true; } return false; } static Sample* Create( SampleContext* context ) { return new ShapeCastChain( context ); } private: b2BodyId characterBodyId_ = b2_nullBodyId; b2Polygon characterBox_; b2Vec2 characterVelocity_ = b2Vec2_zero; b2Vec2 hitPos = b2Vec2_zero; b2Vec2 hitNormal = b2Vec2_zero; }; static int sampleShapeCastChain = RegisterSample( "Issues", "Shape Cast Chain", ShapeCastChain::Create ); class BadSteiner : public Sample { public: explicit BadSteiner( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 1.75f }; m_context->camera.zoom = 2.5f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -100.0f, 0.0f }, { 100.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -48.0f, 62.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Vec2 points[3] = { { 48.7599983f, -60.5699997f }, { 48.7400017f, -60.5400009f }, { 48.6800003f, -60.5600014f }, }; b2Hull hull = b2ComputeHull( points, 3 ); b2Polygon poly = b2MakePolygon( &hull, 0.0f ); b2CreatePolygonShape( bodyId, &shapeDef, &poly ); } } static Sample* Create( SampleContext* context ) { return new BadSteiner( context ); } }; static int sampleBadSteiner = RegisterSample( "Issues", "Bad Steiner", BadSteiner::Create ); class DisableCrash : public Sample { public: explicit DisableCrash( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.8f, 6.4f }; m_context->camera.zoom = 25.0f * 0.4f; } m_isEnabled = true; // Define attachment { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -2.0f, 3.0f }; bodyDef.isEnabled = m_isEnabled; m_attachmentId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 0.5f, 2.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( m_attachmentId, &shapeDef, &box ); } // Define platform { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { -4.0f, 5.0f }; m_platformId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeOffsetBox( 0.5f, 4.0f, { 4.0f, 0.0f }, b2MakeRot( 0.5f * B2_PI ) ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( m_platformId, &shapeDef, &box ); b2RevoluteJointDef revoluteDef = b2DefaultRevoluteJointDef(); b2Vec2 pivot = { -2.0f, 5.0f }; revoluteDef.base.bodyIdA = m_attachmentId; revoluteDef.base.bodyIdB = m_platformId; revoluteDef.base.localFrameA.p = b2Body_GetLocalPoint( m_attachmentId, pivot ); revoluteDef.base.localFrameB.p = b2Body_GetLocalPoint( m_platformId, pivot ); revoluteDef.maxMotorTorque = 50.0f; revoluteDef.enableMotor = true; b2CreateRevoluteJoint( m_worldId, &revoluteDef ); } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 11.0f * fontSize; float winX = 0.5f * fontSize; float winY = m_camera->height - height - 2.0f * fontSize; ImGui::SetNextWindowPos( { winX, winY }, ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 9.0f * fontSize, height ) ); ImGui::Begin( "Disable Crash", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); if ( ImGui::Checkbox( "Enable", &m_isEnabled ) ) { if ( m_isEnabled ) { b2Body_Enable( m_attachmentId ); } else { b2Body_Disable( m_attachmentId ); } } ImGui::End(); } static Sample* Create( SampleContext* context ) { return new DisableCrash( context ); } b2BodyId m_attachmentId; b2BodyId m_platformId; bool m_isEnabled; }; static int sampleDisableCrash = RegisterSample( "Issues", "Disable", DisableCrash::Create ); class Crash01 : public Sample { public: explicit Crash01( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.8f, 6.4f }; m_context->camera.zoom = 25.0f * 0.4f; } m_type = b2_dynamicBody; m_isEnabled = true; b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.name = "ground"; groundId = b2CreateBody( m_worldId, &bodyDef ); b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Define attachment { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -2.0f, 3.0f }; bodyDef.name = "attach1"; m_attachmentId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 0.5f, 2.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; b2CreatePolygonShape( m_attachmentId, &shapeDef, &box ); } // Define platform { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = m_type; bodyDef.isEnabled = m_isEnabled; bodyDef.position = { -4.0f, 5.0f }; bodyDef.name = "platform"; m_platformId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeOffsetBox( 0.5f, 4.0f, { 4.0f, 0.0f }, b2MakeRot( 0.5f * B2_PI ) ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 2.0f; b2CreatePolygonShape( m_platformId, &shapeDef, &box ); b2RevoluteJointDef revoluteDef = b2DefaultRevoluteJointDef(); b2Vec2 pivot = { -2.0f, 5.0f }; revoluteDef.base.bodyIdA = m_attachmentId; revoluteDef.base.bodyIdB = m_platformId; revoluteDef.base.localFrameA.p = b2Body_GetLocalPoint( m_attachmentId, pivot ); revoluteDef.base.localFrameB.p = b2Body_GetLocalPoint( m_platformId, pivot ); revoluteDef.maxMotorTorque = 50.0f; revoluteDef.enableMotor = true; b2CreateRevoluteJoint( m_worldId, &revoluteDef ); b2PrismaticJointDef prismaticDef = b2DefaultPrismaticJointDef(); b2Vec2 anchor = { 0.0f, 5.0f }; prismaticDef.base.bodyIdA = groundId; prismaticDef.base.bodyIdB = m_platformId; prismaticDef.base.localFrameA.p = b2Body_GetLocalPoint( groundId, anchor ); prismaticDef.base.localFrameB.p = b2Body_GetLocalPoint( m_platformId, anchor ); prismaticDef.maxMotorForce = 1000.0f; prismaticDef.motorSpeed = 0.0f; prismaticDef.enableMotor = true; prismaticDef.lowerTranslation = -10.0f; prismaticDef.upperTranslation = 10.0f; prismaticDef.enableLimit = true; b2CreatePrismaticJoint( m_worldId, &prismaticDef ); } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 11.0f * fontSize; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 9.0f * fontSize, height ) ); ImGui::Begin( "Crash 01", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); if ( ImGui::RadioButton( "Static", m_type == b2_staticBody ) ) { m_type = b2_staticBody; b2Body_SetType( m_platformId, b2_staticBody ); } if ( ImGui::RadioButton( "Kinematic", m_type == b2_kinematicBody ) ) { m_type = b2_kinematicBody; b2Body_SetType( m_platformId, b2_kinematicBody ); b2Body_SetLinearVelocity( m_platformId, { -0.1f, 0.0f } ); } if ( ImGui::RadioButton( "Dynamic", m_type == b2_dynamicBody ) ) { m_type = b2_dynamicBody; b2Body_SetType( m_platformId, b2_dynamicBody ); } if ( ImGui::Checkbox( "Enable", &m_isEnabled ) ) { if ( m_isEnabled ) { b2Body_Enable( m_attachmentId ); } else { b2Body_Disable( m_attachmentId ); } } ImGui::End(); } static Sample* Create( SampleContext* context ) { return new Crash01( context ); } b2BodyId m_attachmentId; b2BodyId m_platformId; b2BodyType m_type; bool m_isEnabled; }; static int sampleBodyType = RegisterSample( "Issues", "Crash01", Crash01::Create ); class StaticVsBulletBug : public Sample { public: explicit StaticVsBulletBug( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 48.8525391, 68.1518555 }; m_context->camera.zoom = 100.0f * 0.5f; } { b2BodyDef bd = b2DefaultBodyDef(); bd.type = b2_dynamicBody; // NOTE(bug): Changing this to b2_staticBody fixes the issue b2BodyId staticBodyId = b2CreateBody( m_worldId, &bd ); const b2Vec2 verts[] = { { 48.8525391, 68.1518555 }, { 49.1821289, 68.1152344 }, { 68.8476562, 68.1152344 }, { 68.8476562, 70.2392578 }, { 48.8525391, 70.2392578 }, }; const b2Hull hull = b2ComputeHull( verts, ARRAY_COUNT( verts ) ); const b2Polygon poly = b2MakePolygon( &hull, 0.0f ); b2ShapeDef sd = b2DefaultShapeDef(); sd.density = 1.0f; sd.material.friction = 0.5f; sd.material.restitution = 0.1f; b2CreatePolygonShape( staticBodyId, &sd, &poly ); b2Body_SetType( staticBodyId, b2_staticBody ); } { b2BodyDef bd = b2DefaultBodyDef(); bd.position = { 58.9243050, 77.5401459 }; bd.type = b2_dynamicBody; bd.motionLocks.angularZ = true; bd.linearVelocity = { 104.868881, -281.073883 }; bd.isBullet = true; b2BodyId ballBodyId = b2CreateBody( m_worldId, &bd ); const b2Circle ball = { .center = {}, .radius = 0.3f }; b2ShapeDef ballShape = b2DefaultShapeDef(); ballShape.density = 3.0f; ballShape.material.friction = 0.2f; ballShape.material.restitution = 0.9f; b2CreateCircleShape( ballBodyId, &ballShape, &ball ); } } static Sample* Create( SampleContext* context ) { return new StaticVsBulletBug( context ); } }; static int staticVsBulletBug = RegisterSample( "Issues", "StaticVsBulletBug", StaticVsBulletBug::Create ); // This simulations stresses the solver by putting a light mass between two bodies on a prismatic joint with a stiff spring. // This can be made stable by increasing the size of the middle circle and/or increasing the number of sub-steps. class UnstablePrismaticJoints : public Sample { public: explicit UnstablePrismaticJoints( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 1.75f }; m_context->camera.zoom = 32.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -100.0f, 0.0f }, { 100.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } b2BodyId centerId; { b2BodyDef bd = b2DefaultBodyDef(); bd.type = b2_dynamicBody; bd.position = { 0, 3 }; centerId = b2CreateBody( m_worldId, &bd ); b2ShapeDef sd = b2DefaultShapeDef(); b2Circle circle; circle.center = { 0, 0 }; // Note: this will crash due to divergence (inf/nan) with a radius of 0.1 // circle.radius = 0.1f; circle.radius = 0.5f; b2CreateCircleShape( centerId, &sd, &circle ); } b2PrismaticJointDef jd = b2DefaultPrismaticJointDef(); jd.enableSpring = true; jd.hertz = 10.0f; jd.dampingRatio = 2.0f; { b2BodyDef bd = b2DefaultBodyDef(); bd.type = b2_dynamicBody; bd.position = { -3.5, 3 }; b2BodyId leftId = b2CreateBody( m_worldId, &bd ); b2ShapeDef sd = b2DefaultShapeDef(); b2Circle circle; circle.center = { 0, 0 }; circle.radius = 2.0f; b2CreateCircleShape( leftId, &sd, &circle ); jd.base.bodyIdA = centerId; jd.base.bodyIdB = leftId; jd.targetTranslation = -3.0f; b2CreatePrismaticJoint( m_worldId, &jd ); } { b2BodyDef bd = b2DefaultBodyDef(); bd.type = b2_dynamicBody; bd.position = { 3.5, 3 }; b2BodyId rightId = b2CreateBody( m_worldId, &bd ); b2ShapeDef sd = b2DefaultShapeDef(); b2Circle circle; circle.center = { 0, 0 }; circle.radius = 2.0f; b2CreateCircleShape( rightId, &sd, &circle ); jd.base.bodyIdA = centerId; jd.base.bodyIdB = rightId; jd.targetTranslation = 3.0f; b2CreatePrismaticJoint( m_worldId, &jd ); } } static Sample* Create( SampleContext* context ) { return new UnstablePrismaticJoints( context ); } }; static int sampleUnstablePrismaticJoints = RegisterSample( "Issues", "Unstable Prismatic Joints", UnstablePrismaticJoints::Create ); class UnstableWindmill : public Sample { public: explicit UnstableWindmill( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 1.75f }; m_context->camera.zoom = 32.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -100.0f, -10.0f }, { 100.0f, -10.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } b2BodyDef bdef = b2DefaultBodyDef(); bdef.gravityScale = 0.0f; bdef.type = b2_dynamicBody; b2ShapeDef sdef = b2DefaultShapeDef(); sdef.material = b2DefaultSurfaceMaterial(); sdef.material.friction = 0.1f; // center bdef.position = { 10, 10 }; b2BodyId center = b2CreateBody( m_worldId, &bdef ); b2Circle circle = { .center = { 0, 0 }, .radius = 5 }; b2CreateCircleShape( center, &sdef, &circle ); // rotors b2WeldJointDef wjdef = b2DefaultWeldJointDef(); // This simulation can be stabilized by using a lower constraint stiffness wjdef.base.constraintHertz = 30.0f; wjdef.base.bodyIdA = center; b2Polygon polygon; bdef.position = { 10, 0 }; b2BodyId body = b2CreateBody( m_worldId, &bdef ); b2CreatePolygonShape( body, &sdef, &( polygon = b2MakeBox( 4, 5 ) ) ); wjdef.base.localFrameA = { .p = { 0, -5 }, .q = b2Rot_identity }; wjdef.base.bodyIdB = body; wjdef.base.localFrameB = { .p = { 0, 5 }, .q = b2Rot_identity }; b2CreateWeldJoint( m_worldId, &wjdef ); bdef.position = { 20, 10 }; body = b2CreateBody( m_worldId, &bdef ); b2CreatePolygonShape( body, &sdef, &( polygon = b2MakeBox( 5, 4 ) ) ); wjdef.base.localFrameA = { .p = { 5, 0 }, .q = b2Rot_identity }; wjdef.base.bodyIdB = body; wjdef.base.localFrameB = { .p = { -5, 0 }, .q = b2Rot_identity }; b2CreateWeldJoint( m_worldId, &wjdef ); bdef.position = { 10, 20 }; body = b2CreateBody( m_worldId, &bdef ); b2CreatePolygonShape( body, &sdef, &( polygon = b2MakeBox( 4, 5 ) ) ); wjdef.base.localFrameA = { .p = { 0, 5 }, .q = b2Rot_identity }; wjdef.base.bodyIdB = body; wjdef.base.localFrameB = { .p = { 0, -5 }, .q = b2Rot_identity }; b2CreateWeldJoint( m_worldId, &wjdef ); bdef.position = { 0, 10 }; body = b2CreateBody( m_worldId, &bdef ); b2CreatePolygonShape( body, &sdef, &( polygon = b2MakeBox( 5, 4 ) ) ); wjdef.base.localFrameA = { .p = { -5, 0 }, .q = b2Rot_identity }; wjdef.base.bodyIdB = body; wjdef.base.localFrameB = { .p = { 5, 0 }, .q = b2Rot_identity }; b2CreateWeldJoint( m_worldId, &wjdef ); } static Sample* Create( SampleContext* context ) { return new UnstableWindmill( context ); } }; static int sampleUnstableWindmill = RegisterSample( "Issues", "Unstable Windmill", UnstableWindmill::Create ); ================================================ FILE: samples/sample_joints.cpp ================================================ // SPDX-FileCopyrightText: 2022 Erin Catto // SPDX-License-Identifier: MIT #include "car.h" #include "donut.h" #include "doohickey.h" #include "draw.h" #include "human.h" #include "random.h" #include "sample.h" #include "box2d/box2d.h" #include "box2d/math_functions.h" #include #include // Test the distance joint and all options class DistanceJoint : public Sample { public: enum { e_maxCount = 10 }; explicit DistanceJoint( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 12.0f }; m_context->camera.zoom = 25.0f * 0.35f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); m_groundId = b2CreateBody( m_worldId, &bodyDef ); } m_count = 0; m_hertz = 5.0f; m_dampingRatio = 0.5f; m_length = 1.0f; m_minLength = m_length; m_maxLength = m_length; m_tensionForce = 2000.0f; m_compressionForce = 100.0f; m_enableSpring = false; m_enableLimit = false; for ( int i = 0; i < e_maxCount; ++i ) { m_bodyIds[i] = b2_nullBodyId; m_jointIds[i] = b2_nullJointId; } CreateScene( 1 ); } void CreateScene( int newCount ) { for ( int i = 0; i < m_count; ++i ) { b2DestroyJoint( m_jointIds[i], false ); m_jointIds[i] = b2_nullJointId; } for ( int i = 0; i < m_count; ++i ) { b2DestroyBody( m_bodyIds[i] ); m_bodyIds[i] = b2_nullBodyId; } m_count = newCount; float radius = 0.25f; b2Circle circle = { { 0.0f, 0.0f }, radius }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; float yOffset = 20.0f; b2DistanceJointDef jointDef = b2DefaultDistanceJointDef(); jointDef.hertz = m_hertz; jointDef.dampingRatio = m_dampingRatio; jointDef.length = m_length; jointDef.lowerSpringForce = -m_tensionForce; jointDef.upperSpringForce = m_compressionForce; jointDef.minLength = m_minLength; jointDef.maxLength = m_maxLength; jointDef.enableSpring = m_enableSpring; jointDef.enableLimit = m_enableLimit; b2BodyId prevBodyId = m_groundId; for ( int i = 0; i < m_count; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.angularDamping = 1.0f; bodyDef.position = { m_length * ( i + 1.0f ), yOffset }; m_bodyIds[i] = b2CreateBody( m_worldId, &bodyDef ); b2CreateCircleShape( m_bodyIds[i], &shapeDef, &circle ); b2Vec2 pivotA = { m_length * i, yOffset }; b2Vec2 pivotB = { m_length * ( i + 1.0f ), yOffset }; jointDef.base.bodyIdA = prevBodyId; jointDef.base.bodyIdB = m_bodyIds[i]; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivotA ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivotB ); m_jointIds[i] = b2CreateDistanceJoint( m_worldId, &jointDef ); prevBodyId = m_bodyIds[i]; } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 20.0f * fontSize; ImGui::SetNextWindowPos( { 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize }, ImGuiCond_Once ); ImGui::SetNextWindowSize( { 18.0f * fontSize, height } ); ImGui::Begin( "Distance Joint", nullptr, ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 10.0f * fontSize ); if ( ImGui::SliderFloat( "Length", &m_length, 0.1f, 4.0f, "%3.1f" ) ) { for ( int i = 0; i < m_count; ++i ) { b2DistanceJoint_SetLength( m_jointIds[i], m_length ); b2Joint_WakeBodies( m_jointIds[i] ); } } if ( ImGui::Checkbox( "Spring", &m_enableSpring ) ) { for ( int i = 0; i < m_count; ++i ) { b2DistanceJoint_EnableSpring( m_jointIds[i], m_enableSpring ); b2Joint_WakeBodies( m_jointIds[i] ); } } if ( m_enableSpring ) { if ( ImGui::SliderFloat( "Tension", &m_tensionForce, 0.0f, 4000.0f ) ) { for ( int i = 0; i < m_count; ++i ) { b2DistanceJoint_SetSpringForceRange( m_jointIds[i], -m_tensionForce, m_compressionForce ); b2Joint_WakeBodies( m_jointIds[i] ); } } if ( ImGui::SliderFloat( "Compression", &m_compressionForce, 0.0f, 200.0f ) ) { for ( int i = 0; i < m_count; ++i ) { b2DistanceJoint_SetSpringForceRange( m_jointIds[i], -m_tensionForce, m_compressionForce ); b2Joint_WakeBodies( m_jointIds[i] ); } } if ( ImGui::SliderFloat( "Hertz", &m_hertz, 0.0f, 15.0f, "%3.1f" ) ) { for ( int i = 0; i < m_count; ++i ) { b2DistanceJoint_SetSpringHertz( m_jointIds[i], m_hertz ); b2Joint_WakeBodies( m_jointIds[i] ); } } if ( ImGui::SliderFloat( "Damping", &m_dampingRatio, 0.0f, 4.0f, "%3.1f" ) ) { for ( int i = 0; i < m_count; ++i ) { b2DistanceJoint_SetSpringDampingRatio( m_jointIds[i], m_dampingRatio ); b2Joint_WakeBodies( m_jointIds[i] ); } } } if ( ImGui::Checkbox( "Limit", &m_enableLimit ) ) { for ( int i = 0; i < m_count; ++i ) { b2DistanceJoint_EnableLimit( m_jointIds[i], m_enableLimit ); b2Joint_WakeBodies( m_jointIds[i] ); } } if ( m_enableLimit ) { if ( ImGui::SliderFloat( "Min Length", &m_minLength, 0.1f, 4.0f, "%3.1f" ) ) { for ( int i = 0; i < m_count; ++i ) { b2DistanceJoint_SetLengthRange( m_jointIds[i], m_minLength, m_maxLength ); b2Joint_WakeBodies( m_jointIds[i] ); } } if ( ImGui::SliderFloat( "Max Length", &m_maxLength, 0.1f, 4.0f, "%3.1f" ) ) { for ( int i = 0; i < m_count; ++i ) { b2DistanceJoint_SetLengthRange( m_jointIds[i], m_minLength, m_maxLength ); b2Joint_WakeBodies( m_jointIds[i] ); } } } int count = m_count; if ( ImGui::SliderInt( "Count", &count, 1, e_maxCount ) ) { CreateScene( count ); } ImGui::PopItemWidth(); ImGui::End(); } static Sample* Create( SampleContext* context ) { return new DistanceJoint( context ); } b2BodyId m_groundId; b2BodyId m_bodyIds[e_maxCount]; b2JointId m_jointIds[e_maxCount]; int m_count; float m_hertz; float m_dampingRatio; float m_length; float m_tensionForce; float m_compressionForce; float m_minLength; float m_maxLength; bool m_enableSpring; bool m_enableLimit; }; static int sampleDistanceJoint = RegisterSample( "Joints", "Distance Joint", DistanceJoint::Create ); /// This test shows how to use a motor joint. A motor joint /// can be used to animate a dynamic body. With finite motor forces /// the body can be blocked by collision with other bodies. class MotorJoint : public Sample { public: explicit MotorJoint( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 7.0f }; m_context->camera.zoom = 25.0f * 0.4f; } b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } m_transform = { .p = { 0.0f, 8.0f }, .q = b2Rot_identity }; // Define a target body { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_kinematicBody; bodyDef.position = m_transform.p; m_targetId = b2CreateBody( m_worldId, &bodyDef ); } // Define motorized body { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = m_transform.p; m_bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 2.0f, 0.5f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( m_bodyId, &shapeDef, &box ); m_maxForce = 5000.0f; m_maxTorque = 500.0f; b2MotorJointDef jointDef = b2DefaultMotorJointDef(); jointDef.base.bodyIdA = m_targetId; jointDef.base.bodyIdB = m_bodyId; jointDef.linearHertz = 4.0f; jointDef.linearDampingRatio = 0.7f; jointDef.angularHertz = 4.0f; jointDef.angularDampingRatio = 0.7f; jointDef.maxSpringForce = m_maxForce; jointDef.maxSpringTorque = m_maxTorque; m_jointId = b2CreateMotorJoint( m_worldId, &jointDef ); } // Define spring body { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -2.0f, 2.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeSquare( 0.5f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2MotorJointDef jointDef = b2DefaultMotorJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Add( bodyDef.position, { 0.25f, 0.25f } ); jointDef.base.localFrameB.p = { 0.25f, 0.25f }; jointDef.linearHertz = 7.5f; jointDef.linearDampingRatio = 0.7f; jointDef.angularHertz = 7.5f; jointDef.angularDampingRatio = 0.7f; jointDef.maxSpringForce = 500.0f; jointDef.maxSpringTorque = 10.0f; b2CreateMotorJoint( m_worldId, &jointDef ); } m_speed = 1.0f; m_time = 0.0f; } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 180.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Motor Joint", nullptr, ImGuiWindowFlags_NoResize ); if ( ImGui::SliderFloat( "Speed", &m_speed, -5.0f, 5.0f, "%.0f" ) ) { } if ( ImGui::SliderFloat( "Max Force", &m_maxForce, 0.0f, 10000.0f, "%.0f" ) ) { b2MotorJoint_SetMaxSpringForce( m_jointId, m_maxForce ); } if ( ImGui::SliderFloat( "Max Torque", &m_maxTorque, 0.0f, 10000.0f, "%.0f" ) ) { b2MotorJoint_SetMaxSpringTorque( m_jointId, m_maxTorque ); } if ( ImGui::Button( "Apply Impulse" ) ) { b2Body_ApplyLinearImpulseToCenter( m_bodyId, { 100.0f, 0.0f }, true ); } ImGui::End(); } void Step() override { float timeStep = m_context->hertz > 0.0f ? 1.0f / m_context->hertz : 0.0f; if ( m_context->pause ) { if ( m_context->singleStep == false ) { timeStep = 0.0f; } } if ( timeStep > 0.0f ) { m_time += m_speed * timeStep; b2Vec2 linearOffset; linearOffset.x = 6.0f * sinf( 2.0f * m_time ); linearOffset.y = 8.0f + 4.0f * sinf( 1.0f * m_time ); float angularOffset = 2.0f * m_time; m_transform = { linearOffset, b2MakeRot( angularOffset ) }; bool wake = true; b2Body_SetTargetTransform( m_targetId, m_transform, timeStep, wake ); } DrawTransform( m_draw, m_transform, 1.0f ); Sample::Step(); b2Vec2 force = b2Joint_GetConstraintForce( m_jointId ); float torque = b2Joint_GetConstraintTorque( m_jointId ); DrawTextLine( "force = {%3.f, %3.f}, torque = %3.f", force.x, force.y, torque ); } static Sample* Create( SampleContext* context ) { return new MotorJoint( context ); } b2BodyId m_targetId; b2BodyId m_bodyId; b2JointId m_jointId; b2Transform m_transform; float m_time; float m_speed; float m_maxForce; float m_maxTorque; }; static int sampleMotorJoint = RegisterSample( "Joints", "Motor Joint", MotorJoint::Create ); class TopDownFriction : public Sample { public: explicit TopDownFriction( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 7.0f }; m_context->camera.zoom = 25.0f * 0.4f; } b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -10.0f, 0.0f }, { 10.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); segment = { { -10.0f, 0.0f }, { -10.0f, 20.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); segment = { { 10.0f, 0.0f }, { 10.0f, 20.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); segment = { { -10.0f, 20.0f }, { 10.0f, 20.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } b2MotorJointDef jointDef = b2DefaultMotorJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.collideConnected = true; jointDef.maxVelocityForce = 10.0f; jointDef.maxVelocityTorque = 10.0f; b2Capsule capsule = { { -0.25f, 0.0f }, { 0.25f, 0.0f }, 0.25f }; b2Circle circle = { { 0.0f, 0.0f }, 0.35f }; b2Polygon square = b2MakeSquare( 0.35f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.gravityScale = 0.0f; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.restitution = 0.8f; int n = 10; float x = -5.0f, y = 15.0f; for ( int i = 0; i < n; ++i ) { for ( int j = 0; j < n; ++j ) { bodyDef.position = { x, y }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); int remainder = ( n * i + j ) % 4; if ( remainder == 0 ) { b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); } else if ( remainder == 1 ) { b2CreateCircleShape( bodyId, &shapeDef, &circle ); } else if ( remainder == 2 ) { b2CreatePolygonShape( bodyId, &shapeDef, &square ); } else { b2Polygon poly = RandomPolygon( 0.75f ); poly.radius = 0.1f; b2CreatePolygonShape( bodyId, &shapeDef, &poly ); } jointDef.base.bodyIdB = bodyId; b2CreateMotorJoint( m_worldId, &jointDef ); x += 1.0f; } x = -5.0f; y -= 1.0f; } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 180.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Top Down Friction", nullptr, ImGuiWindowFlags_NoResize ); if ( ImGui::Button( "Explode" ) ) { b2ExplosionDef def = b2DefaultExplosionDef(); def.position = { 0.0f, 10.0f }; def.radius = 10.0f; def.falloff = 5.0f; def.impulsePerLength = 10.0f; b2World_Explode( m_worldId, &def ); DrawCircle( m_draw, def.position, 10.0f, b2_colorWhite ); } ImGui::End(); } static Sample* Create( SampleContext* context ) { return new TopDownFriction( context ); } }; static int sampleTopDownFriction = RegisterSample( "Joints", "Top Down Friction", TopDownFriction::Create ); // This sample shows how to use a filter joint to prevent collision between two bodies. // This is more specific than shape filters. It also shows that sleeping is coupled by the filter joint. class FilterJoint : public Sample { public: explicit FilterJoint( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 7.0f }; m_context->camera.zoom = 25.0f * 0.4f; } { b2BodyId groundId; b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -4.0f, 2.0f }; b2BodyId bodyId1 = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeSquare( 2.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( bodyId1, &shapeDef, &box ); bodyDef.position = { 4.0f, 2.0f }; b2BodyId bodyId2 = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId2, &shapeDef, &box ); b2FilterJointDef jointDef = b2DefaultFilterJointDef(); jointDef.base.bodyIdA = bodyId1; jointDef.base.bodyIdB = bodyId2; b2CreateFilterJoint( m_worldId, &jointDef ); } } static Sample* Create( SampleContext* context ) { return new FilterJoint( context ); } }; static int sampleFilterJoint = RegisterSample( "Joints", "Filter Joint", FilterJoint::Create ); class RevoluteJoint : public Sample { public: explicit RevoluteJoint( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 15.5f }; m_context->camera.zoom = 25.0f * 0.7f; } b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, -1.0f }; groundId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 40.0f, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( groundId, &shapeDef, &box ); } m_enableSpring = false; m_enableLimit = false; m_enableMotor = false; m_hertz = 2.0f; m_dampingRatio = 0.5f; m_targetDegrees = 45.0f; m_motorSpeed = 1.0f; m_motorTorque = 1000.0f; { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -10.0f, 20.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; b2Capsule capsule = { { 0.0f, -1.0f }, { 0.0f, 6.0f }, 0.5f }; b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); b2Vec2 pivot = { -10.0f, 20.5f }; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.q = b2MakeRot( 0.5f * B2_PI ); jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.targetAngle = B2_PI * m_targetDegrees / 180.0f; jointDef.enableSpring = m_enableSpring; jointDef.hertz = m_hertz; jointDef.dampingRatio = m_dampingRatio; jointDef.motorSpeed = m_motorSpeed; jointDef.maxMotorTorque = m_motorTorque; jointDef.enableMotor = m_enableMotor; jointDef.lowerAngle = -0.5f * B2_PI; jointDef.upperAngle = 0.05f * B2_PI; jointDef.enableLimit = m_enableLimit; m_jointId1 = b2CreateRevoluteJoint( m_worldId, &jointDef ); b2Joint_SetConstraintTuning( m_jointId1, 60.0f, 20.0f ); } { b2Circle circle = {}; circle.radius = 2.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 5.0f, 30.0f }; m_ball = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; b2CreateCircleShape( m_ball, &shapeDef, &circle ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 20.0f, 10.0f }; bodyDef.type = b2_dynamicBody; b2BodyId body = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeOffsetBox( 10.0f, 0.5f, { -10.0f, 0.0f }, b2Rot_identity ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; b2CreatePolygonShape( body, &shapeDef, &box ); b2Vec2 pivot = { 19.0f, 10.0f }; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = body; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.lowerAngle = -0.25f * B2_PI; jointDef.upperAngle = 0.0f * B2_PI; jointDef.enableLimit = true; jointDef.enableMotor = true; jointDef.motorSpeed = 0.0f; jointDef.maxMotorTorque = m_motorTorque; m_jointId2 = b2CreateRevoluteJoint( m_worldId, &jointDef ); } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 8.0f * fontSize; ImGui::SetNextWindowPos( { 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize }, ImGuiCond_Once ); ImGui::SetNextWindowSize( { 8.0f * fontSize, height } ); ImGui::Begin( "Revolute Joint", nullptr, ImGuiWindowFlags_NoResize ); if ( ImGui::Checkbox( "Limit", &m_enableLimit ) ) { b2RevoluteJoint_EnableLimit( m_jointId1, m_enableLimit ); b2Joint_WakeBodies( m_jointId1 ); } if ( ImGui::Checkbox( "Motor", &m_enableMotor ) ) { b2RevoluteJoint_EnableMotor( m_jointId1, m_enableMotor ); b2Joint_WakeBodies( m_jointId1 ); } if ( m_enableMotor ) { if ( ImGui::SliderFloat( "Max Torque", &m_motorTorque, 0.0f, 5000.0f, "%.0f" ) ) { b2RevoluteJoint_SetMaxMotorTorque( m_jointId1, m_motorTorque ); b2Joint_WakeBodies( m_jointId1 ); } if ( ImGui::SliderFloat( "Speed", &m_motorSpeed, -20.0f, 20.0f, "%.0f" ) ) { b2RevoluteJoint_SetMotorSpeed( m_jointId1, m_motorSpeed ); b2Joint_WakeBodies( m_jointId1 ); } } if ( ImGui::Checkbox( "Spring", &m_enableSpring ) ) { b2RevoluteJoint_EnableSpring( m_jointId1, m_enableSpring ); b2Joint_WakeBodies( m_jointId1 ); } if ( m_enableSpring ) { if ( ImGui::SliderFloat( "Hertz", &m_hertz, 0.0f, 30.0f, "%.1f" ) ) { b2RevoluteJoint_SetSpringHertz( m_jointId1, m_hertz ); b2Joint_WakeBodies( m_jointId1 ); } if ( ImGui::SliderFloat( "Damping", &m_dampingRatio, 0.0f, 2.0f, "%.1f" ) ) { b2RevoluteJoint_SetSpringDampingRatio( m_jointId1, m_dampingRatio ); b2Joint_WakeBodies( m_jointId1 ); } if ( ImGui::SliderFloat( "Degrees", &m_targetDegrees, -180.0f, 180.0f, "%.0f" ) ) { b2RevoluteJoint_SetTargetAngle( m_jointId1, B2_PI * m_targetDegrees / 180.0f ); b2Joint_WakeBodies( m_jointId1 ); } } ImGui::End(); } void Step() override { Sample::Step(); float angle1 = b2RevoluteJoint_GetAngle( m_jointId1 ); DrawTextLine( "Angle (Deg) 1 = %2.1f", angle1 ); float torque1 = b2RevoluteJoint_GetMotorTorque( m_jointId1 ); DrawTextLine( "Motor Torque 1 = %4.1f", torque1 ); float torque2 = b2RevoluteJoint_GetMotorTorque( m_jointId2 ); DrawTextLine( "Motor Torque 2 = %4.1f", torque2 ); } static Sample* Create( SampleContext* context ) { return new RevoluteJoint( context ); } b2BodyId m_ball; b2JointId m_jointId1; b2JointId m_jointId2; float m_motorSpeed; float m_motorTorque; float m_hertz; float m_dampingRatio; float m_targetDegrees; bool m_enableSpring; bool m_enableMotor; bool m_enableLimit; }; static int sampleRevolute = RegisterSample( "Joints", "Revolute", RevoluteJoint::Create ); class PrismaticJoint : public Sample { public: explicit PrismaticJoint( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 8.0f }; m_context->camera.zoom = 25.0f * 0.5f; } b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); } m_enableSpring = false; m_enableLimit = true; m_enableMotor = false; m_motorSpeed = 2.0f; m_motorForce = 25.0f; m_hertz = 1.0f; m_dampingRatio = 0.5f; m_translation = 0.0f; { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, 10.0f }; bodyDef.type = b2_dynamicBody; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeBox( 0.5f, 2.0f ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2Vec2 pivot = { 0.0f, 9.0f }; // b2Vec2 axis = b2Normalize({1.0f, 0.0f}); b2Vec2 axis = b2Normalize( { 1.0f, 1.0f } ); b2PrismaticJointDef jointDef = b2DefaultPrismaticJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameA.q = b2MakeRotFromUnitVector( axis ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.base.localFrameB.q = b2MakeRotFromUnitVector( axis ); jointDef.base.drawScale = 2.0f; jointDef.motorSpeed = m_motorSpeed; jointDef.maxMotorForce = m_motorForce; jointDef.enableMotor = m_enableMotor; jointDef.lowerTranslation = -10.0f; jointDef.upperTranslation = 10.0f; jointDef.enableLimit = m_enableLimit; jointDef.enableSpring = m_enableSpring; jointDef.hertz = m_hertz; jointDef.dampingRatio = m_dampingRatio; m_jointId = b2CreatePrismaticJoint( m_worldId, &jointDef ); } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 240.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Prismatic Joint", nullptr, ImGuiWindowFlags_NoResize ); if ( ImGui::Checkbox( "Limit", &m_enableLimit ) ) { b2PrismaticJoint_EnableLimit( m_jointId, m_enableLimit ); b2Joint_WakeBodies( m_jointId ); } if ( ImGui::Checkbox( "Motor", &m_enableMotor ) ) { b2PrismaticJoint_EnableMotor( m_jointId, m_enableMotor ); b2Joint_WakeBodies( m_jointId ); } if ( m_enableMotor ) { if ( ImGui::SliderFloat( "Max Force", &m_motorForce, 0.0f, 200.0f, "%.0f" ) ) { b2PrismaticJoint_SetMaxMotorForce( m_jointId, m_motorForce ); b2Joint_WakeBodies( m_jointId ); } if ( ImGui::SliderFloat( "Speed", &m_motorSpeed, -40.0f, 40.0f, "%.0f" ) ) { b2PrismaticJoint_SetMotorSpeed( m_jointId, m_motorSpeed ); b2Joint_WakeBodies( m_jointId ); } } if ( ImGui::Checkbox( "Spring", &m_enableSpring ) ) { b2PrismaticJoint_EnableSpring( m_jointId, m_enableSpring ); b2Joint_WakeBodies( m_jointId ); } if ( m_enableSpring ) { if ( ImGui::SliderFloat( "Hertz", &m_hertz, 0.0f, 10.0f, "%.1f" ) ) { b2PrismaticJoint_SetSpringHertz( m_jointId, m_hertz ); b2Joint_WakeBodies( m_jointId ); } if ( ImGui::SliderFloat( "Damping", &m_dampingRatio, 0.0f, 2.0f, "%.1f" ) ) { b2PrismaticJoint_SetSpringDampingRatio( m_jointId, m_dampingRatio ); b2Joint_WakeBodies( m_jointId ); } if ( ImGui::SliderFloat( "Translation", &m_translation, -15.0f, 15.0f, "%.1f" ) ) { b2PrismaticJoint_SetTargetTranslation( m_jointId, m_translation ); b2Joint_WakeBodies( m_jointId ); } } ImGui::End(); } void Step() override { Sample::Step(); float force = b2PrismaticJoint_GetMotorForce( m_jointId ); DrawTextLine( "Motor Force = %4.1f", force ); float translation = b2PrismaticJoint_GetTranslation( m_jointId ); DrawTextLine( "Translation = %4.1f", translation ); float speed = b2PrismaticJoint_GetSpeed( m_jointId ); DrawTextLine( "Speed = %4.8f", speed ); } static Sample* Create( SampleContext* context ) { return new PrismaticJoint( context ); } b2JointId m_jointId; float m_motorSpeed; float m_motorForce; float m_hertz; float m_dampingRatio; float m_translation; bool m_enableSpring; bool m_enableMotor; bool m_enableLimit; }; static int samplePrismatic = RegisterSample( "Joints", "Prismatic", PrismaticJoint::Create ); class WheelJoint : public Sample { public: explicit WheelJoint( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 10.0f }; m_context->camera.zoom = 25.0f * 0.15f; } b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); } m_enableSpring = true; m_enableLimit = true; m_enableMotor = true; m_motorSpeed = 2.0f; m_motorTorque = 5.0f; m_hertz = 1.0f; m_dampingRatio = 0.7f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, 10.25f }; bodyDef.type = b2_dynamicBody; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Capsule capsule = { { 0.0f, -0.5f }, { 0.0f, 0.5f }, 0.5f }; b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); b2Vec2 pivot = { 0.0f, 10.0f }; b2Vec2 axis = b2Normalize( { 1.0f, 1.0f } ); b2WheelJointDef jointDef = b2DefaultWheelJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.q = b2MakeRotFromUnitVector( axis ); jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.motorSpeed = m_motorSpeed; jointDef.maxMotorTorque = m_motorTorque; jointDef.enableMotor = m_enableMotor; jointDef.lowerTranslation = -3.0f; jointDef.upperTranslation = 3.0f; jointDef.enableLimit = m_enableLimit; jointDef.hertz = m_hertz; jointDef.dampingRatio = m_dampingRatio; m_jointId = b2CreateWheelJoint( m_worldId, &jointDef ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 15.0f * fontSize; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 18.0f * fontSize, height ) ); ImGui::Begin( "Wheel Joint", nullptr, ImGuiWindowFlags_NoResize ); if ( ImGui::Checkbox( "Limit", &m_enableLimit ) ) { b2WheelJoint_EnableLimit( m_jointId, m_enableLimit ); } if ( ImGui::Checkbox( "Motor", &m_enableMotor ) ) { b2WheelJoint_EnableMotor( m_jointId, m_enableMotor ); } if ( m_enableMotor ) { if ( ImGui::SliderFloat( "Torque", &m_motorTorque, 0.0f, 20.0f, "%.0f" ) ) { b2WheelJoint_SetMaxMotorTorque( m_jointId, m_motorTorque ); } if ( ImGui::SliderFloat( "Speed", &m_motorSpeed, -20.0f, 20.0f, "%.0f" ) ) { b2WheelJoint_SetMotorSpeed( m_jointId, m_motorSpeed ); } } if ( ImGui::Checkbox( "Spring", &m_enableSpring ) ) { b2WheelJoint_EnableSpring( m_jointId, m_enableSpring ); } if ( m_enableSpring ) { if ( ImGui::SliderFloat( "Hertz", &m_hertz, 0.0f, 10.0f, "%.1f" ) ) { b2WheelJoint_SetSpringHertz( m_jointId, m_hertz ); } if ( ImGui::SliderFloat( "Damping", &m_dampingRatio, 0.0f, 2.0f, "%.1f" ) ) { b2WheelJoint_SetSpringDampingRatio( m_jointId, m_dampingRatio ); } } ImGui::End(); } void Step() override { Sample::Step(); float torque = b2WheelJoint_GetMotorTorque( m_jointId ); DrawTextLine( "Motor Torque = %4.1f", torque ); } static Sample* Create( SampleContext* context ) { return new WheelJoint( context ); } b2JointId m_jointId; float m_hertz; float m_dampingRatio; float m_motorSpeed; float m_motorTorque; bool m_enableSpring; bool m_enableMotor; bool m_enableLimit; }; static int sampleWheel = RegisterSample( "Joints", "Wheel", WheelJoint::Create ); // A suspension bridge class Bridge : public Sample { public: explicit Bridge( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.zoom = 25.0f * 2.5f; } b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); } { m_constraintHertz = 60.0f; m_constraintDampingRatio = 0.0f; m_springHertz = 2.0f; m_springDampingRatio = 0.7f; m_frictionTorque = 200.0f; b2Polygon box = b2MakeBox( 0.5f, 0.125f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.enableMotor = true; jointDef.maxMotorTorque = m_frictionTorque; jointDef.enableSpring = true; jointDef.hertz = m_springHertz; jointDef.dampingRatio = m_springDampingRatio; int jointIndex = 0; float xbase = -80.0f; b2BodyId prevBodyId = groundId; for ( int i = 0; i < m_count; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { xbase + 0.5f + 1.0f * i, 20.0f }; bodyDef.linearDamping = 0.1f; bodyDef.angularDamping = 0.1f; m_bodyIds[i] = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( m_bodyIds[i], &shapeDef, &box ); b2Vec2 pivot = { xbase + 1.0f * i, 20.0f }; jointDef.base.bodyIdA = prevBodyId; jointDef.base.bodyIdB = m_bodyIds[i]; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); m_jointIds[jointIndex++] = b2CreateRevoluteJoint( m_worldId, &jointDef ); prevBodyId = m_bodyIds[i]; } b2Vec2 pivot = { xbase + 1.0f * m_count, 20.0f }; jointDef.base.bodyIdA = prevBodyId; jointDef.base.bodyIdB = groundId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); m_jointIds[jointIndex++] = b2CreateRevoluteJoint( m_worldId, &jointDef ); assert( jointIndex == m_count + 1 ); } for ( int i = 0; i < 2; ++i ) { b2Vec2 vertices[3] = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, { 0.0f, 1.5f } }; b2Hull hull = b2ComputeHull( vertices, 3 ); b2Polygon triangle = b2MakePolygon( &hull, 0.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -8.0f + 8.0f * i, 22.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &triangle ); } for ( int i = 0; i < 3; ++i ) { b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -6.0f + 6.0f * i, 25.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreateCircleShape( bodyId, &shapeDef, &circle ); } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 180.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 320.0f, height ) ); ImGui::Begin( "Bridge", nullptr, ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( ImGui::GetWindowWidth() * 0.6f ); bool updateFriction = ImGui::SliderFloat( "Joint Friction", &m_frictionTorque, 0.0f, 10000.0f, "%2.f" ); if ( updateFriction ) { for ( int i = 0; i <= m_count; ++i ) { b2RevoluteJoint_SetMaxMotorTorque( m_jointIds[i], m_frictionTorque ); } } if ( ImGui::SliderFloat( "Spring hertz", &m_springHertz, 0.0f, 30.0f, "%.0f" ) ) { for ( int i = 0; i <= m_count; ++i ) { b2RevoluteJoint_SetSpringHertz( m_jointIds[i], m_springHertz ); } } if ( ImGui::SliderFloat( "Spring damping", &m_springDampingRatio, 0.0f, 2.0f, "%.1f" ) ) { for ( int i = 0; i <= m_count; ++i ) { b2RevoluteJoint_SetSpringDampingRatio( m_jointIds[i], m_springDampingRatio ); } } if ( ImGui::SliderFloat( "Constraint hertz", &m_constraintHertz, 15.0f, 240.0f, "%.0f" ) ) { for ( int i = 0; i <= m_count; ++i ) { b2Joint_SetConstraintTuning( m_jointIds[i], m_constraintHertz, m_constraintDampingRatio ); } } if ( ImGui::SliderFloat( "Constraint damping", &m_constraintDampingRatio, 0.0f, 10.0f, "%.1f" ) ) { for ( int i = 0; i <= m_count; ++i ) { b2Joint_SetConstraintTuning( m_jointIds[i], m_constraintHertz, m_constraintDampingRatio ); } } ImGui::PopItemWidth(); ImGui::End(); } static Sample* Create( SampleContext* context ) { return new Bridge( context ); } static constexpr int m_count = 160; b2BodyId m_bodyIds[m_count]; b2JointId m_jointIds[m_count + 1]; float m_frictionTorque; float m_constraintHertz; float m_constraintDampingRatio; float m_springHertz; float m_springDampingRatio; }; static int sampleBridgeIndex = RegisterSample( "Joints", "Bridge", Bridge::Create ); class BallAndChain : public Sample { public: explicit BallAndChain( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, -8.0f }; m_context->camera.zoom = 27.5f; } b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); } m_frictionTorque = 100.0f; { float hx = 0.5f; b2Capsule capsule = { { -hx, 0.0f }, { hx, 0.0f }, 0.125f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; shapeDef.filter.categoryBits = 0x1; shapeDef.filter.maskBits = 0x2; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); int jointIndex = 0; b2BodyId prevBodyId = groundId; for ( int i = 0; i < m_count; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { ( 1.0f + 2.0f * i ) * hx, m_count * hx }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); b2Vec2 pivot = { ( 2.0f * i ) * hx, m_count * hx }; jointDef.base.bodyIdA = prevBodyId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.enableMotor = true; jointDef.maxMotorTorque = m_frictionTorque; jointDef.enableSpring = i > 0; jointDef.hertz = 4.0f; m_jointIds[jointIndex++] = b2CreateRevoluteJoint( m_worldId, &jointDef ); prevBodyId = bodyId; } b2Circle circle = { { 0.0f, 0.0f }, 4.0f }; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { ( 1.0f + 2.0f * m_count ) * hx + circle.radius - hx, m_count * hx }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); shapeDef.filter.categoryBits = 0x2; shapeDef.filter.maskBits = 0x1; b2CreateCircleShape( bodyId, &shapeDef, &circle ); b2Vec2 pivot = { ( 2.0f * m_count ) * hx, m_count * hx }; jointDef.base.bodyIdA = prevBodyId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.enableMotor = true; jointDef.maxMotorTorque = m_frictionTorque; jointDef.enableSpring = true; jointDef.hertz = 4.0f; m_jointIds[jointIndex++] = b2CreateRevoluteJoint( m_worldId, &jointDef ); assert( jointIndex == m_count + 1 ); } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 60.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Ball and Chain", nullptr, ImGuiWindowFlags_NoResize ); bool updateFriction = ImGui::SliderFloat( "Joint Friction", &m_frictionTorque, 0.0f, 1000.0f, "%2.f" ); if ( updateFriction ) { for ( int i = 0; i <= m_count; ++i ) { b2RevoluteJoint_SetMaxMotorTorque( m_jointIds[i], m_frictionTorque ); } } ImGui::End(); } static Sample* Create( SampleContext* context ) { return new BallAndChain( context ); } static constexpr int m_count = 30; b2JointId m_jointIds[m_count + 1]; float m_frictionTorque; }; static int sampleBallAndChainIndex = RegisterSample( "Joints", "Ball & Chain", BallAndChain::Create ); // This sample shows the limitations of an iterative solver. The cantilever sags even though the weld // joint is stiff as possible. class Cantilever : public Sample { public: enum { e_count = 8 }; explicit Cantilever( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 0.0f }; m_context->camera.zoom = 25.0f * 0.35f; } b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); } { m_linearHertz = 15.0f; m_linearDampingRatio = 0.5f; m_angularHertz = 5.0f; m_angularDampingRatio = 0.5f; m_gravityScale = 1.0f; m_collideConnected = false; float hx = 0.5f; b2Capsule capsule = { { -hx, 0.0f }, { hx, 0.0f }, 0.125f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; b2WeldJointDef jointDef = b2DefaultWeldJointDef(); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.isAwake = false; b2BodyId prevBodyId = groundId; for ( int i = 0; i < e_count; ++i ) { bodyDef.position = { ( 1.0f + 2.0f * i ) * hx, 0.0f }; m_bodyIds[i] = b2CreateBody( m_worldId, &bodyDef ); b2CreateCapsuleShape( m_bodyIds[i], &shapeDef, &capsule ); b2Vec2 pivot = { ( 2.0f * i ) * hx, 0.0f }; jointDef.base.bodyIdA = prevBodyId; jointDef.base.bodyIdB = m_bodyIds[i]; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.linearHertz = m_linearHertz; jointDef.linearDampingRatio = m_linearDampingRatio; jointDef.angularHertz = m_angularHertz; jointDef.angularDampingRatio = m_angularDampingRatio; jointDef.base.collideConnected = m_collideConnected; m_jointIds[i] = b2CreateWeldJoint( m_worldId, &jointDef ); // Experimental tuning b2Joint_SetConstraintTuning( m_jointIds[i], 120.0f, 10.0f ); prevBodyId = m_bodyIds[i]; } m_tipId = prevBodyId; } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 14.0f * fontSize; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 19.0f * fontSize, height ) ); ImGui::Begin( "Cantilever", nullptr, ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 8.0f * fontSize ); if ( ImGui::SliderFloat( "Linear Hertz", &m_linearHertz, 0.0f, 20.0f, "%.0f" ) ) { for ( int i = 0; i < e_count; ++i ) { b2WeldJoint_SetLinearHertz( m_jointIds[i], m_linearHertz ); } } if ( ImGui::SliderFloat( "Linear Damping Ratio", &m_linearDampingRatio, 0.0f, 10.0f, "%.1f" ) ) { for ( int i = 0; i < e_count; ++i ) { b2WeldJoint_SetLinearDampingRatio( m_jointIds[i], m_linearDampingRatio ); } } if ( ImGui::SliderFloat( "Angular Hertz", &m_angularHertz, 0.0f, 20.0f, "%.0f" ) ) { for ( int i = 0; i < e_count; ++i ) { b2WeldJoint_SetAngularHertz( m_jointIds[i], m_angularHertz ); } } if ( ImGui::SliderFloat( "Angular Damping Ratio", &m_angularDampingRatio, 0.0f, 10.0f, "%.1f" ) ) { for ( int i = 0; i < e_count; ++i ) { b2WeldJoint_SetAngularDampingRatio( m_jointIds[i], m_angularDampingRatio ); } } if ( ImGui::Checkbox( "Collide Connected", &m_collideConnected ) ) { for ( int i = 0; i < e_count; ++i ) { b2Joint_SetCollideConnected( m_jointIds[i], m_collideConnected ); } } if ( ImGui::SliderFloat( "Gravity Scale", &m_gravityScale, -1.0f, 1.0f, "%.1f" ) ) { for ( int i = 0; i < e_count; ++i ) { b2Body_SetGravityScale( m_bodyIds[i], m_gravityScale ); } } ImGui::PopItemWidth(); ImGui::End(); } void Step() override { Sample::Step(); b2Vec2 tipPosition = b2Body_GetPosition( m_tipId ); DrawTextLine( "tip-y = %.2f", tipPosition.y ); } static Sample* Create( SampleContext* context ) { return new Cantilever( context ); } float m_linearHertz; float m_linearDampingRatio; float m_angularHertz; float m_angularDampingRatio; float m_gravityScale; b2BodyId m_tipId; b2BodyId m_bodyIds[e_count]; b2JointId m_jointIds[e_count]; bool m_collideConnected; }; static int sampleCantileverIndex = RegisterSample( "Joints", "Cantilever", Cantilever::Create ); // This test ensures joints work correctly with bodies that have motion locks class MotionLocks : public Sample { public: enum { e_count = 6 }; explicit MotionLocks( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 8.0f }; m_context->camera.zoom = 25.0f * 0.7f; } b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); m_motionLocks = { false, false, true }; for ( int i = 0; i < e_count; ++i ) { m_bodyIds[i] = b2_nullBodyId; } b2Vec2 position = { -12.5f, 10.0f }; bodyDef.type = b2_dynamicBody; bodyDef.motionLocks = m_motionLocks; b2Polygon box = b2MakeBox( 1.0f, 1.0f ); int index = 0; // distance joint { assert( index < e_count ); bodyDef.position = position; m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); float length = 2.0f; b2Vec2 pivot1 = { position.x, position.y + 1.0f + length }; b2Vec2 pivot2 = { position.x, position.y + 1.0f }; b2DistanceJointDef jointDef = b2DefaultDistanceJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = m_bodyIds[index]; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot1 ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot2 ); jointDef.length = length; b2CreateDistanceJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; // motor joint { assert( index < e_count ); bodyDef.position = position; m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); b2MotorJointDef jointDef = b2DefaultMotorJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = m_bodyIds[index]; jointDef.base.localFrameA.p = position; jointDef.maxVelocityForce = 200.0f; jointDef.maxVelocityTorque = 200.0f; b2CreateMotorJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; // prismatic joint { assert( index < e_count ); bodyDef.position = position; m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); b2Vec2 pivot = { position.x - 1.0f, position.y }; b2PrismaticJointDef jointDef = b2DefaultPrismaticJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = m_bodyIds[index]; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); b2CreatePrismaticJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; // revolute joint { assert( index < e_count ); bodyDef.position = position; m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); b2Vec2 pivot = { position.x - 1.0f, position.y }; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = m_bodyIds[index]; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); b2CreateRevoluteJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; // weld joint { assert( index < e_count ); bodyDef.position = position; m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); b2Vec2 pivot = { position.x - 1.0f, position.y }; b2WeldJointDef jointDef = b2DefaultWeldJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = m_bodyIds[index]; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.angularHertz = 1.0f; jointDef.angularDampingRatio = 0.5f; jointDef.linearHertz = 1.0f; jointDef.linearDampingRatio = 0.5f; b2CreateWeldJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; // wheel joint { assert( index < e_count ); bodyDef.position = position; m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); b2Vec2 pivot = { position.x - 1.0f, position.y }; b2WheelJointDef jointDef = b2DefaultWheelJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = m_bodyIds[index]; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.hertz = 1.0f; jointDef.dampingRatio = 0.7f; jointDef.lowerTranslation = -1.0f; jointDef.upperTranslation = 1.0f; jointDef.enableLimit = true; jointDef.enableMotor = true; jointDef.maxMotorTorque = 10.0f; jointDef.motorSpeed = 1.0f; b2CreateWheelJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 8.0f * fontSize; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 14.0f * fontSize, height ) ); ImGui::Begin( "Motion Locks", nullptr, ImGuiWindowFlags_NoResize ); if ( ImGui::Checkbox( "Lock Linear X", &m_motionLocks.linearX ) ) { for ( int i = 0; i < e_count; ++i ) { b2Body_SetMotionLocks( m_bodyIds[i], m_motionLocks ); b2Body_SetAwake( m_bodyIds[i], true ); } } if ( ImGui::Checkbox( "Lock Linear Y", &m_motionLocks.linearY ) ) { for ( int i = 0; i < e_count; ++i ) { b2Body_SetMotionLocks( m_bodyIds[i], m_motionLocks ); b2Body_SetAwake( m_bodyIds[i], true ); } } if ( ImGui::Checkbox( "Lock Angular Z", &m_motionLocks.angularZ ) ) { for ( int i = 0; i < e_count; ++i ) { b2Body_SetMotionLocks( m_bodyIds[i], m_motionLocks ); b2Body_SetAwake( m_bodyIds[i], true ); } } ImGui::End(); if ( glfwGetKey( m_context->window, GLFW_KEY_L ) == GLFW_PRESS ) { b2Body_ApplyLinearImpulseToCenter( m_bodyIds[0], { 100.0f, 0.0f }, true ); } } static Sample* Create( SampleContext* context ) { return new MotionLocks( context ); } b2BodyId m_bodyIds[e_count]; b2MotionLocks m_motionLocks; }; static int sampleMotionLocks = RegisterSample( "Joints", "Motion Locks", MotionLocks::Create ); // This sample shows how to break joints when the internal reaction force becomes large. class BreakableJoint : public Sample { public: enum { e_count = 6 }; explicit BreakableJoint( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 8.0f }; m_context->camera.zoom = 25.0f * 0.7f; } b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -40.0f, 0.0f }, { 40.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); for ( int i = 0; i < e_count; ++i ) { m_jointIds[i] = b2_nullJointId; } b2Vec2 position = { -12.5f, 10.0f }; bodyDef.type = b2_dynamicBody; bodyDef.enableSleep = false; b2Polygon box = b2MakeBox( 1.0f, 1.0f ); int index = 0; // distance joint { assert( index < e_count ); bodyDef.position = position; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); float length = 2.0f; b2Vec2 pivot1 = { position.x, position.y + 1.0f + length }; b2Vec2 pivot2 = { position.x, position.y + 1.0f }; b2DistanceJointDef jointDef = b2DefaultDistanceJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot1 ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot2 ); jointDef.length = length; jointDef.base.collideConnected = true; m_jointIds[index] = b2CreateDistanceJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; // motor joint { assert( index < e_count ); bodyDef.position = position; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2MotorJointDef jointDef = b2DefaultMotorJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = position; jointDef.maxVelocityForce = 1000.0f; jointDef.maxVelocityTorque = 20.0f; jointDef.base.collideConnected = true; m_jointIds[index] = b2CreateMotorJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; // prismatic joint { assert( index < e_count ); bodyDef.position = position; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2Vec2 pivot = { position.x - 1.0f, position.y }; b2PrismaticJointDef jointDef = b2DefaultPrismaticJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.base.collideConnected = true; m_jointIds[index] = b2CreatePrismaticJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; // revolute joint { assert( index < e_count ); bodyDef.position = position; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2Vec2 pivot = { position.x - 1.0f, position.y }; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.base.collideConnected = true; m_jointIds[index] = b2CreateRevoluteJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; // weld joint { assert( index < e_count ); bodyDef.position = position; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2Vec2 pivot = { position.x - 1.0f, position.y }; b2WeldJointDef jointDef = b2DefaultWeldJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.base.collideConnected = true; m_jointIds[index] = b2CreateWeldJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; // wheel joint { assert( index < e_count ); bodyDef.position = position; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2Vec2 pivot = { position.x - 1.0f, position.y }; b2WheelJointDef jointDef = b2DefaultWheelJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.hertz = 1.0f; jointDef.dampingRatio = 0.7f; jointDef.lowerTranslation = -1.0f; jointDef.upperTranslation = 1.0f; jointDef.enableLimit = true; jointDef.enableMotor = true; jointDef.maxMotorTorque = 10.0f; jointDef.motorSpeed = 1.0f; jointDef.base.collideConnected = true; m_jointIds[index] = b2CreateWheelJoint( m_worldId, &jointDef ); } position.x += 5.0f; ++index; m_breakForce = 1000.0f; } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 100.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Breakable Joint", nullptr, ImGuiWindowFlags_NoResize ); ImGui::SliderFloat( "break force", &m_breakForce, 0.0f, 10000.0f, "%.1f" ); b2Vec2 gravity = b2World_GetGravity( m_worldId ); if ( ImGui::SliderFloat( "gravity", &gravity.y, -50.0f, 50.0f, "%.1f" ) ) { b2World_SetGravity( m_worldId, gravity ); } ImGui::End(); } void Step() override { for ( int i = 0; i < e_count; ++i ) { if ( B2_IS_NULL( m_jointIds[i] ) ) { continue; } b2Vec2 force = b2Joint_GetConstraintForce( m_jointIds[i] ); if ( b2LengthSquared( force ) > m_breakForce * m_breakForce ) { b2DestroyJoint( m_jointIds[i], true ); m_jointIds[i] = b2_nullJointId; } else { b2Transform localFrame = b2Joint_GetLocalFrameA( m_jointIds[i] ); DrawWorldString( m_draw, m_camera, localFrame.p, b2_colorWhite, "(%.1f, %.1f)", force.x, force.y ); } } Sample::Step(); } static Sample* Create( SampleContext* context ) { return new BreakableJoint( context ); } b2JointId m_jointIds[e_count]; float m_breakForce; }; static int sampleBreakableJoint = RegisterSample( "Joints", "Breakable", BreakableJoint::Create ); // This sample shows how to measure joint separation. This is the unresolved constraint error. class JointSeparation : public Sample { public: enum { e_count = 5 }; explicit JointSeparation( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 8.0f }; m_context->camera.zoom = 25.0f; } b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -40.0f, 0.0f }, { 40.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); b2Vec2 position = { -20.0f, 10.0f }; bodyDef.type = b2_dynamicBody; bodyDef.enableSleep = false; b2Polygon box = b2MakeBox( 1.0f, 1.0f ); int index = 0; // distance joint { assert( index < e_count ); bodyDef.position = position; m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); float length = 2.0f; b2Vec2 pivot1 = { position.x, position.y + 1.0f + length }; b2Vec2 pivot2 = { position.x, position.y + 1.0f }; b2DistanceJointDef jointDef = b2DefaultDistanceJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = m_bodyIds[index]; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot1 ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot2 ); jointDef.length = length; jointDef.base.collideConnected = true; m_jointIds[index] = b2CreateDistanceJoint( m_worldId, &jointDef ); } position.x += 10.0f; ++index; // prismatic joint { assert( index < e_count ); bodyDef.position = position; m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); b2Vec2 pivot = { position.x - 1.0f, position.y }; b2PrismaticJointDef jointDef = b2DefaultPrismaticJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = m_bodyIds[index]; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.base.collideConnected = true; m_jointIds[index] = b2CreatePrismaticJoint( m_worldId, &jointDef ); } position.x += 10.0f; ++index; // revolute joint { assert( index < e_count ); bodyDef.position = position; m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); b2Vec2 pivot = { position.x - 1.0f, position.y }; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = m_bodyIds[index]; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.base.collideConnected = true; m_jointIds[index] = b2CreateRevoluteJoint( m_worldId, &jointDef ); } position.x += 10.0f; ++index; // weld joint { assert( index < e_count ); bodyDef.position = position; m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); b2Vec2 pivot = { position.x - 1.0f, position.y }; b2WeldJointDef jointDef = b2DefaultWeldJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = m_bodyIds[index]; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.base.collideConnected = true; m_jointIds[index] = b2CreateWeldJoint( m_worldId, &jointDef ); } position.x += 10.0f; ++index; // wheel joint { assert( index < e_count ); bodyDef.position = position; m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); b2Vec2 pivot = { position.x - 1.0f, position.y }; b2WheelJointDef jointDef = b2DefaultWheelJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = m_bodyIds[index]; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.hertz = 1.0f; jointDef.dampingRatio = 0.7f; jointDef.lowerTranslation = -1.0f; jointDef.upperTranslation = 1.0f; jointDef.enableLimit = true; jointDef.enableMotor = true; jointDef.maxMotorTorque = 10.0f; jointDef.motorSpeed = 1.0f; jointDef.base.collideConnected = true; m_jointIds[index] = b2CreateWheelJoint( m_worldId, &jointDef ); } m_impulse = 500.0f; m_jointHertz = 60.0f; m_jointDampingRatio = 2.0f; } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 14.0f * fontSize; ImGui::SetNextWindowPos( { 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize }, ImGuiCond_Once ); ImGui::SetNextWindowSize( { 20.0f * fontSize, height } ); ImGui::Begin( "Joint Separation", nullptr, ImGuiWindowFlags_NoResize ); b2Vec2 gravity = b2World_GetGravity( m_worldId ); if ( ImGui::SliderFloat( "gravity", &gravity.y, -500.0f, 500.0f, "%.0f" ) ) { b2World_SetGravity( m_worldId, gravity ); } if ( ImGui::Button( "impulse" ) ) { for ( int i = 0; i < e_count; ++i ) { b2Vec2 p = b2Body_GetWorldPoint( m_bodyIds[i], { 1.0f, 1.0f } ); b2Body_ApplyLinearImpulse( m_bodyIds[i], { m_impulse, -m_impulse }, p, true ); } } ImGui::SliderFloat( "magnitude", &m_impulse, 0.0f, 1000.0f, "%.0f" ); if ( ImGui::SliderFloat( "hertz", &m_jointHertz, 15.0f, 120.0f, "%.0f" ) ) { for ( int i = 0; i < e_count; ++i ) { b2Joint_SetConstraintTuning( m_jointIds[i], m_jointHertz, m_jointDampingRatio ); } } if ( ImGui::SliderFloat( "damping", &m_jointDampingRatio, 0.0f, 10.0f, "%.1f" ) ) { for ( int i = 0; i < e_count; ++i ) { b2Joint_SetConstraintTuning( m_jointIds[i], m_jointHertz, m_jointDampingRatio ); } } ImGui::End(); } void Step() override { for ( int i = 0; i < e_count; ++i ) { if ( B2_IS_NULL( m_jointIds[i] ) ) { continue; } float linear = b2Joint_GetLinearSeparation( m_jointIds[i] ); float angular = b2Joint_GetAngularSeparation( m_jointIds[i] ); b2Transform localFrame = b2Joint_GetLocalFrameA( m_jointIds[i] ); DrawWorldString( m_draw, m_camera, localFrame.p, b2_colorWhite, "%.2f m, %.1f deg", linear, 180.0f * angular / B2_PI ); } Sample::Step(); } static Sample* Create( SampleContext* context ) { return new JointSeparation( context ); } b2BodyId m_bodyIds[e_count]; b2JointId m_jointIds[e_count]; float m_impulse; float m_jointHertz; float m_jointDampingRatio; }; static int sampleJointSeparation = RegisterSample( "Joints", "Separation", JointSeparation::Create ); // This shows how you can implement a constraint outside of Box2D class UserConstraint : public Sample { public: explicit UserConstraint( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 3.0f, -1.0f }; m_context->camera.zoom = 25.0f * 0.15f; } b2Polygon box = b2MakeBox( 1.0f, 0.5f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.gravityScale = 1.0f; bodyDef.angularDamping = 0.5f; bodyDef.linearDamping = 0.2f; m_bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( m_bodyId, &shapeDef, &box ); m_impulses[0] = 0.0f; m_impulses[1] = 0.0f; } void Step() override { Sample::Step(); b2Transform axes = b2Transform_identity; DrawTransform( m_draw, axes, 1.0f ); if ( m_context->pause ) { return; } float timeStep = m_context->hertz > 0.0f ? 1.0f / m_context->hertz : 0.0f; if ( timeStep == 0.0f ) { return; } float invTimeStep = m_context->hertz; static float hertz = 3.0f; static float zeta = 0.7f; static float maxForce = 1000.0f; float omega = 2.0f * B2_PI * hertz; float sigma = 2.0f * zeta + timeStep * omega; float s = timeStep * omega * sigma; float impulseCoefficient = 1.0f / ( 1.0f + s ); float massCoefficient = s * impulseCoefficient; float biasCoefficient = omega / sigma; b2Vec2 localAnchors[2] = { { 1.0f, -0.5f }, { 1.0f, 0.5f } }; float mass = b2Body_GetMass( m_bodyId ); float invMass = mass < 0.0001f ? 0.0f : 1.0f / mass; float inertiaTensor = b2Body_GetRotationalInertia( m_bodyId ); float invI = inertiaTensor < 0.0001f ? 0.0f : 1.0f / inertiaTensor; b2Vec2 vB = b2Body_GetLinearVelocity( m_bodyId ); float omegaB = b2Body_GetAngularVelocity( m_bodyId ); b2Vec2 pB = b2Body_GetWorldCenterOfMass( m_bodyId ); for ( int i = 0; i < 2; ++i ) { b2Vec2 anchorA = { 3.0f, 0.0f }; b2Vec2 anchorB = b2Body_GetWorldPoint( m_bodyId, localAnchors[i] ); b2Vec2 deltaAnchor = b2Sub( anchorB, anchorA ); float slackLength = 1.0f; float length = b2Length( deltaAnchor ); float C = length - slackLength; if ( C < 0.0f || length < 0.001f ) { DrawLine( m_draw, anchorA, anchorB, b2_colorLightCyan ); m_impulses[i] = 0.0f; continue; } DrawLine( m_draw, anchorA, anchorB, b2_colorViolet ); b2Vec2 axis = b2Normalize( deltaAnchor ); b2Vec2 rB = b2Sub( anchorB, pB ); float Jb = b2Cross( rB, axis ); float K = invMass + Jb * invI * Jb; float invK = K < 0.0001f ? 0.0f : 1.0f / K; float Cdot = b2Dot( vB, axis ) + Jb * omegaB; float impulse = -massCoefficient * invK * ( Cdot + biasCoefficient * C ); float appliedImpulse = b2ClampFloat( impulse, -maxForce * timeStep, 0.0f ); vB = b2MulAdd( vB, invMass * appliedImpulse, axis ); omegaB += appliedImpulse * invI * Jb; m_impulses[i] = appliedImpulse; } b2Body_SetLinearVelocity( m_bodyId, vB ); b2Body_SetAngularVelocity( m_bodyId, omegaB ); DrawTextLine( "forces = %g, %g", m_impulses[0] * invTimeStep, m_impulses[1] * invTimeStep ); } static Sample* Create( SampleContext* context ) { return new UserConstraint( context ); } b2BodyId m_bodyId; float m_impulses[2]; }; static int sampleUserConstraintIndex = RegisterSample( "Joints", "User Constraint", UserConstraint::Create ); // This is a fun demo that shows off the wheel joint class Driving : public Sample { public: explicit Driving( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center.y = 5.0f; m_context->camera.zoom = 25.0f * 0.4f; m_context->debugDraw.drawJoints = false; } b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); b2Vec2 points[25]; int count = 24; // fill in reverse to match line list convention points[count--] = { -20.0f, -20.0f }; points[count--] = { -20.0f, 0.0f }; points[count--] = { 20.0f, 0.0f }; float hs[10] = { 0.25f, 1.0f, 4.0f, 0.0f, 0.0f, -1.0f, -2.0f, -2.0f, -1.25f, 0.0f }; float x = 20.0f, dx = 5.0f; for ( int j = 0; j < 2; ++j ) { for ( int i = 0; i < 10; ++i ) { float y2 = hs[i]; points[count--] = { x + dx, y2 }; x += dx; } } // flat before bridge points[count--] = { x + 40.0f, 0.0f }; points[count--] = { x + 40.0f, -20.0f }; assert( count == -1 ); b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = 25; chainDef.isLoop = true; b2CreateChain( groundId, &chainDef ); // flat after bridge x += 80.0f; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { x, 0.0f }, { x + 40.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); // jump ramp x += 40.0f; segment = { { x, 0.0f }, { x + 10.0f, 5.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); // final corner x += 20.0f; segment = { { x, 0.0f }, { x + 40.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); x += 40.0f; segment = { { x, 0.0f }, { x, 20.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Teeter { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 140.0f, 1.0f }; bodyDef.angularVelocity = 1.0f; bodyDef.type = b2_dynamicBody; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeBox( 10.0f, 0.25f ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2Vec2 pivot = bodyDef.position; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.lowerAngle = -8.0f * B2_PI / 180.0f; jointDef.upperAngle = 8.0f * B2_PI / 180.0f; jointDef.enableLimit = true; b2CreateRevoluteJoint( m_worldId, &jointDef ); } // Bridge { int N = 20; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Capsule capsule = { { -1.0f, 0.0f }, { 1.0f, 0.0f }, 0.125f }; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); b2BodyId prevBodyId = groundId; for ( int i = 0; i < N; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 161.0f + 2.0f * i, -0.125f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); b2Vec2 pivot = { 160.0f + 2.0f * i, -0.125f }; jointDef.base.bodyIdA = prevBodyId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); b2CreateRevoluteJoint( m_worldId, &jointDef ); prevBodyId = bodyId; } b2Vec2 pivot = { 160.0f + 2.0f * N, -0.125f }; jointDef.base.bodyIdA = prevBodyId; jointDef.base.bodyIdB = groundId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.enableMotor = true; jointDef.maxMotorTorque = 50.0f; b2CreateRevoluteJoint( m_worldId, &jointDef ); } // Boxes { b2Polygon box = b2MakeBox( 0.5f, 0.5f ); b2BodyId bodyId; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.25f; shapeDef.material.restitution = 0.25f; shapeDef.density = 0.25f; bodyDef.position = { 230.0f, 0.5f }; bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); bodyDef.position = { 230.0f, 1.5f }; bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); bodyDef.position = { 230.0f, 2.5f }; bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); bodyDef.position = { 230.0f, 3.5f }; bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); bodyDef.position = { 230.0f, 4.5f }; bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } // Car m_throttle = 0.0f; m_speed = 35.0f; m_torque = 5.0f; m_hertz = 5.0f; m_dampingRatio = 0.7f; m_car.Spawn( m_worldId, { 0.0f, 0.0f }, 1.0f, m_hertz, m_dampingRatio, m_torque, nullptr ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 10.0f * fontSize; ImGui::SetNextWindowPos( { 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize }, ImGuiCond_Once ); ImGui::SetNextWindowSize( { 16.0f * fontSize, height } ); ImGui::Begin( "Driving", nullptr, ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 8.0f * fontSize ); if ( ImGui::SliderFloat( "Spring Hertz", &m_hertz, 0.0f, 20.0f, "%.0f" ) ) { m_car.SetHertz( m_hertz ); } if ( ImGui::SliderFloat( "Damping Ratio", &m_dampingRatio, 0.0f, 10.0f, "%.1f" ) ) { m_car.SetDampingRadio( m_dampingRatio ); } if ( ImGui::SliderFloat( "Speed", &m_speed, 0.0f, 50.0f, "%.0f" ) ) { m_car.SetSpeed( m_throttle * m_speed ); } if ( ImGui::SliderFloat( "Torque", &m_torque, 0.0f, 10.0f, "%.1f" ) ) { m_car.SetTorque( m_torque ); } ImGui::PopItemWidth(); ImGui::End(); } void Step() override { if ( glfwGetKey( m_context->window, GLFW_KEY_A ) == GLFW_PRESS ) { m_throttle = 1.0f; m_car.SetSpeed( m_speed ); } if ( glfwGetKey( m_context->window, GLFW_KEY_S ) == GLFW_PRESS ) { m_throttle = 0.0f; m_car.SetSpeed( 0.0f ); } if ( glfwGetKey( m_context->window, GLFW_KEY_D ) == GLFW_PRESS ) { m_throttle = -1.0f; m_car.SetSpeed( -m_speed ); } DrawTextLine( "Keys: left = a, brake = s, right = d" ); b2Vec2 linearVelocity = b2Body_GetLinearVelocity( m_car.m_chassisId ); float kph = linearVelocity.x * 3.6f; DrawTextLine( "speed in kph: %.2g", kph ); b2Vec2 carPosition = b2Body_GetPosition( m_car.m_chassisId ); m_context->camera.center.x = carPosition.x; Sample::Step(); } static Sample* Create( SampleContext* context ) { return new Driving( context ); } Car m_car; float m_throttle; float m_hertz; float m_dampingRatio; float m_torque; float m_speed; }; static int sampleDriving = RegisterSample( "Joints", "Driving", Driving::Create ); class Ragdoll : public Sample { public: explicit Ragdoll( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 12.0f }; m_context->camera.zoom = 16.0f; // m_context->camera.m_center = { 0.0f, 26.0f }; // m_context->camera.m_zoom = 1.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } m_jointFrictionTorque = 0.03f; m_jointHertz = 5.0f; m_jointDampingRatio = 0.5f; m_human = {}; Spawn(); b2World_SetContactTuning( m_worldId, 240.0f, 0.0f, 2.0f ); } void Spawn() { CreateHuman( &m_human, m_worldId, { 0.0f, 25.0f }, 1.0f, m_jointFrictionTorque, m_jointHertz, m_jointDampingRatio, 1, nullptr, false ); // Human_ApplyRandomAngularImpulse( &m_human, 10.0f ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 10.0f * fontSize; ImGui::SetNextWindowPos( { 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize }, ImGuiCond_Once ); ImGui::SetNextWindowSize( { 14.0f * fontSize, height } ); ImGui::Begin( "Ragdoll", nullptr, ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 8.0f * fontSize ); if ( ImGui::SliderFloat( "Friction", &m_jointFrictionTorque, 0.0f, 1.0f, "%3.2f" ) ) { Human_SetJointFrictionTorque( &m_human, m_jointFrictionTorque ); } if ( ImGui::SliderFloat( "Hertz", &m_jointHertz, 0.0f, 10.0f, "%3.1f" ) ) { Human_SetJointSpringHertz( &m_human, m_jointHertz ); } if ( ImGui::SliderFloat( "Damping", &m_jointDampingRatio, 0.0f, 4.0f, "%3.1f" ) ) { Human_SetJointDampingRatio( &m_human, m_jointDampingRatio ); } if ( ImGui::Button( "Respawn" ) ) { DestroyHuman( &m_human ); Spawn(); } ImGui::PopItemWidth(); ImGui::End(); } static Sample* Create( SampleContext* context ) { return new Ragdoll( context ); } Human m_human; float m_jointFrictionTorque; float m_jointHertz; float m_jointDampingRatio; }; static int sampleRagdoll = RegisterSample( "Joints", "Ragdoll", Ragdoll::Create ); class SoftBody : public Sample { public: explicit SoftBody( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 5.0f }; m_context->camera.zoom = 25.0f * 0.25f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } m_donut.Create( m_worldId, { 0.0f, 10.0f }, 2.0f, 0, false, nullptr ); } static Sample* Create( SampleContext* context ) { return new SoftBody( context ); } Donut m_donut; }; static int sampleDonut = RegisterSample( "Joints", "Soft Body", SoftBody::Create ); class DoohickeyFarm : public Sample { public: explicit DoohickeyFarm( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 5.0f }; m_context->camera.zoom = 25.0f * 0.35f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); b2Polygon box = b2MakeOffsetBox( 1.0f, 1.0f, { 0.0f, 1.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } float y = 4.0f; for ( int i = 0; i < 4; ++i ) { Doohickey doohickey; doohickey.Spawn( m_worldId, { 0.0f, y }, 0.5f ); y += 2.0f; } } void Step() override { Sample::Step(); } static Sample* Create( SampleContext* context ) { return new DoohickeyFarm( context ); } }; static int sampleDoohickey = RegisterSample( "Joints", "Doohickey", DoohickeyFarm::Create ); class ScissorLift : public Sample { public: explicit ScissorLift( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 9.0f }; m_context->camera.zoom = 25.0f * 0.4f; } // Need 8 sub-steps for smoother operation m_context->subStepCount = 8; b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.sleepThreshold = 0.01f; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Capsule capsule = { { -2.5f, 0.0f }, { 2.5f, 0.0f }, 0.15f }; b2BodyId baseId1 = groundId; b2BodyId baseId2 = groundId; b2Vec2 baseAnchor1 = { -2.5f, 0.2f }; b2Vec2 baseAnchor2 = { 2.5f, 0.2f }; float y = 0.5f; b2BodyId linkId1; int N = 3; float constraintDampingRatio = 20.0f; float constraintHertz = 240.0f; for ( int i = 0; i < N; ++i ) { bodyDef.position = { 0.0f, y }; bodyDef.rotation = b2MakeRot( 0.15f ); b2BodyId bodyId1 = b2CreateBody( m_worldId, &bodyDef ); b2CreateCapsuleShape( bodyId1, &shapeDef, &capsule ); bodyDef.position = { 0.0f, y }; bodyDef.rotation = b2MakeRot( -0.15f ); b2BodyId bodyId2 = b2CreateBody( m_worldId, &bodyDef ); b2CreateCapsuleShape( bodyId2, &shapeDef, &capsule ); if ( i == 1 ) { linkId1 = bodyId2; } b2RevoluteJointDef revoluteDef = b2DefaultRevoluteJointDef(); // left pin revoluteDef.base.bodyIdA = baseId1; revoluteDef.base.bodyIdB = bodyId1; revoluteDef.base.localFrameA.p = baseAnchor1; revoluteDef.base.localFrameB.p = { -2.5f, 0.0f }; revoluteDef.base.collideConnected = ( i == 0 ) ? true : false; revoluteDef.base.constraintDampingRatio = constraintDampingRatio; revoluteDef.base.constraintHertz = constraintHertz; b2CreateRevoluteJoint( m_worldId, &revoluteDef ); // right pin if ( i == 0 ) { b2WheelJointDef wheelDef = b2DefaultWheelJointDef(); wheelDef.base.bodyIdA = baseId2; wheelDef.base.bodyIdB = bodyId2; wheelDef.base.localFrameA.p = baseAnchor2; wheelDef.base.localFrameB.p = { 2.5f, 0.0f }; wheelDef.enableSpring = false; wheelDef.base.collideConnected = true; wheelDef.base.constraintDampingRatio = constraintDampingRatio; wheelDef.base.constraintHertz = constraintHertz; b2CreateWheelJoint( m_worldId, &wheelDef ); } else { revoluteDef.base.bodyIdA = baseId2; revoluteDef.base.bodyIdB = bodyId2; revoluteDef.base.localFrameA.p = baseAnchor2; revoluteDef.base.localFrameB.p = { 2.5f, 0.0f }; revoluteDef.base.collideConnected = false; revoluteDef.base.constraintDampingRatio = constraintDampingRatio; revoluteDef.base.constraintHertz = constraintHertz; b2CreateRevoluteJoint( m_worldId, &revoluteDef ); } // middle pin revoluteDef.base.bodyIdA = bodyId1; revoluteDef.base.bodyIdB = bodyId2; revoluteDef.base.localFrameA.p = { 0.0f, 0.0f }; revoluteDef.base.localFrameB.p = { 0.0f, 0.0f }; revoluteDef.base.collideConnected = false; revoluteDef.base.constraintDampingRatio = constraintDampingRatio; revoluteDef.base.constraintHertz = constraintHertz; b2CreateRevoluteJoint( m_worldId, &revoluteDef ); baseId1 = bodyId2; baseId2 = bodyId1; baseAnchor1 = { -2.5f, 0.0f }; baseAnchor2 = { 2.5f, 0.0f }; y += 1.0f; } bodyDef.position = { 0.0f, y }; bodyDef.rotation = b2Rot_identity; b2BodyId platformId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 3.0f, 0.2f ); b2CreatePolygonShape( platformId, &shapeDef, &box ); // left pin b2RevoluteJointDef revoluteDef = b2DefaultRevoluteJointDef(); revoluteDef.base.bodyIdA = platformId; revoluteDef.base.bodyIdB = baseId1; revoluteDef.base.localFrameA.p = { -2.5f, -0.4f }; revoluteDef.base.localFrameB.p = baseAnchor1; revoluteDef.base.collideConnected = true; revoluteDef.base.constraintDampingRatio = constraintDampingRatio; revoluteDef.base.constraintHertz = constraintHertz; b2CreateRevoluteJoint( m_worldId, &revoluteDef ); // right pin b2WheelJointDef wheelDef = b2DefaultWheelJointDef(); wheelDef.base.bodyIdA = platformId; wheelDef.base.bodyIdB = baseId2; wheelDef.base.localFrameA.p = { 2.5f, -0.4f }; wheelDef.base.localFrameB.p = baseAnchor2; wheelDef.enableSpring = false; wheelDef.base.collideConnected = true; wheelDef.base.constraintDampingRatio = constraintDampingRatio; wheelDef.base.constraintHertz = constraintHertz; b2CreateWheelJoint( m_worldId, &wheelDef ); m_enableMotor = false; m_motorSpeed = 0.25f; m_motorForce = 2000.0f; b2DistanceJointDef distanceDef = b2DefaultDistanceJointDef(); distanceDef.base.bodyIdA = groundId; distanceDef.base.bodyIdB = linkId1; distanceDef.base.localFrameA.p = { -2.5f, 0.2f }; distanceDef.base.localFrameB.p = { 0.5f, 0.0f }; distanceDef.enableSpring = true; distanceDef.minLength = 0.2f; distanceDef.maxLength = 5.5f; distanceDef.enableLimit = true; distanceDef.enableMotor = m_enableMotor; distanceDef.motorSpeed = m_motorSpeed; distanceDef.maxMotorForce = m_motorForce; m_liftJointId = b2CreateDistanceJoint( m_worldId, &distanceDef ); Car car; car.Spawn( m_worldId, { 0.0f, y + 2.0f }, 1.0f, 3.0f, 0.7f, 0.0f, nullptr ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 140.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Scissor Lift", nullptr, ImGuiWindowFlags_NoResize ); if ( ImGui::Checkbox( "Motor", &m_enableMotor ) ) { b2DistanceJoint_EnableMotor( m_liftJointId, m_enableMotor ); b2Joint_WakeBodies( m_liftJointId ); } if ( ImGui::SliderFloat( "Max Force", &m_motorForce, 0.0f, 3000.0f, "%.0f" ) ) { b2DistanceJoint_SetMaxMotorForce( m_liftJointId, m_motorForce ); b2Joint_WakeBodies( m_liftJointId ); } if ( ImGui::SliderFloat( "Speed", &m_motorSpeed, -0.3f, 0.3f, "%.2f" ) ) { b2DistanceJoint_SetMotorSpeed( m_liftJointId, m_motorSpeed ); b2Joint_WakeBodies( m_liftJointId ); } ImGui::End(); } void Step() override { Sample::Step(); } static Sample* Create( SampleContext* context ) { return new ScissorLift( context ); } b2JointId m_liftJointId; float m_motorForce; float m_motorSpeed; bool m_enableMotor; }; static int sampleScissorLift = RegisterSample( "Joints", "Scissor Lift", ScissorLift::Create ); class GearLift : public Sample { public: explicit GearLift( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 6.0f }; m_context->camera.zoom = 7.0f; m_context->debugDraw.drawJoints = false; } b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); const char* path = "m 63.500002,201.08333 103.187498,0 1e-5,-37.04166 h -2.64584 l 0,34.39583 h -42.33333 v -2.64583 l " "-2.64584,-1e-5 v -2.64583 h -2.64583 v -2.64584 h -2.64584 v -2.64583 H 111.125 v -2.64583 h -2.64583 v " "-2.64583 h -2.64583 v -2.64584 l -2.64584,1e-5 v -2.64583 l -2.64583,-1e-5 V 174.625 h -2.645834 v -2.64584 l " "-2.645833,1e-5 v -2.64584 H 92.60417 v -2.64583 h -2.645834 v -2.64583 l -26.458334,0 0,37.04166"; b2Vec2 points[128]; b2Vec2 offset = { -120.0f, -200.0f }; float scale = 0.2f; int count = ParsePath( path, offset, points, 64, scale, false ); b2SurfaceMaterial material = b2DefaultSurfaceMaterial(); material.customColor = b2_colorDarkSeaGreen; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = count; chainDef.isLoop = true; chainDef.materials = &material; chainDef.materialCount = 1; b2CreateChain( groundId, &chainDef ); } float gearRadius = 1.0f; float toothHalfWidth = 0.09f; float toothHalfHeight = 0.06f; float toothRadius = 0.03f; float linkHalfLength = 0.07f; float linkRadius = 0.05f; float linkCount = 40; float doorHalfHeight = 1.5f; b2Vec2 gearPosition1 = { -4.25f, 9.75f }; b2Vec2 gearPosition2 = gearPosition1 + b2Vec2{ 2.0f, 1.0f }; b2Vec2 linkAttachPosition = gearPosition2 + b2Vec2{ gearRadius + 2.0f * toothHalfWidth + toothRadius, 0.0f }; b2Vec2 doorPosition = linkAttachPosition - b2Vec2{ 0.0f, 2.0f * linkCount * linkHalfLength + doorHalfHeight }; { b2Vec2 position = gearPosition1; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = position; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.1f; shapeDef.material.customColor = b2_colorSaddleBrown; b2Circle circle = { b2Vec2_zero, gearRadius }; b2CreateCircleShape( bodyId, &shapeDef, &circle ); int count = 16; float deltaAngle = 2.0f * B2_PI / 16; b2Rot dq = b2MakeRot( deltaAngle ); b2Vec2 center = { gearRadius + toothHalfHeight, 0.0f }; b2Rot rotation = b2Rot_identity; for ( int i = 0; i < count; ++i ) { b2Polygon tooth = b2MakeOffsetRoundedBox( toothHalfWidth, toothHalfHeight, center, rotation, toothRadius ); shapeDef.material.customColor = b2_colorGray; b2CreatePolygonShape( bodyId, &shapeDef, &tooth ); rotation = b2MulRot( dq, rotation ); center = b2RotateVector( rotation, { gearRadius + toothHalfHeight, 0.0f } ); } b2RevoluteJointDef revoluteDef = b2DefaultRevoluteJointDef(); m_motorTorque = 80.0f; m_motorSpeed = 0.0f; m_enableMotor = true; revoluteDef.base.bodyIdA = groundId; revoluteDef.base.bodyIdB = bodyId; revoluteDef.base.localFrameA.p = b2Body_GetLocalPoint( groundId, position ); revoluteDef.base.localFrameB.p = b2Vec2_zero; revoluteDef.enableMotor = m_enableMotor; revoluteDef.maxMotorTorque = m_motorTorque; revoluteDef.motorSpeed = m_motorSpeed; m_driverId = b2CreateRevoluteJoint( m_worldId, &revoluteDef ); } b2BodyId followerId; { b2Vec2 position = gearPosition2; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = position; followerId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.1f; shapeDef.material.customColor = b2_colorSaddleBrown; b2Circle circle = { b2Vec2_zero, gearRadius }; b2CreateCircleShape( followerId, &shapeDef, &circle ); int count = 16; float deltaAngle = 2.0f * B2_PI / 16; b2Rot dq = b2MakeRot( deltaAngle ); b2Vec2 center = { gearRadius + toothHalfWidth, 0.0f }; b2Rot rotation = b2Rot_identity; for ( int i = 0; i < count; ++i ) { b2Polygon tooth = b2MakeOffsetRoundedBox( toothHalfWidth, toothHalfHeight, center, rotation, toothRadius ); shapeDef.material.customColor = b2_colorGray; b2CreatePolygonShape( followerId, &shapeDef, &tooth ); rotation = b2MulRot( dq, rotation ); center = b2RotateVector( rotation, { gearRadius + toothHalfWidth, 0.0f } ); } b2RevoluteJointDef revoluteDef = b2DefaultRevoluteJointDef(); revoluteDef.base.bodyIdA = groundId; revoluteDef.base.bodyIdB = followerId; revoluteDef.base.localFrameA.p = b2Body_GetLocalPoint( groundId, position ); revoluteDef.base.localFrameA.q = b2MakeRot( 0.25f * B2_PI ); revoluteDef.base.localFrameB.p = b2Vec2_zero; revoluteDef.enableMotor = true; revoluteDef.maxMotorTorque = 0.5f; revoluteDef.lowerAngle = -0.3f * B2_PI; revoluteDef.upperAngle = 0.8f * B2_PI; revoluteDef.enableLimit = true; b2CreateRevoluteJoint( m_worldId, &revoluteDef ); } b2BodyId lastLinkId; { b2Capsule capsule = { { 0.0f, -linkHalfLength }, { 0.0f, linkHalfLength }, linkRadius }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 2.0f; shapeDef.material.customColor = b2_colorLightSteelBlue; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.maxMotorTorque = 0.05f; jointDef.enableMotor = true; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2Vec2 position = linkAttachPosition + b2Vec2{ 0.0f, -linkHalfLength }; int count = 40; b2BodyId prevBodyId = followerId; for ( int i = 0; i < count; ++i ) { bodyDef.position = position; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); b2Vec2 pivot = { position.x, position.y + linkHalfLength }; jointDef.base.bodyIdA = prevBodyId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.base.drawScale = 0.2f; b2CreateRevoluteJoint( m_worldId, &jointDef ); position.y -= 2.0f * linkHalfLength; prevBodyId = bodyId; } lastLinkId = prevBodyId; } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = doorPosition; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 0.15f, doorHalfHeight ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.1f; shapeDef.material.customColor = b2_colorDarkCyan; b2CreatePolygonShape( bodyId, &shapeDef, &box ); { b2Vec2 pivot = doorPosition + b2Vec2{ 0.0f, doorHalfHeight }; b2RevoluteJointDef revoluteDef = b2DefaultRevoluteJointDef(); revoluteDef.base.bodyIdA = lastLinkId; revoluteDef.base.bodyIdB = bodyId; revoluteDef.base.localFrameA.p = b2Body_GetLocalPoint( lastLinkId, pivot ); revoluteDef.base.localFrameB.p = { 0.0f, doorHalfHeight }; revoluteDef.enableMotor = true; revoluteDef.maxMotorTorque = 0.05f; b2CreateRevoluteJoint( m_worldId, &revoluteDef ); } { b2Vec2 localAxis = { 0.0f, 1.0f }; b2PrismaticJointDef jointDef = b2DefaultPrismaticJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( groundId, doorPosition ); jointDef.base.localFrameA.q = b2MakeRotFromUnitVector( localAxis ); jointDef.base.localFrameB.p = b2Vec2_zero; jointDef.base.localFrameB.q = b2MakeRotFromUnitVector( localAxis ); jointDef.maxMotorForce = 0.2f; jointDef.enableMotor = true; jointDef.base.collideConnected = true; b2CreatePrismaticJoint( m_worldId, &jointDef ); } } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.rollingResistance = 0.3f; b2HexColor colors[5] = { b2_colorGray, b2_colorGainsboro, b2_colorLightGray, b2_colorLightSlateGray, b2_colorDarkGray, }; float y = 4.25f; int xCount = 10, yCount = 20; for ( int i = 0; i < yCount; ++i ) { float x = -3.15f; for ( int j = 0; j < xCount; ++j ) { bodyDef.position = { x, y }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon poly = RandomPolygon( 0.1f ); poly.radius = RandomFloatRange( 0.01f, 0.02f ); int colorIndex = RandomIntRange( 0, 4 ); shapeDef.material.customColor = colors[colorIndex]; b2CreatePolygonShape( bodyId, &shapeDef, &poly ); x += 0.2f; } y += 0.2f; } } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 120.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 25.0f ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Gear Lift", nullptr, ImGuiWindowFlags_NoResize ); if ( ImGui::Checkbox( "Motor", &m_enableMotor ) ) { b2RevoluteJoint_EnableMotor( m_driverId, m_enableMotor ); b2Joint_WakeBodies( m_driverId ); } if ( ImGui::SliderFloat( "Max Torque", &m_motorTorque, 0.0f, 100.0f, "%.0f" ) ) { b2RevoluteJoint_SetMaxMotorTorque( m_driverId, m_motorTorque ); b2Joint_WakeBodies( m_driverId ); } if ( ImGui::SliderFloat( "Speed", &m_motorSpeed, -0.3f, 0.3f, "%.2f" ) ) { b2RevoluteJoint_SetMotorSpeed( m_driverId, m_motorSpeed ); b2Joint_WakeBodies( m_driverId ); } ImGui::End(); } void Step() override { if ( glfwGetKey( m_context->window, GLFW_KEY_A ) ) { m_motorSpeed = b2MaxFloat( -0.3f, m_motorSpeed - 0.01f ); b2RevoluteJoint_SetMotorSpeed( m_driverId, m_motorSpeed ); b2Joint_WakeBodies( m_driverId ); } if ( glfwGetKey( m_context->window, GLFW_KEY_D ) ) { m_motorSpeed = b2MinFloat( 0.3f, m_motorSpeed + 0.01f ); b2RevoluteJoint_SetMotorSpeed( m_driverId, m_motorSpeed ); b2Joint_WakeBodies( m_driverId ); } Sample::Step(); } static Sample* Create( SampleContext* context ) { return new GearLift( context ); } b2JointId m_driverId; float m_motorTorque; float m_motorSpeed; bool m_enableMotor; }; static int sampleGearLift = RegisterSample( "Joints", "Gear Lift", GearLift::Create ); // A top down door class Door : public Sample { public: explicit Door( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 0.0f }; m_context->camera.zoom = 4.0f; } b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, 0.0f }; groundId = b2CreateBody( m_worldId, &bodyDef ); } m_enableLimit = true; m_impulse = 50000.0f; m_translationError = 0.0f; m_jointHertz = 240.0f; m_jointDampingRatio = 1.0f; { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 0.0f, 1.5f }; bodyDef.gravityScale = 0.0f; m_doorId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1000.0f; b2Polygon box = b2MakeBox( 0.1f, 1.5f ); b2CreatePolygonShape( m_doorId, &shapeDef, &box ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = m_doorId; jointDef.base.localFrameA.p = { 0.0f, 0.0f }; jointDef.base.localFrameB.p = { 0.0f, -1.5f }; jointDef.base.constraintHertz = m_jointHertz; jointDef.base.constraintDampingRatio = m_jointDampingRatio; jointDef.targetAngle = 0.0f; jointDef.enableSpring = true; jointDef.hertz = 1.0f; jointDef.dampingRatio = 0.5f; jointDef.motorSpeed = 0.0f; jointDef.maxMotorTorque = 0.0f; jointDef.enableMotor = false; jointDef.lowerAngle = -0.5f * B2_PI; jointDef.upperAngle = 0.5f * B2_PI; jointDef.enableLimit = m_enableLimit; m_jointId = b2CreateRevoluteJoint( m_worldId, &jointDef ); } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 220.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Door", nullptr, ImGuiWindowFlags_NoResize ); if ( ImGui::Button( "impulse" ) ) { b2Vec2 p = b2Body_GetWorldPoint( m_doorId, { 0.0f, 1.5f } ); b2Body_ApplyLinearImpulse( m_doorId, { m_impulse, 0.0f }, p, true ); m_translationError = 0.0f; } ImGui::SliderFloat( "magnitude", &m_impulse, 1000.0f, 100000.0f, "%.0f" ); if ( ImGui::Checkbox( "limit", &m_enableLimit ) ) { b2RevoluteJoint_EnableLimit( m_jointId, m_enableLimit ); } if ( ImGui::SliderFloat( "hertz", &m_jointHertz, 15.0f, 480.0f, "%.0f" ) ) { b2Joint_SetConstraintTuning( m_jointId, m_jointHertz, m_jointDampingRatio ); } if ( ImGui::SliderFloat( "damping", &m_jointDampingRatio, 0.0f, 10.0f, "%.1f" ) ) { b2Joint_SetConstraintTuning( m_jointId, m_jointHertz, m_jointDampingRatio ); } ImGui::End(); } void Step() override { Sample::Step(); b2Vec2 p = b2Body_GetWorldPoint( m_doorId, { 0.0f, 1.5f } ); DrawPoint( m_draw, p, 5.0f, b2_colorDarkKhaki ); float translationError = b2Joint_GetLinearSeparation( m_jointId ); m_translationError = b2MaxFloat( m_translationError, translationError ); DrawTextLine( "translation error = %g", m_translationError ); } static Sample* Create( SampleContext* context ) { return new Door( context ); } b2BodyId m_doorId; b2JointId m_jointId; float m_impulse; float m_translationError; float m_jointHertz; float m_jointDampingRatio; bool m_enableLimit; }; static int sampleDoor = RegisterSample( "Joints", "Door", Door::Create ); class ScaleRagdoll : public Sample { public: explicit ScaleRagdoll( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 4.5f }; m_context->camera.zoom = 6.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeOffsetBox( 20.0f, 1.0f, { 0.0f, -1.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } m_scale = 1.0f; m_human = {}; Spawn(); } void Spawn() { float jointFrictionTorque = 0.03f; float jointHertz = 1.0f; float jointDampingRatio = 0.5f; CreateHuman( &m_human, m_worldId, { 0.0f, 5.0f }, m_scale, jointFrictionTorque, jointHertz, jointDampingRatio, 1, nullptr, false ); Human_ApplyRandomAngularImpulse( &m_human, 10.0f ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 4.0f * fontSize; ImGui::SetNextWindowPos( { 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize }, ImGuiCond_Once ); ImGui::SetNextWindowSize( { 20.0f * fontSize, height } ); ImGui::Begin( "Scale Ragdoll", nullptr, ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 15.0f * fontSize ); if ( ImGui::SliderFloat( "Scale", &m_scale, 0.1f, 10.0f, "%3.2f", ImGuiSliderFlags_ClampOnInput ) ) { Human_SetScale( &m_human, m_scale ); } ImGui::PopItemWidth(); ImGui::End(); } static Sample* Create( SampleContext* context ) { return new ScaleRagdoll( context ); } Human m_human; float m_scale; }; static int sampleScaleRagdoll = RegisterSample( "Joints", "Scale Ragdoll", ScaleRagdoll::Create ); ================================================ FILE: samples/sample_robustness.cpp ================================================ // SPDX-FileCopyrightText: 2022 Erin Catto // SPDX-License-Identifier: MIT #include "draw.h" #include "sample.h" #include "box2d/box2d.h" #include #include // Pyramid with heavy box on top class HighMassRatio1 : public Sample { public: explicit HighMassRatio1( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 3.0f, 14.0f }; m_context->camera.zoom = 25.0f; } float extent = 1.0f; { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeOffsetBox( 50.0f, 1.0f, { 0.0f, -1.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2Polygon box = b2MakeBox( extent, extent ); b2ShapeDef shapeDef = b2DefaultShapeDef(); for ( int j = 0; j < 3; ++j ) { int count = 10; float offset = -20.0f * extent + 2.0f * ( count + 1.0f ) * extent * j; float y = extent; while ( count > 0 ) { for ( int i = 0; i < count; ++i ) { float coeff = i - 0.5f * count; float yy = count == 1 ? y + 2.0f : y; bodyDef.position = { 2.0f * coeff * extent + offset, yy }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); shapeDef.density = count == 1 ? ( j + 1.0f ) * 100.0f : 1.0f; b2CreatePolygonShape( bodyId, &shapeDef, &box ); } --count; y += 2.0f * extent; } } } } static Sample* Create( SampleContext* context ) { return new HighMassRatio1( context ); } }; static int sampleHighMassRatio1 = RegisterSample( "Robustness", "HighMassRatio1", HighMassRatio1::Create ); // Big box on small boxes class HighMassRatio2 : public Sample { public: explicit HighMassRatio2( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 16.5f }; m_context->camera.zoom = 25.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeOffsetBox( 50.0f, 1.0f, { 0.0f, -1.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); float extent = 1.0f; b2Polygon smallBox = b2MakeBox( 0.5f * extent, 0.5f * extent ); b2Polygon bigBox = b2MakeBox( 10.0f * extent, 10.0f * extent ); { bodyDef.position = { -9.0f * extent, 0.5f * extent }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &smallBox ); } { bodyDef.position = { 9.0f * extent, 0.5f * extent }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &smallBox ); } { bodyDef.position = { 0.0f, ( 10.0f + 16.0f ) * extent }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &bigBox ); } } } static Sample* Create( SampleContext* context ) { return new HighMassRatio2( context ); } }; static int sampleHighMassRatio2 = RegisterSample( "Robustness", "HighMassRatio2", HighMassRatio2::Create ); // Big box on small triangles class HighMassRatio3 : public Sample { public: explicit HighMassRatio3( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 16.5f }; m_context->camera.zoom = 25.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeOffsetBox( 50.0f, 1.0f, { 0.0f, -1.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); float extent = 1.0f; b2Vec2 points[3] = { { -0.5f * extent, 0.0f }, { 0.5f * extent, 0.0f }, { 0.0f, 1.0f * extent } }; b2Hull hull = b2ComputeHull( points, 3 ); b2Polygon smallTriangle = b2MakePolygon( &hull, 0.0f ); b2Polygon bigBox = b2MakeBox( 10.0f * extent, 10.0f * extent ); { bodyDef.position = { -9.0f * extent, 0.5f * extent }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &smallTriangle ); } { bodyDef.position = { 9.0f * extent, 0.5f * extent }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &smallTriangle ); } { bodyDef.position = { 0.0f, ( 10.0f + 4.0f ) * extent }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &bigBox ); } } } static Sample* Create( SampleContext* context ) { return new HighMassRatio3( context ); } }; static int sampleHighMassRatio3 = RegisterSample( "Robustness", "HighMassRatio3", HighMassRatio3::Create ); class OverlapRecovery : public Sample { public: explicit OverlapRecovery( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 2.5f }; m_context->camera.zoom = 3.75f; } m_bodyIds = nullptr; m_bodyCount = 0; m_baseCount = 4; m_overlap = 0.25f; m_extent = 0.5f; m_speed = 3.0f; m_hertz = 30.0f; m_dampingRatio = 10.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -40.0f, 0.0f }, { 40.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); CreateScene(); } ~OverlapRecovery() override { free( m_bodyIds ); } void CreateScene() { for ( int i = 0; i < m_bodyCount; ++i ) { b2DestroyBody( m_bodyIds[i] ); } b2World_SetContactTuning( m_worldId, m_hertz, m_dampingRatio, m_speed ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2Polygon box = b2MakeBox( m_extent, m_extent ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; m_bodyCount = m_baseCount * ( m_baseCount + 1 ) / 2; m_bodyIds = (b2BodyId*)realloc( m_bodyIds, m_bodyCount * sizeof( b2BodyId ) ); int bodyIndex = 0; float fraction = 1.0f - m_overlap; float y = m_extent; for ( int i = 0; i < m_baseCount; ++i ) { float x = fraction * m_extent * ( i - m_baseCount ); for ( int j = i; j < m_baseCount; ++j ) { bodyDef.position = { x, y }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); m_bodyIds[bodyIndex++] = bodyId; x += 2.0f * fraction * m_extent; } y += 2.0f * fraction * m_extent; } assert( bodyIndex == m_bodyCount ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 210.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 220.0f, height ) ); ImGui::Begin( "Overlap Recovery", nullptr, ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 100.0f ); bool changed = false; changed = changed || ImGui::SliderFloat( "Extent", &m_extent, 0.1f, 1.0f, "%.1f" ); changed = changed || ImGui::SliderInt( "Base Count", &m_baseCount, 1, 10 ); changed = changed || ImGui::SliderFloat( "Overlap", &m_overlap, 0.0f, 1.0f, "%.2f" ); changed = changed || ImGui::SliderFloat( "Speed", &m_speed, 0.0f, 10.0f, "%.1f" ); changed = changed || ImGui::SliderFloat( "Hertz", &m_hertz, 0.0f, 240.0f, "%.f" ); changed = changed || ImGui::SliderFloat( "Damping Ratio", &m_dampingRatio, 0.0f, 20.0f, "%.1f" ); changed = changed || ImGui::Button( "Reset Scene" ); if ( changed ) { CreateScene(); } ImGui::PopItemWidth(); ImGui::End(); } static Sample* Create( SampleContext* context ) { return new OverlapRecovery( context ); } b2BodyId* m_bodyIds; int m_bodyCount; int m_baseCount; float m_overlap; float m_extent; float m_speed; float m_hertz; float m_dampingRatio; }; static int sampleOverlapRecovery = RegisterSample( "Robustness", "Overlap Recovery", OverlapRecovery::Create ); class TinyPyramid : public Sample { public: explicit TinyPyramid( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 0.8f }; m_context->camera.zoom = 1.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeOffsetBox( 5.0f, 1.0f, { 0.0f, -1.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } { m_extent = 0.025f; int baseCount = 30; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeSquare( m_extent ); for ( int i = 0; i < baseCount; ++i ) { float y = ( 2.0f * i + 1.0f ) * m_extent; for ( int j = i; j < baseCount; ++j ) { float x = ( i + 1.0f ) * m_extent + 2.0f * ( j - i ) * m_extent - baseCount * m_extent; bodyDef.position = { x, y }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } } } void Step() override { DrawTextLine( "%.1fcm squares", 200.0f * m_extent ); Sample::Step(); } static Sample* Create( SampleContext* context ) { return new TinyPyramid( context ); } float m_extent; }; static int sampleTinyPyramid = RegisterSample( "Robustness", "Tiny Pyramid", TinyPyramid::Create ); // High gravity and high mass ratio. This shows how to tune contact and joint stiffness values to // achieve an improved result at a high sub-step count. // There is still a fair bit of bounce with some settings. class Cart : public Sample { public: explicit Cart( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 1.0f }; m_context->camera.zoom = 1.5f; m_context->subStepCount = 12; } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, -1.0f }; b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon groundBox = b2MakeBox( 20.0f, 1.0f ); b2CreatePolygonShape( groundId, &shapeDef, &groundBox ); } b2World_SetGravity( m_worldId, { 0, -22.0f } ); m_contactHertz = 240.0f; m_contactDampingRatio = 10.0f; m_contactSpeed = 0.5f; b2World_SetContactTuning( m_worldId, m_contactHertz, m_contactDampingRatio, m_contactSpeed ); m_constraintHertz = 240.0f; m_constraintDampingRatio = 0.0f; m_chassisId = {}; m_wheelId1 = {}; m_wheelId2 = {}; m_jointId1 = {}; m_jointId2 = {}; CreateScene(); } void CreateScene() { if ( B2_IS_NON_NULL( m_chassisId ) ) { b2DestroyBody( m_chassisId ); } if ( B2_IS_NON_NULL( m_wheelId1 ) ) { b2DestroyBody( m_wheelId1 ); } if ( B2_IS_NON_NULL( m_wheelId2 ) ) { b2DestroyBody( m_wheelId2 ); } float yBase = 2.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 0.0f, yBase }; m_chassisId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1000.0f; b2Polygon box = b2MakeOffsetBox( 1.0f, 0.25f, { 0.0f, 0.25f }, b2Rot_identity ); b2CreatePolygonShape( m_chassisId, &shapeDef, &box ); shapeDef = b2DefaultShapeDef(); shapeDef.material.rollingResistance = 0.02f; shapeDef.density = 50.0f; b2Circle circle = { b2Vec2_zero, 0.1f }; bodyDef.position = { -0.9f, yBase - 0.15f }; m_wheelId1 = b2CreateBody( m_worldId, &bodyDef ); b2CreateCircleShape( m_wheelId1, &shapeDef, &circle ); bodyDef.position = { 0.9f, yBase - 0.15f }; m_wheelId2 = b2CreateBody( m_worldId, &bodyDef ); b2CreateCircleShape( m_wheelId2, &shapeDef, &circle ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.constraintHertz = 120.0f; jointDef.base.constraintDampingRatio = 0.0f; jointDef.base.bodyIdA = m_chassisId; jointDef.base.bodyIdB = m_wheelId1; jointDef.base.localFrameA.p = { -0.9f, -0.15f }; jointDef.base.localFrameB.p = { 0.0f, 0.0f }; m_jointId1 = b2CreateRevoluteJoint( m_worldId, &jointDef ); b2Joint_SetConstraintTuning( m_jointId1, m_constraintHertz, m_constraintDampingRatio ); jointDef.base.bodyIdA = m_chassisId; jointDef.base.bodyIdB = m_wheelId2; jointDef.base.localFrameA.p = { 0.9f, -0.15f }; jointDef.base.localFrameB.p = { 0.0f, 0.0f }; m_jointId2 = b2CreateRevoluteJoint( m_worldId, &jointDef ); b2Joint_SetConstraintTuning( m_jointId2, m_constraintHertz, m_constraintDampingRatio ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 240.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 320.0f, height ) ); ImGui::Begin( "Cart", nullptr, ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 200.0f ); 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 ) { b2World_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 ) { b2Joint_SetConstraintTuning( m_jointId1, m_constraintHertz, m_constraintDampingRatio ); b2Joint_SetConstraintTuning( m_jointId2, m_constraintHertz, m_constraintDampingRatio ); CreateScene(); } ImGui::PopItemWidth(); ImGui::End(); } static Sample* Create( SampleContext* context ) { return new Cart( context ); } b2BodyId m_chassisId; b2BodyId m_wheelId1; b2BodyId m_wheelId2; b2JointId m_jointId1; b2JointId m_jointId2; float m_contactHertz; float m_contactDampingRatio; float m_contactSpeed; float m_constraintHertz; float m_constraintDampingRatio; }; static int sampleCart = RegisterSample( "Robustness", "Cart", Cart::Create ); // Ensure prismatic joint stability when highly distorted class MultiplePrismatic : public Sample { public: explicit MultiplePrismatic( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 8.0f }; m_context->camera.zoom = 25.0f * 0.5f; } b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( m_worldId, &bodyDef ); } b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeBox( 0.5f, 0.5f ); b2PrismaticJointDef jointDef = b2DefaultPrismaticJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.localFrameA.p = { 0.0f, 0.0f }; jointDef.base.localFrameB.p = { 0.0f, -0.6f }; jointDef.base.drawScale = 1.0f; jointDef.base.constraintHertz = 240.0f; jointDef.lowerTranslation = -6.0f; jointDef.upperTranslation = 6.0f; jointDef.enableLimit = true; for ( int i = 0; i < 6; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, 0.6f + 1.2f * i }; bodyDef.type = b2_dynamicBody; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); jointDef.base.bodyIdB = bodyId; b2CreatePrismaticJoint( m_worldId, &jointDef ); jointDef.base.bodyIdA = bodyId; jointDef.base.localFrameA.p = { 0.0f, 0.6f }; } // Increase the mouse force m_mouseForceScale = 100000.0f; } static Sample* Create( SampleContext* context ) { return new MultiplePrismatic( context ); } }; static int sampleMultiplePrismatic = RegisterSample( "Robustness", "Multiple Prismatic", MultiplePrismatic::Create ); ================================================ FILE: samples/sample_shapes.cpp ================================================ // SPDX-FileCopyrightText: 2022 Erin Catto // SPDX-License-Identifier: MIT #include "draw.h" #include "random.h" #include "sample.h" #include "box2d/box2d.h" #include "box2d/math_functions.h" #include #include #include #include // extern "C" int b2_toiCalls; // extern "C" int b2_toiHitCount; class ChainShape : public Sample { public: enum ShapeType { e_circleShape = 0, e_capsuleShape, e_boxShape }; explicit ChainShape( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 0.0f }; m_context->camera.zoom = 25.0f * 1.75f; } m_groundId = b2_nullBodyId; m_bodyId = b2_nullBodyId; m_chainId = b2_nullChainId; m_shapeId = b2_nullShapeId; m_shapeType = e_circleShape; m_material = b2DefaultSurfaceMaterial(); m_material.friction = 0.2f; m_material.customColor = b2_colorSteelBlue; m_material.userMaterialId = 42; CreateScene(); Launch(); } void CreateScene() { if ( B2_IS_NON_NULL( m_groundId ) ) { b2DestroyBody( m_groundId ); } // https://betravis.github.io/shape-tools/path-to-polygon/ // b2Vec2 points[] = {{-20.58325, 14.54175}, {-21.90625, 15.8645}, {-24.552, 17.1875}, // {-27.198, 11.89575}, {-29.84375, 15.8645}, {-29.84375, 21.15625}, // {-25.875, 23.802}, {-20.58325, 25.125}, {-25.875, 29.09375}, // {-20.58325, 31.7395}, {-11.0089998, 23.2290001}, {-8.67700005, 21.15625}, // {-6.03125, 21.15625}, {-7.35424995, 29.09375}, {-3.38549995, 29.09375}, // {1.90625, 30.41675}, {5.875, 17.1875}, {11.16675, 25.125}, // {9.84375, 29.09375}, {13.8125, 31.7395}, {21.75, 30.41675}, // {28.3644981, 26.448}, {25.71875, 18.5105}, {24.3957481, 13.21875}, // {17.78125, 11.89575}, {15.1355, 7.92700005}, {5.875, 9.25}, // {1.90625, 11.89575}, {-3.25, 11.89575}, {-3.25, 9.9375}, // {-4.70825005, 9.25}, {-8.67700005, 9.25}, {-11.323, 11.89575}, // {-13.96875, 11.89575}, {-15.29175, 14.54175}, {-19.2605, 14.54175}}; b2Vec2 points[] = { { -56.885498, 12.8985004 }, { -56.885498, 16.2057495 }, { 56.885498, 16.2057495 }, { 56.885498, -16.2057514 }, { 51.5935059, -16.2057514 }, { 43.6559982, -10.9139996 }, { 35.7184982, -10.9139996 }, { 27.7809982, -10.9139996 }, { 21.1664963, -14.2212505 }, { 11.9059982, -16.2057514 }, { 0, -16.2057514 }, { -10.5835037, -14.8827496 }, { -17.1980019, -13.5597477 }, { -21.1665001, -12.2370014 }, { -25.1355019, -9.5909977 }, { -31.75, -3.63799858 }, { -38.3644981, 6.2840004 }, { -42.3334999, 9.59125137 }, { -47.625, 11.5755005 }, { -56.885498, 12.8985004 }, }; int count = sizeof( points ) / sizeof( points[0] ); // float scale = 0.25f; // b2Vec2 lower = {FLT_MAX, FLT_MAX}; // b2Vec2 upper = {-FLT_MAX, -FLT_MAX}; // for (int i = 0; i < count; ++i) //{ // points[i].x = 2.0f * scale * points[i].x; // points[i].y = -scale * points[i].y; // lower = b2Min(lower, points[i]); // upper = b2Max(upper, points[i]); //} // b2Vec2 center = b2MulSV(0.5f, b2Add(lower, upper)); // for (int i = 0; i < count; ++i) //{ // points[i] = b2Sub(points[i], center); // } // for (int i = 0; i < count / 2; ++i) //{ // b2Vec2 temp = points[i]; // points[i] = points[count - 1 - i]; // points[count - 1 - i] = temp; // } // printf("{"); // for (int i = 0; i < count; ++i) //{ // printf("{%.9g, %.9g},", points[i].x, points[i].y); // } // printf("};\n"); b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = count; chainDef.materials = &m_material; chainDef.materialCount = 1; chainDef.isLoop = true; b2BodyDef bodyDef = b2DefaultBodyDef(); m_groundId = b2CreateBody( m_worldId, &bodyDef ); m_chainId = b2CreateChain( m_groundId, &chainDef ); } void Launch() { if ( B2_IS_NON_NULL( m_bodyId ) ) { b2DestroyBody( m_bodyId ); } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -55.0f, 13.5f }; m_bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material = m_material; if ( m_shapeType == e_circleShape ) { b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; m_shapeId = b2CreateCircleShape( m_bodyId, &shapeDef, &circle ); } else if ( m_shapeType == e_capsuleShape ) { b2Capsule capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, 0.25f }; m_shapeId = b2CreateCapsuleShape( m_bodyId, &shapeDef, &capsule ); } else { float h = 0.5f; b2Polygon box = b2MakeBox( h, h ); m_shapeId = b2CreatePolygonShape( m_bodyId, &shapeDef, &box ); } // b2_toiCalls = 0; // b2_toiHitCount = 0; m_stepCount = 0; } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 155.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Chain Shape", nullptr, ImGuiWindowFlags_NoResize ); const char* shapeTypes[] = { "Circle", "Capsule", "Box" }; int shapeType = int( m_shapeType ); if ( ImGui::Combo( "Shape", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) ) { m_shapeType = ShapeType( shapeType ); Launch(); } if ( ImGui::SliderFloat( "Friction", &m_material.friction, 0.0f, 1.0f, "%.2f" ) ) { b2Shape_SetSurfaceMaterial( m_shapeId, &m_material ); b2Chain_SetSurfaceMaterial( m_chainId, &m_material, 1 ); } if ( ImGui::SliderFloat( "Restitution", &m_material.restitution, 0.0f, 2.0f, "%.1f" ) ) { b2Shape_SetSurfaceMaterial( m_shapeId, &m_material ); } if ( ImGui::Button( "Launch" ) ) { Launch(); } ImGui::End(); } void Step() override { Sample::Step(); DrawLine( m_draw, b2Vec2_zero, { 0.5f, 0.0f }, b2_colorRed ); DrawLine( m_draw, b2Vec2_zero, { 0.0f, 0.5f }, b2_colorGreen ); // DrawTextLine( "toi calls, hits = %d, %d", b2_toiCalls, b2_toiHitCount ); } static Sample* Create( SampleContext* context ) { return new ChainShape( context ); } b2BodyId m_groundId; b2BodyId m_bodyId; b2ChainId m_chainId; ShapeType m_shapeType; b2ShapeId m_shapeId; b2SurfaceMaterial m_material; }; static int sampleChainShape = RegisterSample( "Shapes", "Chain Shape", ChainShape::Create ); // This sample shows how careful creation of compound shapes leads to better simulation and avoids // objects getting stuck. // This also shows how to get the combined AABB for the body. class CompoundShapes : public Sample { public: explicit CompoundShapes( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 6.0f }; m_context->camera.zoom = 25.0f * 0.5f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { 50.0f, 0.0f }, { -50.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Table 1 { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -15.0f, 1.0f }; m_table1Id = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon top = b2MakeOffsetBox( 3.0f, 0.5f, { 0.0f, 3.5f }, b2Rot_identity ); b2Polygon leftLeg = b2MakeOffsetBox( 0.5f, 1.5f, { -2.5f, 1.5f }, b2Rot_identity ); b2Polygon rightLeg = b2MakeOffsetBox( 0.5f, 1.5f, { 2.5f, 1.5f }, b2Rot_identity ); b2CreatePolygonShape( m_table1Id, &shapeDef, &top ); b2CreatePolygonShape( m_table1Id, &shapeDef, &leftLeg ); b2CreatePolygonShape( m_table1Id, &shapeDef, &rightLeg ); } // Table 2 { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -5.0f, 1.0f }; m_table2Id = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon top = b2MakeOffsetBox( 3.0f, 0.5f, { 0.0f, 3.5f }, b2Rot_identity ); b2Polygon leftLeg = b2MakeOffsetBox( 0.5f, 2.0f, { -2.5f, 2.0f }, b2Rot_identity ); b2Polygon rightLeg = b2MakeOffsetBox( 0.5f, 2.0f, { 2.5f, 2.0f }, b2Rot_identity ); b2CreatePolygonShape( m_table2Id, &shapeDef, &top ); b2CreatePolygonShape( m_table2Id, &shapeDef, &leftLeg ); b2CreatePolygonShape( m_table2Id, &shapeDef, &rightLeg ); } // Spaceship 1 { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 5.0f, 1.0f }; m_ship1Id = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Vec2 vertices[3]; vertices[0] = { -2.0f, 0.0f }; vertices[1] = { 0.0f, 4.0f / 3.0f }; vertices[2] = { 0.0f, 4.0f }; b2Hull hull = b2ComputeHull( vertices, 3 ); b2Polygon left = b2MakePolygon( &hull, 0.0f ); vertices[0] = { 2.0f, 0.0f }; vertices[1] = { 0.0f, 4.0f / 3.0f }; vertices[2] = { 0.0f, 4.0f }; hull = b2ComputeHull( vertices, 3 ); b2Polygon right = b2MakePolygon( &hull, 0.0f ); b2CreatePolygonShape( m_ship1Id, &shapeDef, &left ); b2CreatePolygonShape( m_ship1Id, &shapeDef, &right ); } // Spaceship 2 { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 15.0f, 1.0f }; m_ship2Id = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Vec2 vertices[3]; vertices[0] = { -2.0f, 0.0f }; vertices[1] = { 1.0f, 2.0f }; vertices[2] = { 0.0f, 4.0f }; b2Hull hull = b2ComputeHull( vertices, 3 ); b2Polygon left = b2MakePolygon( &hull, 0.0f ); vertices[0] = { 2.0f, 0.0f }; vertices[1] = { -1.0f, 2.0f }; vertices[2] = { 0.0f, 4.0f }; hull = b2ComputeHull( vertices, 3 ); b2Polygon right = b2MakePolygon( &hull, 0.0f ); b2CreatePolygonShape( m_ship2Id, &shapeDef, &left ); b2CreatePolygonShape( m_ship2Id, &shapeDef, &right ); } m_drawBodyAABBs = false; } void Spawn() { // Table 1 obstruction { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = b2Body_GetPosition( m_table1Id ); bodyDef.rotation = b2Body_GetRotation( m_table1Id ); b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeOffsetBox( 4.0f, 0.1f, { 0.0f, 3.0f }, b2Rot_identity ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } // Table 2 obstruction { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = b2Body_GetPosition( m_table2Id ); bodyDef.rotation = b2Body_GetRotation( m_table2Id ); b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeOffsetBox( 4.0f, 0.1f, { 0.0f, 3.0f }, b2Rot_identity ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } // Ship 1 obstruction { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = b2Body_GetPosition( m_ship1Id ); bodyDef.rotation = b2Body_GetRotation( m_ship1Id ); // bodyDef.gravityScale = 0.0f; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Circle circle = { { 0.0f, 2.0f }, 0.5f }; b2CreateCircleShape( bodyId, &shapeDef, &circle ); } // Ship 2 obstruction { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = b2Body_GetPosition( m_ship2Id ); bodyDef.rotation = b2Body_GetRotation( m_ship2Id ); // bodyDef.gravityScale = 0.0f; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Circle circle = { { 0.0f, 2.0f }, 0.5f }; b2CreateCircleShape( bodyId, &shapeDef, &circle ); } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 100.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 180.0f, height ) ); ImGui::Begin( "Compound Shapes", nullptr, ImGuiWindowFlags_NoResize ); if ( ImGui::Button( "Intrude" ) ) { Spawn(); } ImGui::Checkbox( "Body AABBs", &m_drawBodyAABBs ); ImGui::End(); } void Step() override { Sample::Step(); if ( m_drawBodyAABBs ) { b2AABB aabb = b2Body_ComputeAABB( m_table1Id ); DrawBounds( m_draw, aabb, b2_colorYellow ); aabb = b2Body_ComputeAABB( m_table2Id ); DrawBounds( m_draw, aabb, b2_colorYellow ); aabb = b2Body_ComputeAABB( m_ship1Id ); DrawBounds( m_draw, aabb, b2_colorYellow ); aabb = b2Body_ComputeAABB( m_ship2Id ); DrawBounds( m_draw, aabb, b2_colorYellow ); } } static Sample* Create( SampleContext* context ) { return new CompoundShapes( context ); } b2BodyId m_table1Id; b2BodyId m_table2Id; b2BodyId m_ship1Id; b2BodyId m_ship2Id; bool m_drawBodyAABBs; }; static int sampleCompoundShape = RegisterSample( "Shapes", "Compound Shapes", CompoundShapes::Create ); class ShapeFilter : public Sample { public: enum CollisionBits { GROUND = 0x00000001, TEAM1 = 0x00000002, TEAM2 = 0x00000004, TEAM3 = 0x00000008, ALL_BITS = ( ~0u ) }; explicit ShapeFilter( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.zoom = 25.0f * 0.5f; m_context->camera.center = { 0.0f, 5.0f }; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.filter.categoryBits = GROUND; shapeDef.filter.maskBits = ALL_BITS; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 0.0f, 2.0f }; m_player1Id = b2CreateBody( m_worldId, &bodyDef ); bodyDef.position = { 0.0f, 5.0f }; m_player2Id = b2CreateBody( m_worldId, &bodyDef ); bodyDef.position = { 0.0f, 8.0f }; m_player3Id = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 2.0f, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.filter.categoryBits = TEAM1; shapeDef.filter.maskBits = GROUND | TEAM2 | TEAM3; m_shape1Id = b2CreatePolygonShape( m_player1Id, &shapeDef, &box ); shapeDef.filter.categoryBits = TEAM2; shapeDef.filter.maskBits = GROUND | TEAM1 | TEAM3; m_shape2Id = b2CreatePolygonShape( m_player2Id, &shapeDef, &box ); shapeDef.filter.categoryBits = TEAM3; shapeDef.filter.maskBits = GROUND | TEAM1 | TEAM2; m_shape3Id = b2CreatePolygonShape( m_player3Id, &shapeDef, &box ); } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 240.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Shape Filter", nullptr, ImGuiWindowFlags_NoResize ); ImGui::Text( "Player 1 Collides With" ); { b2Filter filter1 = b2Shape_GetFilter( m_shape1Id ); bool team2 = ( filter1.maskBits & TEAM2 ) == TEAM2; if ( ImGui::Checkbox( "Team 2##1", &team2 ) ) { if ( team2 ) { filter1.maskBits |= TEAM2; } else { filter1.maskBits &= ~TEAM2; } b2Shape_SetFilter( m_shape1Id, filter1 ); } bool team3 = ( filter1.maskBits & TEAM3 ) == TEAM3; if ( ImGui::Checkbox( "Team 3##1", &team3 ) ) { if ( team3 ) { filter1.maskBits |= TEAM3; } else { filter1.maskBits &= ~TEAM3; } b2Shape_SetFilter( m_shape1Id, filter1 ); } } ImGui::Separator(); ImGui::Text( "Player 2 Collides With" ); { b2Filter filter2 = b2Shape_GetFilter( m_shape2Id ); bool team1 = ( filter2.maskBits & TEAM1 ) == TEAM1; if ( ImGui::Checkbox( "Team 1##2", &team1 ) ) { if ( team1 ) { filter2.maskBits |= TEAM1; } else { filter2.maskBits &= ~TEAM1; } b2Shape_SetFilter( m_shape2Id, filter2 ); } bool team3 = ( filter2.maskBits & TEAM3 ) == TEAM3; if ( ImGui::Checkbox( "Team 3##2", &team3 ) ) { if ( team3 ) { filter2.maskBits |= TEAM3; } else { filter2.maskBits &= ~TEAM3; } b2Shape_SetFilter( m_shape2Id, filter2 ); } } ImGui::Separator(); ImGui::Text( "Player 3 Collides With" ); { b2Filter filter3 = b2Shape_GetFilter( m_shape3Id ); bool team1 = ( filter3.maskBits & TEAM1 ) == TEAM1; if ( ImGui::Checkbox( "Team 1##3", &team1 ) ) { if ( team1 ) { filter3.maskBits |= TEAM1; } else { filter3.maskBits &= ~TEAM1; } b2Shape_SetFilter( m_shape3Id, filter3 ); } bool team2 = ( filter3.maskBits & TEAM2 ) == TEAM2; if ( ImGui::Checkbox( "Team 2##3", &team2 ) ) { if ( team2 ) { filter3.maskBits |= TEAM2; } else { filter3.maskBits &= ~TEAM2; } b2Shape_SetFilter( m_shape3Id, filter3 ); } } ImGui::End(); } void Step() override { Sample::Step(); b2Vec2 p1 = b2Body_GetPosition( m_player1Id ); DrawWorldString( m_draw, m_camera, { p1.x - 0.5f, p1.y }, b2_colorWhite, "player 1" ); b2Vec2 p2 = b2Body_GetPosition( m_player2Id ); DrawWorldString( m_draw, m_camera, { p2.x - 0.5f, p2.y }, b2_colorWhite, "player 2" ); b2Vec2 p3 = b2Body_GetPosition( m_player3Id ); DrawWorldString( m_draw, m_camera, { p3.x - 0.5f, p3.y }, b2_colorWhite, "player 3" ); } static Sample* Create( SampleContext* context ) { return new ShapeFilter( context ); } b2BodyId m_player1Id; b2BodyId m_player2Id; b2BodyId m_player3Id; b2ShapeId m_shape1Id; b2ShapeId m_shape2Id; b2ShapeId m_shape3Id; }; static int sampleShapeFilter = RegisterSample( "Shapes", "Filter", ShapeFilter::Create ); // This shows how to use custom filtering class CustomFilter : public Sample { public: enum { e_count = 10 }; explicit CustomFilter( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 5.0f }; m_context->camera.zoom = 10.0f; } // Register custom filter b2World_SetCustomFilterCallback( m_worldId, CustomFilterStatic, this ); { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2Segment segment = { { -40.0f, 0.0f }, { 40.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreateSegmentShape( groundId, &shapeDef, &segment ); } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.enableCustomFiltering = true; b2Polygon box = b2MakeSquare( 1.0f ); float x = -e_count; for ( int i = 0; i < e_count; ++i ) { bodyDef.position = { x, 5.0f }; m_bodyIds[i] = b2CreateBody( m_worldId, &bodyDef ); shapeDef.userData = reinterpret_cast( intptr_t( i + 1 ) ); m_shapeIds[i] = b2CreatePolygonShape( m_bodyIds[i], &shapeDef, &box ); x += 2.0f; } } void Step() override { DrawTextLine( "Custom filter disables collision between odd and even shapes" ); Sample::Step(); for ( int i = 0; i < e_count; ++i ) { b2Vec2 p = b2Body_GetPosition( m_bodyIds[i] ); DrawWorldString( m_draw, m_camera, { p.x, p.y }, b2_colorWhite, "%d", i ); } } bool ShouldCollide( b2ShapeId shapeIdA, b2ShapeId shapeIdB ) { void* userDataA = b2Shape_GetUserData( shapeIdA ); void* userDataB = b2Shape_GetUserData( shapeIdB ); if ( userDataA == nullptr || userDataB == nullptr ) { return true; } int indexA = static_cast( reinterpret_cast( userDataA ) ); int indexB = static_cast( reinterpret_cast( userDataB ) ); return ( ( indexA & 1 ) + ( indexB & 1 ) ) != 1; } static bool CustomFilterStatic( b2ShapeId shapeIdA, b2ShapeId shapeIdB, void* context ) { CustomFilter* customFilter = static_cast( context ); return customFilter->ShouldCollide( shapeIdA, shapeIdB ); } static Sample* Create( SampleContext* context ) { return new CustomFilter( context ); } b2BodyId m_bodyIds[e_count]; b2ShapeId m_shapeIds[e_count]; }; static int sampleCustomFilter = RegisterSample( "Shapes", "Custom Filter", CustomFilter::Create ); // Restitution is approximate since Box2D uses speculative collision class Restitution : public Sample { public: enum ShapeType { e_circleShape = 0, e_boxShape }; explicit Restitution( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 4.0f, 17.0f }; m_context->camera.zoom = 27.5f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); float h = 1.0f * m_count; b2Segment segment = { { -h, 0.0f }, { h, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreateSegmentShape( groundId, &shapeDef, &segment ); } m_shapeType = e_circleShape; CreateBodies(); } void CreateBodies() { for ( int i = 0; i < m_count; ++i ) { if ( B2_IS_NON_NULL( m_bodyIds[i] ) ) { b2DestroyBody( m_bodyIds[i] ); m_bodyIds[i] = b2_nullBodyId; } } b2Circle circle = {}; circle.radius = 0.5f; b2Polygon box = b2MakeBox( 0.5f, 0.5f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.material.restitution = 0.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; float dr = 1.0f / ( m_count > 1 ? m_count - 1 : 1 ); float x = -1.0f * ( m_count - 1 ); float dx = 2.0f; for ( int i = 0; i < m_count; ++i ) { bodyDef.position = { x, 40.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); m_bodyIds[i] = bodyId; if ( m_shapeType == e_circleShape ) { b2CreateCircleShape( bodyId, &shapeDef, &circle ); } else { b2CreatePolygonShape( bodyId, &shapeDef, &box ); } shapeDef.material.restitution += dr; x += dx; } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 100.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Restitution", nullptr, ImGuiWindowFlags_NoResize ); bool changed = false; const char* shapeTypes[] = { "Circle", "Box" }; int shapeType = int( m_shapeType ); changed = changed || ImGui::Combo( "Shape", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ); m_shapeType = ShapeType( shapeType ); changed = changed || ImGui::Button( "Reset" ); if ( changed ) { CreateBodies(); } ImGui::End(); } static Sample* Create( SampleContext* context ) { return new Restitution( context ); } static constexpr int m_count = 40; b2BodyId m_bodyIds[m_count] = {}; ShapeType m_shapeType; }; static int sampleIndex = RegisterSample( "Shapes", "Restitution", Restitution::Create ); class Friction : public Sample { public: explicit Friction( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 14.0f }; m_context->camera.zoom = 25.0f * 0.6f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.2f; b2Segment segment = { { -40.0f, 0.0f }, { 40.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); b2Polygon box = b2MakeOffsetBox( 13.0f, 0.25f, { -4.0f, 22.0f }, b2MakeRot( -0.25f ) ); b2CreatePolygonShape( groundId, &shapeDef, &box ); box = b2MakeOffsetBox( 0.25f, 1.0f, { 10.5f, 19.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); box = b2MakeOffsetBox( 13.0f, 0.25f, { 4.0f, 14.0f }, b2MakeRot( 0.25f ) ); b2CreatePolygonShape( groundId, &shapeDef, &box ); box = b2MakeOffsetBox( 0.25f, 1.0f, { -10.5f, 11.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); box = b2MakeOffsetBox( 13.0f, 0.25f, { -4.0f, 6.0f }, b2MakeRot( -0.25f ) ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } { b2Polygon box = b2MakeBox( 0.5f, 0.5f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 25.0f; float friction[5] = { 0.75f, 0.5f, 0.35f, 0.1f, 0.0f }; for ( int i = 0; i < 5; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -15.0f + 4.0f * i, 28.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); shapeDef.material.friction = friction[i]; b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } } static Sample* Create( SampleContext* context ) { return new Friction( context ); } }; static int sampleFriction = RegisterSample( "Shapes", "Friction", Friction::Create ); class RollingResistance : public Sample { public: explicit RollingResistance( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 5.0f, 20.0f }; m_context->camera.zoom = 27.5f; } m_lift = 0.0f; m_resistScale = 0.02f; CreateScene(); } void CreateScene() { b2Circle circle = { b2Vec2_zero, 0.5f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); for ( int i = 0; i < 20; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2Segment segment = { { -40.0f, 2.0f * i }, { 40.0f, 2.0f * i + m_lift } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); bodyDef.type = b2_dynamicBody; bodyDef.position = { -39.5f, 2.0f * i + 0.75f }; bodyDef.angularVelocity = -10.0f; bodyDef.linearVelocity = { 5.0f, 0.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); shapeDef.material.rollingResistance = m_resistScale * i; b2CreateCircleShape( bodyId, &shapeDef, &circle ); } } void Keyboard( int key ) override { switch ( key ) { case GLFW_KEY_1: m_lift = 0.0f; CreateWorld(); CreateScene(); break; case GLFW_KEY_2: m_lift = 5.0f; CreateWorld(); CreateScene(); break; case GLFW_KEY_3: m_lift = -5.0f; CreateWorld(); CreateScene(); break; default: Sample::Keyboard( key ); break; } } void Step() override { Sample::Step(); for ( int i = 0; i < 20; ++i ) { DrawWorldString( m_draw, m_camera, { -41.5f, 2.0f * i + 1.0f }, b2_colorWhite, "%.2f", m_resistScale * i ); } } static Sample* Create( SampleContext* context ) { return new RollingResistance( context ); } float m_resistScale; float m_lift; }; static int sampleRollingResistance = RegisterSample( "Shapes", "Rolling Resistance", RollingResistance::Create ); class ConveyorBelt : public Sample { public: explicit ConveyorBelt( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 2.0f, 7.5f }; m_context->camera.zoom = 12.0f; } // Ground { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Platform { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { -5.0f, 5.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeRoundedBox( 10.0f, 0.25f, 0.25f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.8f; shapeDef.material.tangentSpeed = 2.0f; b2CreatePolygonShape( bodyId, &shapeDef, &box ); } // Boxes b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon cube = b2MakeSquare( 0.5f ); for ( int i = 0; i < 5; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -10.0f + 2.0f * i, 7.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &cube ); } } static Sample* Create( SampleContext* context ) { return new ConveyorBelt( context ); } }; static int sampleConveyorBelt = RegisterSample( "Shapes", "Conveyor Belt", ConveyorBelt::Create ); class TangentSpeed : public Sample { public: explicit TangentSpeed( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 60.0f, -15.0f }; m_context->camera.zoom = 38.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); // const char* path = "M 613.8334,185.20833 H 500.06255 L 470.95838,182.5625 444.50004,174.625 418.04171,161.39583 " // "394.2292,140.22917 h " // "-13.22916 v 44.97916 H 68.791712 V 0 h -21.16671 v 206.375 l 566.208398,-1e-5 z"; const char* path = "m 613.8334,185.20833 -42.33338,0 h -37.04166 l -34.39581,0 -29.10417,-2.64583 -26.45834,-7.9375 " "-26.45833,-13.22917 -23.81251,-21.16666 h -13.22916 v 44.97916 H 68.791712 V 0 h -21.16671 v " "206.375 l 566.208398,-1e-5 z"; b2Vec2 offset = { -47.375002f, 0.25f }; float scale = 0.2f; b2Vec2 points[20] = {}; int count = ParsePath( path, offset, points, 20, scale, true ); b2SurfaceMaterial materials[20] = {}; for ( int i = 0; i < 20; ++i ) { materials[i].friction = 0.6f; } materials[0].tangentSpeed = -10.0; materials[0].customColor = b2_colorDarkBlue; materials[1].tangentSpeed = -20.0; materials[1].customColor = b2_colorDarkCyan; materials[2].tangentSpeed = -30.0; materials[2].customColor = b2_colorDarkGoldenRod; materials[3].tangentSpeed = -40.0; materials[3].customColor = b2_colorDarkGray; materials[4].tangentSpeed = -50.0; materials[4].customColor = b2_colorDarkGreen; materials[5].tangentSpeed = -60.0; materials[5].customColor = b2_colorDarkKhaki; materials[6].tangentSpeed = -70.0; materials[6].customColor = b2_colorDarkMagenta; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = count; chainDef.isLoop = true; chainDef.materials = materials; chainDef.materialCount = count; b2CreateChain( groundId, &chainDef ); m_friction = 0.6f; m_rollingResistance = 0.3f; } } b2BodyId DropBall() { b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 110.0f, -30.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = m_friction; shapeDef.material.rollingResistance = m_rollingResistance; b2CreateCircleShape( bodyId, &shapeDef, &circle ); return bodyId; } void Reset() { int count = int( m_bodyIds.size() ); for ( int i = 0; i < count; ++i ) { b2DestroyBody( m_bodyIds[i] ); } m_bodyIds.clear(); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 80.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 260.0f, height ) ); ImGui::Begin( "Ball Parameters", nullptr, ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 140.0f ); if ( ImGui::SliderFloat( "Friction", &m_friction, 0.0f, 2.0f, "%.2f" ) ) { Reset(); } if ( ImGui::SliderFloat( "Rolling Resistance", &m_rollingResistance, 0.0f, 1.0f, "%.2f" ) ) { Reset(); } ImGui::End(); } void Step() override { if ( m_stepCount % 25 == 0 && m_bodyIds.size() < m_totalCount && m_context->pause == false ) { b2BodyId id = DropBall(); m_bodyIds.push_back( id ); } Sample::Step(); } static Sample* Create( SampleContext* context ) { return new TangentSpeed( context ); } static constexpr int m_totalCount = 200; std::vector m_bodyIds; float m_friction; float m_rollingResistance; }; static int sampleTangentSpeed = RegisterSample( "Shapes", "Tangent Speed", TangentSpeed::Create ); // This sample shows how to modify the geometry on an existing shape. This is only supported on // dynamic and kinematic shapes because static shapes don't look for new collisions. class ModifyGeometry : public Sample { public: explicit ModifyGeometry( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.zoom = 25.0f * 0.25f; m_context->camera.center = { 0.0f, 5.0f }; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeOffsetBox( 10.0f, 1.0f, { 0.0f, -1.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 0.0f, 4.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeBox( 1.0f, 1.0f ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } { m_shapeType = b2_circleShape; m_scale = 1.0f; m_circle = { { 0.0f, 0.0f }, 0.5f }; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_kinematicBody; bodyDef.position = { 0.0f, 1.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); m_shapeId = b2CreateCircleShape( bodyId, &shapeDef, &m_circle ); } } void UpdateShape() { switch ( m_shapeType ) { case b2_circleShape: m_circle = { { 0.0f, 0.0f }, 0.5f * m_scale }; b2Shape_SetCircle( m_shapeId, &m_circle ); break; case b2_capsuleShape: m_capsule = { { -0.5f * m_scale, 0.0f }, { 0.0f, 0.5f * m_scale }, 0.5f * m_scale }; b2Shape_SetCapsule( m_shapeId, &m_capsule ); break; case b2_segmentShape: m_segment = { { -0.5f * m_scale, 0.0f }, { 0.75f * m_scale, 0.0f } }; b2Shape_SetSegment( m_shapeId, &m_segment ); break; case b2_polygonShape: m_polygon = b2MakeBox( 0.5f * m_scale, 0.75f * m_scale ); b2Shape_SetPolygon( m_shapeId, &m_polygon ); break; default: assert( false ); break; } b2BodyId bodyId = b2Shape_GetBody( m_shapeId ); b2Body_ApplyMassFromShapes( bodyId ); } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 230.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); ImGui::Begin( "Modify Geometry", nullptr, ImGuiWindowFlags_NoResize ); if ( ImGui::RadioButton( "Circle", m_shapeType == b2_circleShape ) ) { m_shapeType = b2_circleShape; UpdateShape(); } if ( ImGui::RadioButton( "Capsule", m_shapeType == b2_capsuleShape ) ) { m_shapeType = b2_capsuleShape; UpdateShape(); } if ( ImGui::RadioButton( "Segment", m_shapeType == b2_segmentShape ) ) { m_shapeType = b2_segmentShape; UpdateShape(); } if ( ImGui::RadioButton( "Polygon", m_shapeType == b2_polygonShape ) ) { m_shapeType = b2_polygonShape; UpdateShape(); } if ( ImGui::SliderFloat( "Scale", &m_scale, 0.1f, 10.0f, "%.2f" ) ) { UpdateShape(); } b2BodyId bodyId = b2Shape_GetBody( m_shapeId ); b2BodyType bodyType = b2Body_GetType( bodyId ); if ( ImGui::RadioButton( "Static", bodyType == b2_staticBody ) ) { b2Body_SetType( bodyId, b2_staticBody ); } if ( ImGui::RadioButton( "Kinematic", bodyType == b2_kinematicBody ) ) { b2Body_SetType( bodyId, b2_kinematicBody ); } if ( ImGui::RadioButton( "Dynamic", bodyType == b2_dynamicBody ) ) { b2Body_SetType( bodyId, b2_dynamicBody ); } ImGui::End(); } void Step() override { Sample::Step(); } static Sample* Create( SampleContext* context ) { return new ModifyGeometry( context ); } b2ShapeId m_shapeId; b2ShapeType m_shapeType; float m_scale; union { b2Circle m_circle; b2Capsule m_capsule; b2Segment m_segment; b2Polygon m_polygon; }; }; static int sampleModifyGeometry = RegisterSample( "Shapes", "Modify Geometry", ModifyGeometry::Create ); // Shows how to link to chain shapes together. This is a useful technique for building large game levels with smooth collision. class ChainLink : public Sample { public: explicit ChainLink( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 5.0f }; m_context->camera.zoom = 25.0f * 0.5f; } b2Vec2 points1[] = { { 40.0f, 1.0f }, { 0.0f, 0.0f }, { -40.0f, 0.0f }, { -40.0f, -1.0f }, { 0.0f, -1.0f }, { 40.0f, -1.0f } }; b2Vec2 points2[] = { { -40.0f, -1.0f }, { 0.0f, -1.0f }, { 40.0f, -1.0f }, { 40.0f, 0.0f }, { 0.0f, 0.0f }, { -40.0f, 0.0f } }; int count1 = std::size( points1 ); int count2 = std::size( points2 ); b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); { b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points1; chainDef.count = count1; chainDef.isLoop = false; b2CreateChain( groundId, &chainDef ); } { b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points2; chainDef.count = count2; chainDef.isLoop = false; b2CreateChain( groundId, &chainDef ); } bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); { bodyDef.position = { -5.0f, 2.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; b2CreateCircleShape( bodyId, &shapeDef, &circle ); } { bodyDef.position = { 0.0f, 2.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Capsule capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, 0.25f }; b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); } { bodyDef.position = { 5.0f, 2.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); float h = 0.5f; b2Polygon box = b2MakeBox( h, h ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } void Step() override { Sample::Step(); DrawTextLine( "This shows how to link together two chain shapes" ); } static Sample* Create( SampleContext* context ) { return new ChainLink( context ); } }; static int sampleChainLink = RegisterSample( "Shapes", "Chain Link", ChainLink::Create ); class RoundedShapes : public Sample { public: explicit RoundedShapes( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.zoom = 25.0f * 0.55f; m_context->camera.center = { 2.0f, 8.0f }; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeOffsetBox( 20.0f, 1.0f, { 0.0f, -1.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); box = b2MakeOffsetBox( 1.0f, 5.0f, { 19.0f, 5.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); box = b2MakeOffsetBox( 1.0f, 5.0f, { -19.0f, 5.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } // b2Capsule capsule = {{-0.25f, 0.0f}, {0.25f, 0.0f}, 0.25f}; // b2Circle circle = {{0.0f, 0.0f}, 0.35f}; // b2Polygon square = b2MakeSquare(0.35f); // b2Vec2 points[3] = {{-0.1f, -0.5f}, {0.1f, -0.5f}, {0.0f, 0.5f}}; // b2Hull wedgeHull = b2ComputeHull(points, 3); // b2Polygon wedge = b2MakePolygon(&wedgeHull, 0.0f); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.rollingResistance = 0.3f; float y = 2.0f; int xcount = 10, ycount = 10; for ( int i = 0; i < ycount; ++i ) { float x = -5.0f; for ( int j = 0; j < xcount; ++j ) { bodyDef.position = { x, y }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon poly = RandomPolygon( 0.5f ); poly.radius = RandomFloatRange( 0.05f, 0.25f ); b2CreatePolygonShape( bodyId, &shapeDef, &poly ); x += 1.0f; } y += 1.0f; } } static Sample* Create( SampleContext* context ) { return new RoundedShapes( context ); } }; static int sampleRoundedShapes = RegisterSample( "Shapes", "Rounded", RoundedShapes::Create ); class EllipseShape : public Sample { public: explicit EllipseShape( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.zoom = 25.0f * 0.55f; m_context->camera.center = { 2.0f, 8.0f }; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeOffsetBox( 20.0f, 1.0f, { 0.0f, -1.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); box = b2MakeOffsetBox( 1.0f, 5.0f, { 19.0f, 5.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); box = b2MakeOffsetBox( 1.0f, 5.0f, { -19.0f, 5.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } b2Vec2 points[6] = { { 0.0f, -0.25f }, { 0.0f, 0.25f }, { 0.05f, 0.075f }, { -0.05f, 0.075f }, { 0.05f, -0.075f }, { -0.05f, -0.075f }, }; b2Hull diamondHull = b2ComputeHull( points, 6 ); b2Polygon poly = b2MakePolygon( &diamondHull, 0.2f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.rollingResistance = 0.2f; float y = 2.0f; int xCount = 10, yCount = 10; for ( int i = 0; i < yCount; ++i ) { float x = -5.0f; for ( int j = 0; j < xCount; ++j ) { bodyDef.position = { x, y }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &poly ); x += 1.0f; } y += 1.0f; } } static Sample* Create( SampleContext* context ) { return new EllipseShape( context ); } }; static int sampleEllipseShape = RegisterSample( "Shapes", "Ellipse", EllipseShape::Create ); class OffsetShapes : public Sample { public: explicit OffsetShapes( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.zoom = 25.0f * 0.55f; m_context->camera.center = { 2.0f, 8.0f }; } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { -1.0f, 1.0f }; b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeOffsetBox( 1.0f, 1.0f, { 10.0f, -2.0f }, b2MakeRot( 0.5f * B2_PI ) ); b2CreatePolygonShape( groundId, &shapeDef, &box ); } { b2Capsule capsule = { { -5.0f, 1.0f }, { -4.0f, 1.0f }, 0.25f }; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 13.5f, -0.75f }; bodyDef.type = b2_dynamicBody; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); } { b2Polygon box = b2MakeOffsetBox( 0.75f, 0.5f, { 9.0f, 2.0f }, b2MakeRot( 0.5f * B2_PI ) ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, 0.0f }; bodyDef.type = b2_dynamicBody; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } void Step() override { Sample::Step(); DrawTransform( m_draw, b2Transform_identity, 1.0f ); } static Sample* Create( SampleContext* context ) { return new OffsetShapes( context ); } }; static int sampleOffsetShapes = RegisterSample( "Shapes", "Offset", OffsetShapes::Create ); // This shows how to use explosions and demonstrates the projected perimeter class Explosion : public Sample { public: explicit Explosion( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 0.0f }; m_context->camera.zoom = 14.0f; } b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); bodyDef.type = b2_dynamicBody; bodyDef.gravityScale = 0.0f; b2ShapeDef shapeDef = b2DefaultShapeDef(); m_referenceAngle = 0.0f; b2WeldJointDef weldDef = b2DefaultWeldJointDef(); weldDef.base.bodyIdA = groundId; weldDef.base.localFrameA.q = b2MakeRot( m_referenceAngle ); weldDef.base.localFrameB.p = b2Vec2_zero; weldDef.angularHertz = 0.5f; weldDef.angularDampingRatio = 0.7f; weldDef.linearHertz = 0.5f; weldDef.linearDampingRatio = 0.7f; float r = 8.0f; for ( float angle = 0.0f; angle < 360.0f; angle += 30.0f ) { b2CosSin cosSin = b2ComputeCosSin( angle * B2_PI / 180.0f ); bodyDef.position = { r * cosSin.cosine, r * cosSin.sine }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 1.0f, 0.1f ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); weldDef.base.localFrameA.p = bodyDef.position; weldDef.base.bodyIdB = bodyId; b2JointId jointId = b2CreateWeldJoint( m_worldId, &weldDef ); m_jointIds.push_back( jointId ); } m_radius = 7.0f; m_falloff = 3.0f; m_impulse = 10.0f; } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 160.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Explosion", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); if ( ImGui::Button( "Explode" ) ) { b2ExplosionDef def = b2DefaultExplosionDef(); def.position = b2Vec2_zero; def.radius = m_radius; def.falloff = m_falloff; def.impulsePerLength = m_impulse; b2World_Explode( m_worldId, &def ); } ImGui::SliderFloat( "radius", &m_radius, 0.0f, 20.0f, "%.1f" ); ImGui::SliderFloat( "falloff", &m_falloff, 0.0f, 20.0f, "%.1f" ); ImGui::SliderFloat( "impulse", &m_impulse, -20.0f, 20.0f, "%.1f" ); ImGui::End(); } void Step() override { if ( m_context->pause == false || m_context->singleStep == true ) { m_referenceAngle += m_context->hertz > 0.0f ? 60.0f * B2_PI / 180.0f / m_context->hertz : 0.0f; m_referenceAngle = b2UnwindAngle( m_referenceAngle ); int count = (int)m_jointIds.size(); for ( int i = 0; i < count; ++i ) { b2Transform localFrameA = b2Joint_GetLocalFrameA( m_jointIds[i] ); localFrameA.q = b2MakeRot( m_referenceAngle ); b2Joint_SetLocalFrameA( m_jointIds[i], localFrameA ); } } Sample::Step(); DrawTextLine( "reference angle = %g", m_referenceAngle ); DrawCircle( m_draw, b2Vec2_zero, m_radius + m_falloff, b2_colorBox2DBlue ); DrawCircle( m_draw, b2Vec2_zero, m_radius, b2_colorBox2DYellow ); } static Sample* Create( SampleContext* context ) { return new Explosion( context ); } std::vector m_jointIds; float m_radius; float m_falloff; float m_impulse; float m_referenceAngle; }; static int sampleExplosion = RegisterSample( "Shapes", "Explosion", Explosion::Create ); // This sample tests a static shape being recreated every step. class RecreateStatic : public Sample { public: explicit RecreateStatic( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 2.5f }; m_context->camera.zoom = 3.5f; } b2BodyDef bodyDef = b2DefaultBodyDef(); b2ShapeDef shapeDef = b2DefaultShapeDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { 0.0f, 1.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 1.0f, 1.0f ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); m_groundId = {}; } void Step() override { if ( B2_IS_NON_NULL( m_groundId ) ) { b2DestroyBody( m_groundId ); m_groundId = {}; } b2BodyDef bodyDef = b2DefaultBodyDef(); m_groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); // Invoke contact creation so that contact points are created immediately // on a static body. shapeDef.invokeContactCreation = true; b2Segment segment = { { -10.0f, 0.0f }, { 10.0f, 0.0f } }; b2CreateSegmentShape( m_groundId, &shapeDef, &segment ); Sample::Step(); } static Sample* Create( SampleContext* context ) { return new RecreateStatic( context ); } b2BodyId m_groundId; }; static int sampleSingleBox = RegisterSample( "Shapes", "Recreate Static", RecreateStatic::Create ); class BoxRestitution : public Sample { public: explicit BoxRestitution( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 5.0f }; m_context->camera.zoom = 10.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); float h = 2.0f * m_count; b2Segment segment = { { -h, 0.0f }, { h, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreateSegmentShape( groundId, &shapeDef, &segment ); } b2Polygon box = b2MakeBox( 0.5f, 0.5f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.material.restitution = 0.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; float dr = 1.0f / ( m_count > 1 ? m_count - 1 : 1 ); float x = -1.0f * ( m_count - 1 ); float dx = 2.0f; for ( int i = 0; i < m_count; ++i ) { char buffer[32]; snprintf( buffer, 32, "%.2f", shapeDef.material.restitution ); bodyDef.position = { x, 1.0f }; bodyDef.name = buffer; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); bodyDef.position = { x, 4.0f }; bodyDef.name = buffer; bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); shapeDef.material.restitution += dr; x += dx; } } static Sample* Create( SampleContext* context ) { return new BoxRestitution( context ); } static constexpr int m_count = 10; }; static int sampleBoxRestitution = RegisterSample( "Shapes", "Box Restitution", BoxRestitution::Create ); class Wind : public Sample { public: enum ShapeType { e_circleShape = 0, e_capsuleShape, e_boxShape }; explicit Wind( SampleContext* context ) : Sample( context ) , m_bodyIds{} { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 1.0f }; m_context->camera.zoom = 2.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); m_groundId = b2CreateBody( m_worldId, &bodyDef ); } m_shapeType = e_capsuleShape; m_wind = { 6.0f, 0.0f }; m_drag = 1.0f; m_lift = 0.75f; m_count = 10; m_noise = { 0.0f, 0.0f }; CreateScene(); } void CreateScene() { for ( int i = 0; i < m_maxCount; ++i ) { if ( B2_IS_NON_NULL( m_bodyIds[i] ) ) { b2DestroyBody( m_bodyIds[i] ); m_bodyIds[i] = b2_nullBodyId; } } float radius = 0.1f; b2Circle circle = { { 0.0f, 0.0f }, radius }; b2Capsule capsule = { { 0.0f, -radius }, { 0.0f, radius }, 0.25f * radius }; b2Polygon box = b2MakeBox( 0.25f * radius, 1.25f * radius ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = m_groundId; jointDef.base.localFrameA.p = { 0.0f, 2.0f + radius }; jointDef.base.drawScale = 0.1f; jointDef.hertz = 0.1f; jointDef.dampingRatio = 0.0f; jointDef.enableSpring = true; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.gravityScale = 0.5f; bodyDef.enableSleep = false; for ( int i = 0; i < m_count; ++i ) { bodyDef.position = { 0.0f, 2.0f - 2.0f * radius * i }; m_bodyIds[i] = b2CreateBody( m_worldId, &bodyDef ); if ( m_shapeType == e_circleShape ) { b2CreateCircleShape( m_bodyIds[i], &shapeDef, &circle ); } else if ( m_shapeType == e_capsuleShape ) { b2CreateCapsuleShape( m_bodyIds[i], &shapeDef, &capsule ); } else { b2CreatePolygonShape( m_bodyIds[i], &shapeDef, &box ); } jointDef.base.bodyIdB = m_bodyIds[i]; jointDef.base.localFrameB.p = { 0.0f, radius }; b2CreateRevoluteJoint( m_worldId, &jointDef ); jointDef.base.bodyIdA = m_bodyIds[i]; jointDef.base.localFrameA.p = { 0.0f, -radius }; } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 15.0f * fontSize; ImGui::SetNextWindowPos( { 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize }, ImGuiCond_Once ); ImGui::SetNextWindowSize( { 24.0f * fontSize, height } ); ImGui::Begin( "Wind", nullptr, ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 18.0f * fontSize ); const char* shapeTypes[] = { "Circle", "Capsule", "Box" }; int shapeType = int( m_shapeType ); if ( ImGui::Combo( "Shape", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) ) { m_shapeType = ShapeType( shapeType ); CreateScene(); } ImGui::SliderFloat2( "Wind", &m_wind.x, -20.0f, 20.0f, "%.1f" ); ImGui::SliderFloat( "Drag", &m_drag, 0.0f, 1.0f, "%.2f" ); ImGui::SliderFloat( "Lift", &m_lift, 0.0f, 4.0f, "%.2f" ); if ( ImGui::SliderInt( "Count", &m_count, 1, m_maxCount, "%d" ) ) { CreateScene(); } ImGui::PopItemWidth(); ImGui::End(); } void Step() override { if ( m_context->pause == false || m_context->singleStep == true ) { float speed; b2Vec2 direction = b2GetLengthAndNormalize( &speed, m_wind ); b2Vec2 wind = b2MulSV( speed, b2Add( direction, m_noise ) ); for ( int i = 0; i < m_count; ++i ) { b2ShapeId shapeIds[1]; int count = b2Body_GetShapes( m_bodyIds[i], shapeIds, 1 ); for ( int j = 0; j < count; ++j ) { b2Shape_ApplyWind( shapeIds[j], wind, m_drag, m_lift, true ); } } b2Vec2 rand = RandomVec2( -0.3f, 0.3f ); m_noise = b2Lerp( m_noise, rand, 0.05f ); DrawLine( m_draw, b2Vec2_zero, b2MulSV( 0.2f, wind ), b2_colorFuchsia ); } Sample::Step(); } static Sample* Create( SampleContext* context ) { return new Wind( context ); } static constexpr int m_maxCount = 60; ShapeType m_shapeType; b2Vec2 m_wind; float m_drag; float m_lift; b2Vec2 m_noise; b2BodyId m_groundId; b2BodyId m_bodyIds[m_maxCount]; int m_count; }; static int sampleWind = RegisterSample( "Shapes", "Wind", Wind::Create ); ================================================ FILE: samples/sample_stacking.cpp ================================================ // SPDX-FileCopyrightText: 2022 Erin Catto // SPDX-License-Identifier: MIT #include "draw.h" #include "random.h" #include "sample.h" #include "box2d/box2d.h" #include "box2d/math_functions.h" #include #include #include class SingleBox : public Sample { public: explicit SingleBox( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 2.5f }; m_context->camera.zoom = 3.5f; } float extent = 1.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); float groundWidth = 66.0f * extent; b2ShapeDef shapeDef = b2DefaultShapeDef(); // shapeDef.friction = 0.5f; b2Segment segment = { { -0.5f * 2.0f * groundWidth, 0.0f }, { 0.5f * 2.0f * groundWidth, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); bodyDef.type = b2_dynamicBody; b2Polygon box = b2MakeBox( extent, extent ); bodyDef.position = { 0.0f, 1.0f }; bodyDef.linearVelocity = { 5.0f, 0.0f }; m_bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( m_bodyId, &shapeDef, &box ); } void Step() override { Sample::Step(); // DrawCircle({0.0f, 2.0f}, 1.0f, b2_colorWhite); b2Vec2 position = b2Body_GetPosition( m_bodyId ); DrawTextLine( "(x, y) = (%.2g, %.2g)", position.x, position.y ); } static Sample* Create( SampleContext* context ) { return new SingleBox( context ); } b2BodyId m_bodyId; }; static int sampleSingleBox = RegisterSample( "Stacking", "Single Box", SingleBox::Create ); class TiltedStack : public Sample { public: explicit TiltedStack( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 7.5f, 7.5f }; m_context->camera.zoom = 20.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, -1.0f }; b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 1000.0f, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( groundId, &shapeDef, &box ); } for ( int i = 0; i < m_rows * m_columns; ++i ) { m_bodies[i] = b2_nullBodyId; } b2Polygon box = b2MakeRoundedBox( 0.45f, 0.45f, 0.05f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.material.friction = 0.3f; float offset = 0.2f; float dx = 5.0f; float xroot = -0.5f * dx * ( m_columns - 1.0f ); for ( int j = 0; j < m_columns; ++j ) { float x = xroot + j * dx; for ( int i = 0; i < m_rows; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; int n = j * m_rows + i; bodyDef.position = { x + offset * i, 0.5f + 1.0f * i }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); m_bodies[n] = bodyId; b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } } static Sample* Create( SampleContext* context ) { return new TiltedStack( context ); } static constexpr int m_columns = 10; static constexpr int m_rows = 10; b2BodyId m_bodies[m_rows * m_columns]; }; static int sampleTiltedStack = RegisterSample( "Stacking", "Tilted Stack", TiltedStack::Create ); // This sample shows some aspects of Box2D continuous collision: // - bullet dynamic bodies which support continuous collision with non-bullet dynamic bodies // - prevention of chain reaction tunneling // Try disabling continuous collision and firing a bullet. You might see a bullet push a // a through the static wall. class VerticalStack : public Sample { public: enum { e_maxColumns = 10, e_maxRows = 15, e_maxBullets = 8 }; enum ShapeType { e_circleShape = 0, e_boxShape }; explicit VerticalStack( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { -7.0f, 9.0f }; m_context->camera.zoom = 14.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, 0.0f }; b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Segment segment = { { 10.0f, 0.0f }, { 10.0f, 20.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); segment = { { -30.0f, 0.0f }, { 30.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } for ( int i = 0; i < e_maxRows * e_maxColumns; ++i ) { m_bodies[i] = b2_nullBodyId; } for ( int i = 0; i < e_maxBullets; ++i ) { m_bullets[i] = b2_nullBodyId; } m_shapeType = e_boxShape; m_rowCount = 12; m_columnCount = 1; m_bulletCount = 1; m_bulletType = e_circleShape; CreateStacks(); } void CreateStacks() { for ( int i = 0; i < e_maxRows * e_maxColumns; ++i ) { if ( B2_IS_NON_NULL( m_bodies[i] ) ) { b2DestroyBody( m_bodies[i] ); m_bodies[i] = b2_nullBodyId; } } b2Circle circle = {}; circle.radius = 0.5f; b2Polygon box = b2MakeRoundedBox( 0.45f, 0.45f, 0.05f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.material.friction = 0.3f; float offset; if ( m_shapeType == e_circleShape ) { offset = 0.0f; } else { offset = 0.01f; } float dx = -3.0f; float xroot = 8.0f; for ( int j = 0; j < m_columnCount; ++j ) { float x = xroot + j * dx; for ( int i = 0; i < m_rowCount; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; int n = j * m_rowCount + i; float shift = ( i % 2 == 0 ? -offset : offset ); bodyDef.position = { x + shift, 0.5f + 1.0f * i }; // bodyDef.position = {x + shift, 1.0f + 1.51f * i}; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); m_bodies[n] = bodyId; if ( m_shapeType == e_circleShape ) { b2CreateCircleShape( bodyId, &shapeDef, &circle ); } else { b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } } } void DestroyBody() { for ( int j = 0; j < m_columnCount; ++j ) { for ( int i = 0; i < m_rowCount; ++i ) { int n = j * m_rowCount + i; if ( B2_IS_NON_NULL( m_bodies[n] ) ) { b2DestroyBody( m_bodies[n] ); m_bodies[n] = b2_nullBodyId; break; } } } } void DestroyBullets() { for ( int i = 0; i < e_maxBullets; ++i ) { b2BodyId bullet = m_bullets[i]; if ( B2_IS_NON_NULL( bullet ) ) { b2DestroyBody( bullet ); m_bullets[i] = b2_nullBodyId; } } } void FireBullets() { b2Circle circle = { { 0.0f, 0.0f }, 0.25f }; b2Polygon box = b2MakeBox( 0.25f, 0.25f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 4.0f; for ( int i = 0; i < m_bulletCount; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { -26.7f - i, 6.0f }; float speed = RandomFloatRange( 200.0f, 300.0f ); bodyDef.linearVelocity = { speed, 0.0f }; bodyDef.isBullet = true; b2BodyId bullet = b2CreateBody( m_worldId, &bodyDef ); if ( m_bulletType == e_boxShape ) { b2CreatePolygonShape( bullet, &shapeDef, &box ); } else { b2CreateCircleShape( bullet, &shapeDef, &circle ); } assert( B2_IS_NULL( m_bullets[i] ) ); m_bullets[i] = bullet; } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 230.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); ImGui::Begin( "Vertical Stack", nullptr, ImGuiWindowFlags_NoResize ); ImGui::PushItemWidth( 120.0f ); bool changed = false; const char* shapeTypes[] = { "Circle", "Box" }; int shapeType = int( m_shapeType ); changed = changed || ImGui::Combo( "Shape", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ); m_shapeType = ShapeType( shapeType ); changed = changed || ImGui::SliderInt( "Rows", &m_rowCount, 1, e_maxRows ); changed = changed || ImGui::SliderInt( "Columns", &m_columnCount, 1, e_maxColumns ); ImGui::SliderInt( "Bullets", &m_bulletCount, 1, e_maxBullets ); int bulletType = int( m_bulletType ); ImGui::Combo( "Bullet Shape", &bulletType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ); m_bulletType = ShapeType( bulletType ); ImGui::PopItemWidth(); if ( ImGui::Button( "Fire Bullets" ) || glfwGetKey( m_context->window, GLFW_KEY_B ) == GLFW_PRESS ) { DestroyBullets(); FireBullets(); } if ( ImGui::Button( "Destroy Body" ) ) { DestroyBody(); } changed = changed || ImGui::Button( "Reset Stack" ); if ( changed ) { DestroyBullets(); CreateStacks(); } ImGui::End(); } static Sample* Create( SampleContext* context ) { return new VerticalStack( context ); } b2BodyId m_bullets[e_maxBullets]; b2BodyId m_bodies[e_maxRows * e_maxColumns]; int m_columnCount; int m_rowCount; int m_bulletCount; ShapeType m_shapeType; ShapeType m_bulletType; }; static int sampleVerticalStack = RegisterSample( "Stacking", "Vertical Stack", VerticalStack::Create ); // A simple circle stack that also shows how to collect hit events class CircleStack : public Sample { public: struct Event { int indexA, indexB; }; explicit CircleStack( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 5.0f }; m_context->camera.zoom = 6.0f; } int shapeIndex = 0; { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.userData = reinterpret_cast( intptr_t( shapeIndex ) ); shapeIndex += 1; b2Segment segment = { { -10.0f, 0.0f }, { 10.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } b2World_SetGravity( m_worldId, { 0.0f, -20.0f } ); b2World_SetContactTuning( m_worldId, 0.25f * 360.0f, 10.0f, 3.0f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2Circle circle = {}; circle.radius = 0.5f; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.enableHitEvents = true; // shapeDef.rollingResistance = 0.2f; shapeDef.material.friction = 0.0f; float y = 0.75f; for ( int i = 0; i < 10; ++i ) { bodyDef.position.y = y; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); shapeDef.userData = reinterpret_cast( intptr_t( shapeIndex ) ); shapeDef.density = 1.0f + 4.0f * i; shapeIndex += 1; b2CreateCircleShape( bodyId, &shapeDef, &circle ); y += 1.25f; } } void Step() override { Sample::Step(); b2ContactEvents events = b2World_GetContactEvents( m_worldId ); for ( int i = 0; i < events.hitCount; ++i ) { b2ContactHitEvent* event = events.hitEvents + i; void* userDataA = b2Shape_GetUserData( event->shapeIdA ); void* userDataB = b2Shape_GetUserData( event->shapeIdB ); int indexA = static_cast( reinterpret_cast( userDataA ) ); int indexB = static_cast( reinterpret_cast( userDataB ) ); DrawPoint( m_draw, event->point, 10.0f, b2_colorWhite ); m_events.push_back( { indexA, indexB } ); } int eventCount = (int)m_events.size(); for ( int i = 0; i < eventCount; ++i ) { DrawTextLine( "%d, %d", m_events[i].indexA, m_events[i].indexB ); } } static Sample* Create( SampleContext* context ) { return new CircleStack( context ); } std::vector m_events; }; static int sampleCircleStack = RegisterSample( "Stacking", "Circle Stack", CircleStack::Create ); class CapsuleStack : public Sample { public: struct Event { int indexA, indexB; }; explicit CapsuleStack( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 5.0f }; m_context->camera.zoom = 6.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, -1.0f }; b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon polygon = b2MakeBox( 10.0f, 1.0f ); b2CreatePolygonShape( groundId, &shapeDef, &polygon ); } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; float a = 0.25f; b2Capsule capsule = { { -4.0f * a, 0.0f }, { 4.0f * a, 0.0f }, a }; b2ShapeDef shapeDef = b2DefaultShapeDef(); // rolling resistance increases stacking stability // shapeDef.rollingResistance = 0.2f; float y = 2.0f * a; for ( int i = 0; i < 20; ++i ) { bodyDef.position.y = y; // bodyDef.position.x += ( i & 1 ) == 1 ? -0.5f * a : 0.5f * a; // bodyDef.linearVelocity = { 0.0f, -10.0f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); y += 3.0f * a; } } static Sample* Create( SampleContext* context ) { return new CapsuleStack( context ); } }; static int sampleCapsuleStack = RegisterSample( "Stacking", "Capsule Stack", CapsuleStack::Create ); class Cliff : public Sample { public: explicit Cliff( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.zoom = 25.0f * 0.5f; m_context->camera.center = { 0.0f, 5.0f }; } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, 0.0f }; b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeOffsetBox( 100.0f, 1.0f, { 0.0f, -1.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); b2Segment segment = { { -14.0f, 4.0f }, { -8.0f, 4.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); box = b2MakeOffsetBox( 3.0f, 0.5f, { 0.0f, 4.0f }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); b2Capsule capsule = { { 8.5f, 4.0f }, { 13.5f, 4.0f }, 0.5f }; b2CreateCapsuleShape( groundId, &shapeDef, &capsule ); } m_flip = false; for ( int i = 0; i < 9; ++i ) { m_bodyIds[i] = b2_nullBodyId; } CreateBodies(); } void CreateBodies() { for ( int i = 0; i < 9; ++i ) { if ( B2_IS_NON_NULL( m_bodyIds[i] ) ) { b2DestroyBody( m_bodyIds[i] ); m_bodyIds[i] = b2_nullBodyId; } } float sign = m_flip ? -1.0f : 1.0f; b2Capsule capsule = { { -0.25f, 0.0f }, { 0.25f, 0.0f }, 0.25f }; b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; b2Polygon square = b2MakeSquare( 0.5f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; { b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.01f; bodyDef.linearVelocity = { 2.0f * sign, 0.0f }; float offset = m_flip ? -4.0f : 0.0f; bodyDef.position = { -9.0f + offset, 4.25f }; m_bodyIds[0] = b2CreateBody( m_worldId, &bodyDef ); b2CreateCapsuleShape( m_bodyIds[0], &shapeDef, &capsule ); bodyDef.position = { 2.0f + offset, 4.75f }; m_bodyIds[1] = b2CreateBody( m_worldId, &bodyDef ); b2CreateCapsuleShape( m_bodyIds[1], &shapeDef, &capsule ); bodyDef.position = { 13.0f + offset, 4.75f }; m_bodyIds[2] = b2CreateBody( m_worldId, &bodyDef ); b2CreateCapsuleShape( m_bodyIds[2], &shapeDef, &capsule ); } { b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.01f; bodyDef.linearVelocity = { 2.5f * sign, 0.0f }; bodyDef.position = { -11.0f, 4.5f }; m_bodyIds[3] = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( m_bodyIds[3], &shapeDef, &square ); bodyDef.position = { 0.0f, 5.0f }; m_bodyIds[4] = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( m_bodyIds[4], &shapeDef, &square ); bodyDef.position = { 11.0f, 5.0f }; m_bodyIds[5] = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( m_bodyIds[5], &shapeDef, &square ); } { b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.2f; bodyDef.linearVelocity = { 1.5f * sign, 0.0f }; float offset = m_flip ? 4.0f : 0.0f; bodyDef.position = { -13.0f + offset, 4.5f }; m_bodyIds[6] = b2CreateBody( m_worldId, &bodyDef ); b2CreateCircleShape( m_bodyIds[6], &shapeDef, &circle ); bodyDef.position = { -2.0f + offset, 5.0f }; m_bodyIds[7] = b2CreateBody( m_worldId, &bodyDef ); b2CreateCircleShape( m_bodyIds[7], &shapeDef, &circle ); bodyDef.position = { 9.0f + offset, 5.0f }; m_bodyIds[8] = b2CreateBody( m_worldId, &bodyDef ); b2CreateCircleShape( m_bodyIds[8], &shapeDef, &circle ); } } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 60.0f; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 160.0f, height ) ); ImGui::Begin( "Cliff", nullptr, ImGuiWindowFlags_NoResize ); if ( ImGui::Button( "Flip" ) ) { m_flip = !m_flip; CreateBodies(); } ImGui::End(); } static Sample* Create( SampleContext* context ) { return new Cliff( context ); } b2BodyId m_bodyIds[9]; bool m_flip; }; static int sampleCliff = RegisterSample( "Stacking", "Cliff", Cliff::Create ); class Arch : public Sample { public: explicit Arch( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 8.0f }; m_context->camera.zoom = 25.0f * 0.35f; } b2Vec2 ps1[9] = { { 16.0f, 0.0f }, { 14.93803712795643f, 5.133601056842984f }, { 13.79871746027416f, 10.24928069555078f }, { 12.56252963284711f, 15.34107019122473f }, { 11.20040987372525f, 20.39856541571217f }, { 9.66521217819836f, 25.40369899225096f }, { 7.87179930638133f, 30.3179337000085f }, { 5.635199558196225f, 35.03820717801641f }, { 2.405937953536585f, 39.09554102558315f } }; b2Vec2 ps2[9] = { { 24.0f, 0.0f }, { 22.33619528222415f, 6.02299846205841f }, { 20.54936888969905f, 12.00964361211476f }, { 18.60854610798073f, 17.9470321677465f }, { 16.46769273811807f, 23.81367936585418f }, { 14.05325025774858f, 29.57079353071012f }, { 11.23551045834022f, 35.13775818285372f }, { 7.752568160730571f, 40.30450679009583f }, { 3.016931552701656f, 44.28891593799322f } }; float scale = 0.25f; for ( int i = 0; i < 9; ++i ) { ps1[i] = b2MulSV( scale, ps1[i] ); ps2[i] = b2MulSV( scale, ps2[i] ); } b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.6f; { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2Segment segment = { { -100.0f, 0.0f }, { 100.0f, 0.0f } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; for ( int i = 0; i < 8; ++i ) { b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Vec2 ps[4] = { ps1[i], ps2[i], ps2[i + 1], ps1[i + 1] }; b2Hull hull = b2ComputeHull( ps, 4 ); b2Polygon polygon = b2MakePolygon( &hull, 0.0f ); b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); } for ( int i = 0; i < 8; ++i ) { b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Vec2 ps[4] = { { -ps2[i].x, ps2[i].y }, { -ps1[i].x, ps1[i].y }, { -ps1[i + 1].x, ps1[i + 1].y }, { -ps2[i + 1].x, ps2[i + 1].y } }; b2Hull hull = b2ComputeHull( ps, 4 ); b2Polygon polygon = b2MakePolygon( &hull, 0.0f ); b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); } { b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2Vec2 ps[4] = { ps1[8], ps2[8], { -ps2[8].x, ps2[8].y }, { -ps1[8].x, ps1[8].y } }; b2Hull hull = b2ComputeHull( ps, 4 ); b2Polygon polygon = b2MakePolygon( &hull, 0.0f ); b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); } for ( int i = 0; i < 4; ++i ) { b2Polygon box = b2MakeBox( 2.0f, 0.5f ); bodyDef.position = { 0.0f, 0.5f + ps2[8].y + 1.0f * i }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } static Sample* Create( SampleContext* context ) { return new Arch( context ); } }; static int sampleArch = RegisterSample( "Stacking", "Arch", Arch::Create ); class DoubleDomino : public Sample { public: explicit DoubleDomino( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 4.0f }; m_context->camera.zoom = 25.0f * 0.25f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, -1.0f }; b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2Polygon box = b2MakeBox( 100.0f, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( groundId, &shapeDef, &box ); } b2Polygon box = b2MakeBox( 0.125f, 0.5f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.6f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; int count = 15; float x = -0.5f * count; for ( int i = 0; i < count; ++i ) { bodyDef.position = { x, 0.5f }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); if ( i == 0 ) { b2Body_ApplyLinearImpulse( bodyId, b2Vec2{ 0.2f, 0.0f }, b2Vec2{ x, 1.0f }, true ); } x += 1.0f; } } static Sample* Create( SampleContext* context ) { return new DoubleDomino( context ); } }; static int sampleDoubleDomino = RegisterSample( "Stacking", "Double Domino", DoubleDomino::Create ); class Confined : public Sample { public: explicit Confined( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.0f, 10.0f }; m_context->camera.zoom = 25.0f * 0.5f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Capsule capsule; capsule = { { -10.5f, 0.0f }, { 10.5f, 0.0f }, 0.5f }; b2CreateCapsuleShape( groundId, &shapeDef, &capsule ); capsule = { { -10.5f, 0.0f }, { -10.5f, 20.5f }, 0.5f }; b2CreateCapsuleShape( groundId, &shapeDef, &capsule ); capsule = { { 10.5f, 0.0f }, { 10.5f, 20.5f }, 0.5f }; b2CreateCapsuleShape( groundId, &shapeDef, &capsule ); capsule = { { -10.5f, 20.5f }, { 10.5f, 20.5f }, 0.5f }; b2CreateCapsuleShape( groundId, &shapeDef, &capsule ); } m_row = 0; m_column = 0; m_count = 0; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.gravityScale = 0.0f; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; while ( m_count < m_maxCount ) { m_row = 0; for ( int i = 0; i < m_gridCount; ++i ) { float x = -8.75f + m_column * 18.0f / m_gridCount; float y = 1.5f + m_row * 18.0f / m_gridCount; bodyDef.position = { x, y }; b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreateCircleShape( bodyId, &shapeDef, &circle ); m_count += 1; m_row += 1; } m_column += 1; } } static Sample* Create( SampleContext* context ) { return new Confined( context ); } static constexpr int m_gridCount = 25; static constexpr int m_maxCount = m_gridCount * m_gridCount; int m_row; int m_column; int m_count; }; static int sampleConfined = RegisterSample( "Stacking", "Confined", Confined::Create ); // From PEEL class CardHouse : public Sample { public: explicit CardHouse( SampleContext* context ) : Sample( context ) { if ( m_context->restart == false ) { m_context->camera.center = { 0.75f, 0.9f }; m_context->camera.zoom = 25.0f * 0.05f; } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = { 0.0f, -2.0f }; b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.7f; b2Polygon groundBox = b2MakeBox( 40.0f, 2.0f ); b2CreatePolygonShape( groundId, &shapeDef, &groundBox ); float cardHeight = 0.2f; float cardThickness = 0.001f; float angle0 = 25.0f * B2_PI / 180.0f; float angle1 = -25.0f * B2_PI / 180.0f; float angle2 = 0.5f * B2_PI; b2Polygon cardBox = b2MakeBox( cardThickness, cardHeight ); bodyDef.type = b2_dynamicBody; int Nb = 5; float z0 = 0.0f; float y = cardHeight - 0.02f; while ( Nb ) { float z = z0; for ( int i = 0; i < Nb; i++ ) { if ( i != Nb - 1 ) { bodyDef.position = { z + 0.25f, y + cardHeight - 0.015f }; bodyDef.rotation = b2MakeRot( angle2 ); b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &cardBox ); } bodyDef.position = { z, y }; bodyDef.rotation = b2MakeRot( angle1 ); b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &cardBox ); z += 0.175f; bodyDef.position = { z, y }; bodyDef.rotation = b2MakeRot( angle0 ); bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &cardBox ); z += 0.175f; } y += cardHeight * 2.0f - 0.03f; z0 += 0.175f; Nb--; } } static Sample* Create( SampleContext* context ) { return new CardHouse( context ); } }; static int sampleCardHouse = RegisterSample( "Stacking", "Card House", CardHouse::Create ); ================================================ FILE: samples/sample_world.cpp ================================================ // SPDX-FileCopyrightText: 2022 Erin Catto // SPDX-License-Identifier: MIT #include "car.h" #include "donut.h" #include "draw.h" #include "human.h" #include "sample.h" #include "box2d/box2d.h" #include "box2d/math_functions.h" #include #include class LargeWorld : public Sample { public: explicit LargeWorld( SampleContext* context ) : Sample( context ) { m_period = 40.0f; float omega = 2.0f * B2_PI / m_period; m_cycleCount = m_isDebug ? 10 : 600; m_gridSize = 1.0f; m_gridCount = (int)( m_cycleCount * m_period / m_gridSize ); float xStart = -0.5f * ( m_cycleCount * m_period ); m_viewPosition = { xStart, 15.0f }; if ( m_context->restart == false ) { m_context->camera.center = m_viewPosition; m_context->camera.zoom = 25.0f * 1.0f; m_context->debugDraw.drawJoints = false; } { b2BodyDef bodyDef = b2DefaultBodyDef(); b2ShapeDef shapeDef = b2DefaultShapeDef(); // Setting this to false significantly reduces the cost of creating // static bodies and shapes. shapeDef.invokeContactCreation = false; float height = 4.0f; float xBody = xStart; float xShape = xStart; b2BodyId groundId; for ( int i = 0; i < m_gridCount; ++i ) { // Create a new body regularly so that shapes are not too far from the body origin. // Most algorithms in Box2D work in local coordinates, but contact points are computed // relative to the body origin. // This makes a noticeable improvement in stability far from the origin. if ( i % 10 == 0 ) { bodyDef.position.x = xBody; groundId = b2CreateBody( m_worldId, &bodyDef ); xShape = 0.0f; } float y = 0.0f; int ycount = (int)roundf( height * cosf( omega * xBody ) ) + 12; for ( int j = 0; j < ycount; ++j ) { b2Polygon square = b2MakeOffsetBox( 0.4f * m_gridSize, 0.4f * m_gridSize, { xShape, y }, b2Rot_identity ); square.radius = 0.1f; b2CreatePolygonShape( groundId, &shapeDef, &square ); y += m_gridSize; } xBody += m_gridSize; xShape += m_gridSize; } } int humanIndex = 0; for ( int cycleIndex = 0; cycleIndex < m_cycleCount; ++cycleIndex ) { float xbase = ( 0.5f + cycleIndex ) * m_period + xStart; int remainder = cycleIndex % 3; if ( remainder == 0 ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = { xbase - 3.0f, 10.0f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeBox( 0.3f, 0.2f ); for ( int i = 0; i < 10; ++i ) { bodyDef.position.y = 10.0f; for ( int j = 0; j < 5; ++j ) { b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); bodyDef.position.y += 0.5f; } bodyDef.position.x += 0.6f; } } else if ( remainder == 1 ) { b2Vec2 position = { xbase - 2.0f, 10.0f }; for ( int i = 0; i < 5; ++i ) { Human human = {}; CreateHuman( &human, m_worldId, position, 1.5f, 0.05f, 0.0f, 0.0f, humanIndex + 1, nullptr, false ); humanIndex += 1; position.x += 1.0f; } } else { b2Vec2 position = { xbase - 4.0f, 12.0f }; for ( int i = 0; i < 5; ++i ) { Donut donut; donut.Create( m_worldId, position, 0.75f, 0, false, nullptr ); position.x += 2.0f; } } } m_car.Spawn( m_worldId, { xStart + 20.0f, 40.0f }, 10.0f, 2.0f, 0.7f, 2000.0f, nullptr ); m_cycleIndex = 0; m_speed = 0.0f; m_explosionPosition = { ( 0.5f + m_cycleIndex ) * m_period + xStart, 7.0f }; m_explode = true; m_followCar = false; } void UpdateGui() override { float fontSize = ImGui::GetFontSize(); float height = 13.0f * fontSize; ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->height - height - 2.0f * fontSize ), ImGuiCond_Once ); ImGui::SetNextWindowSize( ImVec2( 18.0f * fontSize, height ) ); ImGui::Begin( "Large World", nullptr, ImGuiWindowFlags_NoResize ); ImGui::SliderFloat( "speed", &m_speed, -400.0f, 400.0f, "%.0f" ); if ( ImGui::Button( "stop" ) ) { m_speed = 0.0f; } ImGui::Checkbox( "explode", &m_explode ); ImGui::Checkbox( "follow car", &m_followCar ); ImGui::Text( "world size = %g kilometers", m_gridSize * m_gridCount / 1000.0f ); ImGui::End(); } void Step() override { float span = 0.5f * ( m_period * m_cycleCount ); float timeStep = m_context->hertz > 0.0f ? 1.0f / m_context->hertz : 0.0f; if ( m_context->pause ) { timeStep = 0.0f; } m_viewPosition.x += timeStep * m_speed; m_viewPosition.x = b2ClampFloat( m_viewPosition.x, -span, span ); if ( m_speed != 0.0f ) { m_context->camera.center = m_viewPosition; } if ( m_followCar ) { m_context->camera.center.x = b2Body_GetPosition( m_car.m_chassisId ).x; } float radius = 2.0f; if ( ( m_stepCount & 0x1 ) == 0x1 && m_explode ) { m_explosionPosition.x = ( 0.5f + m_cycleIndex ) * m_period - span; b2ExplosionDef def = b2DefaultExplosionDef(); def.position = m_explosionPosition; def.radius = radius; def.falloff = 0.1f; def.impulsePerLength = 1.0f; b2World_Explode( m_worldId, &def ); m_cycleIndex = ( m_cycleIndex + 1 ) % m_cycleCount; } if ( m_explode ) { DrawCircle( m_draw, m_explosionPosition, radius, b2_colorAzure ); } if ( glfwGetKey( m_context->window, GLFW_KEY_A ) == GLFW_PRESS ) { m_car.SetSpeed( 20.0f ); } if ( glfwGetKey( m_context->window, GLFW_KEY_S ) == GLFW_PRESS ) { m_car.SetSpeed( 0.0f ); } if ( glfwGetKey( m_context->window, GLFW_KEY_D ) == GLFW_PRESS ) { m_car.SetSpeed( -5.0f ); } Sample::Step(); } static Sample* Create( SampleContext* context ) { return new LargeWorld( context ); } Car m_car; b2Vec2 m_viewPosition; float m_period; int m_cycleCount; int m_cycleIndex; float m_gridCount; float m_gridSize; float m_speed; b2Vec2 m_explosionPosition; bool m_explode; bool m_followCar; }; static int sampleLargeWorld = RegisterSample( "World", "Large World", LargeWorld::Create ); ================================================ FILE: samples/shader.c ================================================ // SPDX-FileCopyrightText: 2024 Erin Catto // SPDX-License-Identifier: MIT #if defined( _MSC_VER ) && !defined( _CRT_SECURE_NO_WARNINGS ) #define _CRT_SECURE_NO_WARNINGS #endif #include "shader.h" #include #include #include #include #if defined( _MSC_VER ) #define _CRTDBG_MAP_ALLOC #include #include #else #include #endif void DumpInfoGL() { const char* renderer = (const char*)glGetString( GL_RENDERER ); const char* vendor = (const char*)glGetString( GL_VENDOR ); const char* version = (const char*)glGetString( GL_VERSION ); const char* glslVersion = (const char*)glGetString( GL_SHADING_LANGUAGE_VERSION ); int major, minor; glGetIntegerv( GL_MAJOR_VERSION, &major ); glGetIntegerv( GL_MINOR_VERSION, &minor ); printf( "-------------------------------------------------------------\n" ); printf( "GL Vendor : %s\n", vendor ); printf( "GL Renderer : %s\n", renderer ); printf( "GL Version : %s\n", version ); printf( "GL Version : %d.%d\n", major, minor ); printf( "GLSL Version : %s\n", glslVersion ); printf( "-------------------------------------------------------------\n" ); } void CheckOpenGL() { GLenum errCode = glGetError(); if ( errCode != GL_NO_ERROR ) { printf( "OpenGL error = %d\n", errCode ); assert( false ); } } void PrintLogGL( uint32_t object ) { GLint log_length = 0; if ( glIsShader( object ) ) { glGetShaderiv( object, GL_INFO_LOG_LENGTH, &log_length ); } else if ( glIsProgram( object ) ) { glGetProgramiv( object, GL_INFO_LOG_LENGTH, &log_length ); } else { printf( "PrintLogGL: Not a shader or a program\n" ); return; } char* log = (char*)malloc( log_length ); if ( glIsShader( object ) ) { glGetShaderInfoLog( object, log_length, NULL, log ); } else if ( glIsProgram( object ) ) { glGetProgramInfoLog( object, log_length, NULL, log ); } printf( "PrintLogGL: %s", log ); free( log ); } static GLuint sCreateShaderFromString( const char* source, GLenum type ) { GLuint shader = glCreateShader( type ); const char* sources[] = { source }; glShaderSource( shader, 1, sources, NULL ); glCompileShader( shader ); int success = GL_FALSE; glGetShaderiv( shader, GL_COMPILE_STATUS, &success ); if ( success == GL_FALSE ) { printf( "Error compiling shader of type %d!\n", type ); PrintLogGL( shader ); glDeleteShader( shader ); return 0; } return shader; } uint32_t CreateProgramFromStrings( const char* vertexString, const char* fragmentString ) { GLuint vertex = sCreateShaderFromString( vertexString, GL_VERTEX_SHADER ); if ( vertex == 0 ) { return 0; } GLuint fragment = sCreateShaderFromString( fragmentString, GL_FRAGMENT_SHADER ); if ( fragment == 0 ) { return 0; } GLuint program = glCreateProgram(); glAttachShader( program, vertex ); glAttachShader( program, fragment ); glLinkProgram( program ); int success = GL_FALSE; glGetProgramiv( program, GL_LINK_STATUS, &success ); if ( success == GL_FALSE ) { printf( "glLinkProgram:" ); PrintLogGL( program ); return 0; } glDeleteShader( vertex ); glDeleteShader( fragment ); return program; } static GLuint sCreateShaderFromFile( const char* filename, GLenum type ) { FILE* file = fopen( filename, "rb" ); if ( file == NULL ) { fprintf( stderr, "Error opening %s\n", filename ); return 0; } fseek( file, 0, SEEK_END ); long size = ftell( file ); fseek( file, 0, SEEK_SET ); char* source = malloc( size + 1 ); size_t count = fread( source, size, 1, file ); (void) count; fclose( file ); source[size] = 0; GLuint shader = glCreateShader( type ); const char* sources[] = { source }; glShaderSource( shader, 1, sources, NULL ); glCompileShader( shader ); int success = GL_FALSE; glGetShaderiv( shader, GL_COMPILE_STATUS, &success ); if ( success == GL_FALSE ) { fprintf( stderr, "Error compiling shader of type %d!\n", type ); PrintLogGL( shader ); } free( source ); return shader; } uint32_t CreateProgramFromFiles( const char* vertexPath, const char* fragmentPath ) { GLuint vertex = sCreateShaderFromFile( vertexPath, GL_VERTEX_SHADER ); if ( vertex == 0 ) { return 0; } GLuint fragment = sCreateShaderFromFile( fragmentPath, GL_FRAGMENT_SHADER ); if ( fragment == 0 ) { return 0; } GLuint program = glCreateProgram(); glAttachShader( program, vertex ); glAttachShader( program, fragment ); glLinkProgram( program ); int success = GL_FALSE; glGetProgramiv( program, GL_LINK_STATUS, &success ); if ( success == GL_FALSE ) { printf( "glLinkProgram:" ); PrintLogGL( program ); return 0; } glDeleteShader( vertex ); glDeleteShader( fragment ); return program; } ================================================ FILE: samples/shader.h ================================================ // SPDX-FileCopyrightText: 2024 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include #ifdef __cplusplus extern "C" { #endif uint32_t CreateProgramFromFiles( const char* vertexPath, const char* fragmentPath ); uint32_t CreateProgramFromStrings( const char* vertexString, const char* fragmentString ); void CheckOpenGL(); void DumpInfoGL(); void PrintLogGL( uint32_t object ); #ifdef __cplusplus } #endif ================================================ FILE: samples/stb_image_write.h ================================================ /* stb_image_write - v1.16 - public domain - http://nothings.org/stb writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015 no warranty implied; use at your own risk Before #including, #define STB_IMAGE_WRITE_IMPLEMENTATION in the file that you want to have the implementation. Will probably not work correctly with strict-aliasing optimizations. ABOUT: This header file is a library for writing images to C stdio or a callback. The PNG output is not optimal; it is 20-50% larger than the file written by a decent optimizing implementation; though providing a custom zlib compress function (see STBIW_ZLIB_COMPRESS) can mitigate that. This library is designed for source code compactness and simplicity, not optimal image file size or run-time performance. BUILDING: You can #define STBIW_ASSERT(x) before the #include to avoid using assert.h. You can #define STBIW_MALLOC(), STBIW_REALLOC(), and STBIW_FREE() to replace malloc,realloc,free. You can #define STBIW_MEMMOVE() to replace memmove() You can #define STBIW_ZLIB_COMPRESS to use a custom zlib-style compress function for PNG compression (instead of the builtin one), it must have the following signature: unsigned char * my_compress(unsigned char *data, int data_len, int *out_len, int quality); The returned data will be freed with STBIW_FREE() (free() by default), so it must be heap allocated with STBIW_MALLOC() (malloc() by default), UNICODE: If compiling for Windows and you wish to use Unicode filenames, compile with #define STBIW_WINDOWS_UTF8 and pass utf8-encoded filenames. Call stbiw_convert_wchar_to_utf8 to convert Windows wchar_t filenames to utf8. USAGE: There are five functions, one for each image file format: int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); int stbi_write_jpg(char const *filename, int w, int h, int comp, const void *data, int quality); int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); void stbi_flip_vertically_on_write(int flag); // flag is non-zero to flip data vertically There are also five equivalent functions that use an arbitrary write function. You are expected to open/close your file-equivalent before and after calling these: int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); where the callback is: void stbi_write_func(void *context, void *data, int size); You can configure it with these global variables: int stbi_write_tga_with_rle; // defaults to true; set to 0 to disable RLE int stbi_write_png_compression_level; // defaults to 8; set to higher for more compression int stbi_write_force_png_filter; // defaults to -1; set to 0..5 to force a filter mode You can define STBI_WRITE_NO_STDIO to disable the file variant of these functions, so the library will not use stdio.h at all. However, this will also disable HDR writing, because it requires stdio for formatted output. Each function returns 0 on failure and non-0 on success. The functions create an image file defined by the parameters. The image is a rectangle of pixels stored from left-to-right, top-to-bottom. Each pixel contains 'comp' channels of data stored interleaved with 8-bits per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall. The *data pointer points to the first byte of the top-left-most pixel. For PNG, "stride_in_bytes" is the distance in bytes from the first byte of a row of pixels to the first byte of the next row of pixels. PNG creates output files with the same number of components as the input. The BMP format expands Y to RGB in the file format and does not output alpha. PNG supports writing rectangles of data even when the bytes storing rows of data are not consecutive in memory (e.g. sub-rectangles of a larger image), by supplying the stride between the beginning of adjacent rows. The other formats do not. (Thus you cannot write a native-format BMP through the BMP writer, both because it is in BGR order and because it may have padding at the end of the line.) PNG allows you to set the deflate compression level by setting the global variable 'stbi_write_png_compression_level' (it defaults to 8). HDR expects linear float data. Since the format is always 32-bit rgb(e) data, alpha (if provided) is discarded, and for monochrome data it is replicated across all three channels. TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed data, set the global variable 'stbi_write_tga_with_rle' to 0. JPEG does ignore alpha channels in input data; quality is between 1 and 100. Higher quality looks better but results in a bigger image. JPEG baseline (no JPEG progressive). CREDITS: Sean Barrett - PNG/BMP/TGA Baldur Karlsson - HDR Jean-Sebastien Guay - TGA monochrome Tim Kelsey - misc enhancements Alan Hickman - TGA RLE Emmanuel Julien - initial file IO callback implementation Jon Olick - original jo_jpeg.cpp code Daniel Gibson - integrate JPEG, allow external zlib Aarni Koskela - allow choosing PNG filter bugfixes: github:Chribba Guillaume Chereau github:jry2 github:romigrou Sergio Gonzalez Jonas Karlsson Filip Wasil Thatcher Ulrich github:poppolopoppo Patrick Boettcher github:xeekworx Cap Petschulat Simon Rodriguez Ivan Tikhonov github:ignotion Adam Schackart Andrew Kensler LICENSE See end of file for license information. */ #ifndef INCLUDE_STB_IMAGE_WRITE_H #define INCLUDE_STB_IMAGE_WRITE_H #include // if STB_IMAGE_WRITE_STATIC causes problems, try defining STBIWDEF to 'inline' or 'static inline' #ifndef STBIWDEF #ifdef STB_IMAGE_WRITE_STATIC #define STBIWDEF static #else #ifdef __cplusplus #define STBIWDEF extern "C" #else #define STBIWDEF extern #endif #endif #endif #ifndef STB_IMAGE_WRITE_STATIC // C++ forbids static forward declarations STBIWDEF int stbi_write_tga_with_rle; STBIWDEF int stbi_write_png_compression_level; STBIWDEF int stbi_write_force_png_filter; #endif #ifndef STBI_WRITE_NO_STDIO STBIWDEF int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); STBIWDEF int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); STBIWDEF int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); STBIWDEF int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality); #ifdef STBIW_WINDOWS_UTF8 STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); #endif #endif typedef void stbi_write_func(void *context, void *data, int size); STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); STBIWDEF void stbi_flip_vertically_on_write(int flip_boolean); #endif//INCLUDE_STB_IMAGE_WRITE_H #ifdef STB_IMAGE_WRITE_IMPLEMENTATION #ifdef _WIN32 #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif #ifndef _CRT_NONSTDC_NO_DEPRECATE #define _CRT_NONSTDC_NO_DEPRECATE #endif #endif #ifndef STBI_WRITE_NO_STDIO #include #endif // STBI_WRITE_NO_STDIO #include #include #include #include #if defined(STBIW_MALLOC) && defined(STBIW_FREE) && (defined(STBIW_REALLOC) || defined(STBIW_REALLOC_SIZED)) // ok #elif !defined(STBIW_MALLOC) && !defined(STBIW_FREE) && !defined(STBIW_REALLOC) && !defined(STBIW_REALLOC_SIZED) // ok #else #error "Must define all or none of STBIW_MALLOC, STBIW_FREE, and STBIW_REALLOC (or STBIW_REALLOC_SIZED)." #endif #ifndef STBIW_MALLOC #define STBIW_MALLOC(sz) malloc(sz) #define STBIW_REALLOC(p,newsz) realloc(p,newsz) #define STBIW_FREE(p) free(p) #endif #ifndef STBIW_REALLOC_SIZED #define STBIW_REALLOC_SIZED(p,oldsz,newsz) STBIW_REALLOC(p,newsz) #endif #ifndef STBIW_MEMMOVE #define STBIW_MEMMOVE(a,b,sz) memmove(a,b,sz) #endif #ifndef STBIW_ASSERT #include #define STBIW_ASSERT(x) assert(x) #endif #define STBIW_UCHAR(x) (unsigned char) ((x) & 0xff) #ifdef STB_IMAGE_WRITE_STATIC static int stbi_write_png_compression_level = 8; static int stbi_write_tga_with_rle = 1; static int stbi_write_force_png_filter = -1; #else int stbi_write_png_compression_level = 8; int stbi_write_tga_with_rle = 1; int stbi_write_force_png_filter = -1; #endif static int stbi__flip_vertically_on_write = 0; STBIWDEF void stbi_flip_vertically_on_write(int flag) { stbi__flip_vertically_on_write = flag; } typedef struct { stbi_write_func *func; void *context; unsigned char buffer[64]; int buf_used; } stbi__write_context; // initialize a callback-based context static void stbi__start_write_callbacks(stbi__write_context *s, stbi_write_func *c, void *context) { s->func = c; s->context = context; } #ifndef STBI_WRITE_NO_STDIO static void stbi__stdio_write(void *context, void *data, int size) { fwrite(data,1,size,(FILE*) context); } #if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8) #ifdef __cplusplus #define STBIW_EXTERN extern "C" #else #define STBIW_EXTERN extern #endif STBIW_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); STBIW_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) { return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); } #endif static FILE *stbiw__fopen(char const *filename, char const *mode) { FILE *f; #if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8) wchar_t wMode[64]; wchar_t wFilename[1024]; if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename))) return 0; if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode))) return 0; #if defined(_MSC_VER) && _MSC_VER >= 1400 if (0 != _wfopen_s(&f, wFilename, wMode)) f = 0; #else f = _wfopen(wFilename, wMode); #endif #elif defined(_MSC_VER) && _MSC_VER >= 1400 if (0 != fopen_s(&f, filename, mode)) f=0; #else f = fopen(filename, mode); #endif return f; } static int stbi__start_write_file(stbi__write_context *s, const char *filename) { FILE *f = stbiw__fopen(filename, "wb"); stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f); return f != NULL; } static void stbi__end_write_file(stbi__write_context *s) { fclose((FILE *)s->context); } #endif // !STBI_WRITE_NO_STDIO typedef unsigned int stbiw_uint32; typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1]; static void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v) { while (*fmt) { switch (*fmt++) { case ' ': break; case '1': { unsigned char x = STBIW_UCHAR(va_arg(v, int)); s->func(s->context,&x,1); break; } case '2': { int x = va_arg(v,int); unsigned char b[2]; b[0] = STBIW_UCHAR(x); b[1] = STBIW_UCHAR(x>>8); s->func(s->context,b,2); break; } case '4': { stbiw_uint32 x = va_arg(v,int); unsigned char b[4]; b[0]=STBIW_UCHAR(x); b[1]=STBIW_UCHAR(x>>8); b[2]=STBIW_UCHAR(x>>16); b[3]=STBIW_UCHAR(x>>24); s->func(s->context,b,4); break; } default: STBIW_ASSERT(0); return; } } } static void stbiw__writef(stbi__write_context *s, const char *fmt, ...) { va_list v; va_start(v, fmt); stbiw__writefv(s, fmt, v); va_end(v); } static void stbiw__write_flush(stbi__write_context *s) { if (s->buf_used) { s->func(s->context, &s->buffer, s->buf_used); s->buf_used = 0; } } static void stbiw__putc(stbi__write_context *s, unsigned char c) { s->func(s->context, &c, 1); } static void stbiw__write1(stbi__write_context *s, unsigned char a) { if ((size_t)s->buf_used + 1 > sizeof(s->buffer)) stbiw__write_flush(s); s->buffer[s->buf_used++] = a; } static void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c) { int n; if ((size_t)s->buf_used + 3 > sizeof(s->buffer)) stbiw__write_flush(s); n = s->buf_used; s->buf_used = n+3; s->buffer[n+0] = a; s->buffer[n+1] = b; s->buffer[n+2] = c; } static void stbiw__write_pixel(stbi__write_context *s, int rgb_dir, int comp, int write_alpha, int expand_mono, unsigned char *d) { unsigned char bg[3] = { 255, 0, 255}, px[3]; int k; if (write_alpha < 0) stbiw__write1(s, d[comp - 1]); switch (comp) { case 2: // 2 pixels = mono + alpha, alpha is written separately, so same as 1-channel case case 1: if (expand_mono) stbiw__write3(s, d[0], d[0], d[0]); // monochrome bmp else stbiw__write1(s, d[0]); // monochrome TGA break; case 4: if (!write_alpha) { // composite against pink background for (k = 0; k < 3; ++k) px[k] = bg[k] + ((d[k] - bg[k]) * d[3]) / 255; stbiw__write3(s, px[1 - rgb_dir], px[1], px[1 + rgb_dir]); break; } /* FALLTHROUGH */ case 3: stbiw__write3(s, d[1 - rgb_dir], d[1], d[1 + rgb_dir]); break; } if (write_alpha > 0) stbiw__write1(s, d[comp - 1]); } static void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad, int expand_mono) { stbiw_uint32 zero = 0; int i,j, j_end; if (y <= 0) return; if (stbi__flip_vertically_on_write) vdir *= -1; if (vdir < 0) { j_end = -1; j = y-1; } else { j_end = y; j = 0; } for (; j != j_end; j += vdir) { for (i=0; i < x; ++i) { unsigned char *d = (unsigned char *) data + (j*x+i)*comp; stbiw__write_pixel(s, rgb_dir, comp, write_alpha, expand_mono, d); } stbiw__write_flush(s); s->func(s->context, &zero, scanline_pad); } } static int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, int expand_mono, void *data, int alpha, int pad, const char *fmt, ...) { if (y < 0 || x < 0) { return 0; } else { va_list v; va_start(v, fmt); stbiw__writefv(s, fmt, v); va_end(v); stbiw__write_pixels(s,rgb_dir,vdir,x,y,comp,data,alpha,pad, expand_mono); return 1; } } static int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp, const void *data) { if (comp != 4) { // write RGB bitmap int pad = (-x*3) & 3; return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *) data,0,pad, "11 4 22 4" "4 44 22 444444", 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header } else { // RGBA bitmaps need a v4 header // use BI_BITFIELDS mode with 32bpp and alpha mask // (straight BI_RGB with alpha mask doesn't work in most readers) return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *)data,1,0, "11 4 22 4" "4 44 22 444444 4444 4 444 444 444 444", 'B', 'M', 14+108+x*y*4, 0, 0, 14+108, // file header 108, x,y, 1,32, 3,0,0,0,0,0, 0xff0000,0xff00,0xff,0xff000000u, 0, 0,0,0, 0,0,0, 0,0,0, 0,0,0); // bitmap V4 header } } STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) { stbi__write_context s = { 0 }; stbi__start_write_callbacks(&s, func, context); return stbi_write_bmp_core(&s, x, y, comp, data); } #ifndef STBI_WRITE_NO_STDIO STBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data) { stbi__write_context s = { 0 }; if (stbi__start_write_file(&s,filename)) { int r = stbi_write_bmp_core(&s, x, y, comp, data); stbi__end_write_file(&s); return r; } else return 0; } #endif //!STBI_WRITE_NO_STDIO static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, void *data) { int has_alpha = (comp == 2 || comp == 4); int colorbytes = has_alpha ? comp-1 : comp; int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3 if (y < 0 || x < 0) return 0; if (!stbi_write_tga_with_rle) { return stbiw__outfile(s, -1, -1, x, y, comp, 0, (void *) data, has_alpha, 0, "111 221 2222 11", 0, 0, format, 0, 0, 0, 0, 0, x, y, (colorbytes + has_alpha) * 8, has_alpha * 8); } else { int i,j,k; int jend, jdir; stbiw__writef(s, "111 221 2222 11", 0,0,format+8, 0,0,0, 0,0,x,y, (colorbytes + has_alpha) * 8, has_alpha * 8); if (stbi__flip_vertically_on_write) { j = 0; jend = y; jdir = 1; } else { j = y-1; jend = -1; jdir = -1; } for (; j != jend; j += jdir) { unsigned char *row = (unsigned char *) data + j * x * comp; int len; for (i = 0; i < x; i += len) { unsigned char *begin = row + i * comp; int diff = 1; len = 1; if (i < x - 1) { ++len; diff = memcmp(begin, row + (i + 1) * comp, comp); if (diff) { const unsigned char *prev = begin; for (k = i + 2; k < x && len < 128; ++k) { if (memcmp(prev, row + k * comp, comp)) { prev += comp; ++len; } else { --len; break; } } } else { for (k = i + 2; k < x && len < 128; ++k) { if (!memcmp(begin, row + k * comp, comp)) { ++len; } else { break; } } } } if (diff) { unsigned char header = STBIW_UCHAR(len - 1); stbiw__write1(s, header); for (k = 0; k < len; ++k) { stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp); } } else { unsigned char header = STBIW_UCHAR(len - 129); stbiw__write1(s, header); stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin); } } } stbiw__write_flush(s); } return 1; } STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) { stbi__write_context s = { 0 }; stbi__start_write_callbacks(&s, func, context); return stbi_write_tga_core(&s, x, y, comp, (void *) data); } #ifndef STBI_WRITE_NO_STDIO STBIWDEF int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data) { stbi__write_context s = { 0 }; if (stbi__start_write_file(&s,filename)) { int r = stbi_write_tga_core(&s, x, y, comp, (void *) data); stbi__end_write_file(&s); return r; } else return 0; } #endif // ************************************************************************************************* // Radiance RGBE HDR writer // by Baldur Karlsson #define stbiw__max(a, b) ((a) > (b) ? (a) : (b)) #ifndef STBI_WRITE_NO_STDIO static void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear) { int exponent; float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2])); if (maxcomp < 1e-32f) { rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0; } else { float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp; rgbe[0] = (unsigned char)(linear[0] * normalize); rgbe[1] = (unsigned char)(linear[1] * normalize); rgbe[2] = (unsigned char)(linear[2] * normalize); rgbe[3] = (unsigned char)(exponent + 128); } } static void stbiw__write_run_data(stbi__write_context *s, int length, unsigned char databyte) { unsigned char lengthbyte = STBIW_UCHAR(length+128); STBIW_ASSERT(length+128 <= 255); s->func(s->context, &lengthbyte, 1); s->func(s->context, &databyte, 1); } static void stbiw__write_dump_data(stbi__write_context *s, int length, unsigned char *data) { unsigned char lengthbyte = STBIW_UCHAR(length); STBIW_ASSERT(length <= 128); // inconsistent with spec but consistent with official code s->func(s->context, &lengthbyte, 1); s->func(s->context, data, length); } static void stbiw__write_hdr_scanline(stbi__write_context *s, int width, int ncomp, unsigned char *scratch, float *scanline) { unsigned char scanlineheader[4] = { 2, 2, 0, 0 }; unsigned char rgbe[4]; float linear[3]; int x; scanlineheader[2] = (width&0xff00)>>8; scanlineheader[3] = (width&0x00ff); /* skip RLE for images too small or large */ if (width < 8 || width >= 32768) { for (x=0; x < width; x++) { switch (ncomp) { case 4: /* fallthrough */ case 3: linear[2] = scanline[x*ncomp + 2]; linear[1] = scanline[x*ncomp + 1]; linear[0] = scanline[x*ncomp + 0]; break; default: linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; break; } stbiw__linear_to_rgbe(rgbe, linear); s->func(s->context, rgbe, 4); } } else { int c,r; /* encode into scratch buffer */ for (x=0; x < width; x++) { switch(ncomp) { case 4: /* fallthrough */ case 3: linear[2] = scanline[x*ncomp + 2]; linear[1] = scanline[x*ncomp + 1]; linear[0] = scanline[x*ncomp + 0]; break; default: linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; break; } stbiw__linear_to_rgbe(rgbe, linear); scratch[x + width*0] = rgbe[0]; scratch[x + width*1] = rgbe[1]; scratch[x + width*2] = rgbe[2]; scratch[x + width*3] = rgbe[3]; } s->func(s->context, scanlineheader, 4); /* RLE each component separately */ for (c=0; c < 4; c++) { unsigned char *comp = &scratch[width*c]; x = 0; while (x < width) { // find first run r = x; while (r+2 < width) { if (comp[r] == comp[r+1] && comp[r] == comp[r+2]) break; ++r; } if (r+2 >= width) r = width; // dump up to first run while (x < r) { int len = r-x; if (len > 128) len = 128; stbiw__write_dump_data(s, len, &comp[x]); x += len; } // if there's a run, output it if (r+2 < width) { // same test as what we break out of in search loop, so only true if we break'd // find next byte after run while (r < width && comp[r] == comp[x]) ++r; // output run up to r while (x < r) { int len = r-x; if (len > 127) len = 127; stbiw__write_run_data(s, len, comp[x]); x += len; } } } } } } static int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp, float *data) { if (y <= 0 || x <= 0 || data == NULL) return 0; else { // Each component is stored separately. Allocate scratch space for full output scanline. unsigned char *scratch = (unsigned char *) STBIW_MALLOC(x*4); int i, len; char buffer[128]; char header[] = "#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n"; s->func(s->context, header, sizeof(header)-1); #ifdef __STDC_LIB_EXT1__ len = sprintf_s(buffer, sizeof(buffer), "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); #else len = snprintf(buffer, sizeof(buffer), "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); #endif s->func(s->context, buffer, len); for(i=0; i < y; i++) stbiw__write_hdr_scanline(s, x, comp, scratch, data + comp*x*(stbi__flip_vertically_on_write ? y-1-i : i)); STBIW_FREE(scratch); return 1; } } STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const float *data) { stbi__write_context s = { 0 }; stbi__start_write_callbacks(&s, func, context); return stbi_write_hdr_core(&s, x, y, comp, (float *) data); } STBIWDEF int stbi_write_hdr(char const *filename, int x, int y, int comp, const float *data) { stbi__write_context s = { 0 }; if (stbi__start_write_file(&s,filename)) { int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data); stbi__end_write_file(&s); return r; } else return 0; } #endif // STBI_WRITE_NO_STDIO ////////////////////////////////////////////////////////////////////////////// // // PNG writer // #ifndef STBIW_ZLIB_COMPRESS // stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size() #define stbiw__sbraw(a) ((int *) (void *) (a) - 2) #define stbiw__sbm(a) stbiw__sbraw(a)[0] #define stbiw__sbn(a) stbiw__sbraw(a)[1] #define stbiw__sbneedgrow(a,n) ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a)) #define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0) #define stbiw__sbgrow(a,n) stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a))) #define stbiw__sbpush(a, v) (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v)) #define stbiw__sbcount(a) ((a) ? stbiw__sbn(a) : 0) #define stbiw__sbfree(a) ((a) ? STBIW_FREE(stbiw__sbraw(a)),0 : 0) static void *stbiw__sbgrowf(void **arr, int increment, int itemsize) { int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1; void *p = STBIW_REALLOC_SIZED(*arr ? stbiw__sbraw(*arr) : 0, *arr ? (stbiw__sbm(*arr)*itemsize + sizeof(int)*2) : 0, itemsize * m + sizeof(int)*2); STBIW_ASSERT(p); if (p) { if (!*arr) ((int *) p)[1] = 0; *arr = (void *) ((int *) p + 2); stbiw__sbm(*arr) = m; } return *arr; } static unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount) { while (*bitcount >= 8) { stbiw__sbpush(data, STBIW_UCHAR(*bitbuffer)); *bitbuffer >>= 8; *bitcount -= 8; } return data; } static int stbiw__zlib_bitrev(int code, int codebits) { int res=0; while (codebits--) { res = (res << 1) | (code & 1); code >>= 1; } return res; } static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit) { int i; for (i=0; i < limit && i < 258; ++i) if (a[i] != b[i]) break; return i; } static unsigned int stbiw__zhash(unsigned char *data) { stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16); hash ^= hash << 3; hash += hash >> 5; hash ^= hash << 4; hash += hash >> 17; hash ^= hash << 25; hash += hash >> 6; return hash; } #define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount)) #define stbiw__zlib_add(code,codebits) \ (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush()) #define stbiw__zlib_huffa(b,c) stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c) // default huffman tables #define stbiw__zlib_huff1(n) stbiw__zlib_huffa(0x30 + (n), 8) #define stbiw__zlib_huff2(n) stbiw__zlib_huffa(0x190 + (n)-144, 9) #define stbiw__zlib_huff3(n) stbiw__zlib_huffa(0 + (n)-256,7) #define stbiw__zlib_huff4(n) stbiw__zlib_huffa(0xc0 + (n)-280,8) #define stbiw__zlib_huff(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n)) #define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n)) #define stbiw__ZHASH 16384 #endif // STBIW_ZLIB_COMPRESS STBIWDEF unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality) { #ifdef STBIW_ZLIB_COMPRESS // user provided a zlib compress implementation, use that return STBIW_ZLIB_COMPRESS(data, data_len, out_len, quality); #else // use builtin static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 }; static unsigned char lengtheb[]= { 0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; static unsigned short distc[] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 32768 }; static unsigned char disteb[] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 }; unsigned int bitbuf=0; int i,j, bitcount=0; unsigned char *out = NULL; unsigned char ***hash_table = (unsigned char***) STBIW_MALLOC(stbiw__ZHASH * sizeof(unsigned char**)); if (hash_table == NULL) return NULL; if (quality < 5) quality = 5; stbiw__sbpush(out, 0x78); // DEFLATE 32K window stbiw__sbpush(out, 0x5e); // FLEVEL = 1 stbiw__zlib_add(1,1); // BFINAL = 1 stbiw__zlib_add(1,2); // BTYPE = 1 -- fixed huffman for (i=0; i < stbiw__ZHASH; ++i) hash_table[i] = NULL; i=0; while (i < data_len-3) { // hash next 3 bytes of data to be compressed int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3; unsigned char *bestloc = 0; unsigned char **hlist = hash_table[h]; int n = stbiw__sbcount(hlist); for (j=0; j < n; ++j) { if (hlist[j]-data > i-32768) { // if entry lies within window int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i); if (d >= best) { best=d; bestloc=hlist[j]; } } } // when hash table entry is too long, delete half the entries if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) { STBIW_MEMMOVE(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality); stbiw__sbn(hash_table[h]) = quality; } stbiw__sbpush(hash_table[h],data+i); if (bestloc) { // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1); hlist = hash_table[h]; n = stbiw__sbcount(hlist); for (j=0; j < n; ++j) { if (hlist[j]-data > i-32767) { int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1); if (e > best) { // if next match is better, bail on current match bestloc = NULL; break; } } } } if (bestloc) { int d = (int) (data+i - bestloc); // distance back STBIW_ASSERT(d <= 32767 && best <= 258); for (j=0; best > lengthc[j+1]-1; ++j); stbiw__zlib_huff(j+257); if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]); for (j=0; d > distc[j+1]-1; ++j); stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5); if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]); i += best; } else { stbiw__zlib_huffb(data[i]); ++i; } } // write out final bytes for (;i < data_len; ++i) stbiw__zlib_huffb(data[i]); stbiw__zlib_huff(256); // end of block // pad with 0 bits to byte boundary while (bitcount) stbiw__zlib_add(0,1); for (i=0; i < stbiw__ZHASH; ++i) (void) stbiw__sbfree(hash_table[i]); STBIW_FREE(hash_table); // store uncompressed instead if compression was worse if (stbiw__sbn(out) > data_len + 2 + ((data_len+32766)/32767)*5) { stbiw__sbn(out) = 2; // truncate to DEFLATE 32K window and FLEVEL = 1 for (j = 0; j < data_len;) { int blocklen = data_len - j; if (blocklen > 32767) blocklen = 32767; stbiw__sbpush(out, data_len - j == blocklen); // BFINAL = ?, BTYPE = 0 -- no compression stbiw__sbpush(out, STBIW_UCHAR(blocklen)); // LEN stbiw__sbpush(out, STBIW_UCHAR(blocklen >> 8)); stbiw__sbpush(out, STBIW_UCHAR(~blocklen)); // NLEN stbiw__sbpush(out, STBIW_UCHAR(~blocklen >> 8)); memcpy(out+stbiw__sbn(out), data+j, blocklen); stbiw__sbn(out) += blocklen; j += blocklen; } } { // compute adler32 on input unsigned int s1=1, s2=0; int blocklen = (int) (data_len % 5552); j=0; while (j < data_len) { for (i=0; i < blocklen; ++i) { s1 += data[j+i]; s2 += s1; } s1 %= 65521; s2 %= 65521; j += blocklen; blocklen = 5552; } stbiw__sbpush(out, STBIW_UCHAR(s2 >> 8)); stbiw__sbpush(out, STBIW_UCHAR(s2)); stbiw__sbpush(out, STBIW_UCHAR(s1 >> 8)); stbiw__sbpush(out, STBIW_UCHAR(s1)); } *out_len = stbiw__sbn(out); // make returned pointer freeable STBIW_MEMMOVE(stbiw__sbraw(out), out, *out_len); return (unsigned char *) stbiw__sbraw(out); #endif // STBIW_ZLIB_COMPRESS } static unsigned int stbiw__crc32(unsigned char *buffer, int len) { #ifdef STBIW_CRC32 return STBIW_CRC32(buffer, len); #else static unsigned int crc_table[256] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0eDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; unsigned int crc = ~0u; int i; for (i=0; i < len; ++i) crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)]; return ~crc; #endif } #define stbiw__wpng4(o,a,b,c,d) ((o)[0]=STBIW_UCHAR(a),(o)[1]=STBIW_UCHAR(b),(o)[2]=STBIW_UCHAR(c),(o)[3]=STBIW_UCHAR(d),(o)+=4) #define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v)); #define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3]) static void stbiw__wpcrc(unsigned char **data, int len) { unsigned int crc = stbiw__crc32(*data - len - 4, len+4); stbiw__wp32(*data, crc); } static unsigned char stbiw__paeth(int a, int b, int c) { int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c); if (pa <= pb && pa <= pc) return STBIW_UCHAR(a); if (pb <= pc) return STBIW_UCHAR(b); return STBIW_UCHAR(c); } // @OPTIMIZE: provide an option that always forces left-predict or paeth predict static void stbiw__encode_png_line(unsigned char *pixels, int stride_bytes, int width, int height, int y, int n, int filter_type, signed char *line_buffer) { static int mapping[] = { 0,1,2,3,4 }; static int firstmap[] = { 0,1,0,5,6 }; int *mymap = (y != 0) ? mapping : firstmap; int i; int type = mymap[filter_type]; unsigned char *z = pixels + stride_bytes * (stbi__flip_vertically_on_write ? height-1-y : y); int signed_stride = stbi__flip_vertically_on_write ? -stride_bytes : stride_bytes; if (type==0) { memcpy(line_buffer, z, width*n); return; } // first loop isn't optimized since it's just one pixel for (i = 0; i < n; ++i) { switch (type) { case 1: line_buffer[i] = z[i]; break; case 2: line_buffer[i] = z[i] - z[i-signed_stride]; break; case 3: line_buffer[i] = z[i] - (z[i-signed_stride]>>1); break; case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-signed_stride],0)); break; case 5: line_buffer[i] = z[i]; break; case 6: line_buffer[i] = z[i]; break; } } switch (type) { case 1: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-n]; break; case 2: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-signed_stride]; break; case 3: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - ((z[i-n] + z[i-signed_stride])>>1); break; case 4: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-signed_stride], z[i-signed_stride-n]); break; case 5: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - (z[i-n]>>1); break; case 6: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break; } } STBIWDEF unsigned char *stbi_write_png_to_mem(const unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len) { int force_filter = stbi_write_force_png_filter; int ctype[5] = { -1, 0, 4, 2, 6 }; unsigned char sig[8] = { 137,80,78,71,13,10,26,10 }; unsigned char *out,*o, *filt, *zlib; signed char *line_buffer; int j,zlen; if (stride_bytes == 0) stride_bytes = x * n; if (force_filter >= 5) { force_filter = -1; } filt = (unsigned char *) STBIW_MALLOC((x*n+1) * y); if (!filt) return 0; line_buffer = (signed char *) STBIW_MALLOC(x * n); if (!line_buffer) { STBIW_FREE(filt); return 0; } for (j=0; j < y; ++j) { int filter_type; if (force_filter > -1) { filter_type = force_filter; stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, force_filter, line_buffer); } else { // Estimate the best filter by running through all of them: int best_filter = 0, best_filter_val = 0x7fffffff, est, i; for (filter_type = 0; filter_type < 5; filter_type++) { stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, filter_type, line_buffer); // Estimate the entropy of the line using this filter; the less, the better. est = 0; for (i = 0; i < x*n; ++i) { est += abs((signed char) line_buffer[i]); } if (est < best_filter_val) { best_filter_val = est; best_filter = filter_type; } } if (filter_type != best_filter) { // If the last iteration already got us the best filter, don't redo it stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, best_filter, line_buffer); filter_type = best_filter; } } // when we get here, filter_type contains the filter type, and line_buffer contains the data filt[j*(x*n+1)] = (unsigned char) filter_type; STBIW_MEMMOVE(filt+j*(x*n+1)+1, line_buffer, x*n); } STBIW_FREE(line_buffer); zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, stbi_write_png_compression_level); STBIW_FREE(filt); if (!zlib) return 0; // each tag requires 12 bytes of overhead out = (unsigned char *) STBIW_MALLOC(8 + 12+13 + 12+zlen + 12); if (!out) return 0; *out_len = 8 + 12+13 + 12+zlen + 12; o=out; STBIW_MEMMOVE(o,sig,8); o+= 8; stbiw__wp32(o, 13); // header length stbiw__wptag(o, "IHDR"); stbiw__wp32(o, x); stbiw__wp32(o, y); *o++ = 8; *o++ = STBIW_UCHAR(ctype[n]); *o++ = 0; *o++ = 0; *o++ = 0; stbiw__wpcrc(&o,13); stbiw__wp32(o, zlen); stbiw__wptag(o, "IDAT"); STBIW_MEMMOVE(o, zlib, zlen); o += zlen; STBIW_FREE(zlib); stbiw__wpcrc(&o, zlen); stbiw__wp32(o,0); stbiw__wptag(o, "IEND"); stbiw__wpcrc(&o,0); STBIW_ASSERT(o == out + *out_len); return out; } #ifndef STBI_WRITE_NO_STDIO STBIWDEF int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes) { FILE *f; int len; unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); if (png == NULL) return 0; f = stbiw__fopen(filename, "wb"); if (!f) { STBIW_FREE(png); return 0; } fwrite(png, 1, len, f); fclose(f); STBIW_FREE(png); return 1; } #endif STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int stride_bytes) { int len; unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); if (png == NULL) return 0; func(context, png, len); STBIW_FREE(png); return 1; } /* *************************************************************************** * * JPEG writer * * This is based on Jon Olick's jo_jpeg.cpp: * public domain Simple, Minimalistic JPEG writer - http://www.jonolick.com/code.html */ static const unsigned char stbiw__jpg_ZigZag[] = { 0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18, 24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63 }; static void stbiw__jpg_writeBits(stbi__write_context *s, int *bitBufP, int *bitCntP, const unsigned short *bs) { int bitBuf = *bitBufP, bitCnt = *bitCntP; bitCnt += bs[1]; bitBuf |= bs[0] << (24 - bitCnt); while(bitCnt >= 8) { unsigned char c = (bitBuf >> 16) & 255; stbiw__putc(s, c); if(c == 255) { stbiw__putc(s, 0); } bitBuf <<= 8; bitCnt -= 8; } *bitBufP = bitBuf; *bitCntP = bitCnt; } static void stbiw__jpg_DCT(float *d0p, float *d1p, float *d2p, float *d3p, float *d4p, float *d5p, float *d6p, float *d7p) { float d0 = *d0p, d1 = *d1p, d2 = *d2p, d3 = *d3p, d4 = *d4p, d5 = *d5p, d6 = *d6p, d7 = *d7p; float z1, z2, z3, z4, z5, z11, z13; float tmp0 = d0 + d7; float tmp7 = d0 - d7; float tmp1 = d1 + d6; float tmp6 = d1 - d6; float tmp2 = d2 + d5; float tmp5 = d2 - d5; float tmp3 = d3 + d4; float tmp4 = d3 - d4; // Even part float tmp10 = tmp0 + tmp3; // phase 2 float tmp13 = tmp0 - tmp3; float tmp11 = tmp1 + tmp2; float tmp12 = tmp1 - tmp2; d0 = tmp10 + tmp11; // phase 3 d4 = tmp10 - tmp11; z1 = (tmp12 + tmp13) * 0.707106781f; // c4 d2 = tmp13 + z1; // phase 5 d6 = tmp13 - z1; // Odd part tmp10 = tmp4 + tmp5; // phase 2 tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; // The rotator is modified from fig 4-8 to avoid extra negations. z5 = (tmp10 - tmp12) * 0.382683433f; // c6 z2 = tmp10 * 0.541196100f + z5; // c2-c6 z4 = tmp12 * 1.306562965f + z5; // c2+c6 z3 = tmp11 * 0.707106781f; // c4 z11 = tmp7 + z3; // phase 5 z13 = tmp7 - z3; *d5p = z13 + z2; // phase 6 *d3p = z13 - z2; *d1p = z11 + z4; *d7p = z11 - z4; *d0p = d0; *d2p = d2; *d4p = d4; *d6p = d6; } static void stbiw__jpg_calcBits(int val, unsigned short bits[2]) { int tmp1 = val < 0 ? -val : val; val = val < 0 ? val-1 : val; bits[1] = 1; while(tmp1 >>= 1) { ++bits[1]; } bits[0] = val & ((1<0)&&(DU[end0pos]==0); --end0pos) { } // end0pos = first element in reverse order !=0 if(end0pos == 0) { stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); return DU[0]; } for(i = 1; i <= end0pos; ++i) { int startpos = i; int nrzeroes; unsigned short bits[2]; for (; DU[i]==0 && i<=end0pos; ++i) { } nrzeroes = i-startpos; if ( nrzeroes >= 16 ) { int lng = nrzeroes>>4; int nrmarker; for (nrmarker=1; nrmarker <= lng; ++nrmarker) stbiw__jpg_writeBits(s, bitBuf, bitCnt, M16zeroes); nrzeroes &= 15; } stbiw__jpg_calcBits(DU[i], bits); stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTAC[(nrzeroes<<4)+bits[1]]); stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits); } if(end0pos != 63) { stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); } return DU[0]; } static int stbi_write_jpg_core(stbi__write_context *s, int width, int height, int comp, const void* data, int quality) { // Constants that don't pollute global namespace static const unsigned char std_dc_luminance_nrcodes[] = {0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0}; static const unsigned char std_dc_luminance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; static const unsigned char std_ac_luminance_nrcodes[] = {0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d}; static const unsigned char std_ac_luminance_values[] = { 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08, 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28, 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59, 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89, 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6, 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2, 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa }; static const unsigned char std_dc_chrominance_nrcodes[] = {0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0}; static const unsigned char std_dc_chrominance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; static const unsigned char std_ac_chrominance_nrcodes[] = {0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77}; static const unsigned char std_ac_chrominance_values[] = { 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91, 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26, 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58, 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87, 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4, 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda, 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa }; // Huffman tables static const unsigned short YDC_HT[256][2] = { {0,2},{2,3},{3,3},{4,3},{5,3},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9}}; static const unsigned short UVDC_HT[256][2] = { {0,2},{1,2},{2,2},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9},{1022,10},{2046,11}}; static const unsigned short YAC_HT[256][2] = { {10,4},{0,2},{1,2},{4,3},{11,4},{26,5},{120,7},{248,8},{1014,10},{65410,16},{65411,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {12,4},{27,5},{121,7},{502,9},{2038,11},{65412,16},{65413,16},{65414,16},{65415,16},{65416,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {28,5},{249,8},{1015,10},{4084,12},{65417,16},{65418,16},{65419,16},{65420,16},{65421,16},{65422,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {58,6},{503,9},{4085,12},{65423,16},{65424,16},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {59,6},{1016,10},{65430,16},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {122,7},{2039,11},{65438,16},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {123,7},{4086,12},{65446,16},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {250,8},{4087,12},{65454,16},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {504,9},{32704,15},{65462,16},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {505,9},{65470,16},{65471,16},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {506,9},{65479,16},{65480,16},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {1017,10},{65488,16},{65489,16},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {1018,10},{65497,16},{65498,16},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {2040,11},{65506,16},{65507,16},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {65515,16},{65516,16},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{0,0},{0,0},{0,0},{0,0},{0,0}, {2041,11},{65525,16},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} }; static const unsigned short UVAC_HT[256][2] = { {0,2},{1,2},{4,3},{10,4},{24,5},{25,5},{56,6},{120,7},{500,9},{1014,10},{4084,12},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {11,4},{57,6},{246,8},{501,9},{2038,11},{4085,12},{65416,16},{65417,16},{65418,16},{65419,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {26,5},{247,8},{1015,10},{4086,12},{32706,15},{65420,16},{65421,16},{65422,16},{65423,16},{65424,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {27,5},{248,8},{1016,10},{4087,12},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{65430,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {58,6},{502,9},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{65438,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {59,6},{1017,10},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{65446,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {121,7},{2039,11},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{65454,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {122,7},{2040,11},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{65462,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {249,8},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{65470,16},{65471,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {503,9},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{65479,16},{65480,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {504,9},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{65488,16},{65489,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {505,9},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{65497,16},{65498,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {506,9},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{65506,16},{65507,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {2041,11},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{65515,16},{65516,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {16352,14},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{65525,16},{0,0},{0,0},{0,0},{0,0},{0,0}, {1018,10},{32707,15},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} }; static const int YQT[] = {16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22, 37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99}; static const int UVQT[] = {17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99, 99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99}; static const float aasf[] = { 1.0f * 2.828427125f, 1.387039845f * 2.828427125f, 1.306562965f * 2.828427125f, 1.175875602f * 2.828427125f, 1.0f * 2.828427125f, 0.785694958f * 2.828427125f, 0.541196100f * 2.828427125f, 0.275899379f * 2.828427125f }; int row, col, i, k, subsample; float fdtbl_Y[64], fdtbl_UV[64]; unsigned char YTable[64], UVTable[64]; if(!data || !width || !height || comp > 4 || comp < 1) { return 0; } quality = quality ? quality : 90; subsample = quality <= 90 ? 1 : 0; quality = quality < 1 ? 1 : quality > 100 ? 100 : quality; quality = quality < 50 ? 5000 / quality : 200 - quality * 2; for(i = 0; i < 64; ++i) { int uvti, yti = (YQT[i]*quality+50)/100; YTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (yti < 1 ? 1 : yti > 255 ? 255 : yti); uvti = (UVQT[i]*quality+50)/100; UVTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (uvti < 1 ? 1 : uvti > 255 ? 255 : uvti); } for(row = 0, k = 0; row < 8; ++row) { for(col = 0; col < 8; ++col, ++k) { fdtbl_Y[k] = 1 / (YTable [stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); fdtbl_UV[k] = 1 / (UVTable[stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); } } // Write Headers { static const unsigned char head0[] = { 0xFF,0xD8,0xFF,0xE0,0,0x10,'J','F','I','F',0,1,1,0,0,1,0,1,0,0,0xFF,0xDB,0,0x84,0 }; static const unsigned char head2[] = { 0xFF,0xDA,0,0xC,3,1,0,2,0x11,3,0x11,0,0x3F,0 }; const unsigned char head1[] = { 0xFF,0xC0,0,0x11,8,(unsigned char)(height>>8),STBIW_UCHAR(height),(unsigned char)(width>>8),STBIW_UCHAR(width), 3,1,(unsigned char)(subsample?0x22:0x11),0,2,0x11,1,3,0x11,1,0xFF,0xC4,0x01,0xA2,0 }; s->func(s->context, (void*)head0, sizeof(head0)); s->func(s->context, (void*)YTable, sizeof(YTable)); stbiw__putc(s, 1); s->func(s->context, UVTable, sizeof(UVTable)); s->func(s->context, (void*)head1, sizeof(head1)); s->func(s->context, (void*)(std_dc_luminance_nrcodes+1), sizeof(std_dc_luminance_nrcodes)-1); s->func(s->context, (void*)std_dc_luminance_values, sizeof(std_dc_luminance_values)); stbiw__putc(s, 0x10); // HTYACinfo s->func(s->context, (void*)(std_ac_luminance_nrcodes+1), sizeof(std_ac_luminance_nrcodes)-1); s->func(s->context, (void*)std_ac_luminance_values, sizeof(std_ac_luminance_values)); stbiw__putc(s, 1); // HTUDCinfo s->func(s->context, (void*)(std_dc_chrominance_nrcodes+1), sizeof(std_dc_chrominance_nrcodes)-1); s->func(s->context, (void*)std_dc_chrominance_values, sizeof(std_dc_chrominance_values)); stbiw__putc(s, 0x11); // HTUACinfo s->func(s->context, (void*)(std_ac_chrominance_nrcodes+1), sizeof(std_ac_chrominance_nrcodes)-1); s->func(s->context, (void*)std_ac_chrominance_values, sizeof(std_ac_chrominance_values)); s->func(s->context, (void*)head2, sizeof(head2)); } // Encode 8x8 macroblocks { static const unsigned short fillBits[] = {0x7F, 7}; int DCY=0, DCU=0, DCV=0; int bitBuf=0, bitCnt=0; // comp == 2 is grey+alpha (alpha is ignored) int ofsG = comp > 2 ? 1 : 0, ofsB = comp > 2 ? 2 : 0; const unsigned char *dataR = (const unsigned char *)data; const unsigned char *dataG = dataR + ofsG; const unsigned char *dataB = dataR + ofsB; int x, y, pos; if(subsample) { for(y = 0; y < height; y += 16) { for(x = 0; x < width; x += 16) { float Y[256], U[256], V[256]; for(row = y, pos = 0; row < y+16; ++row) { // row >= height => use last input row int clamped_row = (row < height) ? row : height - 1; int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; for(col = x; col < x+16; ++col, ++pos) { // if col >= width => use pixel from last input column int p = base_p + ((col < width) ? col : (width-1))*comp; float r = dataR[p], g = dataG[p], b = dataB[p]; Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; } } DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+0, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+8, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+128, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+136, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); // subsample U,V { float subU[64], subV[64]; int yy, xx; for(yy = 0, pos = 0; yy < 8; ++yy) { for(xx = 0; xx < 8; ++xx, ++pos) { int j = yy*32+xx*2; subU[pos] = (U[j+0] + U[j+1] + U[j+16] + U[j+17]) * 0.25f; subV[pos] = (V[j+0] + V[j+1] + V[j+16] + V[j+17]) * 0.25f; } } DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subU, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subV, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); } } } } else { for(y = 0; y < height; y += 8) { for(x = 0; x < width; x += 8) { float Y[64], U[64], V[64]; for(row = y, pos = 0; row < y+8; ++row) { // row >= height => use last input row int clamped_row = (row < height) ? row : height - 1; int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; for(col = x; col < x+8; ++col, ++pos) { // if col >= width => use pixel from last input column int p = base_p + ((col < width) ? col : (width-1))*comp; float r = dataR[p], g = dataG[p], b = dataB[p]; Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; } } DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y, 8, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, U, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, V, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); } } } // Do the bit alignment of the EOI marker stbiw__jpg_writeBits(s, &bitBuf, &bitCnt, fillBits); } // EOI stbiw__putc(s, 0xFF); stbiw__putc(s, 0xD9); return 1; } STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality) { stbi__write_context s = { 0 }; stbi__start_write_callbacks(&s, func, context); return stbi_write_jpg_core(&s, x, y, comp, (void *) data, quality); } #ifndef STBI_WRITE_NO_STDIO STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality) { stbi__write_context s = { 0 }; if (stbi__start_write_file(&s,filename)) { int r = stbi_write_jpg_core(&s, x, y, comp, data, quality); stbi__end_write_file(&s); return r; } else return 0; } #endif #endif // STB_IMAGE_WRITE_IMPLEMENTATION /* Revision history 1.16 (2021-07-11) make Deflate code emit uncompressed blocks when it would otherwise expand support writing BMPs with alpha channel 1.15 (2020-07-13) unknown 1.14 (2020-02-02) updated JPEG writer to downsample chroma channels 1.13 1.12 1.11 (2019-08-11) 1.10 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs 1.09 (2018-02-11) fix typo in zlib quality API, improve STB_I_W_STATIC in C++ 1.08 (2018-01-29) add stbi__flip_vertically_on_write, external zlib, zlib quality, choose PNG filter 1.07 (2017-07-24) doc fix 1.06 (2017-07-23) writing JPEG (using Jon Olick's code) 1.05 ??? 1.04 (2017-03-03) monochrome BMP expansion 1.03 ??? 1.02 (2016-04-02) avoid allocating large structures on the stack 1.01 (2016-01-16) STBIW_REALLOC_SIZED: support allocators with no realloc support avoid race-condition in crc initialization minor compile issues 1.00 (2015-09-14) installable file IO function 0.99 (2015-09-13) warning fixes; TGA rle support 0.98 (2015-04-08) added STBIW_MALLOC, STBIW_ASSERT etc 0.97 (2015-01-18) fixed HDR asserts, rewrote HDR rle logic 0.96 (2015-01-17) add HDR output fix monochrome BMP 0.95 (2014-08-17) add monochrome TGA output 0.94 (2014-05-31) rename private functions to avoid conflicts with stb_image.h 0.93 (2014-05-27) warning fixes 0.92 (2010-08-01) casts to unsigned char to fix warnings 0.91 (2010-07-17) first public release 0.90 first internal release */ /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */ ================================================ FILE: samples/stb_truetype.h ================================================ // stb_truetype.h - v1.26 - public domain // authored from 2009-2021 by Sean Barrett / RAD Game Tools // // ======================================================================= // // NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES // // This library does no range checking of the offsets found in the file, // meaning an attacker can use it to read arbitrary memory. // // ======================================================================= // // This library processes TrueType files: // parse files // extract glyph metrics // extract glyph shapes // render glyphs to one-channel bitmaps with antialiasing (box filter) // render glyphs to one-channel SDF bitmaps (signed-distance field/function) // // Todo: // non-MS cmaps // crashproof on bad data // hinting? (no longer patented) // cleartype-style AA? // optimize: use simple memory allocator for intermediates // optimize: build edge-list directly from curves // optimize: rasterize directly from curves? // // ADDITIONAL CONTRIBUTORS // // Mikko Mononen: compound shape support, more cmap formats // Tor Andersson: kerning, subpixel rendering // Dougall Johnson: OpenType / Type 2 font handling // Daniel Ribeiro Maciel: basic GPOS-based kerning // // Misc other: // Ryan Gordon // Simon Glass // github:IntellectualKitty // Imanol Celaya // Daniel Ribeiro Maciel // // Bug/warning reports/fixes: // "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe // Cass Everitt Martins Mozeiko github:aloucks // stoiko (Haemimont Games) Cap Petschulat github:oyvindjam // Brian Hook Omar Cornut github:vassvik // Walter van Niftrik Ryan Griege // David Gow Peter LaValle // David Given Sergey Popov // Ivan-Assen Ivanov Giumo X. Clanjor // Anthony Pesch Higor Euripedes // Johan Duparc Thomas Fields // Hou Qiming Derek Vinyard // Rob Loach Cort Stratton // Kenney Phillis Jr. Brian Costabile // Ken Voskuil (kaesve) Yakov Galka // // VERSION HISTORY // // 1.26 (2021-08-28) fix broken rasterizer // 1.25 (2021-07-11) many fixes // 1.24 (2020-02-05) fix warning // 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) // 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined // 1.21 (2019-02-25) fix warning // 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() // 1.19 (2018-02-11) GPOS kerning, STBTT_fmod // 1.18 (2018-01-29) add missing function // 1.17 (2017-07-23) make more arguments const; doc fix // 1.16 (2017-07-12) SDF support // 1.15 (2017-03-03) make more arguments const // 1.14 (2017-01-16) num-fonts-in-TTC function // 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual // 1.11 (2016-04-02) fix unused-variable warning // 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef // 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly // 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; // variant PackFontRanges to pack and render in separate phases; // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); // fixed an assert() bug in the new rasterizer // replace assert() with STBTT_assert() in new rasterizer // // Full history can be found at the end of this file. // // LICENSE // // See end of file for license information. // // USAGE // // Include this file in whatever places need to refer to it. In ONE C/C++ // file, write: // #define STB_TRUETYPE_IMPLEMENTATION // before the #include of this file. This expands out the actual // implementation into that C/C++ file. // // To make the implementation private to the file that generates the implementation, // #define STBTT_STATIC // // Simple 3D API (don't ship this, but it's fine for tools and quick start) // stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture // stbtt_GetBakedQuad() -- compute quad to draw for a given char // // Improved 3D API (more shippable): // #include "stb_rect_pack.h" -- optional, but you really want it // stbtt_PackBegin() // stbtt_PackSetOversampling() -- for improved quality on small fonts // stbtt_PackFontRanges() -- pack and renders // stbtt_PackEnd() // stbtt_GetPackedQuad() // // "Load" a font file from a memory buffer (you have to keep the buffer loaded) // stbtt_InitFont() // stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections // stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections // // Render a unicode codepoint to a bitmap // stbtt_GetCodepointBitmap() -- allocates and returns a bitmap // stbtt_MakeCodepointBitmap() -- renders into bitmap you provide // stbtt_GetCodepointBitmapBox() -- how big the bitmap must be // // Character advance/positioning // stbtt_GetCodepointHMetrics() // stbtt_GetFontVMetrics() // stbtt_GetFontVMetricsOS2() // stbtt_GetCodepointKernAdvance() // // Starting with version 1.06, the rasterizer was replaced with a new, // faster and generally-more-precise rasterizer. The new rasterizer more // accurately measures pixel coverage for anti-aliasing, except in the case // where multiple shapes overlap, in which case it overestimates the AA pixel // coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If // this turns out to be a problem, you can re-enable the old rasterizer with // #define STBTT_RASTERIZER_VERSION 1 // which will incur about a 15% speed hit. // // ADDITIONAL DOCUMENTATION // // Immediately after this block comment are a series of sample programs. // // After the sample programs is the "header file" section. This section // includes documentation for each API function. // // Some important concepts to understand to use this library: // // Codepoint // Characters are defined by unicode codepoints, e.g. 65 is // uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is // the hiragana for "ma". // // Glyph // A visual character shape (every codepoint is rendered as // some glyph) // // Glyph index // A font-specific integer ID representing a glyph // // Baseline // Glyph shapes are defined relative to a baseline, which is the // bottom of uppercase characters. Characters extend both above // and below the baseline. // // Current Point // As you draw text to the screen, you keep track of a "current point" // which is the origin of each character. The current point's vertical // position is the baseline. Even "baked fonts" use this model. // // Vertical Font Metrics // The vertical qualities of the font, used to vertically position // and space the characters. See docs for stbtt_GetFontVMetrics. // // Font Size in Pixels or Points // The preferred interface for specifying font sizes in stb_truetype // is to specify how tall the font's vertical extent should be in pixels. // If that sounds good enough, skip the next paragraph. // // Most font APIs instead use "points", which are a common typographic // measurement for describing font size, defined as 72 points per inch. // stb_truetype provides a point API for compatibility. However, true // "per inch" conventions don't make much sense on computer displays // since different monitors have different number of pixels per // inch. For example, Windows traditionally uses a convention that // there are 96 pixels per inch, thus making 'inch' measurements have // nothing to do with inches, and thus effectively defining a point to // be 1.333 pixels. Additionally, the TrueType font data provides // an explicit scale factor to scale a given font's glyphs to points, // but the author has observed that this scale factor is often wrong // for non-commercial fonts, thus making fonts scaled in points // according to the TrueType spec incoherently sized in practice. // // DETAILED USAGE: // // Scale: // Select how high you want the font to be, in points or pixels. // Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute // a scale factor SF that will be used by all other functions. // // Baseline: // You need to select a y-coordinate that is the baseline of where // your text will appear. Call GetFontBoundingBox to get the baseline-relative // bounding box for all characters. SF*-y0 will be the distance in pixels // that the worst-case character could extend above the baseline, so if // you want the top edge of characters to appear at the top of the // screen where y=0, then you would set the baseline to SF*-y0. // // Current point: // Set the current point where the first character will appear. The // first character could extend left of the current point; this is font // dependent. You can either choose a current point that is the leftmost // point and hope, or add some padding, or check the bounding box or // left-side-bearing of the first character to be displayed and set // the current point based on that. // // Displaying a character: // Compute the bounding box of the character. It will contain signed values // relative to . I.e. if it returns x0,y0,x1,y1, // then the character should be displayed in the rectangle from // to = 32 && *text < 128) { stbtt_aligned_quad q; stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y0); glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y0); glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y1); glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y1); } ++text; } glEnd(); } #endif // // ////////////////////////////////////////////////////////////////////////////// // // Complete program (this compiles): get a single bitmap, print as ASCII art // #if 0 #include #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation #include "stb_truetype.h" char ttf_buffer[1<<25]; int main(int argc, char **argv) { stbtt_fontinfo font; unsigned char *bitmap; int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); for (j=0; j < h; ++j) { for (i=0; i < w; ++i) putchar(" .:ioVM@"[bitmap[j*w+i]>>5]); putchar('\n'); } return 0; } #endif // // Output: // // .ii. // @@@@@@. // V@Mio@@o // :i. V@V // :oM@@M // :@@@MM@M // @@o o@M // :@@. M@M // @@@o@@@@ // :M@@V:@@. // ////////////////////////////////////////////////////////////////////////////// // // Complete program: print "Hello World!" banner, with bugs // #if 0 char buffer[24<<20]; unsigned char screen[20][79]; int main(int arg, char **argv) { stbtt_fontinfo font; int i,j,ascent,baseline,ch=0; float scale, xpos=2; // leave a little padding in case the character extends left char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); stbtt_InitFont(&font, buffer, 0); scale = stbtt_ScaleForPixelHeight(&font, 15); stbtt_GetFontVMetrics(&font, &ascent,0,0); baseline = (int) (ascent*scale); while (text[ch]) { int advance,lsb,x0,y0,x1,y1; float x_shift = xpos - (float) floor(xpos); stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb); stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1); stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]); // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong // because this API is really for baking character bitmaps into textures. if you want to render // a sequence of characters, you really need to render each bitmap to a temp buffer, then // "alpha blend" that into the working buffer xpos += (advance * scale); if (text[ch+1]) xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]); ++ch; } for (j=0; j < 20; ++j) { for (i=0; i < 78; ++i) putchar(" .:ioVM@"[screen[j][i]>>5]); putchar('\n'); } return 0; } #endif ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //// //// INTEGRATION WITH YOUR CODEBASE //// //// The following sections allow you to supply alternate definitions //// of C library functions used by stb_truetype, e.g. if you don't //// link with the C runtime library. #ifdef STB_TRUETYPE_IMPLEMENTATION // #define your own (u)stbtt_int8/16/32 before including to override this #ifndef stbtt_uint8 typedef unsigned char stbtt_uint8; typedef signed char stbtt_int8; typedef unsigned short stbtt_uint16; typedef signed short stbtt_int16; typedef unsigned int stbtt_uint32; typedef signed int stbtt_int32; #endif typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h #ifndef STBTT_ifloor #include #define STBTT_ifloor(x) ((int) floor(x)) #define STBTT_iceil(x) ((int) ceil(x)) #endif #ifndef STBTT_sqrt #include #define STBTT_sqrt(x) sqrt(x) #define STBTT_pow(x,y) pow(x,y) #endif #ifndef STBTT_fmod #include #define STBTT_fmod(x,y) fmod(x,y) #endif #ifndef STBTT_cos #include #define STBTT_cos(x) cos(x) #define STBTT_acos(x) acos(x) #endif #ifndef STBTT_fabs #include #define STBTT_fabs(x) fabs(x) #endif // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h #ifndef STBTT_malloc #include #define STBTT_malloc(x,u) ((void)(u),malloc(x)) #define STBTT_free(x,u) ((void)(u),free(x)) #endif #ifndef STBTT_assert #include #define STBTT_assert(x) assert(x) #endif #ifndef STBTT_strlen #include #define STBTT_strlen(x) strlen(x) #endif #ifndef STBTT_memcpy #include #define STBTT_memcpy memcpy #define STBTT_memset memset #endif #endif /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //// //// INTERFACE //// //// #ifndef __STB_INCLUDE_STB_TRUETYPE_H__ #define __STB_INCLUDE_STB_TRUETYPE_H__ #ifdef STBTT_STATIC #define STBTT_DEF static #else #define STBTT_DEF extern #endif #ifdef __cplusplus extern "C" { #endif // private structure typedef struct { unsigned char *data; int cursor; int size; } stbtt__buf; ////////////////////////////////////////////////////////////////////////////// // // TEXTURE BAKING API // // If you use this API, you only have to call two functions ever. // typedef struct { unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap float xoff,yoff,xadvance; } stbtt_bakedchar; STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) float pixel_height, // height of font in pixels unsigned char *pixels, int pw, int ph, // bitmap to be filled in int first_char, int num_chars, // characters to bake stbtt_bakedchar *chardata); // you allocate this, it's num_chars long // if return is positive, the first unused row of the bitmap // if return is negative, returns the negative of the number of characters that fit // if return is 0, no characters fit and no rows were used // This uses a very crappy packing. typedef struct { float x0,y0,s0,t0; // top-left float x1,y1,s1,t1; // bottom-right } stbtt_aligned_quad; STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above int char_index, // character to display float *xpos, float *ypos, // pointers to current position in screen pixel space stbtt_aligned_quad *q, // output: quad to draw int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier // Call GetBakedQuad with char_index = 'character - first_char', and it // creates the quad you need to draw and advances the current position. // // The coordinate system used assumes y increases downwards. // // Characters will extend both above and below the current position; // see discussion of "BASELINE" above. // // It's inefficient; you might want to c&p it and optimize it. STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap); // Query the font vertical metrics without having to create a font first. ////////////////////////////////////////////////////////////////////////////// // // NEW TEXTURE BAKING API // // This provides options for packing multiple fonts into one atlas, not // perfectly but better than nothing. typedef struct { unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap float xoff,yoff,xadvance; float xoff2,yoff2; } stbtt_packedchar; typedef struct stbtt_pack_context stbtt_pack_context; typedef struct stbtt_fontinfo stbtt_fontinfo; #ifndef STB_RECT_PACK_VERSION typedef struct stbrp_rect stbrp_rect; #endif STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context); // Initializes a packing context stored in the passed-in stbtt_pack_context. // Future calls using this context will pack characters into the bitmap passed // in here: a 1-channel bitmap that is width * height. stride_in_bytes is // the distance from one row to the next (or 0 to mean they are packed tightly // together). "padding" is the amount of padding to leave between each // character (normally you want '1' for bitmaps you'll use as textures with // bilinear filtering). // // Returns 0 on failure, 1 on success. STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc); // Cleans up the packing context and frees all memory. #define STBTT_POINT_SIZE(x) (-(x)) STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range); // Creates character bitmaps from the font_index'th font found in fontdata (use // font_index=0 if you don't know what that is). It creates num_chars_in_range // bitmaps for characters with unicode values starting at first_unicode_char_in_range // and increasing. Data for how to render them is stored in chardata_for_range; // pass these to stbtt_GetPackedQuad to get back renderable quads. // // font_size is the full height of the character from ascender to descender, // as computed by stbtt_ScaleForPixelHeight. To use a point size as computed // by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE() // and pass that result as 'font_size': // ..., 20 , ... // font max minus min y is 20 pixels tall // ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall typedef struct { float font_size; int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints int num_chars; stbtt_packedchar *chardata_for_range; // output unsigned char h_oversample, v_oversample; // don't set these, they're used internally } stbtt_pack_range; STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges); // Creates character bitmaps from multiple ranges of characters stored in // ranges. This will usually create a better-packed bitmap than multiple // calls to stbtt_PackFontRange. Note that you can call this multiple // times within a single PackBegin/PackEnd. STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample); // Oversampling a font increases the quality by allowing higher-quality subpixel // positioning, and is especially valuable at smaller text sizes. // // This function sets the amount of oversampling for all following calls to // stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given // pack context. The default (no oversampling) is achieved by h_oversample=1 // and v_oversample=1. The total number of pixels required is // h_oversample*v_oversample larger than the default; for example, 2x2 // oversampling requires 4x the storage of 1x1. For best results, render // oversampled textures with bilinear filtering. Look at the readme in // stb/tests/oversample for information about oversampled fonts // // To use with PackFontRangesGather etc., you must set it before calls // call to PackFontRangesGatherRects. STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip); // If skip != 0, this tells stb_truetype to skip any codepoints for which // there is no corresponding glyph. If skip=0, which is the default, then // codepoints without a glyph recived the font's "missing character" glyph, // typically an empty box by convention. STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above int char_index, // character to display float *xpos, float *ypos, // pointers to current position in screen pixel space stbtt_aligned_quad *q, // output: quad to draw int align_to_integer); STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); // Calling these functions in sequence is roughly equivalent to calling // stbtt_PackFontRanges(). If you more control over the packing of multiple // fonts, or if you want to pack custom data into a font texture, take a look // at the source to of stbtt_PackFontRanges() and create a custom version // using these functions, e.g. call GatherRects multiple times, // building up a single array of rects, then call PackRects once, // then call RenderIntoRects repeatedly. This may result in a // better packing than calling PackFontRanges multiple times // (or it may not). // this is an opaque structure that you shouldn't mess with which holds // all the context needed from PackBegin to PackEnd. struct stbtt_pack_context { void *user_allocator_context; void *pack_info; int width; int height; int stride_in_bytes; int padding; int skip_missing; unsigned int h_oversample, v_oversample; unsigned char *pixels; void *nodes; }; ////////////////////////////////////////////////////////////////////////////// // // FONT LOADING // // STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data); // This function will determine the number of fonts in a font file. TrueType // collection (.ttc) files may contain multiple fonts, while TrueType font // (.ttf) files only contain one font. The number of fonts can be used for // indexing with the previous function where the index is between zero and one // less than the total fonts. If an error occurs, -1 is returned. STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); // Each .ttf/.ttc file may have more than one font. Each font has a sequential // index number starting from 0. Call this function to get the font offset for // a given index; it returns -1 if the index is out of range. A regular .ttf // file will only define one font and it always be at offset 0, so it will // return '0' for index 0, and -1 for all other indices. // The following structure is defined publicly so you can declare one on // the stack or as a global or etc, but you should treat it as opaque. struct stbtt_fontinfo { void * userdata; unsigned char * data; // pointer to .ttf file int fontstart; // offset of start of font int numGlyphs; // number of glyphs, needed for range checking int loca,head,glyf,hhea,hmtx,kern,gpos,svg; // table locations as offset from start of .ttf int index_map; // a cmap mapping for our chosen character encoding int indexToLocFormat; // format needed to map from glyph index to glyph stbtt__buf cff; // cff font data stbtt__buf charstrings; // the charstring index stbtt__buf gsubrs; // global charstring subroutines index stbtt__buf subrs; // private charstring subroutines index stbtt__buf fontdicts; // array of font dicts stbtt__buf fdselect; // map from glyph to fontdict }; STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); // Given an offset into the file that defines a font, this function builds // the necessary cached info for the rest of the system. You must allocate // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't // need to do anything special to free it, because the contents are pure // value data with no additional data structures. Returns 0 on failure. ////////////////////////////////////////////////////////////////////////////// // // CHARACTER TO GLYPH-INDEX CONVERSIOn STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); // If you're going to perform multiple operations on the same character // and you want a speed-up, call this function with the character you're // going to process, then use glyph-based functions instead of the // codepoint-based functions. // Returns 0 if the character codepoint is not defined in the font. ////////////////////////////////////////////////////////////////////////////// // // CHARACTER PROPERTIES // STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); // computes a scale factor to produce a font whose "height" is 'pixels' tall. // Height is measured as the distance from the highest ascender to the lowest // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics // and computing: // scale = pixels / (ascent - descent) // so if you prefer to measure height by the ascent only, use a similar calculation. STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); // computes a scale factor to produce a font whose EM size is mapped to // 'pixels' tall. This is probably what traditional APIs compute, but // I'm not positive. STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); // ascent is the coordinate above the baseline the font extends; descent // is the coordinate below the baseline the font extends (i.e. it is typically negative) // lineGap is the spacing between one row's descent and the next row's ascent... // so you should advance the vertical position by "*ascent - *descent + *lineGap" // these are expressed in unscaled coordinates, so you must multiply by // the scale factor for a given size STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); // analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 // table (specific to MS/Windows TTF files). // // Returns 1 on success (table present), 0 on failure. STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); // the bounding box around all possible characters STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); // leftSideBearing is the offset from the current horizontal position to the left edge of the character // advanceWidth is the offset from the current horizontal position to the next horizontal position // these are expressed in unscaled coordinates STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); // an additional amount to add to the 'advance' value between ch1 and ch2 STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); // Gets the bounding box of the visible part of the glyph, in unscaled coordinates STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); // as above, but takes one or more glyph indices for greater efficiency typedef struct stbtt_kerningentry { int glyph1; // use stbtt_FindGlyphIndex int glyph2; int advance; } stbtt_kerningentry; STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info); STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length); // Retrieves a complete list of all of the kerning pairs provided by the font // stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write. // The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1) ////////////////////////////////////////////////////////////////////////////// // // GLYPH SHAPES (you probably don't need these, but they have to go before // the bitmaps for C declaration-order reasons) // #ifndef STBTT_vmove // you can predefine these to use different values (but why?) enum { STBTT_vmove=1, STBTT_vline, STBTT_vcurve, STBTT_vcubic }; #endif #ifndef stbtt_vertex // you can predefine this to use different values // (we share this with other code at RAD) #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file typedef struct { stbtt_vertex_type x,y,cx,cy,cx1,cy1; unsigned char type,padding; } stbtt_vertex; #endif STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); // returns non-zero if nothing is drawn for this glyph STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); // returns # of vertices and fills *vertices with the pointer to them // these are expressed in "unscaled" coordinates // // The shape is a series of contours. Each one starts with // a STBTT_moveto, then consists of a series of mixed // STBTT_lineto and STBTT_curveto segments. A lineto // draws a line from previous endpoint to its x,y; a curveto // draws a quadratic bezier from previous endpoint to // its x,y, using cx,cy as the bezier control point. STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); // frees the data allocated above STBTT_DEF unsigned char *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl); STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg); STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg); // fills svg with the character's SVG data. // returns data size or 0 if SVG not found. ////////////////////////////////////////////////////////////////////////////// // // BITMAP RENDERING // STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); // frees the bitmap allocated below STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); // allocates a large-enough single-channel 8bpp bitmap and renders the // specified character/glyph at the specified scale into it, with // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). // *width & *height are filled out with the width & height of the bitmap, // which is stored left-to-right, top-to-bottom. // // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff); // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel // shift for the character STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint); // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the // width and height and positioning info for it first. STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint); // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel // shift for the character STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint); // same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering // is performed (see stbtt_PackSetOversampling) STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); // get the bbox of the bitmap centered around the glyph origin; so the // bitmap width is ix1-ix0, height is iy1-iy0, and location to place // the bitmap top left is (leftSideBearing*scale,iy0). // (Note that the bitmap uses y-increases-down, but the shape uses // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel // shift for the character // the following functions are equivalent to the above functions, but operate // on glyph indices instead of Unicode codepoints (for efficiency) STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff); STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph); STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph); STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph); STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); // @TODO: don't expose this structure typedef struct { int w,h,stride; unsigned char *pixels; } stbtt__bitmap; // rasterize a shape with quadratic beziers into a bitmap STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into float flatness_in_pixels, // allowable error of curve in pixels stbtt_vertex *vertices, // array of vertices defining shape int num_verts, // number of vertices in above array float scale_x, float scale_y, // scale applied to input vertices float shift_x, float shift_y, // translation applied to input vertices int x_off, int y_off, // another translation applied to input int invert, // if non-zero, vertically flip shape void *userdata); // context for to STBTT_MALLOC ////////////////////////////////////////////////////////////////////////////// // // Signed Distance Function (or Field) rendering STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata); // frees the SDF bitmap allocated below STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); // These functions compute a discretized SDF field for a single character, suitable for storing // in a single-channel texture, sampling with bilinear filtering, and testing against // larger than some threshold to produce scalable fonts. // info -- the font // scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap // glyph/codepoint -- the character to generate the SDF for // padding -- extra "pixels" around the character which are filled with the distance to the character (not 0), // which allows effects like bit outlines // onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character) // pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale) // if positive, > onedge_value is inside; if negative, < onedge_value is inside // width,height -- output height & width of the SDF bitmap (including padding) // xoff,yoff -- output origin of the character // return value -- a 2D array of bytes 0..255, width*height in size // // pixel_dist_scale & onedge_value are a scale & bias that allows you to make // optimal use of the limited 0..255 for your application, trading off precision // and special effects. SDF values outside the range 0..255 are clamped to 0..255. // // Example: // scale = stbtt_ScaleForPixelHeight(22) // padding = 5 // onedge_value = 180 // pixel_dist_scale = 180/5.0 = 36.0 // // This will create an SDF bitmap in which the character is about 22 pixels // high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled // shape, sample the SDF at each pixel and fill the pixel if the SDF value // is greater than or equal to 180/255. (You'll actually want to antialias, // which is beyond the scope of this example.) Additionally, you can compute // offset outlines (e.g. to stroke the character border inside & outside, // or only outside). For example, to fill outside the character up to 3 SDF // pixels, you would compare against (180-36.0*3)/255 = 72/255. The above // choice of variables maps a range from 5 pixels outside the shape to // 2 pixels inside the shape to 0..255; this is intended primarily for apply // outside effects only (the interior range is needed to allow proper // antialiasing of the font at *smaller* sizes) // // The function computes the SDF analytically at each SDF pixel, not by e.g. // building a higher-res bitmap and approximating it. In theory the quality // should be as high as possible for an SDF of this size & representation, but // unclear if this is true in practice (perhaps building a higher-res bitmap // and computing from that can allow drop-out prevention). // // The algorithm has not been optimized at all, so expect it to be slow // if computing lots of characters or very large sizes. ////////////////////////////////////////////////////////////////////////////// // // Finding the right font... // // You should really just solve this offline, keep your own tables // of what font is what, and don't try to get it out of the .ttf file. // That's because getting it out of the .ttf file is really hard, because // the names in the file can appear in many possible encodings, in many // possible languages, and e.g. if you need a case-insensitive comparison, // the details of that depend on the encoding & language in a complex way // (actually underspecified in truetype, but also gigantic). // // But you can use the provided functions in two possible ways: // stbtt_FindMatchingFont() will use *case-sensitive* comparisons on // unicode-encoded names to try to find the font you want; // you can run this before calling stbtt_InitFont() // // stbtt_GetFontNameString() lets you get any of the various strings // from the file yourself and do your own comparisons on them. // You have to have called stbtt_InitFont() first. STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); // returns the offset (not index) of the font that matches, or -1 if none // if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". // if you use any other flag, use a font name like "Arial"; this checks // the 'macStyle' header field; i don't know if fonts set this consistently #define STBTT_MACSTYLE_DONTCARE 0 #define STBTT_MACSTYLE_BOLD 1 #define STBTT_MACSTYLE_ITALIC 2 #define STBTT_MACSTYLE_UNDERSCORE 4 #define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); // returns 1/0 whether the first string interpreted as utf8 is identical to // the second string interpreted as big-endian utf16... useful for strings from next func STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); // returns the string (which may be big-endian double byte, e.g. for unicode) // and puts the length in bytes in *length. // // some of the values for the IDs are below; for more see the truetype spec: // http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html // http://www.microsoft.com/typography/otspec/name.htm enum { // platformID STBTT_PLATFORM_ID_UNICODE =0, STBTT_PLATFORM_ID_MAC =1, STBTT_PLATFORM_ID_ISO =2, STBTT_PLATFORM_ID_MICROSOFT =3 }; enum { // encodingID for STBTT_PLATFORM_ID_UNICODE STBTT_UNICODE_EID_UNICODE_1_0 =0, STBTT_UNICODE_EID_UNICODE_1_1 =1, STBTT_UNICODE_EID_ISO_10646 =2, STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 }; enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT STBTT_MS_EID_SYMBOL =0, STBTT_MS_EID_UNICODE_BMP =1, STBTT_MS_EID_SHIFTJIS =2, STBTT_MS_EID_UNICODE_FULL =10 }; enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 }; enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D }; enum { // languageID for STBTT_PLATFORM_ID_MAC STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 }; #ifdef __cplusplus } #endif #endif // __STB_INCLUDE_STB_TRUETYPE_H__ /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //// //// IMPLEMENTATION //// //// #ifdef STB_TRUETYPE_IMPLEMENTATION #ifndef STBTT_MAX_OVERSAMPLE #define STBTT_MAX_OVERSAMPLE 8 #endif #if STBTT_MAX_OVERSAMPLE > 255 #error "STBTT_MAX_OVERSAMPLE cannot be > 255" #endif typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1]; #ifndef STBTT_RASTERIZER_VERSION #define STBTT_RASTERIZER_VERSION 2 #endif #ifdef _MSC_VER #define STBTT__NOTUSED(v) (void)(v) #else #define STBTT__NOTUSED(v) (void)sizeof(v) #endif ////////////////////////////////////////////////////////////////////////// // // stbtt__buf helpers to parse data from file // static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b) { if (b->cursor >= b->size) return 0; return b->data[b->cursor++]; } static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b) { if (b->cursor >= b->size) return 0; return b->data[b->cursor]; } static void stbtt__buf_seek(stbtt__buf *b, int o) { STBTT_assert(!(o > b->size || o < 0)); b->cursor = (o > b->size || o < 0) ? b->size : o; } static void stbtt__buf_skip(stbtt__buf *b, int o) { stbtt__buf_seek(b, b->cursor + o); } static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n) { stbtt_uint32 v = 0; int i; STBTT_assert(n >= 1 && n <= 4); for (i = 0; i < n; i++) v = (v << 8) | stbtt__buf_get8(b); return v; } static stbtt__buf stbtt__new_buf(const void *p, size_t size) { stbtt__buf r; STBTT_assert(size < 0x40000000); r.data = (stbtt_uint8*) p; r.size = (int) size; r.cursor = 0; return r; } #define stbtt__buf_get16(b) stbtt__buf_get((b), 2) #define stbtt__buf_get32(b) stbtt__buf_get((b), 4) static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s) { stbtt__buf r = stbtt__new_buf(NULL, 0); if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r; r.data = b->data + o; r.size = s; return r; } static stbtt__buf stbtt__cff_get_index(stbtt__buf *b) { int count, start, offsize; start = b->cursor; count = stbtt__buf_get16(b); if (count) { offsize = stbtt__buf_get8(b); STBTT_assert(offsize >= 1 && offsize <= 4); stbtt__buf_skip(b, offsize * count); stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1); } return stbtt__buf_range(b, start, b->cursor - start); } static stbtt_uint32 stbtt__cff_int(stbtt__buf *b) { int b0 = stbtt__buf_get8(b); if (b0 >= 32 && b0 <= 246) return b0 - 139; else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108; else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108; else if (b0 == 28) return stbtt__buf_get16(b); else if (b0 == 29) return stbtt__buf_get32(b); STBTT_assert(0); return 0; } static void stbtt__cff_skip_operand(stbtt__buf *b) { int v, b0 = stbtt__buf_peek8(b); STBTT_assert(b0 >= 28); if (b0 == 30) { stbtt__buf_skip(b, 1); while (b->cursor < b->size) { v = stbtt__buf_get8(b); if ((v & 0xF) == 0xF || (v >> 4) == 0xF) break; } } else { stbtt__cff_int(b); } } static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key) { stbtt__buf_seek(b, 0); while (b->cursor < b->size) { int start = b->cursor, end, op; while (stbtt__buf_peek8(b) >= 28) stbtt__cff_skip_operand(b); end = b->cursor; op = stbtt__buf_get8(b); if (op == 12) op = stbtt__buf_get8(b) | 0x100; if (op == key) return stbtt__buf_range(b, start, end-start); } return stbtt__buf_range(b, 0, 0); } static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out) { int i; stbtt__buf operands = stbtt__dict_get(b, key); for (i = 0; i < outcount && operands.cursor < operands.size; i++) out[i] = stbtt__cff_int(&operands); } static int stbtt__cff_index_count(stbtt__buf *b) { stbtt__buf_seek(b, 0); return stbtt__buf_get16(b); } static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i) { int count, offsize, start, end; stbtt__buf_seek(&b, 0); count = stbtt__buf_get16(&b); offsize = stbtt__buf_get8(&b); STBTT_assert(i >= 0 && i < count); STBTT_assert(offsize >= 1 && offsize <= 4); stbtt__buf_skip(&b, i*offsize); start = stbtt__buf_get(&b, offsize); end = stbtt__buf_get(&b, offsize); return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start); } ////////////////////////////////////////////////////////////////////////// // // accessors to parse data from file // // on platforms that don't allow misaligned reads, if we want to allow // truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE #define ttBYTE(p) (* (stbtt_uint8 *) (p)) #define ttCHAR(p) (* (stbtt_int8 *) (p)) #define ttFixed(p) ttLONG(p) static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) #define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) static int stbtt__isfont(stbtt_uint8 *font) { // check the version number if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts return 0; } // @OPTIMIZE: binary search static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) { stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); stbtt_uint32 tabledir = fontstart + 12; stbtt_int32 i; for (i=0; i < num_tables; ++i) { stbtt_uint32 loc = tabledir + 16*i; if (stbtt_tag(data+loc+0, tag)) return ttULONG(data+loc+8); } return 0; } static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index) { // if it's just a font, there's only one valid index if (stbtt__isfont(font_collection)) return index == 0 ? 0 : -1; // check if it's a TTC if (stbtt_tag(font_collection, "ttcf")) { // version 1? if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { stbtt_int32 n = ttLONG(font_collection+8); if (index >= n) return -1; return ttULONG(font_collection+12+index*4); } } return -1; } static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection) { // if it's just a font, there's only one valid font if (stbtt__isfont(font_collection)) return 1; // check if it's a TTC if (stbtt_tag(font_collection, "ttcf")) { // version 1? if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { return ttLONG(font_collection+8); } } return 0; } static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict) { stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 }; stbtt__buf pdict; stbtt__dict_get_ints(&fontdict, 18, 2, private_loc); if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0); pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]); stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff); if (!subrsoff) return stbtt__new_buf(NULL, 0); stbtt__buf_seek(&cff, private_loc[1]+subrsoff); return stbtt__cff_get_index(&cff); } // since most people won't use this, find this table the first time it's needed static int stbtt__get_svg(stbtt_fontinfo *info) { stbtt_uint32 t; if (info->svg < 0) { t = stbtt__find_table(info->data, info->fontstart, "SVG "); if (t) { stbtt_uint32 offset = ttULONG(info->data + t + 2); info->svg = t + offset; } else { info->svg = 0; } } return info->svg; } static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart) { stbtt_uint32 cmap, t; stbtt_int32 i,numTables; info->data = data; info->fontstart = fontstart; info->cff = stbtt__new_buf(NULL, 0); cmap = stbtt__find_table(data, fontstart, "cmap"); // required info->loca = stbtt__find_table(data, fontstart, "loca"); // required info->head = stbtt__find_table(data, fontstart, "head"); // required info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required info->kern = stbtt__find_table(data, fontstart, "kern"); // not required info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required if (!cmap || !info->head || !info->hhea || !info->hmtx) return 0; if (info->glyf) { // required for truetype if (!info->loca) return 0; } else { // initialization for CFF / Type2 fonts (OTF) stbtt__buf b, topdict, topdictidx; stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0; stbtt_uint32 cff; cff = stbtt__find_table(data, fontstart, "CFF "); if (!cff) return 0; info->fontdicts = stbtt__new_buf(NULL, 0); info->fdselect = stbtt__new_buf(NULL, 0); // @TODO this should use size from table (not 512MB) info->cff = stbtt__new_buf(data+cff, 512*1024*1024); b = info->cff; // read the header stbtt__buf_skip(&b, 2); stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize // @TODO the name INDEX could list multiple fonts, // but we just use the first one. stbtt__cff_get_index(&b); // name INDEX topdictidx = stbtt__cff_get_index(&b); topdict = stbtt__cff_index_get(topdictidx, 0); stbtt__cff_get_index(&b); // string INDEX info->gsubrs = stbtt__cff_get_index(&b); stbtt__dict_get_ints(&topdict, 17, 1, &charstrings); stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype); stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff); stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff); info->subrs = stbtt__get_subrs(b, topdict); // we only support Type 2 charstrings if (cstype != 2) return 0; if (charstrings == 0) return 0; if (fdarrayoff) { // looks like a CID font if (!fdselectoff) return 0; stbtt__buf_seek(&b, fdarrayoff); info->fontdicts = stbtt__cff_get_index(&b); info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff); } stbtt__buf_seek(&b, charstrings); info->charstrings = stbtt__cff_get_index(&b); } t = stbtt__find_table(data, fontstart, "maxp"); if (t) info->numGlyphs = ttUSHORT(data+t+4); else info->numGlyphs = 0xffff; info->svg = -1; // find a cmap encoding table we understand *now* to avoid searching // later. (todo: could make this installable) // the same regardless of glyph. numTables = ttUSHORT(data + cmap + 2); info->index_map = 0; for (i=0; i < numTables; ++i) { stbtt_uint32 encoding_record = cmap + 4 + 8 * i; // find an encoding we understand: switch(ttUSHORT(data+encoding_record)) { case STBTT_PLATFORM_ID_MICROSOFT: switch (ttUSHORT(data+encoding_record+2)) { case STBTT_MS_EID_UNICODE_BMP: case STBTT_MS_EID_UNICODE_FULL: // MS/Unicode info->index_map = cmap + ttULONG(data+encoding_record+4); break; } break; case STBTT_PLATFORM_ID_UNICODE: // Mac/iOS has these // all the encodingIDs are unicode, so we don't bother to check it info->index_map = cmap + ttULONG(data+encoding_record+4); break; } } if (info->index_map == 0) return 0; info->indexToLocFormat = ttUSHORT(data+info->head + 50); return 1; } STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint) { stbtt_uint8 *data = info->data; stbtt_uint32 index_map = info->index_map; stbtt_uint16 format = ttUSHORT(data + index_map + 0); if (format == 0) { // apple byte encoding stbtt_int32 bytes = ttUSHORT(data + index_map + 2); if (unicode_codepoint < bytes-6) return ttBYTE(data + index_map + 6 + unicode_codepoint); return 0; } else if (format == 6) { stbtt_uint32 first = ttUSHORT(data + index_map + 6); stbtt_uint32 count = ttUSHORT(data + index_map + 8); if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count) return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2); return 0; } else if (format == 2) { STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean return 0; } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1; stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1; stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10); stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; // do a binary search of the segments stbtt_uint32 endCount = index_map + 14; stbtt_uint32 search = endCount; if (unicode_codepoint > 0xffff) return 0; // they lie from endCount .. endCount + segCount // but searchRange is the nearest power of two, so... if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2)) search += rangeShift*2; // now decrement to bias correctly to find smallest search -= 2; while (entrySelector) { stbtt_uint16 end; searchRange >>= 1; end = ttUSHORT(data + search + searchRange*2); if (unicode_codepoint > end) search += searchRange*2; --entrySelector; } search += 2; { stbtt_uint16 offset, start, last; stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); last = ttUSHORT(data + endCount + 2*item); if (unicode_codepoint < start || unicode_codepoint > last) return 0; offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); if (offset == 0) return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); } } else if (format == 12 || format == 13) { stbtt_uint32 ngroups = ttULONG(data+index_map+12); stbtt_int32 low,high; low = 0; high = (stbtt_int32)ngroups; // Binary search the right group. while (low < high) { stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12); stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4); if ((stbtt_uint32) unicode_codepoint < start_char) high = mid; else if ((stbtt_uint32) unicode_codepoint > end_char) low = mid+1; else { stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8); if (format == 12) return start_glyph + unicode_codepoint-start_char; else // format == 13 return start_glyph; } } return 0; // not found } // @TODO STBTT_assert(0); return 0; } STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices) { return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices); } static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy) { v->type = type; v->x = (stbtt_int16) x; v->y = (stbtt_int16) y; v->cx = (stbtt_int16) cx; v->cy = (stbtt_int16) cy; } static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) { int g1,g2; STBTT_assert(!info->cff.size); if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format if (info->indexToLocFormat == 0) { g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; } else { g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4); g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4); } return g1==g2 ? -1 : g1; // if length is 0, return -1 } static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) { if (info->cff.size) { stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); } else { int g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 0; if (x0) *x0 = ttSHORT(info->data + g + 2); if (y0) *y0 = ttSHORT(info->data + g + 4); if (x1) *x1 = ttSHORT(info->data + g + 6); if (y1) *y1 = ttSHORT(info->data + g + 8); } return 1; } STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1) { return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1); } STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) { stbtt_int16 numberOfContours; int g; if (info->cff.size) return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0; g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 1; numberOfContours = ttSHORT(info->data + g); return numberOfContours == 0; } static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off, stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy) { if (start_off) { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy); } else { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy); else stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0); } return num_vertices; } static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) { stbtt_int16 numberOfContours; stbtt_uint8 *endPtsOfContours; stbtt_uint8 *data = info->data; stbtt_vertex *vertices=0; int num_vertices=0; int g = stbtt__GetGlyfOffset(info, glyph_index); *pvertices = NULL; if (g < 0) return 0; numberOfContours = ttSHORT(data + g); if (numberOfContours > 0) { stbtt_uint8 flags=0,flagcount; stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; stbtt_int32 x,y,cx,cy,sx,sy, scx,scy; stbtt_uint8 *points; endPtsOfContours = (data + g + 10); ins = ttUSHORT(data + g + 10 + numberOfContours * 2); points = data + g + 10 + numberOfContours * 2 + 2 + ins; n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2); m = n + 2*numberOfContours; // a loose bound on how many vertices we might need vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata); if (vertices == 0) return 0; next_move = 0; flagcount=0; // in first pass, we load uninterpreted data into the allocated array // above, shifted to the end of the array so we won't overwrite it when // we create our final data starting from the front off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated // first load flags for (i=0; i < n; ++i) { if (flagcount == 0) { flags = *points++; if (flags & 8) flagcount = *points++; } else --flagcount; vertices[off+i].type = flags; } // now load x coordinates x=0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; if (flags & 2) { stbtt_int16 dx = *points++; x += (flags & 16) ? dx : -dx; // ??? } else { if (!(flags & 16)) { x = x + (stbtt_int16) (points[0]*256 + points[1]); points += 2; } } vertices[off+i].x = (stbtt_int16) x; } // now load y coordinates y=0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; if (flags & 4) { stbtt_int16 dy = *points++; y += (flags & 32) ? dy : -dy; // ??? } else { if (!(flags & 32)) { y = y + (stbtt_int16) (points[0]*256 + points[1]); points += 2; } } vertices[off+i].y = (stbtt_int16) y; } // now convert them to our format num_vertices=0; sx = sy = cx = cy = scx = scy = 0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; x = (stbtt_int16) vertices[off+i].x; y = (stbtt_int16) vertices[off+i].y; if (next_move == i) { if (i != 0) num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); // now start the new one start_off = !(flags & 1); if (start_off) { // if we start off with an off-curve point, then when we need to find a point on the curve // where we can start, and we need to save some state for when we wraparound. scx = x; scy = y; if (!(vertices[off+i+1].type & 1)) { // next point is also a curve point, so interpolate an on-point curve sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1; sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1; } else { // otherwise just use the next point as our start point sx = (stbtt_int32) vertices[off+i+1].x; sy = (stbtt_int32) vertices[off+i+1].y; ++i; // we're using point i+1 as the starting point, so skip it } } else { sx = x; sy = y; } stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0); was_off = 0; next_move = 1 + ttUSHORT(endPtsOfContours+j*2); ++j; } else { if (!(flags & 1)) { // if it's a curve if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); cx = x; cy = y; was_off = 1; } else { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy); else stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0); was_off = 0; } } } num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); } else if (numberOfContours < 0) { // Compound shapes. int more = 1; stbtt_uint8 *comp = data + g + 10; num_vertices = 0; vertices = 0; while (more) { stbtt_uint16 flags, gidx; int comp_num_verts = 0, i; stbtt_vertex *comp_verts = 0, *tmp = 0; float mtx[6] = {1,0,0,1,0,0}, m, n; flags = ttSHORT(comp); comp+=2; gidx = ttSHORT(comp); comp+=2; if (flags & 2) { // XY values if (flags & 1) { // shorts mtx[4] = ttSHORT(comp); comp+=2; mtx[5] = ttSHORT(comp); comp+=2; } else { mtx[4] = ttCHAR(comp); comp+=1; mtx[5] = ttCHAR(comp); comp+=1; } } else { // @TODO handle matching point STBTT_assert(0); } if (flags & (1<<3)) { // WE_HAVE_A_SCALE mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = mtx[2] = 0; } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = mtx[2] = 0; mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = ttSHORT(comp)/16384.0f; comp+=2; mtx[2] = ttSHORT(comp)/16384.0f; comp+=2; mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; } // Find transformation scales. m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); // Get indexed glyph. comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); if (comp_num_verts > 0) { // Transform vertices. for (i = 0; i < comp_num_verts; ++i) { stbtt_vertex* v = &comp_verts[i]; stbtt_vertex_type x,y; x=v->x; y=v->y; v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); x=v->cx; y=v->cy; v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); } // Append vertices. tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); if (!tmp) { if (vertices) STBTT_free(vertices, info->userdata); if (comp_verts) STBTT_free(comp_verts, info->userdata); return 0; } if (num_vertices > 0 && vertices) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex)); if (vertices) STBTT_free(vertices, info->userdata); vertices = tmp; STBTT_free(comp_verts, info->userdata); num_vertices += comp_num_verts; } // More components ? more = flags & (1<<5); } } else { // numberOfCounters == 0, do nothing } *pvertices = vertices; return num_vertices; } typedef struct { int bounds; int started; float first_x, first_y; float x, y; stbtt_int32 min_x, max_x, min_y, max_y; stbtt_vertex *pvertices; int num_vertices; } stbtt__csctx; #define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0} static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y) { if (x > c->max_x || !c->started) c->max_x = x; if (y > c->max_y || !c->started) c->max_y = y; if (x < c->min_x || !c->started) c->min_x = x; if (y < c->min_y || !c->started) c->min_y = y; c->started = 1; } static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1) { if (c->bounds) { stbtt__track_vertex(c, x, y); if (type == STBTT_vcubic) { stbtt__track_vertex(c, cx, cy); stbtt__track_vertex(c, cx1, cy1); } } else { stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy); c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1; c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1; } c->num_vertices++; } static void stbtt__csctx_close_shape(stbtt__csctx *ctx) { if (ctx->first_x != ctx->x || ctx->first_y != ctx->y) stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0); } static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy) { stbtt__csctx_close_shape(ctx); ctx->first_x = ctx->x = ctx->x + dx; ctx->first_y = ctx->y = ctx->y + dy; stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); } static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy) { ctx->x += dx; ctx->y += dy; stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); } static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) { float cx1 = ctx->x + dx1; float cy1 = ctx->y + dy1; float cx2 = cx1 + dx2; float cy2 = cy1 + dy2; ctx->x = cx2 + dx3; ctx->y = cy2 + dy3; stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2); } static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n) { int count = stbtt__cff_index_count(&idx); int bias = 107; if (count >= 33900) bias = 32768; else if (count >= 1240) bias = 1131; n += bias; if (n < 0 || n >= count) return stbtt__new_buf(NULL, 0); return stbtt__cff_index_get(idx, n); } static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index) { stbtt__buf fdselect = info->fdselect; int nranges, start, end, v, fmt, fdselector = -1, i; stbtt__buf_seek(&fdselect, 0); fmt = stbtt__buf_get8(&fdselect); if (fmt == 0) { // untested stbtt__buf_skip(&fdselect, glyph_index); fdselector = stbtt__buf_get8(&fdselect); } else if (fmt == 3) { nranges = stbtt__buf_get16(&fdselect); start = stbtt__buf_get16(&fdselect); for (i = 0; i < nranges; i++) { v = stbtt__buf_get8(&fdselect); end = stbtt__buf_get16(&fdselect); if (glyph_index >= start && glyph_index < end) { fdselector = v; break; } start = end; } } if (fdselector == -1) stbtt__new_buf(NULL, 0); return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); } static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c) { int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0; int has_subrs = 0, clear_stack; float s[48]; stbtt__buf subr_stack[10], subrs = info->subrs, b; float f; #define STBTT__CSERR(s) (0) // this currently ignores the initial width value, which isn't needed if we have hmtx b = stbtt__cff_index_get(info->charstrings, glyph_index); while (b.cursor < b.size) { i = 0; clear_stack = 1; b0 = stbtt__buf_get8(&b); switch (b0) { // @TODO implement hinting case 0x13: // hintmask case 0x14: // cntrmask if (in_header) maskbits += (sp / 2); // implicit "vstem" in_header = 0; stbtt__buf_skip(&b, (maskbits + 7) / 8); break; case 0x01: // hstem case 0x03: // vstem case 0x12: // hstemhm case 0x17: // vstemhm maskbits += (sp / 2); break; case 0x15: // rmoveto in_header = 0; if (sp < 2) return STBTT__CSERR("rmoveto stack"); stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]); break; case 0x04: // vmoveto in_header = 0; if (sp < 1) return STBTT__CSERR("vmoveto stack"); stbtt__csctx_rmove_to(c, 0, s[sp-1]); break; case 0x16: // hmoveto in_header = 0; if (sp < 1) return STBTT__CSERR("hmoveto stack"); stbtt__csctx_rmove_to(c, s[sp-1], 0); break; case 0x05: // rlineto if (sp < 2) return STBTT__CSERR("rlineto stack"); for (; i + 1 < sp; i += 2) stbtt__csctx_rline_to(c, s[i], s[i+1]); break; // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical // starting from a different place. case 0x07: // vlineto if (sp < 1) return STBTT__CSERR("vlineto stack"); goto vlineto; case 0x06: // hlineto if (sp < 1) return STBTT__CSERR("hlineto stack"); for (;;) { if (i >= sp) break; stbtt__csctx_rline_to(c, s[i], 0); i++; vlineto: if (i >= sp) break; stbtt__csctx_rline_to(c, 0, s[i]); i++; } break; case 0x1F: // hvcurveto if (sp < 4) return STBTT__CSERR("hvcurveto stack"); goto hvcurveto; case 0x1E: // vhcurveto if (sp < 4) return STBTT__CSERR("vhcurveto stack"); for (;;) { if (i + 3 >= sp) break; stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f); i += 4; hvcurveto: if (i + 3 >= sp) break; stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]); i += 4; } break; case 0x08: // rrcurveto if (sp < 6) return STBTT__CSERR("rcurveline stack"); for (; i + 5 < sp; i += 6) stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); break; case 0x18: // rcurveline if (sp < 8) return STBTT__CSERR("rcurveline stack"); for (; i + 5 < sp - 2; i += 6) stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack"); stbtt__csctx_rline_to(c, s[i], s[i+1]); break; case 0x19: // rlinecurve if (sp < 8) return STBTT__CSERR("rlinecurve stack"); for (; i + 1 < sp - 6; i += 2) stbtt__csctx_rline_to(c, s[i], s[i+1]); if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack"); stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); break; case 0x1A: // vvcurveto case 0x1B: // hhcurveto if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack"); f = 0.0; if (sp & 1) { f = s[i]; i++; } for (; i + 3 < sp; i += 4) { if (b0 == 0x1B) stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0); else stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]); f = 0.0; } break; case 0x0A: // callsubr if (!has_subrs) { if (info->fdselect.size) subrs = stbtt__cid_get_glyph_subrs(info, glyph_index); has_subrs = 1; } // FALLTHROUGH case 0x1D: // callgsubr if (sp < 1) return STBTT__CSERR("call(g|)subr stack"); v = (int) s[--sp]; if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit"); subr_stack[subr_stack_height++] = b; b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v); if (b.size == 0) return STBTT__CSERR("subr not found"); b.cursor = 0; clear_stack = 0; break; case 0x0B: // return if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr"); b = subr_stack[--subr_stack_height]; clear_stack = 0; break; case 0x0E: // endchar stbtt__csctx_close_shape(c); return 1; case 0x0C: { // two-byte escape float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6; float dx, dy; int b1 = stbtt__buf_get8(&b); switch (b1) { // @TODO These "flex" implementations ignore the flex-depth and resolution, // and always draw beziers. case 0x22: // hflex if (sp < 7) return STBTT__CSERR("hflex stack"); dx1 = s[0]; dx2 = s[1]; dy2 = s[2]; dx3 = s[3]; dx4 = s[4]; dx5 = s[5]; dx6 = s[6]; stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0); stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0); break; case 0x23: // flex if (sp < 13) return STBTT__CSERR("flex stack"); dx1 = s[0]; dy1 = s[1]; dx2 = s[2]; dy2 = s[3]; dx3 = s[4]; dy3 = s[5]; dx4 = s[6]; dy4 = s[7]; dx5 = s[8]; dy5 = s[9]; dx6 = s[10]; dy6 = s[11]; //fd is s[12] stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); break; case 0x24: // hflex1 if (sp < 9) return STBTT__CSERR("hflex1 stack"); dx1 = s[0]; dy1 = s[1]; dx2 = s[2]; dy2 = s[3]; dx3 = s[4]; dx4 = s[5]; dx5 = s[6]; dy5 = s[7]; dx6 = s[8]; stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0); stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5)); break; case 0x25: // flex1 if (sp < 11) return STBTT__CSERR("flex1 stack"); dx1 = s[0]; dy1 = s[1]; dx2 = s[2]; dy2 = s[3]; dx3 = s[4]; dy3 = s[5]; dx4 = s[6]; dy4 = s[7]; dx5 = s[8]; dy5 = s[9]; dx6 = dy6 = s[10]; dx = dx1+dx2+dx3+dx4+dx5; dy = dy1+dy2+dy3+dy4+dy5; if (STBTT_fabs(dx) > STBTT_fabs(dy)) dy6 = -dy; else dx6 = -dx; stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); break; default: return STBTT__CSERR("unimplemented"); } } break; default: if (b0 != 255 && b0 != 28 && b0 < 32) return STBTT__CSERR("reserved operator"); // push immediate if (b0 == 255) { f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000; } else { stbtt__buf_skip(&b, -1); f = (float)(stbtt_int16)stbtt__cff_int(&b); } if (sp >= 48) return STBTT__CSERR("push stack overflow"); s[sp++] = f; clear_stack = 0; break; } if (clear_stack) sp = 0; } return STBTT__CSERR("no endchar"); #undef STBTT__CSERR } static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) { // runs the charstring twice, once to count and once to output (to avoid realloc) stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1); stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0); if (stbtt__run_charstring(info, glyph_index, &count_ctx)) { *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata); output_ctx.pvertices = *pvertices; if (stbtt__run_charstring(info, glyph_index, &output_ctx)) { STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices); return output_ctx.num_vertices; } } *pvertices = NULL; return 0; } static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) { stbtt__csctx c = STBTT__CSCTX_INIT(1); int r = stbtt__run_charstring(info, glyph_index, &c); if (x0) *x0 = r ? c.min_x : 0; if (y0) *y0 = r ? c.min_y : 0; if (x1) *x1 = r ? c.max_x : 0; if (y1) *y1 = r ? c.max_y : 0; return r ? c.num_vertices : 0; } STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) { if (!info->cff.size) return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices); else return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices); } STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) { stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); if (glyph_index < numOfLongHorMetrics) { if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index); if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); } else { if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); } } STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info) { stbtt_uint8 *data = info->data + info->kern; // we only look at the first table. it must be 'horizontal' and format 0. if (!info->kern) return 0; if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 return 0; if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format return 0; return ttUSHORT(data+10); } STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length) { stbtt_uint8 *data = info->data + info->kern; int k, length; // we only look at the first table. it must be 'horizontal' and format 0. if (!info->kern) return 0; if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 return 0; if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format return 0; length = ttUSHORT(data+10); if (table_length < length) length = table_length; for (k = 0; k < length; k++) { table[k].glyph1 = ttUSHORT(data+18+(k*6)); table[k].glyph2 = ttUSHORT(data+20+(k*6)); table[k].advance = ttSHORT(data+22+(k*6)); } return length; } static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) { stbtt_uint8 *data = info->data + info->kern; stbtt_uint32 needle, straw; int l, r, m; // we only look at the first table. it must be 'horizontal' and format 0. if (!info->kern) return 0; if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 return 0; if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format return 0; l = 0; r = ttUSHORT(data+10) - 1; needle = glyph1 << 16 | glyph2; while (l <= r) { m = (l + r) >> 1; straw = ttULONG(data+18+(m*6)); // note: unaligned read if (needle < straw) r = m - 1; else if (needle > straw) l = m + 1; else return ttSHORT(data+22+(m*6)); } return 0; } static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph) { stbtt_uint16 coverageFormat = ttUSHORT(coverageTable); switch (coverageFormat) { case 1: { stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2); // Binary search. stbtt_int32 l=0, r=glyphCount-1, m; int straw, needle=glyph; while (l <= r) { stbtt_uint8 *glyphArray = coverageTable + 4; stbtt_uint16 glyphID; m = (l + r) >> 1; glyphID = ttUSHORT(glyphArray + 2 * m); straw = glyphID; if (needle < straw) r = m - 1; else if (needle > straw) l = m + 1; else { return m; } } break; } case 2: { stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2); stbtt_uint8 *rangeArray = coverageTable + 4; // Binary search. stbtt_int32 l=0, r=rangeCount-1, m; int strawStart, strawEnd, needle=glyph; while (l <= r) { stbtt_uint8 *rangeRecord; m = (l + r) >> 1; rangeRecord = rangeArray + 6 * m; strawStart = ttUSHORT(rangeRecord); strawEnd = ttUSHORT(rangeRecord + 2); if (needle < strawStart) r = m - 1; else if (needle > strawEnd) l = m + 1; else { stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4); return startCoverageIndex + glyph - strawStart; } } break; } default: return -1; // unsupported } return -1; } static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph) { stbtt_uint16 classDefFormat = ttUSHORT(classDefTable); switch (classDefFormat) { case 1: { stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2); stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4); stbtt_uint8 *classDef1ValueArray = classDefTable + 6; if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount) return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID)); break; } case 2: { stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2); stbtt_uint8 *classRangeRecords = classDefTable + 4; // Binary search. stbtt_int32 l=0, r=classRangeCount-1, m; int strawStart, strawEnd, needle=glyph; while (l <= r) { stbtt_uint8 *classRangeRecord; m = (l + r) >> 1; classRangeRecord = classRangeRecords + 6 * m; strawStart = ttUSHORT(classRangeRecord); strawEnd = ttUSHORT(classRangeRecord + 2); if (needle < strawStart) r = m - 1; else if (needle > strawEnd) l = m + 1; else return (stbtt_int32)ttUSHORT(classRangeRecord + 4); } break; } default: return -1; // Unsupported definition type, return an error. } // "All glyphs not assigned to a class fall into class 0". (OpenType spec) return 0; } // Define to STBTT_assert(x) if you want to break on unimplemented formats. #define STBTT_GPOS_TODO_assert(x) static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) { stbtt_uint16 lookupListOffset; stbtt_uint8 *lookupList; stbtt_uint16 lookupCount; stbtt_uint8 *data; stbtt_int32 i, sti; if (!info->gpos) return 0; data = info->data + info->gpos; if (ttUSHORT(data+0) != 1) return 0; // Major version 1 if (ttUSHORT(data+2) != 0) return 0; // Minor version 0 lookupListOffset = ttUSHORT(data+8); lookupList = data + lookupListOffset; lookupCount = ttUSHORT(lookupList); for (i=0; i= pairSetCount) return 0; needle=glyph2; r=pairValueCount-1; l=0; // Binary search. while (l <= r) { stbtt_uint16 secondGlyph; stbtt_uint8 *pairValue; m = (l + r) >> 1; pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m; secondGlyph = ttUSHORT(pairValue); straw = secondGlyph; if (needle < straw) r = m - 1; else if (needle > straw) l = m + 1; else { stbtt_int16 xAdvance = ttSHORT(pairValue + 2); return xAdvance; } } } else return 0; break; } case 2: { stbtt_uint16 valueFormat1 = ttUSHORT(table + 4); stbtt_uint16 valueFormat2 = ttUSHORT(table + 6); if (valueFormat1 == 4 && valueFormat2 == 0) { // Support more formats? stbtt_uint16 classDef1Offset = ttUSHORT(table + 8); stbtt_uint16 classDef2Offset = ttUSHORT(table + 10); int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1); int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2); stbtt_uint16 class1Count = ttUSHORT(table + 12); stbtt_uint16 class2Count = ttUSHORT(table + 14); stbtt_uint8 *class1Records, *class2Records; stbtt_int16 xAdvance; if (glyph1class < 0 || glyph1class >= class1Count) return 0; // malformed if (glyph2class < 0 || glyph2class >= class2Count) return 0; // malformed class1Records = table + 16; class2Records = class1Records + 2 * (glyph1class * class2Count); xAdvance = ttSHORT(class2Records + 2 * glyph2class); return xAdvance; } else return 0; break; } default: return 0; // Unsupported position format } } } return 0; } STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2) { int xAdvance = 0; if (info->gpos) xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); else if (info->kern) xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2); return xAdvance; } STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2) { if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs return 0; return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2)); } STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing) { stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); } STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) { if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); if (descent) *descent = ttSHORT(info->data+info->hhea + 6); if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); } STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap) { int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); if (!tab) return 0; if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68); if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70); if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72); return 1; } STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1) { *x0 = ttSHORT(info->data + info->head + 36); *y0 = ttSHORT(info->data + info->head + 38); *x1 = ttSHORT(info->data + info->head + 40); *y1 = ttSHORT(info->data + info->head + 42); } STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) { int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); return (float) height / fheight; } STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) { int unitsPerEm = ttUSHORT(info->data + info->head + 18); return pixels / unitsPerEm; } STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) { STBTT_free(v, info->userdata); } STBTT_DEF stbtt_uint8 *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl) { int i; stbtt_uint8 *data = info->data; stbtt_uint8 *svg_doc_list = data + stbtt__get_svg((stbtt_fontinfo *) info); int numEntries = ttUSHORT(svg_doc_list); stbtt_uint8 *svg_docs = svg_doc_list + 2; for(i=0; i= ttUSHORT(svg_doc)) && (gl <= ttUSHORT(svg_doc + 2))) return svg_doc; } return 0; } STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg) { stbtt_uint8 *data = info->data; stbtt_uint8 *svg_doc; if (info->svg == 0) return 0; svg_doc = stbtt_FindSVGDoc(info, gl); if (svg_doc != NULL) { *svg = (char *) data + info->svg + ttULONG(svg_doc + 4); return ttULONG(svg_doc + 8); } else { return 0; } } STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg) { return stbtt_GetGlyphSVG(info, stbtt_FindGlyphIndex(info, unicode_codepoint), svg); } ////////////////////////////////////////////////////////////////////////////// // // antialiasing software rasterizer // STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) { int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { // e.g. space character if (ix0) *ix0 = 0; if (iy0) *iy0 = 0; if (ix1) *ix1 = 0; if (iy1) *iy1 = 0; } else { // move to integral bboxes (treating pixels as little squares, what pixels get touched)? if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x); if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y); if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x); if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y); } } STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) { stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); } STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) { stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1); } STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) { stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); } ////////////////////////////////////////////////////////////////////////////// // // Rasterizer typedef struct stbtt__hheap_chunk { struct stbtt__hheap_chunk *next; } stbtt__hheap_chunk; typedef struct stbtt__hheap { struct stbtt__hheap_chunk *head; void *first_free; int num_remaining_in_head_chunk; } stbtt__hheap; static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata) { if (hh->first_free) { void *p = hh->first_free; hh->first_free = * (void **) p; return p; } else { if (hh->num_remaining_in_head_chunk == 0) { int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata); if (c == NULL) return NULL; c->next = hh->head; hh->head = c; hh->num_remaining_in_head_chunk = count; } --hh->num_remaining_in_head_chunk; return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk; } } static void stbtt__hheap_free(stbtt__hheap *hh, void *p) { *(void **) p = hh->first_free; hh->first_free = p; } static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata) { stbtt__hheap_chunk *c = hh->head; while (c) { stbtt__hheap_chunk *n = c->next; STBTT_free(c, userdata); c = n; } } typedef struct stbtt__edge { float x0,y0, x1,y1; int invert; } stbtt__edge; typedef struct stbtt__active_edge { struct stbtt__active_edge *next; #if STBTT_RASTERIZER_VERSION==1 int x,dx; float ey; int direction; #elif STBTT_RASTERIZER_VERSION==2 float fx,fdx,fdy; float direction; float sy; float ey; #else #error "Unrecognized value of STBTT_RASTERIZER_VERSION" #endif } stbtt__active_edge; #if STBTT_RASTERIZER_VERSION == 1 #define STBTT_FIXSHIFT 10 #define STBTT_FIX (1 << STBTT_FIXSHIFT) #define STBTT_FIXMASK (STBTT_FIX-1) static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) { stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); STBTT_assert(z != NULL); if (!z) return z; // round dx down to avoid overshooting if (dxdy < 0) z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy); else z->dx = STBTT_ifloor(STBTT_FIX * dxdy); z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount z->x -= off_x * STBTT_FIX; z->ey = e->y1; z->next = 0; z->direction = e->invert ? 1 : -1; return z; } #elif STBTT_RASTERIZER_VERSION == 2 static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) { stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); STBTT_assert(z != NULL); //STBTT_assert(e->y0 <= start_point); if (!z) return z; z->fdx = dxdy; z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f; z->fx = e->x0 + dxdy * (start_point - e->y0); z->fx -= off_x; z->direction = e->invert ? 1.0f : -1.0f; z->sy = e->y0; z->ey = e->y1; z->next = 0; return z; } #else #error "Unrecognized value of STBTT_RASTERIZER_VERSION" #endif #if STBTT_RASTERIZER_VERSION == 1 // note: this routine clips fills that extend off the edges... ideally this // wouldn't happen, but it could happen if the truetype glyph bounding boxes // are wrong, or if the user supplies a too-small bitmap static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight) { // non-zero winding fill int x0=0, w=0; while (e) { if (w == 0) { // if we're currently at zero, we need to record the edge start point x0 = e->x; w += e->direction; } else { int x1 = e->x; w += e->direction; // if we went to zero, we need to draw if (w == 0) { int i = x0 >> STBTT_FIXSHIFT; int j = x1 >> STBTT_FIXSHIFT; if (i < len && j >= 0) { if (i == j) { // x0,x1 are the same pixel, so compute combined coverage scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT); } else { if (i >= 0) // add antialiasing for x0 scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT); else i = -1; // clip if (j < len) // add antialiasing for x1 scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT); else j = len; // clip for (++i; i < j; ++i) // fill pixels between x0 and x1 scanline[i] = scanline[i] + (stbtt_uint8) max_weight; } } } } e = e->next; } } static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) { stbtt__hheap hh = { 0, 0, 0 }; stbtt__active_edge *active = NULL; int y,j=0; int max_weight = (255 / vsubsample); // weight per vertical scanline int s; // vertical subsample index unsigned char scanline_data[512], *scanline; if (result->w > 512) scanline = (unsigned char *) STBTT_malloc(result->w, userdata); else scanline = scanline_data; y = off_y * vsubsample; e[n].y0 = (off_y + result->h) * (float) vsubsample + 1; while (j < result->h) { STBTT_memset(scanline, 0, result->w); for (s=0; s < vsubsample; ++s) { // find center of pixel for this scanline float scan_y = y + 0.5f; stbtt__active_edge **step = &active; // update all active edges; // remove all active edges that terminate before the center of this scanline while (*step) { stbtt__active_edge * z = *step; if (z->ey <= scan_y) { *step = z->next; // delete from list STBTT_assert(z->direction); z->direction = 0; stbtt__hheap_free(&hh, z); } else { z->x += z->dx; // advance to position for current scanline step = &((*step)->next); // advance through list } } // resort the list if needed for(;;) { int changed=0; step = &active; while (*step && (*step)->next) { if ((*step)->x > (*step)->next->x) { stbtt__active_edge *t = *step; stbtt__active_edge *q = t->next; t->next = q->next; q->next = t; *step = q; changed = 1; } step = &(*step)->next; } if (!changed) break; } // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline while (e->y0 <= scan_y) { if (e->y1 > scan_y) { stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata); if (z != NULL) { // find insertion point if (active == NULL) active = z; else if (z->x < active->x) { // insert at front z->next = active; active = z; } else { // find thing to insert AFTER stbtt__active_edge *p = active; while (p->next && p->next->x < z->x) p = p->next; // at this point, p->next->x is NOT < z->x z->next = p->next; p->next = z; } } } ++e; } // now process all active edges in XOR fashion if (active) stbtt__fill_active_edges(scanline, result->w, active, max_weight); ++y; } STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w); ++j; } stbtt__hheap_cleanup(&hh, userdata); if (scanline != scanline_data) STBTT_free(scanline, userdata); } #elif STBTT_RASTERIZER_VERSION == 2 // the edge passed in here does not cross the vertical line at x or the vertical line at x+1 // (i.e. it has already been clipped to those) static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1) { if (y0 == y1) return; STBTT_assert(y0 < y1); STBTT_assert(e->sy <= e->ey); if (y0 > e->ey) return; if (y1 < e->sy) return; if (y0 < e->sy) { x0 += (x1-x0) * (e->sy - y0) / (y1-y0); y0 = e->sy; } if (y1 > e->ey) { x1 += (x1-x0) * (e->ey - y1) / (y1-y0); y1 = e->ey; } if (x0 == x) STBTT_assert(x1 <= x+1); else if (x0 == x+1) STBTT_assert(x1 >= x); else if (x0 <= x) STBTT_assert(x1 <= x); else if (x0 >= x+1) STBTT_assert(x1 >= x+1); else STBTT_assert(x1 >= x && x1 <= x+1); if (x0 <= x && x1 <= x) scanline[x] += e->direction * (y1-y0); else if (x0 >= x+1 && x1 >= x+1) ; else { STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1); scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position } } static float stbtt__sized_trapezoid_area(float height, float top_width, float bottom_width) { STBTT_assert(top_width >= 0); STBTT_assert(bottom_width >= 0); return (top_width + bottom_width) / 2.0f * height; } static float stbtt__position_trapezoid_area(float height, float tx0, float tx1, float bx0, float bx1) { return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0); } static float stbtt__sized_triangle_area(float height, float width) { return height * width / 2; } static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top) { float y_bottom = y_top+1; while (e) { // brute force every pixel // compute intersection points with top & bottom STBTT_assert(e->ey >= y_top); if (e->fdx == 0) { float x0 = e->fx; if (x0 < len) { if (x0 >= 0) { stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom); } else { stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom); } } } else { float x0 = e->fx; float dx = e->fdx; float xb = x0 + dx; float x_top, x_bottom; float sy0,sy1; float dy = e->fdy; STBTT_assert(e->sy <= y_bottom && e->ey >= y_top); // compute endpoints of line segment clipped to this scanline (if the // line segment starts on this scanline. x0 is the intersection of the // line with y_top, but that may be off the line segment. if (e->sy > y_top) { x_top = x0 + dx * (e->sy - y_top); sy0 = e->sy; } else { x_top = x0; sy0 = y_top; } if (e->ey < y_bottom) { x_bottom = x0 + dx * (e->ey - y_top); sy1 = e->ey; } else { x_bottom = xb; sy1 = y_bottom; } if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) { // from here on, we don't have to range check x values if ((int) x_top == (int) x_bottom) { float height; // simple case, only spans one pixel int x = (int) x_top; height = (sy1 - sy0) * e->direction; STBTT_assert(x >= 0 && x < len); scanline[x] += stbtt__position_trapezoid_area(height, x_top, x+1.0f, x_bottom, x+1.0f); scanline_fill[x] += height; // everything right of this pixel is filled } else { int x,x1,x2; float y_crossing, y_final, step, sign, area; // covers 2+ pixels if (x_top > x_bottom) { // flip scanline vertically; signed area is the same float t; sy0 = y_bottom - (sy0 - y_top); sy1 = y_bottom - (sy1 - y_top); t = sy0, sy0 = sy1, sy1 = t; t = x_bottom, x_bottom = x_top, x_top = t; dx = -dx; dy = -dy; t = x0, x0 = xb, xb = t; } STBTT_assert(dy >= 0); STBTT_assert(dx >= 0); x1 = (int) x_top; x2 = (int) x_bottom; // compute intersection with y axis at x1+1 y_crossing = y_top + dy * (x1+1 - x0); // compute intersection with y axis at x2 y_final = y_top + dy * (x2 - x0); // x1 x_top x2 x_bottom // y_top +------|-----+------------+------------+--------|---+------------+ // | | | | | | // | | | | | | // sy0 | Txxxxx|............|............|............|............| // y_crossing | *xxxxx.......|............|............|............| // | | xxxxx..|............|............|............| // | | /- xx*xxxx........|............|............| // | | dy < | xxxxxx..|............|............| // y_final | | \- | xx*xxx.........|............| // sy1 | | | | xxxxxB...|............| // | | | | | | // | | | | | | // y_bottom +------------+------------+------------+------------+------------+ // // goal is to measure the area covered by '.' in each pixel // if x2 is right at the right edge of x1, y_crossing can blow up, github #1057 // @TODO: maybe test against sy1 rather than y_bottom? if (y_crossing > y_bottom) y_crossing = y_bottom; sign = e->direction; // area of the rectangle covered from sy0..y_crossing area = sign * (y_crossing-sy0); // area of the triangle (x_top,sy0), (x1+1,sy0), (x1+1,y_crossing) scanline[x1] += stbtt__sized_triangle_area(area, x1+1 - x_top); // check if final y_crossing is blown up; no test case for this if (y_final > y_bottom) { y_final = y_bottom; dy = (y_final - y_crossing ) / (x2 - (x1+1)); // if denom=0, y_final = y_crossing, so y_final <= y_bottom } // in second pixel, area covered by line segment found in first pixel // is always a rectangle 1 wide * the height of that line segment; this // is exactly what the variable 'area' stores. it also gets a contribution // from the line segment within it. the THIRD pixel will get the first // pixel's rectangle contribution, the second pixel's rectangle contribution, // and its own contribution. the 'own contribution' is the same in every pixel except // the leftmost and rightmost, a trapezoid that slides down in each pixel. // the second pixel's contribution to the third pixel will be the // rectangle 1 wide times the height change in the second pixel, which is dy. step = sign * dy * 1; // dy is dy/dx, change in y for every 1 change in x, // which multiplied by 1-pixel-width is how much pixel area changes for each step in x // so the area advances by 'step' every time for (x = x1+1; x < x2; ++x) { scanline[x] += area + step/2; // area of trapezoid is 1*step/2 area += step; } STBTT_assert(STBTT_fabs(area) <= 1.01f); // accumulated error from area += step unless we round step down STBTT_assert(sy1 > y_final-0.01f); // area covered in the last pixel is the rectangle from all the pixels to the left, // plus the trapezoid filled by the line segment in this pixel all the way to the right edge scanline[x2] += area + sign * stbtt__position_trapezoid_area(sy1-y_final, (float) x2, x2+1.0f, x_bottom, x2+1.0f); // the rest of the line is filled based on the total height of the line segment in this pixel scanline_fill[x2] += sign * (sy1-sy0); } } else { // if edge goes outside of box we're drawing, we require // clipping logic. since this does not match the intended use // of this library, we use a different, very slow brute // force implementation // note though that this does happen some of the time because // x_top and x_bottom can be extrapolated at the top & bottom of // the shape and actually lie outside the bounding box int x; for (x=0; x < len; ++x) { // cases: // // there can be up to two intersections with the pixel. any intersection // with left or right edges can be handled by splitting into two (or three) // regions. intersections with top & bottom do not necessitate case-wise logic. // // the old way of doing this found the intersections with the left & right edges, // then used some simple logic to produce up to three segments in sorted order // from top-to-bottom. however, this had a problem: if an x edge was epsilon // across the x border, then the corresponding y position might not be distinct // from the other y segment, and it might ignored as an empty segment. to avoid // that, we need to explicitly produce segments based on x positions. // rename variables to clearly-defined pairs float y0 = y_top; float x1 = (float) (x); float x2 = (float) (x+1); float x3 = xb; float y3 = y_bottom; // x = e->x + e->dx * (y-y_top) // (y-y_top) = (x - e->x) / e->dx // y = (x - e->x) / e->dx + y_top float y1 = (x - x0) / dx + y_top; float y2 = (x+1 - x0) / dx + y_top; if (x0 < x1 && x3 > x2) { // three segments descending down-right stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2); stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); } else if (x3 < x1 && x0 > x2) { // three segments descending down-left stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1); stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); } else { // one segment stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3); } } } } e = e->next; } } // directly AA rasterize edges w/o supersampling static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) { stbtt__hheap hh = { 0, 0, 0 }; stbtt__active_edge *active = NULL; int y,j=0, i; float scanline_data[129], *scanline, *scanline2; STBTT__NOTUSED(vsubsample); if (result->w > 64) scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata); else scanline = scanline_data; scanline2 = scanline + result->w; y = off_y; e[n].y0 = (float) (off_y + result->h) + 1; while (j < result->h) { // find center of pixel for this scanline float scan_y_top = y + 0.0f; float scan_y_bottom = y + 1.0f; stbtt__active_edge **step = &active; STBTT_memset(scanline , 0, result->w*sizeof(scanline[0])); STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0])); // update all active edges; // remove all active edges that terminate before the top of this scanline while (*step) { stbtt__active_edge * z = *step; if (z->ey <= scan_y_top) { *step = z->next; // delete from list STBTT_assert(z->direction); z->direction = 0; stbtt__hheap_free(&hh, z); } else { step = &((*step)->next); // advance through list } } // insert all edges that start before the bottom of this scanline while (e->y0 <= scan_y_bottom) { if (e->y0 != e->y1) { stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); if (z != NULL) { if (j == 0 && off_y != 0) { if (z->ey < scan_y_top) { // this can happen due to subpixel positioning and some kind of fp rounding error i think z->ey = scan_y_top; } } STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds // insert at front z->next = active; active = z; } } ++e; } // now process all active edges if (active) stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top); { float sum = 0; for (i=0; i < result->w; ++i) { float k; int m; sum += scanline2[i]; k = scanline[i] + sum; k = (float) STBTT_fabs(k)*255 + 0.5f; m = (int) k; if (m > 255) m = 255; result->pixels[j*result->stride + i] = (unsigned char) m; } } // advance all the edges step = &active; while (*step) { stbtt__active_edge *z = *step; z->fx += z->fdx; // advance to position for current scanline step = &((*step)->next); // advance through list } ++y; ++j; } stbtt__hheap_cleanup(&hh, userdata); if (scanline != scanline_data) STBTT_free(scanline, userdata); } #else #error "Unrecognized value of STBTT_RASTERIZER_VERSION" #endif #define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0) static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) { int i,j; for (i=1; i < n; ++i) { stbtt__edge t = p[i], *a = &t; j = i; while (j > 0) { stbtt__edge *b = &p[j-1]; int c = STBTT__COMPARE(a,b); if (!c) break; p[j] = p[j-1]; --j; } if (i != j) p[j] = t; } } static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n) { /* threshold for transitioning to insertion sort */ while (n > 12) { stbtt__edge t; int c01,c12,c,m,i,j; /* compute median of three */ m = n >> 1; c01 = STBTT__COMPARE(&p[0],&p[m]); c12 = STBTT__COMPARE(&p[m],&p[n-1]); /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ if (c01 != c12) { /* otherwise, we'll need to swap something else to middle */ int z; c = STBTT__COMPARE(&p[0],&p[n-1]); /* 0>mid && midn => n; 0 0 */ /* 0n: 0>n => 0; 0 n */ z = (c == c12) ? 0 : n-1; t = p[z]; p[z] = p[m]; p[m] = t; } /* now p[m] is the median-of-three */ /* swap it to the beginning so it won't move around */ t = p[0]; p[0] = p[m]; p[m] = t; /* partition loop */ i=1; j=n-1; for(;;) { /* handling of equality is crucial here */ /* for sentinels & efficiency with duplicates */ for (;;++i) { if (!STBTT__COMPARE(&p[i], &p[0])) break; } for (;;--j) { if (!STBTT__COMPARE(&p[0], &p[j])) break; } /* make sure we haven't crossed */ if (i >= j) break; t = p[i]; p[i] = p[j]; p[j] = t; ++i; --j; } /* recurse on smaller side, iterate on larger */ if (j < (n-i)) { stbtt__sort_edges_quicksort(p,j); p = p+i; n = n-i; } else { stbtt__sort_edges_quicksort(p+i, n-i); n = j; } } } static void stbtt__sort_edges(stbtt__edge *p, int n) { stbtt__sort_edges_quicksort(p, n); stbtt__sort_edges_ins_sort(p, n); } typedef struct { float x,y; } stbtt__point; static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata) { float y_scale_inv = invert ? -scale_y : scale_y; stbtt__edge *e; int n,i,j,k,m; #if STBTT_RASTERIZER_VERSION == 1 int vsubsample = result->h < 8 ? 15 : 5; #elif STBTT_RASTERIZER_VERSION == 2 int vsubsample = 1; #else #error "Unrecognized value of STBTT_RASTERIZER_VERSION" #endif // vsubsample should divide 255 evenly; otherwise we won't reach full opacity // now we have to blow out the windings into explicit edge lists n = 0; for (i=0; i < windings; ++i) n += wcount[i]; e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel if (e == 0) return; n = 0; m=0; for (i=0; i < windings; ++i) { stbtt__point *p = pts + m; m += wcount[i]; j = wcount[i]-1; for (k=0; k < wcount[i]; j=k++) { int a=k,b=j; // skip the edge if horizontal if (p[j].y == p[k].y) continue; // add edge from j to k to the list e[n].invert = 0; if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { e[n].invert = 1; a=j,b=k; } e[n].x0 = p[a].x * scale_x + shift_x; e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample; e[n].x1 = p[b].x * scale_x + shift_x; e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample; ++n; } } // now sort the edges by their highest point (should snap to integer, and then by x) //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); stbtt__sort_edges(e, n); // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata); STBTT_free(e, userdata); } static void stbtt__add_point(stbtt__point *points, int n, float x, float y) { if (!points) return; // during first pass, it's unallocated points[n].x = x; points[n].y = y; } // tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) { // midpoint float mx = (x0 + 2*x1 + x2)/4; float my = (y0 + 2*y1 + y2)/4; // versus directly drawn line float dx = (x0+x2)/2 - mx; float dy = (y0+y2)/2 - my; if (n > 16) // 65536 segments on one curve better be enough! return 1; if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); } else { stbtt__add_point(points, *num_points,x2,y2); *num_points = *num_points+1; } return 1; } static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n) { // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough float dx0 = x1-x0; float dy0 = y1-y0; float dx1 = x2-x1; float dy1 = y2-y1; float dx2 = x3-x2; float dy2 = y3-y2; float dx = x3-x0; float dy = y3-y0; float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2)); float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy); float flatness_squared = longlen*longlen-shortlen*shortlen; if (n > 16) // 65536 segments on one curve better be enough! return; if (flatness_squared > objspace_flatness_squared) { float x01 = (x0+x1)/2; float y01 = (y0+y1)/2; float x12 = (x1+x2)/2; float y12 = (y1+y2)/2; float x23 = (x2+x3)/2; float y23 = (y2+y3)/2; float xa = (x01+x12)/2; float ya = (y01+y12)/2; float xb = (x12+x23)/2; float yb = (y12+y23)/2; float mx = (xa+xb)/2; float my = (ya+yb)/2; stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1); stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1); } else { stbtt__add_point(points, *num_points,x3,y3); *num_points = *num_points+1; } } // returns number of contours static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata) { stbtt__point *points=0; int num_points=0; float objspace_flatness_squared = objspace_flatness * objspace_flatness; int i,n=0,start=0, pass; // count how many "moves" there are to get the contour count for (i=0; i < num_verts; ++i) if (vertices[i].type == STBTT_vmove) ++n; *num_contours = n; if (n == 0) return 0; *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata); if (*contour_lengths == 0) { *num_contours = 0; return 0; } // make two passes through the points so we don't need to realloc for (pass=0; pass < 2; ++pass) { float x=0,y=0; if (pass == 1) { points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata); if (points == NULL) goto error; } num_points = 0; n= -1; for (i=0; i < num_verts; ++i) { switch (vertices[i].type) { case STBTT_vmove: // start the next contour if (n >= 0) (*contour_lengths)[n] = num_points - start; ++n; start = num_points; x = vertices[i].x, y = vertices[i].y; stbtt__add_point(points, num_points++, x,y); break; case STBTT_vline: x = vertices[i].x, y = vertices[i].y; stbtt__add_point(points, num_points++, x, y); break; case STBTT_vcurve: stbtt__tesselate_curve(points, &num_points, x,y, vertices[i].cx, vertices[i].cy, vertices[i].x, vertices[i].y, objspace_flatness_squared, 0); x = vertices[i].x, y = vertices[i].y; break; case STBTT_vcubic: stbtt__tesselate_cubic(points, &num_points, x,y, vertices[i].cx, vertices[i].cy, vertices[i].cx1, vertices[i].cy1, vertices[i].x, vertices[i].y, objspace_flatness_squared, 0); x = vertices[i].x, y = vertices[i].y; break; } } (*contour_lengths)[n] = num_points - start; } return points; error: STBTT_free(points, userdata); STBTT_free(*contour_lengths, userdata); *contour_lengths = 0; *num_contours = 0; return NULL; } STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata) { float scale = scale_x > scale_y ? scale_y : scale_x; int winding_count = 0; int *winding_lengths = NULL; stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata); if (windings) { stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata); STBTT_free(winding_lengths, userdata); STBTT_free(windings, userdata); } } STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata) { STBTT_free(bitmap, userdata); } STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff) { int ix0,iy0,ix1,iy1; stbtt__bitmap gbm; stbtt_vertex *vertices; int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); if (scale_x == 0) scale_x = scale_y; if (scale_y == 0) { if (scale_x == 0) { STBTT_free(vertices, info->userdata); return NULL; } scale_y = scale_x; } stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1); // now we get the size gbm.w = (ix1 - ix0); gbm.h = (iy1 - iy0); gbm.pixels = NULL; // in case we error if (width ) *width = gbm.w; if (height) *height = gbm.h; if (xoff ) *xoff = ix0; if (yoff ) *yoff = iy0; if (gbm.w && gbm.h) { gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata); if (gbm.pixels) { gbm.stride = gbm.w; stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata); } } STBTT_free(vertices, info->userdata); return gbm.pixels; } STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff); } STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph) { int ix0,iy0; stbtt_vertex *vertices; int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); stbtt__bitmap gbm; stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); gbm.pixels = output; gbm.w = out_w; gbm.h = out_h; gbm.stride = out_stride; if (gbm.w && gbm.h) stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata); STBTT_free(vertices, info->userdata); } STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph) { stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph); } STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff); } STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint) { stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint)); } STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint) { stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint)); } STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff); } STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint) { stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint); } ////////////////////////////////////////////////////////////////////////////// // // bitmap baking // // This is SUPER-CRAPPY packing to keep source code small static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) float pixel_height, // height of font in pixels unsigned char *pixels, int pw, int ph, // bitmap to be filled in int first_char, int num_chars, // characters to bake stbtt_bakedchar *chardata) { float scale; int x,y,bottom_y, i; stbtt_fontinfo f; f.userdata = NULL; if (!stbtt_InitFont(&f, data, offset)) return -1; STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels x=y=1; bottom_y = 1; scale = stbtt_ScaleForPixelHeight(&f, pixel_height); for (i=0; i < num_chars; ++i) { int advance, lsb, x0,y0,x1,y1,gw,gh; int g = stbtt_FindGlyphIndex(&f, first_char + i); stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb); stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1); gw = x1-x0; gh = y1-y0; if (x + gw + 1 >= pw) y = bottom_y, x = 1; // advance to next row if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row return -i; STBTT_assert(x+gw < pw); STBTT_assert(y+gh < ph); stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g); chardata[i].x0 = (stbtt_int16) x; chardata[i].y0 = (stbtt_int16) y; chardata[i].x1 = (stbtt_int16) (x + gw); chardata[i].y1 = (stbtt_int16) (y + gh); chardata[i].xadvance = scale * advance; chardata[i].xoff = (float) x0; chardata[i].yoff = (float) y0; x = x + gw + 1; if (y+gh+1 > bottom_y) bottom_y = y+gh+1; } return bottom_y; } STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule) { float d3d_bias = opengl_fillrule ? 0 : -0.5f; float ipw = 1.0f / pw, iph = 1.0f / ph; const stbtt_bakedchar *b = chardata + char_index; int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f); int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f); q->x0 = round_x + d3d_bias; q->y0 = round_y + d3d_bias; q->x1 = round_x + b->x1 - b->x0 + d3d_bias; q->y1 = round_y + b->y1 - b->y0 + d3d_bias; q->s0 = b->x0 * ipw; q->t0 = b->y0 * iph; q->s1 = b->x1 * ipw; q->t1 = b->y1 * iph; *xpos += b->xadvance; } ////////////////////////////////////////////////////////////////////////////// // // rectangle packing replacement routines if you don't have stb_rect_pack.h // #ifndef STB_RECT_PACK_VERSION typedef int stbrp_coord; //////////////////////////////////////////////////////////////////////////////////// // // // // // COMPILER WARNING ?!?!? // // // // // // if you get a compile warning due to these symbols being defined more than // // once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" // // // //////////////////////////////////////////////////////////////////////////////////// typedef struct { int width,height; int x,y,bottom_y; } stbrp_context; typedef struct { unsigned char x; } stbrp_node; struct stbrp_rect { stbrp_coord x,y; int id,w,h,was_packed; }; static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes) { con->width = pw; con->height = ph; con->x = 0; con->y = 0; con->bottom_y = 0; STBTT__NOTUSED(nodes); STBTT__NOTUSED(num_nodes); } static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects) { int i; for (i=0; i < num_rects; ++i) { if (con->x + rects[i].w > con->width) { con->x = 0; con->y = con->bottom_y; } if (con->y + rects[i].h > con->height) break; rects[i].x = con->x; rects[i].y = con->y; rects[i].was_packed = 1; con->x += rects[i].w; if (con->y + rects[i].h > con->bottom_y) con->bottom_y = con->y + rects[i].h; } for ( ; i < num_rects; ++i) rects[i].was_packed = 0; } #endif ////////////////////////////////////////////////////////////////////////////// // // bitmap baking // // This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If // stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy. STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context) { stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context); int num_nodes = pw - padding; stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context); if (context == NULL || nodes == NULL) { if (context != NULL) STBTT_free(context, alloc_context); if (nodes != NULL) STBTT_free(nodes , alloc_context); return 0; } spc->user_allocator_context = alloc_context; spc->width = pw; spc->height = ph; spc->pixels = pixels; spc->pack_info = context; spc->nodes = nodes; spc->padding = padding; spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw; spc->h_oversample = 1; spc->v_oversample = 1; spc->skip_missing = 0; stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes); if (pixels) STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels return 1; } STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc) { STBTT_free(spc->nodes , spc->user_allocator_context); STBTT_free(spc->pack_info, spc->user_allocator_context); } STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample) { STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE); STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE); if (h_oversample <= STBTT_MAX_OVERSAMPLE) spc->h_oversample = h_oversample; if (v_oversample <= STBTT_MAX_OVERSAMPLE) spc->v_oversample = v_oversample; } STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip) { spc->skip_missing = skip; } #define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1) static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) { unsigned char buffer[STBTT_MAX_OVERSAMPLE]; int safe_w = w - kernel_width; int j; STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze for (j=0; j < h; ++j) { int i; unsigned int total; STBTT_memset(buffer, 0, kernel_width); total = 0; // make kernel_width a constant in common cases so compiler can optimize out the divide switch (kernel_width) { case 2: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / 2); } break; case 3: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / 3); } break; case 4: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / 4); } break; case 5: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / 5); } break; default: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / kernel_width); } break; } for (; i < w; ++i) { STBTT_assert(pixels[i] == 0); total -= buffer[i & STBTT__OVER_MASK]; pixels[i] = (unsigned char) (total / kernel_width); } pixels += stride_in_bytes; } } static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) { unsigned char buffer[STBTT_MAX_OVERSAMPLE]; int safe_h = h - kernel_width; int j; STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze for (j=0; j < w; ++j) { int i; unsigned int total; STBTT_memset(buffer, 0, kernel_width); total = 0; // make kernel_width a constant in common cases so compiler can optimize out the divide switch (kernel_width) { case 2: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / 2); } break; case 3: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / 3); } break; case 4: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / 4); } break; case 5: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / 5); } break; default: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); } break; } for (; i < h; ++i) { STBTT_assert(pixels[i*stride_in_bytes] == 0); total -= buffer[i & STBTT__OVER_MASK]; pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); } pixels += 1; } } static float stbtt__oversample_shift(int oversample) { if (!oversample) return 0.0f; // The prefilter is a box filter of width "oversample", // which shifts phase by (oversample - 1)/2 pixels in // oversampled space. We want to shift in the opposite // direction to counter this. return (float)-(oversample - 1) / (2.0f * (float)oversample); } // rects array must be big enough to accommodate all characters in the given ranges STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) { int i,j,k; int missing_glyph_added = 0; k=0; for (i=0; i < num_ranges; ++i) { float fh = ranges[i].font_size; float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); ranges[i].h_oversample = (unsigned char) spc->h_oversample; ranges[i].v_oversample = (unsigned char) spc->v_oversample; for (j=0; j < ranges[i].num_chars; ++j) { int x0,y0,x1,y1; int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; int glyph = stbtt_FindGlyphIndex(info, codepoint); if (glyph == 0 && (spc->skip_missing || missing_glyph_added)) { rects[k].w = rects[k].h = 0; } else { stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, scale * spc->h_oversample, scale * spc->v_oversample, 0,0, &x0,&y0,&x1,&y1); rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); if (glyph == 0) missing_glyph_added = 1; } ++k; } } return k; } STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph) { stbtt_MakeGlyphBitmapSubpixel(info, output, out_w - (prefilter_x - 1), out_h - (prefilter_y - 1), out_stride, scale_x, scale_y, shift_x, shift_y, glyph); if (prefilter_x > 1) stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x); if (prefilter_y > 1) stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y); *sub_x = stbtt__oversample_shift(prefilter_x); *sub_y = stbtt__oversample_shift(prefilter_y); } // rects array must be big enough to accommodate all characters in the given ranges STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) { int i,j,k, missing_glyph = -1, return_value = 1; // save current values int old_h_over = spc->h_oversample; int old_v_over = spc->v_oversample; k = 0; for (i=0; i < num_ranges; ++i) { float fh = ranges[i].font_size; float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); float recip_h,recip_v,sub_x,sub_y; spc->h_oversample = ranges[i].h_oversample; spc->v_oversample = ranges[i].v_oversample; recip_h = 1.0f / spc->h_oversample; recip_v = 1.0f / spc->v_oversample; sub_x = stbtt__oversample_shift(spc->h_oversample); sub_y = stbtt__oversample_shift(spc->v_oversample); for (j=0; j < ranges[i].num_chars; ++j) { stbrp_rect *r = &rects[k]; if (r->was_packed && r->w != 0 && r->h != 0) { stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; int advance, lsb, x0,y0,x1,y1; int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; int glyph = stbtt_FindGlyphIndex(info, codepoint); stbrp_coord pad = (stbrp_coord) spc->padding; // pad on left and top r->x += pad; r->y += pad; r->w -= pad; r->h -= pad; stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb); stbtt_GetGlyphBitmapBox(info, glyph, scale * spc->h_oversample, scale * spc->v_oversample, &x0,&y0,&x1,&y1); stbtt_MakeGlyphBitmapSubpixel(info, spc->pixels + r->x + r->y*spc->stride_in_bytes, r->w - spc->h_oversample+1, r->h - spc->v_oversample+1, spc->stride_in_bytes, scale * spc->h_oversample, scale * spc->v_oversample, 0,0, glyph); if (spc->h_oversample > 1) stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, r->w, r->h, spc->stride_in_bytes, spc->h_oversample); if (spc->v_oversample > 1) stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, r->w, r->h, spc->stride_in_bytes, spc->v_oversample); bc->x0 = (stbtt_int16) r->x; bc->y0 = (stbtt_int16) r->y; bc->x1 = (stbtt_int16) (r->x + r->w); bc->y1 = (stbtt_int16) (r->y + r->h); bc->xadvance = scale * advance; bc->xoff = (float) x0 * recip_h + sub_x; bc->yoff = (float) y0 * recip_v + sub_y; bc->xoff2 = (x0 + r->w) * recip_h + sub_x; bc->yoff2 = (y0 + r->h) * recip_v + sub_y; if (glyph == 0) missing_glyph = j; } else if (spc->skip_missing) { return_value = 0; } else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) { ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph]; } else { return_value = 0; // if any fail, report failure } ++k; } } // restore original values spc->h_oversample = old_h_over; spc->v_oversample = old_v_over; return return_value; } STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects) { stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects); } STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) { stbtt_fontinfo info; int i,j,n, return_value = 1; //stbrp_context *context = (stbrp_context *) spc->pack_info; stbrp_rect *rects; // flag all characters as NOT packed for (i=0; i < num_ranges; ++i) for (j=0; j < ranges[i].num_chars; ++j) ranges[i].chardata_for_range[j].x0 = ranges[i].chardata_for_range[j].y0 = ranges[i].chardata_for_range[j].x1 = ranges[i].chardata_for_range[j].y1 = 0; n = 0; for (i=0; i < num_ranges; ++i) n += ranges[i].num_chars; rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context); if (rects == NULL) return 0; info.userdata = spc->user_allocator_context; stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index)); n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects); stbtt_PackFontRangesPackRects(spc, rects, n); return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects); STBTT_free(rects, spc->user_allocator_context); return return_value; } STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) { stbtt_pack_range range; range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range; range.array_of_unicode_codepoints = NULL; range.num_chars = num_chars_in_range; range.chardata_for_range = chardata_for_range; range.font_size = font_size; return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1); } STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap) { int i_ascent, i_descent, i_lineGap; float scale; stbtt_fontinfo info; stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index)); scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size); stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap); *ascent = (float) i_ascent * scale; *descent = (float) i_descent * scale; *lineGap = (float) i_lineGap * scale; } STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer) { float ipw = 1.0f / pw, iph = 1.0f / ph; const stbtt_packedchar *b = chardata + char_index; if (align_to_integer) { float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f); float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f); q->x0 = x; q->y0 = y; q->x1 = x + b->xoff2 - b->xoff; q->y1 = y + b->yoff2 - b->yoff; } else { q->x0 = *xpos + b->xoff; q->y0 = *ypos + b->yoff; q->x1 = *xpos + b->xoff2; q->y1 = *ypos + b->yoff2; } q->s0 = b->x0 * ipw; q->t0 = b->y0 * iph; q->s1 = b->x1 * ipw; q->t1 = b->y1 * iph; *xpos += b->xadvance; } ////////////////////////////////////////////////////////////////////////////// // // sdf computation // #define STBTT_min(a,b) ((a) < (b) ? (a) : (b)) #define STBTT_max(a,b) ((a) < (b) ? (b) : (a)) static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2]) { float q0perp = q0[1]*ray[0] - q0[0]*ray[1]; float q1perp = q1[1]*ray[0] - q1[0]*ray[1]; float q2perp = q2[1]*ray[0] - q2[0]*ray[1]; float roperp = orig[1]*ray[0] - orig[0]*ray[1]; float a = q0perp - 2*q1perp + q2perp; float b = q1perp - q0perp; float c = q0perp - roperp; float s0 = 0., s1 = 0.; int num_s = 0; if (a != 0.0) { float discr = b*b - a*c; if (discr > 0.0) { float rcpna = -1 / a; float d = (float) STBTT_sqrt(discr); s0 = (b+d) * rcpna; s1 = (b-d) * rcpna; if (s0 >= 0.0 && s0 <= 1.0) num_s = 1; if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) { if (num_s == 0) s0 = s1; ++num_s; } } } else { // 2*b*s + c = 0 // s = -c / (2*b) s0 = c / (-2 * b); if (s0 >= 0.0 && s0 <= 1.0) num_s = 1; } if (num_s == 0) return 0; else { float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]); float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2; float q0d = q0[0]*rayn_x + q0[1]*rayn_y; float q1d = q1[0]*rayn_x + q1[1]*rayn_y; float q2d = q2[0]*rayn_x + q2[1]*rayn_y; float rod = orig[0]*rayn_x + orig[1]*rayn_y; float q10d = q1d - q0d; float q20d = q2d - q0d; float q0rd = q0d - rod; hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d; hits[0][1] = a*s0+b; if (num_s > 1) { hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d; hits[1][1] = a*s1+b; return 2; } else { return 1; } } } static int equal(float *a, float *b) { return (a[0] == b[0] && a[1] == b[1]); } static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts) { int i; float orig[2], ray[2] = { 1, 0 }; float y_frac; int winding = 0; // make sure y never passes through a vertex of the shape y_frac = (float) STBTT_fmod(y, 1.0f); if (y_frac < 0.01f) y += 0.01f; else if (y_frac > 0.99f) y -= 0.01f; orig[0] = x; orig[1] = y; // test a ray from (-infinity,y) to (x,y) for (i=0; i < nverts; ++i) { if (verts[i].type == STBTT_vline) { int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y; int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y; if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; if (x_inter < x) winding += (y0 < y1) ? 1 : -1; } } if (verts[i].type == STBTT_vcurve) { int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ; int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy; int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ; int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2)); int by = STBTT_max(y0,STBTT_max(y1,y2)); if (y > ay && y < by && x > ax) { float q0[2],q1[2],q2[2]; float hits[2][2]; q0[0] = (float)x0; q0[1] = (float)y0; q1[0] = (float)x1; q1[1] = (float)y1; q2[0] = (float)x2; q2[1] = (float)y2; if (equal(q0,q1) || equal(q1,q2)) { x0 = (int)verts[i-1].x; y0 = (int)verts[i-1].y; x1 = (int)verts[i ].x; y1 = (int)verts[i ].y; if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; if (x_inter < x) winding += (y0 < y1) ? 1 : -1; } } else { int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits); if (num_hits >= 1) if (hits[0][0] < 0) winding += (hits[0][1] < 0 ? -1 : 1); if (num_hits >= 2) if (hits[1][0] < 0) winding += (hits[1][1] < 0 ? -1 : 1); } } } } return winding; } static float stbtt__cuberoot( float x ) { if (x<0) return -(float) STBTT_pow(-x,1.0f/3.0f); else return (float) STBTT_pow( x,1.0f/3.0f); } // x^3 + a*x^2 + b*x + c = 0 static int stbtt__solve_cubic(float a, float b, float c, float* r) { float s = -a / 3; float p = b - a*a / 3; float q = a * (2*a*a - 9*b) / 27 + c; float p3 = p*p*p; float d = q*q + 4*p3 / 27; if (d >= 0) { float z = (float) STBTT_sqrt(d); float u = (-q + z) / 2; float v = (-q - z) / 2; u = stbtt__cuberoot(u); v = stbtt__cuberoot(v); r[0] = s + u + v; return 1; } else { float u = (float) STBTT_sqrt(-p/3); float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative float m = (float) STBTT_cos(v); float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f; r[0] = s + u * 2 * m; r[1] = s - u * (m + n); r[2] = s - u * (m - n); //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe? //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f); //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f); return 3; } } STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) { float scale_x = scale, scale_y = scale; int ix0,iy0,ix1,iy1; int w,h; unsigned char *data; if (scale == 0) return NULL; stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1); // if empty, return NULL if (ix0 == ix1 || iy0 == iy1) return NULL; ix0 -= padding; iy0 -= padding; ix1 += padding; iy1 += padding; w = (ix1 - ix0); h = (iy1 - iy0); if (width ) *width = w; if (height) *height = h; if (xoff ) *xoff = ix0; if (yoff ) *yoff = iy0; // invert for y-downwards bitmaps scale_y = -scale_y; { // distance from singular values (in the same units as the pixel grid) const float eps = 1./1024, eps2 = eps*eps; int x,y,i,j; float *precompute; stbtt_vertex *verts; int num_verts = stbtt_GetGlyphShape(info, glyph, &verts); data = (unsigned char *) STBTT_malloc(w * h, info->userdata); precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata); for (i=0,j=num_verts-1; i < num_verts; j=i++) { if (verts[i].type == STBTT_vline) { float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y; float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)); precompute[i] = (dist < eps) ? 0.0f : 1.0f / dist; } else if (verts[i].type == STBTT_vcurve) { float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y; float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y; float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y; float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; float len2 = bx*bx + by*by; if (len2 >= eps2) precompute[i] = 1.0f / len2; else precompute[i] = 0.0f; } else precompute[i] = 0.0f; } for (y=iy0; y < iy1; ++y) { for (x=ix0; x < ix1; ++x) { float val; float min_dist = 999999.0f; float sx = (float) x + 0.5f; float sy = (float) y + 0.5f; float x_gspace = (sx / scale_x); float y_gspace = (sy / scale_y); int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path for (i=0; i < num_verts; ++i) { float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; if (verts[i].type == STBTT_vline && precompute[i] != 0.0f) { float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y; float dist,dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); if (dist2 < min_dist*min_dist) min_dist = (float) STBTT_sqrt(dist2); // coarse culling against bbox //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist && // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist) dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i]; STBTT_assert(i != 0); if (dist < min_dist) { // check position along line // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0) // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy) float dx = x1-x0, dy = y1-y0; float px = x0-sx, py = y0-sy; // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve float t = -(px*dx + py*dy) / (dx*dx + dy*dy); if (t >= 0.0f && t <= 1.0f) min_dist = dist; } } else if (verts[i].type == STBTT_vcurve) { float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y; float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y; float box_x0 = STBTT_min(STBTT_min(x0,x1),x2); float box_y0 = STBTT_min(STBTT_min(y0,y1),y2); float box_x1 = STBTT_max(STBTT_max(x0,x1),x2); float box_y1 = STBTT_max(STBTT_max(y0,y1),y2); // coarse culling against bbox to avoid computing cubic unnecessarily if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) { int num=0; float ax = x1-x0, ay = y1-y0; float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; float mx = x0 - sx, my = y0 - sy; float res[3] = {0.f,0.f,0.f}; float px,py,t,it,dist2; float a_inv = precompute[i]; if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula float a = 3*(ax*bx + ay*by); float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by); float c = mx*ax+my*ay; if (STBTT_fabs(a) < eps2) { // if a is 0, it's linear if (STBTT_fabs(b) >= eps2) { res[num++] = -c/b; } } else { float discriminant = b*b - 4*a*c; if (discriminant < 0) num = 0; else { float root = (float) STBTT_sqrt(discriminant); res[0] = (-b - root)/(2*a); res[1] = (-b + root)/(2*a); num = 2; // don't bother distinguishing 1-solution case, as code below will still work } } } else { float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv; float d = (mx*ax+my*ay) * a_inv; num = stbtt__solve_cubic(b, c, d, res); } dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); if (dist2 < min_dist*min_dist) min_dist = (float) STBTT_sqrt(dist2); if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) { t = res[0], it = 1.0f - t; px = it*it*x0 + 2*t*it*x1 + t*t*x2; py = it*it*y0 + 2*t*it*y1 + t*t*y2; dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); if (dist2 < min_dist * min_dist) min_dist = (float) STBTT_sqrt(dist2); } if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) { t = res[1], it = 1.0f - t; px = it*it*x0 + 2*t*it*x1 + t*t*x2; py = it*it*y0 + 2*t*it*y1 + t*t*y2; dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); if (dist2 < min_dist * min_dist) min_dist = (float) STBTT_sqrt(dist2); } if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) { t = res[2], it = 1.0f - t; px = it*it*x0 + 2*t*it*x1 + t*t*x2; py = it*it*y0 + 2*t*it*y1 + t*t*y2; dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); if (dist2 < min_dist * min_dist) min_dist = (float) STBTT_sqrt(dist2); } } } } if (winding == 0) min_dist = -min_dist; // if outside the shape, value is negative val = onedge_value + pixel_dist_scale * min_dist; if (val < 0) val = 0; else if (val > 255) val = 255; data[(y-iy0)*w+(x-ix0)] = (unsigned char) val; } } STBTT_free(precompute, info->userdata); STBTT_free(verts, info->userdata); } return data; } STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff); } STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata) { STBTT_free(bitmap, userdata); } ////////////////////////////////////////////////////////////////////////////// // // font name matching -- recommended not to use this // // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2) { stbtt_int32 i=0; // convert utf16 to utf8 and compare the results while converting while (len2) { stbtt_uint16 ch = s2[0]*256 + s2[1]; if (ch < 0x80) { if (i >= len1) return -1; if (s1[i++] != ch) return -1; } else if (ch < 0x800) { if (i+1 >= len1) return -1; if (s1[i++] != 0xc0 + (ch >> 6)) return -1; if (s1[i++] != 0x80 + (ch & 0x3f)) return -1; } else if (ch >= 0xd800 && ch < 0xdc00) { stbtt_uint32 c; stbtt_uint16 ch2 = s2[2]*256 + s2[3]; if (i+3 >= len1) return -1; c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; if (s1[i++] != 0xf0 + (c >> 18)) return -1; if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1; if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1; if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1; s2 += 2; // plus another 2 below len2 -= 2; } else if (ch >= 0xdc00 && ch < 0xe000) { return -1; } else { if (i+2 >= len1) return -1; if (s1[i++] != 0xe0 + (ch >> 12)) return -1; if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1; if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1; } s2 += 2; len2 -= 2; } return i; } static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2) { return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2); } // returns results in whatever encoding you request... but note that 2-byte encodings // will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID) { stbtt_int32 i,count,stringOffset; stbtt_uint8 *fc = font->data; stbtt_uint32 offset = font->fontstart; stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); if (!nm) return NULL; count = ttUSHORT(fc+nm+2); stringOffset = nm + ttUSHORT(fc+nm+4); for (i=0; i < count; ++i) { stbtt_uint32 loc = nm + 6 + 12 * i; if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2) && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) { *length = ttUSHORT(fc+loc+8); return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); } } return NULL; } static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) { stbtt_int32 i; stbtt_int32 count = ttUSHORT(fc+nm+2); stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); for (i=0; i < count; ++i) { stbtt_uint32 loc = nm + 6 + 12 * i; stbtt_int32 id = ttUSHORT(fc+loc+6); if (id == target_id) { // find the encoding stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4); // is this a Unicode encoding? if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) { stbtt_int32 slen = ttUSHORT(fc+loc+8); stbtt_int32 off = ttUSHORT(fc+loc+10); // check if there's a prefix match stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen); if (matchlen >= 0) { // check for target_id+1 immediately following, with same encoding & language if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) { slen = ttUSHORT(fc+loc+12+8); off = ttUSHORT(fc+loc+12+10); if (slen == 0) { if (matchlen == nlen) return 1; } else if (matchlen < nlen && name[matchlen] == ' ') { ++matchlen; if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) return 1; } } else { // if nothing immediately following if (matchlen == nlen) return 1; } } } // @TODO handle other encodings } } return 0; } static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags) { stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); stbtt_uint32 nm,hd; if (!stbtt__isfont(fc+offset)) return 0; // check italics/bold/underline flags in macStyle... if (flags) { hd = stbtt__find_table(fc, offset, "head"); if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0; } nm = stbtt__find_table(fc, offset, "name"); if (!nm) return 0; if (flags) { // if we checked the macStyle flags, then just check the family and ignore the subfamily if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; } else { if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; } return 0; } static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags) { stbtt_int32 i; for (i=0;;++i) { stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i); if (off < 0) return off; if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags)) return off; } } #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #endif STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, float pixel_height, unsigned char *pixels, int pw, int ph, int first_char, int num_chars, stbtt_bakedchar *chardata) { return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata); } STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index) { return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index); } STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data) { return stbtt_GetNumberOfFonts_internal((unsigned char *) data); } STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset) { return stbtt_InitFont_internal(info, (unsigned char *) data, offset); } STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags) { return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags); } STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) { return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2); } #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic pop #endif #endif // STB_TRUETYPE_IMPLEMENTATION // FULL VERSION HISTORY // // 1.25 (2021-07-11) many fixes // 1.24 (2020-02-05) fix warning // 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) // 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined // 1.21 (2019-02-25) fix warning // 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() // 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod // 1.18 (2018-01-29) add missing function // 1.17 (2017-07-23) make more arguments const; doc fix // 1.16 (2017-07-12) SDF support // 1.15 (2017-03-03) make more arguments const // 1.14 (2017-01-16) num-fonts-in-TTC function // 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual // 1.11 (2016-04-02) fix unused-variable warning // 1.10 (2016-04-02) allow user-defined fabs() replacement // fix memory leak if fontsize=0.0 // fix warning from duplicate typedef // 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges // 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; // allow PackFontRanges to pack and render in separate phases; // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); // fixed an assert() bug in the new rasterizer // replace assert() with STBTT_assert() in new rasterizer // 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) // also more precise AA rasterizer, except if shapes overlap // remove need for STBTT_sort // 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC // 1.04 (2015-04-15) typo in example // 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes // 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ // 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match // non-oversampled; STBTT_POINT_SIZE for packed case only // 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling // 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) // 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID // 0.8b (2014-07-07) fix a warning // 0.8 (2014-05-25) fix a few more warnings // 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back // 0.6c (2012-07-24) improve documentation // 0.6b (2012-07-20) fix a few more warnings // 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, // stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty // 0.5 (2011-12-09) bugfixes: // subpixel glyph renderer computed wrong bounding box // first vertex of shape can be off-curve (FreeSans) // 0.4b (2011-12-03) fixed an error in the font baking example // 0.4 (2011-12-01) kerning, subpixel rendering (tor) // bugfixes for: // codepoint-to-glyph conversion using table fmt=12 // codepoint-to-glyph conversion using table fmt=4 // stbtt_GetBakedQuad with non-square texture (Zer) // updated Hello World! sample to use kerning and subpixel // fixed some warnings // 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) // userdata, malloc-from-userdata, non-zero fill (stb) // 0.2 (2009-03-11) Fix unsigned/signed char warnings // 0.1 (2009-03-09) First public release // /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */ ================================================ FILE: shared/CMakeLists.txt ================================================ # Box2D code shared by samples, benchmarks, and unit tests set(BOX2D_SHARED_FILES benchmarks.c benchmarks.h determinism.c determinism.h human.c human.h random.c random.h ) add_library(shared STATIC ${BOX2D_SHARED_FILES}) set_target_properties(shared PROPERTIES C_STANDARD 17 ) if (BOX2D_COMPILE_WARNING_AS_ERROR) set_target_properties(shared PROPERTIES COMPILE_WARNING_AS_ERROR ON) endif() target_include_directories(shared PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(shared PRIVATE box2d) source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} PREFIX "" FILES ${BOX2D_SHARED_FILES}) ================================================ FILE: shared/benchmarks.c ================================================ // SPDX-FileCopyrightText: 2022 Erin Catto // SPDX-License-Identifier: MIT #include "benchmarks.h" #include "human.h" #include "box2d/box2d.h" #include #include #include #ifdef NDEBUG #define BENCHMARK_DEBUG 0 #else #define BENCHMARK_DEBUG 1 #endif void CreateJointGrid( b2WorldId worldId ) { b2World_EnableSleeping( worldId, false ); int N = BENCHMARK_DEBUG ? 10 : 100; // Allocate to avoid huge stack usage b2BodyId* bodies = malloc( N * N * sizeof( b2BodyId ) ); int index = 0; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.filter.categoryBits = 2; shapeDef.filter.maskBits = ~2u; b2Circle circle = { { 0.0f, 0.0f }, 0.4f }; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.drawScale = 0.4f; b2BodyDef bodyDef = b2DefaultBodyDef(); for ( int k = 0; k < N; ++k ) { for ( int i = 0; i < N; ++i ) { float fk = (float)k; float fi = (float)i; if ( k >= N / 2 - 3 && k <= N / 2 + 3 && i == 0 ) { bodyDef.type = b2_staticBody; } else { bodyDef.type = b2_dynamicBody; } bodyDef.position = (b2Vec2){ fk, -fi }; b2BodyId body = b2CreateBody( worldId, &bodyDef ); b2CreateCircleShape( body, &shapeDef, &circle ); if ( i > 0 ) { jointDef.base.bodyIdA = bodies[index - 1]; jointDef.base.bodyIdB = body; jointDef.base.localFrameA.p = (b2Vec2){ 0.0f, -0.5f }; jointDef.base.localFrameB.p = (b2Vec2){ 0.0f, 0.5f }; b2CreateRevoluteJoint( worldId, &jointDef ); } if ( k > 0 ) { jointDef.base.bodyIdA = bodies[index - N]; jointDef.base.bodyIdB = body; jointDef.base.localFrameA.p = (b2Vec2){ 0.5f, 0.0f }; jointDef.base.localFrameB.p = (b2Vec2){ -0.5f, 0.0f }; b2CreateRevoluteJoint( worldId, &jointDef ); } bodies[index++] = body; } } free( bodies ); } void CreateLargePyramid( b2WorldId worldId ) { b2World_EnableSleeping( worldId, false ); int baseCount = BENCHMARK_DEBUG ? 20 : 100; { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = (b2Vec2){ 0.0f, -1.0f }; b2BodyId groundId = b2CreateBody( worldId, &bodyDef ); b2Polygon box = b2MakeBox( 100.0f, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( groundId, &shapeDef, &box ); } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; // bodyDef.enableSleep = false; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; float a = 0.5f; b2Polygon box = b2MakeSquare( a ); float shift = 1.0f * a; for ( int i = 0; i < baseCount; ++i ) { float y = ( 2.0f * i + 1.0f ) * shift; for ( int j = i; j < baseCount; ++j ) { float x = ( i + 1.0f ) * shift + 2.0f * ( j - i ) * shift - a * baseCount; bodyDef.position = (b2Vec2){ x, y }; b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } } static void CreateSmallPyramid( b2WorldId worldId, int baseCount, float extent, float centerX, float baseY ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Polygon box = b2MakeSquare( extent ); for ( int i = 0; i < baseCount; ++i ) { float y = ( 2.0f * i + 1.0f ) * extent + baseY; for ( int j = i; j < baseCount; ++j ) { float x = ( i + 1.0f ) * extent + 2.0f * ( j - i ) * extent + centerX - 0.5f; bodyDef.position = (b2Vec2){ x, y }; b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } } void CreateManyPyramids( b2WorldId worldId ) { b2World_EnableSleeping( worldId, false ); int baseCount = 10; float extent = 0.5f; int rowCount = BENCHMARK_DEBUG ? 5 : 20; int columnCount = BENCHMARK_DEBUG ? 5 : 20; b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( worldId, &bodyDef ); float groundDeltaY = 2.0f * extent * ( baseCount + 1.0f ); float groundWidth = 2.0f * extent * columnCount * ( baseCount + 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); float groundY = 0.0f; for ( int i = 0; i < rowCount; ++i ) { b2Segment segment = { { -0.5f * 2.0f * groundWidth, groundY }, { 0.5f * 2.0f * groundWidth, groundY } }; b2CreateSegmentShape( groundId, &shapeDef, &segment ); groundY += groundDeltaY; } float baseWidth = 2.0f * extent * baseCount; float baseY = 0.0f; for ( int i = 0; i < rowCount; ++i ) { for ( int j = 0; j < columnCount; ++j ) { float centerX = -0.5f * groundWidth + j * ( baseWidth + 2.0f * extent ) + extent; CreateSmallPyramid( worldId, baseCount, extent, centerX, baseY ); } baseY += groundDeltaY; } } #ifdef NDEBUG enum RainConstants { RAIN_ROW_COUNT = 5, RAIN_COLUMN_COUNT = 40, RAIN_GROUP_SIZE = 5, }; #else enum RainConstants { RAIN_ROW_COUNT = 3, RAIN_COLUMN_COUNT = 10, RAIN_GROUP_SIZE = 2, }; #endif typedef struct Group { Human humans[RAIN_GROUP_SIZE]; } Group; typedef struct RainData { Group groups[RAIN_ROW_COUNT * RAIN_COLUMN_COUNT]; float gridSize; int gridCount; int columnCount; int columnIndex; } RainData; RainData g_rainData; void CreateRain( b2WorldId worldId ) { memset( &g_rainData, 0, sizeof( g_rainData ) ); g_rainData.gridSize = 0.5f; g_rainData.gridCount = BENCHMARK_DEBUG ? 200 : 500; { b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId groundId = b2CreateBody( worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); float y = 0.0f; float width = g_rainData.gridSize; float height = g_rainData.gridSize; for ( int i = 0; i < RAIN_ROW_COUNT; ++i ) { float x = -0.5f * g_rainData.gridCount * g_rainData.gridSize; for ( int j = 0; j <= g_rainData.gridCount; ++j ) { b2Polygon box = b2MakeOffsetBox( 0.5f * width, 0.5f * height, (b2Vec2){ x, y }, b2Rot_identity ); b2CreatePolygonShape( groundId, &shapeDef, &box ); // b2Segment segment = { { x - 0.5f * width, y }, { x + 0.5f * width, y } }; // b2CreateSegmentShape( groundId, &shapeDef, &segment ); x += g_rainData.gridSize; } y += 45.0f; } } g_rainData.columnCount = 0; g_rainData.columnIndex = 0; } void CreateGroup( b2WorldId worldId, int rowIndex, int columnIndex ) { assert( rowIndex < RAIN_ROW_COUNT && columnIndex < RAIN_COLUMN_COUNT ); int groupIndex = rowIndex * RAIN_COLUMN_COUNT + columnIndex; float span = g_rainData.gridCount * g_rainData.gridSize; float groupDistance = 1.0f * span / RAIN_COLUMN_COUNT; b2Vec2 position; position.x = -0.5f * span + groupDistance * ( columnIndex + 0.5f ); position.y = 40.0f + 45.0f * rowIndex; float scale = 1.0f; float jointFriction = 0.05f; float jointHertz = 5.0f; float jointDamping = 0.5f; for ( int i = 0; i < RAIN_GROUP_SIZE; ++i ) { Human* human = g_rainData.groups[groupIndex].humans + i; CreateHuman( human, worldId, position, scale, jointFriction, jointHertz, jointDamping, i + 1, NULL, false ); position.x += 0.5f; } } void DestroyGroup( int rowIndex, int columnIndex ) { assert( rowIndex < RAIN_ROW_COUNT && columnIndex < RAIN_COLUMN_COUNT ); int groupIndex = rowIndex * RAIN_COLUMN_COUNT + columnIndex; for ( int i = 0; i < RAIN_GROUP_SIZE; ++i ) { DestroyHuman( g_rainData.groups[groupIndex].humans + i ); } } float StepRain( b2WorldId worldId, int stepCount ) { int delay = BENCHMARK_DEBUG ? 0x1F : 0x7; if ( ( stepCount & delay ) == 0 ) { if ( g_rainData.columnCount < RAIN_COLUMN_COUNT ) { for ( int i = 0; i < RAIN_ROW_COUNT; ++i ) { CreateGroup( worldId, i, g_rainData.columnCount ); } g_rainData.columnCount += 1; } else { for ( int i = 0; i < RAIN_ROW_COUNT; ++i ) { DestroyGroup( i, g_rainData.columnIndex ); CreateGroup( worldId, i, g_rainData.columnIndex ); } g_rainData.columnIndex = ( g_rainData.columnIndex + 1 ) % RAIN_COLUMN_COUNT; } } return 0.0f; } #define SPINNER_POINT_COUNT 360 typedef struct { b2JointId spinnerId; } SpinnerData; SpinnerData g_spinnerData; void CreateSpinner( b2WorldId worldId ) { b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( worldId, &bodyDef ); b2Vec2 points[SPINNER_POINT_COUNT]; b2Rot q = b2MakeRot( -2.0f * B2_PI / SPINNER_POINT_COUNT ); b2Vec2 p = { 40.0f, 0.0f }; for ( int i = 0; i < SPINNER_POINT_COUNT; ++i ) { points[i] = (b2Vec2){ p.x, p.y + 32.0f }; p = b2RotateVector( q, p ); } b2SurfaceMaterial material = { 0 }; material.friction = 0.1f; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = SPINNER_POINT_COUNT; chainDef.isLoop = true; chainDef.materials = &material; chainDef.materialCount = 1; b2CreateChain( groundId, &chainDef ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = (b2Vec2){ 0.0, 12.0f }; bodyDef.enableSleep = false; b2BodyId spinnerId = b2CreateBody( worldId, &bodyDef ); b2Polygon box = b2MakeRoundedBox( 0.4f, 20.0f, 0.2f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.0f; b2CreatePolygonShape( spinnerId, &shapeDef, &box ); float motorSpeed = 5.0f; // float maxMotorTorque = 100.0f * 40000.0f; float maxMotorTorque = FLT_MAX; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = spinnerId; jointDef.base.localFrameA.p = bodyDef.position; jointDef.enableMotor = true; jointDef.motorSpeed = motorSpeed; jointDef.maxMotorTorque = maxMotorTorque; g_spinnerData.spinnerId = b2CreateRevoluteJoint( worldId, &jointDef ); } b2Capsule capsule = { { -0.25f, 0.0f }, { 0.25f, 0.0f }, 0.25f }; b2Circle circle = { { 0.0f, 0.0f }, 0.35f }; b2Polygon square = b2MakeSquare( 0.35f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.1f; shapeDef.material.restitution = 0.1f; shapeDef.density = 0.25f; int bodyCount = BENCHMARK_DEBUG ? 499 : 2 * 3038; float x = -23.0f, y = 2.0f; for ( int i = 0; i < bodyCount; ++i ) { bodyDef.position = (b2Vec2){ x, y }; b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); int remainder = i % 3; if ( remainder == 0 ) { b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); } else if ( remainder == 1 ) { b2CreateCircleShape( bodyId, &shapeDef, &circle ); } else if ( remainder == 2 ) { b2CreatePolygonShape( bodyId, &shapeDef, &square ); } x += 0.5f; if ( x >= 23.0f ) { x = -23.0f; y += 0.5f; } } } float StepSpinner( b2WorldId worldId, int stepCount ) { (void)worldId; (void)stepCount; return b2RevoluteJoint_GetAngle( g_spinnerData.spinnerId ); } void CreateSmash( b2WorldId worldId ) { b2World_SetGravity( worldId, b2Vec2_zero ); { b2Polygon box = b2MakeBox( 4.0f, 4.0f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = (b2Vec2){ -20.0f, 0.0f }; bodyDef.linearVelocity = (b2Vec2){ 40.0f, 0.0f }; b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 8.0f; b2CreatePolygonShape( bodyId, &shapeDef, &box ); } float d = 0.4f; b2Polygon box = b2MakeSquare( 0.5f * d ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.isAwake = false; b2ShapeDef shapeDef = b2DefaultShapeDef(); int columns = BENCHMARK_DEBUG ? 20 : 120; int rows = BENCHMARK_DEBUG ? 10 : 80; for ( int i = 0; i < columns; ++i ) { for ( int j = 0; j < rows; ++j ) { bodyDef.position.x = i * d + 30.0f; bodyDef.position.y = ( j - rows / 2.0f ) * d; b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } } void CreateTumbler( b2WorldId worldId ) { b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( worldId, &bodyDef ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = (b2Vec2){ 0.0f, 10.0f }; b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 50.0f; b2Polygon polygon; polygon = b2MakeOffsetBox( 0.5f, 10.0f, (b2Vec2){ 10.0f, 0.0f }, b2Rot_identity ); b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); polygon = b2MakeOffsetBox( 0.5f, 10.0f, (b2Vec2){ -10.0f, 0.0f }, b2Rot_identity ); b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); polygon = b2MakeOffsetBox( 10.0f, 0.5f, (b2Vec2){ 0.0f, 10.0f }, b2Rot_identity ); b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); polygon = b2MakeOffsetBox( 10.0f, 0.5f, (b2Vec2){ 0.0f, -10.0f }, b2Rot_identity ); b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); float motorSpeed = 25.0f; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = (b2Vec2){ 0.0f, 10.0f }; jointDef.base.localFrameB.p = (b2Vec2){ 0.0f, 0.0f }; jointDef.motorSpeed = ( B2_PI / 180.0f ) * motorSpeed; jointDef.maxMotorTorque = 1e8f; jointDef.enableMotor = true; b2CreateRevoluteJoint( worldId, &jointDef ); } int gridCount = BENCHMARK_DEBUG ? 20 : 45; b2Polygon polygon = b2MakeBox( 0.125f, 0.125f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); float y = -0.2f * gridCount + 10.0f; for ( int i = 0; i < gridCount; ++i ) { float x = -0.2f * gridCount; for ( int j = 0; j < gridCount; ++j ) { bodyDef.position = (b2Vec2){ x, y }; b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); x += 0.4f; } y += 0.4f; } } void CreateWasher( b2WorldId worldId ) { bool kinematic = true; b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); groundId = b2CreateBody( worldId, &bodyDef ); } { float motorSpeed = 25.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = (b2Vec2){ 0.0f, 10.0f }; if (kinematic == true) { bodyDef.type = b2_kinematicBody; bodyDef.angularVelocity = ( B2_PI / 180.0f ) * motorSpeed; bodyDef.linearVelocity = (b2Vec2){ 0.001f, -0.002f }; } else { bodyDef.type = b2_dynamicBody; } b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); float r0 = 14.0f; float r1 = 16.0f; float r2 = 18.0f; float angle = B2_PI / 18.0f; b2Rot q = { cosf( angle ), sinf(angle) }; b2Rot qo = { cosf( 0.1f * angle ), sinf(0.1f * angle) }; b2Vec2 u1 = { 1.0f, 0.0f }; for ( int i = 0; i < 36; ++i ) { b2Vec2 u2; if (i == 35) { u2 = (b2Vec2){ 1.0f, 0.0f }; } else { u2 = b2RotateVector( q, u1 ); } { b2Vec2 a1 = b2InvRotateVector( qo, u1 ); b2Vec2 a2 = b2RotateVector( qo, u2 ); b2Vec2 p1 = b2MulSV( r1, a1 ); b2Vec2 p2 = b2MulSV( r2, a1 ); b2Vec2 p3 = b2MulSV( r1, a2 ); b2Vec2 p4 = b2MulSV( r2, a2 ); b2Vec2 points[4] = { p1, p2, p3, p4 }; b2Hull hull = b2ComputeHull( points, 4 ); b2Polygon polygon = b2MakePolygon( &hull, 0.0f ); b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); } if ( i % 9 == 0 ) { b2Vec2 p1 = b2MulSV( r0, u1 ); b2Vec2 p2 = b2MulSV( r1, u1 ); b2Vec2 p3 = b2MulSV( r0, u2 ); b2Vec2 p4 = b2MulSV( r1, u2 ); b2Vec2 points[4] = { p1, p2, p3, p4 }; b2Hull hull = b2ComputeHull( points, 4 ); b2Polygon polygon = b2MakePolygon( &hull, 0.0f ); b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); } u1 = u2; } if ( kinematic == false ) { b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = groundId; jointDef.base.bodyIdB = bodyId; jointDef.base.localFrameA.p = (b2Vec2){ 0.0f, 10.0f }; jointDef.base.localFrameB.p = (b2Vec2){ 0.0f, 0.0f }; jointDef.motorSpeed = ( B2_PI / 180.0f ) * motorSpeed; jointDef.maxMotorTorque = 1e8f; jointDef.enableMotor = true; b2CreateRevoluteJoint( worldId, &jointDef ); } } int gridCount = BENCHMARK_DEBUG ? 20 : 90; float a = 0.1f; b2Polygon polygon = b2MakeSquare( a ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); float y = -1.1f * a * gridCount + 10.0f; for ( int i = 0; i < gridCount; ++i ) { float x = -1.1f * a * gridCount; for ( int j = 0; j < gridCount; ++j ) { bodyDef.position = (b2Vec2){ x, y }; b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); x += 2.1f * a; } y += 2.1f * a; } } ================================================ FILE: shared/benchmarks.h ================================================ // SPDX-FileCopyrightText: 2022 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "box2d/id.h" #include // This allows benchmarks to be tested on the benchmark app and also visualized in the samples app #ifdef __cplusplus extern "C" { #endif void CreateJointGrid( b2WorldId worldId ); void CreateLargePyramid( b2WorldId worldId ); void CreateManyPyramids( b2WorldId worldId ); void CreateRain( b2WorldId worldId ); float StepRain( b2WorldId worldId, int stepCount ); void CreateSpinner( b2WorldId worldId ); float StepSpinner( b2WorldId worldId, int stepCount ); void CreateSmash( b2WorldId worldId ); void CreateTumbler( b2WorldId worldId ); void CreateWasher( b2WorldId worldId ); #ifdef __cplusplus } #endif ================================================ FILE: shared/determinism.c ================================================ // SPDX-FileCopyrightText: 2022 Erin Catto // SPDX-License-Identifier: MIT #include "determinism.h" #include "box2d/box2d.h" #include #include FallingHingeData CreateFallingHinges( b2WorldId worldId ) { { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.position = (b2Vec2){ 0.0f, -1.0f }; b2BodyId groundId = b2CreateBody( worldId, &bodyDef ); b2Polygon box = b2MakeBox( 20.0f, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( groundId, &shapeDef, &box ); } int columnCount = 4; int rowCount = 30; int bodyCount = rowCount * columnCount; b2BodyId* bodyIds = calloc( bodyCount, sizeof( b2BodyId ) ); float h = 0.25f; float r = 0.1f * h; b2Polygon box = b2MakeRoundedBox( h - r, h - r, r ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.3f; float offset = 0.4f * h; float dx = 10.0f * h; float xroot = -0.5f * dx * ( columnCount - 1.0f ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.enableLimit = true; jointDef.lowerAngle = -0.1f * B2_PI; jointDef.upperAngle = 0.2f * B2_PI; jointDef.enableSpring = true; jointDef.hertz = 0.5f; jointDef.dampingRatio = 0.5f; jointDef.base.localFrameA.p = (b2Vec2){ h, h }; jointDef.base.localFrameB.p = (b2Vec2){ offset, -h }; jointDef.base.constraintHertz = 60.0f; jointDef.base.constraintDampingRatio = 0.0f; jointDef.base.drawScale = 0.5f; int bodyIndex = 0; for ( int j = 0; j < columnCount; ++j ) { float x = xroot + j * dx; b2BodyId prevBodyId = b2_nullBodyId; for ( int i = 0; i < rowCount; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position.x = x + offset * i; bodyDef.position.y = h + 2.0f * h * i; // this tests the deterministic cosine and sine functions bodyDef.rotation = b2MakeRot( 0.1f * i - 1.0f ); b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); if ( ( i & 1 ) == 0 ) { prevBodyId = bodyId; } else { jointDef.base.bodyIdA = prevBodyId; jointDef.base.bodyIdB = bodyId; b2CreateRevoluteJoint( worldId, &jointDef ); prevBodyId = b2_nullBodyId; } b2CreatePolygonShape( bodyId, &shapeDef, &box ); assert( bodyIndex < bodyCount ); bodyIds[bodyIndex] = bodyId; bodyIndex += 1; } } assert( bodyIndex == bodyCount ); FallingHingeData data = { .bodyIds = bodyIds, .bodyCount = bodyCount, .stepCount = 0, .sleepStep = -1, .hash = 0, }; return data; } bool UpdateFallingHinges( b2WorldId worldId, FallingHingeData* data ) { if ( data->hash == 0 ) { b2BodyEvents bodyEvents = b2World_GetBodyEvents( worldId ); if ( bodyEvents.moveCount == 0 ) { int awakeCount = b2World_GetAwakeBodyCount( worldId ); assert( awakeCount == 0 ); data->hash = B2_HASH_INIT; for ( int i = 0; i < data->bodyCount; ++i ) { b2Transform xf = b2Body_GetTransform( data->bodyIds[i] ); data->hash = b2Hash( data->hash, (uint8_t*)( &xf ), sizeof( b2Transform ) ); } data->sleepStep = data->stepCount; } } data->stepCount += 1; return data->hash != 0; } void DestroyFallingHinges( FallingHingeData* data ) { free( data->bodyIds ); data->bodyIds = NULL; } ================================================ FILE: shared/determinism.h ================================================ // SPDX-FileCopyrightText: 2025 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "box2d/id.h" #include #ifdef __cplusplus extern "C" { #endif typedef struct FallingHingeData { b2BodyId* bodyIds; int bodyCount; int stepCount; int sleepStep; uint32_t hash; } FallingHingeData; FallingHingeData CreateFallingHinges( b2WorldId worldId ); bool UpdateFallingHinges( b2WorldId worldId, FallingHingeData* data ); void DestroyFallingHinges( FallingHingeData* data ); #ifdef __cplusplus } #endif ================================================ FILE: shared/human.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "human.h" #include "random.h" #include "box2d/box2d.h" #include "box2d/math_functions.h" #include void CreateHuman( Human* human, b2WorldId worldId, b2Vec2 position, float scale, float frictionTorque, float hertz, float dampingRatio, int groupIndex, void* userData, bool colorize ) { assert( human->isSpawned == false ); for ( int i = 0; i < bone_count; ++i ) { human->bones[i].bodyId = b2_nullBodyId; human->bones[i].jointId = b2_nullJointId; human->bones[i].frictionScale = 1.0f; human->bones[i].parentIndex = -1; } human->originalScale = scale; human->scale = scale; human->frictionTorque = frictionTorque; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.sleepThreshold = 0.1f; bodyDef.userData = userData; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.material.friction = 0.2f; shapeDef.filter.groupIndex = -groupIndex; shapeDef.filter.categoryBits = 2; shapeDef.filter.maskBits = ( 1 | 2 ); b2ShapeDef footShapeDef = shapeDef; footShapeDef.material.friction = 0.05f; // feet don't collide with ragdolls footShapeDef.filter.categoryBits = 2; footShapeDef.filter.maskBits = 1; if ( colorize ) { footShapeDef.material.customColor = b2_colorSaddleBrown; } float s = scale; float maxTorque = frictionTorque * s; bool enableMotor = true; bool enableLimit = true; float drawSize = 0.05f; b2HexColor shirtColor = b2_colorMediumTurquoise; b2HexColor pantColor = b2_colorDodgerBlue; b2HexColor skinColors[4] = { b2_colorNavajoWhite, b2_colorLightYellow, b2_colorPeru, b2_colorTan }; b2HexColor skinColor = skinColors[groupIndex % 4]; // hip { Bone* bone = human->bones + bone_hip; bone->parentIndex = -1; bodyDef.position = b2Add( (b2Vec2){ 0.0f, 0.95f * s }, position ); bodyDef.linearDamping = 0.0f; bodyDef.name = "hip"; bone->bodyId = b2CreateBody( worldId, &bodyDef ); if ( colorize ) { shapeDef.material.customColor = pantColor; } b2Capsule capsule = { { 0.0f, -0.02f * s }, { 0.0f, 0.02f * s }, 0.095f * s }; b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); } // torso { Bone* bone = human->bones + bone_torso; bone->parentIndex = bone_hip; bodyDef.position = b2Add( (b2Vec2){ 0.0f, 1.2f * s }, position ); bodyDef.linearDamping = 0.0f; bodyDef.name = "torso"; // bodyDef.type = b2_staticBody; bone->bodyId = b2CreateBody( worldId, &bodyDef ); bone->frictionScale = 0.5f; bodyDef.type = b2_dynamicBody; if ( colorize ) { shapeDef.material.customColor = shirtColor; } b2Capsule capsule = { { 0.0f, -0.135f * s }, { 0.0f, 0.135f * s }, 0.09f * s }; b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); b2Vec2 pivot = b2Add( (b2Vec2){ 0.0f, 1.0f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = human->bones[bone->parentIndex].bodyId; jointDef.base.bodyIdB = bone->bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = -0.25f * B2_PI; jointDef.upperAngle = 0.0f; jointDef.enableMotor = enableMotor; jointDef.maxMotorTorque = bone->frictionScale * maxTorque; jointDef.enableSpring = hertz > 0.0f; jointDef.hertz = hertz; jointDef.dampingRatio = dampingRatio; jointDef.base.drawScale = drawSize; bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // head { Bone* bone = human->bones + bone_head; bone->parentIndex = bone_torso; bodyDef.position = b2Add( (b2Vec2){ 0.0f * s, 1.475f * s }, position ); bodyDef.linearDamping = 0.1f; bodyDef.name = "head"; bone->bodyId = b2CreateBody( worldId, &bodyDef ); bone->frictionScale = 0.25f; if ( colorize ) { shapeDef.material.customColor = skinColor; } b2Capsule capsule = { { 0.0f, -0.038f * s }, { 0.0f, 0.039f * s }, 0.075f * s }; b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); //// neck // capsule = { { 0.0f, -0.12f * s }, { 0.0f, -0.08f * s }, 0.05f * s }; // b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); b2Vec2 pivot = b2Add( (b2Vec2){ 0.0f, 1.4f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = human->bones[bone->parentIndex].bodyId; jointDef.base.bodyIdB = bone->bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = -0.3f * B2_PI; jointDef.upperAngle = 0.1f * B2_PI; jointDef.enableMotor = enableMotor; jointDef.maxMotorTorque = bone->frictionScale * maxTorque; jointDef.enableSpring = hertz > 0.0f; jointDef.hertz = hertz; jointDef.dampingRatio = dampingRatio; jointDef.base.drawScale = drawSize; bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // upper left leg { Bone* bone = human->bones + bone_upperLeftLeg; bone->parentIndex = bone_hip; bodyDef.position = b2Add( (b2Vec2){ 0.0f, 0.775f * s }, position ); bodyDef.linearDamping = 0.0f; bodyDef.name = "upper_left_leg"; bone->bodyId = b2CreateBody( worldId, &bodyDef ); bone->frictionScale = 1.0f; if ( colorize ) { shapeDef.material.customColor = pantColor; } b2Capsule capsule = { { 0.0f, -0.125f * s }, { 0.0f, 0.125f * s }, 0.06f * s }; b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); b2Vec2 pivot = b2Add( (b2Vec2){ 0.0f, 0.9f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = human->bones[bone->parentIndex].bodyId; jointDef.base.bodyIdB = bone->bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = -0.05f * B2_PI; jointDef.upperAngle = 0.4f * B2_PI; jointDef.enableMotor = enableMotor; jointDef.maxMotorTorque = bone->frictionScale * maxTorque; jointDef.enableSpring = hertz > 0.0f; jointDef.hertz = hertz; jointDef.dampingRatio = dampingRatio; jointDef.base.drawScale = drawSize; bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } b2Vec2 points[4] = { { -0.03f * s, -0.185f * s }, { 0.11f * s, -0.185f * s }, { 0.11f * s, -0.16f * s }, { -0.03f * s, -0.14f * s }, }; b2Hull footHull = b2ComputeHull( points, 4 ); b2Polygon footPolygon = b2MakePolygon( &footHull, 0.015f * s ); // lower left leg { Bone* bone = human->bones + bone_lowerLeftLeg; bone->parentIndex = bone_upperLeftLeg; bodyDef.position = b2Add( (b2Vec2){ 0.0f, 0.475f * s }, position ); bodyDef.linearDamping = 0.0f; bodyDef.name = "lower_left_leg"; bone->bodyId = b2CreateBody( worldId, &bodyDef ); bone->frictionScale = 0.5f; if ( colorize ) { shapeDef.material.customColor = pantColor; } b2Capsule capsule = { { 0.0f, -0.155f * s }, { 0.0f, 0.125f * s }, 0.045f * s }; b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); // b2Polygon box = b2MakeOffsetBox(0.1f * s, 0.03f * s, {0.05f * s, -0.175f * s}, 0.0f); // b2CreatePolygonShape(bone->bodyId, &shapeDef, &box); // capsule = { { -0.02f * s, -0.175f * s }, { 0.13f * s, -0.175f * s }, 0.03f * s }; // b2CreateCapsuleShape( bone->bodyId, &footShapeDef, &capsule ); b2CreatePolygonShape( bone->bodyId, &footShapeDef, &footPolygon ); b2Vec2 pivot = b2Add( (b2Vec2){ 0.0f, 0.625f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = human->bones[bone->parentIndex].bodyId; jointDef.base.bodyIdB = bone->bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = -0.5f * B2_PI; jointDef.upperAngle = -0.02f * B2_PI; jointDef.enableMotor = enableMotor; jointDef.maxMotorTorque = bone->frictionScale * maxTorque; jointDef.enableSpring = hertz > 0.0f; jointDef.hertz = hertz; jointDef.dampingRatio = dampingRatio; jointDef.base.drawScale = drawSize; bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // upper right leg { Bone* bone = human->bones + bone_upperRightLeg; bone->parentIndex = bone_hip; bodyDef.position = b2Add( (b2Vec2){ 0.0f, 0.775f * s }, position ); bodyDef.linearDamping = 0.0f; bodyDef.name = "upper_right_leg"; bone->bodyId = b2CreateBody( worldId, &bodyDef ); bone->frictionScale = 1.0f; if ( colorize ) { shapeDef.material.customColor = pantColor; } b2Capsule capsule = { { 0.0f, -0.125f * s }, { 0.0f, 0.125f * s }, 0.06f * s }; b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); b2Vec2 pivot = b2Add( (b2Vec2){ 0.0f, 0.9f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = human->bones[bone->parentIndex].bodyId; jointDef.base.bodyIdB = bone->bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = -0.05f * B2_PI; jointDef.upperAngle = 0.4f * B2_PI; jointDef.enableMotor = enableMotor; jointDef.maxMotorTorque = bone->frictionScale * maxTorque; jointDef.enableSpring = hertz > 0.0f; jointDef.hertz = hertz; jointDef.dampingRatio = dampingRatio; jointDef.base.drawScale = drawSize; bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // lower right leg { Bone* bone = human->bones + bone_lowerRightLeg; bone->parentIndex = bone_upperRightLeg; bodyDef.position = b2Add( (b2Vec2){ 0.0f, 0.475f * s }, position ); bodyDef.linearDamping = 0.0f; bodyDef.name = "lower_right_leg"; bone->bodyId = b2CreateBody( worldId, &bodyDef ); bone->frictionScale = 0.5f; if ( colorize ) { shapeDef.material.customColor = pantColor; } b2Capsule capsule = { { 0.0f, -0.155f * s }, { 0.0f, 0.125f * s }, 0.045f * s }; b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); // b2Polygon box = b2MakeOffsetBox(0.1f * s, 0.03f * s, {0.05f * s, -0.175f * s}, 0.0f); // b2CreatePolygonShape(bone->bodyId, &shapeDef, &box); // capsule = { { -0.02f * s, -0.175f * s }, { 0.13f * s, -0.175f * s }, 0.03f * s }; // b2CreateCapsuleShape( bone->bodyId, &footShapeDef, &capsule ); b2CreatePolygonShape( bone->bodyId, &footShapeDef, &footPolygon ); b2Vec2 pivot = b2Add( (b2Vec2){ 0.0f, 0.625f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = human->bones[bone->parentIndex].bodyId; jointDef.base.bodyIdB = bone->bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = -0.5f * B2_PI; jointDef.upperAngle = -0.02f * B2_PI; jointDef.enableMotor = enableMotor; jointDef.maxMotorTorque = bone->frictionScale * maxTorque; jointDef.enableSpring = hertz > 0.0f; jointDef.hertz = hertz; jointDef.dampingRatio = dampingRatio; jointDef.base.drawScale = drawSize; bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // upper left arm { Bone* bone = human->bones + bone_upperLeftArm; bone->parentIndex = bone_torso; bone->frictionScale = 0.5f; bodyDef.position = b2Add( (b2Vec2){ 0.0f, 1.225f * s }, position ); bodyDef.linearDamping = 0.0f; bodyDef.name = "upper_left_arm"; bone->bodyId = b2CreateBody( worldId, &bodyDef ); if ( colorize ) { shapeDef.material.customColor = shirtColor; } b2Capsule capsule = { { 0.0f, -0.125f * s }, { 0.0f, 0.125f * s }, 0.035f * s }; b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); b2Vec2 pivot = b2Add( (b2Vec2){ 0.0f, 1.35f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = human->bones[bone->parentIndex].bodyId; jointDef.base.bodyIdB = bone->bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = -0.1f * B2_PI; jointDef.upperAngle = 0.8f * B2_PI; jointDef.enableMotor = enableMotor; jointDef.maxMotorTorque = bone->frictionScale * maxTorque; jointDef.enableSpring = hertz > 0.0f; jointDef.hertz = hertz; jointDef.dampingRatio = dampingRatio; jointDef.base.drawScale = drawSize; bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // lower left arm { Bone* bone = human->bones + bone_lowerLeftArm; bone->parentIndex = bone_upperLeftArm; bodyDef.position = b2Add( (b2Vec2){ 0.0f, 0.975f * s }, position ); bodyDef.linearDamping = 0.1f; bodyDef.name = "lower_left_arm"; bone->bodyId = b2CreateBody( worldId, &bodyDef ); bone->frictionScale = 0.1f; if ( colorize ) { shapeDef.material.customColor = skinColor; } b2Capsule capsule = { { 0.0f, -0.125f * s }, { 0.0f, 0.125f * s }, 0.03f * s }; b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); b2Vec2 pivot = b2Add( (b2Vec2){ 0.0f, 1.1f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = human->bones[bone->parentIndex].bodyId; jointDef.base.bodyIdB = bone->bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameA.q = b2MakeRot(0.25f * B2_PI); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = -0.2f * B2_PI; jointDef.upperAngle = 0.3f * B2_PI; jointDef.enableMotor = enableMotor; jointDef.maxMotorTorque = bone->frictionScale * maxTorque; jointDef.enableSpring = hertz > 0.0f; jointDef.hertz = hertz; jointDef.dampingRatio = dampingRatio; jointDef.base.drawScale = drawSize; bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // upper right arm { Bone* bone = human->bones + bone_upperRightArm; bone->parentIndex = bone_torso; bodyDef.position = b2Add( (b2Vec2){ 0.0f, 1.225f * s }, position ); bodyDef.linearDamping = 0.0f; bodyDef.name = "upper_right_arm"; bone->bodyId = b2CreateBody( worldId, &bodyDef ); bone->frictionScale = 0.5f; if ( colorize ) { shapeDef.material.customColor = shirtColor; } b2Capsule capsule = { { 0.0f, -0.125f * s }, { 0.0f, 0.125f * s }, 0.035f * s }; b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); b2Vec2 pivot = b2Add( (b2Vec2){ 0.0f, 1.35f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = human->bones[bone->parentIndex].bodyId; jointDef.base.bodyIdB = bone->bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = -0.1f * B2_PI; jointDef.upperAngle = 0.8f * B2_PI; jointDef.enableMotor = enableMotor; jointDef.maxMotorTorque = bone->frictionScale * maxTorque; jointDef.enableSpring = hertz > 0.0f; jointDef.hertz = hertz; jointDef.dampingRatio = dampingRatio; jointDef.base.drawScale = drawSize; bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // lower right arm { Bone* bone = human->bones + bone_lowerRightArm; bone->parentIndex = bone_upperRightArm; bodyDef.position = b2Add( (b2Vec2){ 0.0f, 0.975f * s }, position ); bodyDef.linearDamping = 0.1f; bodyDef.name = "lower_right_arm"; bone->bodyId = b2CreateBody( worldId, &bodyDef ); bone->frictionScale = 0.1f; if ( colorize ) { shapeDef.material.customColor = skinColor; } b2Capsule capsule = { { 0.0f, -0.125f * s }, { 0.0f, 0.125f * s }, 0.03f * s }; b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); b2Vec2 pivot = b2Add( (b2Vec2){ 0.0f, 1.1f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.base.bodyIdA = human->bones[bone->parentIndex].bodyId; jointDef.base.bodyIdB = bone->bodyId; jointDef.base.localFrameA.p = b2Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); jointDef.base.localFrameA.q = b2MakeRot( 0.25f * B2_PI ); jointDef.base.localFrameB.p = b2Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = -0.2f * B2_PI; jointDef.upperAngle = 0.3f * B2_PI; jointDef.enableMotor = enableMotor; jointDef.maxMotorTorque = bone->frictionScale * maxTorque; jointDef.enableSpring = hertz > 0.0f; jointDef.hertz = hertz; jointDef.dampingRatio = dampingRatio; jointDef.base.drawScale = drawSize; bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } human->isSpawned = true; } void DestroyHuman( Human* human ) { assert( human->isSpawned == true ); for ( int i = 0; i < bone_count; ++i ) { if ( B2_IS_NULL( human->bones[i].jointId ) ) { continue; } b2DestroyJoint( human->bones[i].jointId, false ); human->bones[i].jointId = b2_nullJointId; } for ( int i = 0; i < bone_count; ++i ) { if ( B2_IS_NULL( human->bones[i].bodyId ) ) { continue; } b2DestroyBody( human->bones[i].bodyId ); human->bones[i].bodyId = b2_nullBodyId; } human->isSpawned = false; } void Human_SetVelocity( Human* human, b2Vec2 velocity ) { for ( int i = 0; i < bone_count; ++i ) { b2BodyId bodyId = human->bones[i].bodyId; if ( B2_IS_NULL( bodyId ) ) { continue; } b2Body_SetLinearVelocity( bodyId, velocity ); } } void Human_ApplyRandomAngularImpulse( Human* human, float magnitude ) { assert( human->isSpawned == true ); float impulse = RandomFloatRange( -magnitude, magnitude ); b2Body_ApplyAngularImpulse( human->bones[bone_torso].bodyId, impulse, true ); } void Human_SetJointFrictionTorque( Human* human, float torque ) { assert( human->isSpawned == true ); if ( torque == 0.0f ) { for ( int i = 1; i < bone_count; ++i ) { b2RevoluteJoint_EnableMotor( human->bones[i].jointId, false ); } } else { for ( int i = 1; i < bone_count; ++i ) { b2RevoluteJoint_EnableMotor( human->bones[i].jointId, true ); float scale = human->scale * human->bones[i].frictionScale; b2RevoluteJoint_SetMaxMotorTorque( human->bones[i].jointId, scale * torque ); } } } void Human_SetJointSpringHertz( Human* human, float hertz ) { assert( human->isSpawned == true ); if ( hertz == 0.0f ) { for ( int i = 1; i < bone_count; ++i ) { b2RevoluteJoint_EnableSpring( human->bones[i].jointId, false ); } } else { for ( int i = 1; i < bone_count; ++i ) { b2RevoluteJoint_EnableSpring( human->bones[i].jointId, true ); b2RevoluteJoint_SetSpringHertz( human->bones[i].jointId, hertz ); } } } void Human_SetJointDampingRatio( Human* human, float dampingRatio ) { assert( human->isSpawned == true ); for ( int i = 1; i < bone_count; ++i ) { b2RevoluteJoint_SetSpringDampingRatio( human->bones[i].jointId, dampingRatio ); } } void Human_EnableSensorEvents( Human* human, bool enable ) { assert( human->isSpawned == true ); b2BodyId bodyId = human->bones[bone_torso].bodyId; b2ShapeId shapeId; int count = b2Body_GetShapes( bodyId, &shapeId, 1 ); if ( count == 1 ) { b2Shape_EnableSensorEvents( shapeId, enable ); } } void Human_SetScale( Human* human, float scale ) { assert( human->isSpawned == true ); assert( 0.01f < scale && scale < 100.0f ); assert( 0.0f < human->scale ); float ratio = scale / human->scale; // Torque scales by pow(length, 4) due to mass change and length change. However, gravity is also a factor // so I'm using pow(length, 3) float originalRatio = scale / human->originalScale; float frictionTorque = ( originalRatio * originalRatio * originalRatio ) * human->frictionTorque; b2Vec2 origin = b2Body_GetPosition( human->bones[0].bodyId ); for ( int boneIndex = 0; boneIndex < bone_count; ++boneIndex ) { Bone* bone = human->bones + boneIndex; if ( boneIndex > 0 ) { b2Transform transform = b2Body_GetTransform( bone->bodyId ); transform.p = b2MulAdd( origin, ratio, b2Sub( transform.p, origin ) ); b2Body_SetTransform( bone->bodyId, transform.p, transform.q ); b2Transform localFrameA = b2Joint_GetLocalFrameA( bone->jointId ); b2Transform localFrameB = b2Joint_GetLocalFrameB( bone->jointId ); localFrameA.p = b2MulSV( ratio, localFrameA.p ); localFrameB.p = b2MulSV( ratio, localFrameB.p ); b2Joint_SetLocalFrameA( bone->jointId, localFrameA ); b2Joint_SetLocalFrameB( bone->jointId, localFrameB ); b2JointType type = b2Joint_GetType( bone->jointId ); if ( type == b2_revoluteJoint ) { b2RevoluteJoint_SetMaxMotorTorque( bone->jointId, bone->frictionScale * frictionTorque ); } } b2ShapeId shapeIds[2]; int shapeCount = b2Body_GetShapes( bone->bodyId, shapeIds, 2 ); for ( int shapeIndex = 0; shapeIndex < shapeCount; ++shapeIndex ) { b2ShapeType type = b2Shape_GetType( shapeIds[shapeIndex] ); if ( type == b2_capsuleShape ) { b2Capsule capsule = b2Shape_GetCapsule( shapeIds[shapeIndex] ); capsule.center1 = b2MulSV( ratio, capsule.center1 ); capsule.center2 = b2MulSV( ratio, capsule.center2 ); capsule.radius *= ratio; b2Shape_SetCapsule( shapeIds[shapeIndex], &capsule ); } else if ( type == b2_polygonShape ) { b2Polygon polygon = b2Shape_GetPolygon( shapeIds[shapeIndex] ); for ( int pointIndex = 0; pointIndex < polygon.count; ++pointIndex ) { polygon.vertices[pointIndex] = b2MulSV( ratio, polygon.vertices[pointIndex] ); } polygon.centroid = b2MulSV( ratio, polygon.centroid ); polygon.radius *= ratio; b2Shape_SetPolygon( shapeIds[shapeIndex], &polygon ); } } b2Body_ApplyMassFromShapes( bone->bodyId ); } human->scale = scale; } ================================================ FILE: shared/human.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "box2d/types.h" typedef enum BoneId { bone_hip = 0, bone_torso = 1, bone_head = 2, bone_upperLeftLeg = 3, bone_lowerLeftLeg = 4, bone_upperRightLeg = 5, bone_lowerRightLeg = 6, bone_upperLeftArm = 7, bone_lowerLeftArm = 8, bone_upperRightArm = 9, bone_lowerRightArm = 10, bone_count = 11, } BoneId; typedef struct Bone { b2BodyId bodyId; b2JointId jointId; float frictionScale; float maxTorque; int parentIndex; } Bone; typedef struct Human { Bone bones[bone_count]; float frictionTorque; float originalScale; float scale; bool isSpawned; } Human; #ifdef __cplusplus extern "C" { #endif void CreateHuman( Human* human, b2WorldId worldId, b2Vec2 position, float scale, float frictionTorque, float hertz, float dampingRatio, int groupIndex, void* userData, bool colorize ); void DestroyHuman( Human* human ); void Human_SetVelocity( Human* human, b2Vec2 velocity ); void Human_ApplyRandomAngularImpulse( Human* human, float magnitude ); void Human_SetJointFrictionTorque( Human* human, float torque ); void Human_SetJointSpringHertz( Human* human, float hertz ); void Human_SetJointDampingRatio( Human* human, float dampingRatio ); void Human_EnableSensorEvents( Human* human, bool enable ); void Human_SetScale( Human* human, float scale ); #ifdef __cplusplus } #endif ================================================ FILE: shared/random.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "random.h" uint32_t g_randomSeed = RAND_SEED; b2Polygon RandomPolygon( float extent ) { b2Vec2 points[B2_MAX_POLYGON_VERTICES]; int count = 3 + RandomInt() % 6; for ( int i = 0; i < count; ++i ) { points[i] = RandomVec2( -extent, extent ); } b2Hull hull = b2ComputeHull( points, count ); if ( hull.count > 0 ) { return b2MakePolygon( &hull, 0.0f ); } return b2MakeSquare( extent ); } ================================================ FILE: shared/random.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "box2d/collision.h" #include "box2d/math_functions.h" #define RAND_LIMIT 32767 #define RAND_SEED 12345 // Global seed for simple random number generator. #ifdef __cplusplus extern "C" { #endif extern uint32_t g_randomSeed; b2Polygon RandomPolygon( float extent ); #ifdef __cplusplus } #endif // Simple random number generator. Using this instead of rand() for cross-platform determinism. B2_INLINE int RandomInt() { // XorShift32 algorithm uint32_t x = g_randomSeed; x ^= x << 13; x ^= x >> 17; x ^= x << 5; g_randomSeed = x; // Map the 32-bit value to the range 0 to RAND_LIMIT return (int)( x % ( RAND_LIMIT + 1 ) ); } // Random integer in range [lo, hi] B2_INLINE int RandomIntRange( int lo, int hi ) { return lo + RandomInt() % ( hi - lo + 1 ); } // Random number in range [-1,1] B2_INLINE float RandomFloat() { float r = (float)( RandomInt() & ( RAND_LIMIT ) ); r /= RAND_LIMIT; r = 2.0f * r - 1.0f; return r; } // Random floating point number in range [lo, hi] B2_INLINE float RandomFloatRange( float lo, float hi ) { float r = (float)( RandomInt() & ( RAND_LIMIT ) ); r /= RAND_LIMIT; r = ( hi - lo ) * r + lo; return r; } // Random vector with coordinates in range [lo, hi] B2_INLINE b2Vec2 RandomVec2( float lo, float hi ) { b2Vec2 v; v.x = RandomFloatRange( lo, hi ); v.y = RandomFloatRange( lo, hi ); return v; } // Random rotation with angle in range [-pi, pi] B2_INLINE b2Rot RandomRot( void ) { float angle = RandomFloatRange( -B2_PI, B2_PI ); return b2MakeRot( angle ); } ================================================ FILE: src/CMakeLists.txt ================================================ include(GNUInstallDirs) set(BOX2D_SOURCE_FILES aabb.c aabb.h arena_allocator.c arena_allocator.h array.c array.h atomic.h bitset.c bitset.h body.c body.h broad_phase.c broad_phase.h constants.h constraint_graph.c constraint_graph.h contact.c contact.h contact_solver.c contact_solver.h core.c core.h ctz.h distance.c distance_joint.c dynamic_tree.c geometry.c hull.c id_pool.c id_pool.h island.c island.h joint.c joint.h manifold.c math_functions.c motor_joint.c mover.c physics_world.c physics_world.h prismatic_joint.c revolute_joint.c sensor.c sensor.h shape.c shape.h solver.c solver.h solver_set.c solver_set.h table.c table.h timer.c types.c weld_joint.c wheel_joint.c ) set(BOX2D_API_FILES ../include/box2d/base.h ../include/box2d/box2d.h ../include/box2d/collision.h ../include/box2d/id.h ../include/box2d/math_functions.h ../include/box2d/types.h ) # Hide internal functions # https://gcc.gnu.org/wiki/Visibility set(CMAKE_C_VISIBILITY_PRESET hidden) set(CMAKE_VISIBILITY_INLINES_HIDDEN 1) add_library(box2d ${BOX2D_SOURCE_FILES} ${BOX2D_API_FILES}) target_include_directories(box2d PUBLIC $ $ $ PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ) set(CMAKE_DEBUG_POSTFIX "d") # Box2D uses C17 for _Static_assert and anonymous unions set_target_properties(box2d PROPERTIES C_STANDARD 17 C_STANDARD_REQUIRED YES C_EXTENSIONS YES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR} DEBUG_POSTFIX ${CMAKE_DEBUG_POSTFIX} ) if (BOX2D_COMPILE_WARNING_AS_ERROR) set_target_properties(box2d PROPERTIES COMPILE_WARNING_AS_ERROR ON) endif() if (BOX2D_PROFILE) target_compile_definitions(box2d PRIVATE BOX2D_PROFILE) FetchContent_Declare( tracy GIT_REPOSITORY https://github.com/wolfpld/tracy.git GIT_TAG v0.11.1 GIT_SHALLOW TRUE GIT_PROGRESS TRUE ) FetchContent_MakeAvailable(tracy) target_link_libraries(box2d PUBLIC TracyClient) endif() if (BOX2D_VALIDATE) message(STATUS "Box2D validation ON") target_compile_definitions(box2d PRIVATE BOX2D_VALIDATE) endif() if (BOX2D_DISABLE_SIMD) message(STATUS "Box2D SIMD disabled") target_compile_definitions(box2d PRIVATE BOX2D_DISABLE_SIMD) endif() if (MSVC) message(STATUS "Box2D on MSVC") if (BUILD_SHARED_LIBS) # this is needed by DLL users to import Box2D symbols target_compile_definitions(box2d INTERFACE BOX2D_DLL) endif() # Visual Studio won't load the natvis unless it is in the project target_sources(box2d PRIVATE box2d.natvis) # Enable asserts in release with debug info target_compile_definitions(box2d PUBLIC "$<$:B2_ENABLE_ASSERT>") # Warnings # 4710 - warn about inline functions that are not inlined target_compile_options(box2d PRIVATE /Wall /wd4820 /wd5045 /wd4061 /wd4711 /wd4710) if (BOX2D_AVX2) message(STATUS "Box2D using AVX2") target_compile_definitions(box2d PRIVATE BOX2D_AVX2) target_compile_options(box2d PRIVATE /arch:AVX2) endif() if (${CMAKE_CXX_COMPILER_ID} STREQUAL "Clang") target_compile_options(box2d PRIVATE -Wmissing-prototypes) endif() elseif (MINGW) message(STATUS "Box2D on MinGW") if (BOX2D_AVX2) message(STATUS "Box2D using AVX2") target_compile_definitions(box2d PRIVATE BOX2D_AVX2) target_compile_options(box2d PRIVATE -mavx2) else() endif() elseif (APPLE) message(STATUS "Box2D on Apple") target_compile_options(box2d PRIVATE -Wmissing-prototypes -Wall -Wextra -pedantic) elseif (EMSCRIPTEN) message(STATUS "Box2D on Emscripten") if (NOT BOX2D_DISABLE_SIMD) target_compile_options(box2d PRIVATE -msimd128 -msse2) endif() elseif (UNIX) message(STATUS "Box2D using Unix") target_compile_options(box2d PRIVATE -Wmissing-prototypes -Wall -Wextra -pedantic -Wno-unused-value) if ("${CMAKE_HOST_SYSTEM_PROCESSOR}" STREQUAL "aarch64") # raspberry pi # -mfpu=neon # target_compile_options(box2d PRIVATE) else() if (BOX2D_AVX2) message(STATUS "Box2D using AVX2") target_compile_definitions(box2d PRIVATE BOX2D_AVX2) target_compile_options(box2d PRIVATE -mavx2) else() endif() endif() endif() source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}" PREFIX "src" FILES ${BOX2D_SOURCE_FILES}) source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}/../include" PREFIX "include" FILES ${BOX2D_API_FILES}) add_library(box2d::box2d ALIAS box2d) install( TARGETS box2d EXPORT box2dConfig LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} ) install( EXPORT box2dConfig NAMESPACE box2d:: DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/box2d" ) install( FILES ${BOX2D_API_FILES} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/box2d ) include(CMakePackageConfigHelpers) write_basic_package_version_file( "${CMAKE_CURRENT_BINARY_DIR}/box2dConfigVersion.cmake" VERSION ${BOX2D_VERSION} COMPATIBILITY SameMajorVersion ) install( FILES "${CMAKE_CURRENT_BINARY_DIR}/box2dConfigVersion.cmake" DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/box2d" ) ================================================ FILE: src/aabb.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "aabb.h" #include "box2d/math_functions.h" #include bool b2IsValidAABB( b2AABB a ) { b2Vec2 d = b2Sub( a.upperBound, a.lowerBound ); bool valid = d.x >= 0.0f && d.y >= 0.0f; valid = valid && b2IsValidVec2( a.lowerBound ) && b2IsValidVec2( a.upperBound ); return valid; } // From Real-time Collision Detection, p179. b2CastOutput b2AABB_RayCast( b2AABB a, b2Vec2 p1, b2Vec2 p2 ) { // Radius not handled b2CastOutput output = { 0 }; float tmin = -FLT_MAX; float tmax = FLT_MAX; b2Vec2 p = p1; b2Vec2 d = b2Sub( p2, p1 ); b2Vec2 absD = b2Abs( d ); b2Vec2 normal = b2Vec2_zero; // x-coordinate if ( absD.x < FLT_EPSILON ) { // parallel if ( p.x < a.lowerBound.x || a.upperBound.x < p.x ) { return output; } } else { float inv_d = 1.0f / d.x; float t1 = ( a.lowerBound.x - p.x ) * inv_d; float t2 = ( a.upperBound.x - p.x ) * inv_d; // Sign of the normal vector. float s = -1.0f; if ( t1 > t2 ) { float tmp = t1; t1 = t2; t2 = tmp; s = 1.0f; } // Push the min up if ( t1 > tmin ) { normal.y = 0.0f; normal.x = s; tmin = t1; } // Pull the max down tmax = b2MinFloat( tmax, t2 ); if ( tmin > tmax ) { return output; } } // y-coordinate if ( absD.y < FLT_EPSILON ) { // parallel if ( p.y < a.lowerBound.y || a.upperBound.y < p.y ) { return output; } } else { float inv_d = 1.0f / d.y; float t1 = ( a.lowerBound.y - p.y ) * inv_d; float t2 = ( a.upperBound.y - p.y ) * inv_d; // Sign of the normal vector. float s = -1.0f; if ( t1 > t2 ) { float tmp = t1; t1 = t2; t2 = tmp; s = 1.0f; } // Push the min up if ( t1 > tmin ) { normal.x = 0.0f; normal.y = s; tmin = t1; } // Pull the max down tmax = b2MinFloat( tmax, t2 ); if ( tmin > tmax ) { return output; } } // Does the ray start inside the box? if ( tmin < 0.0f ) { return output; } // Does the ray intersect beyond the segment length? if ( 1.0f < tmin ) { return output; } // Intersection. output.fraction = tmin; output.normal = normal; output.point = b2Lerp( p1, p2, tmin ); output.hit = true; return output; } ================================================ FILE: src/aabb.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "box2d/types.h" // Ray cast an AABB b2CastOutput b2AABB_RayCast( b2AABB a, b2Vec2 p1, b2Vec2 p2 ); // Get surface area of an AABB (the perimeter length) static inline float b2Perimeter( b2AABB a ) { float wx = a.upperBound.x - a.lowerBound.x; float wy = a.upperBound.y - a.lowerBound.y; return 2.0f * ( wx + wy ); } /// Enlarge a to contain b /// @return true if the AABB grew static inline bool b2EnlargeAABB( b2AABB* a, b2AABB b ) { bool changed = false; if ( b.lowerBound.x < a->lowerBound.x ) { a->lowerBound.x = b.lowerBound.x; changed = true; } if ( b.lowerBound.y < a->lowerBound.y ) { a->lowerBound.y = b.lowerBound.y; changed = true; } if ( a->upperBound.x < b.upperBound.x ) { a->upperBound.x = b.upperBound.x; changed = true; } if ( a->upperBound.y < b.upperBound.y ) { a->upperBound.y = b.upperBound.y; changed = true; } return changed; } ================================================ FILE: src/arena_allocator.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "arena_allocator.h" #include "array.h" #include "core.h" #include #include B2_ARRAY_SOURCE( b2ArenaEntry, b2ArenaEntry ) b2ArenaAllocator b2CreateArenaAllocator( int capacity ) { B2_ASSERT( capacity >= 0 ); b2ArenaAllocator allocator = { 0 }; allocator.capacity = capacity; allocator.data = b2Alloc( capacity ); allocator.allocation = 0; allocator.maxAllocation = 0; allocator.index = 0; allocator.entries = b2ArenaEntryArray_Create( 32 ); return allocator; } void b2DestroyArenaAllocator( b2ArenaAllocator* allocator ) { b2ArenaEntryArray_Destroy( &allocator->entries ); b2Free( allocator->data, allocator->capacity ); } void* b2AllocateArenaItem( b2ArenaAllocator* alloc, int size, const char* name ) { // ensure allocation is 32 byte aligned to support 256-bit SIMD int size32 = ( ( size - 1 ) | 0x1F ) + 1; b2ArenaEntry entry; entry.size = size32; entry.name = name; if ( alloc->index + size32 > alloc->capacity ) { // fall back to the heap (undesirable) entry.data = b2Alloc( size32 ); entry.usedMalloc = true; B2_ASSERT( ( (uintptr_t)entry.data & 0x1F ) == 0 ); } else { entry.data = alloc->data + alloc->index; entry.usedMalloc = false; alloc->index += size32; B2_ASSERT( ( (uintptr_t)entry.data & 0x1F ) == 0 ); } alloc->allocation += size32; if ( alloc->allocation > alloc->maxAllocation ) { alloc->maxAllocation = alloc->allocation; } b2ArenaEntryArray_Push( &alloc->entries, entry ); return entry.data; } void b2FreeArenaItem( b2ArenaAllocator* alloc, void* mem ) { int entryCount = alloc->entries.count; B2_ASSERT( entryCount > 0 ); b2ArenaEntry* entry = alloc->entries.data + ( entryCount - 1 ); B2_ASSERT( mem == entry->data ); if ( entry->usedMalloc ) { b2Free( mem, entry->size ); } else { alloc->index -= entry->size; } alloc->allocation -= entry->size; b2ArenaEntryArray_Pop( &alloc->entries ); } void b2GrowArena( b2ArenaAllocator* alloc ) { // Stack must not be in use B2_ASSERT( alloc->allocation == 0 ); if ( alloc->maxAllocation > alloc->capacity ) { b2Free( alloc->data, alloc->capacity ); alloc->capacity = alloc->maxAllocation + alloc->maxAllocation / 2; alloc->data = b2Alloc( alloc->capacity ); } } int b2GetArenaCapacity( b2ArenaAllocator* alloc ) { return alloc->capacity; } int b2GetArenaAllocation( b2ArenaAllocator* alloc ) { return alloc->allocation; } int b2GetMaxArenaAllocation( b2ArenaAllocator* alloc ) { return alloc->maxAllocation; } ================================================ FILE: src/arena_allocator.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "array.h" #include B2_ARRAY_DECLARE( b2ArenaEntry, b2ArenaEntry ); typedef struct b2ArenaEntry { char* data; const char* name; int size; bool usedMalloc; } b2ArenaEntry; // This is a stack-like arena allocator used for fast per step allocations. // You must nest allocate/free pairs. The code will B2_ASSERT // if you try to interleave multiple allocate/free pairs. // This allocator uses the heap if space is insufficient. // I could remove the need to free entries individually. typedef struct b2ArenaAllocator { char* data; int capacity; int index; int allocation; int maxAllocation; b2ArenaEntryArray entries; } b2ArenaAllocator; b2ArenaAllocator b2CreateArenaAllocator( int capacity ); void b2DestroyArenaAllocator( b2ArenaAllocator* allocator ); void* b2AllocateArenaItem( b2ArenaAllocator* alloc, int size, const char* name ); void b2FreeArenaItem( b2ArenaAllocator* alloc, void* mem ); // Grow the arena based on usage void b2GrowArena( b2ArenaAllocator* alloc ); int b2GetArenaCapacity( b2ArenaAllocator* alloc ); int b2GetArenaAllocation( b2ArenaAllocator* alloc ); int b2GetMaxArenaAllocation( b2ArenaAllocator* alloc ); B2_ARRAY_INLINE( b2ArenaEntry, b2ArenaEntry ) ================================================ FILE: src/array.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "array.h" #include B2_ARRAY_SOURCE( int, b2Int ) ================================================ FILE: src/array.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "core.h" // Macro generated functions for dynamic arrays // Pros // - type safe // - array data debuggable (visible count and capacity) // - bounds checking // - forward declaration // - simple implementation // - generates functions (like C++ templates) // - functions have https://en.wikipedia.org/wiki/Sequence_point // - avoids stretchy buffer dropped pointer update bugs // Cons // - cannot debug // - breaks code navigation // The fragmentation problem with factor 2: // When you double capacity, the new allocation is larger than the sum of all previous allocations: // // 1st allocation: 8 bytes // 2nd allocation: 16 bytes // 3rd allocation: 32 bytes (larger than 8 + 16 = 24) // // This means the memory freed from previous allocations can never be reused for future expansions // of the same array. The allocator must always find fresh memory. // todo_erin consider code-gen: https://github.com/IbrahimHindawi/haikal // Array declaration that doesn't need the type T to be defined #define B2_ARRAY_DECLARE( T, PREFIX ) \ typedef struct \ { \ struct T* data; \ int count; \ int capacity; \ } PREFIX##Array; \ PREFIX##Array PREFIX##Array_Create( int capacity ); \ void PREFIX##Array_Reserve( PREFIX##Array* a, int newCapacity ); \ void PREFIX##Array_Destroy( PREFIX##Array* a ) #define B2_DECLARE_ARRAY_NATIVE( T, PREFIX ) \ typedef struct \ { \ T* data; \ int count; \ int capacity; \ } PREFIX##Array; \ /* Create array with initial capacity. Zero initialization is also supported */ \ PREFIX##Array PREFIX##Array_Create( int capacity ); \ void PREFIX##Array_Reserve( PREFIX##Array* a, int newCapacity ); \ void PREFIX##Array_Destroy( PREFIX##Array* a ) // Inline array functions that need the type T to be defined #define B2_ARRAY_INLINE( T, PREFIX ) \ /* Resize */ \ static inline void PREFIX##Array_Resize( PREFIX##Array* a, int count ) \ { \ PREFIX##Array_Reserve( a, count ); \ a->count = count; \ } \ /* Get */ \ static inline T* PREFIX##Array_Get( PREFIX##Array* a, int index ) \ { \ B2_ASSERT( 0 <= index && index < a->count ); \ return a->data + index; \ } \ /* Add */ \ static inline T* PREFIX##Array_Add( PREFIX##Array* a ) \ { \ if ( a->count == a->capacity ) \ { \ int newCapacity = a->capacity < 2 ? 2 : a->capacity + ( a->capacity >> 1 ); \ PREFIX##Array_Reserve( a, newCapacity ); \ } \ a->count += 1; \ return a->data + ( a->count - 1 ); \ } \ /* Push */ \ static inline void PREFIX##Array_Push( PREFIX##Array* a, T value ) \ { \ if ( a->count == a->capacity ) \ { \ int newCapacity = a->capacity < 2 ? 2 : a->capacity + ( a->capacity >> 1 ); \ PREFIX##Array_Reserve( a, newCapacity ); \ } \ a->data[a->count] = value; \ a->count += 1; \ } \ /* Set */ \ static inline void PREFIX##Array_Set( PREFIX##Array* a, int index, T value ) \ { \ B2_ASSERT( 0 <= index && index < a->count ); \ a->data[index] = value; \ } \ /* RemoveSwap */ \ static inline int PREFIX##Array_RemoveSwap( PREFIX##Array* a, int index ) \ { \ B2_ASSERT( 0 <= index && index < a->count ); \ int movedIndex = B2_NULL_INDEX; \ if ( index != a->count - 1 ) \ { \ movedIndex = a->count - 1; \ a->data[index] = a->data[movedIndex]; \ } \ a->count -= 1; \ return movedIndex; \ } \ /* Pop */ \ static inline T PREFIX##Array_Pop( PREFIX##Array* a ) \ { \ B2_ASSERT( a->count > 0 ); \ T value = a->data[a->count - 1]; \ a->count -= 1; \ return value; \ } \ /* Clear */ \ static inline void PREFIX##Array_Clear( PREFIX##Array* a ) \ { \ a->count = 0; \ } \ /* ByteCount */ \ static inline int PREFIX##Array_ByteCount( PREFIX##Array* a ) \ { \ return (int)( a->capacity * sizeof( T ) ); \ } // Array implementations to be instantiated in a source file where the type T is known #define B2_ARRAY_SOURCE( T, PREFIX ) \ /* Create */ \ PREFIX##Array PREFIX##Array_Create( int capacity ) \ { \ PREFIX##Array a = { 0 }; \ if ( capacity > 0 ) \ { \ a.data = b2Alloc( capacity * sizeof( T ) ); \ a.capacity = capacity; \ } \ return a; \ } \ /* Reserve */ \ void PREFIX##Array_Reserve( PREFIX##Array* a, int newCapacity ) \ { \ if ( newCapacity <= a->capacity ) \ { \ return; \ } \ a->data = b2GrowAlloc( a->data, a->capacity * sizeof( T ), newCapacity * sizeof( T ) ); \ a->capacity = newCapacity; \ } \ /* Destroy */ \ void PREFIX##Array_Destroy( PREFIX##Array* a ) \ { \ b2Free( a->data, a->capacity * sizeof( T ) ); \ a->data = NULL; \ a->count = 0; \ a->capacity = 0; \ } B2_DECLARE_ARRAY_NATIVE( int, b2Int ); B2_ARRAY_INLINE( int, b2Int ) // Declare all the arrays B2_ARRAY_DECLARE( b2Body, b2Body ); B2_ARRAY_DECLARE( b2BodyMoveEvent, b2BodyMoveEvent ); B2_ARRAY_DECLARE( b2BodySim, b2BodySim ); B2_ARRAY_DECLARE( b2BodyState, b2BodyState ); B2_ARRAY_DECLARE( b2ChainShape, b2ChainShape ); B2_ARRAY_DECLARE( b2Contact, b2Contact ); B2_ARRAY_DECLARE( b2ContactBeginTouchEvent, b2ContactBeginTouchEvent ); B2_ARRAY_DECLARE( b2ContactEndTouchEvent, b2ContactEndTouchEvent ); B2_ARRAY_DECLARE( b2ContactHitEvent, b2ContactHitEvent ); B2_ARRAY_DECLARE( b2ContactSim, b2ContactSim ); B2_ARRAY_DECLARE( b2Island, b2Island ); B2_ARRAY_DECLARE( b2IslandSim, b2IslandSim ); B2_ARRAY_DECLARE( b2Joint, b2Joint ); B2_ARRAY_DECLARE( b2JointEvent, b2JointEvent ); B2_ARRAY_DECLARE( b2JointSim, b2JointSim ); B2_ARRAY_DECLARE( b2Sensor, b2Sensor ); B2_ARRAY_DECLARE( b2SensorBeginTouchEvent, b2SensorBeginTouchEvent ); B2_ARRAY_DECLARE( b2SensorEndTouchEvent, b2SensorEndTouchEvent ); B2_ARRAY_DECLARE( b2SensorTaskContext, b2SensorTaskContext ); B2_ARRAY_DECLARE( b2Shape, b2Shape ); B2_ARRAY_DECLARE( b2Visitor, b2Visitor ); B2_ARRAY_DECLARE( b2SolverSet, b2SolverSet ); B2_ARRAY_DECLARE( b2TaskContext, b2TaskContext ); B2_ARRAY_DECLARE( b2SensorHit, b2SensorHit ); ================================================ FILE: src/atomic.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "core.h" #include #include #if defined( _MSC_VER ) #include #endif static inline void b2AtomicStoreInt( b2AtomicInt* a, int value ) { #if defined( _MSC_VER ) (void)_InterlockedExchange( (long*)&a->value, value ); #elif defined( __GNUC__ ) || defined( __clang__ ) __atomic_store_n( &a->value, value, __ATOMIC_SEQ_CST ); #else #error "Unsupported platform" #endif } static inline int b2AtomicLoadInt( b2AtomicInt* a ) { #if defined( _MSC_VER ) return _InterlockedOr( (long*)&a->value, 0 ); #elif defined( __GNUC__ ) || defined( __clang__ ) return __atomic_load_n( &a->value, __ATOMIC_SEQ_CST ); #else #error "Unsupported platform" #endif } static inline int b2AtomicFetchAddInt( b2AtomicInt* a, int increment ) { #if defined( _MSC_VER ) return _InterlockedExchangeAdd( (long*)&a->value, (long)increment ); #elif defined( __GNUC__ ) || defined( __clang__ ) return __atomic_fetch_add( &a->value, increment, __ATOMIC_SEQ_CST ); #else #error "Unsupported platform" #endif } static inline bool b2AtomicCompareExchangeInt( b2AtomicInt* a, int expected, int desired ) { #if defined( _MSC_VER ) return _InterlockedCompareExchange( (long*)&a->value, (long)desired, (long)expected ) == expected; #elif defined( __GNUC__ ) || defined( __clang__ ) // The value written to expected is ignored return __atomic_compare_exchange_n( &a->value, &expected, desired, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST ); #else #error "Unsupported platform" #endif } static inline void b2AtomicStoreU32( b2AtomicU32* a, uint32_t value ) { #if defined( _MSC_VER ) (void)_InterlockedExchange( (long*)&a->value, value ); #elif defined( __GNUC__ ) || defined( __clang__ ) __atomic_store_n( &a->value, value, __ATOMIC_SEQ_CST ); #else #error "Unsupported platform" #endif } static inline uint32_t b2AtomicLoadU32( b2AtomicU32* a ) { #if defined( _MSC_VER ) return (uint32_t)_InterlockedOr( (long*)&a->value, 0 ); #elif defined( __GNUC__ ) || defined( __clang__ ) return __atomic_load_n( &a->value, __ATOMIC_SEQ_CST ); #else #error "Unsupported platform" #endif } ================================================ FILE: src/bitset.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "bitset.h" #include b2BitSet b2CreateBitSet( uint32_t bitCapacity ) { b2BitSet bitSet = { 0 }; bitSet.blockCapacity = ( bitCapacity + sizeof( uint64_t ) * 8 - 1 ) / ( sizeof( uint64_t ) * 8 ); bitSet.blockCount = 0; bitSet.bits = b2Alloc( bitSet.blockCapacity * sizeof( uint64_t ) ); memset( bitSet.bits, 0, bitSet.blockCapacity * sizeof( uint64_t ) ); return bitSet; } void b2DestroyBitSet( b2BitSet* bitSet ) { b2Free( bitSet->bits, bitSet->blockCapacity * sizeof( uint64_t ) ); bitSet->blockCapacity = 0; bitSet->blockCount = 0; bitSet->bits = NULL; } void b2SetBitCountAndClear( b2BitSet* bitSet, uint32_t bitCount ) { uint32_t blockCount = ( bitCount + sizeof( uint64_t ) * 8 - 1 ) / ( sizeof( uint64_t ) * 8 ); if ( bitSet->blockCapacity < blockCount ) { b2DestroyBitSet( bitSet ); uint32_t newBitCapacity = bitCount + ( bitCount >> 1 ); *bitSet = b2CreateBitSet( newBitCapacity ); } bitSet->blockCount = blockCount; memset( bitSet->bits, 0, bitSet->blockCount * sizeof( uint64_t ) ); } void b2GrowBitSet( b2BitSet* bitSet, uint32_t blockCount ) { B2_ASSERT( blockCount > bitSet->blockCount ); if ( blockCount > bitSet->blockCapacity ) { uint32_t oldCapacity = bitSet->blockCapacity; bitSet->blockCapacity = blockCount + blockCount / 2; uint64_t* newBits = b2Alloc( bitSet->blockCapacity * sizeof( uint64_t ) ); memset( newBits, 0, bitSet->blockCapacity * sizeof( uint64_t ) ); B2_ASSERT( bitSet->bits != NULL ); memcpy( newBits, bitSet->bits, oldCapacity * sizeof( uint64_t ) ); b2Free( bitSet->bits, oldCapacity * sizeof( uint64_t ) ); bitSet->bits = newBits; } bitSet->blockCount = blockCount; } void b2InPlaceUnion( b2BitSet* B2_RESTRICT setA, const b2BitSet* B2_RESTRICT setB ) { B2_ASSERT( setA->blockCount == setB->blockCount ); uint32_t blockCount = setA->blockCount; for ( uint32_t i = 0; i < blockCount; ++i ) { setA->bits[i] |= setB->bits[i]; } } ================================================ FILE: src/bitset.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "core.h" #include #include // Bit set provides fast operations on large arrays of bits. typedef struct b2BitSet { uint64_t* bits; uint32_t blockCapacity; uint32_t blockCount; } b2BitSet; b2BitSet b2CreateBitSet( uint32_t bitCapacity ); void b2DestroyBitSet( b2BitSet* bitSet ); void b2SetBitCountAndClear( b2BitSet* bitSet, uint32_t bitCount ); void b2InPlaceUnion( b2BitSet* setA, const b2BitSet* setB ); void b2GrowBitSet( b2BitSet* bitSet, uint32_t blockCount ); int b2CountSetBits( b2BitSet* bitSet ); static inline void b2SetBit( b2BitSet* bitSet, uint32_t bitIndex ) { uint32_t blockIndex = bitIndex / 64; B2_ASSERT( blockIndex < bitSet->blockCount ); bitSet->bits[blockIndex] |= ( (uint64_t)1 << bitIndex % 64 ); } static inline void b2SetBitGrow( b2BitSet* bitSet, uint32_t bitIndex ) { uint32_t blockIndex = bitIndex / 64; if ( blockIndex >= bitSet->blockCount ) { b2GrowBitSet( bitSet, blockIndex + 1 ); } bitSet->bits[blockIndex] |= ( (uint64_t)1 << bitIndex % 64 ); } static inline void b2ClearBit( b2BitSet* bitSet, uint32_t bitIndex ) { uint32_t blockIndex = bitIndex / 64; if ( blockIndex >= bitSet->blockCount ) { return; } bitSet->bits[blockIndex] &= ~( (uint64_t)1 << bitIndex % 64 ); } static inline bool b2GetBit( const b2BitSet* bitSet, uint32_t bitIndex ) { uint32_t blockIndex = bitIndex / 64; if ( blockIndex >= bitSet->blockCount ) { return false; } return ( bitSet->bits[blockIndex] & ( (uint64_t)1 << bitIndex % 64 ) ) != 0; } static inline int b2GetBitSetBytes( b2BitSet* bitSet ) { return bitSet->blockCapacity * sizeof( uint64_t ); } ================================================ FILE: src/body.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "body.h" #include "aabb.h" #include "array.h" #include "contact.h" #include "core.h" #include "id_pool.h" #include "island.h" #include "joint.h" #include "physics_world.h" #include "sensor.h" #include "shape.h" #include "solver_set.h" #include "box2d/box2d.h" #include "box2d/id.h" #include // Implement functions for b2BodyArray B2_ARRAY_SOURCE( b2Body, b2Body ) B2_ARRAY_SOURCE( b2BodySim, b2BodySim ) B2_ARRAY_SOURCE( b2BodyState, b2BodyState ) static void b2LimitVelocity( b2BodyState* state, float maxLinearSpeed ) { float v2 = b2LengthSquared( state->linearVelocity ); if ( v2 > maxLinearSpeed * maxLinearSpeed ) { state->linearVelocity = b2MulSV( maxLinearSpeed / sqrtf( v2 ), state->linearVelocity ); } } // Get a validated body from a world using an id. b2Body* b2GetBodyFullId( b2World* world, b2BodyId bodyId ) { B2_ASSERT( b2Body_IsValid( bodyId ) ); // id index starts at one so that zero can represent null return b2BodyArray_Get( &world->bodies, bodyId.index1 - 1 ); } b2Transform b2GetBodyTransformQuick( b2World* world, b2Body* body ) { b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, body->setIndex ); b2BodySim* bodySim = b2BodySimArray_Get( &set->bodySims, body->localIndex ); return bodySim->transform; } b2Transform b2GetBodyTransform( b2World* world, int bodyId ) { b2Body* body = b2BodyArray_Get( &world->bodies, bodyId ); return b2GetBodyTransformQuick( world, body ); } // Create a b2BodyId from a raw id. b2BodyId b2MakeBodyId( b2World* world, int bodyId ) { b2Body* body = b2BodyArray_Get( &world->bodies, bodyId ); return (b2BodyId){ bodyId + 1, world->worldId, body->generation }; } b2BodySim* b2GetBodySim( b2World* world, b2Body* body ) { b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, body->setIndex ); b2BodySim* bodySim = b2BodySimArray_Get( &set->bodySims, body->localIndex ); return bodySim; } b2BodyState* b2GetBodyState( b2World* world, b2Body* body ) { if ( body->setIndex == b2_awakeSet ) { b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); return b2BodyStateArray_Get( &set->bodyStates, body->localIndex ); } return NULL; } static void b2CreateIslandForBody( b2World* world, int setIndex, b2Body* body ) { B2_ASSERT( body->islandId == B2_NULL_INDEX ); B2_ASSERT( body->islandPrev == B2_NULL_INDEX ); B2_ASSERT( body->islandNext == B2_NULL_INDEX ); B2_ASSERT( setIndex != b2_disabledSet ); b2Island* island = b2CreateIsland( world, setIndex ); body->islandId = island->islandId; island->headBody = body->id; island->tailBody = body->id; island->bodyCount = 1; } static void b2RemoveBodyFromIsland( b2World* world, b2Body* body ) { if ( body->islandId == B2_NULL_INDEX ) { B2_ASSERT( body->islandPrev == B2_NULL_INDEX ); B2_ASSERT( body->islandNext == B2_NULL_INDEX ); return; } int islandId = body->islandId; b2Island* island = b2IslandArray_Get( &world->islands, islandId ); // Fix the island's linked list of sims if ( body->islandPrev != B2_NULL_INDEX ) { b2Body* prevBody = b2BodyArray_Get( &world->bodies, body->islandPrev ); prevBody->islandNext = body->islandNext; } if ( body->islandNext != B2_NULL_INDEX ) { b2Body* nextBody = b2BodyArray_Get( &world->bodies, body->islandNext ); nextBody->islandPrev = body->islandPrev; } B2_ASSERT( island->bodyCount > 0 ); island->bodyCount -= 1; bool islandDestroyed = false; if ( island->headBody == body->id ) { island->headBody = body->islandNext; if ( island->headBody == B2_NULL_INDEX ) { // Destroy empty island B2_ASSERT( island->tailBody == body->id ); B2_ASSERT( island->bodyCount == 0 ); B2_ASSERT( island->contactCount == 0 ); B2_ASSERT( island->jointCount == 0 ); // Free the island b2DestroyIsland( world, island->islandId ); islandDestroyed = true; } } else if ( island->tailBody == body->id ) { island->tailBody = body->islandPrev; } if ( islandDestroyed == false ) { b2ValidateIsland( world, islandId ); } body->islandId = B2_NULL_INDEX; body->islandPrev = B2_NULL_INDEX; body->islandNext = B2_NULL_INDEX; } static void b2DestroyBodyContacts( b2World* world, b2Body* body, bool wakeBodies ) { // Destroy the attached contacts int edgeKey = body->headContactKey; while ( edgeKey != B2_NULL_INDEX ) { int contactId = edgeKey >> 1; int edgeIndex = edgeKey & 1; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); edgeKey = contact->edges[edgeIndex].nextKey; b2DestroyContact( world, contact, wakeBodies ); } b2ValidateSolverSets( world ); } b2BodyId b2CreateBody( b2WorldId worldId, const b2BodyDef* def ) { B2_CHECK_DEF( def ); B2_ASSERT( b2IsValidVec2( def->position ) ); B2_ASSERT( b2IsValidRotation( def->rotation ) ); B2_ASSERT( b2IsValidVec2( def->linearVelocity ) ); B2_ASSERT( b2IsValidFloat( def->angularVelocity ) ); B2_ASSERT( b2IsValidFloat( def->linearDamping ) && def->linearDamping >= 0.0f ); B2_ASSERT( b2IsValidFloat( def->angularDamping ) && def->angularDamping >= 0.0f ); B2_ASSERT( b2IsValidFloat( def->sleepThreshold ) && def->sleepThreshold >= 0.0f ); B2_ASSERT( b2IsValidFloat( def->gravityScale ) ); b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return b2_nullBodyId; } bool isAwake = ( def->isAwake || def->enableSleep == false ) && def->isEnabled; // determine the solver set int setId; if ( def->isEnabled == false ) { // any body type can be disabled setId = b2_disabledSet; } else if ( def->type == b2_staticBody ) { setId = b2_staticSet; } else if ( isAwake == true ) { setId = b2_awakeSet; } else { // new set for a sleeping body in its own island setId = b2AllocId( &world->solverSetIdPool ); if ( setId == world->solverSets.count ) { // Create a zero initialized solver set. All sub-arrays are also zero initialized. b2SolverSetArray_Push( &world->solverSets, (b2SolverSet){ 0 } ); } else { B2_ASSERT( world->solverSets.data[setId].setIndex == B2_NULL_INDEX ); } world->solverSets.data[setId].setIndex = setId; } B2_ASSERT( 0 <= setId && setId < world->solverSets.count ); int bodyId = b2AllocId( &world->bodyIdPool ); uint32_t lockFlags = 0; lockFlags |= def->motionLocks.linearX ? b2_lockLinearX : 0; lockFlags |= def->motionLocks.linearY ? b2_lockLinearY : 0; lockFlags |= def->motionLocks.angularZ ? b2_lockAngularZ : 0; b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, setId ); b2BodySim* bodySim = b2BodySimArray_Add( &set->bodySims ); *bodySim = (b2BodySim){ 0 }; bodySim->transform.p = def->position; bodySim->transform.q = def->rotation; bodySim->center = def->position; bodySim->rotation0 = bodySim->transform.q; bodySim->center0 = bodySim->center; bodySim->minExtent = B2_HUGE; bodySim->maxExtent = 0.0f; bodySim->linearDamping = def->linearDamping; bodySim->angularDamping = def->angularDamping; bodySim->gravityScale = def->gravityScale; bodySim->bodyId = bodyId; bodySim->flags = lockFlags; bodySim->flags |= def->isBullet ? b2_isBullet : 0; bodySim->flags |= def->allowFastRotation ? b2_allowFastRotation : 0; bodySim->flags |= def->type == b2_dynamicBody ? b2_dynamicFlag : 0; if ( setId == b2_awakeSet ) { b2BodyState* bodyState = b2BodyStateArray_Add( &set->bodyStates ); B2_ASSERT( ( (uintptr_t)bodyState & 0x1F ) == 0 ); *bodyState = (b2BodyState){ 0 }; bodyState->linearVelocity = def->linearVelocity; bodyState->angularVelocity = def->angularVelocity; bodyState->deltaRotation = b2Rot_identity; bodyState->flags = bodySim->flags; } if ( bodyId == world->bodies.count ) { b2BodyArray_Push( &world->bodies, (b2Body){ 0 } ); } else { B2_ASSERT( world->bodies.data[bodyId].id == B2_NULL_INDEX ); } b2Body* body = b2BodyArray_Get( &world->bodies, bodyId ); if ( def->name ) { int i = 0; while ( i < B2_NAME_LENGTH - 1 && def->name[i] != 0 ) { body->name[i] = def->name[i]; i += 1; } while ( i < B2_NAME_LENGTH ) { body->name[i] = 0; i += 1; } } else { memset( body->name, 0, B2_NAME_LENGTH * sizeof( char ) ); } body->userData = def->userData; body->setIndex = setId; body->localIndex = set->bodySims.count - 1; body->generation += 1; body->headShapeId = B2_NULL_INDEX; body->shapeCount = 0; body->headChainId = B2_NULL_INDEX; body->headContactKey = B2_NULL_INDEX; body->contactCount = 0; body->headJointKey = B2_NULL_INDEX; body->jointCount = 0; body->islandId = B2_NULL_INDEX; body->islandPrev = B2_NULL_INDEX; body->islandNext = B2_NULL_INDEX; body->bodyMoveIndex = B2_NULL_INDEX; body->id = bodyId; body->mass = 0.0f; body->inertia = 0.0f; body->sleepThreshold = def->sleepThreshold; body->sleepTime = 0.0f; body->type = def->type; body->flags = bodySim->flags; body->enableSleep = def->enableSleep; // dynamic and kinematic bodies that are enabled need a island if ( setId >= b2_awakeSet ) { b2CreateIslandForBody( world, setId, body ); } b2ValidateSolverSets( world ); b2BodyId id = { bodyId + 1, world->worldId, body->generation }; return id; } bool b2WakeBody( b2World* world, b2Body* body ) { if ( body->setIndex >= b2_firstSleepingSet ) { b2WakeSolverSet( world, body->setIndex ); b2ValidateSolverSets( world ); return true; } return false; } void b2DestroyBody( b2BodyId bodyId ) { b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return; } b2Body* body = b2GetBodyFullId( world, bodyId ); // Wake bodies attached to this body, even if this body is static. bool wakeBodies = true; // Destroy the attached joints int edgeKey = body->headJointKey; while ( edgeKey != B2_NULL_INDEX ) { int jointId = edgeKey >> 1; int edgeIndex = edgeKey & 1; b2Joint* joint = b2JointArray_Get( &world->joints, jointId ); edgeKey = joint->edges[edgeIndex].nextKey; // Careful because this modifies the list being traversed b2DestroyJointInternal( world, joint, wakeBodies ); } // Destroy all contacts attached to this body. b2DestroyBodyContacts( world, body, wakeBodies ); // Destroy the attached shapes and their broad-phase proxies. int shapeId = body->headShapeId; while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); if ( shape->sensorIndex != B2_NULL_INDEX ) { b2DestroySensor( world, shape ); } b2DestroyShapeProxy( shape, &world->broadPhase ); // Return shape to free list. b2FreeId( &world->shapeIdPool, shapeId ); shape->id = B2_NULL_INDEX; shapeId = shape->nextShapeId; } // Destroy the attached chains. The associated shapes have already been destroyed above. int chainId = body->headChainId; while ( chainId != B2_NULL_INDEX ) { b2ChainShape* chain = b2ChainShapeArray_Get( &world->chainShapes, chainId ); b2FreeChainData( chain ); // Return chain to free list. b2FreeId( &world->chainIdPool, chainId ); chain->id = B2_NULL_INDEX; chainId = chain->nextChainId; } b2RemoveBodyFromIsland( world, body ); // Remove body sim from solver set that owns it b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, body->setIndex ); int movedIndex = b2BodySimArray_RemoveSwap( &set->bodySims, body->localIndex ); if ( movedIndex != B2_NULL_INDEX ) { // Fix moved body index b2BodySim* movedSim = set->bodySims.data + body->localIndex; int movedId = movedSim->bodyId; b2Body* movedBody = b2BodyArray_Get( &world->bodies, movedId ); B2_ASSERT( movedBody->localIndex == movedIndex ); movedBody->localIndex = body->localIndex; } // Remove body state from awake set if ( body->setIndex == b2_awakeSet ) { int result = b2BodyStateArray_RemoveSwap( &set->bodyStates, body->localIndex ); B2_ASSERT( result == movedIndex ); B2_UNUSED( result ); } else if ( set->setIndex >= b2_firstSleepingSet && set->bodySims.count == 0 ) { // Remove solver set if it's now an orphan. b2DestroySolverSet( world, set->setIndex ); } // Free body and id (preserve body generation) b2FreeId( &world->bodyIdPool, body->id ); body->setIndex = B2_NULL_INDEX; body->localIndex = B2_NULL_INDEX; body->id = B2_NULL_INDEX; b2ValidateSolverSets( world ); } int b2Body_GetContactCapacity( b2BodyId bodyId ) { b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return 0; } b2Body* body = b2GetBodyFullId( world, bodyId ); // Conservative and fast return body->contactCount; } int b2Body_GetContactData( b2BodyId bodyId, b2ContactData* contactData, int capacity ) { b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return 0; } b2Body* body = b2GetBodyFullId( world, bodyId ); int contactKey = body->headContactKey; int index = 0; while ( contactKey != B2_NULL_INDEX && index < capacity ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); // Is contact touching? if ( contact->flags & b2_contactTouchingFlag ) { b2Shape* shapeA = b2ShapeArray_Get( &world->shapes, contact->shapeIdA ); b2Shape* shapeB = b2ShapeArray_Get( &world->shapes, contact->shapeIdB ); contactData[index].contactId = (b2ContactId){ contact->contactId + 1, bodyId.world0, 0, contact->generation }; contactData[index].shapeIdA = (b2ShapeId){ shapeA->id + 1, bodyId.world0, shapeA->generation }; contactData[index].shapeIdB = (b2ShapeId){ shapeB->id + 1, bodyId.world0, shapeB->generation }; b2ContactSim* contactSim = b2GetContactSim( world, contact ); contactData[index].manifold = contactSim->manifold; index += 1; } contactKey = contact->edges[edgeIndex].nextKey; } B2_ASSERT( index <= capacity ); return index; } b2AABB b2Body_ComputeAABB( b2BodyId bodyId ) { b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return (b2AABB){ 0 }; } b2Body* body = b2GetBodyFullId( world, bodyId ); if ( body->headShapeId == B2_NULL_INDEX ) { b2Transform transform = b2GetBodyTransform( world, body->id ); return (b2AABB){ transform.p, transform.p }; } b2Shape* shape = b2ShapeArray_Get( &world->shapes, body->headShapeId ); b2AABB aabb = shape->aabb; while ( shape->nextShapeId != B2_NULL_INDEX ) { shape = b2ShapeArray_Get( &world->shapes, shape->nextShapeId ); aabb = b2AABB_Union( aabb, shape->aabb ); } return aabb; } void b2UpdateBodyMassData( b2World* world, b2Body* body ) { b2BodySim* bodySim = b2GetBodySim( world, body ); // Mass is no longer dirty body->flags &= ~b2_dirtyMass; // Compute mass data from shapes. Each shape has its own density. body->mass = 0.0f; body->inertia = 0.0f; bodySim->invMass = 0.0f; bodySim->invInertia = 0.0f; bodySim->localCenter = b2Vec2_zero; bodySim->minExtent = B2_HUGE; bodySim->maxExtent = 0.0f; // Static and kinematic sims have zero mass. if ( body->type != b2_dynamicBody ) { bodySim->center = bodySim->transform.p; bodySim->center0 = bodySim->center; // Need extents for kinematic bodies for sleeping to work correctly. if ( body->type == b2_kinematicBody ) { int shapeId = body->headShapeId; while ( shapeId != B2_NULL_INDEX ) { const b2Shape* s = b2ShapeArray_Get( &world->shapes, shapeId ); b2ShapeExtent extent = b2ComputeShapeExtent( s, b2Vec2_zero ); bodySim->minExtent = b2MinFloat( bodySim->minExtent, extent.minExtent ); bodySim->maxExtent = b2MaxFloat( bodySim->maxExtent, extent.maxExtent ); shapeId = s->nextShapeId; } } return; } int shapeCount = body->shapeCount; b2MassData* masses = b2AllocateArenaItem( &world->arena, shapeCount * sizeof( b2MassData ), "mass data" ); // Accumulate mass over all shapes. b2Vec2 localCenter = b2Vec2_zero; int shapeId = body->headShapeId; int shapeIndex = 0; while ( shapeId != B2_NULL_INDEX ) { const b2Shape* s = b2ShapeArray_Get( &world->shapes, shapeId ); shapeId = s->nextShapeId; if ( s->density == 0.0f ) { masses[shapeIndex] = (b2MassData){ 0 }; shapeIndex += 1; continue; } b2MassData massData = b2ComputeShapeMass( s ); body->mass += massData.mass; localCenter = b2MulAdd( localCenter, massData.mass, massData.center ); masses[shapeIndex] = massData; shapeIndex += 1; } // Compute center of mass. if ( body->mass > 0.0f ) { bodySim->invMass = 1.0f / body->mass; localCenter = b2MulSV( bodySim->invMass, localCenter ); } // Second loop to accumulate the rotational inertia about the center of mass for ( shapeIndex = 0; shapeIndex < shapeCount; ++shapeIndex ) { b2MassData massData = masses[shapeIndex]; if ( massData.mass == 0.0f ) { continue; } // Shift to center of mass. This is safe because it can only increase. b2Vec2 offset = b2Sub( localCenter, massData.center ); float inertia = massData.rotationalInertia + massData.mass * b2Dot( offset, offset ); body->inertia += inertia; } b2FreeArenaItem( &world->arena, masses ); masses = NULL; B2_ASSERT( body->inertia >= 0.0f ); if ( body->inertia > 0.0f ) { bodySim->invInertia = 1.0f / body->inertia; } else { body->inertia = 0.0f; bodySim->invInertia = 0.0f; } // Move center of mass. b2Vec2 oldCenter = bodySim->center; bodySim->localCenter = localCenter; bodySim->center = b2TransformPoint( bodySim->transform, bodySim->localCenter ); bodySim->center0 = bodySim->center; // Update center of mass velocity b2BodyState* state = b2GetBodyState( world, body ); if ( state != NULL ) { b2Vec2 deltaLinear = b2CrossSV( state->angularVelocity, b2Sub( bodySim->center, oldCenter ) ); state->linearVelocity = b2Add( state->linearVelocity, deltaLinear ); } // Compute body extents relative to center of mass shapeId = body->headShapeId; while ( shapeId != B2_NULL_INDEX ) { const b2Shape* s = b2ShapeArray_Get( &world->shapes, shapeId ); b2ShapeExtent extent = b2ComputeShapeExtent( s, localCenter ); bodySim->minExtent = b2MinFloat( bodySim->minExtent, extent.minExtent ); bodySim->maxExtent = b2MaxFloat( bodySim->maxExtent, extent.maxExtent ); shapeId = s->nextShapeId; } } b2Vec2 b2Body_GetPosition( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2Transform transform = b2GetBodyTransformQuick( world, body ); return transform.p; } b2Rot b2Body_GetRotation( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2Transform transform = b2GetBodyTransformQuick( world, body ); return transform.q; } b2Transform b2Body_GetTransform( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); return b2GetBodyTransformQuick( world, body ); } b2Vec2 b2Body_GetLocalPoint( b2BodyId bodyId, b2Vec2 worldPoint ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2Transform transform = b2GetBodyTransformQuick( world, body ); return b2InvTransformPoint( transform, worldPoint ); } b2Vec2 b2Body_GetWorldPoint( b2BodyId bodyId, b2Vec2 localPoint ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2Transform transform = b2GetBodyTransformQuick( world, body ); return b2TransformPoint( transform, localPoint ); } b2Vec2 b2Body_GetLocalVector( b2BodyId bodyId, b2Vec2 worldVector ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2Transform transform = b2GetBodyTransformQuick( world, body ); return b2InvRotateVector( transform.q, worldVector ); } b2Vec2 b2Body_GetWorldVector( b2BodyId bodyId, b2Vec2 localVector ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2Transform transform = b2GetBodyTransformQuick( world, body ); return b2RotateVector( transform.q, localVector ); } void b2Body_SetTransform( b2BodyId bodyId, b2Vec2 position, b2Rot rotation ) { B2_ASSERT( b2IsValidVec2( position ) ); B2_ASSERT( b2IsValidRotation( rotation ) ); B2_ASSERT( b2Body_IsValid( bodyId ) ); b2World* world = b2GetWorld( bodyId.world0 ); B2_ASSERT( world->locked == false ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodySim* bodySim = b2GetBodySim( world, body ); bodySim->transform.p = position; bodySim->transform.q = rotation; bodySim->center = b2TransformPoint( bodySim->transform, bodySim->localCenter ); bodySim->rotation0 = bodySim->transform.q; bodySim->center0 = bodySim->center; b2BroadPhase* broadPhase = &world->broadPhase; b2Transform transform = bodySim->transform; const float margin = B2_AABB_MARGIN; const float speculativeDistance = B2_SPECULATIVE_DISTANCE; int shapeId = body->headShapeId; while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); b2AABB aabb = b2ComputeShapeAABB( shape, transform ); aabb.lowerBound.x -= speculativeDistance; aabb.lowerBound.y -= speculativeDistance; aabb.upperBound.x += speculativeDistance; aabb.upperBound.y += speculativeDistance; shape->aabb = aabb; if ( b2AABB_Contains( shape->fatAABB, aabb ) == false ) { b2AABB fatAABB; fatAABB.lowerBound.x = aabb.lowerBound.x - margin; fatAABB.lowerBound.y = aabb.lowerBound.y - margin; fatAABB.upperBound.x = aabb.upperBound.x + margin; fatAABB.upperBound.y = aabb.upperBound.y + margin; shape->fatAABB = fatAABB; // They body could be disabled if ( shape->proxyKey != B2_NULL_INDEX ) { b2BroadPhase_MoveProxy( broadPhase, shape->proxyKey, fatAABB ); } } shapeId = shape->nextShapeId; } } b2Vec2 b2Body_GetLinearVelocity( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodyState* state = b2GetBodyState( world, body ); if ( state != NULL ) { return state->linearVelocity; } return b2Vec2_zero; } float b2Body_GetAngularVelocity( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodyState* state = b2GetBodyState( world, body ); if ( state != NULL ) { return state->angularVelocity; } return 0.0; } void b2Body_SetLinearVelocity( b2BodyId bodyId, b2Vec2 linearVelocity ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); if ( body->type == b2_staticBody ) { return; } if ( b2LengthSquared( linearVelocity ) > 0.0f ) { b2WakeBody( world, body ); } b2BodyState* state = b2GetBodyState( world, body ); if ( state == NULL ) { return; } state->linearVelocity = linearVelocity; } void b2Body_SetAngularVelocity( b2BodyId bodyId, float angularVelocity ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); if ( body->type == b2_staticBody || ( body->flags & b2_lockAngularZ ) ) { return; } if ( angularVelocity != 0.0f ) { b2WakeBody( world, body ); } b2BodyState* state = b2GetBodyState( world, body ); if ( state == NULL ) { return; } state->angularVelocity = angularVelocity; } void b2Body_SetTargetTransform( b2BodyId bodyId, b2Transform target, float timeStep, bool wake ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); if ( body->setIndex == b2_disabledSet ) { return; } if ( body->type == b2_staticBody || timeStep <= 0.0f ) { return; } if ( body->setIndex != b2_awakeSet && wake == false ) { return; } b2BodySim* sim = b2GetBodySim( world, body ); // Compute linear velocity b2Vec2 center1 = sim->center; b2Vec2 center2 = b2TransformPoint( target, sim->localCenter ); float invTimeStep = 1.0f / timeStep; b2Vec2 linearVelocity = b2MulSV( invTimeStep, b2Sub( center2, center1 ) ); // Compute angular velocity b2Rot q1 = sim->transform.q; b2Rot q2 = target.q; float deltaAngle = b2RelativeAngle( q1, q2 ); float angularVelocity = invTimeStep * deltaAngle; // Early out if the body is asleep already and the desired movement is small if ( body->setIndex != b2_awakeSet ) { float maxVelocity = b2Length( linearVelocity ) + b2AbsFloat( angularVelocity ) * sim->maxExtent; // Return if velocity would be sleepy if ( maxVelocity < body->sleepThreshold ) { return; } // Must wake for state to exist b2WakeBody( world, body ); } B2_ASSERT( body->setIndex == b2_awakeSet ); b2BodyState* state = b2GetBodyState( world, body ); state->linearVelocity = linearVelocity; state->angularVelocity = angularVelocity; } b2Vec2 b2Body_GetLocalPointVelocity( b2BodyId bodyId, b2Vec2 localPoint ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodyState* state = b2GetBodyState( world, body ); if ( state == NULL ) { return b2Vec2_zero; } b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, body->setIndex ); b2BodySim* bodySim = b2BodySimArray_Get( &set->bodySims, body->localIndex ); b2Vec2 r = b2RotateVector( bodySim->transform.q, b2Sub( localPoint, bodySim->localCenter ) ); b2Vec2 v = b2Add( state->linearVelocity, b2CrossSV( state->angularVelocity, r ) ); return v; } b2Vec2 b2Body_GetWorldPointVelocity( b2BodyId bodyId, b2Vec2 worldPoint ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodyState* state = b2GetBodyState( world, body ); if ( state == NULL ) { return b2Vec2_zero; } b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, body->setIndex ); b2BodySim* bodySim = b2BodySimArray_Get( &set->bodySims, body->localIndex ); b2Vec2 r = b2Sub( worldPoint, bodySim->center ); b2Vec2 v = b2Add( state->linearVelocity, b2CrossSV( state->angularVelocity, r ) ); return v; } void b2Body_ApplyForce( b2BodyId bodyId, b2Vec2 force, b2Vec2 point, bool wake ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); if ( body->type != b2_dynamicBody || body->setIndex == b2_disabledSet ) { return; } if ( wake && body->setIndex >= b2_firstSleepingSet ) { b2WakeBody( world, body ); } if ( body->setIndex == b2_awakeSet ) { b2BodySim* bodySim = b2GetBodySim( world, body ); bodySim->force = b2Add( bodySim->force, force ); bodySim->torque += b2Cross( b2Sub( point, bodySim->center ), force ); } } void b2Body_ApplyForceToCenter( b2BodyId bodyId, b2Vec2 force, bool wake ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); if ( body->type != b2_dynamicBody || body->setIndex == b2_disabledSet ) { return; } if ( wake && body->setIndex >= b2_firstSleepingSet ) { b2WakeBody( world, body ); } if ( body->setIndex == b2_awakeSet ) { b2BodySim* bodySim = b2GetBodySim( world, body ); bodySim->force = b2Add( bodySim->force, force ); } } void b2Body_ApplyTorque( b2BodyId bodyId, float torque, bool wake ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); if ( body->type != b2_dynamicBody || body->setIndex == b2_disabledSet ) { return; } if ( wake && body->setIndex >= b2_firstSleepingSet ) { b2WakeBody( world, body ); } if ( body->setIndex == b2_awakeSet ) { b2BodySim* bodySim = b2GetBodySim( world, body ); bodySim->torque += torque; } } void b2Body_ClearForces( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodySim* bodySim = b2GetBodySim( world, body ); bodySim->force = b2Vec2_zero; bodySim->torque = 0.0f; } void b2Body_ApplyLinearImpulse( b2BodyId bodyId, b2Vec2 impulse, b2Vec2 point, bool wake ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); if ( body->type != b2_dynamicBody || body->setIndex == b2_disabledSet ) { return; } if ( wake && body->setIndex >= b2_firstSleepingSet ) { b2WakeBody( world, body ); } if ( body->setIndex == b2_awakeSet ) { int localIndex = body->localIndex; b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); b2BodyState* state = b2BodyStateArray_Get( &set->bodyStates, localIndex ); b2BodySim* bodySim = b2BodySimArray_Get( &set->bodySims, localIndex ); state->linearVelocity = b2MulAdd( state->linearVelocity, bodySim->invMass, impulse ); state->angularVelocity += bodySim->invInertia * b2Cross( b2Sub( point, bodySim->center ), impulse ); b2LimitVelocity( state, world->maxLinearSpeed ); } } void b2Body_ApplyLinearImpulseToCenter( b2BodyId bodyId, b2Vec2 impulse, bool wake ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); if ( body->type != b2_dynamicBody || body->setIndex == b2_disabledSet ) { return; } if ( wake && body->setIndex >= b2_firstSleepingSet ) { b2WakeBody( world, body ); } if ( body->setIndex == b2_awakeSet ) { int localIndex = body->localIndex; b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); b2BodyState* state = b2BodyStateArray_Get( &set->bodyStates, localIndex ); b2BodySim* bodySim = b2BodySimArray_Get( &set->bodySims, localIndex ); state->linearVelocity = b2MulAdd( state->linearVelocity, bodySim->invMass, impulse ); b2LimitVelocity( state, world->maxLinearSpeed ); } } void b2Body_ApplyAngularImpulse( b2BodyId bodyId, float impulse, bool wake ) { B2_ASSERT( b2Body_IsValid( bodyId ) ); b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); if ( body->type != b2_dynamicBody || body->setIndex == b2_disabledSet ) { return; } if ( wake && body->setIndex >= b2_firstSleepingSet ) { // this will not invalidate body pointer b2WakeBody( world, body ); } if ( body->setIndex == b2_awakeSet ) { int localIndex = body->localIndex; b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); b2BodyState* state = b2BodyStateArray_Get( &set->bodyStates, localIndex ); b2BodySim* bodySim = b2BodySimArray_Get( &set->bodySims, localIndex ); state->angularVelocity += bodySim->invInertia * impulse; } } b2BodyType b2Body_GetType( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); return body->type; } // This should follow similar steps as you would get destroying and recreating the body, shapes, and joints. // Contacts are difficult to preserve because the broad-phase pairs change, so I just destroy them. // todo with a bit more effort I could support an option to let the body sleep // // Revised steps: // 1 Skip disabled bodies // 2 Destroy all contacts on the body // 3 Wake the body // 4 For all joints attached to the body // - wake attached bodies // - remove from island // - move to static set temporarily // 5 Change the body type and transfer the body // 6 If the body was static // - create an island for the body // Else if the body is becoming static // - remove it from the island // 7 For all joints // - if either body is non-static // - link into island // - transfer to constraint graph // 8 For all shapes // - Destroy proxy in old tree // - Create proxy in new tree // Notes: // - the implementation below tries to minimize the number of predicates, so some // operations may have no effect, such as transferring a joint to the same set void b2Body_SetType( b2BodyId bodyId, b2BodyType type ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodyType originalType = body->type; if ( originalType == type ) { return; } // Stage 1: skip disabled bodies if ( body->setIndex == b2_disabledSet ) { // Disabled bodies don't change solver sets or islands when they change type. body->type = type; if ( type == b2_dynamicBody ) { body->flags |= b2_dynamicFlag; } else { body->flags &= ~b2_dynamicFlag; } // Body type affects the mass properties b2UpdateBodyMassData( world, body ); return; } // Stage 2: destroy all contacts but don't wake bodies (because we don't need to) bool wakeBodies = false; b2DestroyBodyContacts( world, body, wakeBodies ); // Stage 3: wake this body (does nothing if body is static), otherwise it will also wake // all bodies in the same sleeping solver set. b2WakeBody( world, body ); // Stage 4: move joints to temporary storage b2SolverSet* staticSet = b2SolverSetArray_Get( &world->solverSets, b2_staticSet ); int jointKey = body->headJointKey; while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; b2Joint* joint = b2JointArray_Get( &world->joints, jointId ); jointKey = joint->edges[edgeIndex].nextKey; // Joint may be disabled by other body if ( joint->setIndex == b2_disabledSet ) { continue; } // Wake attached bodies. The b2WakeBody call above does not wake bodies // attached to a static body. But it is necessary because the body may have // no joints. b2Body* bodyA = b2BodyArray_Get( &world->bodies, joint->edges[0].bodyId ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, joint->edges[1].bodyId ); b2WakeBody( world, bodyA ); b2WakeBody( world, bodyB ); // Remove joint from island b2UnlinkJoint( world, joint ); // It is necessary to transfer all joints to the static set // so they can be added to the constraint graph below and acquire consistent colors. b2SolverSet* jointSourceSet = b2SolverSetArray_Get( &world->solverSets, joint->setIndex ); b2TransferJoint( world, staticSet, jointSourceSet, joint ); } // Stage 5: change the body type and transfer body body->type = type; if ( type == b2_dynamicBody ) { body->flags |= b2_dynamicFlag; } else { body->flags &= ~b2_dynamicFlag; } b2SolverSet* awakeSet = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); b2SolverSet* sourceSet = b2SolverSetArray_Get( &world->solverSets, body->setIndex ); b2SolverSet* targetSet = type == b2_staticBody ? staticSet : awakeSet; // Transfer body b2TransferBody( world, targetSet, sourceSet, body ); // Stage 6: update island participation for the body if ( originalType == b2_staticBody ) { // Create island for body b2CreateIslandForBody( world, b2_awakeSet, body ); } else if ( type == b2_staticBody ) { // Remove body from island. b2RemoveBodyFromIsland( world, body ); } // Stage 7: Transfer joints to the target set jointKey = body->headJointKey; while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; b2Joint* joint = b2JointArray_Get( &world->joints, jointId ); jointKey = joint->edges[edgeIndex].nextKey; // Joint may be disabled by other body if ( joint->setIndex == b2_disabledSet ) { continue; } // All joints were transferred to the static set in an earlier stage B2_ASSERT( joint->setIndex == b2_staticSet ); b2Body* bodyA = b2BodyArray_Get( &world->bodies, joint->edges[0].bodyId ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, joint->edges[1].bodyId ); B2_ASSERT( bodyA->setIndex == b2_staticSet || bodyA->setIndex == b2_awakeSet ); B2_ASSERT( bodyB->setIndex == b2_staticSet || bodyB->setIndex == b2_awakeSet ); if ( bodyA->type == b2_dynamicBody || bodyB->type == b2_dynamicBody ) { b2TransferJoint( world, awakeSet, staticSet, joint ); } } // Recreate shape proxies in broadphase b2Transform transform = b2GetBodyTransformQuick( world, body ); int shapeId = body->headShapeId; while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); shapeId = shape->nextShapeId; b2DestroyShapeProxy( shape, &world->broadPhase ); bool forcePairCreation = true; b2CreateShapeProxy( shape, &world->broadPhase, type, transform, forcePairCreation ); } // Relink all joints jointKey = body->headJointKey; while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; b2Joint* joint = b2JointArray_Get( &world->joints, jointId ); jointKey = joint->edges[edgeIndex].nextKey; int otherEdgeIndex = edgeIndex ^ 1; int otherBodyId = joint->edges[otherEdgeIndex].bodyId; b2Body* otherBody = b2BodyArray_Get( &world->bodies, otherBodyId ); if ( otherBody->setIndex == b2_disabledSet ) { continue; } if ( body->type != b2_dynamicBody && otherBody->type != b2_dynamicBody ) { continue; } b2LinkJoint( world, joint ); } // Body type affects the mass b2UpdateBodyMassData( world, body ); b2BodyState* state = b2GetBodyState( world, body ); if ( state != NULL ) { // Ensure flags are in sync (b2_skipSolverWrite) state->flags = body->flags; } b2ValidateSolverSets( world ); b2ValidateIsland( world, body->islandId ); } void b2Body_SetName( b2BodyId bodyId, const char* name ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); if ( name ) { int i = 0; while ( i < B2_NAME_LENGTH - 1 && name[i] != 0 ) { body->name[i] = name[i]; i += 1; } while ( i < B2_NAME_LENGTH ) { body->name[i] = 0; i += 1; } } else { memset( body->name, 0, B2_NAME_LENGTH * sizeof( char ) ); } } const char* b2Body_GetName( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); return body->name; } void b2Body_SetUserData( b2BodyId bodyId, void* userData ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); body->userData = userData; } void* b2Body_GetUserData( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); return body->userData; } float b2Body_GetMass( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); return body->mass; } float b2Body_GetRotationalInertia( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); return body->inertia; } b2Vec2 b2Body_GetLocalCenterOfMass( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodySim* bodySim = b2GetBodySim( world, body ); return bodySim->localCenter; } b2Vec2 b2Body_GetWorldCenterOfMass( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodySim* bodySim = b2GetBodySim( world, body ); return bodySim->center; } void b2Body_SetMassData( b2BodyId bodyId, b2MassData massData ) { B2_ASSERT( b2IsValidFloat( massData.mass ) && massData.mass >= 0.0f ); B2_ASSERT( b2IsValidFloat( massData.rotationalInertia ) && massData.rotationalInertia >= 0.0f ); B2_ASSERT( b2IsValidVec2( massData.center ) ); b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return; } b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodySim* bodySim = b2GetBodySim( world, body ); body->mass = massData.mass; body->inertia = massData.rotationalInertia; bodySim->localCenter = massData.center; b2Vec2 center = b2TransformPoint( bodySim->transform, massData.center ); bodySim->center = center; bodySim->center0 = center; bodySim->invMass = body->mass > 0.0f ? 1.0f / body->mass : 0.0f; bodySim->invInertia = body->inertia > 0.0f ? 1.0f / body->inertia : 0.0f; } b2MassData b2Body_GetMassData( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodySim* bodySim = b2GetBodySim( world, body ); b2MassData massData = { body->mass, bodySim->localCenter, body->inertia }; return massData; } void b2Body_ApplyMassFromShapes( b2BodyId bodyId ) { b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return; } b2Body* body = b2GetBodyFullId( world, bodyId ); b2UpdateBodyMassData( world, body ); } void b2Body_SetLinearDamping( b2BodyId bodyId, float linearDamping ) { B2_ASSERT( b2IsValidFloat( linearDamping ) && linearDamping >= 0.0f ); b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return; } b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodySim* bodySim = b2GetBodySim( world, body ); bodySim->linearDamping = linearDamping; } float b2Body_GetLinearDamping( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodySim* bodySim = b2GetBodySim( world, body ); return bodySim->linearDamping; } void b2Body_SetAngularDamping( b2BodyId bodyId, float angularDamping ) { B2_ASSERT( b2IsValidFloat( angularDamping ) && angularDamping >= 0.0f ); b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return; } b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodySim* bodySim = b2GetBodySim( world, body ); bodySim->angularDamping = angularDamping; } float b2Body_GetAngularDamping( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodySim* bodySim = b2GetBodySim( world, body ); return bodySim->angularDamping; } void b2Body_SetGravityScale( b2BodyId bodyId, float gravityScale ) { B2_ASSERT( b2Body_IsValid( bodyId ) ); B2_ASSERT( b2IsValidFloat( gravityScale ) ); b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return; } b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodySim* bodySim = b2GetBodySim( world, body ); bodySim->gravityScale = gravityScale; } float b2Body_GetGravityScale( b2BodyId bodyId ) { B2_ASSERT( b2Body_IsValid( bodyId ) ); b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodySim* bodySim = b2GetBodySim( world, body ); return bodySim->gravityScale; } bool b2Body_IsAwake( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); return body->setIndex == b2_awakeSet; } void b2Body_SetAwake( b2BodyId bodyId, bool awake ) { b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return; } b2Body* body = b2GetBodyFullId( world, bodyId ); if ( awake && body->setIndex >= b2_firstSleepingSet ) { b2WakeBody( world, body ); } else if ( awake == false && body->setIndex == b2_awakeSet ) { b2Island* island = b2IslandArray_Get( &world->islands, body->islandId ); if ( island->constraintRemoveCount > 0 ) { // Must split the island before sleeping. This is expensive. b2SplitIsland( world, body->islandId ); } b2TrySleepIsland( world, body->islandId ); } } void b2Body_WakeTouching(b2BodyId bodyId) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); int contactKey = body->headContactKey; while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); b2Shape* shapeA = b2ShapeArray_Get( &world->shapes, contact->shapeIdA ); b2Shape* shapeB = b2ShapeArray_Get( &world->shapes, contact->shapeIdB ); if (shapeA->bodyId == bodyId.index1 - 1) { b2Body* otherBody = b2BodyArray_Get( &world->bodies, shapeB->bodyId ); b2WakeBody( world, otherBody ); } else { b2Body* otherBody = b2BodyArray_Get( &world->bodies, shapeA->bodyId ); b2WakeBody( world, otherBody ); } contactKey = contact->edges[edgeIndex].nextKey; } } bool b2Body_IsEnabled( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); return body->setIndex != b2_disabledSet; } bool b2Body_IsSleepEnabled( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); return body->enableSleep; } void b2Body_SetSleepThreshold( b2BodyId bodyId, float sleepThreshold ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); body->sleepThreshold = sleepThreshold; } float b2Body_GetSleepThreshold( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); return body->sleepThreshold; } void b2Body_EnableSleep( b2BodyId bodyId, bool enableSleep ) { b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return; } b2Body* body = b2GetBodyFullId( world, bodyId ); body->enableSleep = enableSleep; if ( enableSleep == false ) { b2WakeBody( world, body ); } } // Disabling a body requires a lot of detailed bookkeeping, but it is a valuable feature. // The most challenging aspect is that joints may connect to bodies that are not disabled. void b2Body_Disable( b2BodyId bodyId ) { b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return; } b2Body* body = b2GetBodyFullId( world, bodyId ); if ( body->setIndex == b2_disabledSet ) { return; } // Destroy contacts and wake bodies touching this body. This avoid floating bodies. // This is necessary even for static bodies. bool wakeBodies = true; b2DestroyBodyContacts( world, body, wakeBodies ); // The current solver set of the body b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, body->setIndex ); // Disabled bodies and connected joints are moved to the disabled set b2SolverSet* disabledSet = b2SolverSetArray_Get( &world->solverSets, b2_disabledSet ); // Unlink joints and transfer them to the disabled set int jointKey = body->headJointKey; while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; b2Joint* joint = b2JointArray_Get( &world->joints, jointId ); jointKey = joint->edges[edgeIndex].nextKey; // joint may already be disabled by other body if ( joint->setIndex == b2_disabledSet ) { continue; } B2_ASSERT( joint->setIndex == set->setIndex || set->setIndex == b2_staticSet ); // Remove joint from island b2UnlinkJoint( world, joint ); // Transfer joint to disabled set b2SolverSet* jointSet = b2SolverSetArray_Get( &world->solverSets, joint->setIndex ); b2TransferJoint( world, disabledSet, jointSet, joint ); } // Remove shapes from broad-phase int shapeId = body->headShapeId; while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); shapeId = shape->nextShapeId; b2DestroyShapeProxy( shape, &world->broadPhase ); } // Disabled bodies are not in an island. If the island becomes empty it will be destroyed. b2RemoveBodyFromIsland( world, body ); // Transfer body sim b2TransferBody( world, disabledSet, set, body ); b2ValidateConnectivity( world ); b2ValidateSolverSets( world ); } void b2Body_Enable( b2BodyId bodyId ) { b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return; } b2Body* body = b2GetBodyFullId( world, bodyId ); if ( body->setIndex != b2_disabledSet ) { return; } b2SolverSet* disabledSet = b2SolverSetArray_Get( &world->solverSets, b2_disabledSet ); int setId = body->type == b2_staticBody ? b2_staticSet : b2_awakeSet; b2SolverSet* targetSet = b2SolverSetArray_Get( &world->solverSets, setId ); b2TransferBody( world, targetSet, disabledSet, body ); b2Transform transform = b2GetBodyTransformQuick( world, body ); // Add shapes to broad-phase b2BodyType proxyType = body->type; bool forcePairCreation = true; int shapeId = body->headShapeId; while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); shapeId = shape->nextShapeId; b2CreateShapeProxy( shape, &world->broadPhase, proxyType, transform, forcePairCreation ); } if ( setId != b2_staticSet ) { b2CreateIslandForBody( world, setId, body ); } // Transfer joints. If the other body is disabled, don't transfer. // If the other body is sleeping, wake it. int jointKey = body->headJointKey; while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; b2Joint* joint = b2JointArray_Get( &world->joints, jointId ); B2_ASSERT( joint->setIndex == b2_disabledSet ); B2_ASSERT( joint->islandId == B2_NULL_INDEX ); jointKey = joint->edges[edgeIndex].nextKey; b2Body* bodyA = b2BodyArray_Get( &world->bodies, joint->edges[0].bodyId ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, joint->edges[1].bodyId ); if ( bodyA->setIndex == b2_disabledSet || bodyB->setIndex == b2_disabledSet ) { // one body is still disabled continue; } // Transfer joint first int jointSetId; if ( bodyA->setIndex == b2_staticSet && bodyB->setIndex == b2_staticSet ) { jointSetId = b2_staticSet; } else if ( bodyA->setIndex == b2_staticSet ) { jointSetId = bodyB->setIndex; } else { jointSetId = bodyA->setIndex; } b2SolverSet* jointSet = b2SolverSetArray_Get( &world->solverSets, jointSetId ); b2TransferJoint( world, jointSet, disabledSet, joint ); // Now that the joint is in the correct set, I can link the joint in the island. if ( jointSetId != b2_staticSet ) { b2LinkJoint( world, joint ); } } b2ValidateSolverSets( world ); } void b2Body_SetMotionLocks( b2BodyId bodyId, b2MotionLocks locks ) { b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return; } uint32_t newFlags = 0; newFlags |= locks.linearX ? b2_lockLinearX : 0; newFlags |= locks.linearY ? b2_lockLinearY : 0; newFlags |= locks.angularZ ? b2_lockAngularZ : 0; b2Body* body = b2GetBodyFullId( world, bodyId ); if ( ( body->flags & b2_allLocks ) != newFlags ) { body->flags &= ~b2_allLocks; body->flags |= newFlags; b2BodySim* bodySim = b2GetBodySim( world, body ); bodySim->flags &= ~b2_allLocks; bodySim->flags |= newFlags; b2BodyState* state = b2GetBodyState( world, body ); if ( state != NULL ) { state->flags = bodySim->flags; if ( locks.linearX ) { state->linearVelocity.x = 0.0f; } if ( locks.linearY ) { state->linearVelocity.y = 0.0f; } if ( locks.angularZ ) { state->angularVelocity = 0.0f; } } } } b2MotionLocks b2Body_GetMotionLocks( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2MotionLocks locks; locks.linearX = ( body->flags & b2_lockLinearX ); locks.linearY = ( body->flags & b2_lockLinearY ); locks.angularZ = ( body->flags & b2_lockAngularZ ); return locks; } void b2Body_SetBullet( b2BodyId bodyId, bool flag ) { b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return; } b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodySim* bodySim = b2GetBodySim( world, body ); if ( flag ) { bodySim->flags |= b2_isBullet; } else { bodySim->flags &= ~b2_isBullet; } } bool b2Body_IsBullet( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodySim* bodySim = b2GetBodySim( world, body ); return ( bodySim->flags & b2_isBullet ) != 0; } void b2Body_EnableContactEvents( b2BodyId bodyId, bool flag ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); int shapeId = body->headShapeId; while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); shape->enableContactEvents = flag; shapeId = shape->nextShapeId; } } void b2Body_EnableHitEvents( b2BodyId bodyId, bool flag ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); int shapeId = body->headShapeId; while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); shape->enableHitEvents = flag; shapeId = shape->nextShapeId; } } b2WorldId b2Body_GetWorld( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); return (b2WorldId){ bodyId.world0 + 1, world->generation }; } int b2Body_GetShapeCount( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); return body->shapeCount; } int b2Body_GetShapes( b2BodyId bodyId, b2ShapeId* shapeArray, int capacity ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); int shapeId = body->headShapeId; int shapeCount = 0; while ( shapeId != B2_NULL_INDEX && shapeCount < capacity ) { b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); b2ShapeId id = { shape->id + 1, bodyId.world0, shape->generation }; shapeArray[shapeCount] = id; shapeCount += 1; shapeId = shape->nextShapeId; } return shapeCount; } int b2Body_GetJointCount( b2BodyId bodyId ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); return body->jointCount; } int b2Body_GetJoints( b2BodyId bodyId, b2JointId* jointArray, int capacity ) { b2World* world = b2GetWorld( bodyId.world0 ); b2Body* body = b2GetBodyFullId( world, bodyId ); int jointKey = body->headJointKey; int jointCount = 0; while ( jointKey != B2_NULL_INDEX && jointCount < capacity ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; b2Joint* joint = b2JointArray_Get( &world->joints, jointId ); b2JointId id = { jointId + 1, bodyId.world0, joint->generation }; jointArray[jointCount] = id; jointCount += 1; jointKey = joint->edges[edgeIndex].nextKey; } return jointCount; } bool b2ShouldBodiesCollide( b2World* world, b2Body* bodyA, b2Body* bodyB ) { if ( bodyA->type != b2_dynamicBody && bodyB->type != b2_dynamicBody ) { return false; } int jointKey; int otherBodyId; if ( bodyA->jointCount < bodyB->jointCount ) { jointKey = bodyA->headJointKey; otherBodyId = bodyB->id; } else { jointKey = bodyB->headJointKey; otherBodyId = bodyA->id; } while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; int otherEdgeIndex = edgeIndex ^ 1; b2Joint* joint = b2JointArray_Get( &world->joints, jointId ); if ( joint->collideConnected == false && joint->edges[otherEdgeIndex].bodyId == otherBodyId ) { return false; } jointKey = joint->edges[edgeIndex].nextKey; } return true; } ================================================ FILE: src/body.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "array.h" #include "box2d/math_functions.h" #include "box2d/types.h" // Length of body debug name #define B2_NAME_LENGTH 32 typedef struct b2World b2World; enum b2BodyFlags { // This body has fixed translation along the x-axis b2_lockLinearX = 0x00000001, // This body has fixed translation along the y-axis b2_lockLinearY = 0x00000002, // This body has fixed rotation b2_lockAngularZ = 0x00000004, // This flag is used for debug draw b2_isFast = 0x00000008, // This dynamic body does a final CCD pass against all body types, but not other bullets b2_isBullet = 0x00000010, // This body was speed capped in the current time step b2_isSpeedCapped = 0x00000020, // This body had a time of impact event in the current time step b2_hadTimeOfImpact = 0x00000040, // This body has no limit on angular velocity b2_allowFastRotation = 0x00000080, // This body need's to have its AABB increased b2_enlargeBounds = 0x00000100, // This body is dynamic so the solver should write to it. // This prevents writing to kinematic bodies that causes a multithreaded sharing // cache coherence problem even when the values are not changing. // Used for b2BodyState flags. b2_dynamicFlag = 0x00000200, // Flag to indicate the user has used the updateBodyMass option to defer mass // computation but b2Body_ApplyMassFromShapes was not called before the world step. b2_dirtyMass = 0x00000400, // All lock flags b2_allLocks = b2_lockAngularZ | b2_lockLinearX | b2_lockLinearY, }; // Body organizational details that are not used in the solver. typedef struct b2Body { char name[B2_NAME_LENGTH]; void* userData; // index of solver set stored in b2World // may be B2_NULL_INDEX int setIndex; // body sim and state index within set // may be B2_NULL_INDEX int localIndex; // [31 : contactId | 1 : edgeIndex] int headContactKey; int contactCount; // todo maybe move this to the body sim int headShapeId; int shapeCount; int headChainId; // [31 : jointId | 1 : edgeIndex] int headJointKey; int jointCount; // All enabled dynamic and kinematic bodies are in an island. int islandId; // doubly-linked island list int islandPrev; int islandNext; float mass; // Rotational inertia about the center of mass. float inertia; float sleepThreshold; float sleepTime; // this is used to adjust the fellAsleep flag in the body move array int bodyMoveIndex; int id; // b2BodyFlags uint32_t flags; b2BodyType type; // This is monotonically advanced when a body is allocated in this slot // Used to check for invalid b2BodyId uint16_t generation; // todo move into flags bool enableSleep; } b2Body; // Body State // The body state is designed for fast conversion to and from SIMD via scatter-gather. // Only awake dynamic and kinematic bodies have a body state. // This is used in the performance critical constraint solver // // The solver operates on the body state. The body state array does not hold static bodies. Static bodies are shared // across worker threads. It would be okay to read their states, but writing to them would cause cache thrashing across // workers, even if the values don't change. // This causes some trouble when computing anchors. I rotate joint anchors using the body rotation every sub-step. For static // bodies the anchor doesn't rotate. Body A or B could be static and this can lead to lots of branching. This branching // should be minimized. // // Solution 1: // Use delta rotations. This means anchors need to be prepared in world space. The delta rotation for static bodies will be // identity using a dummy state. Base separation and angles need to be computed. Manifolds will be behind a frame, but that // is probably best if bodies move fast. // // Solution 2: // Use full rotation. The anchors for static bodies will be in world space while the anchors for dynamic bodies will be in local // space. Potentially confusing and bug prone. // // Note: // I rotate joint anchors each sub-step but not contact anchors. Joint stability improves a lot by rotating joint anchors // according to substep progress. Contacts have reduced stability when anchors are rotated during substeps, especially for // round shapes. // 32 bytes typedef struct b2BodyState { b2Vec2 linearVelocity; // 8 float angularVelocity; // 4 // b2BodyFlags // Important flags: locking, dynamic uint32_t flags; // 4 // Using delta position reduces round-off error far from the origin b2Vec2 deltaPosition; // 8 // Using delta rotation because I cannot access the full rotation on static bodies in // the solver and must use zero delta rotation for static bodies (c,s) = (1,0) b2Rot deltaRotation; // 8 } b2BodyState; // Identity body state, notice the deltaRotation is {1, 0} static const b2BodyState b2_identityBodyState = { { 0.0f, 0.0f }, 0.0f, 0, { 0.0f, 0.0f }, { 1.0f, 0.0f } }; // Body simulation data used for integration of position and velocity // Transform data used for collision and solver preparation. typedef struct b2BodySim { // transform for body origin b2Transform transform; // center of mass position in world space b2Vec2 center; // previous rotation and COM for TOI b2Rot rotation0; b2Vec2 center0; // location of center of mass relative to the body origin b2Vec2 localCenter; b2Vec2 force; float torque; // inverse inertia float invMass; float invInertia; float minExtent; float maxExtent; float linearDamping; float angularDamping; float gravityScale; // Index of b2Body int bodyId; // b2BodyFlags uint32_t flags; } b2BodySim; // Get a validated body from a world using an id. b2Body* b2GetBodyFullId( b2World* world, b2BodyId bodyId ); b2Transform b2GetBodyTransformQuick( b2World* world, b2Body* body ); b2Transform b2GetBodyTransform( b2World* world, int bodyId ); // Create a b2BodyId from a raw id. b2BodyId b2MakeBodyId( b2World* world, int bodyId ); bool b2ShouldBodiesCollide( b2World* world, b2Body* bodyA, b2Body* bodyB ); b2BodySim* b2GetBodySim( b2World* world, b2Body* body ); b2BodyState* b2GetBodyState( b2World* world, b2Body* body ); // careful calling this because it can invalidate body, state, joint, and contact pointers bool b2WakeBody( b2World* world, b2Body* body ); void b2UpdateBodyMassData( b2World* world, b2Body* body ); static inline b2Sweep b2MakeSweep( const b2BodySim* bodySim ) { b2Sweep s; s.c1 = bodySim->center0; s.c2 = bodySim->center; s.q1 = bodySim->rotation0; s.q2 = bodySim->transform.q; s.localCenter = bodySim->localCenter; return s; } // Define inline functions for arrays B2_ARRAY_INLINE( b2Body, b2Body ) B2_ARRAY_INLINE( b2BodySim, b2BodySim ) B2_ARRAY_INLINE( b2BodyState, b2BodyState ) ================================================ FILE: src/box2d.natvis ================================================ [{m128_f32[0]}, {m128_f32[1]}, {m128_f32[2]}, {m128_f32[3]}] m128_f32[0] m128_f32[1] m128_f32[2] m128_f32[3] (void*)this [{m256_f32[0]}, {m256_f32[1]}, {m256_f32[2]}, {m256_f32[3]}, {m256_f32[4]}, {m256_f32[5]}, {m256_f32[6]}, {m256_f32[7]}] m256_f32[0] m256_f32[1] m256_f32[2] m256_f32[3] m256_f32[4] m256_f32[5] m256_f32[6] m256_f32[7] (void*)this index: {index1} b2_worlds[ index1 - 1 ] {b2_worlds[world0].bodies.data[index1-1].name,na}, {b2_worlds[world0].bodies.data[index1-1].type} ================================================ FILE: src/broad_phase.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #if defined( _MSC_VER ) && !defined( _CRT_SECURE_NO_WARNINGS ) #define _CRT_SECURE_NO_WARNINGS #endif #include "broad_phase.h" #include "aabb.h" #include "array.h" #include "atomic.h" #include "body.h" #include "contact.h" #include "core.h" #include "shape.h" #include "arena_allocator.h" #include "physics_world.h" #include #include // #include // static FILE* s_file = NULL; void b2CreateBroadPhase( b2BroadPhase* bp ) { _Static_assert( b2_bodyTypeCount == 3, "must be three body types" ); // if (s_file == NULL) //{ // s_file = fopen("pairs01.txt", "a"); // fprintf(s_file, "============\n\n"); // } bp->moveSet = b2CreateSet( 16 ); bp->moveArray = b2IntArray_Create( 16 ); bp->moveResults = NULL; bp->movePairs = NULL; bp->movePairCapacity = 0; b2AtomicStoreInt( &bp->movePairIndex, 0 ); bp->pairSet = b2CreateSet( 32 ); for ( int i = 0; i < b2_bodyTypeCount; ++i ) { bp->trees[i] = b2DynamicTree_Create(); } } void b2DestroyBroadPhase( b2BroadPhase* bp ) { for ( int i = 0; i < b2_bodyTypeCount; ++i ) { b2DynamicTree_Destroy( bp->trees + i ); } b2DestroySet( &bp->moveSet ); b2IntArray_Destroy( &bp->moveArray ); b2DestroySet( &bp->pairSet ); memset( bp, 0, sizeof( b2BroadPhase ) ); // if (s_file != NULL) //{ // fclose(s_file); // s_file = NULL; // } } static inline void b2UnBufferMove( b2BroadPhase* bp, int proxyKey ) { bool found = b2RemoveKey( &bp->moveSet, proxyKey + 1 ); if ( found ) { // Purge from move buffer. Linear search. // todo if I can iterate the move set then I don't need the moveArray int count = bp->moveArray.count; for ( int i = 0; i < count; ++i ) { if ( bp->moveArray.data[i] == proxyKey ) { b2IntArray_RemoveSwap( &bp->moveArray, i ); break; } } } } int b2BroadPhase_CreateProxy( b2BroadPhase* bp, b2BodyType proxyType, b2AABB aabb, uint64_t categoryBits, int shapeIndex, bool forcePairCreation ) { B2_ASSERT( 0 <= proxyType && proxyType < b2_bodyTypeCount ); int proxyId = b2DynamicTree_CreateProxy( bp->trees + proxyType, aabb, categoryBits, shapeIndex ); int proxyKey = B2_PROXY_KEY( proxyId, proxyType ); if ( proxyType != b2_staticBody || forcePairCreation ) { b2BufferMove( bp, proxyKey ); } return proxyKey; } void b2BroadPhase_DestroyProxy( b2BroadPhase* bp, int proxyKey ) { B2_ASSERT( bp->moveArray.count == (int)bp->moveSet.count ); b2UnBufferMove( bp, proxyKey ); b2BodyType proxyType = B2_PROXY_TYPE( proxyKey ); int proxyId = B2_PROXY_ID( proxyKey ); B2_ASSERT( 0 <= proxyType && proxyType <= b2_bodyTypeCount ); b2DynamicTree_DestroyProxy( bp->trees + proxyType, proxyId ); } void b2BroadPhase_MoveProxy( b2BroadPhase* bp, int proxyKey, b2AABB aabb ) { b2BodyType proxyType = B2_PROXY_TYPE( proxyKey ); int proxyId = B2_PROXY_ID( proxyKey ); b2DynamicTree_MoveProxy( bp->trees + proxyType, proxyId, aabb ); b2BufferMove( bp, proxyKey ); } void b2BroadPhase_EnlargeProxy( b2BroadPhase* bp, int proxyKey, b2AABB aabb ) { B2_ASSERT( proxyKey != B2_NULL_INDEX ); int typeIndex = B2_PROXY_TYPE( proxyKey ); int proxyId = B2_PROXY_ID( proxyKey ); B2_ASSERT( typeIndex != b2_staticBody ); b2DynamicTree_EnlargeProxy( bp->trees + typeIndex, proxyId, aabb ); b2BufferMove( bp, proxyKey ); } typedef struct b2MovePair { int shapeIndexA; int shapeIndexB; b2MovePair* next; bool heap; } b2MovePair; typedef struct b2MoveResult { b2MovePair* pairList; } b2MoveResult; typedef struct b2QueryPairContext { b2World* world; b2MoveResult* moveResult; b2BodyType queryTreeType; int queryProxyKey; int queryShapeIndex; } b2QueryPairContext; // This is called from b2DynamicTree::Query when we are gathering pairs. static bool b2PairQueryCallback( int proxyId, uint64_t userData, void* context ) { int shapeId = (int)userData; b2QueryPairContext* queryContext = context; b2BroadPhase* broadPhase = &queryContext->world->broadPhase; int proxyKey = B2_PROXY_KEY( proxyId, queryContext->queryTreeType ); int queryProxyKey = queryContext->queryProxyKey; // A proxy cannot form a pair with itself. if ( proxyKey == queryContext->queryProxyKey ) { return true; } b2BodyType treeType = queryContext->queryTreeType; b2BodyType queryProxyType = B2_PROXY_TYPE( queryProxyKey ); // De-duplication // It is important to prevent duplicate contacts from being created. Ideally I can prevent duplicates // early and in the worker. Most of the time the moveSet contains dynamic and kinematic proxies, but // sometimes it has static proxies. // I had an optimization here to skip checking the move set if this is a query into // the static tree. The assumption is that the static proxies are never in the move set // so there is no risk of duplication. However, this is not true with // b2ShapeDef::invokeContactCreation or when a static shape is modified. // There can easily be scenarios where the static proxy is in the moveSet but the dynamic proxy is not. // I could have some flag to indicate that there are any static bodies in the moveSet. // Is this proxy also moving? if ( queryProxyType == b2_dynamicBody ) { if ( treeType == b2_dynamicBody && proxyKey < queryProxyKey ) { bool moved = b2ContainsKey( &broadPhase->moveSet, proxyKey + 1 ); if ( moved ) { // Both proxies are moving. Avoid duplicate pairs. return true; } } } else { B2_ASSERT( treeType == b2_dynamicBody ); bool moved = b2ContainsKey( &broadPhase->moveSet, proxyKey + 1 ); if ( moved ) { // Both proxies are moving. Avoid duplicate pairs. return true; } } uint64_t pairKey = B2_SHAPE_PAIR_KEY( shapeId, queryContext->queryShapeIndex ); if ( b2ContainsKey( &broadPhase->pairSet, pairKey ) ) { // contact exists return true; } int shapeIdA, shapeIdB; if ( proxyKey < queryProxyKey ) { shapeIdA = shapeId; shapeIdB = queryContext->queryShapeIndex; } else { shapeIdA = queryContext->queryShapeIndex; shapeIdB = shapeId; } b2World* world = queryContext->world; b2Shape* shapeA = b2ShapeArray_Get( &world->shapes, shapeIdA ); b2Shape* shapeB = b2ShapeArray_Get( &world->shapes, shapeIdB ); int bodyIdA = shapeA->bodyId; int bodyIdB = shapeB->bodyId; // Are the shapes on the same body? if ( bodyIdA == bodyIdB ) { return true; } // Sensors are handled elsewhere if ( shapeA->sensorIndex != B2_NULL_INDEX || shapeB->sensorIndex != B2_NULL_INDEX ) { return true; } if ( b2ShouldShapesCollide( shapeA->filter, shapeB->filter ) == false ) { return true; } // Does a joint override collision? b2Body* bodyA = b2BodyArray_Get( &world->bodies, bodyIdA ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, bodyIdB ); if ( b2ShouldBodiesCollide( world, bodyA, bodyB ) == false ) { return true; } // Custom user filter if ( shapeA->enableCustomFiltering || shapeB->enableCustomFiltering ) { b2CustomFilterFcn* customFilterFcn = queryContext->world->customFilterFcn; if ( customFilterFcn != NULL ) { b2ShapeId idA = { shapeIdA + 1, world->worldId, shapeA->generation }; b2ShapeId idB = { shapeIdB + 1, world->worldId, shapeB->generation }; bool shouldCollide = customFilterFcn( idA, idB, queryContext->world->customFilterContext ); if ( shouldCollide == false ) { return true; } } } // todo per thread to eliminate atomic? int pairIndex = b2AtomicFetchAddInt( &broadPhase->movePairIndex, 1 ); b2MovePair* pair; if ( pairIndex < broadPhase->movePairCapacity ) { pair = broadPhase->movePairs + pairIndex; pair->heap = false; } else { pair = b2Alloc( sizeof( b2MovePair ) ); pair->heap = true; } pair->shapeIndexA = shapeIdA; pair->shapeIndexB = shapeIdB; pair->next = queryContext->moveResult->pairList; queryContext->moveResult->pairList = pair; // continue the query return true; } // Warning: writing to these globals significantly slows multithreading performance #if B2_SNOOP_PAIR_COUNTERS b2TreeStats b2_dynamicStats; b2TreeStats b2_kinematicStats; b2TreeStats b2_staticStats; #endif static void b2FindPairsTask( int startIndex, int endIndex, uint32_t threadIndex, void* context ) { b2TracyCZoneNC( pair_task, "Pair", b2_colorMediumSlateBlue, true ); B2_UNUSED( threadIndex ); b2World* world = context; b2BroadPhase* bp = &world->broadPhase; b2QueryPairContext queryContext; queryContext.world = world; for ( int i = startIndex; i < endIndex; ++i ) { // Initialize move result for this moved proxy queryContext.moveResult = bp->moveResults + i; queryContext.moveResult->pairList = NULL; int proxyKey = bp->moveArray.data[i]; if ( proxyKey == B2_NULL_INDEX ) { // proxy was destroyed after it moved continue; } b2BodyType proxyType = B2_PROXY_TYPE( proxyKey ); int proxyId = B2_PROXY_ID( proxyKey ); queryContext.queryProxyKey = proxyKey; const b2DynamicTree* baseTree = bp->trees + proxyType; // We have to query the tree with the fat AABB so that // we don't fail to create a contact that may touch later. b2AABB fatAABB = b2DynamicTree_GetAABB( baseTree, proxyId ); queryContext.queryShapeIndex = (int)b2DynamicTree_GetUserData( baseTree, proxyId ); // Query trees. Only dynamic proxies collide with kinematic and static proxies. // Using B2_DEFAULT_MASK_BITS so that b2Filter::groupIndex works. b2TreeStats stats = { 0 }; if ( proxyType == b2_dynamicBody ) { // consider using bits = groupIndex > 0 ? B2_DEFAULT_MASK_BITS : maskBits queryContext.queryTreeType = b2_kinematicBody; b2TreeStats statsKinematic = b2DynamicTree_Query( bp->trees + b2_kinematicBody, fatAABB, B2_DEFAULT_MASK_BITS, b2PairQueryCallback, &queryContext ); stats.nodeVisits += statsKinematic.nodeVisits; stats.leafVisits += statsKinematic.leafVisits; queryContext.queryTreeType = b2_staticBody; b2TreeStats statsStatic = b2DynamicTree_Query( bp->trees + b2_staticBody, fatAABB, B2_DEFAULT_MASK_BITS, b2PairQueryCallback, &queryContext ); stats.nodeVisits += statsStatic.nodeVisits; stats.leafVisits += statsStatic.leafVisits; } // All proxies collide with dynamic proxies // Using B2_DEFAULT_MASK_BITS so that b2Filter::groupIndex works. queryContext.queryTreeType = b2_dynamicBody; b2TreeStats statsDynamic = b2DynamicTree_Query( bp->trees + b2_dynamicBody, fatAABB, B2_DEFAULT_MASK_BITS, b2PairQueryCallback, &queryContext ); stats.nodeVisits += statsDynamic.nodeVisits; stats.leafVisits += statsDynamic.leafVisits; } b2TracyCZoneEnd( pair_task ); } void b2UpdateBroadPhasePairs( b2World* world ) { b2BroadPhase* bp = &world->broadPhase; int moveCount = bp->moveArray.count; B2_ASSERT( moveCount == (int)bp->moveSet.count ); if ( moveCount == 0 ) { return; } b2TracyCZoneNC( update_pairs, "Find Pairs", b2_colorMediumSlateBlue, true ); b2ArenaAllocator* alloc = &world->arena; // todo these could be in the step context bp->moveResults = b2AllocateArenaItem( alloc, moveCount * sizeof( b2MoveResult ), "move results" ); bp->movePairCapacity = 16 * moveCount; bp->movePairs = b2AllocateArenaItem( alloc, bp->movePairCapacity * sizeof( b2MovePair ), "move pairs" ); b2AtomicStoreInt( &bp->movePairIndex, 0 ); #if B2_SNOOP_TABLE_COUNTERS extern b2AtomicInt b2_probeCount; b2AtomicStoreInt( &b2_probeCount, 0 ); #endif int minRange = 64; void* userPairTask = world->enqueueTaskFcn( &b2FindPairsTask, moveCount, minRange, world, world->userTaskContext ); if ( userPairTask != NULL ) { world->finishTaskFcn( userPairTask, world->userTaskContext ); world->taskCount += 1; } // todo_erin could start tree rebuild here b2TracyCZoneNC( create_contacts, "Create Contacts", b2_colorCoral, true ); // Single-threaded work // - Clear move flags // - Create contacts in deterministic order for ( int i = 0; i < moveCount; ++i ) { b2MoveResult* result = bp->moveResults + i; b2MovePair* pair = result->pairList; while ( pair != NULL ) { int shapeIdA = pair->shapeIndexA; int shapeIdB = pair->shapeIndexB; // if (s_file != NULL) //{ // fprintf(s_file, "%d %d\n", shapeIdA, shapeIdB); // } b2Shape* shapeA = b2ShapeArray_Get( &world->shapes, shapeIdA ); b2Shape* shapeB = b2ShapeArray_Get( &world->shapes, shapeIdB ); b2CreateContact( world, shapeA, shapeB ); if ( pair->heap ) { b2MovePair* temp = pair; pair = pair->next; b2Free( temp, sizeof( b2MovePair ) ); } else { pair = pair->next; } } // if (s_file != NULL) //{ // fprintf(s_file, "\n"); // } } // if (s_file != NULL) //{ // fprintf(s_file, "count = %d\n\n", pairCount); // } // Reset move buffer b2IntArray_Clear( &bp->moveArray ); b2ClearSet( &bp->moveSet ); b2FreeArenaItem( alloc, bp->movePairs ); bp->movePairs = NULL; b2FreeArenaItem( alloc, bp->moveResults ); bp->moveResults = NULL; b2ValidateSolverSets( world ); b2TracyCZoneEnd( create_contacts ); b2TracyCZoneEnd( update_pairs ); } bool b2BroadPhase_TestOverlap( const b2BroadPhase* bp, int proxyKeyA, int proxyKeyB ) { int typeIndexA = B2_PROXY_TYPE( proxyKeyA ); int proxyIdA = B2_PROXY_ID( proxyKeyA ); int typeIndexB = B2_PROXY_TYPE( proxyKeyB ); int proxyIdB = B2_PROXY_ID( proxyKeyB ); b2AABB aabbA = b2DynamicTree_GetAABB( bp->trees + typeIndexA, proxyIdA ); b2AABB aabbB = b2DynamicTree_GetAABB( bp->trees + typeIndexB, proxyIdB ); return b2AABB_Overlaps( aabbA, aabbB ); } void b2BroadPhase_RebuildTrees( b2BroadPhase* bp ) { b2DynamicTree_Rebuild( bp->trees + b2_dynamicBody, false ); b2DynamicTree_Rebuild( bp->trees + b2_kinematicBody, false ); } int b2BroadPhase_GetShapeIndex( b2BroadPhase* bp, int proxyKey ) { int typeIndex = B2_PROXY_TYPE( proxyKey ); int proxyId = B2_PROXY_ID( proxyKey ); return (int)b2DynamicTree_GetUserData( bp->trees + typeIndex, proxyId ); } void b2ValidateBroadphase( const b2BroadPhase* bp ) { b2DynamicTree_Validate( bp->trees + b2_dynamicBody ); b2DynamicTree_Validate( bp->trees + b2_kinematicBody ); // TODO_ERIN validate every shape AABB is contained in tree AABB } void b2ValidateNoEnlarged( const b2BroadPhase* bp ) { #if B2_VALIDATE == 1 for ( int j = 0; j < b2_bodyTypeCount; ++j ) { const b2DynamicTree* tree = bp->trees + j; b2DynamicTree_ValidateNoEnlarged( tree ); } #else B2_UNUSED( bp ); #endif } ================================================ FILE: src/broad_phase.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "array.h" #include "table.h" #include "box2d/collision.h" #include "box2d/types.h" typedef struct b2Shape b2Shape; typedef struct b2MovePair b2MovePair; typedef struct b2MoveResult b2MoveResult; typedef struct b2ArenaAllocator b2ArenaAllocator; typedef struct b2World b2World; // Store the proxy type in the lower 2 bits of the proxy key. This leaves 30 bits for the id. #define B2_PROXY_TYPE( KEY ) ( (b2BodyType)( ( KEY ) & 3 ) ) #define B2_PROXY_ID( KEY ) ( ( KEY ) >> 2 ) #define B2_PROXY_KEY( ID, TYPE ) ( ( ( ID ) << 2 ) | ( TYPE ) ) /// The broad-phase is used for computing pairs and performing volume queries and ray casts. /// This broad-phase does not persist pairs. Instead, this reports potentially new pairs. /// It is up to the client to consume the new pairs and to track subsequent overlap. typedef struct b2BroadPhase { b2DynamicTree trees[b2_bodyTypeCount]; // The move set and array are used to track shapes that have moved significantly // and need a pair query for new contacts. The array has a deterministic order. // todo perhaps just a move set? // todo implement a 32bit hash set for faster lookup // todo moveSet can grow quite large on the first time step and remain large b2HashSet moveSet; b2IntArray moveArray; // These are the results from the pair query and are used to create new contacts // in deterministic order. // todo these could be in the step context b2MoveResult* moveResults; b2MovePair* movePairs; int movePairCapacity; b2AtomicInt movePairIndex; // Tracks shape pairs that have a b2Contact // todo pairSet can grow quite large on the first time step and remain large b2HashSet pairSet; } b2BroadPhase; void b2CreateBroadPhase( b2BroadPhase* bp ); void b2DestroyBroadPhase( b2BroadPhase* bp ); int b2BroadPhase_CreateProxy( b2BroadPhase* bp, b2BodyType proxyType, b2AABB aabb, uint64_t categoryBits, int shapeIndex, bool forcePairCreation ); void b2BroadPhase_DestroyProxy( b2BroadPhase* bp, int proxyKey ); void b2BroadPhase_MoveProxy( b2BroadPhase* bp, int proxyKey, b2AABB aabb ); void b2BroadPhase_EnlargeProxy( b2BroadPhase* bp, int proxyKey, b2AABB aabb ); void b2BroadPhase_RebuildTrees( b2BroadPhase* bp ); int b2BroadPhase_GetShapeIndex( b2BroadPhase* bp, int proxyKey ); void b2UpdateBroadPhasePairs( b2World* world ); bool b2BroadPhase_TestOverlap( const b2BroadPhase* bp, int proxyKeyA, int proxyKeyB ); void b2ValidateBroadphase( const b2BroadPhase* bp ); void b2ValidateNoEnlarged( const b2BroadPhase* bp ); // This is what triggers new contact pairs to be created // Warning: this must be called in deterministic order static inline void b2BufferMove( b2BroadPhase* bp, int queryProxy ) { // Adding 1 because 0 is the sentinel bool alreadyAdded = b2AddKey( &bp->moveSet, queryProxy + 1 ); if ( alreadyAdded == false ) { b2IntArray_Push( &bp->moveArray, queryProxy ); } } ================================================ FILE: src/constants.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once extern float b2_lengthUnitsPerMeter; // Used to detect bad values. Positions greater than about 16km will have precision // problems, so 100km as a limit should be fine in all cases. #define B2_HUGE ( 100000.0f * b2_lengthUnitsPerMeter ) // Maximum parallel workers. Used to size some static arrays. #define B2_MAX_WORKERS 64 // Maximum number of colors in the constraint graph. Constraints that cannot // find a color are added to the overflow set which are solved single-threaded. // The compound barrel benchmark has minor overflow with 24 colors #define B2_GRAPH_COLOR_COUNT 24 // A small length used as a collision and constraint tolerance. Usually it is // chosen to be numerically significant, but visually insignificant. In meters. // Normally this is 0.5cm. // @warning modifying this can have a significant impact on stability #define B2_LINEAR_SLOP ( 0.005f * b2_lengthUnitsPerMeter ) // Maximum number of simultaneous worlds that can be allocated #ifndef B2_MAX_WORLDS #define B2_MAX_WORLDS 128 #endif // The maximum rotation of a body per time step. This limit is very large and is used // to prevent numerical problems. You shouldn't need to adjust this. // @warning increasing this to 0.5f * b2_pi or greater will break continuous collision. #define B2_MAX_ROTATION ( 0.25f * B2_PI ) // Box2D uses limited speculative collision. This reduces jitter. // Normally this is 2cm. // @warning modifying this can have a significant impact on performance and stability #define B2_SPECULATIVE_DISTANCE ( 4.0f * B2_LINEAR_SLOP ) // This is used to fatten AABBs in the dynamic tree. This allows proxies // to move by a small amount without triggering a tree adjustment. This is in meters. // Normally this is 5cm. // @warning modifying this can have a significant impact on performance #define B2_AABB_MARGIN ( 0.05f * b2_lengthUnitsPerMeter ) // The time that a body must be still before it will go to sleep. In seconds. #define B2_TIME_TO_SLEEP 0.5f enum b2TreeNodeFlags { b2_allocatedNode = 0x0001, b2_enlargedNode = 0x0002, b2_leafNode = 0x0004, }; ================================================ FILE: src/constraint_graph.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "constraint_graph.h" #include "array.h" #include "bitset.h" #include "body.h" #include "contact.h" #include "joint.h" #include "physics_world.h" #include "solver_set.h" #include // Solver using graph coloring. Islands are only used for sleep. // High-Performance Physical Simulations on Next-Generation Architecture with Many Cores // http://web.eecs.umich.edu/~msmelyan/papers/physsim_onmanycore_itj.pdf // Kinematic bodies have to be treated like dynamic bodies in graph coloring. Unlike static bodies, we cannot use a dummy solver // body for kinematic bodies. We cannot access a kinematic body from multiple threads efficiently because the SIMD solver body // scatter would write to the same kinematic body from multiple threads. Even if these writes don't modify the body, they will // cause horrible cache stalls. To make this feasible I would need a way to block these writes. // todo should be possible to branch on the scatters to avoid writing to kinematic bodies // This is used for debugging by making all constraints be assigned to overflow. #define B2_FORCE_OVERFLOW 0 void b2CreateGraph( b2ConstraintGraph* graph, int bodyCapacity ) { _Static_assert( B2_GRAPH_COLOR_COUNT >= 2, "must have at least two constraint graph colors" ); _Static_assert( B2_OVERFLOW_INDEX == B2_GRAPH_COLOR_COUNT - 1, "bad over flow index" ); _Static_assert( B2_DYNAMIC_COLOR_COUNT >= 2, "need more dynamic colors" ); *graph = (b2ConstraintGraph){ 0 }; bodyCapacity = b2MaxInt( bodyCapacity, 8 ); // Initialize graph color bit set. // No bitset for overflow color. for ( int i = 0; i < B2_OVERFLOW_INDEX; ++i ) { b2GraphColor* color = graph->colors + i; color->bodySet = b2CreateBitSet( bodyCapacity ); b2SetBitCountAndClear( &color->bodySet, bodyCapacity ); } } void b2DestroyGraph( b2ConstraintGraph* graph ) { for ( int i = 0; i < B2_GRAPH_COLOR_COUNT; ++i ) { b2GraphColor* color = graph->colors + i; // The bit set should never be used on the overflow color B2_ASSERT( i != B2_OVERFLOW_INDEX || color->bodySet.bits == NULL ); b2DestroyBitSet( &color->bodySet ); b2ContactSimArray_Destroy( &color->contactSims ); b2JointSimArray_Destroy( &color->jointSims ); } } // Contacts are always created as non-touching. They get cloned into the constraint // graph once they are found to be touching. void b2AddContactToGraph( b2World* world, b2ContactSim* contactSim, b2Contact* contact ) { B2_ASSERT( contactSim->manifold.pointCount > 0 ); B2_ASSERT( contactSim->simFlags & b2_simTouchingFlag ); B2_ASSERT( contact->flags & b2_contactTouchingFlag ); b2ConstraintGraph* graph = &world->constraintGraph; int colorIndex = B2_OVERFLOW_INDEX; int bodyIdA = contact->edges[0].bodyId; int bodyIdB = contact->edges[1].bodyId; b2Body* bodyA = b2BodyArray_Get( &world->bodies, bodyIdA ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, bodyIdB ); b2BodyType typeA = bodyA->type; b2BodyType typeB = bodyB->type; B2_ASSERT( typeA == b2_dynamicBody || typeB == b2_dynamicBody ); #if B2_FORCE_OVERFLOW == 0 if (typeA == b2_dynamicBody && typeB == b2_dynamicBody) { // Dynamic constraint colors cannot encroach on colors reserved for static constraints for ( int i = 0; i < B2_DYNAMIC_COLOR_COUNT; ++i ) { b2GraphColor* color = graph->colors + i; if ( b2GetBit( &color->bodySet, bodyIdA ) || b2GetBit( &color->bodySet, bodyIdB ) ) { continue; } b2SetBitGrow( &color->bodySet, bodyIdA ); b2SetBitGrow( &color->bodySet, bodyIdB ); colorIndex = i; break; } } else if ( typeA == b2_dynamicBody ) { // Static constraint colors build from the end to get higher priority than dyn-dyn constraints for ( int i = B2_OVERFLOW_INDEX - 1; i >= 1; --i ) { b2GraphColor* color = graph->colors + i; if ( b2GetBit( &color->bodySet, bodyIdA ) ) { continue; } b2SetBitGrow( &color->bodySet, bodyIdA ); colorIndex = i; break; } } else if ( typeB == b2_dynamicBody ) { // Static constraint colors build from the end to get higher priority than dyn-dyn constraints for ( int i = B2_OVERFLOW_INDEX - 1; i >= 1; --i ) { b2GraphColor* color = graph->colors + i; if ( b2GetBit( &color->bodySet, bodyIdB ) ) { continue; } b2SetBitGrow( &color->bodySet, bodyIdB ); colorIndex = i; break; } } #endif b2GraphColor* color = graph->colors + colorIndex; contact->colorIndex = colorIndex; contact->localIndex = color->contactSims.count; b2ContactSim* newContact = b2ContactSimArray_Add( &color->contactSims ); memcpy( newContact, contactSim, sizeof( b2ContactSim ) ); // todo perhaps skip this if the contact is already awake if ( typeA == b2_staticBody ) { newContact->bodySimIndexA = B2_NULL_INDEX; newContact->invMassA = 0.0f; newContact->invIA = 0.0f; } else { B2_ASSERT( bodyA->setIndex == b2_awakeSet ); b2SolverSet* awakeSet = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); int localIndex = bodyA->localIndex; newContact->bodySimIndexA = localIndex; b2BodySim* bodySimA = b2BodySimArray_Get( &awakeSet->bodySims, localIndex ); newContact->invMassA = bodySimA->invMass; newContact->invIA = bodySimA->invInertia; } if ( typeB == b2_staticBody ) { newContact->bodySimIndexB = B2_NULL_INDEX; newContact->invMassB = 0.0f; newContact->invIB = 0.0f; } else { B2_ASSERT( bodyB->setIndex == b2_awakeSet ); b2SolverSet* awakeSet = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); int localIndex = bodyB->localIndex; newContact->bodySimIndexB = localIndex; b2BodySim* bodySimB = b2BodySimArray_Get( &awakeSet->bodySims, localIndex ); newContact->invMassB = bodySimB->invMass; newContact->invIB = bodySimB->invInertia; } } void b2RemoveContactFromGraph( b2World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex ) { b2ConstraintGraph* graph = &world->constraintGraph; B2_ASSERT( 0 <= colorIndex && colorIndex < B2_GRAPH_COLOR_COUNT ); b2GraphColor* color = graph->colors + colorIndex; if ( colorIndex != B2_OVERFLOW_INDEX ) { // This might clear a bit for a kinematic or static body, but this has no effect b2ClearBit( &color->bodySet, bodyIdA ); b2ClearBit( &color->bodySet, bodyIdB ); } int movedIndex = b2ContactSimArray_RemoveSwap( &color->contactSims, localIndex ); if ( movedIndex != B2_NULL_INDEX ) { // Fix index on swapped contact b2ContactSim* movedContactSim = color->contactSims.data + localIndex; // Fix moved contact int movedId = movedContactSim->contactId; b2Contact* movedContact = b2ContactArray_Get( &world->contacts, movedId ); B2_ASSERT( movedContact->setIndex == b2_awakeSet ); B2_ASSERT( movedContact->colorIndex == colorIndex ); B2_ASSERT( movedContact->localIndex == movedIndex ); movedContact->localIndex = localIndex; } } static int b2AssignJointColor( b2ConstraintGraph* graph, int bodyIdA, int bodyIdB, b2BodyType typeA, b2BodyType typeB ) { B2_ASSERT( typeA == b2_dynamicBody || typeB == b2_dynamicBody ); #if B2_FORCE_OVERFLOW == 0 if ( typeA == b2_dynamicBody && typeB == b2_dynamicBody ) { // Dynamic constraint colors cannot encroach on colors reserved for static constraints for ( int i = 0; i < B2_DYNAMIC_COLOR_COUNT; ++i ) { b2GraphColor* color = graph->colors + i; if ( b2GetBit( &color->bodySet, bodyIdA ) || b2GetBit( &color->bodySet, bodyIdB ) ) { continue; } b2SetBitGrow( &color->bodySet, bodyIdA ); b2SetBitGrow( &color->bodySet, bodyIdB ); return i; } } else if ( typeA == b2_dynamicBody ) { // Static constraint colors build from the end to get higher priority than dyn-dyn constraints for ( int i = B2_OVERFLOW_INDEX - 1; i >= 1; --i ) { b2GraphColor* color = graph->colors + i; if ( b2GetBit( &color->bodySet, bodyIdA ) ) { continue; } b2SetBitGrow( &color->bodySet, bodyIdA ); return i; } } else if ( typeB == b2_dynamicBody ) { // Static constraint colors build from the end to get higher priority than dyn-dyn constraints for ( int i = B2_OVERFLOW_INDEX - 1; i >= 1; --i ) { b2GraphColor* color = graph->colors + i; if ( b2GetBit( &color->bodySet, bodyIdB ) ) { continue; } b2SetBitGrow( &color->bodySet, bodyIdB ); return i; } } #else B2_UNUSED( graph, bodyIdA, bodyIdB ); #endif return B2_OVERFLOW_INDEX; } b2JointSim* b2CreateJointInGraph( b2World* world, b2Joint* joint ) { b2ConstraintGraph* graph = &world->constraintGraph; int bodyIdA = joint->edges[0].bodyId; int bodyIdB = joint->edges[1].bodyId; b2Body* bodyA = b2BodyArray_Get( &world->bodies, bodyIdA ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, bodyIdB ); int colorIndex = b2AssignJointColor( graph, bodyIdA, bodyIdB, bodyA->type, bodyB->type ); b2JointSim* jointSim = b2JointSimArray_Add( &graph->colors[colorIndex].jointSims ); memset( jointSim, 0, sizeof( b2JointSim ) ); joint->colorIndex = colorIndex; joint->localIndex = graph->colors[colorIndex].jointSims.count - 1; return jointSim; } void b2AddJointToGraph( b2World* world, b2JointSim* jointSim, b2Joint* joint ) { b2JointSim* jointDst = b2CreateJointInGraph( world, joint ); memcpy( jointDst, jointSim, sizeof( b2JointSim ) ); } void b2RemoveJointFromGraph( b2World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex ) { b2ConstraintGraph* graph = &world->constraintGraph; B2_ASSERT( 0 <= colorIndex && colorIndex < B2_GRAPH_COLOR_COUNT ); b2GraphColor* color = graph->colors + colorIndex; if ( colorIndex != B2_OVERFLOW_INDEX ) { // May clear static bodies, no effect b2ClearBit( &color->bodySet, bodyIdA ); b2ClearBit( &color->bodySet, bodyIdB ); } int movedIndex = b2JointSimArray_RemoveSwap( &color->jointSims, localIndex ); if ( movedIndex != B2_NULL_INDEX ) { // Fix moved joint b2JointSim* movedJointSim = color->jointSims.data + localIndex; int movedId = movedJointSim->jointId; b2Joint* movedJoint = b2JointArray_Get( &world->joints, movedId ); B2_ASSERT( movedJoint->setIndex == b2_awakeSet ); B2_ASSERT( movedJoint->colorIndex == colorIndex ); B2_ASSERT( movedJoint->localIndex == movedIndex ); movedJoint->localIndex = localIndex; } } b2HexColor b2_graphColors[B2_GRAPH_COLOR_COUNT] = { b2_colorRed, b2_colorOrange, b2_colorYellow, b2_colorGreen, b2_colorCyan, b2_colorBlue, b2_colorViolet, b2_colorPink, b2_colorChocolate, b2_colorGoldenRod, b2_colorCoral, b2_colorRosyBrown, b2_colorAqua, b2_colorPeru, b2_colorLime, b2_colorGold, b2_colorPlum, b2_colorSnow, b2_colorTeal, b2_colorKhaki, b2_colorSalmon, b2_colorPeachPuff, b2_colorHoneyDew, b2_colorBlack, }; ================================================ FILE: src/constraint_graph.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "array.h" #include "bitset.h" #include "constants.h" #include "box2d/types.h" typedef struct b2Body b2Body; typedef struct b2ContactSim b2ContactSim; typedef struct b2Contact b2Contact; typedef struct b2ContactConstraint b2ContactConstraint; typedef struct b2ContactConstraintSIMD b2ContactConstraintSIMD; typedef struct b2JointSim b2JointSim; typedef struct b2Joint b2Joint; typedef struct b2StepContext b2StepContext; typedef struct b2World b2World; // This holds constraints that cannot fit the graph color limit. This happens when a single dynamic body // is touching many other bodies. #define B2_OVERFLOW_INDEX (B2_GRAPH_COLOR_COUNT - 1) // This keeps constraints involving two dynamic bodies at a lower solver priority than constraints // involving a dynamic and static bodies. This reduces tunneling due to push through. #define B2_DYNAMIC_COLOR_COUNT (B2_GRAPH_COLOR_COUNT - 4) typedef struct b2GraphColor { // This bitset is indexed by bodyId so this is over-sized to encompass static bodies // however I never traverse these bits or use the bit count for anything // This bitset is unused on the overflow color. // // Dirk suggested having a uint64_t per body that tracks the graph color membership // but I think this would make debugging harder and be less flexible. With the bitset // I can trivially increase the number of graph colors beyond 64. See usage of b2CountSetBits // for validation. b2BitSet bodySet; // cache friendly arrays b2ContactSimArray contactSims; b2JointSimArray jointSims; // transient union { b2ContactConstraintSIMD* simdConstraints; b2ContactConstraint* overflowConstraints; }; } b2GraphColor; typedef struct b2ConstraintGraph { // including overflow at the end b2GraphColor colors[B2_GRAPH_COLOR_COUNT]; } b2ConstraintGraph; void b2CreateGraph( b2ConstraintGraph* graph, int bodyCapacity ); void b2DestroyGraph( b2ConstraintGraph* graph ); void b2AddContactToGraph( b2World* world, b2ContactSim* contactSim, b2Contact* contact ); void b2RemoveContactFromGraph( b2World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex ); b2JointSim* b2CreateJointInGraph( b2World* world, b2Joint* joint ); void b2AddJointToGraph( b2World* world, b2JointSim* jointSim, b2Joint* joint ); void b2RemoveJointFromGraph( b2World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex ); extern b2HexColor b2_graphColors[B2_GRAPH_COLOR_COUNT]; ================================================ FILE: src/contact.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "contact.h" #include "array.h" #include "body.h" #include "core.h" #include "island.h" #include "physics_world.h" #include "shape.h" #include "solver_set.h" #include "table.h" // needed for dll export #include "box2d/box2d.h" #include B2_ARRAY_SOURCE( b2Contact, b2Contact ) B2_ARRAY_SOURCE( b2ContactSim, b2ContactSim ) // Contacts and determinism // A deterministic simulation requires contacts to exist in the same order in b2Island no matter the thread count. // The order must reproduce from run to run. This is necessary because the Gauss-Seidel constraint solver is order dependent. // // Creation: // - Contacts are created using results from b2UpdateBroadPhasePairs // - These results are ordered according to the order of the broad-phase move array // - The move array is ordered according to the shape creation order using a bitset. // - The island/shape/body order is determined by creation order // - Logically contacts are only created for awake bodies, so they are immediately added to the awake contact array (serially) // // Island linking: // - The awake contact array is built from the body-contact graph for all awake bodies in awake islands. // - Awake contacts are solved in parallel and they generate contact state changes. // - These state changes may link islands together using union find. // - The state changes are ordered using a bit array that encompasses all contacts // - As long as contacts are created in deterministic order, island link order is deterministic. // - This keeps the order of contacts in islands deterministic // Manifold functions should compute important results in local space to improve precision. However, this // interface function takes two world transforms instead of a relative transform for these reasons: // // First: // The anchors need to be computed relative to the shape origin in world space. This is necessary so the // solver does not need to access static body transforms. Not even in constraint preparation. This approach // has world space vectors yet retains precision. // // Second: // b2ManifoldPoint::point is very useful for debugging and it is in world space. // // Third: // The user may call the manifold functions directly and they should be easy to use and have easy to use // results. static b2Contact* b2GetContactFullId( b2World* world, b2ContactId contactId ) { int id = contactId.index1 - 1; b2Contact* contact = b2ContactArray_Get( &world->contacts, id ); B2_ASSERT( contact->contactId == id && contact->generation == contactId.generation ); return contact; } b2ContactData b2Contact_GetData( b2ContactId contactId ) { b2World* world = b2GetWorld( contactId.world0 ); b2Contact* contact = b2GetContactFullId( world, contactId ); b2ContactSim* contactSim = b2GetContactSim( world, contact ); const b2Shape* shapeA = b2ShapeArray_Get( &world->shapes, contact->shapeIdA ); const b2Shape* shapeB = b2ShapeArray_Get( &world->shapes, contact->shapeIdB ); b2ContactData data = { .contactId = contactId, .shapeIdA = { .index1 = shapeA->id + 1, .world0 = (uint16_t)contactId.world0, .generation = shapeA->generation, }, .shapeIdB = { .index1 = shapeB->id + 1, .world0 = (uint16_t)contactId.world0, .generation = shapeB->generation, }, .manifold = contactSim->manifold, }; return data; } typedef b2Manifold b2ManifoldFcn( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, b2SimplexCache* cache ); struct b2ContactRegister { b2ManifoldFcn* fcn; bool primary; }; static struct b2ContactRegister s_registers[b2_shapeTypeCount][b2_shapeTypeCount]; static bool s_initialized = false; static b2Manifold b2CircleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, b2SimplexCache* cache ) { B2_UNUSED( cache ); return b2CollideCircles( &shapeA->circle, xfA, &shapeB->circle, xfB ); } static b2Manifold b2CapsuleAndCircleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, b2SimplexCache* cache ) { B2_UNUSED( cache ); return b2CollideCapsuleAndCircle( &shapeA->capsule, xfA, &shapeB->circle, xfB ); } static b2Manifold b2CapsuleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, b2SimplexCache* cache ) { B2_UNUSED( cache ); return b2CollideCapsules( &shapeA->capsule, xfA, &shapeB->capsule, xfB ); } static b2Manifold b2PolygonAndCircleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, b2SimplexCache* cache ) { B2_UNUSED( cache ); return b2CollidePolygonAndCircle( &shapeA->polygon, xfA, &shapeB->circle, xfB ); } static b2Manifold b2PolygonAndCapsuleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, b2SimplexCache* cache ) { B2_UNUSED( cache ); return b2CollidePolygonAndCapsule( &shapeA->polygon, xfA, &shapeB->capsule, xfB ); } static b2Manifold b2PolygonManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, b2SimplexCache* cache ) { B2_UNUSED( cache ); return b2CollidePolygons( &shapeA->polygon, xfA, &shapeB->polygon, xfB ); } static b2Manifold b2SegmentAndCircleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, b2SimplexCache* cache ) { B2_UNUSED( cache ); return b2CollideSegmentAndCircle( &shapeA->segment, xfA, &shapeB->circle, xfB ); } static b2Manifold b2SegmentAndCapsuleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, b2SimplexCache* cache ) { B2_UNUSED( cache ); return b2CollideSegmentAndCapsule( &shapeA->segment, xfA, &shapeB->capsule, xfB ); } static b2Manifold b2SegmentAndPolygonManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, b2SimplexCache* cache ) { B2_UNUSED( cache ); return b2CollideSegmentAndPolygon( &shapeA->segment, xfA, &shapeB->polygon, xfB ); } static b2Manifold b2ChainSegmentAndCircleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, b2SimplexCache* cache ) { B2_UNUSED( cache ); return b2CollideChainSegmentAndCircle( &shapeA->chainSegment, xfA, &shapeB->circle, xfB ); } static b2Manifold b2ChainSegmentAndCapsuleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, b2SimplexCache* cache ) { return b2CollideChainSegmentAndCapsule( &shapeA->chainSegment, xfA, &shapeB->capsule, xfB, cache ); } static b2Manifold b2ChainSegmentAndPolygonManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, b2SimplexCache* cache ) { return b2CollideChainSegmentAndPolygon( &shapeA->chainSegment, xfA, &shapeB->polygon, xfB, cache ); } static void b2AddType( b2ManifoldFcn* fcn, b2ShapeType type1, b2ShapeType type2 ) { B2_ASSERT( 0 <= type1 && type1 < b2_shapeTypeCount ); B2_ASSERT( 0 <= type2 && type2 < b2_shapeTypeCount ); s_registers[type1][type2].fcn = fcn; s_registers[type1][type2].primary = true; if ( type1 != type2 ) { s_registers[type2][type1].fcn = fcn; s_registers[type2][type1].primary = false; } } void b2InitializeContactRegisters( void ) { if ( s_initialized == false ) { b2AddType( b2CircleManifold, b2_circleShape, b2_circleShape ); b2AddType( b2CapsuleAndCircleManifold, b2_capsuleShape, b2_circleShape ); b2AddType( b2CapsuleManifold, b2_capsuleShape, b2_capsuleShape ); b2AddType( b2PolygonAndCircleManifold, b2_polygonShape, b2_circleShape ); b2AddType( b2PolygonAndCapsuleManifold, b2_polygonShape, b2_capsuleShape ); b2AddType( b2PolygonManifold, b2_polygonShape, b2_polygonShape ); b2AddType( b2SegmentAndCircleManifold, b2_segmentShape, b2_circleShape ); b2AddType( b2SegmentAndCapsuleManifold, b2_segmentShape, b2_capsuleShape ); b2AddType( b2SegmentAndPolygonManifold, b2_segmentShape, b2_polygonShape ); b2AddType( b2ChainSegmentAndCircleManifold, b2_chainSegmentShape, b2_circleShape ); b2AddType( b2ChainSegmentAndCapsuleManifold, b2_chainSegmentShape, b2_capsuleShape ); b2AddType( b2ChainSegmentAndPolygonManifold, b2_chainSegmentShape, b2_polygonShape ); s_initialized = true; } } void b2CreateContact( b2World* world, b2Shape* shapeA, b2Shape* shapeB ) { b2ShapeType type1 = shapeA->type; b2ShapeType type2 = shapeB->type; B2_ASSERT( 0 <= type1 && type1 < b2_shapeTypeCount ); B2_ASSERT( 0 <= type2 && type2 < b2_shapeTypeCount ); if ( s_registers[type1][type2].fcn == NULL ) { // For example, no segment vs segment collision return; } if ( s_registers[type1][type2].primary == false ) { // flip order b2CreateContact( world, shapeB, shapeA ); return; } b2Body* bodyA = b2BodyArray_Get( &world->bodies, shapeA->bodyId ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, shapeB->bodyId ); B2_ASSERT( bodyA->setIndex != b2_disabledSet && bodyB->setIndex != b2_disabledSet ); B2_ASSERT( bodyA->setIndex != b2_staticSet || bodyB->setIndex != b2_staticSet ); int setIndex; if ( bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet ) { setIndex = b2_awakeSet; } else { // sleeping and non-touching contacts live in the disabled set // later if this set is found to be touching then the sleeping // islands will be linked and the contact moved to the merged island setIndex = b2_disabledSet; } b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, setIndex ); // Create contact key and contact int contactId = b2AllocId( &world->contactIdPool ); if ( contactId == world->contacts.count ) { b2ContactArray_Push( &world->contacts, (b2Contact){ 0 } ); } int shapeIdA = shapeA->id; int shapeIdB = shapeB->id; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); contact->contactId = contactId; contact->generation += 1; contact->setIndex = setIndex; contact->colorIndex = B2_NULL_INDEX; contact->localIndex = set->contactSims.count; contact->islandId = B2_NULL_INDEX; contact->islandPrev = B2_NULL_INDEX; contact->islandNext = B2_NULL_INDEX; contact->shapeIdA = shapeIdA; contact->shapeIdB = shapeIdB; //contact->isMarked = false; contact->flags = 0; B2_ASSERT( shapeA->sensorIndex == B2_NULL_INDEX && shapeB->sensorIndex == B2_NULL_INDEX ); if ( shapeA->enableContactEvents || shapeB->enableContactEvents ) { contact->flags |= b2_contactEnableContactEvents; } // Connect to body A { contact->edges[0].bodyId = shapeA->bodyId; contact->edges[0].prevKey = B2_NULL_INDEX; contact->edges[0].nextKey = bodyA->headContactKey; int keyA = ( contactId << 1 ) | 0; int headContactKey = bodyA->headContactKey; if ( headContactKey != B2_NULL_INDEX ) { b2Contact* headContact = b2ContactArray_Get( &world->contacts, headContactKey >> 1 ); headContact->edges[headContactKey & 1].prevKey = keyA; } bodyA->headContactKey = keyA; bodyA->contactCount += 1; } // Connect to body B { contact->edges[1].bodyId = shapeB->bodyId; contact->edges[1].prevKey = B2_NULL_INDEX; contact->edges[1].nextKey = bodyB->headContactKey; int keyB = ( contactId << 1 ) | 1; int headContactKey = bodyB->headContactKey; if ( bodyB->headContactKey != B2_NULL_INDEX ) { b2Contact* headContact = b2ContactArray_Get( &world->contacts, headContactKey >> 1 ); headContact->edges[headContactKey & 1].prevKey = keyB; } bodyB->headContactKey = keyB; bodyB->contactCount += 1; } // Add to pair set for fast lookup uint64_t pairKey = B2_SHAPE_PAIR_KEY( shapeIdA, shapeIdB ); b2AddKey( &world->broadPhase.pairSet, pairKey ); // Contacts are created as non-touching. Later if they are found to be touching // they will link islands and be moved into the constraint graph. b2ContactSim* contactSim = b2ContactSimArray_Add( &set->contactSims ); contactSim->contactId = contactId; #if B2_VALIDATE contactSim->bodyIdA = shapeA->bodyId; contactSim->bodyIdB = shapeB->bodyId; #endif contactSim->bodySimIndexA = B2_NULL_INDEX; contactSim->bodySimIndexB = B2_NULL_INDEX; contactSim->invMassA = 0.0f; contactSim->invIA = 0.0f; contactSim->invMassB = 0.0f; contactSim->invIB = 0.0f; contactSim->shapeIdA = shapeIdA; contactSim->shapeIdB = shapeIdB; contactSim->cache = b2_emptySimplexCache; contactSim->manifold = (b2Manifold){ 0 }; // These also get updated in the narrow phase contactSim->friction = world->frictionCallback( shapeA->material.friction, shapeA->material.userMaterialId, shapeB->material.friction, shapeB->material.userMaterialId ); contactSim->restitution = world->restitutionCallback( shapeA->material.restitution, shapeA->material.userMaterialId, shapeB->material.restitution, shapeB->material.userMaterialId ); contactSim->tangentSpeed = 0.0f; contactSim->simFlags = 0; if ( shapeA->enablePreSolveEvents || shapeB->enablePreSolveEvents ) { contactSim->simFlags |= b2_simEnablePreSolveEvents; } } // A contact is destroyed when: // - broad-phase proxies stop overlapping // - a body is destroyed // - a body is disabled // - a body changes type from dynamic to kinematic or static // - a shape is destroyed // - contact filtering is modified void b2DestroyContact( b2World* world, b2Contact* contact, bool wakeBodies ) { // Remove pair from set uint64_t pairKey = B2_SHAPE_PAIR_KEY( contact->shapeIdA, contact->shapeIdB ); b2RemoveKey( &world->broadPhase.pairSet, pairKey ); b2ContactEdge* edgeA = contact->edges + 0; b2ContactEdge* edgeB = contact->edges + 1; int bodyIdA = edgeA->bodyId; int bodyIdB = edgeB->bodyId; b2Body* bodyA = b2BodyArray_Get( &world->bodies, bodyIdA ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, bodyIdB ); uint32_t flags = contact->flags; bool touching = ( flags & b2_contactTouchingFlag ) != 0; // End touch event if ( touching && ( flags & b2_contactEnableContactEvents ) != 0 ) { uint16_t worldId = world->worldId; const b2Shape* shapeA = b2ShapeArray_Get( &world->shapes, contact->shapeIdA ); const b2Shape* shapeB = b2ShapeArray_Get( &world->shapes, contact->shapeIdB ); b2ShapeId shapeIdA = { shapeA->id + 1, worldId, shapeA->generation }; b2ShapeId shapeIdB = { shapeB->id + 1, worldId, shapeB->generation }; b2ContactId contactId = { .index1 = contact->contactId + 1, .world0 = world->worldId, .padding = 0, .generation = contact->generation, }; b2ContactEndTouchEvent event = { .shapeIdA = shapeIdA, .shapeIdB = shapeIdB, .contactId = contactId, }; b2ContactEndTouchEventArray_Push( world->contactEndEvents + world->endEventArrayIndex, event ); } // Remove from body A if ( edgeA->prevKey != B2_NULL_INDEX ) { b2Contact* prevContact = b2ContactArray_Get( &world->contacts, edgeA->prevKey >> 1 ); b2ContactEdge* prevEdge = prevContact->edges + ( edgeA->prevKey & 1 ); prevEdge->nextKey = edgeA->nextKey; } if ( edgeA->nextKey != B2_NULL_INDEX ) { b2Contact* nextContact = b2ContactArray_Get( &world->contacts, edgeA->nextKey >> 1 ); b2ContactEdge* nextEdge = nextContact->edges + ( edgeA->nextKey & 1 ); nextEdge->prevKey = edgeA->prevKey; } int contactId = contact->contactId; int edgeKeyA = ( contactId << 1 ) | 0; if ( bodyA->headContactKey == edgeKeyA ) { bodyA->headContactKey = edgeA->nextKey; } bodyA->contactCount -= 1; // Remove from body B if ( edgeB->prevKey != B2_NULL_INDEX ) { b2Contact* prevContact = b2ContactArray_Get( &world->contacts, edgeB->prevKey >> 1 ); b2ContactEdge* prevEdge = prevContact->edges + ( edgeB->prevKey & 1 ); prevEdge->nextKey = edgeB->nextKey; } if ( edgeB->nextKey != B2_NULL_INDEX ) { b2Contact* nextContact = b2ContactArray_Get( &world->contacts, edgeB->nextKey >> 1 ); b2ContactEdge* nextEdge = nextContact->edges + ( edgeB->nextKey & 1 ); nextEdge->prevKey = edgeB->prevKey; } int edgeKeyB = ( contactId << 1 ) | 1; if ( bodyB->headContactKey == edgeKeyB ) { bodyB->headContactKey = edgeB->nextKey; } bodyB->contactCount -= 1; // Remove contact from the array that owns it if ( contact->islandId != B2_NULL_INDEX ) { b2UnlinkContact( world, contact ); } if ( contact->colorIndex != B2_NULL_INDEX ) { // contact is an active constraint B2_ASSERT( contact->setIndex == b2_awakeSet ); b2RemoveContactFromGraph( world, bodyIdA, bodyIdB, contact->colorIndex, contact->localIndex ); } else { // contact is non-touching or is sleeping B2_ASSERT( contact->setIndex != b2_awakeSet || ( contact->flags & b2_contactTouchingFlag ) == 0 ); b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, contact->setIndex ); int movedIndex = b2ContactSimArray_RemoveSwap( &set->contactSims, contact->localIndex ); if ( movedIndex != B2_NULL_INDEX ) { b2ContactSim* movedContactSim = set->contactSims.data + contact->localIndex; b2Contact* movedContact = b2ContactArray_Get( &world->contacts, movedContactSim->contactId ); movedContact->localIndex = contact->localIndex; } } // Free contact and id (preserve generation) contact->contactId = B2_NULL_INDEX; contact->setIndex = B2_NULL_INDEX; contact->colorIndex = B2_NULL_INDEX; contact->localIndex = B2_NULL_INDEX; b2FreeId( &world->contactIdPool, contactId ); if ( wakeBodies && touching ) { b2WakeBody( world, bodyA ); b2WakeBody( world, bodyB ); } } b2ContactSim* b2GetContactSim( b2World* world, b2Contact* contact ) { if ( contact->setIndex == b2_awakeSet && contact->colorIndex != B2_NULL_INDEX ) { // contact lives in constraint graph B2_ASSERT( 0 <= contact->colorIndex && contact->colorIndex < B2_GRAPH_COLOR_COUNT ); b2GraphColor* color = world->constraintGraph.colors + contact->colorIndex; return b2ContactSimArray_Get( &color->contactSims, contact->localIndex ); } b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, contact->setIndex ); return b2ContactSimArray_Get( &set->contactSims, contact->localIndex ); } // Update the contact manifold and touching status. // Note: do not assume the shape AABBs are overlapping or are valid. bool b2UpdateContact( b2World* world, b2ContactSim* contactSim, b2Shape* shapeA, b2Transform transformA, b2Vec2 centerOffsetA, b2Shape* shapeB, b2Transform transformB, b2Vec2 centerOffsetB ) { // Save old manifold b2Manifold oldManifold = contactSim->manifold; // Compute new manifold b2ManifoldFcn* fcn = s_registers[shapeA->type][shapeB->type].fcn; contactSim->manifold = fcn( shapeA, transformA, shapeB, transformB, &contactSim->cache ); // Keep these updated in case the values on the shapes are modified contactSim->friction = world->frictionCallback( shapeA->material.friction, shapeA->material.userMaterialId, shapeB->material.friction, shapeB->material.userMaterialId ); contactSim->restitution = world->restitutionCallback( shapeA->material.restitution, shapeA->material.userMaterialId, shapeB->material.restitution, shapeB->material.userMaterialId ); if ( shapeA->material.rollingResistance > 0.0f || shapeB->material.rollingResistance > 0.0f ) { float radiusA = b2GetShapeRadius( shapeA ); float radiusB = b2GetShapeRadius( shapeB ); float maxRadius = b2MaxFloat( radiusA, radiusB ); contactSim->rollingResistance = b2MaxFloat( shapeA->material.rollingResistance, shapeB->material.rollingResistance ) * maxRadius; } else { contactSim->rollingResistance = 0.0f; } contactSim->tangentSpeed = shapeA->material.tangentSpeed + shapeB->material.tangentSpeed; int pointCount = contactSim->manifold.pointCount; bool touching = pointCount > 0; if ( touching && world->preSolveFcn != NULL && ( contactSim->simFlags & b2_simEnablePreSolveEvents ) != 0 ) { b2ShapeId shapeIdA = { shapeA->id + 1, world->worldId, shapeA->generation }; b2ShapeId shapeIdB = { shapeB->id + 1, world->worldId, shapeB->generation }; b2Manifold* manifold = &contactSim->manifold; float bestSeparation = manifold->points[0].separation; b2Vec2 bestPoint = manifold->points[0].point; // Get deepest point for ( int i = 1; i < manifold->pointCount; ++i ) { float separation = manifold->points[i].separation; if ( separation < bestSeparation ) { bestSeparation = separation; bestPoint = manifold->points[i].point; } } // this call assumes thread safety touching = world->preSolveFcn( shapeIdA, shapeIdB, bestPoint, manifold->normal, world->preSolveContext ); if ( touching == false ) { // disable contact pointCount = 0; manifold->pointCount = 0; } } // This flag is for testing if ( world->enableSpeculative == false && pointCount == 2 ) { if ( contactSim->manifold.points[0].separation > 1.5f * B2_LINEAR_SLOP ) { contactSim->manifold.points[0] = contactSim->manifold.points[1]; contactSim->manifold.pointCount = 1; } else if ( contactSim->manifold.points[0].separation > 1.5f * B2_LINEAR_SLOP ) { contactSim->manifold.pointCount = 1; } pointCount = contactSim->manifold.pointCount; } if ( touching && ( shapeA->enableHitEvents || shapeB->enableHitEvents ) ) { contactSim->simFlags |= b2_simEnableHitEvent; } else { contactSim->simFlags &= ~b2_simEnableHitEvent; } if ( pointCount > 0 ) { contactSim->manifold.rollingImpulse = oldManifold.rollingImpulse; } // Match old contact ids to new contact ids and copy the // stored impulses to warm start the solver. int unmatchedCount = 0; for ( int i = 0; i < pointCount; ++i ) { b2ManifoldPoint* mp2 = contactSim->manifold.points + i; // shift anchors to be center of mass relative mp2->anchorA = b2Sub( mp2->anchorA, centerOffsetA ); mp2->anchorB = b2Sub( mp2->anchorB, centerOffsetB ); mp2->normalImpulse = 0.0f; mp2->tangentImpulse = 0.0f; mp2->totalNormalImpulse = 0.0f; mp2->normalVelocity = 0.0f; mp2->persisted = false; uint16_t id2 = mp2->id; for ( int j = 0; j < oldManifold.pointCount; ++j ) { b2ManifoldPoint* mp1 = oldManifold.points + j; if ( mp1->id == id2 ) { mp2->normalImpulse = mp1->normalImpulse; mp2->tangentImpulse = mp1->tangentImpulse; mp2->persisted = true; // clear old impulse mp1->normalImpulse = 0.0f; mp1->tangentImpulse = 0.0f; break; } } unmatchedCount += mp2->persisted ? 0 : 1; } B2_UNUSED( unmatchedCount ); #if 0 // todo I haven't found an improvement from this yet // If there are unmatched new contact points, apply any left over old impulse. if (unmatchedCount > 0) { float unmatchedNormalImpulse = 0.0f; float unmatchedTangentImpulse = 0.0f; for (int i = 0; i < oldManifold.pointCount; ++i) { b2ManifoldPoint* mp = oldManifold.points + i; unmatchedNormalImpulse += mp->normalImpulse; unmatchedTangentImpulse += mp->tangentImpulse; } float inverse = 1.0f / unmatchedCount; unmatchedNormalImpulse *= inverse; unmatchedTangentImpulse *= inverse; for ( int i = 0; i < pointCount; ++i ) { b2ManifoldPoint* mp2 = contactSim->manifold.points + i; if (mp2->persisted) { continue; } mp2->normalImpulse = unmatchedNormalImpulse; mp2->tangentImpulse = unmatchedTangentImpulse; } } #endif if ( touching ) { contactSim->simFlags |= b2_simTouchingFlag; } else { contactSim->simFlags &= ~b2_simTouchingFlag; } return touching; } ================================================ FILE: src/contact.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "array.h" #include "core.h" #include "box2d/collision.h" #include "box2d/types.h" typedef struct b2Shape b2Shape; typedef struct b2World b2World; enum b2ContactFlags { // Set when the solid shapes are touching. b2_contactTouchingFlag = 0x00000001, // Contact has a hit event b2_contactHitEventFlag = 0x00000002, // This contact wants contact events b2_contactEnableContactEvents = 0x00000004, }; // A contact edge is used to connect bodies and contacts together // in a contact graph where each body is a node and each contact // is an edge. A contact edge belongs to a doubly linked list // maintained in each attached body. Each contact has two contact // edges, one for each attached body. typedef struct b2ContactEdge { int bodyId; int prevKey; int nextKey; } b2ContactEdge; // Cold contact data. Used as a persistent handle and for persistent island // connectivity. typedef struct b2Contact { // index of simulation set stored in b2World // B2_NULL_INDEX when slot is free int setIndex; // index into the constraint graph color array // B2_NULL_INDEX for non-touching or sleeping contacts // B2_NULL_INDEX when slot is free int colorIndex; // contact index within set or graph color // B2_NULL_INDEX when slot is free int localIndex; int shapeIdA; int shapeIdB; int contactId; // A contact only belongs to an island if touching, otherwise B2_NULL_INDEX. b2ContactEdge edges[2]; int islandPrev; int islandNext; int islandId; // b2ContactFlags uint32_t flags; // This is monotonically advanced when a contact is allocated in this slot // Used to check for invalid b2ContactId uint32_t generation; } b2Contact; // Shifted to be distinct from b2ContactFlags enum b2ContactSimFlags { // Set when the shapes are touching b2_simTouchingFlag = 0x00010000, // This contact no longer has overlapping AABBs b2_simDisjoint = 0x00020000, // This contact started touching b2_simStartedTouching = 0x00040000, // This contact stopped touching b2_simStoppedTouching = 0x00080000, // This contact has a hit event b2_simEnableHitEvent = 0x00100000, // This contact wants pre-solve events b2_simEnablePreSolveEvents = 0x00200000, }; /// The class manages contact between two shapes. A contact exists for each overlapping /// AABB in the broad-phase (except if filtered). Therefore a contact object may exist /// that has no contact points. typedef struct b2ContactSim { int contactId; #if B2_VALIDATE int bodyIdA; int bodyIdB; #endif // Transient body indices int bodySimIndexA; int bodySimIndexB; int shapeIdA; int shapeIdB; float invMassA; float invIA; float invMassB; float invIB; b2Manifold manifold; // Mixed friction and restitution float friction; float restitution; float rollingResistance; float tangentSpeed; // b2ContactSimFlags uint32_t simFlags; b2SimplexCache cache; } b2ContactSim; void b2InitializeContactRegisters( void ); void b2CreateContact( b2World* world, b2Shape* shapeA, b2Shape* shapeB ); void b2DestroyContact( b2World* world, b2Contact* contact, bool wakeBodies ); b2ContactSim* b2GetContactSim( b2World* world, b2Contact* contact ); bool b2UpdateContact( b2World* world, b2ContactSim* contactSim, b2Shape* shapeA, b2Transform transformA, b2Vec2 centerOffsetA, b2Shape* shapeB, b2Transform transformB, b2Vec2 centerOffsetB ); B2_ARRAY_INLINE( b2Contact, b2Contact ) B2_ARRAY_INLINE( b2ContactSim, b2ContactSim ) ================================================ FILE: src/contact_solver.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "contact_solver.h" #include "body.h" #include "constraint_graph.h" #include "contact.h" #include "core.h" #include "physics_world.h" #include "solver_set.h" #include // contact separation for sub-stepping // s = s0 + dot(cB + rB - cA - rA, normal) // normal is held constant // body positions c can translation and anchors r can rotate // s(t) = s0 + dot(cB(t) + rB(t) - cA(t) - rA(t), normal) // s(t) = s0 + dot(cB0 + dpB + rot(dqB, rB0) - cA0 - dpA - rot(dqA, rA0), normal) // s(t) = s0 + dot(cB0 - cA0, normal) + dot(dpB - dpA + rot(dqB, rB0) - rot(dqA, rA0), normal) // s_base = s0 + dot(cB0 - cA0, normal) void b2PrepareOverflowContacts( b2StepContext* context ) { b2TracyCZoneNC( prepare_overflow_contact, "Prepare Overflow Contact", b2_colorYellow, true ); b2World* world = context->world; b2ConstraintGraph* graph = context->graph; b2GraphColor* color = graph->colors + B2_OVERFLOW_INDEX; b2ContactConstraint* constraints = color->overflowConstraints; int contactCount = color->contactSims.count; b2ContactSim* contacts = color->contactSims.data; b2BodyState* awakeStates = context->states; #if B2_VALIDATE b2Body* bodies = world->bodies.data; #endif // Stiffer for static contacts to avoid bodies getting pushed through the ground b2Softness contactSoftness = context->contactSoftness; b2Softness staticSoftness = context->staticSoftness; float warmStartScale = world->enableWarmStarting ? 1.0f : 0.0f; for ( int i = 0; i < contactCount; ++i ) { b2ContactSim* contactSim = contacts + i; const b2Manifold* manifold = &contactSim->manifold; int pointCount = manifold->pointCount; B2_ASSERT( 0 < pointCount && pointCount <= 2 ); int indexA = contactSim->bodySimIndexA; int indexB = contactSim->bodySimIndexB; #if B2_VALIDATE b2Body* bodyA = bodies + contactSim->bodyIdA; int validIndexA = bodyA->setIndex == b2_awakeSet ? bodyA->localIndex : B2_NULL_INDEX; B2_ASSERT( indexA == validIndexA ); b2Body* bodyB = bodies + contactSim->bodyIdB; int validIndexB = bodyB->setIndex == b2_awakeSet ? bodyB->localIndex : B2_NULL_INDEX; B2_ASSERT( indexB == validIndexB ); #endif b2ContactConstraint* constraint = constraints + i; constraint->indexA = indexA; constraint->indexB = indexB; constraint->normal = manifold->normal; constraint->friction = contactSim->friction; constraint->restitution = contactSim->restitution; constraint->rollingResistance = contactSim->rollingResistance; constraint->rollingImpulse = warmStartScale * manifold->rollingImpulse; constraint->tangentSpeed = contactSim->tangentSpeed; constraint->pointCount = pointCount; b2Vec2 vA = b2Vec2_zero; float wA = 0.0f; float mA = contactSim->invMassA; float iA = contactSim->invIA; if ( indexA != B2_NULL_INDEX ) { b2BodyState* stateA = awakeStates + indexA; vA = stateA->linearVelocity; wA = stateA->angularVelocity; } b2Vec2 vB = b2Vec2_zero; float wB = 0.0f; float mB = contactSim->invMassB; float iB = contactSim->invIB; if ( indexB != B2_NULL_INDEX ) { b2BodyState* stateB = awakeStates + indexB; vB = stateB->linearVelocity; wB = stateB->angularVelocity; } if ( indexA == B2_NULL_INDEX || indexB == B2_NULL_INDEX ) { constraint->softness = staticSoftness; } else { constraint->softness = contactSoftness; } // copy mass into constraint to avoid cache misses during sub-stepping constraint->invMassA = mA; constraint->invIA = iA; constraint->invMassB = mB; constraint->invIB = iB; { float k = iA + iB; constraint->rollingMass = k > 0.0f ? 1.0f / k : 0.0f; } b2Vec2 normal = constraint->normal; b2Vec2 tangent = b2RightPerp( constraint->normal ); for ( int j = 0; j < pointCount; ++j ) { const b2ManifoldPoint* mp = manifold->points + j; b2ContactConstraintPoint* cp = constraint->points + j; cp->normalImpulse = warmStartScale * mp->normalImpulse; cp->tangentImpulse = warmStartScale * mp->tangentImpulse; cp->totalNormalImpulse = 0.0f; b2Vec2 rA = mp->anchorA; b2Vec2 rB = mp->anchorB; cp->anchorA = rA; cp->anchorB = rB; cp->baseSeparation = mp->separation - b2Dot( b2Sub( rB, rA ), normal ); float rnA = b2Cross( rA, normal ); float rnB = b2Cross( rB, normal ); float kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; cp->normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; float rtA = b2Cross( rA, tangent ); float rtB = b2Cross( rB, tangent ); float kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; cp->tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; // Save relative velocity for restitution b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) ); b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) ); cp->relativeVelocity = b2Dot( normal, b2Sub( vrB, vrA ) ); } } b2TracyCZoneEnd( prepare_overflow_contact ); } void b2WarmStartOverflowContacts( b2StepContext* context ) { b2TracyCZoneNC( warmstart_overflow_contact, "WarmStart Overflow Contact", b2_colorDarkOrange, true ); b2ConstraintGraph* graph = context->graph; b2GraphColor* color = graph->colors + B2_OVERFLOW_INDEX; b2ContactConstraint* constraints = color->overflowConstraints; int contactCount = color->contactSims.count; b2World* world = context->world; b2SolverSet* awakeSet = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); b2BodyState* states = awakeSet->bodyStates.data; // This is a dummy state to represent a static body because static bodies don't have a solver body. b2BodyState dummyState = b2_identityBodyState; for ( int i = 0; i < contactCount; ++i ) { b2ContactConstraint* constraint = constraints + i; int indexA = constraint->indexA; int indexB = constraint->indexB; b2BodyState* stateA = indexA == B2_NULL_INDEX ? &dummyState : states + indexA; b2BodyState* stateB = indexB == B2_NULL_INDEX ? &dummyState : states + indexB; b2Vec2 vA = stateA->linearVelocity; float wA = stateA->angularVelocity; b2Vec2 vB = stateB->linearVelocity; float wB = stateB->angularVelocity; float mA = constraint->invMassA; float iA = constraint->invIA; float mB = constraint->invMassB; float iB = constraint->invIB; // Stiffer for static contacts to avoid bodies getting pushed through the ground b2Vec2 normal = constraint->normal; b2Vec2 tangent = b2RightPerp( constraint->normal ); int pointCount = constraint->pointCount; for ( int j = 0; j < pointCount; ++j ) { b2ContactConstraintPoint* cp = constraint->points + j; // fixed anchors b2Vec2 rA = cp->anchorA; b2Vec2 rB = cp->anchorB; b2Vec2 P = b2Add( b2MulSV( cp->normalImpulse, normal ), b2MulSV( cp->tangentImpulse, tangent ) ); cp->totalNormalImpulse += cp->normalImpulse; wA -= iA * b2Cross( rA, P ); vA = b2MulAdd( vA, -mA, P ); wB += iB * b2Cross( rB, P ); vB = b2MulAdd( vB, mB, P ); } wA -= iA * constraint->rollingImpulse; wB += iB * constraint->rollingImpulse; if ( stateA->flags & b2_dynamicFlag ) { stateA->linearVelocity = vA; stateA->angularVelocity = wA; } if ( stateB->flags & b2_dynamicFlag ) { stateB->linearVelocity = vB; stateB->angularVelocity = wB; } } b2TracyCZoneEnd( warmstart_overflow_contact ); } void b2SolveOverflowContacts( b2StepContext* context, bool useBias ) { b2TracyCZoneNC( solve_contact, "Solve Contact", b2_colorAliceBlue, true ); b2ConstraintGraph* graph = context->graph; b2GraphColor* color = graph->colors + B2_OVERFLOW_INDEX; b2ContactConstraint* constraints = color->overflowConstraints; int contactCount = color->contactSims.count; b2World* world = context->world; b2SolverSet* awakeSet = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); b2BodyState* states = awakeSet->bodyStates.data; float inv_h = context->inv_h; const float contactSpeed = context->world->contactSpeed; // This is a dummy body to represent a static body since static bodies don't have a solver body. b2BodyState dummyState = b2_identityBodyState; for ( int i = 0; i < contactCount; ++i ) { b2ContactConstraint* constraint = constraints + i; float mA = constraint->invMassA; float iA = constraint->invIA; float mB = constraint->invMassB; float iB = constraint->invIB; b2BodyState* stateA = constraint->indexA == B2_NULL_INDEX ? &dummyState : states + constraint->indexA; b2Vec2 vA = stateA->linearVelocity; float wA = stateA->angularVelocity; b2Rot dqA = stateA->deltaRotation; b2BodyState* stateB = constraint->indexB == B2_NULL_INDEX ? &dummyState : states + constraint->indexB; b2Vec2 vB = stateB->linearVelocity; float wB = stateB->angularVelocity; b2Rot dqB = stateB->deltaRotation; b2Vec2 dp = b2Sub( stateB->deltaPosition, stateA->deltaPosition ); b2Vec2 normal = constraint->normal; b2Vec2 tangent = b2RightPerp( normal ); float friction = constraint->friction; b2Softness softness = constraint->softness; int pointCount = constraint->pointCount; float totalNormalImpulse = 0.0f; // Non-penetration for ( int j = 0; j < pointCount; ++j ) { b2ContactConstraintPoint* cp = constraint->points + j; // fixed anchor points b2Vec2 rA = cp->anchorA; b2Vec2 rB = cp->anchorB; // compute current separation // this is subject to round-off error if the anchor is far from the body center of mass b2Vec2 ds = b2Add( dp, b2Sub( b2RotateVector( dqB, rB ), b2RotateVector( dqA, rA ) ) ); float s = cp->baseSeparation + b2Dot( ds, normal ); float velocityBias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; if ( s > 0.0f ) { // speculative bias velocityBias = s * inv_h; } else if ( useBias ) { velocityBias = b2MaxFloat( softness.massScale * softness.biasRate * s, -contactSpeed ); massScale = softness.massScale; impulseScale = softness.impulseScale; } // relative normal velocity at contact b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) ); b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) ); float vn = b2Dot( b2Sub( vrB, vrA ), normal ); // incremental normal impulse float impulse = -cp->normalMass * ( massScale * vn + velocityBias ) - impulseScale * cp->normalImpulse; // clamp the accumulated impulse float newImpulse = b2MaxFloat( cp->normalImpulse + impulse, 0.0f ); impulse = newImpulse - cp->normalImpulse; cp->normalImpulse = newImpulse; cp->totalNormalImpulse += impulse; // b2Log( "vn %g impulse %g bias %g", vn, newImpulse, velocityBias ); totalNormalImpulse += newImpulse; // apply normal impulse b2Vec2 P = b2MulSV( impulse, normal ); vA = b2MulSub( vA, mA, P ); wA -= iA * b2Cross( rA, P ); vB = b2MulAdd( vB, mB, P ); wB += iB * b2Cross( rB, P ); } // Friction for ( int j = 0; j < pointCount; ++j ) { b2ContactConstraintPoint* cp = constraint->points + j; // fixed anchor points b2Vec2 rA = cp->anchorA; b2Vec2 rB = cp->anchorB; // relative tangent velocity at contact b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) ); b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) ); // vt = dot(vrB - sB * tangent - (vrA + sA * tangent), tangent) // = dot(vrB - vrA, tangent) - (sA + sB) float vt = b2Dot( b2Sub( vrB, vrA ), tangent ) - constraint->tangentSpeed; // incremental tangent impulse float impulse = cp->tangentMass * ( -vt ); // clamp the accumulated force float maxFriction = friction * cp->normalImpulse; float newImpulse = b2ClampFloat( cp->tangentImpulse + impulse, -maxFriction, maxFriction ); impulse = newImpulse - cp->tangentImpulse; cp->tangentImpulse = newImpulse; // apply tangent impulse b2Vec2 P = b2MulSV( impulse, tangent ); vA = b2MulSub( vA, mA, P ); wA -= iA * b2Cross( rA, P ); vB = b2MulAdd( vB, mB, P ); wB += iB * b2Cross( rB, P ); } // Rolling resistance { float deltaLambda = -constraint->rollingMass * ( wB - wA ); float lambda = constraint->rollingImpulse; float maxLambda = constraint->rollingResistance * totalNormalImpulse; constraint->rollingImpulse = b2ClampFloat( lambda + deltaLambda, -maxLambda, maxLambda ); deltaLambda = constraint->rollingImpulse - lambda; wA -= iA * deltaLambda; wB += iB * deltaLambda; } if ( stateA->flags & b2_dynamicFlag ) { stateA->linearVelocity = vA; stateA->angularVelocity = wA; } if ( stateB->flags & b2_dynamicFlag ) { stateB->linearVelocity = vB; stateB->angularVelocity = wB; } } b2TracyCZoneEnd( solve_contact ); } void b2ApplyOverflowRestitution( b2StepContext* context ) { b2TracyCZoneNC( overflow_resitution, "Overflow Restitution", b2_colorViolet, true ); b2ConstraintGraph* graph = context->graph; b2GraphColor* color = graph->colors + B2_OVERFLOW_INDEX; b2ContactConstraint* constraints = color->overflowConstraints; int contactCount = color->contactSims.count; b2World* world = context->world; b2SolverSet* awakeSet = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); b2BodyState* states = awakeSet->bodyStates.data; float threshold = context->world->restitutionThreshold; // dummy state to represent a static body b2BodyState dummyState = b2_identityBodyState; for ( int i = 0; i < contactCount; ++i ) { b2ContactConstraint* constraint = constraints + i; float restitution = constraint->restitution; if ( restitution == 0.0f ) { continue; } float mA = constraint->invMassA; float iA = constraint->invIA; float mB = constraint->invMassB; float iB = constraint->invIB; b2BodyState* stateA = constraint->indexA == B2_NULL_INDEX ? &dummyState : states + constraint->indexA; b2Vec2 vA = stateA->linearVelocity; float wA = stateA->angularVelocity; b2BodyState* stateB = constraint->indexB == B2_NULL_INDEX ? &dummyState : states + constraint->indexB; b2Vec2 vB = stateB->linearVelocity; float wB = stateB->angularVelocity; b2Vec2 normal = constraint->normal; int pointCount = constraint->pointCount; // it is possible to get more accurate restitution by iterating // this only makes a difference if there are two contact points // for (int iter = 0; iter < 10; ++iter) { for ( int j = 0; j < pointCount; ++j ) { b2ContactConstraintPoint* cp = constraint->points + j; // if the normal impulse is zero then there was no collision // this skips speculative contact points that didn't generate an impulse // The max normal impulse is used in case there was a collision that moved away within the sub-step process if ( cp->relativeVelocity > -threshold || cp->totalNormalImpulse == 0.0f ) { continue; } // fixed anchor points b2Vec2 rA = cp->anchorA; b2Vec2 rB = cp->anchorB; // relative normal velocity at contact b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) ); b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) ); float vn = b2Dot( b2Sub( vrB, vrA ), normal ); // compute normal impulse float impulse = -cp->normalMass * ( vn + restitution * cp->relativeVelocity ); // clamp the accumulated impulse // todo should this be stored? float newImpulse = b2MaxFloat( cp->normalImpulse + impulse, 0.0f ); impulse = newImpulse - cp->normalImpulse; cp->normalImpulse = newImpulse; // Add the incremental impulse rather than the full impulse because this is not a sub-step cp->totalNormalImpulse += impulse; // apply contact impulse b2Vec2 P = b2MulSV( impulse, normal ); vA = b2MulSub( vA, mA, P ); wA -= iA * b2Cross( rA, P ); vB = b2MulAdd( vB, mB, P ); wB += iB * b2Cross( rB, P ); } } if ( stateA->flags & b2_dynamicFlag ) { stateA->linearVelocity = vA; stateA->angularVelocity = wA; } if ( stateB->flags & b2_dynamicFlag ) { stateB->linearVelocity = vB; stateB->angularVelocity = wB; } } b2TracyCZoneEnd( overflow_resitution ); } void b2StoreOverflowImpulses( b2StepContext* context ) { b2TracyCZoneNC( store_impulses, "Store", b2_colorFireBrick, true ); b2ConstraintGraph* graph = context->graph; b2GraphColor* color = graph->colors + B2_OVERFLOW_INDEX; b2ContactConstraint* constraints = color->overflowConstraints; b2ContactSim* contacts = color->contactSims.data; int contactCount = color->contactSims.count; for ( int i = 0; i < contactCount; ++i ) { const b2ContactConstraint* constraint = constraints + i; b2ContactSim* contact = contacts + i; b2Manifold* manifold = &contact->manifold; int pointCount = manifold->pointCount; for ( int j = 0; j < pointCount; ++j ) { manifold->points[j].normalImpulse = constraint->points[j].normalImpulse; manifold->points[j].tangentImpulse = constraint->points[j].tangentImpulse; manifold->points[j].totalNormalImpulse = constraint->points[j].totalNormalImpulse; manifold->points[j].normalVelocity = constraint->points[j].relativeVelocity; } manifold->rollingImpulse = constraint->rollingImpulse; } b2TracyCZoneEnd( store_impulses ); } #if defined( B2_SIMD_AVX2 ) #include // wide float holds 8 numbers typedef __m256 b2FloatW; #elif defined( B2_SIMD_NEON ) #include // wide float holds 4 numbers typedef float32x4_t b2FloatW; #elif defined( B2_SIMD_SSE2 ) #include // wide float holds 4 numbers typedef __m128 b2FloatW; #else // scalar math typedef struct b2FloatW { float x, y, z, w; } b2FloatW; #endif // Wide vec2 typedef struct b2Vec2W { b2FloatW X, Y; } b2Vec2W; // Wide rotation typedef struct b2RotW { b2FloatW C, S; } b2RotW; #if defined( B2_SIMD_AVX2 ) static inline b2FloatW b2ZeroW( void ) { return _mm256_setzero_ps(); } static inline b2FloatW b2SplatW( float scalar ) { return _mm256_set1_ps( scalar ); } static inline b2FloatW b2AddW( b2FloatW a, b2FloatW b ) { return _mm256_add_ps( a, b ); } static inline b2FloatW b2SubW( b2FloatW a, b2FloatW b ) { return _mm256_sub_ps( a, b ); } static inline b2FloatW b2MulW( b2FloatW a, b2FloatW b ) { return _mm256_mul_ps( a, b ); } static inline b2FloatW b2MulAddW( b2FloatW a, b2FloatW b, b2FloatW c ) { // FMA can be emulated: https://github.com/lattera/glibc/blob/master/sysdeps/ieee754/dbl-64/s_fmaf.c#L34 // return _mm256_fmadd_ps( b, c, a ); return _mm256_add_ps( _mm256_mul_ps( b, c ), a ); } static inline b2FloatW b2MulSubW( b2FloatW a, b2FloatW b, b2FloatW c ) { // return _mm256_fnmadd_ps(b, c, a); return _mm256_sub_ps( a, _mm256_mul_ps( b, c ) ); } static inline b2FloatW b2MinW( b2FloatW a, b2FloatW b ) { return _mm256_min_ps( a, b ); } static inline b2FloatW b2MaxW( b2FloatW a, b2FloatW b ) { return _mm256_max_ps( a, b ); } // a = clamp(a, -b, b) static inline b2FloatW b2SymClampW( b2FloatW a, b2FloatW b ) { b2FloatW nb = _mm256_sub_ps( _mm256_setzero_ps(), b ); return _mm256_max_ps( nb, _mm256_min_ps( a, b ) ); } static inline b2FloatW b2OrW( b2FloatW a, b2FloatW b ) { return _mm256_or_ps( a, b ); } static inline b2FloatW b2GreaterThanW( b2FloatW a, b2FloatW b ) { return _mm256_cmp_ps( a, b, _CMP_GT_OQ ); } static inline b2FloatW b2EqualsW( b2FloatW a, b2FloatW b ) { return _mm256_cmp_ps( a, b, _CMP_EQ_OQ ); } static inline bool b2AllZeroW( b2FloatW a ) { // Compare each element with zero b2FloatW zero = _mm256_setzero_ps(); b2FloatW cmp = _mm256_cmp_ps( a, zero, _CMP_EQ_OQ ); // Create a mask from the comparison results int mask = _mm256_movemask_ps( cmp ); // If all elements are zero, the mask will be 0xFF (11111111 in binary) return mask == 0xFF; } // component-wise returns mask ? b : a static inline b2FloatW b2BlendW( b2FloatW a, b2FloatW b, b2FloatW mask ) { return _mm256_blendv_ps( a, b, mask ); } #elif defined( B2_SIMD_NEON ) static inline b2FloatW b2ZeroW( void ) { return vdupq_n_f32( 0.0f ); } static inline b2FloatW b2SplatW( float scalar ) { return vdupq_n_f32( scalar ); } static inline b2FloatW b2SetW( float a, float b, float c, float d ) { float32_t array[4] = { a, b, c, d }; return vld1q_f32( array ); } static inline b2FloatW b2AddW( b2FloatW a, b2FloatW b ) { return vaddq_f32( a, b ); } static inline b2FloatW b2SubW( b2FloatW a, b2FloatW b ) { return vsubq_f32( a, b ); } static inline b2FloatW b2MulW( b2FloatW a, b2FloatW b ) { return vmulq_f32( a, b ); } static inline b2FloatW b2MulAddW( b2FloatW a, b2FloatW b, b2FloatW c ) { return vmlaq_f32( a, b, c ); } static inline b2FloatW b2MulSubW( b2FloatW a, b2FloatW b, b2FloatW c ) { return vmlsq_f32( a, b, c ); } static inline b2FloatW b2MinW( b2FloatW a, b2FloatW b ) { return vminq_f32( a, b ); } static inline b2FloatW b2MaxW( b2FloatW a, b2FloatW b ) { return vmaxq_f32( a, b ); } // a = clamp(a, -b, b) static inline b2FloatW b2SymClampW( b2FloatW a, b2FloatW b ) { b2FloatW nb = vnegq_f32( b ); return vmaxq_f32( nb, vminq_f32( a, b ) ); } static inline b2FloatW b2OrW( b2FloatW a, b2FloatW b ) { return vreinterpretq_f32_u32( vorrq_u32( vreinterpretq_u32_f32( a ), vreinterpretq_u32_f32( b ) ) ); } static inline b2FloatW b2GreaterThanW( b2FloatW a, b2FloatW b ) { return vreinterpretq_f32_u32( vcgtq_f32( a, b ) ); } static inline b2FloatW b2EqualsW( b2FloatW a, b2FloatW b ) { return vreinterpretq_f32_u32( vceqq_f32( a, b ) ); } static inline bool b2AllZeroW( b2FloatW a ) { // Create a zero vector for comparison b2FloatW zero = vdupq_n_f32( 0.0f ); // Compare the input vector with zero uint32x4_t cmp_result = vceqq_f32( a, zero ); // Check if all comparison results are non-zero using vminvq #ifdef __ARM_FEATURE_SVE // ARM v8.2+ has horizontal minimum instruction return vminvq_u32( cmp_result ) != 0; #else // For older ARM architectures, we need to manually check all lanes return vgetq_lane_u32( cmp_result, 0 ) != 0 && vgetq_lane_u32( cmp_result, 1 ) != 0 && vgetq_lane_u32( cmp_result, 2 ) != 0 && vgetq_lane_u32( cmp_result, 3 ) != 0; #endif } // component-wise returns mask ? b : a static inline b2FloatW b2BlendW( b2FloatW a, b2FloatW b, b2FloatW mask ) { uint32x4_t mask32 = vreinterpretq_u32_f32( mask ); return vbslq_f32( mask32, b, a ); } static inline b2FloatW b2LoadW( const float32_t* data ) { return vld1q_f32( data ); } static inline void b2StoreW( float32_t* data, b2FloatW a ) { vst1q_f32( data, a ); } static inline b2FloatW b2UnpackLoW( b2FloatW a, b2FloatW b ) { #if defined( __aarch64__ ) return vzip1q_f32( a, b ); #else float32x2_t a1 = vget_low_f32( a ); float32x2_t b1 = vget_low_f32( b ); float32x2x2_t result = vzip_f32( a1, b1 ); return vcombine_f32( result.val[0], result.val[1] ); #endif } static inline b2FloatW b2UnpackHiW( b2FloatW a, b2FloatW b ) { #if defined( __aarch64__ ) return vzip2q_f32( a, b ); #else float32x2_t a1 = vget_high_f32( a ); float32x2_t b1 = vget_high_f32( b ); float32x2x2_t result = vzip_f32( a1, b1 ); return vcombine_f32( result.val[0], result.val[1] ); #endif } #elif defined( B2_SIMD_SSE2 ) static inline b2FloatW b2ZeroW( void ) { return _mm_setzero_ps(); } static inline b2FloatW b2SplatW( float scalar ) { return _mm_set1_ps( scalar ); } static inline b2FloatW b2SetW( float a, float b, float c, float d ) { return _mm_setr_ps( a, b, c, d ); } static inline b2FloatW b2AddW( b2FloatW a, b2FloatW b ) { return _mm_add_ps( a, b ); } static inline b2FloatW b2SubW( b2FloatW a, b2FloatW b ) { return _mm_sub_ps( a, b ); } static inline b2FloatW b2MulW( b2FloatW a, b2FloatW b ) { return _mm_mul_ps( a, b ); } static inline b2FloatW b2MulAddW( b2FloatW a, b2FloatW b, b2FloatW c ) { return _mm_add_ps( a, _mm_mul_ps( b, c ) ); } static inline b2FloatW b2MulSubW( b2FloatW a, b2FloatW b, b2FloatW c ) { return _mm_sub_ps( a, _mm_mul_ps( b, c ) ); } static inline b2FloatW b2MinW( b2FloatW a, b2FloatW b ) { return _mm_min_ps( a, b ); } static inline b2FloatW b2MaxW( b2FloatW a, b2FloatW b ) { return _mm_max_ps( a, b ); } // a = clamp(a, -b, b) static inline b2FloatW b2SymClampW( b2FloatW a, b2FloatW b ) { // Create a mask with the sign bit set for each element __m128 mask = _mm_set1_ps( -0.0f ); // XOR the input with the mask to negate each element __m128 nb = _mm_xor_ps( b, mask ); return _mm_max_ps( nb, _mm_min_ps( a, b ) ); } static inline b2FloatW b2OrW( b2FloatW a, b2FloatW b ) { return _mm_or_ps( a, b ); } static inline b2FloatW b2GreaterThanW( b2FloatW a, b2FloatW b ) { return _mm_cmpgt_ps( a, b ); } static inline b2FloatW b2EqualsW( b2FloatW a, b2FloatW b ) { return _mm_cmpeq_ps( a, b ); } static inline bool b2AllZeroW( b2FloatW a ) { // Compare each element with zero b2FloatW zero = _mm_setzero_ps(); b2FloatW cmp = _mm_cmpeq_ps( a, zero ); // Create a mask from the comparison results int mask = _mm_movemask_ps( cmp ); // If all elements are zero, the mask will be 0xF (1111 in binary) return mask == 0xF; } // component-wise returns mask ? b : a static inline b2FloatW b2BlendW( b2FloatW a, b2FloatW b, b2FloatW mask ) { return _mm_or_ps( _mm_and_ps( mask, b ), _mm_andnot_ps( mask, a ) ); } static inline b2FloatW b2LoadW( const float* data ) { return _mm_load_ps( data ); } static inline void b2StoreW( float* data, b2FloatW a ) { _mm_store_ps( data, a ); } static inline b2FloatW b2UnpackLoW( b2FloatW a, b2FloatW b ) { return _mm_unpacklo_ps( a, b ); } static inline b2FloatW b2UnpackHiW( b2FloatW a, b2FloatW b ) { return _mm_unpackhi_ps( a, b ); } #else static inline b2FloatW b2ZeroW( void ) { return (b2FloatW){ 0.0f, 0.0f, 0.0f, 0.0f }; } static inline b2FloatW b2SplatW( float scalar ) { return (b2FloatW){ scalar, scalar, scalar, scalar }; } static inline b2FloatW b2AddW( b2FloatW a, b2FloatW b ) { return (b2FloatW){ a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w }; } static inline b2FloatW b2SubW( b2FloatW a, b2FloatW b ) { return (b2FloatW){ a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w }; } static inline b2FloatW b2MulW( b2FloatW a, b2FloatW b ) { return (b2FloatW){ a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w }; } static inline b2FloatW b2MulAddW( b2FloatW a, b2FloatW b, b2FloatW c ) { return (b2FloatW){ a.x + b.x * c.x, a.y + b.y * c.y, a.z + b.z * c.z, a.w + b.w * c.w }; } static inline b2FloatW b2MulSubW( b2FloatW a, b2FloatW b, b2FloatW c ) { return (b2FloatW){ a.x - b.x * c.x, a.y - b.y * c.y, a.z - b.z * c.z, a.w - b.w * c.w }; } static inline b2FloatW b2MinW( b2FloatW a, b2FloatW b ) { b2FloatW r; r.x = a.x <= b.x ? a.x : b.x; r.y = a.y <= b.y ? a.y : b.y; r.z = a.z <= b.z ? a.z : b.z; r.w = a.w <= b.w ? a.w : b.w; return r; } static inline b2FloatW b2MaxW( b2FloatW a, b2FloatW b ) { b2FloatW r; r.x = a.x >= b.x ? a.x : b.x; r.y = a.y >= b.y ? a.y : b.y; r.z = a.z >= b.z ? a.z : b.z; r.w = a.w >= b.w ? a.w : b.w; return r; } // a = clamp(a, -b, b) static inline b2FloatW b2SymClampW( b2FloatW a, b2FloatW b ) { b2FloatW r; r.x = b2ClampFloat( a.x, -b.x, b.x ); r.y = b2ClampFloat( a.y, -b.y, b.y ); r.z = b2ClampFloat( a.z, -b.z, b.z ); r.w = b2ClampFloat( a.w, -b.w, b.w ); return r; } static inline b2FloatW b2OrW( b2FloatW a, b2FloatW b ) { b2FloatW r; r.x = a.x != 0.0f || b.x != 0.0f ? 1.0f : 0.0f; r.y = a.y != 0.0f || b.y != 0.0f ? 1.0f : 0.0f; r.z = a.z != 0.0f || b.z != 0.0f ? 1.0f : 0.0f; r.w = a.w != 0.0f || b.w != 0.0f ? 1.0f : 0.0f; return r; } static inline b2FloatW b2GreaterThanW( b2FloatW a, b2FloatW b ) { b2FloatW r; r.x = a.x > b.x ? 1.0f : 0.0f; r.y = a.y > b.y ? 1.0f : 0.0f; r.z = a.z > b.z ? 1.0f : 0.0f; r.w = a.w > b.w ? 1.0f : 0.0f; return r; } static inline b2FloatW b2EqualsW( b2FloatW a, b2FloatW b ) { b2FloatW r; r.x = a.x == b.x ? 1.0f : 0.0f; r.y = a.y == b.y ? 1.0f : 0.0f; r.z = a.z == b.z ? 1.0f : 0.0f; r.w = a.w == b.w ? 1.0f : 0.0f; return r; } static inline bool b2AllZeroW( b2FloatW a ) { return a.x == 0.0f && a.y == 0.0f && a.z == 0.0f && a.w == 0.0f; } // component-wise returns mask ? b : a static inline b2FloatW b2BlendW( b2FloatW a, b2FloatW b, b2FloatW mask ) { b2FloatW r; r.x = mask.x != 0.0f ? b.x : a.x; r.y = mask.y != 0.0f ? b.y : a.y; r.z = mask.z != 0.0f ? b.z : a.z; r.w = mask.w != 0.0f ? b.w : a.w; return r; } #endif static inline b2FloatW b2DotW( b2Vec2W a, b2Vec2W b ) { return b2AddW( b2MulW( a.X, b.X ), b2MulW( a.Y, b.Y ) ); } static inline b2FloatW b2CrossW( b2Vec2W a, b2Vec2W b ) { return b2SubW( b2MulW( a.X, b.Y ), b2MulW( a.Y, b.X ) ); } static inline b2Vec2W b2RotateVectorW( b2RotW q, b2Vec2W v ) { return (b2Vec2W){ b2SubW( b2MulW( q.C, v.X ), b2MulW( q.S, v.Y ) ), b2AddW( b2MulW( q.S, v.X ), b2MulW( q.C, v.Y ) ) }; } // Soft contact constraints with sub-stepping support // Uses fixed anchors for Jacobians for better behavior on rolling shapes (circles & capsules) // http://mmacklin.com/smallsteps.pdf // https://box2d.org/files/ErinCatto_SoftConstraints_GDC2011.pdf typedef struct b2ContactConstraintSIMD { int indexA[B2_SIMD_WIDTH]; int indexB[B2_SIMD_WIDTH]; b2FloatW invMassA, invMassB; b2FloatW invIA, invIB; b2Vec2W normal; b2FloatW friction; b2FloatW tangentSpeed; b2FloatW rollingResistance; b2FloatW rollingMass; b2FloatW rollingImpulse; b2FloatW biasRate; b2FloatW massScale; b2FloatW impulseScale; b2Vec2W anchorA1, anchorB1; b2FloatW normalMass1, tangentMass1; b2FloatW baseSeparation1; b2FloatW normalImpulse1; b2FloatW totalNormalImpulse1; b2FloatW tangentImpulse1; b2Vec2W anchorA2, anchorB2; b2FloatW baseSeparation2; b2FloatW normalImpulse2; b2FloatW totalNormalImpulse2; b2FloatW tangentImpulse2; b2FloatW normalMass2, tangentMass2; b2FloatW restitution; b2FloatW relativeVelocity1, relativeVelocity2; } b2ContactConstraintSIMD; int b2GetContactConstraintSIMDByteCount( void ) { return sizeof( b2ContactConstraintSIMD ); } // wide version of b2BodyState typedef struct b2BodyStateW { b2Vec2W v; b2FloatW w; b2FloatW flags; b2Vec2W dp; b2RotW dq; } b2BodyStateW; // Custom gather/scatter for each SIMD type #if defined( B2_SIMD_AVX2 ) // This is a load and 8x8 transpose static b2BodyStateW b2GatherBodies( const b2BodyState* B2_RESTRICT states, int* B2_RESTRICT indices ) { _Static_assert( sizeof( b2BodyState ) == 32, "b2BodyState not 32 bytes" ); B2_ASSERT( ( (uintptr_t)states & 0x1F ) == 0 ); // b2BodyState b2_identityBodyState = {{0.0f, 0.0f}, 0.0f, 0, {0.0f, 0.0f}, {1.0f, 0.0f}}; b2FloatW identity = _mm256_setr_ps( 0.0f, 0.0f, 0.0f, 0, 0.0f, 0.0f, 1.0f, 0.0f ); b2FloatW b0 = indices[0] == B2_NULL_INDEX ? identity : _mm256_load_ps( (float*)( states + indices[0] ) ); b2FloatW b1 = indices[1] == B2_NULL_INDEX ? identity : _mm256_load_ps( (float*)( states + indices[1] ) ); b2FloatW b2 = indices[2] == B2_NULL_INDEX ? identity : _mm256_load_ps( (float*)( states + indices[2] ) ); b2FloatW b3 = indices[3] == B2_NULL_INDEX ? identity : _mm256_load_ps( (float*)( states + indices[3] ) ); b2FloatW b4 = indices[4] == B2_NULL_INDEX ? identity : _mm256_load_ps( (float*)( states + indices[4] ) ); b2FloatW b5 = indices[5] == B2_NULL_INDEX ? identity : _mm256_load_ps( (float*)( states + indices[5] ) ); b2FloatW b6 = indices[6] == B2_NULL_INDEX ? identity : _mm256_load_ps( (float*)( states + indices[6] ) ); b2FloatW b7 = indices[7] == B2_NULL_INDEX ? identity : _mm256_load_ps( (float*)( states + indices[7] ) ); b2FloatW t0 = _mm256_unpacklo_ps( b0, b1 ); b2FloatW t1 = _mm256_unpackhi_ps( b0, b1 ); b2FloatW t2 = _mm256_unpacklo_ps( b2, b3 ); b2FloatW t3 = _mm256_unpackhi_ps( b2, b3 ); b2FloatW t4 = _mm256_unpacklo_ps( b4, b5 ); b2FloatW t5 = _mm256_unpackhi_ps( b4, b5 ); b2FloatW t6 = _mm256_unpacklo_ps( b6, b7 ); b2FloatW t7 = _mm256_unpackhi_ps( b6, b7 ); b2FloatW tt0 = _mm256_shuffle_ps( t0, t2, _MM_SHUFFLE( 1, 0, 1, 0 ) ); b2FloatW tt1 = _mm256_shuffle_ps( t0, t2, _MM_SHUFFLE( 3, 2, 3, 2 ) ); b2FloatW tt2 = _mm256_shuffle_ps( t1, t3, _MM_SHUFFLE( 1, 0, 1, 0 ) ); b2FloatW tt3 = _mm256_shuffle_ps( t1, t3, _MM_SHUFFLE( 3, 2, 3, 2 ) ); b2FloatW tt4 = _mm256_shuffle_ps( t4, t6, _MM_SHUFFLE( 1, 0, 1, 0 ) ); b2FloatW tt5 = _mm256_shuffle_ps( t4, t6, _MM_SHUFFLE( 3, 2, 3, 2 ) ); b2FloatW tt6 = _mm256_shuffle_ps( t5, t7, _MM_SHUFFLE( 1, 0, 1, 0 ) ); b2FloatW tt7 = _mm256_shuffle_ps( t5, t7, _MM_SHUFFLE( 3, 2, 3, 2 ) ); b2BodyStateW simdBody; simdBody.v.X = _mm256_permute2f128_ps( tt0, tt4, 0x20 ); simdBody.v.Y = _mm256_permute2f128_ps( tt1, tt5, 0x20 ); simdBody.w = _mm256_permute2f128_ps( tt2, tt6, 0x20 ); simdBody.flags = _mm256_permute2f128_ps( tt3, tt7, 0x20 ); simdBody.dp.X = _mm256_permute2f128_ps( tt0, tt4, 0x31 ); simdBody.dp.Y = _mm256_permute2f128_ps( tt1, tt5, 0x31 ); simdBody.dq.C = _mm256_permute2f128_ps( tt2, tt6, 0x31 ); simdBody.dq.S = _mm256_permute2f128_ps( tt3, tt7, 0x31 ); return simdBody; } // This writes everything back to the solver bodies but only the velocities change static void b2ScatterBodies( b2BodyState* B2_RESTRICT states, int* B2_RESTRICT indices, const b2BodyStateW* B2_RESTRICT simdBody ) { _Static_assert( sizeof( b2BodyState ) == 32, "b2BodyState not 32 bytes" ); B2_ASSERT( ( (uintptr_t)states & 0x1F ) == 0 ); b2FloatW t0 = _mm256_unpacklo_ps( simdBody->v.X, simdBody->v.Y ); b2FloatW t1 = _mm256_unpackhi_ps( simdBody->v.X, simdBody->v.Y ); b2FloatW t2 = _mm256_unpacklo_ps( simdBody->w, simdBody->flags ); b2FloatW t3 = _mm256_unpackhi_ps( simdBody->w, simdBody->flags ); b2FloatW t4 = _mm256_unpacklo_ps( simdBody->dp.X, simdBody->dp.Y ); b2FloatW t5 = _mm256_unpackhi_ps( simdBody->dp.X, simdBody->dp.Y ); b2FloatW t6 = _mm256_unpacklo_ps( simdBody->dq.C, simdBody->dq.S ); b2FloatW t7 = _mm256_unpackhi_ps( simdBody->dq.C, simdBody->dq.S ); b2FloatW tt0 = _mm256_shuffle_ps( t0, t2, _MM_SHUFFLE( 1, 0, 1, 0 ) ); b2FloatW tt1 = _mm256_shuffle_ps( t0, t2, _MM_SHUFFLE( 3, 2, 3, 2 ) ); b2FloatW tt2 = _mm256_shuffle_ps( t1, t3, _MM_SHUFFLE( 1, 0, 1, 0 ) ); b2FloatW tt3 = _mm256_shuffle_ps( t1, t3, _MM_SHUFFLE( 3, 2, 3, 2 ) ); b2FloatW tt4 = _mm256_shuffle_ps( t4, t6, _MM_SHUFFLE( 1, 0, 1, 0 ) ); b2FloatW tt5 = _mm256_shuffle_ps( t4, t6, _MM_SHUFFLE( 3, 2, 3, 2 ) ); b2FloatW tt6 = _mm256_shuffle_ps( t5, t7, _MM_SHUFFLE( 1, 0, 1, 0 ) ); b2FloatW tt7 = _mm256_shuffle_ps( t5, t7, _MM_SHUFFLE( 3, 2, 3, 2 ) ); // I don't use any dummy body in the body array because this will lead to multithreaded sharing and the // associated cache flushing. // todo could add a check for kinematic bodies here if ( indices[0] != B2_NULL_INDEX && ( states[indices[0]].flags & b2_dynamicFlag ) != 0 ) _mm256_store_ps( (float*)( states + indices[0] ), _mm256_permute2f128_ps( tt0, tt4, 0x20 ) ); if ( indices[1] != B2_NULL_INDEX && ( states[indices[1]].flags & b2_dynamicFlag ) != 0 ) _mm256_store_ps( (float*)( states + indices[1] ), _mm256_permute2f128_ps( tt1, tt5, 0x20 ) ); if ( indices[2] != B2_NULL_INDEX && ( states[indices[2]].flags & b2_dynamicFlag ) != 0 ) _mm256_store_ps( (float*)( states + indices[2] ), _mm256_permute2f128_ps( tt2, tt6, 0x20 ) ); if ( indices[3] != B2_NULL_INDEX && ( states[indices[3]].flags & b2_dynamicFlag ) != 0 ) _mm256_store_ps( (float*)( states + indices[3] ), _mm256_permute2f128_ps( tt3, tt7, 0x20 ) ); if ( indices[4] != B2_NULL_INDEX && ( states[indices[4]].flags & b2_dynamicFlag ) != 0 ) _mm256_store_ps( (float*)( states + indices[4] ), _mm256_permute2f128_ps( tt0, tt4, 0x31 ) ); if ( indices[5] != B2_NULL_INDEX && ( states[indices[5]].flags & b2_dynamicFlag ) != 0 ) _mm256_store_ps( (float*)( states + indices[5] ), _mm256_permute2f128_ps( tt1, tt5, 0x31 ) ); if ( indices[6] != B2_NULL_INDEX && ( states[indices[6]].flags & b2_dynamicFlag ) != 0 ) _mm256_store_ps( (float*)( states + indices[6] ), _mm256_permute2f128_ps( tt2, tt6, 0x31 ) ); if ( indices[7] != B2_NULL_INDEX && ( states[indices[7]].flags & b2_dynamicFlag ) != 0 ) _mm256_store_ps( (float*)( states + indices[7] ), _mm256_permute2f128_ps( tt3, tt7, 0x31 ) ); } #elif defined( B2_SIMD_NEON ) // This is a load and transpose static b2BodyStateW b2GatherBodies( const b2BodyState* B2_RESTRICT states, int* B2_RESTRICT indices ) { _Static_assert( sizeof( b2BodyState ) == 32, "b2BodyState not 32 bytes" ); B2_ASSERT( ( (uintptr_t)states & 0x1F ) == 0 ); // [vx vy w flags] b2FloatW identityA = b2ZeroW(); // [dpx dpy dqc dqs] b2FloatW identityB = b2SetW( 0.0f, 0.0f, 1.0f, 0.0f ); b2FloatW b1a = indices[0] == B2_NULL_INDEX ? identityA : b2LoadW( (float*)( states + indices[0] ) + 0 ); b2FloatW b1b = indices[0] == B2_NULL_INDEX ? identityB : b2LoadW( (float*)( states + indices[0] ) + 4 ); b2FloatW b2a = indices[1] == B2_NULL_INDEX ? identityA : b2LoadW( (float*)( states + indices[1] ) + 0 ); b2FloatW b2b = indices[1] == B2_NULL_INDEX ? identityB : b2LoadW( (float*)( states + indices[1] ) + 4 ); b2FloatW b3a = indices[2] == B2_NULL_INDEX ? identityA : b2LoadW( (float*)( states + indices[2] ) + 0 ); b2FloatW b3b = indices[2] == B2_NULL_INDEX ? identityB : b2LoadW( (float*)( states + indices[2] ) + 4 ); b2FloatW b4a = indices[3] == B2_NULL_INDEX ? identityA : b2LoadW( (float*)( states + indices[3] ) + 0 ); b2FloatW b4b = indices[3] == B2_NULL_INDEX ? identityB : b2LoadW( (float*)( states + indices[3] ) + 4 ); // [vx1 vx3 vy1 vy3] b2FloatW t1a = b2UnpackLoW( b1a, b3a ); // [vx2 vx4 vy2 vy4] b2FloatW t2a = b2UnpackLoW( b2a, b4a ); // [w1 w3 f1 f3] b2FloatW t3a = b2UnpackHiW( b1a, b3a ); // [w2 w4 f2 f4] b2FloatW t4a = b2UnpackHiW( b2a, b4a ); b2BodyStateW simdBody; simdBody.v.X = b2UnpackLoW( t1a, t2a ); simdBody.v.Y = b2UnpackHiW( t1a, t2a ); simdBody.w = b2UnpackLoW( t3a, t4a ); simdBody.flags = b2UnpackHiW( t3a, t4a ); b2FloatW t1b = b2UnpackLoW( b1b, b3b ); b2FloatW t2b = b2UnpackLoW( b2b, b4b ); b2FloatW t3b = b2UnpackHiW( b1b, b3b ); b2FloatW t4b = b2UnpackHiW( b2b, b4b ); simdBody.dp.X = b2UnpackLoW( t1b, t2b ); simdBody.dp.Y = b2UnpackHiW( t1b, t2b ); simdBody.dq.C = b2UnpackLoW( t3b, t4b ); simdBody.dq.S = b2UnpackHiW( t3b, t4b ); return simdBody; } // This writes only the velocities back to the solver bodies // https://developer.arm.com/documentation/102107a/0100/Floating-point-4x4-matrix-transposition static void b2ScatterBodies( b2BodyState* B2_RESTRICT states, int* B2_RESTRICT indices, const b2BodyStateW* B2_RESTRICT simdBody ) { _Static_assert( sizeof( b2BodyState ) == 32, "b2BodyState not 32 bytes" ); B2_ASSERT( ( (uintptr_t)states & 0x1F ) == 0 ); // b2FloatW x = b2SetW(0.0f, 1.0f, 2.0f, 3.0f); // b2FloatW y = b2SetW(4.0f, 5.0f, 6.0f, 7.0f); // b2FloatW z = b2SetW(8.0f, 9.0f, 10.0f, 11.0f); // b2FloatW w = b2SetW(12.0f, 13.0f, 14.0f, 15.0f); // // float32x4x2_t rr1 = vtrnq_f32( x, y ); // float32x4x2_t rr2 = vtrnq_f32( z, w ); // // float32x4_t b1 = vcombine_f32(vget_low_f32(rr1.val[0]), vget_low_f32(rr2.val[0])); // float32x4_t b2 = vcombine_f32(vget_low_f32(rr1.val[1]), vget_low_f32(rr2.val[1])); // float32x4_t b3 = vcombine_f32(vget_high_f32(rr1.val[0]), vget_high_f32(rr2.val[0])); // float32x4_t b4 = vcombine_f32(vget_high_f32(rr1.val[1]), vget_high_f32(rr2.val[1])); // transpose float32x4x2_t r1 = vtrnq_f32( simdBody->v.X, simdBody->v.Y ); float32x4x2_t r2 = vtrnq_f32( simdBody->w, simdBody->flags ); // I don't use any dummy body in the body array because this will lead to multithreaded sharing and the // associated cache flushing. if ( indices[0] != B2_NULL_INDEX && ( states[indices[0]].flags & b2_dynamicFlag ) != 0 ) { float32x4_t body1 = vcombine_f32( vget_low_f32( r1.val[0] ), vget_low_f32( r2.val[0] ) ); b2StoreW( (float*)( states + indices[0] ), body1 ); } if ( indices[1] != B2_NULL_INDEX && ( states[indices[1]].flags & b2_dynamicFlag ) != 0 ) { float32x4_t body2 = vcombine_f32( vget_low_f32( r1.val[1] ), vget_low_f32( r2.val[1] ) ); b2StoreW( (float*)( states + indices[1] ), body2 ); } if ( indices[2] != B2_NULL_INDEX && ( states[indices[2]].flags & b2_dynamicFlag ) != 0 ) { float32x4_t body3 = vcombine_f32( vget_high_f32( r1.val[0] ), vget_high_f32( r2.val[0] ) ); b2StoreW( (float*)( states + indices[2] ), body3 ); } if ( indices[3] != B2_NULL_INDEX && ( states[indices[3]].flags & b2_dynamicFlag ) != 0 ) { float32x4_t body4 = vcombine_f32( vget_high_f32( r1.val[1] ), vget_high_f32( r2.val[1] ) ); b2StoreW( (float*)( states + indices[3] ), body4 ); } } #elif defined( B2_SIMD_SSE2 ) // This is a load and transpose static b2BodyStateW b2GatherBodies( const b2BodyState* B2_RESTRICT states, int* B2_RESTRICT indices ) { _Static_assert( sizeof( b2BodyState ) == 32, "b2BodyState not 32 bytes" ); B2_ASSERT( ( (uintptr_t)states & 0x1F ) == 0 ); // [vx vy w flags] b2FloatW identityA = b2ZeroW(); // [dpx dpy dqc dqs] b2FloatW identityB = b2SetW( 0.0f, 0.0f, 1.0f, 0.0f ); b2FloatW b1a = indices[0] == B2_NULL_INDEX ? identityA : b2LoadW( (float*)( states + indices[0] ) + 0 ); b2FloatW b1b = indices[0] == B2_NULL_INDEX ? identityB : b2LoadW( (float*)( states + indices[0] ) + 4 ); b2FloatW b2a = indices[1] == B2_NULL_INDEX ? identityA : b2LoadW( (float*)( states + indices[1] ) + 0 ); b2FloatW b2b = indices[1] == B2_NULL_INDEX ? identityB : b2LoadW( (float*)( states + indices[1] ) + 4 ); b2FloatW b3a = indices[2] == B2_NULL_INDEX ? identityA : b2LoadW( (float*)( states + indices[2] ) + 0 ); b2FloatW b3b = indices[2] == B2_NULL_INDEX ? identityB : b2LoadW( (float*)( states + indices[2] ) + 4 ); b2FloatW b4a = indices[3] == B2_NULL_INDEX ? identityA : b2LoadW( (float*)( states + indices[3] ) + 0 ); b2FloatW b4b = indices[3] == B2_NULL_INDEX ? identityB : b2LoadW( (float*)( states + indices[3] ) + 4 ); // [vx1 vx3 vy1 vy3] b2FloatW t1a = b2UnpackLoW( b1a, b3a ); // [vx2 vx4 vy2 vy4] b2FloatW t2a = b2UnpackLoW( b2a, b4a ); // [w1 w3 f1 f3] b2FloatW t3a = b2UnpackHiW( b1a, b3a ); // [w2 w4 f2 f4] b2FloatW t4a = b2UnpackHiW( b2a, b4a ); b2BodyStateW simdBody; simdBody.v.X = b2UnpackLoW( t1a, t2a ); simdBody.v.Y = b2UnpackHiW( t1a, t2a ); simdBody.w = b2UnpackLoW( t3a, t4a ); simdBody.flags = b2UnpackHiW( t3a, t4a ); b2FloatW t1b = b2UnpackLoW( b1b, b3b ); b2FloatW t2b = b2UnpackLoW( b2b, b4b ); b2FloatW t3b = b2UnpackHiW( b1b, b3b ); b2FloatW t4b = b2UnpackHiW( b2b, b4b ); simdBody.dp.X = b2UnpackLoW( t1b, t2b ); simdBody.dp.Y = b2UnpackHiW( t1b, t2b ); simdBody.dq.C = b2UnpackLoW( t3b, t4b ); simdBody.dq.S = b2UnpackHiW( t3b, t4b ); return simdBody; } // This writes only the velocities back to the solver bodies static void b2ScatterBodies( b2BodyState* B2_RESTRICT states, int* B2_RESTRICT indices, const b2BodyStateW* B2_RESTRICT simdBody ) { _Static_assert( sizeof( b2BodyState ) == 32, "b2BodyState not 32 bytes" ); B2_ASSERT( ( (uintptr_t)states & 0x1F ) == 0 ); // [vx1 vy1 vx2 vy2] b2FloatW t1 = b2UnpackLoW( simdBody->v.X, simdBody->v.Y ); // [vx3 vy3 vx4 vy4] b2FloatW t2 = b2UnpackHiW( simdBody->v.X, simdBody->v.Y ); // [w1 f1 w2 f2] b2FloatW t3 = b2UnpackLoW( simdBody->w, simdBody->flags ); // [w3 f3 w4 f4] b2FloatW t4 = b2UnpackHiW( simdBody->w, simdBody->flags ); #if 1 // I don't use any dummy body in the body array because this will lead to multithreaded cache coherence problems. if ( indices[0] != B2_NULL_INDEX && ( states[indices[0]].flags & b2_dynamicFlag ) != 0 ) { // [t1.x t1.y t3.x t3.y] b2StoreW( (float*)( states + indices[0] ), _mm_shuffle_ps( t1, t3, _MM_SHUFFLE( 1, 0, 1, 0 ) ) ); } if ( indices[1] != B2_NULL_INDEX && ( states[indices[1]].flags & b2_dynamicFlag ) != 0 ) { // [t1.z t1.w t3.z t3.w] b2StoreW( (float*)( states + indices[1] ), _mm_shuffle_ps( t1, t3, _MM_SHUFFLE( 3, 2, 3, 2 ) ) ); } if ( indices[2] != B2_NULL_INDEX && ( states[indices[2]].flags & b2_dynamicFlag ) != 0 ) { // [t2.x t2.y t4.x t4.y] b2StoreW( (float*)( states + indices[2] ), _mm_shuffle_ps( t2, t4, _MM_SHUFFLE( 1, 0, 1, 0 ) ) ); } if ( indices[3] != B2_NULL_INDEX && ( states[indices[3]].flags & b2_dynamicFlag ) != 0 ) { // [t2.z t2.w t4.z t4.w] b2StoreW( (float*)( states + indices[3] ), _mm_shuffle_ps( t2, t4, _MM_SHUFFLE( 3, 2, 3, 2 ) ) ); } #else // todo_erin this is here to test the impact of unsafe writes if ( indices[0] != B2_NULL_INDEX ) { // [t1.x t1.y t3.x t3.y] b2StoreW( (float*)( states + indices[0] ), _mm_shuffle_ps( t1, t3, _MM_SHUFFLE( 1, 0, 1, 0 ) ) ); } if ( indices[1] != B2_NULL_INDEX ) { // [t1.z t1.w t3.z t3.w] b2StoreW( (float*)( states + indices[1] ), _mm_shuffle_ps( t1, t3, _MM_SHUFFLE( 3, 2, 3, 2 ) ) ); } if ( indices[2] != B2_NULL_INDEX) { // [t2.x t2.y t4.x t4.y] b2StoreW( (float*)( states + indices[2] ), _mm_shuffle_ps( t2, t4, _MM_SHUFFLE( 1, 0, 1, 0 ) ) ); } if ( indices[3] != B2_NULL_INDEX ) { // [t2.z t2.w t4.z t4.w] b2StoreW( (float*)( states + indices[3] ), _mm_shuffle_ps( t2, t4, _MM_SHUFFLE( 3, 2, 3, 2 ) ) ); } #endif } #else // This is a load and transpose static b2BodyStateW b2GatherBodies( const b2BodyState* B2_RESTRICT states, int* B2_RESTRICT indices ) { b2BodyState identity = b2_identityBodyState; b2BodyState s1 = indices[0] == B2_NULL_INDEX ? identity : states[indices[0]]; b2BodyState s2 = indices[1] == B2_NULL_INDEX ? identity : states[indices[1]]; b2BodyState s3 = indices[2] == B2_NULL_INDEX ? identity : states[indices[2]]; b2BodyState s4 = indices[3] == B2_NULL_INDEX ? identity : states[indices[3]]; b2BodyStateW simdBody; simdBody.v.X = (b2FloatW){ s1.linearVelocity.x, s2.linearVelocity.x, s3.linearVelocity.x, s4.linearVelocity.x }; simdBody.v.Y = (b2FloatW){ s1.linearVelocity.y, s2.linearVelocity.y, s3.linearVelocity.y, s4.linearVelocity.y }; simdBody.w = (b2FloatW){ s1.angularVelocity, s2.angularVelocity, s3.angularVelocity, s4.angularVelocity }; simdBody.flags = (b2FloatW){ (float)s1.flags, (float)s2.flags, (float)s3.flags, (float)s4.flags }; simdBody.dp.X = (b2FloatW){ s1.deltaPosition.x, s2.deltaPosition.x, s3.deltaPosition.x, s4.deltaPosition.x }; simdBody.dp.Y = (b2FloatW){ s1.deltaPosition.y, s2.deltaPosition.y, s3.deltaPosition.y, s4.deltaPosition.y }; simdBody.dq.C = (b2FloatW){ s1.deltaRotation.c, s2.deltaRotation.c, s3.deltaRotation.c, s4.deltaRotation.c }; simdBody.dq.S = (b2FloatW){ s1.deltaRotation.s, s2.deltaRotation.s, s3.deltaRotation.s, s4.deltaRotation.s }; return simdBody; } // This writes only the velocities back to the solver bodies static void b2ScatterBodies( b2BodyState* B2_RESTRICT states, int* B2_RESTRICT indices, const b2BodyStateW* B2_RESTRICT simdBody ) { if ( indices[0] != B2_NULL_INDEX && ( states[indices[0]].flags & b2_dynamicFlag ) != 0 ) { b2BodyState* state = states + indices[0]; state->linearVelocity.x = simdBody->v.X.x; state->linearVelocity.y = simdBody->v.Y.x; state->angularVelocity = simdBody->w.x; } if ( indices[1] != B2_NULL_INDEX && ( states[indices[1]].flags & b2_dynamicFlag ) != 0 ) { b2BodyState* state = states + indices[1]; state->linearVelocity.x = simdBody->v.X.y; state->linearVelocity.y = simdBody->v.Y.y; state->angularVelocity = simdBody->w.y; } if ( indices[2] != B2_NULL_INDEX && ( states[indices[2]].flags & b2_dynamicFlag ) != 0 ) { b2BodyState* state = states + indices[2]; state->linearVelocity.x = simdBody->v.X.z; state->linearVelocity.y = simdBody->v.Y.z; state->angularVelocity = simdBody->w.z; } if ( indices[3] != B2_NULL_INDEX && ( states[indices[3]].flags & b2_dynamicFlag ) != 0 ) { b2BodyState* state = states + indices[3]; state->linearVelocity.x = simdBody->v.X.w; state->linearVelocity.y = simdBody->v.Y.w; state->angularVelocity = simdBody->w.w; } } #endif void b2PrepareContactsTask( int startIndex, int endIndex, b2StepContext* context ) { b2TracyCZoneNC( prepare_contact, "Prepare Contact", b2_colorYellow, true ); b2World* world = context->world; b2ContactSim** contacts = context->contacts; b2ContactConstraintSIMD* constraints = context->simdContactConstraints; b2BodyState* awakeStates = context->states; #if B2_VALIDATE b2Body* bodies = world->bodies.data; #endif // Stiffer for static contacts to avoid bodies getting pushed through the ground b2Softness contactSoftness = context->contactSoftness; b2Softness staticSoftness = context->staticSoftness; bool enableSoftening = world->enableContactSoftening; float warmStartScale = world->enableWarmStarting ? 1.0f : 0.0f; for ( int i = startIndex; i < endIndex; ++i ) { b2ContactConstraintSIMD* constraint = constraints + i; for ( int j = 0; j < B2_SIMD_WIDTH; ++j ) { b2ContactSim* contactSim = contacts[B2_SIMD_WIDTH * i + j]; if ( contactSim != NULL ) { const b2Manifold* manifold = &contactSim->manifold; int indexA = contactSim->bodySimIndexA; int indexB = contactSim->bodySimIndexB; #if B2_VALIDATE b2Body* bodyA = bodies + contactSim->bodyIdA; int validIndexA = bodyA->setIndex == b2_awakeSet ? bodyA->localIndex : B2_NULL_INDEX; b2Body* bodyB = bodies + contactSim->bodyIdB; int validIndexB = bodyB->setIndex == b2_awakeSet ? bodyB->localIndex : B2_NULL_INDEX; B2_ASSERT( indexA == validIndexA ); B2_ASSERT( indexB == validIndexB ); #endif constraint->indexA[j] = indexA; constraint->indexB[j] = indexB; b2Vec2 vA = b2Vec2_zero; float wA = 0.0f; float mA = contactSim->invMassA; float iA = contactSim->invIA; if ( indexA != B2_NULL_INDEX ) { b2BodyState* stateA = awakeStates + indexA; vA = stateA->linearVelocity; wA = stateA->angularVelocity; } b2Vec2 vB = b2Vec2_zero; float wB = 0.0f; float mB = contactSim->invMassB; float iB = contactSim->invIB; if ( indexB != B2_NULL_INDEX ) { b2BodyState* stateB = awakeStates + indexB; vB = stateB->linearVelocity; wB = stateB->angularVelocity; } ( (float*)&constraint->invMassA )[j] = mA; ( (float*)&constraint->invMassB )[j] = mB; ( (float*)&constraint->invIA )[j] = iA; ( (float*)&constraint->invIB )[j] = iB; { float k = iA + iB; ( (float*)&constraint->rollingMass )[j] = k > 0.0f ? 1.0f / k : 0.0f; } b2Softness soft = contactSoftness; if (indexA == B2_NULL_INDEX || indexB == B2_NULL_INDEX) { soft = staticSoftness; } else if (enableSoftening) { // todo experimental feature float contactHertz = b2MinFloat( world->contactHertz, 0.125f * context->inv_h ); float ratio = 1.0f; if ( mA < mB ) { ratio = b2MaxFloat( 0.5f, mA / mB ); } else if ( mB < mA ) { ratio = b2MaxFloat( 0.5f, mB / mA ); } soft = b2MakeSoft( ratio * contactHertz, ratio * world->contactDampingRatio, context->h ); } b2Vec2 normal = manifold->normal; ( (float*)&constraint->normal.X )[j] = normal.x; ( (float*)&constraint->normal.Y )[j] = normal.y; ( (float*)&constraint->friction )[j] = contactSim->friction; ( (float*)&constraint->tangentSpeed )[j] = contactSim->tangentSpeed; ( (float*)&constraint->restitution )[j] = contactSim->restitution; ( (float*)&constraint->rollingResistance )[j] = contactSim->rollingResistance; ( (float*)&constraint->rollingImpulse )[j] = warmStartScale * manifold->rollingImpulse; ( (float*)&constraint->biasRate )[j] = soft.biasRate; ( (float*)&constraint->massScale )[j] = soft.massScale; ( (float*)&constraint->impulseScale )[j] = soft.impulseScale; b2Vec2 tangent = b2RightPerp( normal ); { const b2ManifoldPoint* mp = manifold->points + 0; b2Vec2 rA = mp->anchorA; b2Vec2 rB = mp->anchorB; ( (float*)&constraint->anchorA1.X )[j] = rA.x; ( (float*)&constraint->anchorA1.Y )[j] = rA.y; ( (float*)&constraint->anchorB1.X )[j] = rB.x; ( (float*)&constraint->anchorB1.Y )[j] = rB.y; ( (float*)&constraint->baseSeparation1 )[j] = mp->separation - b2Dot( b2Sub( rB, rA ), normal ); ( (float*)&constraint->normalImpulse1 )[j] = warmStartScale * mp->normalImpulse; ( (float*)&constraint->tangentImpulse1 )[j] = warmStartScale * mp->tangentImpulse; ( (float*)&constraint->totalNormalImpulse1 )[j] = 0.0f; float rnA = b2Cross( rA, normal ); float rnB = b2Cross( rB, normal ); float kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; ( (float*)&constraint->normalMass1 )[j] = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; float rtA = b2Cross( rA, tangent ); float rtB = b2Cross( rB, tangent ); float kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; ( (float*)&constraint->tangentMass1 )[j] = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; // relative velocity for restitution b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) ); b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) ); ( (float*)&constraint->relativeVelocity1 )[j] = b2Dot( normal, b2Sub( vrB, vrA ) ); } int pointCount = manifold->pointCount; B2_ASSERT( 0 < pointCount && pointCount <= 2 ); if ( pointCount == 2 ) { const b2ManifoldPoint* mp = manifold->points + 1; b2Vec2 rA = mp->anchorA; b2Vec2 rB = mp->anchorB; ( (float*)&constraint->anchorA2.X )[j] = rA.x; ( (float*)&constraint->anchorA2.Y )[j] = rA.y; ( (float*)&constraint->anchorB2.X )[j] = rB.x; ( (float*)&constraint->anchorB2.Y )[j] = rB.y; ( (float*)&constraint->baseSeparation2 )[j] = mp->separation - b2Dot( b2Sub( rB, rA ), normal ); ( (float*)&constraint->normalImpulse2 )[j] = warmStartScale * mp->normalImpulse; ( (float*)&constraint->tangentImpulse2 )[j] = warmStartScale * mp->tangentImpulse; ( (float*)&constraint->totalNormalImpulse2 )[j] = 0.0f; float rnA = b2Cross( rA, normal ); float rnB = b2Cross( rB, normal ); float kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; ( (float*)&constraint->normalMass2 )[j] = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; float rtA = b2Cross( rA, tangent ); float rtB = b2Cross( rB, tangent ); float kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; ( (float*)&constraint->tangentMass2 )[j] = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; // relative velocity for restitution b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) ); b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) ); ( (float*)&constraint->relativeVelocity2 )[j] = b2Dot( normal, b2Sub( vrB, vrA ) ); } else { // dummy data that has no effect ( (float*)&constraint->baseSeparation2 )[j] = 0.0f; ( (float*)&constraint->normalImpulse2 )[j] = 0.0f; ( (float*)&constraint->tangentImpulse2 )[j] = 0.0f; ( (float*)&constraint->totalNormalImpulse2 )[j] = 0.0f; ( (float*)&constraint->anchorA2.X )[j] = 0.0f; ( (float*)&constraint->anchorA2.Y )[j] = 0.0f; ( (float*)&constraint->anchorB2.X )[j] = 0.0f; ( (float*)&constraint->anchorB2.Y )[j] = 0.0f; ( (float*)&constraint->normalMass2 )[j] = 0.0f; ( (float*)&constraint->tangentMass2 )[j] = 0.0f; ( (float*)&constraint->relativeVelocity2 )[j] = 0.0f; } } else { // SIMD remainder constraint->indexA[j] = B2_NULL_INDEX; constraint->indexB[j] = B2_NULL_INDEX; ( (float*)&constraint->invMassA )[j] = 0.0f; ( (float*)&constraint->invMassB )[j] = 0.0f; ( (float*)&constraint->invIA )[j] = 0.0f; ( (float*)&constraint->invIB )[j] = 0.0f; ( (float*)&constraint->normal.X )[j] = 0.0f; ( (float*)&constraint->normal.Y )[j] = 0.0f; ( (float*)&constraint->friction )[j] = 0.0f; ( (float*)&constraint->tangentSpeed )[j] = 0.0f; ( (float*)&constraint->rollingResistance )[j] = 0.0f; ( (float*)&constraint->rollingMass )[j] = 0.0f; ( (float*)&constraint->rollingImpulse )[j] = 0.0f; ( (float*)&constraint->biasRate )[j] = 0.0f; ( (float*)&constraint->massScale )[j] = 0.0f; ( (float*)&constraint->impulseScale )[j] = 0.0f; ( (float*)&constraint->anchorA1.X )[j] = 0.0f; ( (float*)&constraint->anchorA1.Y )[j] = 0.0f; ( (float*)&constraint->anchorB1.X )[j] = 0.0f; ( (float*)&constraint->anchorB1.Y )[j] = 0.0f; ( (float*)&constraint->baseSeparation1 )[j] = 0.0f; ( (float*)&constraint->normalImpulse1 )[j] = 0.0f; ( (float*)&constraint->tangentImpulse1 )[j] = 0.0f; ( (float*)&constraint->totalNormalImpulse1 )[j] = 0.0f; ( (float*)&constraint->normalMass1 )[j] = 0.0f; ( (float*)&constraint->tangentMass1 )[j] = 0.0f; ( (float*)&constraint->anchorA2.X )[j] = 0.0f; ( (float*)&constraint->anchorA2.Y )[j] = 0.0f; ( (float*)&constraint->anchorB2.X )[j] = 0.0f; ( (float*)&constraint->anchorB2.Y )[j] = 0.0f; ( (float*)&constraint->baseSeparation2 )[j] = 0.0f; ( (float*)&constraint->normalImpulse2 )[j] = 0.0f; ( (float*)&constraint->tangentImpulse2 )[j] = 0.0f; ( (float*)&constraint->totalNormalImpulse2 )[j] = 0.0f; ( (float*)&constraint->normalMass2 )[j] = 0.0f; ( (float*)&constraint->tangentMass2 )[j] = 0.0f; ( (float*)&constraint->restitution )[j] = 0.0f; ( (float*)&constraint->relativeVelocity1 )[j] = 0.0f; ( (float*)&constraint->relativeVelocity2 )[j] = 0.0f; } } } b2TracyCZoneEnd( prepare_contact ); } void b2WarmStartContactsTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex ) { b2TracyCZoneNC( warm_start_contact, "Warm Start", b2_colorGreen, true ); b2BodyState* states = context->states; b2ContactConstraintSIMD* constraints = context->graph->colors[colorIndex].simdConstraints; for ( int i = startIndex; i < endIndex; ++i ) { b2ContactConstraintSIMD* c = constraints + i; b2BodyStateW bA = b2GatherBodies( states, c->indexA ); b2BodyStateW bB = b2GatherBodies( states, c->indexB ); b2FloatW tangentX = c->normal.Y; b2FloatW tangentY = b2SubW( b2ZeroW(), c->normal.X ); { // fixed anchors b2Vec2W rA = c->anchorA1; b2Vec2W rB = c->anchorB1; b2Vec2W P; P.X = b2AddW( b2MulW( c->normalImpulse1, c->normal.X ), b2MulW( c->tangentImpulse1, tangentX ) ); P.Y = b2AddW( b2MulW( c->normalImpulse1, c->normal.Y ), b2MulW( c->tangentImpulse1, tangentY ) ); bA.w = b2MulSubW( bA.w, c->invIA, b2CrossW( rA, P ) ); bA.v.X = b2MulSubW( bA.v.X, c->invMassA, P.X ); bA.v.Y = b2MulSubW( bA.v.Y, c->invMassA, P.Y ); bB.w = b2MulAddW( bB.w, c->invIB, b2CrossW( rB, P ) ); bB.v.X = b2MulAddW( bB.v.X, c->invMassB, P.X ); bB.v.Y = b2MulAddW( bB.v.Y, c->invMassB, P.Y ); c->totalNormalImpulse1 = b2AddW( c->totalNormalImpulse1, c->normalImpulse1 ); } { // fixed anchors b2Vec2W rA = c->anchorA2; b2Vec2W rB = c->anchorB2; b2Vec2W P; P.X = b2AddW( b2MulW( c->normalImpulse2, c->normal.X ), b2MulW( c->tangentImpulse2, tangentX ) ); P.Y = b2AddW( b2MulW( c->normalImpulse2, c->normal.Y ), b2MulW( c->tangentImpulse2, tangentY ) ); bA.w = b2MulSubW( bA.w, c->invIA, b2CrossW( rA, P ) ); bA.v.X = b2MulSubW( bA.v.X, c->invMassA, P.X ); bA.v.Y = b2MulSubW( bA.v.Y, c->invMassA, P.Y ); bB.w = b2MulAddW( bB.w, c->invIB, b2CrossW( rB, P ) ); bB.v.X = b2MulAddW( bB.v.X, c->invMassB, P.X ); bB.v.Y = b2MulAddW( bB.v.Y, c->invMassB, P.Y ); c->totalNormalImpulse2 = b2AddW( c->totalNormalImpulse2, c->normalImpulse2 ); } bA.w = b2MulSubW( bA.w, c->invIA, c->rollingImpulse ); bB.w = b2MulAddW( bB.w, c->invIB, c->rollingImpulse ); b2ScatterBodies( states, c->indexA, &bA ); b2ScatterBodies( states, c->indexB, &bB ); } b2TracyCZoneEnd( warm_start_contact ); } void b2SolveContactsTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex, bool useBias ) { b2TracyCZoneNC( solve_contact, "Solve Contact", b2_colorAliceBlue, true ); b2BodyState* states = context->states; b2ContactConstraintSIMD* constraints = context->graph->colors[colorIndex].simdConstraints; b2FloatW inv_h = b2SplatW( context->inv_h ); b2FloatW contactSpeed = b2SplatW( -context->world->contactSpeed ); b2FloatW oneW = b2SplatW( 1.0f ); for ( int i = startIndex; i < endIndex; ++i ) { b2ContactConstraintSIMD* c = constraints + i; b2BodyStateW bA = b2GatherBodies( states, c->indexA ); b2BodyStateW bB = b2GatherBodies( states, c->indexB ); b2FloatW biasRate, massScale, impulseScale; if ( useBias ) { biasRate = b2MulW( c->massScale, c->biasRate ); massScale = c->massScale; impulseScale = c->impulseScale; } else { biasRate = b2ZeroW(); massScale = oneW; impulseScale = b2ZeroW(); } b2FloatW totalNormalImpulse = b2ZeroW(); b2Vec2W dp = { b2SubW( bB.dp.X, bA.dp.X ), b2SubW( bB.dp.Y, bA.dp.Y ) }; // point1 non-penetration constraint { // Fixed anchors for impulses b2Vec2W rA = c->anchorA1; b2Vec2W rB = c->anchorB1; // Moving anchors for current separation b2Vec2W rsA = b2RotateVectorW( bA.dq, rA ); b2Vec2W rsB = b2RotateVectorW( bB.dq, rB ); // compute current separation // this is subject to round-off error if the anchor is far from the body center of mass b2Vec2W ds = { b2AddW( dp.X, b2SubW( rsB.X, rsA.X ) ), b2AddW( dp.Y, b2SubW( rsB.Y, rsA.Y ) ) }; b2FloatW s = b2AddW( b2DotW( c->normal, ds ), c->baseSeparation1 ); // Apply speculative bias if separation is greater than zero, otherwise apply soft constraint bias // The contactSpeed is meant to limit stiffness, not increase it. b2FloatW mask = b2GreaterThanW( s, b2ZeroW() ); b2FloatW specBias = b2MulW( s, inv_h ); b2FloatW softBias = b2MaxW( b2MulW( biasRate, s ), contactSpeed ); // todo try b2MaxW(softBias, specBias); b2FloatW bias = b2BlendW( softBias, specBias, mask ); b2FloatW pointMassScale = b2BlendW( massScale, oneW, mask ); b2FloatW pointImpulseScale = b2BlendW( impulseScale, b2ZeroW(), mask ); // Relative velocity at contact b2FloatW dvx = b2SubW( b2SubW( bB.v.X, b2MulW( bB.w, rB.Y ) ), b2SubW( bA.v.X, b2MulW( bA.w, rA.Y ) ) ); b2FloatW dvy = b2SubW( b2AddW( bB.v.Y, b2MulW( bB.w, rB.X ) ), b2AddW( bA.v.Y, b2MulW( bA.w, rA.X ) ) ); b2FloatW vn = b2AddW( b2MulW( dvx, c->normal.X ), b2MulW( dvy, c->normal.Y ) ); // Compute normal impulse b2FloatW negImpulse = b2AddW( b2MulW( c->normalMass1, b2AddW( b2MulW( pointMassScale, vn ), bias ) ), b2MulW( pointImpulseScale, c->normalImpulse1 ) ); // Clamp the accumulated impulse b2FloatW newImpulse = b2MaxW( b2SubW( c->normalImpulse1, negImpulse ), b2ZeroW() ); b2FloatW impulse = b2SubW( newImpulse, c->normalImpulse1 ); c->normalImpulse1 = newImpulse; c->totalNormalImpulse1 = b2AddW( c->totalNormalImpulse1, impulse ); totalNormalImpulse = b2AddW( totalNormalImpulse, newImpulse ); // Apply contact impulse b2FloatW Px = b2MulW( impulse, c->normal.X ); b2FloatW Py = b2MulW( impulse, c->normal.Y ); bA.v.X = b2MulSubW( bA.v.X, c->invMassA, Px ); bA.v.Y = b2MulSubW( bA.v.Y, c->invMassA, Py ); bA.w = b2MulSubW( bA.w, c->invIA, b2SubW( b2MulW( rA.X, Py ), b2MulW( rA.Y, Px ) ) ); bB.v.X = b2MulAddW( bB.v.X, c->invMassB, Px ); bB.v.Y = b2MulAddW( bB.v.Y, c->invMassB, Py ); bB.w = b2MulAddW( bB.w, c->invIB, b2SubW( b2MulW( rB.X, Py ), b2MulW( rB.Y, Px ) ) ); } // second point non-penetration constraint { // moving anchors for current separation b2Vec2W rsA = b2RotateVectorW( bA.dq, c->anchorA2 ); b2Vec2W rsB = b2RotateVectorW( bB.dq, c->anchorB2 ); // compute current separation b2Vec2W ds = { b2AddW( dp.X, b2SubW( rsB.X, rsA.X ) ), b2AddW( dp.Y, b2SubW( rsB.Y, rsA.Y ) ) }; b2FloatW s = b2AddW( b2DotW( c->normal, ds ), c->baseSeparation2 ); b2FloatW mask = b2GreaterThanW( s, b2ZeroW() ); b2FloatW specBias = b2MulW( s, inv_h ); b2FloatW softBias = b2MaxW( b2MulW( biasRate, s ), contactSpeed ); b2FloatW bias = b2BlendW( softBias, specBias, mask ); b2FloatW pointMassScale = b2BlendW( massScale, oneW, mask ); b2FloatW pointImpulseScale = b2BlendW( impulseScale, b2ZeroW(), mask ); // fixed anchors for Jacobians b2Vec2W rA = c->anchorA2; b2Vec2W rB = c->anchorB2; // Relative velocity at contact b2FloatW dvx = b2SubW( b2SubW( bB.v.X, b2MulW( bB.w, rB.Y ) ), b2SubW( bA.v.X, b2MulW( bA.w, rA.Y ) ) ); b2FloatW dvy = b2SubW( b2AddW( bB.v.Y, b2MulW( bB.w, rB.X ) ), b2AddW( bA.v.Y, b2MulW( bA.w, rA.X ) ) ); b2FloatW vn = b2AddW( b2MulW( dvx, c->normal.X ), b2MulW( dvy, c->normal.Y ) ); // Compute normal impulse b2FloatW negImpulse = b2AddW( b2MulW( c->normalMass2, b2AddW( b2MulW( pointMassScale, vn ), bias ) ), b2MulW( pointImpulseScale, c->normalImpulse2 ) ); // Clamp the accumulated impulse b2FloatW newImpulse = b2MaxW( b2SubW( c->normalImpulse2, negImpulse ), b2ZeroW() ); b2FloatW impulse = b2SubW( newImpulse, c->normalImpulse2 ); c->normalImpulse2 = newImpulse; c->totalNormalImpulse2 = b2AddW( c->totalNormalImpulse2, impulse ); totalNormalImpulse = b2AddW( totalNormalImpulse, newImpulse ); // Apply contact impulse b2FloatW Px = b2MulW( impulse, c->normal.X ); b2FloatW Py = b2MulW( impulse, c->normal.Y ); bA.v.X = b2MulSubW( bA.v.X, c->invMassA, Px ); bA.v.Y = b2MulSubW( bA.v.Y, c->invMassA, Py ); bA.w = b2MulSubW( bA.w, c->invIA, b2SubW( b2MulW( rA.X, Py ), b2MulW( rA.Y, Px ) ) ); bB.v.X = b2MulAddW( bB.v.X, c->invMassB, Px ); bB.v.Y = b2MulAddW( bB.v.Y, c->invMassB, Py ); bB.w = b2MulAddW( bB.w, c->invIB, b2SubW( b2MulW( rB.X, Py ), b2MulW( rB.Y, Px ) ) ); } b2FloatW tangentX = c->normal.Y; b2FloatW tangentY = b2SubW( b2ZeroW(), c->normal.X ); // point 1 friction constraint { // fixed anchors for Jacobians b2Vec2W rA = c->anchorA1; b2Vec2W rB = c->anchorB1; // Relative velocity at contact b2FloatW dvx = b2SubW( b2SubW( bB.v.X, b2MulW( bB.w, rB.Y ) ), b2SubW( bA.v.X, b2MulW( bA.w, rA.Y ) ) ); b2FloatW dvy = b2SubW( b2AddW( bB.v.Y, b2MulW( bB.w, rB.X ) ), b2AddW( bA.v.Y, b2MulW( bA.w, rA.X ) ) ); b2FloatW vt = b2AddW( b2MulW( dvx, tangentX ), b2MulW( dvy, tangentY ) ); // Tangent speed (conveyor belt) vt = b2SubW( vt, c->tangentSpeed ); // Compute tangent force b2FloatW negImpulse = b2MulW( c->tangentMass1, vt ); // Clamp the accumulated force b2FloatW maxFriction = b2MulW( c->friction, c->normalImpulse1 ); b2FloatW newImpulse = b2SubW( c->tangentImpulse1, negImpulse ); newImpulse = b2MaxW( b2SubW( b2ZeroW(), maxFriction ), b2MinW( newImpulse, maxFriction ) ); b2FloatW impulse = b2SubW( newImpulse, c->tangentImpulse1 ); c->tangentImpulse1 = newImpulse; // Apply contact impulse b2FloatW Px = b2MulW( impulse, tangentX ); b2FloatW Py = b2MulW( impulse, tangentY ); bA.v.X = b2MulSubW( bA.v.X, c->invMassA, Px ); bA.v.Y = b2MulSubW( bA.v.Y, c->invMassA, Py ); bA.w = b2MulSubW( bA.w, c->invIA, b2SubW( b2MulW( rA.X, Py ), b2MulW( rA.Y, Px ) ) ); bB.v.X = b2MulAddW( bB.v.X, c->invMassB, Px ); bB.v.Y = b2MulAddW( bB.v.Y, c->invMassB, Py ); bB.w = b2MulAddW( bB.w, c->invIB, b2SubW( b2MulW( rB.X, Py ), b2MulW( rB.Y, Px ) ) ); } // second point friction constraint { // fixed anchors for Jacobians b2Vec2W rA = c->anchorA2; b2Vec2W rB = c->anchorB2; // Relative velocity at contact b2FloatW dvx = b2SubW( b2SubW( bB.v.X, b2MulW( bB.w, rB.Y ) ), b2SubW( bA.v.X, b2MulW( bA.w, rA.Y ) ) ); b2FloatW dvy = b2SubW( b2AddW( bB.v.Y, b2MulW( bB.w, rB.X ) ), b2AddW( bA.v.Y, b2MulW( bA.w, rA.X ) ) ); b2FloatW vt = b2AddW( b2MulW( dvx, tangentX ), b2MulW( dvy, tangentY ) ); // Tangent speed (conveyor belt) vt = b2SubW( vt, c->tangentSpeed ); // Compute tangent force b2FloatW negImpulse = b2MulW( c->tangentMass2, vt ); // Clamp the accumulated force b2FloatW maxFriction = b2MulW( c->friction, c->normalImpulse2 ); b2FloatW newImpulse = b2SubW( c->tangentImpulse2, negImpulse ); newImpulse = b2MaxW( b2SubW( b2ZeroW(), maxFriction ), b2MinW( newImpulse, maxFriction ) ); b2FloatW impulse = b2SubW( newImpulse, c->tangentImpulse2 ); c->tangentImpulse2 = newImpulse; // Apply contact impulse b2FloatW Px = b2MulW( impulse, tangentX ); b2FloatW Py = b2MulW( impulse, tangentY ); bA.v.X = b2MulSubW( bA.v.X, c->invMassA, Px ); bA.v.Y = b2MulSubW( bA.v.Y, c->invMassA, Py ); bA.w = b2MulSubW( bA.w, c->invIA, b2SubW( b2MulW( rA.X, Py ), b2MulW( rA.Y, Px ) ) ); bB.v.X = b2MulAddW( bB.v.X, c->invMassB, Px ); bB.v.Y = b2MulAddW( bB.v.Y, c->invMassB, Py ); bB.w = b2MulAddW( bB.w, c->invIB, b2SubW( b2MulW( rB.X, Py ), b2MulW( rB.Y, Px ) ) ); } // Rolling resistance { b2FloatW deltaLambda = b2MulW( c->rollingMass, b2SubW( bA.w, bB.w ) ); b2FloatW lambda = c->rollingImpulse; b2FloatW maxLambda = b2MulW( c->rollingResistance, totalNormalImpulse ); c->rollingImpulse = b2SymClampW( b2AddW( lambda, deltaLambda ), maxLambda ); deltaLambda = b2SubW( c->rollingImpulse, lambda ); bA.w = b2MulSubW( bA.w, c->invIA, deltaLambda ); bB.w = b2MulAddW( bB.w, c->invIB, deltaLambda ); } b2ScatterBodies( states, c->indexA, &bA ); b2ScatterBodies( states, c->indexB, &bB ); } b2TracyCZoneEnd( solve_contact ); } void b2ApplyRestitutionTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex ) { b2TracyCZoneNC( restitution, "Restitution", b2_colorDodgerBlue, true ); b2BodyState* states = context->states; b2ContactConstraintSIMD* constraints = context->graph->colors[colorIndex].simdConstraints; b2FloatW threshold = b2SplatW( context->world->restitutionThreshold ); b2FloatW zero = b2ZeroW(); for ( int i = startIndex; i < endIndex; ++i ) { b2ContactConstraintSIMD* c = constraints + i; if ( b2AllZeroW( c->restitution ) ) { // No lanes have restitution. Common case. continue; } // Create a mask based on restitution so that lanes with no restitution are not affected // by the calculations below. b2FloatW restitutionMask = b2EqualsW( c->restitution, zero ); b2BodyStateW bA = b2GatherBodies( states, c->indexA ); b2BodyStateW bB = b2GatherBodies( states, c->indexB ); // first point non-penetration constraint { // Set effective mass to zero if restitution should not be applied b2FloatW mask1 = b2GreaterThanW( b2AddW( c->relativeVelocity1, threshold ), zero ); b2FloatW mask2 = b2EqualsW( c->totalNormalImpulse1, zero ); b2FloatW mask = b2OrW( b2OrW( mask1, mask2 ), restitutionMask ); b2FloatW mass = b2BlendW( c->normalMass1, zero, mask ); // fixed anchors for Jacobians b2Vec2W rA = c->anchorA1; b2Vec2W rB = c->anchorB1; // Relative velocity at contact b2FloatW dvx = b2SubW( b2SubW( bB.v.X, b2MulW( bB.w, rB.Y ) ), b2SubW( bA.v.X, b2MulW( bA.w, rA.Y ) ) ); b2FloatW dvy = b2SubW( b2AddW( bB.v.Y, b2MulW( bB.w, rB.X ) ), b2AddW( bA.v.Y, b2MulW( bA.w, rA.X ) ) ); b2FloatW vn = b2AddW( b2MulW( dvx, c->normal.X ), b2MulW( dvy, c->normal.Y ) ); // Compute normal impulse b2FloatW negImpulse = b2MulW( mass, b2AddW( vn, b2MulW( c->restitution, c->relativeVelocity1 ) ) ); // Clamp the accumulated impulse b2FloatW newImpulse = b2MaxW( b2SubW( c->normalImpulse1, negImpulse ), b2ZeroW() ); b2FloatW deltaImpulse = b2SubW( newImpulse, c->normalImpulse1 ); c->normalImpulse1 = newImpulse; c->totalNormalImpulse1 = b2AddW( c->totalNormalImpulse1, deltaImpulse ); // Apply contact impulse b2FloatW Px = b2MulW( deltaImpulse, c->normal.X ); b2FloatW Py = b2MulW( deltaImpulse, c->normal.Y ); bA.v.X = b2MulSubW( bA.v.X, c->invMassA, Px ); bA.v.Y = b2MulSubW( bA.v.Y, c->invMassA, Py ); bA.w = b2MulSubW( bA.w, c->invIA, b2SubW( b2MulW( rA.X, Py ), b2MulW( rA.Y, Px ) ) ); bB.v.X = b2MulAddW( bB.v.X, c->invMassB, Px ); bB.v.Y = b2MulAddW( bB.v.Y, c->invMassB, Py ); bB.w = b2MulAddW( bB.w, c->invIB, b2SubW( b2MulW( rB.X, Py ), b2MulW( rB.Y, Px ) ) ); } // second point non-penetration constraint { // Set effective mass to zero if restitution should not be applied b2FloatW mask1 = b2GreaterThanW( b2AddW( c->relativeVelocity2, threshold ), zero ); b2FloatW mask2 = b2EqualsW( c->totalNormalImpulse2, zero ); b2FloatW mask = b2OrW( b2OrW( mask1, mask2 ), restitutionMask ); b2FloatW mass = b2BlendW( c->normalMass2, zero, mask ); // fixed anchors for Jacobians b2Vec2W rA = c->anchorA2; b2Vec2W rB = c->anchorB2; // Relative velocity at contact b2FloatW dvx = b2SubW( b2SubW( bB.v.X, b2MulW( bB.w, rB.Y ) ), b2SubW( bA.v.X, b2MulW( bA.w, rA.Y ) ) ); b2FloatW dvy = b2SubW( b2AddW( bB.v.Y, b2MulW( bB.w, rB.X ) ), b2AddW( bA.v.Y, b2MulW( bA.w, rA.X ) ) ); b2FloatW vn = b2AddW( b2MulW( dvx, c->normal.X ), b2MulW( dvy, c->normal.Y ) ); // Compute normal impulse b2FloatW negImpulse = b2MulW( mass, b2AddW( vn, b2MulW( c->restitution, c->relativeVelocity2 ) ) ); // Clamp the accumulated impulse b2FloatW newImpulse = b2MaxW( b2SubW( c->normalImpulse2, negImpulse ), b2ZeroW() ); b2FloatW deltaImpulse = b2SubW( newImpulse, c->normalImpulse2 ); c->normalImpulse2 = newImpulse; c->totalNormalImpulse2 = b2AddW( c->totalNormalImpulse2, deltaImpulse ); // Apply contact impulse b2FloatW Px = b2MulW( deltaImpulse, c->normal.X ); b2FloatW Py = b2MulW( deltaImpulse, c->normal.Y ); bA.v.X = b2MulSubW( bA.v.X, c->invMassA, Px ); bA.v.Y = b2MulSubW( bA.v.Y, c->invMassA, Py ); bA.w = b2MulSubW( bA.w, c->invIA, b2SubW( b2MulW( rA.X, Py ), b2MulW( rA.Y, Px ) ) ); bB.v.X = b2MulAddW( bB.v.X, c->invMassB, Px ); bB.v.Y = b2MulAddW( bB.v.Y, c->invMassB, Py ); bB.w = b2MulAddW( bB.w, c->invIB, b2SubW( b2MulW( rB.X, Py ), b2MulW( rB.Y, Px ) ) ); } b2ScatterBodies( states, c->indexA, &bA ); b2ScatterBodies( states, c->indexB, &bB ); } b2TracyCZoneEnd( restitution ); } void b2StoreImpulsesTask( int startIndex, int endIndex, b2StepContext* context ) { b2TracyCZoneNC( store_impulses, "Store", b2_colorFireBrick, true ); b2ContactSim** contacts = context->contacts; const b2ContactConstraintSIMD* constraints = context->simdContactConstraints; b2Manifold dummy = { 0 }; for ( int constraintIndex = startIndex; constraintIndex < endIndex; ++constraintIndex ) { const b2ContactConstraintSIMD* c = constraints + constraintIndex; const float* rollingImpulse = (float*)&c->rollingImpulse; const float* normalImpulse1 = (float*)&c->normalImpulse1; const float* normalImpulse2 = (float*)&c->normalImpulse2; const float* tangentImpulse1 = (float*)&c->tangentImpulse1; const float* tangentImpulse2 = (float*)&c->tangentImpulse2; const float* totalNormalImpulse1 = (float*)&c->totalNormalImpulse1; const float* totalNormalImpulse2 = (float*)&c->totalNormalImpulse2; const float* normalVelocity1 = (float*)&c->relativeVelocity1; const float* normalVelocity2 = (float*)&c->relativeVelocity2; int baseIndex = B2_SIMD_WIDTH * constraintIndex; for ( int laneIndex = 0; laneIndex < B2_SIMD_WIDTH; ++laneIndex ) { b2Manifold* m = contacts[baseIndex + laneIndex] == NULL ? &dummy : &contacts[baseIndex + laneIndex]->manifold; m->rollingImpulse = rollingImpulse[laneIndex]; m->points[0].normalImpulse = normalImpulse1[laneIndex]; m->points[0].tangentImpulse = tangentImpulse1[laneIndex]; m->points[0].totalNormalImpulse = totalNormalImpulse1[laneIndex]; m->points[0].normalVelocity = normalVelocity1[laneIndex]; m->points[1].normalImpulse = normalImpulse2[laneIndex]; m->points[1].tangentImpulse = tangentImpulse2[laneIndex]; m->points[1].totalNormalImpulse = totalNormalImpulse2[laneIndex]; m->points[1].normalVelocity = normalVelocity2[laneIndex]; } } b2TracyCZoneEnd( store_impulses ); } ================================================ FILE: src/contact_solver.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "solver.h" typedef struct b2ContactSim b2ContactSim; typedef struct b2ContactConstraintPoint { b2Vec2 anchorA, anchorB; float baseSeparation; float relativeVelocity; float normalImpulse; float tangentImpulse; float totalNormalImpulse; float normalMass; float tangentMass; } b2ContactConstraintPoint; typedef struct b2ContactConstraint { int indexA; int indexB; b2ContactConstraintPoint points[2]; b2Vec2 normal; float invMassA, invMassB; float invIA, invIB; float friction; float restitution; float tangentSpeed; float rollingResistance; float rollingMass; float rollingImpulse; b2Softness softness; int pointCount; } b2ContactConstraint; int b2GetContactConstraintSIMDByteCount( void ); // Overflow contacts don't fit into the constraint graph coloring void b2PrepareOverflowContacts( b2StepContext* context ); void b2WarmStartOverflowContacts( b2StepContext* context ); void b2SolveOverflowContacts( b2StepContext* context, bool useBias ); void b2ApplyOverflowRestitution( b2StepContext* context ); void b2StoreOverflowImpulses( b2StepContext* context ); // Contacts that live within the constraint graph coloring void b2PrepareContactsTask( int startIndex, int endIndex, b2StepContext* context ); void b2WarmStartContactsTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex ); void b2SolveContactsTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex, bool useBias ); void b2ApplyRestitutionTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex ); void b2StoreImpulsesTask( int startIndex, int endIndex, b2StepContext* context ); ================================================ FILE: src/core.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "core.h" #include "box2d/math_functions.h" #if defined( B2_COMPILER_MSVC ) #define _CRTDBG_MAP_ALLOC #include #include #else #include #endif #include #include #include #ifdef BOX2D_PROFILE #include #define b2TracyCAlloc( ptr, size ) TracyCAlloc( ptr, size ) #define b2TracyCFree( ptr ) TracyCFree( ptr ) #else #define b2TracyCAlloc( ptr, size ) #define b2TracyCFree( ptr ) #endif #include "atomic.h" // This allows the user to change the length units at runtime float b2_lengthUnitsPerMeter = 1.0f; void b2SetLengthUnitsPerMeter( float lengthUnits ) { B2_ASSERT( b2IsValidFloat( lengthUnits ) && lengthUnits > 0.0f ); b2_lengthUnitsPerMeter = lengthUnits; } float b2GetLengthUnitsPerMeter( void ) { return b2_lengthUnitsPerMeter; } static int b2DefaultAssertFcn( const char* condition, const char* fileName, int lineNumber ) { printf( "BOX2D ASSERTION: %s, %s, line %d\n", condition, fileName, lineNumber ); // return non-zero to break to debugger return 1; } static b2AssertFcn* b2AssertHandler = b2DefaultAssertFcn; void b2SetAssertFcn( b2AssertFcn* assertFcn ) { B2_ASSERT( assertFcn != NULL ); b2AssertHandler = assertFcn; } #if !defined( NDEBUG ) || defined( B2_ENABLE_ASSERT ) int b2InternalAssertFcn( const char* condition, const char* fileName, int lineNumber ) { return b2AssertHandler( condition, fileName, lineNumber ); } #endif static void b2DefaultLogFcn( const char* message ) { printf( "Box2D: %s\n", message ); } b2LogFcn* b2LogHandler = b2DefaultLogFcn; void b2SetLogFcn( b2LogFcn* logFcn ) { B2_ASSERT( logFcn != NULL ); b2LogHandler = logFcn; } void b2Log( const char* format, ... ) { va_list args; va_start( args, format ); char buffer[512]; vsnprintf( buffer, sizeof( buffer ), format, args ); b2LogHandler( buffer ); va_end( args ); } b2Version b2GetVersion( void ) { return (b2Version){ .major = 3, .minor = 2, .revision = 0, }; } static b2AllocFcn* b2_allocFcn = NULL; static b2FreeFcn* b2_freeFcn = NULL; static b2AtomicInt b2_byteCount; void b2SetAllocator( b2AllocFcn* allocFcn, b2FreeFcn* freeFcn ) { b2_allocFcn = allocFcn; b2_freeFcn = freeFcn; } // Use 32 byte alignment for everything. Works with 256bit SIMD. #define B2_ALIGNMENT 32 void* b2Alloc( int size ) { if ( size == 0 ) { return NULL; } // This could cause some sharing issues, however Box2D rarely calls b2Alloc. b2AtomicFetchAddInt( &b2_byteCount, size ); // Allocation must be a multiple of 32 or risk a seg fault // https://en.cppreference.com/w/c/memory/aligned_alloc int size32 = ( ( size - 1 ) | 0x1F ) + 1; if ( b2_allocFcn != NULL ) { void* ptr = b2_allocFcn( size32, B2_ALIGNMENT ); b2TracyCAlloc( ptr, size ); B2_ASSERT( ptr != NULL ); B2_ASSERT( ( (uintptr_t)ptr & 0x1F ) == 0 ); return ptr; } #ifdef B2_PLATFORM_WINDOWS void* ptr = _aligned_malloc( size32, B2_ALIGNMENT ); #elif defined( B2_PLATFORM_ANDROID ) void* ptr = NULL; if ( posix_memalign( &ptr, B2_ALIGNMENT, size32 ) != 0 ) { // allocation failed, exit the application exit( EXIT_FAILURE ); } #else void* ptr = aligned_alloc( B2_ALIGNMENT, size32 ); #endif b2TracyCAlloc( ptr, size ); B2_ASSERT( ptr != NULL ); B2_ASSERT( ( (uintptr_t)ptr & 0x1F ) == 0 ); return ptr; } void b2Free( void* mem, int size ) { if ( mem == NULL ) { return; } b2TracyCFree( mem ); if ( b2_freeFcn != NULL ) { b2_freeFcn( mem, size ); } else { #ifdef B2_PLATFORM_WINDOWS _aligned_free( mem ); #else free( mem ); #endif } b2AtomicFetchAddInt( &b2_byteCount, -size ); } void* b2GrowAlloc( void* oldMem, int oldSize, int newSize ) { B2_ASSERT( newSize > oldSize ); void* newMem = b2Alloc( newSize ); if ( oldSize > 0 ) { memcpy( newMem, oldMem, oldSize ); b2Free( oldMem, oldSize ); } return newMem; } int b2GetByteCount( void ) { return b2AtomicLoadInt( &b2_byteCount ); } ================================================ FILE: src/core.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "box2d/base.h" // clang-format off #define B2_NULL_INDEX ( -1 ) // for performance comparisons #define B2_RESTRICT restrict #ifdef NDEBUG #define B2_DEBUG 0 #else #define B2_DEBUG 1 #endif #if defined( BOX2D_VALIDATE ) && !defined( NDEBUG ) #define B2_VALIDATE 1 #else #define B2_VALIDATE 0 #endif // Define platform #if defined(_WIN32) || defined(_WIN64) #define B2_PLATFORM_WINDOWS #elif defined( __ANDROID__ ) #define B2_PLATFORM_ANDROID #elif defined( __linux__ ) #define B2_PLATFORM_LINUX #elif defined( __APPLE__ ) #include #if defined( TARGET_OS_IPHONE ) && !TARGET_OS_IPHONE #define B2_PLATFORM_MACOS #else #define B2_PLATFORM_IOS #endif #elif defined( __EMSCRIPTEN__ ) #define B2_PLATFORM_WASM #else #define B2_PLATFORM_UNKNOWN #endif // Define CPU #if defined( __x86_64__ ) || defined( _M_X64 ) || defined( __i386__ ) || defined( _M_IX86 ) #define B2_CPU_X86_X64 #elif defined( __aarch64__ ) || defined( _M_ARM64 ) || defined( __arm__ ) || defined( _M_ARM ) #define B2_CPU_ARM #elif defined( __EMSCRIPTEN__ ) #define B2_CPU_WASM #else #define B2_CPU_UNKNOWN #endif // Define SIMD #if defined( BOX2D_DISABLE_SIMD ) #define B2_SIMD_NONE // note: I tried width of 1 and got no performance change #define B2_SIMD_WIDTH 4 #else #if defined( B2_CPU_X86_X64 ) #if defined( BOX2D_AVX2 ) #define B2_SIMD_AVX2 #define B2_SIMD_WIDTH 8 #else #define B2_SIMD_SSE2 #define B2_SIMD_WIDTH 4 #endif #elif defined( B2_CPU_ARM ) #define B2_SIMD_NEON #define B2_SIMD_WIDTH 4 #elif defined( B2_CPU_WASM ) #define B2_CPU_WASM #define B2_SIMD_SSE2 #define B2_SIMD_WIDTH 4 #else #define B2_SIMD_NONE #define B2_SIMD_WIDTH 4 #endif #endif // Define compiler #if defined( __clang__ ) #define B2_COMPILER_CLANG #elif defined( __GNUC__ ) #define B2_COMPILER_GCC #elif defined( _MSC_VER ) #define B2_COMPILER_MSVC #endif /// Tracy profiler instrumentation /// https://github.com/wolfpld/tracy #ifdef BOX2D_PROFILE #include #define b2TracyCZoneC( ctx, color, active ) TracyCZoneC( ctx, color, active ) #define b2TracyCZoneNC( ctx, name, color, active ) TracyCZoneNC( ctx, name, color, active ) #define b2TracyCZoneEnd( ctx ) TracyCZoneEnd( ctx ) #define b2TracyCFrame TracyCFrameMark #else #define b2TracyCZoneC( ctx, color, active ) #define b2TracyCZoneNC( ctx, name, color, active ) #define b2TracyCZoneEnd( ctx ) #define b2TracyCFrame #endif // clang-format on // Returns the number of elements of an array #define B2_ARRAY_COUNT( A ) (int)( sizeof( A ) / sizeof( A[0] ) ) // Used to prevent the compiler from warning about unused variables #define B2_UNUSED( ... ) (void)sizeof( ( __VA_ARGS__, 0 ) ) // Use to validate definitions. Do not take my cookie. #define B2_SECRET_COOKIE 1152023 // Snoop counters. These should be disabled in optimized builds because they are expensive. #if defined( box2d_EXPORTS ) #define B2_SNOOP_TABLE_COUNTERS B2_DEBUG #define B2_SNOOP_PAIR_COUNTERS B2_DEBUG #define B2_SNOOP_TOI_COUNTERS B2_DEBUG #else #define B2_SNOOP_TABLE_COUNTERS 0 #define B2_SNOOP_PAIR_COUNTERS 0 #define B2_SNOOP_TOI_COUNTERS 0 #endif #define B2_CHECK_DEF( DEF ) B2_ASSERT( DEF->internalValue == B2_SECRET_COOKIE ) typedef struct b2AtomicInt { int value; } b2AtomicInt; typedef struct b2AtomicU32 { uint32_t value; } b2AtomicU32; void* b2Alloc( int size ); #define B2_ALLOC_STRUCT( type ) b2Alloc(sizeof(type)) #define B2_ALLOC_ARRAY( count, type ) b2Alloc(count * sizeof(type)) void b2Free( void* mem, int size ); #define B2_FREE_STRUCT( mem, type ) b2Free( mem, sizeof(type)); #define B2_FREE_ARRAY( mem, count, type ) b2Free(mem, count * sizeof(type)) void* b2GrowAlloc( void* oldMem, int oldSize, int newSize ); void b2Log( const char* format, ... ); typedef struct b2Mutex b2Mutex; b2Mutex* b2CreateMutex( void ); void b2DestroyMutex( b2Mutex* m ); void b2LockMutex( b2Mutex* m ); void b2UnlockMutex( b2Mutex* m ); ================================================ FILE: src/ctz.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include #include #if defined( _MSC_VER ) && !defined( __clang__ ) #include // https://en.wikipedia.org/wiki/Find_first_set static inline uint32_t b2CTZ32( uint32_t block ) { unsigned long index; _BitScanForward( &index, block ); return index; } // This function doesn't need to be fast, so using the Ivy Bridge fallback. static inline uint32_t b2CLZ32( uint32_t value ) { #if 1 // Use BSR (Bit Scan Reverse) which is available on Ivy Bridge unsigned long index; if ( _BitScanReverse( &index, value ) ) { // BSR gives the index of the most significant 1-bit // We need to invert this to get the number of leading zeros return 31 - index; } else { // If x is 0, BSR sets the zero flag and doesn't modify index // LZCNT should return 32 for an input of 0 return 32; } #else return __lzcnt( value ); #endif } static inline uint32_t b2CTZ64( uint64_t block ) { unsigned long index; #ifdef _WIN64 _BitScanForward64( &index, block ); #else // 32-bit fall back if ( (uint32_t)block != 0 ) { _BitScanForward( &index, (uint32_t)block ); } else { _BitScanForward( &index, (uint32_t)( block >> 32 ) ); index += 32; } #endif return index; } static inline int b2PopCount64( uint64_t block ) { return (int)__popcnt64( block ); } #else static inline uint32_t b2CTZ32( uint32_t block ) { return __builtin_ctz( block ); } static inline uint32_t b2CLZ32( uint32_t value ) { return __builtin_clz( value ); } static inline uint32_t b2CTZ64( uint64_t block ) { return __builtin_ctzll( block ); } static inline int b2PopCount64( uint64_t block ) { return __builtin_popcountll( block ); } #endif static inline bool b2IsPowerOf2( int x ) { return ( x & ( x - 1 ) ) == 0; } static inline int b2BoundingPowerOf2( int x ) { if ( x <= 1 ) { return 1; } return 32 - (int)b2CLZ32( (uint32_t)x - 1 ); } static inline int b2RoundUpPowerOf2( int x ) { if ( x <= 1 ) { return 1; } return 1 << ( 32 - (int)b2CLZ32( (uint32_t)x - 1 ) ); } ================================================ FILE: src/distance.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "constants.h" #include "core.h" #include "box2d/collision.h" #include "box2d/math_functions.h" #include #include b2Transform b2GetSweepTransform( const b2Sweep* sweep, float time ) { // https://fgiesen.wordpress.com/2012/08/15/linear-interpolation-past-present-and-future/ b2Transform xf; xf.p = b2Add( b2MulSV( 1.0f - time, sweep->c1 ), b2MulSV( time, sweep->c2 ) ); b2Rot q = { ( 1.0f - time ) * sweep->q1.c + time * sweep->q2.c, ( 1.0f - time ) * sweep->q1.s + time * sweep->q2.s, }; xf.q = b2NormalizeRot( q ); // Shift to origin xf.p = b2Sub( xf.p, b2RotateVector( xf.q, sweep->localCenter ) ); return xf; } /// Follows Ericson 5.1.9 Closest Points of Two Line Segments b2SegmentDistanceResult b2SegmentDistance( b2Vec2 p1, b2Vec2 q1, b2Vec2 p2, b2Vec2 q2 ) { b2SegmentDistanceResult result = { 0 }; b2Vec2 d1 = b2Sub( q1, p1 ); b2Vec2 d2 = b2Sub( q2, p2 ); b2Vec2 r = b2Sub( p1, p2 ); float dd1 = b2Dot( d1, d1 ); float dd2 = b2Dot( d2, d2 ); float rd1 = b2Dot( r, d1 ); float rd2 = b2Dot( r, d2 ); const float epsSqr = FLT_EPSILON * FLT_EPSILON; if ( dd1 < epsSqr || dd2 < epsSqr ) { // Handle all degeneracies if ( dd1 >= epsSqr ) { // Segment 2 is degenerate result.fraction1 = b2ClampFloat( -rd1 / dd1, 0.0f, 1.0f ); result.fraction2 = 0.0f; } else if ( dd2 >= epsSqr ) { // Segment 1 is degenerate result.fraction1 = 0.0f; result.fraction2 = b2ClampFloat( rd2 / dd2, 0.0f, 1.0f ); } else { result.fraction1 = 0.0f; result.fraction2 = 0.0f; } } else { // Non-degenerate segments float d12 = b2Dot( d1, d2 ); float denominator = dd1 * dd2 - d12 * d12; // Fraction on segment 1 float f1 = 0.0f; if ( denominator != 0.0f ) { // not parallel f1 = b2ClampFloat( ( d12 * rd2 - rd1 * dd2 ) / denominator, 0.0f, 1.0f ); } // Compute point on segment 2 closest to p1 + f1 * d1 float f2 = ( d12 * f1 + rd2 ) / dd2; // Clamping of segment 2 requires a do over on segment 1 if ( f2 < 0.0f ) { f2 = 0.0f; f1 = b2ClampFloat( -rd1 / dd1, 0.0f, 1.0f ); } else if ( f2 > 1.0f ) { f2 = 1.0f; f1 = b2ClampFloat( ( d12 - rd1 ) / dd1, 0.0f, 1.0f ); } result.fraction1 = f1; result.fraction2 = f2; } result.closest1 = b2MulAdd( p1, result.fraction1, d1 ); result.closest2 = b2MulAdd( p2, result.fraction2, d2 ); result.distanceSquared = b2DistanceSquared( result.closest1, result.closest2 ); return result; } b2ShapeProxy b2MakeProxy( const b2Vec2* points, int count, float radius ) { count = b2MinInt( count, B2_MAX_POLYGON_VERTICES ); b2ShapeProxy proxy; for ( int i = 0; i < count; ++i ) { proxy.points[i] = points[i]; } proxy.count = count; proxy.radius = radius; return proxy; } b2ShapeProxy b2MakeOffsetProxy( const b2Vec2* points, int count, float radius, b2Vec2 position, b2Rot rotation ) { count = b2MinInt( count, B2_MAX_POLYGON_VERTICES ); b2Transform transform = { .p = position, .q = rotation, }; b2ShapeProxy proxy; for ( int i = 0; i < count; ++i ) { proxy.points[i] = b2TransformPoint( transform, points[i] ); } proxy.count = count; proxy.radius = radius; return proxy; } static inline b2Vec2 b2Weight2( float a1, b2Vec2 w1, float a2, b2Vec2 w2 ) { return (b2Vec2){ a1 * w1.x + a2 * w2.x, a1 * w1.y + a2 * w2.y }; } static inline b2Vec2 b2Weight3( float a1, b2Vec2 w1, float a2, b2Vec2 w2, float a3, b2Vec2 w3 ) { return (b2Vec2){ a1 * w1.x + a2 * w2.x + a3 * w3.x, a1 * w1.y + a2 * w2.y + a3 * w3.y }; } static inline int b2FindSupport( const b2ShapeProxy* proxy, b2Vec2 direction ) { const b2Vec2* points = proxy->points; int count = proxy->count; int bestIndex = 0; float bestValue = b2Dot( points[0], direction ); for ( int i = 1; i < count; ++i ) { float value = b2Dot( points[i], direction ); if ( value > bestValue ) { bestIndex = i; bestValue = value; } } return bestIndex; } static b2Simplex b2MakeSimplexFromCache( const b2SimplexCache* cache, const b2ShapeProxy* proxyA, const b2ShapeProxy* proxyB ) { B2_ASSERT( cache->count <= 3 ); b2Simplex s; // Copy data from cache. s.count = cache->count; b2SimplexVertex* vertices[] = { &s.v1, &s.v2, &s.v3 }; for ( int i = 0; i < s.count; ++i ) { b2SimplexVertex* v = vertices[i]; v->indexA = cache->indexA[i]; v->indexB = cache->indexB[i]; v->wA = proxyA->points[v->indexA]; v->wB = proxyB->points[v->indexB]; v->w = b2Sub( v->wA, v->wB ); // invalid v->a = -1.0f; } // If the cache is empty or invalid ... if ( s.count == 0 ) { b2SimplexVertex* v = vertices[0]; v->indexA = 0; v->indexB = 0; v->wA = proxyA->points[0]; v->wB = proxyB->points[0]; v->w = b2Sub( v->wA, v->wB ); v->a = 1.0f; s.count = 1; } return s; } static void b2MakeSimplexCache( b2SimplexCache* cache, const b2Simplex* simplex ) { cache->count = (uint16_t)simplex->count; const b2SimplexVertex* vertices[] = { &simplex->v1, &simplex->v2, &simplex->v3 }; for ( int i = 0; i < simplex->count; ++i ) { cache->indexA[i] = (uint8_t)vertices[i]->indexA; cache->indexB[i] = (uint8_t)vertices[i]->indexB; } } static void b2ComputeWitnessPoints( const b2Simplex* s, b2Vec2* a, b2Vec2* b ) { switch ( s->count ) { case 1: *a = s->v1.wA; *b = s->v1.wB; break; case 2: *a = b2Weight2( s->v1.a, s->v1.wA, s->v2.a, s->v2.wA ); *b = b2Weight2( s->v1.a, s->v1.wB, s->v2.a, s->v2.wB ); break; case 3: *a = b2Weight3( s->v1.a, s->v1.wA, s->v2.a, s->v2.wA, s->v3.a, s->v3.wA ); // todo why are these not equal? //*b = b2Weight3(s->v1.a, s->v1.wB, s->v2.a, s->v2.wB, s->v3.a, s->v3.wB); *b = *a; break; default: *a = b2Vec2_zero; *b = b2Vec2_zero; B2_ASSERT( false ); break; } } // Solve a line segment using barycentric coordinates. // // p = a1 * w1 + a2 * w2 // a1 + a2 = 1 // // The vector from the origin to the closest point on the line is // perpendicular to the line. // e12 = w2 - w1 // dot(p, e) = 0 // a1 * dot(w1, e) + a2 * dot(w2, e) = 0 // // 2-by-2 linear system // [1 1 ][a1] = [1] // [w1.e12 w2.e12][a2] = [0] // // Define // d12_1 = dot(w2, e12) // d12_2 = -dot(w1, e12) // d12 = d12_1 + d12_2 // // Solution // a1 = d12_1 / d12 // a2 = d12_2 / d12 // // returns a vector that points towards the origin static b2Vec2 b2SolveSimplex2( b2Simplex* s ) { b2Vec2 w1 = s->v1.w; b2Vec2 w2 = s->v2.w; b2Vec2 e12 = b2Sub( w2, w1 ); // w1 region float d12_2 = -b2Dot( w1, e12 ); if ( d12_2 <= 0.0f ) { // a2 <= 0, so we clamp it to 0 s->v1.a = 1.0f; s->count = 1; return b2Neg( w1 ); } // w2 region float d12_1 = b2Dot( w2, e12 ); if ( d12_1 <= 0.0f ) { // a1 <= 0, so we clamp it to 0 s->v2.a = 1.0f; s->count = 1; s->v1 = s->v2; return b2Neg( w2 ); } // Must be in e12 region. float inv_d12 = 1.0f / ( d12_1 + d12_2 ); s->v1.a = d12_1 * inv_d12; s->v2.a = d12_2 * inv_d12; s->count = 2; return b2CrossSV( b2Cross( b2Add( w1, w2 ), e12 ), e12 ); } static b2Vec2 b2SolveSimplex3( b2Simplex* s ) { b2Vec2 w1 = s->v1.w; b2Vec2 w2 = s->v2.w; b2Vec2 w3 = s->v3.w; // Edge12 // [1 1 ][a1] = [1] // [w1.e12 w2.e12][a2] = [0] // a3 = 0 b2Vec2 e12 = b2Sub( w2, w1 ); float w1e12 = b2Dot( w1, e12 ); float w2e12 = b2Dot( w2, e12 ); float d12_1 = w2e12; float d12_2 = -w1e12; // Edge13 // [1 1 ][a1] = [1] // [w1.e13 w3.e13][a3] = [0] // a2 = 0 b2Vec2 e13 = b2Sub( w3, w1 ); float w1e13 = b2Dot( w1, e13 ); float w3e13 = b2Dot( w3, e13 ); float d13_1 = w3e13; float d13_2 = -w1e13; // Edge23 // [1 1 ][a2] = [1] // [w2.e23 w3.e23][a3] = [0] // a1 = 0 b2Vec2 e23 = b2Sub( w3, w2 ); float w2e23 = b2Dot( w2, e23 ); float w3e23 = b2Dot( w3, e23 ); float d23_1 = w3e23; float d23_2 = -w2e23; // Triangle123 float n123 = b2Cross( e12, e13 ); float d123_1 = n123 * b2Cross( w2, w3 ); float d123_2 = n123 * b2Cross( w3, w1 ); float d123_3 = n123 * b2Cross( w1, w2 ); // w1 region if ( d12_2 <= 0.0f && d13_2 <= 0.0f ) { s->v1.a = 1.0f; s->count = 1; return b2Neg( w1 ); } // e12 if ( d12_1 > 0.0f && d12_2 > 0.0f && d123_3 <= 0.0f ) { float inv_d12 = 1.0f / ( d12_1 + d12_2 ); s->v1.a = d12_1 * inv_d12; s->v2.a = d12_2 * inv_d12; s->count = 2; return b2CrossSV( b2Cross( b2Add( w1, w2 ), e12 ), e12 ); } // e13 if ( d13_1 > 0.0f && d13_2 > 0.0f && d123_2 <= 0.0f ) { float inv_d13 = 1.0f / ( d13_1 + d13_2 ); s->v1.a = d13_1 * inv_d13; s->v3.a = d13_2 * inv_d13; s->count = 2; s->v2 = s->v3; return b2CrossSV( b2Cross( b2Add( w1, w3 ), e13 ), e13 ); } // w2 region if ( d12_1 <= 0.0f && d23_2 <= 0.0f ) { s->v2.a = 1.0f; s->count = 1; s->v1 = s->v2; return b2Neg( w2 ); } // w3 region if ( d13_1 <= 0.0f && d23_1 <= 0.0f ) { s->v3.a = 1.0f; s->count = 1; s->v1 = s->v3; return b2Neg( w3 ); } // e23 if ( d23_1 > 0.0f && d23_2 > 0.0f && d123_1 <= 0.0f ) { float inv_d23 = 1.0f / ( d23_1 + d23_2 ); s->v2.a = d23_1 * inv_d23; s->v3.a = d23_2 * inv_d23; s->count = 2; s->v1 = s->v3; return b2CrossSV( b2Cross( b2Add( w2, w3 ), e23 ), e23 ); } // Must be in triangle123 float inv_d123 = 1.0f / ( d123_1 + d123_2 + d123_3 ); s->v1.a = d123_1 * inv_d123; s->v2.a = d123_2 * inv_d123; s->v3.a = d123_3 * inv_d123; s->count = 3; // No search direction return b2Vec2_zero; } // Uses GJK for computing the distance between convex shapes. // https://box2d.org/files/ErinCatto_GJK_GDC2010.pdf // I spent time optimizing this and could find no further significant gains 3/30/2025 b2DistanceOutput b2ShapeDistance( const b2DistanceInput* input, b2SimplexCache* cache, b2Simplex* simplexes, int simplexCapacity ) { B2_UNUSED( simplexes, simplexCapacity ); B2_ASSERT( input->proxyA.count > 0 && input->proxyB.count > 0 ); B2_ASSERT( input->proxyA.radius >= 0.0f ); B2_ASSERT( input->proxyB.radius >= 0.0f ); b2DistanceOutput output = { 0 }; const b2ShapeProxy* proxyA = &input->proxyA; // Get proxyB in frame A to avoid further transforms in the main loop. // This is still a performance gain at 8 points. b2ShapeProxy localProxyB; { b2Transform transform = b2InvMulTransforms( input->transformA, input->transformB ); localProxyB.count = input->proxyB.count; localProxyB.radius = input->proxyB.radius; for ( int i = 0; i < localProxyB.count; ++i ) { localProxyB.points[i] = b2TransformPoint( transform, input->proxyB.points[i] ); } } // Initialize the simplex. b2Simplex simplex = b2MakeSimplexFromCache( cache, proxyA, &localProxyB ); int simplexIndex = 0; if ( simplexes != NULL && simplexIndex < simplexCapacity ) { simplexes[simplexIndex] = simplex; simplexIndex += 1; } // Get simplex vertices as an array. b2SimplexVertex* vertices[] = { &simplex.v1, &simplex.v2, &simplex.v3 }; b2Vec2 nonUnitNormal = b2Vec2_zero; // These store the vertices of the last simplex so that we can check for duplicates and prevent cycling. int saveA[3], saveB[3]; // Main iteration loop. All computations are done in frame A. const int maxIterations = 20; int iteration = 0; while ( iteration < maxIterations ) { // Copy simplex so we can identify duplicates. int saveCount = simplex.count; for ( int i = 0; i < saveCount; ++i ) { saveA[i] = vertices[i]->indexA; saveB[i] = vertices[i]->indexB; } b2Vec2 d = { 0 }; switch ( simplex.count ) { case 1: d = b2Neg( simplex.v1.w ); break; case 2: d = b2SolveSimplex2( &simplex ); break; case 3: d = b2SolveSimplex3( &simplex ); break; default: B2_ASSERT( false ); } // If we have 3 points, then the origin is in the corresponding triangle. if ( simplex.count == 3 ) { // Overlap b2Vec2 localPointA, localPointB; b2ComputeWitnessPoints( &simplex, &localPointA, &localPointB ); output.pointA = b2TransformPoint( input->transformA, localPointA ); output.pointB = b2TransformPoint( input->transformA, localPointB ); return output; } #ifndef NDEBUG if ( simplexes != NULL && simplexIndex < simplexCapacity ) { simplexes[simplexIndex] = simplex; simplexIndex += 1; } #endif // Ensure the search direction is numerically fit. if ( b2Dot( d, d ) < FLT_EPSILON * FLT_EPSILON ) { // This is unlikely but could lead to bad cycling. // The branch predictor seems to make this check have low cost. // The origin is probably contained by a line segment // or triangle. Thus the shapes are overlapped. // Must return overlap due to invalid normal. b2Vec2 localPointA, localPointB; b2ComputeWitnessPoints( &simplex, &localPointA, &localPointB ); output.pointA = b2TransformPoint( input->transformA, localPointA ); output.pointB = b2TransformPoint( input->transformA, localPointB ); return output; } // Save the normal nonUnitNormal = d; // Compute a tentative new simplex vertex using support points. // support = support(a, d) - support(b, -d) b2SimplexVertex* vertex = vertices[simplex.count]; vertex->indexA = b2FindSupport( proxyA, d ); vertex->wA = proxyA->points[vertex->indexA]; vertex->indexB = b2FindSupport( &localProxyB, b2Neg( d ) ); vertex->wB = localProxyB.points[vertex->indexB]; vertex->w = b2Sub( vertex->wA, vertex->wB ); // Iteration count is equated to the number of support point calls. ++iteration; // Check for duplicate support points. This is the main termination criteria. bool duplicate = false; for ( int i = 0; i < saveCount; ++i ) { if ( vertex->indexA == saveA[i] && vertex->indexB == saveB[i] ) { duplicate = true; break; } } // If we found a duplicate support point we must exit to avoid cycling. if ( duplicate ) { break; } // New vertex is valid and needed. simplex.count += 1; } #ifndef NDEBUG if ( simplexes != NULL && simplexIndex < simplexCapacity ) { simplexes[simplexIndex] = simplex; simplexIndex += 1; } #endif // Prepare output b2Vec2 normal = b2Normalize( nonUnitNormal ); B2_ASSERT( b2IsNormalized( normal ) ); normal = b2RotateVector( input->transformA.q, normal ); b2Vec2 localPointA, localPointB; b2ComputeWitnessPoints( &simplex, &localPointA, &localPointB ); output.normal = normal; output.distance = b2Distance( localPointA, localPointB ); output.pointA = b2TransformPoint( input->transformA, localPointA ); output.pointB = b2TransformPoint( input->transformA, localPointB ); output.iterations = iteration; output.simplexCount = simplexIndex; // Cache the simplex b2MakeSimplexCache( cache, &simplex ); // Apply radii if requested if ( input->useRadii ) { float radiusA = input->proxyA.radius; float radiusB = input->proxyB.radius; output.distance = b2MaxFloat( 0.0f, output.distance - radiusA - radiusB ); // Keep closest points on perimeter even if overlapped, this way the points move smoothly. output.pointA = b2MulAdd( output.pointA, radiusA, normal ); output.pointB = b2MulSub( output.pointB, radiusB, normal ); } return output; } // Shape cast using conservative advancement b2CastOutput b2ShapeCast( const b2ShapeCastPairInput* input ) { // Compute tolerance float linearSlop = B2_LINEAR_SLOP; float totalRadius = input->proxyA.radius + input->proxyB.radius; float target = b2MaxFloat( linearSlop, totalRadius - linearSlop ); float tolerance = 0.25f * linearSlop; B2_ASSERT( target > tolerance ); // Prepare input for distance query b2SimplexCache cache = { 0 }; float fraction = 0.0f; b2DistanceInput distanceInput = { 0 }; distanceInput.proxyA = input->proxyA; distanceInput.proxyB = input->proxyB; distanceInput.transformA = input->transformA; distanceInput.transformB = input->transformB; distanceInput.useRadii = false; b2Vec2 delta2 = input->translationB; b2CastOutput output = { 0 }; int iteration = 0; const int maxIterations = 20; for ( ; iteration < maxIterations; ++iteration ) { output.iterations += 1; b2DistanceOutput distanceOutput = b2ShapeDistance( &distanceInput, &cache, NULL, 0 ); if ( distanceOutput.distance < target + tolerance ) { if ( iteration == 0 ) { if ( input->canEncroach && distanceOutput.distance > 2.0f * linearSlop ) { target = distanceOutput.distance - linearSlop; } else { // Initial overlap output.hit = true; // Compute a common point b2Vec2 c1 = b2MulAdd( distanceOutput.pointA, input->proxyA.radius, distanceOutput.normal ); b2Vec2 c2 = b2MulAdd( distanceOutput.pointB, -input->proxyB.radius, distanceOutput.normal ); output.point = b2Lerp( c1, c2, 0.5f ); return output; } } else { // Regular hit B2_ASSERT( distanceOutput.distance > 0.0f && b2IsNormalized( distanceOutput.normal ) ); output.fraction = fraction; output.point = b2MulAdd( distanceOutput.pointA, input->proxyA.radius, distanceOutput.normal ); output.normal = distanceOutput.normal; output.hit = true; return output; } } B2_ASSERT( distanceOutput.distance > 0.0f ); B2_ASSERT( b2IsNormalized( distanceOutput.normal ) ); // Check if shapes are approaching each other float denominator = b2Dot( delta2, distanceOutput.normal ); if ( denominator >= 0.0f ) { // Miss return output; } // Advance sweep fraction += ( target - distanceOutput.distance ) / denominator; if ( fraction >= input->maxFraction ) { // Miss return output; } distanceInput.transformB.p = b2MulAdd( input->transformB.p, fraction, delta2 ); } // Failure! return output; } #if 0 static inline b2Vec2 b2ComputeSimplexClosestPoint( const b2Simplex* s ) { if ( s->count == 1 ) { return s->v1.w; } if ( s->count == 2 ) { return b2Weight2( s->v1.a, s->v1.w, s->v2.a, s->v2.w ); } return b2Vec2_zero; } typedef struct b2ShapeCastData { b2Simplex simplex; b2Vec2 closestA, closestB; b2Vec2 normal; b2Vec2 p0; float fraction; } b2ShapeCastData; // GJK-raycast // Algorithm by Gino van den Bergen. // "Smooth Mesh Contacts with GJK" in Game Physics Pearls. 2010 // This needs the simplex of A - B because the translation is for B and this // is how the relative motion works out when both shapes are translating. // This is similar to ray vs polygon and involves plane clipping. See b2RayCastPolygon. // In this case the polygon is just points and there are no planes. This uses a modified // version of GJK to generate planes for clipping. // The algorithm works by incrementally building clipping planes using GJK. Once a valid // clip plane is found the simplex origin is moved to the current fraction on the ray. // This resets the simplex after every clip. Later I should compare performance. // However, adapting this to work with encroachment is tricky and confusing because encroachment // needs distance. // Note: this algorithm is difficult to debug and not worth the effort in my opinion 4/1/2025 b2CastOutput b2ShapeCastMerged( const b2ShapeCastPairInput* input, b2ShapeCastData* debugData, int debugCapacity ) { B2_UNUSED( debugData, debugCapacity ); b2CastOutput output = { 0 }; output.fraction = input->maxFraction; b2ShapeProxy proxyA = input->proxyA; b2Transform xf = b2InvMulTransforms( input->transformA, input->transformB ); // Put proxyB in proxyA's frame to reduce round-off error b2ShapeProxy proxyB; proxyB.count = input->proxyB.count; proxyB.radius = input->proxyB.radius; B2_ASSERT( proxyB.count <= B2_MAX_POLYGON_VERTICES ); for ( int i = 0; i < proxyB.count; ++i ) { proxyB.points[i] = b2TransformPoint( xf, input->proxyB.points[i] ); } float radius = proxyA.radius + proxyB.radius; b2Vec2 r = b2RotateVector( xf.q, input->translationB ); float lambda = 0.0f; float maxFraction = input->maxFraction; // Initial simplex b2Simplex simplex; simplex.count = 0; // Get simplex vertices as an array. b2SimplexVertex* vertices[] = { &simplex.v1, &simplex.v2, &simplex.v3 }; // Get an initial point in A - B b2Vec2 wA = proxyA.points[0]; b2Vec2 wB = proxyB.points[0]; b2Vec2 v = b2Sub( wA, wB ); b2Vec2 d = b2Neg( v ); // Sigma is the target distance between proxies const float linearSlop = B2_LINEAR_SLOP; const float sigma = b2MaxFloat( linearSlop, radius - linearSlop ); float tolerance = 0.5f * linearSlop; float stolSquared = ( sigma + tolerance ) * ( sigma + tolerance ); // Main iteration loop. const int maxIterations = 20; int iteration = 0; while ( iteration < maxIterations && b2LengthSquared( v ) > stolSquared ) { B2_ASSERT( simplex.count < 3 ); // Support in direction d (A - B) int indexA = b2FindSupport( &proxyA, d ); wA = proxyA.points[indexA]; int indexB = b2FindSupport( &proxyB, b2Neg( d ) ); wB = proxyB.points[indexB]; b2Vec2 p0 = b2Sub( wA, wB ); // d is a normal at p, normalize to work with sigma b2Vec2 normal = b2Normalize( d ); // Intersect ray with plane // p = origin + t * r // dot(n, p - p0) = sigma // dot(n, origin - p0) + t * dot(n, r) = sigma // t = ( dot(n, p0) + sigma) / dot(n, r) // if t < (dot(n, p0) + sigma) / dot(n, r) then t can be increased // or (flipping sign because dot(n,r) < 0) // dot(n, p0) + sigma < t * dot(n, r) && dot(n, r) < 0 float np0 = b2Dot( normal, p0 ); float nr = b2Dot( normal, r ); if ( np0 + sigma < lambda * nr ) { if ( nr >= 0.0f ) { // miss return output; } lambda = ( np0 + sigma ) / nr; if ( lambda > maxFraction ) { // too far return output; } // reset the simplex simplex.count = 0; } // Shift by lambda * r because we want the closest point to the current clip point. // Note that the support point p is not shifted because we want the plane equation // to be formed in un-shifted space. b2SimplexVertex* vertex = vertices[simplex.count]; vertex->indexA = indexB; vertex->wA = wA; vertex->indexB = indexA; vertex->wB = (b2Vec2){ wB.x + lambda * r.x, wB.y + lambda * r.y }; vertex->w = b2Sub( vertex->wA, vertex->wB ); vertex->a = 1.0f; simplex.count += 1; switch ( simplex.count ) { case 1: d = b2Neg( simplex.v1.w ); break; case 2: d = b2SolveSimplex2( &simplex ); break; case 3: d = b2SolveSimplex3( &simplex ); break; default: B2_ASSERT( false ); } #ifndef NDEBUG if ( debugData != NULL && output.iterations < debugCapacity ) { debugData[output.iterations].simplex = simplex; debugData[output.iterations].normal = normal; debugData[output.iterations].p0 = p0; b2Vec2 cA, cB; b2ComputeSimplexWitnessPoints( &cA, &cB, &simplex ); debugData[output.iterations].closestA = cA; debugData[output.iterations].closestB = cB; debugData[output.iterations].fraction = lambda; } #endif output.iterations += 1; // If we have 3 points, then the origin is in the corresponding triangle. if ( simplex.count == 3 ) { // Overlap return output; } // Get distance vector v = b2ComputeSimplexClosestPoint( &simplex ); // Iteration count is equated to the number of support point calls. ++iteration; } if ( iteration == 0 || lambda == 0.0f ) { // Initial overlap return output; } // Prepare output. b2Vec2 pointA, pointB; b2ComputeSimplexWitnessPoints( &pointB, &pointA, &simplex ); b2Vec2 n = b2Normalize( b2Neg( v ) ); b2Vec2 point = { pointA.x + proxyA.radius * n.x, pointA.y + proxyA.radius * n.y }; output.point = b2TransformPoint( input->transformA, point ); output.normal = b2RotateVector( input->transformA.q, n ); output.fraction = lambda; output.iterations = iteration; output.hit = true; return output; } #endif // Warning: writing to these globals significantly slows multithreading performance #if B2_SNOOP_TOI_COUNTERS float b2_toiTime, b2_toiMaxTime; int b2_toiCalls, b2_toiDistanceIterations, b2_toiMaxDistanceIterations; int b2_toiRootIterations, b2_toiMaxRootIterations; int b2_toiFailedCount; int b2_toiOverlappedCount; int b2_toiHitCount; int b2_toiSeparatedCount; #endif typedef enum b2SeparationType { b2_pointsType, b2_faceAType, b2_faceBType } b2SeparationType; typedef struct b2SeparationFunction { const b2ShapeProxy* proxyA; const b2ShapeProxy* proxyB; b2Sweep sweepA, sweepB; b2Vec2 localPoint; b2Vec2 axis; b2SeparationType type; } b2SeparationFunction; static b2SeparationFunction b2MakeSeparationFunction( const b2SimplexCache* cache, const b2ShapeProxy* proxyA, const b2Sweep* sweepA, const b2ShapeProxy* proxyB, const b2Sweep* sweepB, float t1 ) { b2SeparationFunction f; f.proxyA = proxyA; f.proxyB = proxyB; int count = cache->count; B2_ASSERT( 0 < count && count < 3 ); f.sweepA = *sweepA; f.sweepB = *sweepB; b2Transform xfA = b2GetSweepTransform( sweepA, t1 ); b2Transform xfB = b2GetSweepTransform( sweepB, t1 ); if ( count == 1 ) { f.type = b2_pointsType; b2Vec2 localPointA = proxyA->points[cache->indexA[0]]; b2Vec2 localPointB = proxyB->points[cache->indexB[0]]; b2Vec2 pointA = b2TransformPoint( xfA, localPointA ); b2Vec2 pointB = b2TransformPoint( xfB, localPointB ); f.axis = b2Normalize( b2Sub( pointB, pointA ) ); f.localPoint = b2Vec2_zero; return f; } if ( cache->indexA[0] == cache->indexA[1] ) { // Two points on B and one on A. f.type = b2_faceBType; b2Vec2 localPointB1 = proxyB->points[cache->indexB[0]]; b2Vec2 localPointB2 = proxyB->points[cache->indexB[1]]; f.axis = b2CrossVS( b2Sub( localPointB2, localPointB1 ), 1.0f ); f.axis = b2Normalize( f.axis ); b2Vec2 normal = b2RotateVector( xfB.q, f.axis ); f.localPoint = (b2Vec2){ 0.5f * ( localPointB1.x + localPointB2.x ), 0.5f * ( localPointB1.y + localPointB2.y ) }; b2Vec2 pointB = b2TransformPoint( xfB, f.localPoint ); b2Vec2 localPointA = proxyA->points[cache->indexA[0]]; b2Vec2 pointA = b2TransformPoint( xfA, localPointA ); float s = b2Dot( b2Sub( pointA, pointB ), normal ); if ( s < 0.0f ) { f.axis = b2Neg( f.axis ); } return f; } // Two points on A and one or two points on B. f.type = b2_faceAType; b2Vec2 localPointA1 = proxyA->points[cache->indexA[0]]; b2Vec2 localPointA2 = proxyA->points[cache->indexA[1]]; f.axis = b2CrossVS( b2Sub( localPointA2, localPointA1 ), 1.0f ); f.axis = b2Normalize( f.axis ); b2Vec2 normal = b2RotateVector( xfA.q, f.axis ); f.localPoint = (b2Vec2){ 0.5f * ( localPointA1.x + localPointA2.x ), 0.5f * ( localPointA1.y + localPointA2.y ) }; b2Vec2 pointA = b2TransformPoint( xfA, f.localPoint ); b2Vec2 localPointB = proxyB->points[cache->indexB[0]]; b2Vec2 pointB = b2TransformPoint( xfB, localPointB ); float s = b2Dot( b2Sub( pointB, pointA ), normal ); if ( s < 0.0f ) { f.axis = b2Neg( f.axis ); } return f; } static float b2FindMinSeparation( const b2SeparationFunction* f, int* indexA, int* indexB, float t ) { b2Transform xfA = b2GetSweepTransform( &f->sweepA, t ); b2Transform xfB = b2GetSweepTransform( &f->sweepB, t ); switch ( f->type ) { case b2_pointsType: { b2Vec2 axisA = b2InvRotateVector( xfA.q, f->axis ); b2Vec2 axisB = b2InvRotateVector( xfB.q, b2Neg( f->axis ) ); *indexA = b2FindSupport( f->proxyA, axisA ); *indexB = b2FindSupport( f->proxyB, axisB ); b2Vec2 localPointA = f->proxyA->points[*indexA]; b2Vec2 localPointB = f->proxyB->points[*indexB]; b2Vec2 pointA = b2TransformPoint( xfA, localPointA ); b2Vec2 pointB = b2TransformPoint( xfB, localPointB ); float separation = b2Dot( b2Sub( pointB, pointA ), f->axis ); return separation; } case b2_faceAType: { b2Vec2 normal = b2RotateVector( xfA.q, f->axis ); b2Vec2 pointA = b2TransformPoint( xfA, f->localPoint ); b2Vec2 axisB = b2InvRotateVector( xfB.q, b2Neg( normal ) ); *indexA = -1; *indexB = b2FindSupport( f->proxyB, axisB ); b2Vec2 localPointB = f->proxyB->points[*indexB]; b2Vec2 pointB = b2TransformPoint( xfB, localPointB ); float separation = b2Dot( b2Sub( pointB, pointA ), normal ); return separation; } case b2_faceBType: { b2Vec2 normal = b2RotateVector( xfB.q, f->axis ); b2Vec2 pointB = b2TransformPoint( xfB, f->localPoint ); b2Vec2 axisA = b2InvRotateVector( xfA.q, b2Neg( normal ) ); *indexB = -1; *indexA = b2FindSupport( f->proxyA, axisA ); b2Vec2 localPointA = f->proxyA->points[*indexA]; b2Vec2 pointA = b2TransformPoint( xfA, localPointA ); float separation = b2Dot( b2Sub( pointA, pointB ), normal ); return separation; } default: B2_ASSERT( false ); *indexA = -1; *indexB = -1; return 0.0f; } } // static float b2EvaluateSeparation( const b2SeparationFunction* f, int indexA, int indexB, float t ) { b2Transform xfA = b2GetSweepTransform( &f->sweepA, t ); b2Transform xfB = b2GetSweepTransform( &f->sweepB, t ); switch ( f->type ) { case b2_pointsType: { b2Vec2 localPointA = f->proxyA->points[indexA]; b2Vec2 localPointB = f->proxyB->points[indexB]; b2Vec2 pointA = b2TransformPoint( xfA, localPointA ); b2Vec2 pointB = b2TransformPoint( xfB, localPointB ); float separation = b2Dot( b2Sub( pointB, pointA ), f->axis ); return separation; } case b2_faceAType: { b2Vec2 normal = b2RotateVector( xfA.q, f->axis ); b2Vec2 pointA = b2TransformPoint( xfA, f->localPoint ); b2Vec2 localPointB = f->proxyB->points[indexB]; b2Vec2 pointB = b2TransformPoint( xfB, localPointB ); float separation = b2Dot( b2Sub( pointB, pointA ), normal ); return separation; } case b2_faceBType: { b2Vec2 normal = b2RotateVector( xfB.q, f->axis ); b2Vec2 pointB = b2TransformPoint( xfB, f->localPoint ); b2Vec2 localPointA = f->proxyA->points[indexA]; b2Vec2 pointA = b2TransformPoint( xfA, localPointA ); float separation = b2Dot( b2Sub( pointA, pointB ), normal ); return separation; } default: B2_ASSERT( false ); return 0.0f; } } // CCD via the local separating axis method. This seeks progression // by computing the largest time at which separation is maintained. b2TOIOutput b2TimeOfImpact( const b2TOIInput* input ) { #if B2_SNOOP_TOI_COUNTERS uint64_t ticks = b2GetTicks(); ++b2_toiCalls; #endif b2TOIOutput output; output.state = b2_toiStateUnknown; output.fraction = input->maxFraction; b2Sweep sweepA = input->sweepA; b2Sweep sweepB = input->sweepB; B2_ASSERT( b2IsNormalizedRot( sweepA.q1 ) && b2IsNormalizedRot( sweepA.q2 ) ); B2_ASSERT( b2IsNormalizedRot( sweepB.q1 ) && b2IsNormalizedRot( sweepB.q2 ) ); // todo_erin // c1 can be at the origin yet the points are far away // b2Vec2 origin = b2Add(sweepA.c1, input->proxyA.points[0]); const b2ShapeProxy* proxyA = &input->proxyA; const b2ShapeProxy* proxyB = &input->proxyB; float tMax = input->maxFraction; float totalRadius = proxyA->radius + proxyB->radius; float target = b2MaxFloat( B2_LINEAR_SLOP, totalRadius - B2_LINEAR_SLOP ); float tolerance = 0.25f * B2_LINEAR_SLOP; B2_ASSERT( target > tolerance ); float t1 = 0.0f; const int k_maxIterations = 20; int distanceIterations = 0; // Prepare input for distance query. b2SimplexCache cache = { 0 }; b2DistanceInput distanceInput; distanceInput.proxyA = input->proxyA; distanceInput.proxyB = input->proxyB; distanceInput.useRadii = false; // The outer loop progressively attempts to compute new separating axes. // This loop terminates when an axis is repeated (no progress is made). for ( ;; ) { b2Transform xfA = b2GetSweepTransform( &sweepA, t1 ); b2Transform xfB = b2GetSweepTransform( &sweepB, t1 ); // Get the distance between shapes. We can also use the results // to get a separating axis. distanceInput.transformA = xfA; distanceInput.transformB = xfB; b2DistanceOutput distanceOutput = b2ShapeDistance( &distanceInput, &cache, NULL, 0 ); // Progressive time of impact. This handles slender geometry well but introduces // significant time loss. // if (distanceIterations == 0) //{ // if ( distanceOutput.distance > totalRadius + B2_SPECULATIVE_DISTANCE ) // { // target = totalRadius + B2_SPECULATIVE_DISTANCE - tolerance; // } // else // { // target = distanceOutput.distance - 1.5f * tolerance; // target = b2MaxFloat( target, 2.0f * tolerance ); // } //} distanceIterations += 1; #if B2_SNOOP_TOI_COUNTERS b2_toiDistanceIterations += 1; #endif // If the shapes are overlapped, we give up on continuous collision. if ( distanceOutput.distance <= 0.0f ) { // Failure! output.state = b2_toiStateOverlapped; #if B2_SNOOP_TOI_COUNTERS b2_toiOverlappedCount += 1; #endif output.fraction = 0.0f; break; } if ( distanceOutput.distance <= target + tolerance ) { // Victory! output.state = b2_toiStateHit; #if B2_SNOOP_TOI_COUNTERS b2_toiHitCount += 1; #endif // Averaged hit point b2Vec2 pA = b2MulAdd( distanceOutput.pointA, proxyA->radius, distanceOutput.normal ); b2Vec2 pB = b2MulAdd( distanceOutput.pointB, -proxyB->radius, distanceOutput.normal ); output.point = b2Lerp( pA, pB, 0.5f ); output.normal = distanceOutput.normal; output.fraction = t1; break; } // Initialize the separating axis. b2SeparationFunction fcn = b2MakeSeparationFunction( &cache, proxyA, &sweepA, proxyB, &sweepB, t1 ); #if 0 // Dump the curve seen by the root finder { const int N = 100; float dx = 1.0f / N; float xs[N + 1]; float fs[N + 1]; float x = 0.0f; for (int i = 0; i <= N; ++i) { sweepA.GetTransform(&xfA, x); sweepB.GetTransform(&xfB, x); float f = fcn.Evaluate(xfA, xfB) - target; printf("%g %g\n", x, f); xs[i] = x; fs[i] = f; x += dx; } } #endif // Compute the TOI on the separating axis. We do this by successively // resolving the deepest point. This loop is bounded by the number of vertices. bool done = false; float t2 = tMax; int pushBackIterations = 0; for ( ;; ) { // Find the deepest point at t2. Store the witness point indices. int indexA, indexB; float s2 = b2FindMinSeparation( &fcn, &indexA, &indexB, t2 ); // Is the final configuration separated? if ( s2 > target + tolerance ) { // Victory! output.state = b2_toiStateSeparated; #if B2_SNOOP_TOI_COUNTERS b2_toiSeparatedCount += 1; #endif output.fraction = tMax; done = true; break; } // Has the separation reached tolerance? if ( s2 > target - tolerance ) { // Advance the sweeps t1 = t2; break; } // Compute the initial separation of the witness points. float s1 = b2EvaluateSeparation( &fcn, indexA, indexB, t1 ); // Check for initial overlap. This might happen if the root finder // runs out of iterations. if ( s1 < target - tolerance ) { output.state = b2_toiStateFailed; #if B2_SNOOP_TOI_COUNTERS b2_toiFailedCount += 1; #endif output.fraction = t1; done = true; break; } // Check for touching if ( s1 <= target + tolerance ) { // Victory! t1 should hold the TOI (could be 0.0). output.state = b2_toiStateHit; #if B2_SNOOP_TOI_COUNTERS b2_toiHitCount += 1; #endif // Averaged hit point b2Vec2 pA = b2MulAdd( distanceOutput.pointA, proxyA->radius, distanceOutput.normal ); b2Vec2 pB = b2MulAdd( distanceOutput.pointB, -proxyB->radius, distanceOutput.normal ); output.point = b2Lerp( pA, pB, 0.5f ); output.normal = distanceOutput.normal; output.fraction = t1; done = true; break; } // Compute 1D root of: f(x) - target = 0 int rootIterationCount = 0; float a1 = t1, a2 = t2; for ( ;; ) { // Use a mix of the secant rule and bisection. float t; if ( rootIterationCount & 1 ) { // Secant rule to improve convergence. t = a1 + ( target - s1 ) * ( a2 - a1 ) / ( s2 - s1 ); } else { // Bisection to guarantee progress. t = 0.5f * ( a1 + a2 ); } rootIterationCount += 1; #if B2_SNOOP_TOI_COUNTERS ++b2_toiRootIterations; #endif float s = b2EvaluateSeparation( &fcn, indexA, indexB, t ); if ( b2AbsFloat( s - target ) < tolerance ) { // t2 holds a tentative value for t1 t2 = t; break; } // Ensure we continue to bracket the root. if ( s > target ) { a1 = t; s1 = s; } else { a2 = t; s2 = s; } if ( rootIterationCount == 50 ) { break; } } #if B2_SNOOP_TOI_COUNTERS b2_toiMaxRootIterations = b2MaxInt( b2_toiMaxRootIterations, rootIterationCount ); #endif pushBackIterations += 1; if ( pushBackIterations == B2_MAX_POLYGON_VERTICES ) { break; } } if ( done ) { break; } if ( distanceIterations == k_maxIterations ) { // Root finder got stuck. Semi-victory. output.state = b2_toiStateFailed; #if B2_SNOOP_TOI_COUNTERS b2_toiFailedCount += 1; #endif // Averaged hit point b2Vec2 pA = b2MulAdd( distanceOutput.pointA, proxyA->radius, distanceOutput.normal ); b2Vec2 pB = b2MulAdd( distanceOutput.pointB, -proxyB->radius, distanceOutput.normal ); output.point = b2Lerp( pA, pB, 0.5f ); output.normal = distanceOutput.normal; output.fraction = t1; break; } } #if B2_SNOOP_TOI_COUNTERS b2_toiMaxDistanceIterations = b2MaxInt( b2_toiMaxDistanceIterations, distanceIterations ); float time = b2GetMilliseconds( ticks ); b2_toiMaxTime = b2MaxFloat( b2_toiMaxTime, time ); b2_toiTime += time; #endif return output; } ================================================ FILE: src/distance_joint.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #if defined( _MSC_VER ) && !defined( _CRT_SECURE_NO_WARNINGS ) #define _CRT_SECURE_NO_WARNINGS #endif #include "body.h" #include "core.h" #include "joint.h" #include "physics_world.h" #include "solver.h" #include "solver_set.h" // needed for dll export #include "box2d/box2d.h" void b2DistanceJoint_SetLength( b2JointId jointId, float length ) { b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; joint->length = b2ClampFloat( length, B2_LINEAR_SLOP, B2_HUGE ); joint->impulse = 0.0f; joint->lowerImpulse = 0.0f; joint->upperImpulse = 0.0f; } float b2DistanceJoint_GetLength( b2JointId jointId ) { b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; return joint->length; } void b2DistanceJoint_EnableLimit( b2JointId jointId, bool enableLimit ) { b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; joint->enableLimit = enableLimit; } bool b2DistanceJoint_IsLimitEnabled( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_distanceJoint ); return joint->distanceJoint.enableLimit; } void b2DistanceJoint_SetLengthRange( b2JointId jointId, float minLength, float maxLength ) { b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; minLength = b2ClampFloat( minLength, B2_LINEAR_SLOP, B2_HUGE ); maxLength = b2ClampFloat( maxLength, B2_LINEAR_SLOP, B2_HUGE ); joint->minLength = b2MinFloat( minLength, maxLength ); joint->maxLength = b2MaxFloat( minLength, maxLength ); joint->impulse = 0.0f; joint->lowerImpulse = 0.0f; joint->upperImpulse = 0.0f; } float b2DistanceJoint_GetMinLength( b2JointId jointId ) { b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; return joint->minLength; } float b2DistanceJoint_GetMaxLength( b2JointId jointId ) { b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; return joint->maxLength; } float b2DistanceJoint_GetCurrentLength( b2JointId jointId ) { b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2World* world = b2GetWorld( jointId.world0 ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return 0.0f; } b2Transform transformA = b2GetBodyTransform( world, base->bodyIdA ); b2Transform transformB = b2GetBodyTransform( world, base->bodyIdB ); b2Vec2 pA = b2TransformPoint( transformA, base->localFrameA.p ); b2Vec2 pB = b2TransformPoint( transformB, base->localFrameB.p ); b2Vec2 d = b2Sub( pB, pA ); float length = b2Length( d ); return length; } void b2DistanceJoint_EnableSpring( b2JointId jointId, bool enableSpring ) { b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); base->distanceJoint.enableSpring = enableSpring; } bool b2DistanceJoint_IsSpringEnabled( b2JointId jointId ) { b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); return base->distanceJoint.enableSpring; } void b2DistanceJoint_SetSpringForceRange( b2JointId jointId, float lowerForce, float upperForce ) { B2_ASSERT( lowerForce <= upperForce ); b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); base->distanceJoint.lowerSpringForce = lowerForce; base->distanceJoint.upperSpringForce = upperForce; } void b2DistanceJoint_GetSpringForceRange( b2JointId jointId, float* lowerForce, float* upperForce ) { b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); *lowerForce = base->distanceJoint.lowerSpringForce; *upperForce = base->distanceJoint.upperSpringForce; } void b2DistanceJoint_SetSpringHertz( b2JointId jointId, float hertz ) { b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); base->distanceJoint.hertz = hertz; } void b2DistanceJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ) { b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); base->distanceJoint.dampingRatio = dampingRatio; } float b2DistanceJoint_GetSpringHertz( b2JointId jointId ) { b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; return joint->hertz; } float b2DistanceJoint_GetSpringDampingRatio( b2JointId jointId ) { b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; return joint->dampingRatio; } void b2DistanceJoint_EnableMotor( b2JointId jointId, bool enableMotor ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_distanceJoint ); if ( enableMotor != joint->distanceJoint.enableMotor ) { joint->distanceJoint.enableMotor = enableMotor; joint->distanceJoint.motorImpulse = 0.0f; } } bool b2DistanceJoint_IsMotorEnabled( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_distanceJoint ); return joint->distanceJoint.enableMotor; } void b2DistanceJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_distanceJoint ); joint->distanceJoint.motorSpeed = motorSpeed; } float b2DistanceJoint_GetMotorSpeed( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_distanceJoint ); return joint->distanceJoint.motorSpeed; } float b2DistanceJoint_GetMotorForce( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); return world->inv_h * base->distanceJoint.motorImpulse; } void b2DistanceJoint_SetMaxMotorForce( b2JointId jointId, float force ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_distanceJoint ); joint->distanceJoint.maxMotorForce = force; } float b2DistanceJoint_GetMaxMotorForce( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_distanceJoint ); return joint->distanceJoint.maxMotorForce; } b2Vec2 b2GetDistanceJointForce( b2World* world, b2JointSim* base ) { b2DistanceJoint* joint = &base->distanceJoint; b2Transform transformA = b2GetBodyTransform( world, base->bodyIdA ); b2Transform transformB = b2GetBodyTransform( world, base->bodyIdB ); b2Vec2 pA = b2TransformPoint( transformA, base->localFrameA.p ); b2Vec2 pB = b2TransformPoint( transformB, base->localFrameB.p ); b2Vec2 d = b2Sub( pB, pA ); b2Vec2 axis = b2Normalize( d ); float force = ( joint->impulse + joint->lowerImpulse - joint->upperImpulse + joint->motorImpulse ) * world->inv_h; return b2MulSV( force, axis ); } // 1-D constrained system // m (v2 - v1) = lambda // v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass. // x2 = x1 + h * v2 // 1-D mass-damper-spring system // m (v2 - v1) + h * d * v2 + h * k * // C = norm(p2 - p1) - L // u = (p2 - p1) / norm(p2 - p1) // Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1)) // J = [-u -cross(r1, u) u cross(r2, u)] // K = J * invM * JT // = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2 void b2PrepareDistanceJoint( b2JointSim* base, b2StepContext* context ) { B2_ASSERT( base->type == b2_distanceJoint ); // chase body id to the solver set where the body lives int idA = base->bodyIdA; int idB = base->bodyIdB; b2World* world = context->world; b2Body* bodyA = b2BodyArray_Get( &world->bodies, idA ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, idB ); B2_ASSERT( bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet ); b2SolverSet* setA = b2SolverSetArray_Get( &world->solverSets, bodyA->setIndex ); b2SolverSet* setB = b2SolverSetArray_Get( &world->solverSets, bodyB->setIndex ); int localIndexA = bodyA->localIndex; int localIndexB = bodyB->localIndex; b2BodySim* bodySimA = b2BodySimArray_Get( &setA->bodySims, localIndexA ); b2BodySim* bodySimB = b2BodySimArray_Get( &setB->bodySims, localIndexB ); float mA = bodySimA->invMass; float iA = bodySimA->invInertia; float mB = bodySimB->invMass; float iB = bodySimB->invInertia; base->invMassA = mA; base->invMassB = mB; base->invIA = iA; base->invIB = iB; b2DistanceJoint* joint = &base->distanceJoint; joint->indexA = bodyA->setIndex == b2_awakeSet ? localIndexA : B2_NULL_INDEX; joint->indexB = bodyB->setIndex == b2_awakeSet ? localIndexB : B2_NULL_INDEX; // initial anchors in world space joint->anchorA = b2RotateVector( bodySimA->transform.q, b2Sub( base->localFrameA.p, bodySimA->localCenter ) ); joint->anchorB = b2RotateVector( bodySimB->transform.q, b2Sub( base->localFrameB.p, bodySimB->localCenter ) ); joint->deltaCenter = b2Sub( bodySimB->center, bodySimA->center ); b2Vec2 rA = joint->anchorA; b2Vec2 rB = joint->anchorB; b2Vec2 separation = b2Add( b2Sub( rB, rA ), joint->deltaCenter ); b2Vec2 axis = b2Normalize( separation ); // compute effective mass float crA = b2Cross( rA, axis ); float crB = b2Cross( rB, axis ); float k = mA + mB + iA * crA * crA + iB * crB * crB; joint->axialMass = k > 0.0f ? 1.0f / k : 0.0f; joint->distanceSoftness = b2MakeSoft( joint->hertz, joint->dampingRatio, context->h ); if ( context->enableWarmStarting == false ) { joint->impulse = 0.0f; joint->lowerImpulse = 0.0f; joint->upperImpulse = 0.0f; joint->motorImpulse = 0.0f; } } void b2WarmStartDistanceJoint( b2JointSim* base, b2StepContext* context ) { B2_ASSERT( base->type == b2_distanceJoint ); float mA = base->invMassA; float mB = base->invMassB; float iA = base->invIA; float iB = base->invIB; // dummy state for static bodies b2BodyState dummyState = b2_identityBodyState; b2DistanceJoint* joint = &base->distanceJoint; b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->anchorA ); b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->anchorB ); b2Vec2 ds = b2Add( b2Sub( stateB->deltaPosition, stateA->deltaPosition ), b2Sub( rB, rA ) ); b2Vec2 separation = b2Add( joint->deltaCenter, ds ); b2Vec2 axis = b2Normalize( separation ); float axialImpulse = joint->impulse + joint->lowerImpulse - joint->upperImpulse + joint->motorImpulse; b2Vec2 P = b2MulSV( axialImpulse, axis ); if ( stateA->flags & b2_dynamicFlag ) { stateA->linearVelocity = b2MulSub( stateA->linearVelocity, mA, P ); stateA->angularVelocity -= iA * b2Cross( rA, P ); } if ( stateB->flags & b2_dynamicFlag ) { stateB->linearVelocity = b2MulAdd( stateB->linearVelocity, mB, P ); stateB->angularVelocity += iB * b2Cross( rB, P ); } } void b2SolveDistanceJoint( b2JointSim* base, b2StepContext* context, bool useBias ) { B2_ASSERT( base->type == b2_distanceJoint ); float mA = base->invMassA; float mB = base->invMassB; float iA = base->invIA; float iB = base->invIB; // dummy state for static bodies b2BodyState dummyState = b2_identityBodyState; b2DistanceJoint* joint = &base->distanceJoint; b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; b2Vec2 vA = stateA->linearVelocity; float wA = stateA->angularVelocity; b2Vec2 vB = stateB->linearVelocity; float wB = stateB->angularVelocity; // current anchors b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->anchorA ); b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->anchorB ); // current separation b2Vec2 ds = b2Add( b2Sub( stateB->deltaPosition, stateA->deltaPosition ), b2Sub( rB, rA ) ); b2Vec2 separation = b2Add( joint->deltaCenter, ds ); float length = b2Length( separation ); b2Vec2 axis = b2Normalize( separation ); // joint is soft if // - spring is enabled // - and (joint limit is disabled or limits are not equal) if ( joint->enableSpring && ( joint->minLength < joint->maxLength || joint->enableLimit == false ) ) { // spring if ( joint->hertz > 0.0f ) { // Cdot = dot(u, v + cross(w, r)) b2Vec2 vr = b2Add( b2Sub( vB, vA ), b2Sub( b2CrossSV( wB, rB ), b2CrossSV( wA, rA ) ) ); float Cdot = b2Dot( axis, vr ); float C = length - joint->length; float bias = joint->distanceSoftness.biasRate * C; float m = joint->distanceSoftness.massScale * joint->axialMass; float oldImpulse = joint->impulse; float impulse = -m * ( Cdot + bias ) - joint->distanceSoftness.impulseScale * oldImpulse; float h = context->h; joint->impulse = b2ClampFloat( joint->impulse + impulse, joint->lowerSpringForce * h, joint->upperSpringForce * h ); impulse = joint->impulse - oldImpulse; b2Vec2 P = b2MulSV( impulse, axis ); vA = b2MulSub( vA, mA, P ); wA -= iA * b2Cross( rA, P ); vB = b2MulAdd( vB, mB, P ); wB += iB * b2Cross( rB, P ); } if ( joint->enableMotor ) { b2Vec2 vr = b2Add( b2Sub( vB, vA ), b2Sub( b2CrossSV( wB, rB ), b2CrossSV( wA, rA ) ) ); float Cdot = b2Dot( axis, vr ); float impulse = joint->axialMass * ( joint->motorSpeed - Cdot ); float oldImpulse = joint->motorImpulse; float maxImpulse = context->h * joint->maxMotorForce; joint->motorImpulse = b2ClampFloat( joint->motorImpulse + impulse, -maxImpulse, maxImpulse ); impulse = joint->motorImpulse - oldImpulse; b2Vec2 P = b2MulSV( impulse, axis ); vA = b2MulSub( vA, mA, P ); wA -= iA * b2Cross( rA, P ); vB = b2MulAdd( vB, mB, P ); wB += iB * b2Cross( rB, P ); } if ( joint->enableLimit ) { // lower limit { b2Vec2 vr = b2Add( b2Sub( vB, vA ), b2Sub( b2CrossSV( wB, rB ), b2CrossSV( wA, rA ) ) ); float Cdot = b2Dot( axis, vr ); float C = length - joint->minLength; float bias = 0.0f; float massCoeff = 1.0f; float impulseCoeff = 0.0f; if ( C > 0.0f ) { // speculative bias = C * context->inv_h; } else if ( useBias ) { bias = base->constraintSoftness.biasRate * C; massCoeff = base->constraintSoftness.massScale; impulseCoeff = base->constraintSoftness.impulseScale; } float impulse = -massCoeff * joint->axialMass * ( Cdot + bias ) - impulseCoeff * joint->lowerImpulse; float newImpulse = b2MaxFloat( 0.0f, joint->lowerImpulse + impulse ); impulse = newImpulse - joint->lowerImpulse; joint->lowerImpulse = newImpulse; b2Vec2 P = b2MulSV( impulse, axis ); vA = b2MulSub( vA, mA, P ); wA -= iA * b2Cross( rA, P ); vB = b2MulAdd( vB, mB, P ); wB += iB * b2Cross( rB, P ); } // upper { b2Vec2 vr = b2Add( b2Sub( vA, vB ), b2Sub( b2CrossSV( wA, rA ), b2CrossSV( wB, rB ) ) ); float Cdot = b2Dot( axis, vr ); float C = joint->maxLength - length; float bias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; if ( C > 0.0f ) { // speculative bias = C * context->inv_h; } else if ( useBias ) { bias = base->constraintSoftness.biasRate * C; massScale = base->constraintSoftness.massScale; impulseScale = base->constraintSoftness.impulseScale; } float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->upperImpulse; float newImpulse = b2MaxFloat( 0.0f, joint->upperImpulse + impulse ); impulse = newImpulse - joint->upperImpulse; joint->upperImpulse = newImpulse; b2Vec2 P = b2MulSV( -impulse, axis ); vA = b2MulSub( vA, mA, P ); wA -= iA * b2Cross( rA, P ); vB = b2MulAdd( vB, mB, P ); wB += iB * b2Cross( rB, P ); } } } else { // rigid constraint b2Vec2 vr = b2Add( b2Sub( vB, vA ), b2Sub( b2CrossSV( wB, rB ), b2CrossSV( wA, rA ) ) ); float Cdot = b2Dot( axis, vr ); float C = length - joint->length; float bias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; if ( useBias ) { bias = base->constraintSoftness.biasRate * C; massScale = base->constraintSoftness.massScale; impulseScale = base->constraintSoftness.impulseScale; } float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->impulse; joint->impulse += impulse; b2Vec2 P = b2MulSV( impulse, axis ); vA = b2MulSub( vA, mA, P ); wA -= iA * b2Cross( rA, P ); vB = b2MulAdd( vB, mB, P ); wB += iB * b2Cross( rB, P ); } if ( stateA->flags & b2_dynamicFlag ) { stateA->linearVelocity = vA; stateA->angularVelocity = wA; } if ( stateB->flags & b2_dynamicFlag ) { stateB->linearVelocity = vB; stateB->angularVelocity = wB; } } #if 0 void b2DistanceJoint::Dump() { int32 indexA = m_bodyA->m_islandIndex; int32 indexB = m_bodyB->m_islandIndex; b2Dump(" b2DistanceJointDef jd;\n"); b2Dump(" jd.bodyA = sims[%d];\n", indexA); b2Dump(" jd.bodyB = sims[%d];\n", indexB); b2Dump(" jd.collideConnected = bool(%d);\n", m_collideConnected); b2Dump(" jd.localAnchorA.Set(%.9g, %.9g);\n", m_localAnchorA.x, m_localAnchorA.y); b2Dump(" jd.localAnchorB.Set(%.9g, %.9g);\n", m_localAnchorB.x, m_localAnchorB.y); b2Dump(" jd.length = %.9g;\n", m_length); b2Dump(" jd.minLength = %.9g;\n", m_minLength); b2Dump(" jd.maxLength = %.9g;\n", m_maxLength); b2Dump(" jd.stiffness = %.9g;\n", m_stiffness); b2Dump(" jd.damping = %.9g;\n", m_damping); b2Dump(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); } #endif void b2DrawDistanceJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB ) { B2_ASSERT( base->type == b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; b2Vec2 pA = b2TransformPoint( transformA, base->localFrameA.p ); b2Vec2 pB = b2TransformPoint( transformB, base->localFrameB.p ); b2Vec2 axis = b2Normalize( b2Sub( pB, pA ) ); if ( joint->minLength < joint->maxLength && joint->enableLimit ) { b2Vec2 pMin = b2MulAdd( pA, joint->minLength, axis ); b2Vec2 pMax = b2MulAdd( pA, joint->maxLength, axis ); b2Vec2 offset = b2MulSV( 0.05f * b2_lengthUnitsPerMeter, b2RightPerp( axis ) ); if ( joint->minLength > B2_LINEAR_SLOP ) { // draw->DrawPoint(pMin, 4.0f, c2, draw->context); draw->DrawLineFcn( b2Sub( pMin, offset ), b2Add( pMin, offset ), b2_colorLightGreen, draw->context ); } if ( joint->maxLength < B2_HUGE ) { // draw->DrawPoint(pMax, 4.0f, c3, draw->context); draw->DrawLineFcn( b2Sub( pMax, offset ), b2Add( pMax, offset ), b2_colorRed, draw->context ); } if ( joint->minLength > B2_LINEAR_SLOP && joint->maxLength < B2_HUGE ) { draw->DrawLineFcn( pMin, pMax, b2_colorGray, draw->context ); } } draw->DrawLineFcn( pA, pB, b2_colorWhite, draw->context ); draw->DrawPointFcn( pA, 4.0f, b2_colorWhite, draw->context ); draw->DrawPointFcn( pB, 4.0f, b2_colorWhite, draw->context ); if ( joint->hertz > 0.0f && joint->enableSpring ) { b2Vec2 pRest = b2MulAdd( pA, joint->length, axis ); draw->DrawPointFcn( pRest, 4.0f, b2_colorBlue, draw->context ); } } ================================================ FILE: src/dynamic_tree.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "aabb.h" #include "constants.h" #include "core.h" #include "box2d/collision.h" #include "box2d/math_functions.h" #include #include #define B2_TREE_STACK_SIZE 1024 // todo externalize this to visualize internal nodes and speed up FindPairs // A node in the dynamic tree. typedef struct b2TreeNode { // The node bounding box b2AABB aabb; // 16 // Category bits for collision filtering uint64_t categoryBits; // 8 union { // Children (internal node) struct { int32_t child1, child2; } children; /// User data (leaf node) uint64_t userData; }; // 8 union { /// The node parent index (allocated node) int32_t parent; /// The node freelist next index (free node) int32_t next; }; // 4 uint16_t height; // 2 uint16_t flags; // 2 } b2TreeNode; static b2TreeNode b2_defaultTreeNode = { .aabb = { { 0.0f, 0.0f }, { 0.0f, 0.0f } }, .categoryBits = B2_DEFAULT_CATEGORY_BITS, .children = { .child1 = B2_NULL_INDEX, .child2 = B2_NULL_INDEX, }, .parent = B2_NULL_INDEX, .height = 0, .flags = b2_allocatedNode, }; static bool b2IsLeaf( const b2TreeNode* node ) { return node->flags & b2_leafNode; } static bool b2IsAllocated( const b2TreeNode* node ) { return node->flags & b2_allocatedNode; } static uint16_t b2MaxUInt16( uint16_t a, uint16_t b ) { return a > b ? a : b; } b2DynamicTree b2DynamicTree_Create( void ) { b2DynamicTree tree; // memset needed for deterministic serialization memset( &tree, 0, sizeof( b2DynamicTree ) ); tree.root = B2_NULL_INDEX; tree.nodeCapacity = 16; tree.nodeCount = 0; tree.nodes = (b2TreeNode*)b2Alloc( tree.nodeCapacity * sizeof( b2TreeNode ) ); memset( tree.nodes, 0, tree.nodeCapacity * sizeof( b2TreeNode ) ); // Build a linked list for the free list. for ( int i = 0; i < tree.nodeCapacity - 1; ++i ) { tree.nodes[i].next = i + 1; } tree.nodes[tree.nodeCapacity - 1].next = B2_NULL_INDEX; tree.freeList = 0; tree.proxyCount = 0; tree.leafIndices = NULL; tree.leafBoxes = NULL; tree.leafCenters = NULL; tree.binIndices = NULL; tree.rebuildCapacity = 0; return tree; } void b2DynamicTree_Destroy( b2DynamicTree* tree ) { b2Free( tree->nodes, tree->nodeCapacity * sizeof( b2TreeNode ) ); b2Free( tree->leafIndices, tree->rebuildCapacity * sizeof( int32_t ) ); b2Free( tree->leafBoxes, tree->rebuildCapacity * sizeof( b2AABB ) ); b2Free( tree->leafCenters, tree->rebuildCapacity * sizeof( b2Vec2 ) ); b2Free( tree->binIndices, tree->rebuildCapacity * sizeof( int32_t ) ); memset( tree, 0, sizeof( b2DynamicTree ) ); } // Allocate a node from the pool. Grow the pool if necessary. static int b2AllocateNode( b2DynamicTree* tree ) { // Expand the node pool as needed. if ( tree->freeList == B2_NULL_INDEX ) { B2_ASSERT( tree->nodeCount == tree->nodeCapacity ); // The free list is empty. Rebuild a bigger pool. b2TreeNode* oldNodes = tree->nodes; int oldCapacity = tree->nodeCapacity; tree->nodeCapacity += oldCapacity >> 1; tree->nodes = (b2TreeNode*)b2Alloc( tree->nodeCapacity * sizeof( b2TreeNode ) ); B2_ASSERT( oldNodes != NULL ); memcpy( tree->nodes, oldNodes, tree->nodeCount * sizeof( b2TreeNode ) ); memset( tree->nodes + tree->nodeCount, 0, ( tree->nodeCapacity - tree->nodeCount ) * sizeof( b2TreeNode ) ); b2Free( oldNodes, oldCapacity * sizeof( b2TreeNode ) ); // Build a linked list for the free list. The parent pointer becomes the "next" pointer. // todo avoid building freelist? for ( int i = tree->nodeCount; i < tree->nodeCapacity - 1; ++i ) { tree->nodes[i].next = i + 1; } tree->nodes[tree->nodeCapacity - 1].next = B2_NULL_INDEX; tree->freeList = tree->nodeCount; } // Peel a node off the free list. int nodeIndex = tree->freeList; b2TreeNode* node = tree->nodes + nodeIndex; tree->freeList = node->next; *node = b2_defaultTreeNode; ++tree->nodeCount; return nodeIndex; } // Return a node to the pool. static void b2FreeNode( b2DynamicTree* tree, int nodeId ) { B2_ASSERT( 0 <= nodeId && nodeId < tree->nodeCapacity ); B2_ASSERT( 0 < tree->nodeCount ); tree->nodes[nodeId].next = tree->freeList; tree->nodes[nodeId].flags = 0; tree->freeList = nodeId; --tree->nodeCount; } // Greedy algorithm for sibling selection using the SAH // We have three nodes A-(B,C) and want to add a leaf D, there are three choices. // 1: make a new parent for A and D : E-(A-(B,C), D) // 2: associate D with B // a: B is a leaf : A-(E-(B,D), C) // b: B is an internal node: A-(B{D},C) // 3: associate D with C // a: C is a leaf : A-(B, E-(C,D)) // b: C is an internal node: A-(B, C{D}) // All of these have a clear cost except when B or C is an internal node. Hence we need to be greedy. // The cost for cases 1, 2a, and 3a can be computed using the sibling cost formula. // cost of sibling H = area(union(H, D)) + increased area of ancestors // Suppose B (or C) is an internal node, then the lowest cost would be one of two cases: // case1: D becomes a sibling of B // case2: D becomes a descendant of B along with a new internal node of area(D). static int b2FindBestSibling( const b2DynamicTree* tree, b2AABB boxD ) { b2Vec2 centerD = b2AABB_Center( boxD ); float areaD = b2Perimeter( boxD ); const b2TreeNode* nodes = tree->nodes; int rootIndex = tree->root; b2AABB rootBox = nodes[rootIndex].aabb; // Area of current node float areaBase = b2Perimeter( rootBox ); // Area of inflated node float directCost = b2Perimeter( b2AABB_Union( rootBox, boxD ) ); float inheritedCost = 0.0f; int bestSibling = rootIndex; float bestCost = directCost; // Descend the tree from root, following a single greedy path. int index = rootIndex; while ( nodes[index].height > 0 ) { int child1 = nodes[index].children.child1; int child2 = nodes[index].children.child2; // Cost of creating a new parent for this node and the new leaf float cost = directCost + inheritedCost; // Sometimes there are multiple identical costs within tolerance. // This breaks the ties using the centroid distance. if ( cost < bestCost ) { bestSibling = index; bestCost = cost; } // Inheritance cost seen by children inheritedCost += directCost - areaBase; bool leaf1 = nodes[child1].height == 0; bool leaf2 = nodes[child2].height == 0; // Cost of descending into child 1 float lowerCost1 = FLT_MAX; b2AABB box1 = nodes[child1].aabb; float directCost1 = b2Perimeter( b2AABB_Union( box1, boxD ) ); float area1 = 0.0f; if ( leaf1 ) { // Child 1 is a leaf // Cost of creating new node and increasing area of node P float cost1 = directCost1 + inheritedCost; // Need this here due to while condition above if ( cost1 < bestCost ) { bestSibling = child1; bestCost = cost1; } } else { // Child 1 is an internal node area1 = b2Perimeter( box1 ); // Lower bound cost of inserting under child 1. The minimum accounts for two possibilities: // 1. Child1 could be the sibling with cost1 = inheritedCost + directCost1 // 2. A descendant of child1 could be the sibling with the lower bound cost of // cost1 = inheritedCost + (directCost1 - area1) + areaD // This minimum here leads to the minimum of these two costs. lowerCost1 = inheritedCost + directCost1 + b2MinFloat( areaD - area1, 0.0f ); } // Cost of descending into child 2 float lowerCost2 = FLT_MAX; b2AABB box2 = nodes[child2].aabb; float directCost2 = b2Perimeter( b2AABB_Union( box2, boxD ) ); float area2 = 0.0f; if ( leaf2 ) { float cost2 = directCost2 + inheritedCost; if ( cost2 < bestCost ) { bestSibling = child2; bestCost = cost2; } } else { area2 = b2Perimeter( box2 ); lowerCost2 = inheritedCost + directCost2 + b2MinFloat( areaD - area2, 0.0f ); } if ( leaf1 && leaf2 ) { break; } // Can the cost possibly be decreased? if ( bestCost <= lowerCost1 && bestCost <= lowerCost2 ) { break; } if ( lowerCost1 == lowerCost2 && leaf1 == false ) { B2_ASSERT( lowerCost1 < FLT_MAX ); B2_ASSERT( lowerCost2 < FLT_MAX ); // No clear choice based on lower bound surface area. This can happen when both // children fully contain D. Fall back to node distance. b2Vec2 d1 = b2Sub( b2AABB_Center( box1 ), centerD ); b2Vec2 d2 = b2Sub( b2AABB_Center( box2 ), centerD ); lowerCost1 = b2LengthSquared( d1 ); lowerCost2 = b2LengthSquared( d2 ); } // Descend if ( lowerCost1 < lowerCost2 && leaf1 == false ) { index = child1; areaBase = area1; directCost = directCost1; } else { index = child2; areaBase = area2; directCost = directCost2; } B2_ASSERT( nodes[index].height > 0 ); } return bestSibling; } enum b2RotateType { b2_rotateNone, b2_rotateBF, b2_rotateBG, b2_rotateCD, b2_rotateCE }; // Perform a left or right rotation if node A is imbalanced. // Returns the new root index. static void b2RotateNodes( b2DynamicTree* tree, int iA ) { B2_ASSERT( iA != B2_NULL_INDEX ); b2TreeNode* nodes = tree->nodes; b2TreeNode* A = nodes + iA; if ( A->height < 2 ) { return; } int iB = A->children.child1; int iC = A->children.child2; B2_ASSERT( 0 <= iB && iB < tree->nodeCapacity ); B2_ASSERT( 0 <= iC && iC < tree->nodeCapacity ); b2TreeNode* B = nodes + iB; b2TreeNode* C = nodes + iC; if ( B->height == 0 ) { // B is a leaf and C is internal B2_ASSERT( C->height > 0 ); int iF = C->children.child1; int iG = C->children.child2; b2TreeNode* F = nodes + iF; b2TreeNode* G = nodes + iG; B2_ASSERT( 0 <= iF && iF < tree->nodeCapacity ); B2_ASSERT( 0 <= iG && iG < tree->nodeCapacity ); // Base cost float costBase = b2Perimeter( C->aabb ); // Cost of swapping B and F b2AABB aabbBG = b2AABB_Union( B->aabb, G->aabb ); float costBF = b2Perimeter( aabbBG ); // Cost of swapping B and G b2AABB aabbBF = b2AABB_Union( B->aabb, F->aabb ); float costBG = b2Perimeter( aabbBF ); if ( costBase < costBF && costBase < costBG ) { // Rotation does not improve cost return; } if ( costBF < costBG ) { // Swap B and F A->children.child1 = iF; C->children.child1 = iB; B->parent = iC; F->parent = iA; C->aabb = aabbBG; C->height = 1 + b2MaxUInt16( B->height, G->height ); A->height = 1 + b2MaxUInt16( C->height, F->height ); C->categoryBits = B->categoryBits | G->categoryBits; A->categoryBits = C->categoryBits | F->categoryBits; C->flags |= ( B->flags | G->flags ) & b2_enlargedNode; A->flags |= ( C->flags | F->flags ) & b2_enlargedNode; } else { // Swap B and G A->children.child1 = iG; C->children.child2 = iB; B->parent = iC; G->parent = iA; C->aabb = aabbBF; C->height = 1 + b2MaxUInt16( B->height, F->height ); A->height = 1 + b2MaxUInt16( C->height, G->height ); C->categoryBits = B->categoryBits | F->categoryBits; A->categoryBits = C->categoryBits | G->categoryBits; C->flags |= ( B->flags | F->flags ) & b2_enlargedNode; A->flags |= ( C->flags | G->flags ) & b2_enlargedNode; } } else if ( C->height == 0 ) { // C is a leaf and B is internal B2_ASSERT( B->height > 0 ); int iD = B->children.child1; int iE = B->children.child2; b2TreeNode* D = nodes + iD; b2TreeNode* E = nodes + iE; B2_ASSERT( 0 <= iD && iD < tree->nodeCapacity ); B2_ASSERT( 0 <= iE && iE < tree->nodeCapacity ); // Base cost float costBase = b2Perimeter( B->aabb ); // Cost of swapping C and D b2AABB aabbCE = b2AABB_Union( C->aabb, E->aabb ); float costCD = b2Perimeter( aabbCE ); // Cost of swapping C and E b2AABB aabbCD = b2AABB_Union( C->aabb, D->aabb ); float costCE = b2Perimeter( aabbCD ); if ( costBase < costCD && costBase < costCE ) { // Rotation does not improve cost return; } if ( costCD < costCE ) { // Swap C and D A->children.child2 = iD; B->children.child1 = iC; C->parent = iB; D->parent = iA; B->aabb = aabbCE; B->height = 1 + b2MaxUInt16( C->height, E->height ); A->height = 1 + b2MaxUInt16( B->height, D->height ); B->categoryBits = C->categoryBits | E->categoryBits; A->categoryBits = B->categoryBits | D->categoryBits; B->flags |= ( C->flags | E->flags ) & b2_enlargedNode; A->flags |= ( B->flags | D->flags ) & b2_enlargedNode; } else { // Swap C and E A->children.child2 = iE; B->children.child2 = iC; C->parent = iB; E->parent = iA; B->aabb = aabbCD; B->height = 1 + b2MaxUInt16( C->height, D->height ); A->height = 1 + b2MaxUInt16( B->height, E->height ); B->categoryBits = C->categoryBits | D->categoryBits; A->categoryBits = B->categoryBits | E->categoryBits; B->flags |= ( C->flags | D->flags ) & b2_enlargedNode; A->flags |= ( B->flags | E->flags ) & b2_enlargedNode; } } else { int iD = B->children.child1; int iE = B->children.child2; int iF = C->children.child1; int iG = C->children.child2; B2_ASSERT( 0 <= iD && iD < tree->nodeCapacity ); B2_ASSERT( 0 <= iE && iE < tree->nodeCapacity ); B2_ASSERT( 0 <= iF && iF < tree->nodeCapacity ); B2_ASSERT( 0 <= iG && iG < tree->nodeCapacity ); b2TreeNode* D = nodes + iD; b2TreeNode* E = nodes + iE; b2TreeNode* F = nodes + iF; b2TreeNode* G = nodes + iG; // Base cost float areaB = b2Perimeter( B->aabb ); float areaC = b2Perimeter( C->aabb ); float costBase = areaB + areaC; enum b2RotateType bestRotation = b2_rotateNone; float bestCost = costBase; // Cost of swapping B and F b2AABB aabbBG = b2AABB_Union( B->aabb, G->aabb ); float costBF = areaB + b2Perimeter( aabbBG ); if ( costBF < bestCost ) { bestRotation = b2_rotateBF; bestCost = costBF; } // Cost of swapping B and G b2AABB aabbBF = b2AABB_Union( B->aabb, F->aabb ); float costBG = areaB + b2Perimeter( aabbBF ); if ( costBG < bestCost ) { bestRotation = b2_rotateBG; bestCost = costBG; } // Cost of swapping C and D b2AABB aabbCE = b2AABB_Union( C->aabb, E->aabb ); float costCD = areaC + b2Perimeter( aabbCE ); if ( costCD < bestCost ) { bestRotation = b2_rotateCD; bestCost = costCD; } // Cost of swapping C and E b2AABB aabbCD = b2AABB_Union( C->aabb, D->aabb ); float costCE = areaC + b2Perimeter( aabbCD ); if ( costCE < bestCost ) { bestRotation = b2_rotateCE; // bestCost = costCE; } switch ( bestRotation ) { case b2_rotateNone: break; case b2_rotateBF: A->children.child1 = iF; C->children.child1 = iB; B->parent = iC; F->parent = iA; C->aabb = aabbBG; C->height = 1 + b2MaxUInt16( B->height, G->height ); A->height = 1 + b2MaxUInt16( C->height, F->height ); C->categoryBits = B->categoryBits | G->categoryBits; A->categoryBits = C->categoryBits | F->categoryBits; C->flags |= ( B->flags | G->flags ) & b2_enlargedNode; A->flags |= ( C->flags | F->flags ) & b2_enlargedNode; break; case b2_rotateBG: A->children.child1 = iG; C->children.child2 = iB; B->parent = iC; G->parent = iA; C->aabb = aabbBF; C->height = 1 + b2MaxUInt16( B->height, F->height ); A->height = 1 + b2MaxUInt16( C->height, G->height ); C->categoryBits = B->categoryBits | F->categoryBits; A->categoryBits = C->categoryBits | G->categoryBits; C->flags |= ( B->flags | F->flags ) & b2_enlargedNode; A->flags |= ( C->flags | G->flags ) & b2_enlargedNode; break; case b2_rotateCD: A->children.child2 = iD; B->children.child1 = iC; C->parent = iB; D->parent = iA; B->aabb = aabbCE; B->height = 1 + b2MaxUInt16( C->height, E->height ); A->height = 1 + b2MaxUInt16( B->height, D->height ); B->categoryBits = C->categoryBits | E->categoryBits; A->categoryBits = B->categoryBits | D->categoryBits; B->flags |= ( C->flags | E->flags ) & b2_enlargedNode; A->flags |= ( B->flags | D->flags ) & b2_enlargedNode; break; case b2_rotateCE: A->children.child2 = iE; B->children.child2 = iC; C->parent = iB; E->parent = iA; B->aabb = aabbCD; B->height = 1 + b2MaxUInt16( C->height, D->height ); A->height = 1 + b2MaxUInt16( B->height, E->height ); B->categoryBits = C->categoryBits | D->categoryBits; A->categoryBits = B->categoryBits | E->categoryBits; B->flags |= ( C->flags | D->flags ) & b2_enlargedNode; A->flags |= ( B->flags | E->flags ) & b2_enlargedNode; break; default: B2_ASSERT( false ); break; } } } static void b2InsertLeaf( b2DynamicTree* tree, int leaf, bool shouldRotate ) { if ( tree->root == B2_NULL_INDEX ) { tree->root = leaf; tree->nodes[tree->root].parent = B2_NULL_INDEX; return; } // Stage 1: find the best sibling for this node b2AABB leafAABB = tree->nodes[leaf].aabb; int sibling = b2FindBestSibling( tree, leafAABB ); // Stage 2: create a new parent for the leaf and sibling int oldParent = tree->nodes[sibling].parent; int newParent = b2AllocateNode( tree ); // Warning: node pointer can change after allocation b2TreeNode* nodes = tree->nodes; nodes[newParent].parent = oldParent; nodes[newParent].userData = UINT64_MAX; nodes[newParent].aabb = b2AABB_Union( leafAABB, nodes[sibling].aabb ); nodes[newParent].categoryBits = nodes[leaf].categoryBits | nodes[sibling].categoryBits; nodes[newParent].height = nodes[sibling].height + 1; nodes[newParent].children.child1 = sibling; nodes[newParent].children.child2 = leaf; nodes[sibling].parent = newParent; nodes[leaf].parent = newParent; // Fix grandparent links if ( oldParent != B2_NULL_INDEX ) { // The sibling was not the root if ( nodes[oldParent].children.child1 == sibling ) { nodes[oldParent].children.child1 = newParent; } else { B2_ASSERT( nodes[oldParent].children.child2 == sibling ); nodes[oldParent].children.child2 = newParent; } } else { // The sibling was the root tree->root = newParent; } // Stage 3: walk back up the tree fixing heights and AABBs int index = nodes[leaf].parent; while ( index != B2_NULL_INDEX ) { int child1 = nodes[index].children.child1; int child2 = nodes[index].children.child2; B2_ASSERT( child1 != B2_NULL_INDEX ); B2_ASSERT( child2 != B2_NULL_INDEX ); nodes[index].aabb = b2AABB_Union( nodes[child1].aabb, nodes[child2].aabb ); nodes[index].categoryBits = nodes[child1].categoryBits | nodes[child2].categoryBits; nodes[index].height = 1 + b2MaxUInt16( nodes[child1].height, nodes[child2].height ); nodes[index].flags |= ( nodes[child1].flags | nodes[child2].flags ) & b2_enlargedNode; if ( shouldRotate ) { b2RotateNodes( tree, index ); } index = nodes[index].parent; } } static void b2RemoveLeaf( b2DynamicTree* tree, int leaf ) { if ( leaf == tree->root ) { tree->root = B2_NULL_INDEX; return; } b2TreeNode* nodes = tree->nodes; int parent = nodes[leaf].parent; int grandParent = nodes[parent].parent; int sibling; if ( nodes[parent].children.child1 == leaf ) { sibling = nodes[parent].children.child2; } else { sibling = nodes[parent].children.child1; } if ( grandParent != B2_NULL_INDEX ) { // Destroy parent and connect sibling to grandParent. if ( nodes[grandParent].children.child1 == parent ) { nodes[grandParent].children.child1 = sibling; } else { nodes[grandParent].children.child2 = sibling; } nodes[sibling].parent = grandParent; b2FreeNode( tree, parent ); // Adjust ancestor bounds. int index = grandParent; while ( index != B2_NULL_INDEX ) { b2TreeNode* node = nodes + index; b2TreeNode* child1 = nodes + node->children.child1; b2TreeNode* child2 = nodes + node->children.child2; // Fast union using SSE //__m128 aabb1 = _mm_load_ps(&child1->aabb.lowerBound.x); //__m128 aabb2 = _mm_load_ps(&child2->aabb.lowerBound.x); //__m128 lower = _mm_min_ps(aabb1, aabb2); //__m128 upper = _mm_max_ps(aabb1, aabb2); //__m128 aabb = _mm_shuffle_ps(lower, upper, _MM_SHUFFLE(3, 2, 1, 0)); //_mm_store_ps(&node->aabb.lowerBound.x, aabb); node->aabb = b2AABB_Union( child1->aabb, child2->aabb ); node->categoryBits = child1->categoryBits | child2->categoryBits; node->height = 1 + b2MaxUInt16( child1->height, child2->height ); index = node->parent; } } else { tree->root = sibling; tree->nodes[sibling].parent = B2_NULL_INDEX; b2FreeNode( tree, parent ); } } // Create a proxy in the tree as a leaf node. We return the index of the node instead of a pointer so that we can grow // the node pool. int b2DynamicTree_CreateProxy( b2DynamicTree* tree, b2AABB aabb, uint64_t categoryBits, uint64_t userData ) { B2_ASSERT( -B2_HUGE < aabb.lowerBound.x && aabb.lowerBound.x < B2_HUGE ); B2_ASSERT( -B2_HUGE < aabb.lowerBound.y && aabb.lowerBound.y < B2_HUGE ); B2_ASSERT( -B2_HUGE < aabb.upperBound.x && aabb.upperBound.x < B2_HUGE ); B2_ASSERT( -B2_HUGE < aabb.upperBound.y && aabb.upperBound.y < B2_HUGE ); int proxyId = b2AllocateNode( tree ); b2TreeNode* node = tree->nodes + proxyId; node->aabb = aabb; node->userData = userData; node->categoryBits = categoryBits; node->height = 0; node->flags = b2_allocatedNode | b2_leafNode; bool shouldRotate = true; b2InsertLeaf( tree, proxyId, shouldRotate ); tree->proxyCount += 1; return proxyId; } void b2DynamicTree_DestroyProxy( b2DynamicTree* tree, int proxyId ) { B2_ASSERT( 0 <= proxyId && proxyId < tree->nodeCapacity ); B2_ASSERT( b2IsLeaf( tree->nodes + proxyId ) ); b2RemoveLeaf( tree, proxyId ); b2FreeNode( tree, proxyId ); B2_ASSERT( tree->proxyCount > 0 ); tree->proxyCount -= 1; } int b2DynamicTree_GetProxyCount( const b2DynamicTree* tree ) { return tree->proxyCount; } void b2DynamicTree_MoveProxy( b2DynamicTree* tree, int proxyId, b2AABB aabb ) { B2_ASSERT( b2IsValidAABB( aabb ) ); B2_ASSERT( aabb.upperBound.x - aabb.lowerBound.x < B2_HUGE ); B2_ASSERT( aabb.upperBound.y - aabb.lowerBound.y < B2_HUGE ); B2_ASSERT( 0 <= proxyId && proxyId < tree->nodeCapacity ); B2_ASSERT( b2IsLeaf( tree->nodes + proxyId ) ); b2RemoveLeaf( tree, proxyId ); tree->nodes[proxyId].aabb = aabb; bool shouldRotate = false; b2InsertLeaf( tree, proxyId, shouldRotate ); } void b2DynamicTree_EnlargeProxy( b2DynamicTree* tree, int proxyId, b2AABB aabb ) { b2TreeNode* nodes = tree->nodes; B2_ASSERT( b2IsValidAABB( aabb ) ); B2_ASSERT( aabb.upperBound.x - aabb.lowerBound.x < B2_HUGE ); B2_ASSERT( aabb.upperBound.y - aabb.lowerBound.y < B2_HUGE ); B2_ASSERT( 0 <= proxyId && proxyId < tree->nodeCapacity ); B2_ASSERT( b2IsLeaf( tree->nodes + proxyId ) ); // Caller must ensure this B2_ASSERT( b2AABB_Contains( nodes[proxyId].aabb, aabb ) == false ); nodes[proxyId].aabb = aabb; int parentIndex = nodes[proxyId].parent; while ( parentIndex != B2_NULL_INDEX ) { bool changed = b2EnlargeAABB( &nodes[parentIndex].aabb, aabb ); nodes[parentIndex].flags |= b2_enlargedNode; parentIndex = nodes[parentIndex].parent; if ( changed == false ) { break; } } while ( parentIndex != B2_NULL_INDEX ) { if ( nodes[parentIndex].flags & b2_enlargedNode ) { // early out because this ancestor was previously ascended and marked as enlarged break; } nodes[parentIndex].flags |= b2_enlargedNode; parentIndex = nodes[parentIndex].parent; } } void b2DynamicTree_SetCategoryBits( b2DynamicTree* tree, int proxyId, uint64_t categoryBits ) { b2TreeNode* nodes = tree->nodes; B2_ASSERT( nodes[proxyId].children.child1 == B2_NULL_INDEX ); B2_ASSERT( nodes[proxyId].children.child2 == B2_NULL_INDEX ); B2_ASSERT( ( nodes[proxyId].flags & b2_leafNode ) == b2_leafNode ); nodes[proxyId].categoryBits = categoryBits; // Fix up category bits in ancestor internal nodes int nodeIndex = nodes[proxyId].parent; while ( nodeIndex != B2_NULL_INDEX ) { b2TreeNode* node = nodes + nodeIndex; int child1 = node->children.child1; B2_ASSERT( child1 != B2_NULL_INDEX ); int child2 = node->children.child2; B2_ASSERT( child2 != B2_NULL_INDEX ); node->categoryBits = nodes[child1].categoryBits | nodes[child2].categoryBits; nodeIndex = node->parent; } } uint64_t b2DynamicTree_GetCategoryBits( b2DynamicTree* tree, int proxyId ) { B2_ASSERT( 0 <= proxyId && proxyId < tree->nodeCapacity ); return tree->nodes[proxyId].categoryBits; } int b2DynamicTree_GetHeight( const b2DynamicTree* tree ) { if ( tree->root == B2_NULL_INDEX ) { return 0; } return tree->nodes[tree->root].height; } float b2DynamicTree_GetAreaRatio( const b2DynamicTree* tree ) { if ( tree->root == B2_NULL_INDEX ) { return 0.0f; } const b2TreeNode* root = tree->nodes + tree->root; float rootArea = b2Perimeter( root->aabb ); float totalArea = 0.0f; for ( int i = 0; i < tree->nodeCapacity; ++i ) { const b2TreeNode* node = tree->nodes + i; if ( b2IsAllocated( node ) == false || b2IsLeaf( node ) || i == tree->root ) { continue; } totalArea += b2Perimeter( node->aabb ); } return totalArea / rootArea; } b2AABB b2DynamicTree_GetRootBounds( const b2DynamicTree* tree ) { if ( tree->root != B2_NULL_INDEX ) { return tree->nodes[tree->root].aabb; } b2AABB empty = { b2Vec2_zero, b2Vec2_zero }; return empty; } #if B2_VALIDATE // Compute the height of a sub-tree. static int b2ComputeHeight( const b2DynamicTree* tree, int nodeId ) { B2_ASSERT( 0 <= nodeId && nodeId < tree->nodeCapacity ); b2TreeNode* node = tree->nodes + nodeId; if ( b2IsLeaf( node ) ) { return 0; } int height1 = b2ComputeHeight( tree, node->children.child1 ); int height2 = b2ComputeHeight( tree, node->children.child2 ); return 1 + b2MaxInt( height1, height2 ); } static void b2ValidateStructure( const b2DynamicTree* tree, int index ) { if ( index == B2_NULL_INDEX ) { return; } if ( index == tree->root ) { B2_ASSERT( tree->nodes[index].parent == B2_NULL_INDEX ); } const b2TreeNode* node = tree->nodes + index; B2_ASSERT( node->flags == 0 || ( node->flags & b2_allocatedNode ) != 0 ); if ( b2IsLeaf( node ) ) { B2_ASSERT( node->height == 0 ); return; } int child1 = node->children.child1; int child2 = node->children.child2; B2_ASSERT( 0 <= child1 && child1 < tree->nodeCapacity ); B2_ASSERT( 0 <= child2 && child2 < tree->nodeCapacity ); B2_ASSERT( tree->nodes[child1].parent == index ); B2_ASSERT( tree->nodes[child2].parent == index ); if ( ( tree->nodes[child1].flags | tree->nodes[child2].flags ) & b2_enlargedNode ) { B2_ASSERT( node->flags & b2_enlargedNode ); } b2ValidateStructure( tree, child1 ); b2ValidateStructure( tree, child2 ); } static void b2ValidateMetrics( const b2DynamicTree* tree, int index ) { if ( index == B2_NULL_INDEX ) { return; } const b2TreeNode* node = tree->nodes + index; if ( b2IsLeaf( node ) ) { B2_ASSERT( node->height == 0 ); return; } int child1 = node->children.child1; int child2 = node->children.child2; B2_ASSERT( 0 <= child1 && child1 < tree->nodeCapacity ); B2_ASSERT( 0 <= child2 && child2 < tree->nodeCapacity ); int height1 = tree->nodes[child1].height; int height2 = tree->nodes[child2].height; int height = 1 + b2MaxInt( height1, height2 ); B2_ASSERT( node->height == height ); // b2AABB aabb = b2AABB_Union(tree->nodes[child1].aabb, tree->nodes[child2].aabb); B2_ASSERT( b2AABB_Contains( node->aabb, tree->nodes[child1].aabb ) ); B2_ASSERT( b2AABB_Contains( node->aabb, tree->nodes[child2].aabb ) ); // B2_ASSERT(aabb.lowerBound.x == node->aabb.lowerBound.x); // B2_ASSERT(aabb.lowerBound.y == node->aabb.lowerBound.y); // B2_ASSERT(aabb.upperBound.x == node->aabb.upperBound.x); // B2_ASSERT(aabb.upperBound.y == node->aabb.upperBound.y); uint64_t categoryBits = tree->nodes[child1].categoryBits | tree->nodes[child2].categoryBits; B2_ASSERT( node->categoryBits == categoryBits ); b2ValidateMetrics( tree, child1 ); b2ValidateMetrics( tree, child2 ); } #endif void b2DynamicTree_Validate( const b2DynamicTree* tree ) { #if B2_VALIDATE if ( tree->root == B2_NULL_INDEX ) { return; } b2ValidateStructure( tree, tree->root ); b2ValidateMetrics( tree, tree->root ); int freeCount = 0; int freeIndex = tree->freeList; while ( freeIndex != B2_NULL_INDEX ) { B2_ASSERT( 0 <= freeIndex && freeIndex < tree->nodeCapacity ); freeIndex = tree->nodes[freeIndex].next; ++freeCount; } int height = b2DynamicTree_GetHeight( tree ); int computedHeight = b2ComputeHeight( tree, tree->root ); B2_ASSERT( height == computedHeight ); B2_ASSERT( tree->nodeCount + freeCount == tree->nodeCapacity ); #else B2_UNUSED( tree ); #endif } void b2DynamicTree_ValidateNoEnlarged( const b2DynamicTree* tree ) { #if B2_VALIDATE == 1 int capacity = tree->nodeCapacity; const b2TreeNode* nodes = tree->nodes; for ( int i = 0; i < capacity; ++i ) { const b2TreeNode* node = nodes + i; if ( node->flags & b2_allocatedNode ) { B2_ASSERT( ( node->flags & b2_enlargedNode ) == 0 ); } } #else B2_UNUSED( tree ); #endif } int b2DynamicTree_GetByteCount( const b2DynamicTree* tree ) { size_t size = sizeof( b2DynamicTree ) + sizeof( b2TreeNode ) * tree->nodeCapacity + tree->rebuildCapacity * ( sizeof( int ) + sizeof( b2AABB ) + sizeof( b2Vec2 ) + sizeof( int ) ); return (int)size; } uint64_t b2DynamicTree_GetUserData( const b2DynamicTree* tree, int proxyId ) { B2_ASSERT( 0 <= proxyId && proxyId < tree->nodeCapacity ); return tree->nodes[proxyId].userData; } b2AABB b2DynamicTree_GetAABB( const b2DynamicTree* tree, int proxyId ) { B2_ASSERT( 0 <= proxyId && proxyId < tree->nodeCapacity ); return tree->nodes[proxyId].aabb; } b2TreeStats b2DynamicTree_Query( const b2DynamicTree* tree, b2AABB aabb, uint64_t maskBits, b2TreeQueryCallbackFcn* callback, void* context ) { b2TreeStats result = { 0 }; if ( tree->nodeCount == 0 ) { return result; } int stack[B2_TREE_STACK_SIZE]; int stackCount = 0; stack[stackCount++] = tree->root; while ( stackCount > 0 ) { int nodeId = stack[--stackCount]; const b2TreeNode* node = tree->nodes + nodeId; result.nodeVisits += 1; if ( b2AABB_Overlaps( node->aabb, aabb ) && ( node->categoryBits & maskBits ) != 0 ) { if ( b2IsLeaf( node ) ) { // callback to user code with proxy id bool proceed = callback( nodeId, node->userData, context ); result.leafVisits += 1; if ( proceed == false ) { return result; } } else { if ( stackCount < B2_TREE_STACK_SIZE - 1 ) { stack[stackCount++] = node->children.child1; stack[stackCount++] = node->children.child2; } else { B2_ASSERT( stackCount < B2_TREE_STACK_SIZE - 1 ); } } } } return result; } b2TreeStats b2DynamicTree_QueryAll( const b2DynamicTree* tree, b2AABB aabb, b2TreeQueryCallbackFcn* callback, void* context ) { b2TreeStats result = { 0 }; if ( tree->nodeCount == 0 ) { return result; } int stack[B2_TREE_STACK_SIZE]; int stackCount = 0; stack[stackCount++] = tree->root; while ( stackCount > 0 ) { int nodeId = stack[--stackCount]; const b2TreeNode* node = tree->nodes + nodeId; result.nodeVisits += 1; if ( b2AABB_Overlaps( node->aabb, aabb ) ) { if ( b2IsLeaf( node ) ) { // callback to user code with proxy id bool proceed = callback( nodeId, node->userData, context ); result.leafVisits += 1; if ( proceed == false ) { return result; } } else { if ( stackCount < B2_TREE_STACK_SIZE - 1 ) { stack[stackCount++] = node->children.child1; stack[stackCount++] = node->children.child2; } else { B2_ASSERT( stackCount < B2_TREE_STACK_SIZE - 1 ); } } } } return result; } b2TreeStats b2DynamicTree_RayCast( const b2DynamicTree* tree, const b2RayCastInput* input, uint64_t maskBits, b2TreeRayCastCallbackFcn* callback, void* context ) { b2TreeStats result = { 0 }; if ( tree->nodeCount == 0 ) { return result; } b2Vec2 p1 = input->origin; b2Vec2 d = input->translation; b2Vec2 r = b2Normalize( d ); // v is perpendicular to the segment. b2Vec2 v = b2CrossSV( 1.0f, r ); b2Vec2 abs_v = b2Abs( v ); // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) float maxFraction = input->maxFraction; b2Vec2 p2 = b2MulAdd( p1, maxFraction, d ); // Build a bounding box for the segment. b2AABB segmentAABB = { b2Min( p1, p2 ), b2Max( p1, p2 ) }; int stack[B2_TREE_STACK_SIZE]; int stackCount = 0; stack[stackCount++] = tree->root; const b2TreeNode* nodes = tree->nodes; b2RayCastInput subInput = *input; while ( stackCount > 0 ) { int nodeId = stack[--stackCount]; if ( nodeId == B2_NULL_INDEX ) { // todo is this possible? B2_ASSERT( false ); continue; } const b2TreeNode* node = nodes + nodeId; result.nodeVisits += 1; b2AABB nodeAABB = node->aabb; if ( ( node->categoryBits & maskBits ) == 0 || b2AABB_Overlaps( nodeAABB, segmentAABB ) == false ) { continue; } // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) // radius extension is added to the node in this case b2Vec2 c = b2AABB_Center( nodeAABB ); b2Vec2 h = b2AABB_Extents( nodeAABB ); float term1 = b2AbsFloat( b2Dot( v, b2Sub( p1, c ) ) ); float term2 = b2Dot( abs_v, h ); if ( term2 < term1 ) { continue; } if ( b2IsLeaf( node ) ) { subInput.maxFraction = maxFraction; float value = callback( &subInput, nodeId, node->userData, context ); result.leafVisits += 1; // The user may return -1 to indicate this shape should be skipped if ( value == 0.0f ) { // The client has terminated the ray cast. return result; } if ( 0.0f < value && value <= maxFraction ) { // Update segment bounding box. maxFraction = value; p2 = b2MulAdd( p1, maxFraction, d ); segmentAABB.lowerBound = b2Min( p1, p2 ); segmentAABB.upperBound = b2Max( p1, p2 ); } } else { if ( stackCount < B2_TREE_STACK_SIZE - 1 ) { b2Vec2 c1 = b2AABB_Center( nodes[node->children.child1].aabb ); b2Vec2 c2 = b2AABB_Center( nodes[node->children.child2].aabb ); if ( b2DistanceSquared( c1, p1 ) < b2DistanceSquared( c2, p1 ) ) { stack[stackCount++] = node->children.child2; stack[stackCount++] = node->children.child1; } else { stack[stackCount++] = node->children.child1; stack[stackCount++] = node->children.child2; } } else { B2_ASSERT( stackCount < B2_TREE_STACK_SIZE - 1 ); } } } return result; } b2TreeStats b2DynamicTree_ShapeCast( const b2DynamicTree* tree, const b2ShapeCastInput* input, uint64_t maskBits, b2TreeShapeCastCallbackFcn* callback, void* context ) { b2TreeStats stats = { 0 }; if ( tree->nodeCount == 0 || input->proxy.count == 0 ) { return stats; } b2AABB originAABB = { input->proxy.points[0], input->proxy.points[0] }; for ( int i = 1; i < input->proxy.count; ++i ) { originAABB.lowerBound = b2Min( originAABB.lowerBound, input->proxy.points[i] ); originAABB.upperBound = b2Max( originAABB.upperBound, input->proxy.points[i] ); } b2Vec2 radius = { input->proxy.radius, input->proxy.radius }; originAABB.lowerBound = b2Sub( originAABB.lowerBound, radius ); originAABB.upperBound = b2Add( originAABB.upperBound, radius ); b2Vec2 p1 = b2AABB_Center( originAABB ); b2Vec2 extension = b2AABB_Extents( originAABB ); // v is perpendicular to the segment. b2Vec2 r = input->translation; b2Vec2 v = b2CrossSV( 1.0f, r ); b2Vec2 abs_v = b2Abs( v ); // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) float maxFraction = input->maxFraction; // Build total box for the shape cast b2Vec2 t = b2MulSV( maxFraction, input->translation ); b2AABB totalAABB = { b2Min( originAABB.lowerBound, b2Add( originAABB.lowerBound, t ) ), b2Max( originAABB.upperBound, b2Add( originAABB.upperBound, t ) ), }; b2ShapeCastInput subInput = *input; const b2TreeNode* nodes = tree->nodes; int stack[B2_TREE_STACK_SIZE]; int stackCount = 0; stack[stackCount++] = tree->root; while ( stackCount > 0 ) { int nodeId = stack[--stackCount]; if ( nodeId == B2_NULL_INDEX ) { // todo is this possible? B2_ASSERT( false ); continue; } const b2TreeNode* node = nodes + nodeId; stats.nodeVisits += 1; if ( ( node->categoryBits & maskBits ) == 0 || b2AABB_Overlaps( node->aabb, totalAABB ) == false ) { continue; } // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) // radius extension is added to the node in this case b2Vec2 c = b2AABB_Center( node->aabb ); b2Vec2 h = b2Add( b2AABB_Extents( node->aabb ), extension ); float term1 = b2AbsFloat( b2Dot( v, b2Sub( p1, c ) ) ); float term2 = b2Dot( abs_v, h ); if ( term2 < term1 ) { continue; } if ( b2IsLeaf( node ) ) { subInput.maxFraction = maxFraction; float value = callback( &subInput, nodeId, node->userData, context ); stats.leafVisits += 1; if ( value == 0.0f ) { // The client has terminated the ray cast. return stats; } if ( 0.0f < value && value < maxFraction ) { // Update segment bounding box. maxFraction = value; t = b2MulSV( maxFraction, input->translation ); totalAABB.lowerBound = b2Min( originAABB.lowerBound, b2Add( originAABB.lowerBound, t ) ); totalAABB.upperBound = b2Max( originAABB.upperBound, b2Add( originAABB.upperBound, t ) ); } } else { if ( stackCount < B2_TREE_STACK_SIZE - 1 ) { b2Vec2 c1 = b2AABB_Center( nodes[node->children.child1].aabb ); b2Vec2 c2 = b2AABB_Center( nodes[node->children.child2].aabb ); if ( b2DistanceSquared( c1, p1 ) < b2DistanceSquared( c2, p1 ) ) { stack[stackCount++] = node->children.child2; stack[stackCount++] = node->children.child1; } else { stack[stackCount++] = node->children.child1; stack[stackCount++] = node->children.child2; } } else { B2_ASSERT( stackCount < B2_TREE_STACK_SIZE - 1 ); } } } return stats; } // Median split == 0, Surface area heuristic == 1 #define B2_TREE_HEURISTIC 0 #if B2_TREE_HEURISTIC == 0 // Median split heuristic static int b2PartitionMid( int* indices, b2Vec2* centers, int count ) { // Handle trivial case if ( count <= 2 ) { return count / 2; } b2Vec2 lowerBound = centers[0]; b2Vec2 upperBound = centers[0]; for ( int i = 1; i < count; ++i ) { lowerBound = b2Min( lowerBound, centers[i] ); upperBound = b2Max( upperBound, centers[i] ); } b2Vec2 d = b2Sub( upperBound, lowerBound ); b2Vec2 c = { 0.5f * ( lowerBound.x + upperBound.x ), 0.5f * ( lowerBound.y + upperBound.y ) }; // Partition longest axis using the Hoare partition scheme // https://en.wikipedia.org/wiki/Quicksort // https://nicholasvadivelu.com/2021/01/11/array-partition/ int i1 = 0, i2 = count; if ( d.x > d.y ) { float pivot = c.x; while ( i1 < i2 ) { while ( i1 < i2 && centers[i1].x < pivot ) { i1 += 1; }; while ( i1 < i2 && centers[i2 - 1].x >= pivot ) { i2 -= 1; }; if ( i1 < i2 ) { // Swap indices { int temp = indices[i1]; indices[i1] = indices[i2 - 1]; indices[i2 - 1] = temp; } // Swap centers { b2Vec2 temp = centers[i1]; centers[i1] = centers[i2 - 1]; centers[i2 - 1] = temp; } i1 += 1; i2 -= 1; } } } else { float pivot = c.y; while ( i1 < i2 ) { while ( i1 < i2 && centers[i1].y < pivot ) { i1 += 1; }; while ( i1 < i2 && centers[i2 - 1].y >= pivot ) { i2 -= 1; }; if ( i1 < i2 ) { // Swap indices { int temp = indices[i1]; indices[i1] = indices[i2 - 1]; indices[i2 - 1] = temp; } // Swap centers { b2Vec2 temp = centers[i1]; centers[i1] = centers[i2 - 1]; centers[i2 - 1] = temp; } i1 += 1; i2 -= 1; } } } B2_ASSERT( i1 == i2 ); if ( i1 > 0 && i1 < count ) { return i1; } return count / 2; } #else #define B2_BIN_COUNT 8 typedef struct b2TreeBin { b2AABB aabb; int count; } b2TreeBin; typedef struct b2TreePlane { b2AABB leftAABB; b2AABB rightAABB; int leftCount; int rightCount; } b2TreePlane; // "On Fast Construction of SAH-based Bounding Volume Hierarchies" by Ingo Wald // Returns the left child count static int b2PartitionSAH( int* indices, int* binIndices, b2AABB* boxes, int count ) { B2_ASSERT( count > 0 ); b2TreeBin bins[B2_BIN_COUNT]; b2TreePlane planes[B2_BIN_COUNT - 1]; b2Vec2 center = b2AABB_Center( boxes[0] ); b2AABB centroidAABB; centroidAABB.lowerBound = center; centroidAABB.upperBound = center; for ( int i = 1; i < count; ++i ) { center = b2AABB_Center( boxes[i] ); centroidAABB.lowerBound = b2Min( centroidAABB.lowerBound, center ); centroidAABB.upperBound = b2Max( centroidAABB.upperBound, center ); } b2Vec2 d = b2Sub( centroidAABB.upperBound, centroidAABB.lowerBound ); // Find longest axis int axisIndex; float invD; if ( d.x > d.y ) { axisIndex = 0; invD = d.x; } else { axisIndex = 1; invD = d.y; } invD = invD > 0.0f ? 1.0f / invD : 0.0f; // Initialize bin bounds and count for ( int i = 0; i < B2_BIN_COUNT; ++i ) { bins[i].aabb.lowerBound = (b2Vec2){ FLT_MAX, FLT_MAX }; bins[i].aabb.upperBound = (b2Vec2){ -FLT_MAX, -FLT_MAX }; bins[i].count = 0; } // Assign boxes to bins and compute bin boxes // TODO_ERIN optimize float binCount = B2_BIN_COUNT; float lowerBoundArray[2] = { centroidAABB.lowerBound.x, centroidAABB.lowerBound.y }; float minC = lowerBoundArray[axisIndex]; for ( int i = 0; i < count; ++i ) { b2Vec2 c = b2AABB_Center( boxes[i] ); float cArray[2] = { c.x, c.y }; int binIndex = (int)( binCount * ( cArray[axisIndex] - minC ) * invD ); binIndex = b2ClampInt( binIndex, 0, B2_BIN_COUNT - 1 ); binIndices[i] = binIndex; bins[binIndex].count += 1; bins[binIndex].aabb = b2AABB_Union( bins[binIndex].aabb, boxes[i] ); } int planeCount = B2_BIN_COUNT - 1; // Prepare all the left planes, candidates for left child planes[0].leftCount = bins[0].count; planes[0].leftAABB = bins[0].aabb; for ( int i = 1; i < planeCount; ++i ) { planes[i].leftCount = planes[i - 1].leftCount + bins[i].count; planes[i].leftAABB = b2AABB_Union( planes[i - 1].leftAABB, bins[i].aabb ); } // Prepare all the right planes, candidates for right child planes[planeCount - 1].rightCount = bins[planeCount].count; planes[planeCount - 1].rightAABB = bins[planeCount].aabb; for ( int i = planeCount - 2; i >= 0; --i ) { planes[i].rightCount = planes[i + 1].rightCount + bins[i + 1].count; planes[i].rightAABB = b2AABB_Union( planes[i + 1].rightAABB, bins[i + 1].aabb ); } // Find best split to minimize SAH float minCost = FLT_MAX; int bestPlane = 0; for ( int i = 0; i < planeCount; ++i ) { float leftArea = b2Perimeter( planes[i].leftAABB ); float rightArea = b2Perimeter( planes[i].rightAABB ); int leftCount = planes[i].leftCount; int rightCount = planes[i].rightCount; float cost = leftCount * leftArea + rightCount * rightArea; if ( cost < minCost ) { bestPlane = i; minCost = cost; } } // Partition node indices and boxes using the Hoare partition scheme // https://en.wikipedia.org/wiki/Quicksort // https://nicholasvadivelu.com/2021/01/11/array-partition/ int i1 = 0, i2 = count; while ( i1 < i2 ) { while ( i1 < i2 && binIndices[i1] < bestPlane ) { i1 += 1; }; while ( i1 < i2 && binIndices[i2 - 1] >= bestPlane ) { i2 -= 1; }; if ( i1 < i2 ) { // Swap indices { int temp = indices[i1]; indices[i1] = indices[i2 - 1]; indices[i2 - 1] = temp; } // Swap boxes { b2AABB temp = boxes[i1]; boxes[i1] = boxes[i2 - 1]; boxes[i2 - 1] = temp; } i1 += 1; i2 -= 1; } } B2_ASSERT( i1 == i2 ); if ( i1 > 0 && i1 < count ) { return i1; } else { return count / 2; } } #endif // Temporary data used to track the rebuild of a tree node struct b2RebuildItem { int nodeIndex; int childCount; // Leaf indices int startIndex; int splitIndex; int endIndex; }; // Returns root node index static int b2BuildTree( b2DynamicTree* tree, int leafCount ) { b2TreeNode* nodes = tree->nodes; int* leafIndices = tree->leafIndices; if ( leafCount == 1 ) { nodes[leafIndices[0]].parent = B2_NULL_INDEX; return leafIndices[0]; } #if B2_TREE_HEURISTIC == 0 b2Vec2* leafCenters = tree->leafCenters; #else b2AABB* leafBoxes = tree->leafBoxes; int* binIndices = tree->binIndices; #endif // todo large stack item struct b2RebuildItem stack[B2_TREE_STACK_SIZE]; int top = 0; stack[0].nodeIndex = b2AllocateNode( tree ); stack[0].childCount = -1; stack[0].startIndex = 0; stack[0].endIndex = leafCount; #if B2_TREE_HEURISTIC == 0 stack[0].splitIndex = b2PartitionMid( leafIndices, leafCenters, leafCount ); #else stack[0].splitIndex = b2PartitionSAH( leafIndices, binIndices, leafBoxes, leafCount ); #endif while ( true ) { struct b2RebuildItem* item = stack + top; item->childCount += 1; if ( item->childCount == 2 ) { // This internal node has both children established if ( top == 0 ) { // all done break; } struct b2RebuildItem* parentItem = stack + ( top - 1 ); b2TreeNode* parentNode = nodes + parentItem->nodeIndex; if ( parentItem->childCount == 0 ) { B2_ASSERT( parentNode->children.child1 == B2_NULL_INDEX ); parentNode->children.child1 = item->nodeIndex; } else { B2_ASSERT( parentItem->childCount == 1 ); B2_ASSERT( parentNode->children.child2 == B2_NULL_INDEX ); parentNode->children.child2 = item->nodeIndex; } b2TreeNode* node = nodes + item->nodeIndex; B2_ASSERT( node->parent == B2_NULL_INDEX ); node->parent = parentItem->nodeIndex; B2_ASSERT( node->children.child1 != B2_NULL_INDEX ); B2_ASSERT( node->children.child2 != B2_NULL_INDEX ); b2TreeNode* child1 = nodes + node->children.child1; b2TreeNode* child2 = nodes + node->children.child2; node->aabb = b2AABB_Union( child1->aabb, child2->aabb ); node->height = 1 + b2MaxUInt16( child1->height, child2->height ); node->categoryBits = child1->categoryBits | child2->categoryBits; // Pop stack top -= 1; } else { int startIndex, endIndex; if ( item->childCount == 0 ) { startIndex = item->startIndex; endIndex = item->splitIndex; } else { B2_ASSERT( item->childCount == 1 ); startIndex = item->splitIndex; endIndex = item->endIndex; } int count = endIndex - startIndex; if ( count == 1 ) { int childIndex = leafIndices[startIndex]; b2TreeNode* node = nodes + item->nodeIndex; if ( item->childCount == 0 ) { B2_ASSERT( node->children.child1 == B2_NULL_INDEX ); node->children.child1 = childIndex; } else { B2_ASSERT( item->childCount == 1 ); B2_ASSERT( node->children.child2 == B2_NULL_INDEX ); node->children.child2 = childIndex; } b2TreeNode* childNode = nodes + childIndex; B2_ASSERT( childNode->parent == B2_NULL_INDEX ); childNode->parent = item->nodeIndex; } else { B2_ASSERT( count > 0 ); B2_ASSERT( top < B2_TREE_STACK_SIZE ); top += 1; struct b2RebuildItem* newItem = stack + top; newItem->nodeIndex = b2AllocateNode( tree ); newItem->childCount = -1; newItem->startIndex = startIndex; newItem->endIndex = endIndex; #if B2_TREE_HEURISTIC == 0 newItem->splitIndex = b2PartitionMid( leafIndices + startIndex, leafCenters + startIndex, count ); #else newItem->splitIndex = b2PartitionSAH( leafIndices + startIndex, binIndices + startIndex, leafBoxes + startIndex, count ); #endif newItem->splitIndex += startIndex; } } } b2TreeNode* rootNode = nodes + stack[0].nodeIndex; B2_ASSERT( rootNode->parent == B2_NULL_INDEX ); B2_ASSERT( rootNode->children.child1 != B2_NULL_INDEX ); B2_ASSERT( rootNode->children.child2 != B2_NULL_INDEX ); b2TreeNode* child1 = nodes + rootNode->children.child1; b2TreeNode* child2 = nodes + rootNode->children.child2; rootNode->aabb = b2AABB_Union( child1->aabb, child2->aabb ); rootNode->height = 1 + b2MaxUInt16( child1->height, child2->height ); rootNode->categoryBits = child1->categoryBits | child2->categoryBits; return stack[0].nodeIndex; } // Not safe to access tree during this operation because it may grow int b2DynamicTree_Rebuild( b2DynamicTree* tree, bool fullBuild ) { int proxyCount = tree->proxyCount; if ( proxyCount == 0 ) { return 0; } // Ensure capacity for rebuild space if ( proxyCount > tree->rebuildCapacity ) { int newCapacity = proxyCount + proxyCount / 2; b2Free( tree->leafIndices, tree->rebuildCapacity * sizeof( int ) ); tree->leafIndices = b2Alloc( newCapacity * sizeof( int ) ); #if B2_TREE_HEURISTIC == 0 b2Free( tree->leafCenters, tree->rebuildCapacity * sizeof( b2Vec2 ) ); tree->leafCenters = b2Alloc( newCapacity * sizeof( b2Vec2 ) ); #else b2Free( tree->leafBoxes, tree->rebuildCapacity * sizeof( b2AABB ) ); tree->leafBoxes = b2Alloc( newCapacity * sizeof( b2AABB ) ); b2Free( tree->binIndices, tree->rebuildCapacity * sizeof( int ) ); tree->binIndices = b2Alloc( newCapacity * sizeof( int ) ); #endif tree->rebuildCapacity = newCapacity; } int leafCount = 0; int stack[B2_TREE_STACK_SIZE]; int stackCount = 0; int nodeIndex = tree->root; b2TreeNode* nodes = tree->nodes; b2TreeNode* node = nodes + nodeIndex; // These are the nodes that get sorted to rebuild the tree. // I'm using indices because the node pool may grow during the build. int* leafIndices = tree->leafIndices; #if B2_TREE_HEURISTIC == 0 b2Vec2* leafCenters = tree->leafCenters; #else b2AABB* leafBoxes = tree->leafBoxes; #endif // Gather all proxy nodes that have grown and all internal nodes that haven't grown. Both are // considered leaves in the tree rebuild. // Free all internal nodes that have grown. // todo use a node growth metric instead of simply enlarged to reduce rebuild size and frequency // this should be weighed against B2_AABB_MARGIN while ( true ) { if ( node->height == 0 || ( ( node->flags & b2_enlargedNode ) == 0 && fullBuild == false ) ) { leafIndices[leafCount] = nodeIndex; #if B2_TREE_HEURISTIC == 0 leafCenters[leafCount] = b2AABB_Center( node->aabb ); #else leafBoxes[leafCount] = node->aabb; #endif leafCount += 1; // Detach node->parent = B2_NULL_INDEX; } else { int doomedNodeIndex = nodeIndex; // Handle children nodeIndex = node->children.child1; if ( stackCount < B2_TREE_STACK_SIZE ) { stack[stackCount++] = node->children.child2; } else { B2_ASSERT( stackCount < B2_TREE_STACK_SIZE ); } node = nodes + nodeIndex; // Remove doomed node b2FreeNode( tree, doomedNodeIndex ); continue; } if ( stackCount == 0 ) { break; } nodeIndex = stack[--stackCount]; node = nodes + nodeIndex; } #if B2_VALIDATE == 1 int capacity = tree->nodeCapacity; for ( int i = 0; i < capacity; ++i ) { if ( nodes[i].flags & b2_allocatedNode ) { B2_ASSERT( ( nodes[i].flags & b2_enlargedNode ) == 0 ); } } #endif B2_ASSERT( leafCount <= proxyCount ); tree->root = b2BuildTree( tree, leafCount ); b2DynamicTree_Validate( tree ); return leafCount; } ================================================ FILE: src/geometry.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "constants.h" #include "shape.h" #include "box2d/collision.h" #include "box2d/math_functions.h" #include #include _Static_assert( B2_MAX_POLYGON_VERTICES > 2, "must be 3 or more" ); bool b2IsValidRay( const b2RayCastInput* input ) { bool isValid = b2IsValidVec2( input->origin ) && b2IsValidVec2( input->translation ) && b2IsValidFloat( input->maxFraction ) && 0.0f <= input->maxFraction && input->maxFraction < B2_HUGE; return isValid; } static b2Vec2 b2ComputePolygonCentroid( const b2Vec2* vertices, int count ) { b2Vec2 center = { 0.0f, 0.0f }; float area = 0.0f; // Get a reference point for forming triangles. // Use the first vertex to reduce round-off errors. b2Vec2 origin = vertices[0]; const float inv3 = 1.0f / 3.0f; for ( int i = 1; i < count - 1; ++i ) { // Triangle edges b2Vec2 e1 = b2Sub( vertices[i], origin ); b2Vec2 e2 = b2Sub( vertices[i + 1], origin ); float a = 0.5f * b2Cross( e1, e2 ); // Area weighted centroid center = b2MulAdd( center, a * inv3, b2Add( e1, e2 ) ); area += a; } B2_ASSERT( area > FLT_EPSILON ); float invArea = 1.0f / area; center.x *= invArea; center.y *= invArea; // Restore offset center = b2Add( origin, center ); return center; } b2Polygon b2MakePolygon( const b2Hull* hull, float radius ) { B2_ASSERT( b2ValidateHull( hull ) ); if ( hull->count < 3 ) { // Handle a bad hull when assertions are disabled return b2MakeSquare( 0.5f ); } b2Polygon shape = { 0 }; shape.count = hull->count; shape.radius = radius; // Copy vertices for ( int i = 0; i < shape.count; ++i ) { shape.vertices[i] = hull->points[i]; } // Compute normals. Ensure the edges have non-zero length. for ( int i = 0; i < shape.count; ++i ) { int i1 = i; int i2 = i + 1 < shape.count ? i + 1 : 0; b2Vec2 edge = b2Sub( shape.vertices[i2], shape.vertices[i1] ); B2_ASSERT( b2Dot( edge, edge ) > FLT_EPSILON * FLT_EPSILON ); shape.normals[i] = b2Normalize( b2CrossVS( edge, 1.0f ) ); } shape.centroid = b2ComputePolygonCentroid( shape.vertices, shape.count ); return shape; } b2Polygon b2MakeOffsetPolygon( const b2Hull* hull, b2Vec2 position, b2Rot rotation ) { return b2MakeOffsetRoundedPolygon( hull, position, rotation, 0.0f ); } b2Polygon b2MakeOffsetRoundedPolygon( const b2Hull* hull, b2Vec2 position, b2Rot rotation, float radius ) { B2_ASSERT( b2ValidateHull( hull ) ); if ( hull->count < 3 ) { // Handle a bad hull when assertions are disabled return b2MakeSquare( 0.5f ); } b2Transform transform = { position, rotation }; b2Polygon shape = { 0 }; shape.count = hull->count; shape.radius = radius; // Copy vertices for ( int i = 0; i < shape.count; ++i ) { shape.vertices[i] = b2TransformPoint( transform, hull->points[i] ); } // Compute normals. Ensure the edges have non-zero length. for ( int i = 0; i < shape.count; ++i ) { int i1 = i; int i2 = i + 1 < shape.count ? i + 1 : 0; b2Vec2 edge = b2Sub( shape.vertices[i2], shape.vertices[i1] ); B2_ASSERT( b2Dot( edge, edge ) > FLT_EPSILON * FLT_EPSILON ); shape.normals[i] = b2Normalize( b2CrossVS( edge, 1.0f ) ); } shape.centroid = b2ComputePolygonCentroid( shape.vertices, shape.count ); return shape; } b2Polygon b2MakeSquare( float halfWidth ) { return b2MakeBox( halfWidth, halfWidth ); } b2Polygon b2MakeBox( float halfWidth, float halfHeight ) { B2_ASSERT( b2IsValidFloat( halfWidth ) && halfWidth > 0.0f ); B2_ASSERT( b2IsValidFloat( halfHeight ) && halfHeight > 0.0f ); b2Polygon shape = { 0 }; shape.count = 4; shape.vertices[0] = (b2Vec2){ -halfWidth, -halfHeight }; shape.vertices[1] = (b2Vec2){ halfWidth, -halfHeight }; shape.vertices[2] = (b2Vec2){ halfWidth, halfHeight }; shape.vertices[3] = (b2Vec2){ -halfWidth, halfHeight }; shape.normals[0] = (b2Vec2){ 0.0f, -1.0f }; shape.normals[1] = (b2Vec2){ 1.0f, 0.0f }; shape.normals[2] = (b2Vec2){ 0.0f, 1.0f }; shape.normals[3] = (b2Vec2){ -1.0f, 0.0f }; shape.radius = 0.0f; shape.centroid = b2Vec2_zero; return shape; } b2Polygon b2MakeRoundedBox( float halfWidth, float halfHeight, float radius ) { B2_ASSERT( b2IsValidFloat( radius ) && radius >= 0.0f ); b2Polygon shape = b2MakeBox( halfWidth, halfHeight ); shape.radius = radius; return shape; } b2Polygon b2MakeOffsetBox( float halfWidth, float halfHeight, b2Vec2 center, b2Rot rotation ) { b2Transform xf = { center, rotation }; b2Polygon shape = { 0 }; shape.count = 4; shape.vertices[0] = b2TransformPoint( xf, (b2Vec2){ -halfWidth, -halfHeight } ); shape.vertices[1] = b2TransformPoint( xf, (b2Vec2){ halfWidth, -halfHeight } ); shape.vertices[2] = b2TransformPoint( xf, (b2Vec2){ halfWidth, halfHeight } ); shape.vertices[3] = b2TransformPoint( xf, (b2Vec2){ -halfWidth, halfHeight } ); shape.normals[0] = b2RotateVector( xf.q, (b2Vec2){ 0.0f, -1.0f } ); shape.normals[1] = b2RotateVector( xf.q, (b2Vec2){ 1.0f, 0.0f } ); shape.normals[2] = b2RotateVector( xf.q, (b2Vec2){ 0.0f, 1.0f } ); shape.normals[3] = b2RotateVector( xf.q, (b2Vec2){ -1.0f, 0.0f } ); shape.radius = 0.0f; shape.centroid = xf.p; return shape; } b2Polygon b2MakeOffsetRoundedBox( float halfWidth, float halfHeight, b2Vec2 center, b2Rot rotation, float radius ) { B2_ASSERT( b2IsValidFloat( radius ) && radius >= 0.0f ); b2Transform xf = { center, rotation }; b2Polygon shape = { 0 }; shape.count = 4; shape.vertices[0] = b2TransformPoint( xf, (b2Vec2){ -halfWidth, -halfHeight } ); shape.vertices[1] = b2TransformPoint( xf, (b2Vec2){ halfWidth, -halfHeight } ); shape.vertices[2] = b2TransformPoint( xf, (b2Vec2){ halfWidth, halfHeight } ); shape.vertices[3] = b2TransformPoint( xf, (b2Vec2){ -halfWidth, halfHeight } ); shape.normals[0] = b2RotateVector( xf.q, (b2Vec2){ 0.0f, -1.0f } ); shape.normals[1] = b2RotateVector( xf.q, (b2Vec2){ 1.0f, 0.0f } ); shape.normals[2] = b2RotateVector( xf.q, (b2Vec2){ 0.0f, 1.0f } ); shape.normals[3] = b2RotateVector( xf.q, (b2Vec2){ -1.0f, 0.0f } ); shape.radius = radius; shape.centroid = xf.p; return shape; } b2Polygon b2TransformPolygon( b2Transform transform, const b2Polygon* polygon ) { b2Polygon p = *polygon; for ( int i = 0; i < p.count; ++i ) { p.vertices[i] = b2TransformPoint( transform, p.vertices[i] ); p.normals[i] = b2RotateVector( transform.q, p.normals[i] ); } p.centroid = b2TransformPoint( transform, p.centroid ); return p; } b2MassData b2ComputeCircleMass( const b2Circle* shape, float density ) { float rr = shape->radius * shape->radius; b2MassData massData; massData.mass = density * B2_PI * rr; massData.center = shape->center; // inertia about the center of mass massData.rotationalInertia = massData.mass * 0.5f * rr ; return massData; } b2MassData b2ComputeCapsuleMass( const b2Capsule* shape, float density ) { float radius = shape->radius; float rr = radius * radius; b2Vec2 p1 = shape->center1; b2Vec2 p2 = shape->center2; float length = b2Length( b2Sub( p2, p1 ) ); float ll = length * length; float circleMass = density * ( B2_PI * radius * radius ); float boxMass = density * ( 2.0f * radius * length ); b2MassData massData; massData.mass = circleMass + boxMass; massData.center.x = 0.5f * ( p1.x + p2.x ); massData.center.y = 0.5f * ( p1.y + p2.y ); // two offset half circles, both halves add up to full circle and each half is offset by half length // semi-circle centroid = 4 r / 3 pi // Need to apply parallel-axis theorem twice: // 1. shift semi-circle centroid to origin // 2. shift semi-circle to box end // m * ((h + lc)^2 - lc^2) = m * (h^2 + 2 * h * lc) // See: https://en.wikipedia.org/wiki/Parallel_axis_theorem // I verified this formula by computing the convex hull of a 128 vertex capsule // half circle centroid float lc = 4.0f * radius / ( 3.0f * B2_PI ); // half length of rectangular portion of capsule float h = 0.5f * length; float circleInertia = circleMass * ( 0.5f * rr + h * h + 2.0f * h * lc ); float boxInertia = boxMass * ( 4.0f * rr + ll ) / 12.0f; massData.rotationalInertia = circleInertia + boxInertia; return massData; } b2MassData b2ComputePolygonMass( const b2Polygon* shape, float density ) { // Polygon mass, centroid, and inertia. // Let rho be the polygon density in mass per unit area. // Then: // mass = rho * int(dA) // centroid.x = (1/mass) * rho * int(x * dA) // centroid.y = (1/mass) * rho * int(y * dA) // I = rho * int((x*x + y*y) * dA) // // We can compute these integrals by summing all the integrals // for each triangle of the polygon. To evaluate the integral // for a single triangle, we make a change of variables to // the (u,v) coordinates of the triangle: // x = x0 + e1x * u + e2x * v // y = y0 + e1y * u + e2y * v // where 0 <= u && 0 <= v && u + v <= 1. // // We integrate u from [0,1-v] and then v from [0,1]. // We also need to use the Jacobian of the transformation: // D = cross(e1, e2) // // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) // // The rest of the derivation is handled by computer algebra. B2_ASSERT( shape->count > 0 ); if ( shape->count == 1 ) { b2Circle circle; circle.center = shape->vertices[0]; circle.radius = shape->radius; return b2ComputeCircleMass( &circle, density ); } if ( shape->count == 2 ) { b2Capsule capsule; capsule.center1 = shape->vertices[0]; capsule.center2 = shape->vertices[1]; capsule.radius = shape->radius; return b2ComputeCapsuleMass( &capsule, density ); } b2Vec2 vertices[B2_MAX_POLYGON_VERTICES] = { 0 }; int count = shape->count; float radius = shape->radius; if ( radius > 0.0f ) { // Approximate mass of rounded polygons by pushing out the vertices. float sqrt2 = 1.412f; for ( int i = 0; i < count; ++i ) { int j = i == 0 ? count - 1 : i - 1; b2Vec2 n1 = shape->normals[j]; b2Vec2 n2 = shape->normals[i]; b2Vec2 mid = b2Normalize( b2Add( n1, n2 ) ); vertices[i] = b2MulAdd( shape->vertices[i], sqrt2 * radius, mid ); } } else { for ( int i = 0; i < count; ++i ) { vertices[i] = shape->vertices[i]; } } b2Vec2 center = { 0.0f, 0.0f }; float area = 0.0f; float rotationalInertia = 0.0f; // Get a reference point for forming triangles. // Use the first vertex to reduce round-off errors. b2Vec2 r = vertices[0]; const float inv3 = 1.0f / 3.0f; for ( int i = 1; i < count - 1; ++i ) { // Triangle edges b2Vec2 e1 = b2Sub( vertices[i], r ); b2Vec2 e2 = b2Sub( vertices[i + 1], r ); float D = b2Cross( e1, e2 ); float triangleArea = 0.5f * D; area += triangleArea; // Area weighted centroid, r at origin center = b2MulAdd( center, triangleArea * inv3, b2Add( e1, e2 ) ); float ex1 = e1.x, ey1 = e1.y; float ex2 = e2.x, ey2 = e2.y; float intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2; float inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2; rotationalInertia += ( 0.25f * inv3 * D ) * ( intx2 + inty2 ); } b2MassData massData; // Total mass massData.mass = density * area; // Center of mass, shift back from origin at r B2_ASSERT( area > FLT_EPSILON ); float invArea = 1.0f / area; center.x *= invArea; center.y *= invArea; massData.center = b2Add( r, center ); // Inertia tensor relative to the local origin (point s). massData.rotationalInertia = density * rotationalInertia; // Shift inertia to center of mass massData.rotationalInertia -= massData.mass * b2Dot( center, center ); // If this goes negative we are hosed B2_ASSERT( massData.rotationalInertia >= 0.0f ); return massData; } b2AABB b2ComputeCircleAABB( const b2Circle* shape, b2Transform xf ) { b2Vec2 p = b2TransformPoint( xf, shape->center ); float r = shape->radius; b2AABB aabb = { { p.x - r, p.y - r }, { p.x + r, p.y + r } }; return aabb; } b2AABB b2ComputeCapsuleAABB( const b2Capsule* shape, b2Transform xf ) { b2Vec2 v1 = b2TransformPoint( xf, shape->center1 ); b2Vec2 v2 = b2TransformPoint( xf, shape->center2 ); b2Vec2 r = { shape->radius, shape->radius }; b2Vec2 lower = b2Sub( b2Min( v1, v2 ), r ); b2Vec2 upper = b2Add( b2Max( v1, v2 ), r ); b2AABB aabb = { lower, upper }; return aabb; } b2AABB b2ComputePolygonAABB( const b2Polygon* shape, b2Transform xf ) { B2_ASSERT( shape->count > 0 ); b2Vec2 lower = b2TransformPoint( xf, shape->vertices[0] ); b2Vec2 upper = lower; for ( int i = 1; i < shape->count; ++i ) { b2Vec2 v = b2TransformPoint( xf, shape->vertices[i] ); lower = b2Min( lower, v ); upper = b2Max( upper, v ); } b2Vec2 r = { shape->radius, shape->radius }; lower = b2Sub( lower, r ); upper = b2Add( upper, r ); b2AABB aabb = { lower, upper }; return aabb; } b2AABB b2ComputeSegmentAABB( const b2Segment* shape, b2Transform xf ) { b2Vec2 v1 = b2TransformPoint( xf, shape->point1 ); b2Vec2 v2 = b2TransformPoint( xf, shape->point2 ); b2Vec2 lower = b2Min( v1, v2 ); b2Vec2 upper = b2Max( v1, v2 ); b2AABB aabb = { lower, upper }; return aabb; } bool b2PointInCircle( const b2Circle* shape, b2Vec2 point ) { b2Vec2 center = shape->center; return b2DistanceSquared( point, center ) <= shape->radius * shape->radius; } bool b2PointInCapsule( const b2Capsule* shape, b2Vec2 point ) { float rr = shape->radius * shape->radius; b2Vec2 p1 = shape->center1; b2Vec2 p2 = shape->center2; b2Vec2 d = b2Sub( p2, p1 ); float dd = b2Dot( d, d ); if ( dd == 0.0f ) { // Capsule is really a circle return b2DistanceSquared( point, p1 ) <= rr; } // Get closest point on capsule segment // c = p1 + t * d // dot(point - c, d) = 0 // dot(point - p1 - t * d, d) = 0 // t = dot(point - p1, d) / dot(d, d) float t = b2Dot( b2Sub( point, p1 ), d ) / dd; t = b2ClampFloat( t, 0.0f, 1.0f ); b2Vec2 c = b2MulAdd( p1, t, d ); // Is query point within radius around closest point? return b2DistanceSquared( point, c ) <= rr; } bool b2PointInPolygon( const b2Polygon* shape, b2Vec2 point ) { b2DistanceInput input = { 0 }; input.proxyA = b2MakeProxy( shape->vertices, shape->count, 0.0f ); input.proxyB = b2MakeProxy( &point, 1, 0.0f ); input.transformA = b2Transform_identity; input.transformB = b2Transform_identity; input.useRadii = false; b2SimplexCache cache = { 0 }; b2DistanceOutput output = b2ShapeDistance( &input, &cache, NULL, 0 ); return output.distance <= shape->radius; } // Precision Improvements for Ray / Sphere Intersection - Ray Tracing Gems 2019 // http://www.codercorner.com/blog/?p=321 b2CastOutput b2RayCastCircle( const b2Circle* shape, const b2RayCastInput* input ) { B2_ASSERT( b2IsValidRay( input ) ); b2Vec2 p = shape->center; b2CastOutput output = { 0 }; // Shift ray so circle center is the origin b2Vec2 s = b2Sub( input->origin, p ); float r = shape->radius; float rr = r * r; float length; b2Vec2 d = b2GetLengthAndNormalize( &length, input->translation ); if ( length == 0.0f ) { // zero length ray if ( b2LengthSquared( s ) < rr ) { // initial overlap output.point = input->origin; output.hit = true; } return output; } // Find closest point on ray to origin // solve: dot(s + t * d, d) = 0 float t = -b2Dot( s, d ); // c is the closest point on the line to the origin b2Vec2 c = b2MulAdd( s, t, d ); float cc = b2Dot( c, c ); if ( cc > rr ) { // closest point is outside the circle return output; } // Pythagoras float h = sqrtf( rr - cc ); float fraction = t - h; if ( fraction < 0.0f || input->maxFraction * length < fraction ) { // intersection is point outside the range of the ray segment if ( b2LengthSquared( s ) < rr ) { // initial overlap output.point = input->origin; output.hit = true; } return output; } // hit point relative to center b2Vec2 hitPoint = b2MulAdd( s, fraction, d ); output.fraction = fraction / length; output.normal = b2Normalize( hitPoint ); output.point = b2MulAdd( p, shape->radius, output.normal ); output.hit = true; return output; } b2CastOutput b2RayCastCapsule( const b2Capsule* shape, const b2RayCastInput* input ) { B2_ASSERT( b2IsValidRay( input ) ); b2CastOutput output = { 0 }; b2Vec2 v1 = shape->center1; b2Vec2 v2 = shape->center2; b2Vec2 e = b2Sub( v2, v1 ); float capsuleLength; b2Vec2 a = b2GetLengthAndNormalize( &capsuleLength, e ); if ( capsuleLength < FLT_EPSILON ) { // Capsule is really a circle b2Circle circle = { v1, shape->radius }; return b2RayCastCircle( &circle, input ); } b2Vec2 p1 = input->origin; b2Vec2 d = input->translation; // Ray from capsule start to ray start b2Vec2 q = b2Sub( p1, v1 ); float qa = b2Dot( q, a ); // Vector to ray start that is perpendicular to capsule axis b2Vec2 qp = b2MulAdd( q, -qa, a ); float radius = shape->radius; // Does the ray start within the infinite length capsule? if ( b2Dot( qp, qp ) < radius * radius ) { if ( qa < 0.0f ) { // start point behind capsule segment b2Circle circle = { v1, shape->radius }; return b2RayCastCircle( &circle, input ); } if ( qa > capsuleLength ) { // start point ahead of capsule segment b2Circle circle = { v2, shape->radius }; return b2RayCastCircle( &circle, input ); } // ray starts inside capsule -> no hit output.point = input->origin; output.hit = true; return output; } // Perpendicular to capsule axis, pointing right b2Vec2 n = { a.y, -a.x }; float rayLength; b2Vec2 u = b2GetLengthAndNormalize( &rayLength, d ); // Intersect ray with infinite length capsule // v1 + radius * n + s1 * a = p1 + s2 * u // v1 - radius * n + s1 * a = p1 + s2 * u // s1 * a - s2 * u = b // b = q - radius * ap // or // b = q + radius * ap // Cramer's rule [a -u] float den = -a.x * u.y + u.x * a.y; if ( -FLT_EPSILON < den && den < FLT_EPSILON ) { // Ray is parallel to capsule and outside infinite length capsule return output; } b2Vec2 b1 = b2MulSub( q, radius, n ); b2Vec2 b2 = b2MulAdd( q, radius, n ); float invDen = 1.0f / den; // Cramer's rule [a b1] float s21 = ( a.x * b1.y - b1.x * a.y ) * invDen; // Cramer's rule [a b2] float s22 = ( a.x * b2.y - b2.x * a.y ) * invDen; float s2; b2Vec2 b; if ( s21 < s22 ) { s2 = s21; b = b1; } else { s2 = s22; b = b2; n = b2Neg( n ); } if ( s2 < 0.0f || input->maxFraction * rayLength < s2 ) { return output; } // Cramer's rule [b -u] float s1 = ( -b.x * u.y + u.x * b.y ) * invDen; if ( s1 < 0.0f ) { // ray passes behind capsule segment b2Circle circle = { v1, shape->radius }; return b2RayCastCircle( &circle, input ); } else if ( capsuleLength < s1 ) { // ray passes ahead of capsule segment b2Circle circle = { v2, shape->radius }; return b2RayCastCircle( &circle, input ); } else { // ray hits capsule side output.fraction = s2 / rayLength; output.point = b2Add( b2Lerp( v1, v2, s1 / capsuleLength ), b2MulSV( shape->radius, n ) ); output.normal = n; output.hit = true; return output; } } // Ray vs line segment b2CastOutput b2RayCastSegment( const b2Segment* shape, const b2RayCastInput* input, bool oneSided ) { if ( oneSided ) { // Skip left-side collision float offset = b2Cross( b2Sub( input->origin, shape->point1 ), b2Sub( shape->point2, shape->point1 ) ); if ( offset < 0.0f ) { b2CastOutput output = { 0 }; return output; } } // Put the ray into the edge's frame of reference. b2Vec2 p1 = input->origin; b2Vec2 d = input->translation; b2Vec2 v1 = shape->point1; b2Vec2 v2 = shape->point2; b2Vec2 e = b2Sub( v2, v1 ); b2CastOutput output = { 0 }; float length; b2Vec2 eUnit = b2GetLengthAndNormalize( &length, e ); if ( length == 0.0f ) { return output; } // Normal points to the right, looking from v1 towards v2 b2Vec2 normal = b2RightPerp( eUnit ); // Intersect ray with infinite segment using normal // Similar to intersecting a ray with an infinite plane // p = p1 + t * d // dot(normal, p - v1) = 0 // dot(normal, p1 - v1) + t * dot(normal, d) = 0 float numerator = b2Dot( normal, b2Sub( v1, p1 ) ); float denominator = b2Dot( normal, d ); if ( denominator == 0.0f ) { // parallel return output; } float t = numerator / denominator; if ( t < 0.0f || input->maxFraction < t ) { // out of ray range return output; } // Intersection point on infinite segment b2Vec2 p = b2MulAdd( p1, t, d ); // Compute position of p along segment // p = v1 + s * e // s = dot(p - v1, e) / dot(e, e) float s = b2Dot( b2Sub( p, v1 ), eUnit ); if ( s < 0.0f || length < s ) { // out of segment range return output; } if ( numerator > 0.0f ) { normal = b2Neg( normal ); } output.fraction = t; output.point = p; output.normal = normal; output.hit = true; return output; } b2CastOutput b2RayCastPolygon( const b2Polygon* shape, const b2RayCastInput* input ) { B2_ASSERT( b2IsValidRay( input ) ); if ( shape->radius == 0.0f ) { // Shift all math to first vertex since the polygon may be far // from the origin. b2Vec2 base = shape->vertices[0]; b2Vec2 p1 = b2Sub( input->origin, base ); b2Vec2 d = input->translation; float lower = 0.0f, upper = input->maxFraction; int index = -1; b2CastOutput output = { 0 }; for ( int edgeIndex = 0; edgeIndex < shape->count; ++edgeIndex ) { // p = p1 + a * d // dot(normal, p - v) = 0 // dot(normal, p1 - v) + a * dot(normal, d) = 0 b2Vec2 vertex = b2Sub( shape->vertices[edgeIndex], base ); float numerator = b2Dot( shape->normals[edgeIndex], b2Sub( vertex, p1 ) ); float denominator = b2Dot( shape->normals[edgeIndex], d ); if ( denominator == 0.0f ) { // Parallel and runs outside edge if ( numerator < 0.0f ) { return output; } } else { // Note: we want this predicate without division: // lower < numerator / denominator, where denominator < 0 // Since denominator < 0, we have to flip the inequality: // lower < numerator / denominator <==> denominator * lower > numerator. if ( denominator < 0.0f && numerator < lower * denominator ) { // Increase lower. // The segment enters this half-space. lower = numerator / denominator; index = edgeIndex; } else if ( denominator > 0.0f && numerator < upper * denominator ) { // Decrease upper. // The segment exits this half-space. upper = numerator / denominator; } } if ( upper < lower ) { // Ray misses return output; } } B2_ASSERT( 0.0f <= lower && lower <= input->maxFraction ); if ( index >= 0 ) { output.fraction = lower; output.normal = shape->normals[index]; output.point = b2MulAdd( input->origin, lower, d ); output.hit = true; } else { // initial overlap output.point = input->origin; output.hit = true; } return output; } b2ShapeCastPairInput castInput; castInput.proxyA = b2MakeProxy( shape->vertices, shape->count, shape->radius ); castInput.proxyB = b2MakeProxy( &input->origin, 1, 0.0f ); castInput.transformA = b2Transform_identity; castInput.transformB = b2Transform_identity; castInput.translationB = input->translation; castInput.maxFraction = input->maxFraction; castInput.canEncroach = false; return b2ShapeCast( &castInput ); } b2CastOutput b2ShapeCastCircle( const b2Circle* shape, const b2ShapeCastInput* input ) { b2ShapeCastPairInput pairInput; pairInput.proxyA = b2MakeProxy( &shape->center, 1, shape->radius ); pairInput.proxyB = input->proxy; pairInput.transformA = b2Transform_identity; pairInput.transformB = b2Transform_identity; pairInput.translationB = input->translation; pairInput.maxFraction = input->maxFraction; pairInput.canEncroach = input->canEncroach; b2CastOutput output = b2ShapeCast( &pairInput ); return output; } b2CastOutput b2ShapeCastCapsule( const b2Capsule* shape, const b2ShapeCastInput* input ) { b2ShapeCastPairInput pairInput; pairInput.proxyA = b2MakeProxy( &shape->center1, 2, shape->radius ); pairInput.proxyB = input->proxy; pairInput.transformA = b2Transform_identity; pairInput.transformB = b2Transform_identity; pairInput.translationB = input->translation; pairInput.maxFraction = input->maxFraction; pairInput.canEncroach = input->canEncroach; b2CastOutput output = b2ShapeCast( &pairInput ); return output; } b2CastOutput b2ShapeCastSegment( const b2Segment* shape, const b2ShapeCastInput* input ) { b2ShapeCastPairInput pairInput; pairInput.proxyA = b2MakeProxy( &shape->point1, 2, 0.0f ); pairInput.proxyB = input->proxy; pairInput.transformA = b2Transform_identity; pairInput.transformB = b2Transform_identity; pairInput.translationB = input->translation; pairInput.maxFraction = input->maxFraction; pairInput.canEncroach = input->canEncroach; b2CastOutput output = b2ShapeCast( &pairInput ); return output; } b2CastOutput b2ShapeCastPolygon( const b2Polygon* shape, const b2ShapeCastInput* input ) { b2ShapeCastPairInput pairInput; pairInput.proxyA = b2MakeProxy( shape->vertices, shape->count, shape->radius ); pairInput.proxyB = input->proxy; pairInput.transformA = b2Transform_identity; pairInput.transformB = b2Transform_identity; pairInput.translationB = input->translation; pairInput.maxFraction = input->maxFraction; pairInput.canEncroach = input->canEncroach; b2CastOutput output = b2ShapeCast( &pairInput ); return output; } b2PlaneResult b2CollideMoverAndCircle( const b2Capsule* mover, const b2Circle* shape ) { b2DistanceInput distanceInput; distanceInput.proxyA = b2MakeProxy( &shape->center, 1, 0.0f ); distanceInput.proxyB = b2MakeProxy( &mover->center1, 2, mover->radius ); distanceInput.transformA = b2Transform_identity; distanceInput.transformB = b2Transform_identity; distanceInput.useRadii = false; float totalRadius = mover->radius + shape->radius; b2SimplexCache cache = { 0 }; b2DistanceOutput distanceOutput = b2ShapeDistance( &distanceInput, &cache, NULL, 0 ); if ( distanceOutput.distance <= totalRadius ) { b2Plane plane = { distanceOutput.normal, totalRadius - distanceOutput.distance }; return (b2PlaneResult){ .plane = plane, .point = distanceOutput.pointA, .hit = true, }; } return (b2PlaneResult){ 0 }; } b2PlaneResult b2CollideMoverAndCapsule( const b2Capsule* mover, const b2Capsule* shape ) { b2DistanceInput distanceInput; distanceInput.proxyA = b2MakeProxy( &shape->center1, 2, 0.0f ); distanceInput.proxyB = b2MakeProxy( &mover->center1, 2, mover->radius ); distanceInput.transformA = b2Transform_identity; distanceInput.transformB = b2Transform_identity; distanceInput.useRadii = false; float totalRadius = mover->radius + shape->radius; b2SimplexCache cache = { 0 }; b2DistanceOutput distanceOutput = b2ShapeDistance( &distanceInput, &cache, NULL, 0 ); if ( distanceOutput.distance <= totalRadius ) { b2Plane plane = { distanceOutput.normal, totalRadius - distanceOutput.distance }; return (b2PlaneResult){ .plane = plane, .point = distanceOutput.pointA, .hit = true, }; } return (b2PlaneResult){ 0 }; } b2PlaneResult b2CollideMoverAndPolygon( const b2Capsule* mover, const b2Polygon* shape ) { b2DistanceInput distanceInput; distanceInput.proxyA = b2MakeProxy( shape->vertices, shape->count, shape->radius ); distanceInput.proxyB = b2MakeProxy( &mover->center1, 2, mover->radius ); distanceInput.transformA = b2Transform_identity; distanceInput.transformB = b2Transform_identity; distanceInput.useRadii = false; float totalRadius = mover->radius + shape->radius; b2SimplexCache cache = { 0 }; b2DistanceOutput distanceOutput = b2ShapeDistance( &distanceInput, &cache, NULL, 0 ); if ( distanceOutput.distance <= totalRadius ) { b2Plane plane = { distanceOutput.normal, totalRadius - distanceOutput.distance }; return (b2PlaneResult){ .plane = plane, .point = distanceOutput.pointA, .hit = true, }; } return (b2PlaneResult){ 0 }; } b2PlaneResult b2CollideMoverAndSegment( const b2Capsule* mover, const b2Segment* shape ) { b2DistanceInput distanceInput; distanceInput.proxyA = b2MakeProxy( &shape->point1, 2, 0.0f ); distanceInput.proxyB = b2MakeProxy( &mover->center1, 2, mover->radius ); distanceInput.transformA = b2Transform_identity; distanceInput.transformB = b2Transform_identity; distanceInput.useRadii = false; float totalRadius = mover->radius; b2SimplexCache cache = { 0 }; b2DistanceOutput distanceOutput = b2ShapeDistance( &distanceInput, &cache, NULL, 0 ); if ( distanceOutput.distance <= totalRadius ) { b2Plane plane = { distanceOutput.normal, totalRadius - distanceOutput.distance }; return (b2PlaneResult){ .plane = plane, .point = distanceOutput.pointA, .hit = true, }; } return (b2PlaneResult){ 0 }; } ================================================ FILE: src/hull.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "constants.h" #include "core.h" #include "box2d/collision.h" #include "box2d/math_functions.h" #include // quickhull recursion static b2Hull b2RecurseHull( b2Vec2 p1, b2Vec2 p2, b2Vec2* ps, int count ) { b2Hull hull; hull.count = 0; if ( count == 0 ) { return hull; } // create an edge vector pointing from p1 to p2 b2Vec2 e = b2Normalize( b2Sub( p2, p1 ) ); // discard points left of e and find point furthest to the right of e b2Vec2 rightPoints[B2_MAX_POLYGON_VERTICES]; int rightCount = 0; int bestIndex = 0; float bestDistance = b2Cross( b2Sub( ps[bestIndex], p1 ), e ); if ( bestDistance > 0.0f ) { rightPoints[rightCount++] = ps[bestIndex]; } for ( int i = 1; i < count; ++i ) { float distance = b2Cross( b2Sub( ps[i], p1 ), e ); if ( distance > bestDistance ) { bestIndex = i; bestDistance = distance; } if ( distance > 0.0f ) { rightPoints[rightCount++] = ps[i]; } } if ( bestDistance < 2.0f * B2_LINEAR_SLOP ) { return hull; } b2Vec2 bestPoint = ps[bestIndex]; // compute hull to the right of p1-bestPoint b2Hull hull1 = b2RecurseHull( p1, bestPoint, rightPoints, rightCount ); // compute hull to the right of bestPoint-p2 b2Hull hull2 = b2RecurseHull( bestPoint, p2, rightPoints, rightCount ); // stitch together hulls for ( int i = 0; i < hull1.count; ++i ) { hull.points[hull.count++] = hull1.points[i]; } hull.points[hull.count++] = bestPoint; for ( int i = 0; i < hull2.count; ++i ) { hull.points[hull.count++] = hull2.points[i]; } B2_ASSERT( hull.count < B2_MAX_POLYGON_VERTICES ); return hull; } // quickhull algorithm // - merges vertices based on B2_LINEAR_SLOP // - removes collinear points using B2_LINEAR_SLOP // - returns an empty hull if it fails b2Hull b2ComputeHull( const b2Vec2* points, int count ) { b2Hull hull; hull.count = 0; if ( count < 3 || count > B2_MAX_POLYGON_VERTICES ) { // check your data return hull; } count = b2MinInt( count, B2_MAX_POLYGON_VERTICES ); b2AABB aabb = { { FLT_MAX, FLT_MAX }, { -FLT_MAX, -FLT_MAX } }; // Perform aggressive point welding. First point always remains. // Also compute the bounding box for later. b2Vec2 ps[B2_MAX_POLYGON_VERTICES]; int n = 0; const float linearSlop = B2_LINEAR_SLOP; const float tolSqr = 16.0f * linearSlop * linearSlop; for ( int i = 0; i < count; ++i ) { aabb.lowerBound = b2Min( aabb.lowerBound, points[i] ); aabb.upperBound = b2Max( aabb.upperBound, points[i] ); b2Vec2 vi = points[i]; bool unique = true; for ( int j = 0; j < i; ++j ) { b2Vec2 vj = points[j]; float distSqr = b2DistanceSquared( vi, vj ); if ( distSqr < tolSqr ) { unique = false; break; } } if ( unique ) { ps[n++] = vi; } } if ( n < 3 ) { // all points very close together, check your data and check your scale return hull; } // Find an extreme point as the first point on the hull b2Vec2 c = b2AABB_Center( aabb ); int f1 = 0; float dsq1 = b2DistanceSquared( c, ps[f1] ); for ( int i = 1; i < n; ++i ) { float dsq = b2DistanceSquared( c, ps[i] ); if ( dsq > dsq1 ) { f1 = i; dsq1 = dsq; } } // remove p1 from working set b2Vec2 p1 = ps[f1]; ps[f1] = ps[n - 1]; n = n - 1; int f2 = 0; float dsq2 = b2DistanceSquared( p1, ps[f2] ); for ( int i = 1; i < n; ++i ) { float dsq = b2DistanceSquared( p1, ps[i] ); if ( dsq > dsq2 ) { f2 = i; dsq2 = dsq; } } // remove p2 from working set b2Vec2 p2 = ps[f2]; ps[f2] = ps[n - 1]; n = n - 1; // split the points into points that are left and right of the line p1-p2. b2Vec2 rightPoints[B2_MAX_POLYGON_VERTICES - 2]; int rightCount = 0; b2Vec2 leftPoints[B2_MAX_POLYGON_VERTICES - 2]; int leftCount = 0; b2Vec2 e = b2Normalize( b2Sub( p2, p1 ) ); for ( int i = 0; i < n; ++i ) { float d = b2Cross( b2Sub( ps[i], p1 ), e ); // slop used here to skip points that are very close to the line p1-p2 if ( d >= 2.0f * linearSlop ) { rightPoints[rightCount++] = ps[i]; } else if ( d <= -2.0f * linearSlop ) { leftPoints[leftCount++] = ps[i]; } } // compute hulls on right and left b2Hull hull1 = b2RecurseHull( p1, p2, rightPoints, rightCount ); b2Hull hull2 = b2RecurseHull( p2, p1, leftPoints, leftCount ); if ( hull1.count == 0 && hull2.count == 0 ) { // all points collinear return hull; } // stitch hulls together, preserving CCW winding order hull.points[hull.count++] = p1; for ( int i = 0; i < hull1.count; ++i ) { hull.points[hull.count++] = hull1.points[i]; } hull.points[hull.count++] = p2; for ( int i = 0; i < hull2.count; ++i ) { hull.points[hull.count++] = hull2.points[i]; } B2_ASSERT( hull.count <= B2_MAX_POLYGON_VERTICES ); // merge collinear bool searching = true; while ( searching && hull.count > 2 ) { searching = false; for ( int i = 0; i < hull.count; ++i ) { int i1 = i; int i2 = ( i + 1 ) % hull.count; int i3 = ( i + 2 ) % hull.count; b2Vec2 s1 = hull.points[i1]; b2Vec2 s2 = hull.points[i2]; b2Vec2 s3 = hull.points[i3]; // unit edge vector for s1-s3 b2Vec2 r = b2Normalize( b2Sub( s3, s1 ) ); float distance = b2Cross( b2Sub( s2, s1 ), r ); if ( distance <= 2.0f * linearSlop ) { // remove midpoint from hull for ( int j = i2; j < hull.count - 1; ++j ) { hull.points[j] = hull.points[j + 1]; } hull.count -= 1; // continue searching for collinear points searching = true; break; } } } if ( hull.count < 3 ) { // all points collinear, shouldn't be reached since this was validated above hull.count = 0; } return hull; } bool b2ValidateHull( const b2Hull* hull ) { if ( hull->count < 3 || B2_MAX_POLYGON_VERTICES < hull->count ) { return false; } // test that every point is behind every edge for ( int i = 0; i < hull->count; ++i ) { // create an edge vector int i1 = i; int i2 = i < hull->count - 1 ? i1 + 1 : 0; b2Vec2 p = hull->points[i1]; b2Vec2 e = b2Normalize( b2Sub( hull->points[i2], p ) ); for ( int j = 0; j < hull->count; ++j ) { // skip points that subtend the current edge if ( j == i1 || j == i2 ) { continue; } float distance = b2Cross( b2Sub( hull->points[j], p ), e ); if ( distance >= 0.0f ) { return false; } } } // test for collinear points const float linearSlop = B2_LINEAR_SLOP; for ( int i = 0; i < hull->count; ++i ) { int i1 = i; int i2 = ( i + 1 ) % hull->count; int i3 = ( i + 2 ) % hull->count; b2Vec2 p1 = hull->points[i1]; b2Vec2 p2 = hull->points[i2]; b2Vec2 p3 = hull->points[i3]; b2Vec2 e = b2Normalize( b2Sub( p3, p1 ) ); float distance = b2Cross( b2Sub( p2, p1 ), e ); if ( distance <= linearSlop ) { // p1-p2-p3 are collinear return false; } } return true; } ================================================ FILE: src/id_pool.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "id_pool.h" b2IdPool b2CreateIdPool( void ) { b2IdPool pool = { 0 }; pool.freeArray = b2IntArray_Create( 32 ); return pool; } void b2DestroyIdPool( b2IdPool* pool ) { b2IntArray_Destroy( &pool->freeArray ); *pool = ( b2IdPool ){ 0 }; } int b2AllocId( b2IdPool* pool ) { int count = pool->freeArray.count; if ( count > 0 ) { int id = b2IntArray_Pop( &pool->freeArray ); return id; } int id = pool->nextIndex; pool->nextIndex += 1; return id; } void b2FreeId( b2IdPool* pool, int id ) { B2_ASSERT( pool->nextIndex > 0 ); B2_ASSERT( 0 <= id && id < pool->nextIndex ); b2IntArray_Push( &pool->freeArray, id ); } #if B2_VALIDATE void b2ValidateFreeId( b2IdPool* pool, int id ) { int freeCount = pool->freeArray.count; for ( int i = 0; i < freeCount; ++i ) { if ( pool->freeArray.data[i] == id ) { return; } } B2_ASSERT( 0 ); } void b2ValidateUsedId( b2IdPool* pool, int id ) { int freeCount = pool->freeArray.count; for ( int i = 0; i < freeCount; ++i ) { if ( pool->freeArray.data[i] == id ) { B2_ASSERT( 0 ); } } } #else void b2ValidateFreeId( b2IdPool* pool, int id ) { B2_UNUSED( pool, id ); } void b2ValidateUsedId( b2IdPool* pool, int id ) { B2_UNUSED( pool, id ); } #endif ================================================ FILE: src/id_pool.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "array.h" typedef struct b2IdPool { b2IntArray freeArray; int nextIndex; } b2IdPool; b2IdPool b2CreateIdPool( void ); void b2DestroyIdPool( b2IdPool* pool ); int b2AllocId( b2IdPool* pool ); void b2FreeId( b2IdPool* pool, int id ); void b2ValidateFreeId( b2IdPool* pool, int id ); void b2ValidateUsedId( b2IdPool* pool, int id ); static inline int b2GetIdCount( b2IdPool* pool ) { return pool->nextIndex - pool->freeArray.count; } static inline int b2GetIdCapacity( b2IdPool* pool ) { return pool->nextIndex; } static inline int b2GetIdBytes( b2IdPool* pool ) { return b2IntArray_ByteCount(&pool->freeArray); } ================================================ FILE: src/island.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "island.h" #include "body.h" #include "contact.h" #include "core.h" #include "joint.h" #include "physics_world.h" #include "solver_set.h" #include B2_ARRAY_SOURCE( b2Island, b2Island ) B2_ARRAY_SOURCE( b2IslandSim, b2IslandSim ) b2Island* b2CreateIsland( b2World* world, int setIndex ) { B2_ASSERT( setIndex == b2_awakeSet || setIndex >= b2_firstSleepingSet ); int islandId = b2AllocId( &world->islandIdPool ); if ( islandId == world->islands.count ) { b2Island emptyIsland = { 0 }; b2IslandArray_Push( &world->islands, emptyIsland ); } else { B2_ASSERT( world->islands.data[islandId].setIndex == B2_NULL_INDEX ); } b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, setIndex ); b2Island* island = b2IslandArray_Get( &world->islands, islandId ); island->setIndex = setIndex; island->localIndex = set->islandSims.count; island->islandId = islandId; island->headBody = B2_NULL_INDEX; island->tailBody = B2_NULL_INDEX; island->bodyCount = 0; island->headContact = B2_NULL_INDEX; island->tailContact = B2_NULL_INDEX; island->contactCount = 0; island->headJoint = B2_NULL_INDEX; island->tailJoint = B2_NULL_INDEX; island->jointCount = 0; island->constraintRemoveCount = 0; b2IslandSim* islandSim = b2IslandSimArray_Add( &set->islandSims ); islandSim->islandId = islandId; return island; } void b2DestroyIsland( b2World* world, int islandId ) { if ( world->splitIslandId == islandId ) { world->splitIslandId = B2_NULL_INDEX; } // assume island is empty b2Island* island = b2IslandArray_Get( &world->islands, islandId ); b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, island->setIndex ); int movedIndex = b2IslandSimArray_RemoveSwap( &set->islandSims, island->localIndex ); if ( movedIndex != B2_NULL_INDEX ) { // Fix index on moved element b2IslandSim* movedElement = set->islandSims.data + island->localIndex; int movedId = movedElement->islandId; b2Island* movedIsland = b2IslandArray_Get( &world->islands, movedId ); B2_ASSERT( movedIsland->localIndex == movedIndex ); movedIsland->localIndex = island->localIndex; } // Free island and id (preserve island revision) island->islandId = B2_NULL_INDEX; island->setIndex = B2_NULL_INDEX; island->localIndex = B2_NULL_INDEX; b2FreeId( &world->islandIdPool, islandId ); } static int b2MergeIslands( b2World* world, int islandIdA, int islandIdB ) { if ( islandIdA == islandIdB ) { return islandIdA; } if ( islandIdA == B2_NULL_INDEX ) { B2_ASSERT( islandIdB != B2_NULL_INDEX ); return islandIdB; } if ( islandIdB == B2_NULL_INDEX ) { B2_ASSERT( islandIdA != B2_NULL_INDEX ); return islandIdA; } b2Island* islandA = b2IslandArray_Get( &world->islands, islandIdA ); b2Island* islandB = b2IslandArray_Get( &world->islands, islandIdB ); // Keep the biggest island to reduce cache misses b2Island* big; b2Island* small; if ( islandA->bodyCount >= islandB->bodyCount ) { big = islandA; small = islandB; } else { big = islandB; small = islandA; } int bigId = big->islandId; // remap island indices (cache misses) int bodyId = small->headBody; while ( bodyId != B2_NULL_INDEX ) { b2Body* body = b2BodyArray_Get( &world->bodies, bodyId ); body->islandId = bigId; bodyId = body->islandNext; } int contactId = small->headContact; while ( contactId != B2_NULL_INDEX ) { b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); contact->islandId = bigId; contactId = contact->islandNext; } int jointId = small->headJoint; while ( jointId != B2_NULL_INDEX ) { b2Joint* joint = b2JointArray_Get( &world->joints, jointId ); joint->islandId = bigId; jointId = joint->islandNext; } // connect body lists B2_ASSERT( big->tailBody != B2_NULL_INDEX ); b2Body* tailBody = b2BodyArray_Get( &world->bodies, big->tailBody ); B2_ASSERT( tailBody->islandNext == B2_NULL_INDEX ); tailBody->islandNext = small->headBody; B2_ASSERT( small->headBody != B2_NULL_INDEX ); b2Body* headBody = b2BodyArray_Get( &world->bodies, small->headBody ); B2_ASSERT( headBody->islandPrev == B2_NULL_INDEX ); headBody->islandPrev = big->tailBody; big->tailBody = small->tailBody; big->bodyCount += small->bodyCount; // connect contact lists if ( big->headContact == B2_NULL_INDEX ) { // Big island has no contacts B2_ASSERT( big->tailContact == B2_NULL_INDEX && big->contactCount == 0 ); big->headContact = small->headContact; big->tailContact = small->tailContact; big->contactCount = small->contactCount; } else if ( small->headContact != B2_NULL_INDEX ) { // Both islands have contacts B2_ASSERT( small->tailContact != B2_NULL_INDEX && small->contactCount > 0 ); B2_ASSERT( big->tailContact != B2_NULL_INDEX && big->contactCount > 0 ); b2Contact* tailContact = b2ContactArray_Get( &world->contacts, big->tailContact ); B2_ASSERT( tailContact->islandNext == B2_NULL_INDEX ); tailContact->islandNext = small->headContact; b2Contact* headContact = b2ContactArray_Get( &world->contacts, small->headContact ); B2_ASSERT( headContact->islandPrev == B2_NULL_INDEX ); headContact->islandPrev = big->tailContact; big->tailContact = small->tailContact; big->contactCount += small->contactCount; } if ( big->headJoint == B2_NULL_INDEX ) { // Root island has no joints B2_ASSERT( big->tailJoint == B2_NULL_INDEX && big->jointCount == 0 ); big->headJoint = small->headJoint; big->tailJoint = small->tailJoint; big->jointCount = small->jointCount; } else if ( small->headJoint != B2_NULL_INDEX ) { // Both islands have joints B2_ASSERT( small->tailJoint != B2_NULL_INDEX && small->jointCount > 0 ); B2_ASSERT( big->tailJoint != B2_NULL_INDEX && big->jointCount > 0 ); b2Joint* tailJoint = b2JointArray_Get( &world->joints, big->tailJoint ); B2_ASSERT( tailJoint->islandNext == B2_NULL_INDEX ); tailJoint->islandNext = small->headJoint; b2Joint* headJoint = b2JointArray_Get( &world->joints, small->headJoint ); B2_ASSERT( headJoint->islandPrev == B2_NULL_INDEX ); headJoint->islandPrev = big->tailJoint; big->tailJoint = small->tailJoint; big->jointCount += small->jointCount; } // Track removed constraints big->constraintRemoveCount += small->constraintRemoveCount; small->bodyCount = 0; small->contactCount = 0; small->jointCount = 0; small->headBody = B2_NULL_INDEX; small->headContact = B2_NULL_INDEX; small->headJoint = B2_NULL_INDEX; small->tailBody = B2_NULL_INDEX; small->tailContact = B2_NULL_INDEX; small->tailJoint = B2_NULL_INDEX; small->constraintRemoveCount = 0; b2DestroyIsland( world, small->islandId ); b2ValidateIsland( world, bigId ); return bigId; } static void b2AddContactToIsland( b2World* world, int islandId, b2Contact* contact ) { B2_ASSERT( contact->islandId == B2_NULL_INDEX ); B2_ASSERT( contact->islandPrev == B2_NULL_INDEX ); B2_ASSERT( contact->islandNext == B2_NULL_INDEX ); b2Island* island = b2IslandArray_Get( &world->islands, islandId ); if ( island->headContact != B2_NULL_INDEX ) { contact->islandNext = island->headContact; b2Contact* headContact = b2ContactArray_Get( &world->contacts, island->headContact ); headContact->islandPrev = contact->contactId; } island->headContact = contact->contactId; if ( island->tailContact == B2_NULL_INDEX ) { island->tailContact = island->headContact; } island->contactCount += 1; contact->islandId = islandId; b2ValidateIsland( world, islandId ); } // Link a contact into an island. void b2LinkContact( b2World* world, b2Contact* contact ) { B2_ASSERT( ( contact->flags & b2_contactTouchingFlag ) != 0 ); int bodyIdA = contact->edges[0].bodyId; int bodyIdB = contact->edges[1].bodyId; b2Body* bodyA = b2BodyArray_Get( &world->bodies, bodyIdA ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, bodyIdB ); B2_ASSERT( bodyA->setIndex != b2_disabledSet && bodyB->setIndex != b2_disabledSet ); B2_ASSERT( bodyA->setIndex != b2_staticSet || bodyB->setIndex != b2_staticSet ); // Wake bodyB if bodyA is awake and bodyB is sleeping if ( bodyA->setIndex == b2_awakeSet && bodyB->setIndex >= b2_firstSleepingSet ) { b2WakeSolverSet( world, bodyB->setIndex ); } // Wake bodyA if bodyB is awake and bodyA is sleeping if ( bodyB->setIndex == b2_awakeSet && bodyA->setIndex >= b2_firstSleepingSet ) { b2WakeSolverSet( world, bodyA->setIndex ); } int islandIdA = bodyA->islandId; int islandIdB = bodyB->islandId; // Static bodies have null island indices. B2_ASSERT( bodyA->setIndex != b2_staticSet || islandIdA == B2_NULL_INDEX ); B2_ASSERT( bodyB->setIndex != b2_staticSet || islandIdB == B2_NULL_INDEX ); B2_ASSERT( islandIdA != B2_NULL_INDEX || islandIdB != B2_NULL_INDEX ); // Merge islands. This will destroy one of the islands. int finalIslandId = b2MergeIslands( world, islandIdA, islandIdB ); // Add contact to the island that survived b2AddContactToIsland( world, finalIslandId, contact ); } // This is called when a contact no longer has contact points or when a contact is destroyed. void b2UnlinkContact( b2World* world, b2Contact* contact ) { B2_ASSERT( contact->islandId != B2_NULL_INDEX ); // remove from island int islandId = contact->islandId; b2Island* island = b2IslandArray_Get( &world->islands, islandId ); if ( contact->islandPrev != B2_NULL_INDEX ) { b2Contact* prevContact = b2ContactArray_Get( &world->contacts, contact->islandPrev ); B2_ASSERT( prevContact->islandNext == contact->contactId ); prevContact->islandNext = contact->islandNext; } if ( contact->islandNext != B2_NULL_INDEX ) { b2Contact* nextContact = b2ContactArray_Get( &world->contacts, contact->islandNext ); B2_ASSERT( nextContact->islandPrev == contact->contactId ); nextContact->islandPrev = contact->islandPrev; } if ( island->headContact == contact->contactId ) { island->headContact = contact->islandNext; } if ( island->tailContact == contact->contactId ) { island->tailContact = contact->islandPrev; } B2_ASSERT( island->contactCount > 0 ); island->contactCount -= 1; island->constraintRemoveCount += 1; contact->islandId = B2_NULL_INDEX; contact->islandPrev = B2_NULL_INDEX; contact->islandNext = B2_NULL_INDEX; b2ValidateIsland( world, islandId ); } static void b2AddJointToIsland( b2World* world, int islandId, b2Joint* joint ) { B2_ASSERT( joint->islandId == B2_NULL_INDEX ); B2_ASSERT( joint->islandPrev == B2_NULL_INDEX ); B2_ASSERT( joint->islandNext == B2_NULL_INDEX ); b2Island* island = b2IslandArray_Get( &world->islands, islandId ); if ( island->headJoint != B2_NULL_INDEX ) { joint->islandNext = island->headJoint; b2Joint* headJoint = b2JointArray_Get( &world->joints, island->headJoint ); headJoint->islandPrev = joint->jointId; } island->headJoint = joint->jointId; if ( island->tailJoint == B2_NULL_INDEX ) { island->tailJoint = island->headJoint; } island->jointCount += 1; joint->islandId = islandId; b2ValidateIsland( world, islandId ); } void b2LinkJoint( b2World* world, b2Joint* joint ) { b2Body* bodyA = b2BodyArray_Get( &world->bodies, joint->edges[0].bodyId ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, joint->edges[1].bodyId ); B2_ASSERT( bodyA->type == b2_dynamicBody || bodyB->type == b2_dynamicBody ); if ( bodyA->setIndex == b2_awakeSet && bodyB->setIndex >= b2_firstSleepingSet ) { b2WakeSolverSet( world, bodyB->setIndex ); } else if ( bodyB->setIndex == b2_awakeSet && bodyA->setIndex >= b2_firstSleepingSet ) { b2WakeSolverSet( world, bodyA->setIndex ); } int islandIdA = bodyA->islandId; int islandIdB = bodyB->islandId; B2_ASSERT( islandIdA != B2_NULL_INDEX || islandIdB != B2_NULL_INDEX ); // Merge islands. This will destroy one of the islands. int finalIslandId = b2MergeIslands( world, islandIdA, islandIdB ); // Add joint the island that survived b2AddJointToIsland( world, finalIslandId, joint ); } void b2UnlinkJoint( b2World* world, b2Joint* joint ) { if ( joint->islandId == B2_NULL_INDEX ) { return; } // remove from island int islandId = joint->islandId; b2Island* island = b2IslandArray_Get( &world->islands, islandId ); if ( joint->islandPrev != B2_NULL_INDEX ) { b2Joint* prevJoint = b2JointArray_Get( &world->joints, joint->islandPrev ); B2_ASSERT( prevJoint->islandNext == joint->jointId ); prevJoint->islandNext = joint->islandNext; } if ( joint->islandNext != B2_NULL_INDEX ) { b2Joint* nextJoint = b2JointArray_Get( &world->joints, joint->islandNext ); B2_ASSERT( nextJoint->islandPrev == joint->jointId ); nextJoint->islandPrev = joint->islandPrev; } if ( island->headJoint == joint->jointId ) { island->headJoint = joint->islandNext; } if ( island->tailJoint == joint->jointId ) { island->tailJoint = joint->islandPrev; } B2_ASSERT( island->jointCount > 0 ); island->jointCount -= 1; island->constraintRemoveCount += 1; joint->islandId = B2_NULL_INDEX; joint->islandPrev = B2_NULL_INDEX; joint->islandNext = B2_NULL_INDEX; b2ValidateIsland( world, islandId ); } #define B2_CONTACT_REMOVE_THRESHOLD 1 // Possible optimizations: // 2. start from the sleepy bodies and stop processing if a sleep body is connected to a non-sleepy body // 3. use a sleepy flag on bodies to avoid velocity access void b2SplitIsland( b2World* world, int baseId ) { b2Island* baseIsland = b2IslandArray_Get( &world->islands, baseId ); int setIndex = baseIsland->setIndex; if ( setIndex != b2_awakeSet ) { // can only split awake island return; } if ( baseIsland->constraintRemoveCount == 0 ) { // this island doesn't need to be split return; } b2ValidateIsland( world, baseId ); int bodyCount = baseIsland->bodyCount; b2Body* bodies = world->bodies.data; b2ArenaAllocator* alloc = &world->arena; // No lock is needed because I ensure the allocator is not used while this task is active. int* stack = b2AllocateArenaItem( alloc, bodyCount * sizeof( int ), "island stack" ); int* bodyIds = b2AllocateArenaItem( alloc, bodyCount * sizeof( int ), "body ids" ); // Build array containing all body indices from base island. These // serve as seed bodies for the depth first search (DFS). int index = 0; int nextBody = baseIsland->headBody; while ( nextBody != B2_NULL_INDEX ) { bodyIds[index++] = nextBody; b2Body* body = bodies + nextBody; nextBody = body->islandNext; } B2_ASSERT( index == bodyCount ); // Each island is found as a depth first search starting from a seed body for ( int i = 0; i < bodyCount; ++i ) { int seedIndex = bodyIds[i]; b2Body* seed = bodies + seedIndex; B2_ASSERT( seed->setIndex == setIndex ); if ( seed->islandId != baseId ) { // The body has already been visited continue; } int stackCount = 0; stack[stackCount++] = seedIndex; // Create new island // No lock needed because only a single island can split per time step. No islands are being used during the constraint // solve. However, islands are touched during body finalization. b2Island* island = b2CreateIsland( world, setIndex ); int islandId = island->islandId; seed->islandId = islandId; // Perform a depth first search (DFS) on the constraint graph. while ( stackCount > 0 ) { // Grab the next body off the stack and add it to the island. int bodyId = stack[--stackCount]; b2Body* body = bodies + bodyId; B2_ASSERT( body->setIndex == b2_awakeSet ); B2_ASSERT( body->islandId == islandId ); // Add body to island if ( island->tailBody != B2_NULL_INDEX ) { bodies[island->tailBody].islandNext = bodyId; } body->islandPrev = island->tailBody; body->islandNext = B2_NULL_INDEX; island->tailBody = bodyId; if ( island->headBody == B2_NULL_INDEX ) { island->headBody = bodyId; } island->bodyCount += 1; // Search all contacts connected to this body. int contactKey = body->headContactKey; while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); B2_ASSERT( contact->contactId == contactId ); // Next key contactKey = contact->edges[edgeIndex].nextKey; // Has this contact already been added to this island? if ( contact->islandId == islandId ) { continue; } // Is this contact enabled and touching? if ( ( contact->flags & b2_contactTouchingFlag ) == 0 ) { continue; } int otherEdgeIndex = edgeIndex ^ 1; int otherBodyId = contact->edges[otherEdgeIndex].bodyId; b2Body* otherBody = bodies + otherBodyId; // Maybe add other body to stack if ( otherBody->islandId != islandId && otherBody->setIndex != b2_staticSet ) { B2_ASSERT( stackCount < bodyCount ); stack[stackCount++] = otherBodyId; // Need to update the body's island id immediately so it is not traversed again otherBody->islandId = islandId; } // Add contact to island contact->islandId = islandId; if ( island->tailContact != B2_NULL_INDEX ) { b2Contact* tailContact = b2ContactArray_Get( &world->contacts, island->tailContact ); tailContact->islandNext = contactId; } contact->islandPrev = island->tailContact; contact->islandNext = B2_NULL_INDEX; island->tailContact = contactId; if ( island->headContact == B2_NULL_INDEX ) { island->headContact = contactId; } island->contactCount += 1; } // Search all joints connect to this body. int jointKey = body->headJointKey; while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; b2Joint* joint = b2JointArray_Get( &world->joints, jointId ); B2_ASSERT( joint->jointId == jointId ); // Next key jointKey = joint->edges[edgeIndex].nextKey; // Has this joint already been added to this island? if ( joint->islandId == islandId ) { continue; } // todo redundant with test below? if ( joint->setIndex == b2_disabledSet ) { continue; } int otherEdgeIndex = edgeIndex ^ 1; int otherBodyId = joint->edges[otherEdgeIndex].bodyId; b2Body* otherBody = bodies + otherBodyId; // Don't simulate joints connected to disabled bodies. if ( otherBody->setIndex == b2_disabledSet ) { continue; } // At least one body must be dynamic if ( body->type != b2_dynamicBody && otherBody->type != b2_dynamicBody ) { continue; } // Maybe add other body to stack if ( otherBody->islandId != islandId && otherBody->setIndex == b2_awakeSet ) { B2_ASSERT( stackCount < bodyCount ); stack[stackCount++] = otherBodyId; // Need to update the body's island id immediately so it is not traversed again otherBody->islandId = islandId; } // Add joint to island joint->islandId = islandId; if ( island->tailJoint != B2_NULL_INDEX ) { b2Joint* tailJoint = b2JointArray_Get( &world->joints, island->tailJoint ); tailJoint->islandNext = jointId; } joint->islandPrev = island->tailJoint; joint->islandNext = B2_NULL_INDEX; island->tailJoint = jointId; if ( island->headJoint == B2_NULL_INDEX ) { island->headJoint = jointId; } island->jointCount += 1; } } b2ValidateIsland( world, islandId ); } // Done with the base split island. This is delayed because the baseId is used as a marker and it // should not be recycled in while splitting. b2DestroyIsland( world, baseId ); b2FreeArenaItem( alloc, bodyIds ); b2FreeArenaItem( alloc, stack ); } // Split an island because some contacts and/or joints have been removed. // This is called during the constraint solve while islands are not being touched. This uses DFS and touches a lot of memory, // so it can be quite slow. // Note: contacts/joints connected to static bodies must belong to an island but don't affect island connectivity // Note: static bodies are never in an island // Note: this task interacts with some allocators without locks under the assumption that no other tasks // are interacting with these data structures. void b2SplitIslandTask( int startIndex, int endIndex, uint32_t threadIndex, void* context ) { b2TracyCZoneNC( split, "Split Island", b2_colorOlive, true ); B2_UNUSED( startIndex, endIndex, threadIndex ); uint64_t ticks = b2GetTicks(); b2World* world = context; B2_ASSERT( world->splitIslandId != B2_NULL_INDEX ); b2SplitIsland( world, world->splitIslandId ); world->profile.splitIslands += b2GetMilliseconds( ticks ); b2TracyCZoneEnd( split ); } #if B2_VALIDATE void b2ValidateIsland( b2World* world, int islandId ) { if ( islandId == B2_NULL_INDEX ) { return; } b2Island* island = b2IslandArray_Get( &world->islands, islandId ); B2_ASSERT( island->islandId == islandId ); B2_ASSERT( island->setIndex != B2_NULL_INDEX ); B2_ASSERT( island->headBody != B2_NULL_INDEX ); { B2_ASSERT( island->tailBody != B2_NULL_INDEX ); B2_ASSERT( island->bodyCount > 0 ); if ( island->bodyCount > 1 ) { B2_ASSERT( island->tailBody != island->headBody ); } B2_ASSERT( island->bodyCount <= b2GetIdCount( &world->bodyIdPool ) ); int count = 0; int bodyId = island->headBody; while ( bodyId != B2_NULL_INDEX ) { b2Body* body = b2BodyArray_Get( &world->bodies, bodyId ); B2_ASSERT( body->islandId == islandId ); B2_ASSERT( body->setIndex == island->setIndex ); count += 1; if ( count == island->bodyCount ) { B2_ASSERT( bodyId == island->tailBody ); } bodyId = body->islandNext; } B2_ASSERT( count == island->bodyCount ); } if ( island->headContact != B2_NULL_INDEX ) { B2_ASSERT( island->tailContact != B2_NULL_INDEX ); B2_ASSERT( island->contactCount > 0 ); if ( island->contactCount > 1 ) { B2_ASSERT( island->tailContact != island->headContact ); } B2_ASSERT( island->contactCount <= b2GetIdCount( &world->contactIdPool ) ); int count = 0; int contactId = island->headContact; while ( contactId != B2_NULL_INDEX ) { b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); B2_ASSERT( contact->setIndex == island->setIndex ); B2_ASSERT( contact->islandId == islandId ); count += 1; if ( count == island->contactCount ) { B2_ASSERT( contactId == island->tailContact ); } contactId = contact->islandNext; } B2_ASSERT( count == island->contactCount ); } else { B2_ASSERT( island->tailContact == B2_NULL_INDEX ); B2_ASSERT( island->contactCount == 0 ); } if ( island->headJoint != B2_NULL_INDEX ) { B2_ASSERT( island->tailJoint != B2_NULL_INDEX ); B2_ASSERT( island->jointCount > 0 ); if ( island->jointCount > 1 ) { B2_ASSERT( island->tailJoint != island->headJoint ); } B2_ASSERT( island->jointCount <= b2GetIdCount( &world->jointIdPool ) ); int count = 0; int jointId = island->headJoint; while ( jointId != B2_NULL_INDEX ) { b2Joint* joint = b2JointArray_Get( &world->joints, jointId ); B2_ASSERT( joint->setIndex == island->setIndex ); count += 1; if ( count == island->jointCount ) { B2_ASSERT( jointId == island->tailJoint ); } jointId = joint->islandNext; } B2_ASSERT( count == island->jointCount ); } else { B2_ASSERT( island->tailJoint == B2_NULL_INDEX ); B2_ASSERT( island->jointCount == 0 ); } } #else void b2ValidateIsland( b2World* world, int islandId ) { B2_UNUSED( world ); B2_UNUSED( islandId ); } #endif ================================================ FILE: src/island.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "array.h" #include #include typedef struct b2Contact b2Contact; typedef struct b2Joint b2Joint; typedef struct b2World b2World; // Deterministic solver // // Collide all awake contacts // Use bit array to emit start/stop touching events in defined order, per thread. Try using contact index, assuming contacts are // created in a deterministic order. bit-wise OR together bit arrays and issue changes: // - start touching: merge islands - temporary linked list - mark root island dirty - wake all - largest island is root // - stop touching: increment constraintRemoveCount // Persistent island for awake bodies, joints, and contacts // https://en.wikipedia.org/wiki/Component_(graph_theory) // https://en.wikipedia.org/wiki/Dynamic_connectivity // map from int to solver set and index typedef struct b2Island { // index of solver set stored in b2World // may be B2_NULL_INDEX int setIndex; // island index within set // may be B2_NULL_INDEX int localIndex; int islandId; int headBody; int tailBody; int bodyCount; int headContact; int tailContact; int contactCount; int headJoint; int tailJoint; int jointCount; // Keeps track of how many contacts have been removed from this island. // This is used to determine if an island is a candidate for splitting. int constraintRemoveCount; } b2Island; // This is used to move islands across solver sets typedef struct b2IslandSim { int islandId; } b2IslandSim; b2Island* b2CreateIsland( b2World* world, int setIndex ); void b2DestroyIsland( b2World* world, int islandId ); // Link contacts into the island graph when it starts having contact points void b2LinkContact( b2World* world, b2Contact* contact ); // Unlink contact from the island graph when it stops having contact points void b2UnlinkContact( b2World* world, b2Contact* contact ); // Link a joint into the island graph when it is created void b2LinkJoint( b2World* world, b2Joint* joint ); // Unlink a joint from the island graph when it is destroyed void b2UnlinkJoint( b2World* world, b2Joint* joint ); void b2SplitIsland( b2World* world, int baseId ); void b2SplitIslandTask( int startIndex, int endIndex, uint32_t threadIndex, void* context ); void b2ValidateIsland( b2World* world, int islandId ); B2_ARRAY_INLINE( b2Island, b2Island ) B2_ARRAY_INLINE( b2IslandSim, b2IslandSim ) ================================================ FILE: src/joint.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "joint.h" #include "body.h" #include "contact.h" #include "core.h" #include "island.h" #include "physics_world.h" #include "shape.h" #include "solver.h" #include "solver_set.h" // needed for dll export #include "box2d/box2d.h" #include #include #include B2_ARRAY_SOURCE( b2Joint, b2Joint ) B2_ARRAY_SOURCE( b2JointSim, b2JointSim ) B2_ARRAY_SOURCE( b2JointEvent, b2JointEvent ) static b2JointDef b2DefaultJointDef( void ) { b2JointDef def = { 0 }; def.localFrameA.q = b2Rot_identity; def.localFrameB.q = b2Rot_identity; def.forceThreshold = FLT_MAX; def.torqueThreshold = FLT_MAX; def.constraintHertz = 60.0f; def.constraintDampingRatio = 2.0f; def.drawScale = b2_lengthUnitsPerMeter; return def; } b2DistanceJointDef b2DefaultDistanceJointDef( void ) { b2DistanceJointDef def = { 0 }; def.base = b2DefaultJointDef(); def.lowerSpringForce = -FLT_MAX; def.upperSpringForce = FLT_MAX; def.length = 1.0f; def.maxLength = B2_HUGE; def.internalValue = B2_SECRET_COOKIE; return def; } b2MotorJointDef b2DefaultMotorJointDef( void ) { b2MotorJointDef def = { 0 }; def.base = b2DefaultJointDef(); def.internalValue = B2_SECRET_COOKIE; return def; } b2FilterJointDef b2DefaultFilterJointDef( void ) { b2FilterJointDef def = { 0 }; def.base = b2DefaultJointDef(); def.internalValue = B2_SECRET_COOKIE; return def; } b2PrismaticJointDef b2DefaultPrismaticJointDef( void ) { b2PrismaticJointDef def = { 0 }; def.base = b2DefaultJointDef(); def.internalValue = B2_SECRET_COOKIE; return def; } b2RevoluteJointDef b2DefaultRevoluteJointDef( void ) { b2RevoluteJointDef def = { 0 }; def.base = b2DefaultJointDef(); def.internalValue = B2_SECRET_COOKIE; return def; } b2WeldJointDef b2DefaultWeldJointDef( void ) { b2WeldJointDef def = { 0 }; def.base = b2DefaultJointDef(); def.internalValue = B2_SECRET_COOKIE; return def; } b2WheelJointDef b2DefaultWheelJointDef( void ) { b2WheelJointDef def = { 0 }; def.base = b2DefaultJointDef(); def.enableSpring = true; def.hertz = 1.0f; def.dampingRatio = 0.7f; def.internalValue = B2_SECRET_COOKIE; return def; } b2ExplosionDef b2DefaultExplosionDef( void ) { b2ExplosionDef def = { 0 }; def.maskBits = B2_DEFAULT_MASK_BITS; return def; } b2Joint* b2GetJointFullId( b2World* world, b2JointId jointId ) { int id = jointId.index1 - 1; b2Joint* joint = b2JointArray_Get( &world->joints, id ); B2_ASSERT( joint->jointId == id && joint->generation == jointId.generation ); return joint; } b2JointSim* b2GetJointSim( b2World* world, b2Joint* joint ) { if ( joint->setIndex == b2_awakeSet ) { B2_ASSERT( 0 <= joint->colorIndex && joint->colorIndex < B2_GRAPH_COLOR_COUNT ); b2GraphColor* color = world->constraintGraph.colors + joint->colorIndex; return b2JointSimArray_Get( &color->jointSims, joint->localIndex ); } b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, joint->setIndex ); return b2JointSimArray_Get( &set->jointSims, joint->localIndex ); } b2JointSim* b2GetJointSimCheckType( b2JointId jointId, b2JointType type ) { B2_UNUSED( type ); b2World* world = b2GetWorld( jointId.world0 ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return NULL; } b2Joint* joint = b2GetJointFullId( world, jointId ); B2_ASSERT( joint->type == type ); b2JointSim* jointSim = b2GetJointSim( world, joint ); B2_ASSERT( jointSim->type == type ); return jointSim; } static void b2DestroyContactsBetweenBodies( b2World* world, b2Body* bodyA, b2Body* bodyB ) { int contactKey; int otherBodyId; // use the smaller of the two contact lists if ( bodyA->contactCount < bodyB->contactCount ) { contactKey = bodyA->headContactKey; otherBodyId = bodyB->id; } else { contactKey = bodyB->headContactKey; otherBodyId = bodyA->id; } // no need to wake bodies when a joint removes collision between them bool wakeBodies = false; // destroy the contacts while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); contactKey = contact->edges[edgeIndex].nextKey; int otherEdgeIndex = edgeIndex ^ 1; if ( contact->edges[otherEdgeIndex].bodyId == otherBodyId ) { // Careful, this removes the contact from the current doubly linked list b2DestroyContact( world, contact, wakeBodies ); } } b2ValidateSolverSets( world ); } typedef struct b2JointPair { b2Joint* joint; b2JointSim* jointSim; } b2JointPair; static b2JointPair b2CreateJoint( b2World* world, const b2JointDef* def, b2JointType type ) { B2_ASSERT( b2IsValidTransform( def->localFrameA ) ); B2_ASSERT( b2IsValidTransform( def->localFrameB ) ); B2_ASSERT( world->worldId == def->bodyIdA.world0 ); B2_ASSERT( world->worldId == def->bodyIdB.world0 ); B2_ASSERT( B2_ID_EQUALS( def->bodyIdA, def->bodyIdB ) == false ); b2Body* bodyA = b2GetBodyFullId( world, def->bodyIdA ); b2Body* bodyB = b2GetBodyFullId( world, def->bodyIdB ); int bodyIdA = bodyA->id; int bodyIdB = bodyB->id; int maxSetIndex = b2MaxInt( bodyA->setIndex, bodyB->setIndex ); // Create joint id and joint int jointId = b2AllocId( &world->jointIdPool ); if ( jointId == world->joints.count ) { b2JointArray_Push( &world->joints, (b2Joint){ 0 } ); } b2Joint* joint = b2JointArray_Get( &world->joints, jointId ); joint->jointId = jointId; joint->userData = def->userData; joint->generation += 1; joint->setIndex = B2_NULL_INDEX; joint->colorIndex = B2_NULL_INDEX; joint->localIndex = B2_NULL_INDEX; joint->islandId = B2_NULL_INDEX; joint->islandPrev = B2_NULL_INDEX; joint->islandNext = B2_NULL_INDEX; joint->drawScale = def->drawScale; joint->type = type; joint->collideConnected = def->collideConnected; //joint->isMarked = false; // Doubly linked list on bodyA joint->edges[0].bodyId = bodyIdA; joint->edges[0].prevKey = B2_NULL_INDEX; joint->edges[0].nextKey = bodyA->headJointKey; int keyA = ( jointId << 1 ) | 0; if ( bodyA->headJointKey != B2_NULL_INDEX ) { b2Joint* jointA = b2JointArray_Get( &world->joints, bodyA->headJointKey >> 1 ); b2JointEdge* edgeA = jointA->edges + ( bodyA->headJointKey & 1 ); edgeA->prevKey = keyA; } bodyA->headJointKey = keyA; bodyA->jointCount += 1; // Doubly linked list on bodyB joint->edges[1].bodyId = bodyIdB; joint->edges[1].prevKey = B2_NULL_INDEX; joint->edges[1].nextKey = bodyB->headJointKey; int keyB = ( jointId << 1 ) | 1; if ( bodyB->headJointKey != B2_NULL_INDEX ) { b2Joint* jointB = b2JointArray_Get( &world->joints, bodyB->headJointKey >> 1 ); b2JointEdge* edgeB = jointB->edges + ( bodyB->headJointKey & 1 ); edgeB->prevKey = keyB; } bodyB->headJointKey = keyB; bodyB->jointCount += 1; b2JointSim* jointSim; if ( bodyA->setIndex == b2_disabledSet || bodyB->setIndex == b2_disabledSet ) { // if either body is disabled, create in disabled set b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, b2_disabledSet ); joint->setIndex = b2_disabledSet; joint->localIndex = set->jointSims.count; jointSim = b2JointSimArray_Add( &set->jointSims ); memset( jointSim, 0, sizeof( b2JointSim ) ); jointSim->jointId = jointId; jointSim->bodyIdA = bodyIdA; jointSim->bodyIdB = bodyIdB; } else if ( bodyA->type != b2_dynamicBody && bodyB->type != b2_dynamicBody ) { // joint is not attached to a dynamic body b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, b2_staticSet ); joint->setIndex = b2_staticSet; joint->localIndex = set->jointSims.count; jointSim = b2JointSimArray_Add( &set->jointSims ); memset( jointSim, 0, sizeof( b2JointSim ) ); jointSim->jointId = jointId; jointSim->bodyIdA = bodyIdA; jointSim->bodyIdB = bodyIdB; } else if ( bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet ) { // if either body is sleeping, wake it if ( maxSetIndex >= b2_firstSleepingSet ) { b2WakeSolverSet( world, maxSetIndex ); } joint->setIndex = b2_awakeSet; jointSim = b2CreateJointInGraph( world, joint ); jointSim->jointId = jointId; jointSim->bodyIdA = bodyIdA; jointSim->bodyIdB = bodyIdB; } else { // joint connected between sleeping and/or static bodies B2_ASSERT( bodyA->setIndex >= b2_firstSleepingSet || bodyB->setIndex >= b2_firstSleepingSet ); B2_ASSERT( bodyA->setIndex != b2_staticSet || bodyB->setIndex != b2_staticSet ); // joint should go into the sleeping set (not static set) int setIndex = maxSetIndex; b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, setIndex ); joint->setIndex = setIndex; joint->localIndex = set->jointSims.count; jointSim = b2JointSimArray_Add( &set->jointSims ); memset( jointSim, 0, sizeof( b2JointSim ) ); // These must be set to accommodate the merge below jointSim->jointId = jointId; jointSim->bodyIdA = bodyIdA; jointSim->bodyIdB = bodyIdB; if ( bodyA->setIndex != bodyB->setIndex && bodyA->setIndex >= b2_firstSleepingSet && bodyB->setIndex >= b2_firstSleepingSet ) { // merge sleeping sets b2MergeSolverSets( world, bodyA->setIndex, bodyB->setIndex ); B2_ASSERT( bodyA->setIndex == bodyB->setIndex ); // fix potentially invalid set index setIndex = bodyA->setIndex; b2SolverSet* mergedSet = b2SolverSetArray_Get( &world->solverSets, setIndex ); // Careful! The joint sim pointer was orphaned by the set merge. jointSim = b2JointSimArray_Get( &mergedSet->jointSims, joint->localIndex ); } B2_ASSERT( joint->setIndex == setIndex ); } jointSim->localFrameA = def->localFrameA; jointSim->localFrameB = def->localFrameB; jointSim->type = type; jointSim->constraintHertz = def->constraintHertz; jointSim->constraintDampingRatio = def->constraintDampingRatio; jointSim->constraintSoftness = (b2Softness){ .biasRate = 0.0f, .massScale = 1.0f, .impulseScale = 0.0f, }; B2_ASSERT( b2IsValidFloat( def->forceThreshold ) && def->forceThreshold >= 0.0f ); B2_ASSERT( b2IsValidFloat( def->torqueThreshold ) && def->torqueThreshold >= 0.0f ); jointSim->forceThreshold = def->forceThreshold; jointSim->torqueThreshold = def->torqueThreshold; B2_ASSERT( jointSim->jointId == jointId ); B2_ASSERT( jointSim->bodyIdA == bodyIdA ); B2_ASSERT( jointSim->bodyIdB == bodyIdB ); if ( joint->setIndex > b2_disabledSet ) { // Add edge to island graph b2LinkJoint( world, joint ); } // If the joint prevents collisions, then destroy all contacts between attached bodies if ( def->collideConnected == false ) { b2DestroyContactsBetweenBodies( world, bodyA, bodyB ); } b2ValidateSolverSets( world ); return (b2JointPair){ joint, jointSim }; } b2JointId b2CreateDistanceJoint( b2WorldId worldId, const b2DistanceJointDef* def ) { B2_CHECK_DEF( def ); b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return (b2JointId){ 0 }; } B2_ASSERT( b2IsValidFloat( def->length ) && def->length > 0.0f ); B2_ASSERT( def->lowerSpringForce <= def->upperSpringForce ); b2JointPair pair = b2CreateJoint( world, &def->base, b2_distanceJoint ); b2JointSim* joint = pair.jointSim; b2DistanceJoint empty = { 0 }; joint->distanceJoint = empty; joint->distanceJoint.length = b2MaxFloat( def->length, B2_LINEAR_SLOP ); joint->distanceJoint.hertz = def->hertz; joint->distanceJoint.dampingRatio = def->dampingRatio; joint->distanceJoint.minLength = b2MaxFloat( def->minLength, B2_LINEAR_SLOP ); joint->distanceJoint.maxLength = b2MaxFloat( def->minLength, def->maxLength ); joint->distanceJoint.maxMotorForce = def->maxMotorForce; joint->distanceJoint.motorSpeed = def->motorSpeed; joint->distanceJoint.enableSpring = def->enableSpring; joint->distanceJoint.lowerSpringForce = def->lowerSpringForce; joint->distanceJoint.upperSpringForce = def->upperSpringForce; joint->distanceJoint.enableLimit = def->enableLimit; joint->distanceJoint.enableMotor = def->enableMotor; joint->distanceJoint.impulse = 0.0f; joint->distanceJoint.lowerImpulse = 0.0f; joint->distanceJoint.upperImpulse = 0.0f; joint->distanceJoint.motorImpulse = 0.0f; b2JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation }; return jointId; } b2JointId b2CreateMotorJoint( b2WorldId worldId, const b2MotorJointDef* def ) { B2_CHECK_DEF( def ); b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return (b2JointId){ 0 }; } b2JointPair pair = b2CreateJoint( world, &def->base, b2_motorJoint ); b2JointSim* joint = pair.jointSim; joint->motorJoint = (b2MotorJoint){ 0 }; joint->motorJoint.linearVelocity = def->linearVelocity; joint->motorJoint.maxVelocityForce = def->maxVelocityForce; joint->motorJoint.angularVelocity = def->angularVelocity; joint->motorJoint.maxVelocityTorque = def->maxVelocityTorque; joint->motorJoint.linearHertz = def->linearHertz; joint->motorJoint.linearDampingRatio = def->linearDampingRatio; joint->motorJoint.maxSpringForce = def->maxSpringForce; joint->motorJoint.angularHertz = def->angularHertz; joint->motorJoint.angularDampingRatio = def->angularDampingRatio; joint->motorJoint.maxSpringTorque = def->maxSpringTorque; b2JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation }; return jointId; } b2JointId b2CreateFilterJoint( b2WorldId worldId, const b2FilterJointDef* def ) { B2_CHECK_DEF( def ); b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return (b2JointId){ 0 }; } b2JointPair pair = b2CreateJoint( world, &def->base, b2_filterJoint ); b2JointSim* joint = pair.jointSim; b2JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation }; return jointId; } b2JointId b2CreatePrismaticJoint( b2WorldId worldId, const b2PrismaticJointDef* def ) { B2_CHECK_DEF( def ); B2_ASSERT( def->lowerTranslation <= def->upperTranslation ); b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return (b2JointId){ 0 }; } b2JointPair pair = b2CreateJoint( world, &def->base, b2_prismaticJoint ); b2JointSim* joint = pair.jointSim; joint->prismaticJoint = (b2PrismaticJoint){ 0 }; joint->prismaticJoint.hertz = def->hertz; joint->prismaticJoint.dampingRatio = def->dampingRatio; joint->prismaticJoint.targetTranslation = def->targetTranslation; joint->prismaticJoint.lowerTranslation = def->lowerTranslation; joint->prismaticJoint.upperTranslation = def->upperTranslation; joint->prismaticJoint.maxMotorForce = def->maxMotorForce; joint->prismaticJoint.motorSpeed = def->motorSpeed; joint->prismaticJoint.enableSpring = def->enableSpring; joint->prismaticJoint.enableLimit = def->enableLimit; joint->prismaticJoint.enableMotor = def->enableMotor; b2JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation }; return jointId; } b2JointId b2CreateRevoluteJoint( b2WorldId worldId, const b2RevoluteJointDef* def ) { B2_CHECK_DEF( def ); B2_ASSERT( def->lowerAngle <= def->upperAngle ); B2_ASSERT( def->lowerAngle >= -0.99f * B2_PI ); B2_ASSERT( def->upperAngle <= 0.99f * B2_PI ); b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return (b2JointId){ 0 }; } b2JointPair pair = b2CreateJoint( world, &def->base, b2_revoluteJoint ); b2JointSim* joint = pair.jointSim; b2RevoluteJoint empty = { 0 }; joint->revoluteJoint = empty; joint->revoluteJoint.targetAngle = b2ClampFloat( def->targetAngle, -B2_PI, B2_PI ); joint->revoluteJoint.hertz = def->hertz; joint->revoluteJoint.dampingRatio = def->dampingRatio; joint->revoluteJoint.lowerAngle = def->lowerAngle; joint->revoluteJoint.upperAngle = def->upperAngle; joint->revoluteJoint.maxMotorTorque = def->maxMotorTorque; joint->revoluteJoint.motorSpeed = def->motorSpeed; joint->revoluteJoint.enableSpring = def->enableSpring; joint->revoluteJoint.enableLimit = def->enableLimit; joint->revoluteJoint.enableMotor = def->enableMotor; b2JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation }; return jointId; } b2JointId b2CreateWeldJoint( b2WorldId worldId, const b2WeldJointDef* def ) { B2_CHECK_DEF( def ); b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return (b2JointId){ 0 }; } b2JointPair pair = b2CreateJoint( world, &def->base, b2_weldJoint ); b2JointSim* joint = pair.jointSim; b2WeldJoint empty = { 0 }; joint->weldJoint = empty; joint->weldJoint.linearHertz = def->linearHertz; joint->weldJoint.linearDampingRatio = def->linearDampingRatio; joint->weldJoint.angularHertz = def->angularHertz; joint->weldJoint.angularDampingRatio = def->angularDampingRatio; joint->weldJoint.linearImpulse = b2Vec2_zero; joint->weldJoint.angularImpulse = 0.0f; b2JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation }; return jointId; } b2JointId b2CreateWheelJoint( b2WorldId worldId, const b2WheelJointDef* def ) { B2_CHECK_DEF( def ); B2_ASSERT( def->lowerTranslation <= def->upperTranslation ); b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return (b2JointId){ 0 }; } b2JointPair pair = b2CreateJoint( world, &def->base, b2_wheelJoint ); b2JointSim* joint = pair.jointSim; joint->wheelJoint = (b2WheelJoint){ 0 }; joint->wheelJoint.perpMass = 0.0f; joint->wheelJoint.axialMass = 0.0f; joint->wheelJoint.motorImpulse = 0.0f; joint->wheelJoint.lowerImpulse = 0.0f; joint->wheelJoint.upperImpulse = 0.0f; joint->wheelJoint.lowerTranslation = def->lowerTranslation; joint->wheelJoint.upperTranslation = def->upperTranslation; joint->wheelJoint.maxMotorTorque = def->maxMotorTorque; joint->wheelJoint.motorSpeed = def->motorSpeed; joint->wheelJoint.hertz = def->hertz; joint->wheelJoint.dampingRatio = def->dampingRatio; joint->wheelJoint.enableSpring = def->enableSpring; joint->wheelJoint.enableLimit = def->enableLimit; joint->wheelJoint.enableMotor = def->enableMotor; b2JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation }; return jointId; } void b2DestroyJointInternal( b2World* world, b2Joint* joint, bool wakeBodies ) { int jointId = joint->jointId; b2JointEdge* edgeA = joint->edges + 0; b2JointEdge* edgeB = joint->edges + 1; int idA = edgeA->bodyId; int idB = edgeB->bodyId; b2Body* bodyA = b2BodyArray_Get( &world->bodies, idA ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, idB ); // Remove from body A if ( edgeA->prevKey != B2_NULL_INDEX ) { b2Joint* prevJoint = b2JointArray_Get( &world->joints, edgeA->prevKey >> 1 ); b2JointEdge* prevEdge = prevJoint->edges + ( edgeA->prevKey & 1 ); prevEdge->nextKey = edgeA->nextKey; } if ( edgeA->nextKey != B2_NULL_INDEX ) { b2Joint* nextJoint = b2JointArray_Get( &world->joints, edgeA->nextKey >> 1 ); b2JointEdge* nextEdge = nextJoint->edges + ( edgeA->nextKey & 1 ); nextEdge->prevKey = edgeA->prevKey; } int edgeKeyA = ( jointId << 1 ) | 0; if ( bodyA->headJointKey == edgeKeyA ) { bodyA->headJointKey = edgeA->nextKey; } bodyA->jointCount -= 1; // Remove from body B if ( edgeB->prevKey != B2_NULL_INDEX ) { b2Joint* prevJoint = b2JointArray_Get( &world->joints, edgeB->prevKey >> 1 ); b2JointEdge* prevEdge = prevJoint->edges + ( edgeB->prevKey & 1 ); prevEdge->nextKey = edgeB->nextKey; } if ( edgeB->nextKey != B2_NULL_INDEX ) { b2Joint* nextJoint = b2JointArray_Get( &world->joints, edgeB->nextKey >> 1 ); b2JointEdge* nextEdge = nextJoint->edges + ( edgeB->nextKey & 1 ); nextEdge->prevKey = edgeB->prevKey; } int edgeKeyB = ( jointId << 1 ) | 1; if ( bodyB->headJointKey == edgeKeyB ) { bodyB->headJointKey = edgeB->nextKey; } bodyB->jointCount -= 1; if ( joint->islandId != B2_NULL_INDEX ) { B2_ASSERT( joint->setIndex > b2_disabledSet ); b2UnlinkJoint( world, joint ); } else { B2_ASSERT( joint->setIndex <= b2_disabledSet ); } // Remove joint from solver set that owns it int setIndex = joint->setIndex; int localIndex = joint->localIndex; if ( setIndex == b2_awakeSet ) { b2RemoveJointFromGraph( world, joint->edges[0].bodyId, joint->edges[1].bodyId, joint->colorIndex, localIndex ); } else { b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, setIndex ); int movedIndex = b2JointSimArray_RemoveSwap( &set->jointSims, localIndex ); if ( movedIndex != B2_NULL_INDEX ) { // Fix moved joint b2JointSim* movedJointSim = set->jointSims.data + localIndex; int movedId = movedJointSim->jointId; b2Joint* movedJoint = b2JointArray_Get( &world->joints, movedId ); B2_ASSERT( movedJoint->localIndex == movedIndex ); movedJoint->localIndex = localIndex; } } // Free joint and id (preserve joint generation) joint->setIndex = B2_NULL_INDEX; joint->localIndex = B2_NULL_INDEX; joint->colorIndex = B2_NULL_INDEX; joint->jointId = B2_NULL_INDEX; b2FreeId( &world->jointIdPool, jointId ); if ( wakeBodies ) { b2WakeBody( world, bodyA ); b2WakeBody( world, bodyB ); } b2ValidateSolverSets( world ); } void b2DestroyJoint( b2JointId jointId, bool wakeAttached ) { b2World* world = b2GetWorld( jointId.world0 ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return; } b2Joint* joint = b2GetJointFullId( world, jointId ); b2DestroyJointInternal( world, joint, wakeAttached ); } b2JointType b2Joint_GetType( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); return joint->type; } b2BodyId b2Joint_GetBodyA( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); return b2MakeBodyId( world, joint->edges[0].bodyId ); } b2BodyId b2Joint_GetBodyB( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); return b2MakeBodyId( world, joint->edges[1].bodyId ); } b2WorldId b2Joint_GetWorld( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); return (b2WorldId){ jointId.world0 + 1, world->generation }; } void b2Joint_SetLocalFrameA( b2JointId jointId, b2Transform localFrame ) { B2_ASSERT( b2IsValidTransform( localFrame ) ); b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); b2JointSim* jointSim = b2GetJointSim( world, joint ); jointSim->localFrameA = localFrame; } b2Transform b2Joint_GetLocalFrameA( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); b2JointSim* jointSim = b2GetJointSim( world, joint ); return jointSim->localFrameA; } void b2Joint_SetLocalFrameB( b2JointId jointId, b2Transform localFrame ) { B2_ASSERT( b2IsValidTransform( localFrame ) ); b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); b2JointSim* jointSim = b2GetJointSim( world, joint ); jointSim->localFrameB = localFrame; } b2Transform b2Joint_GetLocalFrameB( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); b2JointSim* jointSim = b2GetJointSim( world, joint ); return jointSim->localFrameB; } void b2Joint_SetCollideConnected( b2JointId jointId, bool shouldCollide ) { b2World* world = b2GetWorldLocked( jointId.world0 ); if ( world == NULL ) { return; } b2Joint* joint = b2GetJointFullId( world, jointId ); if ( joint->collideConnected == shouldCollide ) { return; } joint->collideConnected = shouldCollide; b2Body* bodyA = b2BodyArray_Get( &world->bodies, joint->edges[0].bodyId ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, joint->edges[1].bodyId ); if ( shouldCollide ) { // need to tell the broad-phase to look for new pairs for one of the // two bodies. Pick the one with the fewest shapes. int shapeCountA = bodyA->shapeCount; int shapeCountB = bodyB->shapeCount; int shapeId = shapeCountA < shapeCountB ? bodyA->headShapeId : bodyB->headShapeId; while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); if ( shape->proxyKey != B2_NULL_INDEX ) { b2BufferMove( &world->broadPhase, shape->proxyKey ); } shapeId = shape->nextShapeId; } } else { b2DestroyContactsBetweenBodies( world, bodyA, bodyB ); } } bool b2Joint_GetCollideConnected( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); return joint->collideConnected; } void b2Joint_SetUserData( b2JointId jointId, void* userData ) { b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); joint->userData = userData; } void* b2Joint_GetUserData( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); return joint->userData; } void b2Joint_WakeBodies( b2JointId jointId ) { b2World* world = b2GetWorldLocked( jointId.world0 ); if ( world == NULL ) { return; } b2Joint* joint = b2GetJointFullId( world, jointId ); b2Body* bodyA = b2BodyArray_Get( &world->bodies, joint->edges[0].bodyId ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, joint->edges[1].bodyId ); b2WakeBody( world, bodyA ); b2WakeBody( world, bodyB ); } void b2GetJointReaction( b2JointSim* sim, float invTimeStep, float* force, float* torque ) { float linearImpulse = 0.0f; float angularImpulse = 0.0f; switch ( sim->type ) { case b2_distanceJoint: { b2DistanceJoint* joint = &sim->distanceJoint; linearImpulse = b2AbsFloat( joint->impulse + joint->lowerImpulse - joint->upperImpulse + joint->motorImpulse ); } break; case b2_motorJoint: { b2MotorJoint* joint = &sim->motorJoint; linearImpulse = b2Length( b2Add(joint->linearVelocityImpulse, joint->linearSpringImpulse) ); angularImpulse = b2AbsFloat( joint->angularVelocityImpulse + joint->angularSpringImpulse ); } break; case b2_prismaticJoint: { b2PrismaticJoint* joint = &sim->prismaticJoint; float perpImpulse = joint->impulse.x; float axialImpulse = joint->motorImpulse + joint->lowerImpulse - joint->upperImpulse; linearImpulse = sqrtf( perpImpulse * perpImpulse + axialImpulse * axialImpulse ); angularImpulse = b2AbsFloat( joint->impulse.y ); } break; case b2_revoluteJoint: { b2RevoluteJoint* joint = &sim->revoluteJoint; linearImpulse = b2Length( joint->linearImpulse ); angularImpulse = b2AbsFloat( joint->motorImpulse + joint->lowerImpulse - joint->upperImpulse ); } break; case b2_weldJoint: { b2WeldJoint* joint = &sim->weldJoint; linearImpulse = b2Length( joint->linearImpulse ); angularImpulse = b2AbsFloat( joint->angularImpulse ); } break; case b2_wheelJoint: { b2WheelJoint* joint = &sim->wheelJoint; float perpImpulse = joint->perpImpulse; float axialImpulse = joint->springImpulse + joint->lowerImpulse - joint->upperImpulse; linearImpulse = sqrtf( perpImpulse * perpImpulse + axialImpulse * axialImpulse ); angularImpulse = b2AbsFloat( joint->motorImpulse ); } break; default: break; } *force = linearImpulse * invTimeStep; *torque = angularImpulse * invTimeStep; } static b2Vec2 b2GetJointConstraintForce( b2World* world, b2Joint* joint ) { b2JointSim* base = b2GetJointSim( world, joint ); switch ( joint->type ) { case b2_distanceJoint: return b2GetDistanceJointForce( world, base ); case b2_motorJoint: return b2GetMotorJointForce( world, base ); case b2_filterJoint: return b2Vec2_zero; case b2_prismaticJoint: return b2GetPrismaticJointForce( world, base ); case b2_revoluteJoint: return b2GetRevoluteJointForce( world, base ); case b2_weldJoint: return b2GetWeldJointForce( world, base ); case b2_wheelJoint: return b2GetWheelJointForce( world, base ); default: B2_ASSERT( false ); return b2Vec2_zero; } } static float b2GetJointConstraintTorque( b2World* world, b2Joint* joint ) { b2JointSim* base = b2GetJointSim( world, joint ); switch ( joint->type ) { case b2_distanceJoint: return 0.0f; case b2_motorJoint: return b2GetMotorJointTorque( world, base ); case b2_filterJoint: return 0.0f; case b2_prismaticJoint: return b2GetPrismaticJointTorque( world, base ); case b2_revoluteJoint: return b2GetRevoluteJointTorque( world, base ); case b2_weldJoint: return b2GetWeldJointTorque( world, base ); case b2_wheelJoint: return b2GetWheelJointTorque( world, base ); default: B2_ASSERT( false ); return 0.0f; } } b2Vec2 b2Joint_GetConstraintForce( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); return b2GetJointConstraintForce( world, joint ); } float b2Joint_GetConstraintTorque( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); return b2GetJointConstraintTorque( world, joint ); } float b2Joint_GetLinearSeparation( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); b2JointSim* base = b2GetJointSim( world, joint ); b2Transform xfA = b2GetBodyTransform( world, joint->edges[0].bodyId ); b2Transform xfB = b2GetBodyTransform( world, joint->edges[1].bodyId ); b2Vec2 pA = b2TransformPoint( xfA, base->localFrameA.p ); b2Vec2 pB = b2TransformPoint( xfB, base->localFrameB.p ); b2Vec2 dp = b2Sub( pB, pA ); switch ( joint->type ) { case b2_distanceJoint: { b2DistanceJoint* distanceJoint = &base->distanceJoint; float length = b2Length( dp ); if ( distanceJoint->enableSpring ) { if ( distanceJoint->enableLimit ) { if ( length < distanceJoint->minLength ) { return distanceJoint->minLength - length; } if ( length > distanceJoint->maxLength ) { return length - distanceJoint->maxLength; } return 0.0f; } return 0.0f; } return b2AbsFloat( length - distanceJoint->length ); } case b2_motorJoint: return 0.0f; case b2_filterJoint: return 0.0f; case b2_prismaticJoint: { b2PrismaticJoint* prismaticJoint = &base->prismaticJoint; b2Vec2 axisA = b2RotateVector( xfA.q, (b2Vec2){ 1.0f, 0.0f } ); b2Vec2 perpA = b2LeftPerp( axisA ); float perpendicularSeparation = b2AbsFloat( b2Dot( perpA, dp ) ); float limitSeparation = 0.0f; if ( prismaticJoint->enableLimit ) { float translation = b2Dot( axisA, dp ); if ( translation < prismaticJoint->lowerTranslation ) { limitSeparation = prismaticJoint->lowerTranslation - translation; } if ( prismaticJoint->upperTranslation < translation ) { limitSeparation = translation - prismaticJoint->upperTranslation; } } return sqrtf( perpendicularSeparation * perpendicularSeparation + limitSeparation * limitSeparation ); } case b2_revoluteJoint: return b2Length( dp ); case b2_weldJoint: { b2WeldJoint* weldJoint = &base->weldJoint; if ( weldJoint->linearHertz == 0.0f ) { return b2Length( dp ); } return 0.0f; } case b2_wheelJoint: { b2WheelJoint* wheelJoint = &base->wheelJoint; b2Vec2 axisA = b2RotateVector( xfA.q, (b2Vec2){ 1.0f, 0.0f } ); b2Vec2 perpA = b2LeftPerp( axisA ); float perpendicularSeparation = b2AbsFloat( b2Dot( perpA, dp ) ); float limitSeparation = 0.0f; if ( wheelJoint->enableLimit ) { float translation = b2Dot( axisA, dp ); if ( translation < wheelJoint->lowerTranslation ) { limitSeparation = wheelJoint->lowerTranslation - translation; } if ( wheelJoint->upperTranslation < translation ) { limitSeparation = translation - wheelJoint->upperTranslation; } } return sqrtf( perpendicularSeparation * perpendicularSeparation + limitSeparation * limitSeparation ); } default: B2_ASSERT( false ); return 0.0f; } } float b2Joint_GetAngularSeparation( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); b2JointSim* base = b2GetJointSim( world, joint ); b2Transform xfA = b2GetBodyTransform( world, joint->edges[0].bodyId ); b2Transform xfB = b2GetBodyTransform( world, joint->edges[1].bodyId ); float relativeAngle = b2RelativeAngle( xfA.q, xfB.q ); switch ( joint->type ) { case b2_distanceJoint: return 0.0f; case b2_motorJoint: return 0.0f; case b2_filterJoint: return 0.0f; case b2_prismaticJoint: { return relativeAngle; } case b2_revoluteJoint: { b2RevoluteJoint* revoluteJoint = &base->revoluteJoint; if ( revoluteJoint->enableLimit ) { float angle = relativeAngle; if ( angle < revoluteJoint->lowerAngle ) { return revoluteJoint->lowerAngle - angle; } if ( revoluteJoint->upperAngle < angle ) { return angle - revoluteJoint->upperAngle; } } return 0.0f; } case b2_weldJoint: { b2WeldJoint* weldJoint = &base->weldJoint; if ( weldJoint->angularHertz == 0.0f ) { return relativeAngle; } return 0.0f; } case b2_wheelJoint: return 0.0f; default: B2_ASSERT( false ); return 0.0f; } } void b2Joint_SetConstraintTuning( b2JointId jointId, float hertz, float dampingRatio ) { B2_ASSERT( b2IsValidFloat( hertz ) && hertz >= 0.0f ); B2_ASSERT( b2IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f ); b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); b2JointSim* base = b2GetJointSim( world, joint ); base->constraintHertz = hertz; base->constraintDampingRatio = dampingRatio; } void b2Joint_GetConstraintTuning( b2JointId jointId, float* hertz, float* dampingRatio ) { b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); b2JointSim* base = b2GetJointSim( world, joint ); *hertz = base->constraintHertz; *dampingRatio = base->constraintDampingRatio; } void b2Joint_SetForceThreshold( b2JointId jointId, float threshold ) { B2_ASSERT( b2IsValidFloat( threshold ) && threshold >= 0.0f ); b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); b2JointSim* base = b2GetJointSim( world, joint ); base->forceThreshold = threshold; } float b2Joint_GetForceThreshold( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); b2JointSim* base = b2GetJointSim( world, joint ); return base->forceThreshold; } void b2Joint_SetTorqueThreshold( b2JointId jointId, float threshold ) { B2_ASSERT( b2IsValidFloat( threshold ) && threshold >= 0.0f ); b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); b2JointSim* base = b2GetJointSim( world, joint ); base->torqueThreshold = threshold; } float b2Joint_GetTorqueThreshold( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); b2JointSim* base = b2GetJointSim( world, joint ); return base->torqueThreshold; } void b2PrepareJoint( b2JointSim* joint, b2StepContext* context ) { // Clamp joint hertz based on the time step to reduce jitter. float hertz = b2MinFloat( joint->constraintHertz, 0.25f * context->inv_h ); joint->constraintSoftness = b2MakeSoft( hertz, joint->constraintDampingRatio, context->h ); switch ( joint->type ) { case b2_distanceJoint: b2PrepareDistanceJoint( joint, context ); break; case b2_motorJoint: b2PrepareMotorJoint( joint, context ); break; case b2_filterJoint: break; case b2_prismaticJoint: b2PreparePrismaticJoint( joint, context ); break; case b2_revoluteJoint: b2PrepareRevoluteJoint( joint, context ); break; case b2_weldJoint: b2PrepareWeldJoint( joint, context ); break; case b2_wheelJoint: b2PrepareWheelJoint( joint, context ); break; default: B2_ASSERT( false ); } } void b2WarmStartJoint( b2JointSim* joint, b2StepContext* context ) { switch ( joint->type ) { case b2_distanceJoint: b2WarmStartDistanceJoint( joint, context ); break; case b2_motorJoint: b2WarmStartMotorJoint( joint, context ); break; case b2_filterJoint: break; case b2_prismaticJoint: b2WarmStartPrismaticJoint( joint, context ); break; case b2_revoluteJoint: b2WarmStartRevoluteJoint( joint, context ); break; case b2_weldJoint: b2WarmStartWeldJoint( joint, context ); break; case b2_wheelJoint: b2WarmStartWheelJoint( joint, context ); break; default: B2_ASSERT( false ); } } void b2SolveJoint( b2JointSim* joint, b2StepContext* context, bool useBias ) { switch ( joint->type ) { case b2_distanceJoint: b2SolveDistanceJoint( joint, context, useBias ); break; case b2_motorJoint: b2SolveMotorJoint( joint, context ); break; case b2_filterJoint: break; case b2_prismaticJoint: b2SolvePrismaticJoint( joint, context, useBias ); break; case b2_revoluteJoint: b2SolveRevoluteJoint( joint, context, useBias ); break; case b2_weldJoint: b2SolveWeldJoint( joint, context, useBias ); break; case b2_wheelJoint: b2SolveWheelJoint( joint, context, useBias ); break; default: B2_ASSERT( false ); } } void b2PrepareOverflowJoints( b2StepContext* context ) { b2TracyCZoneNC( prepare_joints, "PrepJoints", b2_colorOldLace, true ); b2ConstraintGraph* graph = context->graph; b2JointSim* joints = graph->colors[B2_OVERFLOW_INDEX].jointSims.data; int jointCount = graph->colors[B2_OVERFLOW_INDEX].jointSims.count; for ( int i = 0; i < jointCount; ++i ) { b2JointSim* joint = joints + i; b2PrepareJoint( joint, context ); } b2TracyCZoneEnd( prepare_joints ); } void b2WarmStartOverflowJoints( b2StepContext* context ) { b2TracyCZoneNC( prepare_joints, "PrepJoints", b2_colorOldLace, true ); b2ConstraintGraph* graph = context->graph; b2JointSim* joints = graph->colors[B2_OVERFLOW_INDEX].jointSims.data; int jointCount = graph->colors[B2_OVERFLOW_INDEX].jointSims.count; for ( int i = 0; i < jointCount; ++i ) { b2JointSim* joint = joints + i; b2WarmStartJoint( joint, context ); } b2TracyCZoneEnd( prepare_joints ); } void b2SolveOverflowJoints( b2StepContext* context, bool useBias ) { b2TracyCZoneNC( solve_joints, "SolveJoints", b2_colorLemonChiffon, true ); b2ConstraintGraph* graph = context->graph; b2JointSim* joints = graph->colors[B2_OVERFLOW_INDEX].jointSims.data; int jointCount = graph->colors[B2_OVERFLOW_INDEX].jointSims.count; for ( int i = 0; i < jointCount; ++i ) { b2JointSim* joint = joints + i; b2SolveJoint( joint, context, useBias ); } b2TracyCZoneEnd( solve_joints ); } void b2DrawJoint( b2DebugDraw* draw, b2World* world, b2Joint* joint ) { b2Body* bodyA = b2BodyArray_Get( &world->bodies, joint->edges[0].bodyId ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, joint->edges[1].bodyId ); if ( bodyA->setIndex == b2_disabledSet || bodyB->setIndex == b2_disabledSet ) { return; } b2JointSim* jointSim = b2GetJointSim( world, joint ); b2Transform transformA = b2GetBodyTransformQuick( world, bodyA ); b2Transform transformB = b2GetBodyTransformQuick( world, bodyB ); b2Vec2 pA = b2TransformPoint( transformA, jointSim->localFrameA.p ); b2Vec2 pB = b2TransformPoint( transformB, jointSim->localFrameB.p ); b2HexColor color = b2_colorDarkSeaGreen; float scale = b2MaxFloat( 0.0001f, draw->jointScale * joint->drawScale ); switch ( joint->type ) { case b2_distanceJoint: b2DrawDistanceJoint( draw, jointSim, transformA, transformB ); break; case b2_filterJoint: draw->DrawLineFcn( pA, pB, b2_colorGold, draw->context ); break; case b2_motorJoint: draw->DrawPointFcn( pA, 8.0f, b2_colorYellowGreen, draw->context ); draw->DrawPointFcn( pB, 8.0f, b2_colorPlum, draw->context ); draw->DrawLineFcn( pA, pB, b2_colorLightGray, draw->context ); break; case b2_prismaticJoint: b2DrawPrismaticJoint( draw, jointSim, transformA, transformB, scale ); break; case b2_revoluteJoint: b2DrawRevoluteJoint( draw, jointSim, transformA, transformB, scale ); break; case b2_weldJoint: b2DrawWeldJoint( draw, jointSim, transformA, transformB, scale ); break; case b2_wheelJoint: b2DrawWheelJoint( draw, jointSim, transformA, transformB, scale ); break; default: draw->DrawLineFcn( transformA.p, pA, color, draw->context ); draw->DrawLineFcn( pA, pB, color, draw->context ); draw->DrawLineFcn( transformB.p, pB, color, draw->context ); break; } if ( draw->drawGraphColors ) { int colorIndex = joint->colorIndex; if ( colorIndex != B2_NULL_INDEX ) { b2Vec2 p = b2Lerp( pA, pB, 0.5f ); draw->DrawPointFcn( p, 5.0f, b2_graphColors[colorIndex], draw->context ); } } if ( draw->drawJointExtras ) { b2Vec2 force = b2GetJointConstraintForce( world, joint ); float torque = b2GetJointConstraintTorque( world, joint ); b2Vec2 p = b2Lerp( pA, pB, 0.5f ); draw->DrawLineFcn( p, b2MulAdd( p, 0.001f, force ), b2_colorAzure, draw->context ); char buffer[64]; snprintf( buffer, 64, "f = [%g, %g], t = %g", force.x, force.y, torque ); draw->DrawStringFcn( p, buffer, b2_colorAzure, draw->context ); } } ================================================ FILE: src/joint.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "array.h" #include "solver.h" #include "box2d/types.h" typedef struct b2DebugDraw b2DebugDraw; typedef struct b2StepContext b2StepContext; typedef struct b2World b2World; /// A joint edge is used to connect bodies and joints together /// in a joint graph where each body is a node and each joint /// is an edge. A joint edge belongs to a doubly linked list /// maintained in each attached body. Each joint has two joint /// nodes, one for each attached body. typedef struct b2JointEdge { int bodyId; int prevKey; int nextKey; } b2JointEdge; // Map from b2JointId to b2Joint in the solver sets typedef struct b2Joint { void* userData; // index of simulation set stored in b2World // B2_NULL_INDEX when slot is free int setIndex; // index into the constraint graph color array, may be B2_NULL_INDEX for sleeping/disabled joints // B2_NULL_INDEX when slot is free int colorIndex; // joint index within set or graph color // B2_NULL_INDEX when slot is free int localIndex; b2JointEdge edges[2]; int jointId; int islandId; int islandPrev; int islandNext; float drawScale; b2JointType type; // This is monotonically advanced when a body is allocated in this slot // Used to check for invalid b2JointId uint16_t generation; bool collideConnected; } b2Joint; typedef struct b2DistanceJoint { float length; float hertz; float dampingRatio; float lowerSpringForce; float upperSpringForce; float minLength; float maxLength; float maxMotorForce; float motorSpeed; float impulse; float lowerImpulse; float upperImpulse; float motorImpulse; int indexA; int indexB; b2Vec2 anchorA; b2Vec2 anchorB; b2Vec2 deltaCenter; b2Softness distanceSoftness; float axialMass; bool enableSpring; bool enableLimit; bool enableMotor; } b2DistanceJoint; typedef struct b2MotorJoint { b2Vec2 linearVelocity; float maxVelocityForce; float angularVelocity; float maxVelocityTorque; float linearHertz; float linearDampingRatio; float maxSpringForce; float angularHertz; float angularDampingRatio; float maxSpringTorque; b2Vec2 linearVelocityImpulse; float angularVelocityImpulse; b2Vec2 linearSpringImpulse; float angularSpringImpulse; b2Softness linearSpring; b2Softness angularSpring; int indexA; int indexB; b2Transform frameA; b2Transform frameB; b2Vec2 deltaCenter; b2Mat22 linearMass; float angularMass; } b2MotorJoint; typedef struct b2PrismaticJoint { b2Vec2 impulse; float springImpulse; float motorImpulse; float lowerImpulse; float upperImpulse; float hertz; float dampingRatio; float targetTranslation; float maxMotorForce; float motorSpeed; float lowerTranslation; float upperTranslation; int indexA; int indexB; b2Transform frameA; b2Transform frameB; b2Vec2 deltaCenter; b2Softness springSoftness; bool enableSpring; bool enableLimit; bool enableMotor; } b2PrismaticJoint; typedef struct b2RevoluteJoint { b2Vec2 linearImpulse; float springImpulse; float motorImpulse; float lowerImpulse; float upperImpulse; float hertz; float dampingRatio; float targetAngle; float maxMotorTorque; float motorSpeed; float lowerAngle; float upperAngle; int indexA; int indexB; b2Transform frameA; b2Transform frameB; b2Vec2 deltaCenter; float axialMass; b2Softness springSoftness; bool enableSpring; bool enableMotor; bool enableLimit; } b2RevoluteJoint; typedef struct b2WeldJoint { float linearHertz; float linearDampingRatio; float angularHertz; float angularDampingRatio; b2Softness linearSpring; b2Softness angularSpring; b2Vec2 linearImpulse; float angularImpulse; int indexA; int indexB; b2Transform frameA; b2Transform frameB; b2Vec2 deltaCenter; float axialMass; } b2WeldJoint; typedef struct b2WheelJoint { float perpImpulse; float motorImpulse; float springImpulse; float lowerImpulse; float upperImpulse; float maxMotorTorque; float motorSpeed; float lowerTranslation; float upperTranslation; float hertz; float dampingRatio; int indexA; int indexB; b2Transform frameA; b2Transform frameB; b2Vec2 deltaCenter; float perpMass; float motorMass; float axialMass; b2Softness springSoftness; bool enableSpring; bool enableMotor; bool enableLimit; } b2WheelJoint; /// The base joint class. Joints are used to constraint two bodies together in /// various fashions. Some joints also feature limits and motors. typedef struct b2JointSim { int jointId; int bodyIdA; int bodyIdB; b2JointType type; b2Transform localFrameA; b2Transform localFrameB; float invMassA, invMassB; float invIA, invIB; float constraintHertz; float constraintDampingRatio; b2Softness constraintSoftness; float forceThreshold; float torqueThreshold; union { b2DistanceJoint distanceJoint; b2MotorJoint motorJoint; b2RevoluteJoint revoluteJoint; b2PrismaticJoint prismaticJoint; b2WeldJoint weldJoint; b2WheelJoint wheelJoint; }; } b2JointSim; void b2DestroyJointInternal( b2World* world, b2Joint* joint, bool wakeBodies ); b2Joint* b2GetJointFullId( b2World* world, b2JointId jointId ); b2JointSim* b2GetJointSim( b2World* world, b2Joint* joint ); b2JointSim* b2GetJointSimCheckType( b2JointId jointId, b2JointType type ); void b2PrepareJoint( b2JointSim* joint, b2StepContext* context ); void b2WarmStartJoint( b2JointSim* joint, b2StepContext* context ); void b2SolveJoint( b2JointSim* joint, b2StepContext* context, bool useBias ); void b2PrepareOverflowJoints( b2StepContext* context ); void b2WarmStartOverflowJoints( b2StepContext* context ); void b2SolveOverflowJoints( b2StepContext* context, bool useBias ); void b2GetJointReaction( b2JointSim* sim, float invTimeStep, float* force, float* torque ); void b2DrawJoint( b2DebugDraw* draw, b2World* world, b2Joint* joint ); b2Vec2 b2GetDistanceJointForce( b2World* world, b2JointSim* base ); b2Vec2 b2GetMotorJointForce( b2World* world, b2JointSim* base ); b2Vec2 b2GetPrismaticJointForce( b2World* world, b2JointSim* base ); b2Vec2 b2GetRevoluteJointForce( b2World* world, b2JointSim* base ); b2Vec2 b2GetWeldJointForce( b2World* world, b2JointSim* base ); b2Vec2 b2GetWheelJointForce( b2World* world, b2JointSim* base ); float b2GetMotorJointTorque( b2World* world, b2JointSim* base ); float b2GetPrismaticJointTorque( b2World* world, b2JointSim* base ); float b2GetRevoluteJointTorque( b2World* world, b2JointSim* base ); float b2GetWeldJointTorque( b2World* world, b2JointSim* base ); float b2GetWheelJointTorque( b2World* world, b2JointSim* base ); void b2PrepareDistanceJoint( b2JointSim* base, b2StepContext* context ); void b2PrepareMotorJoint( b2JointSim* base, b2StepContext* context ); void b2PreparePrismaticJoint( b2JointSim* base, b2StepContext* context ); void b2PrepareRevoluteJoint( b2JointSim* base, b2StepContext* context ); void b2PrepareWeldJoint( b2JointSim* base, b2StepContext* context ); void b2PrepareWheelJoint( b2JointSim* base, b2StepContext* context ); void b2WarmStartDistanceJoint( b2JointSim* base, b2StepContext* context ); void b2WarmStartMotorJoint( b2JointSim* base, b2StepContext* context ); void b2WarmStartPrismaticJoint( b2JointSim* base, b2StepContext* context ); void b2WarmStartRevoluteJoint( b2JointSim* base, b2StepContext* context ); void b2WarmStartWeldJoint( b2JointSim* base, b2StepContext* context ); void b2WarmStartWheelJoint( b2JointSim* base, b2StepContext* context ); void b2SolveDistanceJoint( b2JointSim* base, b2StepContext* context, bool useBias ); void b2SolveMotorJoint( b2JointSim* base, b2StepContext* context ); void b2SolvePrismaticJoint( b2JointSim* base, b2StepContext* context, bool useBias ); void b2SolveRevoluteJoint( b2JointSim* base, b2StepContext* context, bool useBias ); void b2SolveWeldJoint( b2JointSim* base, b2StepContext* context, bool useBias ); void b2SolveWheelJoint( b2JointSim* base, b2StepContext* context, bool useBias ); void b2DrawDistanceJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB ); void b2DrawPrismaticJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB, float drawScale ); void b2DrawRevoluteJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB, float drawScale ); void b2DrawWeldJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB, float drawScale ); void b2DrawWheelJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB, float drawScale ); // Define inline functions for arrays B2_ARRAY_INLINE( b2Joint, b2Joint ) B2_ARRAY_INLINE( b2JointSim, b2JointSim ) ================================================ FILE: src/manifold.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "constants.h" #include "core.h" #include "box2d/collision.h" #include "box2d/math_functions.h" #include #include #include #define B2_MAKE_ID( A, B ) ( (uint8_t)( A ) << 8 | (uint8_t)( B ) ) static b2Polygon b2MakeCapsule( b2Vec2 p1, b2Vec2 p2, float radius ) { b2Polygon shape = { 0 }; shape.vertices[0] = p1; shape.vertices[1] = p2; shape.centroid = b2Lerp( p1, p2, 0.5f ); b2Vec2 d = b2Sub( p2, p1 ); B2_ASSERT( b2LengthSquared( d ) > FLT_EPSILON ); b2Vec2 axis = b2Normalize( d ); b2Vec2 normal = b2RightPerp( axis ); shape.normals[0] = normal; shape.normals[1] = b2Neg( normal ); shape.count = 2; shape.radius = radius; return shape; } // point = qA * localAnchorA + pA // localAnchorB = qBc * (point - pB) // anchorB = point - pB = qA * localAnchorA + pA - pB // = anchorA + (pA - pB) b2Manifold b2CollideCircles( const b2Circle* circleA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB ) { b2Manifold manifold = { 0 }; b2Transform xf = b2InvMulTransforms( xfA, xfB ); b2Vec2 pointA = circleA->center; b2Vec2 pointB = b2TransformPoint( xf, circleB->center ); float distance; b2Vec2 normal = b2GetLengthAndNormalize( &distance, b2Sub( pointB, pointA ) ); float radiusA = circleA->radius; float radiusB = circleB->radius; float separation = distance - radiusA - radiusB; if ( separation > B2_SPECULATIVE_DISTANCE ) { return manifold; } b2Vec2 cA = b2MulAdd( pointA, radiusA, normal ); b2Vec2 cB = b2MulAdd( pointB, -radiusB, normal ); b2Vec2 contactPointA = b2Lerp( cA, cB, 0.5f ); manifold.normal = b2RotateVector( xfA.q, normal ); b2ManifoldPoint* mp = manifold.points + 0; mp->anchorA = b2RotateVector( xfA.q, contactPointA ); mp->anchorB = b2Add( mp->anchorA, b2Sub( xfA.p, xfB.p ) ); mp->point = b2Add( mp->anchorA, xfA.p ); mp->separation = separation; mp->id = 0; manifold.pointCount = 1; return manifold; } /// Compute the collision manifold between a capsule and circle b2Manifold b2CollideCapsuleAndCircle( const b2Capsule* capsuleA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB ) { b2Manifold manifold = { 0 }; b2Transform xf = b2InvMulTransforms( xfA, xfB ); // Compute circle position in the frame of the capsule. b2Vec2 pB = b2TransformPoint( xf, circleB->center ); // Compute closest point b2Vec2 p1 = capsuleA->center1; b2Vec2 p2 = capsuleA->center2; b2Vec2 e = b2Sub( p2, p1 ); // dot(p - pA, e) = 0 // dot(p - (p1 + s1 * e), e) = 0 // s1 = dot(p - p1, e) b2Vec2 pA; float s1 = b2Dot( b2Sub( pB, p1 ), e ); float s2 = b2Dot( b2Sub( p2, pB ), e ); if ( s1 < 0.0f ) { // p1 region pA = p1; } else if ( s2 < 0.0f ) { // p2 region pA = p2; } else { // circle colliding with segment interior float s = s1 / b2Dot( e, e ); pA = b2MulAdd( p1, s, e ); } float distance; b2Vec2 normal = b2GetLengthAndNormalize( &distance, b2Sub( pB, pA ) ); float radiusA = capsuleA->radius; float radiusB = circleB->radius; float separation = distance - radiusA - radiusB; if ( separation > B2_SPECULATIVE_DISTANCE ) { return manifold; } b2Vec2 cA = b2MulAdd( pA, radiusA, normal ); b2Vec2 cB = b2MulAdd( pB, -radiusB, normal ); b2Vec2 contactPointA = b2Lerp( cA, cB, 0.5f ); manifold.normal = b2RotateVector( xfA.q, normal ); b2ManifoldPoint* mp = manifold.points + 0; mp->anchorA = b2RotateVector( xfA.q, contactPointA ); mp->anchorB = b2Add( mp->anchorA, b2Sub( xfA.p, xfB.p ) ); mp->point = b2Add( xfA.p, mp->anchorA ); mp->separation = separation; mp->id = 0; manifold.pointCount = 1; return manifold; } b2Manifold b2CollidePolygonAndCircle( const b2Polygon* polygonA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB ) { b2Manifold manifold = { 0 }; const float speculativeDistance = B2_SPECULATIVE_DISTANCE; b2Transform xf = b2InvMulTransforms( xfA, xfB ); // Compute circle position in the frame of the polygon. b2Vec2 center = b2TransformPoint( xf, circleB->center ); float radiusA = polygonA->radius; float radiusB = circleB->radius; float radius = radiusA + radiusB; // Find the min separating edge. int normalIndex = 0; float separation = -FLT_MAX; int vertexCount = polygonA->count; const b2Vec2* vertices = polygonA->vertices; const b2Vec2* normals = polygonA->normals; for ( int i = 0; i < vertexCount; ++i ) { float s = b2Dot( normals[i], b2Sub( center, vertices[i] ) ); if ( s > separation ) { separation = s; normalIndex = i; } } if ( separation > radius + speculativeDistance ) { return manifold; } // Vertices of the reference edge. int vertIndex1 = normalIndex; int vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; b2Vec2 v1 = vertices[vertIndex1]; b2Vec2 v2 = vertices[vertIndex2]; // Compute barycentric coordinates float u1 = b2Dot( b2Sub( center, v1 ), b2Sub( v2, v1 ) ); float u2 = b2Dot( b2Sub( center, v2 ), b2Sub( v1, v2 ) ); if ( u1 < 0.0f && separation > FLT_EPSILON ) { // Circle center is closest to v1 and safely outside the polygon b2Vec2 normal = b2Normalize( b2Sub( center, v1 ) ); separation = b2Dot( b2Sub( center, v1 ), normal ); if ( separation > radius + speculativeDistance ) { return manifold; } b2Vec2 cA = b2MulAdd( v1, radiusA, normal ); b2Vec2 cB = b2MulSub( center, radiusB, normal ); b2Vec2 contactPointA = b2Lerp( cA, cB, 0.5f ); manifold.normal = b2RotateVector( xfA.q, normal ); b2ManifoldPoint* mp = manifold.points + 0; mp->anchorA = b2RotateVector( xfA.q, contactPointA ); mp->anchorB = b2Add( mp->anchorA, b2Sub( xfA.p, xfB.p ) ); mp->point = b2Add( xfA.p, mp->anchorA ); mp->separation = b2Dot( b2Sub( cB, cA ), normal ); mp->id = 0; manifold.pointCount = 1; } else if ( u2 < 0.0f && separation > FLT_EPSILON ) { // Circle center is closest to v2 and safely outside the polygon b2Vec2 normal = b2Normalize( b2Sub( center, v2 ) ); separation = b2Dot( b2Sub( center, v2 ), normal ); if ( separation > radius + speculativeDistance ) { return manifold; } b2Vec2 cA = b2MulAdd( v2, radiusA, normal ); b2Vec2 cB = b2MulSub( center, radiusB, normal ); b2Vec2 contactPointA = b2Lerp( cA, cB, 0.5f ); manifold.normal = b2RotateVector( xfA.q, normal ); b2ManifoldPoint* mp = manifold.points + 0; mp->anchorA = b2RotateVector( xfA.q, contactPointA ); mp->anchorB = b2Add( mp->anchorA, b2Sub( xfA.p, xfB.p ) ); mp->point = b2Add( xfA.p, mp->anchorA ); mp->separation = b2Dot( b2Sub( cB, cA ), normal ); mp->id = 0; manifold.pointCount = 1; } else { // Circle center is between v1 and v2. Center may be inside polygon b2Vec2 normal = normals[normalIndex]; manifold.normal = b2RotateVector( xfA.q, normal ); // cA is the projection of the circle center onto to the reference edge b2Vec2 cA = b2MulAdd( center, radiusA - b2Dot( b2Sub( center, v1 ), normal ), normal ); // cB is the deepest point on the circle with respect to the reference edge b2Vec2 cB = b2MulSub( center, radiusB, normal ); b2Vec2 contactPointA = b2Lerp( cA, cB, 0.5f ); // The contact point is the midpoint in world space b2ManifoldPoint* mp = manifold.points + 0; mp->anchorA = b2RotateVector( xfA.q, contactPointA ); mp->anchorB = b2Add( mp->anchorA, b2Sub( xfA.p, xfB.p ) ); mp->point = b2Add( xfA.p, mp->anchorA ); mp->separation = separation - radius; mp->id = 0; manifold.pointCount = 1; } return manifold; } // Follows Ericson 5.1.9 Closest Points of Two Line Segments // Adds some logic to support clipping to get two contact points b2Manifold b2CollideCapsules( const b2Capsule* capsuleA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB ) { b2Vec2 origin = capsuleA->center1; // Shift polyA to origin // pw = q * pb + p // pw = q * (pbs + origin) + p // pw = q * pbs + (p + q * origin) b2Transform sfA = { b2Add( xfA.p, b2RotateVector( xfA.q, origin ) ), xfA.q }; b2Transform xf = b2InvMulTransforms( sfA, xfB ); b2Vec2 p1 = b2Vec2_zero; b2Vec2 q1 = b2Sub( capsuleA->center2, origin ); b2Vec2 p2 = b2TransformPoint( xf, capsuleB->center1 ); b2Vec2 q2 = b2TransformPoint( xf, capsuleB->center2 ); b2Vec2 d1 = b2Sub( q1, p1 ); b2Vec2 d2 = b2Sub( q2, p2 ); float dd1 = b2Dot( d1, d1 ); float dd2 = b2Dot( d2, d2 ); const float epsSqr = FLT_EPSILON * FLT_EPSILON; B2_ASSERT( dd1 > epsSqr && dd2 > epsSqr ); b2Vec2 r = b2Sub( p1, p2 ); float rd1 = b2Dot( r, d1 ); float rd2 = b2Dot( r, d2 ); float d12 = b2Dot( d1, d2 ); float denom = dd1 * dd2 - d12 * d12; // Fraction on segment 1 float f1 = 0.0f; if ( denom != 0.0f ) { // not parallel f1 = b2ClampFloat( ( d12 * rd2 - rd1 * dd2 ) / denom, 0.0f, 1.0f ); } // Compute point on segment 2 closest to p1 + f1 * d1 float f2 = ( d12 * f1 + rd2 ) / dd2; // Clamping of segment 2 requires a do over on segment 1 if ( f2 < 0.0f ) { f2 = 0.0f; f1 = b2ClampFloat( -rd1 / dd1, 0.0f, 1.0f ); } else if ( f2 > 1.0f ) { f2 = 1.0f; f1 = b2ClampFloat( ( d12 - rd1 ) / dd1, 0.0f, 1.0f ); } b2Vec2 closest1 = b2MulAdd( p1, f1, d1 ); b2Vec2 closest2 = b2MulAdd( p2, f2, d2 ); float distanceSquared = b2DistanceSquared( closest1, closest2 ); b2Manifold manifold = { 0 }; float radiusA = capsuleA->radius; float radiusB = capsuleB->radius; float radius = radiusA + radiusB; float maxDistance = radius + B2_SPECULATIVE_DISTANCE; if ( distanceSquared > maxDistance * maxDistance ) { return manifold; } float distance = sqrtf( distanceSquared ); float length1, length2; b2Vec2 u1 = b2GetLengthAndNormalize( &length1, d1 ); b2Vec2 u2 = b2GetLengthAndNormalize( &length2, d2 ); // Does segment B project outside segment A? float fp2 = b2Dot( b2Sub( p2, p1 ), u1 ); float fq2 = b2Dot( b2Sub( q2, p1 ), u1 ); bool outsideA = ( fp2 <= 0.0f && fq2 <= 0.0f ) || ( fp2 >= length1 && fq2 >= length1 ); // Does segment A project outside segment B? float fp1 = b2Dot( b2Sub( p1, p2 ), u2 ); float fq1 = b2Dot( b2Sub( q1, p2 ), u2 ); bool outsideB = ( fp1 <= 0.0f && fq1 <= 0.0f ) || ( fp1 >= length2 && fq1 >= length2 ); if ( outsideA == false && outsideB == false ) { // attempt to clip // this may yield contact points with excessive separation // in that case the algorithm falls back to single point collision // find reference edge using SAT b2Vec2 normalA; float separationA; { normalA = b2LeftPerp( u1 ); float ss1 = b2Dot( b2Sub( p2, p1 ), normalA ); float ss2 = b2Dot( b2Sub( q2, p1 ), normalA ); float s1p = ss1 < ss2 ? ss1 : ss2; float s1n = -ss1 < -ss2 ? -ss1 : -ss2; if ( s1p > s1n ) { separationA = s1p; } else { separationA = s1n; normalA = b2Neg( normalA ); } } b2Vec2 normalB; float separationB; { normalB = b2LeftPerp( u2 ); float ss1 = b2Dot( b2Sub( p1, p2 ), normalB ); float ss2 = b2Dot( b2Sub( q1, p2 ), normalB ); float s1p = ss1 < ss2 ? ss1 : ss2; float s1n = -ss1 < -ss2 ? -ss1 : -ss2; if ( s1p > s1n ) { separationB = s1p; } else { separationB = s1n; normalB = b2Neg( normalB ); } } // biased to avoid feature flip-flop // todo more testing? if ( separationA + 0.1f * B2_LINEAR_SLOP >= separationB ) { manifold.normal = normalA; b2Vec2 cp = p2; b2Vec2 cq = q2; // clip to p1 if ( fp2 < 0.0f && fq2 > 0.0f ) { cp = b2Lerp( p2, q2, ( 0.0f - fp2 ) / ( fq2 - fp2 ) ); } else if ( fq2 < 0.0f && fp2 > 0.0f ) { cq = b2Lerp( q2, p2, ( 0.0f - fq2 ) / ( fp2 - fq2 ) ); } // clip to q1 if ( fp2 > length1 && fq2 < length1 ) { cp = b2Lerp( p2, q2, ( fp2 - length1 ) / ( fp2 - fq2 ) ); } else if ( fq2 > length1 && fp2 < length1 ) { cq = b2Lerp( q2, p2, ( fq2 - length1 ) / ( fq2 - fp2 ) ); } float sp = b2Dot( b2Sub( cp, p1 ), normalA ); float sq = b2Dot( b2Sub( cq, p1 ), normalA ); if ( sp <= distance + B2_LINEAR_SLOP || sq <= distance + B2_LINEAR_SLOP ) { b2ManifoldPoint* mp; mp = manifold.points + 0; mp->anchorA = b2MulAdd( cp, 0.5f * ( radiusA - radiusB - sp ), normalA ); mp->separation = sp - radius; mp->id = B2_MAKE_ID( 0, 0 ); mp = manifold.points + 1; mp->anchorA = b2MulAdd( cq, 0.5f * ( radiusA - radiusB - sq ), normalA ); mp->separation = sq - radius; mp->id = B2_MAKE_ID( 0, 1 ); manifold.pointCount = 2; } } else { // normal always points from A to B manifold.normal = b2Neg( normalB ); b2Vec2 cp = p1; b2Vec2 cq = q1; // clip to p2 if ( fp1 < 0.0f && fq1 > 0.0f ) { cp = b2Lerp( p1, q1, ( 0.0f - fp1 ) / ( fq1 - fp1 ) ); } else if ( fq1 < 0.0f && fp1 > 0.0f ) { cq = b2Lerp( q1, p1, ( 0.0f - fq1 ) / ( fp1 - fq1 ) ); } // clip to q2 if ( fp1 > length2 && fq1 < length2 ) { cp = b2Lerp( p1, q1, ( fp1 - length2 ) / ( fp1 - fq1 ) ); } else if ( fq1 > length2 && fp1 < length2 ) { cq = b2Lerp( q1, p1, ( fq1 - length2 ) / ( fq1 - fp1 ) ); } float sp = b2Dot( b2Sub( cp, p2 ), normalB ); float sq = b2Dot( b2Sub( cq, p2 ), normalB ); if ( sp <= distance + B2_LINEAR_SLOP || sq <= distance + B2_LINEAR_SLOP ) { b2ManifoldPoint* mp; mp = manifold.points + 0; mp->anchorA = b2MulAdd( cp, 0.5f * ( radiusB - radiusA - sp ), normalB ); mp->separation = sp - radius; mp->id = B2_MAKE_ID( 0, 0 ); mp = manifold.points + 1; mp->anchorA = b2MulAdd( cq, 0.5f * ( radiusB - radiusA - sq ), normalB ); mp->separation = sq - radius; mp->id = B2_MAKE_ID( 1, 0 ); manifold.pointCount = 2; } } } if ( manifold.pointCount == 0 ) { // single point collision b2Vec2 normal = b2Sub( closest2, closest1 ); if ( b2Dot( normal, normal ) > epsSqr ) { normal = b2Normalize( normal ); } else { normal = b2LeftPerp( u1 ); } b2Vec2 c1 = b2MulAdd( closest1, radiusA, normal ); b2Vec2 c2 = b2MulAdd( closest2, -radiusB, normal ); int i1 = f1 == 0.0f ? 0 : 1; int i2 = f2 == 0.0f ? 0 : 1; manifold.normal = normal; manifold.points[0].anchorA = b2Lerp( c1, c2, 0.5f ); manifold.points[0].separation = sqrtf( distanceSquared ) - radius; manifold.points[0].id = B2_MAKE_ID( i1, i2 ); manifold.pointCount = 1; } // Convert manifold to world space manifold.normal = b2RotateVector( xfA.q, manifold.normal ); for ( int i = 0; i < manifold.pointCount; ++i ) { b2ManifoldPoint* mp = manifold.points + i; // anchor points relative to shape origin in world space mp->anchorA = b2RotateVector( xfA.q, b2Add( mp->anchorA, origin ) ); mp->anchorB = b2Add( mp->anchorA, b2Sub( xfA.p, xfB.p ) ); mp->point = b2Add( xfA.p, mp->anchorA ); } return manifold; } b2Manifold b2CollideSegmentAndCapsule( const b2Segment* segmentA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB ) { b2Capsule capsuleA = { segmentA->point1, segmentA->point2, 0.0f }; return b2CollideCapsules( &capsuleA, xfA, capsuleB, xfB ); } b2Manifold b2CollidePolygonAndCapsule( const b2Polygon* polygonA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB ) { b2Polygon polyB = b2MakeCapsule( capsuleB->center1, capsuleB->center2, capsuleB->radius ); return b2CollidePolygons( polygonA, xfA, &polyB, xfB ); } // Polygon clipper used to compute contact points when there are potentially two contact points. static b2Manifold b2ClipPolygons( const b2Polygon* polyA, const b2Polygon* polyB, int edgeA, int edgeB, bool flip ) { b2Manifold manifold = { 0 }; // reference polygon const b2Polygon* poly1; int i11, i12; // incident polygon const b2Polygon* poly2; int i21, i22; if ( flip ) { poly1 = polyB; poly2 = polyA; i11 = edgeB; i12 = edgeB + 1 < polyB->count ? edgeB + 1 : 0; i21 = edgeA; i22 = edgeA + 1 < polyA->count ? edgeA + 1 : 0; } else { poly1 = polyA; poly2 = polyB; i11 = edgeA; i12 = edgeA + 1 < polyA->count ? edgeA + 1 : 0; i21 = edgeB; i22 = edgeB + 1 < polyB->count ? edgeB + 1 : 0; } b2Vec2 normal = poly1->normals[i11]; // Reference edge vertices b2Vec2 v11 = poly1->vertices[i11]; b2Vec2 v12 = poly1->vertices[i12]; // Incident edge vertices b2Vec2 v21 = poly2->vertices[i21]; b2Vec2 v22 = poly2->vertices[i22]; b2Vec2 tangent = b2CrossSV( 1.0f, normal ); float lower1 = 0.0f; float upper1 = b2Dot( b2Sub( v12, v11 ), tangent ); // Incident edge points opposite of tangent due to CCW winding float upper2 = b2Dot( b2Sub( v21, v11 ), tangent ); float lower2 = b2Dot( b2Sub( v22, v11 ), tangent ); // Are the segments disjoint? if ( upper2 < lower1 || upper1 < lower2 ) { return manifold; } b2Vec2 vLower; if ( lower2 < lower1 && upper2 - lower2 > FLT_EPSILON ) { vLower = b2Lerp( v22, v21, ( lower1 - lower2 ) / ( upper2 - lower2 ) ); } else { vLower = v22; } b2Vec2 vUpper; if ( upper2 > upper1 && upper2 - lower2 > FLT_EPSILON ) { vUpper = b2Lerp( v22, v21, ( upper1 - lower2 ) / ( upper2 - lower2 ) ); } else { vUpper = v21; } // todo vLower can be very close to vUpper, reduce to one point? float separationLower = b2Dot( b2Sub( vLower, v11 ), normal ); float separationUpper = b2Dot( b2Sub( vUpper, v11 ), normal ); float r1 = poly1->radius; float r2 = poly2->radius; // Put contact points at midpoint, accounting for radii vLower = b2MulAdd( vLower, 0.5f * ( r1 - r2 - separationLower ), normal ); vUpper = b2MulAdd( vUpper, 0.5f * ( r1 - r2 - separationUpper ), normal ); float radius = r1 + r2; if ( flip == false ) { manifold.normal = normal; b2ManifoldPoint* cp = manifold.points + 0; { cp->anchorA = vLower; cp->separation = separationLower - radius; cp->id = B2_MAKE_ID( i11, i22 ); manifold.pointCount += 1; cp += 1; } { cp->anchorA = vUpper; cp->separation = separationUpper - radius; cp->id = B2_MAKE_ID( i12, i21 ); manifold.pointCount += 1; } } else { manifold.normal = b2Neg( normal ); b2ManifoldPoint* cp = manifold.points + 0; { cp->anchorA = vUpper; cp->separation = separationUpper - radius; cp->id = B2_MAKE_ID( i21, i12 ); manifold.pointCount += 1; cp += 1; } { cp->anchorA = vLower; cp->separation = separationLower - radius; cp->id = B2_MAKE_ID( i22, i11 ); manifold.pointCount += 1; } } return manifold; } // Find the max separation between poly1 and poly2 using edge normals from poly1. static float b2FindMaxSeparation( int* edgeIndex, const b2Polygon* poly1, const b2Polygon* poly2 ) { int count1 = poly1->count; int count2 = poly2->count; const b2Vec2* n1s = poly1->normals; const b2Vec2* v1s = poly1->vertices; const b2Vec2* v2s = poly2->vertices; int bestIndex = 0; float maxSeparation = -FLT_MAX; for ( int i = 0; i < count1; ++i ) { // Get poly1 normal in frame2. b2Vec2 n = n1s[i]; b2Vec2 v1 = v1s[i]; // Find the deepest point for normal i. float si = FLT_MAX; for ( int j = 0; j < count2; ++j ) { float sij = b2Dot( n, b2Sub( v2s[j], v1 ) ); if ( sij < si ) { si = sij; } } if ( si > maxSeparation ) { maxSeparation = si; bestIndex = i; } } *edgeIndex = bestIndex; return maxSeparation; } // Due to speculation, every polygon is rounded // Algorithm: // // compute edge separation using the separating axis test (SAT) // if (separation > speculation_distance) // return // find reference and incident edge // if separation >= 0.1f * B2_LINEAR_SLOP // compute closest points between reference and incident edge // if vertices are closest // single vertex-vertex contact // else // clip edges // end // else // clip edges // end b2Manifold b2CollidePolygons( const b2Polygon* polygonA, b2Transform xfA, const b2Polygon* polygonB, b2Transform xfB ) { b2Vec2 origin = polygonA->vertices[0]; float linearSlop = B2_LINEAR_SLOP; float speculativeDistance = B2_SPECULATIVE_DISTANCE; // Shift polyA to origin // pw = q * pb + p // pw = q * (pbs + origin) + p // pw = q * pbs + (p + q * origin) b2Transform sfA = { b2Add( xfA.p, b2RotateVector( xfA.q, origin ) ), xfA.q }; b2Transform xf = b2InvMulTransforms( sfA, xfB ); b2Polygon localPolyA; localPolyA.count = polygonA->count; localPolyA.radius = polygonA->radius; localPolyA.vertices[0] = b2Vec2_zero; localPolyA.normals[0] = polygonA->normals[0]; for ( int i = 1; i < localPolyA.count; ++i ) { localPolyA.vertices[i] = b2Sub( polygonA->vertices[i], origin ); localPolyA.normals[i] = polygonA->normals[i]; } // Put polyB in polyA's frame to reduce round-off error b2Polygon localPolyB; localPolyB.count = polygonB->count; localPolyB.radius = polygonB->radius; for ( int i = 0; i < localPolyB.count; ++i ) { localPolyB.vertices[i] = b2TransformPoint( xf, polygonB->vertices[i] ); localPolyB.normals[i] = b2RotateVector( xf.q, polygonB->normals[i] ); } int edgeA = 0; float separationA = b2FindMaxSeparation( &edgeA, &localPolyA, &localPolyB ); int edgeB = 0; float separationB = b2FindMaxSeparation( &edgeB, &localPolyB, &localPolyA ); float radius = localPolyA.radius + localPolyB.radius; if ( separationA > speculativeDistance + radius || separationB > speculativeDistance + radius ) { return (b2Manifold){ 0 }; } // Find incident edge bool flip; if ( separationA >= separationB ) { flip = false; b2Vec2 searchDirection = localPolyA.normals[edgeA]; // Find the incident edge on polyB int count = localPolyB.count; const b2Vec2* normals = localPolyB.normals; edgeB = 0; float minDot = FLT_MAX; for ( int i = 0; i < count; ++i ) { float dot = b2Dot( searchDirection, normals[i] ); if ( dot < minDot ) { minDot = dot; edgeB = i; } } } else { flip = true; b2Vec2 searchDirection = localPolyB.normals[edgeB]; // Find the incident edge on polyA int count = localPolyA.count; const b2Vec2* normals = localPolyA.normals; edgeA = 0; float minDot = FLT_MAX; for ( int i = 0; i < count; ++i ) { float dot = b2Dot( searchDirection, normals[i] ); if ( dot < minDot ) { minDot = dot; edgeA = i; } } } b2Manifold manifold = { 0 }; // Using slop here to ensure vertex-vertex normal vectors can be safely normalized // todo this means edge clipping needs to handle slightly non-overlapping edges. if ( separationA > 0.1f * linearSlop || separationB > 0.1f * linearSlop ) { #if 1 // Edges are disjoint. Find closest points between reference edge and incident edge // Reference edge on polygon A int i11 = edgeA; int i12 = edgeA + 1 < localPolyA.count ? edgeA + 1 : 0; int i21 = edgeB; int i22 = edgeB + 1 < localPolyB.count ? edgeB + 1 : 0; b2Vec2 v11 = localPolyA.vertices[i11]; b2Vec2 v12 = localPolyA.vertices[i12]; b2Vec2 v21 = localPolyB.vertices[i21]; b2Vec2 v22 = localPolyB.vertices[i22]; b2SegmentDistanceResult result = b2SegmentDistance( v11, v12, v21, v22 ); B2_ASSERT( result.distanceSquared > 0.0f ); float distance = sqrtf( result.distanceSquared ); float separation = distance - radius; if ( distance - radius > speculativeDistance ) { // This can happen in the vertex-vertex case return manifold; } // Attempt to clip edges manifold = b2ClipPolygons( &localPolyA, &localPolyB, edgeA, edgeB, flip ); float minSeparation = FLT_MAX; for ( int i = 0; i < manifold.pointCount; ++i ) { minSeparation = b2MinFloat( minSeparation, manifold.points[i].separation ); } // Does vertex-vertex have substantially larger separation? if ( separation + 0.1f * linearSlop < minSeparation ) { if ( result.fraction1 == 0.0f && result.fraction2 == 0.0f ) { // v11 - v21 b2Vec2 normal = b2Sub( v21, v11 ); float invDistance = 1.0f / distance; normal.x *= invDistance; normal.y *= invDistance; b2Vec2 c1 = b2MulAdd( v11, localPolyA.radius, normal ); b2Vec2 c2 = b2MulAdd( v21, -localPolyB.radius, normal ); manifold.normal = normal; manifold.points[0].anchorA = b2Lerp( c1, c2, 0.5f ); manifold.points[0].separation = distance - radius; manifold.points[0].id = B2_MAKE_ID( i11, i21 ); manifold.pointCount = 1; } else if ( result.fraction1 == 0.0f && result.fraction2 == 1.0f ) { // v11 - v22 b2Vec2 normal = b2Sub( v22, v11 ); float invDistance = 1.0f / distance; normal.x *= invDistance; normal.y *= invDistance; b2Vec2 c1 = b2MulAdd( v11, localPolyA.radius, normal ); b2Vec2 c2 = b2MulAdd( v22, -localPolyB.radius, normal ); manifold.normal = normal; manifold.points[0].anchorA = b2Lerp( c1, c2, 0.5f ); manifold.points[0].separation = distance - radius; manifold.points[0].id = B2_MAKE_ID( i11, i22 ); manifold.pointCount = 1; } else if ( result.fraction1 == 1.0f && result.fraction2 == 0.0f ) { // v12 - v21 b2Vec2 normal = b2Sub( v21, v12 ); float invDistance = 1.0f / distance; normal.x *= invDistance; normal.y *= invDistance; b2Vec2 c1 = b2MulAdd( v12, localPolyA.radius, normal ); b2Vec2 c2 = b2MulAdd( v21, -localPolyB.radius, normal ); manifold.normal = normal; manifold.points[0].anchorA = b2Lerp( c1, c2, 0.5f ); manifold.points[0].separation = distance - radius; manifold.points[0].id = B2_MAKE_ID( i12, i21 ); manifold.pointCount = 1; } else if ( result.fraction1 == 1.0f && result.fraction2 == 1.0f ) { // v12 - v22 b2Vec2 normal = b2Sub( v22, v12 ); float invDistance = 1.0f / distance; normal.x *= invDistance; normal.y *= invDistance; b2Vec2 c1 = b2MulAdd( v12, localPolyA.radius, normal ); b2Vec2 c2 = b2MulAdd( v22, -localPolyB.radius, normal ); manifold.normal = normal; manifold.points[0].anchorA = b2Lerp( c1, c2, 0.5f ); manifold.points[0].separation = distance - radius; manifold.points[0].id = B2_MAKE_ID( i12, i22 ); manifold.pointCount = 1; } } #else // Polygons are disjoint. Find closest points between reference edge and incident edge // Reference edge on polygon A int i11 = edgeA; int i12 = edgeA + 1 < localPolyA.count ? edgeA + 1 : 0; int i21 = edgeB; int i22 = edgeB + 1 < localPolyB.count ? edgeB + 1 : 0; b2Vec2 v11 = localPolyA.vertices[i11]; b2Vec2 v12 = localPolyA.vertices[i12]; b2Vec2 v21 = localPolyB.vertices[i21]; b2Vec2 v22 = localPolyB.vertices[i22]; b2SegmentDistanceResult result = b2SegmentDistance( v11, v12, v21, v22 ); if ( result.fraction1 == 0.0f && result.fraction2 == 0.0f ) { // v11 - v21 b2Vec2 normal = b2Sub( v21, v11 ); B2_ASSERT( result.distanceSquared > 0.0f ); float distance = sqrtf( result.distanceSquared ); if ( distance > B2_SPECULATIVE_DISTANCE + radius ) { return manifold; } float invDistance = 1.0f / distance; normal.x *= invDistance; normal.y *= invDistance; b2Vec2 c1 = b2MulAdd( v11, localPolyA.radius, normal ); b2Vec2 c2 = b2MulAdd( v21, -localPolyB.radius, normal ); manifold.normal = normal; manifold.points[0].anchorA = b2Lerp( c1, c2, 0.5f ); manifold.points[0].separation = distance - radius; manifold.points[0].id = B2_MAKE_ID( i11, i21 ); manifold.pointCount = 1; } else if ( result.fraction1 == 0.0f && result.fraction2 == 1.0f ) { // v11 - v22 b2Vec2 normal = b2Sub( v22, v11 ); B2_ASSERT( result.distanceSquared > 0.0f ); float distance = sqrtf( result.distanceSquared ); if ( distance > B2_SPECULATIVE_DISTANCE + radius ) { return manifold; } float invDistance = 1.0f / distance; normal.x *= invDistance; normal.y *= invDistance; b2Vec2 c1 = b2MulAdd( v11, localPolyA.radius, normal ); b2Vec2 c2 = b2MulAdd( v22, -localPolyB.radius, normal ); manifold.normal = normal; manifold.points[0].anchorA = b2Lerp( c1, c2, 0.5f ); manifold.points[0].separation = distance - radius; manifold.points[0].id = B2_MAKE_ID( i11, i22 ); manifold.pointCount = 1; } else if ( result.fraction1 == 1.0f && result.fraction2 == 0.0f ) { // v12 - v21 b2Vec2 normal = b2Sub( v21, v12 ); B2_ASSERT( result.distanceSquared > 0.0f ); float distance = sqrtf( result.distanceSquared ); if ( distance > B2_SPECULATIVE_DISTANCE + radius ) { return manifold; } float invDistance = 1.0f / distance; normal.x *= invDistance; normal.y *= invDistance; b2Vec2 c1 = b2MulAdd( v12, localPolyA.radius, normal ); b2Vec2 c2 = b2MulAdd( v21, -localPolyB.radius, normal ); manifold.normal = normal; manifold.points[0].anchorA = b2Lerp( c1, c2, 0.5f ); manifold.points[0].separation = distance - radius; manifold.points[0].id = B2_MAKE_ID( i12, i21 ); manifold.pointCount = 1; } else if ( result.fraction1 == 1.0f && result.fraction2 == 1.0f ) { // v12 - v22 b2Vec2 normal = b2Sub( v22, v12 ); B2_ASSERT( result.distanceSquared > 0.0f ); float distance = sqrtf( result.distanceSquared ); if ( distance > B2_SPECULATIVE_DISTANCE + radius ) { return manifold; } float invDistance = 1.0f / distance; normal.x *= invDistance; normal.y *= invDistance; b2Vec2 c1 = b2MulAdd( v12, localPolyA.radius, normal ); b2Vec2 c2 = b2MulAdd( v22, -localPolyB.radius, normal ); manifold.normal = normal; manifold.points[0].anchorA = b2Lerp( c1, c2, 0.5f ); manifold.points[0].separation = distance - radius; manifold.points[0].id = B2_MAKE_ID( i12, i22 ); manifold.pointCount = 1; } else { // Edge region manifold = b2ClipPolygons( &localPolyA, &localPolyB, edgeA, edgeB, flip ); } #endif } else { // Polygons overlap manifold = b2ClipPolygons( &localPolyA, &localPolyB, edgeA, edgeB, flip ); } // Convert manifold to world space if ( manifold.pointCount > 0 ) { manifold.normal = b2RotateVector( xfA.q, manifold.normal ); for ( int i = 0; i < manifold.pointCount; ++i ) { b2ManifoldPoint* mp = manifold.points + i; // anchor points relative to shape origin in world space mp->anchorA = b2RotateVector( xfA.q, b2Add( mp->anchorA, origin ) ); mp->anchorB = b2Add( mp->anchorA, b2Sub( xfA.p, xfB.p ) ); mp->point = b2Add( xfA.p, mp->anchorA ); } } return manifold; } b2Manifold b2CollideSegmentAndCircle( const b2Segment* segmentA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB ) { b2Capsule capsuleA = { segmentA->point1, segmentA->point2, 0.0f }; return b2CollideCapsuleAndCircle( &capsuleA, xfA, circleB, xfB ); } b2Manifold b2CollideSegmentAndPolygon( const b2Segment* segmentA, b2Transform xfA, const b2Polygon* polygonB, b2Transform xfB ) { b2Polygon polygonA = b2MakeCapsule( segmentA->point1, segmentA->point2, 0.0f ); return b2CollidePolygons( &polygonA, xfA, polygonB, xfB ); } b2Manifold b2CollideChainSegmentAndCircle( const b2ChainSegment* segmentA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB ) { b2Manifold manifold = { 0 }; b2Transform xf = b2InvMulTransforms( xfA, xfB ); // Compute circle in frame of segment b2Vec2 pB = b2TransformPoint( xf, circleB->center ); b2Vec2 p1 = segmentA->segment.point1; b2Vec2 p2 = segmentA->segment.point2; b2Vec2 e = b2Sub( p2, p1 ); // Normal points to the right float offset = b2Dot( b2RightPerp( e ), b2Sub( pB, p1 ) ); if ( offset < 0.0f ) { // collision is one-sided return manifold; } // Barycentric coordinates float u = b2Dot( e, b2Sub( p2, pB ) ); float v = b2Dot( e, b2Sub( pB, p1 ) ); b2Vec2 pA; if ( v <= 0.0f ) { // Behind point1? // Is pB in the Voronoi region of the previous edge? b2Vec2 prevEdge = b2Sub( p1, segmentA->ghost1 ); float uPrev = b2Dot( prevEdge, b2Sub( pB, p1 ) ); if ( uPrev <= 0.0f ) { return manifold; } pA = p1; } else if ( u <= 0.0f ) { // Ahead of point2? b2Vec2 nextEdge = b2Sub( segmentA->ghost2, p2 ); float vNext = b2Dot( nextEdge, b2Sub( pB, p2 ) ); // Is pB in the Voronoi region of the next edge? if ( vNext > 0.0f ) { return manifold; } pA = p2; } else { float ee = b2Dot( e, e ); pA = (b2Vec2){ u * p1.x + v * p2.x, u * p1.y + v * p2.y }; pA = ee > 0.0f ? b2MulSV( 1.0f / ee, pA ) : p1; } float distance; b2Vec2 normal = b2GetLengthAndNormalize( &distance, b2Sub( pB, pA ) ); float radius = circleB->radius; float separation = distance - radius; if ( separation > B2_SPECULATIVE_DISTANCE ) { return manifold; } b2Vec2 cA = pA; b2Vec2 cB = b2MulAdd( pB, -radius, normal ); b2Vec2 contactPointA = b2Lerp( cA, cB, 0.5f ); manifold.normal = b2RotateVector( xfA.q, normal ); b2ManifoldPoint* mp = manifold.points + 0; mp->anchorA = b2RotateVector( xfA.q, contactPointA ); mp->anchorB = b2Add( mp->anchorA, b2Sub( xfA.p, xfB.p ) ); mp->point = b2Add( xfA.p, mp->anchorA ); mp->separation = separation; mp->id = 0; manifold.pointCount = 1; return manifold; } b2Manifold b2CollideChainSegmentAndCapsule( const b2ChainSegment* segmentA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB, b2SimplexCache* cache ) { b2Polygon polyB = b2MakeCapsule( capsuleB->center1, capsuleB->center2, capsuleB->radius ); return b2CollideChainSegmentAndPolygon( segmentA, xfA, &polyB, xfB, cache ); } static b2Manifold b2ClipSegments( b2Vec2 a1, b2Vec2 a2, b2Vec2 b1, b2Vec2 b2, b2Vec2 normal, float ra, float rb, uint16_t id1, uint16_t id2 ) { b2Manifold manifold = { 0 }; b2Vec2 tangent = b2LeftPerp( normal ); // Barycentric coordinates of each point relative to a1 along tangent float lower1 = 0.0f; float upper1 = b2Dot( b2Sub( a2, a1 ), tangent ); // Incident edge points opposite of tangent due to CCW winding float upper2 = b2Dot( b2Sub( b1, a1 ), tangent ); float lower2 = b2Dot( b2Sub( b2, a1 ), tangent ); // Do segments overlap? if ( upper2 < lower1 || upper1 < lower2 ) { return manifold; } b2Vec2 vLower; if ( lower2 < lower1 && upper2 - lower2 > FLT_EPSILON ) { vLower = b2Lerp( b2, b1, ( lower1 - lower2 ) / ( upper2 - lower2 ) ); } else { vLower = b2; } b2Vec2 vUpper; if ( upper2 > upper1 && upper2 - lower2 > FLT_EPSILON ) { vUpper = b2Lerp( b2, b1, ( upper1 - lower2 ) / ( upper2 - lower2 ) ); } else { vUpper = b1; } // todo vLower can be very close to vUpper, reduce to one point? float separationLower = b2Dot( b2Sub( vLower, a1 ), normal ); float separationUpper = b2Dot( b2Sub( vUpper, a1 ), normal ); // Put contact points at midpoint, accounting for radii vLower = b2MulAdd( vLower, 0.5f * ( ra - rb - separationLower ), normal ); vUpper = b2MulAdd( vUpper, 0.5f * ( ra - rb - separationUpper ), normal ); float radius = ra + rb; manifold.normal = normal; { b2ManifoldPoint* cp = manifold.points + 0; cp->anchorA = vLower; cp->separation = separationLower - radius; cp->id = id1; } { b2ManifoldPoint* cp = manifold.points + 1; cp->anchorA = vUpper; cp->separation = separationUpper - radius; cp->id = id2; } manifold.pointCount = 2; return manifold; } enum b2NormalType { // This means the normal points in a direction that is non-smooth relative to a convex vertex and should be skipped b2_normalSkip, // This means the normal points in a direction that is smooth relative to a convex vertex and should be used for collision b2_normalAdmit, // This means the normal is in a region of a concave vertex and should be snapped to the segment normal b2_normalSnap }; struct b2ChainSegmentParams { b2Vec2 edge1; b2Vec2 normal0; b2Vec2 normal2; bool convex1; bool convex2; }; // Evaluate Gauss map // See https://box2d.org/posts/2020/06/ghost-collisions/ static enum b2NormalType b2ClassifyNormal( struct b2ChainSegmentParams params, b2Vec2 normal ) { const float sinTol = 0.01f; if ( b2Dot( normal, params.edge1 ) <= 0.0f ) { // Normal points towards the segment tail if ( params.convex1 ) { if ( b2Cross( normal, params.normal0 ) > sinTol ) { return b2_normalSkip; } return b2_normalAdmit; } else { return b2_normalSnap; } } else { // Normal points towards segment head if ( params.convex2 ) { if ( b2Cross( params.normal2, normal ) > sinTol ) { return b2_normalSkip; } return b2_normalAdmit; } else { return b2_normalSnap; } } } b2Manifold b2CollideChainSegmentAndPolygon( const b2ChainSegment* segmentA, b2Transform xfA, const b2Polygon* polygonB, b2Transform xfB, b2SimplexCache* cache ) { b2Manifold manifold = { 0 }; b2Transform xf = b2InvMulTransforms( xfA, xfB ); b2Vec2 centroidB = b2TransformPoint( xf, polygonB->centroid ); float radiusB = polygonB->radius; b2Vec2 p1 = segmentA->segment.point1; b2Vec2 p2 = segmentA->segment.point2; b2Vec2 edge1 = b2Normalize( b2Sub( p2, p1 ) ); struct b2ChainSegmentParams smoothParams = { 0 }; smoothParams.edge1 = edge1; const float convexTol = 0.01f; b2Vec2 edge0 = b2Normalize( b2Sub( p1, segmentA->ghost1 ) ); smoothParams.normal0 = b2RightPerp( edge0 ); smoothParams.convex1 = b2Cross( edge0, edge1 ) >= convexTol; b2Vec2 edge2 = b2Normalize( b2Sub( segmentA->ghost2, p2 ) ); smoothParams.normal2 = b2RightPerp( edge2 ); smoothParams.convex2 = b2Cross( edge1, edge2 ) >= convexTol; // Normal points to the right b2Vec2 normal1 = b2RightPerp( edge1 ); bool behind1 = b2Dot( normal1, b2Sub( centroidB, p1 ) ) < 0.0f; bool behind0 = true; bool behind2 = true; if ( smoothParams.convex1 ) { behind0 = b2Dot( smoothParams.normal0, b2Sub( centroidB, p1 ) ) < 0.0f; } if ( smoothParams.convex2 ) { behind2 = b2Dot( smoothParams.normal2, b2Sub( centroidB, p2 ) ) < 0.0f; } if ( behind1 && behind0 && behind2 ) { // one-sided collision return manifold; } // Get polygonB in frameA int count = polygonB->count; b2Vec2 vertices[B2_MAX_POLYGON_VERTICES]; b2Vec2 normals[B2_MAX_POLYGON_VERTICES]; for ( int i = 0; i < count; ++i ) { vertices[i] = b2TransformPoint( xf, polygonB->vertices[i] ); normals[i] = b2RotateVector( xf.q, polygonB->normals[i] ); } // Distance doesn't work correctly with partial polygons b2DistanceInput input; input.proxyA = b2MakeProxy( &segmentA->segment.point1, 2, 0.0f ); input.proxyB = b2MakeProxy( vertices, count, 0.0f ); input.transformA = b2Transform_identity; input.transformB = b2Transform_identity; input.useRadii = false; b2DistanceOutput output = b2ShapeDistance( &input, cache, NULL, 0 ); if ( output.distance > radiusB + B2_SPECULATIVE_DISTANCE ) { return manifold; } // Snap concave normals for partial polygon b2Vec2 n0 = smoothParams.convex1 ? smoothParams.normal0 : normal1; b2Vec2 n2 = smoothParams.convex2 ? smoothParams.normal2 : normal1; // Index of incident vertex on polygon int incidentIndex = -1; int incidentNormal = -1; if ( behind1 == false && output.distance > 0.1f * B2_LINEAR_SLOP ) { // The closest features may be two vertices or an edge and a vertex even when there should // be face contact if ( cache->count == 1 ) { // vertex-vertex collision b2Vec2 pA = output.pointA; b2Vec2 pB = output.pointB; b2Vec2 normal = b2Normalize( b2Sub( pB, pA ) ); enum b2NormalType type = b2ClassifyNormal( smoothParams, normal ); if ( type == b2_normalSkip ) { return manifold; } if ( type == b2_normalAdmit ) { manifold.normal = b2RotateVector( xfA.q, normal ); b2ManifoldPoint* cp = manifold.points + 0; cp->anchorA = b2RotateVector( xfA.q, pA ); cp->anchorB = b2Add( cp->anchorA, b2Sub( xfA.p, xfB.p ) ); cp->point = b2Add( xfA.p, cp->anchorA ); cp->separation = output.distance - radiusB; cp->id = B2_MAKE_ID( cache->indexA[0], cache->indexB[0] ); manifold.pointCount = 1; return manifold; } // fall through b2_normalSnap incidentIndex = cache->indexB[0]; } else { // vertex-edge collision B2_ASSERT( cache->count == 2 ); int ia1 = cache->indexA[0]; int ia2 = cache->indexA[1]; int ib1 = cache->indexB[0]; int ib2 = cache->indexB[1]; if ( ia1 == ia2 ) { // 1 point on A, expect 2 points on B B2_ASSERT( ib1 != ib2 ); // Find polygon normal most aligned with vector between closest points. // This effectively sorts ib1 and ib2 b2Vec2 normalB = b2Sub( output.pointA, output.pointB ); float dot1 = b2Dot( normalB, normals[ib1] ); float dot2 = b2Dot( normalB, normals[ib2] ); int ib = dot1 > dot2 ? ib1 : ib2; // Use accurate normal normalB = normals[ib]; enum b2NormalType type = b2ClassifyNormal( smoothParams, b2Neg( normalB ) ); if ( type == b2_normalSkip ) { return manifold; } if ( type == b2_normalAdmit ) { // Get polygon edge associated with normal ib1 = ib; ib2 = ib < count - 1 ? ib + 1 : 0; b2Vec2 b1 = vertices[ib1]; b2Vec2 b2 = vertices[ib2]; // Find incident segment vertex dot1 = b2Dot( normalB, b2Sub( p1, b1 ) ); dot2 = b2Dot( normalB, b2Sub( p2, b1 ) ); if ( dot1 < dot2 ) { if ( b2Dot( n0, normalB ) < b2Dot( normal1, normalB ) ) { // Neighbor is incident return manifold; } } else { if ( b2Dot( n2, normalB ) < b2Dot( normal1, normalB ) ) { // Neighbor is incident return manifold; } } manifold = b2ClipSegments( b1, b2, p1, p2, normalB, radiusB, 0.0f, B2_MAKE_ID( ib1, 1 ), B2_MAKE_ID( ib2, 0 ) ); B2_ASSERT( manifold.pointCount == 0 || manifold.pointCount == 2 ); if ( manifold.pointCount == 2 ) { manifold.normal = b2RotateVector( xfA.q, b2Neg( normalB ) ); manifold.points[0].anchorA = b2RotateVector( xfA.q, manifold.points[0].anchorA ); manifold.points[1].anchorA = b2RotateVector( xfA.q, manifold.points[1].anchorA ); b2Vec2 pAB = b2Sub( xfA.p, xfB.p ); manifold.points[0].anchorB = b2Add( manifold.points[0].anchorA, pAB ); manifold.points[1].anchorB = b2Add( manifold.points[1].anchorA, pAB ); manifold.points[0].point = b2Add( xfA.p, manifold.points[0].anchorA ); manifold.points[1].point = b2Add( xfA.p, manifold.points[1].anchorA ); } return manifold; } // fall through b2_normalSnap incidentNormal = ib; } else { // Get index of incident polygonB vertex float dot1 = b2Dot( normal1, b2Sub( vertices[ib1], p1 ) ); float dot2 = b2Dot( normal1, b2Sub( vertices[ib2], p2 ) ); incidentIndex = dot1 < dot2 ? ib1 : ib2; } } } else { // SAT edge normal float edgeSeparation = FLT_MAX; for ( int i = 0; i < count; ++i ) { float s = b2Dot( normal1, b2Sub( vertices[i], p1 ) ); if ( s < edgeSeparation ) { edgeSeparation = s; incidentIndex = i; } } // Check convex neighbor for edge separation if ( smoothParams.convex1 ) { float s0 = FLT_MAX; for ( int i = 0; i < count; ++i ) { float s = b2Dot( smoothParams.normal0, b2Sub( vertices[i], p1 ) ); if ( s < s0 ) { s0 = s; } } if ( s0 > edgeSeparation ) { edgeSeparation = s0; // Indicate neighbor owns edge separation incidentIndex = -1; } } // Check convex neighbor for edge separation if ( smoothParams.convex2 ) { float s2 = FLT_MAX; for ( int i = 0; i < count; ++i ) { float s = b2Dot( smoothParams.normal2, b2Sub( vertices[i], p2 ) ); if ( s < s2 ) { s2 = s; } } if ( s2 > edgeSeparation ) { edgeSeparation = s2; // Indicate neighbor owns edge separation incidentIndex = -1; } } // SAT polygon normals float polygonSeparation = -FLT_MAX; int referenceIndex = -1; for ( int i = 0; i < count; ++i ) { b2Vec2 n = normals[i]; enum b2NormalType type = b2ClassifyNormal( smoothParams, b2Neg( n ) ); if ( type != b2_normalAdmit ) { continue; } // Check the infinite sides of the partial polygon // if ((smoothParams.convex1 && b2Cross(n0, n) > 0.0f) || (smoothParams.convex2 && b2Cross(n, n2) > 0.0f)) //{ // continue; //} b2Vec2 p = vertices[i]; float s = b2MinFloat( b2Dot( n, b2Sub( p2, p ) ), b2Dot( n, b2Sub( p1, p ) ) ); if ( s > polygonSeparation ) { polygonSeparation = s; referenceIndex = i; } } if ( polygonSeparation > edgeSeparation ) { int ia1 = referenceIndex; int ia2 = ia1 < count - 1 ? ia1 + 1 : 0; b2Vec2 a1 = vertices[ia1]; b2Vec2 a2 = vertices[ia2]; b2Vec2 n = normals[ia1]; float dot1 = b2Dot( n, b2Sub( p1, a1 ) ); float dot2 = b2Dot( n, b2Sub( p2, a1 ) ); if ( dot1 < dot2 ) { if ( b2Dot( n0, n ) < b2Dot( normal1, n ) ) { // Neighbor is incident return manifold; } } else { if ( b2Dot( n2, n ) < b2Dot( normal1, n ) ) { // Neighbor is incident return manifold; } } manifold = b2ClipSegments( a1, a2, p1, p2, normals[ia1], radiusB, 0.0f, B2_MAKE_ID( ia1, 1 ), B2_MAKE_ID( ia2, 0 ) ); B2_ASSERT( manifold.pointCount == 0 || manifold.pointCount == 2 ); if ( manifold.pointCount == 2 ) { manifold.normal = b2RotateVector( xfA.q, b2Neg( normals[ia1] ) ); manifold.points[0].anchorA = b2RotateVector( xfA.q, manifold.points[0].anchorA ); manifold.points[1].anchorA = b2RotateVector( xfA.q, manifold.points[1].anchorA ); b2Vec2 pAB = b2Sub( xfA.p, xfB.p ); manifold.points[0].anchorB = b2Add( manifold.points[0].anchorA, pAB ); manifold.points[1].anchorB = b2Add( manifold.points[1].anchorA, pAB ); manifold.points[0].point = b2Add( xfA.p, manifold.points[0].anchorA ); manifold.points[1].point = b2Add( xfA.p, manifold.points[1].anchorA ); } return manifold; } if ( incidentIndex == -1 ) { // neighboring segment is the separating axis return manifold; } // fall through segment normal axis } B2_ASSERT( incidentNormal != -1 || incidentIndex != -1 ); // Segment normal // Find incident polygon normal: normal adjacent to deepest vertex that is most anti-parallel to segment normal b2Vec2 b1, b2; int ib1, ib2; if ( incidentNormal != -1 ) { ib1 = incidentNormal; ib2 = ib1 < count - 1 ? ib1 + 1 : 0; b1 = vertices[ib1]; b2 = vertices[ib2]; } else { int i2 = incidentIndex; int i1 = i2 > 0 ? i2 - 1 : count - 1; float d1 = b2Dot( normal1, normals[i1] ); float d2 = b2Dot( normal1, normals[i2] ); if ( d1 < d2 ) { ib1 = i1, ib2 = i2; b1 = vertices[ib1]; b2 = vertices[ib2]; } else { ib1 = i2, ib2 = i2 < count - 1 ? i2 + 1 : 0; b1 = vertices[ib1]; b2 = vertices[ib2]; } } manifold = b2ClipSegments( p1, p2, b1, b2, normal1, 0.0f, radiusB, B2_MAKE_ID( 0, ib2 ), B2_MAKE_ID( 1, ib1 ) ); B2_ASSERT( manifold.pointCount == 0 || manifold.pointCount == 2 ); if ( manifold.pointCount == 2 ) { // There may be no points c manifold.normal = b2RotateVector( xfA.q, manifold.normal ); manifold.points[0].anchorA = b2RotateVector( xfA.q, manifold.points[0].anchorA ); manifold.points[1].anchorA = b2RotateVector( xfA.q, manifold.points[1].anchorA ); b2Vec2 pAB = b2Sub( xfA.p, xfB.p ); manifold.points[0].anchorB = b2Add( manifold.points[0].anchorA, pAB ); manifold.points[1].anchorB = b2Add( manifold.points[1].anchorA, pAB ); manifold.points[0].point = b2Add( xfA.p, manifold.points[0].anchorA ); manifold.points[1].point = b2Add( xfA.p, manifold.points[1].anchorA ); } return manifold; } ================================================ FILE: src/math_functions.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "box2d/math_functions.h" #include _Static_assert( sizeof( int32_t ) == sizeof( int ), "Box2D expects int32_t and int to be the same" ); bool b2IsValidFloat( float a ) { if ( isnan( a ) ) { return false; } if ( isinf( a ) ) { return false; } return true; } bool b2IsValidVec2( b2Vec2 v ) { if ( isnan( v.x ) || isnan( v.y ) ) { return false; } if ( isinf( v.x ) || isinf( v.y ) ) { return false; } return true; } bool b2IsValidRotation( b2Rot q ) { if ( isnan( q.s ) || isnan( q.c ) ) { return false; } if ( isinf( q.s ) || isinf( q.c ) ) { return false; } return b2IsNormalizedRot( q ); } bool b2IsValidTransform(b2Transform t) { if (b2IsValidVec2(t.p) == false) { return false; } return b2IsValidRotation( t.q ); } bool b2IsValidPlane( b2Plane a ) { return b2IsValidVec2( a.normal ) && b2IsNormalized( a.normal ) && b2IsValidFloat( a.offset ); } // https://stackoverflow.com/questions/46210708/atan2-approximation-with-11bits-in-mantissa-on-x86with-sse2-and-armwith-vfpv4 float b2Atan2( float y, float x ) { // Added check for (0,0) to match atan2f and avoid NaN if (x == 0.0f && y == 0.0f) { return 0.0f; } float ax = b2AbsFloat( x ); float ay = b2AbsFloat( y ); float mx = b2MaxFloat( ay, ax ); float mn = b2MinFloat( ay, ax ); float a = mn / mx; // Minimax polynomial approximation to atan(a) on [0,1] float s = a * a; float c = s * a; float q = s * s; float r = 0.024840285f * q + 0.18681418f; float t = -0.094097948f * q - 0.33213072f; r = r * s + t; r = r * c + a; // Map to full circle if ( ay > ax ) { r = 1.57079637f - r; } if ( x < 0 ) { r = 3.14159274f - r; } if ( y < 0 ) { r = -r; } return r; } // Approximate cosine and sine for determinism. In my testing cosf and sinf produced // the same results on x64 and ARM using MSVC, GCC, and Clang. However, I don't trust // this result. // https://en.wikipedia.org/wiki/Bh%C4%81skara_I%27s_sine_approximation_formula b2CosSin b2ComputeCosSin( float radians ) { float x = b2UnwindAngle( radians ); float pi2 = B2_PI * B2_PI; // cosine needs angle in [-pi/2, pi/2] float c; if ( x < -0.5f * B2_PI ) { float y = x + B2_PI; float y2 = y * y; c = -( pi2 - 4.0f * y2 ) / ( pi2 + y2 ); } else if ( x > 0.5f * B2_PI ) { float y = x - B2_PI; float y2 = y * y; c = -( pi2 - 4.0f * y2 ) / ( pi2 + y2 ); } else { float y2 = x * x; c = ( pi2 - 4.0f * y2 ) / ( pi2 + y2 ); } // sine needs angle in [0, pi] float s; if ( x < 0.0f ) { float y = x + B2_PI; s = -16.0f * y * ( B2_PI - y ) / ( 5.0f * pi2 - 4.0f * y * ( B2_PI - y ) ); } else { s = 16.0f * x * ( B2_PI - x ) / ( 5.0f * pi2 - 4.0f * x * ( B2_PI - x ) ); } float mag = sqrtf( s * s + c * c ); float invMag = mag > 0.0f ? 1.0f / mag : 0.0f; b2CosSin cs = { c * invMag, s * invMag }; return cs; } b2Rot b2ComputeRotationBetweenUnitVectors(b2Vec2 v1, b2Vec2 v2) { B2_ASSERT( b2AbsFloat( 1.0f - b2Length( v1 ) ) < 100.0f * FLT_EPSILON ); B2_ASSERT( b2AbsFloat( 1.0f - b2Length( v2 ) ) < 100.0f * FLT_EPSILON ); b2Rot rot; rot.c = b2Dot( v1, v2 ); rot.s = b2Cross( v1, v2 ); return b2NormalizeRot( rot ); } ================================================ FILE: src/motor_joint.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "body.h" #include "core.h" #include "joint.h" #include "physics_world.h" #include "solver.h" #include "solver_set.h" // needed for dll export #include "box2d/box2d.h" void b2MotorJoint_SetLinearVelocity( b2JointId jointId, b2Vec2 velocity ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); joint->motorJoint.linearVelocity = velocity; } b2Vec2 b2MotorJoint_GetLinearVelocity( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); return joint->motorJoint.linearVelocity; } void b2MotorJoint_SetAngularVelocity( b2JointId jointId, float velocity ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); joint->motorJoint.angularVelocity = velocity; } float b2MotorJoint_GetAngularVelocity( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); return joint->motorJoint.angularVelocity; } void b2MotorJoint_SetMaxVelocityTorque( b2JointId jointId, float maxTorque ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); joint->motorJoint.maxVelocityTorque = maxTorque; } float b2MotorJoint_GetMaxVelocityTorque( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); return joint->motorJoint.maxVelocityTorque; } void b2MotorJoint_SetMaxVelocityForce( b2JointId jointId, float maxForce ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); joint->motorJoint.maxVelocityForce = maxForce; } float b2MotorJoint_GetMaxVelocityForce( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); return joint->motorJoint.maxVelocityForce; } void b2MotorJoint_SetLinearHertz( b2JointId jointId, float hertz ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); joint->motorJoint.linearHertz = hertz; } float b2MotorJoint_GetLinearHertz( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); return joint->motorJoint.linearHertz; } void b2MotorJoint_SetLinearDampingRatio( b2JointId jointId, float damping ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); joint->motorJoint.linearDampingRatio = damping; } float b2MotorJoint_GetLinearDampingRatio( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); return joint->motorJoint.linearDampingRatio; } void b2MotorJoint_SetAngularHertz( b2JointId jointId, float hertz ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); joint->motorJoint.angularHertz = hertz; } float b2MotorJoint_GetAngularHertz( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); return joint->motorJoint.angularHertz; } void b2MotorJoint_SetAngularDampingRatio( b2JointId jointId, float damping ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); joint->motorJoint.angularDampingRatio = damping; } float b2MotorJoint_GetAngularDampingRatio( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); return joint->motorJoint.angularDampingRatio; } void b2MotorJoint_SetMaxSpringForce( b2JointId jointId, float maxForce ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); joint->motorJoint.maxSpringForce = b2MaxFloat( 0.0f, maxForce ); } float b2MotorJoint_GetMaxSpringForce( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); return joint->motorJoint.maxSpringForce; } void b2MotorJoint_SetMaxSpringTorque( b2JointId jointId, float maxTorque ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); joint->motorJoint.maxSpringTorque = b2MaxFloat( 0.0f, maxTorque ); } float b2MotorJoint_GetMaxSpringTorque( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); return joint->motorJoint.maxSpringTorque; } b2Vec2 b2GetMotorJointForce( b2World* world, b2JointSim* base ) { b2Vec2 force = b2MulSV( world->inv_h, b2Add( base->motorJoint.linearVelocityImpulse, base->motorJoint.linearSpringImpulse ) ); return force; } float b2GetMotorJointTorque( b2World* world, b2JointSim* base ) { return world->inv_h * ( base->motorJoint.angularVelocityImpulse + base->motorJoint.angularSpringImpulse ); } // Point-to-point constraint // C = p2 - p1 // Cdot = v2 - v1 // = v2 + cross(w2, r2) - v1 - cross(w1, r1) // J = [-I -r1_skew I r2_skew ] // Identity used: // w k % (rx i + ry j) = w * (-ry i + rx j) // Angle constraint // C = angle2 - angle1 - referenceAngle // Cdot = w2 - w1 // J = [0 0 -1 0 0 1] // K = invI1 + invI2 void b2PrepareMotorJoint( b2JointSim* base, b2StepContext* context ) { B2_ASSERT( base->type == b2_motorJoint ); // chase body id to the solver set where the body lives int idA = base->bodyIdA; int idB = base->bodyIdB; b2World* world = context->world; b2Body* bodyA = b2BodyArray_Get( &world->bodies, idA ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, idB ); B2_ASSERT( bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet ); b2SolverSet* setA = b2SolverSetArray_Get( &world->solverSets, bodyA->setIndex ); b2SolverSet* setB = b2SolverSetArray_Get( &world->solverSets, bodyB->setIndex ); int localIndexA = bodyA->localIndex; int localIndexB = bodyB->localIndex; b2BodySim* bodySimA = b2BodySimArray_Get( &setA->bodySims, localIndexA ); b2BodySim* bodySimB = b2BodySimArray_Get( &setB->bodySims, localIndexB ); float mA = bodySimA->invMass; float iA = bodySimA->invInertia; float mB = bodySimB->invMass; float iB = bodySimB->invInertia; base->invMassA = mA; base->invMassB = mB; base->invIA = iA; base->invIB = iB; b2MotorJoint* joint = &base->motorJoint; joint->indexA = bodyA->setIndex == b2_awakeSet ? localIndexA : B2_NULL_INDEX; joint->indexB = bodyB->setIndex == b2_awakeSet ? localIndexB : B2_NULL_INDEX; // Compute joint anchor frames with world space rotation, relative to center of mass joint->frameA.q = b2MulRot( bodySimA->transform.q, base->localFrameA.q ); joint->frameA.p = b2RotateVector( bodySimA->transform.q, b2Sub( base->localFrameA.p, bodySimA->localCenter ) ); joint->frameB.q = b2MulRot( bodySimB->transform.q, base->localFrameB.q ); joint->frameB.p = b2RotateVector( bodySimB->transform.q, b2Sub( base->localFrameB.p, bodySimB->localCenter ) ); // Compute the initial center delta. Incremental position updates are relative to this. joint->deltaCenter = b2Sub( bodySimB->center, bodySimA->center ); b2Vec2 rA = joint->frameA.p; b2Vec2 rB = joint->frameB.p; joint->linearSpring = b2MakeSoft( joint->linearHertz, joint->linearDampingRatio, context->h ); joint->angularSpring = b2MakeSoft( joint->angularHertz, joint->angularDampingRatio, context->h ); b2Mat22 kl; kl.cx.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; kl.cx.y = -rA.y * rA.x * iA - rB.y * rB.x * iB; kl.cy.x = kl.cx.y; kl.cy.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; joint->linearMass = b2GetInverse22( kl ); float ka = iA + iB; joint->angularMass = ka > 0.0f ? 1.0f / ka : 0.0f; if ( context->enableWarmStarting == false ) { joint->linearVelocityImpulse = b2Vec2_zero; joint->angularVelocityImpulse = 0.0f; joint->linearSpringImpulse = b2Vec2_zero; joint->angularSpringImpulse = 0.0f; } } void b2WarmStartMotorJoint( b2JointSim* base, b2StepContext* context ) { B2_ASSERT( base->type == b2_motorJoint ); float mA = base->invMassA; float mB = base->invMassB; float iA = base->invIA; float iB = base->invIB; b2MotorJoint* joint = &base->motorJoint; // dummy state for static bodies b2BodyState dummyState = b2_identityBodyState; b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->frameA.p ); b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->frameB.p ); b2Vec2 linearImpulse = b2Add( joint->linearVelocityImpulse, joint->linearSpringImpulse ); float angularImpulse = joint->angularVelocityImpulse + joint->angularSpringImpulse; if ( stateA->flags & b2_dynamicFlag ) { stateA->linearVelocity = b2MulSub( stateA->linearVelocity, mA, linearImpulse ); stateA->angularVelocity -= iA * ( b2Cross( rA, linearImpulse ) + angularImpulse ); } if ( stateB->flags & b2_dynamicFlag ) { stateB->linearVelocity = b2MulAdd( stateB->linearVelocity, mB, linearImpulse ); stateB->angularVelocity += iB * ( b2Cross( rB, linearImpulse ) + angularImpulse ); } } void b2SolveMotorJoint( b2JointSim* base, b2StepContext* context ) { B2_ASSERT( base->type == b2_motorJoint ); float mA = base->invMassA; float mB = base->invMassB; float iA = base->invIA; float iB = base->invIB; // dummy state for static bodies b2BodyState dummyState = b2_identityBodyState; b2MotorJoint* joint = &base->motorJoint; b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; b2Vec2 vA = stateA->linearVelocity; float wA = stateA->angularVelocity; b2Vec2 vB = stateB->linearVelocity; float wB = stateB->angularVelocity; // angular spring if ( joint->maxSpringTorque > 0.0f && joint->angularHertz > 0.0f ) { b2Rot qA = b2MulRot( stateA->deltaRotation, joint->frameA.q ); b2Rot qB = b2MulRot( stateB->deltaRotation, joint->frameB.q ); b2Rot relQ = b2InvMulRot( qA, qB ); float c = b2Rot_GetAngle( relQ ); float bias = joint->angularSpring.biasRate * c; float massScale = joint->angularSpring.massScale; float impulseScale = joint->angularSpring.impulseScale; float cdot = wB - wA; float maxImpulse = context->h * joint->maxSpringTorque; float oldImpulse = joint->angularSpringImpulse; float impulse = -massScale * joint->angularMass * ( cdot + bias ) - impulseScale * oldImpulse; joint->angularSpringImpulse = b2ClampFloat( oldImpulse + impulse, -maxImpulse, maxImpulse ); impulse = joint->angularSpringImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // angular velocity if ( joint->maxVelocityTorque > 0.0f ) { float cdot = wB - wA - joint->angularVelocity; float impulse = -joint->angularMass * cdot; float maxImpulse = context->h * joint->maxVelocityTorque; float oldImpulse = joint->angularVelocityImpulse; joint->angularVelocityImpulse = b2ClampFloat( oldImpulse + impulse, -maxImpulse, maxImpulse ); impulse = joint->angularVelocityImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->frameA.p ); b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->frameB.p ); // linear spring if ( joint->maxSpringForce > 0.0f && joint->linearHertz > 0.0f ) { b2Vec2 dcA = stateA->deltaPosition; b2Vec2 dcB = stateB->deltaPosition; b2Vec2 c = b2Add( b2Add( b2Sub( dcB, dcA ), b2Sub( rB, rA ) ), joint->deltaCenter ); b2Vec2 bias = b2MulSV( joint->linearSpring.biasRate, c ); float massScale = joint->linearSpring.massScale; float impulseScale = joint->linearSpring.impulseScale; b2Vec2 cdot = b2Sub( b2Add( vB, b2CrossSV( wB, rB ) ), b2Add( vA, b2CrossSV( wA, rA ) ) ); cdot = b2Add( cdot, bias ); // Updating the effective mass here may be overkill b2Mat22 kl; kl.cx.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; kl.cx.y = -rA.y * rA.x * iA - rB.y * rB.x * iB; kl.cy.x = kl.cx.y; kl.cy.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; joint->linearMass = b2GetInverse22( kl ); b2Vec2 b = b2MulMV( joint->linearMass, cdot ); b2Vec2 oldImpulse = joint->linearSpringImpulse; b2Vec2 impulse = { -massScale * b.x - impulseScale * oldImpulse.x, -massScale * b.y - impulseScale * oldImpulse.y, }; float maxImpulse = context->h * joint->maxSpringForce; joint->linearSpringImpulse = b2Add( joint->linearSpringImpulse, impulse ); if ( b2LengthSquared( joint->linearSpringImpulse ) > maxImpulse * maxImpulse ) { joint->linearSpringImpulse = b2Normalize( joint->linearSpringImpulse ); joint->linearSpringImpulse.x *= maxImpulse; joint->linearSpringImpulse.y *= maxImpulse; } impulse = b2Sub( joint->linearSpringImpulse, oldImpulse ); vA = b2MulSub( vA, mA, impulse ); wA -= iA * b2Cross( rA, impulse ); vB = b2MulAdd( vB, mB, impulse ); wB += iB * b2Cross( rB, impulse ); } // linear velocity if ( joint->maxVelocityForce > 0.0f ) { b2Vec2 cdot = b2Sub( b2Add( vB, b2CrossSV( wB, rB ) ), b2Add( vA, b2CrossSV( wA, rA ) ) ); cdot = b2Sub( cdot, joint->linearVelocity ); b2Vec2 b = b2MulMV( joint->linearMass, cdot ); b2Vec2 impulse = { -b.x, -b.y }; b2Vec2 oldImpulse = joint->linearVelocityImpulse; float maxImpulse = context->h * joint->maxVelocityForce; joint->linearVelocityImpulse = b2Add( joint->linearVelocityImpulse, impulse ); if ( b2LengthSquared( joint->linearVelocityImpulse ) > maxImpulse * maxImpulse ) { joint->linearVelocityImpulse = b2Normalize( joint->linearVelocityImpulse ); joint->linearVelocityImpulse.x *= maxImpulse; joint->linearVelocityImpulse.y *= maxImpulse; } impulse = b2Sub( joint->linearVelocityImpulse, oldImpulse ); vA = b2MulSub( vA, mA, impulse ); wA -= iA * b2Cross( rA, impulse ); vB = b2MulAdd( vB, mB, impulse ); wB += iB * b2Cross( rB, impulse ); } if ( stateA->flags & b2_dynamicFlag ) { stateA->linearVelocity = vA; stateA->angularVelocity = wA; } if ( stateB->flags & b2_dynamicFlag ) { stateB->linearVelocity = vB; stateB->angularVelocity = wB; } } #if 0 void b2DumpMotorJoint() { int32 indexA = m_bodyA->m_islandIndex; int32 indexB = m_bodyB->m_islandIndex; b2Dump(" b2MotorJointDef jd;\n"); b2Dump(" jd.bodyA = sims[%d];\n", indexA); b2Dump(" jd.bodyB = sims[%d];\n", indexB); b2Dump(" jd.collideConnected = bool(%d);\n", m_collideConnected); b2Dump(" jd.localAnchorA.Set(%.9g, %.9g);\n", m_localAnchorA.x, m_localAnchorA.y); b2Dump(" jd.localAnchorB.Set(%.9g, %.9g);\n", m_localAnchorB.x, m_localAnchorB.y); b2Dump(" jd.referenceAngle = %.9g;\n", m_referenceAngle); b2Dump(" jd.stiffness = %.9g;\n", m_stiffness); b2Dump(" jd.damping = %.9g;\n", m_damping); b2Dump(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); } #endif ================================================ FILE: src/mover.c ================================================ // SPDX-FileCopyrightText: 2025 Erin Catto // SPDX-License-Identifier: MIT #include "constants.h" #include "box2d/collision.h" b2PlaneSolverResult b2SolvePlanes( b2Vec2 targetDelta, b2CollisionPlane* planes, int count ) { for ( int i = 0; i < count; ++i ) { planes[i].push = 0.0f; } b2Vec2 delta = targetDelta; float tolerance = B2_LINEAR_SLOP; int iteration; for ( iteration = 0; iteration < 20; ++iteration ) { float totalPush = 0.0f; for ( int planeIndex = 0; planeIndex < count; ++planeIndex ) { b2CollisionPlane* plane = planes + planeIndex; // Add slop to prevent jitter float separation = b2PlaneSeparation( plane->plane, delta ) + B2_LINEAR_SLOP; // if (separation > 0.0f) //{ // continue; // } float push = -separation; // Clamp accumulated push float accumulatedPush = plane->push; plane->push = b2ClampFloat( plane->push + push, 0.0f, plane->pushLimit ); push = plane->push - accumulatedPush; delta = b2MulAdd( delta, push, plane->plane.normal ); // Track maximum push for convergence totalPush += b2AbsFloat( push ); } if ( totalPush < tolerance ) { break; } } return (b2PlaneSolverResult){ .translation = delta, .iterationCount = iteration, }; } b2Vec2 b2ClipVector( b2Vec2 vector, const b2CollisionPlane* planes, int count ) { b2Vec2 v = vector; for ( int planeIndex = 0; planeIndex < count; ++planeIndex ) { const b2CollisionPlane* plane = planes + planeIndex; if ( plane->push == 0.0f || plane->clipVelocity == false ) { continue; } v = b2MulSub( v, b2MinFloat( 0.0f, b2Dot( v, plane->plane.normal ) ), plane->plane.normal ); } return v; } ================================================ FILE: src/physics_world.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #if defined( _MSC_VER ) && !defined( _CRT_SECURE_NO_WARNINGS ) #define _CRT_SECURE_NO_WARNINGS #endif #include "physics_world.h" #include "arena_allocator.h" #include "array.h" #include "bitset.h" #include "body.h" #include "broad_phase.h" #include "constants.h" #include "constraint_graph.h" #include "contact.h" #include "core.h" #include "ctz.h" #include "island.h" #include "joint.h" #include "sensor.h" #include "shape.h" #include "solver.h" #include "solver_set.h" #include "box2d/box2d.h" #include #include #include _Static_assert( B2_MAX_WORLDS > 0, "must be 1 or more" ); _Static_assert( B2_MAX_WORLDS < UINT16_MAX, "B2_MAX_WORLDS limit exceeded" ); static b2World b2_worlds[B2_MAX_WORLDS]; B2_ARRAY_SOURCE( b2BodyMoveEvent, b2BodyMoveEvent ) B2_ARRAY_SOURCE( b2ContactBeginTouchEvent, b2ContactBeginTouchEvent ) B2_ARRAY_SOURCE( b2ContactEndTouchEvent, b2ContactEndTouchEvent ) B2_ARRAY_SOURCE( b2ContactHitEvent, b2ContactHitEvent ) B2_ARRAY_SOURCE( b2SensorBeginTouchEvent, b2SensorBeginTouchEvent ) B2_ARRAY_SOURCE( b2SensorEndTouchEvent, b2SensorEndTouchEvent ) B2_ARRAY_SOURCE( b2TaskContext, b2TaskContext ) b2World* b2GetWorldFromId( b2WorldId id ) { B2_ASSERT( 1 <= id.index1 && id.index1 <= B2_MAX_WORLDS ); b2World* world = b2_worlds + ( id.index1 - 1 ); B2_ASSERT( id.index1 == world->worldId + 1 ); B2_ASSERT( id.generation == world->generation ); return world; } b2World* b2GetWorld( int index ) { B2_ASSERT( 0 <= index && index < B2_MAX_WORLDS ); b2World* world = b2_worlds + index; B2_ASSERT( world->worldId == index ); return world; } b2World* b2GetWorldLocked( int index ) { B2_ASSERT( 0 <= index && index < B2_MAX_WORLDS ); b2World* world = b2_worlds + index; B2_ASSERT( world->worldId == index ); if ( world->locked ) { B2_ASSERT( false ); return NULL; } return world; } static void* b2DefaultAddTaskFcn( b2TaskCallback* task, int count, int minRange, void* taskContext, void* userContext ) { B2_UNUSED( minRange, userContext ); task( 0, count, 0, taskContext ); return NULL; } static void b2DefaultFinishTaskFcn( void* userTask, void* userContext ) { B2_UNUSED( userTask, userContext ); } static float b2DefaultFrictionCallback( float frictionA, uint64_t materialA, float frictionB, uint64_t materialB ) { B2_UNUSED( materialA, materialB ); return sqrtf( frictionA * frictionB ); } static float b2DefaultRestitutionCallback( float restitutionA, uint64_t materialA, float restitutionB, uint64_t materialB ) { B2_UNUSED( materialA, materialB ); return b2MaxFloat( restitutionA, restitutionB ); } b2WorldId b2CreateWorld( const b2WorldDef* def ) { _Static_assert( B2_MAX_WORLDS < UINT16_MAX, "B2_MAX_WORLDS limit exceeded" ); B2_CHECK_DEF( def ); int worldId = B2_NULL_INDEX; for ( int i = 0; i < B2_MAX_WORLDS; ++i ) { if ( b2_worlds[i].inUse == false ) { worldId = i; break; } } if ( worldId == B2_NULL_INDEX ) { return (b2WorldId){ 0 }; } b2InitializeContactRegisters(); b2World* world = b2_worlds + worldId; uint16_t generation = world->generation; *world = (b2World){ 0 }; world->worldId = (uint16_t)worldId; world->generation = generation; world->inUse = true; world->arena = b2CreateArenaAllocator( 2048 ); b2CreateBroadPhase( &world->broadPhase ); b2CreateGraph( &world->constraintGraph, 16 ); // pools world->bodyIdPool = b2CreateIdPool(); world->bodies = b2BodyArray_Create( 16 ); world->solverSets = b2SolverSetArray_Create( 8 ); // add empty static, active, and disabled body sets world->solverSetIdPool = b2CreateIdPool(); b2SolverSet set = { 0 }; // static set set.setIndex = b2AllocId( &world->solverSetIdPool ); b2SolverSetArray_Push( &world->solverSets, set ); B2_ASSERT( world->solverSets.data[b2_staticSet].setIndex == b2_staticSet ); // disabled set set.setIndex = b2AllocId( &world->solverSetIdPool ); b2SolverSetArray_Push( &world->solverSets, set ); B2_ASSERT( world->solverSets.data[b2_disabledSet].setIndex == b2_disabledSet ); // awake set set.setIndex = b2AllocId( &world->solverSetIdPool ); b2SolverSetArray_Push( &world->solverSets, set ); B2_ASSERT( world->solverSets.data[b2_awakeSet].setIndex == b2_awakeSet ); world->shapeIdPool = b2CreateIdPool(); world->shapes = b2ShapeArray_Create( 16 ); world->chainIdPool = b2CreateIdPool(); world->chainShapes = b2ChainShapeArray_Create( 4 ); world->contactIdPool = b2CreateIdPool(); world->contacts = b2ContactArray_Create( 16 ); world->jointIdPool = b2CreateIdPool(); world->joints = b2JointArray_Create( 16 ); world->islandIdPool = b2CreateIdPool(); world->islands = b2IslandArray_Create( 8 ); world->sensors = b2SensorArray_Create( 4 ); world->bodyMoveEvents = b2BodyMoveEventArray_Create( 4 ); world->sensorBeginEvents = b2SensorBeginTouchEventArray_Create( 4 ); world->sensorEndEvents[0] = b2SensorEndTouchEventArray_Create( 4 ); world->sensorEndEvents[1] = b2SensorEndTouchEventArray_Create( 4 ); world->contactBeginEvents = b2ContactBeginTouchEventArray_Create( 4 ); world->contactEndEvents[0] = b2ContactEndTouchEventArray_Create( 4 ); world->contactEndEvents[1] = b2ContactEndTouchEventArray_Create( 4 ); world->contactHitEvents = b2ContactHitEventArray_Create( 4 ); world->jointEvents = b2JointEventArray_Create( 4 ); world->endEventArrayIndex = 0; world->stepIndex = 0; world->splitIslandId = B2_NULL_INDEX; world->activeTaskCount = 0; world->taskCount = 0; world->gravity = def->gravity; world->hitEventThreshold = def->hitEventThreshold; world->restitutionThreshold = def->restitutionThreshold; world->maxLinearSpeed = def->maximumLinearSpeed; world->contactSpeed = def->contactSpeed; world->contactHertz = def->contactHertz; world->contactDampingRatio = def->contactDampingRatio; if ( def->frictionCallback == NULL ) { world->frictionCallback = b2DefaultFrictionCallback; } else { world->frictionCallback = def->frictionCallback; } if ( def->restitutionCallback == NULL ) { world->restitutionCallback = b2DefaultRestitutionCallback; } else { world->restitutionCallback = def->restitutionCallback; } world->enableSleep = def->enableSleep; world->locked = false; world->enableWarmStarting = true; world->enableContactSoftening = def->enableContactSoftening; world->enableContinuous = def->enableContinuous; world->enableSpeculative = true; world->userTreeTask = NULL; world->userData = def->userData; if ( def->workerCount > 0 && def->enqueueTask != NULL && def->finishTask != NULL ) { world->workerCount = b2MinInt( def->workerCount, B2_MAX_WORKERS ); world->enqueueTaskFcn = def->enqueueTask; world->finishTaskFcn = def->finishTask; world->userTaskContext = def->userTaskContext; } else { world->workerCount = 1; world->enqueueTaskFcn = b2DefaultAddTaskFcn; world->finishTaskFcn = b2DefaultFinishTaskFcn; world->userTaskContext = NULL; } world->taskContexts = b2TaskContextArray_Create( world->workerCount ); b2TaskContextArray_Resize( &world->taskContexts, world->workerCount ); world->sensorTaskContexts = b2SensorTaskContextArray_Create( world->workerCount ); b2SensorTaskContextArray_Resize( &world->sensorTaskContexts, world->workerCount ); for ( int i = 0; i < world->workerCount; ++i ) { world->taskContexts.data[i].sensorHits = b2SensorHitArray_Create( 8 ); world->taskContexts.data[i].contactStateBitSet = b2CreateBitSet( 1024 ); world->taskContexts.data[i].jointStateBitSet = b2CreateBitSet( 1024 ); world->taskContexts.data[i].enlargedSimBitSet = b2CreateBitSet( 256 ); world->taskContexts.data[i].awakeIslandBitSet = b2CreateBitSet( 256 ); world->sensorTaskContexts.data[i].eventBits = b2CreateBitSet( 128 ); } world->debugBodySet = b2CreateBitSet( 256 ); world->debugJointSet = b2CreateBitSet( 256 ); world->debugContactSet = b2CreateBitSet( 256 ); world->debugIslandSet = b2CreateBitSet( 256 ); // add one to worldId so that 0 represents a null b2WorldId return (b2WorldId){ (uint16_t)( worldId + 1 ), world->generation }; } void b2DestroyWorld( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); b2DestroyBitSet( &world->debugBodySet ); b2DestroyBitSet( &world->debugJointSet ); b2DestroyBitSet( &world->debugContactSet ); b2DestroyBitSet( &world->debugIslandSet ); for ( int i = 0; i < world->workerCount; ++i ) { b2SensorHitArray_Destroy( &world->taskContexts.data[i].sensorHits ); b2DestroyBitSet( &world->taskContexts.data[i].contactStateBitSet ); b2DestroyBitSet( &world->taskContexts.data[i].jointStateBitSet ); b2DestroyBitSet( &world->taskContexts.data[i].enlargedSimBitSet ); b2DestroyBitSet( &world->taskContexts.data[i].awakeIslandBitSet ); b2DestroyBitSet( &world->sensorTaskContexts.data[i].eventBits ); } b2TaskContextArray_Destroy( &world->taskContexts ); b2SensorTaskContextArray_Destroy( &world->sensorTaskContexts ); b2BodyMoveEventArray_Destroy( &world->bodyMoveEvents ); b2SensorBeginTouchEventArray_Destroy( &world->sensorBeginEvents ); b2SensorEndTouchEventArray_Destroy( world->sensorEndEvents + 0 ); b2SensorEndTouchEventArray_Destroy( world->sensorEndEvents + 1 ); b2ContactBeginTouchEventArray_Destroy( &world->contactBeginEvents ); b2ContactEndTouchEventArray_Destroy( world->contactEndEvents + 0 ); b2ContactEndTouchEventArray_Destroy( world->contactEndEvents + 1 ); b2ContactHitEventArray_Destroy( &world->contactHitEvents ); b2JointEventArray_Destroy( &world->jointEvents ); int chainCapacity = world->chainShapes.count; for ( int i = 0; i < chainCapacity; ++i ) { b2ChainShape* chain = world->chainShapes.data + i; if ( chain->id != B2_NULL_INDEX ) { b2FreeChainData( chain ); } else { B2_ASSERT( chain->shapeIndices == NULL ); B2_ASSERT( chain->materials == NULL ); } } int sensorCount = world->sensors.count; for ( int i = 0; i < sensorCount; ++i ) { b2VisitorArray_Destroy( &world->sensors.data[i].hits ); b2VisitorArray_Destroy( &world->sensors.data[i].overlaps1 ); b2VisitorArray_Destroy( &world->sensors.data[i].overlaps2 ); } b2SensorArray_Destroy( &world->sensors ); b2BodyArray_Destroy( &world->bodies ); b2ShapeArray_Destroy( &world->shapes ); b2ChainShapeArray_Destroy( &world->chainShapes ); b2ContactArray_Destroy( &world->contacts ); b2JointArray_Destroy( &world->joints ); b2IslandArray_Destroy( &world->islands ); // Destroy solver sets int setCapacity = world->solverSets.count; for ( int i = 0; i < setCapacity; ++i ) { b2SolverSet* set = world->solverSets.data + i; if ( set->setIndex != B2_NULL_INDEX ) { b2DestroySolverSet( world, i ); } } b2SolverSetArray_Destroy( &world->solverSets ); b2DestroyGraph( &world->constraintGraph ); b2DestroyBroadPhase( &world->broadPhase ); b2DestroyIdPool( &world->bodyIdPool ); b2DestroyIdPool( &world->shapeIdPool ); b2DestroyIdPool( &world->chainIdPool ); b2DestroyIdPool( &world->contactIdPool ); b2DestroyIdPool( &world->jointIdPool ); b2DestroyIdPool( &world->islandIdPool ); b2DestroyIdPool( &world->solverSetIdPool ); b2DestroyArenaAllocator( &world->arena ); // Wipe world but preserve generation uint16_t generation = world->generation; *world = (b2World){ 0 }; world->worldId = 0; world->generation = generation + 1; } static void b2CollideTask( int startIndex, int endIndex, uint32_t threadIndex, void* context ) { b2TracyCZoneNC( collide_task, "Collide", b2_colorDodgerBlue, true ); b2StepContext* stepContext = context; b2World* world = stepContext->world; B2_ASSERT( (int)threadIndex < world->workerCount ); b2TaskContext* taskContext = world->taskContexts.data + threadIndex; b2ContactSim** contactSims = stepContext->contacts; b2Shape* shapes = world->shapes.data; b2Body* bodies = world->bodies.data; B2_ASSERT( startIndex < endIndex ); for ( int contactIndex = startIndex; contactIndex < endIndex; ++contactIndex ) { b2ContactSim* contactSim = contactSims[contactIndex]; int contactId = contactSim->contactId; b2Shape* shapeA = shapes + contactSim->shapeIdA; b2Shape* shapeB = shapes + contactSim->shapeIdB; // Do proxies still overlap? bool overlap = b2AABB_Overlaps( shapeA->fatAABB, shapeB->fatAABB ); if ( overlap == false ) { contactSim->simFlags |= b2_simDisjoint; contactSim->simFlags &= ~b2_simTouchingFlag; b2SetBit( &taskContext->contactStateBitSet, contactId ); } else { bool wasTouching = ( contactSim->simFlags & b2_simTouchingFlag ); // Update contact respecting shape/body order (A,B) b2Body* bodyA = bodies + shapeA->bodyId; b2Body* bodyB = bodies + shapeB->bodyId; b2BodySim* bodySimA = b2GetBodySim( world, bodyA ); b2BodySim* bodySimB = b2GetBodySim( world, bodyB ); // avoid cache misses in b2PrepareContactsTask contactSim->bodySimIndexA = bodyA->setIndex == b2_awakeSet ? bodyA->localIndex : B2_NULL_INDEX; contactSim->invMassA = bodySimA->invMass; contactSim->invIA = bodySimA->invInertia; contactSim->bodySimIndexB = bodyB->setIndex == b2_awakeSet ? bodyB->localIndex : B2_NULL_INDEX; contactSim->invMassB = bodySimB->invMass; contactSim->invIB = bodySimB->invInertia; b2Transform transformA = bodySimA->transform; b2Transform transformB = bodySimB->transform; b2Vec2 centerOffsetA = b2RotateVector( transformA.q, bodySimA->localCenter ); b2Vec2 centerOffsetB = b2RotateVector( transformB.q, bodySimB->localCenter ); // This updates solid contacts bool touching = b2UpdateContact( world, contactSim, shapeA, transformA, centerOffsetA, shapeB, transformB, centerOffsetB ); // State changes that affect island connectivity. Also affects contact events. if ( touching == true && wasTouching == false ) { contactSim->simFlags |= b2_simStartedTouching; b2SetBit( &taskContext->contactStateBitSet, contactId ); } else if ( touching == false && wasTouching == true ) { contactSim->simFlags |= b2_simStoppedTouching; b2SetBit( &taskContext->contactStateBitSet, contactId ); } // To make this work, the time of impact code needs to adjust the target // distance based on the number of TOI events for a body. // if (touching && bodySimB->isFast) //{ // b2Manifold* manifold = &contactSim->manifold; // int pointCount = manifold->pointCount; // for (int i = 0; i < pointCount; ++i) // { // // trick the solver into pushing the fast shapes apart // manifold->points[i].separation -= 0.25f * B2_SPECULATIVE_DISTANCE; // } //} } } b2TracyCZoneEnd( collide_task ); } static void b2UpdateTreesTask( int startIndex, int endIndex, uint32_t threadIndex, void* context ) { B2_UNUSED( startIndex ); B2_UNUSED( endIndex ); B2_UNUSED( threadIndex ); b2TracyCZoneNC( tree_task, "Rebuild BVH", b2_colorFireBrick, true ); b2World* world = context; b2BroadPhase_RebuildTrees( &world->broadPhase ); b2TracyCZoneEnd( tree_task ); } static void b2AddNonTouchingContact( b2World* world, b2Contact* contact, b2ContactSim* contactSim ) { B2_ASSERT( contact->setIndex == b2_awakeSet ); b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); contact->colorIndex = B2_NULL_INDEX; contact->localIndex = set->contactSims.count; b2ContactSim* newContactSim = b2ContactSimArray_Add( &set->contactSims ); memcpy( newContactSim, contactSim, sizeof( b2ContactSim ) ); } static void b2RemoveNonTouchingContact( b2World* world, int setIndex, int localIndex ) { b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, setIndex ); int movedIndex = b2ContactSimArray_RemoveSwap( &set->contactSims, localIndex ); if ( movedIndex != B2_NULL_INDEX ) { b2ContactSim* movedContactSim = set->contactSims.data + localIndex; b2Contact* movedContact = b2ContactArray_Get( &world->contacts, movedContactSim->contactId ); B2_ASSERT( movedContact->setIndex == setIndex ); B2_ASSERT( movedContact->localIndex == movedIndex ); B2_ASSERT( movedContact->colorIndex == B2_NULL_INDEX ); movedContact->localIndex = localIndex; } } // Narrow-phase collision static void b2Collide( b2StepContext* context ) { b2World* world = context->world; B2_ASSERT( world->workerCount > 0 ); b2TracyCZoneNC( collide, "Narrow Phase", b2_colorDodgerBlue, true ); // Task that can be done in parallel with the narrow-phase // - rebuild the collision tree for dynamic and kinematic bodies to keep their query performance good // todo_erin move this to start when contacts are being created world->userTreeTask = world->enqueueTaskFcn( &b2UpdateTreesTask, 1, 1, world, world->userTaskContext ); world->taskCount += 1; world->activeTaskCount += world->userTreeTask == NULL ? 0 : 1; // gather contacts into a single array for easier parallel-for int contactCount = 0; b2GraphColor* graphColors = world->constraintGraph.colors; for ( int i = 0; i < B2_GRAPH_COLOR_COUNT; ++i ) { contactCount += graphColors[i].contactSims.count; } int nonTouchingCount = world->solverSets.data[b2_awakeSet].contactSims.count; contactCount += nonTouchingCount; if ( contactCount == 0 ) { b2TracyCZoneEnd( collide ); return; } b2ContactSim** contactSims = b2AllocateArenaItem( &world->arena, contactCount * sizeof( b2ContactSim* ), "contacts" ); int contactIndex = 0; for ( int i = 0; i < B2_GRAPH_COLOR_COUNT; ++i ) { b2GraphColor* color = graphColors + i; int count = color->contactSims.count; b2ContactSim* base = color->contactSims.data; for ( int j = 0; j < count; ++j ) { contactSims[contactIndex] = base + j; contactIndex += 1; } } { b2ContactSim* base = world->solverSets.data[b2_awakeSet].contactSims.data; for ( int i = 0; i < nonTouchingCount; ++i ) { contactSims[contactIndex] = base + i; contactIndex += 1; } } B2_ASSERT( contactIndex == contactCount ); context->contacts = contactSims; // Contact bit set on ids because contact pointers are unstable as they move between touching and not touching. int contactIdCapacity = b2GetIdCapacity( &world->contactIdPool ); for ( int i = 0; i < world->workerCount; ++i ) { b2SetBitCountAndClear( &world->taskContexts.data[i].contactStateBitSet, contactIdCapacity ); } // Task should take at least 40us on a 4GHz CPU (10K cycles) int minRange = 64; void* userCollideTask = world->enqueueTaskFcn( &b2CollideTask, contactCount, minRange, context, world->userTaskContext ); world->taskCount += 1; if ( userCollideTask != NULL ) { world->finishTaskFcn( userCollideTask, world->userTaskContext ); } b2FreeArenaItem( &world->arena, contactSims ); context->contacts = NULL; contactSims = NULL; // Serially update contact state // todo_erin bring this zone together with island merge b2TracyCZoneNC( contact_state, "Contact State", b2_colorLightSlateGray, true ); // Bitwise OR all contact bits b2BitSet* bitSet = &world->taskContexts.data[0].contactStateBitSet; for ( int i = 1; i < world->workerCount; ++i ) { b2InPlaceUnion( bitSet, &world->taskContexts.data[i].contactStateBitSet ); } b2SolverSet* awakeSet = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); int endEventArrayIndex = world->endEventArrayIndex; const b2Shape* shapes = world->shapes.data; uint16_t worldId = world->worldId; // Process contact state changes. Iterate over set bits for ( uint32_t k = 0; k < bitSet->blockCount; ++k ) { uint64_t bits = bitSet->bits[k]; while ( bits != 0 ) { uint32_t ctz = b2CTZ64( bits ); int contactId = (int)( 64 * k + ctz ); b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); B2_ASSERT( contact->setIndex == b2_awakeSet ); int colorIndex = contact->colorIndex; int localIndex = contact->localIndex; b2ContactSim* contactSim = NULL; if ( colorIndex != B2_NULL_INDEX ) { // contact lives in constraint graph B2_ASSERT( 0 <= colorIndex && colorIndex < B2_GRAPH_COLOR_COUNT ); b2GraphColor* color = graphColors + colorIndex; contactSim = b2ContactSimArray_Get( &color->contactSims, localIndex ); } else { contactSim = b2ContactSimArray_Get( &awakeSet->contactSims, localIndex ); } const b2Shape* shapeA = shapes + contact->shapeIdA; const b2Shape* shapeB = shapes + contact->shapeIdB; b2ShapeId shapeIdA = { shapeA->id + 1, worldId, shapeA->generation }; b2ShapeId shapeIdB = { shapeB->id + 1, worldId, shapeB->generation }; b2ContactId contactFullId = { .index1 = contactId + 1, .world0 = worldId, .padding = 0, .generation = contact->generation, }; uint32_t flags = contact->flags; uint32_t simFlags = contactSim->simFlags; if ( simFlags & b2_simDisjoint ) { // Bounding boxes no longer overlap b2DestroyContact( world, contact, false ); contact = NULL; contactSim = NULL; } else if ( simFlags & b2_simStartedTouching ) { B2_ASSERT( contact->islandId == B2_NULL_INDEX ); if ( flags & b2_contactEnableContactEvents ) { b2ContactBeginTouchEvent event = { shapeIdA, shapeIdB, contactFullId }; b2ContactBeginTouchEventArray_Push( &world->contactBeginEvents, event ); } B2_ASSERT( contactSim->manifold.pointCount > 0 ); B2_ASSERT( contact->setIndex == b2_awakeSet ); // Link first because this wakes colliding bodies and ensures the body sims // are in the correct place. contact->flags |= b2_contactTouchingFlag; b2LinkContact( world, contact ); // Make sure these didn't change B2_ASSERT( contact->colorIndex == B2_NULL_INDEX ); B2_ASSERT( contact->localIndex == localIndex ); // Contact sim pointer may have become orphaned due to awake set growth, // so I just need to refresh it. contactSim = b2ContactSimArray_Get( &awakeSet->contactSims, localIndex ); contactSim->simFlags &= ~b2_simStartedTouching; b2AddContactToGraph( world, contactSim, contact ); b2RemoveNonTouchingContact( world, b2_awakeSet, localIndex ); contactSim = NULL; } else if ( simFlags & b2_simStoppedTouching ) { contactSim->simFlags &= ~b2_simStoppedTouching; contact->flags &= ~b2_contactTouchingFlag; if ( contact->flags & b2_contactEnableContactEvents ) { b2ContactEndTouchEvent event = { shapeIdA, shapeIdB, contactFullId }; b2ContactEndTouchEventArray_Push( world->contactEndEvents + endEventArrayIndex, event ); } B2_ASSERT( contactSim->manifold.pointCount == 0 ); b2UnlinkContact( world, contact ); int bodyIdA = contact->edges[0].bodyId; int bodyIdB = contact->edges[1].bodyId; b2AddNonTouchingContact( world, contact, contactSim ); b2RemoveContactFromGraph( world, bodyIdA, bodyIdB, colorIndex, localIndex ); contact = NULL; contactSim = NULL; } // Clear the smallest set bit bits = bits & ( bits - 1 ); } } b2ValidateSolverSets( world ); b2ValidateContacts( world ); b2TracyCZoneEnd( contact_state ); b2TracyCZoneEnd( collide ); } void b2World_Step( b2WorldId worldId, float timeStep, int subStepCount ) { B2_ASSERT( b2IsValidFloat( timeStep ) ); B2_ASSERT( 0 < subStepCount ); b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { b2TracyCFrame; return; } // Prepare to capture events // Ensure user does not access stale data if there is an early return b2BodyMoveEventArray_Clear( &world->bodyMoveEvents ); b2SensorBeginTouchEventArray_Clear( &world->sensorBeginEvents ); b2ContactBeginTouchEventArray_Clear( &world->contactBeginEvents ); b2ContactHitEventArray_Clear( &world->contactHitEvents ); b2JointEventArray_Clear( &world->jointEvents ); world->profile = (b2Profile){ 0 }; if ( timeStep == 0.0f ) { // Swap end event array buffers world->endEventArrayIndex = 1 - world->endEventArrayIndex; b2SensorEndTouchEventArray_Clear( world->sensorEndEvents + world->endEventArrayIndex ); b2ContactEndTouchEventArray_Clear( world->contactEndEvents + world->endEventArrayIndex ); // todo_erin would be useful to still process collision while paused b2TracyCFrame; return; } b2TracyCZoneNC( world_step, "Step", b2_colorBox2DGreen, true ); world->locked = true; world->activeTaskCount = 0; world->taskCount = 0; uint64_t stepTicks = b2GetTicks(); // Update collision pairs and create contacts { uint64_t pairTicks = b2GetTicks(); b2UpdateBroadPhasePairs( world ); world->profile.pairs = b2GetMilliseconds( pairTicks ); } b2StepContext context = { 0 }; context.world = world; context.dt = timeStep; context.subStepCount = b2MaxInt( 1, subStepCount ); if ( timeStep > 0.0f ) { context.inv_dt = 1.0f / timeStep; context.h = timeStep / context.subStepCount; context.inv_h = context.subStepCount * context.inv_dt; } else { context.inv_dt = 0.0f; context.h = 0.0f; context.inv_h = 0.0f; } world->inv_h = context.inv_h; world->inv_dt = context.inv_dt; // Hertz values get reduced for large time steps float contactHertz = b2MinFloat( world->contactHertz, 0.125f * context.inv_h ); context.contactSoftness = b2MakeSoft( contactHertz, world->contactDampingRatio, context.h ); context.staticSoftness = b2MakeSoft( 2.0f * contactHertz, world->contactDampingRatio, context.h ); context.restitutionThreshold = world->restitutionThreshold; context.maxLinearVelocity = world->maxLinearSpeed; context.enableWarmStarting = world->enableWarmStarting; // Update contacts { uint64_t collideTicks = b2GetTicks(); b2Collide( &context ); world->profile.collide = b2GetMilliseconds( collideTicks ); } // Integrate velocities, solve velocity constraints, and integrate positions. if ( context.dt > 0.0f ) { uint64_t solveTicks = b2GetTicks(); b2Solve( world, &context ); world->profile.solve = b2GetMilliseconds( solveTicks ); } // Update sensors { uint64_t sensorTicks = b2GetTicks(); b2OverlapSensors( world ); world->profile.sensors = b2GetMilliseconds( sensorTicks ); } world->profile.step = b2GetMilliseconds( stepTicks ); B2_ASSERT( b2GetArenaAllocation( &world->arena ) == 0 ); // Ensure stack is large enough b2GrowArena( &world->arena ); // Make sure all tasks that were started were also finished B2_ASSERT( world->activeTaskCount == 0 ); b2TracyCZoneEnd( world_step ); // Swap end event array buffers world->endEventArrayIndex = 1 - world->endEventArrayIndex; b2SensorEndTouchEventArray_Clear( world->sensorEndEvents + world->endEventArrayIndex ); b2ContactEndTouchEventArray_Clear( world->contactEndEvents + world->endEventArrayIndex ); world->locked = false; b2TracyCFrame; } static void b2DrawShape( b2DebugDraw* draw, b2Shape* shape, b2Transform xf, b2HexColor color ) { switch ( shape->type ) { case b2_capsuleShape: { b2Capsule* capsule = &shape->capsule; b2Vec2 p1 = b2TransformPoint( xf, capsule->center1 ); b2Vec2 p2 = b2TransformPoint( xf, capsule->center2 ); draw->DrawSolidCapsuleFcn( p1, p2, capsule->radius, color, draw->context ); } break; case b2_circleShape: { b2Circle* circle = &shape->circle; xf.p = b2TransformPoint( xf, circle->center ); draw->DrawSolidCircleFcn( xf, circle->radius, color, draw->context ); } break; case b2_polygonShape: { b2Polygon* poly = &shape->polygon; draw->DrawSolidPolygonFcn( xf, poly->vertices, poly->count, poly->radius, color, draw->context ); } break; case b2_segmentShape: { b2Segment* segment = &shape->segment; b2Vec2 p1 = b2TransformPoint( xf, segment->point1 ); b2Vec2 p2 = b2TransformPoint( xf, segment->point2 ); draw->DrawLineFcn( p1, p2, color, draw->context ); } break; case b2_chainSegmentShape: { b2Segment* segment = &shape->chainSegment.segment; b2Vec2 p1 = b2TransformPoint( xf, segment->point1 ); b2Vec2 p2 = b2TransformPoint( xf, segment->point2 ); draw->DrawLineFcn( p1, p2, color, draw->context ); draw->DrawPointFcn( p2, 4.0f, color, draw->context ); draw->DrawLineFcn( p1, b2Lerp( p1, p2, 0.1f ), b2_colorPaleGreen, draw->context ); } break; default: break; } } struct DrawContext { b2World* world; b2DebugDraw* draw; }; static bool DrawQueryCallback( int proxyId, uint64_t userData, void* context ) { B2_UNUSED( proxyId ); int shapeId = (int)userData; struct DrawContext* drawContext = context; b2World* world = drawContext->world; b2DebugDraw* draw = drawContext->draw; b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); B2_ASSERT( shape->id == shapeId ); b2SetBit( &world->debugBodySet, shape->bodyId ); if ( draw->drawShapes ) { b2Body* body = b2BodyArray_Get( &world->bodies, shape->bodyId ); b2BodySim* bodySim = b2GetBodySim( world, body ); b2HexColor color; if ( shape->material.customColor != 0 ) { color = shape->material.customColor; } else if ( body->type == b2_dynamicBody && body->mass == 0.0f ) { // Bad body color = b2_colorRed; } else if ( body->setIndex == b2_disabledSet ) { color = b2_colorSlateGray; } else if ( shape->sensorIndex != B2_NULL_INDEX ) { color = b2_colorWheat; } else if ( body->flags & b2_hadTimeOfImpact ) { color = b2_colorLime; } else if ( ( bodySim->flags & b2_isBullet ) && body->setIndex == b2_awakeSet ) { color = b2_colorTurquoise; } else if ( body->flags & b2_isSpeedCapped ) { color = b2_colorYellow; } else if ( bodySim->flags & b2_isFast ) { color = b2_colorSalmon; } else if ( body->type == b2_staticBody ) { color = b2_colorPaleGreen; } else if ( body->type == b2_kinematicBody ) { color = b2_colorRoyalBlue; } else if ( body->setIndex == b2_awakeSet ) { color = b2_colorPink; } else { color = b2_colorGray; } b2DrawShape( draw, shape, bodySim->transform, color ); } if ( draw->drawBounds ) { b2AABB aabb = shape->fatAABB; b2Vec2 vs[4] = { { aabb.lowerBound.x, aabb.lowerBound.y }, { aabb.upperBound.x, aabb.lowerBound.y }, { aabb.upperBound.x, aabb.upperBound.y }, { aabb.lowerBound.x, aabb.upperBound.y } }; draw->DrawPolygonFcn( vs, 4, b2_colorGold, draw->context ); } return true; } // todo this has varying order for moving shapes, causing flicker when overlapping shapes are moving // solution: display order by shape id modulus 3, keep 3 buckets in GLSolid* and flush in 3 passes. void b2World_Draw( b2WorldId worldId, b2DebugDraw* draw ) { b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return; } B2_ASSERT( b2IsValidAABB( draw->drawingBounds ) ); const float k_axisScale = 0.3f; b2HexColor speculativeColor = b2_colorGainsboro; b2HexColor addColor = b2_colorGreen; b2HexColor persistColor = b2_colorBlue; b2HexColor normalColor = b2_colorDimGray; b2HexColor impulseColor = b2_colorMagenta; b2HexColor frictionColor = b2_colorYellow; int bodyCapacity = b2GetIdCapacity( &world->bodyIdPool ); b2SetBitCountAndClear( &world->debugBodySet, bodyCapacity ); int jointCapacity = b2GetIdCapacity( &world->jointIdPool ); b2SetBitCountAndClear( &world->debugJointSet, jointCapacity ); int contactCapacity = b2GetIdCapacity( &world->contactIdPool ); b2SetBitCountAndClear( &world->debugContactSet, contactCapacity ); int islandCapacity = b2GetIdCapacity( &world->islandIdPool ); b2SetBitCountAndClear( &world->debugIslandSet, islandCapacity ); struct DrawContext drawContext = { world, draw }; for ( int i = 0; i < b2_bodyTypeCount; ++i ) { b2DynamicTree_QueryAll( world->broadPhase.trees + i, draw->drawingBounds, DrawQueryCallback, &drawContext ); } uint32_t wordCount = world->debugBodySet.blockCount; uint64_t* bits = world->debugBodySet.bits; for ( uint32_t k = 0; k < wordCount; ++k ) { uint64_t word = bits[k]; while ( word != 0 ) { uint32_t ctz = b2CTZ64( word ); uint32_t bodyId = 64 * k + ctz; b2Body* body = b2BodyArray_Get( &world->bodies, bodyId ); if ( draw->drawBodyNames && body->name[0] != 0 ) { b2Vec2 offset = { 0.1f, 0.1f }; b2BodySim* bodySim = b2GetBodySim( world, body ); b2Transform transform = { bodySim->center, bodySim->transform.q }; b2Vec2 p = b2TransformPoint( transform, offset ); draw->DrawStringFcn( p, body->name, b2_colorBlueViolet, draw->context ); } if ( draw->drawMass && body->type == b2_dynamicBody ) { b2Vec2 offset = { 0.1f, 0.1f }; b2BodySim* bodySim = b2GetBodySim( world, body ); b2Transform transform = { bodySim->center, bodySim->transform.q }; draw->DrawLineFcn( bodySim->center0, bodySim->center, b2_colorWhiteSmoke, draw->context ); draw->DrawTransformFcn( transform, draw->context ); b2Vec2 p = b2TransformPoint( transform, offset ); char buffer[32]; snprintf( buffer, 32, " %.2f", body->mass ); draw->DrawStringFcn( p, buffer, b2_colorWhite, draw->context ); } if ( draw->drawJoints ) { int jointKey = body->headJointKey; while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; b2Joint* joint = b2JointArray_Get( &world->joints, jointId ); // avoid double draw if ( b2GetBit( &world->debugJointSet, jointId ) == false ) { b2DrawJoint( draw, world, joint ); b2SetBit( &world->debugJointSet, jointId ); } jointKey = joint->edges[edgeIndex].nextKey; } } const float linearSlop = B2_LINEAR_SLOP; if ( draw->drawContactPoints && body->type == b2_dynamicBody ) { int contactKey = body->headContactKey; while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); contactKey = contact->edges[edgeIndex].nextKey; // avoid double draw if ( b2GetBit( &world->debugContactSet, contactId ) == false ) { b2ContactSim* contactSim = b2GetContactSim( world, contact ); int pointCount = contactSim->manifold.pointCount; b2Vec2 normal = contactSim->manifold.normal; char buffer[32]; for ( int j = 0; j < pointCount; ++j ) { b2ManifoldPoint* point = contactSim->manifold.points + j; if ( draw->drawGraphColors && contact->colorIndex != B2_NULL_INDEX ) { // graph color float pointSize = contact->colorIndex == B2_OVERFLOW_INDEX ? 7.5f : 5.0f; draw->DrawPointFcn( point->point, pointSize, b2_graphColors[contact->colorIndex], draw->context ); // m_context->draw.DrawString(point->position, "%d", point->color); } else if ( point->separation > linearSlop ) { // Speculative draw->DrawPointFcn( point->point, 5.0f, speculativeColor, draw->context ); } else if ( point->persisted == false ) { // Add draw->DrawPointFcn( point->point, 10.0f, addColor, draw->context ); } else if ( point->persisted == true ) { // Persist draw->DrawPointFcn( point->point, 5.0f, persistColor, draw->context ); } if ( draw->drawContactNormals ) { b2Vec2 p1 = point->point; b2Vec2 p2 = b2MulAdd( p1, k_axisScale, normal ); draw->DrawLineFcn( p1, p2, normalColor, draw->context ); } else if ( draw->drawContactForces ) { // multiply by one-half due to relax iteration float force = 0.5f * point->totalNormalImpulse * world->inv_dt; b2Vec2 p1 = point->point; b2Vec2 p2 = b2MulAdd( p1, draw->forceScale * force, normal ); draw->DrawLineFcn( p1, p2, impulseColor, draw->context ); snprintf( buffer, B2_ARRAY_COUNT( buffer ), "%.1f", force ); draw->DrawStringFcn( p1, buffer, b2_colorWhite, draw->context ); } if ( draw->drawContactFeatures ) { snprintf( buffer, B2_ARRAY_COUNT( buffer ), "%d", point->id ); draw->DrawStringFcn( point->point, buffer, b2_colorOrange, draw->context ); } if ( draw->drawFrictionForces ) { float force = 0.5f * point->tangentImpulse * world->inv_h; b2Vec2 tangent = b2RightPerp( normal ); b2Vec2 p1 = point->point; b2Vec2 p2 = b2MulAdd( p1, draw->forceScale * force, tangent ); draw->DrawLineFcn( p1, p2, frictionColor, draw->context ); snprintf( buffer, B2_ARRAY_COUNT( buffer ), "%.1f", force ); draw->DrawStringFcn( p1, buffer, b2_colorWhite, draw->context ); } } b2SetBit( &world->debugContactSet, contactId ); } contactKey = contact->edges[edgeIndex].nextKey; } } if ( draw->drawIslands ) { int islandId = body->islandId; if ( islandId != B2_NULL_INDEX && b2GetBit( &world->debugIslandSet, islandId ) == false ) { b2Island* island = world->islands.data + islandId; if ( island->setIndex == B2_NULL_INDEX ) { continue; } int shapeCount = 0; b2AABB aabb = { .lowerBound = { FLT_MAX, FLT_MAX }, .upperBound = { -FLT_MAX, -FLT_MAX }, }; int islandBodyId = island->headBody; while ( islandBodyId != B2_NULL_INDEX ) { b2Body* islandBody = b2BodyArray_Get( &world->bodies, islandBodyId ); int shapeId = islandBody->headShapeId; while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); aabb = b2AABB_Union( aabb, shape->fatAABB ); shapeCount += 1; shapeId = shape->nextShapeId; } islandBodyId = islandBody->islandNext; } if ( shapeCount > 0 ) { b2Vec2 vs[4] = { { aabb.lowerBound.x, aabb.lowerBound.y }, { aabb.upperBound.x, aabb.lowerBound.y }, { aabb.upperBound.x, aabb.upperBound.y }, { aabb.lowerBound.x, aabb.upperBound.y } }; draw->DrawPolygonFcn( vs, 4, b2_colorOrangeRed, draw->context ); } b2SetBit( &world->debugIslandSet, islandId ); } } // Clear the smallest set bit word = word & ( word - 1 ); } } } b2BodyEvents b2World_GetBodyEvents( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return (b2BodyEvents){ 0 }; } int count = world->bodyMoveEvents.count; b2BodyEvents events = { world->bodyMoveEvents.data, count }; return events; } b2SensorEvents b2World_GetSensorEvents( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return (b2SensorEvents){ 0 }; } // Careful to use previous buffer int endEventArrayIndex = 1 - world->endEventArrayIndex; int beginCount = world->sensorBeginEvents.count; int endCount = world->sensorEndEvents[endEventArrayIndex].count; b2SensorEvents events = { .beginEvents = world->sensorBeginEvents.data, .endEvents = world->sensorEndEvents[endEventArrayIndex].data, .beginCount = beginCount, .endCount = endCount, }; return events; } b2ContactEvents b2World_GetContactEvents( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return (b2ContactEvents){ 0 }; } // Careful to use previous buffer int endEventArrayIndex = 1 - world->endEventArrayIndex; int beginCount = world->contactBeginEvents.count; int endCount = world->contactEndEvents[endEventArrayIndex].count; int hitCount = world->contactHitEvents.count; b2ContactEvents events = { .beginEvents = world->contactBeginEvents.data, .endEvents = world->contactEndEvents[endEventArrayIndex].data, .hitEvents = world->contactHitEvents.data, .beginCount = beginCount, .endCount = endCount, .hitCount = hitCount, }; return events; } b2JointEvents b2World_GetJointEvents( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return (b2JointEvents){ 0 }; } int count = world->jointEvents.count; b2JointEvents events = { world->jointEvents.data, count }; return events; } bool b2World_IsValid( b2WorldId id ) { if ( id.index1 < 1 || B2_MAX_WORLDS < id.index1 ) { return false; } b2World* world = b2_worlds + ( id.index1 - 1 ); if ( world->worldId != id.index1 - 1 ) { // world is not allocated return false; } return id.generation == world->generation; } bool b2Body_IsValid( b2BodyId id ) { if ( B2_MAX_WORLDS <= id.world0 ) { // invalid world return false; } b2World* world = b2_worlds + id.world0; if ( world->worldId != id.world0 ) { // world is free return false; } if ( id.index1 < 1 || world->bodies.count < id.index1 ) { // invalid index return false; } b2Body* body = world->bodies.data + ( id.index1 - 1 ); if ( body->setIndex == B2_NULL_INDEX ) { // this was freed return false; } B2_ASSERT( body->localIndex != B2_NULL_INDEX ); if ( body->generation != id.generation ) { // this id is orphaned return false; } return true; } bool b2Shape_IsValid( b2ShapeId id ) { if ( B2_MAX_WORLDS <= id.world0 ) { return false; } b2World* world = b2_worlds + id.world0; if ( world->worldId != id.world0 ) { // world is free return false; } int shapeId = id.index1 - 1; if ( shapeId < 0 || world->shapes.count <= shapeId ) { return false; } b2Shape* shape = world->shapes.data + shapeId; if ( shape->id == B2_NULL_INDEX ) { // shape is free return false; } B2_ASSERT( shape->id == shapeId ); return id.generation == shape->generation; } bool b2Chain_IsValid( b2ChainId id ) { if ( B2_MAX_WORLDS <= id.world0 ) { return false; } b2World* world = b2_worlds + id.world0; if ( world->worldId != id.world0 ) { // world is free return false; } int chainId = id.index1 - 1; if ( chainId < 0 || world->chainShapes.count <= chainId ) { return false; } b2ChainShape* chain = world->chainShapes.data + chainId; if ( chain->id == B2_NULL_INDEX ) { // chain is free return false; } B2_ASSERT( chain->id == chainId ); return id.generation == chain->generation; } bool b2Joint_IsValid( b2JointId id ) { if ( B2_MAX_WORLDS <= id.world0 ) { return false; } b2World* world = b2_worlds + id.world0; if ( world->worldId != id.world0 ) { // world is free return false; } int jointId = id.index1 - 1; if ( jointId < 0 || world->joints.count <= jointId ) { return false; } b2Joint* joint = world->joints.data + jointId; if ( joint->jointId == B2_NULL_INDEX ) { // joint is free return false; } B2_ASSERT( joint->jointId == jointId ); return id.generation == joint->generation; } bool b2Contact_IsValid( b2ContactId id ) { if ( B2_MAX_WORLDS <= id.world0 ) { return false; } b2World* world = b2_worlds + id.world0; if ( world->worldId != id.world0 ) { // world is free return false; } int contactId = id.index1 - 1; if ( contactId < 0 || world->contacts.count <= contactId ) { return false; } b2Contact* contact = world->contacts.data + contactId; if ( contact->contactId == B2_NULL_INDEX ) { // contact is free return false; } B2_ASSERT( contact->contactId == contactId ); return id.generation == contact->generation; } void b2World_EnableSleeping( b2WorldId worldId, bool flag ) { b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return; } if ( flag == world->enableSleep ) { return; } world->enableSleep = flag; if ( flag == false ) { int setCount = world->solverSets.count; for ( int i = b2_firstSleepingSet; i < setCount; ++i ) { b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, i ); if ( set->bodySims.count > 0 ) { b2WakeSolverSet( world, i ); } } } } bool b2World_IsSleepingEnabled( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); return world->enableSleep; } void b2World_EnableWarmStarting( b2WorldId worldId, bool flag ) { b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return; } world->enableWarmStarting = flag; } bool b2World_IsWarmStartingEnabled( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); return world->enableWarmStarting; } int b2World_GetAwakeBodyCount( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); b2SolverSet* awakeSet = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); return awakeSet->bodySims.count; } void b2World_EnableContinuous( b2WorldId worldId, bool flag ) { b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return; } world->enableContinuous = flag; } bool b2World_IsContinuousEnabled( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); return world->enableContinuous; } void b2World_SetRestitutionThreshold( b2WorldId worldId, float value ) { b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return; } world->restitutionThreshold = b2ClampFloat( value, 0.0f, FLT_MAX ); } float b2World_GetRestitutionThreshold( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); return world->restitutionThreshold; } void b2World_SetHitEventThreshold( b2WorldId worldId, float value ) { b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return; } world->hitEventThreshold = b2ClampFloat( value, 0.0f, FLT_MAX ); } float b2World_GetHitEventThreshold( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); return world->hitEventThreshold; } void b2World_SetContactTuning( b2WorldId worldId, float hertz, float dampingRatio, float pushSpeed ) { b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return; } world->contactHertz = b2ClampFloat( hertz, 0.0f, FLT_MAX ); world->contactDampingRatio = b2ClampFloat( dampingRatio, 0.0f, FLT_MAX ); world->contactSpeed = b2ClampFloat( pushSpeed, 0.0f, FLT_MAX ); } void b2World_SetMaximumLinearSpeed( b2WorldId worldId, float maximumLinearSpeed ) { B2_ASSERT( b2IsValidFloat( maximumLinearSpeed ) && maximumLinearSpeed > 0.0f ); b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return; } world->maxLinearSpeed = maximumLinearSpeed; } float b2World_GetMaximumLinearSpeed( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); return world->maxLinearSpeed; } b2Profile b2World_GetProfile( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); return world->profile; } b2Counters b2World_GetCounters( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); b2Counters s = { 0 }; s.bodyCount = b2GetIdCount( &world->bodyIdPool ); s.shapeCount = b2GetIdCount( &world->shapeIdPool ); s.contactCount = b2GetIdCount( &world->contactIdPool ); s.jointCount = b2GetIdCount( &world->jointIdPool ); s.islandCount = b2GetIdCount( &world->islandIdPool ); b2DynamicTree* staticTree = world->broadPhase.trees + b2_staticBody; s.staticTreeHeight = b2DynamicTree_GetHeight( staticTree ); b2DynamicTree* dynamicTree = world->broadPhase.trees + b2_dynamicBody; b2DynamicTree* kinematicTree = world->broadPhase.trees + b2_kinematicBody; s.treeHeight = b2MaxInt( b2DynamicTree_GetHeight( dynamicTree ), b2DynamicTree_GetHeight( kinematicTree ) ); s.stackUsed = b2GetMaxArenaAllocation( &world->arena ); s.byteCount = b2GetByteCount(); s.taskCount = world->taskCount; for ( int i = 0; i < B2_GRAPH_COLOR_COUNT; ++i ) { s.colorCounts[i] = world->constraintGraph.colors[i].contactSims.count + world->constraintGraph.colors[i].jointSims.count; } return s; } void b2World_SetUserData( b2WorldId worldId, void* userData ) { b2World* world = b2GetWorldFromId( worldId ); world->userData = userData; } void* b2World_GetUserData( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); return world->userData; } void b2World_SetFrictionCallback( b2WorldId worldId, b2FrictionCallback* callback ) { b2World* world = b2GetWorldFromId( worldId ); if ( world->locked ) { return; } if ( callback != NULL ) { world->frictionCallback = callback; } else { world->frictionCallback = b2DefaultFrictionCallback; } } void b2World_SetRestitutionCallback( b2WorldId worldId, b2RestitutionCallback* callback ) { b2World* world = b2GetWorldFromId( worldId ); if ( world->locked ) { return; } if ( callback != NULL ) { world->restitutionCallback = callback; } else { world->restitutionCallback = b2DefaultRestitutionCallback; } } void b2World_DumpMemoryStats( b2WorldId worldId ) { FILE* file = fopen( "box2d_memory.txt", "w" ); if ( file == NULL ) { return; } b2World* world = b2GetWorldFromId( worldId ); // id pools fprintf( file, "id pools\n" ); fprintf( file, "body ids: %d\n", b2GetIdBytes( &world->bodyIdPool ) ); fprintf( file, "solver set ids: %d\n", b2GetIdBytes( &world->solverSetIdPool ) ); fprintf( file, "joint ids: %d\n", b2GetIdBytes( &world->jointIdPool ) ); fprintf( file, "contact ids: %d\n", b2GetIdBytes( &world->contactIdPool ) ); fprintf( file, "island ids: %d\n", b2GetIdBytes( &world->islandIdPool ) ); fprintf( file, "shape ids: %d\n", b2GetIdBytes( &world->shapeIdPool ) ); fprintf( file, "chain ids: %d\n", b2GetIdBytes( &world->chainIdPool ) ); fprintf( file, "\n" ); // world arrays fprintf( file, "world arrays\n" ); fprintf( file, "bodies: %d\n", b2BodyArray_ByteCount( &world->bodies ) ); fprintf( file, "solver sets: %d\n", b2SolverSetArray_ByteCount( &world->solverSets ) ); fprintf( file, "joints: %d\n", b2JointArray_ByteCount( &world->joints ) ); fprintf( file, "contacts: %d\n", b2ContactArray_ByteCount( &world->contacts ) ); fprintf( file, "islands: %d\n", b2IslandArray_ByteCount( &world->islands ) ); fprintf( file, "shapes: %d\n", b2ShapeArray_ByteCount( &world->shapes ) ); fprintf( file, "chains: %d\n", b2ChainShapeArray_ByteCount( &world->chainShapes ) ); fprintf( file, "\n" ); // broad-phase fprintf( file, "broad-phase\n" ); fprintf( file, "static tree: %d\n", b2DynamicTree_GetByteCount( world->broadPhase.trees + b2_staticBody ) ); fprintf( file, "kinematic tree: %d\n", b2DynamicTree_GetByteCount( world->broadPhase.trees + b2_kinematicBody ) ); fprintf( file, "dynamic tree: %d\n", b2DynamicTree_GetByteCount( world->broadPhase.trees + b2_dynamicBody ) ); b2HashSet* moveSet = &world->broadPhase.moveSet; fprintf( file, "moveSet: %d (%u, %u)\n", b2GetHashSetBytes( moveSet ), moveSet->count, moveSet->capacity ); fprintf( file, "moveArray: %d\n", b2IntArray_ByteCount( &world->broadPhase.moveArray ) ); b2HashSet* pairSet = &world->broadPhase.pairSet; fprintf( file, "pairSet: %d (%u, %u)\n", b2GetHashSetBytes( pairSet ), pairSet->count, pairSet->capacity ); fprintf( file, "\n" ); // solver sets int bodySimCapacity = 0; int bodyStateCapacity = 0; int jointSimCapacity = 0; int contactSimCapacity = 0; int islandSimCapacity = 0; int solverSetCapacity = world->solverSets.count; for ( int i = 0; i < solverSetCapacity; ++i ) { b2SolverSet* set = world->solverSets.data + i; if ( set->setIndex == B2_NULL_INDEX ) { continue; } bodySimCapacity += set->bodySims.capacity; bodyStateCapacity += set->bodyStates.capacity; jointSimCapacity += set->jointSims.capacity; contactSimCapacity += set->contactSims.capacity; islandSimCapacity += set->islandSims.capacity; } fprintf( file, "solver sets\n" ); fprintf( file, "body sim: %d\n", bodySimCapacity * (int)sizeof( b2BodySim ) ); fprintf( file, "body state: %d\n", bodyStateCapacity * (int)sizeof( b2BodyState ) ); fprintf( file, "joint sim: %d\n", jointSimCapacity * (int)sizeof( b2JointSim ) ); fprintf( file, "contact sim: %d\n", contactSimCapacity * (int)sizeof( b2ContactSim ) ); fprintf( file, "island sim: %d\n", islandSimCapacity * (int)sizeof( islandSimCapacity ) ); fprintf( file, "\n" ); // constraint graph int bodyBitSetBytes = 0; contactSimCapacity = 0; jointSimCapacity = 0; for ( int i = 0; i < B2_GRAPH_COLOR_COUNT; ++i ) { b2GraphColor* c = world->constraintGraph.colors + i; bodyBitSetBytes += b2GetBitSetBytes( &c->bodySet ); contactSimCapacity += c->contactSims.capacity; jointSimCapacity += c->jointSims.capacity; } fprintf( file, "constraint graph\n" ); fprintf( file, "body bit sets: %d\n", bodyBitSetBytes ); fprintf( file, "joint sim: %d\n", jointSimCapacity * (int)sizeof( b2JointSim ) ); fprintf( file, "contact sim: %d\n", contactSimCapacity * (int)sizeof( b2ContactSim ) ); fprintf( file, "\n" ); // stack allocator fprintf( file, "stack allocator: %d\n\n", world->arena.capacity ); // chain shapes // todo fclose( file ); } typedef struct WorldQueryContext { b2World* world; b2OverlapResultFcn* fcn; b2QueryFilter filter; void* userContext; } WorldQueryContext; static bool TreeQueryCallback( int proxyId, uint64_t userData, void* context ) { B2_UNUSED( proxyId ); int shapeId = (int)userData; WorldQueryContext* worldContext = context; b2World* world = worldContext->world; b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); if ( b2ShouldQueryCollide( shape->filter, worldContext->filter ) == false ) { return true; } b2ShapeId id = { shapeId + 1, world->worldId, shape->generation }; bool result = worldContext->fcn( id, worldContext->userContext ); return result; } b2TreeStats b2World_OverlapAABB( b2WorldId worldId, b2AABB aabb, b2QueryFilter filter, b2OverlapResultFcn* fcn, void* context ) { b2TreeStats treeStats = { 0 }; b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return treeStats; } B2_ASSERT( b2IsValidAABB( aabb ) ); WorldQueryContext worldContext = { world, fcn, filter, context }; for ( int i = 0; i < b2_bodyTypeCount; ++i ) { b2TreeStats treeResult = b2DynamicTree_Query( world->broadPhase.trees + i, aabb, filter.maskBits, TreeQueryCallback, &worldContext ); treeStats.nodeVisits += treeResult.nodeVisits; treeStats.leafVisits += treeResult.leafVisits; } return treeStats; } typedef struct WorldOverlapContext { b2World* world; b2OverlapResultFcn* fcn; b2QueryFilter filter; const b2ShapeProxy* proxy; void* userContext; } WorldOverlapContext; static bool TreeOverlapCallback( int proxyId, uint64_t userData, void* context ) { B2_UNUSED( proxyId ); int shapeId = (int)userData; WorldOverlapContext* worldContext = context; b2World* world = worldContext->world; b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); if ( b2ShouldQueryCollide( shape->filter, worldContext->filter ) == false ) { return true; } b2Body* body = b2BodyArray_Get( &world->bodies, shape->bodyId ); b2Transform transform = b2GetBodyTransformQuick( world, body ); b2DistanceInput input; input.proxyA = *worldContext->proxy; input.proxyB = b2MakeShapeDistanceProxy( shape ); input.transformA = b2Transform_identity; input.transformB = transform; input.useRadii = true; b2SimplexCache cache = { 0 }; b2DistanceOutput output = b2ShapeDistance( &input, &cache, NULL, 0 ); float tolerance = 0.1f * B2_LINEAR_SLOP; if ( output.distance > tolerance ) { return true; } b2ShapeId id = { shape->id + 1, world->worldId, shape->generation }; bool result = worldContext->fcn( id, worldContext->userContext ); return result; } b2TreeStats b2World_OverlapShape( b2WorldId worldId, const b2ShapeProxy* proxy, b2QueryFilter filter, b2OverlapResultFcn* fcn, void* context ) { b2TreeStats treeStats = { 0 }; b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return treeStats; } b2AABB aabb = b2MakeAABB( proxy->points, proxy->count, proxy->radius ); WorldOverlapContext worldContext = { world, fcn, filter, proxy, context, }; for ( int i = 0; i < b2_bodyTypeCount; ++i ) { b2TreeStats treeResult = b2DynamicTree_Query( world->broadPhase.trees + i, aabb, filter.maskBits, TreeOverlapCallback, &worldContext ); treeStats.nodeVisits += treeResult.nodeVisits; treeStats.leafVisits += treeResult.leafVisits; } return treeStats; } typedef struct WorldRayCastContext { b2World* world; b2CastResultFcn* fcn; b2QueryFilter filter; float fraction; void* userContext; } WorldRayCastContext; static float RayCastCallback( const b2RayCastInput* input, int proxyId, uint64_t userData, void* context ) { B2_UNUSED( proxyId ); int shapeId = (int)userData; WorldRayCastContext* worldContext = context; b2World* world = worldContext->world; b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); if ( b2ShouldQueryCollide( shape->filter, worldContext->filter ) == false ) { return input->maxFraction; } b2Body* body = b2BodyArray_Get( &world->bodies, shape->bodyId ); b2Transform transform = b2GetBodyTransformQuick( world, body ); b2CastOutput output = b2RayCastShape( input, shape, transform ); if ( output.hit ) { b2ShapeId id = { shapeId + 1, world->worldId, shape->generation }; float fraction = worldContext->fcn( id, output.point, output.normal, output.fraction, worldContext->userContext ); // The user may return -1 to skip this shape if ( 0.0f <= fraction && fraction <= 1.0f ) { worldContext->fraction = fraction; } return fraction; } return input->maxFraction; } b2TreeStats b2World_CastRay( b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter, b2CastResultFcn* fcn, void* context ) { b2TreeStats treeStats = { 0 }; b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return treeStats; } B2_ASSERT( b2IsValidVec2( origin ) ); B2_ASSERT( b2IsValidVec2( translation ) ); b2RayCastInput input = { origin, translation, 1.0f }; WorldRayCastContext worldContext = { world, fcn, filter, 1.0f, context }; for ( int i = 0; i < b2_bodyTypeCount; ++i ) { b2TreeStats treeResult = b2DynamicTree_RayCast( world->broadPhase.trees + i, &input, filter.maskBits, RayCastCallback, &worldContext ); treeStats.nodeVisits += treeResult.nodeVisits; treeStats.leafVisits += treeResult.leafVisits; if ( worldContext.fraction == 0.0f ) { return treeStats; } input.maxFraction = worldContext.fraction; } return treeStats; } // This callback finds the closest hit. This is the most common callback used in games. static float b2RayCastClosestFcn( b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context ) { // Ignore initial overlap if ( fraction == 0.0f ) { return -1.0f; } b2RayResult* rayResult = (b2RayResult*)context; rayResult->shapeId = shapeId; rayResult->point = point; rayResult->normal = normal; rayResult->fraction = fraction; rayResult->hit = true; return fraction; } b2RayResult b2World_CastRayClosest( b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter ) { b2RayResult result = { 0 }; b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return result; } B2_ASSERT( b2IsValidVec2( origin ) ); B2_ASSERT( b2IsValidVec2( translation ) ); b2RayCastInput input = { origin, translation, 1.0f }; WorldRayCastContext worldContext = { world, b2RayCastClosestFcn, filter, 1.0f, &result }; for ( int i = 0; i < b2_bodyTypeCount; ++i ) { b2TreeStats treeResult = b2DynamicTree_RayCast( world->broadPhase.trees + i, &input, filter.maskBits, RayCastCallback, &worldContext ); result.nodeVisits += treeResult.nodeVisits; result.leafVisits += treeResult.leafVisits; if ( worldContext.fraction == 0.0f ) { return result; } input.maxFraction = worldContext.fraction; } return result; } static float ShapeCastCallback( const b2ShapeCastInput* input, int proxyId, uint64_t userData, void* context ) { B2_UNUSED( proxyId ); int shapeId = (int)userData; WorldRayCastContext* worldContext = context; b2World* world = worldContext->world; b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); if ( b2ShouldQueryCollide( shape->filter, worldContext->filter ) == false ) { return input->maxFraction; } b2Body* body = b2BodyArray_Get( &world->bodies, shape->bodyId ); b2Transform transform = b2GetBodyTransformQuick( world, body ); b2CastOutput output = b2ShapeCastShape( input, shape, transform ); if ( output.hit ) { b2ShapeId id = { shapeId + 1, world->worldId, shape->generation }; float fraction = worldContext->fcn( id, output.point, output.normal, output.fraction, worldContext->userContext ); // The user may return -1 to skip this shape if ( 0.0f <= fraction && fraction <= 1.0f ) { worldContext->fraction = fraction; } return fraction; } return input->maxFraction; } b2TreeStats b2World_CastShape( b2WorldId worldId, const b2ShapeProxy* proxy, b2Vec2 translation, b2QueryFilter filter, b2CastResultFcn* fcn, void* context ) { b2TreeStats treeStats = { 0 }; b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return treeStats; } B2_ASSERT( b2IsValidVec2( translation ) ); b2ShapeCastInput input = { 0 }; input.proxy = *proxy; input.translation = translation; input.maxFraction = 1.0f; WorldRayCastContext worldContext = { world, fcn, filter, 1.0f, context }; for ( int i = 0; i < b2_bodyTypeCount; ++i ) { b2TreeStats treeResult = b2DynamicTree_ShapeCast( world->broadPhase.trees + i, &input, filter.maskBits, ShapeCastCallback, &worldContext ); treeStats.nodeVisits += treeResult.nodeVisits; treeStats.leafVisits += treeResult.leafVisits; if ( worldContext.fraction == 0.0f ) { return treeStats; } input.maxFraction = worldContext.fraction; } return treeStats; } typedef struct b2MoverContext { b2World* world; b2QueryFilter filter; b2ShapeProxy proxy; b2Transform transform; void* userContext; } b2CharacterCallbackContext; typedef struct WorldMoverCastContext { b2World* world; b2QueryFilter filter; float fraction; } WorldMoverCastContext; static float MoverCastCallback( const b2ShapeCastInput* input, int proxyId, uint64_t userData, void* context ) { B2_UNUSED( proxyId ); int shapeId = (int)userData; WorldMoverCastContext* worldContext = context; b2World* world = worldContext->world; b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); if ( b2ShouldQueryCollide( shape->filter, worldContext->filter ) == false ) { return worldContext->fraction; } b2Body* body = b2BodyArray_Get( &world->bodies, shape->bodyId ); b2Transform transform = b2GetBodyTransformQuick( world, body ); b2CastOutput output = b2ShapeCastShape( input, shape, transform ); if ( output.fraction == 0.0f ) { // Ignore overlapping shapes return worldContext->fraction; } worldContext->fraction = output.fraction; return output.fraction; } float b2World_CastMover( b2WorldId worldId, const b2Capsule* mover, b2Vec2 translation, b2QueryFilter filter ) { B2_ASSERT( b2IsValidVec2( translation ) ); B2_ASSERT( mover->radius > 2.0f * B2_LINEAR_SLOP ); b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return 1.0f; } b2ShapeCastInput input = { 0 }; input.proxy.points[0] = mover->center1; input.proxy.points[1] = mover->center2; input.proxy.count = 2; input.proxy.radius = mover->radius; input.translation = translation; input.maxFraction = 1.0f; input.canEncroach = true; WorldMoverCastContext worldContext = { world, filter, 1.0f }; for ( int i = 0; i < b2_bodyTypeCount; ++i ) { b2DynamicTree_ShapeCast( world->broadPhase.trees + i, &input, filter.maskBits, MoverCastCallback, &worldContext ); if ( worldContext.fraction == 0.0f ) { return 0.0f; } input.maxFraction = worldContext.fraction; } return worldContext.fraction; } typedef struct WorldMoverContext { b2World* world; b2PlaneResultFcn* fcn; b2QueryFilter filter; b2Capsule mover; void* userContext; } WorldMoverContext; static bool TreeCollideCallback( int proxyId, uint64_t userData, void* context ) { B2_UNUSED( proxyId ); int shapeId = (int)userData; WorldMoverContext* worldContext = (WorldMoverContext*)context; b2World* world = worldContext->world; b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); if ( b2ShouldQueryCollide( shape->filter, worldContext->filter ) == false ) { return true; } b2Body* body = b2BodyArray_Get( &world->bodies, shape->bodyId ); b2Transform transform = b2GetBodyTransformQuick( world, body ); b2PlaneResult result = b2CollideMover( &worldContext->mover, shape, transform ); // todo handle deep overlap if ( result.hit && b2IsNormalized( result.plane.normal ) ) { b2ShapeId id = { shape->id + 1, world->worldId, shape->generation }; return worldContext->fcn( id, &result, worldContext->userContext ); } return true; } // It is tempting to use a shape proxy for the mover, but this makes handling deep overlap difficult and the generality may // not be worth it. void b2World_CollideMover( b2WorldId worldId, const b2Capsule* mover, b2QueryFilter filter, b2PlaneResultFcn* fcn, void* context ) { b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return; } b2Vec2 r = { mover->radius, mover->radius }; b2AABB aabb; aabb.lowerBound = b2Sub( b2Min( mover->center1, mover->center2 ), r ); aabb.upperBound = b2Add( b2Max( mover->center1, mover->center2 ), r ); WorldMoverContext worldContext = { world, fcn, filter, *mover, context, }; for ( int i = 0; i < b2_bodyTypeCount; ++i ) { b2DynamicTree_Query( world->broadPhase.trees + i, aabb, filter.maskBits, TreeCollideCallback, &worldContext ); } } #if 0 void b2World_Dump() { if (m_locked) { return; } b2OpenDump("box2d_dump.inl"); b2Dump("b2Vec2 g(%.9g, %.9g);\n", m_gravity.x, m_gravity.y); b2Dump("m_world->SetGravity(g);\n"); b2Dump("b2Body** sims = (b2Body**)b2Alloc(%d * sizeof(b2Body*));\n", m_bodyCount); b2Dump("b2Joint** joints = (b2Joint**)b2Alloc(%d * sizeof(b2Joint*));\n", m_jointCount); int32 i = 0; for (b2Body* b = m_bodyList; b; b = b->m_next) { b->m_islandIndex = i; b->Dump(); ++i; } i = 0; for (b2Joint* j = m_jointList; j; j = j->m_next) { j->m_index = i; ++i; } // First pass on joints, skip gear joints. for (b2Joint* j = m_jointList; j; j = j->m_next) { if (j->m_type == e_gearJoint) { continue; } b2Dump("{\n"); j->Dump(); b2Dump("}\n"); } // Second pass on joints, only gear joints. for (b2Joint* j = m_jointList; j; j = j->m_next) { if (j->m_type != e_gearJoint) { continue; } b2Dump("{\n"); j->Dump(); b2Dump("}\n"); } b2Dump("b2Free(joints);\n"); b2Dump("b2Free(sims);\n"); b2Dump("joints = nullptr;\n"); b2Dump("sims = nullptr;\n"); b2CloseDump(); } #endif void b2World_SetCustomFilterCallback( b2WorldId worldId, b2CustomFilterFcn* fcn, void* context ) { b2World* world = b2GetWorldFromId( worldId ); world->customFilterFcn = fcn; world->customFilterContext = context; } void b2World_SetPreSolveCallback( b2WorldId worldId, b2PreSolveFcn* fcn, void* context ) { b2World* world = b2GetWorldFromId( worldId ); world->preSolveFcn = fcn; world->preSolveContext = context; } void b2World_SetGravity( b2WorldId worldId, b2Vec2 gravity ) { b2World* world = b2GetWorldFromId( worldId ); world->gravity = gravity; } b2Vec2 b2World_GetGravity( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); return world->gravity; } struct ExplosionContext { b2World* world; b2Vec2 position; float radius; float falloff; float impulsePerLength; }; static bool ExplosionCallback( int proxyId, uint64_t userData, void* context ) { B2_UNUSED( proxyId ); int shapeId = (int)userData; struct ExplosionContext* explosionContext = context; b2World* world = explosionContext->world; b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); b2Body* body = b2BodyArray_Get( &world->bodies, shape->bodyId ); B2_ASSERT( body->type == b2_dynamicBody ); b2Transform transform = b2GetBodyTransformQuick( world, body ); b2DistanceInput input; input.proxyA = b2MakeShapeDistanceProxy( shape ); input.proxyB = b2MakeProxy( &explosionContext->position, 1, 0.0f ); input.transformA = transform; input.transformB = b2Transform_identity; input.useRadii = true; b2SimplexCache cache = { 0 }; b2DistanceOutput output = b2ShapeDistance( &input, &cache, NULL, 0 ); float radius = explosionContext->radius; float falloff = explosionContext->falloff; if ( output.distance > radius + falloff ) { return true; } b2WakeBody( world, body ); if ( body->setIndex != b2_awakeSet ) { return true; } b2Vec2 closestPoint = output.pointA; if ( output.distance == 0.0f ) { b2Vec2 localCentroid = b2GetShapeCentroid( shape ); closestPoint = b2TransformPoint( transform, localCentroid ); } b2Vec2 direction = b2Sub( closestPoint, explosionContext->position ); if ( b2LengthSquared( direction ) > 100.0f * FLT_EPSILON * FLT_EPSILON ) { direction = b2Normalize( direction ); } else { direction = (b2Vec2){ 1.0f, 0.0f }; } b2Vec2 localLine = b2InvRotateVector( transform.q, b2LeftPerp( direction ) ); float perimeter = b2GetShapeProjectedPerimeter( shape, localLine ); float scale = 1.0f; if ( output.distance > radius && falloff > 0.0f ) { scale = b2ClampFloat( ( radius + falloff - output.distance ) / falloff, 0.0f, 1.0f ); } float magnitude = explosionContext->impulsePerLength * perimeter * scale; b2Vec2 impulse = b2MulSV( magnitude, direction ); int localIndex = body->localIndex; b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); b2BodyState* state = b2BodyStateArray_Get( &set->bodyStates, localIndex ); b2BodySim* bodySim = b2BodySimArray_Get( &set->bodySims, localIndex ); state->linearVelocity = b2MulAdd( state->linearVelocity, bodySim->invMass, impulse ); state->angularVelocity += bodySim->invInertia * b2Cross( b2Sub( closestPoint, bodySim->center ), impulse ); return true; } void b2World_Explode( b2WorldId worldId, const b2ExplosionDef* explosionDef ) { uint64_t maskBits = explosionDef->maskBits; b2Vec2 position = explosionDef->position; float radius = explosionDef->radius; float falloff = explosionDef->falloff; float impulsePerLength = explosionDef->impulsePerLength; B2_ASSERT( b2IsValidVec2( position ) ); B2_ASSERT( b2IsValidFloat( radius ) && radius >= 0.0f ); B2_ASSERT( b2IsValidFloat( falloff ) && falloff >= 0.0f ); B2_ASSERT( b2IsValidFloat( impulsePerLength ) ); b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return; } struct ExplosionContext explosionContext = { world, position, radius, falloff, impulsePerLength }; b2AABB aabb; aabb.lowerBound.x = position.x - ( radius + falloff ); aabb.lowerBound.y = position.y - ( radius + falloff ); aabb.upperBound.x = position.x + ( radius + falloff ); aabb.upperBound.y = position.y + ( radius + falloff ); b2DynamicTree_Query( world->broadPhase.trees + b2_dynamicBody, aabb, maskBits, ExplosionCallback, &explosionContext ); } void b2World_RebuildStaticTree( b2WorldId worldId ) { b2World* world = b2GetWorldFromId( worldId ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return; } b2DynamicTree* staticTree = world->broadPhase.trees + b2_staticBody; b2DynamicTree_Rebuild( staticTree, true ); } void b2World_EnableSpeculative( b2WorldId worldId, bool flag ) { b2World* world = b2GetWorldFromId( worldId ); world->enableSpeculative = flag; } #if B2_VALIDATE // This validates island graph connectivity for each body void b2ValidateConnectivity( b2World* world ) { b2Body* bodies = world->bodies.data; int bodyCapacity = world->bodies.count; for ( int bodyIndex = 0; bodyIndex < bodyCapacity; ++bodyIndex ) { b2Body* body = bodies + bodyIndex; if ( body->id == B2_NULL_INDEX ) { b2ValidateFreeId( &world->bodyIdPool, bodyIndex ); continue; } b2ValidateUsedId( &world->bodyIdPool, bodyIndex ); B2_ASSERT( bodyIndex == body->id ); // Need to get the root island because islands are not merged until the next time step int bodyIslandId = body->islandId; int bodySetIndex = body->setIndex; int contactKey = body->headContactKey; while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); bool touching = ( contact->flags & b2_contactTouchingFlag ) != 0; if ( touching ) { if ( bodySetIndex != b2_staticSet ) { int contactIslandId = contact->islandId; B2_ASSERT( contactIslandId == bodyIslandId ); } } else { B2_ASSERT( contact->islandId == B2_NULL_INDEX ); } contactKey = contact->edges[edgeIndex].nextKey; } int jointKey = body->headJointKey; while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; b2Joint* joint = b2JointArray_Get( &world->joints, jointId ); int otherEdgeIndex = edgeIndex ^ 1; b2Body* otherBody = b2BodyArray_Get( &world->bodies, joint->edges[otherEdgeIndex].bodyId ); if ( bodySetIndex == b2_disabledSet || otherBody->setIndex == b2_disabledSet ) { B2_ASSERT( joint->islandId == B2_NULL_INDEX ); } else if ( bodySetIndex == b2_staticSet ) { // Intentional nesting if ( otherBody->setIndex == b2_staticSet ) { B2_ASSERT( joint->islandId == B2_NULL_INDEX ); } } else if ( body->type != b2_dynamicBody && otherBody->type != b2_dynamicBody ) { B2_ASSERT( joint->islandId == B2_NULL_INDEX ); } else { int jointIslandId = joint->islandId; B2_ASSERT( jointIslandId == bodyIslandId ); } jointKey = joint->edges[edgeIndex].nextKey; } } } // Validates solver sets, but not island connectivity void b2ValidateSolverSets( b2World* world ) { B2_ASSERT( b2GetIdCapacity( &world->bodyIdPool ) == world->bodies.count ); B2_ASSERT( b2GetIdCapacity( &world->contactIdPool ) == world->contacts.count ); B2_ASSERT( b2GetIdCapacity( &world->jointIdPool ) == world->joints.count ); B2_ASSERT( b2GetIdCapacity( &world->islandIdPool ) == world->islands.count ); B2_ASSERT( b2GetIdCapacity( &world->solverSetIdPool ) == world->solverSets.count ); int activeSetCount = 0; int totalBodyCount = 0; int totalJointCount = 0; int totalContactCount = 0; int totalIslandCount = 0; // Validate all solver sets int setCount = world->solverSets.count; for ( int setIndex = 0; setIndex < setCount; ++setIndex ) { b2SolverSet* set = world->solverSets.data + setIndex; if ( set->setIndex != B2_NULL_INDEX ) { activeSetCount += 1; if ( setIndex == b2_staticSet ) { B2_ASSERT( set->contactSims.count == 0 ); B2_ASSERT( set->islandSims.count == 0 ); B2_ASSERT( set->bodyStates.count == 0 ); } else if ( setIndex == b2_disabledSet ) { B2_ASSERT( set->islandSims.count == 0 ); B2_ASSERT( set->bodyStates.count == 0 ); } else if ( setIndex == b2_awakeSet ) { B2_ASSERT( set->bodySims.count == set->bodyStates.count ); B2_ASSERT( set->jointSims.count == 0 ); } else { B2_ASSERT( set->bodyStates.count == 0 ); } // Validate bodies { b2Body* bodies = world->bodies.data; B2_ASSERT( set->bodySims.count >= 0 ); totalBodyCount += set->bodySims.count; for ( int i = 0; i < set->bodySims.count; ++i ) { b2BodySim* bodySim = set->bodySims.data + i; int bodyId = bodySim->bodyId; B2_ASSERT( 0 <= bodyId && bodyId < world->bodies.count ); b2Body* body = bodies + bodyId; B2_ASSERT( body->setIndex == setIndex ); B2_ASSERT( body->localIndex == i ); if ( body->type == b2_dynamicBody ) { B2_ASSERT( body->flags & b2_dynamicFlag ); } if ( setIndex == b2_disabledSet ) { B2_ASSERT( body->headContactKey == B2_NULL_INDEX ); } // Validate body shapes int prevShapeId = B2_NULL_INDEX; int shapeId = body->headShapeId; while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); B2_ASSERT( shape->id == shapeId ); B2_ASSERT( shape->prevShapeId == prevShapeId ); if ( setIndex == b2_disabledSet ) { B2_ASSERT( shape->proxyKey == B2_NULL_INDEX ); } else if ( setIndex == b2_staticSet ) { B2_ASSERT( B2_PROXY_TYPE( shape->proxyKey ) == b2_staticBody ); } else { b2BodyType proxyType = B2_PROXY_TYPE( shape->proxyKey ); B2_ASSERT( proxyType == b2_kinematicBody || proxyType == b2_dynamicBody ); } prevShapeId = shapeId; shapeId = shape->nextShapeId; } // Validate body contacts int contactKey = body->headContactKey; while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); B2_ASSERT( contact->setIndex != b2_staticSet ); B2_ASSERT( contact->edges[0].bodyId == bodyId || contact->edges[1].bodyId == bodyId ); contactKey = contact->edges[edgeIndex].nextKey; } // Validate body joints int jointKey = body->headJointKey; while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; b2Joint* joint = b2JointArray_Get( &world->joints, jointId ); int otherEdgeIndex = edgeIndex ^ 1; b2Body* otherBody = b2BodyArray_Get( &world->bodies, joint->edges[otherEdgeIndex].bodyId ); if ( setIndex == b2_disabledSet || otherBody->setIndex == b2_disabledSet ) { B2_ASSERT( joint->setIndex == b2_disabledSet ); } else if ( setIndex == b2_staticSet && otherBody->setIndex == b2_staticSet ) { B2_ASSERT( joint->setIndex == b2_staticSet ); } else if ( body->type != b2_dynamicBody && otherBody->type != b2_dynamicBody ) { B2_ASSERT( joint->setIndex == b2_staticSet ); } else if ( setIndex == b2_awakeSet ) { B2_ASSERT( joint->setIndex == b2_awakeSet ); } else if ( setIndex >= b2_firstSleepingSet ) { B2_ASSERT( joint->setIndex == setIndex ); } b2JointSim* jointSim = b2GetJointSim( world, joint ); B2_ASSERT( jointSim->jointId == jointId ); B2_ASSERT( jointSim->bodyIdA == joint->edges[0].bodyId ); B2_ASSERT( jointSim->bodyIdB == joint->edges[1].bodyId ); jointKey = joint->edges[edgeIndex].nextKey; } } } // Validate contacts { B2_ASSERT( set->contactSims.count >= 0 ); totalContactCount += set->contactSims.count; for ( int i = 0; i < set->contactSims.count; ++i ) { b2ContactSim* contactSim = set->contactSims.data + i; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactSim->contactId ); if ( setIndex == b2_awakeSet ) { // contact should be non-touching if awake // or it could be this contact hasn't been transferred yet B2_ASSERT( contactSim->manifold.pointCount == 0 || ( contactSim->simFlags & b2_simStartedTouching ) != 0 ); } B2_ASSERT( contact->setIndex == setIndex ); B2_ASSERT( contact->colorIndex == B2_NULL_INDEX ); B2_ASSERT( contact->localIndex == i ); } } // Validate joints { B2_ASSERT( set->jointSims.count >= 0 ); totalJointCount += set->jointSims.count; for ( int i = 0; i < set->jointSims.count; ++i ) { b2JointSim* jointSim = set->jointSims.data + i; b2Joint* joint = b2JointArray_Get( &world->joints, jointSim->jointId ); B2_ASSERT( joint->setIndex == setIndex ); B2_ASSERT( joint->colorIndex == B2_NULL_INDEX ); B2_ASSERT( joint->localIndex == i ); } } // Validate islands { B2_ASSERT( set->islandSims.count >= 0 ); totalIslandCount += set->islandSims.count; for ( int i = 0; i < set->islandSims.count; ++i ) { b2IslandSim* islandSim = set->islandSims.data + i; b2Island* island = b2IslandArray_Get( &world->islands, islandSim->islandId ); B2_ASSERT( island->setIndex == setIndex ); B2_ASSERT( island->localIndex == i ); } } } else { B2_ASSERT( set->bodySims.count == 0 ); B2_ASSERT( set->contactSims.count == 0 ); B2_ASSERT( set->jointSims.count == 0 ); B2_ASSERT( set->islandSims.count == 0 ); B2_ASSERT( set->bodyStates.count == 0 ); } } int setIdCount = b2GetIdCount( &world->solverSetIdPool ); B2_ASSERT( activeSetCount == setIdCount ); int bodyIdCount = b2GetIdCount( &world->bodyIdPool ); B2_ASSERT( totalBodyCount == bodyIdCount ); int islandIdCount = b2GetIdCount( &world->islandIdPool ); B2_ASSERT( totalIslandCount == islandIdCount ); // Validate constraint graph for ( int colorIndex = 0; colorIndex < B2_GRAPH_COLOR_COUNT; ++colorIndex ) { b2GraphColor* color = world->constraintGraph.colors + colorIndex; int bitCount = 0; B2_ASSERT( color->contactSims.count >= 0 ); totalContactCount += color->contactSims.count; for ( int i = 0; i < color->contactSims.count; ++i ) { b2ContactSim* contactSim = color->contactSims.data + i; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactSim->contactId ); // contact should be touching in the constraint graph or awaiting transfer to non-touching B2_ASSERT( contactSim->manifold.pointCount > 0 || ( contactSim->simFlags & ( b2_simStoppedTouching | b2_simDisjoint ) ) != 0 ); B2_ASSERT( contact->setIndex == b2_awakeSet ); B2_ASSERT( contact->colorIndex == colorIndex ); B2_ASSERT( contact->localIndex == i ); int bodyIdA = contact->edges[0].bodyId; int bodyIdB = contact->edges[1].bodyId; if ( colorIndex < B2_OVERFLOW_INDEX ) { b2Body* bodyA = b2BodyArray_Get( &world->bodies, bodyIdA ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, bodyIdB ); B2_ASSERT( b2GetBit( &color->bodySet, bodyIdA ) == ( bodyA->type == b2_dynamicBody ) ); B2_ASSERT( b2GetBit( &color->bodySet, bodyIdB ) == ( bodyB->type == b2_dynamicBody ) ); bitCount += bodyA->type == b2_dynamicBody ? 1 : 0; bitCount += bodyB->type == b2_dynamicBody ? 1 : 0; } } B2_ASSERT( color->jointSims.count >= 0 ); totalJointCount += color->jointSims.count; for ( int i = 0; i < color->jointSims.count; ++i ) { b2JointSim* jointSim = color->jointSims.data + i; b2Joint* joint = b2JointArray_Get( &world->joints, jointSim->jointId ); B2_ASSERT( joint->setIndex == b2_awakeSet ); B2_ASSERT( joint->colorIndex == colorIndex ); B2_ASSERT( joint->localIndex == i ); int bodyIdA = joint->edges[0].bodyId; int bodyIdB = joint->edges[1].bodyId; if ( colorIndex < B2_OVERFLOW_INDEX ) { b2Body* bodyA = b2BodyArray_Get( &world->bodies, bodyIdA ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, bodyIdB ); B2_ASSERT( b2GetBit( &color->bodySet, bodyIdA ) == ( bodyA->type == b2_dynamicBody ) ); B2_ASSERT( b2GetBit( &color->bodySet, bodyIdB ) == ( bodyB->type == b2_dynamicBody ) ); bitCount += bodyA->type == b2_dynamicBody ? 1 : 0; bitCount += bodyB->type == b2_dynamicBody ? 1 : 0; } } // Validate the bit population for this graph color B2_ASSERT( bitCount == b2CountSetBits( &color->bodySet ) ); } int contactIdCount = b2GetIdCount( &world->contactIdPool ); B2_ASSERT( totalContactCount == contactIdCount ); B2_ASSERT( totalContactCount == (int)world->broadPhase.pairSet.count ); int jointIdCount = b2GetIdCount( &world->jointIdPool ); B2_ASSERT( totalJointCount == jointIdCount ); // Validate shapes // This is very slow on compounds #if 0 int shapeCapacity = b2Array(world->shapeArray).count; for (int shapeIndex = 0; shapeIndex < shapeCapacity; shapeIndex += 1) { b2Shape* shape = world->shapeArray + shapeIndex; if (shape->id != shapeIndex) { continue; } B2_ASSERT(0 <= shape->bodyId && shape->bodyId < b2Array(world->bodyArray).count); b2Body* body = world->bodyArray + shape->bodyId; B2_ASSERT(0 <= body->setIndex && body->setIndex < b2Array(world->solverSetArray).count); b2SolverSet* set = world->solverSetArray + body->setIndex; B2_ASSERT(0 <= body->localIndex && body->localIndex < set->sims.count); b2BodySim* bodySim = set->sims.data + body->localIndex; B2_ASSERT(bodySim->bodyId == shape->bodyId); bool found = false; int shapeCount = 0; int index = body->headShapeId; while (index != B2_NULL_INDEX) { b2CheckId(world->shapeArray, index); b2Shape* s = world->shapeArray + index; if (index == shapeIndex) { found = true; } index = s->nextShapeId; shapeCount += 1; } B2_ASSERT(found); B2_ASSERT(shapeCount == body->shapeCount); } #endif } // Validate contact touching status. void b2ValidateContacts( b2World* world ) { int contactCount = world->contacts.count; B2_ASSERT( contactCount == b2GetIdCapacity( &world->contactIdPool ) ); int allocatedContactCount = 0; for ( int contactIndex = 0; contactIndex < contactCount; ++contactIndex ) { b2Contact* contact = b2ContactArray_Get( &world->contacts, contactIndex ); if ( contact->contactId == B2_NULL_INDEX ) { continue; } B2_ASSERT( contact->contactId == contactIndex ); allocatedContactCount += 1; bool touching = ( contact->flags & b2_contactTouchingFlag ) != 0; int setId = contact->setIndex; if ( setId == b2_awakeSet ) { if ( touching ) { B2_ASSERT( 0 <= contact->colorIndex && contact->colorIndex < B2_GRAPH_COLOR_COUNT ); } else { B2_ASSERT( contact->colorIndex == B2_NULL_INDEX ); } } else if ( setId >= b2_firstSleepingSet ) { // Only touching contacts allowed in a sleeping set B2_ASSERT( touching == true ); } else { // Sleeping and non-touching contacts belong in the disabled set B2_ASSERT( touching == false && setId == b2_disabledSet ); } b2ContactSim* contactSim = b2GetContactSim( world, contact ); B2_ASSERT( contactSim->contactId == contactIndex ); B2_ASSERT( contactSim->bodyIdA == contact->edges[0].bodyId ); B2_ASSERT( contactSim->bodyIdB == contact->edges[1].bodyId ); bool simTouching = ( contactSim->simFlags & b2_simTouchingFlag ) != 0; B2_ASSERT( touching == simTouching ); B2_ASSERT( 0 <= contactSim->manifold.pointCount && contactSim->manifold.pointCount <= 2 ); } int contactIdCount = b2GetIdCount( &world->contactIdPool ); B2_ASSERT( allocatedContactCount == contactIdCount ); } #else void b2ValidateConnectivity( b2World* world ) { B2_UNUSED( world ); } void b2ValidateSolverSets( b2World* world ) { B2_UNUSED( world ); } void b2ValidateContacts( b2World* world ) { B2_UNUSED( world ); } #endif ================================================ FILE: src/physics_world.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "array.h" #include "bitset.h" #include "broad_phase.h" #include "constraint_graph.h" #include "id_pool.h" #include "arena_allocator.h" #include "box2d/types.h" // Per thread task storage typedef struct b2TaskContext { // Collect per thread sensor continuous hit events. b2SensorHitArray sensorHits; // These bits align with the contact id capacity and signal a change in contact status b2BitSet contactStateBitSet; // These bits align with the joint id capacity and signal a change in contact status b2BitSet jointStateBitSet; // Used to track bodies with shapes that have enlarged AABBs. This avoids having a bit array // that is very large when there are many static shapes. b2BitSet enlargedSimBitSet; // Used to put islands to sleep b2BitSet awakeIslandBitSet; // Per worker split island candidate float splitSleepTime; int splitIslandId; } b2TaskContext; // The world struct manages all physics entities, dynamic simulation, and asynchronous queries. // The world also contains efficient memory management facilities. typedef struct b2World { b2ArenaAllocator arena; b2BroadPhase broadPhase; b2ConstraintGraph constraintGraph; // The body id pool is used to allocate and recycle body ids. Body ids // provide a stable identifier for users, but incur caches misses when used // to access body data. Aligns with b2Body. b2IdPool bodyIdPool; // This is a sparse array that maps body ids to the body data // stored in solver sets. As sims move within a set or across set. // Indices come from id pool. b2BodyArray bodies; // Provides free list for solver sets. b2IdPool solverSetIdPool; // Solvers sets allow sims to be stored in contiguous arrays. The first // set is all static sims. The second set is active sims. The third set is disabled // sims. The remaining sets are sleeping islands. b2SolverSetArray solverSets; // Used to create stable ids for joints b2IdPool jointIdPool; // This is a sparse array that maps joint ids to the joint data stored in the constraint graph // or in the solver sets. b2JointArray joints; // Used to create stable ids for contacts b2IdPool contactIdPool; // This is a sparse array that maps contact ids to the contact data stored in the constraint graph // or in the solver sets. b2ContactArray contacts; // Used to create stable ids for islands b2IdPool islandIdPool; // This is a sparse array that maps island ids to the island data stored in the solver sets. b2IslandArray islands; b2IdPool shapeIdPool; b2IdPool chainIdPool; // These are sparse arrays that point into the pools above b2ShapeArray shapes; b2ChainShapeArray chainShapes; // This is a dense array of sensor data. b2SensorArray sensors; // Per thread storage b2TaskContextArray taskContexts; b2SensorTaskContextArray sensorTaskContexts; b2BodyMoveEventArray bodyMoveEvents; b2SensorBeginTouchEventArray sensorBeginEvents; b2ContactBeginTouchEventArray contactBeginEvents; // End events are double buffered so that the user doesn't need to flush events b2SensorEndTouchEventArray sensorEndEvents[2]; b2ContactEndTouchEventArray contactEndEvents[2]; int endEventArrayIndex; b2ContactHitEventArray contactHitEvents; b2JointEventArray jointEvents; // todo consider deferred waking and impulses to make it possible // to apply forces and impulses from multiple threads // impulses must be deferred because sleeping bodies have no velocity state // Problems: // - multiple forces applied to the same body from multiple threads // Deferred wake //b2BitSet bodyWakeSet; //b2ImpulseArray deferredImpulses; // Used to track debug draw b2BitSet debugBodySet; b2BitSet debugJointSet; b2BitSet debugContactSet; b2BitSet debugIslandSet; // Id that is incremented every time step uint64_t stepIndex; // Identify islands for splitting as follows: // - I want to split islands so smaller islands can sleep // - when a body comes to rest and its sleep timer trips, I can look at the island and flag it for splitting // if it has removed constraints // - islands that have removed constraints must be put split first because I don't want to wake bodies incorrectly // - otherwise I can use the awake islands that have bodies wanting to sleep as the splitting candidates // - if no bodies want to sleep then there is no reason to perform island splitting int splitIslandId; b2Vec2 gravity; float hitEventThreshold; float restitutionThreshold; float maxLinearSpeed; float contactSpeed; float contactHertz; float contactDampingRatio; b2FrictionCallback* frictionCallback; b2RestitutionCallback* restitutionCallback; uint16_t generation; b2Profile profile; b2PreSolveFcn* preSolveFcn; void* preSolveContext; b2CustomFilterFcn* customFilterFcn; void* customFilterContext; int workerCount; b2EnqueueTaskCallback* enqueueTaskFcn; b2FinishTaskCallback* finishTaskFcn; void* userTaskContext; void* userTreeTask; void* userData; // Remember type step used for reporting forces and torques // inverse sub-step float inv_h; // inverse full-step float inv_dt; int activeTaskCount; int taskCount; uint16_t worldId; bool enableSleep; bool locked; bool enableWarmStarting; bool enableContactSoftening; bool enableContinuous; bool enableSpeculative; bool inUse; } b2World; b2World* b2GetWorldFromId( b2WorldId id ); b2World* b2GetWorld( int index ); b2World* b2GetWorldLocked( int index ); void b2ValidateConnectivity( b2World* world ); void b2ValidateSolverSets( b2World* world ); void b2ValidateContacts( b2World* world ); B2_ARRAY_INLINE( b2BodyMoveEvent, b2BodyMoveEvent ) B2_ARRAY_INLINE( b2ContactBeginTouchEvent, b2ContactBeginTouchEvent ) B2_ARRAY_INLINE( b2ContactEndTouchEvent, b2ContactEndTouchEvent ) B2_ARRAY_INLINE( b2ContactHitEvent, b2ContactHitEvent ) B2_ARRAY_INLINE( b2JointEvent, b2JointEvent ) B2_ARRAY_INLINE( b2SensorBeginTouchEvent, b2SensorBeginTouchEvent ) B2_ARRAY_INLINE( b2SensorEndTouchEvent, b2SensorEndTouchEvent ) B2_ARRAY_INLINE( b2TaskContext, b2TaskContext ) ================================================ FILE: src/prismatic_joint.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "body.h" #include "core.h" #include "joint.h" #include "physics_world.h" #include "solver.h" #include "solver_set.h" // needed for dll export #include "box2d/box2d.h" #include void b2PrismaticJoint_EnableSpring( b2JointId jointId, bool enableSpring ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); if ( enableSpring != joint->prismaticJoint.enableSpring ) { joint->prismaticJoint.enableSpring = enableSpring; joint->prismaticJoint.springImpulse = 0.0f; } } bool b2PrismaticJoint_IsSpringEnabled( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.enableSpring; } void b2PrismaticJoint_SetSpringHertz( b2JointId jointId, float hertz ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); joint->prismaticJoint.hertz = hertz; } float b2PrismaticJoint_GetSpringHertz( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.hertz; } void b2PrismaticJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); joint->prismaticJoint.dampingRatio = dampingRatio; } float b2PrismaticJoint_GetSpringDampingRatio( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.dampingRatio; } void b2PrismaticJoint_SetTargetTranslation( b2JointId jointId, float translation ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); joint->prismaticJoint.targetTranslation = translation; } float b2PrismaticJoint_GetTargetTranslation( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.targetTranslation; } void b2PrismaticJoint_EnableLimit( b2JointId jointId, bool enableLimit ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); if ( enableLimit != joint->prismaticJoint.enableLimit ) { joint->prismaticJoint.enableLimit = enableLimit; joint->prismaticJoint.lowerImpulse = 0.0f; joint->prismaticJoint.upperImpulse = 0.0f; } } bool b2PrismaticJoint_IsLimitEnabled( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.enableLimit; } float b2PrismaticJoint_GetLowerLimit( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.lowerTranslation; } float b2PrismaticJoint_GetUpperLimit( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.upperTranslation; } void b2PrismaticJoint_SetLimits( b2JointId jointId, float lower, float upper ) { B2_ASSERT( lower <= upper ); b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); if ( lower != joint->prismaticJoint.lowerTranslation || upper != joint->prismaticJoint.upperTranslation ) { joint->prismaticJoint.lowerTranslation = b2MinFloat( lower, upper ); joint->prismaticJoint.upperTranslation = b2MaxFloat( lower, upper ); joint->prismaticJoint.lowerImpulse = 0.0f; joint->prismaticJoint.upperImpulse = 0.0f; } } void b2PrismaticJoint_EnableMotor( b2JointId jointId, bool enableMotor ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); if ( enableMotor != joint->prismaticJoint.enableMotor ) { joint->prismaticJoint.enableMotor = enableMotor; joint->prismaticJoint.motorImpulse = 0.0f; } } bool b2PrismaticJoint_IsMotorEnabled( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.enableMotor; } void b2PrismaticJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); joint->prismaticJoint.motorSpeed = motorSpeed; } float b2PrismaticJoint_GetMotorSpeed( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.motorSpeed; } float b2PrismaticJoint_GetMotorForce( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2JointSim* base = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return world->inv_h * base->prismaticJoint.motorImpulse; } void b2PrismaticJoint_SetMaxMotorForce( b2JointId jointId, float force ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); joint->prismaticJoint.maxMotorForce = force; } float b2PrismaticJoint_GetMaxMotorForce( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.maxMotorForce; } float b2PrismaticJoint_GetTranslation( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2JointSim* jointSim = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); b2Transform transformA = b2GetBodyTransform( world, jointSim->bodyIdA ); b2Transform transformB = b2GetBodyTransform( world, jointSim->bodyIdB ); b2Vec2 localAxisA = b2RotateVector( jointSim->localFrameA.q, (b2Vec2){ 1.0f, 0.0f } ); b2Vec2 axisA = b2RotateVector( transformA.q, localAxisA ); b2Vec2 pA = b2TransformPoint( transformA, jointSim->localFrameA.p ); b2Vec2 pB = b2TransformPoint( transformB, jointSim->localFrameB.p ); b2Vec2 d = b2Sub( pB, pA ); float translation = b2Dot( d, axisA ); return translation; } float b2PrismaticJoint_GetSpeed( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2Joint* joint = b2GetJointFullId( world, jointId ); B2_ASSERT( joint->type == b2_prismaticJoint ); b2JointSim* base = b2GetJointSim( world, joint ); B2_ASSERT( base->type == b2_prismaticJoint ); b2Body* bodyA = b2BodyArray_Get( &world->bodies, base->bodyIdA ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, base->bodyIdB ); b2BodySim* bodySimA = b2GetBodySim( world, bodyA ); b2BodySim* bodySimB = b2GetBodySim( world, bodyB ); b2BodyState* bodyStateA = b2GetBodyState( world, bodyA ); b2BodyState* bodyStateB = b2GetBodyState( world, bodyB ); b2Transform transformA = bodySimA->transform; b2Transform transformB = bodySimB->transform; b2Vec2 localAxisA = b2RotateVector( base->localFrameA.q, (b2Vec2){ 1.0f, 0.0f } ); b2Vec2 axisA = b2RotateVector( transformA.q, localAxisA ); b2Vec2 cA = bodySimA->center; b2Vec2 cB = bodySimB->center; b2Vec2 rA = b2RotateVector( transformA.q, b2Sub( base->localFrameA.p, bodySimA->localCenter ) ); b2Vec2 rB = b2RotateVector( transformB.q, b2Sub( base->localFrameB.p, bodySimB->localCenter ) ); b2Vec2 d = b2Add( b2Sub( cB, cA ), b2Sub( rB, rA ) ); b2Vec2 vA = bodyStateA ? bodyStateA->linearVelocity : b2Vec2_zero; b2Vec2 vB = bodyStateB ? bodyStateB->linearVelocity : b2Vec2_zero; float wA = bodyStateA ? bodyStateA->angularVelocity : 0.0f; float wB = bodyStateB ? bodyStateB->angularVelocity : 0.0f; b2Vec2 vRel = b2Sub( b2Add( vB, b2CrossSV( wB, rB ) ), b2Add( vA, b2CrossSV( wA, rA ) ) ); float speed = b2Dot( d, b2CrossSV( wA, axisA ) ) + b2Dot( axisA, vRel ); return speed; } b2Vec2 b2GetPrismaticJointForce( b2World* world, b2JointSim* base ) { int idA = base->bodyIdA; b2Transform transformA = b2GetBodyTransform( world, idA ); b2PrismaticJoint* joint = &base->prismaticJoint; b2Vec2 localAxisA = b2RotateVector( base->localFrameA.q, (b2Vec2){ 1.0f, 0.0f } ); b2Vec2 axisA = b2RotateVector( transformA.q, localAxisA ); b2Vec2 perpA = b2LeftPerp( axisA ); float inv_h = world->inv_h; float perpForce = inv_h * joint->impulse.x; float axialForce = inv_h * ( joint->motorImpulse + joint->lowerImpulse - joint->upperImpulse ); b2Vec2 force = b2Add( b2MulSV( perpForce, perpA ), b2MulSV( axialForce, axisA ) ); return force; } float b2GetPrismaticJointTorque( b2World* world, b2JointSim* base ) { return world->inv_h * base->prismaticJoint.impulse.y; } // Linear constraint (point-to-line) // d = pB - pA = xB + rB - xA - rA // C = dot(perp, d) // Cdot = dot(d, cross(wA, perp)) + dot(perp, vB + cross(wB, rB) - vA - cross(wA, rA)) // = -dot(perp, vA) - dot(cross(rA + d, perp), wA) + dot(perp, vB) + dot(cross(rB, perp), vB) // J = [-perp, -cross(rA + d, perp), perp, cross(rB, perp)] // // Angular constraint // C = aB - aA + a_initial // Cdot = wB - wA // J = [0 0 -1 0 0 1] // // K = J * invM * JT // // J = [-a -sA a sB] // [0 -1 0 1] // a = perp // sA = cross(rA + d, a) = cross(pB - xA, a) // sB = cross(rB, a) = cross(pB - xB, a) // Motor/Limit linear constraint // C = dot(axA, d) // Cdot = -dot(axA, vA) - dot(cross(rA + d, axA), wA) + dot(axA, vB) + dot(cross(rB, axA), vB) // J = [-axA -cross(rA + d, axA) axA cross(rB, ax1)] // Predictive limit is applied even when the limit is not active. // Prevents a constraint speed that can lead to a constraint error in one time step. // Want C2 = C1 + h * Cdot >= 0 // Or: // Cdot + C1/h >= 0 // I do not apply a negative constraint error because that is handled in position correction. // So: // Cdot + max(C1, 0)/h >= 0 // Block Solver // We develop a block solver that includes the angular and linear constraints. This makes the limit stiffer. // // The Jacobian has 2 rows: // J = [-uT -s1 uT s2] // linear // [0 -1 0 1] // angular // // u = perp // s1 = cross(d + r1, u), s2 = cross(r2, u) // a1 = cross(d + r1, v), a2 = cross(r2, v) void b2PreparePrismaticJoint( b2JointSim* base, b2StepContext* context ) { B2_ASSERT( base->type == b2_prismaticJoint ); // chase body id to the solver set where the body lives int idA = base->bodyIdA; int idB = base->bodyIdB; b2World* world = context->world; b2Body* bodyA = b2BodyArray_Get( &world->bodies, idA ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, idB ); B2_ASSERT( bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet ); b2SolverSet* setA = b2SolverSetArray_Get( &world->solverSets, bodyA->setIndex ); b2SolverSet* setB = b2SolverSetArray_Get( &world->solverSets, bodyB->setIndex ); int localIndexA = bodyA->localIndex; int localIndexB = bodyB->localIndex; b2BodySim* bodySimA = b2BodySimArray_Get( &setA->bodySims, localIndexA ); b2BodySim* bodySimB = b2BodySimArray_Get( &setB->bodySims, localIndexB ); float mA = bodySimA->invMass; float iA = bodySimA->invInertia; float mB = bodySimB->invMass; float iB = bodySimB->invInertia; base->invMassA = mA; base->invMassB = mB; base->invIA = iA; base->invIB = iB; b2PrismaticJoint* joint = &base->prismaticJoint; joint->indexA = bodyA->setIndex == b2_awakeSet ? localIndexA : B2_NULL_INDEX; joint->indexB = bodyB->setIndex == b2_awakeSet ? localIndexB : B2_NULL_INDEX; // Compute joint anchor frames with world space rotation, relative to center of mass joint->frameA.q = b2MulRot( bodySimA->transform.q, base->localFrameA.q ); joint->frameA.p = b2RotateVector( bodySimA->transform.q, b2Sub( base->localFrameA.p, bodySimA->localCenter ) ); joint->frameB.q = b2MulRot( bodySimB->transform.q, base->localFrameB.q ); joint->frameB.p = b2RotateVector( bodySimB->transform.q, b2Sub( base->localFrameB.p, bodySimB->localCenter ) ); // Compute the initial center delta. Incremental position updates are relative to this. joint->deltaCenter = b2Sub( bodySimB->center, bodySimA->center ); joint->springSoftness = b2MakeSoft( joint->hertz, joint->dampingRatio, context->h ); if ( context->enableWarmStarting == false ) { joint->impulse = b2Vec2_zero; joint->springImpulse = 0.0f; joint->motorImpulse = 0.0f; joint->lowerImpulse = 0.0f; joint->upperImpulse = 0.0f; } } void b2WarmStartPrismaticJoint( b2JointSim* base, b2StepContext* context ) { B2_ASSERT( base->type == b2_prismaticJoint ); float mA = base->invMassA; float mB = base->invMassB; float iA = base->invIA; float iB = base->invIB; // dummy state for static bodies b2BodyState dummyState = b2_identityBodyState; b2PrismaticJoint* joint = &base->prismaticJoint; b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->frameA.p ); b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->frameB.p ); b2Vec2 d = b2Add( b2Add( b2Sub( stateB->deltaPosition, stateA->deltaPosition ), joint->deltaCenter ), b2Sub( rB, rA ) ); b2Vec2 axisA = b2RotateVector( joint->frameA.q, (b2Vec2){ 1.0f, 0.0f } ); axisA = b2RotateVector( stateA->deltaRotation, axisA ); // impulse is applied at anchor point on body B float a1 = b2Cross( b2Add( rA, d ), axisA ); float a2 = b2Cross( rB, axisA ); float axialImpulse = joint->springImpulse + joint->motorImpulse + joint->lowerImpulse - joint->upperImpulse; // perpendicular constraint b2Vec2 perpA = b2LeftPerp( axisA ); float s1 = b2Cross( b2Add( rA, d ), perpA ); float s2 = b2Cross( rB, perpA ); float perpImpulse = joint->impulse.x; float angleImpulse = joint->impulse.y; b2Vec2 P = b2Add( b2MulSV( axialImpulse, axisA ), b2MulSV( perpImpulse, perpA ) ); float LA = axialImpulse * a1 + perpImpulse * s1 + angleImpulse; float LB = axialImpulse * a2 + perpImpulse * s2 + angleImpulse; if ( stateA->flags & b2_dynamicFlag ) { stateA->linearVelocity = b2MulSub( stateA->linearVelocity, mA, P ); stateA->angularVelocity -= iA * LA; } if ( stateB->flags & b2_dynamicFlag ) { stateB->linearVelocity = b2MulAdd( stateB->linearVelocity, mB, P ); stateB->angularVelocity += iB * LB; } } void b2SolvePrismaticJoint( b2JointSim* base, b2StepContext* context, bool useBias ) { B2_ASSERT( base->type == b2_prismaticJoint ); float mA = base->invMassA; float mB = base->invMassB; float iA = base->invIA; float iB = base->invIB; // dummy state for static bodies b2BodyState dummyState = b2_identityBodyState; b2PrismaticJoint* joint = &base->prismaticJoint; b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; b2Vec2 vA = stateA->linearVelocity; float wA = stateA->angularVelocity; b2Vec2 vB = stateB->linearVelocity; float wB = stateB->angularVelocity; b2Rot qA = b2MulRot( stateA->deltaRotation, joint->frameA.q ); b2Rot qB = b2MulRot( stateB->deltaRotation, joint->frameB.q ); b2Rot relQ = b2InvMulRot( qA, qB ); // current anchors b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->frameA.p ); b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->frameB.p ); b2Vec2 d = b2Add( b2Add( b2Sub( stateB->deltaPosition, stateA->deltaPosition ), joint->deltaCenter ), b2Sub( rB, rA ) ); b2Vec2 axisA = b2RotateVector( joint->frameA.q, (b2Vec2){ 1.0f, 0.0f } ); axisA = b2RotateVector( stateA->deltaRotation, axisA ); float translation = b2Dot( axisA, d ); // These scalars are for torques generated by axial forces float a1 = b2Cross( b2Add( rA, d ), axisA ); float a2 = b2Cross( rB, axisA ); float k = mA + mB + iA * a1 * a1 + iB * a2 * a2; float axialMass = k > 0.0f ? 1.0f / k : 0.0f; b2Softness softness = base->constraintSoftness; // spring constraint if ( joint->enableSpring ) { // This is a real spring and should be applied even during relax float C = translation - joint->targetTranslation; float bias = joint->springSoftness.biasRate * C; float massScale = joint->springSoftness.massScale; float impulseScale = joint->springSoftness.impulseScale; float Cdot = b2Dot( axisA, b2Sub( vB, vA ) ) + a2 * wB - a1 * wA; float deltaImpulse = -massScale * axialMass * ( Cdot + bias ) - impulseScale * joint->springImpulse; joint->springImpulse += deltaImpulse; b2Vec2 P = b2MulSV( deltaImpulse, axisA ); float LA = deltaImpulse * a1; float LB = deltaImpulse * a2; vA = b2MulSub( vA, mA, P ); wA -= iA * LA; vB = b2MulAdd( vB, mB, P ); wB += iB * LB; } // Solve motor constraint if ( joint->enableMotor ) { float Cdot = b2Dot( axisA, b2Sub( vB, vA ) ) + a2 * wB - a1 * wA; float impulse = axialMass * ( joint->motorSpeed - Cdot ); float oldImpulse = joint->motorImpulse; float maxImpulse = context->h * joint->maxMotorForce; joint->motorImpulse = b2ClampFloat( joint->motorImpulse + impulse, -maxImpulse, maxImpulse ); impulse = joint->motorImpulse - oldImpulse; b2Vec2 P = b2MulSV( impulse, axisA ); float LA = impulse * a1; float LB = impulse * a2; vA = b2MulSub( vA, mA, P ); wA -= iA * LA; vB = b2MulAdd( vB, mB, P ); wB += iB * LB; } if ( joint->enableLimit ) { // Clamp the speculative distance to a reasonable value float speculativeDistance = 0.25f * ( joint->upperTranslation - joint->lowerTranslation ); // Lower limit { float C = translation - joint->lowerTranslation; if ( C < speculativeDistance ) { float bias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; if ( C > 0.0f ) { // speculation float safe = b2_lengthUnitsPerMeter; bias = b2MinFloat( C, safe ) * context->inv_h; } else if ( useBias ) { bias = softness.biasRate * C; massScale = softness.massScale; impulseScale = softness.impulseScale; } float oldImpulse = joint->lowerImpulse; float Cdot = b2Dot( axisA, b2Sub( vB, vA ) ) + a2 * wB - a1 * wA; float deltaImpulse = -axialMass * massScale * ( Cdot + bias ) - impulseScale * oldImpulse; joint->lowerImpulse = b2MaxFloat( oldImpulse + deltaImpulse, 0.0f ); deltaImpulse = joint->lowerImpulse - oldImpulse; b2Vec2 P = b2MulSV( deltaImpulse, axisA ); float LA = deltaImpulse * a1; float LB = deltaImpulse * a2; vA = b2MulSub( vA, mA, P ); wA -= iA * LA; vB = b2MulAdd( vB, mB, P ); wB += iB * LB; } else { joint->lowerImpulse = 0.0f; } } // Upper limit // Note: signs are flipped to keep C positive when the constraint is satisfied. // This also keeps the impulse positive when the limit is active. { // sign flipped float C = joint->upperTranslation - translation; if ( C < speculativeDistance ) { float bias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; if ( C > 0.0f ) { // speculation float safe = b2_lengthUnitsPerMeter; bias = b2MinFloat( C, safe ) * context->inv_h; } else if ( useBias ) { bias = softness.biasRate * C; massScale = softness.massScale; impulseScale = softness.impulseScale; } float oldImpulse = joint->upperImpulse; // sign flipped float Cdot = b2Dot( axisA, b2Sub( vA, vB ) ) + a1 * wA - a2 * wB; float deltaImpulse = -axialMass * massScale * ( Cdot + bias ) - impulseScale * oldImpulse; joint->upperImpulse = b2MaxFloat( oldImpulse + deltaImpulse, 0.0f ); deltaImpulse = joint->upperImpulse - oldImpulse; b2Vec2 P = b2MulSV( deltaImpulse, axisA ); float LA = deltaImpulse * a1; float LB = deltaImpulse * a2; // sign flipped vA = b2MulAdd( vA, mA, P ); wA += iA * LA; vB = b2MulSub( vB, mB, P ); wB -= iB * LB; } else { joint->upperImpulse = 0.0f; } } } // Solve the prismatic constraint in block form { b2Vec2 perpA = b2LeftPerp( axisA ); // These scalars are for torques generated by the perpendicular constraint force float s1 = b2Cross( b2Add( d, rA ), perpA ); float s2 = b2Cross( rB, perpA ); b2Vec2 Cdot; Cdot.x = b2Dot( perpA, b2Sub( vB, vA ) ) + s2 * wB - s1 * wA; Cdot.y = wB - wA; b2Vec2 bias = b2Vec2_zero; float massScale = 1.0f; float impulseScale = 0.0f; if ( useBias ) { b2Vec2 C; C.x = b2Dot( perpA, d ); C.y = b2Rot_GetAngle( relQ ); bias = b2MulSV( softness.biasRate, C ); massScale = softness.massScale; impulseScale = softness.impulseScale; } float k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; float k12 = iA * s1 + iB * s2; float k22 = iA + iB; if ( k22 == 0.0f ) { // For bodies with fixed rotation. k22 = 1.0f; } b2Mat22 K = { { k11, k12 }, { k12, k22 } }; b2Vec2 b = b2Solve22( K, b2Add( Cdot, bias ) ); b2Vec2 deltaImpulse; deltaImpulse.x = -massScale * b.x - impulseScale * joint->impulse.x; deltaImpulse.y = -massScale * b.y - impulseScale * joint->impulse.y; joint->impulse.x += deltaImpulse.x; joint->impulse.y += deltaImpulse.y; b2Vec2 P = b2MulSV( deltaImpulse.x, perpA ); float LA = deltaImpulse.x * s1 + deltaImpulse.y; float LB = deltaImpulse.x * s2 + deltaImpulse.y; vA = b2MulSub( vA, mA, P ); wA -= iA * LA; vB = b2MulAdd( vB, mB, P ); wB += iB * LB; } B2_ASSERT( b2IsValidVec2( vA ) ); B2_ASSERT( b2IsValidFloat( wA ) ); B2_ASSERT( b2IsValidVec2( vB ) ); B2_ASSERT( b2IsValidFloat( wB ) ); if ( stateA->flags & b2_dynamicFlag ) { stateA->linearVelocity = vA; stateA->angularVelocity = wA; } if ( stateB->flags & b2_dynamicFlag ) { stateB->linearVelocity = vB; stateB->angularVelocity = wB; } } #if 0 void b2PrismaticJoint::Dump() { int32 indexA = joint->bodyA->joint->islandIndex; int32 indexB = joint->bodyB->joint->islandIndex; b2Dump(" b2PrismaticJointDef jd;\n"); b2Dump(" jd.bodyA = sims[%d];\n", indexA); b2Dump(" jd.bodyB = sims[%d];\n", indexB); b2Dump(" jd.collideConnected = bool(%d);\n", joint->collideConnected); b2Dump(" jd.localAnchorA.Set(%.9g, %.9g);\n", joint->localAnchorA.x, joint->localAnchorA.y); b2Dump(" jd.localAnchorB.Set(%.9g, %.9g);\n", joint->localAnchorB.x, joint->localAnchorB.y); b2Dump(" jd.referenceAngle = %.9g;\n", joint->referenceAngle); b2Dump(" jd.enableLimit = bool(%d);\n", joint->enableLimit); b2Dump(" jd.lowerAngle = %.9g;\n", joint->lowerAngle); b2Dump(" jd.upperAngle = %.9g;\n", joint->upperAngle); b2Dump(" jd.enableMotor = bool(%d);\n", joint->enableMotor); b2Dump(" jd.motorSpeed = %.9g;\n", joint->motorSpeed); b2Dump(" jd.maxMotorTorque = %.9g;\n", joint->maxMotorTorque); b2Dump(" joints[%d] = joint->world->CreateJoint(&jd);\n", joint->index); } #endif void b2DrawPrismaticJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB, float drawScale ) { B2_ASSERT( base->type == b2_prismaticJoint ); b2PrismaticJoint* joint = &base->prismaticJoint; b2Transform frameA = b2MulTransforms( transformA, base->localFrameA ); b2Transform frameB = b2MulTransforms( transformB, base->localFrameB ); b2Vec2 axisA = b2RotateVector( frameA.q, (b2Vec2){ 1.0f, 0.0f } ); draw->DrawLineFcn( frameA.p, frameB.p, b2_colorDimGray, draw->context ); if ( joint->enableLimit ) { float b = 0.25f * drawScale; b2Vec2 lower = b2MulAdd( frameA.p, joint->lowerTranslation, axisA ); b2Vec2 upper = b2MulAdd( frameA.p, joint->upperTranslation, axisA ); b2Vec2 perp = b2LeftPerp( axisA ); draw->DrawLineFcn( lower, upper, b2_colorGray, draw->context ); draw->DrawLineFcn( b2MulSub( lower, b, perp ), b2MulAdd( lower, b, perp ), b2_colorGreen, draw->context ); draw->DrawLineFcn( b2MulSub( upper, b, perp ), b2MulAdd( upper, b, perp ), b2_colorRed, draw->context ); } else { draw->DrawLineFcn( b2MulSub( frameA.p, 1.0f, axisA ), b2MulAdd( frameA.p, 1.0f, axisA ), b2_colorGray, draw->context ); } if ( joint->enableSpring ) { b2Vec2 p = b2MulAdd( frameA.p, joint->targetTranslation, axisA ); draw->DrawPointFcn( p, 8.0f, b2_colorViolet, draw->context ); } draw->DrawPointFcn( frameA.p, 5.0f, b2_colorGray, draw->context ); draw->DrawPointFcn( frameB.p, 5.0f, b2_colorBlue, draw->context ); } ================================================ FILE: src/revolute_joint.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #if defined( _MSC_VER ) && !defined( _CRT_SECURE_NO_WARNINGS ) #define _CRT_SECURE_NO_WARNINGS #endif #include "body.h" #include "core.h" #include "joint.h" #include "physics_world.h" #include "solver.h" #include "solver_set.h" // needed for dll export #include "box2d/box2d.h" #include // Point-to-point constraint // C = pB - pA // Cdot = vB - vA // = vB + cross(wB, rB) - vA - cross(wA, rA) // J = [-E -skew(rA) E skew(rB) ] // Identity used: // w k % (rx i + ry j) = w * (-ry i + rx j) // Motor constraint // Cdot = wB - wA // J = [0 0 -1 0 0 1] // K = invIA + invIB void b2RevoluteJoint_EnableSpring( b2JointId jointId, bool enableSpring ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); if ( enableSpring != joint->revoluteJoint.enableSpring ) { joint->revoluteJoint.enableSpring = enableSpring; joint->revoluteJoint.springImpulse = 0.0f; } } bool b2RevoluteJoint_IsSpringEnabled( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.enableSpring; } void b2RevoluteJoint_SetSpringHertz( b2JointId jointId, float hertz ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); joint->revoluteJoint.hertz = hertz; } float b2RevoluteJoint_GetSpringHertz( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.hertz; } void b2RevoluteJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); joint->revoluteJoint.dampingRatio = dampingRatio; } float b2RevoluteJoint_GetSpringDampingRatio( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.dampingRatio; } void b2RevoluteJoint_SetTargetAngle( b2JointId jointId, float angle ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); joint->revoluteJoint.targetAngle = angle; } float b2RevoluteJoint_GetTargetAngle( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.targetAngle; } float b2RevoluteJoint_GetAngle( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2JointSim* jointSim = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); b2Transform transformA = b2GetBodyTransform( world, jointSim->bodyIdA ); b2Transform transformB = b2GetBodyTransform( world, jointSim->bodyIdB ); b2Rot qA = b2MulRot( transformA.q, jointSim->localFrameA.q ); b2Rot qB = b2MulRot( transformB.q, jointSim->localFrameB.q ); float angle = b2RelativeAngle( qA, qB ); return angle; } void b2RevoluteJoint_EnableLimit( b2JointId jointId, bool enableLimit ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); if ( enableLimit != joint->revoluteJoint.enableLimit ) { joint->revoluteJoint.enableLimit = enableLimit; joint->revoluteJoint.lowerImpulse = 0.0f; joint->revoluteJoint.upperImpulse = 0.0f; } } bool b2RevoluteJoint_IsLimitEnabled( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.enableLimit; } float b2RevoluteJoint_GetLowerLimit( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.lowerAngle; } float b2RevoluteJoint_GetUpperLimit( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.upperAngle; } void b2RevoluteJoint_SetLimits( b2JointId jointId, float lower, float upper ) { B2_ASSERT( lower <= upper ); B2_ASSERT( lower >= -0.99f * B2_PI ); B2_ASSERT( upper <= 0.99f * B2_PI ); b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); if ( lower != joint->revoluteJoint.lowerAngle || upper != joint->revoluteJoint.upperAngle ) { joint->revoluteJoint.lowerAngle = b2MinFloat( lower, upper ); joint->revoluteJoint.upperAngle = b2MaxFloat( lower, upper ); joint->revoluteJoint.lowerImpulse = 0.0f; joint->revoluteJoint.upperImpulse = 0.0f; } } void b2RevoluteJoint_EnableMotor( b2JointId jointId, bool enableMotor ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); if ( enableMotor != joint->revoluteJoint.enableMotor ) { joint->revoluteJoint.enableMotor = enableMotor; joint->revoluteJoint.motorImpulse = 0.0f; } } bool b2RevoluteJoint_IsMotorEnabled( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.enableMotor; } void b2RevoluteJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); joint->revoluteJoint.motorSpeed = motorSpeed; } float b2RevoluteJoint_GetMotorSpeed( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.motorSpeed; } float b2RevoluteJoint_GetMotorTorque( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return world->inv_h * joint->revoluteJoint.motorImpulse; } void b2RevoluteJoint_SetMaxMotorTorque( b2JointId jointId, float torque ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); joint->revoluteJoint.maxMotorTorque = torque; } float b2RevoluteJoint_GetMaxMotorTorque( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.maxMotorTorque; } b2Vec2 b2GetRevoluteJointForce( b2World* world, b2JointSim* base ) { b2Vec2 force = b2MulSV( world->inv_h, base->revoluteJoint.linearImpulse ); return force; } float b2GetRevoluteJointTorque( b2World* world, b2JointSim* base ) { const b2RevoluteJoint* revolute = &base->revoluteJoint; float torque = world->inv_h * ( revolute->motorImpulse + revolute->lowerImpulse - revolute->upperImpulse ); return torque; } void b2PrepareRevoluteJoint( b2JointSim* base, b2StepContext* context ) { B2_ASSERT( base->type == b2_revoluteJoint ); // chase body id to the solver set where the body lives int idA = base->bodyIdA; int idB = base->bodyIdB; b2World* world = context->world; b2Body* bodyA = b2BodyArray_Get( &world->bodies, idA ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, idB ); B2_ASSERT( bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet ); b2SolverSet* setA = b2SolverSetArray_Get( &world->solverSets, bodyA->setIndex ); b2SolverSet* setB = b2SolverSetArray_Get( &world->solverSets, bodyB->setIndex ); int localIndexA = bodyA->localIndex; int localIndexB = bodyB->localIndex; b2BodySim* bodySimA = b2BodySimArray_Get( &setA->bodySims, localIndexA ); b2BodySim* bodySimB = b2BodySimArray_Get( &setB->bodySims, localIndexB ); float mA = bodySimA->invMass; float iA = bodySimA->invInertia; float mB = bodySimB->invMass; float iB = bodySimB->invInertia; base->invMassA = mA; base->invMassB = mB; base->invIA = iA; base->invIB = iB; b2RevoluteJoint* joint = &base->revoluteJoint; joint->indexA = bodyA->setIndex == b2_awakeSet ? localIndexA : B2_NULL_INDEX; joint->indexB = bodyB->setIndex == b2_awakeSet ? localIndexB : B2_NULL_INDEX; // Compute joint anchor frames with world space rotation, relative to center of mass. // Avoid round-off here as much as possible. // b2Vec2 pf = (xf.p - c) + rot(xf.q, f.p) // pf = xf.p - (xf.p + rot(xf.q, lc)) + rot(xf.q, f.p) // pf = rot(xf.q, f.p - lc) joint->frameA.q = b2MulRot( bodySimA->transform.q, base->localFrameA.q ); joint->frameA.p = b2RotateVector( bodySimA->transform.q, b2Sub( base->localFrameA.p, bodySimA->localCenter ) ); joint->frameB.q = b2MulRot( bodySimB->transform.q, base->localFrameB.q ); joint->frameB.p = b2RotateVector( bodySimB->transform.q, b2Sub( base->localFrameB.p, bodySimB->localCenter ) ); // Compute the initial center delta. Incremental position updates are relative to this. joint->deltaCenter = b2Sub( bodySimB->center, bodySimA->center ); float k = iA + iB; joint->axialMass = k > 0.0f ? 1.0f / k : 0.0f; joint->springSoftness = b2MakeSoft( joint->hertz, joint->dampingRatio, context->h ); if ( context->enableWarmStarting == false ) { joint->linearImpulse = b2Vec2_zero; joint->springImpulse = 0.0f; joint->motorImpulse = 0.0f; joint->lowerImpulse = 0.0f; joint->upperImpulse = 0.0f; } } void b2WarmStartRevoluteJoint( b2JointSim* base, b2StepContext* context ) { B2_ASSERT( base->type == b2_revoluteJoint ); float mA = base->invMassA; float mB = base->invMassB; float iA = base->invIA; float iB = base->invIB; // dummy state for static bodies b2BodyState dummyState = b2_identityBodyState; b2RevoluteJoint* joint = &base->revoluteJoint; b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->frameA.p ); b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->frameB.p ); float axialImpulse = joint->springImpulse + joint->motorImpulse + joint->lowerImpulse - joint->upperImpulse; if ( stateA->flags & b2_dynamicFlag ) { stateA->linearVelocity = b2MulSub( stateA->linearVelocity, mA, joint->linearImpulse ); stateA->angularVelocity -= iA * ( b2Cross( rA, joint->linearImpulse ) + axialImpulse ); } if ( stateB->flags & b2_dynamicFlag ) { stateB->linearVelocity = b2MulAdd( stateB->linearVelocity, mB, joint->linearImpulse ); stateB->angularVelocity += iB * ( b2Cross( rB, joint->linearImpulse ) + axialImpulse ); } } void b2SolveRevoluteJoint( b2JointSim* base, b2StepContext* context, bool useBias ) { B2_ASSERT( base->type == b2_revoluteJoint ); float mA = base->invMassA; float mB = base->invMassB; float iA = base->invIA; float iB = base->invIB; // dummy state for static bodies b2BodyState dummyState = b2_identityBodyState; b2RevoluteJoint* joint = &base->revoluteJoint; b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; b2Vec2 vA = stateA->linearVelocity; float wA = stateA->angularVelocity; b2Vec2 vB = stateB->linearVelocity; float wB = stateB->angularVelocity; b2Rot qA = b2MulRot( stateA->deltaRotation, joint->frameA.q ); b2Rot qB = b2MulRot( stateB->deltaRotation, joint->frameB.q ); b2Rot relQ = b2InvMulRot( qA, qB ); bool fixedRotation = ( iA + iB == 0.0f ); // Solve spring. if ( joint->enableSpring && fixedRotation == false ) { float jointAngle = b2Rot_GetAngle( relQ ); float jointAngleDelta = b2UnwindAngle( jointAngle - joint->targetAngle ); float C = jointAngleDelta; float bias = joint->springSoftness.biasRate * C; float massScale = joint->springSoftness.massScale; float impulseScale = joint->springSoftness.impulseScale; float Cdot = wB - wA; float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->springImpulse; joint->springImpulse += impulse; wA -= iA * impulse; wB += iB * impulse; } // Solve motor constraint. if ( joint->enableMotor && fixedRotation == false ) { float Cdot = wB - wA - joint->motorSpeed; float impulse = -joint->axialMass * Cdot; float oldImpulse = joint->motorImpulse; float maxImpulse = context->h * joint->maxMotorTorque; joint->motorImpulse = b2ClampFloat( joint->motorImpulse + impulse, -maxImpulse, maxImpulse ); impulse = joint->motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } if ( joint->enableLimit && fixedRotation == false ) { float jointAngle = b2Rot_GetAngle( relQ ); // Lower limit { float C = jointAngle - joint->lowerAngle; float bias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; if ( C > 0.0f ) { // speculation bias = C * context->inv_h; } else if ( useBias ) { bias = base->constraintSoftness.biasRate * C; massScale = base->constraintSoftness.massScale; impulseScale = base->constraintSoftness.impulseScale; } float Cdot = wB - wA; float oldImpulse = joint->lowerImpulse; float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * oldImpulse; joint->lowerImpulse = b2MaxFloat( oldImpulse + impulse, 0.0f ); impulse = joint->lowerImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Upper limit // Note: signs are flipped to keep C positive when the constraint is satisfied. // This also keeps the impulse positive when the limit is active. { float C = joint->upperAngle - jointAngle; float bias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; if ( C > 0.0f ) { // speculation bias = C * context->inv_h; } else if ( useBias ) { bias = base->constraintSoftness.biasRate * C; massScale = base->constraintSoftness.massScale; impulseScale = base->constraintSoftness.impulseScale; } // sign flipped on Cdot float Cdot = wA - wB; float oldImpulse = joint->upperImpulse; float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * oldImpulse; joint->upperImpulse = b2MaxFloat( oldImpulse + impulse, 0.0f ); impulse = joint->upperImpulse - oldImpulse; // sign flipped on applied impulse wA += iA * impulse; wB -= iB * impulse; } } // Solve point-to-point constraint { // J = [-I -r1_skew I r2_skew] // r_skew = [-ry; rx] // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB] // current anchors b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->frameA.p ); b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->frameB.p ); b2Vec2 Cdot = b2Sub( b2Add( vB, b2CrossSV( wB, rB ) ), b2Add( vA, b2CrossSV( wA, rA ) ) ); b2Vec2 bias = b2Vec2_zero; float massScale = 1.0f; float impulseScale = 0.0f; if ( useBias ) { b2Vec2 dcA = stateA->deltaPosition; b2Vec2 dcB = stateB->deltaPosition; b2Vec2 separation = b2Add( b2Add( b2Sub( dcB, dcA ), b2Sub( rB, rA ) ), joint->deltaCenter ); bias = b2MulSV( base->constraintSoftness.biasRate, separation ); massScale = base->constraintSoftness.massScale; impulseScale = base->constraintSoftness.impulseScale; } b2Mat22 K; K.cx.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; K.cy.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; K.cx.y = K.cy.x; K.cy.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; b2Vec2 b = b2Solve22( K, b2Add( Cdot, bias ) ); b2Vec2 impulse; impulse.x = -massScale * b.x - impulseScale * joint->linearImpulse.x; impulse.y = -massScale * b.y - impulseScale * joint->linearImpulse.y; joint->linearImpulse.x += impulse.x; joint->linearImpulse.y += impulse.y; vA = b2MulSub( vA, mA, impulse ); wA -= iA * b2Cross( rA, impulse ); vB = b2MulAdd( vB, mB, impulse ); wB += iB * b2Cross( rB, impulse ); } if ( stateA->flags & b2_dynamicFlag ) { stateA->linearVelocity = vA; stateA->angularVelocity = wA; } if ( stateB->flags & b2_dynamicFlag ) { stateB->linearVelocity = vB; stateB->angularVelocity = wB; } } #if 0 void b2RevoluteJoint::Dump() { int32 indexA = joint->bodyA->joint->islandIndex; int32 indexB = joint->bodyB->joint->islandIndex; b2Dump(" b2RevoluteJointDef jd;\n"); b2Dump(" jd.bodyA = bodies[%d];\n", indexA); b2Dump(" jd.bodyB = bodies[%d];\n", indexB); b2Dump(" jd.collideConnected = bool(%d);\n", joint->collideConnected); b2Dump(" jd.localAnchorA.Set(%.9g, %.9g);\n", joint->localAnchorA.x, joint->localAnchorA.y); b2Dump(" jd.localAnchorB.Set(%.9g, %.9g);\n", joint->localAnchorB.x, joint->localAnchorB.y); b2Dump(" jd.referenceAngle = %.9g;\n", joint->referenceAngle); b2Dump(" jd.enableLimit = bool(%d);\n", joint->enableLimit); b2Dump(" jd.lowerAngle = %.9g;\n", joint->lowerAngle); b2Dump(" jd.upperAngle = %.9g;\n", joint->upperAngle); b2Dump(" jd.enableMotor = bool(%d);\n", joint->enableMotor); b2Dump(" jd.motorSpeed = %.9g;\n", joint->motorSpeed); b2Dump(" jd.maxMotorTorque = %.9g;\n", joint->maxMotorTorque); b2Dump(" joints[%d] = joint->world->CreateJoint(&jd);\n", joint->index); } #endif void b2DrawRevoluteJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB, float drawScale ) { B2_ASSERT( base->type == b2_revoluteJoint ); b2RevoluteJoint* joint = &base->revoluteJoint; b2Transform frameA = b2MulTransforms( transformA, base->localFrameA ); b2Transform frameB = b2MulTransforms( transformB, base->localFrameB ); const float radius = 0.25f * drawScale; draw->DrawCircleFcn( frameB.p, radius, b2_colorGray, draw->context ); b2Vec2 rx = { radius, 0.0f }; b2Vec2 r = b2RotateVector( frameA.q, rx ); draw->DrawLineFcn( frameA.p, b2Add( frameA.p, r ), b2_colorGray, draw->context ); r = b2RotateVector( frameB.q, rx ); draw->DrawLineFcn( frameB.p, b2Add( frameB.p, r ), b2_colorBlue, draw->context ); if ( draw->drawJointExtras ) { float jointAngle = b2RelativeAngle( frameA.q, frameB.q ); char buffer[32]; snprintf( buffer, 32, " %.1f deg", 180.0f * jointAngle / B2_PI ); draw->DrawStringFcn( b2Add( frameA.p, r ), buffer, b2_colorWhite, draw->context ); } float lowerAngle = joint->lowerAngle; float upperAngle = joint->upperAngle; if ( joint->enableLimit ) { b2Rot rotLo = b2MulRot( frameA.q, b2MakeRot( lowerAngle ) ); b2Vec2 rlo = b2RotateVector( rotLo, rx ); b2Rot rotHi = b2MulRot( frameA.q, b2MakeRot( upperAngle ) ); b2Vec2 rhi = b2RotateVector( rotHi, rx ); draw->DrawLineFcn( frameB.p, b2Add( frameB.p, rlo ), b2_colorGreen, draw->context ); draw->DrawLineFcn( frameB.p, b2Add( frameB.p, rhi ), b2_colorRed, draw->context ); } if ( joint->enableSpring ) { b2Rot q = b2MulRot( frameA.q, b2MakeRot( joint->targetAngle ) ); b2Vec2 v = b2RotateVector( q, rx ); draw->DrawLineFcn( frameB.p, b2Add( frameB.p, v ), b2_colorViolet, draw->context ); } b2HexColor color = b2_colorGold; draw->DrawLineFcn( transformA.p, frameA.p, color, draw->context ); draw->DrawLineFcn( frameA.p, frameB.p, color, draw->context ); draw->DrawLineFcn( transformB.p, frameB.p, color, draw->context ); // char buffer[32]; // sprintf(buffer, "%.1f", b2Length(joint->impulse)); // draw->DrawString(pA, buffer, draw->context); } ================================================ FILE: src/sensor.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "sensor.h" #include "array.h" #include "body.h" #include "contact.h" #include "ctz.h" #include "physics_world.h" #include "shape.h" #include "solver_set.h" #include "box2d/collision.h" #include #include B2_ARRAY_SOURCE( b2Visitor, b2Visitor ) B2_ARRAY_SOURCE( b2Sensor, b2Sensor ) B2_ARRAY_SOURCE( b2SensorTaskContext, b2SensorTaskContext ) B2_ARRAY_SOURCE( b2SensorHit, b2SensorHit ) struct b2SensorQueryContext { b2World* world; b2SensorTaskContext* taskContext; b2Sensor* sensor; b2Shape* sensorShape; b2Transform transform; }; // Sensor shapes need to // - detect begin and end overlap events // - events must be reported in deterministic order // - maintain an active list of overlaps for query // Assumption // - sensors don't detect shapes on the same body // Algorithm // Query all sensors for overlaps // Check against previous overlaps // Data structures // Each sensor has an double buffered array of overlaps // These overlaps use a shape reference with index and generation static bool b2SensorQueryCallback( int proxyId, uint64_t userData, void* context ) { B2_UNUSED( proxyId ); int shapeId = (int)userData; struct b2SensorQueryContext* queryContext = context; b2Shape* sensorShape = queryContext->sensorShape; int sensorShapeId = sensorShape->id; if ( shapeId == sensorShapeId ) { return true; } b2World* world = queryContext->world; b2Shape* otherShape = b2ShapeArray_Get( &world->shapes, shapeId ); // Are sensor events enabled on the other shape? if ( otherShape->enableSensorEvents == false ) { return true; } // Skip shapes on the same body if ( otherShape->bodyId == sensorShape->bodyId ) { return true; } // Check filter if ( b2ShouldShapesCollide( sensorShape->filter, otherShape->filter ) == false ) { return true; } // Custom user filter if ( sensorShape->enableCustomFiltering || otherShape->enableCustomFiltering ) { b2CustomFilterFcn* customFilterFcn = queryContext->world->customFilterFcn; if ( customFilterFcn != NULL ) { b2ShapeId idA = { sensorShapeId + 1, world->worldId, sensorShape->generation }; b2ShapeId idB = { shapeId + 1, world->worldId, otherShape->generation }; bool shouldCollide = customFilterFcn( idA, idB, queryContext->world->customFilterContext ); if ( shouldCollide == false ) { return true; } } } b2Transform otherTransform = b2GetBodyTransform( world, otherShape->bodyId ); b2DistanceInput input; input.proxyA = b2MakeShapeDistanceProxy( sensorShape ); input.proxyB = b2MakeShapeDistanceProxy( otherShape ); input.transformA = queryContext->transform; input.transformB = otherTransform; input.useRadii = true; b2SimplexCache cache = { 0 }; b2DistanceOutput output = b2ShapeDistance( &input, &cache, NULL, 0 ); bool overlaps = output.distance < 10.0f * FLT_EPSILON; if ( overlaps == false ) { return true; } // Record the overlap b2Sensor* sensor = queryContext->sensor; b2Visitor* shapeRef = b2VisitorArray_Add( &sensor->overlaps2 ); shapeRef->shapeId = shapeId; shapeRef->generation = otherShape->generation; return true; } static int b2CompareVisitors( const void* a, const void* b ) { const b2Visitor* sa = a; const b2Visitor* sb = b; if ( sa->shapeId < sb->shapeId ) { return -1; } return 1; } static void b2SensorTask( int startIndex, int endIndex, uint32_t threadIndex, void* context ) { b2TracyCZoneNC( sensor_task, "Overlap", b2_colorBrown, true ); b2World* world = context; B2_ASSERT( (int)threadIndex < world->workerCount ); b2SensorTaskContext* taskContext = world->sensorTaskContexts.data + threadIndex; B2_ASSERT( startIndex < endIndex ); b2DynamicTree* trees = world->broadPhase.trees; for ( int sensorIndex = startIndex; sensorIndex < endIndex; ++sensorIndex ) { b2Sensor* sensor = b2SensorArray_Get( &world->sensors, sensorIndex ); b2Shape* sensorShape = b2ShapeArray_Get( &world->shapes, sensor->shapeId ); // Swap overlap arrays b2VisitorArray temp = sensor->overlaps1; sensor->overlaps1 = sensor->overlaps2; sensor->overlaps2 = temp; b2VisitorArray_Clear( &sensor->overlaps2 ); // Append sensor hits int hitCount = sensor->hits.count; for ( int i = 0; i < hitCount; ++i ) { b2VisitorArray_Push( &sensor->overlaps2, sensor->hits.data[i] ); } // Clear the hits b2VisitorArray_Clear( &sensor->hits ); b2Body* body = b2BodyArray_Get( &world->bodies, sensorShape->bodyId ); if ( body->setIndex == b2_disabledSet || sensorShape->enableSensorEvents == false ) { if ( sensor->overlaps1.count != 0 ) { // This sensor is dropping all overlaps because it has been disabled. b2SetBit( &taskContext->eventBits, sensorIndex ); } continue; } b2Transform transform = b2GetBodyTransformQuick( world, body ); struct b2SensorQueryContext queryContext = { .world = world, .taskContext = taskContext, .sensor = sensor, .sensorShape = sensorShape, .transform = transform, }; B2_ASSERT( sensorShape->sensorIndex == sensorIndex ); b2AABB queryBounds = sensorShape->aabb; // Query all trees b2DynamicTree_Query( trees + 0, queryBounds, sensorShape->filter.maskBits, b2SensorQueryCallback, &queryContext ); b2DynamicTree_Query( trees + 1, queryBounds, sensorShape->filter.maskBits, b2SensorQueryCallback, &queryContext ); b2DynamicTree_Query( trees + 2, queryBounds, sensorShape->filter.maskBits, b2SensorQueryCallback, &queryContext ); // Sort the overlaps to enable finding begin and end events. qsort( sensor->overlaps2.data, sensor->overlaps2.count, sizeof( b2Visitor ), b2CompareVisitors ); // Remove duplicates from overlaps2 (sorted). Duplicates are possible due to the hit events appended earlier. int uniqueCount = 0; int overlapCount = sensor->overlaps2.count; b2Visitor* overlapData = sensor->overlaps2.data; for ( int i = 0; i < overlapCount; ++i ) { if ( uniqueCount == 0 || overlapData[i].shapeId != overlapData[uniqueCount - 1].shapeId ) { overlapData[uniqueCount] = overlapData[i]; uniqueCount += 1; } } sensor->overlaps2.count = uniqueCount; int count1 = sensor->overlaps1.count; int count2 = sensor->overlaps2.count; if ( count1 != count2 ) { // something changed b2SetBit( &taskContext->eventBits, sensorIndex ); } else { for ( int i = 0; i < count1; ++i ) { b2Visitor* s1 = sensor->overlaps1.data + i; b2Visitor* s2 = sensor->overlaps2.data + i; if ( s1->shapeId != s2->shapeId || s1->generation != s2->generation ) { // something changed b2SetBit( &taskContext->eventBits, sensorIndex ); break; } } } } b2TracyCZoneEnd( sensor_task ); } void b2OverlapSensors( b2World* world ) { int sensorCount = world->sensors.count; if ( sensorCount == 0 ) { return; } B2_ASSERT( world->workerCount > 0 ); b2TracyCZoneNC( overlap_sensors, "Sensors", b2_colorMediumPurple, true ); for ( int i = 0; i < world->workerCount; ++i ) { b2SetBitCountAndClear( &world->sensorTaskContexts.data[i].eventBits, sensorCount ); } // Parallel-for sensors overlaps int minRange = 16; void* userSensorTask = world->enqueueTaskFcn( &b2SensorTask, sensorCount, minRange, world, world->userTaskContext ); world->taskCount += 1; if ( userSensorTask != NULL ) { world->finishTaskFcn( userSensorTask, world->userTaskContext ); } b2TracyCZoneNC( sensor_state, "Events", b2_colorLightSlateGray, true ); b2BitSet* bitSet = &world->sensorTaskContexts.data[0].eventBits; for ( int i = 1; i < world->workerCount; ++i ) { b2InPlaceUnion( bitSet, &world->sensorTaskContexts.data[i].eventBits ); } // Iterate sensors bits and publish events // Process sensor state changes. Iterate over set bits uint64_t* bits = bitSet->bits; uint32_t blockCount = bitSet->blockCount; for ( uint32_t k = 0; k < blockCount; ++k ) { uint64_t word = bits[k]; while ( word != 0 ) { uint32_t ctz = b2CTZ64( word ); int sensorIndex = (int)( 64 * k + ctz ); b2Sensor* sensor = b2SensorArray_Get( &world->sensors, sensorIndex ); b2Shape* sensorShape = b2ShapeArray_Get( &world->shapes, sensor->shapeId ); b2ShapeId sensorId = { sensor->shapeId + 1, world->worldId, sensorShape->generation }; int count1 = sensor->overlaps1.count; int count2 = sensor->overlaps2.count; const b2Visitor* refs1 = sensor->overlaps1.data; const b2Visitor* refs2 = sensor->overlaps2.data; // overlaps1 can have overlaps that end // overlaps2 can have overlaps that begin int index1 = 0, index2 = 0; while ( index1 < count1 && index2 < count2 ) { const b2Visitor* r1 = refs1 + index1; const b2Visitor* r2 = refs2 + index2; if ( r1->shapeId == r2->shapeId ) { if ( r1->generation < r2->generation ) { // end b2ShapeId visitorId = { r1->shapeId + 1, world->worldId, r1->generation }; b2SensorEndTouchEvent event = { .sensorShapeId = sensorId, .visitorShapeId = visitorId, }; b2SensorEndTouchEventArray_Push( &world->sensorEndEvents[world->endEventArrayIndex], event ); index1 += 1; } else if ( r1->generation > r2->generation ) { // begin b2ShapeId visitorId = { r2->shapeId + 1, world->worldId, r2->generation }; b2SensorBeginTouchEvent event = { sensorId, visitorId }; b2SensorBeginTouchEventArray_Push( &world->sensorBeginEvents, event ); index2 += 1; } else { // persisted index1 += 1; index2 += 1; } } else if ( r1->shapeId < r2->shapeId ) { // end b2ShapeId visitorId = { r1->shapeId + 1, world->worldId, r1->generation }; b2SensorEndTouchEvent event = { sensorId, visitorId }; b2SensorEndTouchEventArray_Push( &world->sensorEndEvents[world->endEventArrayIndex], event ); index1 += 1; } else { // begin b2ShapeId visitorId = { r2->shapeId + 1, world->worldId, r2->generation }; b2SensorBeginTouchEvent event = { sensorId, visitorId }; b2SensorBeginTouchEventArray_Push( &world->sensorBeginEvents, event ); index2 += 1; } } while ( index1 < count1 ) { // end const b2Visitor* r1 = refs1 + index1; b2ShapeId visitorId = { r1->shapeId + 1, world->worldId, r1->generation }; b2SensorEndTouchEvent event = { sensorId, visitorId }; b2SensorEndTouchEventArray_Push( &world->sensorEndEvents[world->endEventArrayIndex], event ); index1 += 1; } while ( index2 < count2 ) { // begin const b2Visitor* r2 = refs2 + index2; b2ShapeId visitorId = { r2->shapeId + 1, world->worldId, r2->generation }; b2SensorBeginTouchEvent event = { sensorId, visitorId }; b2SensorBeginTouchEventArray_Push( &world->sensorBeginEvents, event ); index2 += 1; } // Clear the smallest set bit word = word & ( word - 1 ); } } b2TracyCZoneEnd( sensor_state ); b2TracyCZoneEnd( overlap_sensors ); } void b2DestroySensor( b2World* world, b2Shape* sensorShape ) { b2Sensor* sensor = b2SensorArray_Get( &world->sensors, sensorShape->sensorIndex ); for ( int i = 0; i < sensor->overlaps2.count; ++i ) { b2Visitor* ref = sensor->overlaps2.data + i; b2SensorEndTouchEvent event = { .sensorShapeId = { .index1 = sensorShape->id + 1, .world0 = world->worldId, .generation = sensorShape->generation, }, .visitorShapeId = { .index1 = ref->shapeId + 1, .world0 = world->worldId, .generation = ref->generation, }, }; b2SensorEndTouchEventArray_Push( world->sensorEndEvents + world->endEventArrayIndex, event ); } // Destroy sensor b2VisitorArray_Destroy( &sensor->hits ); b2VisitorArray_Destroy( &sensor->overlaps1 ); b2VisitorArray_Destroy( &sensor->overlaps2 ); int movedIndex = b2SensorArray_RemoveSwap( &world->sensors, sensorShape->sensorIndex ); if ( movedIndex != B2_NULL_INDEX ) { // Fixup moved sensor b2Sensor* movedSensor = b2SensorArray_Get( &world->sensors, sensorShape->sensorIndex ); b2Shape* otherSensorShape = b2ShapeArray_Get( &world->shapes, movedSensor->shapeId ); otherSensorShape->sensorIndex = sensorShape->sensorIndex; } } ================================================ FILE: src/sensor.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "array.h" #include "bitset.h" typedef struct b2Shape b2Shape; typedef struct b2World b2World; // Used to track shapes that hit sensors using time of impact typedef struct b2SensorHit { int sensorId; int visitorId; } b2SensorHit; typedef struct b2Visitor { int shapeId; uint16_t generation; } b2Visitor; typedef struct b2Sensor { // todo find a way to pool these b2VisitorArray hits; b2VisitorArray overlaps1; b2VisitorArray overlaps2; int shapeId; } b2Sensor; typedef struct b2SensorTaskContext { b2BitSet eventBits; } b2SensorTaskContext; void b2OverlapSensors( b2World* world ); void b2DestroySensor( b2World* world, b2Shape* sensorShape ); B2_ARRAY_INLINE( b2Sensor, b2Sensor ) B2_ARRAY_INLINE( b2SensorHit, b2SensorHit ) B2_ARRAY_INLINE( b2SensorTaskContext, b2SensorTaskContext ) B2_ARRAY_INLINE( b2Visitor, b2Visitor ) ================================================ FILE: src/shape.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "shape.h" #include "body.h" #include "broad_phase.h" #include "contact.h" #include "physics_world.h" #include "sensor.h" // needed for dll export #include "solver_set.h" #include "box2d/box2d.h" #include B2_ARRAY_SOURCE( b2ChainShape, b2ChainShape ) B2_ARRAY_SOURCE( b2Shape, b2Shape ) static b2Shape* b2GetShape( b2World* world, b2ShapeId shapeId ) { int id = shapeId.index1 - 1; b2Shape* shape = b2ShapeArray_Get( &world->shapes, id ); B2_ASSERT( shape->id == id && shape->generation == shapeId.generation ); return shape; } static b2ChainShape* b2GetChainShape( b2World* world, b2ChainId chainId ) { int id = chainId.index1 - 1; b2ChainShape* chain = b2ChainShapeArray_Get( &world->chainShapes, id ); B2_ASSERT( chain->id == id && chain->generation == chainId.generation ); return chain; } static void b2UpdateShapeAABBs( b2Shape* shape, b2Transform transform, b2BodyType proxyType ) { // Compute a bounding box with a speculative margin const float speculativeDistance = B2_SPECULATIVE_DISTANCE; const float aabbMargin = B2_AABB_MARGIN; b2AABB aabb = b2ComputeShapeAABB( shape, transform ); aabb.lowerBound.x -= speculativeDistance; aabb.lowerBound.y -= speculativeDistance; aabb.upperBound.x += speculativeDistance; aabb.upperBound.y += speculativeDistance; shape->aabb = aabb; // Smaller margin for static bodies. Cannot be zero due to TOI tolerance. float margin = proxyType == b2_staticBody ? speculativeDistance : aabbMargin; b2AABB fatAABB; fatAABB.lowerBound.x = aabb.lowerBound.x - margin; fatAABB.lowerBound.y = aabb.lowerBound.y - margin; fatAABB.upperBound.x = aabb.upperBound.x + margin; fatAABB.upperBound.y = aabb.upperBound.y + margin; shape->fatAABB = fatAABB; } static b2Shape* b2CreateShapeInternal( b2World* world, b2Body* body, b2Transform transform, const b2ShapeDef* def, const void* geometry, b2ShapeType shapeType ) { int shapeId = b2AllocId( &world->shapeIdPool ); if ( shapeId == world->shapes.count ) { b2ShapeArray_Push( &world->shapes, (b2Shape){ 0 } ); } else { B2_ASSERT( world->shapes.data[shapeId].id == B2_NULL_INDEX ); } b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); switch ( shapeType ) { case b2_capsuleShape: shape->capsule = *(const b2Capsule*)geometry; break; case b2_circleShape: shape->circle = *(const b2Circle*)geometry; break; case b2_polygonShape: shape->polygon = *(const b2Polygon*)geometry; break; case b2_segmentShape: shape->segment = *(const b2Segment*)geometry; break; case b2_chainSegmentShape: shape->chainSegment = *(const b2ChainSegment*)geometry; break; default: B2_ASSERT( false ); break; } shape->id = shapeId; shape->bodyId = body->id; shape->type = shapeType; shape->density = def->density; shape->material = def->material; shape->filter = def->filter; shape->userData = def->userData; shape->enlargedAABB = false; shape->enableSensorEvents = def->enableSensorEvents; shape->enableContactEvents = def->enableContactEvents; shape->enableCustomFiltering = def->enableCustomFiltering; shape->enableHitEvents = def->enableHitEvents; shape->enablePreSolveEvents = def->enablePreSolveEvents; shape->proxyKey = B2_NULL_INDEX; shape->localCentroid = b2GetShapeCentroid( shape ); shape->aabb = (b2AABB){ b2Vec2_zero, b2Vec2_zero }; shape->fatAABB = (b2AABB){ b2Vec2_zero, b2Vec2_zero }; shape->generation += 1; if ( body->setIndex != b2_disabledSet ) { b2BodyType proxyType = body->type; b2CreateShapeProxy( shape, &world->broadPhase, proxyType, transform, def->invokeContactCreation || def->isSensor ); } // Add to shape doubly linked list if ( body->headShapeId != B2_NULL_INDEX ) { b2Shape* headShape = b2ShapeArray_Get( &world->shapes, body->headShapeId ); headShape->prevShapeId = shapeId; } shape->prevShapeId = B2_NULL_INDEX; shape->nextShapeId = body->headShapeId; body->headShapeId = shapeId; body->shapeCount += 1; if ( def->isSensor ) { shape->sensorIndex = world->sensors.count; b2Sensor sensor = { .hits = b2VisitorArray_Create( 4 ), .overlaps1 = b2VisitorArray_Create( 16 ), .overlaps2 = b2VisitorArray_Create( 16 ), .shapeId = shapeId, }; b2SensorArray_Push( &world->sensors, sensor ); } else { shape->sensorIndex = B2_NULL_INDEX; } b2ValidateSolverSets( world ); return shape; } static b2ShapeId b2CreateShape( b2BodyId bodyId, const b2ShapeDef* def, const void* geometry, b2ShapeType shapeType ) { B2_CHECK_DEF( def ); B2_ASSERT( b2IsValidFloat( def->density ) && def->density >= 0.0f ); B2_ASSERT( b2IsValidFloat( def->material.friction ) && def->material.friction >= 0.0f ); B2_ASSERT( b2IsValidFloat( def->material.restitution ) && def->material.restitution >= 0.0f ); B2_ASSERT( b2IsValidFloat( def->material.rollingResistance ) && def->material.rollingResistance >= 0.0f ); B2_ASSERT( b2IsValidFloat( def->material.tangentSpeed ) ); b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return (b2ShapeId){ 0 }; } b2Body* body = b2GetBodyFullId( world, bodyId ); b2Transform transform = b2GetBodyTransformQuick( world, body ); b2Shape* shape = b2CreateShapeInternal( world, body, transform, def, geometry, shapeType ); if ( def->updateBodyMass == true ) { b2UpdateBodyMassData( world, body ); } else { body->flags |= b2_dirtyMass; } b2ValidateSolverSets( world ); b2ShapeId id = { shape->id + 1, bodyId.world0, shape->generation }; return id; } b2ShapeId b2CreateCircleShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Circle* circle ) { return b2CreateShape( bodyId, def, circle, b2_circleShape ); } b2ShapeId b2CreateCapsuleShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Capsule* capsule ) { float lengthSqr = b2DistanceSquared( capsule->center1, capsule->center2 ); if ( lengthSqr <= B2_LINEAR_SLOP * B2_LINEAR_SLOP ) { return b2_nullShapeId; } return b2CreateShape( bodyId, def, capsule, b2_capsuleShape ); } b2ShapeId b2CreatePolygonShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Polygon* polygon ) { B2_ASSERT( b2IsValidFloat( polygon->radius ) && polygon->radius >= 0.0f ); return b2CreateShape( bodyId, def, polygon, b2_polygonShape ); } b2ShapeId b2CreateSegmentShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Segment* segment ) { float lengthSqr = b2DistanceSquared( segment->point1, segment->point2 ); if ( lengthSqr <= B2_LINEAR_SLOP * B2_LINEAR_SLOP ) { B2_ASSERT( false ); return b2_nullShapeId; } return b2CreateShape( bodyId, def, segment, b2_segmentShape ); } // Destroy a shape on a body. This doesn't need to be called when destroying a body. static void b2DestroyShapeInternal( b2World* world, b2Shape* shape, b2Body* body, bool wakeBodies ) { int shapeId = shape->id; // Remove the shape from the body's doubly linked list. if ( shape->prevShapeId != B2_NULL_INDEX ) { b2Shape* prevShape = b2ShapeArray_Get( &world->shapes, shape->prevShapeId ); prevShape->nextShapeId = shape->nextShapeId; } if ( shape->nextShapeId != B2_NULL_INDEX ) { b2Shape* nextShape = b2ShapeArray_Get( &world->shapes, shape->nextShapeId ); nextShape->prevShapeId = shape->prevShapeId; } if ( shapeId == body->headShapeId ) { body->headShapeId = shape->nextShapeId; } body->shapeCount -= 1; // Remove from broad-phase. b2DestroyShapeProxy( shape, &world->broadPhase ); // Destroy any contacts associated with the shape. int contactKey = body->headContactKey; while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); contactKey = contact->edges[edgeIndex].nextKey; if ( contact->shapeIdA == shapeId || contact->shapeIdB == shapeId ) { b2DestroyContact( world, contact, wakeBodies ); } } if ( shape->sensorIndex != B2_NULL_INDEX ) { b2Sensor* sensor = b2SensorArray_Get( &world->sensors, shape->sensorIndex ); for ( int i = 0; i < sensor->overlaps2.count; ++i ) { b2Visitor* ref = sensor->overlaps2.data + i; b2SensorEndTouchEvent event = { .sensorShapeId = { .index1 = shapeId + 1, .world0 = world->worldId, .generation = shape->generation, }, .visitorShapeId = { .index1 = ref->shapeId + 1, .world0 = world->worldId, .generation = ref->generation, }, }; b2SensorEndTouchEventArray_Push( world->sensorEndEvents + world->endEventArrayIndex, event ); } // Destroy sensor b2VisitorArray_Destroy( &sensor->hits ); b2VisitorArray_Destroy( &sensor->overlaps1 ); b2VisitorArray_Destroy( &sensor->overlaps2 ); int movedIndex = b2SensorArray_RemoveSwap( &world->sensors, shape->sensorIndex ); if ( movedIndex != B2_NULL_INDEX ) { // Fixup moved sensor b2Sensor* movedSensor = b2SensorArray_Get( &world->sensors, shape->sensorIndex ); b2Shape* otherSensorShape = b2ShapeArray_Get( &world->shapes, movedSensor->shapeId ); otherSensorShape->sensorIndex = shape->sensorIndex; } } // Return shape to free list. b2FreeId( &world->shapeIdPool, shapeId ); shape->id = B2_NULL_INDEX; b2ValidateSolverSets( world ); } void b2DestroyShape( b2ShapeId shapeId, bool updateBodyMass ) { b2World* world = b2GetWorldLocked( shapeId.world0 ); if ( world == NULL ) { return; } b2Shape* shape = b2GetShape( world, shapeId ); // need to wake bodies because this might be a static body bool wakeBodies = true; b2Body* body = b2BodyArray_Get( &world->bodies, shape->bodyId ); b2DestroyShapeInternal( world, shape, body, wakeBodies ); if ( updateBodyMass == true ) { b2UpdateBodyMassData( world, body ); } } b2ChainId b2CreateChain( b2BodyId bodyId, const b2ChainDef* def ) { B2_CHECK_DEF( def ); B2_ASSERT( def->count >= 4 ); B2_ASSERT( def->materialCount == 1 || def->materialCount == def->count ); b2World* world = b2GetWorldLocked( bodyId.world0 ); if ( world == NULL ) { return (b2ChainId){ 0 }; } b2Body* body = b2GetBodyFullId( world, bodyId ); b2Transform transform = b2GetBodyTransformQuick( world, body ); int chainId = b2AllocId( &world->chainIdPool ); if ( chainId == world->chainShapes.count ) { b2ChainShapeArray_Push( &world->chainShapes, (b2ChainShape){ 0 } ); } else { B2_ASSERT( world->chainShapes.data[chainId].id == B2_NULL_INDEX ); } b2ChainShape* chainShape = b2ChainShapeArray_Get( &world->chainShapes, chainId ); chainShape->id = chainId; chainShape->bodyId = body->id; chainShape->nextChainId = body->headChainId; chainShape->generation += 1; int materialCount = def->materialCount; chainShape->materialCount = materialCount; chainShape->materials = b2Alloc( materialCount * sizeof( b2SurfaceMaterial ) ); for ( int i = 0; i < materialCount; ++i ) { const b2SurfaceMaterial* material = def->materials + i; B2_ASSERT( b2IsValidFloat( material->friction ) && material->friction >= 0.0f ); B2_ASSERT( b2IsValidFloat( material->restitution ) && material->restitution >= 0.0f ); B2_ASSERT( b2IsValidFloat( material->rollingResistance ) && material->rollingResistance >= 0.0f ); B2_ASSERT( b2IsValidFloat( material->tangentSpeed ) ); chainShape->materials[i] = *material; } body->headChainId = chainId; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.userData = def->userData; shapeDef.filter = def->filter; shapeDef.enableSensorEvents = def->enableSensorEvents; shapeDef.enableContactEvents = false; shapeDef.enableHitEvents = false; const b2Vec2* points = def->points; int n = def->count; if ( def->isLoop ) { chainShape->count = n; chainShape->shapeIndices = b2Alloc( chainShape->count * sizeof( int ) ); b2ChainSegment chainSegment; int prevIndex = n - 1; for ( int i = 0; i < n - 2; ++i ) { chainSegment.ghost1 = points[prevIndex]; chainSegment.segment.point1 = points[i]; chainSegment.segment.point2 = points[i + 1]; chainSegment.ghost2 = points[i + 2]; chainSegment.chainId = chainId; prevIndex = i; int materialIndex = materialCount == 1 ? 0 : i; shapeDef.material = def->materials[materialIndex]; b2Shape* shape = b2CreateShapeInternal( world, body, transform, &shapeDef, &chainSegment, b2_chainSegmentShape ); chainShape->shapeIndices[i] = shape->id; } { chainSegment.ghost1 = points[n - 3]; chainSegment.segment.point1 = points[n - 2]; chainSegment.segment.point2 = points[n - 1]; chainSegment.ghost2 = points[0]; chainSegment.chainId = chainId; int materialIndex = materialCount == 1 ? 0 : n - 2; shapeDef.material = def->materials[materialIndex]; b2Shape* shape = b2CreateShapeInternal( world, body, transform, &shapeDef, &chainSegment, b2_chainSegmentShape ); chainShape->shapeIndices[n - 2] = shape->id; } { chainSegment.ghost1 = points[n - 2]; chainSegment.segment.point1 = points[n - 1]; chainSegment.segment.point2 = points[0]; chainSegment.ghost2 = points[1]; chainSegment.chainId = chainId; int materialIndex = materialCount == 1 ? 0 : n - 1; shapeDef.material = def->materials[materialIndex]; b2Shape* shape = b2CreateShapeInternal( world, body, transform, &shapeDef, &chainSegment, b2_chainSegmentShape ); chainShape->shapeIndices[n - 1] = shape->id; } } else { chainShape->count = n - 3; chainShape->shapeIndices = b2Alloc( chainShape->count * sizeof( int ) ); b2ChainSegment chainSegment; for ( int i = 0; i < n - 3; ++i ) { chainSegment.ghost1 = points[i]; chainSegment.segment.point1 = points[i + 1]; chainSegment.segment.point2 = points[i + 2]; chainSegment.ghost2 = points[i + 3]; chainSegment.chainId = chainId; // Material is associated with leading point of solid segment int materialIndex = materialCount == 1 ? 0 : i + 1; shapeDef.material = def->materials[materialIndex]; b2Shape* shape = b2CreateShapeInternal( world, body, transform, &shapeDef, &chainSegment, b2_chainSegmentShape ); chainShape->shapeIndices[i] = shape->id; } } b2ChainId id = { chainId + 1, world->worldId, chainShape->generation }; return id; } void b2FreeChainData( b2ChainShape* chain ) { b2Free( chain->shapeIndices, chain->count * sizeof( int ) ); chain->shapeIndices = NULL; b2Free( chain->materials, chain->materialCount * sizeof( b2SurfaceMaterial ) ); chain->materials = NULL; } void b2DestroyChain( b2ChainId chainId ) { b2World* world = b2GetWorldLocked( chainId.world0 ); if ( world == NULL ) { return; } b2ChainShape* chain = b2GetChainShape( world, chainId ); b2Body* body = b2BodyArray_Get( &world->bodies, chain->bodyId ); // Remove the chain from the body's singly linked list. int* chainIdPtr = &body->headChainId; bool found = false; while ( *chainIdPtr != B2_NULL_INDEX ) { if ( *chainIdPtr == chain->id ) { *chainIdPtr = chain->nextChainId; found = true; break; } chainIdPtr = &( world->chainShapes.data[*chainIdPtr].nextChainId ); } B2_ASSERT( found == true ); if ( found == false ) { return; } int count = chain->count; for ( int i = 0; i < count; ++i ) { int shapeId = chain->shapeIndices[i]; b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); bool wakeBodies = true; b2DestroyShapeInternal( world, shape, body, wakeBodies ); } b2FreeChainData( chain ); // Return chain to free list. b2FreeId( &world->chainIdPool, chain->id ); chain->id = B2_NULL_INDEX; b2ValidateSolverSets( world ); } b2WorldId b2Chain_GetWorld( b2ChainId chainId ) { b2World* world = b2GetWorld( chainId.world0 ); return (b2WorldId){ chainId.world0 + 1, world->generation }; } int b2Chain_GetSegmentCount( b2ChainId chainId ) { b2World* world = b2GetWorldLocked( chainId.world0 ); if ( world == NULL ) { return 0; } b2ChainShape* chain = b2GetChainShape( world, chainId ); return chain->count; } int b2Chain_GetSegments( b2ChainId chainId, b2ShapeId* segmentArray, int capacity ) { b2World* world = b2GetWorldLocked( chainId.world0 ); if ( world == NULL ) { return 0; } b2ChainShape* chain = b2GetChainShape( world, chainId ); int count = b2MinInt( chain->count, capacity ); for ( int i = 0; i < count; ++i ) { int shapeId = chain->shapeIndices[i]; b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); segmentArray[i] = (b2ShapeId){ shapeId + 1, chainId.world0, shape->generation }; } return count; } b2AABB b2ComputeShapeAABB( const b2Shape* shape, b2Transform xf ) { switch ( shape->type ) { case b2_capsuleShape: return b2ComputeCapsuleAABB( &shape->capsule, xf ); case b2_circleShape: return b2ComputeCircleAABB( &shape->circle, xf ); case b2_polygonShape: return b2ComputePolygonAABB( &shape->polygon, xf ); case b2_segmentShape: return b2ComputeSegmentAABB( &shape->segment, xf ); case b2_chainSegmentShape: return b2ComputeSegmentAABB( &shape->chainSegment.segment, xf ); default: { B2_ASSERT( false ); b2AABB empty = { xf.p, xf.p }; return empty; } } } b2Vec2 b2GetShapeCentroid( const b2Shape* shape ) { switch ( shape->type ) { case b2_capsuleShape: return b2Lerp( shape->capsule.center1, shape->capsule.center2, 0.5f ); case b2_circleShape: return shape->circle.center; case b2_polygonShape: return shape->polygon.centroid; case b2_segmentShape: return b2Lerp( shape->segment.point1, shape->segment.point2, 0.5f ); case b2_chainSegmentShape: return b2Lerp( shape->chainSegment.segment.point1, shape->chainSegment.segment.point2, 0.5f ); default: return b2Vec2_zero; } } // todo_erin maybe compute this on shape creation float b2GetShapePerimeter( const b2Shape* shape ) { switch ( shape->type ) { case b2_capsuleShape: return 2.0f * b2Length( b2Sub( shape->capsule.center1, shape->capsule.center2 ) ) + 2.0f * B2_PI * shape->capsule.radius; case b2_circleShape: return 2.0f * B2_PI * shape->circle.radius; case b2_polygonShape: { const b2Vec2* points = shape->polygon.vertices; int count = shape->polygon.count; float perimeter = 2.0f * B2_PI * shape->polygon.radius; B2_ASSERT( count > 0 ); b2Vec2 prev = points[count - 1]; for ( int i = 0; i < count; ++i ) { b2Vec2 next = points[i]; perimeter += b2Length( b2Sub( next, prev ) ); prev = next; } return perimeter; } case b2_segmentShape: return 2.0f * b2Length( b2Sub( shape->segment.point1, shape->segment.point2 ) ); case b2_chainSegmentShape: return 2.0f * b2Length( b2Sub( shape->chainSegment.segment.point1, shape->chainSegment.segment.point2 ) ); default: return 0.0f; } } // This projects the shape perimeter onto an infinite line float b2GetShapeProjectedPerimeter( const b2Shape* shape, b2Vec2 line ) { switch ( shape->type ) { case b2_capsuleShape: { b2Vec2 axis = b2Sub( shape->capsule.center2, shape->capsule.center1 ); float projectedLength = b2AbsFloat( b2Dot( axis, line ) ); return projectedLength + 2.0f * shape->capsule.radius; } case b2_circleShape: return 2.0f * shape->circle.radius; case b2_polygonShape: { const b2Vec2* points = shape->polygon.vertices; int count = shape->polygon.count; B2_ASSERT( count > 0 ); float value = b2Dot( points[0], line ); float lower = value; float upper = value; for ( int i = 1; i < count; ++i ) { value = b2Dot( points[i], line ); lower = b2MinFloat( lower, value ); upper = b2MaxFloat( upper, value ); } return ( upper - lower ) + 2.0f * shape->polygon.radius; } case b2_segmentShape: { float value1 = b2Dot( shape->segment.point1, line ); float value2 = b2Dot( shape->segment.point2, line ); return b2AbsFloat( value2 - value1 ); } case b2_chainSegmentShape: { float value1 = b2Dot( shape->chainSegment.segment.point1, line ); float value2 = b2Dot( shape->chainSegment.segment.point2, line ); return b2AbsFloat( value2 - value1 ); } default: return 0.0f; } } b2MassData b2ComputeShapeMass( const b2Shape* shape ) { switch ( shape->type ) { case b2_capsuleShape: return b2ComputeCapsuleMass( &shape->capsule, shape->density ); case b2_circleShape: return b2ComputeCircleMass( &shape->circle, shape->density ); case b2_polygonShape: return b2ComputePolygonMass( &shape->polygon, shape->density ); default: return (b2MassData){ 0 }; } } b2ShapeExtent b2ComputeShapeExtent( const b2Shape* shape, b2Vec2 localCenter ) { b2ShapeExtent extent = { 0 }; switch ( shape->type ) { case b2_capsuleShape: { float radius = shape->capsule.radius; extent.minExtent = radius; b2Vec2 c1 = b2Sub( shape->capsule.center1, localCenter ); b2Vec2 c2 = b2Sub( shape->capsule.center2, localCenter ); extent.maxExtent = sqrtf( b2MaxFloat( b2LengthSquared( c1 ), b2LengthSquared( c2 ) ) ) + radius; } break; case b2_circleShape: { float radius = shape->circle.radius; extent.minExtent = radius; extent.maxExtent = b2Length( b2Sub( shape->circle.center, localCenter ) ) + radius; } break; case b2_polygonShape: { const b2Polygon* poly = &shape->polygon; float minExtent = B2_HUGE; float maxExtentSqr = 0.0f; int count = poly->count; for ( int i = 0; i < count; ++i ) { b2Vec2 v = poly->vertices[i]; float planeOffset = b2Dot( poly->normals[i], b2Sub( v, poly->centroid ) ); minExtent = b2MinFloat( minExtent, planeOffset ); float distanceSqr = b2LengthSquared( b2Sub( v, localCenter ) ); maxExtentSqr = b2MaxFloat( maxExtentSqr, distanceSqr ); } extent.minExtent = minExtent + poly->radius; extent.maxExtent = sqrtf( maxExtentSqr ) + poly->radius; } break; case b2_segmentShape: { extent.minExtent = 0.0f; b2Vec2 c1 = b2Sub( shape->segment.point1, localCenter ); b2Vec2 c2 = b2Sub( shape->segment.point2, localCenter ); extent.maxExtent = sqrtf( b2MaxFloat( b2LengthSquared( c1 ), b2LengthSquared( c2 ) ) ); } break; case b2_chainSegmentShape: { extent.minExtent = 0.0f; b2Vec2 c1 = b2Sub( shape->chainSegment.segment.point1, localCenter ); b2Vec2 c2 = b2Sub( shape->chainSegment.segment.point2, localCenter ); extent.maxExtent = sqrtf( b2MaxFloat( b2LengthSquared( c1 ), b2LengthSquared( c2 ) ) ); } break; default: break; } return extent; } b2CastOutput b2RayCastShape( const b2RayCastInput* input, const b2Shape* shape, b2Transform transform ) { b2RayCastInput localInput = *input; localInput.origin = b2InvTransformPoint( transform, input->origin ); localInput.translation = b2InvRotateVector( transform.q, input->translation ); b2CastOutput output = { 0 }; switch ( shape->type ) { case b2_capsuleShape: output = b2RayCastCapsule( &shape->capsule, &localInput ); break; case b2_circleShape: output = b2RayCastCircle( &shape->circle, &localInput ); break; case b2_polygonShape: output = b2RayCastPolygon( &shape->polygon, &localInput ); break; case b2_segmentShape: output = b2RayCastSegment( &shape->segment, &localInput, false ); break; case b2_chainSegmentShape: output = b2RayCastSegment( &shape->chainSegment.segment, &localInput, true ); break; default: return output; } output.point = b2TransformPoint( transform, output.point ); output.normal = b2RotateVector( transform.q, output.normal ); return output; } b2CastOutput b2ShapeCastShape( const b2ShapeCastInput* input, const b2Shape* shape, b2Transform transform ) { b2CastOutput output = { 0 }; if ( input->proxy.count == 0 ) { return output; } b2ShapeCastInput localInput = *input; for ( int i = 0; i < localInput.proxy.count; ++i ) { localInput.proxy.points[i] = b2InvTransformPoint( transform, input->proxy.points[i] ); } localInput.translation = b2InvRotateVector( transform.q, input->translation ); switch ( shape->type ) { case b2_capsuleShape: output = b2ShapeCastCapsule( &shape->capsule, &localInput ); break; case b2_circleShape: output = b2ShapeCastCircle( &shape->circle, &localInput ); break; case b2_polygonShape: output = b2ShapeCastPolygon( &shape->polygon, &localInput ); break; case b2_segmentShape: output = b2ShapeCastSegment( &shape->segment, &localInput ); break; case b2_chainSegmentShape: { // Check for back side collision b2Vec2 approximateCentroid = localInput.proxy.points[0]; for ( int i = 1; i < localInput.proxy.count; ++i ) { approximateCentroid = b2Add( approximateCentroid, localInput.proxy.points[i] ); } approximateCentroid = b2MulSV( 1.0f / localInput.proxy.count, approximateCentroid ); b2Vec2 edge = b2Sub( shape->chainSegment.segment.point2, shape->chainSegment.segment.point1 ); b2Vec2 r = b2Sub( approximateCentroid, shape->chainSegment.segment.point1 ); if ( b2Cross( r, edge ) < 0.0f ) { // Shape cast starts behind return output; } output = b2ShapeCastSegment( &shape->chainSegment.segment, &localInput ); } break; default: return output; } output.point = b2TransformPoint( transform, output.point ); output.normal = b2RotateVector( transform.q, output.normal ); return output; } b2PlaneResult b2CollideMover( const b2Capsule* mover, const b2Shape* shape, b2Transform transform ) { b2Capsule localMover; localMover.center1 = b2InvTransformPoint( transform, mover->center1 ); localMover.center2 = b2InvTransformPoint( transform, mover->center2 ); localMover.radius = mover->radius; b2PlaneResult result = { 0 }; switch ( shape->type ) { case b2_capsuleShape: result = b2CollideMoverAndCapsule( &localMover, &shape->capsule ); break; case b2_circleShape: result = b2CollideMoverAndCircle( &localMover, &shape->circle ); break; case b2_polygonShape: result = b2CollideMoverAndPolygon( &localMover, &shape->polygon ); break; case b2_segmentShape: result = b2CollideMoverAndSegment( &localMover, &shape->segment ); break; case b2_chainSegmentShape: result = b2CollideMoverAndSegment( &localMover, &shape->chainSegment.segment ); break; default: return result; } if ( result.hit == false ) { return result; } result.plane.normal = b2RotateVector( transform.q, result.plane.normal ); return result; } void b2CreateShapeProxy( b2Shape* shape, b2BroadPhase* bp, b2BodyType type, b2Transform transform, bool forcePairCreation ) { B2_ASSERT( shape->proxyKey == B2_NULL_INDEX ); b2UpdateShapeAABBs( shape, transform, type ); // Create proxies in the broad-phase. shape->proxyKey = b2BroadPhase_CreateProxy( bp, type, shape->fatAABB, shape->filter.categoryBits, shape->id, forcePairCreation ); B2_ASSERT( B2_PROXY_TYPE( shape->proxyKey ) < b2_bodyTypeCount ); } void b2DestroyShapeProxy( b2Shape* shape, b2BroadPhase* bp ) { if ( shape->proxyKey != B2_NULL_INDEX ) { b2BroadPhase_DestroyProxy( bp, shape->proxyKey ); shape->proxyKey = B2_NULL_INDEX; } } b2ShapeProxy b2MakeShapeDistanceProxy( const b2Shape* shape ) { switch ( shape->type ) { case b2_capsuleShape: return b2MakeProxy( &shape->capsule.center1, 2, shape->capsule.radius ); case b2_circleShape: return b2MakeProxy( &shape->circle.center, 1, shape->circle.radius ); case b2_polygonShape: return b2MakeProxy( shape->polygon.vertices, shape->polygon.count, shape->polygon.radius ); case b2_segmentShape: return b2MakeProxy( &shape->segment.point1, 2, 0.0f ); case b2_chainSegmentShape: return b2MakeProxy( &shape->chainSegment.segment.point1, 2, 0.0f ); default: { B2_ASSERT( false ); b2ShapeProxy empty = { 0 }; return empty; } } } b2BodyId b2Shape_GetBody( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); return b2MakeBodyId( world, shape->bodyId ); } b2WorldId b2Shape_GetWorld( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); return (b2WorldId){ shapeId.world0 + 1, world->generation }; } void b2Shape_SetUserData( b2ShapeId shapeId, void* userData ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); shape->userData = userData; } void* b2Shape_GetUserData( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); return shape->userData; } bool b2Shape_IsSensor( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); return shape->sensorIndex != B2_NULL_INDEX; } bool b2Shape_TestPoint( b2ShapeId shapeId, b2Vec2 point ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); b2Transform transform = b2GetBodyTransform( world, shape->bodyId ); b2Vec2 localPoint = b2InvTransformPoint( transform, point ); switch ( shape->type ) { case b2_capsuleShape: return b2PointInCapsule( &shape->capsule, localPoint ); case b2_circleShape: return b2PointInCircle( &shape->circle, localPoint ); case b2_polygonShape: return b2PointInPolygon( &shape->polygon, localPoint ); default: return false; } } // todo_erin untested b2CastOutput b2Shape_RayCast( b2ShapeId shapeId, const b2RayCastInput* input ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); b2Transform transform = b2GetBodyTransform( world, shape->bodyId ); // input in local coordinates b2RayCastInput localInput; localInput.origin = b2InvTransformPoint( transform, input->origin ); localInput.translation = b2InvRotateVector( transform.q, input->translation ); localInput.maxFraction = input->maxFraction; b2CastOutput output = { 0 }; switch ( shape->type ) { case b2_capsuleShape: output = b2RayCastCapsule( &shape->capsule, &localInput ); break; case b2_circleShape: output = b2RayCastCircle( &shape->circle, &localInput ); break; case b2_segmentShape: output = b2RayCastSegment( &shape->segment, &localInput, false ); break; case b2_polygonShape: output = b2RayCastPolygon( &shape->polygon, &localInput ); break; case b2_chainSegmentShape: output = b2RayCastSegment( &shape->chainSegment.segment, &localInput, true ); break; default: B2_ASSERT( false ); return output; } if ( output.hit ) { // convert to world coordinates output.normal = b2RotateVector( transform.q, output.normal ); output.point = b2TransformPoint( transform, output.point ); } return output; } void b2Shape_SetDensity( b2ShapeId shapeId, float density, bool updateBodyMass ) { B2_ASSERT( b2IsValidFloat( density ) && density >= 0.0f ); b2World* world = b2GetWorldLocked( shapeId.world0 ); if ( world == NULL ) { return; } b2Shape* shape = b2GetShape( world, shapeId ); if ( density == shape->density ) { // early return to avoid expensive function return; } shape->density = density; if ( updateBodyMass == true ) { b2Body* body = b2BodyArray_Get( &world->bodies, shape->bodyId ); b2UpdateBodyMassData( world, body ); } } float b2Shape_GetDensity( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); return shape->density; } void b2Shape_SetFriction( b2ShapeId shapeId, float friction ) { B2_ASSERT( b2IsValidFloat( friction ) && friction >= 0.0f ); b2World* world = b2GetWorld( shapeId.world0 ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return; } b2Shape* shape = b2GetShape( world, shapeId ); shape->material.friction = friction; } float b2Shape_GetFriction( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); return shape->material.friction; } void b2Shape_SetRestitution( b2ShapeId shapeId, float restitution ) { B2_ASSERT( b2IsValidFloat( restitution ) && restitution >= 0.0f ); b2World* world = b2GetWorld( shapeId.world0 ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return; } b2Shape* shape = b2GetShape( world, shapeId ); shape->material.restitution = restitution; } float b2Shape_GetRestitution( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); return shape->material.restitution; } void b2Shape_SetUserMaterial( b2ShapeId shapeId, uint64_t material ) { b2World* world = b2GetWorld( shapeId.world0 ); B2_ASSERT( world->locked == false ); if ( world->locked ) { return; } b2Shape* shape = b2GetShape( world, shapeId ); shape->material.userMaterialId = material; } uint64_t b2Shape_GetUserMaterial( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); return shape->material.userMaterialId; } b2SurfaceMaterial b2Shape_GetSurfaceMaterial( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); return shape->material; } void b2Shape_SetSurfaceMaterial( b2ShapeId shapeId, const b2SurfaceMaterial* surfaceMaterial ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); shape->material = *surfaceMaterial; } b2Filter b2Shape_GetFilter( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); return shape->filter; } static void b2ResetProxy( b2World* world, b2Shape* shape, bool wakeBodies, bool destroyProxy ) { b2Body* body = b2BodyArray_Get( &world->bodies, shape->bodyId ); int shapeId = shape->id; // destroy all contacts associated with this shape int contactKey = body->headContactKey; while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); contactKey = contact->edges[edgeIndex].nextKey; if ( contact->shapeIdA == shapeId || contact->shapeIdB == shapeId ) { b2DestroyContact( world, contact, wakeBodies ); } } b2Transform transform = b2GetBodyTransformQuick( world, body ); if ( shape->proxyKey != B2_NULL_INDEX ) { b2BodyType proxyType = B2_PROXY_TYPE( shape->proxyKey ); b2UpdateShapeAABBs( shape, transform, proxyType ); if ( destroyProxy ) { b2BroadPhase_DestroyProxy( &world->broadPhase, shape->proxyKey ); bool forcePairCreation = true; shape->proxyKey = b2BroadPhase_CreateProxy( &world->broadPhase, proxyType, shape->fatAABB, shape->filter.categoryBits, shapeId, forcePairCreation ); } else { b2BroadPhase_MoveProxy( &world->broadPhase, shape->proxyKey, shape->fatAABB ); } } else { b2BodyType proxyType = body->type; b2UpdateShapeAABBs( shape, transform, proxyType ); } b2ValidateSolverSets( world ); } void b2Shape_SetFilter( b2ShapeId shapeId, b2Filter filter ) { b2World* world = b2GetWorldLocked( shapeId.world0 ); if ( world == NULL ) { return; } b2Shape* shape = b2GetShape( world, shapeId ); if ( filter.maskBits == shape->filter.maskBits && filter.categoryBits == shape->filter.categoryBits && filter.groupIndex == shape->filter.groupIndex ) { return; } // If the category bits change, I need to destroy the proxy because it affects the tree sorting. bool destroyProxy = filter.categoryBits != shape->filter.categoryBits; shape->filter = filter; // need to wake bodies because a filter change may destroy contacts bool wakeBodies = true; b2ResetProxy( world, shape, wakeBodies, destroyProxy ); // note: this does not immediately update sensor overlaps. Instead sensor // overlaps are updated the next time step } void b2Shape_EnableSensorEvents( b2ShapeId shapeId, bool flag ) { b2World* world = b2GetWorldLocked( shapeId.world0 ); if ( world == NULL ) { return; } b2Shape* shape = b2GetShape( world, shapeId ); shape->enableSensorEvents = flag; } bool b2Shape_AreSensorEventsEnabled( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); return shape->enableSensorEvents; } void b2Shape_EnableContactEvents( b2ShapeId shapeId, bool flag ) { b2World* world = b2GetWorldLocked( shapeId.world0 ); if ( world == NULL ) { return; } b2Shape* shape = b2GetShape( world, shapeId ); shape->enableContactEvents = flag; } bool b2Shape_AreContactEventsEnabled( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); return shape->enableContactEvents; } void b2Shape_EnablePreSolveEvents( b2ShapeId shapeId, bool flag ) { b2World* world = b2GetWorldLocked( shapeId.world0 ); if ( world == NULL ) { return; } b2Shape* shape = b2GetShape( world, shapeId ); shape->enablePreSolveEvents = flag; } bool b2Shape_ArePreSolveEventsEnabled( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); return shape->enablePreSolveEvents; } void b2Shape_EnableHitEvents( b2ShapeId shapeId, bool flag ) { b2World* world = b2GetWorldLocked( shapeId.world0 ); if ( world == NULL ) { return; } b2Shape* shape = b2GetShape( world, shapeId ); shape->enableHitEvents = flag; } bool b2Shape_AreHitEventsEnabled( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); return shape->enableHitEvents; } b2ShapeType b2Shape_GetType( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); return shape->type; } b2Circle b2Shape_GetCircle( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); B2_ASSERT( shape->type == b2_circleShape ); return shape->circle; } b2Segment b2Shape_GetSegment( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); B2_ASSERT( shape->type == b2_segmentShape ); return shape->segment; } b2ChainSegment b2Shape_GetChainSegment( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); B2_ASSERT( shape->type == b2_chainSegmentShape ); return shape->chainSegment; } b2Capsule b2Shape_GetCapsule( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); B2_ASSERT( shape->type == b2_capsuleShape ); return shape->capsule; } b2Polygon b2Shape_GetPolygon( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); B2_ASSERT( shape->type == b2_polygonShape ); return shape->polygon; } void b2Shape_SetCircle( b2ShapeId shapeId, const b2Circle* circle ) { b2World* world = b2GetWorldLocked( shapeId.world0 ); if ( world == NULL ) { return; } b2Shape* shape = b2GetShape( world, shapeId ); shape->circle = *circle; shape->type = b2_circleShape; // need to wake bodies so they can react to the shape change bool wakeBodies = true; bool destroyProxy = true; b2ResetProxy( world, shape, wakeBodies, destroyProxy ); } void b2Shape_SetCapsule( b2ShapeId shapeId, const b2Capsule* capsule ) { b2World* world = b2GetWorldLocked( shapeId.world0 ); if ( world == NULL ) { return; } float lengthSqr = b2DistanceSquared( capsule->center1, capsule->center2 ); if ( lengthSqr <= B2_LINEAR_SLOP * B2_LINEAR_SLOP ) { return; } b2Shape* shape = b2GetShape( world, shapeId ); shape->capsule = *capsule; shape->type = b2_capsuleShape; // need to wake bodies so they can react to the shape change bool wakeBodies = true; bool destroyProxy = true; b2ResetProxy( world, shape, wakeBodies, destroyProxy ); } void b2Shape_SetSegment( b2ShapeId shapeId, const b2Segment* segment ) { b2World* world = b2GetWorldLocked( shapeId.world0 ); if ( world == NULL ) { return; } b2Shape* shape = b2GetShape( world, shapeId ); shape->segment = *segment; shape->type = b2_segmentShape; // need to wake bodies so they can react to the shape change bool wakeBodies = true; bool destroyProxy = true; b2ResetProxy( world, shape, wakeBodies, destroyProxy ); } void b2Shape_SetPolygon( b2ShapeId shapeId, const b2Polygon* polygon ) { b2World* world = b2GetWorldLocked( shapeId.world0 ); if ( world == NULL ) { return; } b2Shape* shape = b2GetShape( world, shapeId ); shape->polygon = *polygon; shape->type = b2_polygonShape; // need to wake bodies so they can react to the shape change bool wakeBodies = true; bool destroyProxy = true; b2ResetProxy( world, shape, wakeBodies, destroyProxy ); } b2ChainId b2Shape_GetParentChain( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); b2Shape* shape = b2GetShape( world, shapeId ); if ( shape->type == b2_chainSegmentShape ) { int chainId = shape->chainSegment.chainId; if ( chainId != B2_NULL_INDEX ) { b2ChainShape* chain = b2ChainShapeArray_Get( &world->chainShapes, chainId ); b2ChainId id = { chainId + 1, shapeId.world0, chain->generation }; return id; } } return (b2ChainId){ 0 }; } int b2Chain_GetSurfaceMaterialCount( b2ChainId chainId ) { b2World* world = b2GetWorld( chainId.world0 ); b2ChainShape* chainShape = b2GetChainShape( world, chainId ); return chainShape->materialCount; } void b2Chain_SetSurfaceMaterial( b2ChainId chainId, const b2SurfaceMaterial* material, int materialIndex ) { b2World* world = b2GetWorldLocked( chainId.world0 ); if ( world == NULL ) { return; } b2ChainShape* chainShape = b2GetChainShape( world, chainId ); B2_ASSERT( 0 <= materialIndex && materialIndex < chainShape->materialCount ); chainShape->materials[materialIndex] = *material; B2_ASSERT( chainShape->materialCount == 1 || chainShape->materialCount == chainShape->count ); int count = chainShape->count; if ( chainShape->materialCount == 1 ) { for ( int i = 0; i < count; ++i ) { int shapeId = chainShape->shapeIndices[i]; b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); shape->material = *material; } } else { int shapeId = chainShape->shapeIndices[materialIndex]; b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); shape->material = *material; } } b2SurfaceMaterial b2Chain_GetSurfaceMaterial( b2ChainId chainId, int segmentIndex ) { b2World* world = b2GetWorld( chainId.world0 ); b2ChainShape* chainShape = b2GetChainShape( world, chainId ); B2_ASSERT( 0 <= segmentIndex && segmentIndex < chainShape->count ); return chainShape->materials[segmentIndex]; } int b2Shape_GetContactCapacity( b2ShapeId shapeId ) { b2World* world = b2GetWorldLocked( shapeId.world0 ); if ( world == NULL ) { return 0; } b2Shape* shape = b2GetShape( world, shapeId ); if ( shape->sensorIndex != B2_NULL_INDEX ) { return 0; } b2Body* body = b2BodyArray_Get( &world->bodies, shape->bodyId ); // Conservative and fast return body->contactCount; } int b2Shape_GetContactData( b2ShapeId shapeId, b2ContactData* contactData, int capacity ) { b2World* world = b2GetWorldLocked( shapeId.world0 ); if ( world == NULL ) { return 0; } b2Shape* shape = b2GetShape( world, shapeId ); if ( shape->sensorIndex != B2_NULL_INDEX ) { return 0; } b2Body* body = b2BodyArray_Get( &world->bodies, shape->bodyId ); int contactKey = body->headContactKey; int index = 0; while ( contactKey != B2_NULL_INDEX && index < capacity ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); // Does contact involve this shape and is it touching? if ( ( contact->shapeIdA == shapeId.index1 - 1 || contact->shapeIdB == shapeId.index1 - 1 ) && ( contact->flags & b2_contactTouchingFlag ) != 0 ) { b2Shape* shapeA = world->shapes.data + contact->shapeIdA; b2Shape* shapeB = world->shapes.data + contact->shapeIdB; contactData[index].contactId = (b2ContactId){ contact->contactId + 1, shapeId.world0, 0, contact->generation }; contactData[index].shapeIdA = (b2ShapeId){ shapeA->id + 1, shapeId.world0, shapeA->generation }; contactData[index].shapeIdB = (b2ShapeId){ shapeB->id + 1, shapeId.world0, shapeB->generation }; b2ContactSim* contactSim = b2GetContactSim( world, contact ); contactData[index].manifold = contactSim->manifold; index += 1; } contactKey = contact->edges[edgeIndex].nextKey; } B2_ASSERT( index <= capacity ); return index; } int b2Shape_GetSensorCapacity( b2ShapeId shapeId ) { b2World* world = b2GetWorldLocked( shapeId.world0 ); if ( world == NULL ) { return 0; } b2Shape* shape = b2GetShape( world, shapeId ); if ( shape->sensorIndex == B2_NULL_INDEX ) { return 0; } b2Sensor* sensor = b2SensorArray_Get( &world->sensors, shape->sensorIndex ); return sensor->overlaps2.count; } int b2Shape_GetSensorData( b2ShapeId shapeId, b2ShapeId* visitorIds, int capacity ) { b2World* world = b2GetWorldLocked( shapeId.world0 ); if ( world == NULL ) { return 0; } b2Shape* shape = b2GetShape( world, shapeId ); if ( shape->sensorIndex == B2_NULL_INDEX ) { return 0; } b2Sensor* sensor = b2SensorArray_Get( &world->sensors, shape->sensorIndex ); int count = b2MinInt( sensor->overlaps2.count, capacity ); b2Visitor* refs = sensor->overlaps2.data; for ( int i = 0; i < count; ++i ) { b2ShapeId visitorId = { .index1 = refs[i].shapeId + 1, .world0 = shapeId.world0, .generation = refs[i].generation, }; visitorIds[i] = visitorId; } return count; } b2AABB b2Shape_GetAABB( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); if ( world == NULL ) { return (b2AABB){ 0 }; } b2Shape* shape = b2GetShape( world, shapeId ); return shape->aabb; } b2MassData b2Shape_ComputeMassData( b2ShapeId shapeId ) { b2World* world = b2GetWorld( shapeId.world0 ); if ( world == NULL ) { return (b2MassData){ 0 }; } b2Shape* shape = b2GetShape( world, shapeId ); return b2ComputeShapeMass( shape ); } b2Vec2 b2Shape_GetClosestPoint( b2ShapeId shapeId, b2Vec2 target ) { b2World* world = b2GetWorld( shapeId.world0 ); if ( world == NULL ) { return (b2Vec2){ 0 }; } b2Shape* shape = b2GetShape( world, shapeId ); b2Body* body = b2BodyArray_Get( &world->bodies, shape->bodyId ); b2Transform transform = b2GetBodyTransformQuick( world, body ); b2DistanceInput input; input.proxyA = b2MakeShapeDistanceProxy( shape ); input.proxyB = b2MakeProxy( &target, 1, 0.0f ); input.transformA = transform; input.transformB = b2Transform_identity; input.useRadii = true; b2SimplexCache cache = { 0 }; b2DistanceOutput output = b2ShapeDistance( &input, &cache, NULL, 0 ); return output.pointA; } // https://en.wikipedia.org/wiki/Density_of_air // https://www.engineeringtoolbox.com/wind-load-d_1775.html // force = 0.5 * air_density * velocity^2 * area // https://en.wikipedia.org/wiki/Lift_(force) void b2Shape_ApplyWind( b2ShapeId shapeId, b2Vec2 wind, float drag, float lift, bool wake ) { b2World* world = b2GetWorld( shapeId.world0 ); if ( world == NULL ) { return; } b2Shape* shape = b2GetShape( world, shapeId ); b2ShapeType shapeType = shape->type; if ( shapeType != b2_circleShape && shapeType != b2_capsuleShape && shapeType != b2_polygonShape ) { return; } b2Body* body = b2BodyArray_Get( &world->bodies, shape->bodyId ); if ( body->type != b2_dynamicBody ) { return; } if ( body->setIndex >= b2_firstSleepingSet && wake == false ) { return; } b2BodySim* sim = b2GetBodySim( world, body ); if ( body->setIndex != b2_awakeSet ) { // Must wake for state to exist b2WakeBody( world, body ); } B2_ASSERT( body->setIndex == b2_awakeSet ); b2BodyState* state = b2GetBodyState( world, body ); b2Transform transform = sim->transform; float lengthUnits = b2_lengthUnitsPerMeter; float volumeUnits = lengthUnits * lengthUnits * lengthUnits; // In 2D I'm assuming unit depth float airDensity = 1.2250f / ( volumeUnits ); b2Vec2 force = { 0 }; float torque = 0.0f; switch ( shape->type ) { case b2_circleShape: { float radius = shape->circle.radius; b2Vec2 centroid = shape->localCentroid; b2Vec2 lever = b2RotateVector( transform.q, b2Sub( centroid, sim->localCenter ) ); b2Vec2 shapeVelocity = b2Add( state->linearVelocity, b2CrossSV( state->angularVelocity, lever ) ); b2Vec2 relativeVelocity = b2MulSub( wind, drag, shapeVelocity ); float speed; b2Vec2 direction = b2GetLengthAndNormalize( &speed, relativeVelocity ); float projectedArea = 2.0f * radius; force = b2MulSV( 0.5f * airDensity * projectedArea * speed * speed, direction ); torque = b2Cross( lever, force ); } break; case b2_capsuleShape: { b2Vec2 centroid = shape->localCentroid; b2Vec2 lever = b2RotateVector( transform.q, b2Sub( centroid, sim->localCenter ) ); b2Vec2 shapeVelocity = b2Add( state->linearVelocity, b2CrossSV( state->angularVelocity, lever ) ); b2Vec2 relativeVelocity = b2MulSub( wind, drag, shapeVelocity ); float speed; b2Vec2 direction = b2GetLengthAndNormalize( &speed, relativeVelocity ); b2Vec2 d = b2Sub( shape->capsule.center2, shape->capsule.center1 ); d = b2RotateVector( transform.q, d ); float radius = shape->capsule.radius; float projectedArea = 2.0f * radius + b2AbsFloat( b2Cross(d, direction) ); // Normal that opposes the wind b2Vec2 normal = b2LeftPerp( b2Normalize(d) ); normal = b2Dot( normal, direction ) > 0.0f ? b2Neg( normal ) : normal; // portion of wind that is perpendicular to surface b2Vec2 liftDirection = b2CrossSV( b2Cross( normal, direction ), direction ); float forceMagnitude = 0.5f * airDensity * projectedArea * speed * speed; force = b2MulSV( forceMagnitude, b2MulAdd( direction, lift, liftDirection ) ); b2Vec2 edgeLever = b2MulAdd( lever, radius, normal ); torque = b2Cross( edgeLever, force ); } break; case b2_polygonShape: { b2Vec2 centroid = shape->localCentroid; b2Vec2 lever = b2RotateVector( transform.q, b2Sub( centroid, sim->localCenter ) ); b2Vec2 shapeVelocity = b2Add( state->linearVelocity, b2CrossSV( state->angularVelocity, lever ) ); b2Vec2 relativeVelocity = b2MulSub( wind, drag, shapeVelocity ); float speed; b2Vec2 direction = b2GetLengthAndNormalize( &speed, relativeVelocity ); // polygon radius is ignored for simplicity int count = shape->polygon.count; b2Vec2* vertices = shape->polygon.vertices; b2Vec2 v1 = vertices[count - 1]; for ( int i = 0; i < count; ++i ) { b2Vec2 v2 = vertices[i]; b2Vec2 d = b2Sub( v2, v1 ); b2Vec2 edgeCenter = b2Lerp( v1, v2, 0.5f ); v1 = v2; d = b2RotateVector( transform.q, d ); float projectedArea = b2Cross( d, direction ); if ( projectedArea <= 0.0f ) { // back facing continue; } b2Vec2 normal = b2RightPerp( b2Normalize( d ) ); // portion of wind that is perpendicular to surface b2Vec2 liftDirection = b2CrossSV( b2Cross( normal, direction ), direction ); float forceMagnitude = 0.5f * airDensity * projectedArea * speed * speed; b2Vec2 f = b2MulSV( forceMagnitude, b2MulAdd( direction, lift, liftDirection ) ); b2Vec2 edgeLever = b2RotateVector( transform.q, b2Sub( edgeCenter, sim->localCenter ) ); force = b2Add( force, f ); torque += b2Cross( edgeLever, f ); } } break; default: break; } sim->force = b2Add( sim->force, force ); sim->torque += torque; } ================================================ FILE: src/shape.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "array.h" #include "box2d/types.h" typedef struct b2BroadPhase b2BroadPhase; typedef struct b2World b2World; typedef struct b2Shape { int id; int bodyId; int prevShapeId; int nextShapeId; int sensorIndex; b2ShapeType type; b2SurfaceMaterial material; float density; b2AABB aabb; b2AABB fatAABB; b2Vec2 localCentroid; int proxyKey; b2Filter filter; void* userData; union { b2Capsule capsule; b2Circle circle; b2Polygon polygon; b2Segment segment; b2ChainSegment chainSegment; }; uint16_t generation; bool enableSensorEvents; bool enableContactEvents; bool enableCustomFiltering; bool enableHitEvents; bool enablePreSolveEvents; bool enlargedAABB; } b2Shape; typedef struct b2ChainShape { int id; int bodyId; int nextChainId; int count; int materialCount; int* shapeIndices; b2SurfaceMaterial* materials; uint16_t generation; } b2ChainShape; typedef struct b2ShapeExtent { float minExtent; float maxExtent; } b2ShapeExtent; // Sensors are shapes that live in the broad-phase but never have contacts. // At the end of the time step all sensors are queried for overlap with any other shapes. // Sensors ignore body type and sleeping. // Sensors generate events when there is a new overlap or and overlap disappears. // The sensor overlaps don't get cleared until the next time step regardless of the overlapped // shapes being destroyed. // When a sensor is destroyed. typedef struct { b2IntArray overlaps; } b2SensorOverlaps; void b2CreateShapeProxy( b2Shape* shape, b2BroadPhase* bp, b2BodyType type, b2Transform transform, bool forcePairCreation ); void b2DestroyShapeProxy( b2Shape* shape, b2BroadPhase* bp ); void b2FreeChainData( b2ChainShape* chain ); b2MassData b2ComputeShapeMass( const b2Shape* shape ); b2ShapeExtent b2ComputeShapeExtent( const b2Shape* shape, b2Vec2 localCenter ); b2AABB b2ComputeShapeAABB( const b2Shape* shape, b2Transform transform ); b2Vec2 b2GetShapeCentroid( const b2Shape* shape ); float b2GetShapePerimeter( const b2Shape* shape ); float b2GetShapeProjectedPerimeter( const b2Shape* shape, b2Vec2 line ); b2ShapeProxy b2MakeShapeDistanceProxy( const b2Shape* shape ); b2CastOutput b2RayCastShape( const b2RayCastInput* input, const b2Shape* shape, b2Transform transform ); b2CastOutput b2ShapeCastShape( const b2ShapeCastInput* input, const b2Shape* shape, b2Transform transform ); b2PlaneResult b2CollideMoverAndCircle( const b2Capsule* mover, const b2Circle* shape ); b2PlaneResult b2CollideMoverAndCapsule( const b2Capsule* mover, const b2Capsule* shape ); b2PlaneResult b2CollideMoverAndPolygon( const b2Capsule* mover, const b2Polygon* shape ); b2PlaneResult b2CollideMoverAndSegment( const b2Capsule* mover, const b2Segment* shape ); b2PlaneResult b2CollideMover( const b2Capsule* mover, const b2Shape* shape, b2Transform transform ); static inline float b2GetShapeRadius( const b2Shape* shape ) { switch ( shape->type ) { case b2_capsuleShape: return shape->capsule.radius; case b2_circleShape: return shape->circle.radius; case b2_polygonShape: return shape->polygon.radius; default: return 0.0f; } } static inline bool b2ShouldShapesCollide( b2Filter filterA, b2Filter filterB ) { if ( filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0 ) { return filterA.groupIndex > 0; } return ( filterA.maskBits & filterB.categoryBits ) != 0 && ( filterA.categoryBits & filterB.maskBits ) != 0; } static inline bool b2ShouldQueryCollide( b2Filter shapeFilter, b2QueryFilter queryFilter ) { return ( shapeFilter.categoryBits & queryFilter.maskBits ) != 0 && ( shapeFilter.maskBits & queryFilter.categoryBits ) != 0; } B2_ARRAY_INLINE( b2ChainShape, b2ChainShape ) B2_ARRAY_INLINE( b2Shape, b2Shape ) ================================================ FILE: src/solver.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "solver.h" #include "arena_allocator.h" #include "array.h" #include "atomic.h" #include "bitset.h" #include "body.h" #include "contact.h" #include "contact_solver.h" #include "core.h" #include "ctz.h" #include "island.h" #include "joint.h" #include "physics_world.h" #include "sensor.h" #include "shape.h" #include "solver_set.h" #include #include #include // todo testing #define ITERATIONS 1 #define RELAX_ITERATIONS 1 // Compare to SDL_CPUPauseInstruction #if ( defined( __GNUC__ ) || defined( __clang__ ) ) && ( defined( __i386__ ) || defined( __x86_64__ ) ) static inline void b2Pause( void ) { __asm__ __volatile__( "pause\n" ); } #elif ( defined( __arm__ ) && defined( __ARM_ARCH ) && __ARM_ARCH >= 7 ) || defined( __aarch64__ ) static inline void b2Pause( void ) { __asm__ __volatile__( "yield" ::: "memory" ); } #elif defined( _MSC_VER ) && ( defined( _M_IX86 ) || defined( _M_X64 ) ) static inline void b2Pause( void ) { _mm_pause(); } #elif defined( _MSC_VER ) && ( defined( _M_ARM ) || defined( _M_ARM64 ) ) static inline void b2Pause( void ) { __yield(); } #else static inline void b2Pause( void ) { } #endif typedef struct b2WorkerContext { b2StepContext* context; int workerIndex; void* userTask; } b2WorkerContext; // Integrate velocities and apply damping static void b2IntegrateVelocitiesTask( int startIndex, int endIndex, b2StepContext* context ) { b2TracyCZoneNC( integrate_velocity, "IntVel", b2_colorDeepPink, true ); b2BodyState* states = context->states; b2BodySim* sims = context->sims; b2Vec2 gravity = context->world->gravity; float h = context->h; float maxLinearSpeed = context->maxLinearVelocity; float maxAngularSpeed = B2_MAX_ROTATION * context->inv_dt; float maxLinearSpeedSquared = maxLinearSpeed * maxLinearSpeed; float maxAngularSpeedSquared = maxAngularSpeed * maxAngularSpeed; for ( int i = startIndex; i < endIndex; ++i ) { b2BodySim* sim = sims + i; b2BodyState* state = states + i; b2Vec2 v = state->linearVelocity; float w = state->angularVelocity; // Apply forces, torque, gravity, and damping // Apply damping. // Differential equation: dv/dt + c * v = 0 // Solution: v(t) = v0 * exp(-c * t) // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v(t) * exp(-c * dt) // v2 = exp(-c * dt) * v1 // Pade approximation: // v2 = v1 * 1 / (1 + c * dt) float linearDamping = 1.0f / ( 1.0f + h * sim->linearDamping ); float angularDamping = 1.0f / ( 1.0f + h * sim->angularDamping ); // Gravity scale will be zero for kinematic bodies float gravityScale = sim->invMass > 0.0f ? sim->gravityScale : 0.0f; // lvd = h * im * f + h * g b2Vec2 linearVelocityDelta = b2Add( b2MulSV( h * sim->invMass, sim->force ), b2MulSV( h * gravityScale, gravity ) ); float angularVelocityDelta = h * sim->invInertia * sim->torque; v = b2MulAdd( linearVelocityDelta, linearDamping, v ); w = angularVelocityDelta + angularDamping * w; // Clamp to max linear speed if ( b2Dot( v, v ) > maxLinearSpeedSquared ) { float ratio = maxLinearSpeed / b2Length( v ); v = b2MulSV( ratio, v ); sim->flags |= b2_isSpeedCapped; } // Clamp to max angular speed if ( w * w > maxAngularSpeedSquared && ( sim->flags & b2_allowFastRotation ) == 0 ) { float ratio = maxAngularSpeed / b2AbsFloat( w ); w *= ratio; sim->flags |= b2_isSpeedCapped; } if ( state->flags & b2_lockLinearX ) { v.x = 0.0f; } if ( state->flags & b2_lockLinearY ) { v.y = 0.0f; } if ( state->flags & b2_lockAngularZ ) { w = 0.0f; } state->linearVelocity = v; state->angularVelocity = w; } b2TracyCZoneEnd( integrate_velocity ); } static void b2PrepareJointsTask( int startIndex, int endIndex, b2StepContext* context ) { b2TracyCZoneNC( prepare_joints, "PrepJoints", b2_colorOldLace, true ); b2JointSim** joints = context->joints; for ( int i = startIndex; i < endIndex; ++i ) { b2JointSim* joint = joints[i]; b2PrepareJoint( joint, context ); } b2TracyCZoneEnd( prepare_joints ); } static void b2WarmStartJointsTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex ) { b2TracyCZoneNC( warm_joints, "WarmJoints", b2_colorGold, true ); b2GraphColor* color = context->graph->colors + colorIndex; b2JointSim* joints = color->jointSims.data; B2_ASSERT( 0 <= startIndex && startIndex < color->jointSims.count ); B2_ASSERT( startIndex <= endIndex && endIndex <= color->jointSims.count ); for ( int i = startIndex; i < endIndex; ++i ) { b2JointSim* joint = joints + i; b2WarmStartJoint( joint, context ); } b2TracyCZoneEnd( warm_joints ); } static void b2SolveJointsTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex, bool useBias, int workerIndex ) { b2TracyCZoneNC( solve_joints, "SolveJoints", b2_colorLemonChiffon, true ); b2GraphColor* color = context->graph->colors + colorIndex; b2JointSim* joints = color->jointSims.data; B2_ASSERT( 0 <= startIndex && startIndex < color->jointSims.count ); B2_ASSERT( startIndex <= endIndex && endIndex <= color->jointSims.count ); b2BitSet* jointStateBitSet = &context->world->taskContexts.data[workerIndex].jointStateBitSet; for ( int i = startIndex; i < endIndex; ++i ) { b2JointSim* joint = joints + i; b2SolveJoint( joint, context, useBias ); if ( useBias && ( joint->forceThreshold < FLT_MAX || joint->torqueThreshold < FLT_MAX ) && b2GetBit( jointStateBitSet, joint->jointId ) == false ) { float force, torque; b2GetJointReaction( joint, context->inv_h, &force, &torque ); // Check thresholds. A zero threshold means all awake joints get reported. if ( force >= joint->forceThreshold || torque >= joint->torqueThreshold ) { // Flag this joint for processing. b2SetBit( jointStateBitSet, joint->jointId ); } } } b2TracyCZoneEnd( solve_joints ); } static void b2IntegratePositionsTask( int startIndex, int endIndex, b2StepContext* context ) { b2TracyCZoneNC( integrate_positions, "IntPos", b2_colorDarkSeaGreen, true ); b2BodyState* states = context->states; float h = context->h; B2_ASSERT( startIndex <= endIndex ); for ( int i = startIndex; i < endIndex; ++i ) { b2BodyState* state = states + i; if ( state->flags & b2_lockLinearX ) { state->linearVelocity.x = 0.0f; } if ( state->flags & b2_lockLinearY ) { state->linearVelocity.y = 0.0f; } if ( state->flags & b2_lockAngularZ ) { state->angularVelocity = 0.0f; } state->deltaPosition = b2MulAdd( state->deltaPosition, h, state->linearVelocity ); state->deltaRotation = b2IntegrateRotation( state->deltaRotation, h * state->angularVelocity ); } b2TracyCZoneEnd( integrate_positions ); } #define B2_MAX_CONTINUOUS_SENSOR_HITS 8 struct b2ContinuousContext { b2World* world; b2BodySim* fastBodySim; b2Shape* fastShape; b2Vec2 centroid1, centroid2; b2Sweep sweep; float fraction; b2SensorHit sensorHits[B2_MAX_CONTINUOUS_SENSOR_HITS]; float sensorFractions[B2_MAX_CONTINUOUS_SENSOR_HITS]; int sensorCount; }; #define B2_CORE_FRACTION 0.25f // This is called from b2DynamicTree_Query for continuous collision static bool b2ContinuousQueryCallback( int proxyId, uint64_t userData, void* context ) { B2_UNUSED( proxyId ); int shapeId = (int)userData; struct b2ContinuousContext* continuousContext = context; b2Shape* fastShape = continuousContext->fastShape; b2BodySim* fastBodySim = continuousContext->fastBodySim; B2_ASSERT( fastShape->sensorIndex == B2_NULL_INDEX ); // Skip same shape if ( shapeId == fastShape->id ) { return true; } b2World* world = continuousContext->world; b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); // Skip same body if ( shape->bodyId == fastShape->bodyId ) { return true; } bool isSensor = shape->sensorIndex != B2_NULL_INDEX; // Skip sensors unless the shapes want sensor events if ( isSensor && ( shape->enableSensorEvents == false || fastShape->enableSensorEvents == false ) ) { return true; } // Skip filtered shapes bool canCollide = b2ShouldShapesCollide( fastShape->filter, shape->filter ); if ( canCollide == false ) { return true; } b2Body* body = b2BodyArray_Get( &world->bodies, shape->bodyId ); b2BodySim* bodySim = b2GetBodySim( world, body ); B2_ASSERT( body->type == b2_staticBody || ( fastBodySim->flags & b2_isBullet ) ); // Skip bullets if ( bodySim->flags & b2_isBullet ) { return true; } // Skip filtered bodies b2Body* fastBody = b2BodyArray_Get( &world->bodies, fastBodySim->bodyId ); canCollide = b2ShouldBodiesCollide( world, fastBody, body ); if ( canCollide == false ) { return true; } // Custom user filtering if ( shape->enableCustomFiltering || fastShape->enableCustomFiltering ) { b2CustomFilterFcn* customFilterFcn = world->customFilterFcn; if ( customFilterFcn != NULL ) { b2ShapeId idA = { shape->id + 1, world->worldId, shape->generation }; b2ShapeId idB = { fastShape->id + 1, world->worldId, fastShape->generation }; canCollide = customFilterFcn( idA, idB, world->customFilterContext ); if ( canCollide == false ) { return true; } } } // Early out on fast parallel movement over a chain shape. if ( shape->type == b2_chainSegmentShape ) { b2Transform transform = bodySim->transform; b2Vec2 p1 = b2TransformPoint( transform, shape->chainSegment.segment.point1 ); b2Vec2 p2 = b2TransformPoint( transform, shape->chainSegment.segment.point2 ); b2Vec2 e = b2Sub( p2, p1 ); float length; e = b2GetLengthAndNormalize( &length, e ); if ( length > B2_LINEAR_SLOP ) { b2Vec2 c1 = continuousContext->centroid1; float separation1 = b2Cross( b2Sub( c1, p1 ), e ); b2Vec2 c2 = continuousContext->centroid2; float separation2 = b2Cross( b2Sub( c2, p1 ), e ); float coreDistance = B2_CORE_FRACTION * fastBodySim->minExtent; if ( separation1 < 0.0f || ( separation1 - separation2 < coreDistance && separation2 > coreDistance ) ) { // Minimal clipping return true; } } } // todo_erin testing early out for segments #if 0 if ( shape->type == b2_segmentShape ) { b2Transform transform = bodySim->transform; b2Vec2 p1 = b2TransformPoint( transform, shape->segment.point1 ); b2Vec2 p2 = b2TransformPoint( transform, shape->segment.point2 ); b2Vec2 e = b2Sub( p2, p1 ); b2Vec2 c1 = continuousContext->centroid1; b2Vec2 c2 = continuousContext->centroid2; float offset1 = b2Cross( b2Sub( c1, p1 ), e ); float offset2 = b2Cross( b2Sub( c2, p1 ), e ); if ( offset1 > 0.0f && offset2 > 0.0f ) { // Started behind or finished in front return true; } if ( offset1 < 0.0f && offset2 < 0.0f ) { // Started behind or finished in front return true; } } #endif b2TOIInput input; input.proxyA = b2MakeShapeDistanceProxy( shape ); input.proxyB = b2MakeShapeDistanceProxy( fastShape ); input.sweepA = b2MakeSweep( bodySim ); input.sweepB = continuousContext->sweep; input.maxFraction = continuousContext->fraction; b2TOIOutput output = b2TimeOfImpact( &input ); if ( isSensor ) { // Only accept a sensor hit that is sooner than the current solid hit. if ( output.fraction <= continuousContext->fraction && continuousContext->sensorCount < B2_MAX_CONTINUOUS_SENSOR_HITS ) { int index = continuousContext->sensorCount; // The hit shape is a sensor b2SensorHit sensorHit = { .sensorId = shape->id, .visitorId = fastShape->id, }; continuousContext->sensorHits[index] = sensorHit; continuousContext->sensorFractions[index] = output.fraction; continuousContext->sensorCount += 1; } } else { float hitFraction = continuousContext->fraction; bool didHit = false; if ( 0.0f < output.fraction && output.fraction < continuousContext->fraction ) { hitFraction = output.fraction; didHit = true; } else if ( 0.0f == output.fraction ) { // fallback to TOI of a small circle around the fast shape centroid b2Vec2 centroid = b2GetShapeCentroid( fastShape ); b2ShapeExtent extent = b2ComputeShapeExtent( fastShape, centroid ); float radius = B2_CORE_FRACTION * extent.minExtent; input.proxyB = b2MakeProxy( ¢roid, 1, radius ); output = b2TimeOfImpact( &input ); if ( 0.0f < output.fraction && output.fraction < continuousContext->fraction ) { hitFraction = output.fraction; didHit = true; } } if ( didHit && ( shape->enablePreSolveEvents || fastShape->enablePreSolveEvents ) && world->preSolveFcn != NULL ) { b2ShapeId shapeIdA = { shape->id + 1, world->worldId, shape->generation }; b2ShapeId shapeIdB = { fastShape->id + 1, world->worldId, fastShape->generation }; didHit = world->preSolveFcn( shapeIdA, shapeIdB, output.point, output.normal, world->preSolveContext ); } if ( didHit ) { fastBodySim->flags |= b2_hadTimeOfImpact; continuousContext->fraction = hitFraction; } } // Continue query return true; } static void b2SolveContinuous( b2World* world, int bodySimIndex, b2TaskContext* taskContext ) { b2TracyCZoneNC( ccd, "CCD", b2_colorDarkGoldenRod, true ); b2SolverSet* awakeSet = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); b2BodySim* fastBodySim = b2BodySimArray_Get( &awakeSet->bodySims, bodySimIndex ); B2_ASSERT( fastBodySim->flags & b2_isFast ); b2Sweep sweep = b2MakeSweep( fastBodySim ); b2Transform xf1; xf1.q = sweep.q1; xf1.p = b2Sub( sweep.c1, b2RotateVector( sweep.q1, sweep.localCenter ) ); b2Transform xf2; xf2.q = sweep.q2; xf2.p = b2Sub( sweep.c2, b2RotateVector( sweep.q2, sweep.localCenter ) ); b2DynamicTree* staticTree = world->broadPhase.trees + b2_staticBody; b2DynamicTree* kinematicTree = world->broadPhase.trees + b2_kinematicBody; b2DynamicTree* dynamicTree = world->broadPhase.trees + b2_dynamicBody; b2Body* fastBody = b2BodyArray_Get( &world->bodies, fastBodySim->bodyId ); struct b2ContinuousContext context = { 0 }; context.world = world; context.sweep = sweep; context.fastBodySim = fastBodySim; context.fraction = 1.0f; bool isBullet = ( fastBodySim->flags & b2_isBullet ) != 0; int shapeId = fastBody->headShapeId; while ( shapeId != B2_NULL_INDEX ) { b2Shape* fastShape = b2ShapeArray_Get( &world->shapes, shapeId ); shapeId = fastShape->nextShapeId; context.fastShape = fastShape; context.centroid1 = b2TransformPoint( xf1, fastShape->localCentroid ); context.centroid2 = b2TransformPoint( xf2, fastShape->localCentroid ); b2AABB box1 = fastShape->aabb; b2AABB box2 = b2ComputeShapeAABB( fastShape, xf2 ); // Store this to avoid double computation in the case there is no impact event fastShape->aabb = box2; // No continuous collision for sensors (but still need the updated bounds) if ( fastShape->sensorIndex != B2_NULL_INDEX ) { continue; } b2AABB sweptBox = b2AABB_Union( box1, box2 ); b2DynamicTree_Query( staticTree, sweptBox, B2_DEFAULT_MASK_BITS, b2ContinuousQueryCallback, &context ); if ( isBullet ) { b2DynamicTree_Query( kinematicTree, sweptBox, B2_DEFAULT_MASK_BITS, b2ContinuousQueryCallback, &context ); b2DynamicTree_Query( dynamicTree, sweptBox, B2_DEFAULT_MASK_BITS, b2ContinuousQueryCallback, &context ); } } const float speculativeDistance = B2_SPECULATIVE_DISTANCE; const float aabbMargin = B2_AABB_MARGIN; if ( context.fraction < 1.0f ) { // Handle time of impact event b2Rot q = b2NLerp( sweep.q1, sweep.q2, context.fraction ); b2Vec2 c = b2Lerp( sweep.c1, sweep.c2, context.fraction ); b2Vec2 origin = b2Sub( c, b2RotateVector( q, sweep.localCenter ) ); // Advance body b2Transform transform = { origin, q }; fastBodySim->transform = transform; fastBodySim->center = c; fastBodySim->rotation0 = q; fastBodySim->center0 = c; // Update body move event b2BodyMoveEvent* event = b2BodyMoveEventArray_Get( &world->bodyMoveEvents, bodySimIndex ); event->transform = transform; // Prepare AABBs for broad-phase. // Even though a body is fast, it may not move much. So the AABB may not need enlargement. shapeId = fastBody->headShapeId; while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); // Must recompute aabb at the interpolated transform b2AABB aabb = b2ComputeShapeAABB( shape, transform ); aabb.lowerBound.x -= speculativeDistance; aabb.lowerBound.y -= speculativeDistance; aabb.upperBound.x += speculativeDistance; aabb.upperBound.y += speculativeDistance; shape->aabb = aabb; if ( b2AABB_Contains( shape->fatAABB, aabb ) == false ) { b2AABB fatAABB; fatAABB.lowerBound.x = aabb.lowerBound.x - aabbMargin; fatAABB.lowerBound.y = aabb.lowerBound.y - aabbMargin; fatAABB.upperBound.x = aabb.upperBound.x + aabbMargin; fatAABB.upperBound.y = aabb.upperBound.y + aabbMargin; shape->fatAABB = fatAABB; shape->enlargedAABB = true; fastBodySim->flags |= b2_enlargeBounds; } shapeId = shape->nextShapeId; } } else { // No time of impact event // Advance body fastBodySim->rotation0 = fastBodySim->transform.q; fastBodySim->center0 = fastBodySim->center; // Prepare AABBs for broad-phase shapeId = fastBody->headShapeId; while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); // shape->aabb is still valid from above if ( b2AABB_Contains( shape->fatAABB, shape->aabb ) == false ) { b2AABB fatAABB; fatAABB.lowerBound.x = shape->aabb.lowerBound.x - aabbMargin; fatAABB.lowerBound.y = shape->aabb.lowerBound.y - aabbMargin; fatAABB.upperBound.x = shape->aabb.upperBound.x + aabbMargin; fatAABB.upperBound.y = shape->aabb.upperBound.y + aabbMargin; shape->fatAABB = fatAABB; shape->enlargedAABB = true; fastBodySim->flags |= b2_enlargeBounds; } shapeId = shape->nextShapeId; } } // Push sensor hits on the the task context for serial processing. for ( int i = 0; i < context.sensorCount; ++i ) { // Skip any sensor hits that occurred after a solid hit if ( context.sensorFractions[i] < context.fraction ) { b2SensorHitArray_Push( &taskContext->sensorHits, context.sensorHits[i] ); } } b2TracyCZoneEnd( ccd ); } static void b2FinalizeBodiesTask( int startIndex, int endIndex, uint32_t threadIndex, void* context ) { b2TracyCZoneNC( finalize_transfprms, "Transforms", b2_colorMediumSeaGreen, true ); b2StepContext* stepContext = context; b2World* world = stepContext->world; B2_ASSERT( (int)threadIndex < world->workerCount ); bool enableSleep = world->enableSleep; b2BodyState* states = stepContext->states; b2BodySim* sims = stepContext->sims; b2Body* bodies = world->bodies.data; float timeStep = stepContext->dt; float invTimeStep = stepContext->inv_dt; uint16_t worldId = world->worldId; // The body move event array should already have the correct size B2_ASSERT( endIndex <= world->bodyMoveEvents.count ); b2BodyMoveEvent* moveEvents = world->bodyMoveEvents.data; b2BitSet* enlargedSimBitSet = &world->taskContexts.data[threadIndex].enlargedSimBitSet; b2BitSet* awakeIslandBitSet = &world->taskContexts.data[threadIndex].awakeIslandBitSet; b2TaskContext* taskContext = world->taskContexts.data + threadIndex; bool enableContinuous = world->enableContinuous; const float speculativeDistance = B2_SPECULATIVE_DISTANCE; const float aabbMargin = B2_AABB_MARGIN; B2_ASSERT( startIndex <= endIndex ); for ( int simIndex = startIndex; simIndex < endIndex; ++simIndex ) { b2BodyState* state = states + simIndex; b2BodySim* sim = sims + simIndex; if ( state->flags & b2_lockLinearX ) { state->linearVelocity.x = 0.0f; } if ( state->flags & b2_lockLinearY ) { state->linearVelocity.y = 0.0f; } if ( state->flags & b2_lockAngularZ ) { state->angularVelocity = 0.0f; } b2Vec2 v = state->linearVelocity; float w = state->angularVelocity; B2_ASSERT( b2IsValidVec2( v ) ); B2_ASSERT( b2IsValidFloat( w ) ); sim->center = b2Add( sim->center, state->deltaPosition ); sim->transform.q = b2NormalizeRot( b2MulRot( state->deltaRotation, sim->transform.q ) ); // Use the velocity of the farthest point on the body to account for rotation. float maxVelocity = b2Length( v ) + b2AbsFloat( w ) * sim->maxExtent; // Sleep needs to observe position correction as well as true velocity. float maxDeltaPosition = b2Length( state->deltaPosition ) + b2AbsFloat( state->deltaRotation.s ) * sim->maxExtent; // Position correction is not as important for sleep as true velocity. float positionSleepFactor = 0.5f; float sleepVelocity = b2MaxFloat( maxVelocity, positionSleepFactor * invTimeStep * maxDeltaPosition ); // reset state deltas state->deltaPosition = b2Vec2_zero; state->deltaRotation = b2Rot_identity; sim->transform.p = b2Sub( sim->center, b2RotateVector( sim->transform.q, sim->localCenter ) ); // cache miss here, however I need the shape list below b2Body* body = bodies + sim->bodyId; body->bodyMoveIndex = simIndex; moveEvents[simIndex].transform = sim->transform; moveEvents[simIndex].bodyId = (b2BodyId){ sim->bodyId + 1, worldId, body->generation }; moveEvents[simIndex].userData = body->userData; moveEvents[simIndex].fellAsleep = false; // reset applied force and torque sim->force = b2Vec2_zero; sim->torque = 0.0f; // If you hit this then it means you deferred mass computation but never called b2Body_ApplyMassFromShapes B2_ASSERT( ( body->flags & b2_dirtyMass ) == 0 ); body->flags &= ~( b2_isFast | b2_isSpeedCapped | b2_hadTimeOfImpact ); body->flags |= ( sim->flags & ( b2_isSpeedCapped | b2_hadTimeOfImpact ) ); sim->flags &= ~( b2_isFast | b2_isSpeedCapped | b2_hadTimeOfImpact ); if ( enableSleep == false || body->enableSleep == false || sleepVelocity > body->sleepThreshold ) { // Body is not sleepy body->sleepTime = 0.0f; if ( body->type == b2_dynamicBody && enableContinuous && maxVelocity * timeStep > 0.5f * sim->minExtent ) { // This flag is only retained for debug draw sim->flags |= b2_isFast; // Store in fast array for the continuous collision stage // This is deterministic because the order of TOI sweeps doesn't matter if ( sim->flags & b2_isBullet ) { int bulletIndex = b2AtomicFetchAddInt( &stepContext->bulletBodyCount, 1 ); stepContext->bulletBodies[bulletIndex] = simIndex; } else { b2SolveContinuous( world, simIndex, taskContext ); } } else { // Body is safe to advance sim->center0 = sim->center; sim->rotation0 = sim->transform.q; } } else { // Body is safe to advance and is falling asleep sim->center0 = sim->center; sim->rotation0 = sim->transform.q; body->sleepTime += timeStep; } // Any single body in an island can keep it awake b2Island* island = b2IslandArray_Get( &world->islands, body->islandId ); if ( body->sleepTime < B2_TIME_TO_SLEEP ) { // keep island awake int islandIndex = island->localIndex; b2SetBit( awakeIslandBitSet, islandIndex ); } else if ( island->constraintRemoveCount > 0 ) { // body wants to sleep but its island needs splitting first if ( body->sleepTime > taskContext->splitSleepTime ) { // pick the sleepiest candidate taskContext->splitIslandId = body->islandId; taskContext->splitSleepTime = body->sleepTime; } } // Update shapes AABBs b2Transform transform = sim->transform; bool isFast = ( sim->flags & b2_isFast ) != 0; int shapeId = body->headShapeId; while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = b2ShapeArray_Get( &world->shapes, shapeId ); if ( isFast ) { // For fast non-bullet bodies the AABB has already been updated in b2SolveContinuous // For fast bullet bodies the AABB will be updated at a later stage // Add to enlarged shapes regardless of AABB changes. // Bit-set to keep the move array sorted b2SetBit( enlargedSimBitSet, simIndex ); } else { b2AABB aabb = b2ComputeShapeAABB( shape, transform ); aabb.lowerBound.x -= speculativeDistance; aabb.lowerBound.y -= speculativeDistance; aabb.upperBound.x += speculativeDistance; aabb.upperBound.y += speculativeDistance; shape->aabb = aabb; B2_ASSERT( shape->enlargedAABB == false ); if ( b2AABB_Contains( shape->fatAABB, aabb ) == false ) { b2AABB fatAABB; fatAABB.lowerBound.x = aabb.lowerBound.x - aabbMargin; fatAABB.lowerBound.y = aabb.lowerBound.y - aabbMargin; fatAABB.upperBound.x = aabb.upperBound.x + aabbMargin; fatAABB.upperBound.y = aabb.upperBound.y + aabbMargin; shape->fatAABB = fatAABB; shape->enlargedAABB = true; // Bit-set to keep the move array sorted b2SetBit( enlargedSimBitSet, simIndex ); } } shapeId = shape->nextShapeId; } } b2TracyCZoneEnd( finalize_transfprms ); } /* typedef enum b2SolverStageType { b2_stagePrepareJoints, b2_stagePrepareContacts, b2_stageIntegrateVelocities, b2_stageWarmStart, b2_stageSolve, b2_stageIntegratePositions, b2_stageRelax, b2_stageRestitution, b2_stageStoreImpulses } b2SolverStageType; typedef enum b2SolverBlockType { b2_bodyBlock, b2_jointBlock, b2_contactBlock, b2_graphJointBlock, b2_graphContactBlock } b2SolverBlockType; */ static void b2ExecuteBlock( b2SolverStage* stage, b2StepContext* context, b2SolverBlock* block, int workerIndex ) { b2SolverStageType stageType = stage->type; b2SolverBlockType blockType = block->blockType; int startIndex = block->startIndex; int endIndex = startIndex + block->count; switch ( stageType ) { case b2_stagePrepareJoints: b2PrepareJointsTask( startIndex, endIndex, context ); break; case b2_stagePrepareContacts: b2PrepareContactsTask( startIndex, endIndex, context ); break; case b2_stageIntegrateVelocities: b2IntegrateVelocitiesTask( startIndex, endIndex, context ); break; case b2_stageWarmStart: if ( blockType == b2_graphContactBlock ) { b2WarmStartContactsTask( startIndex, endIndex, context, stage->colorIndex ); } else if ( blockType == b2_graphJointBlock ) { b2WarmStartJointsTask( startIndex, endIndex, context, stage->colorIndex ); } break; case b2_stageSolve: if ( blockType == b2_graphContactBlock ) { b2SolveContactsTask( startIndex, endIndex, context, stage->colorIndex, true ); } else if ( blockType == b2_graphJointBlock ) { b2SolveJointsTask( startIndex, endIndex, context, stage->colorIndex, true, workerIndex ); } break; case b2_stageIntegratePositions: b2IntegratePositionsTask( startIndex, endIndex, context ); break; case b2_stageRelax: if ( blockType == b2_graphContactBlock ) { b2SolveContactsTask( startIndex, endIndex, context, stage->colorIndex, false ); } else if ( blockType == b2_graphJointBlock ) { b2SolveJointsTask( startIndex, endIndex, context, stage->colorIndex, false, workerIndex ); } break; case b2_stageRestitution: if ( blockType == b2_graphContactBlock ) { b2ApplyRestitutionTask( startIndex, endIndex, context, stage->colorIndex ); } break; case b2_stageStoreImpulses: b2StoreImpulsesTask( startIndex, endIndex, context ); break; } } static inline int GetWorkerStartIndex( int workerIndex, int blockCount, int workerCount ) { if ( blockCount <= workerCount ) { return workerIndex < blockCount ? workerIndex : B2_NULL_INDEX; } int blocksPerWorker = blockCount / workerCount; int remainder = blockCount - blocksPerWorker * workerCount; return blocksPerWorker * workerIndex + b2MinInt( remainder, workerIndex ); } static void b2ExecuteStage( b2SolverStage* stage, b2StepContext* context, int previousSyncIndex, int syncIndex, int workerIndex ) { int completedCount = 0; b2SolverBlock* blocks = stage->blocks; int blockCount = stage->blockCount; int expectedSyncIndex = previousSyncIndex; int startIndex = GetWorkerStartIndex( workerIndex, blockCount, context->workerCount ); if ( startIndex == B2_NULL_INDEX ) { return; } B2_ASSERT( 0 <= startIndex && startIndex < blockCount ); int blockIndex = startIndex; while ( b2AtomicCompareExchangeInt( &blocks[blockIndex].syncIndex, expectedSyncIndex, syncIndex ) == true ) { B2_ASSERT( stage->type != b2_stagePrepareContacts || syncIndex < 2 ); B2_ASSERT( completedCount < blockCount ); b2ExecuteBlock( stage, context, blocks + blockIndex, workerIndex ); completedCount += 1; blockIndex += 1; if ( blockIndex >= blockCount ) { // Keep looking for work blockIndex = 0; } expectedSyncIndex = previousSyncIndex; } // Search backwards for blocks blockIndex = startIndex - 1; while ( true ) { if ( blockIndex < 0 ) { blockIndex = blockCount - 1; } expectedSyncIndex = previousSyncIndex; if ( b2AtomicCompareExchangeInt( &blocks[blockIndex].syncIndex, expectedSyncIndex, syncIndex ) == false ) { break; } b2ExecuteBlock( stage, context, blocks + blockIndex, workerIndex ); completedCount += 1; blockIndex -= 1; } (void)b2AtomicFetchAddInt( &stage->completionCount, completedCount ); } static void b2ExecuteMainStage( b2SolverStage* stage, b2StepContext* context, uint32_t syncBits ) { int blockCount = stage->blockCount; if ( blockCount == 0 ) { return; } int workerIndex = 0; if ( blockCount == 1 ) { b2ExecuteBlock( stage, context, stage->blocks, workerIndex ); } else { b2AtomicStoreU32( &context->atomicSyncBits, syncBits ); int syncIndex = ( syncBits >> 16 ) & 0xFFFF; B2_ASSERT( syncIndex > 0 ); int previousSyncIndex = syncIndex - 1; b2ExecuteStage( stage, context, previousSyncIndex, syncIndex, workerIndex ); // todo consider using the cycle counter as well while ( b2AtomicLoadInt( &stage->completionCount ) != blockCount ) { b2Pause(); } b2AtomicStoreInt( &stage->completionCount, 0 ); } } // This should not use the thread index because thread 0 can be called twice by enkiTS. static void b2SolverTask( int startIndex, int endIndex, uint32_t threadIndexIgnore, void* taskContext ) { B2_UNUSED( startIndex, endIndex, threadIndexIgnore ); b2WorkerContext* workerContext = taskContext; int workerIndex = workerContext->workerIndex; b2StepContext* context = workerContext->context; int activeColorCount = context->activeColorCount; b2SolverStage* stages = context->stages; b2Profile* profile = &context->world->profile; if ( workerIndex == 0 ) { // Main thread synchronizes the workers and does work itself. // // Stages are re-used by loops so that I don't need more stages for large iteration counts. // The sync indices grow monotonically for the body/graph/constraint groupings because they share solver blocks. // The stage index and sync indices are combined in to sync bits for atomic synchronization. // The workers need to compute the previous sync index for a given stage so that CAS works correctly. This // setup makes this easy to do. /* b2_stagePrepareJoints, b2_stagePrepareContacts, b2_stageIntegrateVelocities, b2_stageWarmStart, b2_stageSolve, b2_stageIntegratePositions, b2_stageRelax, b2_stageRestitution, b2_stageStoreImpulses */ uint64_t ticks = b2GetTicks(); int bodySyncIndex = 1; int stageIndex = 0; // This stage loops over all awake joints uint32_t jointSyncIndex = 1; uint32_t syncBits = ( jointSyncIndex << 16 ) | stageIndex; B2_ASSERT( stages[stageIndex].type == b2_stagePrepareJoints ); b2ExecuteMainStage( stages + stageIndex, context, syncBits ); stageIndex += 1; jointSyncIndex += 1; // This stage loops over all contact constraints uint32_t contactSyncIndex = 1; syncBits = ( contactSyncIndex << 16 ) | stageIndex; B2_ASSERT( stages[stageIndex].type == b2_stagePrepareContacts ); b2ExecuteMainStage( stages + stageIndex, context, syncBits ); stageIndex += 1; contactSyncIndex += 1; int graphSyncIndex = 1; // Single-threaded overflow work. These constraints don't fit in the graph coloring. b2PrepareOverflowJoints( context ); b2PrepareOverflowContacts( context ); profile->prepareConstraints += b2GetMillisecondsAndReset( &ticks ); int subStepCount = context->subStepCount; for ( int i = 0; i < subStepCount; ++i ) { // stage index restarted each iteration // syncBits still increases monotonically because the upper bits increase each iteration int iterStageIndex = stageIndex; // integrate velocities syncBits = ( bodySyncIndex << 16 ) | iterStageIndex; B2_ASSERT( stages[iterStageIndex].type == b2_stageIntegrateVelocities ); b2ExecuteMainStage( stages + iterStageIndex, context, syncBits ); iterStageIndex += 1; bodySyncIndex += 1; profile->integrateVelocities += b2GetMillisecondsAndReset( &ticks ); // warm start constraints b2WarmStartOverflowJoints( context ); b2WarmStartOverflowContacts( context ); for ( int colorIndex = 0; colorIndex < activeColorCount; ++colorIndex ) { syncBits = ( graphSyncIndex << 16 ) | iterStageIndex; B2_ASSERT( stages[iterStageIndex].type == b2_stageWarmStart ); b2ExecuteMainStage( stages + iterStageIndex, context, syncBits ); iterStageIndex += 1; } graphSyncIndex += 1; profile->warmStart += b2GetMillisecondsAndReset( &ticks ); // solve constraints bool useBias = true; for ( int j = 0; j < ITERATIONS; ++j ) { // Overflow constraints have lower priority b2SolveOverflowJoints( context, useBias ); b2SolveOverflowContacts( context, useBias ); for ( int colorIndex = 0; colorIndex < activeColorCount; ++colorIndex ) { syncBits = ( graphSyncIndex << 16 ) | iterStageIndex; B2_ASSERT( stages[iterStageIndex].type == b2_stageSolve ); b2ExecuteMainStage( stages + iterStageIndex, context, syncBits ); iterStageIndex += 1; } graphSyncIndex += 1; } profile->solveImpulses += b2GetMillisecondsAndReset( &ticks ); // integrate positions B2_ASSERT( stages[iterStageIndex].type == b2_stageIntegratePositions ); syncBits = ( bodySyncIndex << 16 ) | iterStageIndex; b2ExecuteMainStage( stages + iterStageIndex, context, syncBits ); iterStageIndex += 1; bodySyncIndex += 1; profile->integratePositions += b2GetMillisecondsAndReset( &ticks ); // relax constraints useBias = false; for ( int j = 0; j < RELAX_ITERATIONS; ++j ) { b2SolveOverflowJoints( context, useBias ); b2SolveOverflowContacts( context, useBias ); for ( int colorIndex = 0; colorIndex < activeColorCount; ++colorIndex ) { syncBits = ( graphSyncIndex << 16 ) | iterStageIndex; B2_ASSERT( stages[iterStageIndex].type == b2_stageRelax ); b2ExecuteMainStage( stages + iterStageIndex, context, syncBits ); iterStageIndex += 1; } graphSyncIndex += 1; } profile->relaxImpulses += b2GetMillisecondsAndReset( &ticks ); } // advance the stage according to the sub-stepping tasks just completed // integrate velocities / warm start / solve / integrate positions / relax stageIndex += 1 + activeColorCount + ITERATIONS * activeColorCount + 1 + RELAX_ITERATIONS * activeColorCount; // Restitution { b2ApplyOverflowRestitution( context ); int iterStageIndex = stageIndex; for ( int colorIndex = 0; colorIndex < activeColorCount; ++colorIndex ) { syncBits = ( graphSyncIndex << 16 ) | iterStageIndex; B2_ASSERT( stages[iterStageIndex].type == b2_stageRestitution ); b2ExecuteMainStage( stages + iterStageIndex, context, syncBits ); iterStageIndex += 1; } // graphSyncIndex += 1; stageIndex += activeColorCount; } profile->applyRestitution += b2GetMillisecondsAndReset( &ticks ); b2StoreOverflowImpulses( context ); syncBits = ( contactSyncIndex << 16 ) | stageIndex; B2_ASSERT( stages[stageIndex].type == b2_stageStoreImpulses ); b2ExecuteMainStage( stages + stageIndex, context, syncBits ); profile->storeImpulses += b2GetMillisecondsAndReset( &ticks ); // Signal workers to finish b2AtomicStoreU32( &context->atomicSyncBits, UINT_MAX ); B2_ASSERT( stageIndex + 1 == context->stageCount ); return; } // Worker spins and waits for work uint32_t lastSyncBits = 0; // uint64_t maxSpinTime = 10; while ( true ) { // Spin until main thread bumps changes the sync bits. This can waste significant time overall, but it is necessary for // parallel simulation with graph coloring. uint32_t syncBits; int spinCount = 0; while ( ( syncBits = b2AtomicLoadU32( &context->atomicSyncBits ) ) == lastSyncBits ) { if ( spinCount > 5 ) { b2Yield(); spinCount = 0; } else { // Using the cycle counter helps to account for variation in mm_pause timing across different // CPUs. However, this is X64 only. // uint64_t prev = __rdtsc(); // do //{ // b2Pause(); //} // while ((__rdtsc() - prev) < maxSpinTime); // maxSpinTime += 10; b2Pause(); b2Pause(); spinCount += 1; } } if ( syncBits == UINT_MAX ) { // sentinel hit break; } int stageIndex = syncBits & 0xFFFF; B2_ASSERT( stageIndex < context->stageCount ); int syncIndex = ( syncBits >> 16 ) & 0xFFFF; B2_ASSERT( syncIndex > 0 ); int previousSyncIndex = syncIndex - 1; b2SolverStage* stage = stages + stageIndex; b2ExecuteStage( stage, context, previousSyncIndex, syncIndex, workerIndex ); lastSyncBits = syncBits; } } static void b2BulletBodyTask( int startIndex, int endIndex, uint32_t threadIndex, void* context ) { B2_UNUSED( threadIndex ); b2TracyCZoneNC( bullet_body_task, "Bullet", b2_colorLightSkyBlue, true ); b2StepContext* stepContext = context; b2TaskContext* taskContext = b2TaskContextArray_Get( &stepContext->world->taskContexts, threadIndex ); B2_ASSERT( startIndex <= endIndex ); for ( int i = startIndex; i < endIndex; ++i ) { int simIndex = stepContext->bulletBodies[i]; b2SolveContinuous( stepContext->world, simIndex, taskContext ); } b2TracyCZoneEnd( bullet_body_task ); } #if B2_SIMD_WIDTH == 8 #define B2_SIMD_SHIFT 3 #elif B2_SIMD_WIDTH == 4 #define B2_SIMD_SHIFT 2 #else #define B2_SIMD_SHIFT 0 #endif // Solve with graph coloring void b2Solve( b2World* world, b2StepContext* stepContext ) { world->stepIndex += 1; // Are there any awake bodies? This scenario should not be important for profiling. b2SolverSet* awakeSet = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); int awakeBodyCount = awakeSet->bodySims.count; if ( awakeBodyCount == 0 ) { // Nothing to simulate, however the tree rebuild must be finished. if ( world->userTreeTask != NULL ) { world->finishTaskFcn( world->userTreeTask, world->userTaskContext ); world->userTreeTask = NULL; world->activeTaskCount -= 1; } b2ValidateNoEnlarged( &world->broadPhase ); return; } // Solve constraints using graph coloring { // Prepare buffers for bullets b2AtomicStoreInt( &stepContext->bulletBodyCount, 0 ); stepContext->bulletBodies = b2AllocateArenaItem( &world->arena, awakeBodyCount * sizeof( int ), "bullet bodies" ); b2TracyCZoneNC( prepare_stages, "Prepare Stages", b2_colorDarkOrange, true ); uint64_t prepareTicks = b2GetTicks(); b2ConstraintGraph* graph = &world->constraintGraph; b2GraphColor* colors = graph->colors; stepContext->sims = awakeSet->bodySims.data; stepContext->states = awakeSet->bodyStates.data; // count contacts, joints, and colors int awakeJointCount = 0; int activeColorCount = 0; for ( int i = 0; i < B2_GRAPH_COLOR_COUNT - 1; ++i ) { int perColorContactCount = colors[i].contactSims.count; int perColorJointCount = colors[i].jointSims.count; int occupancyCount = perColorContactCount + perColorJointCount; activeColorCount += occupancyCount > 0 ? 1 : 0; awakeJointCount += perColorJointCount; } // prepare for move events b2BodyMoveEventArray_Resize( &world->bodyMoveEvents, awakeBodyCount ); // A block is a range of tasks, a start index and count as a sub-array. // Each worker receives at most M blocks of work. The workers may receive less blocks if there is not sufficient work. // Each block of work has a minimum number of elements (block size). This in turn may limit the number of blocks. // If there are many elements then the block size is increased so there are still at most M blocks of work per worker. // M is a tunable number that has two goals: // 1. keep M small to reduce overhead // 2. keep M large enough for other workers to be able to steal work // The block size is a power of two to make math efficient. int workerCount = world->workerCount; // todo 4 seems good but more benchmarking would be good const int blocksPerWorker = 4; const int maxBlockCount = blocksPerWorker * workerCount; // Configure blocks for tasks that parallel-for bodies int bodyBlockSize = 1 << 5; int bodyBlockCount; if ( awakeBodyCount > bodyBlockSize * maxBlockCount ) { // Too many blocks, increase block size bodyBlockSize = awakeBodyCount / maxBlockCount; bodyBlockCount = maxBlockCount; } else { // Divide by bodyBlockSize (32) and ensure there is at least one block bodyBlockCount = ( ( awakeBodyCount - 1 ) >> 5 ) + 1; } // Configure blocks for tasks parallel-for each active graph color // The blocks are a mix of SIMD contact blocks and joint blocks int activeColorIndices[B2_GRAPH_COLOR_COUNT]; int colorContactCounts[B2_GRAPH_COLOR_COUNT]; int colorContactBlockSizes[B2_GRAPH_COLOR_COUNT]; int colorContactBlockCounts[B2_GRAPH_COLOR_COUNT]; int colorJointCounts[B2_GRAPH_COLOR_COUNT]; int colorJointBlockSizes[B2_GRAPH_COLOR_COUNT]; int colorJointBlockCounts[B2_GRAPH_COLOR_COUNT]; int graphBlockCount = 0; // c is the active color index int simdContactCount = 0; int c = 0; for ( int i = 0; i < B2_GRAPH_COLOR_COUNT - 1; ++i ) { int colorContactCount = colors[i].contactSims.count; int colorJointCount = colors[i].jointSims.count; if ( colorContactCount + colorJointCount > 0 ) { activeColorIndices[c] = i; // 4/8-way SIMD int colorContactCountSIMD = colorContactCount > 0 ? ( ( colorContactCount - 1 ) >> B2_SIMD_SHIFT ) + 1 : 0; colorContactCounts[c] = colorContactCountSIMD; // determine the number of contact work blocks for this color if ( colorContactCountSIMD > blocksPerWorker * maxBlockCount ) { // too many contact blocks per worker, so make bigger blocks colorContactBlockSizes[c] = colorContactCountSIMD / maxBlockCount; colorContactBlockCounts[c] = maxBlockCount; } else if ( colorContactCountSIMD > 0 ) { // dividing by blocksPerWorker (4) colorContactBlockSizes[c] = blocksPerWorker; // This math makes sure there is at least one block //colorContactBlockCounts[c] = ( ( colorContactCountSIMD - 1 ) >> 2 ) + 1; colorContactBlockCounts[c] = ( ( colorContactCountSIMD - 1 ) / blocksPerWorker ) + 1; } else { // no contacts in this color colorContactBlockSizes[c] = 0; colorContactBlockCounts[c] = 0; } colorJointCounts[c] = colorJointCount; // determine number of joint work blocks for this color if ( colorJointCount > blocksPerWorker * maxBlockCount ) { // too many joint blocks colorJointBlockSizes[c] = colorJointCount / maxBlockCount; colorJointBlockCounts[c] = maxBlockCount; } else if ( colorJointCount > 0 ) { // dividing by blocksPerWorker (4) colorJointBlockSizes[c] = blocksPerWorker; //colorJointBlockCounts[c] = ( ( colorJointCount - 1 ) >> 2 ) + 1; colorJointBlockCounts[c] = ( ( colorJointCount - 1 ) / 4 ) + 1; } else { colorJointBlockSizes[c] = 0; colorJointBlockCounts[c] = 0; } graphBlockCount += colorContactBlockCounts[c] + colorJointBlockCounts[c]; simdContactCount += colorContactCountSIMD; c += 1; } } activeColorCount = c; // Gather contact pointers for easy parallel-for traversal. Some may be NULL due to SIMD remainders. b2ContactSim** contacts = b2AllocateArenaItem( &world->arena, B2_SIMD_WIDTH * simdContactCount * sizeof( b2ContactSim* ), "contact pointers" ); // Gather joint pointers for easy parallel-for traversal. b2JointSim** joints = b2AllocateArenaItem( &world->arena, awakeJointCount * sizeof( b2JointSim* ), "joint pointers" ); int simdConstraintSize = b2GetContactConstraintSIMDByteCount(); b2ContactConstraintSIMD* simdContactConstraints = b2AllocateArenaItem( &world->arena, simdContactCount * simdConstraintSize, "contact constraint" ); int overflowContactCount = colors[B2_OVERFLOW_INDEX].contactSims.count; b2ContactConstraint* overflowContactConstraints = b2AllocateArenaItem( &world->arena, overflowContactCount * sizeof( b2ContactConstraint ), "overflow contact constraint" ); graph->colors[B2_OVERFLOW_INDEX].overflowConstraints = overflowContactConstraints; // Distribute transient constraints to each graph color and build flat arrays of contact and joint pointers { int contactBase = 0; int jointBase = 0; for ( int i = 0; i < activeColorCount; ++i ) { int j = activeColorIndices[i]; b2GraphColor* color = colors + j; int colorContactCount = color->contactSims.count; if ( colorContactCount == 0 ) { color->simdConstraints = NULL; } else { color->simdConstraints = (b2ContactConstraintSIMD*)( (uint8_t*)simdContactConstraints + contactBase * simdConstraintSize ); for ( int k = 0; k < colorContactCount; ++k ) { contacts[B2_SIMD_WIDTH * contactBase + k] = color->contactSims.data + k; } // remainder int colorContactCountSIMD = ( ( colorContactCount - 1 ) >> B2_SIMD_SHIFT ) + 1; for ( int k = colorContactCount; k < B2_SIMD_WIDTH * colorContactCountSIMD; ++k ) { contacts[B2_SIMD_WIDTH * contactBase + k] = NULL; } contactBase += colorContactCountSIMD; } int colorJointCount = color->jointSims.count; for ( int k = 0; k < colorJointCount; ++k ) { joints[jointBase + k] = color->jointSims.data + k; } jointBase += colorJointCount; } B2_ASSERT( contactBase == simdContactCount ); B2_ASSERT( jointBase == awakeJointCount ); } // Define work blocks for preparing contacts and storing contact impulses int contactBlockSize = blocksPerWorker; //int contactBlockCount = simdContactCount > 0 ? ( ( simdContactCount - 1 ) >> 2 ) + 1 : 0; int contactBlockCount = simdContactCount > 0 ? ( ( simdContactCount - 1 ) / blocksPerWorker ) + 1 : 0; if ( simdContactCount > contactBlockSize * maxBlockCount ) { // Too many blocks, increase block size contactBlockSize = simdContactCount / maxBlockCount; contactBlockCount = maxBlockCount; } // Define work blocks for preparing joints int jointBlockSize = blocksPerWorker; //int jointBlockCount = awakeJointCount > 0 ? ( ( awakeJointCount - 1 ) >> 2 ) + 1 : 0; int jointBlockCount = awakeJointCount > 0 ? ( ( awakeJointCount - 1 ) / blocksPerWorker ) + 1 : 0; if ( awakeJointCount > jointBlockSize * maxBlockCount ) { // Too many blocks, increase block size jointBlockSize = awakeJointCount / maxBlockCount; jointBlockCount = maxBlockCount; } int stageCount = 0; // b2_stagePrepareJoints stageCount += 1; // b2_stagePrepareContacts stageCount += 1; // b2_stageIntegrateVelocities stageCount += 1; // b2_stageWarmStart stageCount += activeColorCount; // b2_stageSolve stageCount += ITERATIONS * activeColorCount; // b2_stageIntegratePositions stageCount += 1; // b2_stageRelax stageCount += RELAX_ITERATIONS * activeColorCount; // b2_stageRestitution stageCount += activeColorCount; // b2_stageStoreImpulses stageCount += 1; b2SolverStage* stages = b2AllocateArenaItem( &world->arena, stageCount * sizeof( b2SolverStage ), "stages" ); b2SolverBlock* bodyBlocks = b2AllocateArenaItem( &world->arena, bodyBlockCount * sizeof( b2SolverBlock ), "body blocks" ); b2SolverBlock* contactBlocks = b2AllocateArenaItem( &world->arena, contactBlockCount * sizeof( b2SolverBlock ), "contact blocks" ); b2SolverBlock* jointBlocks = b2AllocateArenaItem( &world->arena, jointBlockCount * sizeof( b2SolverBlock ), "joint blocks" ); b2SolverBlock* graphBlocks = b2AllocateArenaItem( &world->arena, graphBlockCount * sizeof( b2SolverBlock ), "graph blocks" ); // Split an awake island. This modifies: // - stack allocator // - world island array and solver set // - island indices on bodies, contacts, and joints // I'm squeezing this task in here because it may be expensive and this is a safe place to put it. // Note: cannot split islands in parallel with FinalizeBodies void* splitIslandTask = NULL; if ( world->splitIslandId != B2_NULL_INDEX ) { splitIslandTask = world->enqueueTaskFcn( &b2SplitIslandTask, 1, 1, world, world->userTaskContext ); world->taskCount += 1; world->activeTaskCount += splitIslandTask == NULL ? 0 : 1; } // Prepare body work blocks for ( int i = 0; i < bodyBlockCount; ++i ) { b2SolverBlock* block = bodyBlocks + i; block->startIndex = i * bodyBlockSize; block->count = (int16_t)bodyBlockSize; block->blockType = b2_bodyBlock; b2AtomicStoreInt( &block->syncIndex, 0 ); } bodyBlocks[bodyBlockCount - 1].count = (int16_t)( awakeBodyCount - ( bodyBlockCount - 1 ) * bodyBlockSize ); // Prepare joint work blocks for ( int i = 0; i < jointBlockCount; ++i ) { b2SolverBlock* block = jointBlocks + i; block->startIndex = i * jointBlockSize; block->count = (int16_t)jointBlockSize; block->blockType = b2_jointBlock; b2AtomicStoreInt( &block->syncIndex, 0 ); } if ( jointBlockCount > 0 ) { jointBlocks[jointBlockCount - 1].count = (int16_t)( awakeJointCount - ( jointBlockCount - 1 ) * jointBlockSize ); } // Prepare contact work blocks for ( int i = 0; i < contactBlockCount; ++i ) { b2SolverBlock* block = contactBlocks + i; block->startIndex = i * contactBlockSize; block->count = (int16_t)contactBlockSize; block->blockType = b2_contactBlock; b2AtomicStoreInt( &block->syncIndex, 0 ); } if ( contactBlockCount > 0 ) { contactBlocks[contactBlockCount - 1].count = (int16_t)( simdContactCount - ( contactBlockCount - 1 ) * contactBlockSize ); } // Prepare graph work blocks b2SolverBlock* graphColorBlocks[B2_GRAPH_COLOR_COUNT] = {0}; b2SolverBlock* baseGraphBlock = graphBlocks; for ( int i = 0; i < activeColorCount; ++i ) { graphColorBlocks[i] = baseGraphBlock; int colorJointBlockCount = colorJointBlockCounts[i]; int colorJointBlockSize = colorJointBlockSizes[i]; for ( int j = 0; j < colorJointBlockCount; ++j ) { b2SolverBlock* block = baseGraphBlock + j; block->startIndex = j * colorJointBlockSize; block->count = (int16_t)colorJointBlockSize; block->blockType = b2_graphJointBlock; b2AtomicStoreInt( &block->syncIndex, 0 ); } if ( colorJointBlockCount > 0 ) { baseGraphBlock[colorJointBlockCount - 1].count = (int16_t)( colorJointCounts[i] - ( colorJointBlockCount - 1 ) * colorJointBlockSize ); baseGraphBlock += colorJointBlockCount; } int colorContactBlockCount = colorContactBlockCounts[i]; int colorContactBlockSize = colorContactBlockSizes[i]; for ( int j = 0; j < colorContactBlockCount; ++j ) { b2SolverBlock* block = baseGraphBlock + j; block->startIndex = j * colorContactBlockSize; block->count = (int16_t)colorContactBlockSize; block->blockType = b2_graphContactBlock; b2AtomicStoreInt( &block->syncIndex, 0 ); } if ( colorContactBlockCount > 0 ) { baseGraphBlock[colorContactBlockCount - 1].count = (int16_t)( colorContactCounts[i] - ( colorContactBlockCount - 1 ) * colorContactBlockSize ); baseGraphBlock += colorContactBlockCount; } } B2_ASSERT( (ptrdiff_t)( baseGraphBlock - graphBlocks ) == graphBlockCount ); b2SolverStage* stage = stages; // Prepare joints stage->type = b2_stagePrepareJoints; stage->blocks = jointBlocks; stage->blockCount = jointBlockCount; stage->colorIndex = -1; b2AtomicStoreInt( &stage->completionCount, 0 ); stage += 1; // Prepare contacts stage->type = b2_stagePrepareContacts; stage->blocks = contactBlocks; stage->blockCount = contactBlockCount; stage->colorIndex = -1; b2AtomicStoreInt( &stage->completionCount, 0 ); stage += 1; // Integrate velocities stage->type = b2_stageIntegrateVelocities; stage->blocks = bodyBlocks; stage->blockCount = bodyBlockCount; stage->colorIndex = -1; b2AtomicStoreInt( &stage->completionCount, 0 ); stage += 1; // Warm start for ( int i = 0; i < activeColorCount; ++i ) { stage->type = b2_stageWarmStart; stage->blocks = graphColorBlocks[i]; stage->blockCount = colorJointBlockCounts[i] + colorContactBlockCounts[i]; stage->colorIndex = activeColorIndices[i]; b2AtomicStoreInt( &stage->completionCount, 0 ); stage += 1; } // Solve graph for ( int j = 0; j < ITERATIONS; ++j ) { for ( int i = 0; i < activeColorCount; ++i ) { stage->type = b2_stageSolve; stage->blocks = graphColorBlocks[i]; stage->blockCount = colorJointBlockCounts[i] + colorContactBlockCounts[i]; stage->colorIndex = activeColorIndices[i]; b2AtomicStoreInt( &stage->completionCount, 0 ); stage += 1; } } // Integrate positions stage->type = b2_stageIntegratePositions; stage->blocks = bodyBlocks; stage->blockCount = bodyBlockCount; stage->colorIndex = -1; b2AtomicStoreInt( &stage->completionCount, 0 ); stage += 1; // Relax constraints for ( int j = 0; j < RELAX_ITERATIONS; ++j ) { for ( int i = 0; i < activeColorCount; ++i ) { stage->type = b2_stageRelax; stage->blocks = graphColorBlocks[i]; stage->blockCount = colorJointBlockCounts[i] + colorContactBlockCounts[i]; stage->colorIndex = activeColorIndices[i]; b2AtomicStoreInt( &stage->completionCount, 0 ); stage += 1; } } // Restitution // Note: joint blocks mixed in, could have joint limit restitution for ( int i = 0; i < activeColorCount; ++i ) { stage->type = b2_stageRestitution; stage->blocks = graphColorBlocks[i]; stage->blockCount = colorJointBlockCounts[i] + colorContactBlockCounts[i]; stage->colorIndex = activeColorIndices[i]; b2AtomicStoreInt( &stage->completionCount, 0 ); stage += 1; } // Store impulses stage->type = b2_stageStoreImpulses; stage->blocks = contactBlocks; stage->blockCount = contactBlockCount; stage->colorIndex = -1; b2AtomicStoreInt( &stage->completionCount, 0 ); stage += 1; B2_ASSERT( (int)( stage - stages ) == stageCount ); B2_ASSERT( workerCount <= B2_MAX_WORKERS ); b2WorkerContext workerContext[B2_MAX_WORKERS]; stepContext->graph = graph; stepContext->joints = joints; stepContext->contacts = contacts; stepContext->simdContactConstraints = simdContactConstraints; stepContext->activeColorCount = activeColorCount; stepContext->workerCount = workerCount; stepContext->stageCount = stageCount; stepContext->stages = stages; b2AtomicStoreU32( &stepContext->atomicSyncBits, 0 ); world->profile.prepareStages = b2GetMillisecondsAndReset( &prepareTicks ); b2TracyCZoneEnd( prepare_stages ); b2TracyCZoneNC( solve_constraints, "Solve Constraints", b2_colorIndigo, true ); uint64_t constraintTicks = b2GetTicks(); // Must use worker index because thread 0 can be assigned multiple tasks by enkiTS int jointIdCapacity = b2GetIdCapacity( &world->jointIdPool ); for ( int i = 0; i < workerCount; ++i ) { b2TaskContext* taskContext = b2TaskContextArray_Get( &world->taskContexts, i ); b2SetBitCountAndClear( &taskContext->jointStateBitSet, jointIdCapacity ); workerContext[i].context = stepContext; workerContext[i].workerIndex = i; workerContext[i].userTask = world->enqueueTaskFcn( b2SolverTask, 1, 1, workerContext + i, world->userTaskContext ); world->taskCount += 1; world->activeTaskCount += workerContext[i].userTask == NULL ? 0 : 1; } // Finish island split if ( splitIslandTask != NULL ) { world->finishTaskFcn( splitIslandTask, world->userTaskContext ); world->activeTaskCount -= 1; } world->splitIslandId = B2_NULL_INDEX; // Finish constraint solve for ( int i = 0; i < workerCount; ++i ) { if ( workerContext[i].userTask != NULL ) { world->finishTaskFcn( workerContext[i].userTask, world->userTaskContext ); world->activeTaskCount -= 1; } } world->profile.solveConstraints = b2GetMillisecondsAndReset( &constraintTicks ); b2TracyCZoneEnd( solve_constraints ); b2TracyCZoneNC( update_transforms, "Update Transforms", b2_colorMediumSeaGreen, true ); uint64_t transformTicks = b2GetTicks(); // Prepare contact, enlarged body, and island bit sets used in body finalization. int awakeIslandCount = awakeSet->islandSims.count; for ( int i = 0; i < world->workerCount; ++i ) { b2TaskContext* taskContext = world->taskContexts.data + i; b2SensorHitArray_Clear( &taskContext->sensorHits ); b2SetBitCountAndClear( &taskContext->enlargedSimBitSet, awakeBodyCount ); b2SetBitCountAndClear( &taskContext->awakeIslandBitSet, awakeIslandCount ); taskContext->splitIslandId = B2_NULL_INDEX; taskContext->splitSleepTime = 0.0f; } // Finalize bodies. Must happen after the constraint solver and after island splitting. void* finalizeBodiesTask = world->enqueueTaskFcn( b2FinalizeBodiesTask, awakeBodyCount, 64, stepContext, world->userTaskContext ); world->taskCount += 1; if ( finalizeBodiesTask != NULL ) { world->finishTaskFcn( finalizeBodiesTask, world->userTaskContext ); } b2FreeArenaItem( &world->arena, graphBlocks ); b2FreeArenaItem( &world->arena, jointBlocks ); b2FreeArenaItem( &world->arena, contactBlocks ); b2FreeArenaItem( &world->arena, bodyBlocks ); b2FreeArenaItem( &world->arena, stages ); b2FreeArenaItem( &world->arena, overflowContactConstraints ); b2FreeArenaItem( &world->arena, simdContactConstraints ); b2FreeArenaItem( &world->arena, joints ); b2FreeArenaItem( &world->arena, contacts ); world->profile.transforms = b2GetMilliseconds( transformTicks ); b2TracyCZoneEnd( update_transforms ); } // Report joint events { b2TracyCZoneNC( joint_events, "Joint Events", b2_colorPeru, true ); uint64_t jointEventTicks = b2GetTicks(); // Gather bits for all joints that have force/torque events b2BitSet* jointStateBitSet = &world->taskContexts.data[0].jointStateBitSet; for ( int i = 1; i < world->workerCount; ++i ) { b2InPlaceUnion( jointStateBitSet, &world->taskContexts.data[i].jointStateBitSet ); } { uint32_t wordCount = jointStateBitSet->blockCount; uint64_t* bits = jointStateBitSet->bits; b2Joint* jointArray = world->joints.data; uint16_t worldIndex0 = world->worldId; for ( uint32_t k = 0; k < wordCount; ++k ) { uint64_t word = bits[k]; while ( word != 0 ) { uint32_t ctz = b2CTZ64( word ); int jointId = (int)( 64 * k + ctz ); B2_ASSERT( jointId < world->joints.capacity ); b2Joint* joint = jointArray + jointId; B2_ASSERT( joint->setIndex == b2_awakeSet ); b2JointEvent event = { .jointId = { .index1 = jointId + 1, .world0 = worldIndex0, .generation = joint->generation, }, .userData = joint->userData, }; b2JointEventArray_Push( &world->jointEvents, event ); // Clear the smallest set bit word = word & ( word - 1 ); } } } world->profile.jointEvents = b2GetMilliseconds( jointEventTicks ); b2TracyCZoneEnd( joint_events ); } // Report hit events // todo_erin perhaps optimize this with a bitset // todo_erin perhaps do this in parallel with other work below { b2TracyCZoneNC( hit_events, "Hit Events", b2_colorRosyBrown, true ); uint64_t hitTicks = b2GetTicks(); B2_ASSERT( world->contactHitEvents.count == 0 ); float threshold = world->hitEventThreshold; b2GraphColor* colors = world->constraintGraph.colors; for ( int i = 0; i < B2_GRAPH_COLOR_COUNT; ++i ) { b2GraphColor* color = colors + i; int contactCount = color->contactSims.count; b2ContactSim* contactSims = color->contactSims.data; for ( int j = 0; j < contactCount; ++j ) { b2ContactSim* contactSim = contactSims + j; if ( ( contactSim->simFlags & b2_simEnableHitEvent ) == 0 ) { continue; } b2ContactHitEvent event = { 0 }; event.approachSpeed = threshold; bool hit = false; int pointCount = contactSim->manifold.pointCount; for ( int k = 0; k < pointCount; ++k ) { b2ManifoldPoint* mp = contactSim->manifold.points + k; float approachSpeed = -mp->normalVelocity; // Need to check total impulse because the point may be speculative and not colliding if ( approachSpeed > event.approachSpeed && mp->totalNormalImpulse > 0.0f ) { event.approachSpeed = approachSpeed; event.point = mp->point; hit = true; } } if ( hit == true ) { event.normal = contactSim->manifold.normal; b2Shape* shapeA = b2ShapeArray_Get( &world->shapes, contactSim->shapeIdA ); b2Shape* shapeB = b2ShapeArray_Get( &world->shapes, contactSim->shapeIdB ); event.shapeIdA = (b2ShapeId){ shapeA->id + 1, world->worldId, shapeA->generation }; event.shapeIdB = (b2ShapeId){ shapeB->id + 1, world->worldId, shapeB->generation }; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactSim->contactId ); event.contactId = (b2ContactId){ .index1 = contact->contactId + 1, .world0 = world->worldId, .padding = 0, .generation = contact->generation, }; b2ContactHitEventArray_Push( &world->contactHitEvents, event ); } } } world->profile.hitEvents = b2GetMilliseconds( hitTicks ); b2TracyCZoneEnd( hit_events ); } { b2TracyCZoneNC( refit_bvh, "Refit BVH", b2_colorFireBrick, true ); uint64_t refitTicks = b2GetTicks(); // Finish the user tree task that was queued earlier in the time step. This must be complete before touching the // broad-phase. if ( world->userTreeTask != NULL ) { world->finishTaskFcn( world->userTreeTask, world->userTaskContext ); world->userTreeTask = NULL; world->activeTaskCount -= 1; } b2ValidateNoEnlarged( &world->broadPhase ); // Gather bits for all sim bodies that have enlarged AABBs b2BitSet* enlargedBodyBitSet = &world->taskContexts.data[0].enlargedSimBitSet; for ( int i = 1; i < world->workerCount; ++i ) { b2InPlaceUnion( enlargedBodyBitSet, &world->taskContexts.data[i].enlargedSimBitSet ); } // Enlarge broad-phase proxies and build move array // Apply shape AABB changes to broad-phase. This also create the move array which must be // in deterministic order. I'm tracking sim bodies because the number of shape ids can be huge. // This has to happen before bullets are processed. { b2BroadPhase* broadPhase = &world->broadPhase; uint32_t wordCount = enlargedBodyBitSet->blockCount; uint64_t* bits = enlargedBodyBitSet->bits; // Fast array access is important here b2Body* bodyArray = world->bodies.data; b2BodySim* bodySimArray = awakeSet->bodySims.data; b2Shape* shapeArray = world->shapes.data; for ( uint32_t k = 0; k < wordCount; ++k ) { uint64_t word = bits[k]; while ( word != 0 ) { uint32_t ctz = b2CTZ64( word ); uint32_t bodySimIndex = 64 * k + ctz; b2BodySim* bodySim = bodySimArray + bodySimIndex; b2Body* body = bodyArray + bodySim->bodyId; int shapeId = body->headShapeId; if ( ( bodySim->flags & ( b2_isBullet | b2_isFast ) ) == ( b2_isBullet | b2_isFast ) ) { // Fast bullet bodies don't have their final AABB yet while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = shapeArray + shapeId; // Shape is fast. It's aabb will be enlarged in continuous collision. // Update the move array here for determinism because bullets are processed // below in non-deterministic order. b2BufferMove( broadPhase, shape->proxyKey ); shapeId = shape->nextShapeId; } } else { while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = shapeArray + shapeId; // The AABB may not have been enlarged, despite the body being flagged as enlarged. // For example, a body with multiple shapes may have not have all shapes enlarged. // A fast body may have been flagged as enlarged despite having no shapes enlarged. if ( shape->enlargedAABB ) { b2BroadPhase_EnlargeProxy( broadPhase, shape->proxyKey, shape->fatAABB ); shape->enlargedAABB = false; } shapeId = shape->nextShapeId; } } // Clear the smallest set bit word = word & ( word - 1 ); } } } b2ValidateBroadphase( &world->broadPhase ); world->profile.refit = b2GetMilliseconds( refitTicks ); b2TracyCZoneEnd( refit_bvh ); } int bulletBodyCount = b2AtomicLoadInt( &stepContext->bulletBodyCount ); if ( bulletBodyCount > 0 ) { b2TracyCZoneNC( bullets, "Bullets", b2_colorLightYellow, true ); uint64_t bulletTicks = b2GetTicks(); // Fast bullet bodies // Note: a bullet body may be moving slow int minRange = 8; void* userBulletBodyTask = world->enqueueTaskFcn( &b2BulletBodyTask, bulletBodyCount, minRange, stepContext, world->userTaskContext ); world->taskCount += 1; if ( userBulletBodyTask != NULL ) { world->finishTaskFcn( userBulletBodyTask, world->userTaskContext ); } // Serially enlarge broad-phase proxies for bullet shapes b2BroadPhase* broadPhase = &world->broadPhase; b2DynamicTree* dynamicTree = broadPhase->trees + b2_dynamicBody; // Fast array access is important here b2Body* bodyArray = world->bodies.data; b2BodySim* bodySimArray = awakeSet->bodySims.data; b2Shape* shapeArray = world->shapes.data; // Serially enlarge broad-phase proxies for bullet shapes int* bulletBodySimIndices = stepContext->bulletBodies; // This loop has non-deterministic order but it shouldn't affect the result for ( int i = 0; i < bulletBodyCount; ++i ) { b2BodySim* bulletBodySim = bodySimArray + bulletBodySimIndices[i]; if ( ( bulletBodySim->flags & b2_enlargeBounds ) == 0 ) { continue; } // Clear flag bulletBodySim->flags &= ~b2_enlargeBounds; int bodyId = bulletBodySim->bodyId; B2_ASSERT( 0 <= bodyId && bodyId < world->bodies.count ); b2Body* bulletBody = bodyArray + bodyId; int shapeId = bulletBody->headShapeId; while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = shapeArray + shapeId; if ( shape->enlargedAABB == false ) { shapeId = shape->nextShapeId; continue; } // Clear flag shape->enlargedAABB = false; int proxyKey = shape->proxyKey; int proxyId = B2_PROXY_ID( proxyKey ); B2_ASSERT( B2_PROXY_TYPE( proxyKey ) == b2_dynamicBody ); // all fast bullet shapes should already be in the move buffer B2_ASSERT( b2ContainsKey( &broadPhase->moveSet, proxyKey + 1 ) ); b2DynamicTree_EnlargeProxy( dynamicTree, proxyId, shape->fatAABB ); shapeId = shape->nextShapeId; } } world->profile.bullets = b2GetMilliseconds( bulletTicks ); b2TracyCZoneEnd( bullets ); } // Need to free this even if no bullets got processed. b2FreeArenaItem( &world->arena, stepContext->bulletBodies ); stepContext->bulletBodies = NULL; b2AtomicStoreInt( &stepContext->bulletBodyCount, 0 ); // Report sensor hits. This may include bullets sensor hits. { b2TracyCZoneNC( sensor_hits, "Sensor Hits", b2_colorPowderBlue, true ); uint64_t sensorHitTicks = b2GetTicks(); int workerCount = world->workerCount; B2_ASSERT( workerCount == world->taskContexts.count ); for ( int i = 0; i < workerCount; ++i ) { b2TaskContext* taskContext = world->taskContexts.data + i; int hitCount = taskContext->sensorHits.count; b2SensorHit* hits = taskContext->sensorHits.data; for ( int j = 0; j < hitCount; ++j ) { b2SensorHit hit = hits[j]; b2Shape* sensorShape = b2ShapeArray_Get( &world->shapes, hit.sensorId ); b2Shape* visitor = b2ShapeArray_Get( &world->shapes, hit.visitorId ); b2Sensor* sensor = b2SensorArray_Get( &world->sensors, sensorShape->sensorIndex ); b2Visitor shapeRef = { .shapeId = hit.visitorId, .generation = visitor->generation, }; b2VisitorArray_Push( &sensor->hits, shapeRef ); } } world->profile.sensorHits = b2GetMilliseconds( sensorHitTicks ); b2TracyCZoneEnd( sensor_hits ); } // Island sleeping // This must be done last because putting islands to sleep invalidates the enlarged body bits. // todo_erin figure out how to do this in parallel with tree refit if ( world->enableSleep == true ) { b2TracyCZoneNC( sleep_islands, "Island Sleep", b2_colorLightSlateGray, true ); uint64_t sleepTicks = b2GetTicks(); // Collect split island candidate for the next time step. No need to split if sleeping is disabled. B2_ASSERT( world->splitIslandId == B2_NULL_INDEX ); float splitSleepTimer = 0.0f; for ( int i = 0; i < world->workerCount; ++i ) { b2TaskContext* taskContext = world->taskContexts.data + i; if ( taskContext->splitIslandId != B2_NULL_INDEX && taskContext->splitSleepTime >= splitSleepTimer ) { B2_ASSERT( taskContext->splitSleepTime > 0.0f ); // Tie breaking for determinism. Largest island id wins. Needed due to work stealing. if ( taskContext->splitSleepTime == splitSleepTimer && taskContext->splitIslandId < world->splitIslandId ) { continue; } world->splitIslandId = taskContext->splitIslandId; splitSleepTimer = taskContext->splitSleepTime; } } b2BitSet* awakeIslandBitSet = &world->taskContexts.data[0].awakeIslandBitSet; for ( int i = 1; i < world->workerCount; ++i ) { b2InPlaceUnion( awakeIslandBitSet, &world->taskContexts.data[i].awakeIslandBitSet ); } // Need to process in reverse because this moves islands to sleeping solver sets. b2IslandSim* islands = awakeSet->islandSims.data; int count = awakeSet->islandSims.count; for ( int islandIndex = count - 1; islandIndex >= 0; islandIndex -= 1 ) { if ( b2GetBit( awakeIslandBitSet, islandIndex ) == true ) { // this island is still awake continue; } b2IslandSim* island = islands + islandIndex; int islandId = island->islandId; b2TrySleepIsland( world, islandId ); } b2ValidateSolverSets( world ); world->profile.sleepIslands = b2GetMilliseconds( sleepTicks ); b2TracyCZoneEnd( sleep_islands ); } } ================================================ FILE: src/solver.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "core.h" #include "box2d/math_functions.h" #include #include typedef struct b2BodySim b2BodySim; typedef struct b2BodyState b2BodyState; typedef struct b2ContactSim b2ContactSim; typedef struct b2JointSim b2JointSim; typedef struct b2World b2World; typedef struct b2Softness { float biasRate; float massScale; float impulseScale; } b2Softness; typedef enum b2SolverStageType { b2_stagePrepareJoints, b2_stagePrepareContacts, b2_stageIntegrateVelocities, b2_stageWarmStart, b2_stageSolve, b2_stageIntegratePositions, b2_stageRelax, b2_stageRestitution, b2_stageStoreImpulses } b2SolverStageType; typedef enum b2SolverBlockType { b2_bodyBlock, b2_jointBlock, b2_contactBlock, b2_graphJointBlock, b2_graphContactBlock } b2SolverBlockType; // Each block of work has a sync index that gets incremented when a worker claims the block. This ensures only a single worker // claims a block, yet lets work be distributed dynamically across multiple workers (work stealing). This also reduces contention // on a single block index atomic. For non-iterative stages the sync index is simply set to one. For iterative stages (solver // iteration) the same block of work is executed once per iteration and the atomic sync index is shared across iterations, so it // increases monotonically. typedef struct b2SolverBlock { int startIndex; int16_t count; int16_t blockType; // b2SolverBlockType // todo consider false sharing of this atomic b2AtomicInt syncIndex; } b2SolverBlock; // Each stage must be completed before going to the next stage. // Non-iterative stages use a stage instance once while iterative stages re-use the same instance each iteration. typedef struct b2SolverStage { b2SolverStageType type; b2SolverBlock* blocks; int blockCount; int colorIndex; // todo consider false sharing of this atomic b2AtomicInt completionCount; } b2SolverStage; // Context for a time step. Recreated each time step. typedef struct b2StepContext { // time step float dt; // inverse time step (0 if dt == 0). float inv_dt; // sub-step float h; float inv_h; int subStepCount; b2Softness contactSoftness; b2Softness staticSoftness; float restitutionThreshold; float maxLinearVelocity; struct b2World* world; struct b2ConstraintGraph* graph; // shortcut to body states from awake set b2BodyState* states; // shortcut to body sims from awake set b2BodySim* sims; // array of all shape ids for shapes that have enlarged AABBs int* enlargedShapes; int enlargedShapeCount; // Array of bullet bodies that need continuous collision handling int* bulletBodies; b2AtomicInt bulletBodyCount; // joint pointers for simplified parallel-for access. b2JointSim** joints; // contact pointers for simplified parallel-for access. // - parallel-for collide with no gaps // - parallel-for prepare and store contacts with NULL gaps for SIMD remainders // despite being an array of pointers, these are contiguous sub-arrays corresponding // to constraint graph colors b2ContactSim** contacts; struct b2ContactConstraintSIMD* simdContactConstraints; int activeColorCount; int workerCount; b2SolverStage* stages; int stageCount; bool enableWarmStarting; // todo padding to prevent false sharing char dummy1[64]; // sync index (16-bits) | stage type (16-bits) b2AtomicU32 atomicSyncBits; char dummy2[64]; } b2StepContext; static inline b2Softness b2MakeSoft( float hertz, float zeta, float h ) { if ( hertz == 0.0f ) { return (b2Softness){ .biasRate = 0.0f, .massScale = 0.0f, .impulseScale = 0.0f, }; } float omega = 2.0f * B2_PI * hertz; float a1 = 2.0f * zeta + h * omega; float a2 = h * omega * a1; float a3 = 1.0f / ( 1.0f + a2 ); // bias = w / (2 * z + hw) // massScale = hw * (2 * z + hw) / (1 + hw * (2 * z + hw)) // impulseScale = 1 / (1 + hw * (2 * z + hw)) // If z == 0 // bias = 1/h // massScale = hw^2 / (1 + hw^2) // impulseScale = 1 / (1 + hw^2) // w -> inf // bias = 1/h // massScale = 1 // impulseScale = 0 // if w = pi / 4 * inv_h // massScale = (pi/4)^2 / (1 + (pi/4)^2) = pi^2 / (16 + pi^2) ~= 0.38 // impulseScale = 1 / (1 + (pi/4)^2) = 16 / (16 + pi^2) ~= 0.62 // In all cases: // massScale + impulseScale == 1 return (b2Softness){ .biasRate = omega / a1, .massScale = a2 * a3, .impulseScale = a3, }; } void b2Solve( b2World* world, b2StepContext* stepContext ); ================================================ FILE: src/solver_set.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "solver_set.h" #include "body.h" #include "constraint_graph.h" #include "contact.h" #include "core.h" #include "island.h" #include "joint.h" #include "physics_world.h" #include B2_ARRAY_SOURCE( b2SolverSet, b2SolverSet ) void b2DestroySolverSet( b2World* world, int setIndex ) { b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, setIndex ); b2BodySimArray_Destroy( &set->bodySims ); b2BodyStateArray_Destroy( &set->bodyStates ); b2ContactSimArray_Destroy( &set->contactSims ); b2JointSimArray_Destroy( &set->jointSims ); b2IslandSimArray_Destroy( &set->islandSims ); b2FreeId( &world->solverSetIdPool, setIndex ); *set = ( b2SolverSet ){ 0 }; set->setIndex = B2_NULL_INDEX; } // Wake a solver set. Does not merge islands. // Contacts can be in several places: // 1. non-touching contacts in the disabled set // 2. non-touching contacts already in the awake set // 3. touching contacts in the sleeping set // This handles contact types 1 and 3. Type 2 doesn't need any action. void b2WakeSolverSet( b2World* world, int setIndex ) { B2_ASSERT( setIndex >= b2_firstSleepingSet ); b2SolverSet* set = b2SolverSetArray_Get( &world->solverSets, setIndex ); b2SolverSet* awakeSet = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); b2SolverSet* disabledSet = b2SolverSetArray_Get( &world->solverSets, b2_disabledSet ); b2Body* bodies = world->bodies.data; int bodyCount = set->bodySims.count; for ( int i = 0; i < bodyCount; ++i ) { b2BodySim* simSrc = set->bodySims.data + i; b2Body* body = bodies + simSrc->bodyId; B2_ASSERT( body->setIndex == setIndex ); body->setIndex = b2_awakeSet; body->localIndex = awakeSet->bodySims.count; // Reset sleep timer body->sleepTime = 0.0f; b2BodySim* simDst = b2BodySimArray_Add( &awakeSet->bodySims ); memcpy( simDst, simSrc, sizeof( b2BodySim ) ); b2BodyState* state = b2BodyStateArray_Add( &awakeSet->bodyStates ); *state = b2_identityBodyState; state->flags = body->flags; // move non-touching contacts from disabled set to awake set int contactKey = body->headContactKey; while ( contactKey != B2_NULL_INDEX ) { int edgeIndex = contactKey & 1; int contactId = contactKey >> 1; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); contactKey = contact->edges[edgeIndex].nextKey; if ( contact->setIndex != b2_disabledSet ) { B2_ASSERT( contact->setIndex == b2_awakeSet || contact->setIndex == setIndex ); continue; } int localIndex = contact->localIndex; b2ContactSim* contactSim = b2ContactSimArray_Get( &disabledSet->contactSims, localIndex ); B2_ASSERT( ( contact->flags & b2_contactTouchingFlag ) == 0 && contactSim->manifold.pointCount == 0 ); contact->setIndex = b2_awakeSet; contact->localIndex = awakeSet->contactSims.count; b2ContactSim* awakeContactSim = b2ContactSimArray_Add( &awakeSet->contactSims ); memcpy( awakeContactSim, contactSim, sizeof( b2ContactSim ) ); int movedLocalIndex = b2ContactSimArray_RemoveSwap( &disabledSet->contactSims, localIndex ); if ( movedLocalIndex != B2_NULL_INDEX ) { // fix moved element b2ContactSim* movedContactSim = disabledSet->contactSims.data + localIndex; b2Contact* movedContact = b2ContactArray_Get( &world->contacts, movedContactSim->contactId ); B2_ASSERT( movedContact->localIndex == movedLocalIndex ); movedContact->localIndex = localIndex; } } } // transfer touching contacts from sleeping set to contact graph { int contactCount = set->contactSims.count; for ( int i = 0; i < contactCount; ++i ) { b2ContactSim* contactSim = set->contactSims.data + i; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactSim->contactId ); B2_ASSERT( contact->flags & b2_contactTouchingFlag ); B2_ASSERT( contactSim->simFlags & b2_simTouchingFlag ); B2_ASSERT( contactSim->manifold.pointCount > 0 ); B2_ASSERT( contact->setIndex == setIndex ); b2AddContactToGraph( world, contactSim, contact ); contact->setIndex = b2_awakeSet; } } // transfer joints from sleeping set to awake set { int jointCount = set->jointSims.count; for ( int i = 0; i < jointCount; ++i ) { b2JointSim* jointSim = set->jointSims.data + i; b2Joint* joint = b2JointArray_Get( &world->joints, jointSim->jointId ); B2_ASSERT( joint->setIndex == setIndex ); b2AddJointToGraph( world, jointSim, joint ); joint->setIndex = b2_awakeSet; } } // transfer island from sleeping set to awake set // Usually a sleeping set has only one island, but it is possible // that joints are created between sleeping islands and they // are moved to the same sleeping set. { int islandCount = set->islandSims.count; for ( int i = 0; i < islandCount; ++i ) { b2IslandSim* islandSrc = set->islandSims.data + i; b2Island* island = b2IslandArray_Get( &world->islands, islandSrc->islandId ); island->setIndex = b2_awakeSet; island->localIndex = awakeSet->islandSims.count; b2IslandSim* islandDst = b2IslandSimArray_Add( &awakeSet->islandSims ); memcpy( islandDst, islandSrc, sizeof( b2IslandSim ) ); } } // destroy the sleeping set b2DestroySolverSet( world, setIndex ); } void b2TrySleepIsland( b2World* world, int islandId ) { b2Island* island = b2IslandArray_Get( &world->islands, islandId ); B2_ASSERT( island->setIndex == b2_awakeSet ); // cannot put an island to sleep while it has a pending split if ( island->constraintRemoveCount > 0 ) { return; } // island is sleeping // - create new sleeping solver set // - move island to sleeping solver set // - identify non-touching contacts that should move to sleeping solver set or disabled set // - remove old island // - fix island int sleepSetId = b2AllocId( &world->solverSetIdPool ); if ( sleepSetId == world->solverSets.count ) { b2SolverSet set = { 0 }; set.setIndex = B2_NULL_INDEX; b2SolverSetArray_Push( &world->solverSets, set ); } b2SolverSet* sleepSet = b2SolverSetArray_Get( &world->solverSets, sleepSetId ); *sleepSet = ( b2SolverSet ){ 0 }; // grab awake set after creating the sleep set because the solver set array may have been resized b2SolverSet* awakeSet = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet ); B2_ASSERT( 0 <= island->localIndex && island->localIndex < awakeSet->islandSims.count ); sleepSet->setIndex = sleepSetId; sleepSet->bodySims = b2BodySimArray_Create( island->bodyCount ); sleepSet->contactSims = b2ContactSimArray_Create( island->contactCount ); sleepSet->jointSims = b2JointSimArray_Create( island->jointCount ); // move awake bodies to sleeping set // this shuffles around bodies in the awake set { b2SolverSet* disabledSet = b2SolverSetArray_Get( &world->solverSets, b2_disabledSet ); int bodyId = island->headBody; while ( bodyId != B2_NULL_INDEX ) { b2Body* body = b2BodyArray_Get( &world->bodies, bodyId ); B2_ASSERT( body->setIndex == b2_awakeSet ); B2_ASSERT( body->islandId == islandId ); // Update the body move event to indicate this body fell asleep // It could happen the body is forced asleep before it ever moves. if ( body->bodyMoveIndex != B2_NULL_INDEX ) { b2BodyMoveEvent* moveEvent = b2BodyMoveEventArray_Get( &world->bodyMoveEvents, body->bodyMoveIndex ); B2_ASSERT( moveEvent->bodyId.index1 - 1 == bodyId ); B2_ASSERT( moveEvent->bodyId.generation == body->generation ); moveEvent->fellAsleep = true; body->bodyMoveIndex = B2_NULL_INDEX; } int awakeBodyIndex = body->localIndex; b2BodySim* awakeSim = b2BodySimArray_Get( &awakeSet->bodySims, awakeBodyIndex ); // move body sim to sleep set int sleepBodyIndex = sleepSet->bodySims.count; b2BodySim* sleepBodySim = b2BodySimArray_Add( &sleepSet->bodySims ); memcpy( sleepBodySim, awakeSim, sizeof( b2BodySim ) ); int movedIndex = b2BodySimArray_RemoveSwap( &awakeSet->bodySims, awakeBodyIndex ); if ( movedIndex != B2_NULL_INDEX ) { // fix local index on moved element b2BodySim* movedSim = awakeSet->bodySims.data + awakeBodyIndex; int movedId = movedSim->bodyId; b2Body* movedBody = b2BodyArray_Get( &world->bodies, movedId ); B2_ASSERT( movedBody->localIndex == movedIndex ); movedBody->localIndex = awakeBodyIndex; } // destroy state, no need to clone b2BodyStateArray_RemoveSwap( &awakeSet->bodyStates, awakeBodyIndex ); body->setIndex = sleepSetId; body->localIndex = sleepBodyIndex; // Move non-touching contacts to the disabled set. // Non-touching contacts may exist between sleeping islands and there is no clear ownership. int contactKey = body->headContactKey; while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); B2_ASSERT( contact->setIndex == b2_awakeSet || contact->setIndex == b2_disabledSet ); contactKey = contact->edges[edgeIndex].nextKey; if ( contact->setIndex == b2_disabledSet ) { // already moved to disabled set by another body in the island continue; } if ( contact->colorIndex != B2_NULL_INDEX ) { // contact is touching and will be moved separately B2_ASSERT( ( contact->flags & b2_contactTouchingFlag ) != 0 ); continue; } // the other body may still be awake, it still may go to sleep and then it will be responsible // for moving this contact to the disabled set. int otherEdgeIndex = edgeIndex ^ 1; int otherBodyId = contact->edges[otherEdgeIndex].bodyId; b2Body* otherBody = b2BodyArray_Get( &world->bodies, otherBodyId ); if ( otherBody->setIndex == b2_awakeSet ) { continue; } int localIndex = contact->localIndex; b2ContactSim* contactSim = b2ContactSimArray_Get( &awakeSet->contactSims, localIndex ); B2_ASSERT( contactSim->manifold.pointCount == 0 ); B2_ASSERT( ( contact->flags & b2_contactTouchingFlag ) == 0 ); // move the non-touching contact to the disabled set contact->setIndex = b2_disabledSet; contact->localIndex = disabledSet->contactSims.count; b2ContactSim* disabledContactSim = b2ContactSimArray_Add( &disabledSet->contactSims ); memcpy( disabledContactSim, contactSim, sizeof( b2ContactSim ) ); int movedLocalIndex = b2ContactSimArray_RemoveSwap( &awakeSet->contactSims, localIndex ); if ( movedLocalIndex != B2_NULL_INDEX ) { // fix moved element b2ContactSim* movedContactSim = awakeSet->contactSims.data + localIndex; b2Contact* movedContact = b2ContactArray_Get( &world->contacts, movedContactSim->contactId ); B2_ASSERT( movedContact->localIndex == movedLocalIndex ); movedContact->localIndex = localIndex; } } bodyId = body->islandNext; } } // move touching contacts // this shuffles contacts in the awake set { int contactId = island->headContact; while ( contactId != B2_NULL_INDEX ) { b2Contact* contact = b2ContactArray_Get( &world->contacts, contactId ); B2_ASSERT( contact->setIndex == b2_awakeSet ); B2_ASSERT( contact->islandId == islandId ); int colorIndex = contact->colorIndex; B2_ASSERT( 0 <= colorIndex && colorIndex < B2_GRAPH_COLOR_COUNT ); b2GraphColor* color = world->constraintGraph.colors + colorIndex; // Remove bodies from graph coloring associated with this constraint if ( colorIndex != B2_OVERFLOW_INDEX ) { // might clear a bit for a static body, but this has no effect b2ClearBit( &color->bodySet, contact->edges[0].bodyId ); b2ClearBit( &color->bodySet, contact->edges[1].bodyId ); } int localIndex = contact->localIndex; b2ContactSim* awakeContactSim = b2ContactSimArray_Get( &color->contactSims, localIndex ); int sleepContactIndex = sleepSet->contactSims.count; b2ContactSim* sleepContactSim = b2ContactSimArray_Add( &sleepSet->contactSims ); memcpy( sleepContactSim, awakeContactSim, sizeof( b2ContactSim ) ); int movedLocalIndex = b2ContactSimArray_RemoveSwap( &color->contactSims, localIndex ); if ( movedLocalIndex != B2_NULL_INDEX ) { // fix moved element b2ContactSim* movedContactSim = color->contactSims.data + localIndex; b2Contact* movedContact = b2ContactArray_Get( &world->contacts, movedContactSim->contactId ); B2_ASSERT( movedContact->localIndex == movedLocalIndex ); movedContact->localIndex = localIndex; } contact->setIndex = sleepSetId; contact->colorIndex = B2_NULL_INDEX; contact->localIndex = sleepContactIndex; contactId = contact->islandNext; } } // move joints // this shuffles joints in the awake set { int jointId = island->headJoint; while ( jointId != B2_NULL_INDEX ) { b2Joint* joint = b2JointArray_Get( &world->joints, jointId ); B2_ASSERT( joint->setIndex == b2_awakeSet ); B2_ASSERT( joint->islandId == islandId ); int colorIndex = joint->colorIndex; int localIndex = joint->localIndex; B2_ASSERT( 0 <= colorIndex && colorIndex < B2_GRAPH_COLOR_COUNT ); b2GraphColor* color = world->constraintGraph.colors + colorIndex; b2JointSim* awakeJointSim = b2JointSimArray_Get( &color->jointSims, localIndex ); if ( colorIndex != B2_OVERFLOW_INDEX ) { // might clear a bit for a static body, but this has no effect b2ClearBit( &color->bodySet, joint->edges[0].bodyId ); b2ClearBit( &color->bodySet, joint->edges[1].bodyId ); } int sleepJointIndex = sleepSet->jointSims.count; b2JointSim* sleepJointSim = b2JointSimArray_Add( &sleepSet->jointSims ); memcpy( sleepJointSim, awakeJointSim, sizeof( b2JointSim ) ); int movedIndex = b2JointSimArray_RemoveSwap( &color->jointSims, localIndex ); if ( movedIndex != B2_NULL_INDEX ) { // fix moved element b2JointSim* movedJointSim = color->jointSims.data + localIndex; int movedId = movedJointSim->jointId; b2Joint* movedJoint = b2JointArray_Get( &world->joints, movedId ); B2_ASSERT( movedJoint->localIndex == movedIndex ); movedJoint->localIndex = localIndex; } joint->setIndex = sleepSetId; joint->colorIndex = B2_NULL_INDEX; joint->localIndex = sleepJointIndex; jointId = joint->islandNext; } } // move island struct { B2_ASSERT( island->setIndex == b2_awakeSet ); int islandIndex = island->localIndex; b2IslandSim* sleepIsland = b2IslandSimArray_Add( &sleepSet->islandSims ); sleepIsland->islandId = islandId; int movedIslandIndex = b2IslandSimArray_RemoveSwap( &awakeSet->islandSims, islandIndex ); if ( movedIslandIndex != B2_NULL_INDEX ) { // fix index on moved element b2IslandSim* movedIslandSim = awakeSet->islandSims.data + islandIndex; int movedIslandId = movedIslandSim->islandId; b2Island* movedIsland = b2IslandArray_Get( &world->islands, movedIslandId ); B2_ASSERT( movedIsland->localIndex == movedIslandIndex ); movedIsland->localIndex = islandIndex; } island->setIndex = sleepSetId; island->localIndex = 0; } b2ValidateSolverSets( world ); } // This is called when joints are created between sets. I want to allow the sets // to continue sleeping if both are asleep. Otherwise one set is waked. // Islands will get merge when the set is waked. void b2MergeSolverSets( b2World* world, int setId1, int setId2 ) { B2_ASSERT( setId1 >= b2_firstSleepingSet ); B2_ASSERT( setId2 >= b2_firstSleepingSet ); b2SolverSet* set1 = b2SolverSetArray_Get( &world->solverSets, setId1 ); b2SolverSet* set2 = b2SolverSetArray_Get( &world->solverSets, setId2 ); // Move the fewest number of bodies if ( set1->bodySims.count < set2->bodySims.count ) { b2SolverSet* tempSet = set1; set1 = set2; set2 = tempSet; int tempId = setId1; setId1 = setId2; setId2 = tempId; } // transfer bodies { b2Body* bodies = world->bodies.data; int bodyCount = set2->bodySims.count; for ( int i = 0; i < bodyCount; ++i ) { b2BodySim* simSrc = set2->bodySims.data + i; b2Body* body = bodies + simSrc->bodyId; B2_ASSERT( body->setIndex == setId2 ); body->setIndex = setId1; body->localIndex = set1->bodySims.count; b2BodySim* simDst = b2BodySimArray_Add( &set1->bodySims ); memcpy( simDst, simSrc, sizeof( b2BodySim ) ); } } // transfer contacts { int contactCount = set2->contactSims.count; for ( int i = 0; i < contactCount; ++i ) { b2ContactSim* contactSrc = set2->contactSims.data + i; b2Contact* contact = b2ContactArray_Get( &world->contacts, contactSrc->contactId ); B2_ASSERT( contact->setIndex == setId2 ); contact->setIndex = setId1; contact->localIndex = set1->contactSims.count; b2ContactSim* contactDst = b2ContactSimArray_Add( &set1->contactSims ); memcpy( contactDst, contactSrc, sizeof( b2ContactSim ) ); } } // transfer joints { int jointCount = set2->jointSims.count; for ( int i = 0; i < jointCount; ++i ) { b2JointSim* jointSrc = set2->jointSims.data + i; b2Joint* joint = b2JointArray_Get( &world->joints, jointSrc->jointId ); B2_ASSERT( joint->setIndex == setId2 ); joint->setIndex = setId1; joint->localIndex = set1->jointSims.count; b2JointSim* jointDst = b2JointSimArray_Add( &set1->jointSims ); memcpy( jointDst, jointSrc, sizeof( b2JointSim ) ); } } // transfer islands { int islandCount = set2->islandSims.count; for ( int i = 0; i < islandCount; ++i ) { b2IslandSim* islandSrc = set2->islandSims.data + i; int islandId = islandSrc->islandId; b2Island* island = b2IslandArray_Get( &world->islands, islandId ); island->setIndex = setId1; island->localIndex = set1->islandSims.count; b2IslandSim* islandDst = b2IslandSimArray_Add( &set1->islandSims ); memcpy( islandDst, islandSrc, sizeof( b2IslandSim ) ); } } // destroy the merged set b2DestroySolverSet( world, setId2 ); b2ValidateSolverSets( world ); } void b2TransferBody( b2World* world, b2SolverSet* targetSet, b2SolverSet* sourceSet, b2Body* body ) { if (targetSet == sourceSet) { return; } int sourceIndex = body->localIndex; b2BodySim* sourceSim = b2BodySimArray_Get( &sourceSet->bodySims, sourceIndex ); int targetIndex = targetSet->bodySims.count; b2BodySim* targetSim = b2BodySimArray_Add( &targetSet->bodySims ); memcpy( targetSim, sourceSim, sizeof( b2BodySim ) ); // Clear transient body flags targetSim->flags &= ~(b2_isFast | b2_isSpeedCapped | b2_hadTimeOfImpact); // Remove body sim from solver set that owns it int movedIndex = b2BodySimArray_RemoveSwap( &sourceSet->bodySims, sourceIndex ); if ( movedIndex != B2_NULL_INDEX ) { // Fix moved body index b2BodySim* movedSim = sourceSet->bodySims.data + sourceIndex; int movedId = movedSim->bodyId; b2Body* movedBody = b2BodyArray_Get( &world->bodies, movedId ); B2_ASSERT( movedBody->localIndex == movedIndex ); movedBody->localIndex = sourceIndex; } if ( sourceSet->setIndex == b2_awakeSet ) { b2BodyStateArray_RemoveSwap( &sourceSet->bodyStates, sourceIndex ); } else if ( targetSet->setIndex == b2_awakeSet ) { b2BodyState* state = b2BodyStateArray_Add( &targetSet->bodyStates ); *state = b2_identityBodyState; state->flags = body->flags; } body->setIndex = targetSet->setIndex; body->localIndex = targetIndex; } void b2TransferJoint( b2World* world, b2SolverSet* targetSet, b2SolverSet* sourceSet, b2Joint* joint ) { if (targetSet == sourceSet) { return; } int localIndex = joint->localIndex; int colorIndex = joint->colorIndex; // Retrieve source. b2JointSim* sourceSim; if ( sourceSet->setIndex == b2_awakeSet ) { B2_ASSERT( 0 <= colorIndex && colorIndex < B2_GRAPH_COLOR_COUNT ); b2GraphColor* color = world->constraintGraph.colors + colorIndex; sourceSim = b2JointSimArray_Get( &color->jointSims, localIndex ); } else { B2_ASSERT( colorIndex == B2_NULL_INDEX ); sourceSim = b2JointSimArray_Get( &sourceSet->jointSims, localIndex ); } // Create target and copy. Fix joint. if ( targetSet->setIndex == b2_awakeSet ) { b2AddJointToGraph( world, sourceSim, joint ); joint->setIndex = b2_awakeSet; } else { joint->setIndex = targetSet->setIndex; joint->localIndex = targetSet->jointSims.count; joint->colorIndex = B2_NULL_INDEX; b2JointSim* targetSim = b2JointSimArray_Add( &targetSet->jointSims ); memcpy( targetSim, sourceSim, sizeof( b2JointSim ) ); } // Destroy source. if ( sourceSet->setIndex == b2_awakeSet ) { b2RemoveJointFromGraph( world, joint->edges[0].bodyId, joint->edges[1].bodyId, colorIndex, localIndex ); } else { int movedIndex = b2JointSimArray_RemoveSwap( &sourceSet->jointSims, localIndex ); if ( movedIndex != B2_NULL_INDEX ) { // fix swapped element b2JointSim* movedJointSim = sourceSet->jointSims.data + localIndex; int movedId = movedJointSim->jointId; b2Joint* movedJoint = b2JointArray_Get( &world->joints, movedId ); movedJoint->localIndex = localIndex; } } } ================================================ FILE: src/solver_set.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "array.h" typedef struct b2Body b2Body; typedef struct b2Joint b2Joint; typedef struct b2World b2World; // The solver set type by index enum b2SolverSetType { // Static set for static bodies and joints between static bodies b2_staticSet = 0, // Disabled set for disabled bodies and their joints b2_disabledSet = 1, // Awake set for awake bodies and awake non-touching contacts. Awake touching contacts // and awake joints live in the constraint graph b2_awakeSet = 2, // The index of the first sleeping set. Each island that goes to sleep is put into // a sleeping set. This holds all bodies, contacts, and joints from the sleeping island. // A separate set for each sleeping island makes it very efficient to wake a single island. b2_firstSleepingSet = 3, }; // This holds solver set data. The following sets are used: // - static set for all static bodies and joints between static bodies // - active set for all active bodies with body states (no contacts or joints) // - disabled set for disabled bodies and their joints // - all further sets are sleeping island sets along with their contacts and joints // The purpose of solver sets is to achieve high memory locality. // https://www.youtube.com/watch?v=nZNd5FjSquk typedef struct b2SolverSet { // Body array. Empty for unused set. b2BodySimArray bodySims; // Body state only exists for active set b2BodyStateArray bodyStates; // This holds sleeping/disabled joints. Empty for static/active set. b2JointSimArray jointSims; // This holds all contacts for sleeping sets. // This holds non-touching contacts for the awake set. b2ContactSimArray contactSims; // The awake set has an array of islands. Sleeping sets normally have a single islands. However, joints // created between sleeping sets causes the sets to merge, leaving them with multiple islands. These sleeping // islands will be naturally merged with the set is woken. // The static and disabled sets have no islands. // Islands live in the solver sets to limit the number of islands that need to be considered for sleeping. b2IslandSimArray islandSims; // Aligns with b2World::solverSetIdPool. Used to create a stable id for body/contact/joint/islands. int setIndex; } b2SolverSet; void b2DestroySolverSet( b2World* world, int setIndex ); void b2WakeSolverSet( b2World* world, int setIndex ); void b2TrySleepIsland( b2World* world, int islandId ); // Merge set 2 into set 1 then destroy set 2. // Warning: any pointers into these sets will be orphaned. void b2MergeSolverSets( b2World* world, int setIndex1, int setIndex2 ); void b2TransferBody( b2World* world, b2SolverSet* targetSet, b2SolverSet* sourceSet, b2Body* body ); void b2TransferJoint( b2World* world, b2SolverSet* targetSet, b2SolverSet* sourceSet, b2Joint* joint ); B2_ARRAY_INLINE( b2SolverSet, b2SolverSet ) ================================================ FILE: src/table.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "table.h" #include "atomic.h" #include "bitset.h" #include "core.h" #include "ctz.h" #include #include #if B2_SNOOP_TABLE_COUNTERS b2AtomicInt b2_findCount; b2AtomicInt b2_probeCount; #endif b2HashSet b2CreateSet( int capacity ) { b2HashSet set = { 0 }; // Capacity must be a power of 2 if ( capacity > 16 ) { set.capacity = b2RoundUpPowerOf2( capacity ); } else { set.capacity = 16; } set.count = 0; set.items = b2Alloc( set.capacity * sizeof( b2SetItem ) ); memset( set.items, 0, set.capacity * sizeof( b2SetItem ) ); return set; } void b2DestroySet( b2HashSet* set ) { b2Free( set->items, set->capacity * sizeof( b2SetItem ) ); set->items = NULL; set->count = 0; set->capacity = 0; } void b2ClearSet( b2HashSet* set ) { set->count = 0; memset( set->items, 0, set->capacity * sizeof( b2SetItem ) ); } // I need a good hash because the keys are built from pairs of increasing integers. // A simple hash like hash = (integer1 XOR integer2) has many collisions. // https://lemire.me/blog/2018/08/15/fast-strongly-universal-64-bit-hashing-everywhere/ // https://preshing.com/20130107/this-hash-set-is-faster-than-a-judy-array/ // todo try: https://www.jandrewrogers.com/2019/02/12/fast-perfect-hashing/ // todo try: // https://probablydance.com/2018/06/16/fibonacci-hashing-the-optimization-that-the-world-forgot-or-a-better-alternative-to-integer-modulo/ // I compared with CC on https://jacksonallan.github.io/c_cpp_hash_tables_benchmark/ and got slightly better performance // in the washer benchmark. // I compared with verstable across 8 benchmarks and the performance was similar. #if 0 // Fast-hash // https://jonkagstrom.com/bit-mixer-construction // https://code.google.com/archive/p/fast-hash static uint64_t b2KeyHash( uint64_t key ) { key ^= key >> 23; key *= 0x2127599BF4325C37ULL; key ^= key >> 47; return key; } #elif 1 static uint64_t b2KeyHash( uint64_t key ) { // Murmur hash uint64_t h = key; h ^= h >> 33; h *= 0xff51afd7ed558ccduLL; h ^= h >> 33; h *= 0xc4ceb9fe1a85ec53uLL; h ^= h >> 33; return h; } #endif static int b2FindSlot( const b2HashSet* set, uint64_t key, uint64_t hash ) { #if B2_SNOOP_TABLE_COUNTERS b2AtomicFetchAddInt( &b2_findCount, 1 ); #endif uint32_t capacity = set->capacity; uint32_t index = (uint32_t)hash & ( capacity - 1 ); const b2SetItem* items = set->items; while ( items[index].key != 0 && items[index].key != key ) { #if B2_SNOOP_TABLE_COUNTERS b2AtomicFetchAddInt( &b2_probeCount, 1 ); #endif index = ( index + 1 ) & ( capacity - 1 ); } return index; } static void b2AddKeyHaveCapacity( b2HashSet* set, uint64_t key, uint64_t hash ) { int index = b2FindSlot( set, key, hash ); b2SetItem* items = set->items; B2_ASSERT( items[index].key == 0 ); items[index].key = key; set->count += 1; } static void b2GrowTable( b2HashSet* set ) { uint32_t oldCount = set->count; B2_UNUSED( oldCount ); uint32_t oldCapacity = set->capacity; b2SetItem* oldItems = set->items; set->count = 0; // Capacity must be a power of 2 set->capacity = 2 * oldCapacity; set->items = b2Alloc( set->capacity * sizeof( b2SetItem ) ); memset( set->items, 0, set->capacity * sizeof( b2SetItem ) ); // Transfer items into new array for ( uint32_t i = 0; i < oldCapacity; ++i ) { b2SetItem* item = oldItems + i; if ( item->key == 0 ) { // this item was empty continue; } uint64_t hash = b2KeyHash( item->key ); b2AddKeyHaveCapacity( set, item->key, hash ); } B2_ASSERT( set->count == oldCount ); b2Free( oldItems, oldCapacity * sizeof( b2SetItem ) ); } bool b2ContainsKey( const b2HashSet* set, uint64_t key ) { // key of zero is a sentinel B2_ASSERT( key != 0 ); uint64_t hash = b2KeyHash( key ); int index = b2FindSlot( set, key, hash ); return set->items[index].key == key; } int b2GetHashSetBytes( b2HashSet* set ) { return set->capacity * (int)sizeof( b2SetItem ); } bool b2AddKey( b2HashSet* set, uint64_t key ) { // key of zero is a sentinel B2_ASSERT( key != 0 ); uint64_t hash = b2KeyHash( key ); B2_ASSERT( hash != 0 ); int index = b2FindSlot( set, key, hash ); if ( set->items[index].key != 0 ) { // Already in set B2_ASSERT( set->items[index].key == key ); return true; } if ( 2 * set->count >= set->capacity ) { b2GrowTable( set ); } b2AddKeyHaveCapacity( set, key, hash ); return false; } // See https://en.wikipedia.org/wiki/Open_addressing bool b2RemoveKey( b2HashSet* set, uint64_t key ) { uint64_t hash = b2KeyHash( key ); int i = b2FindSlot( set, key, hash ); b2SetItem* items = set->items; if ( items[i].key == 0 ) { // Not in set return false; } // Mark item i as unoccupied items[i].key = 0; B2_ASSERT( set->count > 0 ); set->count -= 1; // Attempt to fill item i int j = i; uint32_t capacity = set->capacity; for ( ;; ) { j = ( j + 1 ) & ( capacity - 1 ); if ( items[j].key == 0 ) { break; } // k is the first item for the hash of j uint64_t hash_j = b2KeyHash( items[j].key ); int k = hash_j & ( capacity - 1 ); // determine if k lies cyclically in (i,j] // i <= j: | i..k..j | // i > j: |.k..j i....| or |....j i..k.| if ( i <= j ) { if ( i < k && k <= j ) { continue; } } else { if ( i < k || k <= j ) { continue; } } // Move j into i items[i] = items[j]; // Mark item j as unoccupied items[j].key = 0; i = j; } return true; } // This function is here because ctz.h is included by // this file but not in bitset.c int b2CountSetBits( b2BitSet* bitSet ) { int popCount = 0; uint32_t blockCount = bitSet->blockCount; for ( uint32_t i = 0; i < blockCount; ++i ) { popCount += b2PopCount64( bitSet->bits[i] ); } return popCount; } ================================================ FILE: src/table.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include #include #define B2_SHAPE_PAIR_KEY( K1, K2 ) K1 < K2 ? (uint64_t)K1 << 32 | (uint64_t)K2 : (uint64_t)K2 << 32 | (uint64_t)K1 typedef struct b2SetItem { uint64_t key; // storing lower 32 bits of hash // this is wasteful because I just need to know if the item is occupied // I could require the key to be non-zero and use 0 to indicate an empty slot // Update: looks like I store this to make growing the table faster, however this is wasteful once // the table has hit the high water mark //uint32_t hash; } b2SetItem; typedef struct b2HashSet { b2SetItem* items; uint32_t capacity; uint32_t count; } b2HashSet; b2HashSet b2CreateSet( int capacity ); void b2DestroySet( b2HashSet* set ); void b2ClearSet( b2HashSet* set ); // Returns true if key was already in set bool b2AddKey( b2HashSet* set, uint64_t key ); // Returns true if the key was found bool b2RemoveKey( b2HashSet* set, uint64_t key ); bool b2ContainsKey( const b2HashSet* set, uint64_t key ); int b2GetHashSetBytes( b2HashSet* set ); static inline int b2GetSetCount( b2HashSet* set ) { return set->count; } static inline int b2GetSetCapacity( b2HashSet* set ) { return set->capacity; } ================================================ FILE: src/timer.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "core.h" #include "box2d/base.h" #include #if defined( _MSC_VER ) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif #include static double s_invFrequency = 0.0; uint64_t b2GetTicks( void ) { LARGE_INTEGER counter; QueryPerformanceCounter( &counter ); return (uint64_t)counter.QuadPart; } float b2GetMilliseconds( uint64_t ticks ) { if ( s_invFrequency == 0.0 ) { LARGE_INTEGER frequency; QueryPerformanceFrequency( &frequency ); s_invFrequency = (double)frequency.QuadPart; if ( s_invFrequency > 0.0 ) { s_invFrequency = 1000.0 / s_invFrequency; } } uint64_t ticksNow = b2GetTicks(); return (float)( s_invFrequency * ( ticksNow - ticks ) ); } float b2GetMillisecondsAndReset( uint64_t* ticks ) { if ( s_invFrequency == 0.0 ) { LARGE_INTEGER frequency; QueryPerformanceFrequency( &frequency ); s_invFrequency = (double)frequency.QuadPart; if ( s_invFrequency > 0.0 ) { s_invFrequency = 1000.0 / s_invFrequency; } } uint64_t ticksNow = b2GetTicks(); float ms = (float)( s_invFrequency * ( ticksNow - *ticks ) ); *ticks = ticksNow; return ms; } void b2Yield( void ) { SwitchToThread(); } typedef struct b2Mutex { CRITICAL_SECTION cs; } b2Mutex; b2Mutex* b2CreateMutex( void ) { b2Mutex* m = b2Alloc( sizeof( b2Mutex ) ); InitializeCriticalSection( &m->cs ); return m; } void b2DestroyMutex( b2Mutex* m ) { DeleteCriticalSection( &m->cs ); *m = (b2Mutex){ 0 }; b2Free( m, sizeof( b2Mutex ) ); } void b2LockMutex( b2Mutex* m ) { EnterCriticalSection( &m->cs ); } void b2UnlockMutex( b2Mutex* m ) { LeaveCriticalSection( &m->cs ); } #elif defined( __linux__ ) || defined( __EMSCRIPTEN__ ) #include #include uint64_t b2GetTicks( void ) { struct timespec ts; clock_gettime( CLOCK_MONOTONIC, &ts ); return ts.tv_sec * 1000000000LL + ts.tv_nsec; } float b2GetMilliseconds( uint64_t ticks ) { uint64_t ticksNow = b2GetTicks(); return (float)( ( ticksNow - ticks ) / 1000000.0 ); } float b2GetMillisecondsAndReset( uint64_t* ticks ) { uint64_t ticksNow = b2GetTicks(); float ms = (float)( ( ticksNow - *ticks ) / 1000000.0 ); *ticks = ticksNow; return ms; } void b2Yield( void ) { sched_yield(); } #include typedef struct b2Mutex { pthread_mutex_t mtx; } b2Mutex; b2Mutex* b2CreateMutex( void ) { b2Mutex* m = b2Alloc( sizeof( b2Mutex ) ); pthread_mutex_init( &m->mtx, NULL ); return m; } void b2DestroyMutex( b2Mutex* m ) { pthread_mutex_destroy( &m->mtx ); *m = (b2Mutex){ 0 }; b2Free( m, sizeof( b2Mutex ) ); } void b2LockMutex( b2Mutex* m ) { pthread_mutex_lock( &m->mtx ); } void b2UnlockMutex( b2Mutex* m ) { pthread_mutex_unlock( &m->mtx ); } #elif defined( __APPLE__ ) #include #include #include static double s_invFrequency = 0.0; uint64_t b2GetTicks( void ) { return mach_absolute_time(); } float b2GetMilliseconds( uint64_t ticks ) { if ( s_invFrequency == 0 ) { mach_timebase_info_data_t timebase; mach_timebase_info( &timebase ); // convert to ns then to ms s_invFrequency = 1e-6 * (double)timebase.numer / (double)timebase.denom; } uint64_t ticksNow = b2GetTicks(); return (float)( s_invFrequency * ( ticksNow - ticks ) ); } float b2GetMillisecondsAndReset( uint64_t* ticks ) { if ( s_invFrequency == 0 ) { mach_timebase_info_data_t timebase; mach_timebase_info( &timebase ); // convert to ns then to ms s_invFrequency = 1e-6 * (double)timebase.numer / (double)timebase.denom; } uint64_t ticksNow = b2GetTicks(); float ms = (float)( s_invFrequency * ( ticksNow - *ticks ) ); *ticks = ticksNow; return ms; } void b2Yield( void ) { sched_yield(); } #include typedef struct b2Mutex { pthread_mutex_t mtx; } b2Mutex; b2Mutex* b2CreateMutex( void ) { b2Mutex* m = b2Alloc( sizeof( b2Mutex ) ); pthread_mutex_init( &m->mtx, NULL ); return m; } void b2DestroyMutex( b2Mutex* m ) { pthread_mutex_destroy( &m->mtx ); *m = (b2Mutex){ 0 }; b2Free( m, sizeof( b2Mutex ) ); } void b2LockMutex( b2Mutex* m ) { pthread_mutex_lock( &m->mtx ); } void b2UnlockMutex( b2Mutex* m ) { pthread_mutex_unlock( &m->mtx ); } #else uint64_t b2GetTicks( void ) { return 0; } float b2GetMilliseconds( uint64_t ticks ) { ( (void)( ticks ) ); return 0.0f; } float b2GetMillisecondsAndReset( uint64_t* ticks ) { ( (void)( ticks ) ); return 0.0f; } void b2Yield( void ) { } typedef struct b2Mutex { int dummy; } b2Mutex; b2Mutex* b2CreateMutex( void ) { b2Mutex* m = b2Alloc( sizeof( b2Mutex ) ); m->dummy = 42; return m; } void b2DestroyMutex( b2Mutex* m ) { *m = (b2Mutex){ 0 }; b2Free( m, sizeof( b2Mutex ) ); } void b2LockMutex( b2Mutex* m ) { (void)m; } void b2UnlockMutex( b2Mutex* m ) { (void)m; } #endif // djb2 hash // https://en.wikipedia.org/wiki/List_of_hash_functions uint32_t b2Hash( uint32_t hash, const uint8_t* data, int count ) { uint32_t result = hash; for ( int i = 0; i < count; i++ ) { result = ( result << 5 ) + result + data[i]; } return result; } ================================================ FILE: src/types.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "box2d/types.h" #include "constants.h" #include "core.h" b2WorldDef b2DefaultWorldDef( void ) { b2WorldDef def = { 0 }; def.gravity.x = 0.0f; def.gravity.y = -10.0f; def.hitEventThreshold = 1.0f * b2_lengthUnitsPerMeter; def.restitutionThreshold = 1.0f * b2_lengthUnitsPerMeter; def.contactSpeed = 3.0f * b2_lengthUnitsPerMeter; def.contactHertz = 30.0; def.contactDampingRatio = 10.0f; // 400 meters per second, faster than the speed of sound def.maximumLinearSpeed = 400.0f * b2_lengthUnitsPerMeter; def.enableSleep = true; def.enableContinuous = true; def.internalValue = B2_SECRET_COOKIE; return def; } b2BodyDef b2DefaultBodyDef( void ) { b2BodyDef def = { 0 }; def.type = b2_staticBody; def.rotation = b2Rot_identity; def.sleepThreshold = 0.05f * b2_lengthUnitsPerMeter; def.gravityScale = 1.0f; def.enableSleep = true; def.isAwake = true; def.isEnabled = true; def.internalValue = B2_SECRET_COOKIE; return def; } b2Filter b2DefaultFilter( void ) { b2Filter filter = { B2_DEFAULT_CATEGORY_BITS, B2_DEFAULT_MASK_BITS, 0 }; return filter; } b2QueryFilter b2DefaultQueryFilter( void ) { b2QueryFilter filter = { B2_DEFAULT_CATEGORY_BITS, B2_DEFAULT_MASK_BITS }; return filter; } b2ShapeDef b2DefaultShapeDef( void ) { b2ShapeDef def = { 0 }; def.material.friction = 0.6f; def.density = 1.0f; def.filter = b2DefaultFilter(); def.updateBodyMass = true; def.invokeContactCreation = true; def.internalValue = B2_SECRET_COOKIE; return def; } b2SurfaceMaterial b2DefaultSurfaceMaterial( void ) { b2SurfaceMaterial material = { .friction = 0.6f, }; return material; } b2ChainDef b2DefaultChainDef( void ) { static b2SurfaceMaterial defaultMaterial = { .friction = 0.6f, }; b2ChainDef def = { 0 }; def.materials = &defaultMaterial; def.materialCount = 1; def.filter = b2DefaultFilter(); def.internalValue = B2_SECRET_COOKIE; return def; } static void b2EmptyDrawPolygon( const b2Vec2* vertices, int vertexCount, b2HexColor color, void* context ) { B2_UNUSED( vertices, vertexCount, color, context ); } static void b2EmptyDrawSolidPolygon( b2Transform transform, const b2Vec2* vertices, int vertexCount, float radius, b2HexColor color, void* context ) { B2_UNUSED( transform, vertices, vertexCount, radius, color, context ); } static void b2EmptyDrawCircle( b2Vec2 center, float radius, b2HexColor color, void* context ) { B2_UNUSED( center, radius, color, context ); } static void b2EmptyDrawSolidCircle( b2Transform transform, float radius, b2HexColor color, void* context ) { B2_UNUSED( transform, radius, color, context ); } static void b2EmptyDrawSolidCapsule( b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color, void* context ) { B2_UNUSED( p1, p2, radius, color, context ); } static void b2EmptyDrawSegment( b2Vec2 p1, b2Vec2 p2, b2HexColor color, void* context ) { B2_UNUSED( p1, p2, color, context ); } static void b2EmptyDrawTransform( b2Transform transform, void* context ) { B2_UNUSED( transform, context ); } static void b2EmptyDrawPoint( b2Vec2 p, float size, b2HexColor color, void* context ) { B2_UNUSED( p, size, color, context ); } static void b2EmptyDrawString( b2Vec2 p, const char* s, b2HexColor color, void* context ) { B2_UNUSED( p, s, color, context ); } b2DebugDraw b2DefaultDebugDraw( void ) { b2DebugDraw draw = { 0 }; // These allow the user to skip some implementations and not hit null exceptions. draw.DrawPolygonFcn = b2EmptyDrawPolygon; draw.DrawSolidPolygonFcn = b2EmptyDrawSolidPolygon; draw.DrawCircleFcn = b2EmptyDrawCircle; draw.DrawSolidCircleFcn = b2EmptyDrawSolidCircle; draw.DrawSolidCapsuleFcn = b2EmptyDrawSolidCapsule; draw.DrawLineFcn = b2EmptyDrawSegment; draw.DrawTransformFcn = b2EmptyDrawTransform; draw.DrawPointFcn = b2EmptyDrawPoint; draw.DrawStringFcn = b2EmptyDrawString; draw.drawingBounds.lowerBound = (b2Vec2){ -FLT_MAX, -FLT_MAX }; draw.drawingBounds.upperBound = (b2Vec2){ FLT_MAX, FLT_MAX }; draw.forceScale = 1.0f; draw.jointScale = 1.0f; draw.drawShapes = true; return draw; } ================================================ FILE: src/weld_joint.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "body.h" #include "core.h" #include "joint.h" #include "physics_world.h" #include "solver.h" #include "solver_set.h" // needed for dll export #include "box2d/box2d.h" #define B2_WELD_BLOCK_SOLVE 0 #if B2_WELD_BLOCK_SOLVE typedef struct { float x, y, z; } b2Vec3; // A 3-by-3 matrix. Stored in column-major order. typedef struct { b2Vec3 cx, cy, cz; } b2Mat33; static inline float b2Dot3( b2Vec3 a, b2Vec3 b ) { return a.x * b.x + a.y * b.y + a.z * b.z; } static inline b2Vec3 b2Cross3( b2Vec3 a, b2Vec3 b ) { return (b2Vec3){ a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x }; } static inline b2Vec3 b2Solve33(const b2Mat33* m, b2Vec3 b ) { float det = b2Dot3( m->cx, b2Cross3( m->cy, m->cz ) ); if ( det != 0.0f ) { det = 1.0f / det; } b2Vec3 x; x.x = det * b2Dot3( b, b2Cross3( m->cy, m->cz ) ); x.y = det * b2Dot3( m->cx, b2Cross3( b, m->cz ) ); x.z = det * b2Dot3( m->cx, b2Cross3( m->cy, b ) ); return x; } #endif void b2WeldJoint_SetLinearHertz( b2JointId jointId, float hertz ) { B2_ASSERT( b2IsValidFloat( hertz ) && hertz >= 0.0f ); b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_weldJoint ); joint->weldJoint.linearHertz = hertz; } float b2WeldJoint_GetLinearHertz( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_weldJoint ); return joint->weldJoint.linearHertz; } void b2WeldJoint_SetLinearDampingRatio( b2JointId jointId, float dampingRatio ) { B2_ASSERT( b2IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f ); b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_weldJoint ); joint->weldJoint.linearDampingRatio = dampingRatio; } float b2WeldJoint_GetLinearDampingRatio( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_weldJoint ); return joint->weldJoint.linearDampingRatio; } void b2WeldJoint_SetAngularHertz( b2JointId jointId, float hertz ) { B2_ASSERT( b2IsValidFloat( hertz ) && hertz >= 0.0f ); b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_weldJoint ); joint->weldJoint.angularHertz = hertz; } float b2WeldJoint_GetAngularHertz( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_weldJoint ); return joint->weldJoint.angularHertz; } void b2WeldJoint_SetAngularDampingRatio( b2JointId jointId, float dampingRatio ) { B2_ASSERT( b2IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f ); b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_weldJoint ); joint->weldJoint.angularDampingRatio = dampingRatio; } float b2WeldJoint_GetAngularDampingRatio( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_weldJoint ); return joint->weldJoint.angularDampingRatio; } b2Vec2 b2GetWeldJointForce( b2World* world, b2JointSim* base ) { b2Vec2 force = b2MulSV( world->inv_h, base->weldJoint.linearImpulse ); return force; } float b2GetWeldJointTorque( b2World* world, b2JointSim* base ) { return world->inv_h * base->weldJoint.angularImpulse; } // Point-to-point constraint // C = p2 - p1 // Cdot = v2 - v1 // = v2 + cross(w2, r2) - v1 - cross(w1, r1) // J = [-E -r1_skew E r2_skew ] // Identity used: // w k % (rx i + ry j) = w * (-ry i + rx j) // Angle constraint // C = angle2 - angle1 - referenceAngle // Cdot = w2 - w1 // J = [0 0 -1 0 0 1] // K = invI1 + invI2 // 3x3 Block // K = [J1] * invM * [J1T J2T] // [J2] // = [J1] * [invM * J1T invM * J2T] // [J2] // = [J1 * invM * J1T J1 * invM * J2T] // [J2 * invM * J1T J2 * invM * J2T] void b2PrepareWeldJoint( b2JointSim* base, b2StepContext* context ) { B2_ASSERT( base->type == b2_weldJoint ); // chase body id to the solver set where the body lives int idA = base->bodyIdA; int idB = base->bodyIdB; b2World* world = context->world; b2Body* bodyA = b2BodyArray_Get( &world->bodies, idA ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, idB ); B2_ASSERT( bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet ); b2SolverSet* setA = b2SolverSetArray_Get( &world->solverSets, bodyA->setIndex ); b2SolverSet* setB = b2SolverSetArray_Get( &world->solverSets, bodyB->setIndex ); int localIndexA = bodyA->localIndex; int localIndexB = bodyB->localIndex; b2BodySim* bodySimA = b2BodySimArray_Get( &setA->bodySims, localIndexA ); b2BodySim* bodySimB = b2BodySimArray_Get( &setB->bodySims, localIndexB ); float mA = bodySimA->invMass; float iA = bodySimA->invInertia; float mB = bodySimB->invMass; float iB = bodySimB->invInertia; base->invMassA = mA; base->invMassB = mB; base->invIA = iA; base->invIB = iB; b2WeldJoint* joint = &base->weldJoint; joint->indexA = bodyA->setIndex == b2_awakeSet ? localIndexA : B2_NULL_INDEX; joint->indexB = bodyB->setIndex == b2_awakeSet ? localIndexB : B2_NULL_INDEX; // Compute joint anchor frames with world space rotation, relative to center of mass joint->frameA.q = b2MulRot( bodySimA->transform.q, base->localFrameA.q ); joint->frameA.p = b2RotateVector( bodySimA->transform.q, b2Sub( base->localFrameA.p, bodySimA->localCenter ) ); joint->frameB.q = b2MulRot( bodySimB->transform.q, base->localFrameB.q ); joint->frameB.p = b2RotateVector( bodySimB->transform.q, b2Sub( base->localFrameB.p, bodySimB->localCenter ) ); // Compute the initial center delta. Incremental position updates are relative to this. joint->deltaCenter = b2Sub( bodySimB->center, bodySimA->center ); float ka = iA + iB; joint->axialMass = ka > 0.0f ? 1.0f / ka : 0.0f; if ( joint->linearHertz == 0.0f ) { joint->linearSpring = base->constraintSoftness; } else { joint->linearSpring = b2MakeSoft( joint->linearHertz, joint->linearDampingRatio, context->h ); } if ( joint->angularHertz == 0.0f ) { joint->angularSpring = base->constraintSoftness; } else { joint->angularSpring = b2MakeSoft( joint->angularHertz, joint->angularDampingRatio, context->h ); } if ( context->enableWarmStarting == false ) { joint->linearImpulse = b2Vec2_zero; joint->angularImpulse = 0.0f; } } void b2WarmStartWeldJoint( b2JointSim* base, b2StepContext* context ) { float mA = base->invMassA; float mB = base->invMassB; float iA = base->invIA; float iB = base->invIB; // dummy state for static bodies b2BodyState dummyState = b2_identityBodyState; b2WeldJoint* joint = &base->weldJoint; b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->frameA.p ); b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->frameB.p ); if ( stateA->flags & b2_dynamicFlag ) { stateA->linearVelocity = b2MulSub( stateA->linearVelocity, mA, joint->linearImpulse ); stateA->angularVelocity -= iA * ( b2Cross( rA, joint->linearImpulse ) + joint->angularImpulse ); } if ( stateB->flags & b2_dynamicFlag ) { stateB->linearVelocity = b2MulAdd( stateB->linearVelocity, mB, joint->linearImpulse ); stateB->angularVelocity += iB * ( b2Cross( rB, joint->linearImpulse ) + joint->angularImpulse ); } } void b2SolveWeldJoint( b2JointSim* base, b2StepContext* context, bool useBias ) { B2_ASSERT( base->type == b2_weldJoint ); float mA = base->invMassA; float mB = base->invMassB; float iA = base->invIA; float iB = base->invIB; // dummy state for static bodies b2BodyState dummyState = b2_identityBodyState; b2WeldJoint* joint = &base->weldJoint; b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; b2Vec2 vA = stateA->linearVelocity; float wA = stateA->angularVelocity; b2Vec2 vB = stateB->linearVelocity; float wB = stateB->angularVelocity; // Block solve doesn't work correctly with mixed stiffness values #if B2_WELD_BLOCK_SOLVE // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->frameA.p ); b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->frameB.p ); b2Mat33 K; K.cx.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; K.cy.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; K.cz.x = -rA.y * iA - rB.y * iB; K.cx.y = K.cy.x; K.cy.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; K.cz.y = rA.x * iA + rB.x * iB; K.cx.z = K.cz.x; K.cy.z = K.cz.y; K.cz.z = iA + iB; b2Vec3 bias = {0.0f, 0.0f, 0.0f}; float linearMassScale = 1.0f; float linearImpulseScale = 0.0f; if ( useBias || joint->linearHertz > 0.0f ) { // linear b2Vec2 dcA = stateA->deltaPosition; b2Vec2 dcB = stateB->deltaPosition; b2Vec2 jointTranslation = b2Add( b2Add( b2Sub( dcB, dcA ), b2Sub( rB, rA ) ), joint->deltaCenter ); bias.x = joint->linearSpring.biasRate * jointTranslation.x; bias.y = joint->linearSpring.biasRate * jointTranslation.y; linearMassScale = joint->linearSpring.massScale; linearImpulseScale = joint->linearSpring.impulseScale; } float angularMassScale = 1.0f; float angularImpulseScale = 0.0f; if ( useBias || joint->angularHertz > 0.0f ) { // angular b2Rot qA = b2MulRot( stateA->deltaRotation, joint->frameA.q ); b2Rot qB = b2MulRot( stateB->deltaRotation, joint->frameB.q ); b2Rot relQ = b2InvMulRot( qA, qB ); float jointAngle = b2Rot_GetAngle( relQ ); bias.z = joint->angularSpring.biasRate * jointAngle; angularMassScale = joint->angularSpring.massScale; angularImpulseScale = joint->angularSpring.impulseScale; } b2Vec2 Cdot1 = b2Sub( b2Add( vB, b2CrossSV( wB, rB ) ), b2Add( vA, b2CrossSV( wA, rA ) ) ); float Cdot2 = wB - wA; b2Vec3 Cdot = {Cdot1.x + bias.x, Cdot1.y + bias.y, Cdot2 + bias.z}; b2Vec3 b = b2Solve33( &K, Cdot ); b2Vec2 linearImpulse = { -linearMassScale * b.x - linearImpulseScale * joint->linearImpulse.x, -linearMassScale * b.y - linearImpulseScale * joint->linearImpulse.y, }; joint->linearImpulse = b2Add( joint->linearImpulse, linearImpulse ); float angularImpulse = -angularMassScale * b.z - angularImpulseScale * joint->angularImpulse; joint->angularImpulse += angularImpulse; vA = b2MulSub( vA, mA, linearImpulse ); wA -= iA * (b2Cross( rA, linearImpulse ) + angularImpulse); vB = b2MulAdd( vB, mB, linearImpulse ); wB += iB * (b2Cross( rB, linearImpulse ) + angularImpulse); // todo debugging Cdot1 = b2Sub( b2Add( vB, b2CrossSV( wB, rB ) ), b2Add( vA, b2CrossSV( wA, rA ) ) ); Cdot2 = wB - wA; if ( useBias == false && b2Length(Cdot1) > 0.0001f ) { Cdot1.x += 0.0f; } if ( useBias == false && b2AbsFloat( Cdot2 ) > 0.0001f ) { Cdot2 += 0.0f; } #else // angular constraint { b2Rot qA = b2MulRot( stateA->deltaRotation, joint->frameA.q ); b2Rot qB = b2MulRot( stateB->deltaRotation, joint->frameB.q ); b2Rot relQ = b2InvMulRot( qA, qB ); float jointAngle = b2Rot_GetAngle( relQ ); float bias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; if ( useBias || joint->angularHertz > 0.0f ) { float C = jointAngle; bias = joint->angularSpring.biasRate * C; massScale = joint->angularSpring.massScale; impulseScale = joint->angularSpring.impulseScale; } float Cdot = wB - wA; float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->angularImpulse; joint->angularImpulse += impulse; wA -= iA * impulse; wB += iB * impulse; } // linear constraint { b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->frameA.p ); b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->frameB.p ); b2Vec2 bias = b2Vec2_zero; float massScale = 1.0f; float impulseScale = 0.0f; if ( useBias || joint->linearHertz > 0.0f ) { b2Vec2 dcA = stateA->deltaPosition; b2Vec2 dcB = stateB->deltaPosition; b2Vec2 C = b2Add( b2Add( b2Sub( dcB, dcA ), b2Sub( rB, rA ) ), joint->deltaCenter ); bias = b2MulSV( joint->linearSpring.biasRate, C ); massScale = joint->linearSpring.massScale; impulseScale = joint->linearSpring.impulseScale; } b2Vec2 Cdot = b2Sub( b2Add( vB, b2CrossSV( wB, rB ) ), b2Add( vA, b2CrossSV( wA, rA ) ) ); b2Mat22 K; K.cx.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; K.cy.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; K.cx.y = K.cy.x; K.cy.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; b2Vec2 b = b2Solve22( K, b2Add( Cdot, bias ) ); b2Vec2 impulse = { -massScale * b.x - impulseScale * joint->linearImpulse.x, -massScale * b.y - impulseScale * joint->linearImpulse.y, }; joint->linearImpulse = b2Add( joint->linearImpulse, impulse ); vA = b2MulSub( vA, mA, impulse ); wA -= iA * b2Cross( rA, impulse ); vB = b2MulAdd( vB, mB, impulse ); wB += iB * b2Cross( rB, impulse ); } #endif B2_ASSERT( b2IsValidVec2( vA ) ); B2_ASSERT( b2IsValidFloat( wA ) ); B2_ASSERT( b2IsValidVec2( vB ) ); B2_ASSERT( b2IsValidFloat( wB ) ); if ( stateA->flags & b2_dynamicFlag ) { stateA->linearVelocity = vA; stateA->angularVelocity = wA; } if ( stateB->flags & b2_dynamicFlag ) { stateB->linearVelocity = vB; stateB->angularVelocity = wB; } } #if 0 void b2DumpWeldJoint() { int32 indexA = bodyA->islandIndex; int32 indexB = bodyB->islandIndex; b2Dump(" b2WeldJointDef jd;\n"); b2Dump(" jd.bodyA = sims[%d];\n", indexA); b2Dump(" jd.bodyB = sims[%d];\n", indexB); b2Dump(" jd.collideConnected = bool(%d);\n", collideConnected); b2Dump(" jd.localAnchorA.Set(%.9g, %.9g);\n", localAnchorA.x, localAnchorA.y); b2Dump(" jd.localAnchorB.Set(%.9g, %.9g);\n", localAnchorB.x, localAnchorB.y); b2Dump(" jd.referenceAngle = %.9g;\n", referenceAngle); b2Dump(" jd.stiffness = %.9g;\n", stiffness); b2Dump(" jd.damping = %.9g;\n", damping); b2Dump(" joints[%d] = world->CreateJoint(&jd);\n", index); } #endif void b2DrawWeldJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB, float drawScale ) { B2_ASSERT( base->type == b2_weldJoint ); b2Transform frameA = b2MulTransforms( transformA, base->localFrameA ); b2Transform frameB = b2MulTransforms( transformB, base->localFrameB ); b2Polygon box = b2MakeBox( 0.25f * drawScale, 0.125f * drawScale ); b2Vec2 points[4]; for ( int i = 0; i < 4; ++i ) { points[i] = b2TransformPoint( frameA, box.vertices[i] ); } draw->DrawPolygonFcn( points, 4, b2_colorDarkOrange, draw->context ); for ( int i = 0; i < 4; ++i ) { points[i] = b2TransformPoint( frameB, box.vertices[i] ); } draw->DrawPolygonFcn( points, 4, b2_colorDarkCyan, draw->context ); } ================================================ FILE: src/wheel_joint.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "body.h" #include "core.h" #include "joint.h" #include "physics_world.h" #include "solver.h" #include "solver_set.h" // needed for dll export #include "box2d/box2d.h" #include void b2WheelJoint_EnableSpring( b2JointId jointId, bool enableSpring ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); if ( enableSpring != joint->wheelJoint.enableSpring ) { joint->wheelJoint.enableSpring = enableSpring; joint->wheelJoint.springImpulse = 0.0f; } } bool b2WheelJoint_IsSpringEnabled( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.enableSpring; } void b2WheelJoint_SetSpringHertz( b2JointId jointId, float hertz ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); joint->wheelJoint.hertz = hertz; } float b2WheelJoint_GetSpringHertz( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.hertz; } void b2WheelJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); joint->wheelJoint.dampingRatio = dampingRatio; } float b2WheelJoint_GetSpringDampingRatio( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.dampingRatio; } void b2WheelJoint_EnableLimit( b2JointId jointId, bool enableLimit ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); if ( joint->wheelJoint.enableLimit != enableLimit ) { joint->wheelJoint.lowerImpulse = 0.0f; joint->wheelJoint.upperImpulse = 0.0f; joint->wheelJoint.enableLimit = enableLimit; } } bool b2WheelJoint_IsLimitEnabled( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.enableLimit; } float b2WheelJoint_GetLowerLimit( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.lowerTranslation; } float b2WheelJoint_GetUpperLimit( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.upperTranslation; } void b2WheelJoint_SetLimits( b2JointId jointId, float lower, float upper ) { B2_ASSERT( lower <= upper ); b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); if ( lower != joint->wheelJoint.lowerTranslation || upper != joint->wheelJoint.upperTranslation ) { joint->wheelJoint.lowerTranslation = b2MinFloat( lower, upper ); joint->wheelJoint.upperTranslation = b2MaxFloat( lower, upper ); joint->wheelJoint.lowerImpulse = 0.0f; joint->wheelJoint.upperImpulse = 0.0f; } } void b2WheelJoint_EnableMotor( b2JointId jointId, bool enableMotor ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); if ( joint->wheelJoint.enableMotor != enableMotor ) { joint->wheelJoint.motorImpulse = 0.0f; joint->wheelJoint.enableMotor = enableMotor; } } bool b2WheelJoint_IsMotorEnabled( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.enableMotor; } void b2WheelJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); joint->wheelJoint.motorSpeed = motorSpeed; } float b2WheelJoint_GetMotorSpeed( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.motorSpeed; } float b2WheelJoint_GetMotorTorque( b2JointId jointId ) { b2World* world = b2GetWorld( jointId.world0 ); b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return world->inv_h * joint->wheelJoint.motorImpulse; } void b2WheelJoint_SetMaxMotorTorque( b2JointId jointId, float torque ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); joint->wheelJoint.maxMotorTorque = torque; } float b2WheelJoint_GetMaxMotorTorque( b2JointId jointId ) { b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.maxMotorTorque; } b2Vec2 b2GetWheelJointForce( b2World* world, b2JointSim* base ) { int idA = base->bodyIdA; b2Transform transformA = b2GetBodyTransform( world, idA ); b2Vec2 localAxisA = b2RotateVector( base->localFrameA.q, (b2Vec2){ 1.0f, 0.0f } ); b2Vec2 axisA = b2RotateVector( transformA.q, localAxisA ); b2Vec2 perpA = b2LeftPerp( axisA ); b2WheelJoint* joint = &base->wheelJoint; float perpForce = world->inv_h * joint->perpImpulse; float axialForce = world->inv_h * ( joint->springImpulse + joint->lowerImpulse - joint->upperImpulse ); b2Vec2 force = b2Add( b2MulSV( perpForce, perpA ), b2MulSV( axialForce, axisA ) ); return force; } float b2GetWheelJointTorque( b2World* world, b2JointSim* base ) { return world->inv_h * base->wheelJoint.motorImpulse; } // Linear constraint (point-to-line) // d = pB - pA = xB + rB - xA - rA // C = dot(ay, d) // Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, rA)) // = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, ay), vB) // J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)] // Spring linear constraint // C = dot(ax, d) // Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + dot(cross(rB, ax), vB) // J = [-ax -cross(d+rA, ax) ax cross(rB, ax)] // Motor rotational constraint // Cdot = wB - wA // J = [0 0 -1 0 0 1] void b2PrepareWheelJoint( b2JointSim* base, b2StepContext* context ) { B2_ASSERT( base->type == b2_wheelJoint ); // chase body id to the solver set where the body lives int idA = base->bodyIdA; int idB = base->bodyIdB; b2World* world = context->world; b2Body* bodyA = b2BodyArray_Get( &world->bodies, idA ); b2Body* bodyB = b2BodyArray_Get( &world->bodies, idB ); B2_ASSERT( bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet ); b2SolverSet* setA = b2SolverSetArray_Get( &world->solverSets, bodyA->setIndex ); b2SolverSet* setB = b2SolverSetArray_Get( &world->solverSets, bodyB->setIndex ); int localIndexA = bodyA->localIndex; int localIndexB = bodyB->localIndex; b2BodySim* bodySimA = b2BodySimArray_Get( &setA->bodySims, localIndexA ); b2BodySim* bodySimB = b2BodySimArray_Get( &setB->bodySims, localIndexB ); float mA = bodySimA->invMass; float iA = bodySimA->invInertia; float mB = bodySimB->invMass; float iB = bodySimB->invInertia; base->invMassA = mA; base->invMassB = mB; base->invIA = iA; base->invIB = iB; b2WheelJoint* joint = &base->wheelJoint; joint->indexA = bodyA->setIndex == b2_awakeSet ? localIndexA : B2_NULL_INDEX; joint->indexB = bodyB->setIndex == b2_awakeSet ? localIndexB : B2_NULL_INDEX; // Compute joint anchor frames with world space rotation, relative to center of mass joint->frameA.q = b2MulRot( bodySimA->transform.q, base->localFrameA.q ); joint->frameA.p = b2RotateVector( bodySimA->transform.q, b2Sub( base->localFrameA.p, bodySimA->localCenter ) ); joint->frameB.q = b2MulRot( bodySimB->transform.q, base->localFrameB.q ); joint->frameB.p = b2RotateVector( bodySimB->transform.q, b2Sub( base->localFrameB.p, bodySimB->localCenter ) ); // Compute the initial center delta. Incremental position updates are relative to this. joint->deltaCenter = b2Sub( bodySimB->center, bodySimA->center ); b2Vec2 rA = joint->frameA.p; b2Vec2 rB = joint->frameB.p; b2Vec2 d = b2Add( joint->deltaCenter, b2Sub( rB, rA ) ); b2Vec2 axisA = b2RotateVector( joint->frameA.q, (b2Vec2){ 1.0f, 0.0f } ); b2Vec2 perpA = b2LeftPerp( axisA ); // perpendicular constraint (keep wheel on line) float s1 = b2Cross( b2Add( d, rA ), perpA ); float s2 = b2Cross( rB, perpA ); float kp = mA + mB + iA * s1 * s1 + iB * s2 * s2; joint->perpMass = kp > 0.0f ? 1.0f / kp : 0.0f; // spring constraint float a1 = b2Cross( b2Add( d, rA ), axisA ); float a2 = b2Cross( rB, axisA ); float ka = mA + mB + iA * a1 * a1 + iB * a2 * a2; joint->axialMass = ka > 0.0f ? 1.0f / ka : 0.0f; joint->springSoftness = b2MakeSoft( joint->hertz, joint->dampingRatio, context->h ); float km = iA + iB; joint->motorMass = km > 0.0f ? 1.0f / km : 0.0f; if ( context->enableWarmStarting == false ) { joint->perpImpulse = 0.0f; joint->springImpulse = 0.0f; joint->motorImpulse = 0.0f; joint->lowerImpulse = 0.0f; joint->upperImpulse = 0.0f; } } void b2WarmStartWheelJoint( b2JointSim* base, b2StepContext* context ) { B2_ASSERT( base->type == b2_wheelJoint ); float mA = base->invMassA; float mB = base->invMassB; float iA = base->invIA; float iB = base->invIB; // dummy state for static bodies b2BodyState dummyState = b2_identityBodyState; b2WheelJoint* joint = &base->wheelJoint; b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->frameA.p ); b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->frameB.p ); b2Vec2 d = b2Add( b2Add( b2Sub( stateB->deltaPosition, stateA->deltaPosition ), joint->deltaCenter ), b2Sub( rB, rA ) ); b2Vec2 axisA = b2RotateVector( joint->frameA.q, (b2Vec2){ 1.0f, 0.0f } ); axisA = b2RotateVector( stateA->deltaRotation, axisA ); b2Vec2 perpA = b2LeftPerp( axisA ); float a1 = b2Cross( b2Add( d, rA ), axisA ); float a2 = b2Cross( rB, axisA ); float s1 = b2Cross( b2Add( d, rA ), perpA ); float s2 = b2Cross( rB, perpA ); float axialImpulse = joint->springImpulse + joint->lowerImpulse - joint->upperImpulse; b2Vec2 P = b2Add( b2MulSV( axialImpulse, axisA ), b2MulSV( joint->perpImpulse, perpA ) ); float LA = axialImpulse * a1 + joint->perpImpulse * s1 + joint->motorImpulse; float LB = axialImpulse * a2 + joint->perpImpulse * s2 + joint->motorImpulse; if ( stateA->flags & b2_dynamicFlag ) { stateA->linearVelocity = b2MulSub( stateA->linearVelocity, mA, P ); stateA->angularVelocity -= iA * LA; } if ( stateB->flags & b2_dynamicFlag ) { stateB->linearVelocity = b2MulAdd( stateB->linearVelocity, mB, P ); stateB->angularVelocity += iB * LB; } } void b2SolveWheelJoint( b2JointSim* base, b2StepContext* context, bool useBias ) { B2_ASSERT( base->type == b2_wheelJoint ); float mA = base->invMassA; float mB = base->invMassB; float iA = base->invIA; float iB = base->invIB; // dummy state for static bodies b2BodyState dummyState = b2_identityBodyState; b2WheelJoint* joint = &base->wheelJoint; b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; b2Vec2 vA = stateA->linearVelocity; float wA = stateA->angularVelocity; b2Vec2 vB = stateB->linearVelocity; float wB = stateB->angularVelocity; bool fixedRotation = ( iA + iB == 0.0f ); // current anchors b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->frameA.p ); b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->frameB.p ); b2Vec2 d = b2Add( b2Add( b2Sub( stateB->deltaPosition, stateA->deltaPosition ), joint->deltaCenter ), b2Sub( rB, rA ) ); b2Vec2 axisA = b2RotateVector( joint->frameA.q, (b2Vec2){ 1.0f, 0.0f } ); axisA = b2RotateVector( stateA->deltaRotation, axisA ); float translation = b2Dot( axisA, d ); float a1 = b2Cross( b2Add( d, rA ), axisA ); float a2 = b2Cross( rB, axisA ); // motor constraint if ( joint->enableMotor && fixedRotation == false ) { float Cdot = wB - wA - joint->motorSpeed; float impulse = -joint->motorMass * Cdot; float oldImpulse = joint->motorImpulse; float maxImpulse = context->h * joint->maxMotorTorque; joint->motorImpulse = b2ClampFloat( joint->motorImpulse + impulse, -maxImpulse, maxImpulse ); impulse = joint->motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // spring constraint if ( joint->enableSpring ) { // This is a real spring and should be applied even during relax float C = translation; float bias = joint->springSoftness.biasRate * C; float massScale = joint->springSoftness.massScale; float impulseScale = joint->springSoftness.impulseScale; float Cdot = b2Dot( axisA, b2Sub( vB, vA ) ) + a2 * wB - a1 * wA; float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->springImpulse; joint->springImpulse += impulse; b2Vec2 P = b2MulSV( impulse, axisA ); float LA = impulse * a1; float LB = impulse * a2; vA = b2MulSub( vA, mA, P ); wA -= iA * LA; vB = b2MulAdd( vB, mB, P ); wB += iB * LB; } if ( joint->enableLimit ) { // Lower limit { float C = translation - joint->lowerTranslation; float bias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; if ( C > 0.0f ) { // speculation bias = C * context->inv_h; } else if ( useBias ) { bias = base->constraintSoftness.biasRate * C; massScale = base->constraintSoftness.massScale; impulseScale = base->constraintSoftness.impulseScale; } float Cdot = b2Dot( axisA, b2Sub( vB, vA ) ) + a2 * wB - a1 * wA; float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->lowerImpulse; float oldImpulse = joint->lowerImpulse; joint->lowerImpulse = b2MaxFloat( oldImpulse + impulse, 0.0f ); impulse = joint->lowerImpulse - oldImpulse; b2Vec2 P = b2MulSV( impulse, axisA ); float LA = impulse * a1; float LB = impulse * a2; vA = b2MulSub( vA, mA, P ); wA -= iA * LA; vB = b2MulAdd( vB, mB, P ); wB += iB * LB; } // Upper limit // Note: signs are flipped to keep C positive when the constraint is satisfied. // This also keeps the impulse positive when the limit is active. { // sign flipped float C = joint->upperTranslation - translation; float bias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; if ( C > 0.0f ) { // speculation bias = C * context->inv_h; } else if ( useBias ) { bias = base->constraintSoftness.biasRate * C; massScale = base->constraintSoftness.massScale; impulseScale = base->constraintSoftness.impulseScale; } // sign flipped on Cdot float Cdot = b2Dot( axisA, b2Sub( vA, vB ) ) + a1 * wA - a2 * wB; float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->upperImpulse; float oldImpulse = joint->upperImpulse; joint->upperImpulse = b2MaxFloat( oldImpulse + impulse, 0.0f ); impulse = joint->upperImpulse - oldImpulse; b2Vec2 P = b2MulSV( impulse, axisA ); float LA = impulse * a1; float LB = impulse * a2; // sign flipped on applied impulse vA = b2MulAdd( vA, mA, P ); wA += iA * LA; vB = b2MulSub( vB, mB, P ); wB -= iB * LB; } } // point to line constraint { b2Vec2 perpA = b2LeftPerp( axisA ); float bias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; if ( useBias ) { float C = b2Dot( perpA, d ); bias = base->constraintSoftness.biasRate * C; massScale = base->constraintSoftness.massScale; impulseScale = base->constraintSoftness.impulseScale; } float s1 = b2Cross( b2Add( d, rA ), perpA ); float s2 = b2Cross( rB, perpA ); float Cdot = b2Dot( perpA, b2Sub( vB, vA ) ) + s2 * wB - s1 * wA; float impulse = -massScale * joint->perpMass * ( Cdot + bias ) - impulseScale * joint->perpImpulse; joint->perpImpulse += impulse; b2Vec2 P = b2MulSV( impulse, perpA ); float LA = impulse * s1; float LB = impulse * s2; vA = b2MulSub( vA, mA, P ); wA -= iA * LA; vB = b2MulAdd( vB, mB, P ); wB += iB * LB; } if ( stateA->flags & b2_dynamicFlag ) { stateA->linearVelocity = vA; stateA->angularVelocity = wA; } if ( stateB->flags & b2_dynamicFlag ) { stateB->linearVelocity = vB; stateB->angularVelocity = wB; } } #if 0 void b2WheelJoint_Dump() { int32 indexA = joint->bodyA->joint->islandIndex; int32 indexB = joint->bodyB->joint->islandIndex; b2Dump(" b2WheelJointDef jd;\n"); b2Dump(" jd.bodyA = sims[%d];\n", indexA); b2Dump(" jd.bodyB = sims[%d];\n", indexB); b2Dump(" jd.collideConnected = bool(%d);\n", joint->collideConnected); b2Dump(" jd.localAnchorA.Set(%.9g, %.9g);\n", joint->localAnchorA.x, joint->localAnchorA.y); b2Dump(" jd.localAnchorB.Set(%.9g, %.9g);\n", joint->localAnchorB.x, joint->localAnchorB.y); b2Dump(" jd.referenceAngle = %.9g;\n", joint->referenceAngle); b2Dump(" jd.enableLimit = bool(%d);\n", joint->enableLimit); b2Dump(" jd.lowerAngle = %.9g;\n", joint->lowerAngle); b2Dump(" jd.upperAngle = %.9g;\n", joint->upperAngle); b2Dump(" jd.enableMotor = bool(%d);\n", joint->enableMotor); b2Dump(" jd.motorSpeed = %.9g;\n", joint->motorSpeed); b2Dump(" jd.maxMotorTorque = %.9g;\n", joint->maxMotorTorque); b2Dump(" joints[%d] = joint->world->CreateJoint(&jd);\n", joint->index); } #endif void b2DrawWheelJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB, float drawScale ) { B2_ASSERT( base->type == b2_wheelJoint ); b2WheelJoint* joint = &base->wheelJoint; b2Transform frameA = b2MulTransforms( transformA, base->localFrameA ); b2Transform frameB = b2MulTransforms( transformB, base->localFrameB ); b2Vec2 axisA = b2RotateVector( frameA.q, (b2Vec2){ 1.0f, 0.0f } ); b2HexColor c1 = b2_colorGray; b2HexColor c2 = b2_colorGreen; b2HexColor c3 = b2_colorRed; b2HexColor c4 = b2_colorDimGray; b2HexColor c5 = b2_colorBlue; draw->DrawLineFcn( frameA.p, frameB.p, c5, draw->context ); if ( joint->enableLimit ) { b2Vec2 lower = b2MulAdd( frameA.p, joint->lowerTranslation, axisA ); b2Vec2 upper = b2MulAdd( frameA.p, joint->upperTranslation, axisA ); b2Vec2 perp = b2LeftPerp( axisA ); draw->DrawLineFcn( lower, upper, c1, draw->context ); draw->DrawLineFcn( b2MulSub( lower, 0.1f * drawScale, perp ), b2MulAdd( lower, 0.1f * drawScale, perp ), c2, draw->context ); draw->DrawLineFcn( b2MulSub( upper, 0.1f * drawScale, perp ), b2MulAdd( upper, 0.1f * drawScale, perp ), c3, draw->context ); } else { draw->DrawLineFcn( b2MulSub( frameA.p, 1.0f, axisA ), b2MulAdd( frameA.p, 1.0f, axisA ), c1, draw->context ); } draw->DrawPointFcn( frameA.p, 5.0f, c1, draw->context ); draw->DrawPointFcn( frameB.p, 5.0f, c4, draw->context ); } ================================================ FILE: test/CMakeLists.txt ================================================ # Box2D unit test app set(BOX2D_TEST_FILES main.c test_bitset.c test_collision.c test_determinism.c test_distance.c test_dynamic_tree.c test_id.c test_macros.h test_math.c test_shape.c test_table.c test_world.c ) add_executable(test ${BOX2D_TEST_FILES}) set_target_properties(test PROPERTIES C_STANDARD 17 C_STANDARD_REQUIRED YES C_EXTENSIONS NO ) if (BOX2D_COMPILE_WARNING_AS_ERROR) set_target_properties(test PROPERTIES COMPILE_WARNING_AS_ERROR ON) endif() # Special access to Box2D internals for testing target_include_directories(test PRIVATE ${CMAKE_SOURCE_DIR}/src) target_link_libraries(test PRIVATE box2d shared enkiTS) source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}" PREFIX "" FILES ${BOX2D_TEST_FILES}) ================================================ FILE: test/main.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "test_macros.h" #if defined( _MSC_VER ) #include // int MyAllocHook(int allocType, void* userData, size_t size, int blockType, long requestNumber, const unsigned char* filename, // int lineNumber) //{ // if (size == 16416) // { // size += 0; // } // // return 1; // } #endif extern int BitSetTest( void ); extern int CollisionTest( void ); extern int DeterminismTest( void ); extern int DistanceTest( void ); extern int DynamicTreeTest( void ); extern int IdTest( void ); extern int MathTest( void ); extern int ShapeTest( void ); extern int TableTest( void ); extern int WorldTest( void ); int main( void ) { #if defined( _MSC_VER ) // Enable memory-leak reports // How to break at the leaking allocation, in the watch window enter this variable // and set it to the allocation number in {}. Do this at the first line in main. // {,,ucrtbased.dll}_crtBreakAlloc = 3970 // Note: // Just _crtBreakAlloc in static link // Tracy Profile server leaks _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR ); //_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG)); //_CrtSetAllocHook(MyAllocHook); //_CrtSetBreakAlloc(196); #endif printf( "Starting Box2D unit tests\n" ); printf( "======================================\n" ); RUN_TEST( TableTest ); RUN_TEST( MathTest ); RUN_TEST( BitSetTest ); RUN_TEST( CollisionTest ); RUN_TEST( DeterminismTest ); RUN_TEST( DistanceTest ); RUN_TEST( DynamicTreeTest ); RUN_TEST( IdTest ); RUN_TEST( ShapeTest ); RUN_TEST( WorldTest ); printf( "======================================\n" ); printf( "All Box2D tests passed!\n" ); #if defined( _MSC_VER ) if ( _CrtDumpMemoryLeaks() ) { return 1; } #endif return 0; } ================================================ FILE: test/test_bitset.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "bitset.h" #include "test_macros.h" #define COUNT 169 int BitSetTest( void ) { b2BitSet bitSet = b2CreateBitSet( COUNT ); b2SetBitCountAndClear( &bitSet, COUNT ); bool values[COUNT] = { false }; int32_t i1 = 0, i2 = 1; b2SetBit( &bitSet, i1 ); values[i1] = true; while ( i2 < COUNT ) { b2SetBit( &bitSet, i2 ); values[i2] = true; int32_t next = i1 + i2; i1 = i2; i2 = next; } for ( int32_t i = 0; i < COUNT; ++i ) { bool value = b2GetBit( &bitSet, i ); ENSURE( value == values[i] ); } b2DestroyBitSet( &bitSet ); return 0; } ================================================ FILE: test/test_collision.c ================================================ // SPDX-FileCopyrightText: 2025 Erin Catto // SPDX-License-Identifier: MIT #include "aabb.h" #include "test_macros.h" #include "box2d/math_functions.h" static int AABBTest( void ) { b2AABB a; a.lowerBound = (b2Vec2){ -1.0f, -1.0f }; a.upperBound = (b2Vec2){ -2.0f, -2.0f }; ENSURE( b2IsValidAABB( a ) == false ); a.upperBound = (b2Vec2){ 1.0f, 1.0f }; ENSURE( b2IsValidAABB( a ) == true ); b2AABB b = { { 2.0f, 2.0f }, { 4.0f, 4.0f } }; ENSURE( b2AABB_Overlaps( a, b ) == false ); ENSURE( b2AABB_Contains( a, b ) == false ); return 0; } static int AABBRayCastTest( void ) { // Test AABB centered at origin with bounds [-1, -1] to [1, 1] b2AABB aabb = { { -1.0f, -1.0f }, { 1.0f, 1.0f } }; // Test 1: Ray hits AABB from left side { b2Vec2 p1 = { -3.0f, 0.0f }; b2Vec2 p2 = { 3.0f, 0.0f }; b2CastOutput output = b2AABB_RayCast( aabb, p1, p2 ); ENSURE( output.hit == true ); ENSURE_SMALL( output.fraction - 1.0f / 3.0f, FLT_EPSILON ); ENSURE_SMALL( output.normal.x + 1.0f, FLT_EPSILON ); ENSURE_SMALL( output.normal.y, FLT_EPSILON ); ENSURE_SMALL( output.point.x + 1.0f, FLT_EPSILON ); ENSURE_SMALL( output.point.y, FLT_EPSILON ); } // Test 2: Ray hits AABB from right side { b2Vec2 p1 = { 3.0f, 0.0f }; b2Vec2 p2 = { -3.0f, 0.0f }; b2CastOutput output = b2AABB_RayCast( aabb, p1, p2 ); ENSURE( output.hit == true ); ENSURE_SMALL( output.fraction - 1.0f / 3.0f, FLT_EPSILON ); ENSURE_SMALL( output.normal.x - 1.0f, FLT_EPSILON ); ENSURE_SMALL( output.normal.y, FLT_EPSILON ); ENSURE_SMALL( output.point.x - 1.0f, FLT_EPSILON ); ENSURE_SMALL( output.point.y, FLT_EPSILON ); } // Test 3: Ray hits AABB from bottom { b2Vec2 p1 = { 0.0f, -3.0f }; b2Vec2 p2 = { 0.0f, 3.0f }; b2CastOutput output = b2AABB_RayCast( aabb, p1, p2 ); ENSURE( output.hit == true ); ENSURE_SMALL( output.fraction - 1.0f / 3.0f, FLT_EPSILON ); ENSURE_SMALL( output.normal.x, FLT_EPSILON ); ENSURE_SMALL( output.normal.y + 1.0f, FLT_EPSILON ); ENSURE_SMALL( output.point.x, FLT_EPSILON ); ENSURE_SMALL( output.point.y + 1.0f, FLT_EPSILON ); } // Test 4: Ray hits AABB from top { b2Vec2 p1 = { 0.0f, 3.0f }; b2Vec2 p2 = { 0.0f, -3.0f }; b2CastOutput output = b2AABB_RayCast( aabb, p1, p2 ); ENSURE( output.hit == true ); ENSURE_SMALL( output.fraction - 1.0f / 3.0f, FLT_EPSILON ); ENSURE_SMALL( output.normal.x, FLT_EPSILON ); ENSURE_SMALL( output.normal.y - 1.0f, FLT_EPSILON ); ENSURE_SMALL( output.point.x, FLT_EPSILON ); ENSURE_SMALL( output.point.y - 1.0f, FLT_EPSILON ); } // Test 5: Ray misses AABB completely (parallel to x-axis) { b2Vec2 p1 = { -3.0f, 2.0f }; b2Vec2 p2 = { 3.0f, 2.0f }; b2CastOutput output = b2AABB_RayCast( aabb, p1, p2 ); ENSURE( output.hit == false ); } // Test 6: Ray misses AABB completely (parallel to y-axis) { b2Vec2 p1 = { 2.0f, -3.0f }; b2Vec2 p2 = { 2.0f, 3.0f }; b2CastOutput output = b2AABB_RayCast( aabb, p1, p2 ); ENSURE( output.hit == false ); } // Test 7: Ray starts inside AABB { b2Vec2 p1 = { 0.0f, 0.0f }; b2Vec2 p2 = { 2.0f, 0.0f }; b2CastOutput output = b2AABB_RayCast( aabb, p1, p2 ); ENSURE( output.hit == false ); } // Test 8: Ray hits corner of AABB (diagonal ray) { b2Vec2 p1 = { -2.0f, -2.0f }; b2Vec2 p2 = { 2.0f, 2.0f }; b2CastOutput output = b2AABB_RayCast( aabb, p1, p2 ); ENSURE( output.hit == true ); ENSURE_SMALL( output.fraction - 0.25f, FLT_EPSILON ); // Normal should be either (-1, 0) or (0, -1) depending on which edge is hit first ENSURE( ( output.normal.x == -1.0f && output.normal.y == 0.0f ) || ( output.normal.x == 0.0f && output.normal.y == -1.0f ) ); } // Test 9: Ray parallel to AABB edge but outside { b2Vec2 p1 = { -2.0f, 1.5f }; b2Vec2 p2 = { 2.0f, 1.5f }; b2CastOutput output = b2AABB_RayCast( aabb, p1, p2 ); ENSURE( output.hit == false ); } // Test 10: Ray parallel to AABB edge and exactly on boundary { b2Vec2 p1 = { -2.0f, 1.0f }; b2Vec2 p2 = { 2.0f, 1.0f }; b2CastOutput output = b2AABB_RayCast( aabb, p1, p2 ); ENSURE( output.hit == true ); ENSURE_SMALL( output.fraction - 0.25f, FLT_EPSILON ); ENSURE_SMALL( output.normal.x + 1.0f, FLT_EPSILON ); ENSURE_SMALL( output.normal.y, FLT_EPSILON ); } // Test 11: Very short ray that doesn't reach AABB { b2Vec2 p1 = { -3.0f, 0.0f }; b2Vec2 p2 = { -2.5f, 0.0f }; b2CastOutput output = b2AABB_RayCast( aabb, p1, p2 ); ENSURE( output.hit == false ); } // Test 12: Zero-length ray (degenerate case) { b2Vec2 p1 = { 0.0f, 0.0f }; b2Vec2 p2 = { 0.0f, 0.0f }; b2CastOutput output = b2AABB_RayCast( aabb, p1, p2 ); ENSURE( output.hit == false ); } // Test 13: Ray hits AABB at exact boundary condition (t = 1.0) { b2Vec2 p1 = { -2.0f, 0.0f }; b2Vec2 p2 = { -1.0f, 0.0f }; b2CastOutput output = b2AABB_RayCast( aabb, p1, p2 ); ENSURE( output.hit == true ); ENSURE_SMALL( output.fraction - 1.0f, FLT_EPSILON ); ENSURE_SMALL( output.normal.x + 1.0f, FLT_EPSILON ); ENSURE_SMALL( output.normal.y, FLT_EPSILON ); } // Test 14: Different AABB position (not centered at origin) { b2AABB offsetAABB = { { 2.0f, 3.0f }, { 4.0f, 5.0f } }; b2Vec2 p1 = { 0.0f, 4.0f }; b2Vec2 p2 = { 6.0f, 4.0f }; b2CastOutput output = b2AABB_RayCast( offsetAABB, p1, p2 ); ENSURE( output.hit == true ); ENSURE_SMALL( output.fraction - 1.0f / 3.0f, FLT_EPSILON ); ENSURE_SMALL( output.normal.x + 1.0f, FLT_EPSILON ); ENSURE_SMALL( output.normal.y, FLT_EPSILON ); ENSURE_SMALL( output.point.x - 2.0f, FLT_EPSILON ); ENSURE_SMALL( output.point.y - 4.0f, FLT_EPSILON ); } return 0; } int CollisionTest( void ) { RUN_SUBTEST( AABBTest ); RUN_SUBTEST( AABBRayCastTest ); return 0; } ================================================ FILE: test/test_determinism.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "TaskScheduler_c.h" #include "determinism.h" #include "test_macros.h" #include "box2d/box2d.h" #include "box2d/types.h" #include #include #ifdef BOX2D_PROFILE #include #else #define TracyCFrameMark #endif #define EXPECTED_SLEEP_STEP 300 #define EXPECTED_HASH 0xD4F49FD3 enum { e_maxTasks = 128, }; typedef struct TaskData { b2TaskCallback* box2dTask; void* box2dContext; } TaskData; enkiTaskScheduler* scheduler; enkiTaskSet* tasks[e_maxTasks]; TaskData taskData[e_maxTasks]; int taskCount; static void ExecuteRangeTask( uint32_t start, uint32_t end, uint32_t threadIndex, void* context ) { TaskData* data = context; data->box2dTask( start, end, threadIndex, data->box2dContext ); } static void* EnqueueTask( b2TaskCallback* box2dTask, int itemCount, int minRange, void* box2dContext, void* userContext ) { MAYBE_UNUSED( userContext ); if ( taskCount < e_maxTasks ) { enkiTaskSet* task = tasks[taskCount]; TaskData* data = taskData + taskCount; data->box2dTask = box2dTask; data->box2dContext = box2dContext; struct enkiParamsTaskSet params; params.minRange = minRange; params.setSize = itemCount; params.pArgs = data; params.priority = 0; enkiSetParamsTaskSet( task, params ); enkiAddTaskSet( scheduler, task ); ++taskCount; return task; } box2dTask( 0, itemCount, 0, box2dContext ); return NULL; } static void FinishTask( void* userTask, void* userContext ) { MAYBE_UNUSED( userContext ); enkiTaskSet* task = userTask; enkiWaitForTaskSet( scheduler, task ); } static int SingleMultithreadingTest( int workerCount ) { scheduler = enkiNewTaskScheduler(); struct enkiTaskSchedulerConfig config = enkiGetTaskSchedulerConfig( scheduler ); config.numTaskThreadsToCreate = workerCount - 1; enkiInitTaskSchedulerWithConfig( scheduler, config ); for ( int i = 0; i < e_maxTasks; ++i ) { tasks[i] = enkiCreateTaskSet( scheduler, ExecuteRangeTask ); } b2WorldDef worldDef = b2DefaultWorldDef(); worldDef.enqueueTask = EnqueueTask; worldDef.finishTask = FinishTask; worldDef.workerCount = workerCount; b2WorldId worldId = b2CreateWorld( &worldDef ); FallingHingeData data = CreateFallingHinges( worldId ); float timeStep = 1.0f / 60.0f; bool done = false; while ( done == false ) { int subStepCount = 4; b2World_Step( worldId, timeStep, subStepCount ); TracyCFrameMark; done = UpdateFallingHinges( worldId, &data ); } b2DestroyWorld( worldId ); for ( int i = 0; i < e_maxTasks; ++i ) { enkiDeleteTaskSet( scheduler, tasks[i] ); } enkiDeleteTaskScheduler( scheduler ); ENSURE( data.sleepStep == EXPECTED_SLEEP_STEP ); ENSURE( data.hash == EXPECTED_HASH ); DestroyFallingHinges( &data ); return 0; } // Test multithreaded determinism. static int MultithreadingTest( void ) { for ( int workerCount = 1; workerCount < 6; ++workerCount ) { int result = SingleMultithreadingTest( workerCount ); ENSURE( result == 0 ); } return 0; } // Test cross-platform determinism. static int CrossPlatformTest( void ) { b2WorldDef worldDef = b2DefaultWorldDef(); b2WorldId worldId = b2CreateWorld( &worldDef ); FallingHingeData data = CreateFallingHinges( worldId ); float timeStep = 1.0f / 60.0f; bool done = false; while ( done == false ) { int subStepCount = 4; b2World_Step( worldId, timeStep, subStepCount ); TracyCFrameMark; done = UpdateFallingHinges( worldId, &data ); } ENSURE( data.sleepStep == EXPECTED_SLEEP_STEP ); ENSURE( data.hash == EXPECTED_HASH ); DestroyFallingHinges( &data ); b2DestroyWorld( worldId ); return 0; } int DeterminismTest( void ) { RUN_SUBTEST( MultithreadingTest ); RUN_SUBTEST( CrossPlatformTest ); return 0; } ================================================ FILE: test/test_distance.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "test_macros.h" #include "box2d/collision.h" #include "box2d/math_functions.h" #include static int SegmentDistanceTest( void ) { b2Vec2 p1 = { -1.0f, -1.0f }; b2Vec2 q1 = { -1.0f, 1.0f }; b2Vec2 p2 = { 2.0f, 0.0f }; b2Vec2 q2 = { 1.0f, 0.0f }; b2SegmentDistanceResult result = b2SegmentDistance( p1, q1, p2, q2 ); ENSURE_SMALL( result.fraction1 - 0.5f, FLT_EPSILON ); ENSURE_SMALL( result.fraction2 - 1.0f, FLT_EPSILON ); ENSURE_SMALL( result.closest1.x + 1.0f, FLT_EPSILON ); ENSURE_SMALL( result.closest1.y, FLT_EPSILON ); ENSURE_SMALL( result.closest2.x - 1.0f, FLT_EPSILON ); ENSURE_SMALL( result.closest2.y, FLT_EPSILON ); ENSURE_SMALL( result.distanceSquared - 4.0f, FLT_EPSILON ); return 0; } static int ShapeDistanceTest( void ) { b2Vec2 vas[] = { ( b2Vec2 ){ -1.0f, -1.0f }, ( b2Vec2 ){ 1.0f, -1.0f }, ( b2Vec2 ){ 1.0f, 1.0f }, ( b2Vec2 ){ -1.0f, 1.0f } }; b2Vec2 vbs[] = { ( b2Vec2 ){ 2.0f, -1.0f }, ( b2Vec2 ){ 2.0f, 1.0f }, }; b2DistanceInput input; input.proxyA = b2MakeProxy( vas, ARRAY_COUNT( vas ), 0.0f ); input.proxyB = b2MakeProxy( vbs, ARRAY_COUNT( vbs ), 0.0f ); input.transformA = b2Transform_identity; input.transformB = b2Transform_identity; input.useRadii = false; b2SimplexCache cache = { 0 }; b2DistanceOutput output = b2ShapeDistance(&input, &cache, NULL, 0 ); ENSURE_SMALL( output.distance - 1.0f, FLT_EPSILON ); return 0; } static int ShapeCastTest( void ) { b2Vec2 vas[] = { ( b2Vec2 ){ -1.0f, -1.0f }, ( b2Vec2 ){ 1.0f, -1.0f }, ( b2Vec2 ){ 1.0f, 1.0f }, ( b2Vec2 ){ -1.0f, 1.0f } }; b2Vec2 vbs[] = { ( b2Vec2 ){ 2.0f, -1.0f }, ( b2Vec2 ){ 2.0f, 1.0f }, }; b2ShapeCastPairInput input; input.proxyA = b2MakeProxy( vas, ARRAY_COUNT( vas ), 0.0f ); input.proxyB = b2MakeProxy( vbs, ARRAY_COUNT( vbs ), 0.0f ); input.transformA = b2Transform_identity; input.transformB = b2Transform_identity; input.translationB = ( b2Vec2 ){ -2.0f, 0.0f }; input.maxFraction = 1.0f; b2CastOutput output = b2ShapeCast( &input ); ENSURE( output.hit ); ENSURE_SMALL( output.fraction - 0.5f, 0.005f ); return 0; } static int TimeOfImpactTest( void ) { b2Vec2 vas[] = { { -1.0f, -1.0f }, { 1.0f, -1.0f }, { 1.0f, 1.0f }, { -1.0f, 1.0f } }; b2Vec2 vbs[] = { { 2.0f, -1.0f }, { 2.0f, 1.0f }, }; b2TOIInput input; input.proxyA = b2MakeProxy( vas, ARRAY_COUNT( vas ), 0.0f ); input.proxyB = b2MakeProxy( vbs, ARRAY_COUNT( vbs ), 0.0f ); input.sweepA = ( b2Sweep ){ b2Vec2_zero, b2Vec2_zero, b2Vec2_zero, b2Rot_identity, b2Rot_identity }; input.sweepB = ( b2Sweep ){ b2Vec2_zero, b2Vec2_zero, ( b2Vec2 ){ -2.0f, 0.0f }, b2Rot_identity, b2Rot_identity }; input.maxFraction = 1.0f; b2TOIOutput output = b2TimeOfImpact( &input ); ENSURE( output.state == b2_toiStateHit ); ENSURE_SMALL( output.fraction - 0.5f, 0.005f ); return 0; } int DistanceTest( void ) { RUN_SUBTEST( SegmentDistanceTest ); RUN_SUBTEST( ShapeDistanceTest ); RUN_SUBTEST( ShapeCastTest ); RUN_SUBTEST( TimeOfImpactTest ); return 0; } ================================================ FILE: test/test_dynamic_tree.c ================================================ // SPDX-FileCopyrightText: 2025 Erin Catto // SPDX-License-Identifier: MIT #include "test_macros.h" #include "box2d/collision.h" static int TreeCreateDestroy( void ) { b2AABB a = { .lowerBound = { -1.0f, -1.0f }, .upperBound = { 2.0f, 2.0f }, }; b2DynamicTree tree = b2DynamicTree_Create(); b2DynamicTree_CreateProxy( &tree, a, 1, 0 ); ENSURE( tree.nodeCount > 0 ); ENSURE( tree.proxyCount == 1 ); b2DynamicTree_Destroy( &tree ); ENSURE( tree.nodeCount == 0 ); ENSURE( tree.proxyCount == 0 ); return 0; } float RayCastCallbackFcn( const b2RayCastInput* input, int proxyId, uint64_t userData, void* context ) { (void)input; (void)userData; int* proxyHit = context; *proxyHit = proxyId; return 0.0f; } static int TreeRayCastTest( void ) { // Test AABB centered at origin with bounds [-1, -1] to [1, 1] b2AABB a = { .lowerBound = { -1.0f, -1.0f }, .upperBound = { 1.0f, 1.0f }, }; b2DynamicTree tree = b2DynamicTree_Create(); int proxyId = b2DynamicTree_CreateProxy( &tree, a, 1, 0 ); b2RayCastInput input = {}; input.maxFraction = 1.0f; // Test 1: Ray hits AABB from left side { b2Vec2 p1 = { -3.0f, 0.0f }; b2Vec2 p2 = { 3.0f, 0.0f }; input.origin = p1; input.translation = b2Sub( p2, p1 ); int proxyHit = -1; b2DynamicTree_RayCast( &tree, &input, 1, RayCastCallbackFcn, &proxyHit ); ENSURE( proxyHit == proxyId ); } // Test 2: Ray hits AABB from right side { b2Vec2 p1 = { 3.0f, 0.0f }; b2Vec2 p2 = { -3.0f, 0.0f }; input.origin = p1; input.translation = b2Sub( p2, p1 ); int proxyHit = -1; b2DynamicTree_RayCast( &tree, &input, 1, RayCastCallbackFcn, &proxyHit ); ENSURE( proxyHit == proxyId ); } // Test 3: Ray hits AABB from bottom { b2Vec2 p1 = { 0.0f, -3.0f }; b2Vec2 p2 = { 0.0f, 3.0f }; input.origin = p1; input.translation = b2Sub( p2, p1 ); int proxyHit = -1; b2DynamicTree_RayCast( &tree, &input, 1, RayCastCallbackFcn, &proxyHit ); ENSURE( proxyHit == proxyId ); } // Test 4: Ray hits AABB from top { b2Vec2 p1 = { 0.0f, 3.0f }; b2Vec2 p2 = { 0.0f, -3.0f }; input.origin = p1; input.translation = b2Sub( p2, p1 ); int proxyHit = -1; b2DynamicTree_RayCast( &tree, &input, 1, RayCastCallbackFcn, &proxyHit ); ENSURE( proxyHit == proxyId ); } // Test 5: Ray misses AABB completely (parallel to x-axis) { b2Vec2 p1 = { -3.0f, 2.0f }; b2Vec2 p2 = { 3.0f, 2.0f }; input.origin = p1; input.translation = b2Sub( p2, p1 ); int proxyHit = -1; b2DynamicTree_RayCast( &tree, &input, 1, RayCastCallbackFcn, &proxyHit ); ENSURE( proxyHit == -1 ); } // Test 6: Ray misses AABB completely (parallel to y-axis) { b2Vec2 p1 = { 2.0f, -3.0f }; b2Vec2 p2 = { 2.0f, 3.0f }; input.origin = p1; input.translation = b2Sub( p2, p1 ); int proxyHit = -1; b2DynamicTree_RayCast( &tree, &input, 1, RayCastCallbackFcn, &proxyHit ); ENSURE( proxyHit == -1 ); } // Test 7: Ray starts inside AABB { b2Vec2 p1 = { 0.0f, 0.0f }; b2Vec2 p2 = { 2.0f, 0.0f }; input.origin = p1; input.translation = b2Sub( p2, p1 ); int proxyHit = -1; b2DynamicTree_RayCast( &tree, &input, 1, RayCastCallbackFcn, &proxyHit ); ENSURE( proxyHit == proxyId ); } // Test 8: Ray hits corner of AABB (diagonal ray) { b2Vec2 p1 = { -2.0f, -2.0f }; b2Vec2 p2 = { 2.0f, 2.0f }; input.origin = p1; input.translation = b2Sub( p2, p1 ); int proxyHit = -1; b2DynamicTree_RayCast( &tree, &input, 1, RayCastCallbackFcn, &proxyHit ); ENSURE( proxyHit == proxyId ); } // Test 9: Ray parallel to AABB edge but outside { b2Vec2 p1 = { -2.0f, 1.5f }; b2Vec2 p2 = { 2.0f, 1.5f }; input.origin = p1; input.translation = b2Sub( p2, p1 ); int proxyHit = -1; b2DynamicTree_RayCast( &tree, &input, 1, RayCastCallbackFcn, &proxyHit ); ENSURE( proxyHit == -1 ); } // Test 10: Ray parallel to AABB edge and exactly on boundary { b2Vec2 p1 = { -2.0f, 1.0f }; b2Vec2 p2 = { 2.0f, 1.0f }; input.origin = p1; input.translation = b2Sub( p2, p1 ); int proxyHit = -1; b2DynamicTree_RayCast( &tree, &input, 1, RayCastCallbackFcn, &proxyHit ); ENSURE( proxyHit == proxyId ); } // Test 11: Very short ray that doesn't reach AABB { b2Vec2 p1 = { -3.0f, 0.0f }; b2Vec2 p2 = { -2.5f, 0.0f }; input.origin = p1; input.translation = b2Sub( p2, p1 ); int proxyHit = -1; b2DynamicTree_RayCast( &tree, &input, 1, RayCastCallbackFcn, &proxyHit ); ENSURE( proxyHit == -1 ); } // Test 12: Zero-length ray (degenerate case) { b2Vec2 p1 = { 0.0f, 0.0f }; b2Vec2 p2 = { 0.0f, 0.0f }; input.origin = p1; input.translation = b2Sub( p2, p1 ); int proxyHit = -1; b2DynamicTree_RayCast( &tree, &input, 1, RayCastCallbackFcn, &proxyHit ); ENSURE( proxyHit == proxyId ); } // Test 13: Ray hits AABB at exact boundary condition (t = 1.0) { b2Vec2 p1 = { -2.0f, 0.0f }; b2Vec2 p2 = { -1.0f, 0.0f }; input.origin = p1; input.translation = b2Sub( p2, p1 ); int proxyHit = -1; b2DynamicTree_RayCast( &tree, &input, 1, RayCastCallbackFcn, &proxyHit ); ENSURE( proxyHit == proxyId ); } b2DynamicTree_Destroy( &tree ); return 0; } static bool QueryCollectCallback( int proxyId, uint64_t userData, void* context ) { (void)userData; int* out = context; out[proxyId] = 1; return true; // continue the query } static bool QueryCollectListCallback( int proxyId, uint64_t userData, void* context ) { (void)userData; int* list = context; int count = list[0]; list[count + 1] = proxyId; list[0] = count + 1; return true; } static int TreeMultipleProxiesTest( void ) { b2DynamicTree tree = b2DynamicTree_Create(); b2AABB a1 = { .lowerBound = { -5.0f, -1.0f }, .upperBound = { -3.0f, 1.0f } }; b2AABB a2 = { .lowerBound = { -1.0f, -1.0f }, .upperBound = { 1.0f, 1.0f } }; b2AABB a3 = { .lowerBound = { 3.0f, -1.0f }, .upperBound = { 5.0f, 1.0f } }; int id1 = b2DynamicTree_CreateProxy( &tree, a1, 0x1ull, 42 ); int id2 = b2DynamicTree_CreateProxy( &tree, a2, 0x2ull, 43 ); int id3 = b2DynamicTree_CreateProxy( &tree, a3, 0x4ull, 44 ); ENSURE( b2DynamicTree_GetProxyCount( &tree ) == 3 ); ENSURE( b2DynamicTree_GetUserData( &tree, id1 ) == 42 ); ENSURE( b2DynamicTree_GetUserData( &tree, id2 ) == 43 ); ENSURE( b2DynamicTree_GetUserData( &tree, id3 ) == 44 ); ENSURE( b2DynamicTree_GetCategoryBits( &tree, id1 ) == 0x1ull ); ENSURE( b2DynamicTree_GetCategoryBits( &tree, id2 ) == 0x2ull ); ENSURE( b2DynamicTree_GetCategoryBits( &tree, id3 ) == 0x4ull ); b2DynamicTree_Destroy( &tree ); return 0; } static int TreeQueryTest( void ) { b2DynamicTree tree = b2DynamicTree_Create(); b2AABB a1 = { .lowerBound = { -5.0f, -1.0f }, .upperBound = { -3.0f, 1.0f } }; b2AABB a2 = { .lowerBound = { -1.0f, -1.0f }, .upperBound = { 1.0f, 1.0f } }; b2AABB a3 = { .lowerBound = { 3.0f, -1.0f }, .upperBound = { 5.0f, 1.0f } }; int id1 = b2DynamicTree_CreateProxy( &tree, a1, 0xFFull, 0 ); int id2 = b2DynamicTree_CreateProxy( &tree, a2, 0xFFull, 0 ); int id3 = b2DynamicTree_CreateProxy( &tree, a3, 0xFFull, 0 ); b2AABB queryA = { .lowerBound = { -2.0f, -2.0f }, .upperBound = { 2.0f, 2.0f } }; int foundFlags[32] = { 0 }; b2TreeStats stats = b2DynamicTree_Query( &tree, queryA, 0xFFFFFFFFull, QueryCollectCallback, foundFlags ); // We expect at least the middle proxy to be visited. ENSURE( foundFlags[id2] == 1 ); ENSURE( stats.leafVisits >= 1 ); // Test QueryAll using list collector int list[16] = { 0 }; // list[0] holds count, following entries are ids b2TreeStats allStats = b2DynamicTree_QueryAll( &tree, queryA, QueryCollectListCallback, list ); ENSURE( list[0] >= 1 ); // at least one proxy should be collected ENSURE( allStats.leafVisits >= 1 ); b2DynamicTree_Destroy( &tree ); (void)id1; (void)id3; return 0; } static int TreeMoveAndEnlargeTest( void ) { b2DynamicTree tree = b2DynamicTree_Create(); b2AABB a = { .lowerBound = { 0.0f, 0.0f }, .upperBound = { 1.0f, 1.0f } }; int id = b2DynamicTree_CreateProxy( &tree, a, 0x1ull, 100 ); // Move proxy to a new place b2AABB moved = { .lowerBound = { 10.0f, 10.0f }, .upperBound = { 11.0f, 11.0f } }; b2DynamicTree_MoveProxy( &tree, id, moved ); b2AABB got = b2DynamicTree_GetAABB( &tree, id ); ENSURE( got.lowerBound.x == moved.lowerBound.x ); ENSURE( got.lowerBound.y == moved.lowerBound.y ); ENSURE( got.upperBound.x == moved.upperBound.x ); ENSURE( got.upperBound.y == moved.upperBound.y ); // Now enlarge the proxy b2AABB enlarge = { .lowerBound = { 9.5f, 9.5f }, .upperBound = { 11.5f, 11.5f } }; b2DynamicTree_EnlargeProxy( &tree, id, enlarge ); b2AABB got2 = b2DynamicTree_GetAABB( &tree, id ); ENSURE( got2.lowerBound.x <= enlarge.lowerBound.x + 1e-6f ); ENSURE( got2.upperBound.x >= enlarge.upperBound.x - 1e-6f ); b2DynamicTree_Destroy( &tree ); return 0; } static int TreeRebuildAndValidateTest( void ) { b2DynamicTree tree = b2DynamicTree_Create(); // Create a number of proxies to make rebuild meaningful for ( int i = 0; i < 12; ++i ) { float x = (float)i * 2.0f; b2AABB a = { .lowerBound = { x - 0.5f, -0.5f }, .upperBound = { x + 0.5f, 0.5f } }; b2DynamicTree_CreateProxy( &tree, a, 0xFFull, (uint64_t)i ); } int sorted = b2DynamicTree_Rebuild( &tree, true ); ENSURE( sorted >= 0 ); ENSURE( b2DynamicTree_GetByteCount( &tree ) > 0 ); ENSURE( b2DynamicTree_GetHeight( &tree ) > 0 ); b2DynamicTree_Destroy( &tree ); return 0; } static int TreeRowHeightTest( void ) { b2DynamicTree tree = b2DynamicTree_Create(); int columnCount = 200; for (int i = 0; i < columnCount; ++i) { float x = 1.0f * i; b2AABB a = { .lowerBound = { x, 0.0f }, .upperBound = { x + 1.0f, 1.0f } }; b2DynamicTree_CreateProxy( &tree, a, 1, (uint64_t)i ); } float minHeight = log2f((float)columnCount); ENSURE( b2DynamicTree_GetHeight( &tree ) < 2.0f * minHeight ); b2DynamicTree_Destroy( &tree ); return 0; } static int TreeGridHeightTest( void ) { b2DynamicTree tree = b2DynamicTree_Create(); int columnCount = 20; int rowCount = 20; for (int i = 0; i < columnCount; ++i) { float x = 1.0f * i; for (int j = 0; j < rowCount; ++j) { float y = 1.0f * j; b2AABB a = { .lowerBound = { x, y }, .upperBound = { x + 1.0f, y + 1.0f } }; b2DynamicTree_CreateProxy( &tree, a, 1, (uint64_t)i ); } } float minHeight = log2f( (float)(rowCount * columnCount) ); ENSURE( b2DynamicTree_GetHeight( &tree ) < 2.0f * minHeight ); b2DynamicTree_Destroy( &tree ); return 0; } #define GRID_COUNT 20 static int TreeGridMovementTest( void ) { b2DynamicTree tree = b2DynamicTree_Create(); int proxyIds[GRID_COUNT * GRID_COUNT]; int index = 0; for (int i = 0; i < GRID_COUNT; ++i) { float x = 1.0f * i; for (int j = 0; j < GRID_COUNT; ++j) { float y = 1.0f * j; b2AABB a = { .lowerBound = { x, y }, .upperBound = { x + 1.0f, y + 1.0f } }; proxyIds[index] = b2DynamicTree_CreateProxy( &tree, a, 1, (uint64_t)i ); index += 1; } } ENSURE( index == GRID_COUNT * GRID_COUNT ); float minHeight = log2f( (float)( GRID_COUNT * GRID_COUNT ) ); int height1 = b2DynamicTree_GetHeight( &tree ); ENSURE( height1 < 2.0f * minHeight ); b2Vec2 offset = {10.0f, 20.0f}; index = 0; for (int i = 0; i < GRID_COUNT; ++i) { for (int j = 0; j < GRID_COUNT; ++j) { b2AABB a = b2DynamicTree_GetAABB( &tree, proxyIds[index] ); a.lowerBound = b2Add( a.lowerBound, offset ); a.upperBound = b2Add( a.upperBound, offset ); b2DynamicTree_MoveProxy( &tree, proxyIds[index], a ); index += 1; } } int height2 = b2DynamicTree_GetHeight( &tree ); ENSURE( height2 < 3.0f * minHeight ); b2DynamicTree_Rebuild( &tree, true ); int height3 = b2DynamicTree_GetHeight( &tree ); ENSURE( height3 < 2.0f * minHeight ); b2DynamicTree_Destroy( &tree ); return 0; } int DynamicTreeTest( void ) { RUN_SUBTEST( TreeCreateDestroy ); RUN_SUBTEST( TreeRayCastTest ); RUN_SUBTEST( TreeMultipleProxiesTest ); RUN_SUBTEST( TreeQueryTest ); RUN_SUBTEST( TreeMoveAndEnlargeTest ); RUN_SUBTEST( TreeRebuildAndValidateTest ); RUN_SUBTEST( TreeRowHeightTest ); RUN_SUBTEST( TreeGridHeightTest ); RUN_SUBTEST( TreeGridMovementTest ); return 0; } ================================================ FILE: test/test_id.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "test_macros.h" #include "box2d/id.h" int IdTest( void ) { uint32_t a = 0x01234567; { b2WorldId id = b2LoadWorldId( a ); uint32_t b = b2StoreWorldId( id ); ENSURE( b == a ); } uint64_t x = 0x0123456789ABCDEFull; { b2BodyId id = b2LoadBodyId( x ); uint64_t y = b2StoreBodyId( id ); ENSURE( x == y ); } { b2ShapeId id = b2LoadShapeId( x ); uint64_t y = b2StoreShapeId( id ); ENSURE( x == y ); } { b2ChainId id = b2LoadChainId( x ); uint64_t y = b2StoreChainId( id ); ENSURE( x == y ); } { b2JointId id = b2LoadJointId( x ); uint64_t y = b2StoreJointId( id ); ENSURE( x == y ); } return 0; } ================================================ FILE: test/test_macros.h ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include #include #include #define RUN_TEST( T ) \ do \ { \ int result = T(); \ if ( result == 1 ) \ { \ printf( "test failed: " #T "\n" ); \ return 1; \ } \ else \ { \ printf( "test passed: " #T "\n" ); \ } \ } \ while ( false ) #define RUN_SUBTEST( T ) \ do \ { \ int result = T(); \ if ( result == 1 ) \ { \ printf( " subtest failed: " #T "\n" ); \ return 1; \ } \ else \ { \ printf( " subtest passed: " #T "\n" ); \ } \ } \ while ( false ) #define ENSURE( C ) \ do \ { \ if ( ( C ) == false ) \ { \ printf( "condition false: " #C "\n" ); \ assert( false ); \ return 1; \ } \ } \ while ( false ) #define ENSURE_SMALL( C, tol ) \ do \ { \ if ( ( C ) < -( tol ) || ( tol ) < ( C ) ) \ { \ printf( "condition false: abs(" #C ") < %g\n", tol ); \ assert( false ); \ return 1; \ } \ } \ while ( false ) #define ARRAY_COUNT( A ) (int)( sizeof( A ) / sizeof( A[0] ) ) /// Used to prevent the compiler from warning about unused variables #define MAYBE_UNUSED( x ) ( (void)( x ) ) ================================================ FILE: test/test_math.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "test_macros.h" #include "box2d/math_functions.h" #include #include // 0.0023 degrees #define ATAN_TOL 0.00004f int MathTest( void ) { for ( float t = -10.0f; t < 10.0f; t += 0.01f ) { float angle = B2_PI * t; b2Rot r = b2MakeRot( angle ); float c = cosf( angle ); float s = sinf( angle ); // The cosine and sine approximations are accurate to about 0.1 degrees (0.002 radians) // printf( "%g %g\n", r.c - c, r.s - s ); ENSURE_SMALL( r.c - c, 0.002f ); ENSURE_SMALL( r.s - s, 0.002f ); float xn = b2UnwindAngle( angle ); ENSURE( -B2_PI <= xn && xn <= B2_PI ); float a = b2Atan2( s, c ); ENSURE( b2IsValidFloat( a ) ); float diff = b2AbsFloat( a - xn ); // The two results can be off by 360 degrees (-pi and pi) if ( diff > B2_PI ) { diff -= 2.0f * B2_PI; } // The approximate atan2 is quite accurate ENSURE_SMALL( diff, ATAN_TOL ); } for ( float y = -1.0f; y <= 1.0f; y += 0.01f ) { for ( float x = -1.0f; x <= 1.0f; x += 0.01f ) { float a1 = b2Atan2( y, x ); float a2 = atan2f( y, x ); float diff = b2AbsFloat( a1 - a2 ); ENSURE( b2IsValidFloat( a1 ) ); ENSURE_SMALL( diff, ATAN_TOL ); } } { float a1 = b2Atan2( 1.0f, 0.0f ); float a2 = atan2f( 1.0f, 0.0f ); float diff = b2AbsFloat( a1 - a2 ); ENSURE( b2IsValidFloat( a1 ) ); ENSURE_SMALL( diff, ATAN_TOL ); } { float a1 = b2Atan2( -1.0f, 0.0f ); float a2 = atan2f( -1.0f, 0.0f ); float diff = b2AbsFloat( a1 - a2 ); ENSURE( b2IsValidFloat( a1 ) ); ENSURE_SMALL( diff, ATAN_TOL ); } { float a1 = b2Atan2( 0.0f, 1.0f ); float a2 = atan2f( 0.0f, 1.0f ); float diff = b2AbsFloat( a1 - a2 ); ENSURE( b2IsValidFloat( a1 ) ); ENSURE_SMALL( diff, ATAN_TOL ); } { float a1 = b2Atan2( 0.0f, -1.0f ); float a2 = atan2f( 0.0f, -1.0f ); float diff = b2AbsFloat( a1 - a2 ); ENSURE( b2IsValidFloat( a1 ) ); ENSURE_SMALL( diff, ATAN_TOL ); } { float a1 = b2Atan2( 0.0f, 0.0f ); float a2 = atan2f( 0.0f, 0.0f ); float diff = b2AbsFloat( a1 - a2 ); ENSURE( b2IsValidFloat( a1 ) ); ENSURE_SMALL( diff, ATAN_TOL ); } b2Vec2 zero = b2Vec2_zero; b2Vec2 one = { 1.0f, 1.0f }; b2Vec2 two = { 2.0f, 2.0f }; b2Vec2 v = b2Add( one, two ); ENSURE( v.x == 3.0f && v.y == 3.0f ); v = b2Sub( zero, two ); ENSURE( v.x == -2.0f && v.y == -2.0f ); v = b2Add( two, two ); ENSURE( v.x != 5.0f && v.y != 5.0f ); b2Transform transform1 = { { -2.0f, 3.0f }, b2MakeRot( 1.0f ) }; b2Transform transform2 = { { 1.0f, 0.0f }, b2MakeRot( -2.0f ) }; b2Transform transform = b2MulTransforms( transform2, transform1 ); v = b2TransformPoint( transform2, b2TransformPoint( transform1, two ) ); b2Vec2 u = b2TransformPoint( transform, two ); ENSURE_SMALL( u.x - v.x, 10.0f * FLT_EPSILON ); ENSURE_SMALL( u.y - v.y, 10.0f * FLT_EPSILON ); v = b2TransformPoint( transform1, two ); v = b2InvTransformPoint( transform1, v ); ENSURE_SMALL( v.x - two.x, 8.0f * FLT_EPSILON ); ENSURE_SMALL( v.y - two.y, 8.0f * FLT_EPSILON ); v = b2Normalize(( b2Vec2 ){ 0.2f, -0.5f }); for ( float y = -1.0f; y <= 1.0f; y += 0.01f ) { for ( float x = -1.0f; x <= 1.0f; x += 0.01f ) { if (x == 0.0f && y == 0.0f) { continue; } u = b2Normalize( ( b2Vec2 ){ x, y } ); b2Rot r = b2ComputeRotationBetweenUnitVectors( v, u ); b2Vec2 w = b2RotateVector( r, v ); ENSURE_SMALL( w.x - u.x, 4.0f * FLT_EPSILON ); ENSURE_SMALL( w.y - u.y, 4.0f * FLT_EPSILON ); } } // NLerp of b2Rot has an error of over 4 degrees. // 2D quaternions should have an error under 1 degree. b2Rot q1 = b2Rot_identity; b2Rot q2 = b2MakeRot(0.5f * B2_PI); int n = 100; for (int i = 0; i <= n; ++i) { float alpha = (float)i / (float)n; b2Rot q = b2NLerp(q1, q2, alpha); float angle = b2Rot_GetAngle(q); ENSURE_SMALL( alpha * 0.5f * B2_PI - angle, 5.0f * B2_PI / 180.0f ); //printf("angle = [%g %g %g]\n", alpha, alpha * 0.5f * B2_PI, angle); } // Test relative angle float baseAngle = 0.75f * B2_PI; q1 = b2MakeRot(baseAngle); for ( float t = -10.0f; t < 10.0f; t += 0.01f ) { float angle = B2_PI * t; q2 = b2MakeRot(angle); float relativeAngle = b2RelativeAngle( q1, q2 ); float unwoundAngle = b2UnwindAngle( angle - baseAngle ); float tolerance = 0.1f * B2_PI / 180.0f; ENSURE_SMALL( relativeAngle - unwoundAngle, tolerance ); } return 0; } ================================================ FILE: test/test_shape.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "test_macros.h" #include "box2d/collision.h" #include "box2d/math_functions.h" #include static b2Capsule capsule = { { -1.0f, 0.0f }, { 1.0f, 0.0f }, 1.0f }; static b2Circle circle = { { 1.0f, 0.0f }, 1.0f }; static b2Polygon box; static b2Segment segment = { { 0.0f, 1.0f }, { 0.0f, -1.0f } }; #define N 4 static int ShapeMassTest( void ) { { b2MassData md = b2ComputeCircleMass( &circle, 1.0f ); ENSURE_SMALL( md.mass - B2_PI, FLT_EPSILON ); ENSURE( md.center.x == 1.0f && md.center.y == 0.0f ); ENSURE_SMALL( md.rotationalInertia - 0.5f * B2_PI, FLT_EPSILON ); } { float radius = capsule.radius; float length = b2Distance( capsule.center1, capsule.center2 ); b2MassData md = b2ComputeCapsuleMass( &capsule, 1.0f ); // Box that full contains capsule b2Polygon r = b2MakeBox( radius, radius + 0.5f * length ); b2MassData mdr = b2ComputePolygonMass( &r, 1.0f ); // Approximate capsule using convex hull b2Vec2 points[2 * N]; float d = B2_PI / ( N - 1.0f ); float angle = -0.5f * B2_PI; for ( int i = 0; i < N; ++i ) { points[i].x = 1.0f + radius * cosf( angle ); points[i].y = radius * sinf( angle ); angle += d; } angle = 0.5f * B2_PI; for ( int i = N; i < 2 * N; ++i ) { points[i].x = -1.0f + radius * cosf( angle ); points[i].y = radius * sinf( angle ); angle += d; } b2Hull hull = b2ComputeHull( points, 2 * N ); b2Polygon ac = b2MakePolygon( &hull, 0.0f ); b2MassData ma = b2ComputePolygonMass( &ac, 1.0f ); ENSURE( ma.mass < md.mass && md.mass < mdr.mass ); ENSURE( ma.rotationalInertia < md.rotationalInertia && md.rotationalInertia < mdr.rotationalInertia ); } { b2MassData md = b2ComputePolygonMass( &box, 1.0f ); ENSURE_SMALL( md.mass - 4.0f, FLT_EPSILON ); ENSURE_SMALL( md.center.x, FLT_EPSILON ); ENSURE_SMALL( md.center.y, FLT_EPSILON ); ENSURE_SMALL( md.rotationalInertia - 8.0f / 3.0f, 2.0f * FLT_EPSILON ); } return 0; } static int ShapeAABBTest( void ) { { b2AABB b = b2ComputeCircleAABB( &circle, b2Transform_identity ); ENSURE_SMALL( b.lowerBound.x, FLT_EPSILON ); ENSURE_SMALL( b.lowerBound.y + 1.0f, FLT_EPSILON ); ENSURE_SMALL( b.upperBound.x - 2.0f, FLT_EPSILON ); ENSURE_SMALL( b.upperBound.y - 1.0f, FLT_EPSILON ); } { b2AABB b = b2ComputePolygonAABB( &box, b2Transform_identity ); ENSURE_SMALL( b.lowerBound.x + 1.0f, FLT_EPSILON ); ENSURE_SMALL( b.lowerBound.y + 1.0f, FLT_EPSILON ); ENSURE_SMALL( b.upperBound.x - 1.0f, FLT_EPSILON ); ENSURE_SMALL( b.upperBound.y - 1.0f, FLT_EPSILON ); } { b2AABB b = b2ComputeSegmentAABB( &segment, b2Transform_identity ); ENSURE_SMALL( b.lowerBound.x, FLT_EPSILON ); ENSURE_SMALL( b.lowerBound.y + 1.0f, FLT_EPSILON ); ENSURE_SMALL( b.upperBound.x, FLT_EPSILON ); ENSURE_SMALL( b.upperBound.y - 1.0f, FLT_EPSILON ); } return 0; } static int PointInShapeTest( void ) { b2Vec2 p1 = { 0.5f, 0.5f }; b2Vec2 p2 = { 4.0f, -4.0f }; { bool hit; hit = b2PointInCircle(&circle, p1 ); ENSURE( hit == true ); hit = b2PointInCircle( &circle, p2 ); ENSURE( hit == false ); } { bool hit; hit = b2PointInPolygon( &box, p1); ENSURE( hit == true ); hit = b2PointInPolygon(&box, p2); ENSURE( hit == false ); } return 0; } static int RayCastShapeTest( void ) { b2RayCastInput input = { { -4.0f, 0.0f }, { 8.0f, 0.0f }, 1.0f }; { b2CastOutput output = b2RayCastCircle( &circle, & input ); ENSURE( output.hit ); ENSURE_SMALL( output.normal.x + 1.0f, FLT_EPSILON ); ENSURE_SMALL( output.normal.y, FLT_EPSILON ); ENSURE_SMALL( output.fraction - 0.5f, FLT_EPSILON ); } { b2CastOutput output = b2RayCastPolygon( &box, & input); ENSURE( output.hit ); ENSURE_SMALL( output.normal.x + 1.0f, FLT_EPSILON ); ENSURE_SMALL( output.normal.y, FLT_EPSILON ); ENSURE_SMALL( output.fraction - 3.0f / 8.0f, FLT_EPSILON ); } { b2CastOutput output = b2RayCastSegment( &segment, &input, true ); ENSURE( output.hit ); ENSURE_SMALL( output.normal.x + 1.0f, FLT_EPSILON ); ENSURE_SMALL( output.normal.y, FLT_EPSILON ); ENSURE_SMALL( output.fraction - 0.5f, FLT_EPSILON ); } return 0; } int ShapeTest( void ) { box = b2MakeBox( 1.0f, 1.0f ); RUN_SUBTEST( ShapeMassTest ); RUN_SUBTEST( ShapeAABBTest ); RUN_SUBTEST( PointInShapeTest ); RUN_SUBTEST( RayCastShapeTest ); return 0; } ================================================ FILE: test/test_table.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "atomic.h" #include "core.h" #include "ctz.h" #include "table.h" #include "test_macros.h" #include "box2d/base.h" #define SET_SPAN 317 #define ITEM_COUNT ( ( SET_SPAN * SET_SPAN - SET_SPAN ) / 2 ) static int BasicHashSetTest( void ) { // Test basic creation and destruction b2HashSet set = b2CreateSet( 16 ); ENSURE( b2GetSetCount( &set ) == 0 ); ENSURE( b2GetSetCapacity( &set ) == 16 ); b2DestroySet( &set ); ENSURE( set.items == NULL ); ENSURE( set.count == 0 ); ENSURE( set.capacity == 0 ); return 0; } static int HashSetCapacityTest( void ) { // Test capacity adjustments - capacity should be power of 2 { b2HashSet set = b2CreateSet( 1 ); ENSURE( b2GetSetCapacity( &set ) == 16 ); // Minimum capacity b2DestroySet( &set ); } { b2HashSet set = b2CreateSet( 15 ); ENSURE( b2GetSetCapacity( &set ) == 16 ); // Should round up to 16 b2DestroySet( &set ); } { b2HashSet set = b2CreateSet( 32 ); ENSURE( b2GetSetCapacity( &set ) == 32 ); // Should stay at 32 b2DestroySet( &set ); } { b2HashSet set = b2CreateSet( 33 ); ENSURE( b2GetSetCapacity( &set ) == 64 ); // Should round up to 64 b2DestroySet( &set ); } return 0; } static int HashSetAddRemoveTest( void ) { b2HashSet set = b2CreateSet( 16 ); // Test adding new keys bool found = b2AddKey( &set, 42 ); ENSURE( found == false ); // Should be new ENSURE( b2GetSetCount( &set ) == 1 ); found = b2AddKey( &set, 123 ); ENSURE( found == false ); // Should be new ENSURE( b2GetSetCount( &set ) == 2 ); // Test adding duplicate key found = b2AddKey( &set, 42 ); ENSURE( found == true ); // Should already exist ENSURE( b2GetSetCount( &set ) == 2 ); // Count shouldn't change // Test contains ENSURE( b2ContainsKey( &set, 42 ) == true ); ENSURE( b2ContainsKey( &set, 123 ) == true ); ENSURE( b2ContainsKey( &set, 999 ) == false ); // Test removal bool removed = b2RemoveKey( &set, 42 ); ENSURE( removed == true ); ENSURE( b2GetSetCount( &set ) == 1 ); ENSURE( b2ContainsKey( &set, 42 ) == false ); ENSURE( b2ContainsKey( &set, 123 ) == true ); // Test removing non-existent key removed = b2RemoveKey( &set, 999 ); ENSURE( removed == false ); ENSURE( b2GetSetCount( &set ) == 1 ); // Test removing same key twice removed = b2RemoveKey( &set, 42 ); ENSURE( removed == false ); ENSURE( b2GetSetCount( &set ) == 1 ); b2DestroySet( &set ); return 0; } static int HashSetClearTest( void ) { b2HashSet set = b2CreateSet( 16 ); // Add some keys b2AddKey( &set, 10 ); b2AddKey( &set, 20 ); b2AddKey( &set, 30 ); ENSURE( b2GetSetCount( &set ) == 3 ); // Clear the set b2ClearSet( &set ); ENSURE( b2GetSetCount( &set ) == 0 ); ENSURE( b2ContainsKey( &set, 10 ) == false ); ENSURE( b2ContainsKey( &set, 20 ) == false ); ENSURE( b2ContainsKey( &set, 30 ) == false ); // Test that we can add keys after clearing b2AddKey( &set, 40 ); ENSURE( b2GetSetCount( &set ) == 1 ); ENSURE( b2ContainsKey( &set, 40 ) == true ); b2DestroySet( &set ); return 0; } static int HashSetGrowthTest( void ) { b2HashSet set = b2CreateSet( 16 ); int initialCapacity = b2GetSetCapacity( &set ); // Add enough keys to trigger growth (load factor is 0.5) // With capacity 16, growth should happen when count reaches 8 for ( uint64_t i = 0; i < 8; ++i ) { b2AddKey( &set, i + 1); } // Should have grown int newCapacity = b2GetSetCapacity( &set ); ENSURE( newCapacity >= initialCapacity ); ENSURE( b2GetSetCount( &set ) == 8 ); // Verify all keys are still present after growth for ( uint64_t i = 1; i <= 8; ++i ) { ENSURE( b2ContainsKey( &set, i ) == true ); } b2DestroySet( &set ); return 0; } static int HashSetEdgeCasesTest( void ) { b2HashSet set = b2CreateSet( 16 ); // Test large key values uint64_t largeKey = 0xFFFFFFFFFFFFFFFFULL - 1; // Max value minus 1 (since 0 is sentinel) b2AddKey( &set, largeKey ); ENSURE( b2ContainsKey( &set, largeKey ) == true ); ENSURE( b2GetSetCount( &set ) == 1 ); // Test keys that might cause hash collisions uint64_t key1 = 0x123456789ABCDEFULL; uint64_t key2 = 0x987654321FEDCBAULL; b2AddKey( &set, key1 ); b2AddKey( &set, key2 ); ENSURE( b2ContainsKey( &set, key1 ) == true ); ENSURE( b2ContainsKey( &set, key2 ) == true ); // Test pattern that could cause clustering for ( uint64_t i = 0x1000; i < 0x1010; ++i ) { b2AddKey( &set, i ); } for ( uint64_t i = 0x1000; i < 0x1010; ++i ) { ENSURE( b2ContainsKey( &set, i ) == true ); } b2DestroySet( &set ); return 0; } static int HashSetRemovalReorganizationTest( void ) { b2HashSet set = b2CreateSet( 16 ); // Add keys that might cluster together uint64_t keys[] = { 100, 116, 132, 148, 164 }; // These might hash to similar slots int keyCount = sizeof( keys ) / sizeof( keys[0] ); for ( int i = 0; i < keyCount; ++i ) { b2AddKey( &set, keys[i] ); } // Verify all keys are present for ( int i = 0; i < keyCount; ++i ) { ENSURE( b2ContainsKey( &set, keys[i] ) == true ); } // Remove a key from the middle b2RemoveKey( &set, keys[2] ); ENSURE( b2ContainsKey( &set, keys[2] ) == false ); // Verify other keys are still present (tests reorganization) for ( int i = 0; i < keyCount; ++i ) { if ( i != 2 ) { ENSURE( b2ContainsKey( &set, keys[i] ) == true ); } } b2DestroySet( &set ); return 0; } #define TEST_SIZE 1000 static int HashSetStressTest( void ) { b2HashSet set = b2CreateSet( 32 ); const int testSize = TEST_SIZE; uint64_t keys[TEST_SIZE]; // Generate test keys for ( int i = 0; i < testSize; ++i ) { keys[i] = (uint64_t)( i * 7 + 13 ); // Some pattern to avoid zero } // Add all keys for ( int i = 0; i < testSize; ++i ) { bool found = b2AddKey( &set, keys[i] ); ENSURE( found == false ); } ENSURE( b2GetSetCount( &set ) == testSize ); // Verify all keys are present for ( int i = 0; i < testSize; ++i ) { ENSURE( b2ContainsKey( &set, keys[i] ) == true ); } // Remove every other key int removedCount = 0; for ( int i = 0; i < testSize; i += 2 ) { bool removed = b2RemoveKey( &set, keys[i] ); ENSURE( removed == true ); removedCount++; } ENSURE( b2GetSetCount( &set ) == testSize - removedCount ); // Verify remaining keys are still present for ( int i = 0; i < testSize; ++i ) { bool shouldBePresent = ( i % 2 == 1 ); ENSURE( b2ContainsKey( &set, keys[i] ) == shouldBePresent ); } b2DestroySet( &set ); return 0; } static int HashSetShapePairKeyTest( void ) { b2HashSet set = b2CreateSet( 16 ); // Test the B2_SHAPE_PAIR_KEY macro uint64_t key1 = B2_SHAPE_PAIR_KEY( 5, 10 ); uint64_t key2 = B2_SHAPE_PAIR_KEY( 10, 5 ); // Should be same as key1 ENSURE( key1 == key2 ); b2AddKey( &set, key1 ); ENSURE( b2ContainsKey( &set, key1 ) == true ); ENSURE( b2ContainsKey( &set, key2 ) == true ); // Should find same key // Test different pairs uint64_t key3 = B2_SHAPE_PAIR_KEY( 1, 2 ); uint64_t key4 = B2_SHAPE_PAIR_KEY( 2, 3 ); ENSURE( key3 != key4 ); b2AddKey( &set, key3 ); b2AddKey( &set, key4 ); ENSURE( b2GetSetCount( &set ) == 3 ); b2DestroySet( &set ); return 0; } static int HashSetBytesTest( void ) { b2HashSet set = b2CreateSet( 32 ); int bytes = b2GetHashSetBytes( &set ); int expectedBytes = 32 * (int)sizeof( b2SetItem ); ENSURE( bytes == expectedBytes ); // Add some items and verify bytes calculation doesn't change b2AddKey( &set, 100 ); b2AddKey( &set, 200 ); int bytesAfterAdd = b2GetHashSetBytes( &set ); ENSURE( bytesAfterAdd == expectedBytes ); b2DestroySet( &set ); return 0; } static int HashSetTest( void ) { const int N = SET_SPAN; const uint32_t itemCount = ITEM_COUNT; bool removed[ITEM_COUNT] = { 0 }; for ( int iter = 0; iter < 1; ++iter ) { b2HashSet set = b2CreateSet( 16 ); // Fill set for ( int i = 0; i < N; ++i ) { for ( int j = i + 1; j < N; ++j ) { uint64_t key = B2_SHAPE_PAIR_KEY( i, j ); bool found = b2AddKey( &set, key ); ENSURE( found == false ); } } ENSURE( b2GetSetCount( &set ) == itemCount ); // Remove a portion of the set int k = 0; uint32_t removeCount = 0; for ( int i = 0; i < N; ++i ) { for ( int j = i + 1; j < N; ++j ) { if ( j == i + 1 ) { uint64_t key = B2_SHAPE_PAIR_KEY( i, j ); int size1 = b2GetSetCount( &set ); bool found = b2RemoveKey( &set, key ); ENSURE( found ); int size2 = b2GetSetCount( &set ); ENSURE( size2 == size1 - 1 ); removed[k++] = true; removeCount += 1; } else { removed[k++] = false; } } } ENSURE( b2GetSetCount( &set ) == ( itemCount - removeCount ) ); #if B2_SNOOP_TABLE_COUNTERS extern b2AtomicInt b2_probeCount; b2AtomicStoreInt( &b2_probeCount, 0 ); #endif // Test key search // ~5ns per search on an AMD 7950x uint64_t ticks = b2GetTicks(); k = 0; for ( int i = 0; i < N; ++i ) { for ( int j = i + 1; j < N; ++j ) { uint64_t key = B2_SHAPE_PAIR_KEY( j, i ); bool found = b2ContainsKey( &set, key ); ENSURE( found || removed[k] ); k += 1; } } // uint64_t ticks = b2GetTicks(&timer); // printf("set ticks = %llu\n", ticks); float ms = b2GetMilliseconds( ticks ); printf( "set: count = %d, b2ContainsKey = %.5f ms, ave = %.5f us\n", itemCount, ms, 1000.0f * ms / itemCount ); #if B2_SNOOP_TABLE_COUNTERS int probeCount = b2AtomicLoadInt( &b2_probeCount ); float aveProbeCount = (float)probeCount / (float)itemCount; printf( "item count = %d, probe count = %d, ave probe count %.2f\n", itemCount, probeCount, aveProbeCount ); #endif // Remove all keys from set for ( int i = 0; i < N; ++i ) { for ( int j = i + 1; j < N; ++j ) { uint64_t key = B2_SHAPE_PAIR_KEY( i, j ); b2RemoveKey( &set, key ); } } ENSURE( b2GetSetCount( &set ) == 0 ); b2DestroySet( &set ); } return 0; } int TableTest( void ) { // Test helper functions first int power = b2BoundingPowerOf2( 3008 ); ENSURE( power == 12 ); int nextPowerOf2 = b2RoundUpPowerOf2( 3008 ); ENSURE( nextPowerOf2 == ( 1 << power ) ); // Run all hash set tests RUN_SUBTEST( BasicHashSetTest ); RUN_SUBTEST( HashSetCapacityTest ); RUN_SUBTEST( HashSetAddRemoveTest ); RUN_SUBTEST( HashSetClearTest ); RUN_SUBTEST( HashSetGrowthTest ); RUN_SUBTEST( HashSetEdgeCasesTest ); RUN_SUBTEST( HashSetRemovalReorganizationTest ); RUN_SUBTEST( HashSetStressTest ); RUN_SUBTEST( HashSetShapePairKeyTest ); RUN_SUBTEST( HashSetBytesTest ); RUN_SUBTEST( HashSetTest ); return 0; } ================================================ FILE: test/test_world.c ================================================ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #include "constants.h" #include "core.h" #include "test_macros.h" #include "box2d/box2d.h" #include "box2d/collision.h" #include "box2d/math_functions.h" #include // This is a simple example of building and running a simulation // using Box2D. Here we create a large ground box and a small dynamic // box. // There are no graphics for this example. Box2D is meant to be used // with your rendering engine in your game engine. int HelloWorld( void ) { // Construct a world object, which will hold and simulate the rigid bodies. b2WorldDef worldDef = b2DefaultWorldDef(); worldDef.gravity = ( b2Vec2 ){ 0.0f, -10.0f }; b2WorldId worldId = b2CreateWorld( &worldDef ); ENSURE( b2World_IsValid( worldId ) ); // Define the ground body. b2BodyDef groundBodyDef = b2DefaultBodyDef(); groundBodyDef.position = ( b2Vec2 ){ 0.0f, -10.0f }; // Call the body factory which allocates memory for the ground body // from a pool and creates the ground box shape (also from a pool). // The body is also added to the world. b2BodyId groundId = b2CreateBody( worldId, &groundBodyDef ); ENSURE( b2Body_IsValid( groundId ) ); // Define the ground box shape. The extents are the half-widths of the box. b2Polygon groundBox = b2MakeBox( 50.0f, 10.0f ); // Add the box shape to the ground body. b2ShapeDef groundShapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( groundId, &groundShapeDef, &groundBox ); // Define the dynamic body. We set its position and call the body factory. b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = ( b2Vec2 ){ 0.0f, 4.0f }; b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); // Define another box shape for our dynamic body. b2Polygon dynamicBox = b2MakeBox( 1.0f, 1.0f ); // Define the dynamic body shape b2ShapeDef shapeDef = b2DefaultShapeDef(); // Set the box density to be non-zero, so it will be dynamic. shapeDef.density = 1.0f; // Override the default friction. shapeDef.material.friction = 0.3f; // Add the shape to the body. b2CreatePolygonShape( bodyId, &shapeDef, &dynamicBox ); // Prepare for simulation. Typically we use a time step of 1/60 of a // second (60Hz) and 4 sub-steps. This provides a high quality simulation // in most game scenarios. float timeStep = 1.0f / 60.0f; int subStepCount = 4; b2Vec2 position = b2Body_GetPosition( bodyId ); b2Rot rotation = b2Body_GetRotation( bodyId ); // This is our little game loop. for ( int i = 0; i < 90; ++i ) { // Instruct the world to perform a single step of simulation. // It is generally best to keep the time step and iterations fixed. b2World_Step( worldId, timeStep, subStepCount ); // Now print the position and angle of the body. position = b2Body_GetPosition( bodyId ); rotation = b2Body_GetRotation( bodyId ); // printf("%4.2f %4.2f %4.2f\n", position.x, position.y, b2Rot_GetAngle(rotation)); } // When the world destructor is called, all bodies and joints are freed. This can // create orphaned ids, so be careful about your world management. b2DestroyWorld( worldId ); ENSURE( b2AbsFloat( position.x ) < 0.01f ); ENSURE( b2AbsFloat( position.y - 1.00f ) < 0.01f ); ENSURE( b2AbsFloat( b2Rot_GetAngle( rotation ) ) < 0.01f ); return 0; } int EmptyWorld( void ) { b2WorldDef worldDef = b2DefaultWorldDef(); b2WorldId worldId = b2CreateWorld( &worldDef ); ENSURE( b2World_IsValid( worldId ) == true ); float timeStep = 1.0f / 60.0f; int32_t subStepCount = 1; for ( int32_t i = 0; i < 60; ++i ) { b2World_Step( worldId, timeStep, subStepCount ); } b2DestroyWorld( worldId ); ENSURE( b2World_IsValid( worldId ) == false ); return 0; } #define BODY_COUNT 10 int DestroyAllBodiesWorld( void ) { b2WorldDef worldDef = b2DefaultWorldDef(); b2WorldId worldId = b2CreateWorld( &worldDef ); ENSURE( b2World_IsValid( worldId ) == true ); int count = 0; bool creating = true; b2BodyId bodyIds[BODY_COUNT]; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2Polygon square = b2MakeSquare( 0.5f ); for ( int32_t i = 0; i < 2 * BODY_COUNT + 10; ++i ) { if ( creating ) { if ( count < BODY_COUNT ) { bodyIds[count] = b2CreateBody( worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2CreatePolygonShape( bodyIds[count], &shapeDef, &square ); count += 1; } else { creating = false; } } else if ( count > 0 ) { b2DestroyBody( bodyIds[count - 1] ); bodyIds[count - 1] = b2_nullBodyId; count -= 1; } b2World_Step( worldId, 1.0f / 60.0f, 3 ); } b2Counters counters = b2World_GetCounters( worldId ); ENSURE( counters.bodyCount == 0 ); b2DestroyWorld( worldId ); ENSURE( b2World_IsValid( worldId ) == false ); return 0; } static int TestIsValid( void ) { b2WorldDef worldDef = b2DefaultWorldDef(); b2WorldId worldId = b2CreateWorld( &worldDef ); ENSURE( b2World_IsValid( worldId ) ); b2BodyDef bodyDef = b2DefaultBodyDef(); b2BodyId bodyId1 = b2CreateBody( worldId, &bodyDef ); ENSURE( b2Body_IsValid( bodyId1 ) == true ); b2BodyId bodyId2 = b2CreateBody( worldId, &bodyDef ); ENSURE( b2Body_IsValid( bodyId2 ) == true ); b2DestroyBody( bodyId1 ); ENSURE( b2Body_IsValid( bodyId1 ) == false ); b2DestroyBody( bodyId2 ); ENSURE( b2Body_IsValid( bodyId2 ) == false ); b2DestroyWorld( worldId ); ENSURE( b2World_IsValid( worldId ) == false ); ENSURE( b2Body_IsValid( bodyId2 ) == false ); ENSURE( b2Body_IsValid( bodyId1 ) == false ); return 0; } #define WORLD_COUNT ( B2_MAX_WORLDS / 2 ) int TestWorldRecycle( void ) { _Static_assert( WORLD_COUNT > 0, "world count" ); int count = 100; b2WorldId worldIds[WORLD_COUNT]; for ( int i = 0; i < count; ++i ) { b2WorldDef worldDef = b2DefaultWorldDef(); for ( int j = 0; j < WORLD_COUNT; ++j ) { worldIds[j] = b2CreateWorld( &worldDef ); ENSURE( b2World_IsValid( worldIds[j] ) == true ); b2BodyDef bodyDef = b2DefaultBodyDef(); b2CreateBody( worldIds[j], &bodyDef ); } for ( int j = 0; j < WORLD_COUNT; ++j ) { float timeStep = 1.0f / 60.0f; int subStepCount = 1; for ( int k = 0; k < 10; ++k ) { b2World_Step( worldIds[j], timeStep, subStepCount ); } } for ( int j = WORLD_COUNT - 1; j >= 0; --j ) { b2DestroyWorld( worldIds[j] ); ENSURE( b2World_IsValid( worldIds[j] ) == false ); worldIds[j] = b2_nullWorldId; } } return 0; } static bool CustomFilter( b2ShapeId shapeIdA, b2ShapeId shapeIdB, void* context ) { (void)shapeIdA; (void)shapeIdB; ENSURE( context == NULL ); return true; } static bool PreSolveStatic( b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Vec2 point, b2Vec2 normal, void* context ) { (void)shapeIdA; (void)shapeIdB; (void)point; (void)normal; ENSURE( context == NULL ); return false; } // This test is here to ensure all API functions link correctly. int TestWorldCoverage( void ) { b2WorldDef worldDef = b2DefaultWorldDef(); b2WorldId worldId = b2CreateWorld( &worldDef ); ENSURE( b2World_IsValid( worldId ) ); b2World_EnableSleeping( worldId, true ); b2World_EnableSleeping( worldId, false ); bool flag = b2World_IsSleepingEnabled( worldId ); ENSURE( flag == false ); b2World_EnableContinuous( worldId, false ); b2World_EnableContinuous( worldId, true ); flag = b2World_IsContinuousEnabled( worldId ); ENSURE( flag == true ); b2World_SetRestitutionThreshold( worldId, 0.0f ); b2World_SetRestitutionThreshold( worldId, 2.0f ); float value = b2World_GetRestitutionThreshold( worldId ); ENSURE( value == 2.0f ); b2World_SetHitEventThreshold( worldId, 0.0f ); b2World_SetHitEventThreshold( worldId, 100.0f ); value = b2World_GetHitEventThreshold( worldId ); ENSURE( value == 100.0f ); b2World_SetCustomFilterCallback( worldId, CustomFilter, NULL ); b2World_SetPreSolveCallback( worldId, PreSolveStatic, NULL ); b2Vec2 g = { 1.0f, 2.0f }; b2World_SetGravity( worldId, g ); b2Vec2 v = b2World_GetGravity( worldId ); ENSURE( v.x == g.x ); ENSURE( v.y == g.y ); b2ExplosionDef explosionDef = b2DefaultExplosionDef(); b2World_Explode( worldId, &explosionDef ); b2World_SetContactTuning( worldId, 10.0f, 2.0f, 4.0f ); b2World_SetMaximumLinearSpeed( worldId, 10.0f ); value = b2World_GetMaximumLinearSpeed( worldId ); ENSURE( value == 10.0f ); b2World_EnableWarmStarting( worldId, true ); flag = b2World_IsWarmStartingEnabled( worldId ); ENSURE( flag == true ); int count = b2World_GetAwakeBodyCount( worldId ); ENSURE( count == 0 ); b2World_SetUserData( worldId, &value ); void* userData = b2World_GetUserData( worldId ); ENSURE( userData == &value ); b2World_Step( worldId, 1.0f, 1 ); b2DestroyWorld( worldId ); return 0; } static int TestSensor( void ) { b2WorldDef worldDef = b2DefaultWorldDef(); b2WorldId worldId = b2CreateWorld( &worldDef ); // Wall from x = 1 to x = 2 b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_staticBody; bodyDef.position.x = 1.5f; bodyDef.position.y = 11.0f; b2BodyId wallId = b2CreateBody( worldId, &bodyDef ); b2Polygon box = b2MakeBox( 0.5f, 10.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.enableSensorEvents = true; b2CreatePolygonShape( wallId, &shapeDef, &box ); // Bullet fired towards the wall bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.isBullet = true; bodyDef.gravityScale = 0.0f; bodyDef.position = (b2Vec2){ 7.39814f, 4.0f }; bodyDef.linearVelocity = (b2Vec2){ -20.0f, 0.0f }; b2BodyId bulletId = b2CreateBody( worldId, &bodyDef ); shapeDef = b2DefaultShapeDef(); shapeDef.isSensor = true; shapeDef.enableSensorEvents = true; b2Circle circle = { { 0.0f, 0.0f }, 0.1f }; b2CreateCircleShape( bulletId, &shapeDef, &circle ); int beginCount = 0; int endCount = 0; while ( true ) { float timeStep = 1.0f / 60.0f; int subStepCount = 4; b2World_Step( worldId, timeStep, subStepCount ); b2Vec2 bulletPos = b2Body_GetPosition( bulletId ); //printf( "Bullet pos: %g %g\n", bulletPos.x, bulletPos.y ); b2SensorEvents events = b2World_GetSensorEvents( worldId ); if ( events.beginCount > 0 ) { beginCount += 1; } if ( events.endCount > 0 ) { endCount += 1; } if ( bulletPos.x < -1.0f ) { break; } } b2DestroyWorld( worldId ); ENSURE( beginCount == 1 ); ENSURE( endCount == 1 ); return 0; } int WorldTest( void ) { RUN_SUBTEST( HelloWorld ); RUN_SUBTEST( EmptyWorld ); RUN_SUBTEST( DestroyAllBodiesWorld ); RUN_SUBTEST( TestIsValid ); RUN_SUBTEST( TestWorldRecycle ); RUN_SUBTEST( TestWorldCoverage ); RUN_SUBTEST( TestSensor ); return 0; }