diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..f0cdb58 --- /dev/null +++ b/.clang-format @@ -0,0 +1,42 @@ +# Reference: https://clang.llvm.org/docs/ClangFormatStyleOptions.html +# /c/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/Llvm/bin +# 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: '^"(box3d\/)' + Priority: 2 + - Regex: '^<.*' + Priority: 3 + - Regex: '^".*' + Priority: 1 + +IndentExternBlock: NoIndent +IndentCaseLabels: true +IndentAccessModifiers: false +AccessModifierOffset: -4 + +SpacesInParens: Custom +SpacesInParensOptions: + ExceptDoubleParentheses: false + InConditionalStatements: true + InCStyleCasts: false + InEmptyParentheses: false + Other: true diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..a04f5fa --- /dev/null +++ b/.gitattributes @@ -0,0 +1,10 @@ +* text=auto + +*.c text +*.cpp text +*.h text +*.md text +*.txt text +*.sh text eol=lf + +*.ttf binary diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..b31f021 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,14 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +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'] + +github: [erincatto] diff --git a/.github/issue_template.md b/.github/issue_template.md new file mode 100644 index 0000000..abbe499 --- /dev/null +++ b/.github/issue_template.md @@ -0,0 +1 @@ +Thank you for filing an issue! diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..9fdfc2c --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1 @@ +Pull requests for Box3D code are not accepted. Please consider filing an issue instead. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..05a89a6 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,119 @@ +# https://docs.github.com/en/actions +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 + if: github.event_name == 'push' || github.event.pull_request.draft == false + timeout-minutes: 4 + steps: + - uses: actions/checkout@v4 + + - name: Configure CMake + run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX3D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON + + - name: Build + run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} + + - name: Test + working-directory: ${{github.workspace}}/build + run: ./bin/test + + build-ubuntu-clang: + name: ubuntu-clang + runs-on: ubuntu-latest + if: github.event_name == 'push' || github.event.pull_request.draft == false + timeout-minutes: 4 + steps: + - uses: actions/checkout@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-18 -DCMAKE_C_FLAGS="-fsanitize=thread -fno-omit-frame-pointer" -DCMAKE_CXX_FLAGS="-fsanitize=thread -fno-omit-frame-pointer" -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=thread" -DBOX3D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON + + - name: Build + run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} + + - name: Test + working-directory: ${{github.workspace}}/build + run: ./bin/test + + build-macos: + name: macos + runs-on: macos-latest + if: github.event_name == 'push' || github.event.pull_request.draft == false + timeout-minutes: 4 + steps: + - uses: actions/checkout@v4 + + - name: Configure CMake + run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX3D_SAMPLES=OFF -DBOX3D_SANITIZE=ON -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON + + - name: Build + run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} + + - name: Test + working-directory: ${{github.workspace}}/build + run: ./bin/test + + build-windows: + name: windows + runs-on: windows-latest + if: github.event_name == 'push' || github.event.pull_request.draft == false + timeout-minutes: 4 + steps: + - uses: actions/checkout@v3 + + - name: Configure CMake + run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX3D_SAMPLES=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON + + - name: Build + run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} + + - name: Test + working-directory: ${{github.workspace}}/build + run: ./bin/${{env.BUILD_TYPE}}/test + + samples-windows: + name: samples-windows + runs-on: windows-latest + if: github.event_name == 'push' || github.event.pull_request.draft == false + timeout-minutes: 6 + steps: + + - uses: actions/checkout@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 -DBOX3D_SAMPLES=ON -DBUILD_SHARED_LIBS=OFF -DBOX3D_UNIT_TESTS=OFF + + - name: Build + run: cmake --build ${{github.workspace}}/build --config Release + + samples-macos: + name: samples-macos + runs-on: macos-latest + if: github.event_name == 'push' || github.event.pull_request.draft == false + timeout-minutes: 6 + steps: + - uses: actions/checkout@v4 + + - name: Configure CMake + run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=Release -DBOX3D_SAMPLES=ON -DBUILD_SHARED_LIBS=OFF -DBOX3D_UNIT_TESTS=OFF + + - name: Build + run: cmake --build ${{github.workspace}}/build --config Release + \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..344933e --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +build/ +imgui.ini +settings.ini +.vscode/ +.vs/ +.cap +.DS_Store +CMakeUserPresets.json +.cache/ +.idea/ +.claude/ +.tmp/ +AGENTS.md +GEMINI.md diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..9fa66f2 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,155 @@ +cmake_minimum_required(VERSION 3.22) +include(FetchContent) +include(CMakeDependentOption) + +project(box3d + VERSION 0.1.0 + DESCRIPTION "A 3D 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 OR UNIX) + option(BOX3D_SANITIZE "Enable sanitizers for some builds" OFF) + set(BOX3D_SANITIZER_TYPE "address" CACHE STRING "Type of sanitizer to use (address, thread, undefined, memory)") + set_property(CACHE BOX3D_SANITIZER_TYPE PROPERTY STRINGS "address" "thread" "undefined" "memory") + + if(BOX3D_SANITIZE) + message(STATUS "Box3D Sanitize: ${BOX3D_SANITIZER_TYPE}") + # 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) + # more sanitizers on Apple clang + if(BOX3D_SANITIZER_TYPE STREQUAL "thread") + add_compile_options(-fsanitize=thread -fno-omit-frame-pointer) + add_link_options(-fsanitize=thread) + elseif(BOX3D_SANITIZER_TYPE STREQUAL "undefined") + add_compile_options(-fsanitize=undefined -fno-omit-frame-pointer) + add_link_options(-fsanitize=undefined) + else() + # default to address sanitizer + 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() + elseif(UNIX) + # Linux/WSL2 sanitizer support + if(BOX3D_SANITIZER_TYPE STREQUAL "thread") + # Disable ASLR first to avoid crash on launch + # echo 0 | sudo tee /proc/sys/kernel/randomize_va_space + add_compile_options(-fsanitize=thread -fno-omit-frame-pointer -fPIE) + add_link_options(-fsanitize=thread -pie) + elseif(BOX3D_SANITIZER_TYPE STREQUAL "undefined") + add_compile_options(-fsanitize=undefined -fno-omit-frame-pointer) + add_link_options(-fsanitize=undefined) + elseif(BOX3D_SANITIZER_TYPE STREQUAL "memory") + add_compile_options(-fsanitize=memory -fno-omit-frame-pointer) + add_link_options(-fsanitize=memory) + else() + # default to address sanitizer + add_compile_options(-fsanitize=address -fno-omit-frame-pointer) + add_link_options(-fsanitize=address) + endif() + endif() + else() + if(MSVC) + # 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(BOX3D_DISABLE_SIMD "Disable SIMD math (slower)" OFF) +option(BOX3D_COMPILE_WARNING_AS_ERROR "Compile warnings as errors" OFF) + +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 box3d via FetchContent +if(PROJECT_IS_TOP_LEVEL) + option(BOX3D_SAMPLES "Build the Box3D samples" ON) + option(BOX3D_BENCHMARKS "Build the Box3D benchmarks" OFF) + option(BOX3D_DOCS "Build the Box3D documentation" OFF) + option(BOX3D_PROFILE "Enable profiling with Tracy" OFF) + option(BOX3D_VALIDATE "Enable heavy validation" ON) + option(BOX3D_UNIT_TESTS "Build the Box3D unit tests" ON) + + if(BOX3D_UNIT_TESTS OR BOX3D_SAMPLES OR BOX3D_BENCHMARKS) + + # Emscripten pthread support + 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() + + add_subdirectory(shared) + endif() + + # Tests need static linkage because they test internal Box3D functions + if(NOT BUILD_SHARED_LIBS AND BOX3D_UNIT_TESTS) + message(STATUS "Adding Box3D unit tests") + add_subdirectory(test) + set_target_properties(test PROPERTIES XCODE_GENERATE_SCHEME TRUE) + else() + message(STATUS "Skipping Box3D unit tests") + endif() + + if(BOX3D_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() + + set_target_properties(samples PROPERTIES + XCODE_GENERATE_SCHEME TRUE + XCODE_SCHEME_WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + endif() + + if(BOX3D_BENCHMARKS) + add_subdirectory(benchmark) + set_target_properties(benchmark PROPERTIES XCODE_GENERATE_SCHEME TRUE) + endif() + + if(BOX3D_DOCS) + # todo + # add_subdirectory(docs) + endif() +endif() + +# https://stackoverflow.com/questions/72635402/how-to-set-working-directory-in-cmake-visual-studio-2022 +# launch.vs.json +# "currentDir": "${workspaceRoot}" \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..62bbc3c --- /dev/null +++ b/README.md @@ -0,0 +1,98 @@ +![Box3D Logo](https://box2d.org/images/logo.svg) + +# Build Status +[![Build Status](https://github.com/erincatto/box3d/actions/workflows/build.yml/badge.svg)](https://github.com/erincatto/box3d/actions) + +# Box3D +Box3D is a 3D physics engine for games. + +[![Box3D 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 +- Graphical user interface with imgui +- Many samples to demonstrate features and performance + +## Building All Platforms +- Install [CMake](https://cmake.org/) +- Install [git](https://git-scm.com/) +- Ensure these run from the command line + +## Building for Visual Studio +- Install [Visual Studio](https://visualstudio.microsoft.com/) +- Run `build_vs2026.bat` +- Open and build `build/box3d.slnx` + +## Building for Linux +- Run `build.sh` from a bash shell +- Results are in the build sub-folder + +## Building for Xcode +- mkdir build +- cd build +- cmake -G Xcode .. +- Open `box3d.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 Box3D library and samples build and run on Windows, Linux, and Mac. + +You will need a compiler that supports C17 to build the Box3D library. + +You will need a compiler that supports C++20 to build the samples. + +Box3D uses SSE2 and Neon SIMD math to improve performance. This can be disabled by defining `BOX3D_DISABLE_SIMD`. + +## Documentation +- [Manual](https://box2d.org/documentation/) + +## 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/box3d/discussions). + +## License +Box3D is developed by Erin Catto and uses the [MIT license](https://en.wikipedia.org/wiki/MIT_License). + +## Sponsorship +Support development of Box3D 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). diff --git a/benchmark/CMakeLists.txt b/benchmark/CMakeLists.txt new file mode 100644 index 0000000..73f7210 --- /dev/null +++ b/benchmark/CMakeLists.txt @@ -0,0 +1,13 @@ +# Benchmark app + +set(BOX3D_BENCHMARK_FILES + main.c +) + +add_executable(benchmark ${BOX3D_BENCHMARK_FILES}) + +set_target_properties(benchmark PROPERTIES C_STANDARD 17) + +target_link_libraries(benchmark PRIVATE box3d shared) + +source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} PREFIX "" FILES ${BOX3D_BENCHMARK_FILES}) \ No newline at end of file diff --git a/benchmark/amd7950x_scalar/washer.csv b/benchmark/amd7950x_scalar/washer.csv new file mode 100644 index 0000000..83bc876 --- /dev/null +++ b/benchmark/amd7950x_scalar/washer.csv @@ -0,0 +1,9 @@ +threads,ms +1,0 +2,0 +3,0 +4,0 +5,0 +6,0 +7,0 +8,5488.14 diff --git a/benchmark/amd7950x_sse2/compound_capsules.csv b/benchmark/amd7950x_sse2/compound_capsules.csv new file mode 100644 index 0000000..e0179bc --- /dev/null +++ b/benchmark/amd7950x_sse2/compound_capsules.csv @@ -0,0 +1,9 @@ +threads,ms +1,730.575 +2,424.323 +3,324.045 +4,276.202 +5,242.944 +6,226.599 +7,211.694 +8,205.856 diff --git a/benchmark/amd7950x_sse2/compound_hulls.csv b/benchmark/amd7950x_sse2/compound_hulls.csv new file mode 100644 index 0000000..2854909 --- /dev/null +++ b/benchmark/amd7950x_sse2/compound_hulls.csv @@ -0,0 +1,9 @@ +threads,ms +1,462.769 +2,292.812 +3,230.578 +4,197.733 +5,178.241 +6,166.567 +7,161.298 +8,157.091 diff --git a/benchmark/amd7950x_sse2/joint_grid.csv b/benchmark/amd7950x_sse2/joint_grid.csv new file mode 100644 index 0000000..898d654 --- /dev/null +++ b/benchmark/amd7950x_sse2/joint_grid.csv @@ -0,0 +1,9 @@ +threads,ms +1,1796.4 +2,954.375 +3,641.176 +4,481.819 +5,390.785 +6,328.059 +7,287.637 +8,258.124 diff --git a/benchmark/amd7950x_sse2/junkyard.csv b/benchmark/amd7950x_sse2/junkyard.csv new file mode 100644 index 0000000..50a6450 --- /dev/null +++ b/benchmark/amd7950x_sse2/junkyard.csv @@ -0,0 +1,9 @@ +threads,ms +1,24717.7 +2,13513.9 +3,9716.35 +4,7493.39 +5,6140.22 +6,5221.34 +7,4550.24 +8,4106.65 diff --git a/benchmark/amd7950x_sse2/large_pyramid.csv b/benchmark/amd7950x_sse2/large_pyramid.csv new file mode 100644 index 0000000..852f52b --- /dev/null +++ b/benchmark/amd7950x_sse2/large_pyramid.csv @@ -0,0 +1,9 @@ +threads,ms +1,1682.1 +2,878.51 +3,613.252 +4,478.075 +5,387.426 +6,337.026 +7,294.737 +8,270.737 diff --git a/benchmark/amd7950x_sse2/many_pyramids.csv b/benchmark/amd7950x_sse2/many_pyramids.csv new file mode 100644 index 0000000..cdbba91 --- /dev/null +++ b/benchmark/amd7950x_sse2/many_pyramids.csv @@ -0,0 +1,9 @@ +threads,ms +1,2575.34 +2,1278.03 +3,878.515 +4,629.084 +5,507.933 +6,413.473 +7,362.456 +8,320.241 diff --git a/benchmark/amd7950x_sse2/rain.csv b/benchmark/amd7950x_sse2/rain.csv new file mode 100644 index 0000000..ec9581b --- /dev/null +++ b/benchmark/amd7950x_sse2/rain.csv @@ -0,0 +1,9 @@ +threads,ms +1,2627.76 +2,1427.39 +3,1012.48 +4,796.119 +5,664.231 +6,577.576 +7,518.164 +8,483.436 diff --git a/benchmark/amd7950x_sse2/washer.csv b/benchmark/amd7950x_sse2/washer.csv new file mode 100644 index 0000000..e1caa96 --- /dev/null +++ b/benchmark/amd7950x_sse2/washer.csv @@ -0,0 +1,9 @@ +threads,ms +1,31480.4 +2,17010.7 +3,11890.1 +4,9295.49 +5,7696.31 +6,6645.53 +7,5843.28 +8,5249.02 diff --git a/benchmark/amd7950x_sse2/welded_hulls.csv b/benchmark/amd7950x_sse2/welded_hulls.csv new file mode 100644 index 0000000..3b28fcd --- /dev/null +++ b/benchmark/amd7950x_sse2/welded_hulls.csv @@ -0,0 +1,9 @@ +threads,ms +1,726.988 +2,430.503 +3,324.672 +4,268.082 +5,232.24 +6,213.849 +7,199.971 +8,193.328 diff --git a/benchmark/main.c b/benchmark/main.c new file mode 100644 index 0000000..1fc8fd8 --- /dev/null +++ b/benchmark/main.c @@ -0,0 +1,344 @@ +// 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 "benchmarks.h" +#include "utils.h" + +#include "box3d/box3d.h" +#include "box3d/constants.h" +#include "box3d/math_functions.h" + +#include +#include +#include +#include +#include + +#ifdef TRACY_ENABLE +#include +#endif + +#define ARRAY_COUNT( A ) (int)( sizeof( A ) / sizeof( A[0] ) ) +#define MAYBE_UNUSED( x ) ( (void)( x ) ) + +typedef void CapacityFcn( b3Capacity* capacity ); +typedef void CreateFcn( b3WorldId worldId ); +typedef void DestroyFcn( void ); +typedef void StepFcn( b3WorldId worldId, int stepCount ); + +typedef struct Benchmark +{ + const char* name; + CapacityFcn* capacityFcn; + CreateFcn* createFcn; + DestroyFcn* destroyFcn; + StepFcn* stepFcn; + int totalStepCount; +} Benchmark; + +static void MinProfile( b3Profile* p1, const b3Profile* p2 ) +{ + p1->step = b3MinFloat( p1->step, p2->step ); + p1->pairs = b3MinFloat( p1->pairs, p2->pairs ); + p1->collide = b3MinFloat( p1->collide, p2->collide ); + p1->constraints = b3MinFloat( p1->constraints, p2->constraints ); + p1->transforms = b3MinFloat( p1->transforms, p2->transforms ); + p1->refit = b3MinFloat( p1->refit, p2->refit ); + p1->sleepIslands = b3MinFloat( p1->sleepIslands, p2->sleepIslands ); +} + +// Box3D 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 + +// start /affinity 0x5555 .\build\bin\Release\benchmark.exe -t=4 -w=4 -b=5 -r=5 + +// 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 + +// 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 ) +{ +#ifdef TRACY_ENABLE + ___tracy_startup_profiler(); +#endif + + Benchmark benchmarks[] = { + { "compound_capsules", NULL, CreateCompoundCapsules, DestroyCompoundCapsules, NULL, 500 }, + { "compound_hulls", NULL, CreateCompoundHulls, DestroyCompoundHulls, NULL, 500 }, + { "joint_grid", NULL, CreateJointGrid, NULL, NULL, 100 }, + { "junkyard", NULL, CreateJunkyard, NULL, StepJunkyard, 500 }, + { "large_pyramid", NULL, CreateLargePyramid, NULL, NULL, 200 }, + { "many_pyramids", NULL, CreateManyPyramids, NULL, NULL, 100 }, + { "rain", GetRainCapacity, CreateRain, DestroyRain, StepRain, 400 }, + { "washer", GetWasherCapacity, CreateWasher, NULL, NULL, 1000 }, + { "welded_hulls", NULL, CreateWeldedHulls, DestroyWeldedHulls, NULL, 500 }, + //{ "smash", CreateSmash, NULL, 300 }, + //{ "spinner", CreateSpinner, StepSpinner, 1400 }, + //{ "tumbler", CreateTumbler, NULL, 750 }, + }; + + int benchmarkCount = ARRAY_COUNT( benchmarks ); + + int maxSteps = benchmarks[0].totalStepCount; + for ( int i = 1; i < benchmarkCount; ++i ) + { + maxSteps = b3MaxInt( maxSteps, benchmarks[i].totalStepCount ); + } + + b3Profile maxProfile = { + .step = FLT_MAX, + .pairs = FLT_MAX, + .collide = FLT_MAX, + .solve = FLT_MAX, + .solverSetup = FLT_MAX, + .constraints = 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, + }; + + b3Profile* profiles = malloc( maxSteps * sizeof( b3Profile ) ); + for ( int i = 0; i < maxSteps; ++i ) + { + profiles[i] = maxProfile; + } + + int maxThreadCount = GetNumberOfCores(); + int runCount = 4; + int singleBenchmark = -1; + int singleWorkerCount = -1; + b3Counters counters = { 0 }; + bool enableContinuous = true; + bool recordStepTimes = false; + + assert( maxThreadCount <= B3_MAX_WORKERS ); + + for ( int i = 1; i < argc; ++i ) + { + const char* arg = argv[i]; + if ( strncmp( arg, "-t=", 3 ) == 0 ) + { + int threadCount = atoi( arg + 3 ); + maxThreadCount = b3ClampInt( threadCount, 1, maxThreadCount ); + } + else if ( strncmp( arg, "-b=", 3 ) == 0 ) + { + singleBenchmark = atoi( arg + 3 ); + singleBenchmark = b3ClampInt( singleBenchmark, 0, benchmarkCount - 1 ); + } + else if ( strncmp( arg, "-w=", 3 ) == 0 ) + { + singleWorkerCount = atoi( arg + 3 ); + } + else if ( strncmp( arg, "-r=", 3 ) == 0 ) + { + runCount = b3ClampInt( 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 = b3ClampInt( singleWorkerCount, 1, maxThreadCount ); + } + + printf( "Starting 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[B3_MAX_WORKERS] = { 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 ) + { + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.enableContinuous = enableContinuous; + worldDef.workerCount = threadCount; + + if (benchmark->capacityFcn != NULL) + { + benchmark->capacityFcn( &worldDef.capacity ); + } + + b3WorldId worldId = b3CreateWorld( &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 ) + { + benchmark->stepFcn( worldId, 0 ); + } + + assert( stepCount <= maxSteps ); + + b3World_Step( worldId, timeStep, subStepCount ); +\ + b3Profile profile = b3World_GetProfile( worldId ); + MinProfile( profiles + 0, &profile ); + + uint64_t ticks = b3GetTicks(); + + for ( int stepIndex = 1; stepIndex < stepCount; ++stepIndex ) + { + if ( benchmark->stepFcn != NULL ) + { + benchmark->stepFcn( worldId, stepIndex ); + } + + b3World_Step( worldId, timeStep, subStepCount ); +\ + profile = b3World_GetProfile( worldId ); + MinProfile( profiles + stepIndex, &profile ); + } + + float ms = b3GetMilliseconds( ticks ); + printf( "run %d : %g (ms)\n", runIndex, ms ); + + if ( runIndex == 0 ) + { + minTime[threadCount - 1] = ms; + } + else + { + minTime[threadCount - 1] = b3MinFloat( minTime[threadCount - 1], ms ); + } + + if ( countersAcquired == false ) + { + counters = b3World_GetCounters( worldId ); + countersAcquired = true; + } + + if ( benchmark->destroyFcn != NULL ) + { + benchmark->destroyFcn(); + } + + b3DestroyWorld( worldId ); + } + + 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 ) + { + b3Profile p = profiles[stepIndex]; + fprintf( file, "%g %g %g %g %g %g %g\n", p.step, p.pairs, p.collide, p.constraints, 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 benchmarks complete!\n" ); + + free( profiles ); + +#ifdef TRACY_ENABLE + ___tracy_shutdown_profiler(); +#endif + + return 0; +} diff --git a/build.sh b/build.sh new file mode 100644 index 0000000..e678e44 --- /dev/null +++ b/build.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash + +# Use this to build Box3D on any system with a bash shell +rm -rf build + +# I haven't been able to get Wayland working on WSL but X11 works. +# https://www.glfw.org/docs/latest/compile.html +cmake -S . -B build -DGLFW_BUILD_WAYLAND=OFF +cmake --build build diff --git a/build_vs2026.bat b/build_vs2026.bat new file mode 100644 index 0000000..bc38e44 --- /dev/null +++ b/build_vs2026.bat @@ -0,0 +1,24 @@ +@echo off +rem Use this batch file to generate Visual Studio 2026 project files for box3d. +rem +rem Usage: +rem build_vs2026.bat Configure or update project files in build\ +rem build_vs2026.bat fresh Delete build\ first, then configure from scratch +rem +rem Re-running without "fresh" updates the existing project files in place. +rem CMake rewrites .vcxproj/.sln files atomically, so this works even while +rem Visual Studio has the solution open -- VS will detect the change and +rem prompt to reload. + +if /i "%~1"=="fresh" ( + if exist build ( + echo Fresh build requested, removing build\ ... + rmdir /s /q build + if exist build ( + echo ERROR: failed to remove build\ -- is something holding files open? + exit /b 1 + ) + ) +) + +cmake -S . -B build -G "Visual Studio 18 2026" diff --git a/data/dumps/single_box/box3d_dump.inl b/data/dumps/single_box/box3d_dump.inl new file mode 100644 index 0000000..f60be18 --- /dev/null +++ b/data/dumps/single_box/box3d_dump.inl @@ -0,0 +1,85 @@ +b3Vec3 gravity = {0, -10, 0}; +b3World_SetGravity(m_worldId, gravity); +std::vector bodies; +std::vector joints; + +{ + b3BodyDef bd = b3DefaultBodyDef(); + bd.name = "cube"; + bd.type = b3BodyType(2); + bd.position = {-7.98573353e-07, 0.499929696, -9.86034479e-07}; + bd.rotation = {{-4.03613463e-08, 0.825855613, 4.68083634e-08}, 0.563881755}; + bd.linearVelocity = {2.47239775e-08, -1.7695136e-08, 8.65693384e-09}; + bd.angularVelocity = {1.73163173e-08, -4.2026933e-15, -4.94549042e-08}; + bd.linearDamping = 0; + bd.angularDamping = 0; + bd.enableSleep = bool(1); + bd.isAwake = bool(1); + bd.gravityScale = 1; + b3BodyId bodyId = b3CreateBody(m_worldId, &bd); + bodies.push_back(bodyId); + + { + b3ShapeDef sd = b3DefaultShapeDef(); + sd.density = 1000; + sd.isSensor = bool(0); + sd.filter.categoryBits = 0x1; + sd.filter.maskBits = 0xffffffffffffffff; + sd.filter.groupIndex = 0; + sd.baseMaterial.friction = 0.600000024; + sd.baseMaterial.restitution = 0; + sd.baseMaterial.rollingResistance = 0; + b3Vec3 vs[8]; + vs[0] = {0.5, 0.5, 0.5}; + vs[1] = {-0.5, 0.5, 0.5}; + vs[2] = {-0.5, -0.5, 0.5}; + vs[3] = {0.5, -0.5, 0.5}; + vs[4] = {0.5, 0.5, -0.5}; + vs[5] = {-0.5, 0.5, -0.5}; + vs[6] = {-0.5, -0.5, -0.5}; + vs[7] = {0.5, -0.5, -0.5}; + b3Hull* hull = b3CreateHull(vs, 8, 8); + b3CreateHullShape(bodyId, &sd, hull); + b3DestroyHull(hull); + } +} +{ + b3BodyDef bd = b3DefaultBodyDef(); + bd.name = "ground"; + bd.type = b3BodyType(0); + bd.position = {0, -1, 0}; + bd.rotation = {{0, 0, 0}, 1}; + bd.linearVelocity = {0, 0, 0}; + bd.angularVelocity = {0, 0, 0}; + bd.linearDamping = 0; + bd.angularDamping = 0; + bd.enableSleep = bool(1); + bd.isAwake = bool(0); + bd.gravityScale = 1; + b3BodyId bodyId = b3CreateBody(m_worldId, &bd); + bodies.push_back(bodyId); + + { + b3ShapeDef sd = b3DefaultShapeDef(); + sd.density = 1000; + sd.isSensor = bool(0); + sd.filter.categoryBits = 0x1; + sd.filter.maskBits = 0xffffffffffffffff; + sd.filter.groupIndex = 0; + sd.baseMaterial.friction = 0.600000024; + sd.baseMaterial.restitution = 0; + sd.baseMaterial.rollingResistance = 0; + b3Vec3 vs[8]; + vs[0] = {15, 1, 15}; + vs[1] = {-15, 1, 15}; + vs[2] = {-15, -1, 15}; + vs[3] = {15, -1, 15}; + vs[4] = {15, 1, -15}; + vs[5] = {-15, 1, -15}; + vs[6] = {-15, -1, -15}; + vs[7] = {15, -1, -15}; + b3Hull* hull = b3CreateHull(vs, 8, 8); + b3CreateHullShape(bodyId, &sd, hull); + b3DestroyHull(hull); + } +} diff --git a/data/fonts/Roboto-Medium.ttf b/data/fonts/Roboto-Medium.ttf new file mode 100644 index 0000000..e89b0b7 Binary files /dev/null and b/data/fonts/Roboto-Medium.ttf differ diff --git a/data/meshes/building.obj b/data/meshes/building.obj new file mode 100644 index 0000000..f107a27 --- /dev/null +++ b/data/meshes/building.obj @@ -0,0 +1,4971 @@ +# Blender 4.1.1 +# www.blender.org +o SM_Bld_House_01 +v -5.285142 5.730380 -1.352991 +v -5.285142 5.730380 -2.515749 +v -5.285142 5.019040 -1.339708 +v -5.285142 5.019040 -2.529024 +v -5.123500 3.995276 -1.352991 +v -5.285142 3.995276 -1.352991 +v -5.285142 3.995276 -2.515748 +v -5.123500 3.995276 -2.515748 +v -5.123500 3.826025 -1.323716 +v -5.123500 3.826025 -2.545015 +v -5.319871 3.826025 -2.512529 +v -5.351707 3.826025 -1.323716 +v -5.351707 3.950457 -1.323716 +v -5.123500 3.975301 -1.323716 +v -5.351707 3.953848 -2.545015 +v -5.123500 3.975300 -2.545015 +v -5.154387 3.826025 -1.373278 +v -5.154387 3.826025 -2.495454 +v -5.303140 3.826025 -2.495454 +v -5.303140 3.826025 -1.373276 +v -5.156000 3.728936 -1.391389 +v -5.156000 3.728936 -2.477343 +v -5.301527 3.728936 -2.477341 +v -5.301527 3.728936 -1.391389 +v -5.285142 5.019040 -1.440996 +v -5.229968 5.019040 -2.427736 +v -5.285142 5.678292 -2.422853 +v -5.285142 5.664947 -1.452013 +v -5.285142 4.060710 -1.452013 +v -5.285142 4.048209 -2.416719 +v -5.139280 5.019040 -1.440996 +v -5.139280 5.019040 -2.427736 +v -5.139280 5.664947 -2.416719 +v -5.139280 5.664947 -1.452013 +v -5.139280 4.060710 -1.452013 +v -5.139280 4.060710 -2.416719 +v -5.103979 4.773667 -1.551377 +v -5.139280 5.019040 -2.317354 +v -5.139280 5.544402 -2.308809 +v -5.139280 5.544402 -1.559923 +v -5.139280 4.181253 -1.559923 +v -5.139280 4.181253 -2.308809 +v -5.139280 5.544402 -1.934367 +v -5.139280 4.181253 -1.934367 +v -5.011294 5.019040 -2.317354 +v -5.011294 5.544402 -2.308809 +v -5.011294 5.544402 -1.934365 +v -5.011294 4.181253 -2.308809 +v -5.011294 4.181253 -1.934365 +v -5.011294 4.771373 -1.551378 +v -5.011294 5.544402 -1.559923 +v -5.011294 4.181253 -1.559923 +v -5.011294 4.751149 -2.427736 +v -5.011294 5.664947 -2.416719 +v -5.011294 5.664947 -1.934365 +v -5.011294 4.060710 -2.416719 +v -5.011294 4.060710 -1.934365 +v -5.011294 5.019040 -1.440996 +v -5.011294 5.664947 -1.452013 +v -5.011271 4.065799 -1.457106 +v -4.901605 4.769232 -2.427736 +v -4.863695 5.664947 -2.416719 +v -4.863695 4.060710 -2.416719 +v -4.863695 5.019040 -1.440996 +v -4.864050 5.668319 -1.450332 +v -4.863695 4.060710 -1.452013 +v -4.863695 4.752041 -2.529023 +v -4.863695 5.730380 -2.515749 +v -4.863695 3.995276 -2.515748 +v -4.863695 5.019040 -1.339708 +v -4.863695 5.730380 -1.352991 +v -4.863695 4.043036 -1.425264 +v -5.285142 5.019040 -2.455548 +v -5.285142 5.209441 -2.427736 +v -5.285142 4.802351 -2.427736 +v -5.139280 4.889651 -1.551378 +v -5.139280 4.773667 -1.519784 +v -5.139280 4.609974 -1.551378 +v -5.351707 3.962600 -1.462144 +v -5.351707 3.975301 -1.947633 +v -5.326912 3.972971 -1.608400 +v -5.351707 3.931852 -1.726273 +v -5.351707 3.929867 -1.545801 +v -5.351707 3.888962 -2.545015 +v -5.351707 3.826025 -2.457139 +v -5.296060 3.826025 -2.545015 +v -4.863695 4.924029 -2.425088 +v -4.863695 4.769232 -2.456176 +v -4.863695 4.597419 -2.426073 +v -4.863695 3.995276 -1.437776 +v -4.892284 3.995276 -1.352991 +v -4.863695 4.117898 -1.352418 +v 0.686113 5.730380 -3.469511 +v 1.848871 5.730380 -3.469511 +v 0.672830 5.019040 -3.469511 +v 1.862146 5.019040 -3.469511 +v 0.686113 3.995276 -3.307868 +v 0.686113 3.995276 -3.469510 +v 1.848871 3.995276 -3.469510 +v 1.848871 3.995276 -3.307868 +v 0.656839 3.826025 -3.307868 +v 1.878137 3.826025 -3.307868 +v 1.845651 3.826025 -3.504239 +v 0.656839 3.826025 -3.536075 +v 0.656839 3.950457 -3.536075 +v 0.656839 3.975300 -3.307868 +v 1.878137 3.953848 -3.536075 +v 1.878137 3.975300 -3.307868 +v 0.706400 3.826025 -3.338756 +v 1.828577 3.826025 -3.338756 +v 1.828577 3.826025 -3.487509 +v 0.706400 3.826025 -3.487509 +v 0.724512 3.728936 -3.340369 +v 1.810464 3.728936 -3.340369 +v 1.810464 3.728936 -3.485895 +v 0.724512 3.728936 -3.485895 +v 0.774118 5.019040 -3.469511 +v 1.760858 5.019040 -3.414336 +v 1.755975 5.678292 -3.469511 +v 0.785135 5.664947 -3.469511 +v 0.785135 4.060710 -3.469510 +v 1.749841 4.048209 -3.469510 +v 0.774118 5.019040 -3.323649 +v 1.760858 5.019040 -3.323649 +v 1.749841 5.664947 -3.323649 +v 0.785135 5.664947 -3.323649 +v 0.785135 4.060710 -3.323649 +v 1.749841 4.060710 -3.323649 +v 0.884500 4.773667 -3.288346 +v 1.650476 5.019040 -3.323649 +v 1.641931 5.544402 -3.323649 +v 0.893045 5.544402 -3.323649 +v 0.893045 4.181253 -3.323649 +v 1.641931 4.181253 -3.323649 +v 1.267488 5.544402 -3.323649 +v 1.267488 4.181253 -3.323649 +v 1.650476 5.019040 -3.195663 +v 1.641931 5.544402 -3.195663 +v 1.267488 5.544402 -3.195663 +v 1.641931 4.181253 -3.195663 +v 1.267488 4.181253 -3.195663 +v 0.884500 4.771372 -3.195663 +v 0.893045 5.544402 -3.195663 +v 0.893045 4.181253 -3.195663 +v 1.760858 4.751149 -3.195663 +v 1.749841 5.664947 -3.195663 +v 1.267488 5.664947 -3.195663 +v 1.749841 4.060710 -3.195663 +v 1.267488 4.060710 -3.195663 +v 0.774118 5.019040 -3.195663 +v 0.785135 5.664947 -3.195663 +v 0.790228 4.065799 -3.195640 +v 1.760858 4.769232 -3.085974 +v 1.749841 5.664947 -3.048063 +v 1.749841 4.060710 -3.048063 +v 0.774118 5.019040 -3.048063 +v 0.783455 5.668319 -3.048419 +v 0.785135 4.060710 -3.048063 +v 1.862146 4.752041 -3.048063 +v 1.848871 5.730380 -3.048063 +v 1.848871 3.995276 -3.048063 +v 0.672830 5.019040 -3.048063 +v 0.686113 5.730380 -3.048063 +v 0.758386 4.043036 -3.048063 +v 1.788671 5.019040 -3.469511 +v 1.760858 5.209441 -3.469511 +v 1.760858 4.802351 -3.469510 +v 0.884500 4.889651 -3.323649 +v 0.852906 4.773667 -3.323649 +v 0.884500 4.609973 -3.323649 +v 0.795267 3.962600 -3.536075 +v 1.280756 3.975300 -3.536075 +v 0.941522 3.972971 -3.511281 +v 1.059396 3.931852 -3.536075 +v 0.878923 3.929867 -3.536075 +v 1.878137 3.888962 -3.536075 +v 1.790262 3.826025 -3.536075 +v 1.878137 3.826025 -3.480428 +v 1.758210 4.924029 -3.048063 +v 1.789297 4.769232 -3.048063 +v 1.759195 4.597419 -3.048063 +v 0.770898 3.995276 -3.048063 +v 0.686113 3.995276 -3.076653 +v 0.685541 4.117898 -3.048063 +v 5.285144 5.730380 -0.015740 +v 5.285144 5.730381 1.147018 +v 5.285144 5.019040 -0.029024 +v 5.285144 5.019040 1.160293 +v 5.123502 3.995276 -0.015740 +v 5.285144 3.995276 -0.015740 +v 5.285144 3.995276 1.147018 +v 5.123502 3.995276 1.147018 +v 5.123502 3.826026 -0.045013 +v 5.123502 3.826026 1.176284 +v 5.319873 3.826026 1.143798 +v 5.351709 3.826026 -0.045013 +v 5.351709 3.950458 -0.045013 +v 5.123502 3.975301 -0.045013 +v 5.351709 3.953849 1.176284 +v 5.123502 3.975301 1.176284 +v 5.154389 3.826026 0.004546 +v 5.154389 3.826026 1.126724 +v 5.303142 3.826026 1.126724 +v 5.303142 3.826026 0.004547 +v 5.156001 3.728936 0.022659 +v 5.156001 3.728936 1.108611 +v 5.301528 3.728936 1.108612 +v 5.301528 3.728936 0.022659 +v 5.285144 5.019040 0.072264 +v 5.229970 5.019040 1.059005 +v 5.285144 5.678292 1.054122 +v 5.285144 5.664947 0.083281 +v 5.285144 4.060711 0.083281 +v 5.285144 4.048209 1.047988 +v 5.139281 5.019040 0.072264 +v 5.139281 5.019040 1.059005 +v 5.139281 5.664947 1.047988 +v 5.139281 5.664947 0.083281 +v 5.139281 4.060711 0.083281 +v 5.139281 4.060711 1.047988 +v 5.103980 4.773667 0.182648 +v 5.139281 5.019040 0.948623 +v 5.139281 5.544402 0.940078 +v 5.139281 5.544402 0.191191 +v 5.139281 4.181253 0.191191 +v 5.139281 4.181253 0.940078 +v 5.139282 5.544402 0.565635 +v 5.139282 4.181253 0.565635 +v 5.011296 5.019040 0.948623 +v 5.011296 5.544402 0.940078 +v 5.011296 5.544402 0.565635 +v 5.011296 4.181253 0.940078 +v 5.011296 4.181253 0.565635 +v 5.011296 4.771373 0.182646 +v 5.011296 5.544402 0.191191 +v 5.011296 4.181253 0.191191 +v 5.011296 4.751149 1.059005 +v 5.011296 5.664947 1.047988 +v 5.011296 5.664947 0.565635 +v 5.011296 4.060711 1.047988 +v 5.011296 4.060711 0.565635 +v 5.011296 5.019040 0.072264 +v 5.011296 5.664947 0.083281 +v 5.011273 4.065800 0.088374 +v 4.901607 4.769233 1.059005 +v 4.863696 5.664947 1.047988 +v 4.863696 4.060711 1.047988 +v 4.863696 5.019040 0.072264 +v 4.864053 5.668319 0.081603 +v 4.863696 4.060711 0.083281 +v 4.863696 4.752042 1.160293 +v 4.863696 5.730380 1.147018 +v 4.863696 3.995276 1.147018 +v 4.863696 5.019040 -0.029024 +v 4.863696 5.730380 -0.015740 +v 4.863696 4.043036 0.056533 +v 5.285144 5.019040 1.086818 +v 5.285144 5.209442 1.059005 +v 5.285144 4.802351 1.059005 +v 5.139281 4.889651 0.182646 +v 5.139281 4.773667 0.151053 +v 5.139281 4.609974 0.182646 +v 5.351709 3.962600 0.093414 +v 5.351709 3.975301 0.578903 +v 5.326914 3.972971 0.239669 +v 5.351709 3.931852 0.357544 +v 5.351709 3.929867 0.177070 +v 5.351709 3.888963 1.176284 +v 5.351707 3.826026 1.088409 +v 5.296062 3.826026 1.176284 +v 4.863696 4.924029 1.056357 +v 4.863696 4.769233 1.087444 +v 4.863696 4.597419 1.057341 +v 4.863696 3.995276 0.069045 +v 4.892286 3.995276 -0.015741 +v 4.863696 4.117898 -0.016312 +v 5.285143 2.730381 2.484260 +v 5.285143 2.730381 3.647019 +v 5.285143 2.019040 2.470977 +v 5.285143 2.019040 3.660293 +v 5.123501 0.995276 2.484260 +v 5.285143 0.995276 2.484260 +v 5.285143 0.995276 3.647019 +v 5.123501 0.995276 3.647019 +v 5.123501 0.826026 2.454987 +v 5.123501 0.826026 3.676284 +v 5.319872 0.826026 3.643799 +v 5.351707 0.826026 2.454987 +v 5.351707 0.950458 2.454987 +v 5.123501 0.975301 2.454987 +v 5.351707 0.953849 3.676284 +v 5.123501 0.975301 3.676284 +v 5.154388 0.826026 2.504546 +v 5.154388 0.826026 3.626724 +v 5.303141 0.826026 3.626724 +v 5.303141 0.826026 2.504547 +v 5.156000 0.728936 2.522659 +v 5.156000 0.728936 3.608611 +v 5.301527 0.728936 3.608613 +v 5.301527 0.728936 2.522659 +v 5.285143 2.019040 2.572264 +v 5.229970 2.019040 3.559006 +v 5.285143 2.678293 3.554123 +v 5.285143 2.664947 2.583281 +v 5.285143 1.060711 2.583282 +v 5.285143 1.048209 3.547988 +v 5.139280 2.019040 2.572264 +v 5.139280 2.019040 3.559006 +v 5.139280 2.664947 3.547988 +v 5.139280 2.664947 2.583281 +v 5.139280 1.060711 2.583282 +v 5.139280 1.060711 3.547988 +v 5.103980 1.773667 2.682648 +v 5.139280 2.019040 3.448623 +v 5.139280 2.544403 3.440078 +v 5.139280 2.544403 2.691191 +v 5.139280 1.181254 2.691192 +v 5.139280 1.181254 3.440078 +v 5.139281 2.544403 3.065635 +v 5.139281 1.181254 3.065635 +v 5.011295 2.019040 3.448623 +v 5.011295 2.544403 3.440078 +v 5.011295 2.544403 3.065635 +v 5.011295 1.181254 3.440078 +v 5.011295 1.181254 3.065635 +v 5.011295 1.771373 2.682647 +v 5.011295 2.544403 2.691191 +v 5.011295 1.181254 2.691192 +v 5.011295 1.751149 3.559006 +v 5.011295 2.664947 3.547988 +v 5.011295 2.664947 3.065635 +v 5.011295 1.060711 3.547988 +v 5.011295 1.060711 3.065635 +v 5.011295 2.019040 2.572264 +v 5.011295 2.664947 2.583281 +v 5.011272 1.065800 2.588374 +v 4.901605 1.769233 3.559006 +v 4.863695 2.664947 3.547988 +v 4.863695 1.060711 3.547988 +v 4.863695 2.019040 2.572264 +v 4.864051 2.668319 2.581603 +v 4.863695 1.060711 2.583282 +v 4.863695 1.752042 3.660293 +v 4.863695 2.730381 3.647019 +v 4.863695 0.995276 3.647019 +v 4.863695 2.019040 2.470977 +v 4.863695 2.730381 2.484260 +v 4.863695 1.043036 2.556533 +v 5.285143 2.019040 3.586819 +v 5.285143 2.209442 3.559006 +v 5.285143 1.802351 3.559006 +v 5.139280 1.889651 2.682647 +v 5.139280 1.773667 2.651054 +v 5.139280 1.609974 2.682647 +v 5.351707 0.962600 2.593415 +v 5.351707 0.975301 3.078903 +v 5.326913 0.972971 2.739669 +v 5.351707 0.931853 2.857544 +v 5.351707 0.929867 2.677070 +v 5.351707 0.888963 3.676284 +v 5.351707 0.826026 3.588411 +v 5.296061 0.826026 3.676284 +v 4.863695 1.924029 3.556357 +v 4.863695 1.769233 3.587444 +v 4.863695 1.597420 3.557342 +v 4.863695 0.995276 2.569046 +v 4.892285 0.995276 2.484259 +v 4.863695 1.117898 2.483688 +v 4.331377 2.730381 4.600781 +v 3.168619 2.730381 4.600781 +v 4.344659 2.019041 4.600781 +v 3.155344 2.019041 4.600781 +v 4.331377 0.995276 4.439138 +v 4.331377 0.995276 4.600781 +v 3.168619 0.995276 4.600781 +v 3.168619 0.995276 4.439138 +v 4.360651 0.826026 4.439138 +v 3.139352 0.826026 4.439138 +v 3.171838 0.826026 4.635510 +v 4.360651 0.826026 4.667344 +v 4.360651 0.950458 4.667344 +v 4.360651 0.975301 4.439138 +v 3.139352 0.953849 4.667344 +v 3.139352 0.975301 4.439138 +v 4.311090 0.826026 4.470027 +v 3.188913 0.826026 4.470027 +v 3.188913 0.826026 4.618777 +v 4.311090 0.826026 4.618777 +v 4.292978 0.728936 4.471638 +v 3.207025 0.728936 4.471638 +v 3.207025 0.728936 4.617163 +v 4.292978 0.728936 4.617163 +v 4.243371 2.019041 4.600781 +v 3.256631 2.019041 4.545606 +v 3.261514 2.678293 4.600781 +v 4.232355 2.664947 4.600781 +v 4.232355 1.060711 4.600781 +v 3.267648 1.048209 4.600781 +v 4.243371 2.019041 4.454917 +v 3.256631 2.019041 4.454917 +v 3.267648 2.664947 4.454917 +v 4.232355 2.664947 4.454917 +v 4.232355 1.060711 4.454917 +v 3.267648 1.060711 4.454917 +v 4.132989 1.773668 4.419617 +v 3.367013 2.019041 4.454917 +v 3.375558 2.544403 4.454917 +v 4.124444 2.544403 4.454917 +v 4.124444 1.181254 4.454917 +v 3.375558 1.181254 4.454917 +v 3.750001 2.544403 4.454917 +v 3.750001 1.181254 4.454917 +v 3.367013 2.019041 4.326933 +v 3.375558 2.544403 4.326933 +v 3.750001 2.544403 4.326933 +v 3.375558 1.181254 4.326933 +v 3.750001 1.181254 4.326933 +v 4.132989 1.771373 4.326933 +v 4.124444 2.544403 4.326933 +v 4.124444 1.181254 4.326933 +v 3.256631 1.751149 4.326933 +v 3.267648 2.664947 4.326933 +v 3.750001 2.664947 4.326933 +v 3.267648 1.060711 4.326933 +v 3.750001 1.060711 4.326933 +v 4.243371 2.019041 4.326933 +v 4.232355 2.664947 4.326933 +v 4.227262 1.065800 4.326909 +v 3.256631 1.769233 4.217244 +v 3.267648 2.664947 4.179334 +v 3.267648 1.060711 4.179334 +v 4.243371 2.019041 4.179334 +v 4.234035 2.668319 4.179690 +v 4.232355 1.060711 4.179334 +v 3.155344 1.752042 4.179334 +v 3.168619 2.730381 4.179334 +v 3.168619 0.995276 4.179334 +v 4.344659 2.019041 4.179334 +v 4.331377 2.730381 4.179334 +v 4.259103 1.043036 4.179334 +v 3.228819 2.019041 4.600781 +v 3.256631 2.209442 4.600781 +v 3.256631 1.802351 4.600781 +v 4.132989 1.889652 4.454917 +v 4.164583 1.773668 4.454917 +v 4.132989 1.609974 4.454917 +v 4.222223 0.962600 4.667344 +v 3.736734 0.975301 4.667344 +v 4.075967 0.972971 4.642551 +v 3.958093 0.931853 4.667344 +v 4.138566 0.929867 4.667344 +v 3.139352 0.888963 4.667344 +v 3.227228 0.826026 4.667344 +v 3.139352 0.826026 4.611697 +v 3.259279 1.924030 4.179334 +v 3.228192 1.769233 4.179334 +v 3.258295 1.597420 4.179334 +v 4.246591 0.995276 4.179334 +v 4.331377 0.995276 4.207922 +v 4.331949 1.117898 4.179334 +v 4.331377 5.730381 4.600781 +v 3.168619 5.730381 4.600781 +v 4.344659 5.019040 4.600781 +v 3.155344 5.019040 4.600781 +v 4.331377 3.995276 4.439138 +v 4.331377 3.995276 4.600781 +v 3.168619 3.995276 4.600781 +v 3.168619 3.995276 4.439138 +v 4.360651 3.826026 4.439138 +v 3.139352 3.826026 4.439138 +v 3.171838 3.826026 4.635510 +v 4.360651 3.826026 4.667344 +v 4.360651 3.950458 4.667344 +v 4.360651 3.975301 4.439138 +v 3.139352 3.953849 4.667344 +v 3.139352 3.975301 4.439138 +v 4.311090 3.826026 4.470027 +v 3.188913 3.826026 4.470027 +v 3.188913 3.826026 4.618777 +v 4.311090 3.826026 4.618777 +v 4.292978 3.728936 4.471638 +v 3.207025 3.728936 4.471638 +v 3.207025 3.728936 4.617163 +v 4.292978 3.728936 4.617163 +v 4.243371 5.019040 4.600781 +v 3.256631 5.019040 4.545606 +v 3.261514 5.678292 4.600781 +v 4.232355 5.664947 4.600781 +v 4.232355 4.060711 4.600781 +v 3.267648 4.048209 4.600781 +v 4.243371 5.019040 4.454917 +v 3.256631 5.019040 4.454917 +v 3.267648 5.664947 4.454917 +v 4.232355 5.664947 4.454917 +v 4.232355 4.060711 4.454917 +v 3.267648 4.060711 4.454917 +v 4.132989 4.773667 4.419617 +v 3.367013 5.019040 4.454917 +v 3.375558 5.544403 4.454917 +v 4.124444 5.544403 4.454917 +v 4.124444 4.181253 4.454917 +v 3.375558 4.181253 4.454917 +v 3.750001 5.544403 4.454917 +v 3.750001 4.181253 4.454917 +v 3.367013 5.019040 4.326933 +v 3.375558 5.544403 4.326933 +v 3.750001 5.544403 4.326933 +v 3.375558 4.181253 4.326933 +v 3.750001 4.181253 4.326933 +v 4.132989 4.771373 4.326933 +v 4.124444 5.544403 4.326933 +v 4.124444 4.181253 4.326933 +v 3.256631 4.751149 4.326933 +v 3.267648 5.664947 4.326933 +v 3.750001 5.664947 4.326933 +v 3.267648 4.060711 4.326933 +v 3.750001 4.060711 4.326933 +v 4.243371 5.019040 4.326933 +v 4.232355 5.664947 4.326933 +v 4.227262 4.065800 4.326909 +v 3.256631 4.769233 4.217244 +v 3.267648 5.664947 4.179334 +v 3.267648 4.060711 4.179334 +v 4.243371 5.019040 4.179334 +v 4.234035 5.668319 4.179690 +v 4.232355 4.060711 4.179334 +v 3.155344 4.752042 4.179334 +v 3.168619 5.730381 4.179334 +v 3.168619 3.995276 4.179334 +v 4.344659 5.019040 4.179334 +v 4.331377 5.730381 4.179334 +v 4.259103 4.043036 4.179334 +v 3.228819 5.019040 4.600781 +v 3.256631 5.209442 4.600781 +v 3.256631 4.802351 4.600781 +v 4.132989 4.889651 4.454917 +v 4.164583 4.773667 4.454917 +v 4.132989 4.609974 4.454917 +v 4.222223 3.962600 4.667344 +v 3.736734 3.975301 4.667344 +v 4.075967 3.972971 4.642551 +v 3.958093 3.931853 4.667344 +v 4.138566 3.929867 4.667344 +v 3.139352 3.888963 4.667344 +v 3.227228 3.826026 4.667344 +v 3.139352 3.826026 4.611697 +v 3.259279 4.924029 4.179334 +v 3.228192 4.769233 4.179334 +v 3.258295 4.597420 4.179334 +v 4.246591 3.995276 4.179334 +v 4.331377 3.995276 4.207922 +v 4.331949 4.117898 4.179334 +v 1.831378 5.730381 4.600781 +v 0.668621 5.730381 4.600781 +v 1.844661 5.019040 4.600781 +v 0.655345 5.019040 4.600781 +v 1.831378 3.995276 4.439138 +v 1.831378 3.995276 4.600781 +v 0.668621 3.995276 4.600781 +v 0.668621 3.995276 4.439138 +v 1.860652 3.826026 4.439138 +v 0.639354 3.826026 4.439138 +v 0.671840 3.826026 4.635510 +v 1.860652 3.826026 4.667344 +v 1.860652 3.950458 4.667344 +v 1.860652 3.975301 4.439138 +v 0.639354 3.953849 4.667344 +v 0.639354 3.975301 4.439138 +v 1.811092 3.826026 4.470027 +v 0.688915 3.826026 4.470027 +v 0.688915 3.826026 4.618777 +v 1.811092 3.826026 4.618777 +v 1.792980 3.728936 4.471638 +v 0.707027 3.728936 4.471638 +v 0.707027 3.728936 4.617163 +v 1.792980 3.728936 4.617163 +v 1.743373 5.019040 4.600781 +v 0.756633 5.019040 4.545606 +v 0.761516 5.678292 4.600781 +v 1.732357 5.664947 4.600781 +v 1.732357 4.060711 4.600781 +v 0.767650 4.048209 4.600781 +v 1.743373 5.019040 4.454917 +v 0.756633 5.019040 4.454917 +v 0.767650 5.664947 4.454917 +v 1.732357 5.664947 4.454917 +v 1.732357 4.060711 4.454917 +v 0.767650 4.060711 4.454917 +v 1.632991 4.773667 4.419617 +v 0.867015 5.019040 4.454917 +v 0.875560 5.544403 4.454917 +v 1.624446 5.544403 4.454917 +v 1.624446 4.181253 4.454917 +v 0.875560 4.181253 4.454917 +v 1.250003 5.544403 4.454917 +v 1.250003 4.181253 4.454917 +v 0.867015 5.019040 4.326933 +v 0.875560 5.544403 4.326933 +v 1.250003 5.544403 4.326933 +v 0.875560 4.181253 4.326933 +v 1.250003 4.181253 4.326933 +v 1.632991 4.771373 4.326933 +v 1.624446 5.544403 4.326933 +v 1.624446 4.181253 4.326933 +v 0.756633 4.751149 4.326933 +v 0.767650 5.664947 4.326933 +v 1.250003 5.664947 4.326933 +v 0.767650 4.060711 4.326933 +v 1.250003 4.060711 4.326933 +v 1.743373 5.019040 4.326933 +v 1.732357 5.664947 4.326933 +v 1.727264 4.065800 4.326909 +v 0.756633 4.769233 4.217244 +v 0.767650 5.664947 4.179334 +v 0.767650 4.060711 4.179334 +v 1.743373 5.019040 4.179334 +v 1.734036 5.668319 4.179690 +v 1.732357 4.060711 4.179334 +v 0.655345 4.752042 4.179334 +v 0.668621 5.730381 4.179334 +v 0.668621 3.995276 4.179334 +v 1.844661 5.019040 4.179334 +v 1.831378 5.730381 4.179334 +v 1.759105 4.043036 4.179334 +v 0.728821 5.019040 4.600781 +v 0.756633 5.209442 4.600781 +v 0.756633 4.802351 4.600781 +v 1.632991 4.889651 4.454917 +v 1.664585 4.773667 4.454917 +v 1.632991 4.609974 4.454917 +v 1.722225 3.962600 4.667344 +v 1.236736 3.975301 4.667344 +v 1.575969 3.972971 4.642551 +v 1.458095 3.931853 4.667344 +v 1.638568 3.929867 4.667344 +v 0.639354 3.888963 4.667344 +v 0.727230 3.826026 4.667344 +v 0.639354 3.826026 4.611697 +v 0.759280 4.924029 4.179334 +v 0.728194 4.769233 4.179334 +v 0.758296 4.597420 4.179334 +v 1.746593 3.995276 4.179334 +v 1.831378 3.995276 4.207922 +v 1.831951 4.117898 4.179334 +v 1.831378 2.730381 4.600781 +v 0.668621 2.730381 4.600781 +v 1.844661 2.019041 4.600781 +v 0.655345 2.019041 4.600781 +v 1.831378 0.995276 4.439138 +v 1.831378 0.995276 4.600781 +v 0.668621 0.995276 4.600781 +v 0.668621 0.995276 4.439138 +v 1.860652 0.826026 4.439138 +v 0.639354 0.826026 4.439138 +v 0.671840 0.826026 4.635510 +v 1.860652 0.826026 4.667344 +v 1.860652 0.950458 4.667344 +v 1.860652 0.975301 4.439138 +v 0.639354 0.953849 4.667344 +v 0.639354 0.975301 4.439138 +v 1.811092 0.826026 4.470027 +v 0.688915 0.826026 4.470027 +v 0.688915 0.826026 4.618777 +v 1.811092 0.826026 4.618777 +v 1.792980 0.728936 4.471638 +v 0.707027 0.728936 4.471638 +v 0.707027 0.728936 4.617163 +v 1.792980 0.728936 4.617163 +v 1.743373 2.019041 4.600781 +v 0.756633 2.019041 4.545606 +v 0.761516 2.678293 4.600781 +v 1.732357 2.664947 4.600781 +v 1.732357 1.060711 4.600781 +v 0.767650 1.048209 4.600781 +v 1.743373 2.019041 4.454917 +v 0.756633 2.019041 4.454917 +v 0.767650 2.664947 4.454917 +v 1.732357 2.664947 4.454917 +v 1.732357 1.060711 4.454917 +v 0.767650 1.060711 4.454917 +v 1.632991 1.773668 4.419617 +v 0.867015 2.019041 4.454917 +v 0.875560 2.544403 4.454917 +v 1.624446 2.544403 4.454917 +v 1.624446 1.181254 4.454917 +v 0.875560 1.181254 4.454917 +v 1.250003 2.544403 4.454917 +v 1.250003 1.181254 4.454917 +v 0.867015 2.019041 4.326933 +v 0.875560 2.544403 4.326933 +v 1.250003 2.544403 4.326933 +v 0.875560 1.181254 4.326933 +v 1.250003 1.181254 4.326933 +v 1.632991 1.771373 4.326933 +v 1.624446 2.544403 4.326933 +v 1.624446 1.181254 4.326933 +v 0.756633 1.751149 4.326933 +v 0.767650 2.664947 4.326933 +v 1.250003 2.664947 4.326933 +v 0.767650 1.060711 4.326933 +v 1.250003 1.060711 4.326933 +v 1.743373 2.019041 4.326933 +v 1.732357 2.664947 4.326933 +v 1.727264 1.065800 4.326909 +v 0.756633 1.769233 4.217244 +v 0.767650 2.664947 4.179334 +v 0.767650 1.060711 4.179334 +v 1.743373 2.019041 4.179334 +v 1.734036 2.668319 4.179690 +v 1.732357 1.060711 4.179334 +v 0.655345 1.752042 4.179334 +v 0.668621 2.730381 4.179334 +v 0.668621 0.995276 4.179334 +v 1.844661 2.019041 4.179334 +v 1.831378 2.730381 4.179334 +v 1.759105 1.043036 4.179334 +v 0.728821 2.019041 4.600781 +v 0.756633 2.209442 4.600781 +v 0.756633 1.802351 4.600781 +v 1.632991 1.889652 4.454917 +v 1.664585 1.773668 4.454917 +v 1.632991 1.609974 4.454917 +v 1.722225 0.962600 4.667344 +v 1.236736 0.975301 4.667344 +v 1.575969 0.972971 4.642551 +v 1.458095 0.931853 4.667344 +v 1.638568 0.929867 4.667344 +v 0.639354 0.888963 4.667344 +v 0.727230 0.826026 4.667344 +v 0.639354 0.826026 4.611697 +v 0.759280 1.924030 4.179334 +v 0.728194 1.769233 4.179334 +v 0.758296 1.597420 4.179334 +v 1.746593 0.995276 4.179334 +v 1.831378 0.995276 4.207922 +v 1.831951 1.117898 4.179334 +v -0.668622 5.730381 4.600781 +v -1.831380 5.730381 4.600781 +v -0.655339 5.019040 4.600781 +v -1.844655 5.019040 4.600781 +v -0.668622 3.995276 4.439138 +v -0.668622 3.995276 4.600781 +v -1.831380 3.995276 4.600781 +v -1.831380 3.995276 4.439138 +v -0.639348 3.826026 4.439138 +v -1.860646 3.826026 4.439138 +v -1.828160 3.826026 4.635510 +v -0.639348 3.826026 4.667344 +v -0.639348 3.950458 4.667344 +v -0.639348 3.975301 4.439138 +v -1.860646 3.953849 4.667344 +v -1.860646 3.975301 4.439138 +v -0.688909 3.826026 4.470027 +v -1.811086 3.826026 4.470027 +v -1.811086 3.826026 4.618777 +v -0.688909 3.826026 4.618777 +v -0.707021 3.728936 4.471638 +v -1.792974 3.728936 4.471638 +v -1.792974 3.728936 4.617163 +v -0.707021 3.728936 4.617163 +v -0.756627 5.019040 4.600781 +v -1.743367 5.019040 4.545606 +v -1.738485 5.678292 4.600781 +v -0.767644 5.664947 4.600781 +v -0.767644 4.060711 4.600781 +v -1.732350 4.048209 4.600781 +v -0.756627 5.019040 4.454917 +v -1.743367 5.019040 4.454917 +v -1.732350 5.664947 4.454917 +v -0.767644 5.664947 4.454917 +v -0.767644 4.060711 4.454917 +v -1.732350 4.060711 4.454917 +v -0.867009 4.773667 4.419617 +v -1.632985 5.019040 4.454917 +v -1.624440 5.544403 4.454917 +v -0.875554 5.544403 4.454917 +v -0.875554 4.181253 4.454917 +v -1.624440 4.181253 4.454917 +v -1.249997 5.544403 4.454917 +v -1.249997 4.181253 4.454917 +v -1.632985 5.019040 4.326933 +v -1.624440 5.544403 4.326933 +v -1.249997 5.544403 4.326933 +v -1.624440 4.181253 4.326933 +v -1.249997 4.181253 4.326933 +v -0.867009 4.771373 4.326933 +v -0.875554 5.544403 4.326933 +v -0.875554 4.181253 4.326933 +v -1.743367 4.751149 4.326933 +v -1.732350 5.664947 4.326933 +v -1.249997 5.664947 4.326933 +v -1.732350 4.060711 4.326933 +v -1.249997 4.060711 4.326933 +v -0.756627 5.019040 4.326933 +v -0.767644 5.664947 4.326933 +v -0.772737 4.065800 4.326909 +v -1.743367 4.769233 4.217244 +v -1.732350 5.664947 4.179334 +v -1.732350 4.060711 4.179334 +v -0.756627 5.019040 4.179334 +v -0.765964 5.668319 4.179690 +v -0.767644 4.060711 4.179334 +v -1.844655 4.752042 4.179334 +v -1.831380 5.730381 4.179334 +v -1.831380 3.995276 4.179334 +v -0.655339 5.019040 4.179334 +v -0.668622 5.730381 4.179334 +v -0.740895 4.043036 4.179334 +v -1.771180 5.019040 4.600781 +v -1.743367 5.209442 4.600781 +v -1.743367 4.802351 4.600781 +v -0.867009 4.889651 4.454917 +v -0.835416 4.773667 4.454917 +v -0.867009 4.609974 4.454917 +v -0.777776 3.962600 4.667344 +v -1.263265 3.975301 4.667344 +v -0.924031 3.972971 4.642551 +v -1.041906 3.931853 4.667344 +v -0.861432 3.929867 4.667344 +v -1.860646 3.888963 4.667344 +v -1.772771 3.826026 4.667344 +v -1.860646 3.826026 4.611697 +v -1.740720 4.924029 4.179334 +v -1.771807 4.769233 4.179334 +v -1.741704 4.597420 4.179334 +v -0.753408 3.995276 4.179334 +v -0.668622 3.995276 4.207922 +v -0.668050 4.117898 4.179334 +v -3.168622 5.730381 4.600781 +v -4.331380 5.730381 4.600781 +v -3.155339 5.019040 4.600781 +v -4.344655 5.019040 4.600781 +v -3.168622 3.995276 4.439138 +v -3.168622 3.995276 4.600781 +v -4.331380 3.995276 4.600781 +v -4.331380 3.995276 4.439138 +v -3.139348 3.826026 4.439138 +v -4.360646 3.826026 4.439138 +v -4.328160 3.826026 4.635510 +v -3.139348 3.826026 4.667344 +v -3.139348 3.950458 4.667344 +v -3.139348 3.975301 4.439138 +v -4.360646 3.953849 4.667344 +v -4.360646 3.975301 4.439138 +v -3.188909 3.826026 4.470027 +v -4.311086 3.826026 4.470027 +v -4.311086 3.826026 4.618777 +v -3.188909 3.826026 4.618777 +v -3.207021 3.728936 4.471638 +v -4.292974 3.728936 4.471638 +v -4.292974 3.728936 4.617163 +v -3.207021 3.728936 4.617163 +v -3.256627 5.019040 4.600781 +v -4.243367 5.019040 4.545606 +v -4.238484 5.678292 4.600781 +v -3.267644 5.664947 4.600781 +v -3.267644 4.060711 4.600781 +v -4.232350 4.048209 4.600781 +v -3.256627 5.019040 4.454917 +v -4.243367 5.019040 4.454917 +v -4.232350 5.664947 4.454917 +v -3.267644 5.664947 4.454917 +v -3.267644 4.060711 4.454917 +v -4.232350 4.060711 4.454917 +v -3.367009 4.773667 4.419617 +v -4.132985 5.019040 4.454917 +v -4.124440 5.544403 4.454917 +v -3.375554 5.544403 4.454917 +v -3.375554 4.181253 4.454917 +v -4.124440 4.181253 4.454917 +v -3.749997 5.544403 4.454917 +v -3.749997 4.181253 4.454917 +v -4.132985 5.019040 4.326933 +v -4.124440 5.544403 4.326933 +v -3.749997 5.544403 4.326933 +v -4.124440 4.181253 4.326933 +v -3.749997 4.181253 4.326933 +v -3.367009 4.771373 4.326933 +v -3.375554 5.544403 4.326933 +v -3.375554 4.181253 4.326933 +v -4.243367 4.751149 4.326933 +v -4.232350 5.664947 4.326933 +v -3.749997 5.664947 4.326933 +v -4.232350 4.060711 4.326933 +v -3.749997 4.060711 4.326933 +v -3.256627 5.019040 4.326933 +v -3.267644 5.664947 4.326933 +v -3.272737 4.065800 4.326909 +v -4.243367 4.769233 4.217244 +v -4.232350 5.664947 4.179334 +v -4.232350 4.060711 4.179334 +v -3.256627 5.019040 4.179334 +v -3.265964 5.668319 4.179690 +v -3.267644 4.060711 4.179334 +v -4.344655 4.752042 4.179334 +v -4.331380 5.730381 4.179334 +v -4.331380 3.995276 4.179334 +v -3.155339 5.019040 4.179334 +v -3.168622 5.730381 4.179334 +v -3.240895 4.043036 4.179334 +v -4.271180 5.019040 4.600781 +v -4.243367 5.209442 4.600781 +v -4.243367 4.802351 4.600781 +v -3.367009 4.889651 4.454917 +v -3.335416 4.773667 4.454917 +v -3.367009 4.609974 4.454917 +v -3.277776 3.962600 4.667344 +v -3.763265 3.975301 4.667344 +v -3.424031 3.972971 4.642551 +v -3.541905 3.931853 4.667344 +v -3.361432 3.929867 4.667344 +v -4.360646 3.888963 4.667344 +v -4.272771 3.826026 4.667344 +v -4.360646 3.826026 4.611697 +v -4.240720 4.924029 4.179334 +v -4.271807 4.769233 4.179334 +v -4.241704 4.597420 4.179334 +v -3.253407 3.995276 4.179334 +v -3.168622 3.995276 4.207922 +v -3.168050 4.117898 4.179334 +v -3.168622 2.730381 4.600781 +v -4.331380 2.730381 4.600781 +v -3.155339 2.019041 4.600781 +v -4.344655 2.019041 4.600781 +v -3.168622 0.995276 4.439138 +v -3.168622 0.995276 4.600781 +v -4.331380 0.995276 4.600781 +v -4.331380 0.995276 4.439138 +v -3.139348 0.826026 4.439138 +v -4.360646 0.826026 4.439138 +v -4.328160 0.826026 4.635510 +v -3.139348 0.826026 4.667344 +v -3.139348 0.950458 4.667344 +v -3.139348 0.975301 4.439138 +v -4.360646 0.953849 4.667344 +v -4.360646 0.975301 4.439138 +v -3.188909 0.826026 4.470027 +v -4.311086 0.826026 4.470027 +v -4.311086 0.826026 4.618777 +v -3.188909 0.826026 4.618777 +v -3.207021 0.728936 4.471638 +v -4.292974 0.728936 4.471638 +v -4.292974 0.728936 4.617163 +v -3.207021 0.728936 4.617163 +v -3.256627 2.019041 4.600781 +v -4.243367 2.019041 4.545606 +v -4.238484 2.678293 4.600781 +v -3.267644 2.664947 4.600781 +v -3.267644 1.060711 4.600781 +v -4.232350 1.048209 4.600781 +v -3.256627 2.019041 4.454917 +v -4.243367 2.019041 4.454917 +v -4.232350 2.664947 4.454917 +v -3.267644 2.664947 4.454917 +v -3.267644 1.060711 4.454917 +v -4.232350 1.060711 4.454917 +v -3.367009 1.773668 4.419617 +v -4.132985 2.019041 4.454917 +v -4.124440 2.544403 4.454917 +v -3.375554 2.544403 4.454917 +v -3.375554 1.181254 4.454917 +v -4.124440 1.181254 4.454917 +v -3.749997 2.544403 4.454917 +v -3.749997 1.181254 4.454917 +v -4.132985 2.019041 4.326933 +v -4.124440 2.544403 4.326933 +v -3.749997 2.544403 4.326933 +v -4.124440 1.181254 4.326933 +v -3.749997 1.181254 4.326933 +v -3.367009 1.771373 4.326933 +v -3.375554 2.544403 4.326933 +v -3.375554 1.181254 4.326933 +v -4.243367 1.751149 4.326933 +v -4.232350 2.664947 4.326933 +v -3.749997 2.664947 4.326933 +v -4.232350 1.060711 4.326933 +v -3.749997 1.060711 4.326933 +v -3.256627 2.019041 4.326933 +v -3.267644 2.664947 4.326933 +v -3.272737 1.065800 4.326909 +v -4.243367 1.769233 4.217244 +v -4.232350 2.664947 4.179334 +v -4.232350 1.060711 4.179334 +v -3.256627 2.019041 4.179334 +v -3.265964 2.668319 4.179690 +v -3.267644 1.060711 4.179334 +v -4.344655 1.752042 4.179334 +v -4.331380 2.730381 4.179334 +v -4.331380 0.995276 4.179334 +v -3.155339 2.019041 4.179334 +v -3.168622 2.730381 4.179334 +v -3.240895 1.043036 4.179334 +v -4.271180 2.019041 4.600781 +v -4.243367 2.209442 4.600781 +v -4.243367 1.802351 4.600781 +v -3.367009 1.889652 4.454917 +v -3.335416 1.773668 4.454917 +v -3.367009 1.609974 4.454917 +v -3.277776 0.962600 4.667344 +v -3.763265 0.975301 4.667344 +v -3.424031 0.972971 4.642551 +v -3.541905 0.931853 4.667344 +v -3.361432 0.929867 4.667344 +v -4.360646 0.888963 4.667344 +v -4.272771 0.826026 4.667344 +v -4.360646 0.826026 4.611697 +v -4.240720 1.924030 4.179334 +v -4.271807 1.769233 4.179334 +v -4.241704 1.597420 4.179334 +v -3.253407 0.995276 4.179334 +v -3.168622 0.995276 4.207922 +v -3.168050 1.117898 4.179334 +v -5.314072 0.522178 1.529073 +v -5.314072 0.568346 1.529073 +v -5.380199 0.568346 1.529073 +v -5.380199 0.522178 1.529073 +v -5.314072 1.022473 1.529072 +v -5.314072 1.068640 1.529072 +v -5.380199 1.068640 1.529072 +v -5.380199 1.022473 1.529072 +v -5.314072 1.522767 1.529072 +v -5.314072 1.568935 1.529072 +v -5.380199 1.568935 1.529072 +v -5.380199 1.522767 1.529072 +v -5.314072 2.023062 1.529072 +v -5.314072 2.069228 1.529072 +v -5.380199 2.069228 1.529072 +v -5.380199 2.023062 1.529072 +v -5.314072 2.523356 1.529072 +v -5.314072 2.569523 1.529072 +v -5.380199 2.569523 1.529072 +v -5.380199 2.523356 1.529072 +v -5.314072 3.023650 1.529072 +v -5.314072 3.069817 1.529072 +v -5.380199 3.069817 1.529072 +v -5.380199 3.023650 1.529072 +v -5.314072 3.523945 1.529072 +v -5.314072 3.570111 1.529072 +v -5.380199 3.570111 1.529072 +v -5.380199 3.523945 1.529072 +v -5.314072 4.024240 1.529072 +v -5.314072 4.070405 1.529072 +v -5.380199 4.070405 1.529072 +v -5.380199 4.024240 1.529072 +v -5.314072 4.524533 1.529072 +v -5.314072 4.570700 1.529072 +v -5.380199 4.570700 1.529072 +v -5.380199 4.524533 1.529072 +v -5.314072 5.024827 1.529072 +v -5.314072 5.070994 1.529072 +v -5.380199 5.070994 1.529072 +v -5.380199 5.024827 1.529072 +v -5.314072 5.525121 1.529072 +v -5.314072 5.571288 1.529072 +v -5.380199 5.571288 1.529072 +v -5.380199 5.525121 1.529072 +v -5.314072 6.025415 1.529072 +v -5.314072 6.071582 1.529072 +v -5.380199 6.071582 1.529072 +v -5.380199 6.025415 1.529072 +v -5.314072 6.525710 1.529072 +v -5.314072 6.571876 1.529072 +v -5.380199 6.571876 1.529072 +v -5.380199 6.525710 1.529072 +v -5.314072 7.026004 1.529072 +v -5.314072 7.072170 1.529072 +v -5.380199 7.072170 1.529072 +v -5.380199 7.026004 1.529072 +v -5.292270 7.586403 1.529073 +v -5.292270 7.522140 1.593336 +v -5.417535 7.522140 1.593336 +v -5.292270 0.000000 1.529073 +v -5.292270 0.000000 1.593335 +v -5.417535 0.000000 1.593335 +v -5.417535 0.000000 1.529073 +v -5.417535 7.586403 1.529073 +v -5.314072 0.522178 1.090320 +v -5.314072 0.568346 1.090320 +v -5.380199 0.568346 1.090320 +v -5.380199 0.522178 1.090320 +v -5.314072 1.022473 1.090320 +v -5.314072 1.068640 1.090320 +v -5.380199 1.068640 1.090320 +v -5.380199 1.022473 1.090320 +v -5.314072 1.522767 1.090320 +v -5.314072 1.568935 1.090320 +v -5.380199 1.568935 1.090320 +v -5.380199 1.522767 1.090320 +v -5.314072 2.023062 1.090320 +v -5.314072 2.069228 1.090320 +v -5.380199 2.069228 1.090320 +v -5.380199 2.023062 1.090320 +v -5.314072 2.523356 1.090320 +v -5.314072 2.569523 1.090320 +v -5.380199 2.569523 1.090320 +v -5.380199 2.523356 1.090320 +v -5.314072 3.023650 1.090320 +v -5.314072 3.069817 1.090320 +v -5.380199 3.069817 1.090320 +v -5.380199 3.023650 1.090320 +v -5.314072 3.523945 1.090320 +v -5.314072 3.570111 1.090320 +v -5.380199 3.570111 1.090320 +v -5.380199 3.523945 1.090320 +v -5.314072 4.024239 1.090320 +v -5.314072 4.070405 1.090320 +v -5.380199 4.070405 1.090320 +v -5.380199 4.024239 1.090320 +v -5.314072 4.524533 1.090320 +v -5.314072 4.570700 1.090320 +v -5.380199 4.570700 1.090320 +v -5.380199 4.524533 1.090320 +v -5.314072 5.024827 1.090320 +v -5.314072 5.070994 1.090320 +v -5.380199 5.070994 1.090320 +v -5.380199 5.024827 1.090320 +v -5.314072 5.525121 1.090320 +v -5.314072 5.571288 1.090320 +v -5.380199 5.571288 1.090320 +v -5.380199 5.525121 1.090320 +v -5.314072 6.025415 1.090320 +v -5.314072 6.071582 1.090320 +v -5.380199 6.071582 1.090320 +v -5.380199 6.025415 1.090320 +v -5.314072 6.525710 1.090320 +v -5.314072 6.571876 1.090320 +v -5.380199 6.571876 1.090320 +v -5.380199 6.525710 1.090320 +v -5.314072 7.026004 1.090320 +v -5.314072 7.072170 1.090320 +v -5.380199 7.072170 1.090320 +v -5.380199 7.026004 1.090320 +v -5.292270 7.586403 1.090318 +v -5.292270 7.522140 1.026056 +v -5.417535 7.522140 1.026056 +v -5.292270 0.000000 1.090320 +v -5.292270 0.000000 1.026057 +v -5.417535 0.000000 1.026057 +v -5.417535 0.000000 1.090320 +v -5.417535 7.586403 1.090318 +v 5.383783 7.010900 -3.186068 +v 5.383783 7.527450 -3.186068 +v 5.383783 7.010900 -3.140304 +v 5.383783 7.527450 -3.140303 +v 5.317655 7.010900 -3.140304 +v 5.317655 7.527450 -3.140303 +v 5.317655 7.010900 -3.186068 +v 5.317655 7.527450 -3.186068 +v 5.383783 7.010900 -2.690133 +v 5.383783 7.527450 -2.690133 +v 5.383783 7.010900 -2.644368 +v 5.383783 7.527450 -2.644368 +v 5.317655 7.010900 -2.644368 +v 5.317655 7.527450 -2.644368 +v 5.317655 7.010900 -2.690133 +v 5.317655 7.527450 -2.690133 +v 5.383783 7.010900 -2.194198 +v 5.383783 7.527450 -2.194198 +v 5.383783 7.010900 -2.148433 +v 5.383783 7.527450 -2.148433 +v 5.317655 7.010900 -2.148433 +v 5.317655 7.527450 -2.148433 +v 5.317655 7.010900 -2.194198 +v 5.317655 7.527450 -2.194198 +v 5.383783 7.010900 -1.698263 +v 5.383783 7.527450 -1.698263 +v 5.383783 7.010900 -1.652499 +v 5.383783 7.527450 -1.652499 +v 5.317655 7.010900 -1.652499 +v 5.317655 7.527450 -1.652499 +v 5.317655 7.010900 -1.698263 +v 5.317655 7.527450 -1.698263 +v 5.383783 7.010900 -1.202328 +v 5.383783 7.527450 -1.202328 +v 5.383783 7.010900 -1.156564 +v 5.383783 7.527450 -1.156564 +v 5.317655 7.010900 -1.156564 +v 5.317655 7.527450 -1.156564 +v 5.317655 7.010900 -1.202328 +v 5.317655 7.527450 -1.202328 +v 5.383783 7.010900 -0.706393 +v 5.383783 7.527450 -0.706393 +v 5.383783 7.010900 -0.660629 +v 5.383783 7.527450 -0.660629 +v 5.317655 7.010900 -0.660629 +v 5.317655 7.527450 -0.660629 +v 5.317655 7.010900 -0.706393 +v 5.317655 7.527450 -0.706393 +v 5.383783 7.010900 -0.210458 +v 5.383783 7.527450 -0.210458 +v 5.383783 7.010900 -0.164694 +v 5.383783 7.527450 -0.164694 +v 5.317655 7.010900 -0.164694 +v 5.317655 7.527450 -0.164694 +v 5.317655 7.010900 -0.210458 +v 5.317655 7.527450 -0.210458 +v 5.383783 7.010900 0.285477 +v 5.383783 7.527450 0.285477 +v 5.383783 7.010900 0.331241 +v 5.383783 7.527450 0.331241 +v 5.317655 7.010900 0.331241 +v 5.317655 7.527450 0.331241 +v 5.317655 7.010900 0.285477 +v 5.317655 7.527450 0.285477 +v 5.383783 7.010900 0.781412 +v 5.383783 7.527450 0.781412 +v 5.383783 7.010900 0.827175 +v 5.383783 7.527450 0.827176 +v 5.317655 7.010900 0.827175 +v 5.317655 7.527450 0.827176 +v 5.317655 7.010900 0.781412 +v 5.317655 7.527450 0.781412 +v 5.383783 7.010900 1.277346 +v 5.383783 7.527450 1.277346 +v 5.383783 7.010900 1.323110 +v 5.383783 7.527450 1.323111 +v 5.317655 7.010900 1.323110 +v 5.317655 7.527450 1.323111 +v 5.317655 7.010900 1.277346 +v 5.317655 7.527450 1.277346 +v 5.383783 7.010900 1.773281 +v 5.383783 7.527450 1.773281 +v 5.383783 7.010900 1.819045 +v 5.383783 7.527450 1.819046 +v 5.317655 7.010900 1.819045 +v 5.317655 7.527450 1.819046 +v 5.317655 7.010900 1.773281 +v 5.317655 7.527450 1.773281 +v 5.383783 7.010900 2.269216 +v 5.383783 7.527450 2.269216 +v 5.383783 7.010900 2.314980 +v 5.383783 7.527450 2.314980 +v 5.317655 7.010900 2.314980 +v 5.317655 7.527450 2.314980 +v 5.317655 7.010900 2.269216 +v 5.317655 7.527450 2.269216 +v 5.383783 7.010900 2.765151 +v 5.383783 7.527450 2.765151 +v 5.383783 7.010900 2.810915 +v 5.383783 7.527450 2.810915 +v 5.317655 7.010900 2.810915 +v 5.317655 7.527450 2.810915 +v 5.317655 7.010900 2.765151 +v 5.317655 7.527450 2.765151 +v 5.383783 7.010900 3.261086 +v 5.383783 7.527451 3.261086 +v 5.383783 7.010900 3.306850 +v 5.383783 7.527451 3.306850 +v 5.317655 7.010900 3.306850 +v 5.317655 7.527451 3.306850 +v 5.317655 7.010900 3.261086 +v 5.317655 7.527451 3.261086 +v 5.383783 7.010900 3.757021 +v 5.383783 7.527451 3.757021 +v 5.383783 7.010900 3.802785 +v 5.383783 7.527451 3.802785 +v 5.317655 7.010900 3.802785 +v 5.317655 7.527451 3.802785 +v 5.317655 7.010900 3.757021 +v 5.317655 7.527451 3.757021 +v 5.383783 7.010900 4.252955 +v 5.383783 7.527451 4.252955 +v 5.383783 7.010900 4.298718 +v 5.383783 7.527451 4.298720 +v 5.317655 7.010900 4.298718 +v 5.317655 7.527451 4.298720 +v 5.317655 7.010900 4.252955 +v 5.317655 7.527451 4.252955 +v 5.343286 7.010900 4.829345 +v 5.343286 7.527451 4.829345 +v 5.296208 7.010900 4.829345 +v 5.296208 7.527451 4.829345 +v 5.296208 7.010900 4.763220 +v 5.296208 7.527451 4.763220 +v 5.343286 7.010900 4.763220 +v 5.343286 7.527451 4.763220 +v 4.836644 7.010900 4.829345 +v 4.836644 7.527451 4.829345 +v 4.789565 7.010900 4.829345 +v 4.789565 7.527451 4.829345 +v 4.789565 7.010900 4.763220 +v 4.789565 7.527451 4.763220 +v 4.836644 7.010900 4.763220 +v 4.836644 7.527451 4.763220 +v 4.330002 7.010900 4.829345 +v 4.330002 7.527451 4.829345 +v 4.282924 7.010900 4.829345 +v 4.282924 7.527451 4.829345 +v 4.282924 7.010900 4.763220 +v 4.282924 7.527451 4.763220 +v 4.330002 7.010900 4.763220 +v 4.330002 7.527451 4.763220 +v 3.823360 7.010900 4.829345 +v 3.823360 7.527451 4.829345 +v 3.776282 7.010900 4.829345 +v 3.776282 7.527451 4.829345 +v 3.776282 7.010900 4.763220 +v 3.776282 7.527451 4.763220 +v 3.823360 7.010900 4.763220 +v 3.823360 7.527451 4.763220 +v 3.316717 7.010900 4.829345 +v 3.316717 7.527451 4.829345 +v 3.269640 7.010900 4.829345 +v 3.269639 7.527451 4.829345 +v 3.269640 7.010900 4.763220 +v 3.269639 7.527451 4.763220 +v 3.316717 7.010900 4.763220 +v 3.316717 7.527451 4.763220 +v 2.810075 7.010900 4.829345 +v 2.810075 7.527451 4.829345 +v 2.762997 7.010900 4.829345 +v 2.762997 7.527451 4.829345 +v 2.762997 7.010900 4.763220 +v 2.762997 7.527451 4.763220 +v 2.810075 7.010900 4.763220 +v 2.810075 7.527451 4.763220 +v 2.303433 7.010900 4.829345 +v 2.303433 7.527451 4.829345 +v 2.256354 7.010900 4.829345 +v 2.256354 7.527451 4.829345 +v 2.256354 7.010900 4.763220 +v 2.256354 7.527451 4.763220 +v 2.303433 7.010900 4.763220 +v 2.303433 7.527451 4.763220 +v 1.796791 7.010900 4.829345 +v 1.796791 7.527451 4.829345 +v 1.749712 7.010900 4.829345 +v 1.749712 7.527451 4.829345 +v 1.749712 7.010900 4.763220 +v 1.749712 7.527451 4.763220 +v 1.796791 7.010900 4.763220 +v 1.796791 7.527451 4.763220 +v 1.290148 7.010900 4.829345 +v 1.290148 7.527451 4.829345 +v 1.243071 7.010900 4.829345 +v 1.243070 7.527451 4.829345 +v 1.243071 7.010900 4.763220 +v 1.243070 7.527451 4.763220 +v 1.290148 7.010900 4.763220 +v 1.290148 7.527451 4.763220 +v 0.783506 7.010900 4.829345 +v 0.783506 7.527451 4.829345 +v 0.736428 7.010900 4.829345 +v 0.736428 7.527451 4.829345 +v 0.736428 7.010900 4.763220 +v 0.736428 7.527451 4.763220 +v 0.783506 7.010900 4.763220 +v 0.783506 7.527451 4.763220 +v 0.276863 7.010900 4.829345 +v 0.276863 7.527451 4.829345 +v 0.229785 7.010900 4.829345 +v 0.229785 7.527451 4.829345 +v 0.229785 7.010900 4.763220 +v 0.229785 7.527451 4.763220 +v 0.276863 7.010900 4.763220 +v 0.276863 7.527451 4.763220 +v -0.229779 7.010900 4.829345 +v -0.229779 7.527451 4.829345 +v -0.276857 7.010900 4.829345 +v -0.276857 7.527451 4.829345 +v -0.276857 7.010900 4.763220 +v -0.276857 7.527451 4.763220 +v -0.229779 7.010900 4.763220 +v -0.229779 7.527451 4.763220 +v -0.736421 7.010900 4.829345 +v -0.736421 7.527451 4.829345 +v -0.783499 7.010900 4.829345 +v -0.783499 7.527451 4.829345 +v -0.783499 7.010900 4.763220 +v -0.783499 7.527451 4.763220 +v -0.736421 7.010900 4.763220 +v -0.736421 7.527451 4.763220 +v -1.243063 7.010900 4.829345 +v -1.243063 7.527451 4.829345 +v -1.290141 7.010900 4.829345 +v -1.290141 7.527451 4.829345 +v -1.290141 7.010900 4.763220 +v -1.290141 7.527451 4.763220 +v -1.243063 7.010900 4.763220 +v -1.243063 7.527451 4.763220 +v -1.749705 7.010900 4.829345 +v -1.749705 7.527451 4.829345 +v -1.796783 7.010900 4.829345 +v -1.796784 7.527451 4.829345 +v -1.796783 7.010900 4.763220 +v -1.796784 7.527451 4.763220 +v -1.749705 7.010900 4.763220 +v -1.749705 7.527451 4.763220 +v -2.256348 7.010900 4.829345 +v -2.256348 7.527451 4.829345 +v -2.303426 7.010900 4.829345 +v -2.303426 7.527451 4.829345 +v -2.303426 7.010900 4.763220 +v -2.303426 7.527451 4.763220 +v -2.256348 7.010900 4.763220 +v -2.256348 7.527451 4.763220 +v -2.762990 7.010900 4.829345 +v -2.762990 7.527451 4.829345 +v -2.810068 7.010900 4.829345 +v -2.810068 7.527451 4.829345 +v -2.810068 7.010900 4.763220 +v -2.810068 7.527451 4.763220 +v -2.762990 7.010900 4.763220 +v -2.762990 7.527451 4.763220 +v -3.269633 7.010900 4.829345 +v -3.269633 7.527451 4.829345 +v -3.316710 7.010900 4.829345 +v -3.316711 7.527451 4.829345 +v -3.316710 7.010900 4.763220 +v -3.316711 7.527451 4.763220 +v -3.269633 7.010900 4.763220 +v -3.269633 7.527451 4.763220 +v -3.776275 7.010900 4.829345 +v -3.776275 7.527451 4.829345 +v -3.823353 7.010900 4.829345 +v -3.823353 7.527451 4.829345 +v -3.823353 7.010900 4.763220 +v -3.823353 7.527451 4.763220 +v -3.776275 7.010900 4.763220 +v -3.776275 7.527451 4.763220 +v -4.282917 7.010900 4.829345 +v -4.282917 7.527451 4.829345 +v -4.329995 7.010900 4.829345 +v -4.329996 7.527451 4.829345 +v -4.329995 7.010900 4.763220 +v -4.329996 7.527451 4.763220 +v -4.282917 7.010900 4.763220 +v -4.282917 7.527451 4.763220 +v -4.789560 7.010900 4.829345 +v -4.789560 7.527451 4.829345 +v -4.836637 7.010900 4.829345 +v -4.836638 7.527451 4.829345 +v -4.836637 7.010900 4.763220 +v -4.836638 7.527451 4.763220 +v -4.789560 7.010900 4.763220 +v -4.789560 7.527451 4.763220 +v -5.296202 7.010900 4.829345 +v -5.296202 7.527451 4.829345 +v -5.343279 7.010900 4.829345 +v -5.343280 7.527451 4.829345 +v -5.343279 7.010900 4.763220 +v -5.343280 7.527451 4.763220 +v -5.296202 7.010900 4.763220 +v -5.296202 7.527451 4.763220 +v -5.309542 7.010900 -3.186068 +v -5.309542 7.527450 -3.186068 +v -5.309542 7.010900 -3.140304 +v -5.309542 7.527450 -3.140303 +v -5.375670 7.010900 -3.140304 +v -5.375670 7.527450 -3.140303 +v -5.375670 7.010900 -3.186068 +v -5.375670 7.527450 -3.186068 +v -5.309542 7.010900 -2.690133 +v -5.309542 7.527450 -2.690133 +v -5.309542 7.010900 -2.644368 +v -5.309542 7.527450 -2.644368 +v -5.375670 7.010900 -2.644368 +v -5.375670 7.527450 -2.644368 +v -5.375670 7.010900 -2.690133 +v -5.375670 7.527450 -2.690133 +v -5.309542 7.010900 -2.194198 +v -5.309542 7.527450 -2.194198 +v -5.309542 7.010900 -2.148433 +v -5.309542 7.527450 -2.148433 +v -5.375670 7.010900 -2.148433 +v -5.375670 7.527450 -2.148433 +v -5.375670 7.010900 -2.194198 +v -5.375670 7.527450 -2.194198 +v -5.309542 7.010900 -1.698263 +v -5.309542 7.527450 -1.698263 +v -5.309542 7.010900 -1.652499 +v -5.309542 7.527450 -1.652499 +v -5.375670 7.010900 -1.652499 +v -5.375670 7.527450 -1.652499 +v -5.375670 7.010900 -1.698263 +v -5.375670 7.527450 -1.698263 +v -5.309542 7.010900 -1.202328 +v -5.309542 7.527450 -1.202328 +v -5.309542 7.010900 -1.156564 +v -5.309542 7.527450 -1.156564 +v -5.375670 7.010900 -1.156564 +v -5.375670 7.527450 -1.156564 +v -5.375670 7.010900 -1.202328 +v -5.375670 7.527450 -1.202328 +v -5.309542 7.010900 -0.706393 +v -5.309542 7.527450 -0.706393 +v -5.309542 7.010900 -0.660629 +v -5.309542 7.527450 -0.660629 +v -5.375670 7.010900 -0.660629 +v -5.375670 7.527450 -0.660629 +v -5.375670 7.010900 -0.706393 +v -5.375670 7.527450 -0.706393 +v -5.309542 7.010900 -0.210458 +v -5.309542 7.527450 -0.210458 +v -5.309542 7.010900 -0.164694 +v -5.309542 7.527450 -0.164694 +v -5.375670 7.010900 -0.164694 +v -5.375670 7.527450 -0.164694 +v -5.375670 7.010900 -0.210458 +v -5.375670 7.527450 -0.210458 +v -5.309542 7.010900 0.285477 +v -5.309542 7.527450 0.285477 +v -5.309542 7.010900 0.331241 +v -5.309542 7.527450 0.331241 +v -5.375670 7.010900 0.331241 +v -5.375670 7.527450 0.331241 +v -5.375670 7.010900 0.285477 +v -5.375670 7.527450 0.285477 +v -5.309542 7.010900 2.269216 +v -5.309542 7.527450 2.269216 +v -5.309542 7.010900 2.314980 +v -5.309542 7.527450 2.314980 +v -5.375670 7.010900 2.314980 +v -5.375670 7.527450 2.314980 +v -5.375670 7.010900 2.269216 +v -5.375670 7.527450 2.269216 +v -5.309542 7.010900 2.765151 +v -5.309542 7.527450 2.765151 +v -5.309542 7.010900 2.810915 +v -5.309542 7.527450 2.810915 +v -5.375670 7.010900 2.810915 +v -5.375670 7.527450 2.810915 +v -5.375670 7.010900 2.765151 +v -5.375670 7.527450 2.765151 +v -5.309542 7.010900 3.261086 +v -5.309542 7.527451 3.261086 +v -5.309542 7.010900 3.306850 +v -5.309542 7.527451 3.306850 +v -5.375670 7.010900 3.306850 +v -5.375670 7.527451 3.306850 +v -5.375670 7.010900 3.261086 +v -5.375670 7.527451 3.261086 +v -5.309542 7.010900 3.757021 +v -5.309542 7.527451 3.757021 +v -5.309542 7.010900 3.802785 +v -5.309542 7.527451 3.802785 +v -5.375670 7.010900 3.802785 +v -5.375670 7.527451 3.802785 +v -5.375670 7.010900 3.757021 +v -5.375670 7.527451 3.757021 +v -5.309542 7.010900 4.252955 +v -5.309542 7.527451 4.252955 +v -5.309542 7.010900 4.298718 +v -5.309542 7.527451 4.298720 +v -5.375670 7.010900 4.298718 +v -5.375670 7.527451 4.298720 +v -5.375670 7.010900 4.252955 +v -5.375670 7.527451 4.252955 +v 5.343286 7.010900 -3.620531 +v 5.343286 7.527450 -3.620531 +v 5.296208 7.010900 -3.620531 +v 5.296208 7.527450 -3.620531 +v 5.296208 7.010900 -3.686659 +v 5.296208 7.527450 -3.686659 +v 5.343286 7.010900 -3.686659 +v 5.343286 7.527450 -3.686659 +v 4.836644 7.010900 -3.620531 +v 4.836644 7.527450 -3.620531 +v 4.789565 7.010900 -3.620531 +v 4.789565 7.527450 -3.620531 +v 4.789565 7.010900 -3.686659 +v 4.789565 7.527450 -3.686659 +v 4.836644 7.010900 -3.686659 +v 4.836644 7.527450 -3.686659 +v 4.330002 7.010900 -3.620531 +v 4.330002 7.527450 -3.620531 +v 4.282924 7.010900 -3.620531 +v 4.282924 7.527450 -3.620531 +v 4.282924 7.010900 -3.686659 +v 4.282924 7.527450 -3.686659 +v 4.330002 7.010900 -3.686659 +v 4.330002 7.527450 -3.686659 +v 3.823360 7.010900 -3.620531 +v 3.823360 7.527450 -3.620531 +v 3.776282 7.010900 -3.620531 +v 3.776282 7.527450 -3.620531 +v 3.776282 7.010900 -3.686659 +v 3.776282 7.527450 -3.686659 +v 3.823360 7.010900 -3.686659 +v 3.823360 7.527450 -3.686659 +v 3.316717 7.010900 -3.620531 +v 3.316717 7.527450 -3.620531 +v 3.269640 7.010900 -3.620531 +v 3.269639 7.527450 -3.620531 +v 3.269640 7.010900 -3.686659 +v 3.269639 7.527450 -3.686659 +v 3.316717 7.010900 -3.686659 +v 3.316717 7.527450 -3.686659 +v 2.810075 7.010900 -3.620531 +v 2.810075 7.527450 -3.620531 +v 2.762997 7.010900 -3.620531 +v 2.762997 7.527450 -3.620531 +v 2.762997 7.010900 -3.686659 +v 2.762997 7.527450 -3.686659 +v 2.810075 7.010900 -3.686659 +v 2.810075 7.527450 -3.686659 +v 2.303433 7.010900 -3.620531 +v 2.303433 7.527450 -3.620531 +v 2.256354 7.010900 -3.620531 +v 2.256354 7.527450 -3.620531 +v 2.256354 7.010900 -3.686659 +v 2.256354 7.527450 -3.686659 +v 2.303433 7.010900 -3.686659 +v 2.303433 7.527450 -3.686659 +v 1.796791 7.010900 -3.620531 +v 1.796791 7.527450 -3.620531 +v 1.749712 7.010900 -3.620531 +v 1.749712 7.527450 -3.620531 +v 1.749712 7.010900 -3.686659 +v 1.749712 7.527450 -3.686659 +v 1.796791 7.010900 -3.686659 +v 1.796791 7.527450 -3.686659 +v 1.290148 7.010900 -3.620531 +v 1.290148 7.527450 -3.620531 +v 1.243071 7.010900 -3.620531 +v 1.243070 7.527450 -3.620531 +v 1.243071 7.010900 -3.686659 +v 1.243070 7.527450 -3.686659 +v 1.290148 7.010900 -3.686659 +v 1.290148 7.527450 -3.686659 +v 0.783506 7.010900 -3.620531 +v 0.783506 7.527450 -3.620531 +v 0.736428 7.010900 -3.620531 +v 0.736428 7.527450 -3.620531 +v 0.736428 7.010900 -3.686659 +v 0.736428 7.527450 -3.686659 +v 0.783506 7.010900 -3.686659 +v 0.783506 7.527450 -3.686659 +v 0.276863 7.010900 -3.620531 +v 0.276863 7.527450 -3.620531 +v 0.229785 7.010900 -3.620531 +v 0.229785 7.527450 -3.620531 +v 0.229785 7.010900 -3.686659 +v 0.229785 7.527450 -3.686659 +v 0.276863 7.010900 -3.686659 +v 0.276863 7.527450 -3.686659 +v -0.229779 7.010900 -3.620531 +v -0.229779 7.527450 -3.620531 +v -0.276857 7.010900 -3.620531 +v -0.276857 7.527450 -3.620531 +v -0.276857 7.010900 -3.686659 +v -0.276857 7.527450 -3.686659 +v -0.229779 7.010900 -3.686659 +v -0.229779 7.527450 -3.686659 +v -0.736421 7.010900 -3.620531 +v -0.736421 7.527450 -3.620531 +v -0.783499 7.010900 -3.620531 +v -0.783499 7.527450 -3.620531 +v -0.783499 7.010900 -3.686659 +v -0.783499 7.527450 -3.686659 +v -0.736421 7.010900 -3.686659 +v -0.736421 7.527450 -3.686659 +v -1.243063 7.010900 -3.620531 +v -1.243063 7.527450 -3.620531 +v -1.290141 7.010900 -3.620531 +v -1.290141 7.527450 -3.620531 +v -1.290141 7.010900 -3.686659 +v -1.290141 7.527450 -3.686659 +v -1.243063 7.010900 -3.686659 +v -1.243063 7.527450 -3.686659 +v -1.749705 7.010900 -3.620531 +v -1.749705 7.527450 -3.620531 +v -1.796783 7.010900 -3.620531 +v -1.796784 7.527450 -3.620531 +v -1.796783 7.010900 -3.686659 +v -1.796784 7.527450 -3.686659 +v -1.749705 7.010900 -3.686659 +v -1.749705 7.527450 -3.686659 +v -2.256348 7.010900 -3.620531 +v -2.256348 7.527450 -3.620531 +v -2.303426 7.010900 -3.620531 +v -2.303426 7.527450 -3.620531 +v -2.303426 7.010900 -3.686659 +v -2.303426 7.527450 -3.686659 +v -2.256348 7.010900 -3.686659 +v -2.256348 7.527450 -3.686659 +v -2.762990 7.010900 -3.620531 +v -2.762990 7.527450 -3.620531 +v -2.810068 7.010900 -3.620531 +v -2.810068 7.527450 -3.620531 +v -2.810068 7.010900 -3.686659 +v -2.810068 7.527450 -3.686659 +v -2.762990 7.010900 -3.686659 +v -2.762990 7.527450 -3.686659 +v -3.269633 7.010900 -3.620531 +v -3.269633 7.527450 -3.620531 +v -3.316710 7.010900 -3.620531 +v -3.316711 7.527450 -3.620531 +v -3.316710 7.010900 -3.686659 +v -3.316711 7.527450 -3.686659 +v -3.269633 7.010900 -3.686659 +v -3.269633 7.527450 -3.686659 +v -3.776275 7.010900 -3.620531 +v -3.776275 7.527450 -3.620531 +v -3.823353 7.010900 -3.620531 +v -3.823353 7.527450 -3.620531 +v -3.823353 7.010900 -3.686659 +v -3.823353 7.527450 -3.686659 +v -3.776275 7.010900 -3.686659 +v -3.776275 7.527450 -3.686659 +v -4.282917 7.010900 -3.620531 +v -4.282917 7.527450 -3.620531 +v -4.329995 7.010900 -3.620531 +v -4.329996 7.527450 -3.620531 +v -4.329995 7.010900 -3.686659 +v -4.329996 7.527450 -3.686659 +v -4.282917 7.010900 -3.686659 +v -4.282917 7.527450 -3.686659 +v -4.789560 7.010900 -3.620531 +v -4.789560 7.527450 -3.620531 +v -4.836637 7.010900 -3.620531 +v -4.836638 7.527450 -3.620531 +v -4.836637 7.010900 -3.686659 +v -4.836638 7.527450 -3.686659 +v -4.789560 7.010900 -3.686659 +v -4.789560 7.527450 -3.686659 +v -5.296202 7.010900 -3.620531 +v -5.296202 7.527450 -3.620531 +v -5.343279 7.010900 -3.620531 +v -5.343280 7.527450 -3.620531 +v -5.343279 7.010900 -3.686659 +v -5.343280 7.527450 -3.686659 +v -5.296202 7.010900 -3.686659 +v -5.296202 7.527450 -3.686659 +v -5.287740 7.522141 4.746301 +v 5.297492 7.522141 4.746301 +v -5.287740 7.586403 4.746301 +v 5.297492 7.586403 4.746301 +v 5.400997 7.586403 4.851665 +v -5.413006 7.586403 4.851665 +v -5.287740 7.522140 -3.598670 +v 5.297492 7.522140 -3.598670 +v -5.287740 7.586402 -3.598670 +v 5.297492 7.586402 -3.598670 +v 5.400997 7.586402 -3.703695 +v -5.413006 7.586402 -3.703695 +v -5.413006 7.522140 -3.703695 +v -5.413006 7.522141 4.851665 +v 5.400997 7.522141 4.851665 +v 5.400997 7.522140 -3.703695 +v -5.304326 6.321735 4.667395 +v 5.304325 6.321735 4.667395 +v -5.201069 6.779107 4.653073 +v 5.201069 6.779107 4.653073 +v -5.201069 7.010900 4.653073 +v 5.201069 7.010900 4.653073 +v 5.483452 7.010900 4.941982 +v -5.483453 7.010900 4.941982 +v -5.304326 6.321735 -3.534409 +v 5.304325 6.321735 -3.534409 +v -5.201069 6.779106 -3.520086 +v 5.201069 6.779106 -3.520086 +v -5.201069 7.010900 -3.520086 +v 5.201069 7.010900 -3.520086 +v 5.483452 7.010900 -3.808995 +v -5.483453 7.010900 -3.808995 +v -5.483453 6.916430 -3.808995 +v -5.483453 6.916431 4.941982 +v 5.483452 6.916431 4.941982 +v 5.483452 6.916430 -3.808995 +v -5.404641 6.916430 -3.737515 +v -5.404641 6.916431 4.870502 +v 5.404641 6.916431 4.870502 +v 5.404641 6.916430 -3.737515 +v 4.949667 6.779107 4.432048 +v 4.949667 6.779106 -3.299062 +v -4.949667 6.779106 -3.299062 +v -4.949667 6.779107 4.432048 +v 4.901502 6.727391 4.388181 +v 4.901502 6.727391 -3.255194 +v -4.901503 6.727391 -3.255194 +v -4.901503 6.727391 4.388181 +v -5.304326 6.398671 4.667395 +v 5.304325 6.398671 4.667395 +v 5.304325 6.398671 -3.534408 +v -5.304326 6.398671 -3.534408 +v 5.364899 6.434315 -3.657051 +v 5.404641 6.457701 4.870503 +v -5.404641 6.457701 4.870503 +v -5.404641 6.457700 -3.737515 +v 5.201069 6.779106 1.293623 +v 4.949667 6.779106 1.293623 +v 4.901502 6.727391 1.293623 +v -4.901503 6.727391 0.902070 +v -4.949667 6.779106 0.902070 +v -5.201069 6.779106 0.902070 +v -5.201069 7.010900 0.834373 +v -5.483453 7.010900 0.834373 +v -5.483453 6.916430 0.834373 +v -5.404641 6.916430 0.834373 +v -5.404641 6.457700 0.834374 +v -5.304326 6.398671 0.902070 +v -5.304326 6.321735 0.902070 +v 5.304325 6.321735 1.293623 +v 5.304325 6.398671 1.293623 +v 5.404641 6.457700 1.293623 +v 5.404641 6.916430 1.293623 +v 5.483452 6.916430 1.293623 +v 5.483452 7.010900 1.293623 +v 5.201069 7.010900 1.293623 +v -5.304326 6.321735 1.685177 +v -5.304326 6.398671 1.685177 +v -5.404641 6.457700 1.752874 +v -5.404641 6.916430 1.752874 +v -5.483453 6.916430 1.752873 +v -5.483453 7.010900 1.752873 +v -5.201069 7.010900 1.752874 +v -5.201069 6.779107 1.685177 +v -4.949667 6.779107 1.685177 +v -4.901503 6.727391 1.685177 +v -5.302855 6.734300 0.902070 +v -5.302855 6.734300 1.685177 +v -5.413006 7.522140 1.026057 +v -5.413006 7.586403 1.090318 +v -5.287740 7.586403 1.090318 +v -5.287740 7.522140 1.026057 +v -5.413006 7.522140 1.593336 +v -5.413006 7.586403 1.529073 +v -5.287740 7.586403 1.529073 +v -5.287740 7.522140 1.593336 +v -5.201069 6.916430 0.834373 +v -5.201069 6.916430 1.752874 +v 5.183062 6.321735 1.220675 +v -5.183062 6.321735 1.601893 +v -5.183062 6.321735 0.839458 +v -5.183062 6.321735 -3.335493 +v 5.183062 6.321735 -3.335493 +v -5.183062 6.321735 4.505395 +v 5.183062 6.321735 4.505395 +v -3.795972 7.340625 4.806005 +v -3.748894 7.340625 4.806005 +v -3.748894 7.340625 4.739880 +v -3.795972 7.340625 4.739880 +v -0.305199 7.202352 4.787436 +v -0.305199 7.202352 4.853564 +v -0.258121 7.202352 4.853564 +v -0.258121 7.202352 4.787436 +v 2.837456 7.374579 4.739880 +v 2.790378 7.374579 4.739880 +v 2.790378 7.374579 4.806005 +v 2.837456 7.374579 4.806005 +v 5.346174 7.226153 4.307058 +v 5.412302 7.226153 4.307058 +v 5.412302 7.226153 4.261296 +v 5.346174 7.226153 4.261296 +v 5.308817 7.425541 1.746163 +v 5.308817 7.425541 1.791927 +v 5.374945 7.425541 1.791927 +v 5.374945 7.425541 1.746163 +v 5.290658 7.203070 -2.617259 +v 5.356784 7.203070 -2.617259 +v 5.356784 7.203070 -2.663023 +v 5.290658 7.203070 -2.663023 +v 3.808212 7.372484 -3.671466 +v 3.761135 7.372484 -3.671466 +v 3.761135 7.372484 -3.605338 +v 3.808212 7.372484 -3.605338 +v 1.311147 7.165864 -3.719279 +v 1.264069 7.165864 -3.719279 +v 1.264069 7.165864 -3.653151 +v 1.311147 7.165864 -3.653151 +v -2.786102 7.363735 -3.630520 +v -2.786102 7.363735 -3.696648 +v -2.833180 7.363735 -3.696648 +v -2.833180 7.363735 -3.630520 +v -5.272075 7.295649 -2.164279 +v -5.272075 7.295649 -2.210044 +v -5.338202 7.295649 -2.210044 +v -5.338202 7.295649 -2.164279 +v -5.339547 7.413024 -0.150630 +v -5.339547 7.413024 -0.196396 +v -5.405675 7.413024 -0.196396 +v -5.405675 7.413024 -0.150630 +v -5.295941 7.189904 2.827558 +v -5.295941 7.189904 2.781793 +v -5.362069 7.189904 2.781793 +v -5.362069 7.189904 2.827558 +v -2.301678 7.586403 4.746301 +v -2.380786 7.586403 4.851665 +v -2.380786 7.522141 4.851665 +v -2.301678 7.522141 4.746301 +v -1.707457 7.492457 4.851665 +v -1.707457 7.539046 4.851665 +v -1.660583 7.539046 4.746301 +v -1.660583 7.492457 4.746301 +v -0.189916 7.522141 4.851665 +v -0.189916 7.586403 4.851665 +v -0.175145 7.586403 4.746301 +v -0.175145 7.522141 4.746301 +v 5.297492 7.586403 3.581967 +v 5.400997 7.586403 3.657978 +v 5.400997 7.522141 3.657978 +v 5.297492 7.522141 3.581967 +v 5.400997 7.539045 3.085398 +v 5.297492 7.539045 3.023469 +v 5.297492 7.492456 3.023469 +v 5.400997 7.492456 3.085398 +v 5.400997 7.522140 2.528519 +v 5.400997 7.586403 2.528519 +v 5.297492 7.586403 2.480284 +v 5.297492 7.522140 2.480284 +v 3.970845 7.522139 -3.703696 +v 3.970845 7.586402 -3.703696 +v 3.897594 7.586402 -3.598670 +v 3.897594 7.522140 -3.598670 +v 2.921590 7.539045 -3.703696 +v 2.870536 7.539045 -3.598670 +v 2.870536 7.492456 -3.598670 +v 2.921590 7.492456 -3.703696 +v 2.187087 7.586402 -3.703696 +v 2.151571 7.586402 -3.598670 +v 2.151571 7.522140 -3.598670 +v 2.187091 7.522140 -3.703696 +v -2.606495 7.522140 -3.703695 +v -2.606497 7.586402 -3.703695 +v -2.540604 7.586402 -3.598670 +v -2.540604 7.522140 -3.598670 +v -3.265107 7.492455 -3.703696 +v -3.265109 7.539045 -3.703695 +v -3.185282 7.539045 -3.598670 +v -3.185282 7.492456 -3.598670 +v -3.899536 7.522140 -3.598670 +v -3.994798 7.522139 -3.703696 +v -3.994798 7.586402 -3.703695 +v -3.899536 7.586402 -3.598670 +v -5.287740 7.586403 0.237437 +v -5.413006 7.586403 0.218335 +v -5.413006 7.522140 0.165761 +v -5.287740 7.522140 0.184864 +v -5.287740 7.586403 -1.126921 +v -5.413006 7.586403 -1.176582 +v -5.413006 7.522140 -1.210457 +v -5.287740 7.522140 -1.160795 +v -5.413006 7.492456 -0.651805 +v -5.413006 7.539045 -0.610340 +v -5.287740 7.539045 -0.573083 +v -5.287740 7.492456 -0.614549 +v -4.238533 7.010900 4.941982 +v -3.576001 7.010900 4.941982 +v -3.977441 7.010900 4.818838 +v -3.981600 6.964285 4.941982 +v -3.287679 7.010900 4.653073 +v -2.516537 7.010900 4.653073 +v -2.956492 7.010900 4.726183 +v -2.980420 6.927682 4.653073 +v 1.389091 6.457701 4.870503 +v -0.237167 6.457701 4.870503 +v 0.379203 6.560380 4.870502 +v 0.871623 6.554255 4.870502 +v 0.571617 6.426082 4.761709 +v 2.401178 6.457701 4.870503 +v 1.800202 6.457701 4.870503 +v 2.097049 6.539375 4.870502 +v 2.085422 6.432156 4.782610 +v 5.435837 7.010900 4.893269 +v 5.483452 7.010900 4.828276 +v 5.483452 6.948892 4.941982 +v 5.400147 7.010900 4.941982 +v 5.483452 7.010900 2.249184 +v 5.483452 7.010900 1.725660 +v 5.395040 7.010900 2.002146 +v 5.483452 6.951154 2.008894 +v 5.404641 6.457700 -3.070528 +v 5.404641 6.573779 -3.737515 +v 4.887590 6.457700 -3.737515 +v 1.537166 7.010900 -3.808995 +v 2.385378 7.010900 -3.808995 +v 2.004467 7.010900 -3.696868 +v 2.006238 6.957960 -3.808995 +v 0.409720 7.010900 -3.520086 +v 1.198191 7.010900 -3.520086 +v 0.972678 7.010900 -3.592000 +v 0.959525 6.913384 -3.520086 +v -5.483453 7.010900 0.716511 +v -5.483453 7.010900 -0.110891 +v -5.389662 7.010900 0.385425 +v -5.483453 6.963934 0.430811 +v -5.483453 6.916430 -0.732388 +v -5.483453 6.916430 -0.169472 +v -5.404641 6.916430 -0.432954 +v -5.483453 6.961850 -0.445944 +v -5.201069 7.010900 -2.695556 +v -5.201069 7.010900 -2.142366 +v -5.293396 7.010900 -2.421228 +v -5.201069 6.944556 -2.389034 +v -1.883293 5.737078 -3.469517 +v -0.659111 5.737078 -3.469498 +v -1.896583 5.211138 -3.469517 +v -0.656548 4.043475 -3.469496 +v -1.883293 3.398328 -3.141367 +v -1.883293 3.398328 -3.469517 +v -0.659111 3.398328 -3.469498 +v -0.659111 3.398328 -3.141442 +v -1.795295 5.211138 -3.469519 +v -0.757836 4.043475 -3.414341 +v -0.752007 5.669146 -3.469512 +v -1.784279 5.655794 -3.469517 +v -1.784279 3.442298 -3.469517 +v -0.758141 3.429796 -3.469509 +v -1.795295 5.211138 -3.141370 +v -0.757836 4.043475 -3.141455 +v -0.758141 5.655794 -3.141458 +v -1.784280 5.655794 -3.141367 +v -1.784280 3.442298 -3.141367 +v -0.758141 3.442298 -3.141458 +v -0.730023 4.043475 -3.469498 +v -0.757836 4.233873 -3.469512 +v -0.757836 3.826784 -3.469512 +v -1.896584 5.211138 -3.141367 +v -1.883293 5.737078 -3.141367 +v -0.659111 5.737078 -3.141442 +v -0.656547 4.043475 -3.141444 +v 0.616704 2.730380 -3.469501 +v 1.840886 2.730380 -3.469496 +v 0.603413 2.204440 -3.469501 +v 1.843450 1.036777 -3.469493 +v 0.616704 0.391630 -3.141351 +v 0.616704 0.391630 -3.469500 +v 1.840886 0.391630 -3.469496 +v 1.840886 0.391630 -3.141439 +v 0.587422 0.253709 -3.257450 +v 1.870153 0.253709 -3.257538 +v 1.856282 0.253709 -3.565514 +v 0.587422 0.253709 -3.576175 +v 0.587422 0.346811 -3.576175 +v 0.587422 0.371655 -3.257450 +v 1.870153 0.350202 -3.576161 +v 1.870153 0.371655 -3.257538 +v 0.704702 2.204440 -3.469503 +v 1.742162 1.036777 -3.414325 +v 1.747991 2.662448 -3.469496 +v 0.715718 2.649096 -3.469501 +v 0.715718 0.435601 -3.469500 +v 1.741857 0.423099 -3.469493 +v 0.704701 2.204440 -3.141354 +v 1.742162 1.036777 -3.141439 +v 1.741857 2.649096 -3.141442 +v 0.715718 2.649096 -3.141351 +v 0.715718 0.435601 -3.141351 +v 1.741857 0.435601 -3.141441 +v 1.769974 1.036777 -3.469496 +v 1.742162 1.227176 -3.469496 +v 1.742162 0.820086 -3.469496 +v 1.638455 0.369325 -3.576161 +v 1.870153 0.313029 -3.576161 +v 1.782278 0.253709 -3.576161 +v 1.870153 0.253709 -3.520511 +v 0.603413 2.204440 -3.141351 +v 0.616704 2.730380 -3.141351 +v 1.840886 2.730380 -3.141439 +v 1.843450 1.036777 -3.141441 +v 1.905419 0.057462 -3.770116 +v 1.905698 0.220488 -3.770113 +v 1.905698 0.263079 -3.364308 +v 0.559410 0.290785 -3.353463 +v 0.558440 0.057462 -3.746788 +v 1.160065 0.275450 -3.356407 +v 1.163016 0.244978 -3.759938 +v 1.162888 0.057462 -3.759938 +v 0.558440 0.057462 -3.353463 +v 1.905419 0.057462 -3.364310 +v 0.660030 0.244978 -3.749015 +v 0.557732 0.156670 -3.746790 +v 0.557708 0.250108 -3.699198 +v 1.844260 0.244978 -3.739134 +v 1.868193 0.276969 -3.363909 +v -0.616704 2.730381 4.600784 +v -1.840886 2.730381 4.600779 +v -0.603413 2.204441 4.600784 +v -1.843450 1.036777 4.600776 +v -0.616704 0.391630 4.272635 +v -0.616704 0.391630 4.600784 +v -1.840886 0.391630 4.600779 +v -1.840886 0.391630 4.272722 +v -0.587422 0.253710 4.388733 +v -1.870153 0.253710 4.388821 +v -1.856282 0.253710 4.696797 +v -0.587422 0.253710 4.707458 +v -0.587422 0.346812 4.707458 +v -0.587422 0.371655 4.388733 +v -1.870153 0.350203 4.707444 +v -1.870153 0.371655 4.388821 +v -0.704702 2.204441 4.600786 +v -1.742162 1.036777 4.545608 +v -1.747991 2.662448 4.600779 +v -0.715718 2.649097 4.600784 +v -0.715718 0.435601 4.600784 +v -1.741857 0.423099 4.600776 +v -0.704701 2.204441 4.272637 +v -1.742162 1.036777 4.272722 +v -1.741857 2.649097 4.272725 +v -0.715718 2.649097 4.272635 +v -0.715718 0.435601 4.272635 +v -1.741857 0.435601 4.272725 +v -1.769974 1.036777 4.600779 +v -1.742162 1.227176 4.600779 +v -1.742162 0.820087 4.600779 +v -1.638455 0.369325 4.707444 +v -1.870153 0.313030 4.707444 +v -1.782278 0.253710 4.707444 +v -1.870153 0.253710 4.651794 +v -0.603413 2.204441 4.272635 +v -0.616704 2.730381 4.272635 +v -1.840886 2.730381 4.272722 +v -1.843450 1.036777 4.272725 +v -1.905419 0.057463 4.901402 +v -1.905698 0.220489 4.901396 +v -1.905698 0.263079 4.495591 +v -0.559410 0.290786 4.484746 +v -0.558440 0.057463 4.878072 +v -1.160065 0.275451 4.487690 +v -1.163016 0.244979 4.891221 +v -1.162888 0.057463 4.891221 +v -0.558440 0.057462 4.484746 +v -1.905419 0.057462 4.495594 +v -0.660030 0.244979 4.880298 +v -0.557732 0.156671 4.878077 +v -0.557708 0.250108 4.830483 +v -1.844260 0.244979 4.870420 +v -1.868193 0.276970 4.495193 +v -2.291038 3.010788 5.222182 +v -0.173674 3.010788 5.222182 +v -2.291038 3.201726 5.222182 +v -0.173674 3.201726 5.222182 +v -2.291038 3.201726 4.515635 +v -0.173674 3.201726 4.515635 +v -2.291038 3.010788 4.515635 +v -0.173674 3.010788 4.515635 +v -5.199997 0.321734 -3.384367 +v -5.199995 0.321735 -0.684365 +v -5.199997 3.321735 -0.684365 +v -5.199997 3.321734 -3.384365 +v -4.999998 3.321735 -0.684365 +v -4.999998 0.421735 -0.684365 +v -4.999998 0.421734 -3.184365 +v -4.999998 3.321734 -3.184365 +v -5.199995 0.321735 1.815635 +v -5.199997 3.321735 1.815635 +v -4.999998 3.321735 1.815635 +v -4.999998 0.421735 1.815635 +v 5.000001 1.855671 -2.146430 +v 3.675001 1.855671 -2.146430 +v 5.000001 2.608652 -1.316091 +v 3.675001 3.331519 -0.684351 +v 5.000001 2.229017 -1.731261 +v 5.000001 3.206505 -0.715398 +v 5.000001 2.804150 -1.108508 +v 5.000001 2.416941 -1.523677 +v 5.000001 2.044881 -1.938844 +v 5.000001 3.195636 -0.891936 +v 5.000001 2.796904 -1.307104 +v 5.000001 2.413318 -1.722273 +v 5.000001 2.044881 -2.146430 +v 5.000001 3.421735 -0.715398 +v 5.000001 2.603218 -1.514689 +v 5.000001 2.227206 -1.929858 +v 3.675001 0.782434 -0.900923 +v 3.675001 1.684181 -1.938846 +v 3.675001 0.602084 -0.684352 +v 3.675001 1.684181 -2.137442 +v 3.675001 0.602084 -0.891937 +v 3.675001 0.962784 -1.108509 +v 3.675001 1.143134 -1.316092 +v 3.675001 1.323483 -1.523677 +v 3.675001 1.503833 -1.731262 +v 3.675001 1.503832 -1.929858 +v 3.675001 1.323483 -1.722273 +v 3.675001 1.143133 -1.514691 +v 3.675001 0.962784 -1.307105 +v 3.675001 0.782434 -1.099521 +v 3.825001 2.044881 -2.146430 +v 3.825001 2.044881 -1.938844 +v 3.825001 2.227206 -1.929858 +v 3.825001 2.229017 -1.731261 +v 3.825001 2.413318 -1.722273 +v 3.825001 2.416941 -1.523677 +v 3.825001 2.603218 -1.514689 +v 3.825001 2.608652 -1.316091 +v 3.825001 2.796904 -1.307104 +v 3.825001 2.804150 -1.108508 +v 3.825001 2.994377 -1.099520 +v 3.825001 3.003434 -0.900923 +v 3.825001 3.195636 -0.891936 +v 3.825001 3.206505 -0.715398 +v 3.825001 3.421735 -0.715398 +v 3.825001 0.421735 -0.684352 +v 3.825001 3.331519 -0.684353 +v 3.825001 6.321734 -0.684352 +v 3.675001 4.642562 -2.144933 +v 3.825001 4.642562 -2.144183 +v 5.000001 3.331519 -0.684351 +v 2.500001 0.421735 -0.684352 +v 2.500001 1.855671 -3.184352 +v 5.000001 1.855671 -3.184352 +v 2.500001 1.143133 -1.514691 +v 2.500001 0.782434 -1.099521 +v 2.500001 1.503833 -1.929858 +v 2.500001 1.684181 -2.137442 +v 2.500001 1.323483 -1.722273 +v 2.500001 0.962783 -1.307105 +v 2.500001 0.602084 -0.891937 +v 2.500001 1.684181 -1.938846 +v 2.500001 1.323483 -1.523677 +v 2.500001 0.962783 -1.108509 +v 2.500001 0.602084 -0.684352 +v 2.500001 1.855671 -2.146430 +v 2.500001 1.143134 -1.316092 +v 2.500001 0.782434 -0.900923 +v 2.500001 1.503833 -1.731262 +v 5.000000 0.421735 -0.684352 +v 2.500001 4.642562 -2.146430 +v 2.500002 3.321735 -0.684352 +v 5.000000 6.321734 -0.684352 +v 5.000001 4.642562 -2.146430 +v 5.000001 4.642562 -3.184352 +v 2.500001 4.642562 -3.184352 +v 5.000000 3.421735 -0.684352 +v 3.825001 3.421735 -0.684352 +v 5.000001 3.003434 -0.900923 +v 5.000001 3.003434 -1.108508 +v 2.385719 3.421735 -0.684352 +v 2.385719 6.321734 -0.684352 +v 3.675001 0.421735 -0.684352 +v 3.825001 1.855671 -2.146430 +v 2.500000 0.421734 -3.184351 +v 2.385719 6.321734 -3.184353 +v 2.385719 3.421734 -3.184352 +v 2.500002 3.321734 -3.184352 +v 0.718986 5.700859 -3.184352 +v 1.781025 5.700859 -3.184352 +v 0.718986 4.009157 -3.184352 +v 1.781025 4.009157 -3.184352 +v 0.000002 6.321734 -3.184352 +v 0.000005 3.421734 -3.184352 +v -2.499999 6.321734 -3.384368 +v -0.735967 5.705902 -3.384354 +v -1.799316 5.705902 -3.384368 +v -0.000002 6.321734 -3.384354 +v 0.000000 3.321734 -3.384353 +v -0.735969 3.321734 -3.384354 +v -2.499995 3.321734 -3.384365 +v -1.800984 3.321734 -3.384368 +v -2.499999 6.321734 -3.184366 +v -2.499999 3.421734 -3.184365 +v -0.735969 3.421734 -3.184354 +v -1.800984 3.421734 -3.184368 +v -1.799316 5.705902 -3.184368 +v -0.735967 5.705902 -3.184354 +v 1.781014 4.009157 -3.384354 +v 0.718977 4.009157 -3.384354 +v 1.781019 5.700859 -3.384354 +v 0.718977 5.700859 -3.384354 +v 2.499994 6.321734 -3.384354 +v 2.499998 3.321734 -3.384353 +v 5.000000 3.321735 -0.684352 +v 4.999998 3.321734 -3.184352 +v 2.500002 3.321735 1.815635 +v 5.000000 3.321735 1.815635 +v 2.500002 3.321735 4.315635 +v 4.999999 3.321735 4.315635 +v 0.000002 3.321735 -0.684365 +v 0.000002 3.321734 -3.184352 +v 0.000002 3.321735 1.815635 +v 0.000002 3.321735 4.315635 +v -2.499998 3.321735 -0.684365 +v -2.499998 3.321734 -3.184365 +v -2.499998 3.321735 1.815635 +v -2.499998 3.321735 4.315635 +v -4.999998 3.321735 4.315635 +v 4.999998 6.321734 -3.184352 +v 2.500002 6.321734 1.815634 +v 5.000000 6.321734 1.815634 +v 2.500002 6.321734 4.315635 +v 5.000000 6.321734 4.315635 +v 0.000002 6.321734 -0.684365 +v 0.000002 6.321734 1.815634 +v 0.000002 6.321734 4.315635 +v -2.499998 6.321734 -0.684365 +v -2.499998 6.321734 1.815634 +v -2.499998 6.321734 4.315635 +v -4.999998 6.321734 -0.684365 +v -4.999998 6.321734 -3.184366 +v -4.999998 6.321734 1.815634 +v -4.999998 6.321734 4.315635 +v -4.999998 0.421735 4.315635 +v -5.199997 3.321735 4.515635 +v -5.199997 0.321735 4.515635 +v -5.362224 0.279648 1.888504 +v -5.362224 0.279648 4.675467 +v -5.362224 0.057462 1.888504 +v -5.362224 0.057462 4.675467 +v -2.499996 3.321735 4.515635 +v -2.499996 0.321735 4.515635 +v 0.000002 3.321735 4.515635 +v 0.000002 0.321735 4.515635 +v -1.764031 2.705902 4.515635 +v -1.764027 0.421735 4.515635 +v -0.699012 0.421735 4.515635 +v -0.700681 2.705902 4.515635 +v -2.611417 0.279648 4.675467 +v 0.000000 0.279648 4.675467 +v -2.611417 0.057462 4.675467 +v 0.000000 0.057462 4.675467 +v -1.232649 0.321735 4.515635 +v -1.315228 0.279648 4.675467 +v -1.528828 0.057462 4.675467 +v -2.499996 0.421735 4.315635 +v 0.000004 0.421735 4.315635 +v -1.764027 0.421735 4.315635 +v -0.699012 0.421735 4.315635 +v -0.700681 2.705902 4.315635 +v -1.764031 2.705902 4.315635 +v -4.281013 1.009157 4.515635 +v -3.218977 1.009157 4.515635 +v -4.281021 2.700860 4.515635 +v -3.218977 2.700860 4.515635 +v -3.437910 0.279648 4.675467 +v -3.306669 0.324558 4.515635 +v -3.218976 2.700860 4.315635 +v -4.281018 2.700860 4.315635 +v -3.218976 1.009157 4.315635 +v -4.281018 1.009157 4.315635 +v 2.500000 0.321735 4.515635 +v 2.611415 0.279648 4.675467 +v 2.611415 0.057462 4.675467 +v 2.500002 3.321735 4.515635 +v 0.718984 1.009157 4.515635 +v 1.781023 1.009157 4.515635 +v 0.718979 2.700860 4.515635 +v 1.781023 2.700860 4.515635 +v 1.693330 0.324558 4.515635 +v 1.784927 0.279648 4.675467 +v 1.833303 0.057462 4.675467 +v 2.500002 0.421735 4.315635 +v 1.781023 2.700860 4.315635 +v 0.718982 2.700860 4.315635 +v 1.781023 1.009157 4.315635 +v 0.718982 1.009157 4.315635 +v 5.199993 0.321735 4.515635 +v 5.362222 0.279648 4.675467 +v 5.362222 0.057462 4.675467 +v 5.199995 3.321735 4.515635 +v 3.218979 1.009157 4.515635 +v 4.281018 1.009157 4.515635 +v 3.218975 2.700860 4.515635 +v 4.281018 2.700860 4.515635 +v 4.193325 0.324558 4.515635 +v 4.396340 0.279648 4.675467 +v 4.328950 0.057462 4.675467 +v 4.999998 0.421735 4.315635 +v 4.281018 2.700860 4.315635 +v 3.218977 2.700860 4.315635 +v 4.281018 1.009157 4.315635 +v 3.218977 1.009157 4.315635 +v -2.499996 6.321734 4.515635 +v -5.199997 6.321734 4.515635 +v -4.281015 4.009157 4.515635 +v -3.218977 4.009157 4.515635 +v -4.281021 5.700860 4.515635 +v -3.218977 5.700860 4.515635 +v -4.999998 3.421735 4.315635 +v -2.499998 3.421735 4.315635 +v -3.218976 5.700860 4.315635 +v -4.281018 5.700860 4.315635 +v -3.218976 4.009157 4.315635 +v -4.281018 4.009157 4.315635 +v 0.000002 6.321734 4.515635 +v -1.781014 4.009157 4.515635 +v -0.718977 4.009157 4.515635 +v -1.781019 5.700860 4.515635 +v -0.718977 5.700860 4.515635 +v 0.000004 3.421735 4.315635 +v -0.718977 5.700860 4.315635 +v -1.781017 5.700860 4.315635 +v -0.718977 4.009157 4.315635 +v -1.781017 4.009157 4.315635 +v 2.500002 6.321734 4.515635 +v 0.718984 4.009157 4.515635 +v 1.781023 4.009157 4.515635 +v 0.718979 5.700860 4.515635 +v 1.781023 5.700860 4.515635 +v 2.500002 3.421735 4.315635 +v 1.781023 5.700860 4.315635 +v 0.718982 5.700860 4.315635 +v 1.781023 4.009157 4.315635 +v 0.718982 4.009157 4.315635 +v 5.199996 6.321734 4.515635 +v 3.218984 4.009157 4.515635 +v 4.281023 4.009157 4.515635 +v 3.218979 5.700860 4.515635 +v 4.281023 5.700860 4.515635 +v 4.999999 3.421735 4.315635 +v 4.281023 5.700860 4.315635 +v 3.218982 5.700860 4.315635 +v 4.281023 4.009157 4.315635 +v 3.218982 4.009157 4.315635 +v -5.362224 0.279647 -3.544194 +v -5.362224 0.279648 -0.757234 +v -5.362224 0.057462 -3.544194 +v -5.362224 0.057462 -0.757234 +v -5.199997 6.321734 -0.684365 +v -5.199997 6.321734 -3.384365 +v -5.199997 4.009157 -2.465383 +v -5.199997 4.009157 -1.403345 +v -5.199997 5.700859 -2.465389 +v -5.199997 5.700859 -1.403345 +v -4.999998 3.421734 -3.184365 +v -4.999998 3.421735 -0.684365 +v -4.999998 5.700859 -1.403345 +v -4.999998 5.700859 -2.465386 +v -4.999998 4.009157 -1.403345 +v -4.999998 4.009157 -2.465386 +v 5.199993 0.321735 1.815635 +v 5.362220 0.279648 1.888508 +v 5.362220 0.057462 1.888508 +v 5.199994 3.321735 1.815635 +v 5.199994 1.009157 3.596653 +v 5.199994 1.009157 2.534614 +v 5.199994 2.700860 3.596658 +v 5.199994 2.700860 2.534614 +v 5.199994 0.324558 2.622307 +v 5.362222 0.279648 2.725862 +v 5.362222 0.057462 2.670884 +v 4.999998 0.421735 1.815635 +v 4.999994 2.700860 2.534614 +v 4.999994 2.700860 3.596655 +v 4.999994 1.009157 2.534614 +v 4.999994 1.009157 3.596655 +v 5.199995 3.321735 -0.684352 +v 5.199993 0.321735 -0.684353 +v 5.362220 0.279648 -0.757218 +v 5.362220 0.057462 -0.757218 +v -5.199997 6.321734 1.815634 +v -4.999998 3.421735 1.815635 +v 5.199995 6.321734 1.815634 +v 4.999999 3.421735 1.815635 +v 5.199995 0.321734 -3.384351 +v 5.362222 0.279647 -3.544182 +v 5.362222 0.057462 -3.544182 +v 5.199995 3.321734 -3.384352 +v 4.999998 0.421734 -3.184351 +v 5.199995 6.321734 -0.684352 +v 5.199995 4.009157 1.096653 +v 5.199995 4.009157 0.034614 +v 5.199995 5.700859 1.096658 +v 5.199995 5.700859 0.034614 +v 4.999994 5.700859 0.034614 +v 4.999995 5.700859 1.096655 +v 4.999994 4.009157 0.034614 +v 4.999995 4.009157 1.096655 +v 5.199995 6.321734 -3.384352 +v 4.999998 3.421734 -3.184352 +v 2.500000 0.321734 -3.384351 +v 2.611416 0.279647 -3.544182 +v 2.611416 0.057462 -3.544182 +v 3.732646 0.321734 -3.384351 +v 3.926643 0.279647 -3.544182 +v 4.140243 0.057462 -3.544182 +v -2.499998 0.421734 -3.184365 +v -2.499996 0.321734 -3.384365 +v -2.611416 0.279647 -3.544194 +v -2.611416 0.057462 -3.544194 +v 0.000002 0.421734 -3.184351 +v 0.000001 0.321734 -3.384351 +v 0.000000 0.279647 -3.544182 +v 0.000000 0.057462 -3.544182 +v 1.764023 3.421734 -3.384354 +v 0.699009 3.421734 -3.384354 +v -2.499998 3.421735 -0.684365 +v 0.000002 3.421735 -0.684365 +v -2.499998 3.421735 1.815635 +v 0.000002 3.421735 1.815635 +v 2.500001 3.421735 1.815635 +v -2.499998 0.421735 -0.684365 +v 0.000002 0.421735 -0.684365 +v -2.499998 0.421735 1.815635 +v 0.000002 0.421735 1.815635 +v 2.500001 0.421735 1.815635 +v 1.764031 2.705902 -3.384352 +v 1.764027 0.421734 -3.384351 +v 0.699012 0.421734 -3.384351 +v 0.700681 2.705902 -3.384352 +v 1.232649 0.321734 -3.384351 +v 1.764027 0.421734 -3.184351 +v 0.699012 0.421734 -3.184351 +v 0.700681 2.705902 -3.184352 +v 1.764031 2.705902 -3.184352 +v -5.022524 3.001347 -3.384368 +v 5.022524 3.001347 -3.384354 +v -5.022524 3.001347 -5.222186 +v 5.022524 3.001347 -5.222173 +v -4.833345 3.421734 -3.384368 +v 4.833345 3.421734 -3.384354 +v -4.833345 3.421734 -5.004756 +v 4.833345 3.421734 -5.004743 +v -4.833345 4.183304 -5.004756 +v 4.833345 4.183304 -5.004743 +v 5.022524 4.183304 -5.222173 +v -5.022524 4.183304 -5.222186 +v -5.022524 4.183304 -3.384368 +v -4.833345 4.183304 -3.384368 +v 4.833345 4.183304 -3.384354 +v 5.022524 4.183304 -3.384354 +v 0.000000 3.001347 -3.384354 +v 0.000000 3.001347 -5.222173 +v 0.000000 4.183304 -5.222173 +v 0.000000 4.183304 -5.004743 +v 0.000000 3.421734 -5.004743 +v 0.000000 3.421734 -3.384354 +v -1.329814 0.057462 3.103345 +v -2.226382 0.057462 -1.713584 +v 2.917582 0.057462 -1.713570 +v 2.766904 0.057462 2.776844 +v 5.000001 2.759566 -3.184365 +v 5.000001 2.802798 -3.184365 +v 4.930929 2.802798 -3.115293 +v 4.930929 2.759566 -3.115293 +v 2.675447 2.759566 -3.115293 +v 2.506883 2.760445 -3.184365 +v 2.675447 2.802798 -3.115293 +v 2.506883 2.802798 -3.184365 +v 5.000001 2.768427 -2.227548 +v 5.000001 2.810779 -2.247510 +v 4.930929 2.810779 -2.247510 +v 4.930929 2.768427 -2.227548 +v 4.930929 3.191229 -1.750784 +v 5.000001 3.191229 -1.750784 +v 5.000001 3.148876 -1.730818 +v 4.930929 3.148876 -1.730818 +v 5.000001 4.024854 -0.707108 +v 4.921729 4.024598 -0.707108 +v 5.000001 3.981406 -0.707108 +v 4.921802 3.980256 -0.707108 +v 2.572527 1.963308 -2.772471 +v 2.572527 1.963308 -2.722990 +v 2.572527 2.760446 -2.772471 +v 2.572527 2.760446 -2.722990 +v 2.629747 2.760446 -2.772471 +v 2.629747 2.760446 -2.722990 +v 2.629747 1.963308 -2.772471 +v 2.629747 1.963308 -2.722990 +v 2.572527 1.963308 -3.069148 +v 2.572527 1.963308 -3.019668 +v 2.572527 2.760445 -3.069148 +v 2.572527 2.760445 -3.019668 +v 2.629747 2.760445 -3.069148 +v 2.629747 2.760445 -3.019668 +v 2.629747 1.963308 -3.069148 +v 2.629747 1.963308 -3.019668 +v 2.572527 1.963308 -2.482250 +v 2.572527 1.963308 -2.432769 +v 2.572527 2.760446 -2.482250 +v 2.572527 2.760446 -2.432769 +v 2.629747 2.760446 -2.482250 +v 2.629747 2.760446 -2.432769 +v 2.629747 1.963308 -2.482250 +v 2.629747 1.963308 -2.432769 +v 2.515531 1.920761 -3.184365 +v 2.515531 1.963308 -3.184365 +v 2.675382 1.963308 -3.184365 +v 2.675382 1.920761 -3.184365 +v 2.572527 1.291812 -1.463298 +v 2.572527 1.273700 -1.413818 +v 2.572527 2.114810 -1.463298 +v 2.572527 2.079700 -1.413818 +v 2.629747 2.114810 -1.463298 +v 2.629747 2.079700 -1.413818 +v 2.629747 1.291812 -1.463298 +v 2.629747 1.273700 -1.413818 +v 2.572527 1.500278 -1.722715 +v 2.572527 1.474378 -1.673234 +v 2.572527 2.325665 -1.722715 +v 2.572527 2.290546 -1.673236 +v 2.629747 2.325665 -1.722715 +v 2.629747 2.290546 -1.673236 +v 2.629747 1.500278 -1.722715 +v 2.629747 1.474378 -1.673234 +v 2.572527 1.702731 -1.982130 +v 2.572527 1.671233 -1.932649 +v 2.572527 2.534976 -1.982130 +v 2.572527 2.497181 -1.932651 +v 2.629747 2.534976 -1.982130 +v 2.629747 2.497181 -1.932651 +v 2.629747 1.702731 -1.982130 +v 2.629747 1.671233 -1.932651 +v 2.572527 1.805464 -2.241545 +v 2.572527 1.805464 -2.192068 +v 2.572527 2.747263 -2.241545 +v 2.572527 2.711723 -2.192068 +v 2.629747 2.747263 -2.241545 +v 2.629747 2.711723 -2.192068 +v 2.629747 1.805464 -2.241545 +v 2.629747 1.805464 -2.192068 +v 2.572527 1.564686 -0.757602 +v 2.572527 1.529847 -0.708125 +v 2.629747 1.564686 -0.757602 +v 2.629747 1.529847 -0.708125 +v 2.572527 0.929265 -0.976949 +v 2.572527 0.897672 -0.927471 +v 2.572527 1.730195 -0.976952 +v 2.572527 1.694825 -0.927471 +v 2.629747 1.730195 -0.976952 +v 2.629747 1.694825 -0.927471 +v 2.629747 0.929265 -0.976949 +v 2.629747 0.897672 -0.927471 +v 2.572527 1.088851 -1.203883 +v 2.572527 1.069078 -1.154402 +v 2.572527 1.901071 -1.203883 +v 2.572527 1.861056 -1.154402 +v 2.629747 1.901071 -1.203883 +v 2.629747 1.861056 -1.154402 +v 2.629747 1.088851 -1.203883 +v 2.629747 1.069078 -1.154402 +v 2.493097 0.679768 -0.685547 +v 2.493097 0.706899 -0.672756 +v 2.652948 0.706899 -0.672756 +v 2.652948 0.679768 -0.685547 +v 2.484186 1.425959 -0.603262 +v 2.484186 1.468311 -0.583299 +v 2.661852 1.468311 -0.583299 +v 2.661852 1.425959 -0.603262 +v 2.646036 0.421734 -0.583291 +v 2.618150 0.421733 -0.684365 +v 2.527894 0.421733 -0.684365 +v 2.500001 0.421734 -0.583291 +v 2.573022 0.421734 -0.520830 +v 2.646036 1.430324 -0.583291 +v 2.618150 1.502170 -0.684365 +v 2.527894 1.502170 -0.684365 +v 2.500001 1.430324 -0.583291 +v 2.573022 1.430324 -0.520830 +v 2.618150 0.630375 -0.684365 +v 2.527894 0.630375 -0.684365 +v 2.500001 0.630377 -0.583291 +v 2.573022 0.630375 -0.520830 +v 2.646036 0.630377 -0.583291 +v 2.620965 0.676206 -0.579027 +v 2.573022 0.674874 -0.548908 +v 2.525079 0.676206 -0.579027 +v 2.543390 0.678353 -0.627766 +v 2.602655 0.678353 -0.627766 +v 2.646036 1.262728 -0.583291 +v 2.573022 1.262727 -0.520830 +v 2.500001 1.262728 -0.583291 +v 2.527894 1.262726 -0.684365 +v 2.618150 1.262726 -0.684365 +v 2.602655 1.218379 -0.656289 +v 2.543390 1.218379 -0.656289 +v 2.525079 1.218381 -0.589922 +v 2.573022 1.218378 -0.548908 +v 2.620965 1.218381 -0.589922 +v 2.670991 1.963308 -2.273673 +v 2.517488 1.963308 -2.273673 +v 2.517488 1.920762 -2.273673 +v 2.670991 1.920762 -2.273673 +v 2.640695 1.848761 -1.080024 +v 2.521501 1.815001 -1.035947 +v 2.481393 1.761289 -1.041079 +v 2.640695 1.806408 -1.099990 +v 2.675447 2.802798 -2.273673 +v 2.506883 2.802798 -2.273673 +v 2.506883 2.760444 -2.273673 +v 2.675447 2.760444 -2.273673 +v 2.629747 0.769470 -0.763086 +v 2.572527 0.769470 -0.763086 +v 2.572527 0.726114 -0.713605 +v 2.629747 0.726114 -0.713605 +v 2.484850 1.897678 -1.146350 +v 2.481958 1.725063 -0.918520 +v 2.481393 1.786819 -1.029039 +v 2.652948 0.667278 -0.475679 +v 2.493097 0.667278 -0.475679 +v 2.652948 0.694973 -0.475679 +v 2.493097 0.694973 -0.475679 +v 2.661852 1.417098 -0.475679 +v 2.484186 1.417098 -0.475679 +v 2.661852 1.460330 -0.475679 +v 2.484186 1.460330 -0.475679 +s 1 +f 70 3 6 5 91 92 +f 9 14 13 12 +f 84 11 85 +f 11 84 86 +f 14 9 10 16 +f 6 13 14 5 +f 7 81 6 +f 8 16 15 7 +f 5 14 16 8 +f 9 17 18 10 +f 12 20 17 9 +f 17 21 22 18 +f 18 22 23 19 +f 19 23 24 20 +f 20 24 21 17 +f 73 26 74 +f 2 27 28 1 +f 1 28 25 3 +f 6 29 30 7 +f 75 26 73 +f 3 25 29 6 +f 27 33 34 28 +f 28 34 31 25 +f 29 35 36 30 +f 25 31 35 29 +f 32 38 39 33 +f 33 43 34 +f 76 37 77 +f 35 41 44 +f 36 42 38 32 +f 77 37 78 +f 44 42 36 +f 35 44 36 +f 43 40 34 +f 33 39 43 +f 38 45 46 39 +f 39 46 47 43 +f 42 48 45 38 +f 44 49 48 42 +f 43 47 51 40 +f 41 52 49 44 +f 45 53 54 46 +f 46 54 55 47 +f 48 56 53 45 +f 49 57 56 48 +f 51 59 58 50 +f 47 55 59 51 +f 50 58 60 52 +f 52 60 57 49 +f 62 65 55 +f 59 65 64 58 +f 58 64 66 60 +f 63 56 57 +f 61 88 87 +f 68 71 65 62 +f 88 61 89 +f 65 71 70 64 +f 68 67 4 2 +f 71 68 2 1 +f 67 69 8 7 4 +f 70 71 1 3 +f 91 72 92 +f 90 72 91 +f 66 57 60 +f 66 63 57 +f 54 62 55 +f 55 65 59 +f 5 8 69 90 91 +f 4 73 74 27 2 +f 26 32 33 27 74 +f 30 36 32 26 75 +f 7 30 75 73 4 +f 40 51 50 37 76 +f 34 40 76 77 31 +f 31 77 78 41 35 +f 37 50 52 41 78 +f 79 81 83 +f 81 80 82 +f 81 82 83 +f 12 13 79 83 +f 11 19 20 12 85 +f 10 18 19 11 86 +f 84 15 16 10 86 +f 82 80 15 84 85 +f 12 83 82 85 +f 81 79 13 6 +f 7 15 80 81 +f 53 61 87 62 54 +f 88 67 68 62 87 +f 63 69 67 88 89 +f 56 63 89 61 53 +f 64 70 92 72 66 +f 90 69 63 66 72 +f 162 95 98 97 183 184 +f 101 106 105 104 +f 176 103 177 +f 103 176 178 +f 106 101 102 108 +f 98 105 106 97 +f 99 173 98 +f 100 108 107 99 +f 97 106 108 100 +f 101 109 110 102 +f 104 112 109 101 +f 109 113 114 110 +f 110 114 115 111 +f 111 115 116 112 +f 112 116 113 109 +f 165 118 166 +f 94 119 120 93 +f 93 120 117 95 +f 98 121 122 99 +f 167 118 165 +f 95 117 121 98 +f 119 125 126 120 +f 120 126 123 117 +f 121 127 128 122 +f 117 123 127 121 +f 124 130 131 125 +f 125 135 126 +f 168 129 169 +f 127 133 136 +f 128 134 130 124 +f 169 129 170 +f 136 134 128 +f 127 136 128 +f 135 132 126 +f 125 131 135 +f 130 137 138 131 +f 131 138 139 135 +f 134 140 137 130 +f 136 141 140 134 +f 135 139 143 132 +f 133 144 141 136 +f 137 145 146 138 +f 138 146 147 139 +f 140 148 145 137 +f 141 149 148 140 +f 143 151 150 142 +f 139 147 151 143 +f 142 150 152 144 +f 144 152 149 141 +f 154 157 147 +f 151 157 156 150 +f 150 156 158 152 +f 155 148 149 +f 153 180 179 +f 160 163 157 154 +f 180 153 181 +f 157 163 162 156 +f 160 159 96 94 +f 163 160 94 93 +f 159 161 100 99 96 +f 162 163 93 95 +f 183 164 184 +f 182 164 183 +f 158 149 152 +f 158 155 149 +f 146 154 147 +f 147 157 151 +f 97 100 161 182 183 +f 96 165 166 119 94 +f 118 124 125 119 166 +f 122 128 124 118 167 +f 99 122 167 165 96 +f 132 143 142 129 168 +f 126 132 168 169 123 +f 123 169 170 133 127 +f 129 142 144 133 170 +f 171 173 175 +f 173 172 174 +f 173 174 175 +f 104 105 171 175 +f 103 111 112 104 177 +f 102 110 111 103 178 +f 176 107 108 102 178 +f 174 172 107 176 177 +f 104 175 174 177 +f 173 171 105 98 +f 99 107 172 173 +f 145 153 179 154 146 +f 180 159 160 154 179 +f 155 161 159 180 181 +f 148 155 181 153 145 +f 156 162 184 164 158 +f 182 161 155 158 164 +f 254 187 190 189 275 276 +f 193 198 197 196 +f 268 195 269 +f 195 268 270 +f 198 193 194 200 +f 190 197 198 189 +f 191 265 190 +f 192 200 199 191 +f 189 198 200 192 +f 193 201 202 194 +f 196 204 201 193 +f 201 205 206 202 +f 202 206 207 203 +f 203 207 208 204 +f 204 208 205 201 +f 257 210 258 +f 186 211 212 185 +f 185 212 209 187 +f 190 213 214 191 +f 259 210 257 +f 187 209 213 190 +f 211 217 218 212 +f 212 218 215 209 +f 213 219 220 214 +f 209 215 219 213 +f 216 222 223 217 +f 217 227 218 +f 260 221 261 +f 219 225 228 +f 220 226 222 216 +f 261 221 262 +f 228 226 220 +f 219 228 220 +f 227 224 218 +f 217 223 227 +f 222 229 230 223 +f 223 230 231 227 +f 226 232 229 222 +f 228 233 232 226 +f 227 231 235 224 +f 225 236 233 228 +f 229 237 238 230 +f 230 238 239 231 +f 232 240 237 229 +f 233 241 240 232 +f 235 243 242 234 +f 231 239 243 235 +f 234 242 244 236 +f 236 244 241 233 +f 246 249 239 +f 243 249 248 242 +f 242 248 250 244 +f 247 240 241 +f 245 272 271 +f 252 255 249 246 +f 272 245 273 +f 249 255 254 248 +f 252 251 188 186 +f 255 252 186 185 +f 251 253 192 191 188 +f 254 255 185 187 +f 275 256 276 +f 274 256 275 +f 250 241 244 +f 250 247 241 +f 238 246 239 +f 239 249 243 +f 189 192 253 274 275 +f 188 257 258 211 186 +f 210 216 217 211 258 +f 214 220 216 210 259 +f 191 214 259 257 188 +f 224 235 234 221 260 +f 218 224 260 261 215 +f 215 261 262 225 219 +f 221 234 236 225 262 +f 263 265 267 +f 265 264 266 +f 265 266 267 +f 196 197 263 267 +f 195 203 204 196 269 +f 194 202 203 195 270 +f 268 199 200 194 270 +f 266 264 199 268 269 +f 196 267 266 269 +f 265 263 197 190 +f 191 199 264 265 +f 237 245 271 246 238 +f 272 251 252 246 271 +f 247 253 251 272 273 +f 240 247 273 245 237 +f 248 254 276 256 250 +f 274 253 247 250 256 +f 346 279 282 281 367 368 +f 285 290 289 288 +f 360 287 361 +f 287 360 362 +f 290 285 286 292 +f 282 289 290 281 +f 283 357 282 +f 284 292 291 283 +f 281 290 292 284 +f 285 293 294 286 +f 288 296 293 285 +f 293 297 298 294 +f 294 298 299 295 +f 295 299 300 296 +f 296 300 297 293 +f 349 302 350 +f 278 303 304 277 +f 277 304 301 279 +f 282 305 306 283 +f 351 302 349 +f 279 301 305 282 +f 303 309 310 304 +f 304 310 307 301 +f 305 311 312 306 +f 301 307 311 305 +f 308 314 315 309 +f 309 319 310 +f 352 313 353 +f 311 317 320 +f 312 318 314 308 +f 353 313 354 +f 320 318 312 +f 311 320 312 +f 319 316 310 +f 309 315 319 +f 314 321 322 315 +f 315 322 323 319 +f 318 324 321 314 +f 320 325 324 318 +f 319 323 327 316 +f 317 328 325 320 +f 321 329 330 322 +f 322 330 331 323 +f 324 332 329 321 +f 325 333 332 324 +f 327 335 334 326 +f 323 331 335 327 +f 326 334 336 328 +f 328 336 333 325 +f 338 341 331 +f 335 341 340 334 +f 334 340 342 336 +f 339 332 333 +f 337 364 363 +f 344 347 341 338 +f 364 337 365 +f 341 347 346 340 +f 344 343 280 278 +f 347 344 278 277 +f 343 345 284 283 280 +f 346 347 277 279 +f 367 348 368 +f 366 348 367 +f 342 333 336 +f 342 339 333 +f 330 338 331 +f 331 341 335 +f 281 284 345 366 367 +f 280 349 350 303 278 +f 302 308 309 303 350 +f 306 312 308 302 351 +f 283 306 351 349 280 +f 316 327 326 313 352 +f 310 316 352 353 307 +f 307 353 354 317 311 +f 313 326 328 317 354 +f 355 357 359 +f 357 356 358 +f 357 358 359 +f 288 289 355 359 +f 287 295 296 288 361 +f 286 294 295 287 362 +f 360 291 292 286 362 +f 358 356 291 360 361 +f 288 359 358 361 +f 357 355 289 282 +f 283 291 356 357 +f 329 337 363 338 330 +f 364 343 344 338 363 +f 339 345 343 364 365 +f 332 339 365 337 329 +f 340 346 368 348 342 +f 366 345 339 342 348 +f 438 371 374 373 459 460 +f 377 382 381 380 +f 452 379 453 +f 379 452 454 +f 382 377 378 384 +f 374 381 382 373 +f 375 449 374 +f 376 384 383 375 +f 373 382 384 376 +f 377 385 386 378 +f 380 388 385 377 +f 385 389 390 386 +f 386 390 391 387 +f 387 391 392 388 +f 388 392 389 385 +f 441 394 442 +f 370 395 396 369 +f 369 396 393 371 +f 374 397 398 375 +f 443 394 441 +f 371 393 397 374 +f 395 401 402 396 +f 396 402 399 393 +f 397 403 404 398 +f 393 399 403 397 +f 400 406 407 401 +f 401 411 402 +f 444 405 445 +f 403 409 412 +f 404 410 406 400 +f 445 405 446 +f 412 410 404 +f 403 412 404 +f 411 408 402 +f 401 407 411 +f 406 413 414 407 +f 407 414 415 411 +f 410 416 413 406 +f 412 417 416 410 +f 411 415 419 408 +f 409 420 417 412 +f 413 421 422 414 +f 414 422 423 415 +f 416 424 421 413 +f 417 425 424 416 +f 419 427 426 418 +f 415 423 427 419 +f 418 426 428 420 +f 420 428 425 417 +f 430 433 423 +f 427 433 432 426 +f 426 432 434 428 +f 431 424 425 +f 429 456 455 +f 436 439 433 430 +f 456 429 457 +f 433 439 438 432 +f 436 435 372 370 +f 439 436 370 369 +f 435 437 376 375 372 +f 438 439 369 371 +f 459 440 460 +f 458 440 459 +f 434 425 428 +f 434 431 425 +f 422 430 423 +f 423 433 427 +f 373 376 437 458 459 +f 372 441 442 395 370 +f 394 400 401 395 442 +f 398 404 400 394 443 +f 375 398 443 441 372 +f 408 419 418 405 444 +f 402 408 444 445 399 +f 399 445 446 409 403 +f 405 418 420 409 446 +f 447 449 451 +f 449 448 450 +f 449 450 451 +f 380 381 447 451 +f 379 387 388 380 453 +f 378 386 387 379 454 +f 452 383 384 378 454 +f 450 448 383 452 453 +f 380 451 450 453 +f 449 447 381 374 +f 375 383 448 449 +f 421 429 455 430 422 +f 456 435 436 430 455 +f 431 437 435 456 457 +f 424 431 457 429 421 +f 432 438 460 440 434 +f 458 437 431 434 440 +f 530 463 466 465 551 552 +f 469 474 473 472 +f 544 471 545 +f 471 544 546 +f 474 469 470 476 +f 466 473 474 465 +f 467 541 466 +f 468 476 475 467 +f 465 474 476 468 +f 469 477 478 470 +f 472 480 477 469 +f 477 481 482 478 +f 478 482 483 479 +f 479 483 484 480 +f 480 484 481 477 +f 533 486 534 +f 462 487 488 461 +f 461 488 485 463 +f 466 489 490 467 +f 535 486 533 +f 463 485 489 466 +f 487 493 494 488 +f 488 494 491 485 +f 489 495 496 490 +f 485 491 495 489 +f 492 498 499 493 +f 493 503 494 +f 536 497 537 +f 495 501 504 +f 496 502 498 492 +f 537 497 538 +f 504 502 496 +f 495 504 496 +f 503 500 494 +f 493 499 503 +f 498 505 506 499 +f 499 506 507 503 +f 502 508 505 498 +f 504 509 508 502 +f 503 507 511 500 +f 501 512 509 504 +f 505 513 514 506 +f 506 514 515 507 +f 508 516 513 505 +f 509 517 516 508 +f 511 519 518 510 +f 507 515 519 511 +f 510 518 520 512 +f 512 520 517 509 +f 522 525 515 +f 519 525 524 518 +f 518 524 526 520 +f 523 516 517 +f 521 548 547 +f 528 531 525 522 +f 548 521 549 +f 525 531 530 524 +f 528 527 464 462 +f 531 528 462 461 +f 527 529 468 467 464 +f 530 531 461 463 +f 551 532 552 +f 550 532 551 +f 526 517 520 +f 526 523 517 +f 514 522 515 +f 515 525 519 +f 465 468 529 550 551 +f 464 533 534 487 462 +f 486 492 493 487 534 +f 490 496 492 486 535 +f 467 490 535 533 464 +f 500 511 510 497 536 +f 494 500 536 537 491 +f 491 537 538 501 495 +f 497 510 512 501 538 +f 539 541 543 +f 541 540 542 +f 541 542 543 +f 472 473 539 543 +f 471 479 480 472 545 +f 470 478 479 471 546 +f 544 475 476 470 546 +f 542 540 475 544 545 +f 472 543 542 545 +f 541 539 473 466 +f 467 475 540 541 +f 513 521 547 522 514 +f 548 527 528 522 547 +f 523 529 527 548 549 +f 516 523 549 521 513 +f 524 530 552 532 526 +f 550 529 523 526 532 +f 622 555 558 557 643 644 +f 561 566 565 564 +f 636 563 637 +f 563 636 638 +f 566 561 562 568 +f 558 565 566 557 +f 559 633 558 +f 560 568 567 559 +f 557 566 568 560 +f 561 569 570 562 +f 564 572 569 561 +f 569 573 574 570 +f 570 574 575 571 +f 571 575 576 572 +f 572 576 573 569 +f 625 578 626 +f 554 579 580 553 +f 553 580 577 555 +f 558 581 582 559 +f 627 578 625 +f 555 577 581 558 +f 579 585 586 580 +f 580 586 583 577 +f 581 587 588 582 +f 577 583 587 581 +f 584 590 591 585 +f 585 595 586 +f 628 589 629 +f 587 593 596 +f 588 594 590 584 +f 629 589 630 +f 596 594 588 +f 587 596 588 +f 595 592 586 +f 585 591 595 +f 590 597 598 591 +f 591 598 599 595 +f 594 600 597 590 +f 596 601 600 594 +f 595 599 603 592 +f 593 604 601 596 +f 597 605 606 598 +f 598 606 607 599 +f 600 608 605 597 +f 601 609 608 600 +f 603 611 610 602 +f 599 607 611 603 +f 602 610 612 604 +f 604 612 609 601 +f 614 617 607 +f 611 617 616 610 +f 610 616 618 612 +f 615 608 609 +f 613 640 639 +f 620 623 617 614 +f 640 613 641 +f 617 623 622 616 +f 620 619 556 554 +f 623 620 554 553 +f 619 621 560 559 556 +f 622 623 553 555 +f 643 624 644 +f 642 624 643 +f 618 609 612 +f 618 615 609 +f 606 614 607 +f 607 617 611 +f 557 560 621 642 643 +f 556 625 626 579 554 +f 578 584 585 579 626 +f 582 588 584 578 627 +f 559 582 627 625 556 +f 592 603 602 589 628 +f 586 592 628 629 583 +f 583 629 630 593 587 +f 589 602 604 593 630 +f 631 633 635 +f 633 632 634 +f 633 634 635 +f 564 565 631 635 +f 563 571 572 564 637 +f 562 570 571 563 638 +f 636 567 568 562 638 +f 634 632 567 636 637 +f 564 635 634 637 +f 633 631 565 558 +f 559 567 632 633 +f 605 613 639 614 606 +f 640 619 620 614 639 +f 615 621 619 640 641 +f 608 615 641 613 605 +f 616 622 644 624 618 +f 642 621 615 618 624 +f 714 647 650 649 735 736 +f 653 658 657 656 +f 728 655 729 +f 655 728 730 +f 658 653 654 660 +f 650 657 658 649 +f 651 725 650 +f 652 660 659 651 +f 649 658 660 652 +f 653 661 662 654 +f 656 664 661 653 +f 661 665 666 662 +f 662 666 667 663 +f 663 667 668 664 +f 664 668 665 661 +f 717 670 718 +f 646 671 672 645 +f 645 672 669 647 +f 650 673 674 651 +f 719 670 717 +f 647 669 673 650 +f 671 677 678 672 +f 672 678 675 669 +f 673 679 680 674 +f 669 675 679 673 +f 676 682 683 677 +f 677 687 678 +f 720 681 721 +f 679 685 688 +f 680 686 682 676 +f 721 681 722 +f 688 686 680 +f 679 688 680 +f 687 684 678 +f 677 683 687 +f 682 689 690 683 +f 683 690 691 687 +f 686 692 689 682 +f 688 693 692 686 +f 687 691 695 684 +f 685 696 693 688 +f 689 697 698 690 +f 690 698 699 691 +f 692 700 697 689 +f 693 701 700 692 +f 695 703 702 694 +f 691 699 703 695 +f 694 702 704 696 +f 696 704 701 693 +f 706 709 699 +f 703 709 708 702 +f 702 708 710 704 +f 707 700 701 +f 705 732 731 +f 712 715 709 706 +f 732 705 733 +f 709 715 714 708 +f 712 711 648 646 +f 715 712 646 645 +f 711 713 652 651 648 +f 714 715 645 647 +f 735 716 736 +f 734 716 735 +f 710 701 704 +f 710 707 701 +f 698 706 699 +f 699 709 703 +f 649 652 713 734 735 +f 648 717 718 671 646 +f 670 676 677 671 718 +f 674 680 676 670 719 +f 651 674 719 717 648 +f 684 695 694 681 720 +f 678 684 720 721 675 +f 675 721 722 685 679 +f 681 694 696 685 722 +f 723 725 727 +f 725 724 726 +f 725 726 727 +f 656 657 723 727 +f 655 663 664 656 729 +f 654 662 663 655 730 +f 728 659 660 654 730 +f 726 724 659 728 729 +f 656 727 726 729 +f 725 723 657 650 +f 651 659 724 725 +f 697 705 731 706 698 +f 732 711 712 706 731 +f 707 713 711 732 733 +f 700 707 733 705 697 +f 708 714 736 716 710 +f 734 713 707 710 716 +f 806 739 742 741 827 828 +f 745 750 749 748 +f 820 747 821 +f 747 820 822 +f 750 745 746 752 +f 742 749 750 741 +f 743 817 742 +f 744 752 751 743 +f 741 750 752 744 +f 745 753 754 746 +f 748 756 753 745 +f 753 757 758 754 +f 754 758 759 755 +f 755 759 760 756 +f 756 760 757 753 +f 809 762 810 +f 738 763 764 737 +f 737 764 761 739 +f 742 765 766 743 +f 811 762 809 +f 739 761 765 742 +f 763 769 770 764 +f 764 770 767 761 +f 765 771 772 766 +f 761 767 771 765 +f 768 774 775 769 +f 769 779 770 +f 812 773 813 +f 771 777 780 +f 772 778 774 768 +f 813 773 814 +f 780 778 772 +f 771 780 772 +f 779 776 770 +f 769 775 779 +f 774 781 782 775 +f 775 782 783 779 +f 778 784 781 774 +f 780 785 784 778 +f 779 783 787 776 +f 777 788 785 780 +f 781 789 790 782 +f 782 790 791 783 +f 784 792 789 781 +f 785 793 792 784 +f 787 795 794 786 +f 783 791 795 787 +f 786 794 796 788 +f 788 796 793 785 +f 798 801 791 +f 795 801 800 794 +f 794 800 802 796 +f 799 792 793 +f 797 824 823 +f 804 807 801 798 +f 824 797 825 +f 801 807 806 800 +f 804 803 740 738 +f 807 804 738 737 +f 803 805 744 743 740 +f 806 807 737 739 +f 827 808 828 +f 826 808 827 +f 802 793 796 +f 802 799 793 +f 790 798 791 +f 791 801 795 +f 741 744 805 826 827 +f 740 809 810 763 738 +f 762 768 769 763 810 +f 766 772 768 762 811 +f 743 766 811 809 740 +f 776 787 786 773 812 +f 770 776 812 813 767 +f 767 813 814 777 771 +f 773 786 788 777 814 +f 815 817 819 +f 817 816 818 +f 817 818 819 +f 748 749 815 819 +f 747 755 756 748 821 +f 746 754 755 747 822 +f 820 751 752 746 822 +f 818 816 751 820 821 +f 748 819 818 821 +f 817 815 749 742 +f 743 751 816 817 +f 789 797 823 798 790 +f 824 803 804 798 823 +f 799 805 803 824 825 +f 792 799 825 797 789 +f 800 806 828 808 802 +f 826 805 799 802 808 +f 898 831 834 833 919 920 +f 837 842 841 840 +f 912 839 913 +f 839 912 914 +f 842 837 838 844 +f 834 841 842 833 +f 835 909 834 +f 836 844 843 835 +f 833 842 844 836 +f 837 845 846 838 +f 840 848 845 837 +f 845 849 850 846 +f 846 850 851 847 +f 847 851 852 848 +f 848 852 849 845 +f 901 854 902 +f 830 855 856 829 +f 829 856 853 831 +f 834 857 858 835 +f 903 854 901 +f 831 853 857 834 +f 855 861 862 856 +f 856 862 859 853 +f 857 863 864 858 +f 853 859 863 857 +f 860 866 867 861 +f 861 871 862 +f 904 865 905 +f 863 869 872 +f 864 870 866 860 +f 905 865 906 +f 872 870 864 +f 863 872 864 +f 871 868 862 +f 861 867 871 +f 866 873 874 867 +f 867 874 875 871 +f 870 876 873 866 +f 872 877 876 870 +f 871 875 879 868 +f 869 880 877 872 +f 873 881 882 874 +f 874 882 883 875 +f 876 884 881 873 +f 877 885 884 876 +f 879 887 886 878 +f 875 883 887 879 +f 878 886 888 880 +f 880 888 885 877 +f 890 893 883 +f 887 893 892 886 +f 886 892 894 888 +f 891 884 885 +f 889 916 915 +f 896 899 893 890 +f 916 889 917 +f 893 899 898 892 +f 896 895 832 830 +f 899 896 830 829 +f 895 897 836 835 832 +f 898 899 829 831 +f 919 900 920 +f 918 900 919 +f 894 885 888 +f 894 891 885 +f 882 890 883 +f 883 893 887 +f 833 836 897 918 919 +f 832 901 902 855 830 +f 854 860 861 855 902 +f 858 864 860 854 903 +f 835 858 903 901 832 +f 868 879 878 865 904 +f 862 868 904 905 859 +f 859 905 906 869 863 +f 865 878 880 869 906 +f 907 909 911 +f 909 908 910 +f 909 910 911 +f 840 841 907 911 +f 839 847 848 840 913 +f 838 846 847 839 914 +f 912 843 844 838 914 +f 910 908 843 912 913 +f 840 911 910 913 +f 909 907 841 834 +f 835 843 908 909 +f 881 889 915 890 882 +f 916 895 896 890 915 +f 891 897 895 916 917 +f 884 891 917 889 881 +f 892 898 920 900 894 +f 918 897 891 894 900 +f 990 923 926 925 1011 1012 +f 929 934 933 932 +f 1004 931 1005 +f 931 1004 1006 +f 934 929 930 936 +f 926 933 934 925 +f 927 1001 926 +f 928 936 935 927 +f 925 934 936 928 +f 929 937 938 930 +f 932 940 937 929 +f 937 941 942 938 +f 938 942 943 939 +f 939 943 944 940 +f 940 944 941 937 +f 993 946 994 +f 922 947 948 921 +f 921 948 945 923 +f 926 949 950 927 +f 995 946 993 +f 923 945 949 926 +f 947 953 954 948 +f 948 954 951 945 +f 949 955 956 950 +f 945 951 955 949 +f 952 958 959 953 +f 953 963 954 +f 996 957 997 +f 955 961 964 +f 956 962 958 952 +f 997 957 998 +f 964 962 956 +f 955 964 956 +f 963 960 954 +f 953 959 963 +f 958 965 966 959 +f 959 966 967 963 +f 962 968 965 958 +f 964 969 968 962 +f 963 967 971 960 +f 961 972 969 964 +f 965 973 974 966 +f 966 974 975 967 +f 968 976 973 965 +f 969 977 976 968 +f 971 979 978 970 +f 967 975 979 971 +f 970 978 980 972 +f 972 980 977 969 +f 982 985 975 +f 979 985 984 978 +f 978 984 986 980 +f 983 976 977 +f 981 1008 1007 +f 988 991 985 982 +f 1008 981 1009 +f 985 991 990 984 +f 988 987 924 922 +f 991 988 922 921 +f 987 989 928 927 924 +f 990 991 921 923 +f 1011 992 1012 +f 1010 992 1011 +f 986 977 980 +f 986 983 977 +f 974 982 975 +f 975 985 979 +f 925 928 989 1010 1011 +f 924 993 994 947 922 +f 946 952 953 947 994 +f 950 956 952 946 995 +f 927 950 995 993 924 +f 960 971 970 957 996 +f 954 960 996 997 951 +f 951 997 998 961 955 +f 957 970 972 961 998 +f 999 1001 1003 +f 1001 1000 1002 +f 1001 1002 1003 +f 932 933 999 1003 +f 931 939 940 932 1005 +f 930 938 939 931 1006 +f 1004 935 936 930 1006 +f 1002 1000 935 1004 1005 +f 932 1003 1002 1005 +f 1001 999 933 926 +f 927 935 1000 1001 +f 973 981 1007 982 974 +f 1008 987 988 982 1007 +f 983 989 987 1008 1009 +f 976 983 1009 981 973 +f 984 990 1012 992 986 +f 1010 989 983 986 992 +f 1014 1013 1077 1078 +f 1015 1014 1078 1079 +f 1016 1015 1079 1080 +f 1013 1016 1080 1077 +f 1018 1017 1081 1082 +f 1019 1018 1082 1083 +f 1020 1019 1083 1084 +f 1017 1020 1084 1081 +f 1022 1021 1085 1086 +f 1023 1022 1086 1087 +f 1024 1023 1087 1088 +f 1021 1024 1088 1085 +f 1026 1025 1089 1090 +f 1027 1026 1090 1091 +f 1028 1027 1091 1092 +f 1025 1028 1092 1089 +f 1030 1029 1093 1094 +f 1031 1030 1094 1095 +f 1032 1031 1095 1096 +f 1029 1032 1096 1093 +f 1034 1033 1097 1098 +f 1035 1034 1098 1099 +f 1036 1035 1099 1100 +f 1033 1036 1100 1097 +f 1038 1037 1101 1102 +f 1039 1038 1102 1103 +f 1040 1039 1103 1104 +f 1037 1040 1104 1101 +f 1042 1041 1105 1106 +f 1043 1042 1106 1107 +f 1044 1043 1107 1108 +f 1041 1044 1108 1105 +f 1046 1045 1109 1110 +f 1047 1046 1110 1111 +f 1048 1047 1111 1112 +f 1045 1048 1112 1109 +f 1050 1049 1113 1114 +f 1051 1050 1114 1115 +f 1052 1051 1115 1116 +f 1049 1052 1116 1113 +f 1054 1053 1117 1118 +f 1055 1054 1118 1119 +f 1056 1055 1119 1120 +f 1053 1056 1120 1117 +f 1058 1057 1121 1122 +f 1059 1058 1122 1123 +f 1060 1059 1123 1124 +f 1057 1060 1124 1121 +f 1062 1061 1125 1126 +f 1063 1062 1126 1127 +f 1064 1063 1127 1128 +f 1061 1064 1128 1125 +f 1066 1065 1129 1130 +f 1067 1066 1130 1131 +f 1068 1067 1131 1132 +f 1065 1068 1132 1129 +f 1070 1073 1072 1069 +f 1070 1071 1074 1073 +f 1071 1076 1075 1074 +f 1076 1069 1072 1075 +f 1134 1133 1136 1137 +f 1134 1137 1138 1135 +f 1135 1138 1139 1140 +f 1140 1139 1136 1133 +f 1141 1142 1144 1143 +f 1143 1144 1146 1145 +f 1145 1146 1148 1147 +f 1147 1148 1142 1141 +f 1851 1852 1150 1152 +f 1850 1851 1152 1154 +f 1853 1850 1154 1156 +f 1852 1853 1156 1150 +f 1157 1158 1160 1159 +f 1159 1160 1162 1161 +f 1161 1162 1164 1163 +f 1163 1164 1158 1157 +f 1165 1166 1168 1167 +f 1167 1168 1170 1169 +f 1169 1170 1172 1171 +f 1171 1172 1166 1165 +f 1173 1174 1176 1175 +f 1175 1176 1178 1177 +f 1177 1178 1180 1179 +f 1179 1180 1174 1173 +f 1181 1182 1184 1183 +f 1183 1184 1186 1185 +f 1185 1186 1188 1187 +f 1187 1188 1182 1181 +f 1189 1190 1192 1191 +f 1191 1192 1194 1193 +f 1193 1194 1196 1195 +f 1195 1196 1190 1189 +f 1197 1198 1200 1199 +f 1199 1200 1202 1201 +f 1201 1202 1204 1203 +f 1203 1204 1198 1197 +f 1205 1206 1208 1207 +f 1207 1208 1210 1209 +f 1209 1210 1212 1211 +f 1211 1212 1206 1205 +f 1213 1214 1216 1215 +f 1215 1216 1218 1217 +f 1217 1218 1220 1219 +f 1219 1220 1214 1213 +f 1848 1849 1222 1224 +f 1847 1848 1224 1226 +f 1846 1847 1226 1228 +f 1849 1846 1228 1222 +f 1229 1230 1232 1231 +f 1231 1232 1234 1233 +f 1233 1234 1236 1235 +f 1235 1236 1230 1229 +f 1237 1238 1240 1239 +f 1239 1240 1242 1241 +f 1241 1242 1244 1243 +f 1243 1244 1238 1237 +f 1245 1246 1248 1247 +f 1247 1248 1250 1249 +f 1249 1250 1252 1251 +f 1251 1252 1246 1245 +f 1253 1254 1256 1255 +f 1255 1256 1258 1257 +f 1257 1258 1260 1259 +f 1259 1260 1254 1253 +f 1843 1844 1262 1264 +f 1842 1843 1264 1266 +f 1845 1842 1266 1268 +f 1844 1845 1268 1262 +f 1269 1270 1272 1271 +f 1271 1272 1274 1273 +f 1273 1274 1276 1275 +f 1275 1276 1270 1269 +f 1277 1278 1280 1279 +f 1279 1280 1282 1281 +f 1281 1282 1284 1283 +f 1283 1284 1278 1277 +f 1285 1286 1288 1287 +f 1287 1288 1290 1289 +f 1289 1290 1292 1291 +f 1291 1292 1286 1285 +f 1293 1294 1296 1295 +f 1295 1296 1298 1297 +f 1297 1298 1300 1299 +f 1299 1300 1294 1293 +f 1301 1302 1304 1303 +f 1303 1304 1306 1305 +f 1305 1306 1308 1307 +f 1307 1308 1302 1301 +f 1840 1841 1310 1312 +f 1839 1840 1312 1314 +f 1838 1839 1314 1316 +f 1841 1838 1316 1310 +f 1317 1318 1320 1319 +f 1319 1320 1322 1321 +f 1321 1322 1324 1323 +f 1323 1324 1318 1317 +f 1325 1326 1328 1327 +f 1327 1328 1330 1329 +f 1329 1330 1332 1331 +f 1331 1332 1326 1325 +f 1333 1334 1336 1335 +f 1335 1336 1338 1337 +f 1337 1338 1340 1339 +f 1339 1340 1334 1333 +f 1341 1342 1344 1343 +f 1343 1344 1346 1345 +f 1345 1346 1348 1347 +f 1347 1348 1342 1341 +f 1349 1350 1352 1351 +f 1351 1352 1354 1353 +f 1353 1354 1356 1355 +f 1355 1356 1350 1349 +f 1835 1836 1358 1360 +f 1834 1835 1360 1362 +f 1837 1834 1362 1364 +f 1836 1837 1364 1358 +f 1365 1366 1368 1367 +f 1367 1368 1370 1369 +f 1369 1370 1372 1371 +f 1371 1372 1366 1365 +f 1373 1374 1376 1375 +f 1375 1376 1378 1377 +f 1377 1378 1380 1379 +f 1379 1380 1374 1373 +f 1381 1382 1384 1383 +f 1383 1384 1386 1385 +f 1385 1386 1388 1387 +f 1387 1388 1382 1381 +f 1389 1390 1392 1391 +f 1391 1392 1394 1393 +f 1393 1394 1396 1395 +f 1395 1396 1390 1389 +f 1397 1398 1400 1399 +f 1399 1400 1402 1401 +f 1401 1402 1404 1403 +f 1403 1404 1398 1397 +f 1405 1406 1408 1407 +f 1407 1408 1410 1409 +f 1409 1410 1412 1411 +f 1411 1412 1406 1405 +f 1830 1831 1414 1416 +f 1833 1830 1416 1418 +f 1832 1833 1418 1420 +f 1831 1832 1420 1414 +f 1421 1422 1424 1423 +f 1423 1424 1426 1425 +f 1425 1426 1428 1427 +f 1427 1428 1422 1421 +f 1429 1430 1432 1431 +f 1431 1432 1434 1433 +f 1433 1434 1436 1435 +f 1435 1436 1430 1429 +f 1437 1438 1440 1439 +f 1439 1440 1442 1441 +f 1441 1442 1444 1443 +f 1443 1444 1438 1437 +f 1445 1446 1448 1447 +f 1447 1448 1450 1449 +f 1449 1450 1452 1451 +f 1451 1452 1446 1445 +f 1453 1454 1456 1455 +f 1455 1456 1458 1457 +f 1457 1458 1460 1459 +f 1459 1460 1454 1453 +f 1866 1867 1462 1464 +f 1869 1866 1464 1466 +f 1868 1869 1466 1468 +f 1867 1868 1468 1462 +f 1469 1470 1472 1471 +f 1471 1472 1474 1473 +f 1473 1474 1476 1475 +f 1475 1476 1470 1469 +f 1477 1478 1480 1479 +f 1479 1480 1482 1481 +f 1481 1482 1484 1483 +f 1483 1484 1478 1477 +f 1485 1486 1488 1487 +f 1487 1488 1490 1489 +f 1489 1490 1492 1491 +f 1491 1492 1486 1485 +f 1870 1871 1494 1496 +f 1873 1870 1496 1498 +f 1872 1873 1498 1500 +f 1871 1872 1500 1494 +f 1501 1502 1504 1503 +f 1503 1504 1506 1505 +f 1505 1506 1508 1507 +f 1507 1508 1502 1501 +f 1509 1510 1512 1511 +f 1511 1512 1514 1513 +f 1513 1514 1516 1515 +f 1515 1516 1510 1509 +f 1874 1875 1518 1520 +f 1877 1874 1520 1522 +f 1876 1877 1522 1524 +f 1875 1876 1524 1518 +f 1525 1526 1528 1527 +f 1527 1528 1530 1529 +f 1529 1530 1532 1531 +f 1531 1532 1526 1525 +f 1533 1534 1536 1535 +f 1535 1536 1538 1537 +f 1537 1538 1540 1539 +f 1539 1540 1534 1533 +f 1541 1542 1544 1543 +f 1543 1544 1546 1545 +f 1545 1546 1548 1547 +f 1547 1548 1542 1541 +f 1549 1550 1552 1551 +f 1551 1552 1554 1553 +f 1553 1554 1556 1555 +f 1555 1556 1550 1549 +f 1557 1558 1560 1559 +f 1559 1560 1562 1561 +f 1561 1562 1564 1563 +f 1563 1564 1558 1557 +f 1565 1566 1568 1567 +f 1567 1568 1570 1569 +f 1569 1570 1572 1571 +f 1571 1572 1566 1565 +f 1856 1857 1574 1576 +f 1855 1856 1576 1578 +f 1854 1855 1578 1580 +f 1857 1854 1580 1574 +f 1581 1582 1584 1583 +f 1583 1584 1586 1585 +f 1585 1586 1588 1587 +f 1587 1588 1582 1581 +f 1589 1590 1592 1591 +f 1591 1592 1594 1593 +f 1593 1594 1596 1595 +f 1595 1596 1590 1589 +f 1597 1598 1600 1599 +f 1599 1600 1602 1601 +f 1601 1602 1604 1603 +f 1603 1604 1598 1597 +f 1605 1606 1608 1607 +f 1607 1608 1610 1609 +f 1609 1610 1612 1611 +f 1611 1612 1606 1605 +f 1860 1861 1614 1616 +f 1859 1860 1616 1618 +f 1858 1859 1618 1620 +f 1861 1858 1620 1614 +f 1621 1622 1624 1623 +f 1623 1624 1626 1625 +f 1625 1626 1628 1627 +f 1627 1628 1622 1621 +f 1629 1630 1632 1631 +f 1631 1632 1634 1633 +f 1633 1634 1636 1635 +f 1635 1636 1630 1629 +f 1637 1638 1640 1639 +f 1639 1640 1642 1641 +f 1641 1642 1644 1643 +f 1643 1644 1638 1637 +f 1645 1646 1648 1647 +f 1647 1648 1650 1649 +f 1649 1650 1652 1651 +f 1651 1652 1646 1645 +f 1653 1654 1656 1655 +f 1655 1656 1658 1657 +f 1657 1658 1660 1659 +f 1659 1660 1654 1653 +f 1661 1662 1664 1663 +f 1663 1664 1666 1665 +f 1665 1666 1668 1667 +f 1667 1668 1662 1661 +f 1669 1670 1672 1671 +f 1671 1672 1674 1673 +f 1673 1674 1676 1675 +f 1675 1676 1670 1669 +f 1865 1862 1678 1680 +f 1864 1865 1680 1682 +f 1863 1864 1682 1684 +f 1862 1863 1684 1678 +f 1685 1686 1688 1687 +f 1687 1688 1690 1689 +f 1689 1690 1692 1691 +f 1691 1692 1686 1685 +f 1693 1694 1696 1695 +f 1695 1696 1698 1697 +f 1697 1698 1700 1699 +f 1699 1700 1694 1693 +f 1701 1702 1704 1703 +f 1703 1704 1706 1705 +f 1705 1706 1708 1707 +f 1707 1708 1702 1701 +f 1709 1710 1712 1711 +f 1711 1712 1714 1713 +f 1713 1714 1716 1715 +f 1715 1716 1710 1709 +f 1717 1718 1720 1719 +f 1719 1720 1722 1721 +f 1721 1722 1724 1723 +f 1723 1724 1718 1717 +f 1878 1879 1883 1884 +f 1881 1878 1884 1885 +f 1879 1880 1882 1883 +f 1815 1816 1929 1926 +f 1891 1892 1897 1894 +f 1903 1904 1734 1735 +f 1814 1815 1926 1927 +f 1890 1891 1894 1895 +f 1904 1905 1732 1734 +f 1740 1902 1903 1735 +f 1813 1814 1927 1928 +f 1893 1890 1895 1896 +f 1816 1813 1928 1929 +f 1880 1881 1885 1882 +f 1896 1897 1892 1893 +f 1732 1905 1902 1740 +f 1745 1940 1944 1942 +f 1744 1945 1943 1746 +f 1758 1941 1938 1748 +f 1756 1972 1968 1966 +f 1810 1783 1784 +f 1751 1973 1970 1753 +f 1760 1757 1969 +f 1762 1763 1759 1758 +f 1764 1761 1757 1760 +f 1773 1774 1954 1950 +f 1775 1776 1780 1965 1777 +f 1752 1751 1767 1766 +f 1785 1786 1808 1809 +f 1743 1744 1765 1768 +f 1766 1767 1771 1770 +f 1784 1785 1809 1810 +f 1768 1765 1769 1772 +f 1742 1774 1773 1741 +f 1750 1749 1776 1775 +f 1762 1948 1949 1953 1763 +f 1964 1965 1780 1761 1764 +f 1782 1781 1752 1766 +f 1783 1782 1766 1770 +f 1770 1771 1784 1783 +f 1767 1785 1784 1771 +f 1751 1786 1785 1767 +f 1787 1821 1985 1983 +f 1788 1787 1976 1974 +f 1789 1977 1981 1979 +f 1980 1981 1978 +f 1780 1980 1761 +f 1792 1791 1780 1776 +f 1793 1792 1776 1749 +f 1775 1795 1794 1750 +f 1777 1963 1796 1795 1775 +f 1764 1797 1796 1963 1964 +f 1760 1798 1797 1764 +f 1799 1798 1760 1755 +f 1800 1799 1755 1754 +f 1781 1800 1754 1752 +f 1747 1957 1956 +f 1797 1798 1759 1763 +f 1796 1797 1763 1778 +f 1795 1796 1778 1774 +f 1794 1795 1774 1742 +f 1773 1802 1801 1741 +f 1779 1803 1802 1773 +f 1762 1804 1803 1779 +f 1758 1805 1804 1762 +f 1748 1806 1805 1758 +f 1745 1807 1806 1748 +f 1822 1743 1808 +f 1809 1808 1743 1768 +f 1810 1809 1768 1772 +f 1769 1783 1810 1772 +f 1765 1782 1783 1769 +f 1744 1781 1782 1765 +f 1746 1800 1781 1744 +f 1747 1956 1955 +f 1804 1822 1808 1812 +f 1787 1790 1821 +f 1790 1787 1788 1789 +f 1807 1804 1805 1806 +f 1812 1802 1803 1804 +f 1792 1802 1812 1811 +f 1808 1786 1811 1812 +f 1811 1790 1791 1792 +f 1793 1801 1802 1792 +f 1730 1818 1817 1738 +f 1727 1819 1818 1730 +f 1727 1725 1820 1819 +f 1738 1817 1820 1725 +f 1821 1790 1811 1786 +f 1751 1821 1786 +f 1807 1822 1804 +f 1745 1743 1822 1807 +f 1801 1793 1825 1824 +f 1793 1749 1826 1825 +f 1749 1750 1827 1826 +f 1750 1794 1823 1827 +f 1742 1741 1828 1829 +f 1741 1801 1824 1828 +f 1794 1742 1829 1823 +f 1413 1831 1830 1415 +f 1419 1832 1831 1413 +f 1417 1833 1832 1419 +f 1415 1830 1833 1417 +f 1359 1835 1834 1361 +f 1357 1836 1835 1359 +f 1363 1837 1836 1357 +f 1361 1834 1837 1363 +f 1313 1839 1838 1315 +f 1311 1840 1839 1313 +f 1309 1841 1840 1311 +f 1315 1838 1841 1309 +f 1263 1843 1842 1265 +f 1261 1844 1843 1263 +f 1267 1845 1844 1261 +f 1265 1842 1845 1267 +f 1225 1847 1846 1227 +f 1223 1848 1847 1225 +f 1221 1849 1848 1223 +f 1227 1846 1849 1221 +f 1151 1851 1850 1153 +f 1149 1852 1851 1151 +f 1155 1853 1852 1149 +f 1153 1850 1853 1155 +f 1577 1855 1854 1579 +f 1575 1856 1855 1577 +f 1573 1857 1856 1575 +f 1579 1854 1857 1573 +f 1617 1859 1858 1619 +f 1615 1860 1859 1617 +f 1613 1861 1860 1615 +f 1619 1858 1861 1613 +f 1683 1863 1862 1677 +f 1681 1864 1863 1683 +f 1679 1865 1864 1681 +f 1677 1862 1865 1679 +f 1461 1867 1866 1463 +f 1467 1868 1867 1461 +f 1465 1869 1868 1467 +f 1463 1866 1869 1465 +f 1493 1871 1870 1495 +f 1499 1872 1871 1493 +f 1497 1873 1872 1499 +f 1495 1870 1873 1497 +f 1517 1875 1874 1519 +f 1523 1876 1875 1517 +f 1521 1877 1876 1523 +f 1519 1874 1877 1521 +f 1727 1730 1879 1878 +f 1738 1880 1879 1730 +f 1725 1881 1880 1738 +f 1725 1727 1878 1881 +f 1883 1882 1886 1887 +f 1884 1883 1887 1888 +f 1885 1884 1888 1889 +f 1882 1885 1889 1886 +f 1887 1886 1739 1729 +f 1888 1887 1729 1728 +f 1889 1888 1728 1726 +f 1886 1889 1726 1739 +f 1729 1891 1890 1728 +f 1729 1739 1892 1891 +f 1893 1892 1739 1726 +f 1728 1890 1893 1726 +f 1895 1894 1899 1900 +f 1896 1895 1900 1901 +f 1901 1898 1897 1896 +f 1894 1897 1898 1899 +f 1899 1898 1740 1735 +f 1900 1899 1735 1734 +f 1901 1900 1734 1732 +f 1740 1898 1901 1732 +f 1903 1902 1909 1906 +f 1906 1907 1904 1903 +f 1907 1908 1905 1904 +f 1902 1905 1908 1909 +f 1910 1911 1907 1906 +f 1911 1912 1908 1907 +f 1909 1908 1912 1913 +f 1906 1909 1913 1910 +f 1915 1916 1911 1910 +f 1916 1917 1912 1911 +f 1913 1912 1917 1914 +f 1910 1913 1914 1915 +f 1915 1914 1918 1919 +f 1919 1920 1916 1915 +f 1920 1921 1917 1916 +f 1914 1917 1921 1918 +f 1919 1918 1923 1924 +f 1924 1925 1920 1919 +f 1925 1922 1921 1920 +f 1918 1921 1922 1923 +f 1923 1922 1731 1737 +f 1924 1923 1737 1736 +f 1733 1925 1924 1736 +f 1731 1922 1925 1733 +f 1935 1936 1930 1931 +f 1934 1935 1931 1932 +f 1937 1934 1932 1933 +f 1936 1937 1933 1930 +f 1931 1930 1733 1736 +f 1932 1931 1736 1737 +f 1933 1932 1737 1731 +f 1930 1933 1731 1733 +f 1928 1927 1935 1934 +f 1927 1926 1936 1935 +f 1926 1929 1937 1936 +f 1929 1928 1934 1937 +f 1939 1940 1941 +f 1943 1945 1944 +f 1944 1945 1942 +f 1941 1940 1938 +f 1950 1948 1947 +f 1954 1953 1952 +f 1955 1958 1747 +f 1958 1957 1747 +f 1962 1759 1798 +f 1746 1961 1800 +f 1962 1961 1959 +f 1960 1961 1962 +f 1964 1963 1777 +f 1777 1965 1964 +f 1969 1968 1967 +f 1966 1968 1969 +f 1973 1972 1970 +f 1971 1972 1973 +f 1977 1976 1975 +f 1974 1976 1977 +f 1980 1978 1757 1761 +f 1790 1789 1979 1980 +f 1980 1979 1981 +f 1983 1985 1984 +f 1984 1985 1982 +f 1745 1748 1938 1940 +f 1944 1958 1955 1746 1943 +f 1944 1940 1939 1958 +f 1743 1745 1942 1945 +f 1743 1945 1744 +f 1941 1759 1957 1958 1939 +f 1758 1759 1941 +f 1950 1949 1948 +f 1946 1949 1950 +f 1951 1953 1954 +f 1779 1947 1948 1762 +f 1953 1949 1946 1952 +f 1763 1953 1951 1778 +f 1954 1774 1778 1951 +f 1950 1954 1952 1946 +f 1773 1950 1947 1779 +f 1791 1790 1980 +f 1791 1980 1780 +f 1789 1788 1974 1977 +f 1981 1756 1757 1978 +f 1981 1977 1975 1756 +f 1969 1757 1756 1966 +f 1760 1969 1967 1755 +f 1753 1970 1972 1756 +f 1968 1754 1755 1967 +f 1968 1972 1971 1754 +f 1962 1798 1799 1960 +f 1956 1957 1759 1962 1959 +f 1955 1956 1959 1961 1746 +f 1800 1961 1960 1799 +f 1985 1751 1753 1982 +f 1985 1821 1751 +f 1973 1752 1754 1971 +f 1751 1752 1973 +f 1976 1984 1756 1975 +f 1976 1787 1983 1984 +f 1756 1984 1982 1753 +f 2006 1995 2007 +f 1987 1996 1997 1986 +f 1986 1997 1994 1988 +f 1991 1998 1999 1992 +f 2008 1995 2006 +f 1988 1994 1998 1991 +f 1996 2002 2003 1997 +f 2003 2000 1994 1997 +f 2004 2005 1999 1998 +f 2000 2004 1998 1994 +f 1989 2006 2007 1996 1987 +f 1995 2001 2002 1996 2007 +f 1999 2005 2001 1995 2008 +f 1992 1999 2008 2006 1989 +f 1988 1991 1990 2009 +f 1986 1988 2009 2010 +f 1987 1986 2010 2011 +f 1992 1989 2012 1993 +f 1989 1987 2011 2012 +f 2003 2002 2011 2010 +f 2005 2004 1990 1993 +f 1990 2004 2000 2009 +f 2012 2001 2005 1993 +f 2012 2011 2002 2001 +f 2009 2000 2003 2010 +f 2021 2026 2025 2024 +f 2045 2023 2046 +f 2023 2045 2047 +f 2026 2021 2022 2028 +f 2018 2025 2026 2017 +f 2019 2044 2018 +f 2020 2028 2027 2019 +f 2017 2026 2028 2020 +f 2041 2030 2042 +f 2014 2031 2032 2013 +f 2013 2032 2029 2015 +f 2018 2033 2034 2019 +f 2043 2030 2041 +f 2015 2029 2033 2018 +f 2031 2037 2038 2032 +f 2038 2035 2029 2032 +f 2039 2040 2034 2033 +f 2035 2039 2033 2029 +f 2016 2041 2042 2031 2014 +f 2030 2036 2037 2031 2042 +f 2034 2040 2036 2030 2043 +f 2019 2034 2043 2041 2016 +f 2044 2024 2025 +f 2044 2027 2045 2046 +f 2044 2046 2024 +f 2045 2027 2028 2022 2047 +f 2044 2025 2018 +f 2019 2027 2044 +f 2015 2018 2017 2048 +f 2013 2015 2048 2049 +f 2014 2013 2049 2050 +f 2019 2016 2051 2020 +f 2016 2014 2050 2051 +f 2038 2037 2050 2049 +f 2040 2039 2017 2020 +f 2017 2039 2035 2048 +f 2051 2036 2040 2020 +f 2051 2050 2037 2036 +f 2048 2035 2038 2049 +f 2064 2062 2063 +f 2053 2054 2061 2052 +f 2053 2058 2065 +f 2065 2066 2054 2053 +f 2063 2062 2058 2059 2056 +f 2064 2063 2056 2060 2055 +f 2062 2064 2055 2057 2058 +f 2057 2066 2065 2058 +f 2052 2059 2058 2053 +f 2075 2080 2079 2078 +f 2099 2077 2100 +f 2077 2099 2101 +f 2080 2075 2076 2082 +f 2072 2079 2080 2071 +f 2073 2098 2072 +f 2074 2082 2081 2073 +f 2071 2080 2082 2074 +f 2095 2084 2096 +f 2068 2085 2086 2067 +f 2067 2086 2083 2069 +f 2072 2087 2088 2073 +f 2097 2084 2095 +f 2069 2083 2087 2072 +f 2085 2091 2092 2086 +f 2092 2089 2083 2086 +f 2093 2094 2088 2087 +f 2089 2093 2087 2083 +f 2070 2095 2096 2085 2068 +f 2084 2090 2091 2085 2096 +f 2088 2094 2090 2084 2097 +f 2073 2088 2097 2095 2070 +f 2098 2078 2079 +f 2098 2081 2099 2100 +f 2098 2100 2078 +f 2099 2081 2082 2076 2101 +f 2098 2079 2072 +f 2073 2081 2098 +f 2069 2072 2071 2102 +f 2067 2069 2102 2103 +f 2068 2067 2103 2104 +f 2073 2070 2105 2074 +f 2070 2068 2104 2105 +f 2092 2091 2104 2103 +f 2094 2093 2071 2074 +f 2071 2093 2089 2102 +f 2105 2090 2094 2074 +f 2105 2104 2091 2090 +f 2102 2089 2092 2103 +f 2118 2116 2117 +f 2107 2108 2115 2106 +f 2107 2112 2119 +f 2119 2120 2108 2107 +f 2117 2116 2112 2113 2110 +f 2118 2117 2110 2114 2109 +f 2116 2118 2109 2111 2112 +f 2111 2120 2119 2112 +f 2106 2113 2112 2107 +f 2121 2122 2124 2123 +f 2123 2124 2126 2125 +f 2127 2128 2122 2121 +f 2122 2128 2126 2124 +f 2127 2121 2123 2125 +f 2132 2129 2130 2131 +f 2133 2134 2135 2136 +f 2131 2130 2137 2138 +f 2139 2140 2134 2133 +f 2155 2177 2178 2143 +f 2156 2173 2174 2145 +f 2182 2219 2220 2181 +f 2150 2183 2184 2146 +f 2180 2147 2151 2179 +f 2152 2175 2176 2148 +f 2153 2171 2172 2149 +f 2143 2178 2179 2151 +f 2145 2174 2175 2152 +f 2171 2224 2142 +f 2148 2176 2177 2155 +f 2149 2172 2173 2156 +f 2162 2163 2169 +f 2158 2142 2160 +f 2144 2189 2142 +f 2157 2162 2170 +f 2163 2164 2168 +f 2164 2165 2167 +f 2165 2158 2166 +f 2144 2142 2158 +f 2164 2144 2165 +f 2158 2165 2144 +f 2144 2164 2163 +f 2159 2157 2161 +f 2162 2144 2163 +f 2157 2144 2162 +f 2159 2144 2157 +f 2171 2189 2190 +f 2175 2177 2176 +f 2171 2173 2172 +f 2173 2175 2174 +f 2183 2185 2184 +f 2177 2179 2178 +f 2179 2181 2180 +f 2181 2183 2182 +f 2185 2188 2218 +f 2159 2186 2187 2144 +f 2210 2191 2187 2186 +f 2193 2142 2194 +f 2207 2163 2168 2195 +f 2208 2157 2170 2196 +f 2209 2165 2166 2197 +f 2202 2158 2160 2198 +f 2203 2164 2167 2199 +f 2204 2162 2169 2200 +f 2205 2159 2161 2201 +f 2197 2166 2158 2202 +f 2195 2168 2164 2203 +f 2196 2170 2162 2204 +f 2159 2223 2186 +f 2198 2160 2142 2206 +f 2200 2169 2163 2207 +f 2201 2161 2157 2208 +f 2199 2167 2165 2209 +f 2206 2142 2193 +f 2189 2144 2212 2211 +f 2188 2190 2214 2213 +f 2189 2211 2216 +f 2190 2216 2215 2214 +f 2190 2189 2216 +f 2194 2142 2224 +f 2154 2146 2184 2185 +f 2183 2190 2188 +f 2190 2183 2181 2179 +f 2154 2185 2218 2217 +f 2150 2219 2182 2183 +f 2181 2220 2147 2180 +f 2183 2188 2185 +f 2218 2188 2222 2221 +f 2159 2205 2192 2223 +f 2141 2224 2171 2153 +f 2194 2224 2141 +f 2171 2142 2189 +f 2225 2197 2202 2198 +f 2225 2195 2203 2199 +f 2225 2196 2204 2200 +f 2225 2198 2206 2193 +f 2225 2200 2207 2195 +f 2225 2201 2208 2196 +f 2225 2199 2209 2197 +f 2225 2192 2205 2201 +f 2221 2222 2226 2227 +f 2190 2175 2173 2171 +f 2190 2179 2177 2175 +f 2211 2212 2228 2216 +f 2233 2234 2229 +f 2229 2234 2231 +f 2226 2230 2227 +f 2227 2230 2232 +f 2231 2234 2227 2232 +f 2226 2233 2229 2230 +f 2236 2238 2239 2240 +f 2241 2235 2237 2242 +f 2235 2238 2236 2237 +f 2233 2248 2234 +f 2234 2248 2245 +f 2243 2244 2247 +f 2247 2244 2246 +f 2243 2247 2248 2233 +f 2252 2238 2253 2251 +f 2238 2252 2250 2239 +f 2253 2254 2249 2251 +f 2250 2249 2254 2239 +f 2257 2212 2255 2258 +f 2259 2257 2258 2260 +f 2263 2261 2212 2257 +f 2264 2263 2257 2259 +f 2265 2266 2262 2261 +f 2267 2265 2261 2263 +f 2268 2267 2263 2264 +f 2133 2136 2266 2265 +f 2139 2133 2265 2267 +f 2269 2139 2267 2268 +f 2222 2226 2270 2213 +f 2271 2222 2213 2272 +f 2273 2271 2272 2274 +f 2275 2233 2226 2222 +f 2276 2275 2222 2271 +f 2277 2276 2271 2273 +f 2278 2243 2233 2275 +f 2279 2278 2275 2276 +f 2280 2279 2276 2277 +f 2281 2282 2243 2278 +f 2283 2281 2278 2279 +f 2284 2283 2279 2280 +f 2269 2285 2140 2139 +f 2138 2137 2287 2286 +f 2287 2137 2288 2289 +f 2289 2288 2290 2291 +f 2292 2293 2296 +f 2296 2293 2297 +f 2298 2304 2295 +f 2294 2299 2295 +f 2295 2299 2298 +f 2294 2292 2296 2299 +f 2295 2304 2305 2301 +f 2301 2305 2306 2303 +f 2293 2304 2297 +f 2305 2304 2293 2300 +f 2306 2305 2300 2302 +f 2297 2304 2298 +f 2268 2312 2307 +f 2307 2312 2309 +f 2264 2308 2311 +f 2311 2308 2310 +f 2264 2311 2312 2268 +f 2317 2318 2287 2289 +f 2291 2317 2289 +f 2316 2292 2286 2315 +f 2292 2316 2314 2293 +f 2286 2287 2313 2315 +f 2287 2318 2314 2313 +f 2300 2317 2302 +f 2293 2318 2317 2300 +f 2314 2318 2293 +f 2302 2317 2291 +f 2268 2307 2319 +f 2319 2307 2321 +f 2269 2320 2285 +f 2285 2320 2322 +f 2321 2307 2285 2322 +f 2269 2268 2319 2320 +f 2330 2326 2294 2329 +f 2326 2330 2328 2323 +f 2294 2295 2327 2329 +f 2295 2328 2327 +f 2324 2332 2333 2325 +f 2323 2331 2332 2324 +f 2328 2295 2331 +f 2332 2331 2295 2301 +f 2328 2331 2323 +f 2333 2332 2301 2303 +f 2259 2334 2335 +f 2335 2334 2337 +f 2264 2336 2308 +f 2308 2336 2338 +f 2337 2334 2308 2338 +f 2264 2259 2335 2336 +f 2346 2342 2326 2345 +f 2342 2346 2344 2339 +f 2326 2323 2343 2345 +f 2323 2344 2343 +f 2340 2348 2349 2341 +f 2339 2347 2348 2340 +f 2344 2323 2347 +f 2348 2347 2323 2324 +f 2344 2347 2339 +f 2349 2348 2324 2325 +f 2260 2350 2351 +f 2351 2350 2353 +f 2259 2352 2334 +f 2334 2352 2354 +f 2353 2350 2334 2354 +f 2259 2260 2351 2352 +f 2360 2355 2356 2359 +f 2355 2360 2358 2292 +f 2356 2286 2357 2359 +f 2358 2357 2286 2292 +f 2280 2362 2363 +f 2363 2362 2365 +f 2284 2364 2361 +f 2361 2364 2366 +f 2365 2362 2361 2366 +f 2284 2280 2363 2364 +f 2371 2367 2355 2370 +f 2367 2371 2369 2294 +f 2355 2292 2368 2370 +f 2369 2368 2292 2294 +f 2277 2372 2373 +f 2373 2372 2375 +f 2280 2374 2362 +f 2362 2374 2376 +f 2375 2372 2362 2376 +f 2280 2277 2373 2374 +f 2381 2377 2367 2380 +f 2377 2381 2379 2326 +f 2367 2294 2378 2380 +f 2379 2378 2294 2326 +f 2273 2382 2383 +f 2383 2382 2385 +f 2277 2384 2372 +f 2372 2384 2386 +f 2385 2382 2372 2386 +f 2277 2273 2383 2384 +f 2391 2387 2377 2390 +f 2387 2391 2389 2342 +f 2377 2326 2388 2390 +f 2389 2388 2326 2342 +f 2274 2392 2393 +f 2393 2392 2395 +f 2273 2394 2382 +f 2382 2394 2396 +f 2395 2392 2382 2396 +f 2273 2274 2393 2394 +f 2130 2129 2397 2398 +f 2398 2397 2399 2400 +f 2406 2401 2402 2405 +f 2401 2406 2404 2131 +f 2402 2132 2403 2405 +f 2404 2403 2132 2131 +f 2281 2408 2409 +f 2409 2408 2411 +f 2282 2410 2407 +f 2407 2410 2412 +f 2411 2408 2407 2412 +f 2282 2281 2409 2410 +f 2137 2130 2398 2288 +f 2288 2398 2400 2290 +f 2339 2340 2422 2421 +f 2340 2341 2423 2422 +f 2420 2416 2342 2419 +f 2416 2420 2418 2413 +f 2342 2339 2417 2419 +f 2418 2417 2339 2421 +f 2414 2422 2423 2415 +f 2413 2421 2422 2414 +f 2418 2421 2413 +f 2258 2424 2425 +f 2425 2424 2427 +f 2260 2426 2350 +f 2350 2426 2428 +f 2427 2424 2350 2428 +f 2260 2258 2425 2426 +f 2255 2210 2424 2258 +f 2416 2413 2430 2429 +f 2430 2413 2414 2431 +f 2431 2414 2415 2432 +f 2401 2131 2138 2433 +f 2283 2434 2408 2281 +f 2433 2138 2286 2356 +f 2284 2361 2434 2283 +f 2387 2342 2416 2435 +f 2272 2436 2392 2274 +f 2432 2439 2438 2431 +f 2438 2437 2430 2431 +f 2446 2442 2435 2445 +f 2442 2446 2444 2429 +f 2435 2416 2443 2445 +f 2444 2443 2416 2429 +f 2213 2217 2447 +f 2447 2217 2449 +f 2272 2448 2436 +f 2436 2448 2450 +f 2449 2217 2436 2450 +f 2272 2213 2447 2448 +f 2453 2456 2457 2454 +f 2454 2457 2458 2455 +f 2457 2456 2437 2438 +f 2458 2457 2438 2439 +f 2136 2135 2459 2266 +f 2241 2460 2129 2132 +f 2129 2460 2461 2397 +f 2397 2461 2462 2399 +f 2266 2459 2463 2262 +f 2239 2464 2460 2241 +f 2460 2464 2465 2461 +f 2461 2465 2466 2462 +f 2464 2453 2454 2465 +f 2465 2454 2455 2466 +f 2451 2440 2254 2253 +f 2226 2227 2452 2270 +f 2254 2239 2468 2467 +f 2235 2241 2132 2402 +f 2282 2407 2244 2243 +f 2469 2470 2234 2244 +f 2471 2472 2470 2469 +f 2362 2372 2472 2471 +f 2408 2469 2244 2407 +f 2434 2471 2469 2408 +f 2361 2362 2471 2434 +f 2470 2221 2227 2234 +f 2472 2473 2221 2470 +f 2372 2382 2473 2472 +f 2473 2436 2217 2221 +f 2382 2392 2436 2473 +f 2474 2475 2463 2459 +f 2476 2477 2475 2474 +f 2307 2308 2477 2476 +f 2134 2474 2459 2135 +f 2140 2476 2474 2134 +f 2285 2307 2476 2140 +f 2475 2192 2225 2463 +f 2477 2478 2192 2475 +f 2308 2334 2478 2477 +f 2192 2210 2441 2225 +f 2478 2424 2210 2192 +f 2334 2350 2424 2478 +f 2479 2254 2453 2480 +f 2481 2483 2464 +f 2464 2239 2482 2481 +f 2239 2254 2479 2482 +f 2453 2483 2480 +f 2480 2483 2481 +f 2228 2487 2225 +f 2225 2487 2484 +f 2262 2463 2486 +f 2486 2463 2485 +f 2262 2486 2487 2228 +f 2440 2437 2453 2254 +f 2228 2225 2441 2256 +f 2429 2430 2437 2440 +f 2442 2429 2440 2451 +f 2210 2255 2256 2441 +f 2217 2213 2270 2452 +f 2262 2228 2212 2261 +f 2452 2227 2228 2256 +f 2217 2452 2256 2255 +f 2489 2493 2509 2504 +f 2489 2504 2505 2491 +f 2506 2507 2497 2498 +f 2499 2500 2501 2496 +f 2502 2503 2498 2497 +f 2493 2495 2508 2509 +f 2507 2508 2495 2497 +f 2491 2505 2506 2498 +f 2490 2488 2500 2499 +f 2488 2492 2501 2500 +f 2492 2494 2496 2501 +f 2493 2489 2503 2502 +f 2489 2491 2498 2503 +f 2495 2493 2502 2497 +f 2505 2504 2488 2490 +f 2506 2505 2490 2499 +f 2496 2507 2506 2499 +f 2494 2508 2507 2496 +f 2509 2508 2494 2492 +f 2504 2509 2492 2488 +f 2510 2511 2512 2513 +f 2291 2290 2510 +f 2290 2400 2511 2510 +f 2400 2399 2511 +f 2399 2462 2511 +f 2462 2466 2511 +f 2466 2455 2512 2511 +f 2455 2458 2512 +f 2458 2439 2512 +f 2439 2432 2512 +f 2432 2415 2513 2512 +f 2415 2423 2513 +f 2423 2341 2513 +f 2341 2349 2513 +f 2349 2325 2513 +f 2325 2333 2513 +f 2333 2303 2510 2513 +f 2303 2306 2510 +f 2306 2302 2510 +f 2302 2291 2510 +f 2514 2517 2518 2519 +f 2517 2516 2520 2518 +f 2516 2515 2521 2520 +f 2526 2527 2523 2524 +f 2529 2526 2524 2525 +f 2528 2529 2525 2522 +f 2522 2525 2517 2514 +f 2525 2524 2516 2517 +f 2524 2523 2515 2516 +f 2531 2530 2527 2526 +f 2532 2533 2529 2528 +f 2533 2531 2526 2529 +f 2531 2533 2532 2530 +f 2537 2536 2534 2535 +f 2538 2539 2541 2540 +f 2539 2537 2535 2541 +f 2536 2538 2540 2534 +f 2545 2544 2542 2543 +f 2546 2547 2549 2548 +f 2547 2545 2543 2549 +f 2544 2546 2548 2542 +f 2553 2552 2550 2551 +f 2554 2555 2557 2556 +f 2555 2553 2551 2557 +f 2552 2554 2556 2550 +f 2562 2563 2565 2564 +f 2566 2567 2569 2568 +f 2563 2569 2567 2565 +f 2568 2562 2564 2566 +f 2570 2571 2573 2572 +f 2574 2575 2577 2576 +f 2571 2577 2575 2573 +f 2576 2570 2572 2574 +f 2581 2580 2578 2579 +f 2582 2583 2585 2584 +f 2581 2579 2585 2583 +f 2580 2582 2584 2578 +f 2589 2588 2586 2587 +f 2590 2591 2593 2592 +f 2591 2589 2587 2593 +f 2588 2590 2592 2586 +f 2665 2666 2595 2594 +f 2596 2597 2667 2664 +f 2666 2667 2597 2595 +f 2664 2665 2594 2596 +f 2598 2599 2601 2600 +f 2602 2603 2605 2604 +f 2599 2605 2603 2601 +f 2604 2598 2600 2602 +f 2609 2608 2606 2607 +f 2610 2611 2613 2612 +f 2611 2609 2607 2613 +f 2608 2610 2612 2606 +f 2655 2652 2616 2617 +f 2654 2655 2617 2614 +f 2672 2671 2673 2674 +f 2669 2670 2658 2618 2619 +f 2656 2657 2669 2619 2620 +f 2659 2656 2620 2621 +f 2658 2659 2621 2618 +f 2676 2675 2677 2678 +f 2636 2632 2641 2637 +f 2632 2633 2640 2641 +f 2633 2634 2639 2640 +f 2634 2635 2638 2639 +f 2635 2636 2637 2638 +f 2623 2624 2633 2632 +f 2624 2625 2634 2633 +f 2625 2626 2635 2634 +f 2626 2622 2636 2635 +f 2622 2623 2632 2636 +f 2650 2651 2642 2643 +f 2649 2650 2643 2644 +f 2648 2649 2644 2645 +f 2647 2648 2645 2646 +f 2651 2647 2646 2642 +f 2643 2642 2627 2631 +f 2644 2643 2631 2630 +f 2645 2644 2630 2629 +f 2646 2645 2629 2628 +f 2642 2646 2628 2627 +f 2641 2640 2648 2647 +f 2640 2639 2649 2648 +f 2639 2638 2650 2649 +f 2638 2637 2651 2650 +f 2637 2641 2647 2651 +f 2561 2655 2654 2558 +f 2560 2652 2655 2561 +f 2660 2661 2668 2657 2656 +f 2661 2662 2658 2670 2668 +f 2662 2663 2659 2658 +f 2663 2660 2656 2659 +f 2521 2661 2660 2520 +f 2519 2662 2661 2521 +f 2518 2663 2662 2519 +f 2520 2660 2663 2518 +f 2657 2670 2669 +f 2668 2670 2657 +f 2559 2653 2652 2560 +f 2558 2654 2653 2559 +f 2653 2654 2614 2615 +f 2652 2653 2615 2616 +f 2614 2617 2671 2672 +f 2617 2616 2673 2671 +f 2616 2615 2674 2673 +f 2615 2614 2672 2674 +f 2618 2621 2675 2676 +f 2621 2620 2677 2675 +f 2620 2619 2678 2677 +f 2619 2618 2676 2678 +f 483 482 481 484 +f 389 392 391 390 +f 22 21 24 23 +f 114 113 116 115 +f 206 205 208 207 +f 298 297 300 299 +f 574 573 576 575 +f 666 665 668 667 +f 758 757 760 759 +f 850 849 852 851 +f 942 941 944 943 +f 1991 1992 1993 1990 +f 2021 2024 2046 2023 2047 2022 +f 2075 2078 2100 2077 2101 2076 diff --git a/data/meshes/collision_mesh_01.obj b/data/meshes/collision_mesh_01.obj new file mode 100644 index 0000000..d19b396 --- /dev/null +++ b/data/meshes/collision_mesh_01.obj @@ -0,0 +1,4056 @@ +v 1700.000000000 0.000000000 197.653961182 +v 1666.644653320 0.000000000 200.000000000 +v 1700.000000000 14.302844048 200.000000000 +v 1800.000000000 0.000000000 190.620483398 +v 1800.000000000 57.183097839 200.000000000 +v 1890.002807617 100.000000000 200.000000000 +v 1900.000000000 100.000000000 199.219924927 +v 1900.000000000 0.000000000 182.817306519 +v 2000.000000000 100.000000000 190.620483398 +v 2000.000000000 0.000000000 174.987609863 +v 2100.000000000 100.000000000 182.021072388 +v 2100.000000000 0.000000000 167.184417725 +v 2200.000000000 100.000000000 172.651947021 +v 2200.000000000 0.000000000 159.381240845 +v 2300.000000000 100.000000000 164.052520752 +v 2300.000000000 0.000000000 151.551513672 +v 2400.000000000 100.000000000 154.683395386 +v 2400.000000000 0.000000000 142.978637695 +v 2500.000000000 100.000000000 146.083984375 +v 2500.000000000 0.000000000 135.148910522 +v 2600.000000000 100.000000000 136.714859009 +v 2600.000000000 0.000000000 127.345741272 +v 2700.000000000 100.000000000 128.911682129 +v 2700.000000000 0.000000000 120.312263489 +v 2800.000000000 100.000000000 121.081962585 +v 2800.000000000 0.000000000 113.278785706 +v 2900.000000000 100.000000000 113.278785706 +v 2900.000000000 0.000000000 107.041549683 +v 3000.000000000 100.000000000 107.041549683 +v 3000.000000000 0.000000000 103.113410950 +v 3100.000000000 100.000000000 103.113410950 +v 3100.000000000 0.000000000 100.008071899 +v 3200.000000000 100.000000000 100.008071899 +v 3200.000000000 0.000000000 100.008071899 +v 1900.000000000 104.755889893 200.000000000 +v 2000.000000000 157.183105469 200.000000000 +v 2074.959960938 200.000000000 200.000000000 +v 2100.000000000 200.000000000 197.653961182 +v 2200.000000000 200.000000000 188.284835815 +v 2300.000000000 200.000000000 178.119476318 +v 2400.000000000 200.000000000 167.980651855 +v 2500.000000000 200.000000000 157.815292358 +v 2600.000000000 200.000000000 148.446166992 +v 2700.000000000 200.000000000 139.050506592 +v 2800.000000000 200.000000000 129.681381226 +v 2900.000000000 200.000000000 121.081962585 +v 3000.000000000 200.000000000 113.278785706 +v 3100.000000000 200.000000000 107.811264038 +v 3200.000000000 200.000000000 103.113410950 +v 2100.000000000 214.302856445 200.000000000 +v 2200.000000000 274.939147949 200.000000000 +v 2235.740478516 300.000000000 200.000000000 +v 2300.000000000 300.000000000 192.956130981 +v 2400.000000000 300.000000000 181.251358032 +v 2500.000000000 300.000000000 171.085998535 +v 2600.000000000 300.000000000 160.150939941 +v 2700.000000000 300.000000000 150.012115479 +v 2800.000000000 300.000000000 139.846740723 +v 2900.000000000 300.000000000 129.681381226 +v 3000.000000000 300.000000000 120.312263489 +v 3100.000000000 300.000000000 113.278785706 +v 3200.000000000 300.000000000 107.811264038 +v 2300.000000000 345.057952881 200.000000000 +v 2368.706787109 400.000000000 200.000000000 +v 2400.000000000 400.000000000 196.087997437 +v 2500.000000000 400.000000000 184.383255005 +v 2600.000000000 400.000000000 172.651947021 +v 2700.000000000 400.000000000 161.716873169 +v 2800.000000000 400.000000000 150.012115479 +v 2900.000000000 400.000000000 139.050506592 +v 3000.000000000 400.000000000 129.681381226 +v 3100.000000000 400.000000000 121.081962585 +v 3200.000000000 400.000000000 113.278785706 +v 2400.000000000 425.024078369 200.000000000 +v 2493.759765625 500.000000000 200.000000000 +v 2500.000000000 500.000000000 199.219924927 +v 2600.000000000 500.000000000 186.718902588 +v 2700.000000000 500.000000000 174.217895508 +v 2800.000000000 500.000000000 161.716873169 +v 2900.000000000 500.000000000 150.012115479 +v 3000.000000000 500.000000000 139.846740723 +v 3100.000000000 500.000000000 129.681381226 +v 3200.000000000 500.000000000 121.081962585 +v 2500.000000000 505.257843018 200.000000000 +v 2600.000000000 594.413452148 200.000000000 +v 2606.286376953 600.000000000 200.000000000 +v 2700.000000000 600.000000000 188.284835815 +v 2800.000000000 600.000000000 174.987609863 +v 2900.000000000 600.000000000 162.513122559 +v 3000.000000000 600.000000000 150.781829834 +v 3100.000000000 600.000000000 139.846740723 +v 3200.000000000 600.000000000 128.911682129 +v 2700.000000000 683.281433105 200.000000000 +v 2716.718505859 700.000000000 200.000000000 +v 2800.000000000 700.000000000 188.284835815 +v 2900.000000000 700.000000000 174.987609863 +v 3000.000000000 700.000000000 162.513122559 +v 3100.000000000 700.000000000 150.781829834 +v 3200.000000000 700.000000000 139.050506592 +v 2800.000000000 778.960937500 200.000000000 +v 2822.190185547 800.000000000 200.000000000 +v 2900.000000000 800.000000000 189.054550171 +v 3000.000000000 800.000000000 174.987609863 +v 3100.000000000 800.000000000 161.716873169 +v 3200.000000000 800.000000000 150.012115479 +v 2900.000000000 877.809692383 200.000000000 +v 2921.039062500 900.000000000 200.000000000 +v 3000.000000000 900.000000000 188.284835815 +v 3100.000000000 900.000000000 174.987609863 +v 3200.000000000 900.000000000 160.947174072 +v 3000.000000000 978.960998535 200.000000000 +v 3021.039062500 1000.000000000 200.000000000 +v 3100.000000000 1000.000000000 188.284835815 +v 3200.000000000 1000.000000000 174.217895508 +v 3100.000000000 1078.960937500 200.000000000 +v 3119.030273438 1100.000000000 200.000000000 +v 3200.000000000 1100.000000000 186.718902588 +v 3200.000000000 1194.413452148 200.000000000 +v 500.000000000 0.000000000 296.096099854 +v 475.027648926 0.000000000 300.000000000 +v 500.000000000 20.833856583 300.000000000 +v 600.000000000 0.000000000 282.029144287 +v 600.000000000 95.769119263 300.000000000 +v 606.767517090 100.000000000 300.000000000 +v 700.000000000 100.000000000 289.062622070 +v 700.000000000 0.000000000 273.429718018 +v 800.000000000 100.000000000 278.897247314 +v 800.000000000 0.000000000 263.290893555 +v 900.000000000 100.000000000 271.094085693 +v 900.000000000 0.000000000 255.461166382 +v 1000.000000000 100.000000000 264.060607910 +v 1000.000000000 0.000000000 248.427703857 +v 1100.000000000 100.000000000 256.257415771 +v 1100.000000000 0.000000000 240.624526978 +v 1200.000000000 100.000000000 249.223953247 +v 1200.000000000 0.000000000 232.821350098 +v 1300.000000000 100.000000000 242.960174561 +v 1300.000000000 0.000000000 225.787872314 +v 1400.000000000 100.000000000 235.926696777 +v 1400.000000000 0.000000000 217.958145142 +v 1500.000000000 100.000000000 228.893234253 +v 1500.000000000 0.000000000 210.924667358 +v 1600.000000000 100.000000000 221.886276245 +v 1600.000000000 0.000000000 204.687423706 +v 1700.000000000 100.000000000 214.056564331 +v 1800.000000000 100.000000000 207.023101807 +v 700.000000000 158.369262695 300.000000000 +v 771.338012695 200.000000000 300.000000000 +v 800.000000000 200.000000000 296.865783691 +v 900.000000000 200.000000000 288.292907715 +v 1000.000000000 200.000000000 281.259429932 +v 1100.000000000 200.000000000 274.995666504 +v 1200.000000000 200.000000000 268.758422852 +v 1300.000000000 200.000000000 260.928710938 +v 1400.000000000 200.000000000 254.691482544 +v 1500.000000000 200.000000000 246.861740112 +v 1600.000000000 200.000000000 239.058593750 +v 1700.000000000 200.000000000 231.255386353 +v 1800.000000000 200.000000000 223.425704956 +v 1900.000000000 200.000000000 215.622528076 +v 2000.000000000 200.000000000 207.023101807 +v 800.000000000 214.313644409 300.000000000 +v 900.000000000 257.658477783 300.000000000 +v 1000.000000000 295.935821533 300.000000000 +v 1012.674682617 300.000000000 300.000000000 +v 1100.000000000 300.000000000 294.530151367 +v 1200.000000000 300.000000000 288.292907715 +v 1300.000000000 300.000000000 281.259429932 +v 1400.000000000 300.000000000 273.429718018 +v 1500.000000000 300.000000000 265.626556396 +v 1600.000000000 300.000000000 257.823364258 +v 1700.000000000 300.000000000 249.223953247 +v 1800.000000000 300.000000000 241.394226074 +v 1900.000000000 300.000000000 232.821350098 +v 2000.000000000 300.000000000 223.425704956 +v 2100.000000000 300.000000000 214.056564331 +v 2200.000000000 300.000000000 203.917739868 +v 1100.000000000 324.131988525 300.000000000 +v 1200.000000000 355.552612305 300.000000000 +v 1300.000000000 392.298980713 300.000000000 +v 1320.038330078 400.000000000 300.000000000 +v 1400.000000000 400.000000000 293.760437012 +v 1500.000000000 400.000000000 285.930725098 +v 1600.000000000 400.000000000 277.331298828 +v 1700.000000000 400.000000000 269.528137207 +v 1800.000000000 400.000000000 260.928710938 +v 1900.000000000 400.000000000 251.559585571 +v 2000.000000000 400.000000000 240.624526978 +v 2100.000000000 400.000000000 230.459167480 +v 2200.000000000 400.000000000 219.524093628 +v 2300.000000000 400.000000000 208.589035034 +v 1400.000000000 428.530029297 300.000000000 +v 1500.000000000 464.330963135 300.000000000 +v 1583.261352539 500.000000000 300.000000000 +v 1600.000000000 500.000000000 298.431732178 +v 1700.000000000 500.000000000 289.832305908 +v 1800.000000000 500.000000000 280.463195801 +v 1900.000000000 500.000000000 270.324371338 +v 2000.000000000 500.000000000 259.362762451 +v 2100.000000000 500.000000000 247.658020020 +v 2200.000000000 500.000000000 235.926696777 +v 2300.000000000 500.000000000 224.221923828 +v 2400.000000000 500.000000000 211.720916748 +v 1600.000000000 507.170806885 300.000000000 +v 1700.000000000 548.187133789 300.000000000 +v 1799.978881836 600.000000000 300.000000000 +v 1900.000000000 600.000000000 289.062622070 +v 2000.000000000 600.000000000 277.331298828 +v 2100.000000000 600.000000000 265.626556396 +v 2200.000000000 600.000000000 253.125518799 +v 2300.000000000 600.000000000 240.624526978 +v 2400.000000000 600.000000000 227.353805542 +v 2500.000000000 600.000000000 214.056564331 +v 2600.000000000 600.000000000 200.785858154 +v 0.000000000 3102.962158203 1100.000000000 +v 0.000000000 3200.000000000 1125.780883789 +v 59.996593475 3200.000000000 1100.000000000 +v 1900.000000000 655.990112305 300.000000000 +v 1968.771362305 700.000000000 300.000000000 +v 2000.000000000 700.000000000 296.096099854 +v 2100.000000000 700.000000000 283.595092773 +v 2200.000000000 700.000000000 270.324371338 +v 2300.000000000 700.000000000 257.823364258 +v 2400.000000000 700.000000000 243.756408691 +v 2500.000000000 700.000000000 230.459167480 +v 2600.000000000 700.000000000 216.418746948 +v 2700.000000000 700.000000000 202.351791382 +v 2000.000000000 720.833862305 300.000000000 +v 2100.000000000 791.297973633 300.000000000 +v 2111.782470703 800.000000000 300.000000000 +v 2200.000000000 800.000000000 288.292907715 +v 2300.000000000 800.000000000 274.995666504 +v 2400.000000000 800.000000000 260.928710938 +v 2500.000000000 800.000000000 246.092056274 +v 2600.000000000 800.000000000 232.025100708 +v 2700.000000000 800.000000000 217.188446045 +v 2800.000000000 800.000000000 203.121490479 +v 2200.000000000 862.476989746 300.000000000 +v 2249.983642578 900.000000000 300.000000000 +v 2300.000000000 900.000000000 292.964202881 +v 2400.000000000 900.000000000 278.127563477 +v 2500.000000000 900.000000000 263.290893555 +v 2600.000000000 900.000000000 248.427703857 +v 2700.000000000 900.000000000 232.821350098 +v 2800.000000000 900.000000000 217.958145142 +v 2900.000000000 900.000000000 203.121490479 +v 2300.000000000 939.156250000 300.000000000 +v 2373.687255859 1000.000000000 300.000000000 +v 2400.000000000 1000.000000000 296.096099854 +v 2500.000000000 1000.000000000 280.463195801 +v 2600.000000000 1000.000000000 265.626556396 +v 2700.000000000 1000.000000000 249.993652344 +v 2800.000000000 1000.000000000 233.591049194 +v 2900.000000000 1000.000000000 218.754394531 +v 3000.000000000 1000.000000000 203.121490479 +v 2400.000000000 1021.726318359 300.000000000 +v 2489.968017578 1100.000000000 300.000000000 +v 2500.000000000 1100.000000000 298.431732178 +v 2600.000000000 1100.000000000 282.029144287 +v 2700.000000000 1100.000000000 266.396240234 +v 2800.000000000 1100.000000000 250.789886475 +v 2900.000000000 1100.000000000 234.387283325 +v 3000.000000000 1100.000000000 218.754394531 +v 3100.000000000 1100.000000000 203.121490479 +v 2500.000000000 1109.118408203 300.000000000 +v 2599.985107422 1200.000000000 300.000000000 +v 2700.000000000 1200.000000000 283.595092773 +v 2800.000000000 1200.000000000 267.192474365 +v 2900.000000000 1200.000000000 250.789886475 +v 3000.000000000 1200.000000000 233.591049194 +v 3100.000000000 1200.000000000 217.188446045 +v 3200.000000000 1200.000000000 200.785858154 +v 300.000000000 3196.815429688 1000.000000000 +v 300.000000000 3200.000000000 1000.770874023 +v 302.014007568 3200.000000000 1000.000000000 +v 2700.000000000 1291.297851562 300.000000000 +v 2709.091552734 1300.000000000 300.000000000 +v 2800.000000000 1300.000000000 284.364776611 +v 2900.000000000 1300.000000000 267.962188721 +v 3000.000000000 1300.000000000 249.993652344 +v 3100.000000000 1300.000000000 232.821350098 +v 3200.000000000 1300.000000000 215.622528076 +v 2800.000000000 1387.014282227 300.000000000 +v 2813.587646484 1400.000000000 300.000000000 +v 2900.000000000 1400.000000000 285.161041260 +v 3000.000000000 1400.000000000 267.192474365 +v 3100.000000000 1400.000000000 249.993652344 +v 3200.000000000 1400.000000000 230.459167480 +v 2900.000000000 1486.412109375 300.000000000 +v 2912.985595703 1500.000000000 300.000000000 +v 3000.000000000 1500.000000000 284.364776611 +v 3100.000000000 1500.000000000 265.626556396 +v 3200.000000000 1500.000000000 246.861740112 +v 3000.000000000 1590.908569336 300.000000000 +v 3008.344726562 1600.000000000 300.000000000 +v 3100.000000000 1600.000000000 282.825378418 +v 3200.000000000 1600.000000000 263.290893555 +v 3099.988281250 1700.000000000 300.000000000 +v 3200.000000000 1700.000000000 279.693481445 +v 240.016510010 3100.000000000 1000.000000000 +v 200.000000000 3100.000000000 1015.634033203 +v 200.000000000 3200.000000000 1039.839843750 +v 3185.146240234 1800.000000000 300.000000000 +v 3200.000000000 1800.000000000 296.865783691 +v 3200.000000000 1816.044677734 300.000000000 +v 48.268959045 100.000000000 400.000000000 +v 100.000000000 100.000000000 388.274444580 +v 100.000000000 0.000000000 364.838378906 +v 0.000000000 0.000000000 387.504760742 +v 0.000000000 53.316284180 400.000000000 +v 200.000000000 100.000000000 366.404327393 +v 200.000000000 0.000000000 346.100128174 +v 300.000000000 100.000000000 347.666076660 +v 300.000000000 0.000000000 328.131591797 +v 400.000000000 100.000000000 330.467224121 +v 400.000000000 0.000000000 311.729003906 +v 500.000000000 100.000000000 314.834350586 +v 600.000000000 100.000000000 300.793914795 +v 100.000000000 146.898437500 400.000000000 +v 158.642028809 200.000000000 400.000000000 +v 200.000000000 200.000000000 390.636627197 +v 300.000000000 200.000000000 370.305908203 +v 400.000000000 200.000000000 352.337371826 +v 500.000000000 200.000000000 335.934753418 +v 600.000000000 200.000000000 321.098114014 +v 700.000000000 200.000000000 307.800872803 +v 200.000000000 237.490249634 400.000000000 +v 276.891082764 300.000000000 400.000000000 +v 300.000000000 300.000000000 395.307922363 +v 400.000000000 300.000000000 375.003753662 +v 500.000000000 300.000000000 358.601135254 +v 600.000000000 300.000000000 342.968231201 +v 700.000000000 300.000000000 329.697540283 +v 800.000000000 300.000000000 318.762481689 +v 900.000000000 300.000000000 308.597106934 +v 1000.000000000 300.000000000 300.793914795 +v 300.000000000 318.766815186 400.000000000 +v 400.000000000 399.976928711 400.000000000 +v 500.000000000 400.000000000 381.240966797 +v 600.000000000 400.000000000 365.634613037 +v 700.000000000 400.000000000 352.337371826 +v 800.000000000 400.000000000 341.402313232 +v 900.000000000 400.000000000 332.033172607 +v 1000.000000000 400.000000000 324.230010986 +v 1100.000000000 400.000000000 317.196533203 +v 1200.000000000 400.000000000 309.366790771 +v 1300.000000000 400.000000000 301.563629150 +v 500.000000000 472.714294434 400.000000000 +v 542.915405273 500.000000000 400.000000000 +v 600.000000000 500.000000000 390.636627197 +v 700.000000000 500.000000000 377.339385986 +v 800.000000000 500.000000000 365.634613037 +v 900.000000000 500.000000000 356.238952637 +v 1000.000000000 500.000000000 347.666076660 +v 1100.000000000 500.000000000 339.836364746 +v 1200.000000000 500.000000000 331.236938477 +v 1300.000000000 500.000000000 323.433746338 +v 1400.000000000 500.000000000 315.630584717 +v 1500.000000000 500.000000000 307.800872803 +v 600.000000000 535.278320312 400.000000000 +v 700.000000000 587.837768555 400.000000000 +v 726.745849609 600.000000000 400.000000000 +v 800.000000000 600.000000000 391.406341553 +v 900.000000000 600.000000000 382.037231445 +v 1000.000000000 600.000000000 373.437805176 +v 1100.000000000 600.000000000 365.634613037 +v 1200.000000000 600.000000000 357.035186768 +v 1300.000000000 600.000000000 348.435791016 +v 1400.000000000 600.000000000 339.066650391 +v 1500.000000000 600.000000000 329.697540283 +v 1600.000000000 600.000000000 320.301879883 +v 1700.000000000 600.000000000 310.932739258 +v 800.000000000 632.345947266 400.000000000 +v 900.000000000 667.610656738 400.000000000 +v 1000.000000000 699.978332520 400.000000000 +v 1100.000000000 700.000000000 391.406341553 +v 1200.000000000 700.000000000 382.037231445 +v 1300.000000000 700.000000000 372.668090820 +v 1400.000000000 700.000000000 362.502716064 +v 1500.000000000 700.000000000 353.133605957 +v 1600.000000000 700.000000000 343.737945557 +v 1700.000000000 700.000000000 332.033172607 +v 1800.000000000 700.000000000 320.301879883 +v 1900.000000000 700.000000000 308.597106934 +v 1100.000000000 732.345947266 400.000000000 +v 1200.000000000 769.699584961 400.000000000 +v 1271.411865234 800.000000000 400.000000000 +v 1300.000000000 800.000000000 396.873870850 +v 1400.000000000 800.000000000 386.708496094 +v 1500.000000000 800.000000000 376.569671631 +v 1600.000000000 800.000000000 365.634613037 +v 1700.000000000 800.000000000 353.133605957 +v 1800.000000000 800.000000000 340.632598877 +v 1900.000000000 800.000000000 328.131591797 +v 2000.000000000 800.000000000 314.834350586 +v 2100.000000000 800.000000000 301.563629150 +v 1300.000000000 812.503540039 400.000000000 +v 1400.000000000 856.713745117 400.000000000 +v 1492.770996094 900.000000000 400.000000000 +v 1500.000000000 900.000000000 399.209503174 +v 1600.000000000 900.000000000 388.274444580 +v 1700.000000000 900.000000000 375.003753662 +v 1800.000000000 900.000000000 361.706481934 +v 1900.000000000 900.000000000 348.435791016 +v 2000.000000000 900.000000000 334.368835449 +v 2100.000000000 900.000000000 321.098114014 +v 2200.000000000 900.000000000 307.031158447 +v 1500.000000000 903.372924805 400.000000000 +v 1600.000000000 955.570190430 400.000000000 +v 1666.644653320 1000.000000000 400.000000000 +v 1700.000000000 1000.000000000 395.307922363 +v 1800.000000000 1000.000000000 382.806915283 +v 1900.000000000 1000.000000000 368.739959717 +v 2000.000000000 1000.000000000 354.699554443 +v 2100.000000000 1000.000000000 339.836364746 +v 2200.000000000 1000.000000000 325.769409180 +v 2300.000000000 1000.000000000 310.932739258 +v 1700.000000000 1020.700622559 400.000000000 +v 1800.000000000 1081.482177734 400.000000000 +v 1826.335693359 1100.000000000 400.000000000 +v 1900.000000000 1100.000000000 389.070678711 +v 2000.000000000 1100.000000000 375.003753662 +v 2100.000000000 1100.000000000 359.370849609 +v 2200.000000000 1100.000000000 344.534179688 +v 2300.000000000 1100.000000000 328.901306152 +v 2400.000000000 1100.000000000 314.064636230 +v 1900.000000000 1153.827880859 400.000000000 +v 1963.187377930 1200.000000000 400.000000000 +v 2000.000000000 1200.000000000 394.538238525 +v 2100.000000000 1200.000000000 378.905334473 +v 2200.000000000 1200.000000000 363.272430420 +v 2300.000000000 1200.000000000 347.666076660 +v 2400.000000000 1200.000000000 332.033172607 +v 2500.000000000 1200.000000000 315.630584717 +v 2000.000000000 1229.147705078 400.000000000 +v 2084.926513672 1300.000000000 400.000000000 +v 2100.000000000 1300.000000000 397.643585205 +v 2200.000000000 1300.000000000 382.037231445 +v 2300.000000000 1300.000000000 365.634613037 +v 2400.000000000 1300.000000000 350.001708984 +v 2500.000000000 1300.000000000 334.368835449 +v 2600.000000000 1300.000000000 317.966217041 +v 2700.000000000 1300.000000000 301.563629150 +v 2100.000000000 1312.062866211 400.000000000 +v 2200.000000000 1395.861572266 400.000000000 +v 2204.727539062 1400.000000000 400.000000000 +v 2300.000000000 1400.000000000 384.372863770 +v 2400.000000000 1400.000000000 368.739959717 +v 2500.000000000 1400.000000000 352.337371826 +v 2600.000000000 1400.000000000 335.934753418 +v 2700.000000000 1400.000000000 319.532165527 +v 2800.000000000 1400.000000000 302.333343506 +v 2300.000000000 1479.997680664 400.000000000 +v 2323.821533203 1500.000000000 400.000000000 +v 2400.000000000 1500.000000000 387.504760742 +v 2500.000000000 1500.000000000 371.871856689 +v 2600.000000000 1500.000000000 354.699554443 +v 2700.000000000 1500.000000000 337.500701904 +v 2800.000000000 1500.000000000 320.301879883 +v 2900.000000000 1500.000000000 302.333343506 +v 2400.000000000 1566.683227539 400.000000000 +v 2442.078125000 1600.000000000 400.000000000 +v 2500.000000000 1600.000000000 391.406341553 +v 2600.000000000 1600.000000000 374.207489014 +v 2700.000000000 1600.000000000 357.035186768 +v 2800.000000000 1600.000000000 338.270416260 +v 2900.000000000 1600.000000000 320.301879883 +v 3000.000000000 1600.000000000 301.563629150 +v 2500.000000000 1645.861572266 400.000000000 +v 2565.002929688 1700.000000000 400.000000000 +v 2600.000000000 1700.000000000 394.538238525 +v 2700.000000000 1700.000000000 376.569671631 +v 2800.000000000 1700.000000000 357.804901123 +v 2900.000000000 1700.000000000 339.066650391 +v 3000.000000000 1700.000000000 319.532165527 +v 2600.000000000 1729.147705078 400.000000000 +v 2677.313232422 1800.000000000 400.000000000 +v 2700.000000000 1800.000000000 396.104156494 +v 2800.000000000 1800.000000000 377.339385986 +v 2900.000000000 1800.000000000 358.601135254 +v 3000.000000000 1800.000000000 339.066650391 +v 3100.000000000 1800.000000000 317.966217041 +v 2700.000000000 1819.970458984 400.000000000 +v 2783.316894531 1900.000000000 400.000000000 +v 2800.000000000 1900.000000000 396.873870850 +v 2900.000000000 1900.000000000 378.905334473 +v 3000.000000000 1900.000000000 358.601135254 +v 3100.000000000 1900.000000000 337.500701904 +v 3200.000000000 1900.000000000 316.400268555 +v 2800.000000000 1915.396484375 400.000000000 +v 2891.673828125 2000.000000000 400.000000000 +v 2900.000000000 2000.000000000 398.439819336 +v 3000.000000000 2000.000000000 378.135620117 +v 3100.000000000 2000.000000000 357.804901123 +v 3200.000000000 2000.000000000 335.934753418 +v 2900.000000000 2007.684082031 400.000000000 +v 2992.316162109 2100.000000000 400.000000000 +v 3000.000000000 2100.000000000 398.439819336 +v 3100.000000000 2100.000000000 378.135620117 +v 3200.000000000 2100.000000000 356.238952637 +v 3000.000000000 2107.684082031 400.000000000 +v 3088.832275391 2200.000000000 400.000000000 +v 3100.000000000 2200.000000000 397.643585205 +v 3200.000000000 2200.000000000 375.773437500 +v 3100.000000000 2211.167724609 400.000000000 +v 3182.791992188 2300.000000000 400.000000000 +v 3200.000000000 2300.000000000 396.104156494 +v 3200.000000000 2320.790771484 400.000000000 +v 0.000000000 100.000000000 410.940826416 +v 0.000000000 200.000000000 437.508789062 +v 100.000000000 200.000000000 413.276489258 +v 0.000000000 300.000000000 464.050201416 +v 100.000000000 300.000000000 439.074768066 +v 200.000000000 300.000000000 415.612121582 +v 0.000000000 400.000000000 489.052185059 +v 100.000000000 400.000000000 464.846435547 +v 200.000000000 400.000000000 441.410339355 +v 300.000000000 400.000000000 420.309936523 +v 100.000000000 3100.000000000 1057.808349609 +v 100.000000000 3200.000000000 1082.810302734 +v 54.821578979 500.000000000 500.000000000 +v 100.000000000 500.000000000 489.052185059 +v 0.000000000 445.178405762 500.000000000 +v 200.000000000 500.000000000 466.412414551 +v 300.000000000 500.000000000 445.311920166 +v 400.000000000 500.000000000 425.777496338 +v 500.000000000 500.000000000 407.039245605 +v 100.000000000 545.178405762 500.000000000 +v 162.958648682 600.000000000 500.000000000 +v 200.000000000 600.000000000 492.184112549 +v 300.000000000 600.000000000 471.879913330 +v 400.000000000 600.000000000 452.345428467 +v 500.000000000 600.000000000 433.580627441 +v 600.000000000 600.000000000 417.178070068 +v 700.000000000 600.000000000 403.137634277 +v 200.000000000 630.327392578 500.000000000 +v 295.824523926 700.000000000 500.000000000 +v 300.000000000 700.000000000 499.217590332 +v 400.000000000 700.000000000 479.683105469 +v 500.000000000 700.000000000 460.944854736 +v 600.000000000 700.000000000 444.542266846 +v 700.000000000 700.000000000 429.679046631 +v 800.000000000 700.000000000 417.974273682 +v 900.000000000 700.000000000 408.605194092 +v 0.000000000 3100.000000000 1099.213012695 +v 300.000000000 702.944946289 500.000000000 +v 400.000000000 770.291931152 500.000000000 +v 447.787414551 800.000000000 500.000000000 +v 500.000000000 800.000000000 490.618194580 +v 600.000000000 800.000000000 474.215606689 +v 700.000000000 800.000000000 458.582702637 +v 800.000000000 800.000000000 446.877899170 +v 900.000000000 800.000000000 436.712554932 +v 1000.000000000 800.000000000 428.113128662 +v 1100.000000000 800.000000000 417.974273682 +v 1200.000000000 800.000000000 407.808929443 +v 500.000000000 833.347045898 500.000000000 +v 600.000000000 889.208435059 500.000000000 +v 619.986511230 900.000000000 500.000000000 +v 700.000000000 900.000000000 487.512817383 +v 800.000000000 900.000000000 476.551208496 +v 900.000000000 900.000000000 466.412414551 +v 1000.000000000 900.000000000 455.477325439 +v 1100.000000000 900.000000000 443.746032715 +v 1200.000000000 900.000000000 432.810913086 +v 1300.000000000 900.000000000 421.875915527 +v 1400.000000000 900.000000000 410.144622803 +v 700.000000000 942.082092285 500.000000000 +v 800.000000000 981.053161621 500.000000000 +v 853.921997070 1000.000000000 500.000000000 +v 900.000000000 1000.000000000 495.316040039 +v 1000.000000000 1000.000000000 482.018768311 +v 1100.000000000 1000.000000000 468.748046875 +v 1200.000000000 1000.000000000 459.378906250 +v 1300.000000000 1000.000000000 447.647613525 +v 1400.000000000 1000.000000000 435.146606445 +v 1500.000000000 1000.000000000 422.645629883 +v 1600.000000000 1000.000000000 409.374847412 +v 900.000000000 1019.350708008 500.000000000 +v 1000.000000000 1071.919189453 500.000000000 +v 1064.204101562 1100.000000000 500.000000000 +v 1100.000000000 1100.000000000 496.085693359 +v 1200.000000000 1100.000000000 484.380950928 +v 1300.000000000 1100.000000000 471.879913330 +v 1400.000000000 1100.000000000 458.582702637 +v 1500.000000000 1100.000000000 445.311920166 +v 1600.000000000 1100.000000000 431.245056152 +v 1700.000000000 1100.000000000 417.974273682 +v 1800.000000000 1100.000000000 403.907348633 +v 1100.000000000 1117.269287109 500.000000000 +v 1200.000000000 1168.989257812 500.000000000 +v 1250.004028320 1200.000000000 500.000000000 +v 1300.000000000 1200.000000000 492.980346680 +v 1400.000000000 1200.000000000 482.018768311 +v 1500.000000000 1200.000000000 467.978332520 +v 1600.000000000 1200.000000000 453.115142822 +v 1700.000000000 1200.000000000 439.074768066 +v 1800.000000000 1200.000000000 425.007781982 +v 1900.000000000 1200.000000000 409.374847412 +v 1300.000000000 1234.572387695 500.000000000 +v 1399.904541016 1300.000000000 500.000000000 +v 1500.000000000 1300.000000000 488.282531738 +v 1600.000000000 1300.000000000 474.215606689 +v 1700.000000000 1300.000000000 459.378906250 +v 1800.000000000 1300.000000000 443.746032715 +v 1900.000000000 1300.000000000 428.909362793 +v 2000.000000000 1300.000000000 413.276489258 +v 200.000000000 3037.468994141 1000.000000000 +v 1500.000000000 1371.436645508 500.000000000 +v 1540.027465820 1400.000000000 500.000000000 +v 1600.000000000 1400.000000000 492.980346680 +v 1700.000000000 1400.000000000 479.683105469 +v 1800.000000000 1400.000000000 464.846435547 +v 1900.000000000 1400.000000000 449.213562012 +v 2000.000000000 1400.000000000 432.810913086 +v 2100.000000000 1400.000000000 417.178070068 +v 2200.000000000 1400.000000000 400.775421143 +v 1600.000000000 1442.795898438 500.000000000 +v 1675.057617188 1500.000000000 500.000000000 +v 1700.000000000 1500.000000000 496.881958008 +v 1800.000000000 1500.000000000 484.380950928 +v 1900.000000000 1500.000000000 468.748046875 +v 2000.000000000 1500.000000000 452.345428467 +v 2100.000000000 1500.000000000 436.712554932 +v 2200.000000000 1500.000000000 420.309936523 +v 2300.000000000 1500.000000000 403.907348633 +v 1700.000000000 1519.979370117 500.000000000 +v 1799.898559570 1600.000000000 500.000000000 +v 1900.000000000 1600.000000000 488.282531738 +v 2000.000000000 1600.000000000 471.879913330 +v 2100.000000000 1600.000000000 455.477325439 +v 2200.000000000 1600.000000000 439.844421387 +v 2300.000000000 1600.000000000 423.441833496 +v 2400.000000000 1600.000000000 406.242980957 +v 177.374542236 3000.000000000 1000.000000000 +v 100.000000000 3000.000000000 1032.036621094 +v 1900.000000000 1674.953857422 500.000000000 +v 1931.320922852 1700.000000000 500.000000000 +v 2000.000000000 1700.000000000 491.414398193 +v 2100.000000000 1700.000000000 475.011840820 +v 2200.000000000 1700.000000000 458.582702637 +v 2300.000000000 1700.000000000 442.180053711 +v 2400.000000000 1700.000000000 425.777496338 +v 2500.000000000 1700.000000000 410.144622803 +v 2000.000000000 1755.013427734 500.000000000 +v 2050.003906250 1800.000000000 500.000000000 +v 2100.000000000 1800.000000000 492.980346680 +v 2200.000000000 1800.000000000 476.551208496 +v 2300.000000000 1800.000000000 460.944854736 +v 2400.000000000 1800.000000000 445.311920166 +v 2500.000000000 1800.000000000 428.113128662 +v 2600.000000000 1800.000000000 413.276489258 +v 2100.000000000 1842.795898438 500.000000000 +v 2166.702148438 1900.000000000 500.000000000 +v 2200.000000000 1900.000000000 495.316040039 +v 2300.000000000 1900.000000000 479.683105469 +v 2400.000000000 1900.000000000 463.280548096 +v 2500.000000000 1900.000000000 447.647613525 +v 2600.000000000 1900.000000000 430.475341797 +v 2700.000000000 1900.000000000 415.612121582 +v 2200.000000000 1926.067749023 500.000000000 +v 2284.978027344 2000.000000000 500.000000000 +v 2300.000000000 2000.000000000 497.651611328 +v 2400.000000000 2000.000000000 482.018768311 +v 2500.000000000 2000.000000000 467.182098389 +v 2600.000000000 2000.000000000 450.779541016 +v 2700.000000000 2000.000000000 435.942840576 +v 2800.000000000 2000.000000000 417.178070068 +v 2300.000000000 2013.069335938 500.000000000 +v 2399.918701172 2100.000000000 500.000000000 +v 2500.000000000 2100.000000000 485.150634766 +v 2600.000000000 2100.000000000 469.544281006 +v 2700.000000000 2100.000000000 454.681121826 +v 2800.000000000 2100.000000000 437.508789062 +v 2900.000000000 2100.000000000 418.743988037 +v 0.000000000 3000.000000000 1072.645019531 +v 2500.000000000 2182.640869141 500.000000000 +v 2521.023437500 2200.000000000 500.000000000 +v 2600.000000000 2200.000000000 488.282531738 +v 2700.000000000 2200.000000000 471.879913330 +v 2800.000000000 2200.000000000 456.247039795 +v 2900.000000000 2200.000000000 438.278472900 +v 3000.000000000 2200.000000000 418.743988037 +v 2600.000000000 2268.129638672 500.000000000 +v 2635.062988281 2300.000000000 500.000000000 +v 2700.000000000 2300.000000000 489.848480225 +v 2800.000000000 2300.000000000 474.215606689 +v 2900.000000000 2300.000000000 458.582702637 +v 3000.000000000 2300.000000000 439.844421387 +v 3100.000000000 2300.000000000 418.743988037 +v 2700.000000000 2359.115722656 500.000000000 +v 2744.986572266 2400.000000000 500.000000000 +v 2800.000000000 2400.000000000 491.414398193 +v 2900.000000000 2400.000000000 475.011840820 +v 3000.000000000 2400.000000000 457.812988281 +v 3100.000000000 2400.000000000 438.278472900 +v 3200.000000000 2400.000000000 414.842407227 +v 2800.000000000 2452.342773438 500.000000000 +v 2847.657226562 2500.000000000 500.000000000 +v 2900.000000000 2500.000000000 491.414398193 +v 3000.000000000 2500.000000000 474.215606689 +v 3100.000000000 2500.000000000 455.477325439 +v 3200.000000000 2500.000000000 434.376892090 +v 2900.000000000 2549.996826172 500.000000000 +v 2947.787597656 2600.000000000 500.000000000 +v 3000.000000000 2600.000000000 490.618194580 +v 3100.000000000 2600.000000000 471.083679199 +v 3200.000000000 2600.000000000 450.779541016 +v 3000.000000000 2652.212402344 500.000000000 +v 3043.956542969 2700.000000000 500.000000000 +v 3100.000000000 2700.000000000 489.052185059 +v 3200.000000000 2700.000000000 468.748046875 +v 3100.000000000 2763.654052734 500.000000000 +v 3133.359863281 2800.000000000 500.000000000 +v 3200.000000000 2800.000000000 487.512817383 +v 3200.000000000 2884.164306641 500.000000000 +v 0.000000000 500.000000000 513.284545898 +v 0.000000000 600.000000000 535.924377441 +v 100.000000000 600.000000000 513.284545898 +v 0.000000000 700.000000000 557.821044922 +v 100.000000000 700.000000000 537.490295410 +v 200.000000000 700.000000000 517.955810547 +v 0.000000000 800.000000000 578.894958496 +v 100.000000000 800.000000000 560.926391602 +v 200.000000000 800.000000000 542.957824707 +v 300.000000000 800.000000000 525.785583496 +v 400.000000000 800.000000000 508.586700439 +v 4.818426609 900.000000000 600.000000000 +v 100.000000000 900.000000000 584.362487793 +v 0.000000000 896.384704590 600.000000000 +v 200.000000000 900.000000000 566.393920898 +v 300.000000000 900.000000000 549.991333008 +v 400.000000000 900.000000000 534.384948730 +v 500.000000000 900.000000000 518.752075195 +v 600.000000000 900.000000000 503.119171143 +v 100.000000000 976.915832520 600.000000000 +v 130.021209717 1000.000000000 600.000000000 +v 200.000000000 1000.000000000 589.060302734 +v 300.000000000 1000.000000000 573.427429199 +v 400.000000000 1000.000000000 558.590759277 +v 500.000000000 1000.000000000 544.523803711 +v 600.000000000 1000.000000000 530.456848145 +v 700.000000000 1000.000000000 517.186157227 +v 800.000000000 1000.000000000 505.481323242 +v 200.000000000 1053.879028320 600.000000000 +v 263.117279053 1100.000000000 600.000000000 +v 300.000000000 1100.000000000 594.527832031 +v 400.000000000 1100.000000000 580.460876465 +v 500.000000000 1100.000000000 566.393920898 +v 600.000000000 1100.000000000 553.123229980 +v 700.000000000 1100.000000000 541.418457031 +v 800.000000000 1100.000000000 529.687133789 +v 900.000000000 1100.000000000 519.521789551 +v 1000.000000000 1100.000000000 507.020751953 +v 300.000000000 1128.012817383 600.000000000 +v 399.967041016 1200.000000000 600.000000000 +v 500.000000000 1200.000000000 586.724670410 +v 600.000000000 1200.000000000 574.223632812 +v 700.000000000 1200.000000000 563.288574219 +v 800.000000000 1200.000000000 552.353515625 +v 900.000000000 1200.000000000 540.622192383 +v 1000.000000000 1200.000000000 530.456848145 +v 1100.000000000 1200.000000000 518.752075195 +v 1200.000000000 1200.000000000 507.020751953 +v 100.000000000 2900.000000000 1005.468627930 +v 114.581993103 2900.000000000 1000.000000000 +v 500.000000000 1270.846313477 600.000000000 +v 546.672363281 1300.000000000 600.000000000 +v 600.000000000 1300.000000000 593.758117676 +v 700.000000000 1300.000000000 582.026855469 +v 800.000000000 1300.000000000 571.888000488 +v 900.000000000 1300.000000000 560.156677246 +v 1000.000000000 1300.000000000 549.991333008 +v 1100.000000000 1300.000000000 537.490295410 +v 1200.000000000 1300.000000000 526.555236816 +v 1300.000000000 1300.000000000 513.284545898 +v 600.000000000 1338.054321289 600.000000000 +v 699.954345703 1400.000000000 600.000000000 +v 800.000000000 1400.000000000 589.856567383 +v 900.000000000 1400.000000000 578.894958496 +v 1000.000000000 1400.000000000 564.058288574 +v 1100.000000000 1400.000000000 553.123229980 +v 1200.000000000 1400.000000000 542.957824707 +v 1300.000000000 1400.000000000 530.456848145 +v 1400.000000000 1400.000000000 517.186157227 +v 1500.000000000 1400.000000000 504.685119629 +v 0.000000000 2900.000000000 1046.103515625 +v 800.000000000 1468.367553711 600.000000000 +v 842.918579102 1500.000000000 600.000000000 +v 900.000000000 1500.000000000 593.758117676 +v 1000.000000000 1500.000000000 578.125244141 +v 1100.000000000 1500.000000000 567.959899902 +v 1200.000000000 1500.000000000 557.024780273 +v 1300.000000000 1500.000000000 546.089721680 +v 1400.000000000 1500.000000000 534.384948730 +v 1500.000000000 1500.000000000 521.087707520 +v 1600.000000000 1500.000000000 509.382965088 +v 900.000000000 1557.081420898 600.000000000 +v 933.363159180 1600.000000000 600.000000000 +v 1000.000000000 1600.000000000 590.626220703 +v 1100.000000000 1600.000000000 579.691162109 +v 1200.000000000 1600.000000000 570.322082520 +v 1300.000000000 1600.000000000 560.156677246 +v 1400.000000000 1600.000000000 549.221618652 +v 1500.000000000 1600.000000000 537.490295410 +v 1600.000000000 1600.000000000 524.989318848 +v 1700.000000000 1600.000000000 512.488281250 +v 1000.000000000 1680.085205078 600.000000000 +v 1021.316711426 1700.000000000 600.000000000 +v 1100.000000000 1700.000000000 591.395935059 +v 1200.000000000 1700.000000000 582.026855469 +v 1300.000000000 1700.000000000 572.657714844 +v 1400.000000000 1700.000000000 562.492309570 +v 1500.000000000 1700.000000000 551.557250977 +v 1600.000000000 1700.000000000 540.622192383 +v 1700.000000000 1700.000000000 528.121215820 +v 1800.000000000 1700.000000000 516.416442871 +v 1900.000000000 1700.000000000 503.915466309 +v 1100.000000000 1773.342651367 600.000000000 +v 1133.378295898 1800.000000000 600.000000000 +v 1200.000000000 1800.000000000 593.758117676 +v 1300.000000000 1800.000000000 585.158691406 +v 1400.000000000 1800.000000000 575.789611816 +v 1500.000000000 1800.000000000 565.624206543 +v 1600.000000000 1800.000000000 554.689147949 +v 1700.000000000 1800.000000000 543.754089355 +v 1800.000000000 1800.000000000 532.022766113 +v 1900.000000000 1800.000000000 519.521789551 +v 2000.000000000 1800.000000000 507.020751953 +v 1200.000000000 1853.327758789 600.000000000 +v 1263.526245117 1900.000000000 600.000000000 +v 1300.000000000 1900.000000000 596.863464355 +v 1400.000000000 1900.000000000 588.290588379 +v 1500.000000000 1900.000000000 578.894958496 +v 1600.000000000 1900.000000000 568.756103516 +v 1700.000000000 1900.000000000 557.821044922 +v 1800.000000000 1900.000000000 546.885986328 +v 1900.000000000 1900.000000000 535.154663086 +v 2000.000000000 1900.000000000 522.653686523 +v 2100.000000000 1900.000000000 509.382965088 +v 1300.000000000 1926.736450195 600.000000000 +v 1399.946044922 2000.000000000 600.000000000 +v 1500.000000000 2000.000000000 591.395935059 +v 1600.000000000 2000.000000000 582.026855469 +v 1700.000000000 2000.000000000 571.888000488 +v 1800.000000000 2000.000000000 560.926391602 +v 1900.000000000 2000.000000000 549.991333008 +v 2000.000000000 2000.000000000 538.286560059 +v 2100.000000000 2000.000000000 526.555236816 +v 2200.000000000 2000.000000000 513.284545898 +v 100.000000000 2875.873291016 1000.000000000 +v 1500.000000000 2068.826904297 600.000000000 +v 1545.457031250 2100.000000000 600.000000000 +v 1600.000000000 2100.000000000 595.324096680 +v 1700.000000000 2100.000000000 585.928405762 +v 1800.000000000 2100.000000000 574.993347168 +v 1900.000000000 2100.000000000 564.058288574 +v 2000.000000000 2100.000000000 552.353515625 +v 2100.000000000 2100.000000000 540.622192383 +v 2200.000000000 2100.000000000 528.121215820 +v 2300.000000000 2100.000000000 515.620178223 +v 1600.000000000 2137.404296875 600.000000000 +v 1676.977905273 2200.000000000 600.000000000 +v 1700.000000000 2200.000000000 597.659729004 +v 1800.000000000 2200.000000000 587.494384766 +v 1900.000000000 2200.000000000 577.355529785 +v 2000.000000000 2200.000000000 567.190185547 +v 2100.000000000 2200.000000000 555.458862305 +v 2200.000000000 2200.000000000 545.320068359 +v 2300.000000000 2200.000000000 532.819030762 +v 2400.000000000 2200.000000000 517.955810547 +v 2500.000000000 2200.000000000 503.119171143 +v 1700.000000000 2217.635009766 600.000000000 +v 1800.000000000 2294.046875000 600.000000000 +v 1807.787475586 2300.000000000 600.000000000 +v 1900.000000000 2300.000000000 590.626220703 +v 2000.000000000 2300.000000000 579.691162109 +v 2100.000000000 2300.000000000 568.756103516 +v 2200.000000000 2300.000000000 558.590759277 +v 2300.000000000 2300.000000000 546.089721680 +v 2400.000000000 2300.000000000 535.154663086 +v 2500.000000000 2300.000000000 520.317993164 +v 2600.000000000 2300.000000000 505.481323242 +v 1900.000000000 2370.634765625 600.000000000 +v 1938.435913086 2400.000000000 600.000000000 +v 2000.000000000 2400.000000000 593.758117676 +v 2100.000000000 2400.000000000 584.362487793 +v 2200.000000000 2400.000000000 572.657714844 +v 2300.000000000 2400.000000000 560.926391602 +v 2400.000000000 2400.000000000 549.221618652 +v 2500.000000000 2400.000000000 536.720642090 +v 2600.000000000 2400.000000000 521.883972168 +v 2700.000000000 2400.000000000 507.020751953 +v 2000.000000000 2444.372802734 600.000000000 +v 2071.386230469 2500.000000000 600.000000000 +v 2100.000000000 2500.000000000 596.863464355 +v 2200.000000000 2500.000000000 587.494384766 +v 2300.000000000 2500.000000000 575.789611816 +v 2400.000000000 2500.000000000 564.058288574 +v 2500.000000000 2500.000000000 551.557250977 +v 2600.000000000 2500.000000000 539.056274414 +v 2700.000000000 2500.000000000 524.219604492 +v 2800.000000000 2500.000000000 507.817016602 +v 2100.000000000 2521.102783203 600.000000000 +v 2200.000000000 2594.046875000 600.000000000 +v 2206.748046875 2600.000000000 600.000000000 +v 2300.000000000 2600.000000000 589.060302734 +v 2400.000000000 2600.000000000 578.125244141 +v 2500.000000000 2600.000000000 566.393920898 +v 2600.000000000 2600.000000000 553.919433594 +v 2700.000000000 2600.000000000 540.622192383 +v 2800.000000000 2600.000000000 524.989318848 +v 2900.000000000 2600.000000000 508.586700439 +v 2300.000000000 2677.768798828 600.000000000 +v 2326.657226562 2700.000000000 600.000000000 +v 2400.000000000 2700.000000000 591.395935059 +v 2500.000000000 2700.000000000 580.460876465 +v 2600.000000000 2700.000000000 567.959899902 +v 2700.000000000 2700.000000000 554.689147949 +v 2800.000000000 2700.000000000 540.622192383 +v 2900.000000000 2700.000000000 524.989318848 +v 3000.000000000 2700.000000000 508.586700439 +v 2400.000000000 2755.038085938 600.000000000 +v 2456.226318359 2800.000000000 600.000000000 +v 2500.000000000 2800.000000000 594.527832031 +v 2600.000000000 2800.000000000 582.026855469 +v 2700.000000000 2800.000000000 569.525817871 +v 2800.000000000 2800.000000000 555.458862305 +v 2900.000000000 2800.000000000 539.852478027 +v 3000.000000000 2800.000000000 523.449890137 +v 3100.000000000 2800.000000000 506.251037598 +v 2500.000000000 2835.004150391 600.000000000 +v 2581.279296875 2900.000000000 600.000000000 +v 2600.000000000 2900.000000000 597.659729004 +v 2700.000000000 2900.000000000 584.362487793 +v 2800.000000000 2900.000000000 570.322082520 +v 2900.000000000 2900.000000000 554.689147949 +v 3000.000000000 2900.000000000 539.056274414 +v 3100.000000000 2900.000000000 521.883972168 +v 3200.000000000 2900.000000000 502.349487305 +v 2600.000000000 2914.970214844 600.000000000 +v 2694.495117188 3000.000000000 600.000000000 +v 2700.000000000 3000.000000000 599.225646973 +v 2800.000000000 3000.000000000 585.158691406 +v 2900.000000000 3000.000000000 570.322082520 +v 3000.000000000 3000.000000000 553.919433594 +v 3100.000000000 3000.000000000 536.720642090 +v 3200.000000000 3000.000000000 517.955810547 +v 2700.000000000 3004.720947266 600.000000000 +v 2800.000000000 3090.481201172 600.000000000 +v 2810.523681641 3100.000000000 600.000000000 +v 2900.000000000 3100.000000000 586.724670410 +v 3000.000000000 3100.000000000 570.322082520 +v 3100.000000000 3100.000000000 552.353515625 +v 3200.000000000 3100.000000000 533.588745117 +v 2900.000000000 3180.934326172 600.000000000 +v 2919.065673828 3200.000000000 600.000000000 +v 3000.000000000 3200.000000000 586.724670410 +v 3100.000000000 3200.000000000 568.756103516 +v 3200.000000000 3200.000000000 549.221618652 +v 0.000000000 900.000000000 600.791625977 +v 0.000000000 1000.000000000 621.095825195 +v 100.000000000 1000.000000000 604.693176270 +v 0.000000000 1100.000000000 641.399963379 +v 100.000000000 1100.000000000 625.793640137 +v 200.000000000 1100.000000000 609.364501953 +v 0.000000000 1200.000000000 660.164794922 +v 100.000000000 1200.000000000 645.301574707 +v 200.000000000 1200.000000000 629.695190430 +v 300.000000000 1200.000000000 614.062316895 +v 0.000000000 1300.000000000 678.903015137 +v 100.000000000 1300.000000000 663.270141602 +v 200.000000000 1300.000000000 648.433471680 +v 300.000000000 1300.000000000 633.596801758 +v 400.000000000 1300.000000000 618.760131836 +v 500.000000000 1300.000000000 605.462890625 +v 4.302708149 1400.000000000 700.000000000 +v 100.000000000 1400.000000000 682.804626465 +v 0.000000000 1396.464965820 700.000000000 +v 200.000000000 1400.000000000 667.198242188 +v 300.000000000 1400.000000000 652.335021973 +v 400.000000000 1400.000000000 637.498413086 +v 500.000000000 1400.000000000 623.431457520 +v 600.000000000 1400.000000000 610.160705566 +v 100.000000000 1484.578369141 700.000000000 +v 118.229797363 1500.000000000 700.000000000 +v 200.000000000 1500.000000000 685.936462402 +v 300.000000000 1500.000000000 670.303588867 +v 400.000000000 1500.000000000 655.466918945 +v 500.000000000 1500.000000000 641.399963379 +v 600.000000000 1500.000000000 627.333007812 +v 700.000000000 1500.000000000 614.832031250 +v 800.000000000 1500.000000000 604.693176270 +v 200.000000000 1571.993408203 700.000000000 +v 230.447433472 1600.000000000 700.000000000 +v 300.000000000 1600.000000000 687.502441406 +v 400.000000000 1600.000000000 671.869506836 +v 500.000000000 1600.000000000 657.032897949 +v 600.000000000 1600.000000000 642.965942383 +v 700.000000000 1600.000000000 629.695190430 +v 800.000000000 1600.000000000 617.194213867 +v 900.000000000 1600.000000000 604.693176270 +v 300.000000000 1666.695556641 700.000000000 +v 333.304443359 1700.000000000 700.000000000 +v 400.000000000 1700.000000000 687.502441406 +v 500.000000000 1700.000000000 671.099853516 +v 600.000000000 1700.000000000 657.032897949 +v 700.000000000 1700.000000000 643.762145996 +v 800.000000000 1700.000000000 630.464904785 +v 900.000000000 1700.000000000 614.832031250 +v 1000.000000000 1700.000000000 602.330993652 +v 400.000000000 1776.192626953 700.000000000 +v 422.705169678 1800.000000000 700.000000000 +v 500.000000000 1800.000000000 686.706176758 +v 600.000000000 1800.000000000 669.533874512 +v 700.000000000 1800.000000000 654.697265625 +v 800.000000000 1800.000000000 640.630310059 +v 900.000000000 1800.000000000 625.793640137 +v 1000.000000000 1800.000000000 613.292602539 +v 1100.000000000 1800.000000000 603.127258301 +v 500.000000000 1889.441162109 700.000000000 +v 508.734130859 1900.000000000 700.000000000 +v 600.000000000 1900.000000000 683.600830078 +v 700.000000000 1900.000000000 667.198242188 +v 800.000000000 1900.000000000 650.769104004 +v 900.000000000 1900.000000000 635.932434082 +v 1000.000000000 1900.000000000 624.227661133 +v 1100.000000000 1900.000000000 613.292602539 +v 1200.000000000 1900.000000000 605.462890625 +v 588.044799805 2000.000000000 700.000000000 +v 600.000000000 2000.000000000 697.667785645 +v 700.000000000 2000.000000000 678.903015137 +v 800.000000000 2000.000000000 660.934448242 +v 900.000000000 2000.000000000 646.097839355 +v 1000.000000000 2000.000000000 633.596801758 +v 1100.000000000 2000.000000000 624.227661133 +v 1200.000000000 2000.000000000 616.397949219 +v 1300.000000000 2000.000000000 608.594787598 +v 600.000000000 2019.925292969 700.000000000 +v 647.979553223 2100.000000000 700.000000000 +v 700.000000000 2100.000000000 689.838073730 +v 800.000000000 2100.000000000 671.869506836 +v 900.000000000 2100.000000000 655.466918945 +v 1000.000000000 2100.000000000 642.965942383 +v 1100.000000000 2100.000000000 635.162780762 +v 1200.000000000 2100.000000000 628.129272461 +v 1300.000000000 2100.000000000 620.299560547 +v 1400.000000000 2100.000000000 612.496398926 +v 1500.000000000 2100.000000000 603.896972656 +v 700.000000000 2186.622314453 700.000000000 +v 708.363525391 2200.000000000 700.000000000 +v 800.000000000 2200.000000000 682.804626465 +v 900.000000000 2200.000000000 665.632324219 +v 1000.000000000 2200.000000000 652.335021973 +v 1100.000000000 2200.000000000 645.301574707 +v 1200.000000000 2200.000000000 639.834045410 +v 1300.000000000 2200.000000000 632.800537109 +v 1400.000000000 2200.000000000 624.997375488 +v 1500.000000000 2200.000000000 617.194213867 +v 1600.000000000 2200.000000000 607.825073242 +v 766.682983398 2300.000000000 700.000000000 +v 800.000000000 2300.000000000 692.969970703 +v 900.000000000 2300.000000000 675.001403809 +v 1000.000000000 2300.000000000 664.066345215 +v 1100.000000000 2300.000000000 658.598815918 +v 1200.000000000 2300.000000000 652.335021973 +v 1300.000000000 2300.000000000 645.301574707 +v 1400.000000000 2300.000000000 637.498413086 +v 1500.000000000 2300.000000000 629.695190430 +v 1600.000000000 2300.000000000 620.299560547 +v 1700.000000000 2300.000000000 610.930419922 +v 1800.000000000 2300.000000000 600.791625977 +v 800.000000000 2360.061279297 700.000000000 +v 827.222534180 2400.000000000 700.000000000 +v 900.000000000 2400.000000000 687.502441406 +v 1000.000000000 2400.000000000 677.337097168 +v 1100.000000000 2400.000000000 671.099853516 +v 1200.000000000 2400.000000000 665.632324219 +v 1300.000000000 2400.000000000 658.598815918 +v 1400.000000000 2400.000000000 650.769104004 +v 1500.000000000 2400.000000000 642.196228027 +v 1600.000000000 2400.000000000 632.800537109 +v 1700.000000000 2400.000000000 623.431457520 +v 1800.000000000 2400.000000000 613.292602539 +v 1900.000000000 2400.000000000 603.896972656 +v 900.000000000 2488.843261719 700.000000000 +v 915.438659668 2500.000000000 700.000000000 +v 1000.000000000 2500.000000000 691.403991699 +v 1100.000000000 2500.000000000 684.370544434 +v 1200.000000000 2500.000000000 678.903015137 +v 1300.000000000 2500.000000000 671.869506836 +v 1400.000000000 2500.000000000 663.270141602 +v 1500.000000000 2500.000000000 655.466918945 +v 1600.000000000 2500.000000000 646.867492676 +v 1700.000000000 2500.000000000 637.498413086 +v 1800.000000000 2500.000000000 627.333007812 +v 1900.000000000 2500.000000000 617.963928223 +v 2000.000000000 2500.000000000 607.825073242 +v 1000.000000000 2557.937500000 700.000000000 +v 1079.976074219 2600.000000000 700.000000000 +v 1100.000000000 2600.000000000 698.437500000 +v 1200.000000000 2600.000000000 692.200256348 +v 1300.000000000 2600.000000000 685.166809082 +v 1400.000000000 2600.000000000 677.337097168 +v 1500.000000000 2600.000000000 668.737670898 +v 1600.000000000 2600.000000000 660.164794922 +v 1700.000000000 2600.000000000 651.565368652 +v 1800.000000000 2600.000000000 642.196228027 +v 1900.000000000 2600.000000000 632.030883789 +v 2000.000000000 2600.000000000 621.865478516 +v 2100.000000000 2600.000000000 611.726684570 +v 2200.000000000 2600.000000000 600.791625977 +v 1100.000000000 2611.107666016 700.000000000 +v 1200.000000000 2655.552001953 700.000000000 +v 1279.976074219 2700.000000000 700.000000000 +v 1300.000000000 2700.000000000 698.437500000 +v 1400.000000000 2700.000000000 690.634338379 +v 1500.000000000 2700.000000000 682.804626465 +v 1600.000000000 2700.000000000 674.231750488 +v 1700.000000000 2700.000000000 664.836059570 +v 1800.000000000 2700.000000000 655.466918945 +v 1900.000000000 2700.000000000 646.097839355 +v 2000.000000000 2700.000000000 635.932434082 +v 2100.000000000 2700.000000000 625.793640137 +v 2200.000000000 2700.000000000 614.832031250 +v 2300.000000000 2700.000000000 603.127258301 +v 1300.000000000 2710.531494141 700.000000000 +v 1400.000000000 2763.125488281 700.000000000 +v 1463.620361328 2800.000000000 700.000000000 +v 1500.000000000 2800.000000000 696.871582031 +v 1600.000000000 2800.000000000 688.272155762 +v 1700.000000000 2800.000000000 679.699279785 +v 1800.000000000 2800.000000000 670.303588867 +v 1900.000000000 2800.000000000 660.934448242 +v 2000.000000000 2800.000000000 650.769104004 +v 2100.000000000 2800.000000000 640.630310059 +v 2200.000000000 2800.000000000 629.695190430 +v 2300.000000000 2800.000000000 618.760131836 +v 2400.000000000 2800.000000000 607.028869629 +v 1500.000000000 2821.085693359 700.000000000 +v 1600.000000000 2878.905517578 700.000000000 +v 1633.369995117 2900.000000000 700.000000000 +v 1700.000000000 2900.000000000 693.739685059 +v 1800.000000000 2900.000000000 684.370544434 +v 1900.000000000 2900.000000000 675.001403809 +v 2000.000000000 2900.000000000 665.632324219 +v 2100.000000000 2900.000000000 655.466918945 +v 2200.000000000 2900.000000000 644.531860352 +v 2300.000000000 2900.000000000 633.596801758 +v 2400.000000000 2900.000000000 622.661743164 +v 2500.000000000 2900.000000000 610.160705566 +v 1700.000000000 2942.119628906 700.000000000 +v 1791.562255859 3000.000000000 700.000000000 +v 1800.000000000 3000.000000000 699.207214355 +v 1900.000000000 3000.000000000 689.838073730 +v 2000.000000000 3000.000000000 680.468933105 +v 2100.000000000 3000.000000000 670.303588867 +v 2200.000000000 3000.000000000 660.164794922 +v 2300.000000000 3000.000000000 649.229675293 +v 2400.000000000 3000.000000000 638.268066406 +v 2500.000000000 3000.000000000 626.563354492 +v 2600.000000000 3000.000000000 613.292602539 +v 1800.000000000 3005.071289062 700.000000000 +v 1900.000000000 3065.003662109 700.000000000 +v 1958.393676758 3100.000000000 700.000000000 +v 2000.000000000 3100.000000000 696.101867676 +v 2100.000000000 3100.000000000 685.936462402 +v 2200.000000000 3100.000000000 676.567382812 +v 2300.000000000 3100.000000000 665.632324219 +v 2400.000000000 3100.000000000 654.697265625 +v 2500.000000000 3100.000000000 642.196228027 +v 2600.000000000 3100.000000000 629.695190430 +v 2700.000000000 3100.000000000 615.628234863 +v 2800.000000000 3100.000000000 601.561340332 +v 2000.000000000 3126.273681641 700.000000000 +v 2100.000000000 3189.960937500 700.000000000 +v 2116.750732422 3200.000000000 700.000000000 +v 2200.000000000 3200.000000000 692.200256348 +v 2300.000000000 3200.000000000 682.034912109 +v 2400.000000000 3200.000000000 670.303588867 +v 2500.000000000 3200.000000000 658.598815918 +v 2600.000000000 3200.000000000 646.097839355 +v 2700.000000000 3200.000000000 632.030883789 +v 2800.000000000 3200.000000000 617.963928223 +v 2900.000000000 3200.000000000 603.127258301 +v 0.000000000 1400.000000000 700.773132324 +v 0.000000000 1500.000000000 722.643249512 +v 100.000000000 1500.000000000 703.135314941 +v 0.000000000 1600.000000000 743.743713379 +v 100.000000000 1600.000000000 724.209228516 +v 200.000000000 1600.000000000 705.470947266 +v 0.000000000 1700.000000000 765.613830566 +v 100.000000000 1700.000000000 744.539916992 +v 200.000000000 1700.000000000 725.005432129 +v 300.000000000 1700.000000000 706.240661621 +v 0.000000000 1800.000000000 787.510498047 +v 100.000000000 1800.000000000 765.613830566 +v 200.000000000 1800.000000000 743.743713379 +v 300.000000000 1800.000000000 723.439514160 +v 400.000000000 1800.000000000 703.905029297 +v 40.026458740 1900.000000000 800.000000000 +v 100.000000000 1900.000000000 785.944580078 +v 0.000000000 1857.107543945 800.000000000 +v 200.000000000 1900.000000000 762.508483887 +v 300.000000000 1900.000000000 741.408081055 +v 400.000000000 1900.000000000 721.103881836 +v 500.000000000 1900.000000000 701.569396973 +v 100.000000000 1969.224121094 800.000000000 +v 125.815200806 2000.000000000 800.000000000 +v 200.000000000 2000.000000000 782.042968750 +v 300.000000000 2000.000000000 759.376586914 +v 400.000000000 2000.000000000 736.710205078 +v 500.000000000 2000.000000000 717.175720215 +v 200.000000000 2092.049804688 800.000000000 +v 206.209701538 2100.000000000 800.000000000 +v 300.000000000 2100.000000000 776.575439453 +v 400.000000000 2100.000000000 753.112854004 +v 500.000000000 2100.000000000 730.473022461 +v 600.000000000 2100.000000000 709.372558594 +v 279.443450928 2200.000000000 800.000000000 +v 300.000000000 2200.000000000 794.544006348 +v 400.000000000 2200.000000000 768.745727539 +v 500.000000000 2200.000000000 745.309631348 +v 600.000000000 2200.000000000 722.643249512 +v 700.000000000 2200.000000000 701.569396973 +v 300.000000000 2230.364257812 800.000000000 +v 347.096313477 2300.000000000 800.000000000 +v 400.000000000 2300.000000000 785.944580078 +v 500.000000000 2300.000000000 760.146301270 +v 600.000000000 2300.000000000 736.710205078 +v 700.000000000 2300.000000000 714.070373535 +v 400.000000000 2381.849365234 800.000000000 +v 411.401428223 2400.000000000 800.000000000 +v 500.000000000 2400.000000000 775.779174805 +v 600.000000000 2400.000000000 750.777160645 +v 700.000000000 2400.000000000 726.571411133 +v 800.000000000 2400.000000000 704.674743652 +v 472.210845947 2500.000000000 800.000000000 +v 500.000000000 2500.000000000 792.181823730 +v 600.000000000 2500.000000000 764.844116211 +v 700.000000000 2500.000000000 739.072387695 +v 800.000000000 2500.000000000 716.406066895 +v 900.000000000 2500.000000000 701.569396973 +v 500.000000000 2547.664306641 800.000000000 +v 529.700134277 2600.000000000 800.000000000 +v 600.000000000 2600.000000000 779.680786133 +v 700.000000000 2600.000000000 753.112854004 +v 800.000000000 2600.000000000 732.038940430 +v 900.000000000 2600.000000000 716.406066895 +v 1000.000000000 2600.000000000 706.240661621 +v 586.812622070 2700.000000000 800.000000000 +v 600.000000000 2700.000000000 796.083374023 +v 700.000000000 2700.000000000 769.541992188 +v 800.000000000 2700.000000000 749.211242676 +v 900.000000000 2700.000000000 732.038940430 +v 1000.000000000 2700.000000000 721.103881836 +v 1100.000000000 2700.000000000 712.504455566 +v 1200.000000000 2700.000000000 706.240661621 +v 600.000000000 2722.772705078 800.000000000 +v 649.993469238 2800.000000000 800.000000000 +v 700.000000000 2800.000000000 786.714294434 +v 800.000000000 2800.000000000 766.410095215 +v 900.000000000 2800.000000000 749.211242676 +v 1000.000000000 2800.000000000 736.710205078 +v 1100.000000000 2800.000000000 728.137329102 +v 1200.000000000 2800.000000000 721.103881836 +v 1300.000000000 2800.000000000 713.274169922 +v 1400.000000000 2800.000000000 705.470947266 +v 700.000000000 2868.011474609 800.000000000 +v 730.775756836 2900.000000000 800.000000000 +v 800.000000000 2900.000000000 785.944580078 +v 900.000000000 2900.000000000 767.179809570 +v 1000.000000000 2900.000000000 752.343139648 +v 1100.000000000 2900.000000000 743.743713379 +v 1200.000000000 2900.000000000 735.940551758 +v 1300.000000000 2900.000000000 728.137329102 +v 1400.000000000 2900.000000000 720.307617188 +v 1500.000000000 2900.000000000 711.708190918 +v 1600.000000000 2900.000000000 703.135314941 +v 800.000000000 2975.009277344 800.000000000 +v 824.990661621 3000.000000000 800.000000000 +v 900.000000000 3000.000000000 785.944580078 +v 1000.000000000 3000.000000000 770.311645508 +v 1100.000000000 3000.000000000 759.376586914 +v 1200.000000000 3000.000000000 751.573425293 +v 1300.000000000 3000.000000000 742.973999023 +v 1400.000000000 3000.000000000 734.374572754 +v 1500.000000000 3000.000000000 726.571411133 +v 1600.000000000 3000.000000000 717.971984863 +v 1700.000000000 3000.000000000 708.602844238 +v 900.000000000 3078.222412109 800.000000000 +v 925.031066895 3100.000000000 800.000000000 +v 1000.000000000 3100.000000000 788.280212402 +v 1100.000000000 3100.000000000 775.779174805 +v 1200.000000000 3100.000000000 767.179809570 +v 1300.000000000 3100.000000000 758.606872559 +v 1400.000000000 3100.000000000 750.007507324 +v 1500.000000000 3100.000000000 741.408081055 +v 1600.000000000 3100.000000000 732.038940430 +v 1700.000000000 3100.000000000 723.439514160 +v 1800.000000000 3100.000000000 714.840087891 +v 1900.000000000 3100.000000000 705.470947266 +v 1000.000000000 3165.223876953 800.000000000 +v 1044.421630859 3200.000000000 800.000000000 +v 1100.000000000 3200.000000000 792.181823730 +v 1200.000000000 3200.000000000 782.812683105 +v 1300.000000000 3200.000000000 773.443542480 +v 1400.000000000 3200.000000000 764.844116211 +v 1500.000000000 3200.000000000 756.244689941 +v 1600.000000000 3200.000000000 747.645263672 +v 1700.000000000 3200.000000000 738.276184082 +v 1800.000000000 3200.000000000 729.676757812 +v 1900.000000000 3200.000000000 720.307617188 +v 2000.000000000 3200.000000000 710.938537598 +v 2100.000000000 3200.000000000 701.569396973 +v 0.000000000 1900.000000000 809.380615234 +v 0.000000000 2000.000000000 832.020446777 +v 100.000000000 2000.000000000 806.248779297 +v 0.000000000 2100.000000000 854.686828613 +v 100.000000000 2100.000000000 828.118896484 +v 200.000000000 2100.000000000 801.550842285 +v 0.000000000 2200.000000000 877.353210449 +v 100.000000000 2200.000000000 849.219299316 +v 200.000000000 2200.000000000 821.085327148 +v 2.590477467 2300.000000000 900.000000000 +v 100.000000000 2300.000000000 870.319763184 +v 0.000000000 2296.632080078 900.000000000 +v 200.000000000 2300.000000000 841.416137695 +v 300.000000000 2300.000000000 812.512512207 +v 75.620391846 2400.000000000 900.000000000 +v 100.000000000 2400.000000000 892.189880371 +v 200.000000000 2400.000000000 861.720397949 +v 300.000000000 2400.000000000 831.250732422 +v 400.000000000 2400.000000000 803.116882324 +v 100.000000000 2435.711181641 900.000000000 +v 143.888854980 2500.000000000 900.000000000 +v 200.000000000 2500.000000000 882.024597168 +v 300.000000000 2500.000000000 850.785278320 +v 400.000000000 2500.000000000 820.315734863 +v 200.000000000 2585.190185547 900.000000000 +v 209.300018311 2600.000000000 900.000000000 +v 300.000000000 2600.000000000 869.523498535 +v 400.000000000 2600.000000000 838.284179688 +v 500.000000000 2600.000000000 808.584411621 +v 272.721038818 2700.000000000 900.000000000 +v 300.000000000 2700.000000000 890.623840332 +v 400.000000000 2700.000000000 857.022460938 +v 500.000000000 2700.000000000 825.783264160 +v 300.000000000 2746.177978516 900.000000000 +v 331.794403076 2800.000000000 900.000000000 +v 400.000000000 2800.000000000 876.556945801 +v 500.000000000 2800.000000000 843.751831055 +v 600.000000000 2800.000000000 813.282226562 +v 391.143341064 2900.000000000 900.000000000 +v 400.000000000 2900.000000000 896.887695312 +v 500.000000000 2900.000000000 863.286193848 +v 600.000000000 2900.000000000 832.816711426 +v 700.000000000 2900.000000000 806.248779297 +v 400.000000000 2914.768554688 900.000000000 +v 452.257812500 3000.000000000 900.000000000 +v 500.000000000 3000.000000000 883.590393066 +v 600.000000000 3000.000000000 853.120910645 +v 700.000000000 3000.000000000 826.552978516 +v 800.000000000 3000.000000000 804.682800293 +v 500.000000000 3077.768798828 900.000000000 +v 515.395202637 3100.000000000 900.000000000 +v 600.000000000 3100.000000000 874.221313477 +v 700.000000000 3100.000000000 847.653381348 +v 800.000000000 3100.000000000 824.217346191 +v 900.000000000 3100.000000000 803.913085938 +v 587.488464355 3200.000000000 900.000000000 +v 600.000000000 3200.000000000 896.091430664 +v 700.000000000 3200.000000000 868.753784180 +v 800.000000000 3200.000000000 844.521545410 +v 900.000000000 3200.000000000 822.651367188 +v 1000.000000000 3200.000000000 806.248779297 +v 0.000000000 2300.000000000 900.789245605 +v 0.000000000 2400.000000000 924.225341797 +v 0.000000000 2500.000000000 947.661376953 +v 100.000000000 2500.000000000 914.059997559 +v 0.000000000 2600.000000000 971.097534180 +v 100.000000000 2600.000000000 936.726379395 +v 200.000000000 2600.000000000 903.124877930 +v 0.000000000 2700.000000000 995.303222656 +v 100.000000000 2700.000000000 959.366210938 +v 200.000000000 2700.000000000 924.995056152 +v 52.144981384 2800.000000000 1000.000000000 +v 100.000000000 2800.000000000 982.802307129 +v 0.000000000 2720.040527344 1000.000000000 +v 200.000000000 2800.000000000 946.865173340 +v 300.000000000 2800.000000000 910.928039551 +v 200.000000000 2900.000000000 967.965576172 +v 300.000000000 2900.000000000 932.028564453 +v 200.000000000 3000.000000000 990.632080078 +v 300.000000000 3000.000000000 953.129028320 +v 400.000000000 3000.000000000 917.961608887 +v 300.000000000 3100.000000000 976.565063477 +v 400.000000000 3100.000000000 939.062011719 +v 500.000000000 3100.000000000 904.690856934 +v 400.000000000 3200.000000000 962.498107910 +v 500.000000000 3200.000000000 927.330688477 +v 0.000000000 2800.000000000 1018.739440918 +f 309 307 310 +f 308 307 309 +f 307 306 310 +f 509 310 306 +f 306 307 319 +f 510 509 511 +f 509 306 319 +f 511 509 319 +f 307 308 311 +f 311 308 312 +f 311 321 307 +f 307 321 319 +f 321 320 319 +f 511 319 320 +f 513 510 511 +f 512 510 513 +f 513 511 514 +f 320 321 327 +f 514 511 327 +f 511 320 327 +f 516 512 513 +f 515 512 516 +f 516 513 517 +f 517 513 514 +f 321 311 322 +f 322 311 313 +f 311 312 313 +f 313 312 314 +f 313 314 315 +f 315 314 316 +f 322 313 323 +f 323 313 315 +f 514 327 328 +f 322 329 321 +f 329 328 327 +f 321 329 327 +f 518 514 337 +f 328 329 337 +f 517 514 518 +f 514 328 337 +f 329 322 330 +f 330 322 323 +f 329 330 337 +f 337 330 338 +f 518 337 338 +f 316 120 121 +f 317 316 121 +f 315 316 317 +f 120 119 121 +f 318 121 123 +f 317 121 318 +f 119 122 121 +f 121 122 123 +f 325 317 318 +f 323 315 324 +f 324 315 317 +f 324 317 325 +f 125 124 123 +f 318 123 124 +f 122 125 123 +f 126 125 122 +f 326 318 147 +f 124 125 147 +f 325 318 326 +f 318 124 147 +f 125 126 127 +f 127 126 128 +f 149 148 147 +f 125 149 147 +f 127 149 125 +f 326 147 148 +f 330 323 331 +f 331 323 324 +f 330 339 338 +f 331 339 330 +f 340 331 332 +f 339 331 340 +f 332 324 325 +f 331 324 332 +f 332 325 333 +f 333 325 326 +f 326 148 162 +f 334 326 162 +f 333 326 334 +f 148 149 162 +f 342 333 334 +f 341 333 342 +f 341 332 333 +f 340 332 341 +f 522 521 523 +f 516 522 515 +f 515 522 523 +f 717 523 521 +f 522 516 524 +f 524 516 517 +f 719 717 528 +f 521 522 528 +f 718 717 719 +f 717 521 528 +f 719 528 529 +f 524 530 522 +f 522 530 528 +f 530 529 528 +f 720 718 721 +f 721 718 719 +f 529 530 536 +f 719 529 536 +f 722 719 536 +f 721 719 722 +f 723 720 724 +f 724 720 721 +f 724 721 725 +f 725 721 722 +f 526 518 338 +f 524 517 525 +f 525 517 518 +f 525 518 526 +f 531 525 532 +f 532 525 526 +f 530 524 531 +f 531 524 525 +f 722 536 537 +f 531 538 530 +f 538 537 536 +f 530 538 536 +f 726 722 546 +f 722 537 546 +f 725 722 726 +f 537 538 546 +f 539 531 532 +f 538 531 539 +f 546 539 547 +f 538 539 546 +f 727 546 547 +f 726 546 727 +f 338 339 348 +f 526 338 527 +f 527 338 348 +f 532 526 533 +f 533 526 527 +f 527 348 349 +f 340 350 339 +f 339 350 348 +f 350 349 348 +f 534 527 360 +f 533 527 534 +f 349 350 360 +f 527 349 360 +f 351 340 341 +f 350 340 351 +f 350 351 360 +f 351 341 352 +f 352 341 342 +f 360 351 361 +f 534 360 535 +f 535 360 361 +f 352 363 351 +f 535 361 362 +f 351 363 361 +f 363 362 361 +f 540 532 533 +f 540 533 541 +f 541 533 534 +f 539 532 540 +f 727 547 548 +f 540 549 539 +f 539 549 547 +f 549 548 547 +f 550 540 541 +f 549 540 550 +f 541 534 542 +f 542 534 535 +f 543 535 373 +f 535 362 373 +f 542 535 543 +f 362 363 373 +f 550 541 551 +f 551 541 542 +f 551 542 552 +f 552 542 543 +f 724 729 723 +f 729 728 730 +f 723 729 730 +f 961 730 728 +f 961 728 736 +f 962 961 963 +f 963 961 736 +f 728 729 736 +f 731 724 725 +f 729 724 731 +f 738 737 736 +f 963 736 737 +f 731 738 729 +f 729 738 736 +f 965 962 963 +f 964 962 965 +f 737 738 745 +f 965 963 966 +f 966 963 745 +f 963 737 745 +f 968 965 969 +f 968 964 965 +f 967 964 968 +f 969 965 966 +f 732 725 726 +f 731 725 732 +f 739 731 732 +f 738 731 739 +f 739 732 740 +f 740 732 733 +f 733 726 727 +f 732 726 733 +f 738 747 745 +f 747 746 745 +f 739 747 738 +f 966 745 746 +f 746 747 755 +f 969 966 970 +f 970 966 755 +f 966 746 755 +f 747 739 748 +f 748 739 740 +f 748 756 747 +f 747 756 755 +f 970 755 756 +f 734 727 557 +f 548 549 557 +f 733 727 734 +f 727 548 557 +f 557 550 558 +f 549 550 557 +f 734 557 735 +f 735 557 558 +f 742 734 735 +f 741 734 742 +f 741 733 734 +f 740 733 741 +f 735 558 559 +f 560 559 558 +f 550 560 558 +f 551 560 550 +f 742 735 743 +f 743 735 568 +f 559 560 568 +f 735 559 568 +f 561 551 552 +f 560 551 561 +f 743 568 744 +f 744 568 569 +f 568 561 569 +f 560 561 568 +f 757 748 749 +f 756 748 757 +f 749 740 741 +f 748 740 749 +f 750 741 742 +f 758 749 750 +f 749 741 750 +f 757 749 758 +f 750 742 751 +f 758 750 759 +f 759 750 751 +f 751 742 743 +f 760 751 752 +f 759 751 760 +f 751 743 752 +f 752 743 744 +f 971 967 972 +f 972 968 973 +f 973 968 969 +f 972 967 968 +f 972 978 971 +f 971 978 979 +f 978 977 979 +f 1186 979 977 +f 978 972 980 +f 980 972 973 +f 1187 1186 1188 +f 1188 1186 985 +f 1186 977 985 +f 977 978 985 +f 1189 1187 1190 +f 1190 1187 1188 +f 1188 985 986 +f 987 986 985 +f 980 987 978 +f 978 987 985 +f 1191 1188 994 +f 1190 1188 1191 +f 1188 986 994 +f 986 987 994 +f 980 973 981 +f 981 973 974 +f 974 969 970 +f 973 969 974 +f 982 974 975 +f 981 974 982 +f 975 970 756 +f 974 970 975 +f 987 980 988 +f 988 980 981 +f 988 981 989 +f 989 981 982 +f 988 996 987 +f 996 995 994 +f 987 996 994 +f 1191 994 995 +f 997 988 989 +f 996 988 997 +f 976 756 767 +f 975 756 976 +f 756 757 767 +f 982 975 983 +f 983 975 976 +f 758 769 757 +f 976 767 768 +f 757 769 767 +f 769 768 767 +f 984 976 777 +f 976 768 777 +f 983 976 984 +f 768 769 777 +f 769 758 770 +f 771 759 760 +f 770 759 771 +f 770 758 759 +f 984 777 778 +f 770 778 769 +f 769 778 777 +f 779 770 771 +f 778 770 779 +f 998 989 990 +f 989 982 990 +f 997 989 998 +f 990 982 983 +f 999 990 991 +f 991 983 984 +f 998 990 999 +f 990 983 991 +f 991 984 992 +f 992 984 778 +f 993 778 788 +f 778 779 788 +f 992 778 993 +f 1000 992 1001 +f 999 991 1000 +f 1000 991 992 +f 1001 992 993 +f 149 127 150 +f 150 127 129 +f 129 128 130 +f 127 128 129 +f 151 129 131 +f 150 129 151 +f 129 130 131 +f 131 130 132 +f 151 131 152 +f 152 131 133 +f 133 132 134 +f 131 132 133 +f 153 133 135 +f 152 133 153 +f 133 134 135 +f 135 134 136 +f 149 150 162 +f 335 162 163 +f 162 150 163 +f 334 162 335 +f 163 151 164 +f 150 151 163 +f 342 334 343 +f 343 334 335 +f 343 335 344 +f 335 163 336 +f 344 335 336 +f 336 163 164 +f 336 164 165 +f 151 166 164 +f 152 166 151 +f 166 165 164 +f 345 336 178 +f 344 336 345 +f 165 166 178 +f 336 165 178 +f 166 152 167 +f 167 152 153 +f 178 167 179 +f 166 167 178 +f 345 178 346 +f 346 178 179 +f 153 135 154 +f 154 135 137 +f 137 136 138 +f 135 136 137 +f 155 137 139 +f 154 137 155 +f 137 138 139 +f 139 138 140 +f 155 139 156 +f 156 139 141 +f 141 140 142 +f 139 140 141 +f 157 141 143 +f 156 141 157 +f 141 142 143 +f 143 142 144 +f 167 168 179 +f 167 153 168 +f 168 153 154 +f 168 154 169 +f 169 154 155 +f 347 179 180 +f 179 168 180 +f 346 179 347 +f 168 182 180 +f 169 182 168 +f 182 181 180 +f 347 180 181 +f 347 181 192 +f 181 182 192 +f 171 156 157 +f 170 156 171 +f 170 155 156 +f 169 155 170 +f 182 169 183 +f 183 169 170 +f 182 183 192 +f 184 170 171 +f 183 170 184 +f 363 352 364 +f 364 352 353 +f 353 342 343 +f 352 342 353 +f 364 353 365 +f 365 353 354 +f 353 343 354 +f 354 343 344 +f 354 344 355 +f 365 354 366 +f 366 354 355 +f 355 344 345 +f 366 355 367 +f 355 345 356 +f 356 345 346 +f 367 355 356 +f 543 373 544 +f 544 373 374 +f 363 364 373 +f 373 364 374 +f 364 365 374 +f 374 365 375 +f 553 543 544 +f 552 543 553 +f 544 374 375 +f 553 544 554 +f 554 544 375 +f 377 366 367 +f 366 376 365 +f 365 376 375 +f 376 366 377 +f 375 376 385 +f 555 375 385 +f 554 375 555 +f 555 385 556 +f 556 385 386 +f 376 377 385 +f 385 377 386 +f 356 346 357 +f 357 346 347 +f 367 356 368 +f 368 356 357 +f 368 357 369 +f 369 357 358 +f 358 347 192 +f 357 347 358 +f 192 183 193 +f 359 192 193 +f 358 192 359 +f 370 358 359 +f 369 358 370 +f 183 195 193 +f 195 194 193 +f 184 195 183 +f 359 193 194 +f 194 195 204 +f 359 194 204 +f 371 359 204 +f 370 359 371 +f 378 367 368 +f 378 368 379 +f 379 368 369 +f 377 367 378 +f 378 388 377 +f 377 388 386 +f 388 387 386 +f 387 388 397 +f 556 387 397 +f 556 386 387 +f 388 378 389 +f 389 378 379 +f 388 389 397 +f 379 369 380 +f 380 369 370 +f 389 379 390 +f 390 379 380 +f 390 380 391 +f 391 380 381 +f 380 370 381 +f 381 370 371 +f 562 553 563 +f 562 552 553 +f 561 552 562 +f 563 553 554 +f 562 571 561 +f 744 569 570 +f 571 570 569 +f 561 571 569 +f 572 562 563 +f 571 562 572 +f 570 571 579 +f 744 570 579 +f 753 744 579 +f 752 744 753 +f 579 572 580 +f 753 579 754 +f 571 572 579 +f 754 579 580 +f 760 752 761 +f 761 752 753 +f 761 753 762 +f 762 753 754 +f 563 554 564 +f 564 554 555 +f 572 563 573 +f 573 563 564 +f 573 564 574 +f 564 555 565 +f 574 564 565 +f 565 555 556 +f 582 581 580 +f 754 580 581 +f 572 582 580 +f 573 582 572 +f 763 754 590 +f 762 754 763 +f 754 581 590 +f 581 582 590 +f 583 573 574 +f 582 573 583 +f 763 590 764 +f 764 590 591 +f 590 583 591 +f 582 583 590 +f 566 556 397 +f 565 556 566 +f 566 397 567 +f 567 397 398 +f 397 389 398 +f 575 566 576 +f 576 566 567 +f 574 565 575 +f 575 565 566 +f 567 398 399 +f 400 399 398 +f 389 400 398 +f 390 400 389 +f 577 567 408 +f 567 399 408 +f 399 400 408 +f 576 567 577 +f 400 390 401 +f 401 390 391 +f 408 401 409 +f 400 401 408 +f 577 408 578 +f 578 408 409 +f 583 574 584 +f 584 574 575 +f 584 575 585 +f 585 575 576 +f 583 593 591 +f 764 591 592 +f 584 593 583 +f 593 592 591 +f 593 584 594 +f 594 584 585 +f 585 576 586 +f 586 576 577 +f 594 585 595 +f 595 585 586 +f 595 586 596 +f 596 586 587 +f 586 577 587 +f 587 577 578 +f 779 771 780 +f 780 771 772 +f 772 760 761 +f 771 760 772 +f 781 772 773 +f 780 772 781 +f 773 761 762 +f 772 761 773 +f 782 773 774 +f 781 773 782 +f 773 762 774 +f 774 762 763 +f 774 763 775 +f 775 763 764 +f 782 774 783 +f 783 774 775 +f 779 790 788 +f 790 789 788 +f 780 790 779 +f 993 788 789 +f 790 780 791 +f 791 780 781 +f 789 790 798 +f 1001 993 1002 +f 1002 993 798 +f 993 789 798 +f 790 800 798 +f 800 799 798 +f 791 800 790 +f 1002 798 799 +f 801 791 792 +f 800 791 801 +f 792 781 782 +f 791 781 792 +f 792 782 793 +f 793 782 783 +f 801 792 802 +f 802 792 793 +f 592 593 600 +f 764 592 600 +f 776 764 600 +f 775 764 776 +f 594 601 593 +f 776 600 601 +f 593 601 600 +f 784 776 785 +f 785 776 601 +f 784 775 776 +f 783 775 784 +f 601 594 602 +f 602 594 595 +f 601 602 609 +f 786 601 609 +f 785 601 786 +f 603 595 596 +f 602 595 603 +f 602 611 609 +f 603 611 602 +f 802 793 803 +f 803 793 794 +f 793 783 794 +f 794 783 784 +f 794 784 795 +f 795 784 785 +f 803 794 804 +f 804 794 795 +f 796 785 786 +f 795 785 796 +f 611 610 609 +f 786 609 610 +f 610 611 618 +f 796 786 797 +f 786 610 618 +f 797 786 618 +f 804 795 805 +f 805 795 796 +f 806 796 797 +f 805 796 806 +f 1196 1192 1197 +f 1193 1189 1190 +f 1192 1189 1193 +f 1197 1192 1193 +f 1198 1193 1194 +f 1197 1193 1198 +f 1194 1190 1191 +f 1193 1190 1194 +f 1195 1191 1003 +f 1194 1191 1195 +f 995 996 1003 +f 1191 995 1003 +f 1198 1194 1199 +f 1199 1194 1195 +f 997 1005 996 +f 996 1005 1003 +f 1195 1003 1004 +f 1005 1004 1003 +f 1004 1005 1012 +f 1195 1004 1012 +f 1200 1195 1012 +f 1199 1195 1200 +f 1202 1201 1203 +f 1196 1202 1203 +f 1197 1202 1196 +f 1316 1203 1201 +f 1204 1197 1198 +f 1202 1197 1204 +f 1316 1201 1208 +f 1318 1316 1208 +f 1317 1316 1318 +f 1201 1202 1208 +f 1318 1208 1209 +f 1210 1209 1208 +f 1202 1210 1208 +f 1204 1210 1202 +f 1210 1204 1211 +f 1211 1204 1205 +f 1204 1198 1205 +f 1205 1198 1199 +f 1206 1199 1200 +f 1205 1199 1206 +f 1212 1205 1206 +f 1211 1205 1212 +f 1323 1319 1320 +f 1322 1319 1323 +f 1319 1317 1320 +f 1320 1317 1318 +f 1318 1209 1214 +f 1321 1318 1214 +f 1209 1210 1214 +f 1320 1318 1321 +f 1324 1320 1321 +f 1323 1320 1324 +f 1323 1326 1322 +f 1377 1327 1325 +f 1326 1325 1327 +f 1322 1326 1327 +f 1325 1326 1330 +f 1330 1377 1325 +f 1378 1377 1330 +f 1326 1323 1328 +f 1328 1323 1324 +f 1330 1326 1331 +f 1331 1326 1332 +f 1332 1326 1328 +f 1321 1214 1215 +f 1211 1216 1210 +f 1210 1216 1214 +f 1216 1215 1214 +f 1215 1216 1220 +f 1220 1321 1215 +f 1324 1321 1220 +f 1216 1211 1217 +f 1217 1211 1212 +f 1220 1216 1221 +f 1222 1216 1217 +f 1221 1216 1222 +f 1328 1324 1329 +f 1220 1221 1226 +f 1324 1220 1226 +f 1329 1324 1226 +f 1221 1228 1226 +f 1228 1227 1226 +f 1222 1228 1221 +f 1329 1226 1227 +f 1332 1328 1333 +f 1333 1328 1329 +f 1227 1228 1232 +f 1329 1227 1232 +f 1334 1329 1232 +f 1333 1329 1334 +f 1005 997 1006 +f 1006 997 998 +f 1006 1014 1005 +f 1005 1014 1012 +f 1200 1012 1013 +f 1014 1013 1012 +f 1007 998 999 +f 1015 1006 1007 +f 1006 998 1007 +f 1014 1006 1015 +f 1008 999 1000 +f 1015 1007 1016 +f 1007 999 1008 +f 1016 1007 1008 +f 1009 1000 1001 +f 1016 1008 1017 +f 1017 1008 1009 +f 1008 1000 1009 +f 1207 1200 1021 +f 1200 1013 1021 +f 1206 1200 1207 +f 1013 1014 1021 +f 1015 1023 1014 +f 1207 1021 1022 +f 1023 1022 1021 +f 1014 1023 1021 +f 1212 1206 1213 +f 1213 1206 1207 +f 1022 1023 1030 +f 1030 1023 1031 +f 1213 1207 1030 +f 1030 1207 1022 +f 1030 1031 1039 +f 1213 1030 1039 +f 1032 1023 1024 +f 1031 1023 1032 +f 1024 1015 1016 +f 1023 1015 1024 +f 1024 1016 1025 +f 1025 1016 1017 +f 1032 1024 1033 +f 1033 1024 1025 +f 1217 1212 1218 +f 1218 1212 1213 +f 1222 1217 1223 +f 1223 1217 1218 +f 1223 1218 1224 +f 1219 1213 1039 +f 1224 1218 1219 +f 1218 1213 1219 +f 1228 1222 1229 +f 1229 1222 1223 +f 1229 1234 1228 +f 1234 1233 1232 +f 1334 1232 1233 +f 1228 1234 1232 +f 1229 1223 1230 +f 1230 1223 1224 +f 1235 1229 1230 +f 1234 1229 1235 +f 1041 1040 1039 +f 1031 1041 1039 +f 1032 1041 1031 +f 1219 1039 1040 +f 1042 1032 1033 +f 1041 1032 1042 +f 1225 1219 1050 +f 1224 1219 1225 +f 1040 1041 1050 +f 1219 1040 1050 +f 1042 1052 1041 +f 1041 1052 1050 +f 1052 1051 1050 +f 1225 1050 1051 +f 1236 1230 1231 +f 1230 1224 1231 +f 1235 1230 1236 +f 1231 1224 1225 +f 1061 1225 1051 +f 1231 1225 1061 +f 1051 1052 1061 +f 1061 1052 1062 +f 1061 1062 1073 +f 1237 1231 1073 +f 1236 1231 1237 +f 1231 1061 1073 +f 1380 1378 1335 +f 1378 1330 1335 +f 1379 1378 1380 +f 1330 1331 1335 +f 1380 1335 1336 +f 1337 1336 1335 +f 1331 1337 1335 +f 1332 1337 1331 +f 1381 1379 1382 +f 1382 1379 1380 +f 1336 1337 1340 +f 1383 1380 1340 +f 1382 1380 1383 +f 1380 1336 1340 +f 1337 1332 1338 +f 1338 1332 1333 +f 1338 1342 1337 +f 1383 1340 1341 +f 1337 1342 1340 +f 1342 1341 1340 +f 1339 1333 1334 +f 1338 1333 1339 +f 1343 1338 1339 +f 1342 1338 1343 +f 1385 1381 1382 +f 1384 1381 1385 +f 1402 1389 1387 +f 1388 1387 1389 +f 1384 1388 1389 +f 1385 1388 1384 +f 1388 1385 1390 +f 1385 1382 1386 +f 1386 1382 1383 +f 1390 1385 1386 +f 1345 1383 1341 +f 1341 1342 1345 +f 1345 1342 1346 +f 1386 1383 1345 +f 1347 1342 1343 +f 1346 1342 1347 +f 1390 1386 1391 +f 1391 1386 1349 +f 1386 1345 1349 +f 1345 1346 1349 +f 1351 1350 1349 +f 1346 1351 1349 +f 1347 1351 1346 +f 1391 1349 1350 +f 1339 1334 1238 +f 1238 1334 1233 +f 1233 1234 1238 +f 1238 1234 1239 +f 1239 1234 1240 +f 1240 1234 1235 +f 1339 1238 1244 +f 1344 1339 1244 +f 1343 1339 1344 +f 1238 1239 1244 +f 1246 1245 1244 +f 1239 1246 1244 +f 1240 1246 1239 +f 1344 1244 1245 +f 1352 1347 1348 +f 1351 1347 1352 +f 1348 1343 1344 +f 1347 1343 1348 +f 1245 1246 1251 +f 1348 1344 1251 +f 1251 1344 1245 +f 1348 1251 1259 +f 1353 1348 1259 +f 1352 1348 1353 +f 1241 1235 1236 +f 1240 1235 1241 +f 1247 1240 1241 +f 1246 1240 1247 +f 1247 1241 1248 +f 1248 1241 1242 +f 1241 1236 1242 +f 1242 1236 1237 +f 1251 1246 1252 +f 1252 1246 1253 +f 1253 1246 1247 +f 1251 1252 1259 +f 1253 1261 1252 +f 1261 1260 1259 +f 1252 1261 1259 +f 1353 1259 1260 +f 1254 1247 1248 +f 1262 1253 1254 +f 1253 1247 1254 +f 1261 1253 1262 +f 1387 1388 851 +f 787 1402 765 +f 765 1402 851 +f 1402 1387 851 +f 765 851 766 +f 636 787 765 +f 676 787 636 +f 1392 766 851 +f 1388 1392 851 +f 1390 1392 1388 +f 766 1392 635 +f 635 1392 1394 +f 636 765 635 +f 635 765 766 +f 519 676 636 +f 545 676 519 +f 545 520 215 +f 520 217 215 +f 216 215 217 +f 519 520 545 +f 636 635 608 +f 519 636 301 +f 635 1394 608 +f 301 636 608 +f 520 519 302 +f 302 519 301 +f 1393 1390 1391 +f 1395 1392 1393 +f 1394 1392 1395 +f 1392 1390 1393 +f 1350 1351 1354 +f 1354 1391 1350 +f 1393 1391 1354 +f 1354 1351 1355 +f 1396 1393 1359 +f 1393 1354 1359 +f 1395 1393 1396 +f 1354 1355 1359 +f 301 608 300 +f 1397 300 608 +f 1395 1397 1394 +f 1394 1397 608 +f 1398 1395 1396 +f 1397 1395 1398 +f 302 301 274 +f 301 300 273 +f 274 301 273 +f 300 1397 273 +f 1398 1400 1397 +f 1397 1400 273 +f 274 273 275 +f 1400 275 273 +f 1356 1351 1352 +f 1355 1351 1356 +f 1356 1361 1355 +f 1355 1361 1359 +f 1361 1360 1359 +f 1396 1359 1360 +f 1361 1356 1362 +f 1357 1352 1353 +f 1356 1352 1357 +f 1362 1356 1357 +f 1360 1361 1365 +f 1396 1360 1365 +f 1398 1396 1399 +f 1399 1396 1365 +f 1399 1365 1366 +f 1400 1398 1401 +f 1401 1398 1399 +f 1362 1367 1361 +f 1367 1366 1365 +f 1361 1367 1365 +f 1401 1399 1371 +f 1371 1399 1366 +f 1371 1367 1372 +f 1366 1367 1371 +f 1353 1260 1269 +f 1358 1353 1269 +f 1357 1353 1358 +f 1260 1261 1269 +f 1271 1270 1269 +f 1261 1271 1269 +f 1262 1271 1261 +f 1358 1269 1270 +f 1362 1357 1363 +f 1363 1357 1358 +f 1358 1270 1280 +f 1364 1358 1280 +f 1363 1358 1364 +f 1270 1271 1280 +f 1373 1367 1368 +f 1367 1362 1368 +f 1368 1362 1363 +f 1372 1367 1373 +f 1369 1363 1364 +f 1368 1363 1369 +f 1374 1368 1369 +f 1373 1368 1374 +f 1009 1001 1010 +f 1010 1001 1002 +f 1017 1009 1018 +f 1018 1009 1010 +f 1011 1002 808 +f 1010 1002 1011 +f 799 800 808 +f 1002 799 808 +f 1019 1010 1011 +f 1018 1010 1019 +f 1026 1017 1018 +f 1034 1025 1026 +f 1025 1017 1026 +f 1033 1025 1034 +f 1035 1026 1027 +f 1034 1026 1035 +f 1027 1018 1019 +f 1026 1018 1027 +f 1011 808 809 +f 800 810 808 +f 810 809 808 +f 801 810 800 +f 1019 1011 1020 +f 1020 1011 819 +f 1011 809 819 +f 809 810 819 +f 811 801 802 +f 810 801 811 +f 821 820 819 +f 810 821 819 +f 1020 819 820 +f 811 821 810 +f 1028 1019 1020 +f 1027 1019 1028 +f 1028 1020 1029 +f 1029 1020 830 +f 820 821 830 +f 1020 820 830 +f 1037 1028 1029 +f 1036 1028 1037 +f 1036 1027 1028 +f 1035 1027 1036 +f 1052 1042 1053 +f 1053 1042 1043 +f 1043 1033 1034 +f 1042 1033 1043 +f 1054 1043 1044 +f 1053 1043 1054 +f 1043 1034 1044 +f 1044 1034 1035 +f 1062 1052 1063 +f 1063 1052 1053 +f 1237 1073 1074 +f 1063 1075 1062 +f 1062 1075 1073 +f 1075 1074 1073 +f 1064 1053 1054 +f 1075 1063 1076 +f 1076 1063 1064 +f 1063 1053 1064 +f 1044 1035 1045 +f 1045 1035 1036 +f 1054 1044 1055 +f 1055 1044 1045 +f 1056 1045 1046 +f 1055 1045 1056 +f 1046 1036 1037 +f 1045 1036 1046 +f 1064 1054 1065 +f 1065 1054 1055 +f 1077 1064 1065 +f 1076 1064 1077 +f 1066 1055 1056 +f 1077 1065 1078 +f 1078 1065 1066 +f 1065 1055 1066 +f 812 802 803 +f 822 811 812 +f 811 802 812 +f 821 811 822 +f 813 803 804 +f 823 812 813 +f 822 812 823 +f 812 803 813 +f 1029 830 831 +f 832 831 830 +f 821 832 830 +f 822 832 821 +f 1029 831 841 +f 1037 1029 1038 +f 1038 1029 841 +f 831 832 841 +f 832 822 833 +f 833 822 823 +f 833 842 832 +f 832 842 841 +f 1038 841 842 +f 824 813 814 +f 814 804 805 +f 813 804 814 +f 823 813 824 +f 825 814 815 +f 824 814 825 +f 814 805 815 +f 815 805 806 +f 842 833 843 +f 833 823 834 +f 834 823 824 +f 843 833 834 +f 835 824 825 +f 843 834 844 +f 834 824 835 +f 844 834 835 +f 1056 1046 1057 +f 1047 1037 1038 +f 1057 1046 1047 +f 1046 1037 1047 +f 1047 1038 1048 +f 1048 1038 842 +f 1057 1047 1058 +f 1058 1047 1048 +f 1078 1066 1079 +f 1079 1066 1067 +f 1066 1056 1067 +f 1067 1056 1057 +f 1067 1057 1068 +f 1068 1057 1058 +f 1079 1067 1080 +f 1080 1067 1068 +f 842 843 852 +f 1049 842 852 +f 1048 842 1049 +f 1059 1048 1049 +f 1058 1048 1059 +f 844 854 843 +f 843 854 852 +f 854 853 852 +f 1049 852 853 +f 1059 1049 1060 +f 1060 1049 862 +f 1049 853 862 +f 853 854 862 +f 1081 1068 1069 +f 1080 1068 1081 +f 1069 1058 1059 +f 1068 1058 1069 +f 1069 1059 1070 +f 1070 1059 1060 +f 1081 1069 1082 +f 1082 1069 1070 +f 1074 1075 1086 +f 1237 1074 1086 +f 1243 1237 1086 +f 1242 1237 1243 +f 1248 1242 1249 +f 1249 1242 1243 +f 1088 1087 1086 +f 1075 1088 1086 +f 1076 1088 1075 +f 1243 1086 1087 +f 1087 1088 1099 +f 1249 1243 1250 +f 1243 1087 1099 +f 1250 1243 1099 +f 1089 1076 1077 +f 1089 1077 1090 +f 1090 1077 1078 +f 1088 1076 1089 +f 1089 1101 1088 +f 1088 1101 1099 +f 1101 1100 1099 +f 1250 1099 1100 +f 1102 1089 1090 +f 1101 1089 1102 +f 1254 1248 1255 +f 1255 1248 1249 +f 1262 1254 1263 +f 1263 1254 1255 +f 1263 1255 1264 +f 1264 1255 1256 +f 1255 1249 1256 +f 1256 1249 1250 +f 1100 1101 1113 +f 1250 1100 1113 +f 1256 1250 1257 +f 1257 1250 1113 +f 1101 1102 1113 +f 1113 1102 1114 +f 1258 1113 1114 +f 1257 1113 1258 +f 1264 1256 1265 +f 1265 1256 1257 +f 1266 1257 1258 +f 1265 1257 1266 +f 1090 1078 1091 +f 1091 1078 1079 +f 1103 1090 1091 +f 1102 1090 1103 +f 1092 1079 1080 +f 1091 1079 1092 +f 1103 1091 1104 +f 1104 1091 1092 +f 1104 1092 1105 +f 1105 1092 1093 +f 1093 1080 1081 +f 1092 1080 1093 +f 1106 1093 1094 +f 1105 1093 1106 +f 1093 1081 1094 +f 1094 1081 1082 +f 1103 1116 1102 +f 1102 1116 1114 +f 1116 1115 1114 +f 1258 1114 1115 +f 1266 1258 1267 +f 1258 1115 1127 +f 1267 1258 1127 +f 1115 1116 1127 +f 1117 1103 1104 +f 1116 1103 1117 +f 1268 1127 1128 +f 1267 1127 1268 +f 1127 1117 1128 +f 1116 1117 1127 +f 1119 1105 1106 +f 1118 1105 1119 +f 1118 1104 1105 +f 1117 1104 1118 +f 1117 1130 1128 +f 1118 1130 1117 +f 1129 1130 1140 +f 1268 1129 1140 +f 1130 1129 1128 +f 1268 1128 1129 +f 1131 1118 1119 +f 1130 1118 1131 +f 1130 1131 1140 +f 1272 1262 1263 +f 1271 1262 1272 +f 1272 1282 1271 +f 1364 1280 1281 +f 1282 1281 1280 +f 1271 1282 1280 +f 1273 1263 1264 +f 1283 1272 1273 +f 1282 1272 1283 +f 1272 1263 1273 +f 1370 1364 1291 +f 1364 1281 1291 +f 1369 1364 1370 +f 1281 1282 1291 +f 1375 1369 1370 +f 1374 1369 1375 +f 1293 1292 1291 +f 1283 1293 1282 +f 1370 1291 1292 +f 1282 1293 1291 +f 1376 1370 1303 +f 1370 1292 1303 +f 1375 1370 1376 +f 1292 1293 1303 +f 1273 1264 1274 +f 1274 1264 1265 +f 1283 1273 1284 +f 1284 1273 1274 +f 1285 1274 1275 +f 1284 1274 1285 +f 1275 1265 1266 +f 1274 1265 1275 +f 1293 1283 1294 +f 1295 1284 1285 +f 1294 1284 1295 +f 1294 1283 1284 +f 1305 1304 1303 +f 1293 1305 1303 +f 1294 1305 1293 +f 1376 1303 1304 +f 1306 1294 1295 +f 1305 1294 1306 +f 1285 1275 1286 +f 1286 1275 1276 +f 1276 1266 1267 +f 1275 1266 1276 +f 1287 1276 1277 +f 1286 1276 1287 +f 1277 1267 1268 +f 1276 1267 1277 +f 1278 1268 1140 +f 1277 1268 1278 +f 1140 1131 1141 +f 1279 1140 1141 +f 1278 1140 1279 +f 1288 1277 1278 +f 1287 1277 1288 +f 1289 1278 1279 +f 1288 1278 1289 +f 1295 1285 1296 +f 1306 1295 1307 +f 1296 1285 1286 +f 1307 1295 1296 +f 1297 1286 1287 +f 1296 1286 1297 +f 1307 1296 1308 +f 1308 1296 1297 +f 1297 1287 1298 +f 1298 1287 1288 +f 1309 1297 1298 +f 1308 1297 1309 +f 1298 1288 1299 +f 1309 1298 1310 +f 1310 1298 1299 +f 1299 1288 1289 +f 2 1 3 +f 143 144 145 +f 145 144 3 +f 144 2 3 +f 3 4 5 +f 1 4 3 +f 145 3 146 +f 146 3 5 +f 157 143 158 +f 158 143 145 +f 158 145 159 +f 159 145 146 +f 7 6 5 +f 146 5 6 +f 8 7 4 +f 4 7 5 +f 146 6 35 +f 6 7 35 +f 160 146 35 +f 159 146 160 +f 9 8 10 +f 7 8 9 +f 35 9 36 +f 7 9 35 +f 161 35 36 +f 160 35 161 +f 184 171 185 +f 185 171 172 +f 172 157 158 +f 171 157 172 +f 186 172 173 +f 185 172 186 +f 172 158 173 +f 173 158 159 +f 186 173 187 +f 187 173 174 +f 174 159 160 +f 173 159 174 +f 187 174 188 +f 174 160 175 +f 175 160 161 +f 188 174 175 +f 11 10 12 +f 9 10 11 +f 13 12 14 +f 11 12 13 +f 9 38 36 +f 11 38 9 +f 161 37 50 +f 37 38 50 +f 38 37 36 +f 161 36 37 +f 38 11 39 +f 39 11 13 +f 38 39 50 +f 39 13 40 +f 40 13 15 +f 13 14 15 +f 15 14 16 +f 15 16 17 +f 41 15 17 +f 40 15 41 +f 17 16 18 +f 176 161 50 +f 175 161 176 +f 177 50 51 +f 50 39 51 +f 176 50 177 +f 188 175 189 +f 189 175 176 +f 189 176 190 +f 190 176 177 +f 177 51 52 +f 53 52 51 +f 39 53 51 +f 40 53 39 +f 190 177 191 +f 52 53 63 +f 177 52 63 +f 191 177 63 +f 53 40 54 +f 54 40 41 +f 54 65 53 +f 53 65 63 +f 191 63 64 +f 65 64 63 +f 195 196 204 +f 195 184 196 +f 196 184 185 +f 196 185 197 +f 197 185 186 +f 372 204 205 +f 204 196 205 +f 371 204 372 +f 372 205 206 +f 196 206 205 +f 197 206 196 +f 381 371 382 +f 382 371 372 +f 392 381 382 +f 391 381 392 +f 383 372 206 +f 392 382 393 +f 382 372 383 +f 393 382 383 +f 197 186 198 +f 198 186 187 +f 207 197 198 +f 206 197 207 +f 208 198 199 +f 198 187 199 +f 207 198 208 +f 199 187 188 +f 206 207 218 +f 383 206 384 +f 384 206 218 +f 394 383 384 +f 393 383 394 +f 384 218 219 +f 220 219 218 +f 207 220 218 +f 208 220 207 +f 219 220 228 +f 394 384 395 +f 395 384 228 +f 384 219 228 +f 200 188 189 +f 209 199 200 +f 208 199 209 +f 199 188 200 +f 210 200 201 +f 209 200 210 +f 200 189 201 +f 201 189 190 +f 201 190 202 +f 202 190 191 +f 191 64 74 +f 203 191 74 +f 202 191 203 +f 64 65 74 +f 210 201 211 +f 211 201 202 +f 211 202 212 +f 212 202 203 +f 220 221 228 +f 221 208 209 +f 220 208 221 +f 221 209 222 +f 222 209 210 +f 228 221 229 +f 395 228 396 +f 396 228 229 +f 396 229 230 +f 231 230 229 +f 222 231 221 +f 221 231 229 +f 222 210 223 +f 223 210 211 +f 231 222 232 +f 232 222 223 +f 232 223 233 +f 224 211 212 +f 233 223 224 +f 223 211 224 +f 17 18 19 +f 19 18 20 +f 42 17 19 +f 41 17 42 +f 21 20 22 +f 19 20 21 +f 42 19 43 +f 43 19 21 +f 65 54 66 +f 66 54 55 +f 55 41 42 +f 54 41 55 +f 67 55 56 +f 66 55 67 +f 55 42 56 +f 56 42 43 +f 21 22 23 +f 23 22 24 +f 44 21 23 +f 43 21 44 +f 25 24 26 +f 23 24 25 +f 44 23 45 +f 45 23 25 +f 67 56 68 +f 68 56 57 +f 57 43 44 +f 56 43 57 +f 69 57 58 +f 68 57 69 +f 57 44 58 +f 58 44 45 +f 45 25 46 +f 46 25 27 +f 27 26 28 +f 25 26 27 +f 47 27 29 +f 46 27 47 +f 27 28 29 +f 29 28 30 +f 58 45 59 +f 59 45 46 +f 70 58 59 +f 69 58 70 +f 60 46 47 +f 59 46 60 +f 70 59 71 +f 71 59 60 +f 47 29 48 +f 48 29 31 +f 31 30 32 +f 29 30 31 +f 49 31 33 +f 48 31 49 +f 31 32 33 +f 33 32 34 +f 60 47 61 +f 61 47 48 +f 72 60 61 +f 71 60 72 +f 62 48 49 +f 61 48 62 +f 72 61 73 +f 73 61 62 +f 76 75 74 +f 65 76 74 +f 66 76 65 +f 203 74 75 +f 75 76 84 +f 212 203 213 +f 203 75 84 +f 213 203 84 +f 76 66 77 +f 77 66 67 +f 214 84 85 +f 213 84 214 +f 76 77 84 +f 84 77 85 +f 233 224 234 +f 225 212 213 +f 224 212 225 +f 234 224 225 +f 234 225 235 +f 235 225 226 +f 226 213 214 +f 225 213 226 +f 79 68 69 +f 78 68 79 +f 78 67 68 +f 77 67 78 +f 87 86 85 +f 78 87 77 +f 77 87 85 +f 214 85 86 +f 87 78 88 +f 88 78 79 +f 86 87 93 +f 226 214 227 +f 227 214 93 +f 214 86 93 +f 235 226 236 +f 236 226 227 +f 95 94 93 +f 87 95 93 +f 88 95 87 +f 227 93 94 +f 94 95 100 +f 236 227 237 +f 227 94 100 +f 237 227 100 +f 88 79 89 +f 79 69 80 +f 89 79 80 +f 80 69 70 +f 90 80 81 +f 89 80 90 +f 80 70 81 +f 81 70 71 +f 90 81 91 +f 91 81 82 +f 82 71 72 +f 81 71 82 +f 91 82 92 +f 82 72 83 +f 83 72 73 +f 92 82 83 +f 95 88 96 +f 96 88 89 +f 96 89 97 +f 97 89 90 +f 96 102 95 +f 237 100 101 +f 102 101 100 +f 95 102 100 +f 102 96 103 +f 103 96 97 +f 97 90 98 +f 98 90 91 +f 104 97 98 +f 103 97 104 +f 99 91 92 +f 98 91 99 +f 104 98 105 +f 105 98 99 +f 403 392 393 +f 402 392 403 +f 402 391 392 +f 401 391 402 +f 402 411 401 +f 578 409 410 +f 401 411 409 +f 411 410 409 +f 578 410 418 +f 410 411 418 +f 411 402 412 +f 412 402 403 +f 411 412 418 +f 413 403 404 +f 404 393 394 +f 403 393 404 +f 412 403 413 +f 405 394 395 +f 404 394 405 +f 414 404 405 +f 413 404 414 +f 587 578 588 +f 588 578 418 +f 418 412 419 +f 588 418 589 +f 589 418 419 +f 596 587 597 +f 597 587 588 +f 597 588 598 +f 598 588 589 +f 412 421 419 +f 413 421 412 +f 589 419 420 +f 421 420 419 +f 589 420 427 +f 599 589 427 +f 420 421 427 +f 598 589 599 +f 421 413 422 +f 422 413 414 +f 421 429 427 +f 429 428 427 +f 422 429 421 +f 599 427 428 +f 611 603 612 +f 604 596 597 +f 612 603 604 +f 603 596 604 +f 612 604 613 +f 604 597 605 +f 605 597 598 +f 613 604 605 +f 605 598 606 +f 606 598 599 +f 599 428 435 +f 607 599 435 +f 606 599 607 +f 428 429 435 +f 614 605 606 +f 615 606 607 +f 614 606 615 +f 613 605 614 +f 612 620 611 +f 797 618 619 +f 620 619 618 +f 611 620 618 +f 807 797 627 +f 806 797 807 +f 619 620 627 +f 797 619 627 +f 620 612 621 +f 621 612 613 +f 807 627 628 +f 621 628 620 +f 620 628 627 +f 621 613 622 +f 622 613 614 +f 629 621 622 +f 628 621 629 +f 623 614 615 +f 622 614 623 +f 629 622 630 +f 630 622 623 +f 405 395 406 +f 406 395 396 +f 396 230 238 +f 406 396 407 +f 230 231 238 +f 407 396 238 +f 416 406 407 +f 415 406 416 +f 415 405 406 +f 414 405 415 +f 429 422 430 +f 430 422 423 +f 423 414 415 +f 422 414 423 +f 430 423 431 +f 423 415 424 +f 424 415 416 +f 431 423 424 +f 240 239 238 +f 231 240 238 +f 232 240 231 +f 407 238 239 +f 239 240 247 +f 407 239 247 +f 417 407 247 +f 416 407 417 +f 241 232 233 +f 240 232 241 +f 417 247 248 +f 241 249 240 +f 249 248 247 +f 240 249 247 +f 424 416 425 +f 425 416 417 +f 417 248 256 +f 426 417 256 +f 425 417 426 +f 248 249 256 +f 432 424 425 +f 432 425 433 +f 433 425 426 +f 431 424 432 +f 430 437 429 +f 429 437 435 +f 437 436 435 +f 607 435 436 +f 436 437 444 +f 607 436 444 +f 615 607 616 +f 616 607 444 +f 438 430 431 +f 437 430 438 +f 616 444 617 +f 437 438 444 +f 444 438 445 +f 617 444 445 +f 623 615 624 +f 624 615 616 +f 630 623 631 +f 631 623 624 +f 625 616 617 +f 631 624 632 +f 632 624 625 +f 624 616 625 +f 439 432 440 +f 440 432 433 +f 438 431 439 +f 439 431 432 +f 617 445 446 +f 447 446 445 +f 438 447 445 +f 439 447 438 +f 447 439 448 +f 448 439 440 +f 446 447 453 +f 625 617 626 +f 626 617 453 +f 617 446 453 +f 632 625 633 +f 633 625 626 +f 626 453 454 +f 455 454 453 +f 447 455 453 +f 448 455 447 +f 633 626 634 +f 454 455 461 +f 634 626 461 +f 626 454 461 +f 249 241 250 +f 250 241 242 +f 241 233 242 +f 242 233 234 +f 242 234 243 +f 243 234 235 +f 251 242 243 +f 250 242 251 +f 426 256 257 +f 250 258 249 +f 249 258 256 +f 258 257 256 +f 426 257 265 +f 434 426 265 +f 433 426 434 +f 257 258 265 +f 259 250 251 +f 258 250 259 +f 434 265 266 +f 259 266 258 +f 258 266 265 +f 251 243 252 +f 243 235 244 +f 244 235 236 +f 252 243 244 +f 244 236 245 +f 252 244 253 +f 245 236 237 +f 253 244 245 +f 267 259 260 +f 259 251 260 +f 260 251 252 +f 266 259 267 +f 260 252 261 +f 261 252 253 +f 267 260 268 +f 268 260 261 +f 101 102 106 +f 245 237 246 +f 246 237 106 +f 237 101 106 +f 102 108 106 +f 108 107 106 +f 103 108 102 +f 246 106 107 +f 253 245 254 +f 254 245 246 +f 255 246 111 +f 254 246 255 +f 107 108 111 +f 246 107 111 +f 108 103 109 +f 109 103 104 +f 255 111 112 +f 113 112 111 +f 109 113 108 +f 108 113 111 +f 113 109 114 +f 114 109 110 +f 110 104 105 +f 109 104 110 +f 268 261 269 +f 269 261 262 +f 261 253 262 +f 262 253 254 +f 263 254 255 +f 262 254 263 +f 270 262 263 +f 269 262 270 +f 264 255 115 +f 112 113 115 +f 255 112 115 +f 263 255 264 +f 264 115 116 +f 117 116 115 +f 113 117 115 +f 114 117 113 +f 270 263 271 +f 271 263 264 +f 264 116 118 +f 272 264 118 +f 271 264 272 +f 116 117 118 +f 440 433 441 +f 448 440 449 +f 441 433 434 +f 449 440 441 +f 441 434 442 +f 449 441 450 +f 442 434 266 +f 450 441 442 +f 266 267 276 +f 443 266 276 +f 442 266 443 +f 451 442 443 +f 450 442 451 +f 267 278 276 +f 278 277 276 +f 443 276 277 +f 268 278 267 +f 443 277 283 +f 452 443 283 +f 451 443 452 +f 277 278 283 +f 456 448 449 +f 456 449 457 +f 455 448 456 +f 457 449 450 +f 455 463 461 +f 463 462 461 +f 634 461 462 +f 456 463 455 +f 464 456 457 +f 463 456 464 +f 464 457 465 +f 458 450 451 +f 465 457 458 +f 457 450 458 +f 465 458 466 +f 458 451 459 +f 459 451 452 +f 466 458 459 +f 278 268 279 +f 280 269 270 +f 279 269 280 +f 279 268 269 +f 285 284 283 +f 278 285 283 +f 452 283 284 +f 279 285 278 +f 285 279 286 +f 286 279 280 +f 286 280 287 +f 287 280 281 +f 281 270 271 +f 280 270 281 +f 287 281 288 +f 281 271 282 +f 282 271 272 +f 288 281 282 +f 452 284 289 +f 459 452 460 +f 284 285 289 +f 460 452 289 +f 286 291 285 +f 285 291 289 +f 291 290 289 +f 460 289 290 +f 467 459 460 +f 466 459 467 +f 468 460 294 +f 467 460 468 +f 460 290 294 +f 290 291 294 +f 291 286 292 +f 292 286 287 +f 291 296 294 +f 296 295 294 +f 468 294 295 +f 292 296 291 +f 292 287 293 +f 293 287 288 +f 297 292 293 +f 296 292 297 +f 815 806 816 +f 826 815 816 +f 816 806 807 +f 825 815 826 +f 816 807 817 +f 817 807 628 +f 827 816 817 +f 826 816 827 +f 845 835 836 +f 835 825 836 +f 844 835 845 +f 836 825 826 +f 836 826 837 +f 837 826 827 +f 845 836 846 +f 846 836 837 +f 628 629 637 +f 817 628 818 +f 818 628 637 +f 828 817 818 +f 827 817 828 +f 639 638 637 +f 818 637 638 +f 630 639 629 +f 629 639 637 +f 828 818 829 +f 818 638 645 +f 638 639 645 +f 829 818 645 +f 837 827 838 +f 847 837 838 +f 838 827 828 +f 846 837 847 +f 838 828 839 +f 847 838 848 +f 848 838 839 +f 839 828 829 +f 641 631 632 +f 640 631 641 +f 640 630 631 +f 639 630 640 +f 647 646 645 +f 640 647 639 +f 639 647 645 +f 829 645 646 +f 829 646 653 +f 646 647 653 +f 648 640 641 +f 647 640 648 +f 641 632 642 +f 642 632 633 +f 649 641 642 +f 648 641 649 +f 642 633 643 +f 643 633 634 +f 649 642 650 +f 650 642 643 +f 848 839 849 +f 849 839 840 +f 840 829 653 +f 839 829 840 +f 840 653 654 +f 655 654 653 +f 647 655 653 +f 648 655 647 +f 850 840 661 +f 840 654 661 +f 654 655 661 +f 849 840 850 +f 657 649 650 +f 655 648 656 +f 656 648 649 +f 656 649 657 +f 656 663 655 +f 663 662 661 +f 850 661 662 +f 655 663 661 +f 662 663 669 +f 850 662 669 +f 664 656 657 +f 663 656 664 +f 856 845 846 +f 855 845 856 +f 854 844 855 +f 855 844 845 +f 864 863 862 +f 1060 862 863 +f 855 864 854 +f 854 864 862 +f 863 864 873 +f 1060 863 873 +f 864 855 865 +f 864 865 873 +f 865 855 856 +f 856 846 857 +f 866 856 857 +f 865 856 866 +f 857 846 847 +f 858 847 848 +f 857 847 858 +f 867 857 858 +f 866 857 867 +f 1071 1060 873 +f 1070 1060 1071 +f 873 865 874 +f 1071 873 1072 +f 1072 873 874 +f 1083 1070 1071 +f 1084 1071 1072 +f 1083 1071 1084 +f 1082 1070 1083 +f 866 876 865 +f 865 876 874 +f 876 875 874 +f 1072 874 875 +f 1072 875 884 +f 1085 1072 884 +f 875 876 884 +f 1084 1072 1085 +f 876 866 877 +f 877 866 867 +f 886 885 884 +f 876 886 884 +f 877 886 876 +f 1085 884 885 +f 867 858 868 +f 859 848 849 +f 868 858 859 +f 858 848 859 +f 868 859 869 +f 859 849 860 +f 860 849 850 +f 869 859 860 +f 886 877 887 +f 887 877 878 +f 878 867 868 +f 877 867 878 +f 888 878 879 +f 887 878 888 +f 878 868 879 +f 879 868 869 +f 869 860 870 +f 870 860 861 +f 861 850 669 +f 860 850 861 +f 861 669 670 +f 663 670 669 +f 664 670 663 +f 871 861 670 +f 870 861 871 +f 879 869 880 +f 880 869 870 +f 889 879 880 +f 888 879 889 +f 881 870 871 +f 880 870 881 +f 889 880 890 +f 890 880 881 +f 1106 1094 1107 +f 1107 1094 1095 +f 1095 1082 1083 +f 1094 1082 1095 +f 1107 1095 1108 +f 1108 1095 1096 +f 1095 1083 1096 +f 1096 1083 1084 +f 1096 1084 1097 +f 1097 1084 1085 +f 1085 885 894 +f 885 886 894 +f 1098 1085 894 +f 1097 1085 1098 +f 1108 1096 1109 +f 1109 1096 1097 +f 1110 1097 1098 +f 1109 1097 1110 +f 1119 1106 1120 +f 1120 1106 1107 +f 1131 1119 1132 +f 1132 1119 1120 +f 1133 1120 1121 +f 1132 1120 1133 +f 1121 1107 1108 +f 1120 1107 1121 +f 1134 1121 1122 +f 1133 1121 1134 +f 1122 1108 1109 +f 1121 1108 1122 +f 1122 1109 1123 +f 1123 1109 1110 +f 1134 1122 1135 +f 1135 1122 1123 +f 1098 894 895 +f 896 895 894 +f 886 896 894 +f 887 896 886 +f 895 896 904 +f 1110 1098 1111 +f 1111 1098 904 +f 1098 895 904 +f 896 887 897 +f 897 887 888 +f 1111 904 1112 +f 1112 904 905 +f 896 897 904 +f 904 897 905 +f 1135 1123 1136 +f 1123 1110 1124 +f 1124 1110 1111 +f 1136 1123 1124 +f 1136 1124 1137 +f 1137 1124 1125 +f 1124 1111 1125 +f 1125 1111 1112 +f 898 888 889 +f 899 889 890 +f 898 889 899 +f 897 888 898 +f 1112 905 906 +f 907 906 905 +f 898 907 897 +f 897 907 905 +f 908 898 899 +f 907 898 908 +f 1125 1112 1126 +f 906 907 914 +f 1112 906 914 +f 1126 1112 914 +f 1137 1125 1138 +f 1138 1125 1126 +f 1126 914 915 +f 907 916 914 +f 908 916 907 +f 916 915 914 +f 1139 1126 923 +f 1138 1126 1139 +f 915 916 923 +f 1126 915 923 +f 1143 1142 1141 +f 1131 1143 1141 +f 1279 1141 1142 +f 1132 1143 1131 +f 1289 1279 1290 +f 1142 1143 1152 +f 1290 1279 1152 +f 1279 1142 1152 +f 1144 1132 1133 +f 1143 1132 1144 +f 1290 1152 1153 +f 1154 1153 1152 +f 1143 1154 1152 +f 1144 1154 1143 +f 1300 1289 1290 +f 1299 1289 1300 +f 1153 1154 1163 +f 1301 1290 1163 +f 1290 1153 1163 +f 1300 1290 1301 +f 1312 1300 1301 +f 1311 1300 1312 +f 1310 1299 1311 +f 1311 1299 1300 +f 1155 1144 1145 +f 1145 1133 1134 +f 1144 1133 1145 +f 1154 1144 1155 +f 1146 1134 1135 +f 1145 1134 1146 +f 1156 1145 1146 +f 1155 1145 1156 +f 1301 1163 1302 +f 1302 1163 1164 +f 1154 1155 1163 +f 1163 1155 1164 +f 1156 1166 1155 +f 1155 1166 1164 +f 1312 1301 1313 +f 1313 1301 1302 +f 1302 1165 1175 +f 1166 1165 1164 +f 1302 1164 1165 +f 1165 1166 1175 +f 1313 1302 1314 +f 1314 1302 1175 +f 1157 1146 1147 +f 1156 1146 1157 +f 1146 1135 1147 +f 1147 1135 1136 +f 1147 1136 1148 +f 1148 1136 1137 +f 1158 1147 1148 +f 1157 1147 1158 +f 1148 1137 1149 +f 1149 1137 1138 +f 1159 1148 1149 +f 1158 1148 1159 +f 1150 1138 1139 +f 1149 1138 1150 +f 1160 1149 1150 +f 1159 1149 1160 +f 1166 1167 1175 +f 1167 1156 1157 +f 1166 1156 1167 +f 1167 1157 1168 +f 1168 1157 1158 +f 1314 1175 1315 +f 1175 1167 1176 +f 1315 1175 1176 +f 1315 1176 1177 +f 1167 1178 1176 +f 1178 1177 1176 +f 1168 1178 1167 +f 1179 1168 1169 +f 1168 1158 1169 +f 1178 1168 1179 +f 1169 1158 1159 +f 1170 1159 1160 +f 1180 1169 1170 +f 1179 1169 1180 +f 1169 1159 1170 +f 462 463 469 +f 643 634 644 +f 644 634 469 +f 634 462 469 +f 650 643 651 +f 651 643 644 +f 644 469 470 +f 471 470 469 +f 464 471 463 +f 463 471 469 +f 470 471 476 +f 651 644 652 +f 652 644 476 +f 644 470 476 +f 664 657 665 +f 665 657 658 +f 658 650 651 +f 657 650 658 +f 666 658 659 +f 665 658 666 +f 658 651 659 +f 659 651 652 +f 472 465 473 +f 472 464 465 +f 471 464 472 +f 473 465 466 +f 478 477 476 +f 472 478 471 +f 652 476 477 +f 471 478 476 +f 479 472 473 +f 478 472 479 +f 652 477 483 +f 477 478 483 +f 659 652 660 +f 660 652 483 +f 666 659 667 +f 667 659 660 +f 479 485 478 +f 660 483 484 +f 478 485 483 +f 485 484 483 +f 660 484 490 +f 667 660 668 +f 484 485 490 +f 668 660 490 +f 479 473 480 +f 480 473 474 +f 474 466 467 +f 473 466 474 +f 481 474 475 +f 480 474 481 +f 474 467 475 +f 475 467 468 +f 485 479 486 +f 486 479 480 +f 486 480 487 +f 487 480 481 +f 668 490 491 +f 485 492 490 +f 492 491 490 +f 486 492 485 +f 492 486 493 +f 493 486 487 +f 295 296 298 +f 475 468 298 +f 298 468 295 +f 482 475 298 +f 481 475 482 +f 298 296 299 +f 299 296 297 +f 304 303 298 +f 299 304 298 +f 482 298 303 +f 494 487 488 +f 493 487 494 +f 487 481 488 +f 488 481 482 +f 482 303 305 +f 303 304 305 +f 489 482 305 +f 488 482 489 +f 494 488 495 +f 495 488 489 +f 671 664 665 +f 670 664 671 +f 672 665 666 +f 671 665 672 +f 872 670 677 +f 871 670 872 +f 670 671 677 +f 672 679 671 +f 671 679 677 +f 679 678 677 +f 872 677 678 +f 679 672 680 +f 680 672 673 +f 672 666 673 +f 673 666 667 +f 673 667 674 +f 674 667 668 +f 680 673 681 +f 681 673 674 +f 882 871 872 +f 881 871 882 +f 872 678 684 +f 678 679 684 +f 883 872 684 +f 882 872 883 +f 892 882 883 +f 891 882 892 +f 891 881 882 +f 890 881 891 +f 680 686 679 +f 679 686 684 +f 883 684 685 +f 686 685 684 +f 883 685 691 +f 685 686 691 +f 892 883 893 +f 893 883 691 +f 687 680 681 +f 686 680 687 +f 893 691 692 +f 686 693 691 +f 693 692 691 +f 687 693 686 +f 491 492 496 +f 674 668 675 +f 675 668 496 +f 668 491 496 +f 681 674 682 +f 682 674 675 +f 498 497 496 +f 492 498 496 +f 493 498 492 +f 675 496 497 +f 675 497 501 +f 683 675 501 +f 682 675 683 +f 497 498 501 +f 498 493 499 +f 499 493 494 +f 499 503 498 +f 683 501 502 +f 498 503 501 +f 503 502 501 +f 500 494 495 +f 499 494 500 +f 504 499 500 +f 503 499 504 +f 687 681 688 +f 688 681 682 +f 693 687 694 +f 694 687 688 +f 694 688 695 +f 695 688 689 +f 689 682 683 +f 688 682 689 +f 502 503 505 +f 683 502 505 +f 690 683 505 +f 689 683 690 +f 690 505 506 +f 504 507 503 +f 507 506 505 +f 503 507 505 +f 695 689 696 +f 696 689 690 +f 696 690 697 +f 697 690 508 +f 690 506 508 +f 506 507 508 +f 909 899 900 +f 908 899 909 +f 900 890 891 +f 899 890 900 +f 900 891 901 +f 910 900 901 +f 909 900 910 +f 901 891 892 +f 901 892 902 +f 902 892 893 +f 692 693 698 +f 893 692 698 +f 902 893 903 +f 903 893 698 +f 912 902 903 +f 911 902 912 +f 911 901 902 +f 910 901 911 +f 916 908 917 +f 918 909 910 +f 917 909 918 +f 917 908 909 +f 925 924 923 +f 916 925 923 +f 917 925 916 +f 1139 923 924 +f 925 917 926 +f 926 917 918 +f 926 918 927 +f 918 910 919 +f 919 910 911 +f 927 918 919 +f 920 911 912 +f 919 911 920 +f 927 919 928 +f 928 919 920 +f 694 700 693 +f 693 700 698 +f 700 699 698 +f 903 698 699 +f 912 903 913 +f 913 903 704 +f 903 699 704 +f 699 700 704 +f 701 694 695 +f 700 694 701 +f 700 706 704 +f 706 705 704 +f 701 706 700 +f 913 704 705 +f 701 695 702 +f 707 701 702 +f 706 701 707 +f 702 695 696 +f 703 696 697 +f 702 696 703 +f 708 702 703 +f 707 702 708 +f 928 920 929 +f 929 920 921 +f 921 912 913 +f 920 912 921 +f 705 706 709 +f 921 913 922 +f 922 913 709 +f 913 705 709 +f 929 921 930 +f 930 921 922 +f 707 711 706 +f 706 711 709 +f 922 709 710 +f 711 710 709 +f 712 707 708 +f 711 707 712 +f 930 922 931 +f 931 922 713 +f 922 710 713 +f 710 711 713 +f 715 714 713 +f 711 715 713 +f 712 715 711 +f 931 713 714 +f 1151 1139 932 +f 924 925 932 +f 1139 924 932 +f 1150 1139 1151 +f 1160 1150 1161 +f 1161 1150 1151 +f 934 933 932 +f 925 934 932 +f 1151 932 933 +f 926 934 925 +f 933 934 941 +f 1161 1151 1162 +f 1151 933 941 +f 1162 1151 941 +f 1180 1170 1181 +f 1181 1170 1171 +f 1170 1160 1171 +f 1171 1160 1161 +f 1172 1161 1162 +f 1171 1161 1172 +f 1182 1171 1172 +f 1181 1171 1182 +f 936 927 928 +f 935 927 936 +f 935 926 927 +f 934 926 935 +f 934 943 941 +f 943 942 941 +f 935 943 934 +f 1162 941 942 +f 943 935 944 +f 944 935 936 +f 942 943 949 +f 1172 1162 1173 +f 1162 942 949 +f 1173 1162 949 +f 1182 1172 1183 +f 1183 1172 1173 +f 943 944 949 +f 1174 949 950 +f 1173 949 1174 +f 949 944 950 +f 1174 950 951 +f 1183 1173 1184 +f 1184 1173 1174 +f 944 936 945 +f 936 928 937 +f 937 928 929 +f 945 936 937 +f 938 929 930 +f 945 937 946 +f 937 929 938 +f 946 937 938 +f 947 938 939 +f 946 938 947 +f 938 930 939 +f 939 930 931 +f 931 714 716 +f 714 715 716 +f 939 931 940 +f 940 931 716 +f 947 939 948 +f 948 939 940 +f 945 952 944 +f 944 952 950 +f 952 951 950 +f 952 945 953 +f 953 945 946 +f 1185 1174 956 +f 1174 951 956 +f 951 952 956 +f 1184 1174 1185 +f 1185 956 957 +f 958 957 956 +f 953 958 952 +f 952 958 956 +f 953 946 954 +f 954 946 947 +f 958 953 959 +f 959 953 954 +f 959 954 960 +f 960 954 955 +f 954 947 955 +f 955 947 948 diff --git a/data/meshes/conveyor.obj b/data/meshes/conveyor.obj new file mode 100644 index 0000000..a8fd1db --- /dev/null +++ b/data/meshes/conveyor.obj @@ -0,0 +1,76 @@ +# Blender 4.5.0 +# www.blender.org +o Cube +v 2.168610 1.000000 -8.647873 +v 2.168610 -1.000000 -8.647873 +v 2.076996 1.000000 7.657975 +v 2.076996 -1.000000 7.657975 +v -4.037379 1.000000 -13.208730 +v -4.037379 -1.000000 -13.208730 +v -4.037379 1.000000 13.208730 +v -4.037379 -1.000000 13.208730 +v 7.006480 -1.000000 16.726564 +v 7.006480 1.000000 16.726564 +v 6.719464 1.000000 9.863844 +v 6.719464 -1.000000 9.863844 +v 16.463598 -1.000000 12.302612 +v 16.463598 1.000000 12.302612 +v 10.010764 1.000000 7.959058 +v 10.010764 -1.000000 7.959058 +v 16.463598 -1.000000 -11.446518 +v 16.463598 1.000000 -11.446518 +v 9.855768 1.000000 -7.927011 +v 9.855768 -1.000000 -7.927011 +v 7.919923 -1.000000 -16.801933 +v 7.919923 1.000000 -16.801933 +v 6.476316 1.000000 -9.520320 +v 6.476316 -1.000000 -9.520320 +s 1 +f 5 3 1 +f 4 9 8 +f 7 6 8 +f 6 4 8 +f 1 4 2 +f 2 21 24 +f 3 10 11 +f 3 12 4 +f 8 10 7 +f 9 16 13 +f 15 18 19 +f 11 16 12 +f 10 15 11 +f 9 14 10 +f 20 21 17 +f 13 18 14 +f 16 17 13 +f 15 20 16 +f 19 24 20 +f 19 22 23 +f 17 22 18 +f 1 22 5 +f 2 23 1 +f 5 21 6 +f 5 7 3 +f 4 12 9 +f 7 5 6 +f 6 2 4 +f 1 3 4 +f 2 6 21 +f 3 7 10 +f 3 11 12 +f 8 9 10 +f 9 12 16 +f 15 14 18 +f 11 15 16 +f 10 14 15 +f 9 13 14 +f 20 24 21 +f 13 17 18 +f 16 20 17 +f 15 19 20 +f 19 23 24 +f 19 18 22 +f 17 21 22 +f 1 23 22 +f 2 24 23 +f 5 22 21 diff --git a/data/meshes/single_triangle.obj b/data/meshes/single_triangle.obj new file mode 100644 index 0000000..243b015 --- /dev/null +++ b/data/meshes/single_triangle.obj @@ -0,0 +1,4 @@ +v 1 0 1 +v 1 0 -1 +v -1 0 -1 +f 1 2 3 diff --git a/data/meshes/stairs.obj b/data/meshes/stairs.obj new file mode 100644 index 0000000..92b90ae --- /dev/null +++ b/data/meshes/stairs.obj @@ -0,0 +1,42 @@ +# Blender 4.1.1 +# www.blender.org +o Cube +v -1.423823 -0.087425 1.000000 +v -1.423823 -0.087425 -1.000000 +v 1.423823 -0.087425 1.000000 +v 1.423823 1.912575 1.000000 +v 1.423823 -0.087425 -1.000000 +v 1.423823 1.912575 -1.000000 +v 0.711911 1.912575 1.000000 +v -1.423823 0.412575 1.000000 +v 0.711911 1.537575 1.000000 +v 0.177978 1.537575 1.000000 +v 0.177978 1.162575 1.000000 +v -0.355956 1.162575 1.000000 +v -0.355956 0.787575 1.000000 +v -0.889889 0.787575 1.000000 +v -0.889889 0.412575 1.000000 +v -1.423823 0.412575 -1.000000 +v 0.711911 1.912575 -1.000000 +v -0.889889 0.412575 -1.000000 +v -0.889889 0.787575 -1.000000 +v -0.355956 0.787575 -1.000000 +v -0.355956 1.162575 -1.000000 +v 0.177978 1.162575 -1.000000 +v 0.177978 1.537575 -1.000000 +v 0.711911 1.537575 -1.000000 +s 0 +f 6 17 7 4 +f 5 6 4 3 +f 1 8 16 2 +f 2 5 3 1 +f 2 16 18 19 20 21 22 23 24 17 6 5 +f 7 17 24 9 +f 9 24 23 10 +f 10 23 22 11 +f 11 22 21 12 +f 12 21 20 13 +f 13 20 19 14 +f 14 19 18 15 +f 15 18 16 8 +f 3 4 7 9 10 11 12 13 14 15 8 1 diff --git a/data/meshes/test_map01.obj b/data/meshes/test_map01.obj new file mode 100644 index 0000000..69a6337 --- /dev/null +++ b/data/meshes/test_map01.obj @@ -0,0 +1,258 @@ +# Blender 4.1.1 +# www.blender.org +o Cube +v -20.000000 -1.000000 20.000000 +v -20.000000 0.000000 20.000000 +v -20.000000 -1.000000 -20.000000 +v -20.000000 0.000000 -20.000000 +v 20.000000 -1.000000 20.000000 +v 20.000000 0.000000 20.000000 +v 20.000000 -1.000000 -20.000000 +v 20.000000 0.000000 -20.000000 +s 0 +f 1 2 4 3 +f 3 4 8 7 +f 7 8 6 5 +f 5 6 2 1 +f 3 7 5 1 +f 8 4 2 6 +o Cube.001 +v -1.000000 0.500000 11.454407 +v -1.000000 2.500000 11.454407 +v -1.000000 0.500000 9.454407 +v -1.000000 2.500000 9.454407 +v 1.000000 0.500000 11.454407 +v 1.000000 2.500000 11.454407 +v 1.000000 0.500000 9.454407 +v 1.000000 2.500000 9.454407 +s 0 +f 9 10 12 11 +f 11 12 16 15 +f 15 16 14 13 +f 13 14 10 9 +f 11 15 13 9 +f 16 12 10 14 +o Cube.002 +v -9.640553 -0.538823 -5.348382 +v -9.761864 -0.053763 -5.348382 +v -9.640553 -0.538823 -9.348381 +v -9.761864 -0.053763 -9.348381 +v 9.761864 4.313619 -5.348382 +v 9.640553 4.798679 -5.348382 +v 9.761864 4.313619 -9.348381 +v 9.640553 4.798679 -9.348381 +s 0 +f 17 18 20 19 +f 19 20 24 23 +f 23 24 22 21 +f 21 22 18 17 +f 19 23 21 17 +f 24 20 18 22 +o Cylinder +v 0.000000 0.250000 -1.000000 +v 0.000000 0.250000 1.000000 +v 0.057403 0.238582 -1.000000 +v 0.057403 0.238582 1.000000 +v 0.106066 0.206066 -1.000000 +v 0.106066 0.206066 1.000000 +v 0.138582 0.157403 -1.000000 +v 0.138582 0.157402 1.000000 +v 0.150000 0.100000 -1.000000 +v 0.150000 0.100000 1.000000 +v 0.138582 0.042598 -1.000000 +v 0.138582 0.042597 1.000000 +v 0.106066 -0.006066 -1.000000 +v 0.106066 -0.006066 1.000000 +v 0.057403 -0.038582 -1.000000 +v 0.057403 -0.038582 1.000000 +v 0.000000 -0.050000 -1.000000 +v 0.000000 -0.050000 1.000000 +v -0.057403 -0.038582 -1.000000 +v -0.057403 -0.038582 1.000000 +v -0.106066 -0.006066 -1.000000 +v -0.106066 -0.006066 1.000000 +v -0.138582 0.042598 -1.000000 +v -0.138582 0.042597 1.000000 +v -0.150000 0.100000 -1.000000 +v -0.150000 0.100000 1.000000 +v -0.138582 0.157403 -1.000000 +v -0.138582 0.157402 1.000000 +v -0.106066 0.206066 -1.000000 +v -0.106066 0.206066 1.000000 +v -0.057403 0.238582 -1.000000 +v -0.057403 0.238582 1.000000 +s 0 +f 25 26 28 27 +f 27 28 30 29 +f 29 30 32 31 +f 31 32 34 33 +f 33 34 36 35 +f 35 36 38 37 +f 37 38 40 39 +f 39 40 42 41 +f 41 42 44 43 +f 43 44 46 45 +f 45 46 48 47 +f 47 48 50 49 +f 49 50 52 51 +f 51 52 54 53 +f 28 26 56 54 52 50 48 46 44 42 40 38 36 34 32 30 +f 53 54 56 55 +f 55 56 26 25 +f 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 +o Cylinder.001 +v 1.916919 0.250000 -1.000000 +v 1.916919 0.250000 1.000000 +v 1.974321 0.238582 -1.000000 +v 1.974321 0.238582 1.000000 +v 2.022985 0.206066 -1.000000 +v 2.022985 0.206066 1.000000 +v 2.055501 0.157403 -1.000000 +v 2.055501 0.157402 1.000000 +v 2.066919 0.100000 -1.000000 +v 2.066919 0.100000 1.000000 +v 2.055501 0.042598 -1.000000 +v 2.055501 0.042597 1.000000 +v 2.022985 -0.006066 -1.000000 +v 2.022985 -0.006066 1.000000 +v 1.974321 -0.038582 -1.000000 +v 1.974321 -0.038582 1.000000 +v 1.916919 -0.050000 -1.000000 +v 1.916919 -0.050000 1.000000 +v 1.859516 -0.038582 -1.000000 +v 1.859516 -0.038582 1.000000 +v 1.810853 -0.006066 -1.000000 +v 1.810853 -0.006066 1.000000 +v 1.778337 0.042598 -1.000000 +v 1.778337 0.042597 1.000000 +v 1.766919 0.100000 -1.000000 +v 1.766919 0.100000 1.000000 +v 1.778337 0.157403 -1.000000 +v 1.778337 0.157402 1.000000 +v 1.810853 0.206066 -1.000000 +v 1.810853 0.206066 1.000000 +v 1.859516 0.238582 -1.000000 +v 1.859516 0.238582 1.000000 +s 0 +f 57 58 60 59 +f 59 60 62 61 +f 61 62 64 63 +f 63 64 66 65 +f 65 66 68 67 +f 67 68 70 69 +f 69 70 72 71 +f 71 72 74 73 +f 73 74 76 75 +f 75 76 78 77 +f 77 78 80 79 +f 79 80 82 81 +f 81 82 84 83 +f 83 84 86 85 +f 60 58 88 86 84 82 80 78 76 74 72 70 68 66 64 62 +f 85 86 88 87 +f 87 88 58 57 +f 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 +o Cylinder.002 +v 2.280946 0.250000 -1.000000 +v 2.280946 0.250000 1.000000 +v 2.338348 0.238582 -1.000000 +v 2.338348 0.238582 1.000000 +v 2.387012 0.206066 -1.000000 +v 2.387012 0.206066 1.000000 +v 2.419528 0.157403 -1.000000 +v 2.419528 0.157402 1.000000 +v 2.430946 0.100000 -1.000000 +v 2.430946 0.100000 1.000000 +v 2.419528 0.042598 -1.000000 +v 2.419528 0.042597 1.000000 +v 2.387012 -0.006066 -1.000000 +v 2.387012 -0.006066 1.000000 +v 2.338348 -0.038582 -1.000000 +v 2.338348 -0.038582 1.000000 +v 2.280946 -0.050000 -1.000000 +v 2.280946 -0.050000 1.000000 +v 2.223543 -0.038582 -1.000000 +v 2.223543 -0.038582 1.000000 +v 2.174880 -0.006066 -1.000000 +v 2.174880 -0.006066 1.000000 +v 2.142364 0.042598 -1.000000 +v 2.142364 0.042597 1.000000 +v 2.130946 0.100000 -1.000000 +v 2.130946 0.100000 1.000000 +v 2.142364 0.157403 -1.000000 +v 2.142364 0.157402 1.000000 +v 2.174880 0.206066 -1.000000 +v 2.174880 0.206066 1.000000 +v 2.223543 0.238582 -1.000000 +v 2.223543 0.238582 1.000000 +s 0 +f 89 90 92 91 +f 91 92 94 93 +f 93 94 96 95 +f 95 96 98 97 +f 97 98 100 99 +f 99 100 102 101 +f 101 102 104 103 +f 103 104 106 105 +f 105 106 108 107 +f 107 108 110 109 +f 109 110 112 111 +f 111 112 114 113 +f 113 114 116 115 +f 115 116 118 117 +f 92 90 120 118 116 114 112 110 108 106 104 102 100 98 96 94 +f 117 118 120 119 +f 119 120 90 89 +f 89 91 93 95 97 99 101 103 105 107 109 111 113 115 117 119 +o Cylinder.003 +v 2.636716 0.250000 -1.000000 +v 2.636716 0.250000 1.000000 +v 2.694119 0.238582 -1.000000 +v 2.694119 0.238582 1.000000 +v 2.742782 0.206066 -1.000000 +v 2.742782 0.206066 1.000000 +v 2.775298 0.157403 -1.000000 +v 2.775298 0.157402 1.000000 +v 2.786716 0.100000 -1.000000 +v 2.786716 0.100000 1.000000 +v 2.775298 0.042598 -1.000000 +v 2.775298 0.042597 1.000000 +v 2.742782 -0.006066 -1.000000 +v 2.742782 -0.006066 1.000000 +v 2.694119 -0.038582 -1.000000 +v 2.694119 -0.038582 1.000000 +v 2.636716 -0.050000 -1.000000 +v 2.636716 -0.050000 1.000000 +v 2.579314 -0.038582 -1.000000 +v 2.579314 -0.038582 1.000000 +v 2.530650 -0.006066 -1.000000 +v 2.530650 -0.006066 1.000000 +v 2.498134 0.042598 -1.000000 +v 2.498134 0.042597 1.000000 +v 2.486716 0.100000 -1.000000 +v 2.486716 0.100000 1.000000 +v 2.498134 0.157403 -1.000000 +v 2.498134 0.157402 1.000000 +v 2.530650 0.206066 -1.000000 +v 2.530650 0.206066 1.000000 +v 2.579314 0.238582 -1.000000 +v 2.579314 0.238582 1.000000 +s 0 +f 121 122 124 123 +f 123 124 126 125 +f 125 126 128 127 +f 127 128 130 129 +f 129 130 132 131 +f 131 132 134 133 +f 133 134 136 135 +f 135 136 138 137 +f 137 138 140 139 +f 139 140 142 141 +f 141 142 144 143 +f 143 144 146 145 +f 145 146 148 147 +f 147 148 150 149 +f 124 122 152 150 148 146 144 142 140 138 136 134 132 130 128 126 +f 149 150 152 151 +f 151 152 122 121 +f 121 123 125 127 129 131 133 135 137 139 141 143 145 147 149 151 diff --git a/data/meshes/voxel_mesh_01.obj b/data/meshes/voxel_mesh_01.obj new file mode 100644 index 0000000..6acad31 --- /dev/null +++ b/data/meshes/voxel_mesh_01.obj @@ -0,0 +1,5323 @@ +# voxel +v 3200.000000000 0.000000000 387.504760742 +v 3146.683593750 0.000000000 400.000000000 +v 3200.000000000 53.316284180 400.000000000 +v 2800.000000000 0.000000000 494.519744873 +v 2780.520751953 0.000000000 500.000000000 +v 2900.000000000 0.000000000 464.846435547 +v 3000.000000000 0.000000000 437.508789062 +v 3100.000000000 0.000000000 410.940826416 +v 3200.000000000 100.000000000 410.940826416 +v 3200.000000000 200.000000000 437.508789062 +v 3200.000000000 300.000000000 464.050201416 +v 3200.000000000 400.000000000 489.052185059 +v 3200.000000000 445.178405762 500.000000000 +v 0.000000000 0.000000000 527.351501465 +v 0.000000000 100.000000000 567.190185547 +v 77.496421814 0.000000000 600.000000000 +v 2500.000000000 0.000000000 579.691162109 +v 2425.711181641 0.000000000 600.000000000 +v 2600.000000000 0.000000000 551.557250977 +v 2700.000000000 0.000000000 522.653686523 +v 0.000000000 166.676086426 600.000000000 +v 3200.000000000 500.000000000 513.284545898 +v 3200.000000000 600.000000000 535.924377441 +v 3200.000000000 700.000000000 557.821044922 +v 3200.000000000 800.000000000 578.894958496 +v 3200.000000000 896.384704590 600.000000000 +v 100.000000000 0.000000000 621.095825195 +v 195.284301758 0.000000000 700.000000000 +v 2000.000000000 0.000000000 691.403991699 +v 1942.062377930 0.000000000 700.000000000 +v 2100.000000000 0.000000000 675.001403809 +v 2200.000000000 0.000000000 656.263183594 +v 2300.000000000 0.000000000 632.800537109 +v 2400.000000000 0.000000000 607.028869629 +v 0.000000000 200.000000000 616.397949219 +v 0.000000000 300.000000000 660.164794922 +v 0.000000000 389.497314453 700.000000000 +v 3200.000000000 900.000000000 600.791625977 +v 3200.000000000 1000.000000000 621.095825195 +v 3200.000000000 1100.000000000 641.399963379 +v 3200.000000000 1200.000000000 660.164794922 +v 3200.000000000 1300.000000000 678.903015137 +v 3200.000000000 1396.464965820 700.000000000 +v 200.000000000 0.000000000 703.905029297 +v 300.000000000 0.000000000 775.009521484 +v 358.157257080 0.000000000 800.000000000 +v 1300.000000000 0.000000000 794.544006348 +v 1263.226074219 0.000000000 800.000000000 +v 1400.000000000 0.000000000 779.680786133 +v 1500.000000000 0.000000000 764.844116211 +v 1600.000000000 0.000000000 750.007507324 +v 1700.000000000 0.000000000 735.940551758 +v 1800.000000000 0.000000000 721.103881836 +v 1900.000000000 0.000000000 706.240661621 +v 0.000000000 400.000000000 704.674743652 +v 0.000000000 500.000000000 751.573425293 +v 0.000000000 600.000000000 799.215270996 +v 0.000000000 601.732055664 800.000000000 +v 3200.000000000 1400.000000000 700.773132324 +v 3200.000000000 1500.000000000 722.643249512 +v 3200.000000000 1600.000000000 743.743713379 +v 3200.000000000 1700.000000000 765.613830566 +v 3200.000000000 1800.000000000 787.510498047 +v 3200.000000000 1857.107543945 800.000000000 +v 400.000000000 0.000000000 817.979980469 +v 500.000000000 0.000000000 841.416137695 +v 600.000000000 0.000000000 851.554992676 +v 700.000000000 0.000000000 854.686828613 +v 800.000000000 0.000000000 853.917114258 +v 900.000000000 0.000000000 847.653381348 +v 1000.000000000 0.000000000 837.487976074 +v 1100.000000000 0.000000000 825.783264160 +v 1200.000000000 0.000000000 809.380615234 +v 0.000000000 700.000000000 844.521545410 +v 0.000000000 800.000000000 894.525512695 +v 0.000000000 812.083312988 900.000000000 +v 3200.000000000 1900.000000000 809.380615234 +v 3200.000000000 2000.000000000 832.020446777 +v 3200.000000000 2100.000000000 854.686828613 +v 3200.000000000 2200.000000000 877.353210449 +v 3200.000000000 2296.632080078 900.000000000 +v 0.000000000 900.000000000 939.831726074 +v 0.000000000 1000.000000000 994.533569336 +v 0.000000000 1012.065490723 1000.000000000 +v 3200.000000000 2300.000000000 900.789245605 +v 3200.000000000 2400.000000000 924.225341797 +v 3200.000000000 2500.000000000 947.661376953 +v 3200.000000000 2600.000000000 971.097534180 +v 3200.000000000 2700.000000000 995.303222656 +v 3200.000000000 2720.040527344 1000.000000000 +v 0.000000000 1100.000000000 1039.839843750 +v 0.000000000 1200.000000000 1078.112548828 +v 0.000000000 1282.382812500 1100.000000000 +v 3200.000000000 2800.000000000 1018.739440918 +v 3200.000000000 2900.000000000 1046.103515625 +v 3200.000000000 3000.000000000 1072.645019531 +v 3200.000000000 3100.000000000 1099.213012695 +v 3200.000000000 3102.962158203 1100.000000000 +v 0.000000000 1300.000000000 1104.680541992 +v 0.000000000 1400.000000000 1130.478759766 +v 0.000000000 1500.000000000 1155.480712891 +v 0.000000000 1600.000000000 1182.022216797 +v 0.000000000 1671.905517578 1200.000000000 +v 3022.242187500 3200.000000000 1200.000000000 +v 3100.000000000 3200.000000000 1167.185546875 +v 3200.000000000 3200.000000000 1125.780883789 +v 0.000000000 1700.000000000 1207.024169922 +v 0.000000000 1800.000000000 1233.592163086 +v 0.000000000 1900.000000000 1259.363891602 +v 0.000000000 2000.000000000 1285.162109375 +v 0.000000000 2057.574218750 1300.000000000 +v 2784.637695312 3200.000000000 1300.000000000 +v 2800.000000000 3200.000000000 1293.761596680 +v 2900.000000000 3200.000000000 1250.791015625 +v 3000.000000000 3200.000000000 1209.386352539 +v 0.000000000 2100.000000000 1310.933837891 +v 0.000000000 2200.000000000 1336.705566406 +v 0.000000000 2300.000000000 1362.503906250 +v 0.000000000 2400.000000000 1389.071777344 +v 0.000000000 2443.709228516 1400.000000000 +v 2529.176025391 3200.000000000 1400.000000000 +v 2600.000000000 3200.000000000 1373.438964844 +v 2700.000000000 3200.000000000 1334.369995117 +v 0.000000000 2500.000000000 1414.073852539 +v 0.000000000 2600.000000000 1439.845581055 +v 0.000000000 2700.000000000 1465.617309570 +v 0.000000000 2800.000000000 1491.415527344 +v 0.000000000 2836.629394531 1500.000000000 +v 2221.631347656 3200.000000000 1500.000000000 +v 2300.000000000 3200.000000000 1477.348632812 +v 2400.000000000 3200.000000000 1444.543334961 +v 2500.000000000 3200.000000000 1410.941894531 +v 0.000000000 2900.000000000 1514.851562500 +v 0.000000000 3000.000000000 1537.491455078 +v 0.000000000 3100.000000000 1559.388061523 +v 0.000000000 3200.000000000 1578.896118164 +v 100.000000000 3200.000000000 1578.126342773 +v 200.000000000 3200.000000000 1577.356689453 +v 300.000000000 3200.000000000 1578.896118164 +v 400.000000000 3200.000000000 1582.824218750 +v 500.000000000 3200.000000000 1587.495483398 +v 600.000000000 3200.000000000 1593.759277344 +v 700.000000000 3200.000000000 1599.996459961 +v 700.050354004 3200.000000000 1600.000000000 +v 1784.234252930 3200.000000000 1600.000000000 +v 1800.000000000 3200.000000000 1597.660888672 +v 1900.000000000 3200.000000000 1578.896118164 +v 2000.000000000 3200.000000000 1557.822143555 +v 2100.000000000 3200.000000000 1533.589843750 +v 2200.000000000 3200.000000000 1506.252197266 +v 800.000000000 3200.000000000 1607.030151367 +v 900.000000000 3200.000000000 1614.063476562 +v 1000.000000000 3200.000000000 1621.866577148 +v 1100.000000000 3200.000000000 1628.130371094 +v 1200.000000000 3200.000000000 1632.031982422 +v 1300.000000000 3200.000000000 1634.367797852 +v 1400.000000000 3200.000000000 1632.801635742 +v 1500.000000000 3200.000000000 1630.466064453 +v 1600.000000000 3200.000000000 1623.432495117 +v 1700.000000000 3200.000000000 1612.497558594 +v 2800.000000000 500.000000000 617.194213867 +v 2700.000000000 400.000000000 628.129272461 +v 2800.000000000 404.309448242 600.000000000 +v 2700.000000000 400.000000000 628.129272461 +v 2800.000000000 404.309448242 600.000000000 +v 2500.000000000 542.119689941 700.000000000 +v 2500.000000000 500.000000000 693.739685059 +v 2472.380615234 500.000000000 700.000000000 +v 2535.501464844 600.000000000 700.000000000 +v 2600.000000000 600.000000000 684.370544434 +v 2500.000000000 500.000000000 693.739685059 +v 2600.000000000 500.000000000 669.533874512 +v 2500.000000000 500.000000000 693.739685059 +v 2700.000000000 600.000000000 659.368530273 +v 2600.000000000 500.000000000 669.533874512 +v 2600.000000000 500.000000000 669.533874512 +v 2800.000000000 600.000000000 634.366516113 +v 2900.000000000 600.000000000 608.594787598 +v 2600.000000000 699.978149414 700.000000000 +v 2600.014160156 700.000000000 700.000000000 +v 2700.000000000 700.000000000 675.771118164 +v 2800.000000000 700.000000000 651.565368652 +v 2900.000000000 700.000000000 627.333007812 +v 3000.000000000 700.000000000 603.127258301 +v 2666.718994141 800.000000000 700.000000000 +v 2700.000000000 800.000000000 692.200256348 +v 2800.000000000 800.000000000 667.967956543 +v 2900.000000000 800.000000000 644.531860352 +v 3000.000000000 800.000000000 621.865478516 +v 2700.000000000 849.977905273 700.000000000 +v 2733.310302734 900.000000000 700.000000000 +v 2800.000000000 900.000000000 684.370544434 +v 2900.000000000 900.000000000 661.730712891 +v 3000.000000000 900.000000000 639.834045410 +v 3100.000000000 900.000000000 620.299560547 +v 2700.000000000 100.000000000 553.919433594 +v 2800.000000000 990.874938965 700.000000000 +v 2806.923828125 1000.000000000 700.000000000 +v 2900.000000000 1000.000000000 678.903015137 +v 3000.000000000 1000.000000000 658.598815918 +v 3100.000000000 1000.000000000 639.064331055 +v 3000.000000000 231.405731201 500.000000000 +v 2888.933105469 1100.000000000 700.000000000 +v 2900.000000000 1100.000000000 697.667785645 +v 3000.000000000 1100.000000000 676.567382812 +v 3100.000000000 1100.000000000 657.802612305 +v 2800.000000000 100.000000000 524.219604492 +v 2900.000000000 1113.581298828 700.000000000 +v 2973.088867188 1200.000000000 700.000000000 +v 3000.000000000 1200.000000000 694.535888672 +v 3100.000000000 1200.000000000 675.771118164 +v 3066.652832031 300.000000000 500.000000000 +v 3000.000000000 1226.911254883 700.000000000 +v 3082.589355469 1300.000000000 700.000000000 +v 3100.000000000 1300.000000000 696.871582031 +v 2600.000000000 152.651855469 600.000000000 +v 3100.000000000 1314.304565430 700.000000000 +v 2646.152099609 200.000000000 600.000000000 +v 200.000000000 100.000000000 746.105895996 +v 2700.000000000 200.000000000 583.592773438 +v 300.000000000 60.356765747 800.000000000 +v 2800.000000000 200.000000000 551.557250977 +v 276.654052734 100.000000000 800.000000000 +v 2900.000000000 200.000000000 521.883972168 +v 2700.000000000 267.708099365 600.000000000 +v 2725.681640625 300.000000000 600.000000000 +v 1300.000000000 26.871337891 800.000000000 +v 2800.000000000 300.000000000 577.355529785 +v 1400.000000000 99.943260193 800.000000000 +v 1400.086791992 100.000000000 800.000000000 +v 1500.000000000 100.000000000 786.714294434 +v 2900.000000000 300.000000000 547.655700684 +v 1600.000000000 100.000000000 772.647338867 +v 3000.000000000 300.000000000 518.752075195 +v 1700.000000000 100.000000000 758.606872559 +v 2797.321044922 400.000000000 600.000000000 +v 1800.000000000 100.000000000 746.105895996 +v 2800.000000000 400.000000000 599.225646973 +v 1900.000000000 100.000000000 731.242675781 +v 2800.000000000 300.000000000 577.355529785 +v 2000.000000000 100.000000000 715.636352539 +v 2100.000000000 100.000000000 700.003417969 +v 100.000000000 200.000000000 707.036926270 +v 200.000000000 200.000000000 787.510498047 +v 219.738510132 200.000000000 800.000000000 +v 1500.000000000 173.938842773 800.000000000 +v 1533.289306641 200.000000000 800.000000000 +v 1600.000000000 200.000000000 790.615844727 +v 1700.000000000 200.000000000 777.345153809 +v 1800.000000000 200.000000000 764.844116211 +v 1900.000000000 200.000000000 752.343139648 +v 2000.000000000 200.000000000 737.506469727 +v 2100.000000000 200.000000000 721.873596191 +v 2200.000000000 200.000000000 704.674743652 +v 100.000000000 300.000000000 749.211242676 +v 200.000000000 231.350189209 800.000000000 +v 164.998840332 300.000000000 800.000000000 +v 1600.000000000 270.572174072 800.000000000 +v 1631.302246094 300.000000000 800.000000000 +v 1700.000000000 300.000000000 791.412109375 +v 1800.000000000 300.000000000 779.680786133 +v 1900.000000000 300.000000000 767.179809570 +v 2000.000000000 300.000000000 753.909057617 +v 2100.000000000 300.000000000 739.842102051 +v 2200.000000000 300.000000000 724.209228516 +v 2300.000000000 300.000000000 704.674743652 +v 2725.681640625 300.000000000 600.000000000 +v 100.000000000 400.000000000 795.313659668 +v 106.451103210 400.000000000 800.000000000 +v 1700.000000000 357.882873535 800.000000000 +v 1753.386718750 400.000000000 800.000000000 +v 1800.000000000 400.000000000 794.544006348 +v 1900.000000000 400.000000000 782.042968750 +v 2000.000000000 400.000000000 768.745727539 +v 2100.000000000 400.000000000 755.475036621 +v 2000.000000000 300.000000000 753.909057617 +v 2000.000000000 400.000000000 768.745727539 +v 2000.000000000 300.000000000 753.909057617 +v 2100.000000000 300.000000000 739.842102051 +v 2200.000000000 400.000000000 739.072387695 +v 2100.000000000 300.000000000 739.842102051 +v 2100.000000000 300.000000000 739.842102051 +v 2200.000000000 300.000000000 724.209228516 +v 2300.000000000 400.000000000 721.873596191 +v 2200.000000000 300.000000000 724.209228516 +v 2200.000000000 300.000000000 724.209228516 +v 2300.000000000 300.000000000 704.674743652 +v 2400.000000000 400.000000000 700.773132324 +v 2323.023681641 300.000000000 700.000000000 +v 2300.000000000 300.000000000 704.674743652 +v 2300.000000000 300.000000000 704.674743652 +v 2300.000000000 300.000000000 704.674743652 +v 100.000000000 410.905944824 800.000000000 +v 2800.000000000 300.000000000 577.355529785 +v 55.848365784 500.000000000 800.000000000 +v 1800.000000000 441.113098145 800.000000000 +v 1800.000000000 400.000000000 794.544006348 +v 1753.386718750 400.000000000 800.000000000 +v 1876.875854492 500.000000000 800.000000000 +v 1900.000000000 500.000000000 797.649353027 +v 1800.000000000 400.000000000 794.544006348 +v 1900.000000000 400.000000000 782.042968750 +v 1800.000000000 400.000000000 794.544006348 +v 2000.000000000 500.000000000 784.378601074 +v 1900.000000000 400.000000000 782.042968750 +v 1900.000000000 400.000000000 782.042968750 +v 2000.000000000 400.000000000 768.745727539 +v 2100.000000000 500.000000000 770.311645508 +v 2000.000000000 400.000000000 768.745727539 +v 2000.000000000 400.000000000 768.745727539 +v 2200.000000000 500.000000000 753.909057617 +v 2300.000000000 500.000000000 735.940551758 +v 2400.000000000 500.000000000 716.406066895 +v 2900.000000000 400.000000000 570.322082520 +v 0.938609600 600.000000000 800.000000000 +v 1900.000000000 518.803710938 800.000000000 +v 1981.196166992 600.000000000 800.000000000 +v 2000.000000000 600.000000000 797.649353027 +v 2100.000000000 600.000000000 784.378601074 +v 2200.000000000 600.000000000 768.745727539 +v 2300.000000000 600.000000000 750.777160645 +v 2200.000000000 500.000000000 753.909057617 +v 2200.000000000 600.000000000 768.745727539 +v 2200.000000000 500.000000000 753.909057617 +v 2300.000000000 500.000000000 735.940551758 +v 2400.000000000 600.000000000 730.473022461 +v 2300.000000000 500.000000000 735.940551758 +v 2300.000000000 500.000000000 735.940551758 +v 2400.000000000 500.000000000 716.406066895 +v 2500.000000000 600.000000000 708.602844238 +v 2472.380615234 500.000000000 700.000000000 +v 2400.000000000 500.000000000 716.406066895 +v 2400.000000000 500.000000000 716.406066895 +v 2400.000000000 500.000000000 716.406066895 +v 2800.000000000 400.000000000 599.225646973 +v 2000.000000000 615.036560059 800.000000000 +v 2089.522949219 700.000000000 800.000000000 +v 2100.000000000 700.000000000 798.445556641 +v 2000.000000000 615.036560059 800.000000000 +v 2000.000000000 600.000000000 797.649353027 +v 2000.000000000 615.036560059 800.000000000 +v 2100.000000000 600.000000000 784.378601074 +v 2000.000000000 600.000000000 797.649353027 +v 2200.000000000 700.000000000 782.812683105 +v 2100.000000000 600.000000000 784.378601074 +v 2100.000000000 600.000000000 784.378601074 +v 2200.000000000 600.000000000 768.745727539 +v 2300.000000000 700.000000000 765.613830566 +v 2200.000000000 600.000000000 768.745727539 +v 2200.000000000 600.000000000 768.745727539 +v 2400.000000000 700.000000000 746.105895996 +v 2500.000000000 700.000000000 724.209228516 +v 2600.000000000 700.000000000 700.003417969 +v 2100.000000000 709.476806641 800.000000000 +v 2186.332519531 800.000000000 800.000000000 +v 2200.000000000 800.000000000 797.649353027 +v 2300.000000000 800.000000000 779.680786133 +v 2400.000000000 800.000000000 760.146301270 +v 2500.000000000 800.000000000 739.072387695 +v 2600.000000000 800.000000000 715.636352539 +v 2200.000000000 812.526916504 800.000000000 +v 2287.473144531 900.000000000 800.000000000 +v 2300.000000000 900.000000000 797.649353027 +v 2400.000000000 900.000000000 776.575439453 +v 2500.000000000 900.000000000 753.909057617 +v 2600.000000000 900.000000000 731.242675781 +v 2700.000000000 900.000000000 707.806640625 +v 2300.000000000 912.526916504 800.000000000 +v 2375.052734375 1000.000000000 800.000000000 +v 2400.000000000 1000.000000000 794.544006348 +v 2500.000000000 1000.000000000 771.877624512 +v 2600.000000000 1000.000000000 748.441528320 +v 2700.000000000 1000.000000000 725.005432129 +v 2800.000000000 1000.000000000 701.569396973 +v 2400.000000000 1027.968139648 800.000000000 +v 2459.958496094 1100.000000000 800.000000000 +v 2500.000000000 1100.000000000 790.615844727 +v 2600.000000000 1100.000000000 767.976013184 +v 2700.000000000 1100.000000000 742.973999023 +v 2800.000000000 1100.000000000 718.741699219 +v 2500.000000000 1142.856445312 800.000000000 +v 2548.501464844 1200.000000000 800.000000000 +v 2600.000000000 1200.000000000 786.714294434 +v 2700.000000000 1200.000000000 761.712219238 +v 2800.000000000 1200.000000000 736.710205078 +v 2900.000000000 1200.000000000 714.840087891 +v 2600.000000000 1260.748168945 800.000000000 +v 2632.343505859 1300.000000000 800.000000000 +v 2700.000000000 1300.000000000 782.042968750 +v 2800.000000000 1300.000000000 756.244689941 +v 2900.000000000 1300.000000000 733.604858398 +v 3000.000000000 1300.000000000 714.840087891 +v 2700.000000000 1379.316162109 800.000000000 +v 2700.000000000 1300.000000000 782.042968750 +v 2632.343505859 1300.000000000 800.000000000 +v 2717.625732422 1400.000000000 800.000000000 +v 2800.000000000 1400.000000000 778.114868164 +v 2700.000000000 1379.316162109 800.000000000 +v 2800.000000000 1400.000000000 778.114868164 +v 2700.000000000 1300.000000000 782.042968750 +v 2800.000000000 1400.000000000 778.114868164 +v 2800.000000000 1300.000000000 756.244689941 +v 2700.000000000 1300.000000000 782.042968750 +v 2900.000000000 1400.000000000 758.606872559 +v 2800.000000000 1300.000000000 756.244689941 +v 2800.000000000 1400.000000000 778.114868164 +v 2800.000000000 1300.000000000 756.244689941 +v 2900.000000000 1300.000000000 733.604858398 +v 3000.000000000 1400.000000000 738.276184082 +v 2900.000000000 1300.000000000 733.604858398 +v 2900.000000000 1300.000000000 733.604858398 +v 3000.000000000 1300.000000000 714.840087891 +v 3100.000000000 1400.000000000 718.741699219 +v 3000.000000000 1300.000000000 714.840087891 +v 3100.000000000 1400.000000000 718.741699219 +v 3000.000000000 400.000000000 542.188171387 +v 2800.000000000 1479.977172852 800.000000000 +v 2825.022216797 1500.000000000 800.000000000 +v 2900.000000000 1500.000000000 783.582397461 +v 2900.000000000 1400.000000000 758.606872559 +v 3000.000000000 1500.000000000 761.712219238 +v 2900.000000000 1400.000000000 758.606872559 +v 2900.000000000 1400.000000000 758.606872559 +v 3000.000000000 1400.000000000 738.276184082 +v 3100.000000000 1500.000000000 741.408081055 +v 3000.000000000 1400.000000000 738.276184082 +v 3100.000000000 1500.000000000 741.408081055 +v 3100.000000000 1400.000000000 718.741699219 +v 3100.000000000 400.000000000 515.620178223 +v 3100.000000000 1500.000000000 741.408081055 +v 2900.000000000 1565.665161133 800.000000000 +v 2937.917236328 1600.000000000 800.000000000 +v 3000.000000000 1600.000000000 785.944580078 +v 3100.000000000 1600.000000000 764.074462891 +v 2800.000000000 404.309448242 600.000000000 +v 3100.000000000 1500.000000000 741.408081055 +v 3100.000000000 1600.000000000 764.074462891 +v 3100.000000000 1500.000000000 741.408081055 +v 3200.000000000 1500.000000000 722.643249512 +v 3000.000000000 1658.066406250 800.000000000 +v 3044.833984375 1700.000000000 800.000000000 +v 3100.000000000 1700.000000000 787.510498047 +v 3000.000000000 1658.066406250 800.000000000 +v 3000.000000000 1600.000000000 785.944580078 +v 3000.000000000 1658.066406250 800.000000000 +v 3100.000000000 1600.000000000 764.074462891 +v 3000.000000000 1600.000000000 785.944580078 +v 2862.895751953 500.000000000 600.000000000 +v 3100.000000000 1600.000000000 764.074462891 +v 3100.000000000 1600.000000000 764.074462891 +v 3100.000000000 1753.291748047 800.000000000 +v 3146.708251953 1800.000000000 800.000000000 +v 2900.000000000 500.000000000 589.856567383 +v 2800.000000000 404.309448242 600.000000000 +v 300.000000000 100.000000000 816.414184570 +v 400.000000000 100.000000000 858.588378906 +v 2800.000000000 400.000000000 599.225646973 +v 500.000000000 100.000000000 884.386718750 +v 2800.000000000 404.309448242 600.000000000 +v 600.000000000 100.000000000 893.755798340 +v 2900.000000000 400.000000000 570.322082520 +v 700.000000000 100.000000000 892.189880371 +v 2800.000000000 400.000000000 599.225646973 +v 800.000000000 100.000000000 887.492065430 +v 3000.000000000 500.000000000 563.288574219 +v 900.000000000 100.000000000 877.353210449 +v 2900.000000000 400.000000000 570.322082520 +v 1000.000000000 100.000000000 861.720397949 +v 2900.000000000 400.000000000 570.322082520 +v 1100.000000000 100.000000000 846.087341309 +v 3000.000000000 400.000000000 542.188171387 +v 1200.000000000 100.000000000 829.684814453 +v 3100.000000000 500.000000000 538.286560059 +v 1300.000000000 100.000000000 814.848144531 +v 1400.000000000 100.000000000 800.011535645 +v 300.000000000 200.000000000 850.785278320 +v 400.000000000 200.000000000 896.887695312 +v 500.000000000 138.448471069 900.000000000 +v 411.072937012 200.000000000 900.000000000 +v 600.000000000 115.982505798 900.000000000 +v 700.000000000 121.732757568 900.000000000 +v 800.000000000 140.005233765 900.000000000 +v 892.263488770 200.000000000 900.000000000 +v 900.000000000 200.000000000 898.427124023 +v 1000.000000000 200.000000000 880.458557129 +v 1100.000000000 200.000000000 862.490112305 +v 1200.000000000 200.000000000 846.883666992 +v 1300.000000000 200.000000000 831.250732422 +v 1400.000000000 200.000000000 818.749694824 +v 1500.000000000 200.000000000 804.682800293 +v 200.000000000 300.000000000 827.349182129 +v 300.000000000 300.000000000 884.386718750 +v 400.000000000 209.723236084 900.000000000 +v 335.078186035 300.000000000 900.000000000 +v 900.000000000 208.753509521 900.000000000 +v 972.419372559 300.000000000 900.000000000 +v 1000.000000000 300.000000000 893.755798340 +v 1100.000000000 300.000000000 874.991027832 +v 1200.000000000 300.000000000 858.588378906 +v 1300.000000000 300.000000000 843.751831055 +v 1400.000000000 300.000000000 829.684814453 +v 1500.000000000 300.000000000 816.414184570 +v 1600.000000000 300.000000000 803.913085938 +v 200.000000000 400.000000000 867.957580566 +v 300.000000000 339.191314697 900.000000000 +v 256.946319580 400.000000000 900.000000000 +v 1000.000000000 366.646484375 900.000000000 +v 1015.997009277 400.000000000 900.000000000 +v 1100.000000000 400.000000000 883.590393066 +v 1200.000000000 400.000000000 867.957580566 +v 1300.000000000 400.000000000 853.917114258 +v 1400.000000000 400.000000000 841.416137695 +v 1500.000000000 400.000000000 829.684814453 +v 1600.000000000 400.000000000 817.979980469 +v 1700.000000000 400.000000000 806.248779297 +v 100.000000000 500.000000000 838.284179688 +v 184.956604004 500.000000000 900.000000000 +v 200.000000000 474.568359375 900.000000000 +v 1036.379394531 500.000000000 900.000000000 +v 1100.000000000 500.000000000 889.058044434 +v 1200.000000000 500.000000000 874.991027832 +v 1300.000000000 500.000000000 863.286193848 +v 1400.000000000 500.000000000 852.351196289 +v 1500.000000000 500.000000000 841.416137695 +v 1600.000000000 500.000000000 829.684814453 +v 1700.000000000 500.000000000 818.749694824 +v 1600.000000000 400.000000000 817.979980469 +v 1600.000000000 500.000000000 829.684814453 +v 1600.000000000 400.000000000 817.979980469 +v 1700.000000000 400.000000000 806.248779297 +v 1800.000000000 500.000000000 807.814697266 +v 1753.386718750 400.000000000 800.000000000 +v 1700.000000000 400.000000000 806.248779297 +v 1700.000000000 400.000000000 806.248779297 +v 1700.000000000 400.000000000 806.248779297 +v 100.000000000 600.000000000 882.820678711 +v 126.183738708 600.000000000 900.000000000 +v 1075.050659180 600.000000000 900.000000000 +v 1100.000000000 600.000000000 896.887695312 +v 1200.000000000 600.000000000 885.926025391 +v 1300.000000000 600.000000000 875.787231445 +v 1400.000000000 600.000000000 865.621826172 +v 1500.000000000 600.000000000 854.686828613 +v 1400.000000000 500.000000000 852.351196289 +v 1400.000000000 600.000000000 865.621826172 +v 1400.000000000 500.000000000 852.351196289 +v 1500.000000000 500.000000000 841.416137695 +v 1600.000000000 600.000000000 843.751831055 +v 1500.000000000 500.000000000 841.416137695 +v 1500.000000000 500.000000000 841.416137695 +v 1600.000000000 500.000000000 829.684814453 +v 1700.000000000 600.000000000 832.816711426 +v 1600.000000000 500.000000000 829.684814453 +v 1600.000000000 500.000000000 829.684814453 +v 1800.000000000 600.000000000 821.085327148 +v 1900.000000000 600.000000000 810.150329590 +v 66.357513428 700.000000000 900.000000000 +v 100.000000000 637.918090820 900.000000000 +v 3000.000000000 400.000000000 542.188171387 +v 1100.000000000 619.942504883 900.000000000 +v 1199.944335938 700.000000000 900.000000000 +v 1200.000000000 700.000000000 899.993041992 +v 1300.000000000 700.000000000 889.058044434 +v 1400.000000000 700.000000000 880.458557129 +v 1300.000000000 600.000000000 875.787231445 +v 1300.000000000 700.000000000 889.058044434 +v 1300.000000000 600.000000000 875.787231445 +v 1400.000000000 600.000000000 865.621826172 +v 1500.000000000 700.000000000 870.319763184 +v 1400.000000000 600.000000000 865.621826172 +v 1400.000000000 600.000000000 865.621826172 +v 1600.000000000 700.000000000 860.154357910 +v 1700.000000000 700.000000000 849.219299316 +v 1800.000000000 700.000000000 836.718383789 +v 1900.000000000 700.000000000 824.987060547 +v 2000.000000000 700.000000000 813.282226562 +v 1900.000000000 600.000000000 810.150329590 +v 2000.000000000 615.036560059 800.000000000 +v 1900.000000000 600.000000000 810.150329590 +v 1900.000000000 700.000000000 824.987060547 +v 2000.000000000 615.036560059 800.000000000 +v 3000.000000000 400.000000000 542.188171387 +v 7.006183147 800.000000000 900.000000000 +v 1200.000000000 700.037109375 900.000000000 +v 1300.000000000 756.013854980 900.000000000 +v 1300.000000000 700.000000000 889.058044434 +v 1200.000000000 700.037109375 900.000000000 +v 1384.527099609 800.000000000 900.000000000 +v 1400.000000000 800.000000000 898.427124023 +v 1300.000000000 700.000000000 889.058044434 +v 1300.000000000 700.000000000 889.058044434 +v 1500.000000000 800.000000000 886.722351074 +v 1600.000000000 800.000000000 878.122924805 +v 1700.000000000 800.000000000 867.187866211 +v 1800.000000000 800.000000000 855.456542969 +v 1900.000000000 800.000000000 842.185852051 +v 1800.000000000 700.000000000 836.718383789 +v 1800.000000000 800.000000000 855.456542969 +v 1800.000000000 700.000000000 836.718383789 +v 1900.000000000 700.000000000 824.987060547 +v 2000.000000000 800.000000000 828.915100098 +v 1900.000000000 700.000000000 824.987060547 +v 1900.000000000 700.000000000 824.987060547 +v 2100.000000000 800.000000000 814.848144531 +v 3100.000000000 500.000000000 538.286560059 +v 1400.000000000 807.183166504 900.000000000 +v 1500.000000000 858.647277832 900.000000000 +v 1585.616210938 900.000000000 900.000000000 +v 1600.000000000 900.000000000 898.427124023 +v 1700.000000000 900.000000000 886.722351074 +v 1600.000000000 800.000000000 878.122924805 +v 1600.000000000 900.000000000 898.427124023 +v 1600.000000000 800.000000000 878.122924805 +v 1700.000000000 800.000000000 867.187866211 +v 1800.000000000 900.000000000 874.991027832 +v 1700.000000000 800.000000000 867.187866211 +v 1700.000000000 800.000000000 867.187866211 +v 1800.000000000 800.000000000 855.456542969 +v 1900.000000000 900.000000000 861.720397949 +v 1800.000000000 800.000000000 855.456542969 +v 1800.000000000 800.000000000 855.456542969 +v 2000.000000000 900.000000000 847.653381348 +v 2100.000000000 900.000000000 832.020446777 +v 2200.000000000 900.000000000 816.414184570 +v 1600.000000000 906.711364746 900.000000000 +v 1700.000000000 958.647277832 900.000000000 +v 1600.000000000 900.000000000 898.427124023 +v 1600.000000000 906.711364746 900.000000000 +v 1600.000000000 906.711364746 900.000000000 +v 1775.050781250 1000.000000000 900.000000000 +v 1800.000000000 1000.000000000 896.887695312 +v 1900.000000000 1000.000000000 883.590393066 +v 2000.000000000 1000.000000000 868.753784180 +v 2100.000000000 1000.000000000 852.351196289 +v 2200.000000000 1000.000000000 835.152343750 +v 2300.000000000 1000.000000000 816.414184570 +v 1800.000000000 1012.857604980 900.000000000 +v 1900.000000000 1070.018310547 900.000000000 +v 1944.947021484 1100.000000000 900.000000000 +v 2000.000000000 1100.000000000 891.393676758 +v 2100.000000000 1100.000000000 874.991027832 +v 2200.000000000 1100.000000000 857.022460938 +v 2300.000000000 1100.000000000 836.718383789 +v 2400.000000000 1100.000000000 814.051940918 +v 2000.000000000 1134.422729492 900.000000000 +v 2099.957763672 1200.000000000 900.000000000 +v 2100.000000000 1200.000000000 899.993041992 +v 2200.000000000 1200.000000000 880.458557129 +v 2300.000000000 1200.000000000 859.384704590 +v 2400.000000000 1200.000000000 836.718383789 +v 2500.000000000 1200.000000000 812.512512207 +v 2100.000000000 1200.026977539 900.000000000 +v 2200.000000000 1278.159545898 900.000000000 +v 2224.968261719 1300.000000000 900.000000000 +v 2300.000000000 1300.000000000 883.590393066 +v 2400.000000000 1300.000000000 860.154357910 +v 2500.000000000 1300.000000000 833.586425781 +v 2600.000000000 1300.000000000 808.584411621 +v 2300.000000000 1360.025390625 900.000000000 +v 2343.708740234 1400.000000000 900.000000000 +v 2400.000000000 1400.000000000 885.926025391 +v 2300.000000000 1360.025390625 900.000000000 +v 2300.000000000 1300.000000000 883.590393066 +v 2300.000000000 1360.025390625 900.000000000 +v 2400.000000000 1300.000000000 860.154357910 +v 2300.000000000 1300.000000000 883.590393066 +v 2500.000000000 1400.000000000 858.588378906 +v 2400.000000000 1300.000000000 860.154357910 +v 2400.000000000 1300.000000000 860.154357910 +v 2500.000000000 1300.000000000 833.586425781 +v 2600.000000000 1400.000000000 832.020446777 +v 2500.000000000 1300.000000000 833.586425781 +v 2500.000000000 1300.000000000 833.586425781 +v 2600.000000000 1300.000000000 808.584411621 +v 2700.000000000 1400.000000000 804.682800293 +v 2632.343505859 1300.000000000 800.000000000 +v 2600.000000000 1300.000000000 808.584411621 +v 2600.000000000 1300.000000000 808.584411621 +v 2600.000000000 1300.000000000 808.584411621 +v 2700.000000000 1379.316162109 800.000000000 +v 2700.000000000 1400.000000000 804.682800293 +v 2400.000000000 1452.973144531 900.000000000 +v 2445.702636719 1500.000000000 900.000000000 +v 2500.000000000 1500.000000000 885.156372070 +v 2400.000000000 1452.973144531 900.000000000 +v 2400.000000000 1400.000000000 885.926025391 +v 2400.000000000 1452.973144531 900.000000000 +v 2500.000000000 1400.000000000 858.588378906 +v 2400.000000000 1400.000000000 885.926025391 +v 2600.000000000 1500.000000000 857.022460938 +v 2500.000000000 1400.000000000 858.588378906 +v 2500.000000000 1400.000000000 858.588378906 +v 2600.000000000 1400.000000000 832.020446777 +v 2700.000000000 1500.000000000 828.915100098 +v 2600.000000000 1400.000000000 832.020446777 +v 2600.000000000 1400.000000000 832.020446777 +v 2700.000000000 1400.000000000 804.682800293 +v 2800.000000000 1500.000000000 805.479064941 +v 2700.000000000 1400.000000000 804.682800293 +v 2700.000000000 1400.000000000 804.682800293 +v 2700.000000000 1400.000000000 804.682800293 +v 2500.000000000 1552.760620117 900.000000000 +v 2544.748779297 1600.000000000 900.000000000 +v 2600.000000000 1600.000000000 883.590393066 +v 2700.000000000 1600.000000000 856.252746582 +v 2800.000000000 1600.000000000 832.020446777 +v 2900.000000000 1600.000000000 808.584411621 +v 2600.000000000 1658.326538086 900.000000000 +v 2642.887207031 1700.000000000 900.000000000 +v 2700.000000000 1700.000000000 884.386718750 +v 2800.000000000 1700.000000000 859.384704590 +v 2900.000000000 1700.000000000 834.382629395 +v 3000.000000000 1700.000000000 810.150329590 +v 3000.000000000 1658.066406250 800.000000000 +v 3000.000000000 1700.000000000 810.150329590 +v 2700.000000000 1752.617309570 900.000000000 +v 2752.920898438 1800.000000000 900.000000000 +v 2800.000000000 1800.000000000 887.492065430 +v 2900.000000000 1800.000000000 860.950683594 +v 3000.000000000 1800.000000000 835.152343750 +v 2900.000000000 1700.000000000 834.382629395 +v 2900.000000000 1800.000000000 860.950683594 +v 2900.000000000 1700.000000000 834.382629395 +v 3000.000000000 1700.000000000 810.150329590 +v 3100.000000000 1800.000000000 810.946533203 +v 3000.000000000 1700.000000000 810.150329590 +v 3000.000000000 1700.000000000 810.150329590 +v 3000.000000000 1700.000000000 810.150329590 +v 2800.000000000 1844.458618164 900.000000000 +v 2800.000000000 1800.000000000 887.492065430 +v 2752.920898438 1800.000000000 900.000000000 +v 2855.541503906 1900.000000000 900.000000000 +v 2900.000000000 1900.000000000 887.492065430 +v 2800.000000000 1844.458618164 900.000000000 +v 2800.000000000 1800.000000000 887.492065430 +v 2800.000000000 1844.458618164 900.000000000 +v 2900.000000000 1800.000000000 860.950683594 +v 2800.000000000 1800.000000000 887.492065430 +v 3000.000000000 1900.000000000 860.154357910 +v 2900.000000000 1800.000000000 860.950683594 +v 2900.000000000 1800.000000000 860.950683594 +v 3100.000000000 1900.000000000 835.152343750 +v 3100.000000000 400.000000000 515.620178223 +v 2900.000000000 1945.708984375 900.000000000 +v 2951.352050781 2000.000000000 900.000000000 +v 3000.000000000 2000.000000000 885.926025391 +v 3100.000000000 2000.000000000 858.588378906 +v 3100.000000000 300.000000000 490.618194580 +v 3000.000000000 2054.553710938 900.000000000 +v 3040.563476562 2100.000000000 900.000000000 +v 3100.000000000 2100.000000000 882.820678711 +v 3100.000000000 400.000000000 515.620178223 +v 3100.000000000 2170.971679688 900.000000000 +v 3123.679687500 2200.000000000 900.000000000 +v 3100.000000000 500.000000000 538.286560059 +v 3200.000000000 500.000000000 513.284545898 +v 500.000000000 200.000000000 924.995056152 +v 600.000000000 200.000000000 932.824829102 +v 700.000000000 200.000000000 928.126892090 +v 800.000000000 200.000000000 918.757812500 +v 400.000000000 300.000000000 928.896728516 +v 500.000000000 300.000000000 957.030578613 +v 600.000000000 300.000000000 966.399658203 +v 700.000000000 300.000000000 959.366210938 +v 800.000000000 300.000000000 937.496093750 +v 900.000000000 300.000000000 916.395690918 +v 300.000000000 400.000000000 924.225341797 +v 400.000000000 400.000000000 959.366210938 +v 500.000000000 400.000000000 980.466674805 +v 600.000000000 400.000000000 990.632080078 +v 700.000000000 400.000000000 974.229431152 +v 800.000000000 400.000000000 949.997070312 +v 900.000000000 400.000000000 927.330688477 +v 1000.000000000 400.000000000 903.124877930 +v 200.000000000 500.000000000 910.928039551 +v 300.000000000 500.000000000 962.498107910 +v 400.000000000 500.000000000 994.533569336 +v 500.000000000 462.528320312 1000.000000000 +v 431.832824707 500.000000000 1000.000000000 +v 600.000000000 466.595642090 1000.000000000 +v 620.050170898 500.000000000 1000.000000000 +v 700.000000000 500.000000000 981.262878418 +v 800.000000000 500.000000000 953.129028320 +v 900.000000000 500.000000000 927.330688477 +v 1000.000000000 500.000000000 906.256835938 +v 200.000000000 600.000000000 948.431091309 +v 300.000000000 600.000000000 996.869262695 +v 400.000000000 516.268432617 1000.000000000 +v 310.013305664 600.000000000 1000.000000000 +v 633.337707520 600.000000000 1000.000000000 +v 700.000000000 600.000000000 982.802307129 +v 800.000000000 600.000000000 954.694946289 +v 900.000000000 600.000000000 928.126892090 +v 1000.000000000 600.000000000 909.362243652 +v 100.000000000 700.000000000 928.126892090 +v 200.000000000 700.000000000 991.401794434 +v 300.000000000 610.541259766 1000.000000000 +v 224.449569702 700.000000000 1000.000000000 +v 657.133178711 700.000000000 1000.000000000 +v 700.000000000 700.000000000 988.269775391 +v 800.000000000 700.000000000 956.260864258 +v 900.000000000 700.000000000 937.496093750 +v 1000.000000000 700.000000000 924.225341797 +v 1100.000000000 700.000000000 912.494079590 +v 100.000000000 800.000000000 972.663513184 +v 200.000000000 727.500610352 1000.000000000 +v 154.668685913 800.000000000 1000.000000000 +v 684.186096191 800.000000000 1000.000000000 +v 700.000000000 800.000000000 995.303222656 +v 800.000000000 800.000000000 970.301269531 +v 900.000000000 800.000000000 954.694946289 +v 1000.000000000 800.000000000 942.963623047 +v 1100.000000000 800.000000000 931.258850098 +v 1200.000000000 800.000000000 918.757812500 +v 1300.000000000 800.000000000 908.592529297 +v 1200.000000000 700.037109375 900.000000000 +v 1200.000000000 800.000000000 918.757812500 +v 1200.000000000 700.037109375 900.000000000 +v 84.619506836 900.000000000 1000.000000000 +v 100.000000000 871.425659180 1000.000000000 +v 2900.000000000 554.132324219 600.000000000 +v 700.000000000 830.043701172 1000.000000000 +v 758.362976074 900.000000000 1000.000000000 +v 800.000000000 900.000000000 992.197875977 +v 900.000000000 900.000000000 977.334777832 +v 1000.000000000 900.000000000 964.064025879 +v 1100.000000000 900.000000000 951.563049316 +v 1200.000000000 900.000000000 941.397644043 +v 1300.000000000 900.000000000 929.692871094 +v 1200.000000000 800.000000000 918.757812500 +v 1200.000000000 900.000000000 941.397644043 +v 1200.000000000 800.000000000 918.757812500 +v 1400.000000000 900.000000000 920.323730469 +v 1500.000000000 900.000000000 909.362243652 +v 2934.376220703 600.000000000 600.000000000 +v 9.719596863 1000.000000000 1000.000000000 +v 800.000000000 934.461669922 1000.000000000 +v 900.000000000 996.710937500 1000.000000000 +v 905.808349609 1000.000000000 1000.000000000 +v 1000.000000000 1000.000000000 987.500122070 +v 1100.000000000 1000.000000000 974.999023438 +v 1200.000000000 1000.000000000 963.294311523 +v 1300.000000000 1000.000000000 953.129028320 +v 1200.000000000 900.000000000 941.397644043 +v 1200.000000000 1000.000000000 963.294311523 +v 1200.000000000 900.000000000 941.397644043 +v 1400.000000000 1000.000000000 942.193908691 +v 1500.000000000 1000.000000000 932.028564453 +v 1600.000000000 1000.000000000 921.863159180 +v 1500.000000000 900.000000000 909.362243652 +v 1600.000000000 906.711364746 900.000000000 +v 1500.000000000 900.000000000 909.362243652 +v 1500.000000000 1000.000000000 932.028564453 +v 1700.000000000 1000.000000000 909.362243652 +v 1600.000000000 906.711364746 900.000000000 +v 1600.000000000 906.711364746 900.000000000 +v 3000.000000000 600.000000000 583.592773438 +v 1000.000000000 1051.640136719 1000.000000000 +v 1093.838989258 1100.000000000 1000.000000000 +v 1100.000000000 1100.000000000 999.231445312 +v 1200.000000000 1100.000000000 988.269775391 +v 1300.000000000 1100.000000000 977.334777832 +v 1200.000000000 1000.000000000 963.294311523 +v 1200.000000000 1100.000000000 988.269775391 +v 1200.000000000 1000.000000000 963.294311523 +v 1400.000000000 1100.000000000 967.195922852 +v 1500.000000000 1100.000000000 957.030578613 +v 1400.000000000 1000.000000000 942.193908691 +v 1400.000000000 1100.000000000 967.195922852 +v 1400.000000000 1000.000000000 942.193908691 +v 1500.000000000 1000.000000000 932.028564453 +v 1600.000000000 1100.000000000 946.095581055 +v 1500.000000000 1000.000000000 932.028564453 +v 1500.000000000 1000.000000000 932.028564453 +v 1700.000000000 1100.000000000 933.594482422 +v 1800.000000000 1100.000000000 921.093444824 +v 1900.000000000 1100.000000000 907.026550293 +v 1100.000000000 1102.982177734 1000.000000000 +v 1200.000000000 1145.468872070 1000.000000000 +v 1300.000000000 1185.310424805 1000.000000000 +v 1200.000000000 1100.000000000 988.269775391 +v 1200.000000000 1145.468872070 1000.000000000 +v 1200.000000000 1145.468872070 1000.000000000 +v 1338.392211914 1200.000000000 1000.000000000 +v 1400.000000000 1200.000000000 993.737426758 +v 1300.000000000 1185.310424805 1000.000000000 +v 1300.000000000 1100.000000000 977.334777832 +v 1300.000000000 1185.310424805 1000.000000000 +v 1400.000000000 1100.000000000 967.195922852 +v 1300.000000000 1100.000000000 977.334777832 +v 1500.000000000 1200.000000000 983.598510742 +v 1400.000000000 1100.000000000 967.195922852 +v 1400.000000000 1100.000000000 967.195922852 +v 1600.000000000 1200.000000000 972.663513184 +v 1700.000000000 1200.000000000 959.366210938 +v 1800.000000000 1200.000000000 946.095581055 +v 1900.000000000 1200.000000000 932.028564453 +v 2000.000000000 1200.000000000 916.395690918 +v 1400.000000000 1222.260131836 1000.000000000 +v 1500.000000000 1258.353027344 1000.000000000 +v 1600.000000000 1294.578247070 1000.000000000 +v 1612.535644531 1300.000000000 1000.000000000 +v 1700.000000000 1300.000000000 989.066040039 +v 1800.000000000 1300.000000000 974.999023438 +v 1900.000000000 1300.000000000 960.932128906 +v 2000.000000000 1300.000000000 944.529541016 +v 2100.000000000 1300.000000000 925.791381836 +v 2200.000000000 1300.000000000 905.460571289 +v 1700.000000000 1336.847778320 1000.000000000 +v 1800.000000000 1380.030395508 1000.000000000 +v 1842.046875000 1400.000000000 1000.000000000 +v 1900.000000000 1400.000000000 991.401794434 +v 2000.000000000 1400.000000000 973.433227539 +v 2100.000000000 1400.000000000 954.694946289 +v 2200.000000000 1400.000000000 933.594482422 +v 2300.000000000 1400.000000000 910.928039551 +v 2300.000000000 1360.025390625 900.000000000 +v 2300.000000000 1400.000000000 910.928039551 +v 1900.000000000 1427.500610352 1000.000000000 +v 2000.000000000 1484.970825195 1000.000000000 +v 2023.112670898 1500.000000000 1000.000000000 +v 2100.000000000 1500.000000000 984.368225098 +v 2200.000000000 1500.000000000 963.294311523 +v 2100.000000000 1400.000000000 954.694946289 +v 2100.000000000 1500.000000000 984.368225098 +v 2100.000000000 1400.000000000 954.694946289 +v 2200.000000000 1400.000000000 933.594482422 +v 2300.000000000 1500.000000000 939.062011719 +v 2200.000000000 1400.000000000 933.594482422 +v 2200.000000000 1400.000000000 933.594482422 +v 2300.000000000 1400.000000000 910.928039551 +v 2400.000000000 1500.000000000 912.494079590 +v 2300.000000000 1400.000000000 910.928039551 +v 2300.000000000 1400.000000000 910.928039551 +v 2300.000000000 1400.000000000 910.928039551 +v 2400.000000000 1452.973144531 900.000000000 +v 2400.000000000 1500.000000000 912.494079590 +v 2100.000000000 1545.479248047 1000.000000000 +v 2100.000000000 1500.000000000 984.368225098 +v 2023.112670898 1500.000000000 1000.000000000 +v 2179.959472656 1600.000000000 1000.000000000 +v 2200.000000000 1600.000000000 995.303222656 +v 2100.000000000 1500.000000000 984.368225098 +v 2100.000000000 1500.000000000 984.368225098 +v 2300.000000000 1600.000000000 970.301269531 +v 2200.000000000 1500.000000000 963.294311523 +v 2200.000000000 1600.000000000 995.303222656 +v 2200.000000000 1500.000000000 963.294311523 +v 2300.000000000 1500.000000000 939.062011719 +v 2400.000000000 1600.000000000 942.193908691 +v 2300.000000000 1500.000000000 939.062011719 +v 2300.000000000 1500.000000000 939.062011719 +v 2400.000000000 1500.000000000 912.494079590 +v 2500.000000000 1600.000000000 913.290283203 +v 2400.000000000 1500.000000000 912.494079590 +v 2400.000000000 1500.000000000 912.494079590 +v 2400.000000000 1500.000000000 912.494079590 +v 2200.000000000 1613.977661133 1000.000000000 +v 2200.000000000 1600.000000000 995.303222656 +v 2179.959472656 1600.000000000 1000.000000000 +v 2300.000000000 1692.705566406 1000.000000000 +v 2200.000000000 1600.000000000 995.303222656 +v 2308.084716797 1700.000000000 1000.000000000 +v 2400.000000000 1700.000000000 973.433227539 +v 2500.000000000 1700.000000000 942.963623047 +v 2600.000000000 1700.000000000 911.724365234 +v 2400.000000000 1780.983764648 1000.000000000 +v 2419.969482422 1800.000000000 1000.000000000 +v 2500.000000000 1800.000000000 974.999023438 +v 2600.000000000 1800.000000000 942.193908691 +v 2700.000000000 1800.000000000 914.059997559 +v 2500.000000000 1876.210205078 1000.000000000 +v 2522.706054688 1900.000000000 1000.000000000 +v 2600.000000000 1900.000000000 973.433227539 +v 2700.000000000 1900.000000000 944.529541016 +v 2800.000000000 1900.000000000 915.625976562 +v 2800.000000000 1844.458618164 900.000000000 +v 2800.000000000 1844.458618164 900.000000000 +v 2800.000000000 1844.458618164 900.000000000 +v 2800.000000000 1900.000000000 915.625976562 +v 2600.000000000 1980.983764648 1000.000000000 +v 2600.000000000 1900.000000000 973.433227539 +v 2522.706054688 1900.000000000 1000.000000000 +v 2619.489501953 2000.000000000 1000.000000000 +v 2700.000000000 2000.000000000 974.229431152 +v 2600.000000000 1900.000000000 973.433227539 +v 2700.000000000 1900.000000000 944.529541016 +v 2600.000000000 1900.000000000 973.433227539 +v 2800.000000000 2000.000000000 944.529541016 +v 2700.000000000 1900.000000000 944.529541016 +v 2700.000000000 2000.000000000 974.229431152 +v 2700.000000000 1900.000000000 944.529541016 +v 2800.000000000 1900.000000000 915.625976562 +v 2900.000000000 2000.000000000 914.856262207 +v 2800.000000000 1900.000000000 915.625976562 +v 2800.000000000 1900.000000000 915.625976562 +v 2800.000000000 1900.000000000 915.625976562 +v 2700.000000000 2084.578125000 1000.000000000 +v 2700.000000000 2000.000000000 974.229431152 +v 2619.489501953 2000.000000000 1000.000000000 +v 2715.029052734 2100.000000000 1000.000000000 +v 2800.000000000 2100.000000000 973.433227539 +v 2700.000000000 2000.000000000 974.229431152 +v 2700.000000000 2000.000000000 974.229431152 +v 2900.000000000 2100.000000000 942.193908691 +v 3000.000000000 2100.000000000 911.724365234 +v 2800.000000000 2191.915039062 1000.000000000 +v 2807.123291016 2200.000000000 1000.000000000 +v 2900.000000000 2200.000000000 969.531555176 +v 3000.000000000 2200.000000000 938.292297363 +v 3100.000000000 2200.000000000 907.026550293 +v 2893.208007812 2300.000000000 1000.000000000 +v 2900.000000000 2300.000000000 997.665527344 +v 3000.000000000 2300.000000000 964.064025879 +v 3100.000000000 2300.000000000 932.028564453 +v 3100.000000000 600.000000000 559.386962891 +v 2900.000000000 2308.305664062 1000.000000000 +v 2973.341552734 2400.000000000 1000.000000000 +v 3000.000000000 2400.000000000 990.632080078 +v 3100.000000000 2400.000000000 957.030578613 +v 2881.547851562 100.000000000 500.000000000 +v 3000.000000000 2436.349853516 1000.000000000 +v 3047.725341797 2500.000000000 1000.000000000 +v 3100.000000000 2500.000000000 982.032592773 +v 3100.000000000 500.000000000 538.286560059 +v 3100.000000000 2571.864013672 1000.000000000 +v 3119.574707031 2600.000000000 1000.000000000 +v 3200.000000000 600.000000000 535.924377441 +v 3186.930664062 2700.000000000 1000.000000000 +v 3200.000000000 500.000000000 513.284545898 +v 3000.000000000 683.991088867 600.000000000 +v 500.000000000 500.000000000 1011.705871582 +v 600.000000000 500.000000000 1004.698974609 +v 400.000000000 600.000000000 1028.135009766 +v 500.000000000 600.000000000 1034.372314453 +v 600.000000000 600.000000000 1008.600524902 +v 300.000000000 700.000000000 1026.569091797 +v 400.000000000 700.000000000 1045.307373047 +v 500.000000000 700.000000000 1041.405761719 +v 600.000000000 700.000000000 1015.634033203 +v 200.000000000 800.000000000 1022.667480469 +v 300.000000000 800.000000000 1048.439208984 +v 400.000000000 800.000000000 1060.144042969 +v 500.000000000 800.000000000 1050.005126953 +v 600.000000000 800.000000000 1025.003173828 +v 100.000000000 900.000000000 1010.936279297 +v 200.000000000 900.000000000 1050.005126953 +v 300.000000000 900.000000000 1068.743408203 +v 400.000000000 900.000000000 1071.875244141 +v 500.000000000 900.000000000 1063.275878906 +v 600.000000000 900.000000000 1038.273803711 +v 700.000000000 900.000000000 1010.936279297 +v 100.000000000 1000.000000000 1050.774902344 +v 200.000000000 1000.000000000 1079.678466797 +v 300.000000000 1000.000000000 1092.179443359 +v 400.000000000 1000.000000000 1090.613525391 +v 500.000000000 1000.000000000 1078.908813477 +v 600.000000000 1000.000000000 1054.676513672 +v 700.000000000 1000.000000000 1031.240356445 +v 800.000000000 1000.000000000 1014.837768555 +v 900.000000000 1000.000000000 1000.770874023 +v 3013.343750000 700.000000000 600.000000000 +v 100.000000000 1100.000000000 1085.145996094 +v 200.000000000 1070.307983398 1100.000000000 +v 163.381057739 1100.000000000 1100.000000000 +v 300.000000000 1028.579467773 1100.000000000 +v 400.000000000 1036.384155273 1100.000000000 +v 477.779541016 1100.000000000 1100.000000000 +v 500.000000000 1100.000000000 1095.311401367 +v 600.000000000 1100.000000000 1074.210937500 +v 700.000000000 1100.000000000 1053.137084961 +v 800.000000000 1100.000000000 1037.504150391 +v 900.000000000 1100.000000000 1024.206909180 +v 1000.000000000 1100.000000000 1011.705871582 +v 100.000000000 1152.797485352 1100.000000000 +v 3100.000000000 700.000000000 579.691162109 +v 62.237972260 1200.000000000 1100.000000000 +v 500.000000000 1126.093383789 1100.000000000 +v 570.870422363 1200.000000000 1100.000000000 +v 600.000000000 1200.000000000 1094.541625977 +v 700.000000000 1200.000000000 1075.776855469 +v 800.000000000 1200.000000000 1062.506225586 +v 900.000000000 1200.000000000 1049.208862305 +v 1000.000000000 1200.000000000 1036.707885742 +v 1100.000000000 1200.000000000 1025.003173828 +v 1200.000000000 1200.000000000 1014.068054199 +v 1300.000000000 1200.000000000 1003.902709961 +v 1200.000000000 1145.468872070 1000.000000000 +v 1300.000000000 1200.000000000 1003.902709961 +v 1300.000000000 1185.310424805 1000.000000000 +v 1300.000000000 1200.000000000 1003.902709961 +v 3100.000000000 337.524322510 500.000000000 +v 600.000000000 1224.958129883 1100.000000000 +v 700.000000000 1296.884521484 1100.000000000 +v 705.869506836 1300.000000000 1100.000000000 +v 800.000000000 1300.000000000 1087.508178711 +v 900.000000000 1300.000000000 1074.210937500 +v 1000.000000000 1300.000000000 1062.506225586 +v 1100.000000000 1300.000000000 1051.571166992 +v 1200.000000000 1300.000000000 1042.175415039 +v 1300.000000000 1300.000000000 1032.036621094 +v 1400.000000000 1300.000000000 1021.871276855 +v 1300.000000000 1200.000000000 1003.902709961 +v 1300.000000000 1200.000000000 1003.902709961 +v 1300.000000000 1200.000000000 1003.902709961 +v 1300.000000000 1300.000000000 1032.036621094 +v 1500.000000000 1300.000000000 1011.705871582 +v 1600.000000000 1300.000000000 1001.567077637 +v 800.000000000 1348.471069336 1100.000000000 +v 900.000000000 1394.243652344 1100.000000000 +v 914.370056152 1400.000000000 1100.000000000 +v 1000.000000000 1400.000000000 1090.613525391 +v 1100.000000000 1400.000000000 1080.474731445 +v 1200.000000000 1400.000000000 1071.105590820 +v 1300.000000000 1400.000000000 1061.709960938 +v 1200.000000000 1300.000000000 1042.175415039 +v 1200.000000000 1400.000000000 1071.105590820 +v 1200.000000000 1300.000000000 1042.175415039 +v 1300.000000000 1300.000000000 1032.036621094 +v 1400.000000000 1400.000000000 1052.340820312 +v 1300.000000000 1300.000000000 1032.036621094 +v 1300.000000000 1400.000000000 1061.709960938 +v 1300.000000000 1300.000000000 1032.036621094 +v 1500.000000000 1400.000000000 1042.175415039 +v 1600.000000000 1400.000000000 1031.240356445 +v 1700.000000000 1400.000000000 1018.739440918 +v 1800.000000000 1400.000000000 1006.238342285 +v 1000.000000000 1432.445190430 1100.000000000 +v 1100.000000000 1465.800659180 1100.000000000 +v 1200.000000000 1497.375000000 1100.000000000 +v 1200.000000000 1400.000000000 1071.105590820 +v 1100.000000000 1465.800659180 1100.000000000 +v 1208.313720703 1500.000000000 1100.000000000 +v 1300.000000000 1500.000000000 1091.409790039 +v 1200.000000000 1497.375000000 1100.000000000 +v 1200.000000000 1400.000000000 1071.105590820 +v 1200.000000000 1497.375000000 1100.000000000 +v 1300.000000000 1400.000000000 1061.709960938 +v 1200.000000000 1400.000000000 1071.105590820 +v 1400.000000000 1500.000000000 1082.040649414 +v 1300.000000000 1400.000000000 1061.709960938 +v 1300.000000000 1400.000000000 1061.709960938 +v 1500.000000000 1500.000000000 1072.645019531 +v 1600.000000000 1500.000000000 1063.275878906 +v 1700.000000000 1500.000000000 1051.571166992 +v 1800.000000000 1500.000000000 1039.070068359 +v 1900.000000000 1500.000000000 1022.667480469 +v 2000.000000000 1500.000000000 1004.698974609 +v 1300.000000000 1527.498168945 1100.000000000 +v 1400.000000000 1557.489624023 1100.000000000 +v 1500.000000000 1587.491943359 1100.000000000 +v 1538.471801758 1600.000000000 1100.000000000 +v 1600.000000000 1600.000000000 1093.745483398 +v 1700.000000000 1600.000000000 1082.810302734 +v 1800.000000000 1600.000000000 1071.875244141 +v 1900.000000000 1600.000000000 1056.242431641 +v 2000.000000000 1600.000000000 1038.273803711 +v 2100.000000000 1600.000000000 1018.739440918 +v 2023.112670898 1500.000000000 1000.000000000 +v 2000.000000000 1500.000000000 1004.698974609 +v 2000.000000000 1500.000000000 1004.698974609 +v 2000.000000000 1500.000000000 1004.698974609 +v 2000.000000000 1600.000000000 1038.273803711 +v 1600.000000000 1618.613769531 1100.000000000 +v 1700.000000000 1650.011840820 1100.000000000 +v 1800.000000000 1685.732299805 1100.000000000 +v 1833.273071289 1700.000000000 1100.000000000 +v 1900.000000000 1700.000000000 1090.613525391 +v 1800.000000000 1685.732299805 1100.000000000 +v 1800.000000000 1600.000000000 1071.875244141 +v 1800.000000000 1685.732299805 1100.000000000 +v 1900.000000000 1600.000000000 1056.242431641 +v 1800.000000000 1600.000000000 1071.875244141 +v 2000.000000000 1700.000000000 1072.645019531 +v 1900.000000000 1600.000000000 1056.242431641 +v 1900.000000000 1600.000000000 1056.242431641 +v 2000.000000000 1600.000000000 1038.273803711 +v 2100.000000000 1700.000000000 1053.137084961 +v 2000.000000000 1600.000000000 1038.273803711 +v 2000.000000000 1600.000000000 1038.273803711 +v 2200.000000000 1700.000000000 1028.904785156 +v 2179.959472656 1600.000000000 1000.000000000 +v 2100.000000000 1600.000000000 1018.739440918 +v 2100.000000000 1600.000000000 1018.739440918 +v 2100.000000000 1600.000000000 1018.739440918 +v 2100.000000000 1700.000000000 1053.137084961 +v 2300.000000000 1700.000000000 1002.336791992 +v 1900.000000000 1726.690917969 1100.000000000 +v 2000.000000000 1777.785156250 1100.000000000 +v 2000.000000000 1700.000000000 1072.645019531 +v 1900.000000000 1700.000000000 1090.613525391 +v 1900.000000000 1726.690917969 1100.000000000 +v 2000.000000000 1700.000000000 1072.645019531 +v 1900.000000000 1726.690917969 1100.000000000 +v 2037.024658203 1800.000000000 1100.000000000 +v 2100.000000000 1800.000000000 1086.711914062 +v 2000.000000000 1700.000000000 1072.645019531 +v 2100.000000000 1700.000000000 1053.137084961 +v 2000.000000000 1700.000000000 1072.645019531 +v 2200.000000000 1800.000000000 1064.841796875 +v 2100.000000000 1700.000000000 1053.137084961 +v 2100.000000000 1700.000000000 1053.137084961 +v 2300.000000000 1800.000000000 1036.707885742 +v 2400.000000000 1800.000000000 1006.238342285 +v 2100.000000000 1835.432006836 1100.000000000 +v 2100.000000000 1800.000000000 1086.711914062 +v 2037.024658203 1800.000000000 1100.000000000 +v 2200.000000000 1899.974121094 1100.000000000 +v 2200.000000000 1800.000000000 1064.841796875 +v 2100.000000000 1800.000000000 1086.711914062 +v 2200.000000000 1800.000000000 1064.841796875 +v 2200.033447266 1900.000000000 1100.000000000 +v 2300.000000000 1900.000000000 1072.645019531 +v 2200.000000000 1800.000000000 1064.841796875 +v 2300.000000000 1800.000000000 1036.707885742 +v 2200.000000000 1800.000000000 1064.841796875 +v 2400.000000000 1900.000000000 1040.635986328 +v 2300.000000000 1800.000000000 1036.707885742 +v 2300.000000000 1800.000000000 1036.707885742 +v 2400.000000000 1800.000000000 1006.238342285 +v 2500.000000000 1900.000000000 1007.804321289 +v 2400.000000000 1800.000000000 1006.238342285 +v 2500.000000000 1900.000000000 1007.804321289 +v 2300.000000000 1979.525512695 1100.000000000 +v 2321.984130859 2000.000000000 1100.000000000 +v 2400.000000000 2000.000000000 1075.007202148 +v 2500.000000000 2000.000000000 1041.405761719 +v 2500.000000000 1900.000000000 1007.804321289 +v 2600.000000000 2000.000000000 1006.238342285 +v 2522.706054688 1900.000000000 1000.000000000 +v 2500.000000000 1900.000000000 1007.804321289 +v 2500.000000000 1900.000000000 1007.804321289 +v 2500.000000000 1900.000000000 1007.804321289 +v 2400.000000000 2072.714599609 1100.000000000 +v 2427.285400391 2100.000000000 1100.000000000 +v 2500.000000000 2100.000000000 1075.007202148 +v 2600.000000000 2100.000000000 1039.070068359 +v 2700.000000000 2100.000000000 1004.698974609 +v 2619.489501953 2000.000000000 1000.000000000 +v 2600.000000000 2000.000000000 1006.238342285 +v 2600.000000000 2000.000000000 1006.238342285 +v 2600.000000000 2000.000000000 1006.238342285 +v 2600.000000000 2100.000000000 1039.070068359 +v 2500.000000000 2174.438964844 1100.000000000 +v 2523.379882812 2200.000000000 1100.000000000 +v 2600.000000000 2200.000000000 1071.875244141 +v 2700.000000000 2200.000000000 1035.938232422 +v 2600.000000000 2100.000000000 1039.070068359 +v 2600.000000000 2200.000000000 1071.875244141 +v 2600.000000000 2100.000000000 1039.070068359 +v 2800.000000000 2200.000000000 1002.336791992 +v 2600.000000000 2285.732177734 1100.000000000 +v 2600.000000000 2200.000000000 1071.875244141 +v 2523.379882812 2200.000000000 1100.000000000 +v 2612.480468750 2300.000000000 1100.000000000 +v 2700.000000000 2300.000000000 1067.177490234 +v 2600.000000000 2200.000000000 1071.875244141 +v 2600.000000000 2200.000000000 1071.875244141 +v 2800.000000000 2300.000000000 1032.036621094 +v 2696.015380859 2400.000000000 1100.000000000 +v 2700.000000000 2400.000000000 1098.443237305 +v 2800.000000000 2400.000000000 1060.940185547 +v 2900.000000000 2400.000000000 1025.772827148 +v 2700.000000000 2404.983398438 1100.000000000 +v 2777.555175781 2500.000000000 1100.000000000 +v 2800.000000000 2500.000000000 1091.409790039 +v 2900.000000000 2500.000000000 1053.137084961 +v 3000.000000000 2500.000000000 1016.403747559 +v 2800.000000000 2528.949218750 1100.000000000 +v 2852.921142578 2600.000000000 1100.000000000 +v 2900.000000000 2600.000000000 1081.244384766 +v 3000.000000000 2600.000000000 1042.971679688 +v 3100.000000000 2600.000000000 1007.034606934 +v 2900.000000000 2664.890136719 1100.000000000 +v 2925.472900391 2700.000000000 1100.000000000 +v 3000.000000000 2700.000000000 1070.309326172 +v 3100.000000000 2700.000000000 1031.240356445 +v 2998.024658203 2800.000000000 1100.000000000 +v 3000.000000000 2800.000000000 1099.213012695 +v 3100.000000000 2800.000000000 1058.604614258 +v 3096.579833984 800.000000000 600.000000000 +v 3000.000000000 2802.797363281 1100.000000000 +v 3066.047851562 2900.000000000 1100.000000000 +v 3100.000000000 2900.000000000 1085.942260742 +v 3100.000000000 800.000000000 599.225646973 +v 3100.000000000 2950.014404297 1100.000000000 +v 3133.932617188 3000.000000000 1100.000000000 +v 3158.793212891 400.000000000 500.000000000 +v 3198.099365234 3100.000000000 1100.000000000 +v 3100.000000000 803.674499512 600.000000000 +v 3100.000000000 100.000000000 436.712554932 +v 200.000000000 1100.000000000 1108.582031250 +v 300.000000000 1100.000000000 1119.543701172 +v 400.000000000 1100.000000000 1116.411743164 +v 100.000000000 1200.000000000 1113.279907227 +v 200.000000000 1200.000000000 1135.150024414 +v 300.000000000 1200.000000000 1142.979736328 +v 400.000000000 1200.000000000 1132.018188477 +v 500.000000000 1200.000000000 1113.279907227 +v 100.000000000 100.000000000 665.632324219 +v 100.000000000 1300.000000000 1140.617553711 +v 200.000000000 1300.000000000 1160.948364258 +v 300.000000000 1300.000000000 1162.487670898 +v 400.000000000 1300.000000000 1149.217041016 +v 500.000000000 1300.000000000 1129.682495117 +v 600.000000000 1300.000000000 1116.411743164 +v 700.000000000 1300.000000000 1100.778930664 +v 2900.000000000 100.000000000 494.519744873 +v 100.000000000 1400.000000000 1166.415893555 +v 200.000000000 1400.000000000 1181.252441406 +v 300.000000000 1400.000000000 1177.350952148 +v 400.000000000 1400.000000000 1164.849853516 +v 500.000000000 1400.000000000 1149.986694336 +v 600.000000000 1400.000000000 1139.051635742 +v 700.000000000 1400.000000000 1125.780883789 +v 800.000000000 1400.000000000 1113.279907227 +v 900.000000000 1400.000000000 1101.575195312 +v 142.706787109 100.000000000 700.000000000 +v 100.000000000 1500.000000000 1179.686523438 +v 200.000000000 1500.000000000 1192.957275391 +v 300.000000000 1500.000000000 1192.187500000 +v 400.000000000 1500.000000000 1181.252441406 +v 500.000000000 1500.000000000 1171.883422852 +v 600.000000000 1500.000000000 1163.283935547 +v 700.000000000 1500.000000000 1152.348876953 +v 800.000000000 1500.000000000 1141.413818359 +v 900.000000000 1500.000000000 1129.682495117 +v 1000.000000000 1500.000000000 1119.543701172 +v 1100.000000000 1500.000000000 1110.148071289 +v 1200.000000000 1500.000000000 1100.778930664 +v 1100.000000000 1465.800659180 1100.000000000 +v 1100.000000000 1500.000000000 1110.148071289 +v 1100.000000000 1465.800659180 1100.000000000 +v 1200.000000000 1497.375000000 1100.000000000 +v 1200.000000000 1500.000000000 1100.778930664 +v 100.000000000 1589.619384766 1200.000000000 +v 2800.000000000 18.452123642 500.000000000 +v 88.426826477 1600.000000000 1200.000000000 +v 200.000000000 1536.052856445 1200.000000000 +v 300.000000000 1543.478637695 1200.000000000 +v 400.000000000 1585.721801758 1200.000000000 +v 444.396820068 1600.000000000 1200.000000000 +v 500.000000000 1600.000000000 1196.089111328 +v 600.000000000 1600.000000000 1188.286010742 +v 700.000000000 1600.000000000 1178.916870117 +v 800.000000000 1600.000000000 1168.751464844 +v 900.000000000 1600.000000000 1158.586059570 +v 1000.000000000 1600.000000000 1149.217041016 +v 1100.000000000 1600.000000000 1140.617553711 +v 1200.000000000 1600.000000000 1132.018188477 +v 1100.000000000 1500.000000000 1110.148071289 +v 1100.000000000 1600.000000000 1140.617553711 +v 1100.000000000 1500.000000000 1110.148071289 +v 1200.000000000 1500.000000000 1100.778930664 +v 1300.000000000 1600.000000000 1122.649047852 +v 1200.000000000 1500.000000000 1100.778930664 +v 1200.000000000 1500.000000000 1100.778930664 +v 1200.000000000 1500.000000000 1100.778930664 +v 1400.000000000 1600.000000000 1113.279907227 +v 1500.000000000 1600.000000000 1103.910766602 +v 2900.000000000 120.027076721 500.000000000 +v 500.000000000 1616.139160156 1200.000000000 +v 600.000000000 1645.452880859 1200.000000000 +v 700.000000000 1677.121215820 1200.000000000 +v 779.881835938 1700.000000000 1200.000000000 +v 800.000000000 1700.000000000 1198.424804688 +v 900.000000000 1700.000000000 1189.055664062 +v 1000.000000000 1700.000000000 1181.252441406 +v 1100.000000000 1700.000000000 1173.449340820 +v 1000.000000000 1600.000000000 1149.217041016 +v 1000.000000000 1700.000000000 1181.252441406 +v 1000.000000000 1600.000000000 1149.217041016 +v 1100.000000000 1600.000000000 1140.617553711 +v 1200.000000000 1700.000000000 1164.849853516 +v 1100.000000000 1600.000000000 1140.617553711 +v 1100.000000000 1600.000000000 1140.617553711 +v 1300.000000000 1700.000000000 1156.250488281 +v 1400.000000000 1700.000000000 1146.881347656 +v 1500.000000000 1700.000000000 1137.512207031 +v 1600.000000000 1700.000000000 1127.346923828 +v 1700.000000000 1700.000000000 1117.181518555 +v 1800.000000000 1700.000000000 1104.680541992 +v 1800.000000000 1685.732299805 1100.000000000 +v 1800.000000000 1700.000000000 1104.680541992 +v 800.000000000 1705.303710938 1200.000000000 +v 900.000000000 1734.163085938 1200.000000000 +v 1000.000000000 1758.521118164 1200.000000000 +v 1000.000000000 1700.000000000 1181.252441406 +v 900.000000000 1734.163085938 1200.000000000 +v 1100.000000000 1780.934326172 1200.000000000 +v 1000.000000000 1700.000000000 1181.252441406 +v 1000.000000000 1758.521118164 1200.000000000 +v 1000.000000000 1758.521118164 1200.000000000 +v 1179.881835938 1800.000000000 1200.000000000 +v 1200.000000000 1800.000000000 1198.424804688 +v 1300.000000000 1800.000000000 1190.621582031 +v 1400.000000000 1800.000000000 1182.022216797 +v 1500.000000000 1800.000000000 1173.449340820 +v 1600.000000000 1800.000000000 1163.283935547 +v 1700.000000000 1800.000000000 1153.118530273 +v 1800.000000000 1800.000000000 1140.617553711 +v 1700.000000000 1700.000000000 1117.181518555 +v 1700.000000000 1800.000000000 1153.118530273 +v 1700.000000000 1700.000000000 1117.181518555 +v 1800.000000000 1700.000000000 1104.680541992 +v 1900.000000000 1800.000000000 1125.780883789 +v 1800.000000000 1700.000000000 1104.680541992 +v 1800.000000000 1700.000000000 1104.680541992 +v 1800.000000000 1700.000000000 1104.680541992 +v 2000.000000000 1800.000000000 1107.812377930 +v 1900.000000000 1726.690917969 1100.000000000 +v 1900.000000000 1800.000000000 1125.780883789 +v 1900.000000000 1726.690917969 1100.000000000 +v 1200.000000000 1804.687866211 1200.000000000 +v 1300.000000000 1827.285766602 1200.000000000 +v 1400.000000000 1851.120605469 1200.000000000 +v 1500.000000000 1873.881103516 1200.000000000 +v 1600.000000000 1897.901489258 1200.000000000 +v 1607.741699219 1900.000000000 1200.000000000 +v 1700.000000000 1900.000000000 1190.621582031 +v 1600.000000000 1897.901489258 1200.000000000 +v 1600.000000000 1800.000000000 1163.283935547 +v 1600.000000000 1897.901489258 1200.000000000 +v 1700.000000000 1800.000000000 1153.118530273 +v 1600.000000000 1800.000000000 1163.283935547 +v 1800.000000000 1900.000000000 1177.350952148 +v 1700.000000000 1800.000000000 1153.118530273 +v 1700.000000000 1800.000000000 1153.118530273 +v 1900.000000000 1900.000000000 1162.487670898 +v 1800.000000000 1800.000000000 1140.617553711 +v 1800.000000000 1900.000000000 1177.350952148 +v 1800.000000000 1800.000000000 1140.617553711 +v 1900.000000000 1800.000000000 1125.780883789 +v 2000.000000000 1900.000000000 1145.315429688 +v 1900.000000000 1800.000000000 1125.780883789 +v 1900.000000000 1800.000000000 1125.780883789 +v 2100.000000000 1900.000000000 1124.214965820 +v 2037.024658203 1800.000000000 1100.000000000 +v 2000.000000000 1800.000000000 1107.812377930 +v 2000.000000000 1800.000000000 1107.812377930 +v 2000.000000000 1800.000000000 1107.812377930 +v 2000.000000000 1900.000000000 1145.315429688 +v 2200.000000000 1900.000000000 1100.009155273 +v 1700.000000000 1925.007080078 1200.000000000 +v 1800.000000000 1959.178222656 1200.000000000 +v 1800.000000000 1900.000000000 1177.350952148 +v 1700.000000000 1900.000000000 1190.621582031 +v 1700.000000000 1925.007080078 1200.000000000 +v 1800.000000000 1900.000000000 1177.350952148 +v 1700.000000000 1925.007080078 1200.000000000 +v 1900.000000000 1997.945190430 1200.000000000 +v 1800.000000000 1900.000000000 1177.350952148 +v 1904.575683594 2000.000000000 1200.000000000 +v 2000.000000000 2000.000000000 1183.588134766 +v 1900.000000000 1997.945190430 1200.000000000 +v 1900.000000000 1900.000000000 1162.487670898 +v 1900.000000000 1997.945190430 1200.000000000 +v 2000.000000000 1900.000000000 1145.315429688 +v 1900.000000000 1900.000000000 1162.487670898 +v 2100.000000000 2000.000000000 1162.487670898 +v 2000.000000000 1900.000000000 1145.315429688 +v 2000.000000000 1900.000000000 1145.315429688 +v 2200.000000000 2000.000000000 1136.715942383 +v 2300.000000000 2000.000000000 1107.042724609 +v 2000.000000000 2042.007446289 1200.000000000 +v 2100.000000000 2096.015625000 1200.000000000 +v 2105.859130859 2100.000000000 1200.000000000 +v 2200.000000000 2100.000000000 1174.988769531 +v 2300.000000000 2100.000000000 1142.979736328 +v 2400.000000000 2100.000000000 1109.378295898 +v 2200.000000000 2166.691406250 1200.000000000 +v 2238.078613281 2200.000000000 1200.000000000 +v 2300.000000000 2200.000000000 1179.686523438 +v 2400.000000000 2200.000000000 1144.519165039 +v 2500.000000000 2200.000000000 1108.582031250 +v 2300.000000000 2254.164794922 1200.000000000 +v 2345.835205078 2300.000000000 1200.000000000 +v 2400.000000000 2300.000000000 1179.686523438 +v 2500.000000000 2300.000000000 1142.183471680 +v 2600.000000000 2300.000000000 1104.680541992 +v 2523.379882812 2200.000000000 1100.000000000 +v 2500.000000000 2200.000000000 1108.582031250 +v 2500.000000000 2200.000000000 1108.582031250 +v 2500.000000000 2200.000000000 1108.582031250 +v 2500.000000000 2300.000000000 1142.183471680 +v 2400.000000000 2357.762451172 1200.000000000 +v 2438.019531250 2400.000000000 1200.000000000 +v 2500.000000000 2400.000000000 1175.784912109 +v 2600.000000000 2400.000000000 1137.512207031 +v 2500.000000000 2300.000000000 1142.183471680 +v 2500.000000000 2400.000000000 1175.784912109 +v 2500.000000000 2300.000000000 1142.183471680 +v 2500.000000000 2470.451660156 1200.000000000 +v 2500.000000000 2400.000000000 1175.784912109 +v 2438.019531250 2400.000000000 1200.000000000 +v 2525.493164062 2500.000000000 1200.000000000 +v 2600.000000000 2500.000000000 1170.317382812 +v 2500.000000000 2400.000000000 1175.784912109 +v 2500.000000000 2400.000000000 1175.784912109 +v 2700.000000000 2500.000000000 1129.682495117 +v 2600.000000000 2592.655273438 1200.000000000 +v 2605.790283203 2600.000000000 1200.000000000 +v 2700.000000000 2600.000000000 1161.718017578 +v 2800.000000000 2600.000000000 1121.083129883 +v 2681.475585938 2700.000000000 1200.000000000 +v 2700.000000000 2700.000000000 1192.187500000 +v 2800.000000000 2700.000000000 1150.782958984 +v 2900.000000000 2700.000000000 1110.148071289 +v 2700.000000000 2725.008544922 1200.000000000 +v 2754.518310547 2800.000000000 1200.000000000 +v 2800.000000000 2800.000000000 1180.456298828 +v 2900.000000000 2800.000000000 1139.051635742 +v 2800.000000000 2867.554931641 1200.000000000 +v 2822.669677734 2900.000000000 1200.000000000 +v 2900.000000000 2900.000000000 1167.981811523 +v 3000.000000000 2900.000000000 1127.346923828 +v 2890.898681641 3000.000000000 1200.000000000 +v 2900.000000000 3000.000000000 1196.089111328 +v 3000.000000000 3000.000000000 1154.684570312 +v 3100.000000000 3000.000000000 1114.049560547 +v 2900.000000000 3013.900878906 1200.000000000 +v 2957.399414062 3100.000000000 1200.000000000 +v 3000.000000000 3100.000000000 1182.022216797 +v 3100.000000000 3100.000000000 1140.617553711 +v 3000.000000000 3165.698486328 1200.000000000 +v 33.329032898 100.000000000 600.000000000 +v 2000.000000000 35.473258972 700.000000000 +v 2971.822265625 200.000000000 500.000000000 +v 100.000000000 1600.000000000 1202.352905273 +v 200.000000000 1600.000000000 1212.491699219 +v 300.000000000 1600.000000000 1210.156127930 +v 400.000000000 1600.000000000 1203.122680664 +v 2100.000000000 99.986328125 700.000000000 +v 100.000000000 1700.000000000 1226.558715820 +v 200.000000000 1700.000000000 1233.592163086 +v 300.000000000 1700.000000000 1230.460327148 +v 400.000000000 1700.000000000 1224.223022461 +v 500.000000000 1700.000000000 1220.321411133 +v 600.000000000 1700.000000000 1214.057739258 +v 700.000000000 1700.000000000 1206.254516602 +v 2100.020751953 100.000000000 700.000000000 +v 100.000000000 1800.000000000 1250.791015625 +v 200.000000000 1800.000000000 1254.692626953 +v 300.000000000 1800.000000000 1252.356933594 +v 400.000000000 1800.000000000 1248.428833008 +v 500.000000000 1800.000000000 1245.323486328 +v 600.000000000 1800.000000000 1240.625610352 +v 700.000000000 1800.000000000 1234.361816406 +v 800.000000000 1800.000000000 1228.124633789 +v 900.000000000 1800.000000000 1221.091186523 +v 1000.000000000 1800.000000000 1213.287963867 +v 900.000000000 1734.163085938 1200.000000000 +v 900.000000000 1800.000000000 1221.091186523 +v 900.000000000 1734.163085938 1200.000000000 +v 1100.000000000 1800.000000000 1206.254516602 +v 1000.000000000 1758.521118164 1200.000000000 +v 1000.000000000 1800.000000000 1213.287963867 +v 1000.000000000 1758.521118164 1200.000000000 +v 2200.000000000 100.000000000 683.600830078 +v 100.000000000 1900.000000000 1274.227050781 +v 200.000000000 1900.000000000 1277.332397461 +v 300.000000000 1900.000000000 1275.793090820 +v 400.000000000 1900.000000000 1273.430908203 +v 500.000000000 1900.000000000 1272.661132812 +v 600.000000000 1900.000000000 1268.759521484 +v 700.000000000 1900.000000000 1262.495727539 +v 800.000000000 1900.000000000 1257.028198242 +v 700.000000000 1800.000000000 1234.361816406 +v 700.000000000 1900.000000000 1262.495727539 +v 700.000000000 1800.000000000 1234.361816406 +v 800.000000000 1800.000000000 1228.124633789 +v 900.000000000 1900.000000000 1251.560668945 +v 800.000000000 1800.000000000 1228.124633789 +v 800.000000000 1800.000000000 1228.124633789 +v 900.000000000 1800.000000000 1221.091186523 +v 1000.000000000 1900.000000000 1245.323486328 +v 900.000000000 1800.000000000 1221.091186523 +v 900.000000000 1800.000000000 1221.091186523 +v 1100.000000000 1900.000000000 1239.059692383 +v 1000.000000000 1800.000000000 1213.287963867 +v 1000.000000000 1900.000000000 1245.323486328 +v 1000.000000000 1800.000000000 1213.287963867 +v 1200.000000000 1900.000000000 1232.026245117 +v 1300.000000000 1900.000000000 1224.992797852 +v 1400.000000000 1900.000000000 1217.189575195 +v 1500.000000000 1900.000000000 1209.386352539 +v 1600.000000000 1900.000000000 1200.786987305 +v 1600.000000000 1897.901489258 1200.000000000 +v 1600.000000000 1900.000000000 1200.786987305 +v 3000.000000000 200.000000000 491.414398193 +v 100.000000000 2000.000000000 1298.432861328 +v 200.000000000 1993.542846680 1300.000000000 +v 150.038986206 2000.000000000 1300.000000000 +v 300.000000000 1993.928466797 1300.000000000 +v 366.994201660 2000.000000000 1300.000000000 +v 400.000000000 2000.000000000 1299.229125977 +v 500.000000000 2000.000000000 1299.229125977 +v 600.000000000 2000.000000000 1296.866943359 +v 700.000000000 2000.000000000 1292.965332031 +v 800.000000000 2000.000000000 1287.497802734 +v 700.000000000 1900.000000000 1262.495727539 +v 700.000000000 2000.000000000 1292.965332031 +v 700.000000000 1900.000000000 1262.495727539 +v 900.000000000 2000.000000000 1282.030273438 +v 1000.000000000 2000.000000000 1277.332397461 +v 900.000000000 1900.000000000 1251.560668945 +v 900.000000000 2000.000000000 1282.030273438 +v 900.000000000 1900.000000000 1251.560668945 +v 1000.000000000 1900.000000000 1245.323486328 +v 1100.000000000 2000.000000000 1271.864868164 +v 1000.000000000 1900.000000000 1245.323486328 +v 1000.000000000 1900.000000000 1245.323486328 +v 1200.000000000 2000.000000000 1265.627685547 +v 1300.000000000 2000.000000000 1259.363891602 +v 1400.000000000 2000.000000000 1252.356933594 +v 1500.000000000 2000.000000000 1245.323486328 +v 1600.000000000 2000.000000000 1237.493774414 +v 1500.000000000 1900.000000000 1209.386352539 +v 1500.000000000 2000.000000000 1245.323486328 +v 1500.000000000 1900.000000000 1209.386352539 +v 1600.000000000 1900.000000000 1200.786987305 +v 1700.000000000 2000.000000000 1228.124633789 +v 1600.000000000 1900.000000000 1200.786987305 +v 1600.000000000 1900.000000000 1200.786987305 +v 1600.000000000 1900.000000000 1200.786987305 +v 1800.000000000 2000.000000000 1215.623657227 +v 1700.000000000 1925.007080078 1200.000000000 +v 1700.000000000 2000.000000000 1228.124633789 +v 1700.000000000 1925.007080078 1200.000000000 +v 1900.000000000 2000.000000000 1200.786987305 +v 1900.000000000 1997.945190430 1200.000000000 +v 1900.000000000 2000.000000000 1200.786987305 +v 2300.000000000 100.000000000 663.270141602 +v 100.000000000 2006.268066406 1300.000000000 +v 400.000000000 2002.904541016 1300.000000000 +v 500.000000000 2002.819824219 1300.000000000 +v 600.000000000 2011.449462891 1300.000000000 +v 700.000000000 2023.685791016 1300.000000000 +v 700.000000000 2000.000000000 1292.965332031 +v 600.000000000 2011.449462891 1300.000000000 +v 800.000000000 2040.020751953 1300.000000000 +v 700.000000000 2000.000000000 1292.965332031 +v 900.000000000 2054.777099609 1300.000000000 +v 1000.000000000 2070.757568359 1300.000000000 +v 900.000000000 2000.000000000 1282.030273438 +v 900.000000000 2054.777099609 1300.000000000 +v 900.000000000 2054.777099609 1300.000000000 +v 1100.000000000 2085.694824219 1300.000000000 +v 1185.900878906 2100.000000000 1300.000000000 +v 1200.000000000 2100.000000000 1299.229125977 +v 1300.000000000 2100.000000000 1292.965332031 +v 1400.000000000 2100.000000000 1287.497802734 +v 1500.000000000 2100.000000000 1281.260620117 +v 1400.000000000 2000.000000000 1252.356933594 +v 1400.000000000 2100.000000000 1287.497802734 +v 1400.000000000 2000.000000000 1252.356933594 +v 1500.000000000 2000.000000000 1245.323486328 +v 1600.000000000 2100.000000000 1274.227050781 +v 1500.000000000 2000.000000000 1245.323486328 +v 1500.000000000 2000.000000000 1245.323486328 +v 1700.000000000 2100.000000000 1264.831420898 +v 1600.000000000 2000.000000000 1237.493774414 +v 1600.000000000 2100.000000000 1274.227050781 +v 1600.000000000 2000.000000000 1237.493774414 +v 1700.000000000 2000.000000000 1228.124633789 +v 1800.000000000 2100.000000000 1253.896362305 +v 1700.000000000 2000.000000000 1228.124633789 +v 1700.000000000 2100.000000000 1264.831420898 +v 1700.000000000 2000.000000000 1228.124633789 +v 1800.000000000 2000.000000000 1215.623657227 +v 1900.000000000 2100.000000000 1239.855957031 +v 1800.000000000 2000.000000000 1215.623657227 +v 1800.000000000 2000.000000000 1215.623657227 +v 1900.000000000 2000.000000000 1200.786987305 +v 2000.000000000 2100.000000000 1222.657104492 +v 1900.000000000 2000.000000000 1200.786987305 +v 1900.000000000 2000.000000000 1200.786987305 +v 1900.000000000 2000.000000000 1200.786987305 +v 2100.000000000 2100.000000000 1201.556640625 +v 1200.000000000 2102.296142578 1300.000000000 +v 1300.000000000 2120.466796875 1300.000000000 +v 1400.000000000 2135.550537109 1300.000000000 +v 1400.000000000 2100.000000000 1287.497802734 +v 1300.000000000 2120.466796875 1300.000000000 +v 1500.000000000 2151.051513672 1300.000000000 +v 1400.000000000 2100.000000000 1287.497802734 +v 1600.000000000 2171.716796875 1300.000000000 +v 1600.000000000 2100.000000000 1274.227050781 +v 1500.000000000 2100.000000000 1281.260620117 +v 1500.000000000 2151.051513672 1300.000000000 +v 1600.000000000 2100.000000000 1274.227050781 +v 1500.000000000 2151.051513672 1300.000000000 +v 1700.000000000 2195.740234375 1300.000000000 +v 1700.000000000 2100.000000000 1264.831420898 +v 1600.000000000 2100.000000000 1274.227050781 +v 1600.000000000 2171.716796875 1300.000000000 +v 1700.000000000 2100.000000000 1264.831420898 +v 1600.000000000 2171.716796875 1300.000000000 +v 1715.392456055 2200.000000000 1300.000000000 +v 1800.000000000 2200.000000000 1291.399414062 +v 1700.000000000 2100.000000000 1264.831420898 +v 1700.000000000 2100.000000000 1264.831420898 +v 1900.000000000 2200.000000000 1277.332397461 +v 2000.000000000 2200.000000000 1260.929809570 +v 2100.000000000 2200.000000000 1239.059692383 +v 2200.000000000 2200.000000000 1212.491699219 +v 1800.000000000 2223.932373047 1300.000000000 +v 1900.000000000 2259.185302734 1300.000000000 +v 1995.300292969 2300.000000000 1300.000000000 +v 2000.000000000 2300.000000000 1299.229125977 +v 2100.000000000 2300.000000000 1275.793090820 +v 2200.000000000 2300.000000000 1249.225097656 +v 2300.000000000 2300.000000000 1217.189575195 +v 2000.000000000 2302.193603516 1300.000000000 +v 2100.000000000 2367.359375000 1300.000000000 +v 2142.866699219 2400.000000000 1300.000000000 +v 2200.000000000 2400.000000000 1284.365966797 +v 2300.000000000 2400.000000000 1252.356933594 +v 2400.000000000 2400.000000000 1214.853881836 +v 2200.000000000 2443.503906250 1300.000000000 +v 2263.428955078 2500.000000000 1300.000000000 +v 2300.000000000 2500.000000000 1288.294067383 +v 2400.000000000 2500.000000000 1250.791015625 +v 2500.000000000 2500.000000000 1210.156127930 +v 2438.019531250 2400.000000000 1200.000000000 +v 2400.000000000 2400.000000000 1214.853881836 +v 2400.000000000 2400.000000000 1214.853881836 +v 2400.000000000 2400.000000000 1214.853881836 +v 2400.000000000 2500.000000000 1250.791015625 +v 2300.000000000 2534.057373047 1300.000000000 +v 2360.435546875 2600.000000000 1300.000000000 +v 2400.000000000 2600.000000000 1285.162109375 +v 2500.000000000 2600.000000000 1243.757568359 +v 2400.000000000 2500.000000000 1250.791015625 +v 2400.000000000 2600.000000000 1285.162109375 +v 2400.000000000 2500.000000000 1250.791015625 +v 2600.000000000 2600.000000000 1202.352905273 +v 2400.000000000 2645.229980469 1300.000000000 +v 2445.100341797 2700.000000000 1300.000000000 +v 2500.000000000 2700.000000000 1278.128662109 +v 2400.000000000 2645.229980469 1300.000000000 +v 2400.000000000 2600.000000000 1285.162109375 +v 2400.000000000 2645.229980469 1300.000000000 +v 2400.000000000 2600.000000000 1285.162109375 +v 2600.000000000 2700.000000000 1234.361816406 +v 2500.000000000 2770.012207031 1300.000000000 +v 2522.212402344 2800.000000000 1300.000000000 +v 2600.000000000 2800.000000000 1267.193603516 +v 2700.000000000 2800.000000000 1223.426757812 +v 2590.573974609 2900.000000000 1300.000000000 +v 2600.000000000 2900.000000000 1296.097167969 +v 2700.000000000 2900.000000000 1253.896362305 +v 2800.000000000 2900.000000000 1209.386352539 +v 2600.000000000 2913.502929688 1300.000000000 +v 2660.381591797 3000.000000000 1300.000000000 +v 2700.000000000 3000.000000000 1283.596191406 +v 2800.000000000 3000.000000000 1239.059692383 +v 2700.000000000 3063.650390625 1300.000000000 +v 2722.212402344 3100.000000000 1300.000000000 +v 2800.000000000 3100.000000000 1267.193603516 +v 2900.000000000 3100.000000000 1224.223022461 +v 3100.000000000 200.000000000 463.280548096 +v 2400.000000000 100.000000000 639.834045410 +v 2500.000000000 59.086864471 600.000000000 +v 2500.000000000 100.000000000 614.062316895 +v 200.000000000 2000.000000000 1301.564697266 +v 300.000000000 2000.000000000 1301.564697266 +v 92.236312866 200.000000000 700.000000000 +v 100.000000000 2100.000000000 1323.434936523 +v 200.000000000 2100.000000000 1326.566772461 +v 300.000000000 2100.000000000 1327.336425781 +v 400.000000000 2100.000000000 1325.770507812 +v 500.000000000 2100.000000000 1326.566772461 +v 600.000000000 2100.000000000 1324.231079102 +v 700.000000000 2100.000000000 1322.665161133 +v 600.000000000 2011.449462891 1300.000000000 +v 600.000000000 2100.000000000 1324.231079102 +v 600.000000000 2011.449462891 1300.000000000 +v 800.000000000 2100.000000000 1318.737060547 +v 900.000000000 2100.000000000 1314.835449219 +v 1000.000000000 2100.000000000 1309.367919922 +v 900.000000000 2054.777099609 1300.000000000 +v 900.000000000 2100.000000000 1314.835449219 +v 900.000000000 2054.777099609 1300.000000000 +v 1100.000000000 2100.000000000 1304.696655273 +v 100.000000000 183.004470825 700.000000000 +v 100.000000000 2200.000000000 1349.206665039 +v 200.000000000 2200.000000000 1352.338500977 +v 300.000000000 2200.000000000 1353.134765625 +v 400.000000000 2200.000000000 1352.338500977 +v 500.000000000 2200.000000000 1353.904418945 +v 600.000000000 2200.000000000 1352.338500977 +v 700.000000000 2200.000000000 1350.772583008 +v 600.000000000 2100.000000000 1324.231079102 +v 600.000000000 2200.000000000 1352.338500977 +v 600.000000000 2100.000000000 1324.231079102 +v 800.000000000 2200.000000000 1349.206665039 +v 900.000000000 2200.000000000 1346.870971680 +v 1000.000000000 2200.000000000 1342.969360352 +v 900.000000000 2100.000000000 1314.835449219 +v 900.000000000 2200.000000000 1346.870971680 +v 900.000000000 2100.000000000 1314.835449219 +v 1100.000000000 2200.000000000 1338.271484375 +v 1200.000000000 2200.000000000 1332.803955078 +v 1300.000000000 2200.000000000 1327.336425781 +v 1400.000000000 2200.000000000 1322.665161133 +v 1300.000000000 2120.466796875 1300.000000000 +v 1300.000000000 2200.000000000 1327.336425781 +v 1300.000000000 2120.466796875 1300.000000000 +v 1500.000000000 2200.000000000 1317.967407227 +v 1600.000000000 2200.000000000 1310.164184570 +v 1500.000000000 2151.051513672 1300.000000000 +v 1500.000000000 2200.000000000 1317.967407227 +v 1500.000000000 2151.051513672 1300.000000000 +v 1700.000000000 2200.000000000 1301.564697266 +v 1600.000000000 2171.716796875 1300.000000000 +v 1600.000000000 2200.000000000 1310.164184570 +v 1600.000000000 2171.716796875 1300.000000000 +v 2547.348144531 100.000000000 600.000000000 +v 100.000000000 2300.000000000 1374.208618164 +v 200.000000000 2300.000000000 1378.136718750 +v 300.000000000 2300.000000000 1380.472412109 +v 400.000000000 2300.000000000 1380.472412109 +v 500.000000000 2300.000000000 1382.038330078 +v 400.000000000 2200.000000000 1352.338500977 +v 400.000000000 2300.000000000 1380.472412109 +v 400.000000000 2200.000000000 1352.338500977 +v 500.000000000 2200.000000000 1353.904418945 +v 600.000000000 2300.000000000 1381.242065430 +v 500.000000000 2200.000000000 1353.904418945 +v 500.000000000 2200.000000000 1353.904418945 +v 600.000000000 2200.000000000 1352.338500977 +v 700.000000000 2300.000000000 1380.472412109 +v 600.000000000 2200.000000000 1352.338500977 +v 600.000000000 2200.000000000 1352.338500977 +v 800.000000000 2300.000000000 1378.906494141 +v 900.000000000 2300.000000000 1377.340454102 +v 1000.000000000 2300.000000000 1374.208618164 +v 900.000000000 2200.000000000 1346.870971680 +v 900.000000000 2300.000000000 1377.340454102 +v 900.000000000 2200.000000000 1346.870971680 +v 1100.000000000 2300.000000000 1371.103271484 +v 1200.000000000 2300.000000000 1366.405395508 +v 1300.000000000 2300.000000000 1361.707641602 +v 1200.000000000 2200.000000000 1332.803955078 +v 1200.000000000 2300.000000000 1366.405395508 +v 1200.000000000 2200.000000000 1332.803955078 +v 1300.000000000 2200.000000000 1327.336425781 +v 1400.000000000 2300.000000000 1357.036376953 +v 1300.000000000 2200.000000000 1327.336425781 +v 1300.000000000 2200.000000000 1327.336425781 +v 1500.000000000 2300.000000000 1352.338500977 +v 1400.000000000 2200.000000000 1322.665161133 +v 1400.000000000 2300.000000000 1357.036376953 +v 1400.000000000 2200.000000000 1322.665161133 +v 1500.000000000 2200.000000000 1317.967407227 +v 1600.000000000 2300.000000000 1346.101318359 +v 1500.000000000 2200.000000000 1317.967407227 +v 1500.000000000 2300.000000000 1352.338500977 +v 1500.000000000 2200.000000000 1317.967407227 +v 1600.000000000 2200.000000000 1310.164184570 +v 1700.000000000 2300.000000000 1338.271484375 +v 1600.000000000 2200.000000000 1310.164184570 +v 1600.000000000 2200.000000000 1310.164184570 +v 1800.000000000 2300.000000000 1327.336425781 +v 1900.000000000 2300.000000000 1315.631713867 +v 100.000000000 2399.973388672 1400.000000000 +v 2200.000000000 177.817398071 700.000000000 +v 99.937484741 2400.000000000 1400.000000000 +v 200.000000000 2382.374023438 1400.000000000 +v 300.000000000 2375.771240234 1400.000000000 +v 400.000000000 2371.431152344 1400.000000000 +v 500.000000000 2365.703125000 1400.000000000 +v 400.000000000 2300.000000000 1380.472412109 +v 400.000000000 2371.431152344 1400.000000000 +v 400.000000000 2371.431152344 1400.000000000 +v 600.000000000 2366.673583984 1400.000000000 +v 700.000000000 2367.561035156 1400.000000000 +v 800.000000000 2372.979003906 1400.000000000 +v 900.000000000 2376.294921875 1400.000000000 +v 1000.000000000 2380.508544922 1400.000000000 +v 900.000000000 2300.000000000 1377.340454102 +v 900.000000000 2376.294921875 1400.000000000 +v 900.000000000 2376.294921875 1400.000000000 +v 1100.000000000 2390.277099609 1400.000000000 +v 1200.000000000 2399.979492188 1400.000000000 +v 1200.175170898 2400.000000000 1400.000000000 +v 1300.000000000 2400.000000000 1396.105346680 +v 1200.000000000 2399.979492188 1400.000000000 +v 1200.000000000 2300.000000000 1366.405395508 +v 1200.000000000 2399.979492188 1400.000000000 +v 1200.000000000 2300.000000000 1366.405395508 +v 1400.000000000 2400.000000000 1391.407470703 +v 1300.000000000 2300.000000000 1361.707641602 +v 1300.000000000 2400.000000000 1396.105346680 +v 1300.000000000 2300.000000000 1361.707641602 +v 1400.000000000 2300.000000000 1357.036376953 +v 1500.000000000 2400.000000000 1388.275634766 +v 1400.000000000 2300.000000000 1357.036376953 +v 1400.000000000 2400.000000000 1391.407470703 +v 1400.000000000 2300.000000000 1357.036376953 +v 1500.000000000 2300.000000000 1352.338500977 +v 1600.000000000 2400.000000000 1381.242065430 +v 1500.000000000 2300.000000000 1352.338500977 +v 1500.000000000 2300.000000000 1352.338500977 +v 1700.000000000 2400.000000000 1373.438964844 +v 1800.000000000 2400.000000000 1364.069824219 +v 1900.000000000 2400.000000000 1350.772583008 +v 2000.000000000 2400.000000000 1334.369995117 +v 2100.000000000 2400.000000000 1311.730102539 +v 2224.947509766 200.000000000 700.000000000 +v 1300.000000000 2411.599853516 1400.000000000 +v 1400.000000000 2424.999267578 1400.000000000 +v 1300.000000000 2400.000000000 1396.105346680 +v 1300.000000000 2411.599853516 1400.000000000 +v 1300.000000000 2411.599853516 1400.000000000 +v 1500.000000000 2434.892578125 1400.000000000 +v 1400.000000000 2400.000000000 1391.407470703 +v 1400.000000000 2424.999267578 1400.000000000 +v 1400.000000000 2424.999267578 1400.000000000 +v 1600.000000000 2454.574707031 1400.000000000 +v 1700.000000000 2473.909912109 1400.000000000 +v 1800.000000000 2499.980957031 1400.000000000 +v 1800.048583984 2500.000000000 1400.000000000 +v 1900.000000000 2500.000000000 1385.939941406 +v 2000.000000000 2500.000000000 1370.307006836 +v 2100.000000000 2500.000000000 1346.870971680 +v 2200.000000000 2500.000000000 1320.302978516 +v 1900.000000000 2540.906738281 1400.000000000 +v 2000.000000000 2586.389160156 1400.000000000 +v 2019.961547852 2600.000000000 1400.000000000 +v 2100.000000000 2600.000000000 1381.242065430 +v 2200.000000000 2600.000000000 1353.134765625 +v 2300.000000000 2600.000000000 1322.665161133 +v 2100.000000000 2659.994873047 1400.000000000 +v 2148.483398438 2700.000000000 1400.000000000 +v 2200.000000000 2700.000000000 1386.709594727 +v 2300.000000000 2700.000000000 1353.904418945 +v 2400.000000000 2700.000000000 1317.967407227 +v 2400.000000000 2645.229980469 1300.000000000 +v 2400.000000000 2700.000000000 1317.967407227 +v 2200.000000000 2743.618652344 1400.000000000 +v 2253.625488281 2800.000000000 1400.000000000 +v 2300.000000000 2800.000000000 1385.143676758 +v 2400.000000000 2800.000000000 1349.206665039 +v 2500.000000000 2800.000000000 1309.367919922 +v 2400.000000000 2700.000000000 1317.967407227 +v 2400.000000000 2700.000000000 1317.967407227 +v 2400.000000000 2700.000000000 1317.967407227 +v 2400.000000000 2800.000000000 1349.206665039 +v 2300.000000000 2852.805664062 1400.000000000 +v 2336.946777344 2900.000000000 1400.000000000 +v 2400.000000000 2900.000000000 1377.340454102 +v 2500.000000000 2900.000000000 1337.501831055 +v 2400.000000000 2800.000000000 1349.206665039 +v 2400.000000000 2900.000000000 1377.340454102 +v 2400.000000000 2800.000000000 1349.206665039 +v 2400.000000000 2990.630615234 1400.000000000 +v 2406.120605469 3000.000000000 1400.000000000 +v 2500.000000000 3000.000000000 1364.069824219 +v 2400.000000000 2990.630615234 1400.000000000 +v 2400.000000000 2900.000000000 1377.340454102 +v 2400.000000000 2990.630615234 1400.000000000 +v 2400.000000000 2900.000000000 1377.340454102 +v 2600.000000000 3000.000000000 1325.000854492 +v 2468.082519531 3100.000000000 1400.000000000 +v 2500.000000000 3100.000000000 1388.275634766 +v 2600.000000000 3100.000000000 1350.772583008 +v 2700.000000000 3100.000000000 1309.367919922 +v 2500.000000000 3151.726074219 1400.000000000 +v 2300.000000000 200.000000000 685.936462402 +v 2400.000000000 200.000000000 666.401977539 +v 2500.000000000 200.000000000 642.196228027 +v 100.000000000 2400.000000000 1400.006835938 +v 200.000000000 2400.000000000 1404.678222656 +v 300.000000000 2400.000000000 1406.244140625 +v 400.000000000 2400.000000000 1407.810058594 +v 500.000000000 2400.000000000 1409.375976562 +v 400.000000000 2371.431152344 1400.000000000 +v 500.000000000 2400.000000000 1409.375976562 +v 600.000000000 2400.000000000 1409.375976562 +v 500.000000000 2400.000000000 1409.375976562 +v 700.000000000 2400.000000000 1409.375976562 +v 800.000000000 2400.000000000 1407.810058594 +v 900.000000000 2400.000000000 1407.040405273 +v 1000.000000000 2400.000000000 1406.244140625 +v 900.000000000 2376.294921875 1400.000000000 +v 900.000000000 2400.000000000 1407.040405273 +v 900.000000000 2376.294921875 1400.000000000 +v 1100.000000000 2400.000000000 1403.112182617 +v 1200.000000000 2400.000000000 1400.006835938 +v 2600.000000000 200.000000000 614.062316895 +v 100.000000000 2500.000000000 1426.574829102 +v 200.000000000 2500.000000000 1429.680175781 +v 300.000000000 2500.000000000 1432.042358398 +v 400.000000000 2500.000000000 1433.581787109 +v 500.000000000 2500.000000000 1435.943969727 +v 600.000000000 2500.000000000 1437.509887695 +v 500.000000000 2400.000000000 1409.375976562 +v 500.000000000 2500.000000000 1435.943969727 +v 500.000000000 2400.000000000 1409.375976562 +v 700.000000000 2500.000000000 1437.509887695 +v 800.000000000 2500.000000000 1437.509887695 +v 900.000000000 2500.000000000 1436.713623047 +v 1000.000000000 2500.000000000 1437.509887695 +v 900.000000000 2400.000000000 1407.040405273 +v 900.000000000 2500.000000000 1436.713623047 +v 900.000000000 2400.000000000 1407.040405273 +v 1100.000000000 2500.000000000 1435.943969727 +v 1200.000000000 2500.000000000 1432.812133789 +v 1100.000000000 2400.000000000 1403.112182617 +v 1100.000000000 2500.000000000 1435.943969727 +v 1100.000000000 2400.000000000 1403.112182617 +v 1200.000000000 2400.000000000 1400.006835938 +v 1300.000000000 2500.000000000 1429.680175781 +v 1200.000000000 2400.000000000 1400.006835938 +v 1200.000000000 2400.000000000 1400.006835938 +v 1200.000000000 2400.000000000 1400.006835938 +v 1400.000000000 2500.000000000 1425.778564453 +v 1300.000000000 2411.599853516 1400.000000000 +v 1300.000000000 2500.000000000 1429.680175781 +v 1300.000000000 2411.599853516 1400.000000000 +v 1500.000000000 2500.000000000 1421.877075195 +v 1400.000000000 2424.999267578 1400.000000000 +v 1400.000000000 2500.000000000 1425.778564453 +v 1400.000000000 2424.999267578 1400.000000000 +v 1600.000000000 2500.000000000 1415.613281250 +v 1700.000000000 2500.000000000 1409.375976562 +v 1800.000000000 2500.000000000 1400.006835938 +v 2600.000000000 100.000000000 584.362487793 +v 100.000000000 2600.000000000 1450.780639648 +v 200.000000000 2600.000000000 1454.682250977 +v 300.000000000 2600.000000000 1457.044433594 +v 400.000000000 2600.000000000 1459.380004883 +v 500.000000000 2600.000000000 1462.511962891 +v 600.000000000 2600.000000000 1464.051391602 +v 500.000000000 2500.000000000 1435.943969727 +v 600.000000000 2600.000000000 1464.051391602 +v 700.000000000 2600.000000000 1464.847534180 +v 600.000000000 2600.000000000 1464.051391602 +v 800.000000000 2600.000000000 1466.413574219 +v 900.000000000 2600.000000000 1466.413574219 +v 1000.000000000 2600.000000000 1467.183227539 +v 900.000000000 2500.000000000 1436.713623047 +v 900.000000000 2600.000000000 1466.413574219 +v 900.000000000 2500.000000000 1436.713623047 +v 1100.000000000 2600.000000000 1466.413574219 +v 1200.000000000 2600.000000000 1464.051391602 +v 1100.000000000 2500.000000000 1435.943969727 +v 1100.000000000 2600.000000000 1466.413574219 +v 1100.000000000 2500.000000000 1435.943969727 +v 1300.000000000 2600.000000000 1461.715698242 +v 1200.000000000 2500.000000000 1432.812133789 +v 1200.000000000 2600.000000000 1464.051391602 +v 1200.000000000 2500.000000000 1432.812133789 +v 1300.000000000 2500.000000000 1429.680175781 +v 1400.000000000 2600.000000000 1458.583862305 +v 1300.000000000 2500.000000000 1429.680175781 +v 1300.000000000 2600.000000000 1461.715698242 +v 1300.000000000 2500.000000000 1429.680175781 +v 1400.000000000 2500.000000000 1425.778564453 +v 1500.000000000 2600.000000000 1457.044433594 +v 1400.000000000 2500.000000000 1425.778564453 +v 1400.000000000 2500.000000000 1425.778564453 +v 1600.000000000 2600.000000000 1450.010864258 +v 1700.000000000 2600.000000000 1442.977416992 +v 1800.000000000 2600.000000000 1432.812133789 +v 1900.000000000 2600.000000000 1420.311035156 +v 2000.000000000 2600.000000000 1404.678222656 +v 44.735309601 300.000000000 700.000000000 +v 100.000000000 2700.000000000 1475.012939453 +v 200.000000000 2700.000000000 1478.914550781 +v 300.000000000 2700.000000000 1482.019897461 +v 400.000000000 2700.000000000 1484.382080078 +v 500.000000000 2700.000000000 1487.487426758 +v 600.000000000 2700.000000000 1489.849609375 +v 700.000000000 2700.000000000 1492.185180664 +v 600.000000000 2600.000000000 1464.051391602 +v 600.000000000 2700.000000000 1489.849609375 +v 600.000000000 2600.000000000 1464.051391602 +v 800.000000000 2700.000000000 1492.981445312 +v 900.000000000 2700.000000000 1494.520874023 +v 1000.000000000 2700.000000000 1496.086791992 +v 900.000000000 2600.000000000 1466.413574219 +v 900.000000000 2700.000000000 1494.520874023 +v 900.000000000 2600.000000000 1466.413574219 +v 1100.000000000 2700.000000000 1496.086791992 +v 1200.000000000 2700.000000000 1495.317138672 +v 1100.000000000 2600.000000000 1466.413574219 +v 1100.000000000 2700.000000000 1496.086791992 +v 1100.000000000 2600.000000000 1466.413574219 +v 1300.000000000 2700.000000000 1493.751220703 +v 1200.000000000 2600.000000000 1464.051391602 +v 1200.000000000 2700.000000000 1495.317138672 +v 1200.000000000 2600.000000000 1464.051391602 +v 1400.000000000 2700.000000000 1492.185180664 +v 1300.000000000 2600.000000000 1461.715698242 +v 1300.000000000 2700.000000000 1493.751220703 +v 1300.000000000 2600.000000000 1461.715698242 +v 1500.000000000 2700.000000000 1489.053344727 +v 1600.000000000 2700.000000000 1483.585815430 +v 1700.000000000 2700.000000000 1477.348632812 +v 1800.000000000 2700.000000000 1465.617309570 +v 1900.000000000 2700.000000000 1453.912475586 +v 2000.000000000 2700.000000000 1436.713623047 +v 2100.000000000 2700.000000000 1412.507934570 +v 2300.000000000 275.052459717 700.000000000 +v 100.000000000 2800.000000000 1499.988403320 +v 200.000000000 2787.108886719 1500.000000000 +v 100.370262146 2800.000000000 1500.000000000 +v 300.000000000 2779.324951172 1500.000000000 +v 400.000000000 2766.640625000 1500.000000000 +v 500.000000000 2751.635986328 1500.000000000 +v 600.000000000 2741.933593750 1500.000000000 +v 700.000000000 2732.249511719 1500.000000000 +v 600.000000000 2700.000000000 1489.849609375 +v 600.000000000 2741.933593750 1500.000000000 +v 600.000000000 2741.933593750 1500.000000000 +v 800.000000000 2726.443603516 1500.000000000 +v 900.000000000 2719.475097656 1500.000000000 +v 1000.000000000 2713.909179688 1500.000000000 +v 900.000000000 2700.000000000 1494.520874023 +v 900.000000000 2719.475097656 1500.000000000 +v 900.000000000 2719.475097656 1500.000000000 +v 1100.000000000 2713.538818359 1500.000000000 +v 1200.000000000 2715.781494141 1500.000000000 +v 1100.000000000 2700.000000000 1496.086791992 +v 1100.000000000 2713.538818359 1500.000000000 +v 1100.000000000 2713.538818359 1500.000000000 +v 1300.000000000 2720.508300781 1500.000000000 +v 1200.000000000 2700.000000000 1495.317138672 +v 1200.000000000 2715.781494141 1500.000000000 +v 1200.000000000 2715.781494141 1500.000000000 +v 1400.000000000 2725.016113281 1500.000000000 +v 1300.000000000 2700.000000000 1493.751220703 +v 1300.000000000 2720.508300781 1500.000000000 +v 1300.000000000 2720.508300781 1500.000000000 +v 1500.000000000 2735.011718750 1500.000000000 +v 1600.000000000 2752.499023438 1500.000000000 +v 1700.000000000 2772.509277344 1500.000000000 +v 1784.702270508 2800.000000000 1500.000000000 +v 1800.000000000 2800.000000000 1498.448974609 +v 1900.000000000 2800.000000000 1485.151733398 +v 2000.000000000 2800.000000000 1467.183227539 +v 2100.000000000 2800.000000000 1443.747192383 +v 2200.000000000 2800.000000000 1417.179199219 +v 2323.023681641 300.000000000 700.000000000 +v 100.000000000 2800.051025391 1500.000000000 +v 1800.000000000 2805.227050781 1500.000000000 +v 1900.000000000 2851.371582031 1500.000000000 +v 1975.009155273 2900.000000000 1500.000000000 +v 2000.000000000 2900.000000000 1495.317138672 +v 2100.000000000 2900.000000000 1471.881103516 +v 2200.000000000 2900.000000000 1444.543334961 +v 2300.000000000 2900.000000000 1413.277587891 +v 2000.000000000 2919.981445312 1500.000000000 +v 2080.018554688 3000.000000000 1500.000000000 +v 2100.000000000 3000.000000000 1495.317138672 +v 2200.000000000 3000.000000000 1468.749145508 +v 2300.000000000 3000.000000000 1437.509887695 +v 2400.000000000 3000.000000000 1402.342529297 +v 2400.000000000 2990.630615234 1400.000000000 +v 2400.000000000 3000.000000000 1402.342529297 +v 2100.000000000 3022.193115234 1500.000000000 +v 2159.996582031 3100.000000000 1500.000000000 +v 2200.000000000 3100.000000000 1489.053344727 +v 2300.000000000 3100.000000000 1458.583862305 +v 2400.000000000 3100.000000000 1425.008911133 +v 2400.000000000 3000.000000000 1402.342529297 +v 2400.000000000 3100.000000000 1425.008911133 +v 2400.000000000 3000.000000000 1402.342529297 +v 2200.000000000 3163.647705078 1500.000000000 +v 2400.000000000 300.000000000 684.370544434 +v 2500.000000000 300.000000000 661.730712891 +v 2600.000000000 300.000000000 636.728698730 +v 2700.000000000 300.000000000 607.825073242 +v 2400.000000000 3100.000000000 1425.008911133 +v 2400.000000000 3100.000000000 1425.008911133 +v 2400.000000000 3100.000000000 1425.008911133 +v 2400.000000000 3200.000000000 1444.543334961 +v 200.000000000 2800.000000000 1503.120361328 +v 300.000000000 2800.000000000 1504.686279297 +v 400.000000000 2800.000000000 1507.818115234 +v 500.000000000 2800.000000000 1511.719726562 +v 600.000000000 2800.000000000 1514.055419922 +v 700.000000000 2800.000000000 1516.417602539 +v 600.000000000 2741.933593750 1500.000000000 +v 600.000000000 2800.000000000 1514.055419922 +v 600.000000000 2741.933593750 1500.000000000 +v 800.000000000 2800.000000000 1519.522949219 +v 900.000000000 2800.000000000 1522.654785156 +v 1000.000000000 2800.000000000 1524.220703125 +v 900.000000000 2719.475097656 1500.000000000 +v 900.000000000 2800.000000000 1522.654785156 +v 900.000000000 2719.475097656 1500.000000000 +v 1100.000000000 2800.000000000 1524.990478516 +v 1200.000000000 2800.000000000 1524.990478516 +v 1100.000000000 2713.538818359 1500.000000000 +v 1100.000000000 2800.000000000 1524.990478516 +v 1100.000000000 2713.538818359 1500.000000000 +v 1300.000000000 2800.000000000 1524.220703125 +v 1200.000000000 2715.781494141 1500.000000000 +v 1200.000000000 2800.000000000 1524.990478516 +v 1200.000000000 2715.781494141 1500.000000000 +v 1400.000000000 2800.000000000 1523.424438477 +v 1300.000000000 2720.508300781 1500.000000000 +v 1400.000000000 2800.000000000 1523.424438477 +v 1500.000000000 2800.000000000 1520.319091797 +v 1400.000000000 2800.000000000 1523.424438477 +v 1600.000000000 2800.000000000 1514.851562500 +v 1700.000000000 2800.000000000 1508.587890625 +v 3000.000000000 100.000000000 464.050201416 +v 100.000000000 2900.000000000 1522.654785156 +v 200.000000000 2900.000000000 1524.220703125 +v 300.000000000 2900.000000000 1526.556396484 +v 400.000000000 2900.000000000 1529.688232422 +v 300.000000000 2800.000000000 1504.686279297 +v 300.000000000 2900.000000000 1526.556396484 +v 300.000000000 2800.000000000 1504.686279297 +v 400.000000000 2800.000000000 1507.818115234 +v 500.000000000 2900.000000000 1534.386108398 +v 400.000000000 2800.000000000 1507.818115234 +v 400.000000000 2800.000000000 1507.818115234 +v 500.000000000 2800.000000000 1511.719726562 +v 600.000000000 2900.000000000 1537.491455078 +v 500.000000000 2800.000000000 1511.719726562 +v 500.000000000 2800.000000000 1511.719726562 +v 600.000000000 2800.000000000 1514.055419922 +v 700.000000000 2900.000000000 1540.623291016 +v 600.000000000 2800.000000000 1514.055419922 +v 600.000000000 2800.000000000 1514.055419922 +v 800.000000000 2900.000000000 1544.524902344 +v 900.000000000 2900.000000000 1548.426513672 +v 1000.000000000 2900.000000000 1550.788696289 +v 900.000000000 2800.000000000 1522.654785156 +v 900.000000000 2900.000000000 1548.426513672 +v 900.000000000 2800.000000000 1522.654785156 +v 1100.000000000 2900.000000000 1553.124389648 +v 1200.000000000 2900.000000000 1553.124389648 +v 1100.000000000 2800.000000000 1524.990478516 +v 1200.000000000 2900.000000000 1553.124389648 +v 1300.000000000 2900.000000000 1553.894042969 +v 1200.000000000 2900.000000000 1553.124389648 +v 1200.000000000 2800.000000000 1524.990478516 +v 1300.000000000 2900.000000000 1553.894042969 +v 1400.000000000 2900.000000000 1553.894042969 +v 1300.000000000 2900.000000000 1553.894042969 +v 1500.000000000 2900.000000000 1549.992431641 +v 1400.000000000 2800.000000000 1523.424438477 +v 1500.000000000 2900.000000000 1549.992431641 +v 1600.000000000 2900.000000000 1546.090820312 +v 1500.000000000 2900.000000000 1549.992431641 +v 1700.000000000 2900.000000000 1539.057373047 +v 1800.000000000 2900.000000000 1528.122314453 +v 1900.000000000 2900.000000000 1514.055419922 +v 2400.000000000 395.286499023 700.000000000 +v 100.000000000 3000.000000000 1542.958984375 +v 200.000000000 3000.000000000 1543.755249023 +v 300.000000000 3000.000000000 1546.887084961 +v 200.000000000 2900.000000000 1524.220703125 +v 200.000000000 3000.000000000 1543.755249023 +v 200.000000000 2900.000000000 1524.220703125 +v 300.000000000 2900.000000000 1526.556396484 +v 400.000000000 3000.000000000 1550.788696289 +v 300.000000000 2900.000000000 1526.556396484 +v 300.000000000 2900.000000000 1526.556396484 +v 500.000000000 3000.000000000 1553.894042969 +v 600.000000000 3000.000000000 1557.822143555 +v 700.000000000 3000.000000000 1562.493408203 +v 800.000000000 3000.000000000 1568.757202148 +v 900.000000000 3000.000000000 1572.658813477 +v 1000.000000000 3000.000000000 1576.560424805 +v 900.000000000 2900.000000000 1548.426513672 +v 1000.000000000 3000.000000000 1576.560424805 +v 1100.000000000 3000.000000000 1578.896118164 +v 1000.000000000 3000.000000000 1576.560424805 +v 1200.000000000 3000.000000000 1581.258300781 +v 1300.000000000 3000.000000000 1583.593872070 +v 1200.000000000 2900.000000000 1553.124389648 +v 1200.000000000 3000.000000000 1581.258300781 +v 1200.000000000 2900.000000000 1553.124389648 +v 1400.000000000 3000.000000000 1582.027954102 +v 1300.000000000 2900.000000000 1553.894042969 +v 1300.000000000 3000.000000000 1583.593872070 +v 1300.000000000 2900.000000000 1553.894042969 +v 1500.000000000 3000.000000000 1578.126342773 +v 1600.000000000 3000.000000000 1574.224731445 +v 1600.000000000 2900.000000000 1546.090820312 +v 1700.000000000 3000.000000000 1565.625366211 +v 1600.000000000 2900.000000000 1546.090820312 +v 1700.000000000 3000.000000000 1565.625366211 +v 1800.000000000 3000.000000000 1553.894042969 +v 1700.000000000 3000.000000000 1565.625366211 +v 1900.000000000 3000.000000000 1541.393066406 +v 2000.000000000 3000.000000000 1518.753173828 +v 2400.000000000 300.000000000 684.370544434 +v 100.000000000 3100.000000000 1560.927490234 +v 200.000000000 3100.000000000 1560.927490234 +v 300.000000000 3100.000000000 1563.289672852 +v 200.000000000 3000.000000000 1543.755249023 +v 300.000000000 3100.000000000 1563.289672852 +v 400.000000000 3100.000000000 1567.960937500 +v 300.000000000 3100.000000000 1563.289672852 +v 500.000000000 3100.000000000 1572.658813477 +v 600.000000000 3100.000000000 1578.126342773 +v 700.000000000 3100.000000000 1583.593872070 +v 800.000000000 3100.000000000 1589.061401367 +v 900.000000000 3100.000000000 1594.528930664 +v 1000.000000000 3100.000000000 1599.226806641 +v 1100.000000000 3081.803710938 1600.000000000 +v 1014.141540527 3100.000000000 1600.000000000 +v 1000.000000000 3100.000000000 1599.226806641 +v 1000.000000000 3000.000000000 1576.560424805 +v 1000.000000000 3100.000000000 1599.226806641 +v 1200.000000000 3068.556396484 1600.000000000 +v 1300.000000000 3063.659423828 1600.000000000 +v 1200.000000000 3000.000000000 1581.258300781 +v 1200.000000000 3068.556396484 1600.000000000 +v 1200.000000000 3068.556396484 1600.000000000 +v 1400.000000000 3065.740966797 1600.000000000 +v 1400.000000000 3000.000000000 1582.027954102 +v 1400.000000000 3000.000000000 1582.027954102 +v 1500.000000000 3080.012939453 1600.000000000 +v 1400.000000000 3065.740966797 1600.000000000 +v 1400.000000000 3065.740966797 1600.000000000 +v 1600.000000000 3094.284912109 1600.000000000 +v 1615.369750977 3100.000000000 1600.000000000 +v 1700.000000000 3100.000000000 1591.397094727 +v 1800.000000000 3100.000000000 1578.896118164 +v 1700.000000000 3000.000000000 1565.625366211 +v 1700.000000000 3100.000000000 1591.397094727 +v 1700.000000000 3000.000000000 1565.625366211 +v 1900.000000000 3100.000000000 1562.493408203 +v 2000.000000000 3100.000000000 1539.853637695 +v 2100.000000000 3100.000000000 1516.417602539 +v 2323.023681641 300.000000000 700.000000000 +v 2403.298828125 400.000000000 700.000000000 +v 2500.000000000 400.000000000 677.337097168 +v 2400.000000000 300.000000000 684.370544434 +v 2500.000000000 300.000000000 661.730712891 +v 300.000000000 3100.000000000 1563.289672852 +v 400.000000000 3200.000000000 1582.824218750 +v 2400.000000000 300.000000000 684.370544434 +v 400.000000000 3200.000000000 1582.824218750 +v 2600.000000000 400.000000000 654.697265625 +v 2500.000000000 300.000000000 661.730712891 +v 800.000000000 3160.875976562 1600.000000000 +v 2500.000000000 300.000000000 661.730712891 +v 900.000000000 3128.007080078 1600.000000000 +v 1000.000000000 3103.415039062 1600.000000000 +v 1014.141540527 3100.000000000 1600.000000000 +v 1700.000000000 3140.770996094 1600.000000000 +v 2600.000000000 300.000000000 636.728698730 +v 2700.000000000 400.000000000 628.129272461 +v 1800.000000000 3200.000000000 1597.660888672 +v 1700.000000000 3100.000000000 1591.397094727 +v 2600.000000000 300.000000000 636.728698730 +v 1800.000000000 3200.000000000 1597.660888672 +v 2600.000000000 300.000000000 636.728698730 +v 2700.000000000 300.000000000 607.825073242 +v 2700.000000000 300.000000000 607.825073242 +v 1100.000000000 3100.000000000 1604.694335938 +v 1200.000000000 3100.000000000 1608.596069336 +v 1300.000000000 3100.000000000 1609.365600586 +v 1200.000000000 3068.556396484 1600.000000000 +v 1300.000000000 3100.000000000 1609.365600586 +v 1400.000000000 3100.000000000 1609.365600586 +v 1300.000000000 3100.000000000 1609.365600586 +v 1500.000000000 3100.000000000 1605.463989258 +v 1400.000000000 3065.740966797 1600.000000000 +v 1400.000000000 3100.000000000 1609.365600586 +v 1400.000000000 3065.740966797 1600.000000000 +v 1600.000000000 3100.000000000 1601.562255859 +v 2700.000000000 300.000000000 607.825073242 +v 2725.681640625 300.000000000 600.000000000 +v 2472.380615234 500.000000000 700.000000000 +v 2500.000000000 500.000000000 693.739685059 +v 1014.141540527 3100.000000000 1600.000000000 +v 1000.000000000 3200.000000000 1621.866577148 +v 1000.000000000 3200.000000000 1621.866577148 +v 2600.000000000 500.000000000 669.533874512 +v 2700.000000000 500.000000000 645.301574707 +v 2600.000000000 400.000000000 654.697265625 +v 1300.000000000 3100.000000000 1609.365600586 +v 1400.000000000 3200.000000000 1632.801635742 +v 2600.000000000 500.000000000 669.533874512 +v 1400.000000000 3200.000000000 1632.801635742 +v 1400.000000000 3100.000000000 1609.365600586 +v 1500.000000000 3200.000000000 1630.466064453 +v 2600.000000000 400.000000000 654.697265625 +v 1500.000000000 3200.000000000 1630.466064453 +v 2700.000000000 400.000000000 628.129272461 +f 2 1 3 +f 5 4 1337 +f 1308 1021 1337 +f 4 1308 1337 +f 6 1308 4 +f 1308 6 2212 +f 2212 6 7 +f 2212 7 1291 +f 1291 7 8 +f 8 2 3 +f 9 8 3 +f 1291 8 9 +f 1021 1308 1361 +f 1590 1528 1361 +f 1308 1590 1361 +f 2212 1590 1308 +f 1590 2212 1762 +f 1762 2212 1291 +f 1762 1291 10 +f 10 1291 9 +f 1528 1590 202 +f 748 212 202 +f 1590 748 202 +f 1762 748 1590 +f 748 1762 11 +f 11 1762 10 +f 212 748 1092 +f 12 1288 1092 +f 748 12 1092 +f 11 12 748 +f 1288 12 13 +f 15 14 1526 +f 1526 14 16 +f 18 17 1764 +f 2030 1819 1764 +f 17 2030 1764 +f 19 2030 17 +f 2030 19 196 +f 196 19 20 +f 20 5 1337 +f 207 20 1337 +f 196 20 207 +f 207 1337 1021 +f 21 15 1526 +f 1819 2030 216 +f 220 218 216 +f 2030 220 216 +f 196 220 2030 +f 220 196 222 +f 222 196 207 +f 207 1021 1361 +f 224 207 1361 +f 222 207 224 +f 224 1361 1528 +f 218 220 225 +f 228 226 225 +f 220 228 225 +f 222 228 220 +f 228 222 232 +f 232 222 224 +f 224 1528 202 +f 234 224 202 +f 232 224 234 +f 234 202 212 +f 267 240 236 +f 236 294 238 +f 335 228 314 +f 314 228 232 +f 314 232 416 +f 416 232 234 +f 234 212 1092 +f 429 234 1092 +f 416 234 429 +f 429 1092 1288 +f 236 238 435 +f 453 448 454 +f 457 453 459 +f 461 453 463 +f 453 467 465 +f 465 469 471 +f 465 559 473 +f 605 582 743 +f 429 1288 13 +f 22 429 13 +f 755 752 756 +f 448 453 821 +f 857 835 821 +f 453 857 821 +f 465 857 453 +f 857 465 1016 +f 1016 465 473 +f 1016 473 23 +f 1028 1025 1030 +f 835 857 1031 +f 1076 1062 1031 +f 857 1076 1031 +f 1016 1076 857 +f 1076 1016 24 +f 24 1016 23 +f 1062 1076 1281 +f 1281 1076 1285 +f 1285 1076 25 +f 25 1076 24 +f 1281 1285 1290 +f 1285 25 1290 +f 1290 25 26 +f 1526 16 1300 +f 1300 16 27 +f 1300 27 1318 +f 1318 27 28 +f 30 29 1527 +f 29 31 1527 +f 1527 31 1533 +f 31 1559 1533 +f 32 1559 31 +f 1559 32 1633 +f 1633 32 33 +f 1633 33 1763 +f 1763 33 34 +f 34 18 1764 +f 1765 34 1764 +f 1763 34 1765 +f 1765 1764 1819 +f 21 1768 35 +f 1526 1768 21 +f 1786 1768 1526 +f 1300 1786 1526 +f 1786 1300 1318 +f 1541 1559 1868 +f 1971 1911 1868 +f 1559 1971 1868 +f 1633 1971 1559 +f 1971 1633 1972 +f 1972 1633 1763 +f 1972 1763 1973 +f 1973 1763 1765 +f 1765 1819 216 +f 1992 1765 216 +f 1973 1765 1992 +f 1992 216 218 +f 36 35 2070 +f 2070 35 1768 +f 1911 1971 2107 +f 2173 2147 2107 +f 1971 2173 2107 +f 1972 2173 1971 +f 2173 1972 2174 +f 2174 1972 1973 +f 2174 1973 2175 +f 2175 1973 1992 +f 1992 218 225 +f 2176 1992 225 +f 2175 1992 2176 +f 2176 225 226 +f 37 36 2070 +f 2336 2296 2256 +f 2338 2337 2256 +f 2339 2338 2256 +f 2340 2338 2343 +f 2338 2346 2345 +f 2345 2348 2353 +f 2345 2357 2354 +f 2354 2359 2360 +f 2354 2361 236 +f 236 2374 2375 +f 2337 2338 2376 +f 2376 2338 2377 +f 2377 2338 2381 +f 2381 2338 2345 +f 2386 2383 2382 +f 2382 2390 2392 +f 2354 236 435 +f 161 162 163 +f 2382 164 161 +f 161 165 448 +f 168 167 166 +f 170 169 166 +f 171 170 166 +f 172 170 173 +f 170 175 174 +f 174 176 2382 +f 174 2382 177 +f 177 2382 161 +f 161 448 821 +f 178 161 821 +f 177 161 178 +f 178 821 835 +f 169 170 179 +f 181 180 179 +f 170 181 179 +f 174 181 170 +f 181 174 182 +f 182 174 177 +f 182 177 183 +f 183 177 178 +f 178 835 1031 +f 184 178 1031 +f 183 178 184 +f 184 1031 1062 +f 180 181 185 +f 185 181 186 +f 186 181 187 +f 187 181 182 +f 187 182 188 +f 188 182 183 +f 188 183 189 +f 189 183 184 +f 189 184 1281 +f 1281 184 1062 +f 185 186 190 +f 192 191 190 +f 186 192 190 +f 187 192 186 +f 192 187 193 +f 193 187 188 +f 193 188 194 +f 194 188 189 +f 189 1281 1290 +f 195 189 1290 +f 194 189 195 +f 195 1290 38 +f 38 1290 26 +f 191 192 197 +f 199 198 197 +f 192 199 197 +f 193 199 192 +f 199 193 200 +f 200 193 194 +f 200 194 201 +f 201 194 195 +f 201 195 39 +f 39 195 38 +f 198 199 203 +f 203 199 204 +f 204 199 205 +f 205 199 200 +f 205 200 206 +f 206 200 201 +f 206 201 40 +f 40 201 39 +f 203 204 208 +f 210 209 208 +f 204 210 208 +f 205 210 204 +f 210 205 211 +f 211 205 206 +f 211 206 41 +f 41 206 40 +f 209 210 213 +f 215 214 213 +f 210 215 213 +f 211 215 210 +f 215 211 42 +f 42 211 41 +f 214 215 217 +f 215 42 217 +f 217 42 43 +f 1318 28 219 +f 219 28 44 +f 45 221 223 +f 219 45 223 +f 44 45 219 +f 221 45 46 +f 48 47 227 +f 47 49 227 +f 227 49 229 +f 231 230 229 +f 49 231 229 +f 50 231 49 +f 231 50 233 +f 233 50 51 +f 233 51 235 +f 235 51 52 +f 235 52 237 +f 237 52 53 +f 237 53 239 +f 239 53 54 +f 54 30 1527 +f 241 54 1527 +f 239 54 241 +f 241 1527 242 +f 1768 1786 243 +f 243 1786 1318 +f 219 243 1318 +f 244 243 219 +f 244 219 245 +f 245 219 223 +f 230 231 246 +f 248 247 246 +f 231 248 246 +f 233 248 231 +f 248 233 249 +f 249 233 235 +f 249 235 250 +f 250 235 237 +f 250 237 251 +f 251 237 239 +f 251 239 252 +f 252 239 241 +f 252 241 253 +f 253 241 242 +f 254 242 1868 +f 253 242 254 +f 254 1868 1911 +f 2070 1768 255 +f 255 1768 243 +f 244 256 257 +f 255 244 257 +f 243 244 255 +f 256 244 245 +f 247 248 258 +f 260 259 258 +f 248 260 258 +f 249 260 248 +f 260 249 261 +f 261 249 250 +f 261 250 262 +f 262 250 251 +f 262 251 263 +f 263 251 252 +f 263 252 264 +f 264 252 253 +f 264 253 265 +f 265 253 254 +f 254 1911 2107 +f 266 254 2107 +f 265 254 266 +f 266 2107 2147 +f 55 37 2070 +f 255 55 2070 +f 268 55 255 +f 268 255 269 +f 269 255 257 +f 259 260 270 +f 272 271 270 +f 260 272 270 +f 261 272 260 +f 272 261 273 +f 273 261 262 +f 273 262 274 +f 274 262 263 +f 277 276 275 +f 275 278 279 +f 275 281 280 +f 280 282 283 +f 280 285 284 +f 284 286 287 +f 290 289 2256 +f 288 291 2256 +f 284 292 288 +f 288 2256 2337 +f 268 293 295 +f 56 268 295 +f 55 268 56 +f 293 268 269 +f 298 297 296 +f 300 299 296 +f 301 300 296 +f 302 300 303 +f 300 305 304 +f 304 306 307 +f 304 309 308 +f 308 310 275 +f 308 275 311 +f 311 275 280 +f 311 280 312 +f 312 280 284 +f 312 284 313 +f 313 284 288 +f 313 288 2376 +f 2376 288 2337 +f 57 56 315 +f 315 56 295 +f 299 300 316 +f 318 317 316 +f 300 318 316 +f 304 318 300 +f 318 304 319 +f 319 304 308 +f 319 308 320 +f 320 308 311 +f 323 322 321 +f 321 324 325 +f 321 327 326 +f 326 328 329 +f 332 331 166 +f 330 333 166 +f 326 334 330 +f 330 166 169 +f 58 57 315 +f 317 318 336 +f 338 337 339 +f 340 338 341 +f 342 338 343 +f 338 345 344 +f 344 346 347 +f 344 349 348 +f 348 350 321 +f 348 321 351 +f 351 321 326 +f 351 326 352 +f 352 326 330 +f 330 169 179 +f 353 330 179 +f 352 330 353 +f 337 338 354 +f 356 355 354 +f 338 356 354 +f 344 356 338 +f 356 344 357 +f 357 344 348 +f 357 348 358 +f 358 348 351 +f 358 351 359 +f 359 351 352 +f 359 352 360 +f 360 352 353 +f 360 353 185 +f 355 356 361 +f 363 362 361 +f 356 363 361 +f 357 363 356 +f 363 357 364 +f 364 357 358 +f 364 358 365 +f 365 358 359 +f 365 359 366 +f 366 359 360 +f 360 185 190 +f 367 360 190 +f 366 360 367 +f 367 190 191 +f 362 363 368 +f 370 369 368 +f 363 370 368 +f 364 370 363 +f 370 364 371 +f 371 364 365 +f 371 365 372 +f 372 365 366 +f 372 366 373 +f 373 366 367 +f 367 191 197 +f 374 367 197 +f 373 367 374 +f 374 197 198 +f 369 370 375 +f 377 376 375 +f 370 377 375 +f 371 377 370 +f 377 371 378 +f 378 371 372 +f 378 372 379 +f 379 372 373 +f 379 373 380 +f 380 373 374 +f 380 374 203 +f 203 374 198 +f 376 377 381 +f 383 382 381 +f 377 383 381 +f 378 383 377 +f 383 378 384 +f 384 378 379 +f 384 379 385 +f 385 379 380 +f 380 203 208 +f 386 380 208 +f 385 380 386 +f 386 208 209 +f 382 383 387 +f 389 388 387 +f 383 389 387 +f 384 389 383 +f 389 384 390 +f 390 384 385 +f 390 385 391 +f 391 385 386 +f 386 209 213 +f 392 386 213 +f 391 386 392 +f 392 213 214 +f 395 394 393 +f 397 396 398 +f 400 399 393 +f 402 401 403 +f 406 405 404 +f 404 407 408 +f 404 410 409 +f 409 411 412 +f 392 214 217 +f 413 392 217 +f 409 414 415 +f 413 217 59 +f 59 217 43 +f 396 397 417 +f 419 418 417 +f 397 419 417 +f 420 419 397 +f 419 422 421 +f 421 423 424 +f 421 426 425 +f 427 409 428 +f 430 413 60 +f 60 413 59 +f 418 419 431 +f 433 432 431 +f 419 433 431 +f 421 433 419 +f 433 421 434 +f 434 421 425 +f 437 436 61 +f 61 438 439 +f 432 433 440 +f 442 441 443 +f 444 442 445 +f 446 442 447 +f 442 449 62 +f 62 450 61 +f 441 442 451 +f 63 452 451 +f 442 63 451 +f 62 63 442 +f 452 63 64 +f 223 221 455 +f 455 221 46 +f 65 455 46 +f 456 455 65 +f 456 65 458 +f 458 65 66 +f 458 66 460 +f 460 66 67 +f 460 67 462 +f 462 67 68 +f 462 68 464 +f 464 68 69 +f 464 69 466 +f 466 69 70 +f 466 70 468 +f 468 70 71 +f 468 71 470 +f 470 71 72 +f 470 72 472 +f 472 72 73 +f 73 48 227 +f 474 73 227 +f 472 73 474 +f 474 227 475 +f 475 227 229 +f 245 223 476 +f 476 223 455 +f 476 455 477 +f 477 455 456 +f 458 478 479 +f 477 458 479 +f 456 458 477 +f 458 460 478 +f 478 460 480 +f 460 462 480 +f 480 462 481 +f 462 464 481 +f 481 464 482 +f 484 483 482 +f 464 484 482 +f 466 484 464 +f 484 466 485 +f 485 466 468 +f 485 468 486 +f 486 468 470 +f 486 470 487 +f 487 470 472 +f 487 472 488 +f 488 472 474 +f 488 474 489 +f 489 474 475 +f 475 230 246 +f 490 475 246 +f 489 475 490 +f 490 246 247 +f 257 256 491 +f 491 256 245 +f 476 491 245 +f 492 491 476 +f 477 493 494 +f 492 477 494 +f 476 477 492 +f 493 477 479 +f 483 484 495 +f 497 496 495 +f 484 497 495 +f 485 497 484 +f 497 485 498 +f 498 485 486 +f 498 486 499 +f 499 486 487 +f 499 487 500 +f 500 487 488 +f 500 488 501 +f 501 488 489 +f 501 489 502 +f 502 489 490 +f 490 247 258 +f 503 490 258 +f 502 490 503 +f 503 258 259 +f 269 257 504 +f 504 257 491 +f 492 505 506 +f 504 492 506 +f 491 492 504 +f 505 492 494 +f 496 497 507 +f 509 508 507 +f 497 509 507 +f 498 509 497 +f 509 498 510 +f 510 498 499 +f 510 499 511 +f 511 499 500 +f 511 500 512 +f 512 500 501 +f 512 501 513 +f 513 501 502 +f 513 502 514 +f 514 502 503 +f 503 259 270 +f 515 503 270 +f 514 503 515 +f 515 270 271 +f 295 293 516 +f 293 517 516 +f 269 517 293 +f 518 517 269 +f 504 518 269 +f 518 504 506 +f 508 509 519 +f 519 509 520 +f 520 509 521 +f 521 509 510 +f 521 510 522 +f 522 510 511 +f 522 511 523 +f 523 511 512 +f 523 512 524 +f 524 512 513 +f 524 513 525 +f 525 513 514 +f 528 527 526 +f 526 529 530 +f 533 532 296 +f 531 534 296 +f 526 535 531 +f 531 296 299 +f 315 295 536 +f 536 295 516 +f 536 516 537 +f 537 516 517 +f 519 520 538 +f 538 520 539 +f 539 520 540 +f 540 520 521 +f 540 521 541 +f 541 521 522 +f 541 522 542 +f 542 522 523 +f 545 544 543 +f 543 546 547 +f 543 549 548 +f 548 550 551 +f 548 553 552 +f 552 554 526 +f 552 526 555 +f 555 526 531 +f 531 299 316 +f 556 531 316 +f 555 531 556 +f 556 316 317 +f 58 557 74 +f 315 557 58 +f 558 557 315 +f 536 558 315 +f 558 536 537 +f 538 539 560 +f 562 561 560 +f 539 562 560 +f 540 562 539 +f 562 540 563 +f 563 540 541 +f 566 565 564 +f 564 567 568 +f 564 570 569 +f 569 571 543 +f 569 543 572 +f 572 543 548 +f 572 548 573 +f 573 548 552 +f 573 552 574 +f 574 552 555 +f 574 555 575 +f 575 555 556 +f 556 317 336 +f 576 577 578 +f 580 579 576 +f 576 581 337 +f 75 74 583 +f 583 74 557 +f 562 563 584 +f 587 586 585 +f 589 588 585 +f 590 589 585 +f 564 589 591 +f 589 564 592 +f 592 564 569 +f 592 569 593 +f 593 569 572 +f 593 572 594 +f 594 572 573 +f 594 573 595 +f 595 573 574 +f 598 597 596 +f 596 599 600 +f 596 602 601 +f 601 603 576 +f 576 337 354 +f 604 576 354 +f 601 576 604 +f 604 354 355 +f 76 75 583 +f 588 589 606 +f 589 592 606 +f 606 592 607 +f 609 608 607 +f 592 609 607 +f 593 609 592 +f 612 611 610 +f 610 613 614 +f 610 616 615 +f 615 617 618 +f 615 620 619 +f 619 621 596 +f 619 596 622 +f 622 596 601 +f 622 601 623 +f 623 601 604 +f 604 355 361 +f 624 604 361 +f 623 604 624 +f 624 361 362 +f 608 609 625 +f 627 610 628 +f 629 610 626 +f 631 630 626 +f 610 631 626 +f 615 631 610 +f 631 615 632 +f 632 615 619 +f 632 619 633 +f 633 619 622 +f 633 622 634 +f 634 622 623 +f 634 623 635 +f 635 623 624 +f 624 362 368 +f 636 624 368 +f 635 624 636 +f 636 368 369 +f 630 631 637 +f 631 632 637 +f 637 632 638 +f 640 639 638 +f 632 640 638 +f 633 640 632 +f 640 633 641 +f 641 633 634 +f 641 634 642 +f 642 634 635 +f 642 635 643 +f 643 635 636 +f 636 369 375 +f 644 636 375 +f 643 636 644 +f 644 375 376 +f 639 640 645 +f 647 646 645 +f 640 647 645 +f 641 647 640 +f 647 641 648 +f 648 641 642 +f 648 642 649 +f 649 642 643 +f 649 643 650 +f 650 643 644 +f 644 376 381 +f 651 644 381 +f 650 644 651 +f 651 381 382 +f 647 648 652 +f 652 648 653 +f 655 654 653 +f 648 655 653 +f 649 655 648 +f 655 649 656 +f 656 649 650 +f 656 650 657 +f 657 650 651 +f 651 382 387 +f 658 651 387 +f 657 651 658 +f 658 387 388 +f 654 655 659 +f 661 660 662 +f 663 661 664 +f 665 661 666 +f 661 668 667 +f 667 669 670 +f 667 672 671 +f 671 673 674 +f 677 676 393 +f 675 678 393 +f 671 679 675 +f 681 680 396 +f 660 661 682 +f 684 683 685 +f 686 684 687 +f 688 684 689 +f 684 691 690 +f 690 692 693 +f 690 695 694 +f 694 696 697 +f 699 396 417 +f 698 700 417 +f 694 701 698 +f 698 417 418 +f 683 684 702 +f 704 703 702 +f 684 704 702 +f 690 704 684 +f 704 690 705 +f 705 690 694 +f 705 694 706 +f 706 694 698 +f 698 418 431 +f 707 698 431 +f 706 698 707 +f 707 431 432 +f 703 704 708 +f 710 709 708 +f 704 710 708 +f 705 710 704 +f 710 705 711 +f 711 705 706 +f 711 706 712 +f 712 706 707 +f 707 432 440 +f 713 707 440 +f 712 707 713 +f 715 714 441 +f 709 710 716 +f 718 717 716 +f 710 718 716 +f 711 718 710 +f 718 711 719 +f 719 711 712 +f 722 721 720 +f 720 723 724 +f 726 441 451 +f 725 727 451 +f 720 728 725 +f 725 451 452 +f 731 730 729 +f 733 732 734 +f 735 733 736 +f 737 733 738 +f 733 740 739 +f 739 741 720 +f 739 720 742 +f 742 720 725 +f 725 452 64 +f 77 725 64 +f 742 725 77 +f 732 733 744 +f 746 745 744 +f 733 746 744 +f 739 746 733 +f 746 739 747 +f 747 739 742 +f 747 742 78 +f 78 742 77 +f 745 746 749 +f 751 750 749 +f 746 751 749 +f 747 751 746 +f 751 747 79 +f 79 747 78 +f 750 751 753 +f 80 754 753 +f 751 80 753 +f 79 80 751 +f 754 80 81 +f 479 478 757 +f 757 478 758 +f 758 478 480 +f 758 480 759 +f 759 480 481 +f 759 481 760 +f 760 481 482 +f 760 482 483 +f 494 493 761 +f 761 493 479 +f 757 761 479 +f 762 761 757 +f 762 757 763 +f 763 757 758 +f 763 758 764 +f 764 758 759 +f 764 759 765 +f 765 759 760 +f 760 483 495 +f 766 760 495 +f 765 760 766 +f 766 495 496 +f 506 505 767 +f 767 505 494 +f 761 767 494 +f 768 767 761 +f 768 761 769 +f 769 761 762 +f 769 762 770 +f 770 762 763 +f 770 763 771 +f 771 763 764 +f 771 764 772 +f 772 764 765 +f 772 765 773 +f 773 765 766 +f 766 496 507 +f 774 766 507 +f 773 766 774 +f 774 507 508 +f 517 518 775 +f 775 518 506 +f 767 775 506 +f 776 775 767 +f 776 767 777 +f 777 767 768 +f 769 778 779 +f 777 769 779 +f 768 769 777 +f 769 770 778 +f 778 770 780 +f 782 781 780 +f 770 782 780 +f 771 782 770 +f 782 771 783 +f 783 771 772 +f 783 772 784 +f 784 772 773 +f 784 773 785 +f 785 773 774 +f 785 774 519 +f 519 774 508 +f 537 517 786 +f 786 517 775 +f 786 775 787 +f 787 775 776 +f 777 788 789 +f 787 777 789 +f 776 777 787 +f 788 777 779 +f 781 782 790 +f 790 782 791 +f 791 782 792 +f 792 782 783 +f 792 783 793 +f 793 783 784 +f 793 784 794 +f 794 784 785 +f 794 785 538 +f 538 785 519 +f 557 558 795 +f 795 558 537 +f 786 795 537 +f 796 795 786 +f 787 797 798 +f 796 787 798 +f 786 787 796 +f 797 787 789 +f 790 791 799 +f 799 791 800 +f 800 791 801 +f 801 791 792 +f 801 792 802 +f 802 792 793 +f 802 793 803 +f 803 793 794 +f 794 538 560 +f 804 794 560 +f 803 794 804 +f 804 560 561 +f 583 557 805 +f 805 557 795 +f 796 806 807 +f 805 796 807 +f 795 796 805 +f 806 796 798 +f 799 800 808 +f 808 800 809 +f 809 800 810 +f 810 800 801 +f 810 801 811 +f 811 801 802 +f 811 802 812 +f 812 802 803 +f 812 803 813 +f 813 803 804 +f 804 561 584 +f 814 804 584 +f 813 804 814 +f 817 816 815 +f 815 818 585 +f 815 585 588 +f 76 819 82 +f 583 819 76 +f 820 819 583 +f 805 820 583 +f 820 805 807 +f 808 809 822 +f 824 823 822 +f 809 824 822 +f 810 824 809 +f 824 810 825 +f 825 810 811 +f 825 811 826 +f 826 811 812 +f 826 812 827 +f 827 812 813 +f 827 813 828 +f 828 813 814 +f 831 830 829 +f 829 832 815 +f 815 588 606 +f 833 815 606 +f 829 815 833 +f 833 606 834 +f 834 606 607 +f 834 607 608 +f 83 82 836 +f 836 82 819 +f 823 824 837 +f 824 825 837 +f 837 825 838 +f 840 839 838 +f 825 840 838 +f 826 840 825 +f 840 826 841 +f 841 826 827 +f 841 827 842 +f 842 827 828 +f 845 844 843 +f 843 846 829 +f 843 829 847 +f 847 829 833 +f 847 833 848 +f 848 833 834 +f 834 608 625 +f 849 850 851 +f 853 852 849 +f 849 855 854 +f 854 856 626 +f 854 626 630 +f 84 83 836 +f 839 840 858 +f 860 859 858 +f 840 860 858 +f 841 860 840 +f 860 841 861 +f 861 841 842 +f 864 863 862 +f 862 865 843 +f 862 843 866 +f 866 843 847 +f 869 868 867 +f 867 870 871 +f 867 873 872 +f 872 874 849 +f 872 849 875 +f 875 849 854 +f 854 630 637 +f 876 854 637 +f 875 854 876 +f 876 637 877 +f 877 637 638 +f 877 638 639 +f 859 860 878 +f 860 861 878 +f 878 861 879 +f 881 862 882 +f 883 862 880 +f 885 884 886 +f 887 885 888 +f 889 885 890 +f 885 892 891 +f 891 893 867 +f 891 867 894 +f 894 867 872 +f 894 872 895 +f 895 872 875 +f 895 875 896 +f 896 875 876 +f 896 876 897 +f 897 876 877 +f 877 639 645 +f 898 877 645 +f 897 877 898 +f 898 645 646 +f 884 885 899 +f 885 891 899 +f 899 891 900 +f 891 894 900 +f 900 894 901 +f 903 902 901 +f 894 903 901 +f 895 903 894 +f 903 895 904 +f 904 895 896 +f 904 896 905 +f 905 896 897 +f 905 897 906 +f 906 897 898 +f 898 646 652 +f 907 898 652 +f 906 898 907 +f 907 652 908 +f 908 652 653 +f 908 653 654 +f 902 903 909 +f 903 904 909 +f 909 904 910 +f 912 911 910 +f 904 912 910 +f 905 912 904 +f 912 905 913 +f 913 905 906 +f 913 906 914 +f 914 906 907 +f 914 907 915 +f 915 907 908 +f 908 654 659 +f 916 908 659 +f 915 908 916 +f 918 917 660 +f 911 912 919 +f 912 913 919 +f 919 913 920 +f 922 921 920 +f 913 922 920 +f 914 922 913 +f 925 924 923 +f 923 926 927 +f 923 929 928 +f 928 930 931 +f 933 660 682 +f 932 934 682 +f 928 935 932 +f 937 936 683 +f 940 939 938 +f 942 941 938 +f 943 942 938 +f 923 942 944 +f 947 946 945 +f 945 948 949 +f 945 951 950 +f 950 952 953 +f 955 683 702 +f 954 956 702 +f 950 957 954 +f 954 702 703 +f 960 959 958 +f 962 945 958 +f 958 945 961 +f 964 963 961 +f 945 964 961 +f 950 964 945 +f 964 950 965 +f 965 950 954 +f 954 703 708 +f 966 954 708 +f 965 954 966 +f 966 708 709 +f 963 964 967 +f 969 968 967 +f 964 969 967 +f 965 969 964 +f 969 965 970 +f 970 965 966 +f 966 709 716 +f 971 966 716 +f 970 966 971 +f 971 716 717 +f 968 969 972 +f 974 973 972 +f 969 974 972 +f 970 974 969 +f 974 970 975 +f 975 970 971 +f 971 717 977 +f 976 971 978 +f 975 971 976 +f 980 979 732 +f 983 982 981 +f 985 984 981 +f 986 985 981 +f 987 985 988 +f 991 990 989 +f 989 992 993 +f 995 732 744 +f 994 996 744 +f 989 997 994 +f 994 744 745 +f 1000 999 998 +f 1002 1001 998 +f 1003 1002 998 +f 989 1002 1004 +f 1002 989 1005 +f 1005 989 994 +f 994 745 749 +f 1006 994 749 +f 1005 994 1006 +f 1006 749 750 +f 1001 1002 1007 +f 1009 1008 1007 +f 1002 1009 1007 +f 1005 1009 1002 +f 1009 1005 1010 +f 1010 1005 1006 +f 1006 750 753 +f 1011 1006 753 +f 1010 1006 1011 +f 1011 753 754 +f 1008 1009 1012 +f 1012 1009 1013 +f 1013 1009 1014 +f 1014 1009 1010 +f 1014 1010 1015 +f 1015 1010 1011 +f 1011 754 81 +f 85 1011 81 +f 1015 1011 85 +f 1012 1013 1017 +f 1019 1018 1017 +f 1013 1019 1017 +f 1014 1019 1013 +f 1019 1014 1020 +f 1020 1014 1015 +f 1020 1015 86 +f 86 1015 85 +f 1018 1019 1022 +f 1024 1023 1022 +f 1019 1024 1022 +f 1020 1024 1019 +f 1024 1020 87 +f 87 1020 86 +f 1023 1024 1026 +f 88 1027 1026 +f 1024 88 1026 +f 87 88 1024 +f 1027 88 1029 +f 1029 88 89 +f 1029 89 90 +f 779 778 1032 +f 1032 778 1033 +f 1033 778 780 +f 1033 780 781 +f 789 788 1034 +f 1034 788 779 +f 1032 1034 779 +f 1035 1034 1032 +f 1035 1032 1036 +f 1036 1032 1033 +f 1036 1033 790 +f 790 1033 781 +f 798 797 1037 +f 1037 797 789 +f 1034 1037 789 +f 1038 1037 1034 +f 1038 1034 1039 +f 1039 1034 1035 +f 1039 1035 1040 +f 1040 1035 1036 +f 1040 1036 799 +f 799 1036 790 +f 807 806 1041 +f 1041 806 798 +f 1037 1041 798 +f 1042 1041 1037 +f 1042 1037 1043 +f 1043 1037 1038 +f 1043 1038 1044 +f 1044 1038 1039 +f 1044 1039 1045 +f 1045 1039 1040 +f 1045 1040 808 +f 808 1040 799 +f 819 820 1046 +f 1046 820 807 +f 1041 1046 807 +f 1047 1046 1041 +f 1047 1041 1048 +f 1048 1041 1042 +f 1048 1042 1049 +f 1049 1042 1043 +f 1049 1043 1050 +f 1050 1043 1044 +f 1050 1044 1051 +f 1051 1044 1045 +f 1045 808 822 +f 1052 1045 822 +f 1051 1045 1052 +f 1052 822 823 +f 836 819 1053 +f 1053 819 1046 +f 1053 1046 1054 +f 1054 1046 1047 +f 1054 1047 1055 +f 1055 1047 1048 +f 1055 1048 1056 +f 1056 1048 1049 +f 1056 1049 1057 +f 1057 1049 1050 +f 1057 1050 1058 +f 1058 1050 1051 +f 1058 1051 1059 +f 1059 1051 1052 +f 1052 823 837 +f 1060 1052 837 +f 1059 1052 1060 +f 1060 837 1061 +f 1061 837 838 +f 1061 838 839 +f 91 84 836 +f 1053 91 836 +f 1063 91 1053 +f 1054 1064 1065 +f 1063 1054 1065 +f 1053 1054 1063 +f 1054 1055 1064 +f 1064 1055 1066 +f 1055 1056 1066 +f 1066 1056 1067 +f 1069 1068 1067 +f 1056 1069 1067 +f 1057 1069 1056 +f 1069 1057 1070 +f 1070 1057 1058 +f 1070 1058 1071 +f 1071 1058 1059 +f 1071 1059 1072 +f 1072 1059 1060 +f 1072 1060 1073 +f 1073 1060 1061 +f 1061 839 858 +f 1074 1061 858 +f 1073 1061 1074 +f 1074 858 859 +f 1063 1075 1077 +f 92 1063 1077 +f 91 1063 92 +f 1075 1063 1065 +f 1068 1069 1078 +f 1080 1079 1078 +f 1069 1080 1078 +f 1070 1080 1069 +f 1080 1070 1081 +f 1081 1070 1071 +f 1081 1071 1082 +f 1082 1071 1072 +f 1082 1072 1083 +f 1083 1072 1073 +f 1083 1073 1084 +f 1084 1073 1074 +f 1074 859 878 +f 1085 1074 878 +f 1084 1074 1085 +f 1085 878 1086 +f 1086 878 879 +f 1086 879 1087 +f 1089 1088 880 +f 1091 1090 884 +f 93 92 1077 +f 1079 1080 1093 +f 1080 1081 1093 +f 1093 1081 1094 +f 1096 1095 1094 +f 1081 1096 1094 +f 1082 1096 1081 +f 1096 1082 1097 +f 1097 1082 1083 +f 1097 1083 1098 +f 1098 1083 1084 +f 1098 1084 1099 +f 1099 1084 1085 +f 1099 1085 1100 +f 1100 1085 1086 +f 1100 1086 1101 +f 1101 1086 1087 +f 1103 884 899 +f 1102 1104 899 +f 1106 1105 1102 +f 1102 899 1107 +f 1107 899 900 +f 1107 900 1108 +f 1108 900 901 +f 1108 901 902 +f 1095 1096 1109 +f 1096 1097 1109 +f 1109 1097 1110 +f 1112 1111 1110 +f 1097 1112 1110 +f 1098 1112 1097 +f 1112 1098 1113 +f 1113 1098 1099 +f 1113 1099 1114 +f 1114 1099 1100 +f 1117 1116 1115 +f 1115 1118 1119 +f 1122 1121 1120 +f 1120 1123 1102 +f 1120 1102 1124 +f 1124 1102 1107 +f 1124 1107 1125 +f 1125 1107 1108 +f 1108 902 909 +f 1126 1108 909 +f 1125 1108 1126 +f 1126 909 1127 +f 1127 909 910 +f 1127 910 911 +f 1111 1112 1128 +f 1112 1113 1128 +f 1128 1113 1129 +f 1113 1114 1129 +f 1132 1131 1130 +f 1134 1133 1135 +f 1136 1134 1137 +f 1138 1134 1139 +f 1134 1141 1140 +f 1140 1142 1120 +f 1140 1120 1143 +f 1143 1120 1124 +f 1143 1124 1144 +f 1144 1124 1125 +f 1144 1125 1145 +f 1145 1125 1126 +f 1145 1126 1146 +f 1146 1126 1127 +f 1127 911 919 +f 1147 1127 919 +f 1146 1127 1147 +f 1147 919 1148 +f 1148 919 920 +f 1148 920 921 +f 1133 1134 1149 +f 1134 1140 1149 +f 1149 1140 1150 +f 1140 1143 1150 +f 1150 1143 1151 +f 1153 1152 1151 +f 1143 1153 1151 +f 1144 1153 1143 +f 1153 1144 1154 +f 1154 1144 1145 +f 1154 1145 1155 +f 1155 1145 1146 +f 1155 1146 1156 +f 1156 1146 1147 +f 1156 1147 1157 +f 1157 1147 1148 +f 1160 1159 938 +f 1158 1161 938 +f 1163 1162 1158 +f 1158 938 941 +f 1152 1153 1164 +f 1153 1154 1164 +f 1164 1154 1165 +f 1154 1155 1165 +f 1165 1155 1166 +f 1168 1167 1169 +f 1170 1168 1171 +f 1172 1168 1173 +f 1168 1175 1174 +f 1174 1176 1177 +f 1174 1179 1178 +f 1178 1180 1158 +f 1183 1182 958 +f 1181 1184 958 +f 1186 1185 1181 +f 1181 958 1187 +f 1187 958 961 +f 1187 961 963 +f 1167 1168 1188 +f 1191 1190 1192 +f 1194 1193 1189 +f 1196 1195 1189 +f 1197 1196 1189 +f 1198 1196 1199 +f 1196 1201 1200 +f 1200 1202 1181 +f 1200 1181 1203 +f 1203 1181 1187 +f 1187 963 967 +f 1204 1187 967 +f 1203 1187 1204 +f 1204 967 968 +f 1207 1206 1205 +f 1210 1209 1205 +f 1205 1211 1208 +f 1213 1212 1208 +f 1214 1213 1208 +f 1215 1213 1216 +f 1213 1218 1217 +f 1217 1219 1220 +f 1204 968 972 +f 1221 1204 972 +f 1217 1222 1223 +f 1221 972 973 +f 1212 1213 1224 +f 1226 1225 1224 +f 1213 1226 1224 +f 1217 1226 1213 +f 1226 1217 1227 +f 1227 1217 1228 +f 1231 1230 981 +f 1229 1232 981 +f 1227 1233 1229 +f 1229 981 984 +f 1225 1226 1234 +f 1236 1235 1234 +f 1226 1236 1234 +f 1227 1236 1226 +f 1236 1227 1237 +f 1237 1227 1229 +f 1240 1239 998 +f 1238 1241 998 +f 1243 1242 1238 +f 1238 998 1001 +f 1235 1236 1244 +f 1246 1245 1244 +f 1236 1246 1244 +f 1237 1246 1236 +f 1249 1248 1247 +f 1247 1250 1238 +f 1238 1001 1007 +f 1251 1238 1007 +f 1247 1238 1251 +f 1251 1007 1008 +f 1254 1253 1252 +f 1256 1255 1252 +f 1257 1256 1252 +f 1247 1256 1258 +f 1256 1247 1259 +f 1259 1247 1251 +f 1259 1251 1012 +f 1012 1251 1008 +f 1255 1256 1260 +f 1260 1256 1261 +f 1261 1256 1262 +f 1262 1256 1259 +f 1259 1012 1017 +f 1263 1259 1017 +f 1262 1259 1263 +f 1263 1017 1018 +f 1260 1261 1264 +f 1266 1265 1264 +f 1261 1266 1264 +f 1262 1266 1261 +f 1266 1262 1267 +f 1267 1262 1263 +f 1263 1018 1022 +f 1268 1263 1022 +f 1267 1263 1268 +f 1268 1022 1023 +f 1265 1266 1269 +f 1271 1270 1269 +f 1266 1271 1269 +f 1267 1271 1266 +f 1271 1267 1272 +f 1272 1267 1268 +f 1268 1023 1026 +f 1273 1268 1026 +f 1272 1268 1273 +f 1273 1026 1027 +f 1270 1271 1274 +f 1276 1275 1274 +f 1271 1276 1274 +f 1272 1276 1271 +f 1276 1272 1277 +f 1277 1272 1273 +f 1277 1273 1029 +f 1029 1273 1027 +f 1275 1276 1278 +f 1278 1276 1279 +f 1279 1276 1280 +f 1280 1276 1277 +f 1277 1029 90 +f 94 1277 90 +f 1280 1277 94 +f 1278 1279 1282 +f 1284 1283 1282 +f 1279 1284 1282 +f 1280 1284 1279 +f 1284 1280 95 +f 95 1280 94 +f 1283 1284 1286 +f 96 1287 1286 +f 1284 96 1286 +f 95 96 1284 +f 1287 96 1289 +f 1289 96 97 +f 1289 97 98 +f 1065 1064 1292 +f 1292 1064 1293 +f 1293 1064 1066 +f 1293 1066 1294 +f 1294 1066 1067 +f 1294 1067 1068 +f 1077 1075 1295 +f 1295 1075 1065 +f 1292 1295 1065 +f 1296 1295 1292 +f 1296 1292 1297 +f 1297 1292 1293 +f 1297 1293 1298 +f 1298 1293 1294 +f 1294 1068 1078 +f 1299 1294 1078 +f 1298 1294 1299 +f 1299 1078 1079 +f 99 93 1077 +f 1295 99 1077 +f 1301 99 1295 +f 1301 1295 1302 +f 1302 1295 1296 +f 1302 1296 1303 +f 1303 1296 1297 +f 1303 1297 1304 +f 1304 1297 1298 +f 1304 1298 1305 +f 1305 1298 1299 +f 1299 1079 1093 +f 1306 1299 1093 +f 1305 1299 1306 +f 1306 1093 1307 +f 1307 1093 1094 +f 1307 1094 1095 +f 100 99 1309 +f 1309 99 1301 +f 1309 1301 1310 +f 1310 1301 1302 +f 1310 1302 1311 +f 1311 1302 1303 +f 1311 1303 1312 +f 1312 1303 1304 +f 1312 1304 1313 +f 1313 1304 1305 +f 1313 1305 1314 +f 1314 1305 1306 +f 1314 1306 1315 +f 1315 1306 1307 +f 1307 1095 1109 +f 1316 1307 1109 +f 1315 1307 1316 +f 1316 1109 1317 +f 1317 1109 1110 +f 1317 1110 1111 +f 101 100 1319 +f 1319 100 1309 +f 1319 1309 1320 +f 1320 1309 1310 +f 1320 1310 1321 +f 1321 1310 1311 +f 1321 1311 1322 +f 1322 1311 1312 +f 1322 1312 1323 +f 1323 1312 1313 +f 1323 1313 1324 +f 1324 1313 1314 +f 1324 1314 1325 +f 1325 1314 1315 +f 1325 1315 1326 +f 1326 1315 1316 +f 1326 1316 1327 +f 1327 1316 1317 +f 1317 1111 1128 +f 1328 1317 1128 +f 1327 1317 1328 +f 1328 1128 1329 +f 1329 1128 1129 +f 1332 1331 1330 +f 1330 1333 1130 +f 1335 1334 1133 +f 1319 1336 1338 +f 102 1319 1338 +f 101 1319 102 +f 1319 1320 1336 +f 1336 1320 1339 +f 1320 1321 1339 +f 1339 1321 1340 +f 1321 1322 1340 +f 1340 1322 1341 +f 1343 1342 1341 +f 1322 1343 1341 +f 1323 1343 1322 +f 1343 1323 1344 +f 1344 1323 1324 +f 1344 1324 1345 +f 1345 1324 1325 +f 1345 1325 1346 +f 1346 1325 1326 +f 1346 1326 1347 +f 1347 1326 1327 +f 1347 1327 1348 +f 1348 1327 1328 +f 1348 1328 1349 +f 1349 1328 1329 +f 1352 1351 1350 +f 1350 1353 1354 +f 1356 1133 1149 +f 1355 1357 1149 +f 1350 1358 1355 +f 1355 1149 1359 +f 1359 1149 1150 +f 1359 1150 1360 +f 1360 1150 1151 +f 1360 1151 1152 +f 103 102 1338 +f 1342 1343 1362 +f 1343 1344 1362 +f 1362 1344 1363 +f 1344 1345 1363 +f 1363 1345 1364 +f 1366 1365 1364 +f 1345 1366 1364 +f 1346 1366 1345 +f 1366 1346 1367 +f 1367 1346 1347 +f 1367 1347 1368 +f 1368 1347 1348 +f 1371 1370 1369 +f 1369 1372 1373 +f 1369 1375 1374 +f 1374 1376 1350 +f 1374 1350 1377 +f 1377 1350 1355 +f 1377 1355 1378 +f 1378 1355 1359 +f 1378 1359 1379 +f 1379 1359 1360 +f 1360 1152 1164 +f 1380 1360 1164 +f 1379 1360 1380 +f 1380 1164 1381 +f 1381 1164 1165 +f 1381 1165 1382 +f 1382 1165 1166 +f 1384 1383 1167 +f 1365 1366 1385 +f 1366 1367 1385 +f 1385 1367 1386 +f 1367 1368 1386 +f 1389 1388 1387 +f 1391 1369 1392 +f 1393 1369 1390 +f 1395 1394 1390 +f 1369 1395 1390 +f 1374 1395 1369 +f 1395 1374 1396 +f 1396 1374 1377 +f 1396 1377 1397 +f 1397 1377 1378 +f 1397 1378 1398 +f 1398 1378 1379 +f 1398 1379 1399 +f 1399 1379 1380 +f 1399 1380 1400 +f 1400 1380 1381 +f 1403 1402 1401 +f 1401 1404 1405 +f 1407 1167 1188 +f 1406 1408 1188 +f 1401 1409 1406 +f 1412 1411 1410 +f 1410 1413 1189 +f 1410 1189 1195 +f 1394 1395 1414 +f 1395 1396 1414 +f 1414 1396 1415 +f 1396 1397 1415 +f 1415 1397 1416 +f 1397 1398 1416 +f 1416 1398 1417 +f 1398 1399 1417 +f 1417 1399 1418 +f 1420 1419 1421 +f 1422 1420 1423 +f 1424 1420 1425 +f 1420 1427 1426 +f 1426 1428 1401 +f 1431 1430 1429 +f 1429 1432 1433 +f 1429 1435 1434 +f 1434 1436 1410 +f 1439 1438 1205 +f 1437 1440 1205 +f 1442 1441 1437 +f 1437 1205 1443 +f 1443 1205 1208 +f 1419 1420 1444 +f 1447 1446 1448 +f 1450 1449 1445 +f 1452 1429 1445 +f 1445 1429 1451 +f 1454 1453 1455 +f 1456 1454 1457 +f 1458 1454 1459 +f 1454 1461 1460 +f 1460 1462 1437 +f 1460 1437 1463 +f 1463 1437 1443 +f 1443 1212 1224 +f 1464 1443 1224 +f 1463 1443 1464 +f 1464 1224 1225 +f 1453 1454 1465 +f 1454 1460 1465 +f 1465 1460 1466 +f 1468 1467 1466 +f 1460 1468 1466 +f 1463 1468 1460 +f 1468 1463 1469 +f 1469 1463 1464 +f 1464 1225 1234 +f 1470 1464 1234 +f 1469 1464 1470 +f 1470 1234 1235 +f 1467 1468 1471 +f 1473 1472 1471 +f 1468 1473 1471 +f 1469 1473 1468 +f 1473 1469 1474 +f 1474 1469 1470 +f 1470 1235 1244 +f 1475 1470 1244 +f 1474 1470 1475 +f 1475 1244 1245 +f 1472 1473 1476 +f 1478 1477 1476 +f 1473 1478 1476 +f 1474 1478 1473 +f 1478 1474 1479 +f 1479 1474 1475 +f 1482 1481 1252 +f 1480 1483 1252 +f 1485 1484 1480 +f 1480 1252 1255 +f 1477 1478 1486 +f 1488 1487 1486 +f 1478 1488 1486 +f 1479 1488 1478 +f 1491 1490 1489 +f 1489 1492 1480 +f 1489 1480 1260 +f 1260 1480 1255 +f 1495 1494 1493 +f 1497 1496 1493 +f 1498 1497 1493 +f 1489 1497 1499 +f 1489 1260 1264 +f 1500 1489 1264 +f 1497 1489 1500 +f 1500 1264 1265 +f 1496 1497 1501 +f 1503 1502 1501 +f 1497 1503 1501 +f 1500 1503 1497 +f 1500 1265 1269 +f 1504 1500 1269 +f 1503 1500 1504 +f 1504 1269 1270 +f 1502 1503 1505 +f 1505 1503 1506 +f 1506 1503 1507 +f 1507 1503 1504 +f 1504 1270 1274 +f 1508 1504 1274 +f 1507 1504 1508 +f 1508 1274 1275 +f 1505 1506 1509 +f 1511 1510 1509 +f 1506 1511 1509 +f 1507 1511 1506 +f 1511 1507 1512 +f 1512 1507 1508 +f 1512 1508 1278 +f 1278 1508 1275 +f 1510 1511 1513 +f 1515 1514 1513 +f 1511 1515 1513 +f 1512 1515 1511 +f 1512 1278 1282 +f 1516 1512 1282 +f 1515 1512 1516 +f 1516 1282 1283 +f 1514 1515 1517 +f 1517 1515 1518 +f 1518 1515 1519 +f 1519 1515 1516 +f 1516 1283 1286 +f 1520 1516 1286 +f 1519 1516 1520 +f 1520 1286 1287 +f 1517 1518 1521 +f 1523 1522 1521 +f 1518 1523 1521 +f 1519 1523 1518 +f 1523 1519 1524 +f 1524 1519 1520 +f 1524 1520 1289 +f 1289 1520 1287 +f 1522 1523 1525 +f 105 104 1525 +f 1523 105 1525 +f 1524 105 1523 +f 1524 1289 98 +f 106 1524 98 +f 105 1524 106 +f 1338 1336 1529 +f 1529 1336 1530 +f 1530 1336 1339 +f 1530 1339 1531 +f 1531 1339 1340 +f 1531 1340 1532 +f 1532 1340 1341 +f 1532 1341 1342 +f 107 103 1338 +f 1529 107 1338 +f 1534 107 1529 +f 1534 1529 1535 +f 1535 1529 1530 +f 1535 1530 1536 +f 1536 1530 1531 +f 1536 1531 1537 +f 1537 1531 1532 +f 1532 1342 1362 +f 1538 1532 1362 +f 1537 1532 1538 +f 1538 1362 1539 +f 1539 1362 1363 +f 1539 1363 1540 +f 1540 1363 1364 +f 1540 1364 1365 +f 108 107 1542 +f 1542 107 1534 +f 1542 1534 1543 +f 1543 1534 1535 +f 1543 1535 1544 +f 1544 1535 1536 +f 1544 1536 1545 +f 1545 1536 1537 +f 1545 1537 1546 +f 1546 1537 1538 +f 1546 1538 1547 +f 1547 1538 1539 +f 1547 1539 1548 +f 1548 1539 1540 +f 1540 1365 1385 +f 1549 1540 1385 +f 1548 1540 1549 +f 1549 1385 1550 +f 1550 1385 1386 +f 1553 1552 1551 +f 1551 1554 1387 +f 1557 1556 1555 +f 1555 1558 1390 +f 1555 1390 1394 +f 109 108 1560 +f 1560 108 1542 +f 1560 1542 1561 +f 1561 1542 1543 +f 1561 1543 1562 +f 1562 1543 1544 +f 1562 1544 1563 +f 1563 1544 1545 +f 1563 1545 1564 +f 1564 1545 1546 +f 1564 1546 1565 +f 1565 1546 1547 +f 1565 1547 1566 +f 1566 1547 1548 +f 1569 1568 1567 +f 1567 1570 1571 +f 1567 1573 1572 +f 1572 1574 1575 +f 1572 1577 1576 +f 1576 1578 1551 +f 1581 1580 1579 +f 1579 1582 1555 +f 1555 1394 1414 +f 1583 1555 1414 +f 1579 1555 1583 +f 1583 1414 1584 +f 1584 1414 1415 +f 1584 1415 1585 +f 1585 1415 1416 +f 1585 1416 1586 +f 1586 1416 1417 +f 1586 1417 1587 +f 1587 1417 1418 +f 1589 1588 1419 +f 110 109 1591 +f 1591 109 1560 +f 1561 1592 1593 +f 1591 1561 1593 +f 1560 1561 1591 +f 1561 1562 1592 +f 1592 1562 1594 +f 1596 1595 1594 +f 1562 1596 1594 +f 1563 1596 1562 +f 1596 1563 1597 +f 1597 1563 1564 +f 1597 1564 1598 +f 1598 1564 1565 +f 1598 1565 1599 +f 1599 1565 1566 +f 1602 1601 1600 +f 1600 1603 1567 +f 1600 1567 1604 +f 1604 1567 1572 +f 1607 1606 1605 +f 1605 1608 1609 +f 1605 1611 1610 +f 1610 1612 1579 +f 1610 1579 1613 +f 1613 1579 1583 +f 1613 1583 1614 +f 1614 1583 1584 +f 1614 1584 1615 +f 1615 1584 1585 +f 1615 1585 1616 +f 1616 1585 1586 +f 1619 1618 1617 +f 1617 1620 1621 +f 1623 1419 1444 +f 1622 1624 1444 +f 1617 1625 1622 +f 1628 1627 1626 +f 1626 1629 1445 +f 1626 1445 1630 +f 1630 1445 1451 +f 1632 1631 1453 +f 110 1591 111 +f 111 1591 1634 +f 1634 1591 1593 +f 1595 1596 1635 +f 1596 1597 1635 +f 1635 1597 1636 +f 1597 1598 1636 +f 1636 1598 1637 +f 1598 1599 1637 +f 1640 1639 1638 +f 1642 1600 1638 +f 1638 1600 1641 +f 1600 1604 1641 +f 1641 1604 1643 +f 1645 1605 1646 +f 1647 1605 1644 +f 1605 1610 1644 +f 1644 1610 1648 +f 1650 1649 1648 +f 1610 1650 1648 +f 1613 1650 1610 +f 1650 1613 1651 +f 1651 1613 1614 +f 1651 1614 1652 +f 1652 1614 1615 +f 1655 1654 1653 +f 1653 1656 1657 +f 1653 1659 1658 +f 1658 1660 1617 +f 1663 1662 1661 +f 1661 1664 1665 +f 1668 1667 1666 +f 1666 1669 1670 +f 1666 1672 1671 +f 1671 1673 1674 +f 1676 1453 1465 +f 1675 1677 1465 +f 1671 1678 1675 +f 1675 1465 1679 +f 1679 1465 1466 +f 1679 1466 1467 +f 1649 1650 1680 +f 1650 1651 1680 +f 1680 1651 1681 +f 1651 1652 1681 +f 1684 1683 1682 +f 1686 1653 1682 +f 1682 1653 1685 +f 1689 1688 1690 +f 1692 1691 1687 +f 1695 1694 1696 +f 1698 1697 1693 +f 1700 1699 1693 +f 1701 1700 1693 +f 1666 1700 1702 +f 1700 1666 1703 +f 1703 1666 1671 +f 1703 1671 1704 +f 1704 1671 1675 +f 1704 1675 1705 +f 1705 1675 1679 +f 1679 1467 1471 +f 1706 1679 1471 +f 1705 1679 1706 +f 1706 1471 1472 +f 1699 1700 1707 +f 1700 1703 1707 +f 1707 1703 1708 +f 1710 1709 1708 +f 1703 1710 1708 +f 1704 1710 1703 +f 1710 1704 1711 +f 1711 1704 1705 +f 1711 1705 1712 +f 1712 1705 1706 +f 1706 1472 1476 +f 1713 1706 1476 +f 1712 1706 1713 +f 1713 1476 1477 +f 1709 1710 1714 +f 1710 1711 1714 +f 1714 1711 1715 +f 1717 1716 1715 +f 1711 1717 1715 +f 1712 1717 1711 +f 1717 1712 1718 +f 1718 1712 1713 +f 1713 1477 1486 +f 1719 1713 1486 +f 1718 1713 1719 +f 1719 1486 1487 +f 1716 1717 1720 +f 1722 1721 1720 +f 1717 1722 1720 +f 1718 1722 1717 +f 1722 1718 1723 +f 1723 1718 1719 +f 1726 1725 1493 +f 1724 1727 1493 +f 1729 1728 1724 +f 1724 1493 1496 +f 1721 1722 1730 +f 1732 1731 1730 +f 1722 1732 1730 +f 1723 1732 1722 +f 1735 1734 1733 +f 1733 1736 1724 +f 1724 1496 1501 +f 1737 1724 1501 +f 1733 1724 1737 +f 1737 1501 1502 +f 1731 1732 1738 +f 1740 1739 1741 +f 1742 1740 1743 +f 1733 1740 1744 +f 1740 1733 1745 +f 1745 1733 1737 +f 1745 1737 1505 +f 1505 1737 1502 +f 1739 1740 1746 +f 1748 1747 1746 +f 1740 1748 1746 +f 1745 1748 1740 +f 1745 1505 1509 +f 1749 1745 1509 +f 1748 1745 1749 +f 1749 1509 1510 +f 1747 1748 1750 +f 1750 1748 1751 +f 1751 1748 1752 +f 1752 1748 1749 +f 1749 1510 1513 +f 1753 1749 1513 +f 1752 1749 1753 +f 1753 1513 1514 +f 1750 1751 1754 +f 1756 1755 1754 +f 1751 1756 1754 +f 1752 1756 1751 +f 1756 1752 1757 +f 1757 1752 1753 +f 1757 1753 1517 +f 1517 1753 1514 +f 1755 1756 1758 +f 1760 1759 1758 +f 1756 1760 1758 +f 1757 1760 1756 +f 1757 1517 1521 +f 1761 1757 1521 +f 1760 1757 1761 +f 1761 1521 1522 +f 1759 1760 112 +f 112 1760 113 +f 113 1760 114 +f 114 1760 1761 +f 1761 1522 1525 +f 115 1761 1525 +f 114 1761 115 +f 115 1525 104 +f 1593 1592 1766 +f 1766 1592 1767 +f 1767 1592 1594 +f 1767 1594 1595 +f 116 111 1769 +f 1769 111 1634 +f 1769 1634 1593 +f 1766 1769 1593 +f 1770 1769 1766 +f 1770 1766 1771 +f 1771 1766 1767 +f 1767 1595 1635 +f 1772 1767 1635 +f 1771 1767 1772 +f 1772 1635 1773 +f 1773 1635 1636 +f 1773 1636 1774 +f 1774 1636 1637 +f 1777 1776 1775 +f 1775 1778 1638 +f 1775 1638 1779 +f 1779 1638 1641 +f 1779 1641 1780 +f 1780 1641 1643 +f 1783 1782 1781 +f 1781 1784 1644 +f 1781 1644 1785 +f 1785 1644 1648 +f 1785 1648 1649 +f 117 116 1787 +f 1787 116 1769 +f 1787 1769 1788 +f 1788 1769 1770 +f 1788 1770 1789 +f 1789 1770 1771 +f 1789 1771 1790 +f 1790 1771 1772 +f 1790 1772 1791 +f 1791 1772 1773 +f 1791 1773 1792 +f 1792 1773 1774 +f 1795 1794 1793 +f 1793 1796 1775 +f 1793 1775 1797 +f 1797 1775 1779 +f 1797 1779 1798 +f 1798 1779 1780 +f 1801 1800 1799 +f 1799 1802 1781 +f 1799 1781 1803 +f 1803 1781 1785 +f 1785 1649 1680 +f 1804 1785 1680 +f 1803 1785 1804 +f 1804 1680 1805 +f 1805 1680 1681 +f 1808 1807 1806 +f 1806 1809 1682 +f 1806 1682 1810 +f 1810 1682 1685 +f 1813 1812 1811 +f 1811 1814 1687 +f 1817 1816 1815 +f 1815 1818 1693 +f 1815 1693 1699 +f 118 117 1820 +f 1820 117 1787 +f 1820 1787 1821 +f 1821 1787 1788 +f 1821 1788 1822 +f 1822 1788 1789 +f 1822 1789 1823 +f 1823 1789 1790 +f 1826 1825 1824 +f 1824 1827 1828 +f 1824 1830 1829 +f 1829 1831 1832 +f 1829 1834 1833 +f 1833 1835 1793 +f 1833 1793 1836 +f 1836 1793 1797 +f 1836 1797 1837 +f 1837 1797 1798 +f 1840 1839 1838 +f 1838 1841 1799 +f 1838 1799 1842 +f 1842 1799 1803 +f 1842 1803 1843 +f 1843 1803 1804 +f 1846 1845 1844 +f 1844 1847 1848 +f 1844 1850 1849 +f 1849 1851 1806 +f 1854 1853 1852 +f 1852 1855 1856 +f 1859 1858 1857 +f 1857 1860 1861 +f 1857 1863 1862 +f 1862 1864 1815 +f 1815 1699 1707 +f 1865 1815 1707 +f 1862 1815 1865 +f 1865 1707 1866 +f 1866 1707 1708 +f 1866 1708 1709 +f 1820 1867 1869 +f 119 1820 1869 +f 118 1820 119 +f 1820 1821 1867 +f 1867 1821 1870 +f 1821 1822 1870 +f 1870 1822 1871 +f 1822 1823 1871 +f 1871 1823 1872 +f 1874 1824 1875 +f 1876 1824 1873 +f 1824 1829 1873 +f 1873 1829 1877 +f 1829 1833 1877 +f 1877 1833 1878 +f 1833 1836 1878 +f 1878 1836 1879 +f 1836 1837 1879 +f 1879 1837 1880 +f 1882 1838 1883 +f 1884 1838 1881 +f 1838 1842 1881 +f 1881 1842 1885 +f 1842 1843 1885 +f 1885 1843 1886 +f 1888 1887 1889 +f 1890 1888 1891 +f 1844 1888 1892 +f 1895 1894 1893 +f 1893 1896 1897 +f 1900 1899 1898 +f 1898 1901 1902 +f 1898 1904 1903 +f 1903 1905 1857 +f 1903 1857 1906 +f 1906 1857 1862 +f 1906 1862 1907 +f 1907 1862 1865 +f 1907 1865 1908 +f 1908 1865 1866 +f 1866 1709 1714 +f 1909 1866 1714 +f 1908 1866 1909 +f 1909 1714 1910 +f 1910 1714 1715 +f 1910 1715 1716 +f 120 119 1869 +f 1887 1888 1912 +f 1914 1893 1915 +f 1916 1893 1913 +f 1918 1898 1919 +f 1920 1898 1917 +f 1898 1903 1917 +f 1917 1903 1921 +f 1903 1906 1921 +f 1921 1906 1922 +f 1906 1907 1922 +f 1922 1907 1923 +f 1925 1924 1923 +f 1907 1925 1923 +f 1908 1925 1907 +f 1925 1908 1926 +f 1926 1908 1909 +f 1926 1909 1927 +f 1927 1909 1910 +f 1910 1716 1720 +f 1928 1910 1720 +f 1927 1910 1928 +f 1928 1720 1721 +f 1924 1925 1929 +f 1925 1926 1929 +f 1929 1926 1930 +f 1932 1931 1930 +f 1926 1932 1930 +f 1927 1932 1926 +f 1932 1927 1933 +f 1933 1927 1928 +f 1928 1721 1730 +f 1934 1928 1730 +f 1933 1928 1934 +f 1934 1730 1731 +f 1931 1932 1935 +f 1937 1936 1935 +f 1932 1937 1935 +f 1933 1937 1932 +f 1937 1933 1938 +f 1938 1933 1934 +f 1934 1731 1738 +f 1939 1934 1738 +f 1938 1934 1939 +f 1941 1940 1739 +f 1936 1937 1942 +f 1944 1943 1942 +f 1937 1944 1942 +f 1938 1944 1937 +f 1944 1938 1945 +f 1945 1938 1939 +f 1947 1739 1746 +f 1946 1948 1746 +f 1950 1949 1946 +f 1946 1746 1747 +f 1943 1944 1951 +f 1953 1952 1951 +f 1944 1953 1951 +f 1945 1953 1944 +f 1956 1955 1954 +f 1954 1957 1946 +f 1954 1946 1750 +f 1750 1946 1747 +f 1952 1953 1958 +f 1960 1959 1961 +f 1962 1960 1963 +f 1954 1960 1964 +f 1954 1750 1754 +f 1965 1954 1754 +f 1960 1954 1965 +f 1965 1754 1755 +f 1959 1960 1966 +f 1966 1960 1967 +f 1967 1960 1968 +f 1968 1960 1965 +f 1965 1755 1758 +f 1969 1965 1758 +f 1968 1965 1969 +f 1969 1758 1759 +f 1966 1967 1970 +f 122 121 1970 +f 1967 122 1970 +f 1968 122 1967 +f 122 1968 123 +f 123 1968 1969 +f 123 1969 112 +f 112 1969 1759 +f 1974 1867 1975 +f 1975 1867 1870 +f 1975 1870 1976 +f 1976 1870 1871 +f 1976 1871 1977 +f 1977 1871 1872 +f 1977 1872 1978 +f 1980 1979 1873 +f 1982 1873 1981 +f 1981 1873 1877 +f 1981 1877 1983 +f 1983 1877 1878 +f 1983 1878 1984 +f 1984 1878 1879 +f 1984 1879 1985 +f 1985 1879 1880 +f 1988 1987 1986 +f 1986 1989 1881 +f 1986 1881 1990 +f 1990 1881 1885 +f 1990 1885 1991 +f 1991 1885 1886 +f 124 120 1869 +f 1974 124 1869 +f 1993 124 1974 +f 1993 1974 1994 +f 1994 1974 1975 +f 1994 1975 1995 +f 1995 1975 1976 +f 1995 1976 1996 +f 1996 1976 1977 +f 1996 1977 1997 +f 1997 1977 1978 +f 2000 1999 1998 +f 1998 2001 1981 +f 1998 1981 2002 +f 2002 1981 1983 +f 2002 1983 2003 +f 2003 1983 1984 +f 2003 1984 2004 +f 2004 1984 1985 +f 2007 2006 2005 +f 2005 2008 1986 +f 2005 1986 2009 +f 2009 1986 1990 +f 2012 2011 2010 +f 2010 2013 2014 +f 2016 1887 1912 +f 2015 2017 1912 +f 2010 2018 2015 +f 2021 2020 2019 +f 2019 2022 1913 +f 2025 2024 2023 +f 2023 2026 1917 +f 2023 1917 2027 +f 2027 1917 1921 +f 2027 1921 2028 +f 2028 1921 1922 +f 2028 1922 2029 +f 2029 1922 1923 +f 125 124 2031 +f 2031 124 1993 +f 2031 1993 2032 +f 2032 1993 1994 +f 2032 1994 2033 +f 2033 1994 1995 +f 2033 1995 2034 +f 2034 1995 1996 +f 2034 1996 2035 +f 2035 1996 1997 +f 2035 1997 2036 +f 2038 2037 1998 +f 2040 1998 2039 +f 2039 1998 2002 +f 2039 2002 2041 +f 2041 2002 2003 +f 2041 2003 2042 +f 2042 2003 2004 +f 2045 2044 2043 +f 2043 2046 2005 +f 2043 2005 2047 +f 2047 2005 2009 +f 2050 2049 2048 +f 2048 2051 2010 +f 2054 2053 2052 +f 2052 2055 2056 +f 2059 2058 2057 +f 2057 2060 2061 +f 2057 2063 2062 +f 2062 2064 2023 +f 2062 2023 2065 +f 2065 2023 2027 +f 2065 2027 2066 +f 2066 2027 2028 +f 2066 2028 2067 +f 2067 2028 2029 +f 2029 1924 1929 +f 2068 2029 1929 +f 2067 2029 2068 +f 2068 1929 2069 +f 2069 1929 1930 +f 2069 1930 1931 +f 126 125 2071 +f 2071 125 2031 +f 2071 2031 2072 +f 2072 2031 2032 +f 2072 2032 2073 +f 2073 2032 2033 +f 2073 2033 2074 +f 2074 2033 2034 +f 2074 2034 2075 +f 2075 2034 2035 +f 2075 2035 2076 +f 2076 2035 2036 +f 2079 2078 2077 +f 2077 2080 2039 +f 2077 2039 2081 +f 2081 2039 2041 +f 2081 2041 2082 +f 2082 2041 2042 +f 2085 2084 2083 +f 2083 2086 2043 +f 2083 2043 2087 +f 2087 2043 2047 +f 2090 2089 2088 +f 2088 2091 2048 +f 2094 2093 2092 +f 2092 2095 2052 +f 2098 2097 2096 +f 2096 2099 2057 +f 2096 2057 2100 +f 2100 2057 2062 +f 2100 2062 2101 +f 2101 2062 2065 +f 2101 2065 2102 +f 2102 2065 2066 +f 2102 2066 2103 +f 2103 2066 2067 +f 2103 2067 2104 +f 2104 2067 2068 +f 2104 2068 2105 +f 2105 2068 2069 +f 2069 1931 1935 +f 2106 2069 1935 +f 2105 2069 2106 +f 2106 1935 1936 +f 127 126 2108 +f 2108 126 2071 +f 2072 2109 2110 +f 2108 2072 2110 +f 2071 2072 2108 +f 2072 2073 2109 +f 2109 2073 2111 +f 2073 2074 2111 +f 2111 2074 2112 +f 2074 2075 2112 +f 2112 2075 2113 +f 2075 2076 2113 +f 2113 2076 2114 +f 2116 2077 2117 +f 2118 2077 2115 +f 2077 2081 2115 +f 2115 2081 2119 +f 2081 2082 2119 +f 2119 2082 2120 +f 2122 2083 2123 +f 2124 2083 2121 +f 2083 2087 2121 +f 2121 2087 2125 +f 2127 2088 2128 +f 2129 2088 2126 +f 2131 2092 2132 +f 2133 2092 2130 +f 2135 2096 2136 +f 2137 2096 2134 +f 2096 2100 2134 +f 2134 2100 2138 +f 2100 2101 2138 +f 2138 2101 2139 +f 2101 2102 2139 +f 2139 2102 2140 +f 2142 2141 2140 +f 2102 2142 2140 +f 2103 2142 2102 +f 2142 2103 2143 +f 2143 2103 2104 +f 2143 2104 2144 +f 2144 2104 2105 +f 2144 2105 2145 +f 2145 2105 2106 +f 2106 1936 1942 +f 2146 2106 1942 +f 2145 2106 2146 +f 2146 1942 1943 +f 127 2108 128 +f 128 2108 2148 +f 2141 2142 2149 +f 2142 2143 2149 +f 2149 2143 2150 +f 2152 2151 2150 +f 2143 2152 2150 +f 2144 2152 2143 +f 2152 2144 2153 +f 2153 2144 2145 +f 2153 2145 2154 +f 2154 2145 2146 +f 2146 1943 1951 +f 2155 2146 1951 +f 2154 2146 2155 +f 2155 1951 1952 +f 2151 2152 2156 +f 2158 2157 2156 +f 2152 2158 2156 +f 2153 2158 2152 +f 2158 2153 2159 +f 2159 2153 2154 +f 2159 2154 2160 +f 2160 2154 2155 +f 2155 1952 1958 +f 2161 2155 1958 +f 2160 2155 2161 +f 2163 2162 1959 +f 2157 2158 2164 +f 2166 2165 2164 +f 2158 2166 2164 +f 2159 2166 2158 +f 2166 2159 2167 +f 2167 2159 2160 +f 2167 2160 2168 +f 2168 2160 2161 +f 2170 2169 1966 +f 1966 2171 1959 +f 2165 2166 2172 +f 130 129 2172 +f 2166 130 2172 +f 2167 130 2166 +f 130 2167 131 +f 131 2167 2168 +f 2177 1966 1970 +f 132 2178 1970 +f 2180 2179 132 +f 132 1970 121 +f 2110 2109 2181 +f 2181 2109 2182 +f 2182 2109 2111 +f 2182 2111 2183 +f 2183 2111 2112 +f 2183 2112 2184 +f 2184 2112 2113 +f 2184 2113 2185 +f 2185 2113 2114 +f 2188 2187 2186 +f 2186 2189 2115 +f 2186 2115 2190 +f 2190 2115 2119 +f 2190 2119 2191 +f 2191 2119 2120 +f 2194 2193 2192 +f 2192 2195 2121 +f 2192 2121 2196 +f 2196 2121 2125 +f 2199 2198 2197 +f 2197 2200 2126 +f 2203 2202 2201 +f 2201 2204 2130 +f 2201 2130 2205 +f 2207 2206 2134 +f 2209 2134 2208 +f 2208 2134 2138 +f 2208 2138 2210 +f 2210 2138 2139 +f 2210 2139 2211 +f 2211 2139 2140 +f 2211 2140 2141 +f 133 128 2213 +f 2213 128 2148 +f 2213 2148 2110 +f 2181 2213 2110 +f 2214 2213 2181 +f 2214 2181 2215 +f 2215 2181 2182 +f 2218 2217 2216 +f 2216 2219 2220 +f 2216 2222 2221 +f 2221 2223 2224 +f 2221 2226 2225 +f 2225 2227 2228 +f 2225 2230 2229 +f 2229 2231 2186 +f 2229 2186 2232 +f 2232 2186 2190 +f 2232 2190 2233 +f 2233 2190 2191 +f 2236 2235 2234 +f 2234 2237 2192 +f 2234 2192 2238 +f 2238 2192 2196 +f 2238 2196 2239 +f 2241 2240 2197 +f 2243 2197 2242 +f 2245 2244 2201 +f 2247 2201 2246 +f 2246 2201 2205 +f 2246 2205 2248 +f 2250 2249 2208 +f 2252 2208 2251 +f 2251 2208 2210 +f 2251 2210 2253 +f 2253 2210 2211 +f 2211 2141 2149 +f 2254 2211 2149 +f 2253 2211 2254 +f 2254 2149 2255 +f 2255 2149 2150 +f 2255 2150 2151 +f 134 133 2257 +f 2257 133 2213 +f 2257 2213 2258 +f 2258 2213 2214 +f 2261 2260 2259 +f 2259 2262 2263 +f 2259 2265 2264 +f 2264 2266 2216 +f 2264 2216 2267 +f 2267 2216 2221 +f 2267 2221 2268 +f 2268 2221 2225 +f 2268 2225 2269 +f 2269 2225 2229 +f 2269 2229 2270 +f 2270 2229 2232 +f 2270 2232 2271 +f 2271 2232 2233 +f 2271 2233 2272 +f 2274 2273 2234 +f 2276 2234 2275 +f 2275 2234 2238 +f 2275 2238 2277 +f 2277 2238 2239 +f 2280 2279 2278 +f 2278 2281 2242 +f 2284 2283 2282 +f 2282 2285 2246 +f 2282 2246 2286 +f 2286 2246 2248 +f 2286 2248 2287 +f 2287 2248 2288 +f 2287 2290 2289 +f 2291 2251 2253 +f 2293 2253 2292 +f 2292 2253 2254 +f 2292 2254 2294 +f 2294 2254 2255 +f 2255 2151 2156 +f 2295 2255 2156 +f 2294 2255 2295 +f 2295 2156 2157 +f 135 134 2297 +f 2297 134 2257 +f 2297 2257 2298 +f 2298 2257 2258 +f 2298 2258 2299 +f 2301 2300 2259 +f 2303 2259 2302 +f 2302 2259 2264 +f 2302 2264 2304 +f 2304 2264 2267 +f 2304 2267 2305 +f 2305 2267 2268 +f 2305 2268 2306 +f 2306 2268 2269 +f 2306 2269 2307 +f 2307 2269 2270 +f 2307 2270 2308 +f 2308 2270 2271 +f 2308 2271 2309 +f 2309 2271 2272 +f 2275 2310 2311 +f 2312 2275 2311 +f 2313 2275 2314 +f 2275 2277 2310 +f 2310 2277 2315 +f 2317 2278 2318 +f 2319 2278 2316 +f 2278 2321 2316 +f 2316 2322 2320 +f 2282 2286 2324 +f 2325 2286 2323 +f 2286 2287 2323 +f 2323 2287 2326 +f 2328 2327 2326 +f 2287 2328 2326 +f 2289 2328 2287 +f 2331 2330 2329 +f 2329 2332 2292 +f 2329 2292 2333 +f 2333 2292 2294 +f 2333 2294 2334 +f 2334 2294 2295 +f 2295 2157 2164 +f 2335 2295 2164 +f 2334 2295 2335 +f 2335 2164 2165 +f 136 135 137 +f 137 135 2297 +f 137 2297 138 +f 138 2297 2298 +f 138 2298 139 +f 139 2298 2299 +f 139 2299 140 +f 2342 2341 2302 +f 2344 2302 141 +f 141 2302 2304 +f 141 2304 142 +f 142 2304 2305 +f 142 2305 143 +f 143 2305 2306 +f 2307 2347 144 +f 143 2307 144 +f 2306 2307 143 +f 2307 2308 2347 +f 2347 2308 2349 +f 2308 2309 2349 +f 2349 2309 2350 +f 2350 2309 2351 +f 2327 2328 2352 +f 146 145 2352 +f 2328 146 2352 +f 2329 2355 2356 +f 2358 2329 147 +f 147 2329 2333 +f 147 2333 148 +f 148 2333 2334 +f 148 2334 149 +f 149 2334 2335 +f 2335 2165 2172 +f 150 2335 2172 +f 149 2335 150 +f 150 2172 129 +f 2311 2310 2362 +f 2362 2310 2363 +f 2363 2310 2315 +f 2363 2315 2364 +f 2366 2365 2316 +f 2368 2316 2367 +f 2367 2316 2320 +f 2371 2370 2369 +f 2369 2372 2323 +f 2369 2323 2373 +f 2373 2323 2326 +f 2373 2326 2327 +f 144 2347 151 +f 151 2347 152 +f 152 2347 2349 +f 152 2349 153 +f 153 2349 2350 +f 153 2350 2378 +f 2362 2379 2311 +f 154 2380 2362 +f 154 2362 155 +f 155 2362 2363 +f 155 2363 156 +f 156 2363 2364 +f 156 2364 157 +f 2385 2384 2367 +f 2387 2367 158 +f 2389 2388 2369 +f 2391 2369 159 +f 159 2369 2373 +f 2373 2327 2352 +f 160 2373 2352 +f 159 2373 160 +f 160 2352 145 diff --git a/data/meshes/voxel_mesh_02.obj b/data/meshes/voxel_mesh_02.obj new file mode 100644 index 0000000..1eb5f9f --- /dev/null +++ b/data/meshes/voxel_mesh_02.obj @@ -0,0 +1,6418 @@ +v 800.000000000 325.000000000 198.267181396 +v 800.000000000 315.189971924 200.000000000 +v 789.529968262 325.000000000 200.000000000 +v 625.000000000 350.000000000 198.084365845 +v 625.000000000 342.952789307 200.000000000 +v 610.345520020 350.000000000 200.000000000 +v 650.000000000 350.000000000 196.522384644 +v 650.000000000 339.915313721 200.000000000 +v 675.000000000 350.000000000 199.029205322 +v 675.000000000 345.960906982 200.000000000 +v 689.008239746 350.000000000 200.000000000 +v 775.000000000 350.000000000 198.766906738 +v 775.000000000 341.199432373 200.000000000 +v 758.531066895 350.000000000 200.000000000 +v 800.000000000 350.000000000 197.916107178 +v 525.000000000 375.000000000 197.136032104 +v 525.000000000 362.466583252 200.000000000 +v 502.870086670 375.000000000 200.000000000 +v 547.255310059 375.000000000 200.000000000 +v 575.000000000 375.000000000 197.259597778 +v 575.000000000 358.991760254 200.000000000 +v 552.118896484 375.000000000 200.000000000 +v 600.000000000 375.000000000 196.051712036 +v 600.000000000 355.821929932 200.000000000 +v 625.000000000 375.000000000 191.822189331 +v 650.000000000 375.000000000 191.412399292 +v 675.000000000 375.000000000 193.169982910 +v 700.000000000 375.000000000 193.979736328 +v 700.000000000 352.750671387 200.000000000 +v 725.000000000 375.000000000 196.385009766 +v 725.000000000 356.257568359 200.000000000 +v 750.000000000 375.000000000 196.297790527 +v 750.000000000 354.123413086 200.000000000 +v 775.000000000 375.000000000 195.101196289 +v 800.000000000 375.000000000 197.691528320 +v 500.000000000 400.000000000 198.451614380 +v 500.000000000 379.933532715 200.000000000 +v 482.366790771 400.000000000 200.000000000 +v 525.000000000 400.000000000 195.686157227 +v 550.000000000 400.000000000 197.296951294 +v 550.000000000 377.264709473 200.000000000 +v 575.000000000 400.000000000 194.570388794 +v 600.000000000 400.000000000 189.646865845 +v 625.000000000 400.000000000 186.325805664 +v 650.000000000 400.000000000 185.439163208 +v 675.000000000 400.000000000 190.221099854 +v 700.000000000 400.000000000 193.374160767 +v 725.000000000 400.000000000 193.864929199 +v 750.000000000 400.000000000 192.747360229 +v 775.000000000 400.000000000 196.288116455 +v 800.000000000 400.000000000 196.737579346 +v 475.000000000 425.000000000 199.925476074 +v 475.000000000 422.307525635 200.000000000 +v 474.378723145 425.000000000 200.000000000 +v 500.000000000 425.000000000 197.722656250 +v 525.000000000 425.000000000 195.303222656 +v 550.000000000 425.000000000 195.360916138 +v 575.000000000 425.000000000 192.317443848 +v 600.000000000 425.000000000 189.669219971 +v 625.000000000 425.000000000 188.922042847 +v 650.000000000 425.000000000 187.637573242 +v 675.000000000 425.000000000 190.318649292 +v 700.000000000 425.000000000 193.282791138 +v 725.000000000 425.000000000 193.451599121 +v 750.000000000 425.000000000 189.315521240 +v 775.000000000 425.000000000 195.624755859 +v 800.000000000 425.000000000 199.034072876 +v 466.057312012 450.000000000 200.000000000 +v 475.000000000 450.000000000 199.359466553 +v 500.000000000 450.000000000 197.802383423 +v 525.000000000 450.000000000 194.783889771 +v 550.000000000 450.000000000 196.163803101 +v 575.000000000 450.000000000 193.176376343 +v 600.000000000 450.000000000 193.615173340 +v 625.000000000 450.000000000 191.546005249 +v 650.000000000 450.000000000 189.146072388 +v 675.000000000 450.000000000 193.754165649 +v 700.000000000 450.000000000 195.928604126 +v 725.000000000 450.000000000 194.781356812 +v 750.000000000 450.000000000 193.964523315 +v 775.000000000 450.000000000 197.477203369 +v 800.000000000 445.958221436 200.000000000 +v 798.234130859 450.000000000 200.000000000 +v 466.498748779 475.000000000 200.000000000 +v 475.000000000 475.000000000 199.064254761 +v 475.000000000 450.000000000 199.359466553 +v 466.057312012 450.000000000 200.000000000 +v 475.000000000 450.000000000 199.359466553 +v 500.000000000 475.000000000 198.646011353 +v 475.000000000 450.000000000 199.359466553 +v 500.000000000 475.000000000 198.646011353 +v 525.000000000 475.000000000 196.442550659 +v 500.000000000 475.000000000 198.646011353 +v 550.000000000 475.000000000 193.733016968 +v 575.000000000 475.000000000 189.770751953 +v 600.000000000 475.000000000 192.370758057 +v 625.000000000 475.000000000 194.302398682 +v 650.000000000 475.000000000 192.554687500 +v 675.000000000 475.000000000 193.504760742 +v 700.000000000 475.000000000 196.514297485 +v 725.000000000 475.000000000 196.427291870 +v 750.000000000 475.000000000 198.925811768 +v 775.000000000 469.841247559 200.000000000 +v 766.599060059 475.000000000 200.000000000 +v 471.357666016 500.000000000 200.000000000 +v 475.000000000 500.000000000 199.493865967 +v 500.000000000 500.000000000 197.924560547 +v 475.000000000 475.000000000 199.064254761 +v 475.000000000 500.000000000 199.493865967 +v 475.000000000 475.000000000 199.064254761 +v 500.000000000 475.000000000 198.646011353 +v 525.000000000 500.000000000 194.683197021 +v 500.000000000 475.000000000 198.646011353 +v 500.000000000 475.000000000 198.646011353 +v 550.000000000 500.000000000 189.807785034 +v 575.000000000 500.000000000 185.608291626 +v 600.000000000 500.000000000 188.849609375 +v 625.000000000 500.000000000 191.999435425 +v 650.000000000 500.000000000 193.824508667 +v 675.000000000 500.000000000 195.540145874 +v 700.000000000 500.000000000 198.090744019 +v 725.000000000 498.331512451 200.000000000 +v 721.968811035 500.000000000 200.000000000 +v 750.000000000 484.987060547 200.000000000 +v 775.000000000 500.000000000 199.191635132 +v 775.000000000 483.762023926 200.000000000 +v 765.394592285 500.000000000 200.000000000 +v 780.788452148 500.000000000 200.000000000 +v 475.000000000 515.670166016 200.000000000 +v 479.896392822 525.000000000 200.000000000 +v 500.000000000 525.000000000 199.050369263 +v 475.000000000 515.670166016 200.000000000 +v 475.000000000 500.000000000 199.493865967 +v 475.000000000 515.670166016 200.000000000 +v 475.000000000 500.000000000 199.493865967 +v 525.000000000 525.000000000 195.927841187 +v 550.000000000 525.000000000 190.833801270 +v 575.000000000 525.000000000 190.412445068 +v 600.000000000 525.000000000 192.010009766 +v 625.000000000 525.000000000 192.494323730 +v 650.000000000 525.000000000 194.909454346 +v 675.000000000 525.000000000 196.831573486 +v 700.000000000 525.000000000 198.326461792 +v 725.000000000 525.000000000 199.529998779 +v 725.000000000 510.843414307 200.000000000 +v 728.073791504 525.000000000 200.000000000 +v 775.000000000 519.871398926 200.000000000 +v 500.000000000 532.603088379 200.000000000 +v 516.587768555 550.000000000 200.000000000 +v 525.000000000 550.000000000 198.882598877 +v 550.000000000 550.000000000 193.211990356 +v 575.000000000 550.000000000 193.833999634 +v 600.000000000 550.000000000 192.191619873 +v 625.000000000 550.000000000 193.832107544 +v 650.000000000 550.000000000 196.673599243 +v 675.000000000 550.000000000 199.788024902 +v 700.000000000 550.000000000 196.834381104 +v 725.000000000 550.000000000 197.557098389 +v 741.501831055 550.000000000 200.000000000 +v 775.000000000 550.000000000 199.574874878 +v 775.000000000 535.018432617 200.000000000 +v 769.677368164 550.000000000 200.000000000 +v 782.422912598 550.000000000 200.000000000 +v 525.000000000 564.159729004 200.000000000 +v 528.582641602 575.000000000 200.000000000 +v 550.000000000 575.000000000 195.590438843 +v 575.000000000 575.000000000 194.238525391 +v 600.000000000 575.000000000 194.747390747 +v 625.000000000 575.000000000 196.992416382 +v 650.000000000 569.587524414 200.000000000 +v 643.890258789 575.000000000 200.000000000 +v 675.000000000 553.258117676 200.000000000 +v 700.000000000 570.338317871 200.000000000 +v 713.030212402 575.000000000 200.000000000 +v 725.000000000 575.000000000 199.309127808 +v 750.000000000 575.000000000 197.949356079 +v 750.000000000 560.825073242 200.000000000 +v 775.000000000 575.000000000 196.571380615 +v 800.000000000 575.000000000 197.946228027 +v 800.000000000 556.902770996 200.000000000 +v 550.000000000 599.907836914 200.000000000 +v 550.149597168 600.000000000 200.000000000 +v 575.000000000 600.000000000 196.924468994 +v 600.000000000 600.000000000 197.976013184 +v 625.000000000 585.627502441 200.000000000 +v 607.828369141 600.000000000 200.000000000 +v 725.000000000 577.267578125 200.000000000 +v 750.000000000 582.008239746 200.000000000 +v 775.000000000 587.036254883 200.000000000 +v 800.000000000 591.438110352 200.000000000 +v 575.000000000 610.910827637 200.000000000 +v 600.000000000 605.517272949 200.000000000 +v 450.000000000 650.000000000 199.358871460 +v 450.000000000 648.279479980 200.000000000 +v 448.211822510 650.000000000 200.000000000 +v 475.000000000 650.000000000 195.660095215 +v 475.000000000 635.716552734 200.000000000 +v 494.789489746 650.000000000 200.000000000 +v 550.000000000 650.000000000 198.757156372 +v 550.000000000 642.518859863 200.000000000 +v 541.307006836 650.000000000 200.000000000 +v 574.536010742 650.000000000 200.000000000 +v 425.000000000 675.000000000 192.283813477 +v 425.000000000 665.235107422 200.000000000 +v 415.376129150 675.000000000 200.000000000 +v 450.000000000 675.000000000 187.062591553 +v 475.000000000 675.000000000 190.869018555 +v 500.000000000 675.000000000 196.653900146 +v 500.000000000 655.524780273 200.000000000 +v 515.306152344 675.000000000 200.000000000 +v 550.000000000 658.128845215 200.000000000 +v 650.000000000 675.000000000 198.573333740 +v 650.000000000 651.706665039 200.000000000 +v 628.404907227 675.000000000 200.000000000 +v 670.520446777 675.000000000 200.000000000 +v 415.294586182 700.000000000 200.000000000 +v 425.000000000 700.000000000 184.726303101 +v 450.000000000 700.000000000 187.724517822 +v 475.000000000 700.000000000 189.504928589 +v 500.000000000 700.000000000 196.847900391 +v 507.331604004 700.000000000 200.000000000 +v 650.000000000 678.383056641 200.000000000 +v 416.794769287 725.000000000 200.000000000 +v 425.000000000 725.000000000 190.145950317 +v 450.000000000 725.000000000 187.086029053 +v 475.000000000 725.000000000 190.769439697 +v 500.000000000 716.424926758 200.000000000 +v 495.908508301 725.000000000 200.000000000 +v 411.781799316 750.000000000 200.000000000 +v 425.000000000 750.000000000 183.417922974 +v 450.000000000 750.000000000 184.341384888 +v 475.000000000 750.000000000 193.315719604 +v 492.535583496 750.000000000 200.000000000 +v 800.000000000 750.000000000 198.037094116 +v 800.000000000 744.284851074 200.000000000 +v 796.053710938 750.000000000 200.000000000 +v 403.072631836 775.000000000 200.000000000 +v 425.000000000 775.000000000 181.522018433 +v 450.000000000 775.000000000 183.428390503 +v 475.000000000 775.000000000 190.898376465 +v 500.000000000 775.000000000 198.962219238 +v 500.000000000 767.909423828 200.000000000 +v 503.017272949 775.000000000 200.000000000 +v 800.000000000 761.427429199 200.000000000 +v 406.666503906 800.000000000 200.000000000 +v 425.000000000 800.000000000 184.078613281 +v 450.000000000 800.000000000 184.097335815 +v 475.000000000 800.000000000 191.231811523 +v 500.000000000 800.000000000 193.700546265 +v 512.531250000 800.000000000 200.000000000 +v 800.000000000 250.000000000 218.759445190 +v 800.000000000 245.663864136 225.000000000 +v 790.215515137 250.000000000 225.000000000 +v 750.000000000 275.000000000 221.898910522 +v 750.000000000 271.154144287 225.000000000 +v 737.260803223 275.000000000 225.000000000 +v 775.000000000 275.000000000 211.655090332 +v 775.000000000 258.770294189 225.000000000 +v 800.000000000 275.000000000 200.083679199 +v 450.000000000 300.000000000 223.796890259 +v 450.000000000 298.041748047 225.000000000 +v 444.958831787 300.000000000 225.000000000 +v 475.000000000 300.000000000 220.663909912 +v 475.000000000 292.656402588 225.000000000 +v 500.000000000 300.000000000 220.445007324 +v 500.000000000 292.683227539 225.000000000 +v 525.000000000 300.000000000 220.190765381 +v 525.000000000 292.611145020 225.000000000 +v 550.000000000 300.000000000 220.745178223 +v 550.000000000 294.086883545 225.000000000 +v 575.000000000 300.000000000 222.385955811 +v 575.000000000 296.567718506 225.000000000 +v 550.000000000 300.000000000 220.745178223 +v 550.000000000 300.000000000 220.745178223 +v 550.000000000 294.086883545 225.000000000 +v 600.000000000 300.000000000 222.372009277 +v 600.000000000 296.779693604 225.000000000 +v 625.000000000 300.000000000 221.085067749 +v 625.000000000 295.202789307 225.000000000 +v 650.000000000 300.000000000 218.891647339 +v 650.000000000 291.703979492 225.000000000 +v 675.000000000 300.000000000 215.972305298 +v 675.000000000 285.744873047 225.000000000 +v 700.000000000 300.000000000 214.474029541 +v 700.000000000 281.582794189 225.000000000 +v 725.000000000 300.000000000 213.644149780 +v 725.000000000 279.083190918 225.000000000 +v 750.000000000 300.000000000 211.479003906 +v 775.000000000 300.000000000 207.382064819 +v 800.000000000 300.000000000 202.721191406 +v 425.000000000 325.000000000 219.493911743 +v 425.000000000 311.723937988 225.000000000 +v 404.502624512 325.000000000 225.000000000 +v 450.000000000 325.000000000 212.832397461 +v 475.000000000 325.000000000 208.428665161 +v 500.000000000 325.000000000 207.972290039 +v 525.000000000 325.000000000 206.023361206 +v 550.000000000 325.000000000 206.122665405 +v 525.000000000 300.000000000 220.190765381 +v 525.000000000 325.000000000 206.023361206 +v 525.000000000 300.000000000 220.190765381 +v 550.000000000 300.000000000 220.745178223 +v 575.000000000 325.000000000 206.017562866 +v 550.000000000 300.000000000 220.745178223 +v 550.000000000 300.000000000 220.745178223 +v 600.000000000 325.000000000 206.870910645 +v 625.000000000 325.000000000 204.765563965 +v 650.000000000 325.000000000 204.101608276 +v 675.000000000 325.000000000 204.051422119 +v 700.000000000 325.000000000 204.180099487 +v 675.000000000 300.000000000 215.972305298 +v 700.000000000 325.000000000 204.180099487 +v 700.000000000 300.000000000 214.474029541 +v 725.000000000 325.000000000 203.451187134 +v 750.000000000 325.000000000 203.004119873 +v 775.000000000 325.000000000 202.018875122 +v 400.000000000 350.000000000 218.368957520 +v 400.000000000 329.112182617 225.000000000 +v 387.683380127 350.000000000 225.000000000 +v 425.000000000 350.000000000 211.455276489 +v 450.000000000 350.000000000 206.830780029 +v 475.000000000 350.000000000 204.283432007 +v 500.000000000 350.000000000 202.665237427 +v 475.000000000 325.000000000 208.428665161 +v 475.000000000 350.000000000 204.283432007 +v 475.000000000 325.000000000 208.428665161 +v 500.000000000 325.000000000 207.972290039 +v 525.000000000 350.000000000 201.907699585 +v 500.000000000 325.000000000 207.972290039 +v 500.000000000 325.000000000 207.972290039 +v 525.000000000 325.000000000 206.023361206 +v 550.000000000 350.000000000 201.969497681 +v 525.000000000 325.000000000 206.023361206 +v 525.000000000 325.000000000 206.023361206 +v 575.000000000 350.000000000 201.476806641 +v 600.000000000 350.000000000 201.008102417 +v 700.000000000 350.000000000 200.522369385 +v 725.000000000 350.000000000 200.715209961 +v 750.000000000 350.000000000 200.429229736 +v 375.000000000 375.000000000 224.494964600 +v 375.000000000 373.334075928 225.000000000 +v 374.308929443 375.000000000 225.000000000 +v 400.000000000 375.000000000 209.903427124 +v 425.000000000 375.000000000 205.549621582 +v 450.000000000 375.000000000 203.233581543 +v 475.000000000 375.000000000 201.360153198 +v 500.000000000 375.000000000 200.193527222 +v 475.000000000 350.000000000 204.283432007 +v 475.000000000 375.000000000 201.360153198 +v 475.000000000 350.000000000 204.283432007 +v 550.000000000 375.000000000 200.181076050 +v 368.657012939 400.000000000 225.000000000 +v 375.000000000 400.000000000 220.095245361 +v 400.000000000 400.000000000 205.012329102 +v 425.000000000 400.000000000 202.693725586 +v 450.000000000 400.000000000 202.110977173 +v 475.000000000 400.000000000 200.342971802 +v 450.000000000 375.000000000 203.233581543 +v 450.000000000 400.000000000 202.110977173 +v 450.000000000 375.000000000 203.233581543 +v 475.000000000 375.000000000 201.360153198 +v 475.000000000 375.000000000 201.360153198 +v 365.625701904 425.000000000 225.000000000 +v 375.000000000 425.000000000 218.316223145 +v 400.000000000 425.000000000 204.645202637 +v 425.000000000 425.000000000 203.693008423 +v 450.000000000 425.000000000 201.337783813 +v 450.000000000 425.000000000 201.337783813 +v 450.000000000 400.000000000 202.110977173 +v 450.000000000 425.000000000 201.337783813 +v 362.472717285 450.000000000 225.000000000 +v 375.000000000 450.000000000 216.847747803 +v 400.000000000 450.000000000 206.037322998 +v 425.000000000 450.000000000 202.742218018 +v 450.000000000 450.000000000 200.584228516 +v 466.057312012 450.000000000 200.000000000 +v 466.057312012 450.000000000 200.000000000 +v 474.378723145 425.000000000 200.000000000 +v 800.000000000 450.000000000 200.161773682 +v 364.924133301 475.000000000 225.000000000 +v 375.000000000 475.000000000 218.174652100 +v 400.000000000 475.000000000 206.395263672 +v 425.000000000 475.000000000 202.872634888 +v 450.000000000 475.000000000 200.738098145 +v 466.057312012 450.000000000 200.000000000 +v 775.000000000 475.000000000 200.484436035 +v 800.000000000 475.000000000 200.714797974 +v 371.359985352 500.000000000 225.000000000 +v 375.000000000 500.000000000 222.141693115 +v 400.000000000 500.000000000 207.967712402 +v 425.000000000 500.000000000 204.118759155 +v 450.000000000 500.000000000 201.221054077 +v 725.000000000 500.000000000 200.270111084 +v 750.000000000 500.000000000 201.562835693 +v 800.000000000 500.000000000 202.372192383 +v 375.000000000 512.421386719 225.000000000 +v 379.659698486 525.000000000 225.000000000 +v 400.000000000 525.000000000 211.435577393 +v 375.000000000 512.421386719 225.000000000 +v 400.000000000 525.000000000 211.435577393 +v 400.000000000 525.000000000 211.435577393 +v 425.000000000 525.000000000 205.163284302 +v 400.000000000 525.000000000 211.435577393 +v 450.000000000 525.000000000 201.795120239 +v 475.000000000 525.000000000 200.096984863 +v 475.000000000 515.670166016 200.000000000 +v 475.000000000 525.000000000 200.096984863 +v 750.000000000 525.000000000 202.487899780 +v 775.000000000 525.000000000 200.218826294 +v 800.000000000 525.000000000 201.635772705 +v 389.372711182 550.000000000 225.000000000 +v 400.000000000 550.000000000 217.370864868 +v 425.000000000 550.000000000 208.338119507 +v 425.000000000 525.000000000 205.163284302 +v 450.000000000 550.000000000 203.186676025 +v 425.000000000 525.000000000 205.163284302 +v 425.000000000 525.000000000 205.163284302 +v 450.000000000 525.000000000 201.795120239 +v 475.000000000 550.000000000 201.320831299 +v 450.000000000 525.000000000 201.795120239 +v 475.000000000 550.000000000 201.320831299 +v 500.000000000 550.000000000 201.064392090 +v 475.000000000 525.000000000 200.096984863 +v 475.000000000 525.000000000 200.096984863 +v 475.000000000 525.000000000 200.096984863 +v 750.000000000 550.000000000 201.088928223 +v 800.000000000 550.000000000 200.700729370 +v 400.000000000 563.817687988 225.000000000 +v 408.683074951 575.000000000 225.000000000 +v 425.000000000 575.000000000 214.283843994 +v 450.000000000 575.000000000 206.488540649 +v 475.000000000 575.000000000 202.519058228 +v 500.000000000 575.000000000 202.352813721 +v 525.000000000 575.000000000 200.546722412 +v 650.000000000 575.000000000 200.741867065 +v 675.000000000 575.000000000 201.336669922 +v 700.000000000 575.000000000 200.675781250 +v 425.000000000 595.072509766 225.000000000 +v 427.925354004 600.000000000 225.000000000 +v 450.000000000 600.000000000 210.113784790 +v 475.000000000 600.000000000 204.056900024 +v 500.000000000 600.000000000 203.305267334 +v 525.000000000 600.000000000 202.560089111 +v 550.000000000 600.000000000 200.021743774 +v 794.797851562 775.000000000 775.000000000 +v 798.395202637 775.000000000 800.000000000 +v 789.214721680 800.000000000 800.000000000 +v 786.282958984 800.000000000 775.000000000 +v 625.000000000 600.000000000 203.204895020 +v 650.000000000 600.000000000 203.966430664 +v 675.000000000 600.000000000 206.072402954 +v 700.000000000 600.000000000 205.412322998 +v 725.000000000 600.000000000 205.558090210 +v 750.000000000 600.000000000 203.986862183 +v 775.000000000 600.000000000 202.818634033 +v 800.000000000 600.000000000 201.143676758 +v 433.622589111 625.000000000 225.000000000 +v 450.000000000 625.000000000 208.426254272 +v 475.000000000 625.000000000 202.663040161 +v 500.000000000 625.000000000 202.252548218 +v 525.000000000 625.000000000 202.527145386 +v 550.000000000 625.000000000 202.710601807 +v 575.000000000 625.000000000 203.787521362 +v 600.000000000 625.000000000 205.431838989 +v 625.000000000 625.000000000 205.309555054 +v 650.000000000 625.000000000 203.437377930 +v 675.000000000 625.000000000 206.292221069 +v 700.000000000 625.000000000 205.563659668 +v 725.000000000 625.000000000 208.796829224 +v 750.000000000 625.000000000 209.180969238 +v 775.000000000 625.000000000 207.358337402 +v 800.000000000 625.000000000 200.286453247 +v 427.317749023 650.000000000 225.000000000 +v 500.000000000 650.000000000 200.484558105 +v 525.000000000 650.000000000 201.471405029 +v 575.000000000 650.000000000 200.023391724 +v 600.000000000 650.000000000 202.128631592 +v 625.000000000 650.000000000 202.267868042 +v 650.000000000 650.000000000 200.108917236 +v 675.000000000 650.000000000 202.423980713 +v 700.000000000 650.000000000 205.579071045 +v 725.000000000 650.000000000 209.396621704 +v 750.000000000 650.000000000 210.713119507 +v 775.000000000 650.000000000 208.754898071 +v 800.000000000 650.000000000 204.500930786 +v 0.000000000 675.000000000 208.108993530 +v 25.000000000 675.000000000 214.593246460 +v 25.000000000 669.584777832 225.000000000 +v 0.000000000 668.019287109 225.000000000 +v 42.190952301 675.000000000 225.000000000 +v 425.000000000 661.338623047 225.000000000 +v 419.890502930 675.000000000 225.000000000 +v 525.000000000 675.000000000 201.176452637 +v 550.000000000 675.000000000 202.544113159 +v 575.000000000 675.000000000 204.237319946 +v 600.000000000 675.000000000 203.661376953 +v 625.000000000 675.000000000 200.240798950 +v 675.000000000 675.000000000 200.325317383 +v 700.000000000 675.000000000 204.873916626 +v 725.000000000 675.000000000 209.178024292 +v 750.000000000 675.000000000 211.050582886 +v 775.000000000 675.000000000 211.078048706 +v 800.000000000 675.000000000 207.729629517 +v 0.000000000 700.000000000 210.753158569 +v 25.000000000 700.000000000 211.062545776 +v 50.000000000 700.000000000 213.127593994 +v 50.000000000 679.802795410 225.000000000 +v 75.000000000 700.000000000 218.548767090 +v 75.000000000 695.985412598 225.000000000 +v 100.000000000 700.000000000 220.625213623 +v 100.000000000 697.293884277 225.000000000 +v 125.000000000 700.000000000 218.588607788 +v 125.000000000 696.013000488 225.000000000 +v 150.000000000 700.000000000 214.834625244 +v 150.000000000 690.103881836 225.000000000 +v 175.000000000 700.000000000 216.741134644 +v 175.000000000 693.542480469 225.000000000 +v 200.000000000 700.000000000 222.568542480 +v 200.000000000 698.537902832 225.000000000 +v 225.000000000 700.000000000 217.868804932 +v 225.000000000 691.763427734 225.000000000 +v 250.000000000 700.000000000 217.948394775 +v 250.000000000 693.254394531 225.000000000 +v 275.000000000 700.000000000 220.103378296 +v 275.000000000 696.136108398 225.000000000 +v 298.339202881 700.000000000 225.000000000 +v 325.000000000 700.000000000 220.992858887 +v 325.000000000 697.737915039 225.000000000 +v 302.371795654 700.000000000 225.000000000 +v 350.000000000 700.000000000 215.358856201 +v 350.000000000 694.726745605 225.000000000 +v 325.000000000 700.000000000 220.992858887 +v 325.000000000 700.000000000 220.992858887 +v 325.000000000 697.737915039 225.000000000 +v 375.000000000 700.000000000 214.659286499 +v 375.000000000 684.001037598 225.000000000 +v 400.000000000 700.000000000 216.271759033 +v 400.000000000 689.524719238 225.000000000 +v 415.294586182 700.000000000 200.000000000 +v 415.294586182 700.000000000 200.000000000 +v 419.890502930 675.000000000 225.000000000 +v 525.000000000 700.000000000 205.650970459 +v 550.000000000 700.000000000 208.124206543 +v 575.000000000 700.000000000 209.847305298 +v 600.000000000 700.000000000 208.453155518 +v 625.000000000 700.000000000 208.442932129 +v 650.000000000 700.000000000 207.692214966 +v 675.000000000 700.000000000 208.430343628 +v 700.000000000 700.000000000 209.850219727 +v 725.000000000 700.000000000 212.513702393 +v 750.000000000 700.000000000 211.575439453 +v 775.000000000 700.000000000 212.279220581 +v 800.000000000 700.000000000 206.710342407 +v 0.000000000 725.000000000 210.207290649 +v 25.000000000 725.000000000 210.653778076 +v 0.000000000 700.000000000 210.753158569 +v 0.000000000 700.000000000 210.753158569 +v 25.000000000 700.000000000 211.062545776 +v 50.000000000 725.000000000 210.955780029 +v 25.000000000 700.000000000 211.062545776 +v 50.000000000 725.000000000 210.955780029 +v 75.000000000 725.000000000 211.749298096 +v 50.000000000 725.000000000 210.955780029 +v 100.000000000 725.000000000 211.987884521 +v 125.000000000 725.000000000 211.308532715 +v 150.000000000 725.000000000 210.919448853 +v 175.000000000 725.000000000 211.099838257 +v 150.000000000 700.000000000 214.834625244 +v 150.000000000 725.000000000 210.919448853 +v 175.000000000 725.000000000 211.099838257 +v 200.000000000 725.000000000 212.097900391 +v 175.000000000 725.000000000 211.099838257 +v 225.000000000 725.000000000 211.989547729 +v 250.000000000 725.000000000 213.376663208 +v 275.000000000 725.000000000 213.781021118 +v 300.000000000 725.000000000 213.738662720 +v 300.000000000 700.591430664 225.000000000 +v 325.000000000 725.000000000 212.245773315 +v 350.000000000 725.000000000 211.305358887 +v 325.000000000 700.000000000 220.992858887 +v 325.000000000 725.000000000 212.245773315 +v 325.000000000 700.000000000 220.992858887 +v 375.000000000 725.000000000 213.725753784 +v 400.000000000 725.000000000 213.075012207 +v 416.794769287 725.000000000 200.000000000 +v 416.794769287 725.000000000 200.000000000 +v 415.294586182 700.000000000 200.000000000 +v 500.000000000 725.000000000 201.386718750 +v 525.000000000 725.000000000 210.065368652 +v 550.000000000 725.000000000 213.097595215 +v 575.000000000 725.000000000 213.239868164 +v 600.000000000 725.000000000 213.336135864 +v 625.000000000 725.000000000 212.470596313 +v 650.000000000 725.000000000 212.252624512 +v 675.000000000 725.000000000 211.714004517 +v 700.000000000 725.000000000 212.528640747 +v 725.000000000 725.000000000 214.141174316 +v 750.000000000 725.000000000 213.778182983 +v 775.000000000 725.000000000 212.651306152 +v 800.000000000 725.000000000 205.795806885 +v 0.000000000 750.000000000 209.956481934 +v 25.000000000 750.000000000 210.572082520 +v 50.000000000 750.000000000 210.938262939 +v 75.000000000 750.000000000 211.196685791 +v 75.000000000 725.000000000 211.749298096 +v 100.000000000 750.000000000 211.053054810 +v 75.000000000 725.000000000 211.749298096 +v 75.000000000 725.000000000 211.749298096 +v 100.000000000 725.000000000 211.987884521 +v 125.000000000 750.000000000 210.771606445 +v 100.000000000 725.000000000 211.987884521 +v 100.000000000 725.000000000 211.987884521 +v 125.000000000 725.000000000 211.308532715 +v 150.000000000 750.000000000 210.589508057 +v 125.000000000 725.000000000 211.308532715 +v 125.000000000 725.000000000 211.308532715 +v 150.000000000 725.000000000 210.919448853 +v 175.000000000 750.000000000 210.154968262 +v 150.000000000 725.000000000 210.919448853 +v 150.000000000 725.000000000 210.919448853 +v 200.000000000 750.000000000 209.935455322 +v 200.000000000 725.000000000 212.097900391 +v 225.000000000 750.000000000 210.979156494 +v 200.000000000 725.000000000 212.097900391 +v 200.000000000 725.000000000 212.097900391 +v 225.000000000 725.000000000 211.989547729 +v 250.000000000 750.000000000 211.702392578 +v 225.000000000 725.000000000 211.989547729 +v 225.000000000 725.000000000 211.989547729 +v 250.000000000 725.000000000 213.376663208 +v 275.000000000 750.000000000 211.282302856 +v 250.000000000 725.000000000 213.376663208 +v 250.000000000 725.000000000 213.376663208 +v 275.000000000 725.000000000 213.781021118 +v 300.000000000 750.000000000 210.847503662 +v 275.000000000 725.000000000 213.781021118 +v 300.000000000 750.000000000 210.847503662 +v 325.000000000 750.000000000 211.043243408 +v 300.000000000 750.000000000 210.847503662 +v 350.000000000 750.000000000 212.169128418 +v 325.000000000 725.000000000 212.245773315 +v 325.000000000 750.000000000 211.043243408 +v 325.000000000 725.000000000 212.245773315 +v 375.000000000 750.000000000 213.716293335 +v 400.000000000 750.000000000 210.549713135 +v 411.781799316 750.000000000 200.000000000 +v 411.781799316 750.000000000 200.000000000 +v 416.794769287 725.000000000 200.000000000 +v 500.000000000 750.000000000 202.449340820 +v 525.000000000 750.000000000 211.889266968 +v 550.000000000 750.000000000 215.408020020 +v 575.000000000 750.000000000 215.812469482 +v 600.000000000 750.000000000 216.119476318 +v 625.000000000 750.000000000 212.644500732 +v 650.000000000 750.000000000 211.599044800 +v 675.000000000 750.000000000 213.918472290 +v 700.000000000 750.000000000 214.077117920 +v 725.000000000 750.000000000 213.698074341 +v 750.000000000 750.000000000 209.899307251 +v 775.000000000 750.000000000 208.384658813 +v 0.000000000 775.000000000 209.587982178 +v 25.000000000 775.000000000 210.751052856 +v 50.000000000 775.000000000 211.146789551 +v 75.000000000 775.000000000 211.173889160 +v 100.000000000 775.000000000 210.833145142 +v 125.000000000 775.000000000 210.530059814 +v 150.000000000 775.000000000 210.264160156 +v 175.000000000 775.000000000 209.686065674 +v 200.000000000 775.000000000 209.569641113 +v 225.000000000 775.000000000 210.804992676 +v 250.000000000 775.000000000 210.867172241 +v 275.000000000 775.000000000 210.545700073 +v 300.000000000 775.000000000 209.930297852 +v 325.000000000 775.000000000 212.104324341 +v 325.000000000 750.000000000 211.043243408 +v 350.000000000 775.000000000 213.597366333 +v 325.000000000 750.000000000 211.043243408 +v 325.000000000 750.000000000 211.043243408 +v 375.000000000 775.000000000 213.733886719 +v 400.000000000 775.000000000 202.198577881 +v 403.072631836 775.000000000 200.000000000 +v 403.072631836 775.000000000 200.000000000 +v 411.781799316 750.000000000 200.000000000 +v 525.000000000 775.000000000 208.948608398 +v 550.000000000 775.000000000 213.252136230 +v 575.000000000 775.000000000 216.774887085 +v 600.000000000 775.000000000 219.127487183 +v 625.000000000 775.000000000 218.247604370 +v 650.000000000 775.000000000 217.035125732 +v 675.000000000 775.000000000 217.890045166 +v 700.000000000 775.000000000 218.497604370 +v 725.000000000 775.000000000 217.635559082 +v 750.000000000 775.000000000 214.996383667 +v 775.000000000 775.000000000 211.557800293 +v 800.000000000 775.000000000 202.360839844 +v 0.000000000 800.000000000 209.093444824 +v 25.000000000 800.000000000 211.300567627 +v 50.000000000 800.000000000 211.585067749 +v 75.000000000 800.000000000 211.270980835 +v 100.000000000 800.000000000 210.642288208 +v 125.000000000 800.000000000 210.296371460 +v 150.000000000 800.000000000 209.956710815 +v 175.000000000 800.000000000 209.259506226 +v 200.000000000 800.000000000 208.533386230 +v 225.000000000 800.000000000 209.468429565 +v 250.000000000 800.000000000 212.309509277 +v 275.000000000 800.000000000 212.803695679 +v 300.000000000 800.000000000 212.400863647 +v 325.000000000 800.000000000 213.069534302 +v 350.000000000 800.000000000 214.530593872 +v 375.000000000 800.000000000 213.839752197 +v 400.000000000 800.000000000 205.278686523 +v 406.666503906 800.000000000 200.000000000 +v 406.666503906 800.000000000 200.000000000 +v 403.072631836 775.000000000 200.000000000 +v 525.000000000 800.000000000 207.156158447 +v 550.000000000 800.000000000 213.372421265 +v 575.000000000 800.000000000 217.830566406 +v 600.000000000 800.000000000 220.674758911 +v 625.000000000 800.000000000 220.738098145 +v 650.000000000 800.000000000 221.099517822 +v 675.000000000 800.000000000 221.711090088 +v 700.000000000 800.000000000 222.209167480 +v 725.000000000 800.000000000 222.364089966 +v 750.000000000 800.000000000 220.799468994 +v 775.000000000 800.000000000 211.586853027 +v 800.000000000 800.000000000 205.424591064 +v 800.000000000 241.848281860 250.000000000 +v 781.547668457 250.000000000 250.000000000 +v 750.000000000 267.409423828 250.000000000 +v 734.253417969 275.000000000 250.000000000 +v 775.000000000 253.483230591 250.000000000 +v 450.000000000 291.007263184 250.000000000 +v 433.908935547 300.000000000 250.000000000 +v 475.000000000 284.463409424 250.000000000 +v 500.000000000 288.840606689 250.000000000 +v 525.000000000 293.013916016 250.000000000 +v 525.000000000 292.611145020 225.000000000 +v 500.000000000 288.840606689 250.000000000 +v 550.000000000 294.717010498 250.000000000 +v 550.000000000 294.086883545 225.000000000 +v 550.000000000 294.086883545 225.000000000 +v 525.000000000 292.611145020 225.000000000 +v 575.000000000 295.362915039 250.000000000 +v 550.000000000 294.086883545 225.000000000 +v 600.000000000 292.620697021 250.000000000 +v 625.000000000 288.194000244 250.000000000 +v 650.000000000 289.984252930 250.000000000 +v 675.000000000 291.095275879 250.000000000 +v 700.000000000 287.442687988 250.000000000 +v 725.000000000 279.722290039 250.000000000 +v 425.000000000 308.047790527 250.000000000 +v 406.547180176 325.000000000 250.000000000 +v 400.000000000 334.483520508 250.000000000 +v 392.169342041 350.000000000 250.000000000 +v 375.000000000 375.000000000 228.266387939 +v 380.077362061 375.000000000 250.000000000 +v 375.000000000 396.698730469 250.000000000 +v 374.221649170 400.000000000 250.000000000 +v 371.584564209 425.000000000 250.000000000 +v 369.001861572 450.000000000 250.000000000 +v 370.564971924 475.000000000 250.000000000 +v 375.000000000 500.000000000 245.659057617 +v 375.000000000 496.151458740 250.000000000 +v 375.803649902 500.000000000 250.000000000 +v 382.398284912 525.000000000 250.000000000 +v 375.803649902 500.000000000 250.000000000 +v 375.000000000 512.421386719 225.000000000 +v 375.803649902 500.000000000 250.000000000 +v 392.644958496 550.000000000 250.000000000 +v 400.000000000 561.216857910 250.000000000 +v 410.207183838 575.000000000 250.000000000 +v 425.000000000 595.606140137 250.000000000 +v 427.368530273 600.000000000 250.000000000 +v 432.255310059 625.000000000 250.000000000 +v 427.287780762 650.000000000 250.000000000 +v 0.000000000 675.000000000 247.694686890 +v 25.000000000 669.791198730 250.000000000 +v 2.836338520 675.000000000 250.000000000 +v 38.629333496 675.000000000 250.000000000 +v 425.000000000 656.621887207 250.000000000 +v 417.227355957 675.000000000 250.000000000 +v 425.000000000 661.338623047 225.000000000 +v 425.000000000 661.338623047 225.000000000 +v 419.890502930 675.000000000 225.000000000 +v 425.000000000 656.621887207 250.000000000 +v 425.000000000 656.621887207 250.000000000 +v 0.000000000 675.713867188 250.000000000 +v 50.000000000 680.773254395 250.000000000 +v 75.000000000 695.158935547 250.000000000 +v 100.000000000 694.447753906 250.000000000 +v 125.000000000 692.814941406 250.000000000 +v 150.000000000 683.465209961 250.000000000 +v 175.000000000 692.675781250 250.000000000 +v 200.000000000 694.843566895 250.000000000 +v 225.000000000 687.281677246 250.000000000 +v 250.000000000 684.878112793 250.000000000 +v 275.000000000 690.146606445 250.000000000 +v 300.000000000 700.000000000 238.415527344 +v 300.000000000 699.813110352 250.000000000 +v 325.000000000 699.912597656 250.000000000 +v 350.000000000 695.801330566 250.000000000 +v 350.000000000 694.726745605 225.000000000 +v 350.000000000 694.726745605 225.000000000 +v 375.000000000 683.109313965 250.000000000 +v 350.000000000 695.801330566 250.000000000 +v 350.000000000 695.801330566 250.000000000 +v 400.000000000 690.859619141 250.000000000 +v 419.890502930 675.000000000 225.000000000 +v 419.890502930 675.000000000 225.000000000 +v 800.000000000 245.005447388 275.000000000 +v 785.441040039 250.000000000 275.000000000 +v 750.000000000 269.610229492 275.000000000 +v 736.382568359 275.000000000 275.000000000 +v 775.000000000 255.301330566 275.000000000 +v 450.000000000 300.000000000 273.644439697 +v 475.000000000 291.517059326 275.000000000 +v 451.831481934 300.000000000 275.000000000 +v 500.000000000 290.458526611 275.000000000 +v 525.000000000 288.958984375 275.000000000 +v 500.000000000 290.458526611 275.000000000 +v 500.000000000 290.458526611 275.000000000 +v 500.000000000 288.840606689 250.000000000 +v 550.000000000 286.314544678 275.000000000 +v 575.000000000 288.130889893 275.000000000 +v 600.000000000 288.299530029 275.000000000 +v 625.000000000 287.479339600 275.000000000 +v 650.000000000 287.984100342 275.000000000 +v 675.000000000 288.823547363 275.000000000 +v 700.000000000 286.307037354 275.000000000 +v 725.000000000 280.104309082 275.000000000 +v 425.000000000 323.408905029 275.000000000 +v 423.289398193 325.000000000 275.000000000 +v 450.000000000 300.731170654 275.000000000 +v 400.000000000 350.000000000 268.659698486 +v 403.220855713 350.000000000 275.000000000 +v 400.000000000 353.998443604 275.000000000 +v 387.175506592 375.000000000 275.000000000 +v 375.000000000 400.000000000 253.078491211 +v 381.586517334 400.000000000 275.000000000 +v 375.000000000 425.000000000 259.104248047 +v 381.623535156 425.000000000 275.000000000 +v 375.000000000 450.000000000 262.501647949 +v 381.251129150 450.000000000 275.000000000 +v 375.000000000 475.000000000 260.834777832 +v 381.306610107 475.000000000 275.000000000 +v 381.032287598 500.000000000 275.000000000 +v 381.210449219 525.000000000 275.000000000 +v 375.803649902 500.000000000 250.000000000 +v 381.210449219 525.000000000 275.000000000 +v 388.639129639 550.000000000 275.000000000 +v 381.210449219 525.000000000 275.000000000 +v 400.000000000 567.693420410 275.000000000 +v 404.898254395 575.000000000 275.000000000 +v 422.285400391 600.000000000 275.000000000 +v 425.000000000 600.000000000 261.808837891 +v 425.000000000 609.602600098 275.000000000 +v 429.082061768 625.000000000 275.000000000 +v 425.000000000 650.000000000 264.376892090 +v 425.000000000 643.236328125 275.000000000 +v 423.406036377 650.000000000 275.000000000 +v 25.000000000 675.000000000 261.818420410 +v 412.813079834 675.000000000 275.000000000 +v 425.000000000 656.621887207 250.000000000 +v 423.406036377 650.000000000 275.000000000 +v 423.406036377 650.000000000 275.000000000 +v 425.000000000 656.621887207 250.000000000 +v 25.000000000 680.923278809 275.000000000 +v 0.000000000 683.636901855 275.000000000 +v 50.000000000 687.925415039 275.000000000 +v 75.000000000 696.470947266 275.000000000 +v 100.000000000 695.284057617 275.000000000 +v 125.000000000 690.986694336 275.000000000 +v 150.000000000 687.069030762 275.000000000 +v 175.000000000 695.440368652 275.000000000 +v 200.000000000 689.597961426 275.000000000 +v 225.000000000 689.874450684 275.000000000 +v 250.000000000 688.393249512 275.000000000 +v 275.000000000 691.694946289 275.000000000 +v 300.000000000 699.026977539 275.000000000 +v 325.000000000 694.682617188 275.000000000 +v 350.000000000 695.819885254 275.000000000 +v 375.000000000 693.090820312 275.000000000 +v 350.000000000 695.819885254 275.000000000 +v 350.000000000 695.819885254 275.000000000 +v 350.000000000 695.801330566 250.000000000 +v 400.000000000 688.733215332 275.000000000 +v 800.000000000 250.000000000 298.064788818 +v 750.000000000 275.000000000 292.726959229 +v 775.000000000 263.002136230 300.000000000 +v 754.974060059 275.000000000 300.000000000 +v 800.000000000 250.566818237 300.000000000 +v 475.000000000 300.000000000 291.661315918 +v 500.000000000 299.519805908 300.000000000 +v 497.289520264 300.000000000 300.000000000 +v 525.000000000 295.090698242 300.000000000 +v 525.000000000 288.958984375 275.000000000 +v 525.000000000 288.958984375 275.000000000 +v 550.000000000 292.018218994 300.000000000 +v 525.000000000 295.090698242 300.000000000 +v 525.000000000 295.090698242 300.000000000 +v 575.000000000 290.833526611 300.000000000 +v 575.000000000 288.130889893 275.000000000 +v 550.000000000 292.018218994 300.000000000 +v 600.000000000 289.272155762 300.000000000 +v 575.000000000 290.833526611 300.000000000 +v 575.000000000 290.833526611 300.000000000 +v 625.000000000 288.945068359 300.000000000 +v 650.000000000 290.281799316 300.000000000 +v 675.000000000 291.490600586 300.000000000 +v 700.000000000 289.899383545 300.000000000 +v 725.000000000 287.320098877 300.000000000 +v 750.000000000 278.754730225 300.000000000 +v 425.000000000 325.000000000 277.071807861 +v 450.000000000 319.719970703 300.000000000 +v 444.212097168 325.000000000 300.000000000 +v 475.000000000 304.197631836 300.000000000 +v 425.000000000 347.173126221 300.000000000 +v 422.551788330 350.000000000 300.000000000 +v 400.000000000 375.000000000 298.811767578 +v 400.558898926 375.000000000 300.000000000 +v 400.000000000 376.961822510 300.000000000 +v 391.540588379 400.000000000 300.000000000 +v 390.064758301 425.000000000 300.000000000 +v 388.262207031 450.000000000 300.000000000 +v 387.349029541 475.000000000 300.000000000 +v 386.504211426 500.000000000 300.000000000 +v 386.874114990 525.000000000 300.000000000 +v 381.032287598 500.000000000 275.000000000 +v 386.504211426 500.000000000 300.000000000 +v 381.032287598 500.000000000 275.000000000 +v 381.210449219 525.000000000 275.000000000 +v 392.661956787 550.000000000 300.000000000 +v 381.210449219 525.000000000 275.000000000 +v 381.210449219 525.000000000 275.000000000 +v 400.000000000 564.752868652 300.000000000 +v 405.662963867 575.000000000 300.000000000 +v 424.384704590 600.000000000 300.000000000 +v 425.000000000 601.674377441 300.000000000 +v 431.990814209 625.000000000 300.000000000 +v 425.000000000 649.547607422 300.000000000 +v 424.869720459 650.000000000 300.000000000 +v 413.262786865 675.000000000 300.000000000 +v 423.406036377 650.000000000 275.000000000 +v 424.869720459 650.000000000 300.000000000 +v 423.406036377 650.000000000 275.000000000 +v 25.000000000 693.612548828 300.000000000 +v 0.000000000 688.148437500 300.000000000 +v 50.000000000 697.135620117 300.000000000 +v 75.000000000 697.694702148 300.000000000 +v 100.000000000 696.584838867 300.000000000 +v 125.000000000 697.419067383 300.000000000 +v 125.000000000 690.986694336 275.000000000 +v 100.000000000 696.584838867 300.000000000 +v 125.000000000 690.986694336 275.000000000 +v 100.000000000 696.584838867 300.000000000 +v 100.000000000 695.284057617 275.000000000 +v 150.000000000 697.795288086 300.000000000 +v 125.000000000 697.419067383 300.000000000 +v 150.000000000 687.069030762 275.000000000 +v 125.000000000 690.986694336 275.000000000 +v 175.000000000 696.443298340 300.000000000 +v 200.000000000 690.308288574 300.000000000 +v 225.000000000 689.834533691 300.000000000 +v 250.000000000 696.176208496 300.000000000 +v 275.000000000 699.099853516 300.000000000 +v 298.328674316 700.000000000 300.000000000 +v 300.000000000 700.000000000 298.242767334 +v 325.000000000 698.910827637 300.000000000 +v 301.601287842 700.000000000 300.000000000 +v 350.000000000 699.816101074 300.000000000 +v 375.000000000 698.758666992 300.000000000 +v 350.000000000 699.816101074 300.000000000 +v 350.000000000 699.816101074 300.000000000 +v 350.000000000 695.819885254 275.000000000 +v 400.000000000 688.496032715 300.000000000 +v 300.000000000 700.073181152 300.000000000 +v 775.000000000 270.760925293 325.000000000 +v 768.036193848 275.000000000 325.000000000 +v 800.000000000 256.286590576 325.000000000 +v 500.000000000 300.000000000 301.058959961 +v 525.000000000 300.000000000 310.856231689 +v 550.000000000 300.000000000 316.948394775 +v 550.000000000 292.018218994 300.000000000 +v 575.000000000 300.000000000 319.021057129 +v 550.000000000 292.018218994 300.000000000 +v 550.000000000 292.018218994 300.000000000 +v 600.000000000 300.000000000 320.843231201 +v 600.000000000 289.272155762 300.000000000 +v 625.000000000 299.916168213 325.000000000 +v 623.997253418 300.000000000 325.000000000 +v 600.000000000 289.272155762 300.000000000 +v 600.000000000 289.272155762 300.000000000 +v 600.000000000 289.272155762 300.000000000 +v 625.000000000 288.945068359 300.000000000 +v 650.000000000 295.627593994 325.000000000 +v 650.000000000 290.281799316 300.000000000 +v 650.000000000 290.281799316 300.000000000 +v 625.000000000 288.945068359 300.000000000 +v 675.000000000 291.338562012 325.000000000 +v 675.000000000 291.490600586 300.000000000 +v 675.000000000 291.490600586 300.000000000 +v 650.000000000 290.281799316 300.000000000 +v 700.000000000 290.000427246 325.000000000 +v 675.000000000 291.338562012 325.000000000 +v 675.000000000 291.338562012 325.000000000 +v 725.000000000 290.975524902 325.000000000 +v 750.000000000 289.936187744 325.000000000 +v 450.000000000 325.000000000 307.667388916 +v 475.000000000 316.190093994 325.000000000 +v 463.422241211 325.000000000 325.000000000 +v 500.000000000 311.449218750 325.000000000 +v 525.000000000 306.474365234 325.000000000 +v 550.000000000 303.755249023 325.000000000 +v 575.000000000 302.986389160 325.000000000 +v 600.000000000 302.212097168 325.000000000 +v 425.000000000 350.000000000 303.208648682 +v 450.000000000 333.676422119 325.000000000 +v 435.081634521 350.000000000 325.000000000 +v 425.000000000 361.031250000 325.000000000 +v 412.233459473 375.000000000 325.000000000 +v 400.000000000 400.000000000 319.661651611 +v 402.132415771 400.000000000 325.000000000 +v 400.000000000 416.652740479 325.000000000 +v 398.927429199 425.000000000 325.000000000 +v 395.690216064 450.000000000 325.000000000 +v 394.770538330 475.000000000 325.000000000 +v 395.424713135 500.000000000 325.000000000 +v 396.537139893 525.000000000 325.000000000 +v 386.504211426 500.000000000 300.000000000 +v 396.537139893 525.000000000 325.000000000 +v 400.000000000 550.000000000 320.473419189 +v 400.000000000 541.944335938 325.000000000 +v 396.537139893 525.000000000 325.000000000 +v 396.537139893 525.000000000 325.000000000 +v 401.669738770 550.000000000 325.000000000 +v 412.344848633 575.000000000 325.000000000 +v 425.000000000 600.000000000 305.108032227 +v 425.000000000 596.012329102 325.000000000 +v 427.009582520 600.000000000 325.000000000 +v 434.728424072 625.000000000 325.000000000 +v 425.000000000 650.000000000 300.765838623 +v 429.129974365 650.000000000 325.000000000 +v 425.000000000 660.699890137 325.000000000 +v 418.893768311 675.000000000 325.000000000 +v 418.893768311 675.000000000 325.000000000 +v 424.869720459 650.000000000 300.000000000 +v 25.000000000 698.669982910 325.000000000 +v 0.000000000 694.871643066 325.000000000 +v 50.000000000 699.928955078 325.000000000 +v 75.000000000 699.524291992 325.000000000 +v 100.000000000 698.867065430 325.000000000 +v 125.000000000 699.862976074 325.000000000 +v 125.000000000 697.419067383 300.000000000 +v 125.000000000 697.419067383 300.000000000 +v 136.091674805 700.000000000 325.000000000 +v 150.000000000 700.000000000 323.118927002 +v 125.000000000 697.419067383 300.000000000 +v 175.000000000 698.645874023 325.000000000 +v 152.581832886 700.000000000 325.000000000 +v 200.000000000 692.342346191 325.000000000 +v 225.000000000 695.540954590 325.000000000 +v 241.580169678 700.000000000 325.000000000 +v 250.000000000 700.000000000 315.765594482 +v 275.000000000 700.000000000 305.681243896 +v 325.000000000 700.000000000 309.741821289 +v 350.000000000 700.000000000 301.571777344 +v 375.000000000 700.000000000 314.290771484 +v 350.000000000 699.816101074 300.000000000 +v 350.000000000 699.816101074 300.000000000 +v 350.000000000 700.000000000 301.571777344 +v 400.000000000 693.687255859 325.000000000 +v 378.199279785 700.000000000 325.000000000 +v 418.893768311 675.000000000 325.000000000 +v 150.000000000 700.176574707 325.000000000 +v 250.000000000 702.278564453 325.000000000 +v 275.000000000 703.502014160 325.000000000 +v 300.000000000 702.529602051 325.000000000 +v 325.000000000 701.625366211 325.000000000 +v 350.000000000 702.901367188 325.000000000 +v 375.000000000 700.928161621 325.000000000 +v 350.000000000 702.901367188 325.000000000 +v 350.000000000 702.901367188 325.000000000 +v 350.000000000 700.000000000 301.571777344 +v 775.000000000 275.000000000 349.589630127 +v 800.000000000 258.285247803 350.000000000 +v 775.099060059 275.000000000 350.000000000 +v 625.000000000 300.000000000 325.310699463 +v 650.000000000 300.000000000 337.945617676 +v 675.000000000 300.000000000 346.289886475 +v 700.000000000 299.322143555 350.000000000 +v 692.800903320 300.000000000 350.000000000 +v 700.000000000 290.000427246 325.000000000 +v 725.000000000 296.475219727 350.000000000 +v 700.000000000 299.322143555 350.000000000 +v 700.000000000 299.322143555 350.000000000 +v 750.000000000 290.134094238 350.000000000 +v 775.000000000 275.103240967 350.000000000 +v 800.000000000 764.486572266 800.000000000 +v 798.155334473 750.000000000 775.000000000 +v 800.000000000 750.000000000 786.411437988 +v 475.000000000 316.418212891 350.000000000 +v 463.524566650 325.000000000 350.000000000 +v 500.000000000 315.192504883 350.000000000 +v 525.000000000 313.236358643 350.000000000 +v 550.000000000 311.533081055 350.000000000 +v 575.000000000 310.199829102 350.000000000 +v 600.000000000 309.004913330 350.000000000 +v 625.000000000 306.962310791 350.000000000 +v 650.000000000 304.273437500 350.000000000 +v 675.000000000 301.550292969 350.000000000 +v 450.000000000 332.912384033 350.000000000 +v 435.238922119 350.000000000 350.000000000 +v 425.000000000 361.852752686 350.000000000 +v 413.642547607 375.000000000 350.000000000 +v 404.783355713 400.000000000 350.000000000 +v 400.000000000 425.000000000 331.765136719 +v 402.977508545 425.000000000 350.000000000 +v 400.000000000 450.000000000 344.890289307 +v 401.156097412 450.000000000 350.000000000 +v 400.000000000 474.480102539 350.000000000 +v 399.974975586 475.000000000 350.000000000 +v 398.467651367 500.000000000 350.000000000 +v 397.493255615 525.000000000 350.000000000 +v 400.000000000 533.693908691 350.000000000 +v 396.537139893 525.000000000 325.000000000 +v 397.493255615 525.000000000 350.000000000 +v 397.493255615 525.000000000 350.000000000 +v 404.404937744 550.000000000 350.000000000 +v 417.469848633 575.000000000 350.000000000 +v 425.000000000 587.273864746 350.000000000 +v 431.963195801 600.000000000 350.000000000 +v 441.342742920 625.000000000 350.000000000 +v 434.050262451 650.000000000 350.000000000 +v 425.000000000 669.979003906 350.000000000 +v 422.630676270 675.000000000 350.000000000 +v 425.000000000 660.699890137 325.000000000 +v 425.000000000 660.699890137 325.000000000 +v 418.893768311 675.000000000 325.000000000 +v 425.000000000 669.979003906 350.000000000 +v 425.000000000 669.979003906 350.000000000 +v 22.139307022 700.000000000 350.000000000 +v 0.000000000 694.352844238 350.000000000 +v 25.000000000 700.000000000 339.931793213 +v 50.000000000 700.000000000 325.563201904 +v 75.000000000 700.000000000 330.369812012 +v 100.000000000 697.212585449 350.000000000 +v 84.022270203 700.000000000 350.000000000 +v 75.000000000 700.000000000 330.369812012 +v 75.000000000 699.524291992 325.000000000 +v 84.022270203 700.000000000 350.000000000 +v 120.942474365 700.000000000 350.000000000 +v 125.000000000 700.000000000 329.789672852 +v 175.000000000 696.068908691 350.000000000 +v 154.086441040 700.000000000 350.000000000 +v 200.000000000 692.611450195 350.000000000 +v 225.000000000 697.457641602 350.000000000 +v 233.258895874 700.000000000 350.000000000 +v 400.000000000 696.819091797 350.000000000 +v 384.608856201 700.000000000 350.000000000 +v 418.893768311 675.000000000 325.000000000 +v 418.893768311 675.000000000 325.000000000 +v 25.000000000 700.870483398 350.000000000 +v 50.000000000 703.129089355 350.000000000 +v 75.000000000 701.627319336 350.000000000 +v 75.000000000 700.000000000 330.369812012 +v 50.000000000 703.129089355 350.000000000 +v 75.000000000 700.000000000 330.369812012 +v 125.000000000 700.573669434 350.000000000 +v 150.000000000 700.891601562 350.000000000 +v 250.000000000 705.182373047 350.000000000 +v 275.000000000 705.861816406 350.000000000 +v 300.000000000 704.194885254 350.000000000 +v 325.000000000 702.276184082 350.000000000 +v 350.000000000 703.922180176 350.000000000 +v 375.000000000 701.901977539 350.000000000 +v 350.000000000 703.922180176 350.000000000 +v 350.000000000 703.922180176 350.000000000 +v 350.000000000 702.901367188 325.000000000 +v 775.000000000 275.000000000 350.148925781 +v 775.000000000 266.021759033 375.000000000 +v 752.404846191 275.000000000 375.000000000 +v 800.000000000 255.154510498 375.000000000 +v 575.000000000 300.000000000 374.272094727 +v 575.000000000 299.719116211 375.000000000 +v 573.350952148 300.000000000 375.000000000 +v 600.000000000 300.000000000 366.050445557 +v 600.000000000 295.460723877 375.000000000 +v 625.000000000 300.000000000 362.971893311 +v 625.000000000 292.745025635 375.000000000 +v 650.000000000 300.000000000 360.073181152 +v 650.000000000 292.948333740 375.000000000 +v 675.000000000 300.000000000 355.082214355 +v 675.000000000 293.085754395 375.000000000 +v 700.000000000 290.885742188 375.000000000 +v 725.000000000 284.872009277 375.000000000 +v 700.000000000 290.885742188 375.000000000 +v 725.000000000 296.475219727 350.000000000 +v 750.000000000 276.029907227 375.000000000 +v 798.085327148 725.000000000 775.000000000 +v 797.812438965 725.000000000 800.000000000 +v 800.000000000 738.093200684 800.000000000 +v 475.000000000 310.310638428 375.000000000 +v 451.480682373 325.000000000 375.000000000 +v 500.000000000 308.746398926 375.000000000 +v 525.000000000 306.681427002 375.000000000 +v 550.000000000 304.000610352 375.000000000 +v 450.000000000 325.729583740 375.000000000 +v 427.375793457 350.000000000 375.000000000 +v 425.000000000 352.548675537 375.000000000 +v 404.071044922 375.000000000 375.000000000 +v 400.000000000 400.000000000 362.451538086 +v 400.000000000 387.584686279 375.000000000 +v 394.869720459 400.000000000 375.000000000 +v 393.198486328 425.000000000 375.000000000 +v 400.000000000 425.000000000 357.896362305 +v 391.255676270 450.000000000 375.000000000 +v 400.000000000 450.000000000 352.982299805 +v 392.900360107 475.000000000 375.000000000 +v 395.981750488 500.000000000 375.000000000 +v 399.726348877 525.000000000 375.000000000 +v 400.000000000 525.804016113 375.000000000 +v 397.493255615 525.000000000 350.000000000 +v 399.726348877 525.000000000 375.000000000 +v 399.726348877 525.000000000 375.000000000 +v 407.725524902 550.000000000 375.000000000 +v 419.395599365 575.000000000 375.000000000 +v 425.000000000 584.968811035 375.000000000 +v 433.434570312 600.000000000 375.000000000 +v 443.072662354 625.000000000 375.000000000 +v 437.214935303 650.000000000 375.000000000 +v 425.000000000 675.000000000 373.264709473 +v 425.183471680 675.000000000 375.000000000 +v 434.050262451 650.000000000 350.000000000 +v 434.050262451 650.000000000 350.000000000 +v 425.183471680 675.000000000 375.000000000 +v 25.000000000 700.000000000 373.274993896 +v 25.000000000 699.930603027 375.000000000 +v 0.000000000 689.075439453 375.000000000 +v 25.446975708 700.000000000 375.000000000 +v 75.000000000 700.000000000 355.074523926 +v 75.000000000 693.474365234 375.000000000 +v 58.698547363 700.000000000 375.000000000 +v 100.000000000 688.937377930 375.000000000 +v 84.022270203 700.000000000 350.000000000 +v 125.000000000 700.000000000 361.618560791 +v 125.000000000 699.340332031 375.000000000 +v 150.000000000 700.000000000 352.793518066 +v 150.000000000 693.644592285 375.000000000 +v 175.000000000 691.515563965 375.000000000 +v 200.000000000 691.888122559 375.000000000 +v 225.000000000 693.367919922 375.000000000 +v 238.414077759 700.000000000 375.000000000 +v 400.000000000 700.000000000 374.852478027 +v 425.000000000 675.209472656 375.000000000 +v 400.023376465 700.000000000 375.000000000 +v 50.000000000 703.342224121 375.000000000 +v 50.000000000 703.342224121 375.000000000 +v 75.000000000 700.000000000 355.074523926 +v 50.000000000 703.342224121 375.000000000 +v 50.000000000 703.129089355 350.000000000 +v 75.000000000 700.000000000 355.074523926 +v 250.000000000 705.627746582 375.000000000 +v 275.000000000 708.189636230 375.000000000 +v 300.000000000 707.319641113 375.000000000 +v 325.000000000 705.268310547 375.000000000 +v 350.000000000 705.853820801 375.000000000 +v 350.000000000 703.922180176 350.000000000 +v 325.000000000 705.268310547 375.000000000 +v 375.000000000 703.457275391 375.000000000 +v 350.000000000 703.922180176 350.000000000 +v 400.000000000 700.018371582 375.000000000 +v 800.000000000 719.424804688 775.000000000 +v 800.000000000 703.492187500 800.000000000 +v 750.000000000 275.000000000 379.345184326 +v 750.000000000 270.705841064 400.000000000 +v 734.203247070 275.000000000 400.000000000 +v 775.000000000 261.863739014 400.000000000 +v 800.000000000 251.861953735 400.000000000 +v 550.000000000 300.000000000 392.947326660 +v 550.000000000 298.353088379 400.000000000 +v 539.635986328 300.000000000 400.000000000 +v 575.000000000 293.810333252 400.000000000 +v 600.000000000 289.114562988 400.000000000 +v 625.000000000 286.156280518 400.000000000 +v 650.000000000 284.595367432 400.000000000 +v 675.000000000 283.486450195 400.000000000 +v 700.000000000 281.157104492 400.000000000 +v 725.000000000 277.457550049 400.000000000 +v 700.000000000 281.157104492 400.000000000 +v 700.000000000 281.157104492 400.000000000 +v 700.000000000 290.885742188 375.000000000 +v 475.000000000 310.387145996 400.000000000 +v 453.560455322 325.000000000 400.000000000 +v 500.000000000 306.389648438 400.000000000 +v 525.000000000 302.348205566 400.000000000 +v 450.000000000 327.024627686 400.000000000 +v 428.011901855 350.000000000 400.000000000 +v 425.000000000 353.058135986 400.000000000 +v 403.974975586 375.000000000 400.000000000 +v 400.000000000 387.930114746 400.000000000 +v 395.107086182 400.000000000 400.000000000 +v 394.285400391 425.000000000 400.000000000 +v 393.638854980 450.000000000 400.000000000 +v 397.905059814 475.000000000 400.000000000 +v 400.000000000 500.000000000 385.742401123 +v 400.000000000 482.317169189 400.000000000 +v 405.263183594 500.000000000 400.000000000 +v 400.000000000 525.000000000 375.522644043 +v 412.048767090 525.000000000 400.000000000 +v 399.726348877 525.000000000 375.000000000 +v 400.000000000 525.000000000 375.522644043 +v 420.352111816 550.000000000 400.000000000 +v 400.000000000 525.000000000 375.522644043 +v 412.048767090 525.000000000 400.000000000 +v 412.048767090 525.000000000 400.000000000 +v 412.048767090 525.000000000 400.000000000 +v 425.000000000 575.000000000 386.992919922 +v 425.000000000 560.808410645 400.000000000 +v 431.087677002 575.000000000 400.000000000 +v 442.221557617 600.000000000 400.000000000 +v 448.818359375 625.000000000 400.000000000 +v 442.952209473 650.000000000 400.000000000 +v 428.900421143 675.000000000 400.000000000 +v 425.183471680 675.000000000 375.000000000 +v 25.000000000 681.654174805 400.000000000 +v 0.000000000 686.404052734 400.000000000 +v 50.000000000 700.000000000 379.967437744 +v 50.000000000 684.812133789 400.000000000 +v 75.000000000 683.277587891 400.000000000 +v 100.000000000 685.786560059 400.000000000 +v 125.000000000 692.230773926 400.000000000 +v 150.000000000 689.532653809 400.000000000 +v 175.000000000 687.953979492 400.000000000 +v 200.000000000 687.304565430 400.000000000 +v 225.000000000 690.620483398 400.000000000 +v 250.000000000 700.000000000 398.182952881 +v 250.000000000 699.572631836 400.000000000 +v 251.587341309 700.000000000 400.000000000 +v 375.000000000 700.000000000 395.945129395 +v 375.000000000 699.367797852 400.000000000 +v 373.196746826 700.000000000 400.000000000 +v 386.410400391 700.000000000 400.000000000 +v 425.000000000 679.610290527 400.000000000 +v 401.317504883 700.000000000 400.000000000 +v 428.900421143 675.000000000 400.000000000 +v 275.000000000 706.808471680 400.000000000 +v 300.000000000 706.312072754 400.000000000 +v 325.000000000 706.997802734 400.000000000 +v 350.000000000 707.972839355 400.000000000 +v 350.000000000 705.853820801 375.000000000 +v 350.000000000 705.853820801 375.000000000 +v 350.000000000 707.972839355 400.000000000 +v 350.000000000 707.972839355 400.000000000 +v 350.000000000 707.972839355 400.000000000 +v 400.000000000 700.808227539 400.000000000 +v 800.000000000 250.000000000 405.392791748 +v 800.000000000 244.325500488 425.000000000 +v 787.080322266 250.000000000 425.000000000 +v 725.000000000 275.000000000 422.715515137 +v 725.000000000 274.717468262 425.000000000 +v 721.834106445 275.000000000 425.000000000 +v 750.000000000 268.446594238 425.000000000 +v 775.000000000 257.390594482 425.000000000 +v 525.000000000 300.000000000 407.515563965 +v 525.000000000 295.174011230 425.000000000 +v 503.653106689 300.000000000 425.000000000 +v 550.000000000 291.560882568 425.000000000 +v 575.000000000 290.846099854 425.000000000 +v 600.000000000 290.086120605 425.000000000 +v 625.000000000 287.847625732 425.000000000 +v 650.000000000 283.415985107 425.000000000 +v 675.000000000 279.342834473 425.000000000 +v 700.000000000 276.880554199 425.000000000 +v 700.000000000 276.880554199 425.000000000 +v 700.000000000 276.880554199 425.000000000 +v 725.000000000 277.457550049 400.000000000 +v 475.000000000 307.453674316 425.000000000 +v 451.605072021 325.000000000 425.000000000 +v 500.000000000 300.909790039 425.000000000 +v 450.000000000 326.252441406 425.000000000 +v 429.769805908 350.000000000 425.000000000 +v 450.000000000 327.024627686 400.000000000 +v 450.000000000 327.024627686 400.000000000 +v 428.011901855 350.000000000 400.000000000 +v 450.000000000 326.252441406 425.000000000 +v 450.000000000 326.252441406 425.000000000 +v 425.000000000 354.955810547 425.000000000 +v 407.628631592 375.000000000 425.000000000 +v 428.011901855 350.000000000 400.000000000 +v 425.000000000 354.955810547 425.000000000 +v 400.000000000 400.000000000 422.255462646 +v 400.605712891 400.000000000 425.000000000 +v 400.000000000 425.000000000 418.405822754 +v 401.926910400 425.000000000 425.000000000 +v 400.000000000 450.000000000 417.638580322 +v 402.607879639 450.000000000 425.000000000 +v 400.000000000 475.000000000 405.757812500 +v 407.032409668 475.000000000 425.000000000 +v 413.160522461 500.000000000 425.000000000 +v 420.531982422 525.000000000 425.000000000 +v 425.000000000 550.000000000 415.705108643 +v 425.000000000 540.641784668 425.000000000 +v 420.531982422 525.000000000 425.000000000 +v 412.048767090 525.000000000 400.000000000 +v 420.531982422 525.000000000 425.000000000 +v 427.935729980 550.000000000 425.000000000 +v 435.574768066 575.000000000 425.000000000 +v 443.532806396 600.000000000 425.000000000 +v 448.471160889 625.000000000 425.000000000 +v 444.548858643 650.000000000 425.000000000 +v 435.855377197 675.000000000 425.000000000 +v 25.000000000 676.574584961 425.000000000 +v 0.000000000 676.976928711 425.000000000 +v 50.000000000 678.476196289 425.000000000 +v 75.000000000 685.206176758 425.000000000 +v 100.000000000 692.844909668 425.000000000 +v 125.000000000 695.905029297 425.000000000 +v 150.000000000 691.734313965 425.000000000 +v 175.000000000 690.116760254 425.000000000 +v 200.000000000 690.378051758 425.000000000 +v 225.000000000 692.596740723 425.000000000 +v 250.000000000 699.674621582 425.000000000 +v 251.881958008 700.000000000 425.000000000 +v 375.000000000 697.846191406 425.000000000 +v 370.517578125 700.000000000 425.000000000 +v 400.000000000 700.000000000 419.555725098 +v 400.000000000 699.739013672 425.000000000 +v 425.000000000 683.718505859 425.000000000 +v 425.000000000 679.610290527 400.000000000 +v 400.000000000 699.739013672 425.000000000 +v 425.000000000 679.610290527 400.000000000 +v 275.000000000 704.097290039 425.000000000 +v 300.000000000 705.868713379 425.000000000 +v 325.000000000 711.427795410 425.000000000 +v 350.000000000 708.997070312 425.000000000 +v 350.000000000 708.997070312 425.000000000 +v 350.000000000 708.997070312 425.000000000 +v 350.000000000 707.972839355 400.000000000 +v 800.000000000 238.972396851 450.000000000 +v 776.088928223 250.000000000 450.000000000 +v 725.000000000 275.000000000 431.018676758 +v 750.000000000 265.659057617 450.000000000 +v 727.326354980 275.000000000 450.000000000 +v 775.000000000 250.770904541 450.000000000 +v 475.000000000 300.000000000 438.931365967 +v 475.000000000 293.599151611 450.000000000 +v 458.691162109 300.000000000 450.000000000 +v 500.000000000 300.000000000 428.427124023 +v 500.000000000 293.657287598 450.000000000 +v 475.000000000 300.000000000 438.931365967 +v 475.000000000 300.000000000 438.931365967 +v 475.000000000 293.599151611 450.000000000 +v 525.000000000 291.244110107 450.000000000 +v 500.000000000 300.000000000 428.427124023 +v 525.000000000 295.174011230 425.000000000 +v 525.000000000 295.174011230 425.000000000 +v 550.000000000 291.797973633 450.000000000 +v 550.000000000 291.560882568 425.000000000 +v 550.000000000 291.560882568 425.000000000 +v 525.000000000 295.174011230 425.000000000 +v 575.000000000 291.122009277 450.000000000 +v 575.000000000 290.846099854 425.000000000 +v 575.000000000 290.846099854 425.000000000 +v 550.000000000 291.560882568 425.000000000 +v 600.000000000 288.605560303 450.000000000 +v 600.000000000 290.086120605 425.000000000 +v 600.000000000 290.086120605 425.000000000 +v 575.000000000 290.846099854 425.000000000 +v 625.000000000 287.520874023 450.000000000 +v 600.000000000 288.605560303 450.000000000 +v 600.000000000 288.605560303 450.000000000 +v 650.000000000 286.461486816 450.000000000 +v 675.000000000 285.071105957 450.000000000 +v 700.000000000 282.422271729 450.000000000 +v 725.000000000 275.859680176 450.000000000 +v 700.000000000 276.880554199 425.000000000 +v 700.000000000 282.422271729 450.000000000 +v 700.000000000 276.880554199 425.000000000 +v 450.000000000 325.000000000 427.786834717 +v 450.000000000 306.187438965 450.000000000 +v 433.763824463 325.000000000 450.000000000 +v 450.000000000 325.000000000 427.786834717 +v 475.000000000 307.453674316 425.000000000 +v 475.000000000 307.453674316 425.000000000 +v 475.000000000 300.000000000 438.931365967 +v 475.000000000 300.000000000 438.931365967 +v 458.691162109 300.000000000 450.000000000 +v 500.000000000 300.000000000 428.427124023 +v 500.000000000 300.000000000 428.427124023 +v 500.000000000 300.000000000 428.427124023 +v 425.000000000 350.000000000 441.958190918 +v 425.000000000 341.747680664 450.000000000 +v 421.414276123 350.000000000 450.000000000 +v 425.000000000 350.000000000 441.958190918 +v 450.000000000 326.252441406 425.000000000 +v 450.000000000 326.252441406 425.000000000 +v 450.000000000 325.000000000 427.786834717 +v 425.000000000 341.747680664 450.000000000 +v 450.000000000 325.000000000 427.786834717 +v 450.000000000 326.252441406 425.000000000 +v 409.029052734 375.000000000 450.000000000 +v 421.414276123 350.000000000 450.000000000 +v 407.628631592 375.000000000 425.000000000 +v 425.000000000 350.000000000 441.958190918 +v 425.000000000 354.955810547 425.000000000 +v 406.727874756 400.000000000 450.000000000 +v 407.628631592 375.000000000 425.000000000 +v 407.628631592 375.000000000 425.000000000 +v 400.605712891 400.000000000 425.000000000 +v 406.055969238 425.000000000 450.000000000 +v 400.605712891 400.000000000 425.000000000 +v 400.605712891 400.000000000 425.000000000 +v 401.926910400 425.000000000 425.000000000 +v 406.297729492 450.000000000 450.000000000 +v 401.926910400 425.000000000 425.000000000 +v 406.297729492 450.000000000 450.000000000 +v 409.064483643 475.000000000 450.000000000 +v 406.297729492 450.000000000 450.000000000 +v 412.803741455 500.000000000 450.000000000 +v 419.174530029 525.000000000 450.000000000 +v 425.000000000 541.870056152 450.000000000 +v 420.531982422 525.000000000 425.000000000 +v 419.174530029 525.000000000 450.000000000 +v 419.174530029 525.000000000 450.000000000 +v 427.908935547 550.000000000 450.000000000 +v 437.595123291 575.000000000 450.000000000 +v 446.444854736 600.000000000 450.000000000 +v 450.000000000 625.000000000 438.694915771 +v 450.000000000 618.821533203 450.000000000 +v 451.262176514 625.000000000 450.000000000 +v 450.000000000 629.652954102 450.000000000 +v 441.933715820 650.000000000 450.000000000 +v 429.376800537 675.000000000 450.000000000 +v 25.000000000 684.692871094 450.000000000 +v 0.000000000 682.803833008 450.000000000 +v 50.000000000 687.338256836 450.000000000 +v 75.000000000 698.440063477 450.000000000 +v 78.188110352 700.000000000 450.000000000 +v 100.000000000 700.000000000 435.326049805 +v 125.000000000 700.000000000 433.890533447 +v 150.000000000 698.246032715 450.000000000 +v 145.255950928 700.000000000 450.000000000 +v 175.000000000 698.130371094 450.000000000 +v 183.405929565 700.000000000 450.000000000 +v 200.000000000 700.000000000 443.037231445 +v 225.000000000 700.000000000 438.753417969 +v 250.000000000 700.000000000 425.869812012 +v 375.000000000 699.326416016 450.000000000 +v 373.854827881 700.000000000 450.000000000 +v 381.373443604 700.000000000 450.000000000 +v 400.000000000 700.000000000 427.647460938 +v 425.000000000 683.066467285 450.000000000 +v 406.717498779 700.000000000 450.000000000 +v 400.000000000 699.739013672 425.000000000 +v 425.000000000 683.066467285 450.000000000 +v 425.000000000 683.066467285 450.000000000 +v 425.000000000 683.066467285 450.000000000 +v 100.000000000 710.213256836 450.000000000 +v 125.000000000 707.810668945 450.000000000 +v 200.000000000 703.838806152 450.000000000 +v 225.000000000 706.252319336 450.000000000 +v 250.000000000 709.868896484 450.000000000 +v 275.000000000 710.549072266 450.000000000 +v 300.000000000 714.867431641 450.000000000 +v 325.000000000 717.030700684 450.000000000 +v 350.000000000 712.655639648 450.000000000 +v 350.000000000 712.655639648 450.000000000 +v 350.000000000 712.655639648 450.000000000 +v 350.000000000 708.997070312 425.000000000 +v 400.000000000 702.358032227 450.000000000 +v 800.000000000 242.585754395 475.000000000 +v 785.012512207 250.000000000 475.000000000 +v 725.000000000 275.000000000 459.548889160 +v 725.000000000 273.686126709 475.000000000 +v 718.220520020 275.000000000 475.000000000 +v 750.000000000 265.806091309 475.000000000 +v 775.000000000 255.287902832 475.000000000 +v 450.000000000 300.000000000 458.763061523 +v 450.000000000 294.785797119 475.000000000 +v 439.636230469 300.000000000 475.000000000 +v 475.000000000 286.663330078 475.000000000 +v 458.691162109 300.000000000 450.000000000 +v 475.000000000 293.599151611 450.000000000 +v 475.000000000 293.599151611 450.000000000 +v 475.000000000 293.599151611 450.000000000 +v 500.000000000 285.965820312 475.000000000 +v 475.000000000 293.599151611 450.000000000 +v 525.000000000 292.299163818 475.000000000 +v 550.000000000 293.413146973 475.000000000 +v 575.000000000 288.582672119 475.000000000 +v 600.000000000 283.048339844 475.000000000 +v 625.000000000 277.970245361 475.000000000 +v 625.000000000 287.520874023 450.000000000 +v 625.000000000 287.520874023 450.000000000 +v 650.000000000 277.649383545 475.000000000 +v 650.000000000 286.461486816 450.000000000 +v 650.000000000 286.461486816 450.000000000 +v 625.000000000 287.520874023 450.000000000 +v 675.000000000 279.005645752 475.000000000 +v 650.000000000 277.649383545 475.000000000 +v 650.000000000 277.649383545 475.000000000 +v 700.000000000 278.369689941 475.000000000 +v 700.000000000 278.369689941 475.000000000 +v 700.000000000 278.369689941 475.000000000 +v 700.000000000 278.369689941 475.000000000 +v 700.000000000 282.422271729 450.000000000 +v 425.000000000 325.000000000 461.253173828 +v 425.000000000 314.155029297 475.000000000 +v 414.192443848 325.000000000 475.000000000 +v 458.691162109 300.000000000 450.000000000 +v 401.595733643 350.000000000 475.000000000 +v 425.000000000 341.747680664 450.000000000 +v 421.414276123 350.000000000 450.000000000 +v 425.000000000 341.747680664 450.000000000 +v 421.414276123 350.000000000 450.000000000 +v 425.000000000 341.747680664 450.000000000 +v 400.000000000 375.000000000 469.024810791 +v 400.000000000 355.253387451 475.000000000 +v 395.878875732 375.000000000 475.000000000 +v 421.414276123 350.000000000 450.000000000 +v 398.591522217 400.000000000 475.000000000 +v 400.000000000 400.000000000 471.466003418 +v 400.000000000 411.016754150 475.000000000 +v 401.470428467 425.000000000 475.000000000 +v 400.274169922 450.000000000 475.000000000 +v 403.349670410 475.000000000 475.000000000 +v 409.064483643 475.000000000 450.000000000 +v 406.566894531 500.000000000 475.000000000 +v 409.064483643 475.000000000 450.000000000 +v 409.064483643 475.000000000 450.000000000 +v 412.803741455 500.000000000 450.000000000 +v 410.141357422 525.000000000 475.000000000 +v 412.803741455 500.000000000 450.000000000 +v 412.803741455 500.000000000 450.000000000 +v 419.174530029 525.000000000 450.000000000 +v 416.892730713 550.000000000 475.000000000 +v 425.000000000 550.000000000 456.257690430 +v 419.174530029 525.000000000 450.000000000 +v 419.174530029 525.000000000 450.000000000 +v 419.174530029 525.000000000 450.000000000 +v 425.000000000 569.135864258 475.000000000 +v 427.488098145 575.000000000 475.000000000 +v 439.573150635 600.000000000 475.000000000 +v 447.614562988 625.000000000 475.000000000 +v 450.000000000 625.000000000 458.981658936 +v 442.247161865 650.000000000 475.000000000 +v 433.360351562 675.000000000 475.000000000 +v 441.933715820 650.000000000 450.000000000 +v 433.360351562 675.000000000 475.000000000 +v 429.376800537 675.000000000 450.000000000 +v 25.000000000 693.220397949 475.000000000 +v 0.000000000 696.100830078 475.000000000 +v 50.000000000 695.524475098 475.000000000 +v 56.945060730 700.000000000 475.000000000 +v 75.000000000 700.000000000 452.714385986 +v 150.000000000 698.968444824 475.000000000 +v 147.345779419 700.000000000 475.000000000 +v 175.000000000 699.269958496 475.000000000 +v 177.953598022 700.000000000 475.000000000 +v 375.000000000 700.000000000 454.095947266 +v 425.000000000 694.406982422 475.000000000 +v 420.658782959 700.000000000 475.000000000 +v 429.376800537 675.000000000 450.000000000 +v 433.360351562 675.000000000 475.000000000 +v 429.376800537 675.000000000 450.000000000 +v 75.000000000 712.142944336 475.000000000 +v 100.000000000 712.955932617 475.000000000 +v 125.000000000 709.637817383 475.000000000 +v 200.000000000 705.944885254 475.000000000 +v 225.000000000 706.969116211 475.000000000 +v 250.000000000 707.672424316 475.000000000 +v 275.000000000 712.664245605 475.000000000 +v 300.000000000 718.368408203 475.000000000 +v 325.000000000 719.001037598 475.000000000 +v 350.000000000 714.303588867 475.000000000 +v 375.000000000 703.180419922 475.000000000 +v 350.000000000 712.655639648 450.000000000 +v 350.000000000 714.303588867 475.000000000 +v 350.000000000 712.655639648 450.000000000 +v 400.000000000 709.133789062 475.000000000 +v 800.000000000 250.000000000 487.821258545 +v 725.000000000 275.000000000 482.505950928 +v 750.000000000 275.000000000 498.793518066 +v 775.000000000 266.355407715 500.000000000 +v 751.193359375 275.000000000 500.000000000 +v 800.000000000 256.427856445 500.000000000 +v 450.000000000 300.000000000 492.818603516 +v 475.000000000 300.000000000 496.460205078 +v 500.000000000 300.000000000 488.437805176 +v 525.000000000 300.000000000 480.957611084 +v 550.000000000 300.000000000 481.543060303 +v 575.000000000 300.000000000 486.618225098 +v 600.000000000 300.000000000 491.980133057 +v 625.000000000 296.891021729 500.000000000 +v 618.843627930 300.000000000 500.000000000 +v 650.000000000 284.873840332 500.000000000 +v 675.000000000 279.815917969 500.000000000 +v 675.000000000 279.005645752 475.000000000 +v 675.000000000 279.005645752 475.000000000 +v 700.000000000 278.878845215 500.000000000 +v 700.000000000 278.369689941 475.000000000 +v 700.000000000 278.369689941 475.000000000 +v 675.000000000 279.005645752 475.000000000 +v 725.000000000 278.249023438 500.000000000 +v 725.000000000 275.000000000 482.505950928 +v 718.220520020 275.000000000 475.000000000 +v 718.220520020 275.000000000 475.000000000 +v 700.000000000 278.878845215 500.000000000 +v 750.000000000 275.514495850 500.000000000 +v 725.000000000 278.249023438 500.000000000 +v 725.000000000 278.249023438 500.000000000 +v 425.000000000 325.000000000 498.695709229 +v 450.000000000 317.087493896 500.000000000 +v 431.048004150 325.000000000 500.000000000 +v 475.000000000 325.000000000 495.936645508 +v 456.351623535 325.000000000 500.000000000 +v 500.000000000 325.000000000 491.814575195 +v 525.000000000 325.000000000 494.975860596 +v 550.000000000 325.000000000 497.486877441 +v 565.606933594 325.000000000 500.000000000 +v 575.000000000 322.067718506 500.000000000 +v 600.000000000 312.275421143 500.000000000 +v 425.000000000 350.000000000 498.011535645 +v 441.895690918 350.000000000 500.000000000 +v 475.000000000 350.000000000 492.595153809 +v 451.777496338 350.000000000 500.000000000 +v 500.000000000 350.000000000 499.091339111 +v 505.551147461 350.000000000 500.000000000 +v 525.000000000 339.081756592 500.000000000 +v 550.000000000 330.398681641 500.000000000 +v 400.000000000 375.000000000 481.599426270 +v 425.000000000 375.000000000 497.950256348 +v 450.000000000 353.436248779 500.000000000 +v 450.000000000 375.000000000 497.424316406 +v 475.000000000 368.123229980 500.000000000 +v 463.966705322 375.000000000 500.000000000 +v 450.000000000 375.000000000 497.424316406 +v 475.000000000 368.123229980 500.000000000 +v 500.000000000 353.105560303 500.000000000 +v 400.000000000 400.000000000 476.456939697 +v 425.000000000 400.000000000 490.103729248 +v 444.476898193 400.000000000 500.000000000 +v 450.000000000 389.437530518 500.000000000 +v 463.966705322 375.000000000 500.000000000 +v 425.000000000 425.000000000 495.468292236 +v 432.658142090 425.000000000 500.000000000 +v 425.000000000 450.000000000 498.714111328 +v 426.763549805 450.000000000 500.000000000 +v 425.000000000 457.674468994 500.000000000 +v 421.560729980 475.000000000 500.000000000 +v 418.458374023 500.000000000 500.000000000 +v 414.522216797 525.000000000 500.000000000 +v 415.012878418 550.000000000 500.000000000 +v 422.739685059 575.000000000 500.000000000 +v 425.000000000 575.000000000 488.607543945 +v 425.000000000 579.907531738 500.000000000 +v 433.784912109 600.000000000 500.000000000 +v 443.060028076 625.000000000 500.000000000 +v 438.861602783 650.000000000 500.000000000 +v 434.184753418 675.000000000 500.000000000 +v 25.000000000 700.000000000 499.558929443 +v 0.000000000 700.000000000 487.459808350 +v 50.000000000 700.000000000 498.663330078 +v 150.000000000 700.000000000 490.103485107 +v 175.000000000 700.000000000 480.587280273 +v 425.000000000 689.656738281 500.000000000 +v 417.088562012 700.000000000 500.000000000 +v 433.360351562 675.000000000 475.000000000 +v 434.184753418 675.000000000 500.000000000 +v 433.360351562 675.000000000 475.000000000 +v 25.000000000 700.160339355 500.000000000 +v 0.000000000 704.675720215 500.000000000 +v 50.000000000 700.364196777 500.000000000 +v 75.000000000 717.171325684 500.000000000 +v 100.000000000 710.392822266 500.000000000 +v 125.000000000 703.710754395 500.000000000 +v 150.000000000 700.781982422 500.000000000 +v 175.000000000 703.006286621 500.000000000 +v 200.000000000 703.289428711 500.000000000 +v 225.000000000 704.158752441 500.000000000 +v 250.000000000 707.741271973 500.000000000 +v 275.000000000 716.158203125 500.000000000 +v 300.000000000 719.197387695 500.000000000 +v 325.000000000 719.053649902 500.000000000 +v 350.000000000 716.874938965 500.000000000 +v 375.000000000 711.854858398 500.000000000 +v 350.000000000 716.874938965 500.000000000 +v 350.000000000 716.874938965 500.000000000 +v 350.000000000 714.303588867 475.000000000 +v 400.000000000 714.657531738 500.000000000 +v 775.000000000 271.104125977 525.000000000 +v 757.422119141 275.000000000 525.000000000 +v 800.000000000 262.312805176 525.000000000 +v 625.000000000 300.000000000 502.050354004 +v 650.000000000 300.000000000 515.239013672 +v 675.000000000 286.792175293 525.000000000 +v 661.354492188 300.000000000 525.000000000 +v 700.000000000 278.752288818 525.000000000 +v 725.000000000 277.691802979 525.000000000 +v 725.000000000 278.249023438 500.000000000 +v 725.000000000 278.249023438 500.000000000 +v 750.000000000 276.901123047 525.000000000 +v 725.000000000 278.249023438 500.000000000 +v 450.000000000 325.000000000 503.082366943 +v 575.000000000 325.000000000 501.042114258 +v 600.000000000 325.000000000 505.335479736 +v 625.000000000 325.000000000 515.107177734 +v 639.720642090 325.000000000 525.000000000 +v 650.000000000 312.407775879 525.000000000 +v 450.000000000 350.000000000 501.463653564 +v 525.000000000 350.000000000 503.455749512 +v 550.000000000 350.000000000 505.764923096 +v 575.000000000 350.000000000 512.502929688 +v 600.000000000 350.000000000 523.798278809 +v 601.906860352 350.000000000 525.000000000 +v 625.000000000 336.290893555 525.000000000 +v 475.000000000 375.000000000 501.916687012 +v 475.000000000 368.123229980 500.000000000 +v 500.000000000 375.000000000 506.165985107 +v 475.000000000 368.123229980 500.000000000 +v 500.000000000 375.000000000 506.165985107 +v 525.000000000 375.000000000 509.930419922 +v 550.000000000 375.000000000 517.985900879 +v 565.440124512 375.000000000 525.000000000 +v 575.000000000 368.140502930 525.000000000 +v 550.000000000 375.000000000 517.985900879 +v 575.000000000 368.140502930 525.000000000 +v 600.000000000 351.224792480 525.000000000 +v 575.000000000 368.140502930 525.000000000 +v 575.000000000 368.140502930 525.000000000 +v 450.000000000 400.000000000 501.539367676 +v 475.000000000 400.000000000 506.732116699 +v 463.966705322 375.000000000 500.000000000 +v 475.000000000 375.000000000 501.916687012 +v 475.000000000 375.000000000 501.916687012 +v 475.000000000 375.000000000 501.916687012 +v 500.000000000 400.000000000 512.497497559 +v 500.000000000 375.000000000 506.165985107 +v 475.000000000 400.000000000 506.732116699 +v 525.000000000 400.000000000 522.129516602 +v 500.000000000 375.000000000 506.165985107 +v 525.000000000 375.000000000 509.930419922 +v 500.000000000 375.000000000 506.165985107 +v 531.843444824 400.000000000 525.000000000 +v 550.000000000 386.183227539 525.000000000 +v 550.000000000 375.000000000 517.985900879 +v 525.000000000 375.000000000 509.930419922 +v 550.000000000 375.000000000 517.985900879 +v 550.000000000 375.000000000 517.985900879 +v 450.000000000 425.000000000 505.343200684 +v 475.000000000 425.000000000 514.495727539 +v 500.000000000 425.000000000 524.311950684 +v 475.000000000 400.000000000 506.732116699 +v 475.000000000 400.000000000 506.732116699 +v 475.000000000 425.000000000 514.495727539 +v 501.534118652 425.000000000 525.000000000 +v 525.000000000 405.394805908 525.000000000 +v 450.000000000 450.000000000 511.773773193 +v 470.207550049 450.000000000 525.000000000 +v 475.000000000 445.352111816 525.000000000 +v 500.000000000 426.239440918 525.000000000 +v 475.000000000 445.352111816 525.000000000 +v 475.000000000 445.352111816 525.000000000 +v 475.000000000 425.000000000 514.495727539 +v 425.000000000 475.000000000 502.703338623 +v 450.000000000 475.000000000 522.872558594 +v 452.379943848 475.000000000 525.000000000 +v 425.000000000 500.000000000 508.619110107 +v 437.814819336 500.000000000 525.000000000 +v 450.000000000 479.310089111 525.000000000 +v 425.000000000 523.613403320 525.000000000 +v 424.290740967 525.000000000 525.000000000 +v 416.505798340 550.000000000 525.000000000 +v 422.800445557 575.000000000 525.000000000 +v 425.000000000 581.246704102 525.000000000 +v 431.305541992 600.000000000 525.000000000 +v 436.649078369 625.000000000 525.000000000 +v 436.450622559 650.000000000 525.000000000 +v 435.042968750 675.000000000 525.000000000 +v 425.000000000 692.051147461 525.000000000 +v 419.788421631 700.000000000 525.000000000 +v 434.184753418 675.000000000 500.000000000 +v 435.042968750 675.000000000 525.000000000 +v 434.184753418 675.000000000 500.000000000 +v 25.000000000 709.410034180 525.000000000 +v 0.000000000 709.908874512 525.000000000 +v 50.000000000 711.869689941 525.000000000 +v 75.000000000 719.463623047 525.000000000 +v 100.000000000 710.267639160 525.000000000 +v 125.000000000 710.311096191 525.000000000 +v 150.000000000 712.947814941 525.000000000 +v 175.000000000 717.916198730 525.000000000 +v 200.000000000 709.808288574 525.000000000 +v 225.000000000 711.656494141 525.000000000 +v 250.000000000 716.767333984 525.000000000 +v 275.000000000 724.183593750 525.000000000 +v 296.476715088 725.000000000 525.000000000 +v 300.000000000 725.000000000 524.447814941 +v 325.000000000 723.679809570 525.000000000 +v 302.411254883 725.000000000 525.000000000 +v 350.000000000 720.776733398 525.000000000 +v 375.000000000 718.141540527 525.000000000 +v 350.000000000 720.776733398 525.000000000 +v 350.000000000 720.776733398 525.000000000 +v 350.000000000 716.874938965 500.000000000 +v 400.000000000 718.211303711 525.000000000 +v 300.000000000 725.145080566 525.000000000 +v 750.000000000 275.000000000 534.466369629 +v 750.000000000 272.364349365 550.000000000 +v 735.392639160 275.000000000 550.000000000 +v 775.000000000 267.470916748 550.000000000 +v 800.000000000 260.954895020 550.000000000 +v 675.000000000 300.000000000 549.779052734 +v 700.000000000 285.757080078 550.000000000 +v 675.201721191 300.000000000 550.000000000 +v 725.000000000 277.554779053 550.000000000 +v 650.000000000 325.000000000 539.446105957 +v 675.000000000 300.304412842 550.000000000 +v 661.508544922 325.000000000 550.000000000 +v 788.258728027 775.000000000 750.000000000 +v 786.440734863 800.000000000 750.000000000 +v 625.000000000 350.000000000 538.460571289 +v 650.000000000 350.000000000 547.255004883 +v 662.065429688 350.000000000 550.000000000 +v 575.000000000 375.000000000 530.634338379 +v 600.000000000 375.000000000 540.053955078 +v 575.000000000 368.140502930 525.000000000 +v 600.000000000 375.000000000 540.053955078 +v 625.000000000 375.000000000 545.511413574 +v 650.000000000 375.000000000 548.346923828 +v 662.427062988 375.000000000 550.000000000 +v 550.000000000 400.000000000 535.549194336 +v 575.000000000 400.000000000 543.648315430 +v 600.000000000 400.000000000 547.584594727 +v 600.000000000 375.000000000 540.053955078 +v 625.000000000 400.000000000 549.722961426 +v 600.000000000 375.000000000 540.053955078 +v 625.000000000 375.000000000 545.511413574 +v 600.000000000 375.000000000 540.053955078 +v 626.981567383 400.000000000 550.000000000 +v 650.000000000 382.984985352 550.000000000 +v 650.000000000 375.000000000 548.346923828 +v 625.000000000 375.000000000 545.511413574 +v 650.000000000 375.000000000 548.346923828 +v 650.000000000 375.000000000 548.346923828 +v 662.427062988 375.000000000 550.000000000 +v 525.000000000 425.000000000 538.062927246 +v 550.000000000 424.529693604 550.000000000 +v 549.486206055 425.000000000 550.000000000 +v 575.000000000 411.225189209 550.000000000 +v 600.000000000 406.077911377 550.000000000 +v 625.000000000 401.313629150 550.000000000 +v 475.000000000 450.000000000 528.126037598 +v 475.000000000 445.352111816 525.000000000 +v 470.207550049 450.000000000 525.000000000 +v 500.000000000 450.000000000 538.888000488 +v 475.000000000 445.352111816 525.000000000 +v 475.000000000 445.352111816 525.000000000 +v 525.000000000 450.000000000 549.443786621 +v 526.401306152 450.000000000 550.000000000 +v 475.000000000 475.000000000 539.445861816 +v 475.000000000 450.000000000 528.126037598 +v 500.000000000 475.000000000 546.459533691 +v 475.000000000 450.000000000 528.126037598 +v 500.000000000 475.000000000 546.459533691 +v 511.933074951 475.000000000 550.000000000 +v 525.000000000 452.543548584 550.000000000 +v 450.000000000 500.000000000 534.055175781 +v 475.000000000 500.000000000 545.437500000 +v 497.972961426 500.000000000 550.000000000 +v 500.000000000 497.903259277 550.000000000 +v 500.000000000 475.000000000 546.459533691 +v 500.000000000 475.000000000 546.459533691 +v 500.000000000 497.903259277 550.000000000 +v 425.000000000 525.000000000 525.568664551 +v 450.000000000 525.000000000 540.869995117 +v 474.768341064 525.000000000 550.000000000 +v 475.000000000 524.603820801 550.000000000 +v 425.000000000 550.000000000 531.637878418 +v 450.000000000 550.000000000 545.140136719 +v 459.359802246 550.000000000 550.000000000 +v 425.000000000 575.000000000 527.475280762 +v 448.757781982 575.000000000 550.000000000 +v 450.000000000 571.910766602 550.000000000 +v 443.607757568 600.000000000 550.000000000 +v 444.092742920 625.000000000 550.000000000 +v 443.498809814 650.000000000 550.000000000 +v 440.439086914 675.000000000 550.000000000 +v 425.000000000 700.000000000 543.553649902 +v 427.500091553 700.000000000 550.000000000 +v 435.042968750 675.000000000 525.000000000 +v 435.042968750 675.000000000 525.000000000 +v 427.500091553 700.000000000 550.000000000 +v 9.043959618 725.000000000 550.000000000 +v 0.000000000 721.610290527 550.000000000 +v 25.000000000 725.000000000 543.203918457 +v 50.000000000 725.000000000 541.242309570 +v 75.000000000 725.000000000 536.700561523 +v 100.000000000 725.000000000 545.550842285 +v 125.000000000 725.000000000 542.523498535 +v 150.000000000 725.000000000 540.533325195 +v 175.000000000 725.000000000 537.653991699 +v 200.000000000 725.000000000 548.973144531 +v 225.000000000 725.000000000 547.812194824 +v 250.000000000 725.000000000 548.735656738 +v 275.000000000 725.000000000 527.712829590 +v 325.000000000 725.000000000 528.946166992 +v 350.000000000 725.000000000 536.628662109 +v 375.000000000 725.000000000 544.395507812 +v 350.000000000 720.776733398 525.000000000 +v 350.000000000 720.776733398 525.000000000 +v 350.000000000 725.000000000 536.628662109 +v 400.000000000 725.000000000 545.683410645 +v 425.000000000 703.120422363 550.000000000 +v 402.703521729 725.000000000 550.000000000 +v 25.000000000 732.719482422 550.000000000 +v 50.000000000 734.914001465 550.000000000 +v 75.000000000 734.622253418 550.000000000 +v 100.000000000 730.509643555 550.000000000 +v 125.000000000 733.560119629 550.000000000 +v 150.000000000 734.538391113 550.000000000 +v 175.000000000 732.994384766 550.000000000 +v 200.000000000 726.167480469 550.000000000 +v 225.000000000 727.384216309 550.000000000 +v 250.000000000 726.001098633 550.000000000 +v 275.000000000 736.683959961 550.000000000 +v 300.000000000 737.206726074 550.000000000 +v 325.000000000 736.334777832 550.000000000 +v 350.000000000 732.089660645 550.000000000 +v 375.000000000 728.162658691 550.000000000 +v 350.000000000 732.089660645 550.000000000 +v 350.000000000 732.089660645 550.000000000 +v 350.000000000 725.000000000 536.628662109 +v 400.000000000 727.145568848 550.000000000 +v 725.000000000 275.000000000 564.707092285 +v 725.000000000 273.680694580 575.000000000 +v 718.736755371 275.000000000 575.000000000 +v 750.000000000 269.064605713 575.000000000 +v 775.000000000 264.669830322 575.000000000 +v 800.000000000 260.587066650 575.000000000 +v 675.000000000 300.000000000 567.797607422 +v 675.000000000 299.920043945 575.000000000 +v 674.927978516 300.000000000 575.000000000 +v 700.000000000 282.446563721 575.000000000 +v 675.000000000 325.000000000 564.272583008 +v 675.000000000 300.164825439 575.000000000 +v 683.175964355 325.000000000 575.000000000 +v 675.000000000 350.000000000 556.905090332 +v 684.379699707 350.000000000 575.000000000 +v 675.000000000 375.000000000 555.577026367 +v 688.046386719 375.000000000 575.000000000 +v 650.000000000 400.000000000 557.556274414 +v 675.000000000 400.000000000 569.755676270 +v 662.427062988 375.000000000 550.000000000 +v 675.000000000 375.000000000 555.577026367 +v 675.000000000 375.000000000 555.577026367 +v 650.000000000 400.000000000 557.556274414 +v 689.124023438 400.000000000 575.000000000 +v 550.000000000 425.000000000 550.136169434 +v 575.000000000 425.000000000 555.670898438 +v 600.000000000 425.000000000 559.058166504 +v 625.000000000 425.000000000 561.751098633 +v 650.000000000 425.000000000 571.088439941 +v 650.000000000 400.000000000 557.556274414 +v 625.000000000 425.000000000 561.751098633 +v 667.433288574 425.000000000 575.000000000 +v 675.000000000 418.620727539 575.000000000 +v 650.000000000 400.000000000 557.556274414 +v 550.000000000 450.000000000 556.163085938 +v 575.000000000 450.000000000 561.607727051 +v 600.000000000 450.000000000 568.372924805 +v 625.000000000 450.000000000 573.298339844 +v 600.000000000 425.000000000 559.058166504 +v 625.000000000 425.000000000 561.751098633 +v 600.000000000 425.000000000 559.058166504 +v 600.000000000 450.000000000 568.372924805 +v 638.380615234 450.000000000 575.000000000 +v 650.000000000 440.587463379 575.000000000 +v 625.000000000 425.000000000 561.751098633 +v 525.000000000 475.000000000 554.473815918 +v 550.000000000 475.000000000 562.782165527 +v 550.000000000 450.000000000 556.163085938 +v 525.000000000 475.000000000 554.473815918 +v 575.000000000 475.000000000 569.050720215 +v 550.000000000 450.000000000 556.163085938 +v 575.000000000 450.000000000 561.607727051 +v 550.000000000 450.000000000 556.163085938 +v 596.716186523 475.000000000 575.000000000 +v 600.000000000 472.432220459 575.000000000 +v 600.000000000 450.000000000 568.372924805 +v 575.000000000 450.000000000 561.607727051 +v 600.000000000 450.000000000 568.372924805 +v 625.000000000 465.262542725 575.000000000 +v 600.000000000 450.000000000 568.372924805 +v 500.000000000 500.000000000 550.336914062 +v 500.000000000 497.903259277 550.000000000 +v 497.972961426 500.000000000 550.000000000 +v 525.000000000 500.000000000 559.755371094 +v 500.000000000 497.903259277 550.000000000 +v 500.000000000 497.903259277 550.000000000 +v 550.000000000 500.000000000 570.083740234 +v 525.000000000 475.000000000 554.473815918 +v 525.000000000 475.000000000 554.473815918 +v 525.000000000 500.000000000 559.755371094 +v 568.863586426 500.000000000 575.000000000 +v 575.000000000 494.570220947 575.000000000 +v 475.000000000 525.000000000 550.056701660 +v 789.532958984 750.000000000 750.000000000 +v 500.000000000 525.000000000 557.440002441 +v 500.000000000 500.000000000 550.336914062 +v 500.000000000 500.000000000 550.336914062 +v 500.000000000 500.000000000 550.336914062 +v 525.000000000 525.000000000 566.166687012 +v 500.000000000 500.000000000 550.336914062 +v 525.000000000 525.000000000 566.166687012 +v 550.000000000 525.000000000 574.834838867 +v 525.000000000 500.000000000 559.755371094 +v 525.000000000 500.000000000 559.755371094 +v 525.000000000 525.000000000 566.166687012 +v 550.656921387 525.000000000 575.000000000 +v 475.000000000 550.000000000 556.163146973 +v 500.000000000 550.000000000 564.638732910 +v 525.000000000 550.000000000 571.928588867 +v 525.000000000 525.000000000 566.166687012 +v 538.319458008 550.000000000 575.000000000 +v 550.000000000 526.145263672 575.000000000 +v 525.000000000 525.000000000 566.166687012 +v 450.000000000 575.000000000 551.296081543 +v 475.000000000 575.000000000 565.179748535 +v 500.000000000 575.000000000 570.423767090 +v 520.067382812 575.000000000 575.000000000 +v 525.000000000 568.751831055 575.000000000 +v 450.000000000 600.000000000 560.898376465 +v 473.816284180 600.000000000 575.000000000 +v 475.000000000 599.350830078 575.000000000 +v 500.000000000 591.459472656 575.000000000 +v 450.000000000 625.000000000 560.384399414 +v 462.600097656 625.000000000 575.000000000 +v 450.000000000 650.000000000 559.085876465 +v 475.000000000 645.593261719 575.000000000 +v 475.000000000 650.000000000 573.541931152 +v 487.021636963 650.000000000 575.000000000 +v 450.000000000 675.000000000 559.335205078 +v 475.000000000 675.000000000 566.281005859 +v 500.000000000 664.469787598 575.000000000 +v 500.000000000 675.000000000 574.265258789 +v 503.410766602 675.000000000 575.000000000 +v 450.000000000 700.000000000 566.489501953 +v 427.500091553 700.000000000 550.000000000 +v 475.000000000 700.000000000 569.588806152 +v 488.233886719 700.000000000 575.000000000 +v 500.000000000 679.982421875 575.000000000 +v 0.000000000 725.000000000 553.471679688 +v 425.000000000 725.000000000 562.674560547 +v 450.000000000 725.000000000 572.172302246 +v 427.500091553 700.000000000 550.000000000 +v 425.000000000 703.120422363 550.000000000 +v 425.000000000 725.000000000 562.674560547 +v 425.000000000 703.120422363 550.000000000 +v 425.000000000 725.000000000 562.674560547 +v 475.000000000 725.000000000 573.759094238 +v 477.960296631 725.000000000 575.000000000 +v 25.000000000 750.000000000 563.007690430 +v 0.403049946 750.000000000 575.000000000 +v 0.000000000 749.761779785 575.000000000 +v 50.000000000 750.000000000 559.903320312 +v 75.000000000 750.000000000 560.094726562 +v 100.000000000 750.000000000 562.978820801 +v 125.000000000 750.000000000 563.983032227 +v 150.000000000 750.000000000 563.418884277 +v 175.000000000 750.000000000 564.123535156 +v 200.000000000 750.000000000 563.636291504 +v 225.000000000 750.000000000 560.866149902 +v 250.000000000 750.000000000 560.439331055 +v 275.000000000 750.000000000 558.072387695 +v 300.000000000 750.000000000 557.932922363 +v 325.000000000 750.000000000 559.167724609 +v 350.000000000 750.000000000 563.948486328 +v 375.000000000 750.000000000 568.454345703 +v 350.000000000 732.089660645 550.000000000 +v 350.000000000 732.089660645 550.000000000 +v 350.000000000 750.000000000 563.948486328 +v 400.000000000 750.000000000 566.625183105 +v 425.000000000 750.000000000 570.939575195 +v 441.455352783 750.000000000 575.000000000 +v 450.000000000 738.988769531 575.000000000 +v 450.000000000 725.000000000 572.172302246 +v 450.000000000 725.000000000 572.172302246 +v 475.000000000 731.813598633 575.000000000 +v 475.000000000 725.000000000 573.759094238 +v 475.000000000 725.000000000 573.759094238 +v 450.000000000 725.000000000 572.172302246 +v 475.000000000 725.000000000 573.759094238 +v 477.960296631 725.000000000 575.000000000 +v 25.000000000 775.000000000 573.482299805 +v 20.910318375 775.000000000 575.000000000 +v 50.000000000 775.000000000 568.081726074 +v 75.000000000 775.000000000 570.299133301 +v 100.000000000 775.000000000 571.591125488 +v 125.000000000 775.000000000 573.382507324 +v 150.000000000 775.000000000 573.180541992 +v 175.000000000 775.000000000 572.443054199 +v 200.000000000 775.000000000 569.413818359 +v 225.000000000 775.000000000 566.408752441 +v 250.000000000 775.000000000 565.181579590 +v 275.000000000 775.000000000 564.357727051 +v 300.000000000 775.000000000 563.674499512 +v 325.000000000 775.000000000 568.688964844 +v 350.000000000 775.000000000 570.499633789 +v 375.000000000 775.000000000 573.929687500 +v 350.000000000 750.000000000 563.948486328 +v 350.000000000 750.000000000 563.948486328 +v 350.000000000 775.000000000 570.499633789 +v 400.000000000 775.000000000 572.257934570 +v 425.000000000 775.000000000 573.360656738 +v 435.239501953 775.000000000 575.000000000 +v 25.000000000 783.630920410 575.000000000 +v 50.000000000 800.000000000 572.796325684 +v 38.755012512 800.000000000 575.000000000 +v 75.000000000 800.000000000 572.608337402 +v 100.000000000 800.000000000 573.616027832 +v 125.000000000 800.000000000 573.409179688 +v 150.000000000 800.000000000 574.342224121 +v 170.500701904 800.000000000 575.000000000 +v 175.000000000 798.608459473 575.000000000 +v 200.000000000 800.000000000 572.316162109 +v 176.368484497 800.000000000 575.000000000 +v 225.000000000 800.000000000 571.430419922 +v 250.000000000 800.000000000 569.146972656 +v 275.000000000 800.000000000 567.369384766 +v 300.000000000 800.000000000 566.857360840 +v 325.000000000 800.000000000 568.426513672 +v 350.000000000 800.000000000 573.754028320 +v 374.438385010 800.000000000 575.000000000 +v 375.000000000 799.312377930 575.000000000 +v 350.000000000 800.000000000 573.754028320 +v 350.000000000 800.000000000 573.754028320 +v 350.000000000 800.000000000 573.754028320 +v 350.000000000 775.000000000 570.499633789 +v 400.000000000 800.000000000 572.823120117 +v 375.347930908 800.000000000 575.000000000 +v 425.000000000 800.000000000 573.503234863 +v 433.748474121 800.000000000 575.000000000 +v 725.000000000 275.000000000 576.328002930 +v 750.000000000 275.000000000 580.382751465 +v 725.000000000 273.680694580 575.000000000 +v 750.000000000 269.064605713 575.000000000 +v 725.000000000 273.680694580 575.000000000 +v 725.000000000 275.000000000 576.328002930 +v 775.000000000 275.000000000 583.435485840 +v 750.000000000 275.000000000 580.382751465 +v 800.000000000 275.000000000 589.811950684 +v 675.000000000 300.000000000 575.033142090 +v 792.581909180 725.000000000 750.000000000 +v 700.000000000 300.000000000 584.351379395 +v 725.000000000 300.000000000 589.802429199 +v 750.000000000 300.000000000 593.661621094 +v 750.000000000 275.000000000 580.382751465 +v 775.000000000 300.000000000 596.226562500 +v 750.000000000 275.000000000 580.382751465 +v 750.000000000 275.000000000 580.382751465 +v 796.568115234 300.000000000 600.000000000 +v 800.000000000 298.013641357 600.000000000 +v 800.000000000 710.833801270 750.000000000 +v 700.000000000 325.000000000 584.303344727 +v 725.000000000 325.000000000 593.479309082 +v 750.000000000 325.000000000 597.163146973 +v 775.000000000 325.000000000 598.881591797 +v 783.620910645 325.000000000 600.000000000 +v 700.000000000 350.000000000 585.296020508 +v 725.000000000 350.000000000 592.456359863 +v 750.000000000 350.000000000 596.470703125 +v 775.000000000 350.000000000 599.280456543 +v 787.898254395 350.000000000 600.000000000 +v 700.000000000 375.000000000 582.473693848 +v 725.000000000 375.000000000 590.264404297 +v 750.000000000 375.000000000 595.598632812 +v 775.000000000 375.000000000 598.951843262 +v 793.863586426 375.000000000 600.000000000 +v 700.000000000 400.000000000 577.480224609 +v 725.000000000 400.000000000 583.085571289 +v 750.000000000 400.000000000 591.271362305 +v 775.000000000 400.000000000 596.865966797 +v 800.000000000 389.650054932 600.000000000 +v 800.000000000 400.000000000 599.679077148 +v 675.000000000 425.000000000 576.359680176 +v 700.000000000 425.000000000 577.565002441 +v 725.000000000 425.000000000 581.503173828 +v 750.000000000 425.000000000 588.092590332 +v 775.000000000 425.000000000 594.490661621 +v 800.000000000 425.000000000 598.197509766 +v 650.000000000 450.000000000 576.841857910 +v 675.000000000 450.000000000 578.583984375 +v 700.000000000 450.000000000 580.559753418 +v 725.000000000 450.000000000 581.476379395 +v 750.000000000 450.000000000 586.157958984 +v 775.000000000 450.000000000 592.048645020 +v 800.000000000 450.000000000 597.753112793 +v 600.000000000 475.000000000 576.058776855 +v 625.000000000 475.000000000 576.356811523 +v 650.000000000 475.000000000 577.459594727 +v 675.000000000 475.000000000 579.475524902 +v 700.000000000 475.000000000 580.813842773 +v 725.000000000 475.000000000 583.696472168 +v 750.000000000 475.000000000 585.864990234 +v 775.000000000 475.000000000 589.836914062 +v 800.000000000 475.000000000 596.384338379 +v 575.000000000 500.000000000 576.797912598 +v 600.000000000 500.000000000 578.198669434 +v 625.000000000 500.000000000 578.568725586 +v 650.000000000 500.000000000 579.540100098 +v 675.000000000 500.000000000 581.268859863 +v 700.000000000 500.000000000 583.022338867 +v 725.000000000 500.000000000 587.003967285 +v 750.000000000 500.000000000 587.809936523 +v 775.000000000 500.000000000 590.997070312 +v 800.000000000 500.000000000 597.278747559 +v 575.000000000 525.000000000 580.335021973 +v 600.000000000 525.000000000 578.910400391 +v 625.000000000 525.000000000 579.669250488 +v 650.000000000 525.000000000 580.899963379 +v 675.000000000 525.000000000 583.392578125 +v 700.000000000 525.000000000 585.737304688 +v 725.000000000 525.000000000 587.732055664 +v 750.000000000 525.000000000 590.694824219 +v 775.000000000 525.000000000 593.926452637 +v 800.000000000 525.000000000 597.622802734 +v 550.000000000 550.000000000 577.987182617 +v 575.000000000 550.000000000 581.936645508 +v 600.000000000 550.000000000 581.850463867 +v 625.000000000 550.000000000 583.054321289 +v 650.000000000 550.000000000 583.802917480 +v 675.000000000 550.000000000 587.062500000 +v 700.000000000 550.000000000 586.945373535 +v 725.000000000 550.000000000 590.081420898 +v 750.000000000 550.000000000 592.891723633 +v 775.000000000 550.000000000 596.459655762 +v 800.000000000 550.000000000 598.479614258 +v 525.000000000 575.000000000 576.171752930 +v 550.000000000 575.000000000 579.302429199 +v 575.000000000 575.000000000 583.270019531 +v 600.000000000 575.000000000 583.314636230 +v 625.000000000 575.000000000 583.865661621 +v 650.000000000 575.000000000 585.427612305 +v 675.000000000 575.000000000 589.308166504 +v 700.000000000 575.000000000 590.465026855 +v 725.000000000 575.000000000 593.279113770 +v 750.000000000 575.000000000 596.234802246 +v 775.000000000 575.000000000 598.661254883 +v 800.000000000 575.000000000 599.552062988 +v 475.000000000 600.000000000 575.189331055 +v 500.000000000 600.000000000 577.065307617 +v 525.000000000 600.000000000 579.527770996 +v 550.000000000 600.000000000 580.641845703 +v 575.000000000 600.000000000 583.007934570 +v 600.000000000 600.000000000 584.717346191 +v 625.000000000 600.000000000 585.345825195 +v 650.000000000 600.000000000 588.232727051 +v 675.000000000 600.000000000 592.154785156 +v 700.000000000 600.000000000 594.125305176 +v 725.000000000 600.000000000 596.590026855 +v 750.000000000 600.000000000 598.443115234 +v 775.000000000 600.000000000 599.226501465 +v 800.000000000 600.000000000 598.536560059 +v 475.000000000 625.000000000 578.862060547 +v 500.000000000 625.000000000 580.612976074 +v 525.000000000 625.000000000 581.386108398 +v 550.000000000 625.000000000 580.391723633 +v 575.000000000 625.000000000 582.040954590 +v 600.000000000 625.000000000 586.059753418 +v 625.000000000 625.000000000 589.170898438 +v 650.000000000 625.000000000 592.216308594 +v 675.000000000 625.000000000 595.314575195 +v 700.000000000 625.000000000 597.703674316 +v 725.000000000 625.000000000 598.973876953 +v 750.000000000 625.000000000 599.630004883 +v 775.000000000 625.000000000 598.552062988 +v 800.000000000 625.000000000 598.091430664 +v 775.000000000 600.000000000 599.226501465 +v 800.000000000 600.000000000 598.536560059 +v 775.000000000 600.000000000 599.226501465 +v 775.000000000 625.000000000 598.552062988 +v 500.000000000 650.000000000 576.153015137 +v 525.000000000 650.000000000 579.307861328 +v 550.000000000 650.000000000 581.309020996 +v 575.000000000 650.000000000 585.875244141 +v 600.000000000 650.000000000 589.384033203 +v 625.000000000 650.000000000 592.827514648 +v 650.000000000 650.000000000 595.755065918 +v 675.000000000 650.000000000 598.369445801 +v 700.000000000 650.000000000 599.860290527 +v 705.930297852 650.000000000 600.000000000 +v 725.000000000 642.370727539 600.000000000 +v 750.000000000 650.000000000 599.091979980 +v 732.109863281 650.000000000 600.000000000 +v 775.000000000 650.000000000 597.971069336 +v 750.000000000 625.000000000 599.630004883 +v 775.000000000 625.000000000 598.552062988 +v 750.000000000 625.000000000 599.630004883 +v 750.000000000 650.000000000 599.091979980 +v 798.472229004 650.000000000 600.000000000 +v 800.000000000 648.371337891 600.000000000 +v 775.000000000 625.000000000 598.552062988 +v 525.000000000 675.000000000 580.208557129 +v 550.000000000 675.000000000 583.985168457 +v 575.000000000 675.000000000 589.356445312 +v 600.000000000 675.000000000 592.609802246 +v 625.000000000 675.000000000 596.273803711 +v 650.000000000 675.000000000 598.431518555 +v 670.363403320 675.000000000 600.000000000 +v 675.000000000 670.530822754 600.000000000 +v 700.000000000 652.356506348 600.000000000 +v 725.000000000 666.294250488 600.000000000 +v 725.000000000 675.000000000 599.808349609 +v 721.208007812 675.000000000 600.000000000 +v 750.000000000 675.000000000 598.539978027 +v 732.109863281 650.000000000 600.000000000 +v 750.000000000 650.000000000 599.091979980 +v 725.000000000 666.294250488 600.000000000 +v 750.000000000 650.000000000 599.091979980 +v 725.000000000 675.000000000 599.808349609 +v 725.000000000 666.294250488 600.000000000 +v 750.000000000 650.000000000 599.091979980 +v 725.000000000 675.000000000 599.808349609 +v 775.000000000 675.000000000 598.145751953 +v 750.000000000 650.000000000 599.091979980 +v 750.000000000 650.000000000 599.091979980 +v 781.816101074 675.000000000 600.000000000 +v 500.000000000 700.000000000 579.101684570 +v 525.000000000 700.000000000 584.652221680 +v 550.000000000 700.000000000 587.206054688 +v 575.000000000 700.000000000 591.431457520 +v 600.000000000 700.000000000 595.197082520 +v 625.000000000 700.000000000 597.833923340 +v 650.000000000 700.000000000 599.439147949 +v 663.088439941 700.000000000 600.000000000 +v 725.000000000 700.000000000 599.376953125 +v 711.863159180 700.000000000 600.000000000 +v 725.000000000 675.000000000 599.808349609 +v 725.000000000 675.000000000 599.808349609 +v 721.208007812 675.000000000 600.000000000 +v 750.000000000 700.000000000 598.083190918 +v 725.000000000 675.000000000 599.808349609 +v 725.000000000 675.000000000 599.808349609 +v 775.000000000 700.000000000 599.427185059 +v 776.731933594 700.000000000 600.000000000 +v 500.000000000 725.000000000 583.481750488 +v 525.000000000 725.000000000 587.452148438 +v 550.000000000 725.000000000 589.921936035 +v 575.000000000 725.000000000 593.536071777 +v 600.000000000 725.000000000 595.910705566 +v 625.000000000 725.000000000 597.969299316 +v 650.000000000 725.000000000 599.059082031 +v 673.774963379 725.000000000 600.000000000 +v 650.000000000 700.000000000 599.439147949 +v 663.088439941 700.000000000 600.000000000 +v 650.000000000 700.000000000 599.439147949 +v 650.000000000 725.000000000 599.059082031 +v 725.000000000 725.000000000 598.889709473 +v 701.807312012 725.000000000 600.000000000 +v 750.000000000 725.000000000 599.650878906 +v 752.851074219 725.000000000 600.000000000 +v 775.000000000 704.381896973 600.000000000 +v 0.000000000 750.000000000 575.180603027 +v 450.000000000 750.000000000 576.344665527 +v 475.000000000 750.000000000 578.596435547 +v 500.000000000 750.000000000 593.466003418 +v 475.000000000 731.813598633 575.000000000 +v 475.000000000 750.000000000 578.596435547 +v 475.000000000 731.813598633 575.000000000 +v 475.000000000 750.000000000 578.596435547 +v 525.000000000 750.000000000 596.703369141 +v 550.000000000 750.000000000 593.713256836 +v 575.000000000 750.000000000 593.915527344 +v 600.000000000 750.000000000 595.654968262 +v 625.000000000 750.000000000 597.560668945 +v 600.000000000 725.000000000 595.910705566 +v 625.000000000 725.000000000 597.969299316 +v 600.000000000 725.000000000 595.910705566 +v 600.000000000 750.000000000 595.654968262 +v 650.000000000 750.000000000 598.598999023 +v 625.000000000 725.000000000 597.969299316 +v 650.000000000 725.000000000 599.059082031 +v 625.000000000 725.000000000 597.969299316 +v 675.000000000 727.630493164 600.000000000 +v 675.000000000 750.000000000 599.596069336 +v 650.000000000 725.000000000 599.059082031 +v 650.000000000 725.000000000 599.059082031 +v 700.000000000 730.505981445 600.000000000 +v 700.000000000 750.000000000 599.694885254 +v 725.000000000 750.000000000 599.975036621 +v 725.771545410 750.000000000 600.000000000 +v 750.000000000 732.570678711 600.000000000 +v 0.000000000 775.000000000 582.807373047 +v 450.000000000 775.000000000 577.011169434 +v 475.000000000 775.000000000 578.506347656 +v 500.000000000 775.000000000 589.576721191 +v 500.000000000 750.000000000 593.466003418 +v 525.000000000 775.000000000 594.520019531 +v 500.000000000 775.000000000 589.576721191 +v 550.000000000 775.000000000 594.425964355 +v 575.000000000 775.000000000 594.651489258 +v 600.000000000 775.000000000 596.510070801 +v 575.000000000 750.000000000 593.915527344 +v 600.000000000 750.000000000 595.654968262 +v 575.000000000 750.000000000 593.915527344 +v 575.000000000 775.000000000 594.651489258 +v 625.000000000 775.000000000 597.878173828 +v 600.000000000 750.000000000 595.654968262 +v 600.000000000 750.000000000 595.654968262 +v 650.000000000 775.000000000 598.841247559 +v 675.000000000 775.000000000 599.683166504 +v 698.051635742 775.000000000 600.000000000 +v 700.000000000 773.259094238 600.000000000 +v 725.000000000 752.367370605 600.000000000 +v 25.000000000 800.000000000 577.851196289 +v 0.000000000 800.000000000 581.310668945 +v 175.000000000 800.000000000 575.142883301 +v 375.000000000 800.000000000 575.028015137 +v 450.000000000 800.000000000 577.212646484 +v 475.000000000 800.000000000 578.228149414 +v 500.000000000 800.000000000 589.352905273 +v 475.000000000 775.000000000 578.506347656 +v 500.000000000 775.000000000 589.576721191 +v 475.000000000 775.000000000 578.506347656 +v 475.000000000 800.000000000 578.228149414 +v 525.000000000 800.000000000 594.977172852 +v 500.000000000 775.000000000 589.576721191 +v 500.000000000 775.000000000 589.576721191 +v 550.000000000 800.000000000 595.526000977 +v 575.000000000 800.000000000 596.109130859 +v 600.000000000 800.000000000 597.112487793 +v 575.000000000 775.000000000 594.651489258 +v 575.000000000 775.000000000 594.651489258 +v 575.000000000 800.000000000 596.109130859 +v 625.000000000 800.000000000 598.395996094 +v 650.000000000 800.000000000 599.194274902 +v 675.000000000 800.000000000 599.619812012 +v 700.000000000 785.997192383 600.000000000 +v 700.000000000 800.000000000 599.961242676 +v 703.425720215 800.000000000 600.000000000 +v 750.000000000 800.000000000 599.949096680 +v 744.324157715 800.000000000 600.000000000 +v 750.000000000 798.935913086 600.000000000 +v 750.560974121 800.000000000 600.000000000 +v 800.000000000 300.000000000 600.602050781 +v 800.000000000 325.000000000 602.297668457 +v 800.000000000 350.000000000 600.926513672 +v 800.000000000 375.000000000 600.531738281 +v 725.000000000 650.000000000 600.442993164 +v 725.000000000 642.370727539 600.000000000 +v 705.930297852 650.000000000 600.000000000 +v 725.000000000 642.370727539 600.000000000 +v 732.109863281 650.000000000 600.000000000 +v 800.000000000 650.000000000 600.319213867 +v 675.000000000 675.000000000 600.355895996 +v 675.000000000 670.530822754 600.000000000 +v 670.363403320 675.000000000 600.000000000 +v 700.000000000 675.000000000 601.098327637 +v 675.000000000 670.530822754 600.000000000 +v 700.000000000 652.356506348 600.000000000 +v 675.000000000 670.530822754 600.000000000 +v 705.930297852 650.000000000 600.000000000 +v 725.000000000 666.294250488 600.000000000 +v 700.000000000 652.356506348 600.000000000 +v 721.208007812 675.000000000 600.000000000 +v 732.109863281 650.000000000 600.000000000 +v 725.000000000 666.294250488 600.000000000 +v 800.000000000 674.133972168 625.000000000 +v 799.353149414 675.000000000 625.000000000 +v 675.000000000 700.000000000 600.586730957 +v 670.363403320 675.000000000 600.000000000 +v 670.363403320 675.000000000 600.000000000 +v 663.088439941 700.000000000 600.000000000 +v 700.000000000 700.000000000 600.583862305 +v 721.208007812 675.000000000 600.000000000 +v 788.759094238 700.000000000 625.000000000 +v 675.000000000 725.000000000 600.055969238 +v 663.088439941 700.000000000 600.000000000 +v 663.088439941 700.000000000 600.000000000 +v 700.000000000 725.000000000 600.079101562 +v 775.000000000 725.000000000 608.514099121 +v 783.205749512 725.000000000 625.000000000 +v 750.000000000 750.000000000 601.117553711 +v 775.000000000 750.000000000 610.747070312 +v 782.919921875 750.000000000 625.000000000 +v 700.000000000 775.000000000 600.028381348 +v 725.000000000 775.000000000 600.329711914 +v 750.000000000 775.000000000 601.636840820 +v 775.000000000 775.000000000 610.153503418 +v 787.852294922 775.000000000 625.000000000 +v 725.000000000 800.000000000 600.180847168 +v 775.000000000 800.000000000 604.976928711 +v 793.659851074 800.000000000 625.000000000 +v 800.000000000 675.000000000 632.320617676 +v 800.000000000 678.057800293 650.000000000 +v 792.066345215 700.000000000 650.000000000 +v 780.867980957 725.000000000 650.000000000 +v 784.011169434 750.000000000 650.000000000 +v 786.523986816 775.000000000 650.000000000 +v 788.516113281 800.000000000 650.000000000 +v 800.000000000 677.479492188 675.000000000 +v 789.618896484 700.000000000 675.000000000 +v 785.336181641 725.000000000 675.000000000 +v 786.430114746 750.000000000 675.000000000 +v 788.516906738 775.000000000 675.000000000 +v 787.743896484 800.000000000 675.000000000 +v 800.000000000 680.341369629 700.000000000 +v 784.844421387 700.000000000 700.000000000 +v 783.145446777 725.000000000 700.000000000 +v 784.222045898 750.000000000 700.000000000 +v 789.008178711 775.000000000 700.000000000 +v 788.648681641 800.000000000 700.000000000 +v 800.000000000 694.694213867 725.000000000 +v 796.911071777 700.000000000 725.000000000 +v 800.000000000 680.341369629 700.000000000 +v 800.000000000 680.341369629 700.000000000 +v 784.844421387 700.000000000 700.000000000 +v 784.133056641 725.000000000 725.000000000 +v 784.844421387 700.000000000 700.000000000 +v 784.844421387 700.000000000 700.000000000 +v 783.145446777 725.000000000 700.000000000 +v 785.415039062 750.000000000 725.000000000 +v 783.145446777 725.000000000 700.000000000 +v 783.145446777 725.000000000 700.000000000 +v 784.222045898 750.000000000 700.000000000 +v 788.679809570 775.000000000 725.000000000 +v 784.222045898 750.000000000 700.000000000 +v 784.222045898 750.000000000 700.000000000 +v 789.008178711 775.000000000 700.000000000 +v 787.847167969 800.000000000 725.000000000 +v 789.008178711 775.000000000 700.000000000 +v 787.847167969 800.000000000 725.000000000 +v 800.000000000 700.000000000 733.723510742 +f 2 1 3 +f 5 4 6 +f 7 4 8 +f 8 4 5 +f 9 7 10 +f 10 7 8 +f 11 9 10 +f 13 12 14 +f 12 13 3 +f 1 12 3 +f 15 12 1 +f 17 16 18 +f 19 16 17 +f 21 20 22 +f 23 20 24 +f 24 20 21 +f 23 24 6 +f 4 23 6 +f 25 23 4 +f 25 4 26 +f 26 4 7 +f 26 7 27 +f 27 7 9 +f 9 11 29 +f 28 9 29 +f 27 9 28 +f 30 28 31 +f 31 28 29 +f 32 30 33 +f 33 30 31 +f 32 33 14 +f 12 32 14 +f 34 32 12 +f 34 12 35 +f 35 12 15 +f 37 36 38 +f 36 37 18 +f 16 36 18 +f 39 36 16 +f 16 19 41 +f 40 16 41 +f 39 16 40 +f 40 41 22 +f 20 40 22 +f 42 40 20 +f 42 20 43 +f 43 20 23 +f 43 23 44 +f 44 23 25 +f 44 25 45 +f 45 25 26 +f 45 26 46 +f 46 26 27 +f 46 27 47 +f 47 27 28 +f 47 28 48 +f 48 28 30 +f 48 30 49 +f 49 30 32 +f 49 32 50 +f 50 32 34 +f 50 34 51 +f 51 34 35 +f 53 52 54 +f 52 53 38 +f 36 52 38 +f 55 52 36 +f 55 36 56 +f 56 36 39 +f 56 39 57 +f 57 39 40 +f 57 40 58 +f 58 40 42 +f 58 42 59 +f 59 42 43 +f 59 43 60 +f 60 43 44 +f 60 44 61 +f 61 44 45 +f 61 45 62 +f 62 45 46 +f 62 46 63 +f 63 46 47 +f 63 47 64 +f 64 47 48 +f 64 48 65 +f 65 48 49 +f 65 49 66 +f 66 49 50 +f 66 50 67 +f 67 50 51 +f 54 52 68 +f 68 52 69 +f 69 52 70 +f 70 52 55 +f 70 55 71 +f 71 55 56 +f 71 56 72 +f 72 56 57 +f 72 57 73 +f 73 57 58 +f 73 58 74 +f 74 58 59 +f 74 59 75 +f 75 59 60 +f 75 60 76 +f 76 60 61 +f 76 61 77 +f 77 61 62 +f 77 62 78 +f 78 62 63 +f 78 63 79 +f 79 63 64 +f 79 64 80 +f 80 64 65 +f 80 65 81 +f 81 65 66 +f 67 82 83 +f 81 67 83 +f 66 67 81 +f 87 86 84 +f 84 88 85 +f 85 90 89 +f 91 69 70 +f 93 70 92 +f 92 70 71 +f 92 71 94 +f 94 71 72 +f 94 72 95 +f 95 72 73 +f 95 73 96 +f 96 73 74 +f 96 74 97 +f 97 74 75 +f 97 75 98 +f 98 75 76 +f 98 76 99 +f 99 76 77 +f 99 77 100 +f 100 77 78 +f 100 78 101 +f 101 78 79 +f 101 79 102 +f 102 79 80 +f 81 103 104 +f 102 81 104 +f 80 81 102 +f 103 81 83 +f 84 85 105 +f 105 85 106 +f 109 108 107 +f 107 110 111 +f 107 113 112 +f 112 114 92 +f 112 92 115 +f 115 92 94 +f 115 94 116 +f 116 94 95 +f 116 95 117 +f 117 95 96 +f 117 96 118 +f 118 96 97 +f 118 97 119 +f 119 97 98 +f 119 98 120 +f 120 98 99 +f 120 99 121 +f 121 99 100 +f 101 122 123 +f 121 101 123 +f 100 101 121 +f 101 102 122 +f 122 102 124 +f 124 102 104 +f 126 125 127 +f 128 125 126 +f 105 106 129 +f 131 130 132 +f 133 131 134 +f 107 131 135 +f 131 107 136 +f 136 107 112 +f 136 112 137 +f 137 112 115 +f 137 115 138 +f 138 115 116 +f 138 116 139 +f 139 116 117 +f 139 117 140 +f 140 117 118 +f 140 118 141 +f 141 118 119 +f 141 119 142 +f 142 119 120 +f 142 120 143 +f 143 120 121 +f 121 123 145 +f 144 121 145 +f 143 121 144 +f 146 144 145 +f 127 125 147 +f 147 125 128 +f 130 131 148 +f 150 149 148 +f 131 150 148 +f 136 150 131 +f 150 136 151 +f 151 136 137 +f 151 137 152 +f 152 137 138 +f 152 138 153 +f 153 138 139 +f 153 139 154 +f 154 139 140 +f 154 140 155 +f 155 140 141 +f 155 141 156 +f 156 141 142 +f 156 142 157 +f 157 142 143 +f 157 143 158 +f 158 143 144 +f 158 144 159 +f 159 144 146 +f 161 160 162 +f 163 160 161 +f 149 150 164 +f 166 165 164 +f 150 166 164 +f 151 166 150 +f 166 151 167 +f 167 151 152 +f 167 152 168 +f 168 152 153 +f 168 153 169 +f 169 153 154 +f 155 170 171 +f 169 155 171 +f 154 155 169 +f 155 156 170 +f 170 156 172 +f 156 157 172 +f 172 157 173 +f 175 174 173 +f 157 175 173 +f 158 175 157 +f 158 159 177 +f 176 158 177 +f 175 158 176 +f 176 177 162 +f 160 176 162 +f 178 176 160 +f 160 163 180 +f 179 160 180 +f 178 160 179 +f 165 166 181 +f 183 182 181 +f 166 183 181 +f 167 183 166 +f 183 167 184 +f 184 167 168 +f 169 185 186 +f 184 169 186 +f 168 169 184 +f 185 169 171 +f 174 175 187 +f 175 176 187 +f 187 176 188 +f 176 178 188 +f 188 178 189 +f 178 179 189 +f 189 179 190 +f 182 183 191 +f 183 184 191 +f 191 184 192 +f 192 184 186 +f 194 193 195 +f 196 193 197 +f 197 193 194 +f 198 196 197 +f 200 199 201 +f 202 199 200 +f 204 203 205 +f 203 204 195 +f 193 203 195 +f 206 203 193 +f 206 193 207 +f 207 193 196 +f 196 198 209 +f 208 196 209 +f 207 196 208 +f 210 208 209 +f 201 199 211 +f 211 199 202 +f 213 212 214 +f 215 212 213 +f 205 203 216 +f 216 203 217 +f 217 203 218 +f 218 203 206 +f 218 206 219 +f 219 206 207 +f 219 207 220 +f 220 207 208 +f 220 208 221 +f 221 208 210 +f 214 212 222 +f 222 212 215 +f 216 217 223 +f 223 217 224 +f 224 217 225 +f 225 217 218 +f 225 218 226 +f 226 218 219 +f 220 227 228 +f 226 220 228 +f 219 220 226 +f 227 220 221 +f 223 224 229 +f 229 224 230 +f 230 224 231 +f 231 224 225 +f 231 225 232 +f 232 225 226 +f 232 226 233 +f 233 226 228 +f 235 234 236 +f 229 230 237 +f 237 230 238 +f 238 230 239 +f 239 230 231 +f 239 231 240 +f 240 231 232 +f 232 233 242 +f 241 232 242 +f 240 232 241 +f 243 241 242 +f 236 234 244 +f 237 238 245 +f 245 238 246 +f 246 238 247 +f 247 238 239 +f 247 239 248 +f 248 239 240 +f 248 240 249 +f 249 240 241 +f 249 241 250 +f 250 241 243 +f 252 251 253 +f 255 254 256 +f 257 254 258 +f 258 254 255 +f 257 258 253 +f 251 257 253 +f 259 257 251 +f 261 260 262 +f 263 260 264 +f 264 260 261 +f 265 263 266 +f 266 263 264 +f 267 265 268 +f 268 265 266 +f 269 267 270 +f 270 267 268 +f 271 273 272 +f 272 274 275 +f 276 271 277 +f 277 271 272 +f 278 276 279 +f 279 276 277 +f 280 278 281 +f 281 278 279 +f 282 280 283 +f 283 280 281 +f 284 282 285 +f 285 282 283 +f 286 284 287 +f 287 284 285 +f 286 287 256 +f 254 286 256 +f 288 286 254 +f 288 254 289 +f 289 254 257 +f 289 257 290 +f 290 257 259 +f 292 291 293 +f 291 292 262 +f 260 291 262 +f 294 291 260 +f 294 260 295 +f 295 260 263 +f 295 263 296 +f 296 263 265 +f 296 265 297 +f 297 265 267 +f 300 299 298 +f 298 301 302 +f 298 304 303 +f 303 305 271 +f 303 271 306 +f 306 271 276 +f 306 276 307 +f 307 276 278 +f 307 278 308 +f 308 278 280 +f 308 280 309 +f 309 280 282 +f 309 282 310 +f 312 311 313 +f 310 284 314 +f 314 284 286 +f 314 286 315 +f 315 286 288 +f 315 288 316 +f 316 288 289 +f 290 2 3 +f 316 290 3 +f 289 290 316 +f 318 317 319 +f 317 318 293 +f 291 317 293 +f 320 317 291 +f 320 291 321 +f 321 291 294 +f 321 294 322 +f 322 294 295 +f 325 324 323 +f 323 326 327 +f 323 329 328 +f 328 330 331 +f 328 333 332 +f 332 334 298 +f 332 298 335 +f 335 298 303 +f 335 303 336 +f 336 303 306 +f 307 5 6 +f 336 307 6 +f 306 307 336 +f 8 5 308 +f 308 5 307 +f 10 8 309 +f 309 8 308 +f 337 11 10 +f 309 337 10 +f 310 337 309 +f 337 310 338 +f 338 310 314 +f 338 314 339 +f 339 314 315 +f 316 13 14 +f 339 316 14 +f 315 316 339 +f 316 3 13 +f 341 340 342 +f 340 341 319 +f 317 340 319 +f 343 340 317 +f 343 317 344 +f 344 317 320 +f 344 320 345 +f 345 320 321 +f 345 321 346 +f 346 321 322 +f 349 348 347 +f 347 350 323 +f 328 17 18 +f 347 328 18 +f 323 328 347 +f 351 19 17 +f 328 351 17 +f 332 351 328 +f 335 21 22 +f 351 335 22 +f 332 335 351 +f 24 21 336 +f 336 21 335 +f 336 6 24 +f 29 11 337 +f 31 29 338 +f 338 29 337 +f 33 31 339 +f 339 31 338 +f 339 14 33 +f 342 340 352 +f 352 340 353 +f 353 340 354 +f 354 340 343 +f 354 343 355 +f 355 343 344 +f 355 344 356 +f 356 344 345 +f 359 358 357 +f 357 360 361 +f 347 37 38 +f 357 347 38 +f 362 347 357 +f 347 18 37 +f 41 19 351 +f 351 22 41 +f 352 353 363 +f 363 353 364 +f 364 353 365 +f 365 353 354 +f 365 354 366 +f 366 354 355 +f 366 355 367 +f 367 355 356 +f 357 53 54 +f 368 357 54 +f 369 357 370 +f 357 38 53 +f 363 364 371 +f 371 364 372 +f 372 364 373 +f 373 364 365 +f 373 365 374 +f 374 365 366 +f 374 366 375 +f 375 366 367 +f 375 367 376 +f 377 367 378 +f 83 82 379 +f 371 372 380 +f 380 372 381 +f 381 372 382 +f 382 372 373 +f 382 373 383 +f 383 373 374 +f 383 374 384 +f 384 374 375 +f 384 375 84 +f 84 375 385 +f 104 103 386 +f 386 103 83 +f 379 386 83 +f 387 386 379 +f 380 381 388 +f 388 381 389 +f 389 381 390 +f 390 381 382 +f 390 382 391 +f 391 382 383 +f 391 383 392 +f 392 383 384 +f 392 384 105 +f 105 384 84 +f 123 122 393 +f 393 122 394 +f 394 122 124 +f 127 394 126 +f 126 394 386 +f 386 394 104 +f 104 394 124 +f 395 128 126 +f 386 395 126 +f 387 395 386 +f 388 389 396 +f 398 397 399 +f 389 400 396 +f 390 401 389 +f 403 390 402 +f 402 390 391 +f 402 391 404 +f 404 391 392 +f 392 105 129 +f 405 392 129 +f 404 392 405 +f 407 406 130 +f 145 123 393 +f 408 146 145 +f 393 408 145 +f 394 408 393 +f 394 127 147 +f 409 394 147 +f 408 394 409 +f 409 147 128 +f 395 409 128 +f 410 409 395 +f 397 398 411 +f 411 398 412 +f 412 398 413 +f 413 398 414 +f 413 416 415 +f 415 417 418 +f 415 420 419 +f 421 404 405 +f 423 130 148 +f 422 424 148 +f 419 425 422 +f 422 148 149 +f 159 146 426 +f 426 146 408 +f 409 161 162 +f 426 409 162 +f 408 409 426 +f 427 163 161 +f 409 427 161 +f 410 427 409 +f 411 412 428 +f 430 429 428 +f 412 430 428 +f 413 430 412 +f 430 413 431 +f 431 413 415 +f 431 415 432 +f 432 415 419 +f 432 419 433 +f 433 419 422 +f 422 149 164 +f 434 422 164 +f 433 422 434 +f 434 164 165 +f 171 170 435 +f 435 170 436 +f 436 170 172 +f 436 172 437 +f 437 172 173 +f 437 173 174 +f 177 159 426 +f 426 162 177 +f 180 163 427 +f 429 430 438 +f 440 439 438 +f 430 440 438 +f 431 440 430 +f 440 431 441 +f 441 431 432 +f 441 432 442 +f 442 432 433 +f 442 433 443 +f 443 433 434 +f 434 165 181 +f 444 434 181 +f 443 434 444 +f 446 445 447 +f 447 445 448 +f 186 185 449 +f 449 185 171 +f 435 449 171 +f 450 449 435 +f 450 435 451 +f 451 435 436 +f 451 436 452 +f 452 436 437 +f 437 174 187 +f 453 437 187 +f 452 437 453 +f 453 187 454 +f 454 187 188 +f 454 188 455 +f 455 188 189 +f 455 189 456 +f 456 189 190 +f 439 440 457 +f 457 440 458 +f 458 440 459 +f 459 440 441 +f 459 441 460 +f 460 441 442 +f 460 442 461 +f 461 442 443 +f 461 443 462 +f 462 443 444 +f 444 182 191 +f 463 444 191 +f 462 444 463 +f 463 191 464 +f 464 191 192 +f 464 192 186 +f 449 464 186 +f 465 464 449 +f 465 449 466 +f 466 449 450 +f 466 450 467 +f 467 450 451 +f 467 451 468 +f 468 451 452 +f 468 452 469 +f 469 452 453 +f 469 453 470 +f 470 453 454 +f 470 454 471 +f 471 454 455 +f 471 455 472 +f 472 455 456 +f 457 458 194 +f 195 457 194 +f 473 457 195 +f 197 194 459 +f 459 194 458 +f 474 198 197 +f 459 474 197 +f 460 474 459 +f 474 460 475 +f 475 460 461 +f 462 200 201 +f 475 462 201 +f 461 462 475 +f 476 202 200 +f 462 476 200 +f 463 476 462 +f 476 463 477 +f 477 463 464 +f 477 464 478 +f 478 464 465 +f 478 465 479 +f 479 465 466 +f 479 466 480 +f 480 466 467 +f 480 467 481 +f 481 467 468 +f 481 468 482 +f 482 468 469 +f 482 469 483 +f 483 469 470 +f 483 470 484 +f 484 470 471 +f 484 471 485 +f 485 471 472 +f 487 486 488 +f 488 486 489 +f 490 487 488 +f 491 204 492 +f 492 204 205 +f 473 195 491 +f 491 195 204 +f 209 198 474 +f 493 210 209 +f 474 493 209 +f 475 493 474 +f 475 201 211 +f 494 475 211 +f 493 475 494 +f 494 211 202 +f 476 494 202 +f 495 494 476 +f 495 476 496 +f 496 476 477 +f 496 477 497 +f 497 477 478 +f 479 213 214 +f 497 479 214 +f 478 479 497 +f 498 215 213 +f 479 498 213 +f 480 498 479 +f 498 480 499 +f 499 480 481 +f 499 481 500 +f 500 481 482 +f 500 482 501 +f 501 482 483 +f 501 483 502 +f 502 483 484 +f 502 484 503 +f 503 484 485 +f 504 486 505 +f 505 486 487 +f 487 490 507 +f 506 487 507 +f 505 487 506 +f 508 506 509 +f 509 506 507 +f 510 508 511 +f 511 508 509 +f 512 510 513 +f 513 510 511 +f 514 512 515 +f 515 512 513 +f 516 514 517 +f 517 514 515 +f 518 516 519 +f 519 516 517 +f 520 518 521 +f 521 518 519 +f 522 520 523 +f 523 520 521 +f 524 522 525 +f 525 522 523 +f 526 524 525 +f 528 527 529 +f 530 532 531 +f 531 533 534 +f 535 530 536 +f 536 530 531 +f 537 535 538 +f 538 535 536 +f 539 537 538 +f 541 540 538 +f 205 216 492 +f 221 210 542 +f 542 210 493 +f 542 493 543 +f 543 493 494 +f 543 494 544 +f 544 494 495 +f 544 495 545 +f 545 495 496 +f 545 496 546 +f 546 496 497 +f 497 214 222 +f 547 497 222 +f 546 497 547 +f 547 222 215 +f 498 547 215 +f 548 547 498 +f 548 498 549 +f 549 498 499 +f 549 499 550 +f 550 499 500 +f 550 500 551 +f 551 500 501 +f 551 501 552 +f 552 501 502 +f 552 502 553 +f 553 502 503 +f 554 556 555 +f 555 557 558 +f 555 560 559 +f 561 505 506 +f 563 506 562 +f 562 506 508 +f 562 508 564 +f 564 508 510 +f 564 510 565 +f 565 510 512 +f 565 512 566 +f 566 512 514 +f 569 568 567 +f 570 514 516 +f 572 516 571 +f 571 516 518 +f 571 518 573 +f 573 518 520 +f 573 520 574 +f 574 520 522 +f 574 522 575 +f 575 522 524 +f 524 526 577 +f 576 524 577 +f 575 524 576 +f 576 577 529 +f 527 576 529 +f 578 576 527 +f 581 580 579 +f 579 582 530 +f 579 530 583 +f 583 530 535 +f 583 535 584 +f 584 535 537 +f 584 537 585 +f 586 537 587 +f 228 227 588 +f 588 227 221 +f 542 588 221 +f 589 588 542 +f 589 542 590 +f 590 542 543 +f 590 543 591 +f 591 543 544 +f 591 544 592 +f 592 544 545 +f 592 545 593 +f 593 545 546 +f 593 546 594 +f 594 546 547 +f 594 547 595 +f 595 547 548 +f 595 548 596 +f 596 548 549 +f 596 549 597 +f 597 549 550 +f 597 550 598 +f 598 550 551 +f 598 551 599 +f 599 551 552 +f 599 552 600 +f 600 552 553 +f 601 554 602 +f 602 554 555 +f 602 555 603 +f 603 555 559 +f 603 559 604 +f 604 559 605 +f 604 607 606 +f 606 608 609 +f 606 611 610 +f 610 612 613 +f 610 615 614 +f 614 616 617 +f 614 619 618 +f 618 620 567 +f 618 567 621 +f 621 567 622 +f 621 624 623 +f 623 625 626 +f 623 628 627 +f 627 629 630 +f 627 632 631 +f 631 633 634 +f 631 636 635 +f 637 575 576 +f 639 576 638 +f 638 576 578 +f 642 641 640 +f 640 643 579 +f 640 579 644 +f 644 579 583 +f 644 583 645 +f 645 583 584 +f 645 584 646 +f 647 584 648 +f 233 228 649 +f 649 228 588 +f 649 588 650 +f 650 588 589 +f 650 589 651 +f 651 589 590 +f 651 590 652 +f 652 590 591 +f 652 591 653 +f 653 591 592 +f 653 592 654 +f 654 592 593 +f 654 593 655 +f 655 593 594 +f 655 594 656 +f 656 594 595 +f 656 595 657 +f 657 595 596 +f 657 596 658 +f 658 596 597 +f 658 597 659 +f 659 597 598 +f 659 598 660 +f 660 598 599 +f 600 235 236 +f 660 600 236 +f 599 600 660 +f 661 601 662 +f 662 601 602 +f 662 602 663 +f 663 602 603 +f 663 603 664 +f 664 603 604 +f 664 604 665 +f 665 604 606 +f 665 606 666 +f 666 606 610 +f 666 610 667 +f 667 610 614 +f 667 614 668 +f 668 614 618 +f 668 618 669 +f 669 618 621 +f 669 621 670 +f 670 621 623 +f 670 623 671 +f 671 623 627 +f 671 627 672 +f 672 627 631 +f 672 631 673 +f 673 631 635 +f 673 635 674 +f 674 635 675 +f 674 677 676 +f 676 678 640 +f 676 640 679 +f 679 640 644 +f 679 644 680 +f 680 644 645 +f 680 645 681 +f 682 645 683 +f 242 233 649 +f 684 243 242 +f 649 684 242 +f 650 684 649 +f 684 650 685 +f 685 650 651 +f 685 651 686 +f 686 651 652 +f 686 652 687 +f 687 652 653 +f 687 653 688 +f 688 653 654 +f 688 654 689 +f 689 654 655 +f 689 655 690 +f 690 655 656 +f 690 656 691 +f 691 656 657 +f 691 657 692 +f 692 657 658 +f 692 658 693 +f 693 658 659 +f 693 659 694 +f 694 659 660 +f 660 236 244 +f 695 660 244 +f 694 660 695 +f 696 661 697 +f 697 661 662 +f 697 662 698 +f 698 662 663 +f 698 663 699 +f 699 663 664 +f 699 664 700 +f 700 664 665 +f 700 665 701 +f 701 665 666 +f 701 666 702 +f 702 666 667 +f 702 667 703 +f 703 667 668 +f 703 668 704 +f 704 668 669 +f 704 669 705 +f 705 669 670 +f 705 670 706 +f 706 670 671 +f 706 671 707 +f 707 671 672 +f 707 672 708 +f 708 672 673 +f 708 673 709 +f 709 673 674 +f 709 674 710 +f 710 674 676 +f 710 676 711 +f 711 676 679 +f 711 679 712 +f 712 679 680 +f 712 680 713 +f 714 680 715 +f 250 243 716 +f 716 243 684 +f 716 684 717 +f 717 684 685 +f 717 685 718 +f 718 685 686 +f 718 686 719 +f 719 686 687 +f 719 687 720 +f 720 687 688 +f 720 688 721 +f 721 688 689 +f 721 689 722 +f 722 689 690 +f 722 690 723 +f 723 690 691 +f 723 691 724 +f 724 691 692 +f 724 692 725 +f 725 692 693 +f 725 693 726 +f 726 693 694 +f 726 694 727 +f 727 694 695 +f 728 252 729 +f 729 252 253 +f 730 255 731 +f 731 255 256 +f 732 258 730 +f 730 258 255 +f 729 253 732 +f 732 253 258 +f 733 261 734 +f 734 261 262 +f 735 264 733 +f 733 264 261 +f 736 266 735 +f 735 266 264 +f 737 738 739 +f 736 268 266 +f 740 741 737 +f 737 742 743 +f 744 272 740 +f 740 272 745 +f 746 277 744 +f 744 277 272 +f 747 279 746 +f 746 279 277 +f 748 281 747 +f 747 281 279 +f 749 283 748 +f 748 283 281 +f 750 285 749 +f 749 285 283 +f 751 287 750 +f 750 287 285 +f 731 256 751 +f 751 256 287 +f 752 292 753 +f 753 292 293 +f 734 262 752 +f 752 262 292 +f 754 318 755 +f 755 318 319 +f 753 293 754 +f 754 293 318 +f 756 341 342 +f 319 341 756 +f 757 319 756 +f 755 319 757 +f 759 758 756 +f 342 759 756 +f 352 759 342 +f 757 756 758 +f 759 352 760 +f 760 352 363 +f 760 363 761 +f 761 363 371 +f 761 371 762 +f 762 371 380 +f 388 763 764 +f 762 388 764 +f 380 388 762 +f 764 763 765 +f 763 388 396 +f 765 763 396 +f 397 767 768 +f 766 769 397 +f 766 397 770 +f 770 397 411 +f 411 428 770 +f 770 428 771 +f 771 428 772 +f 772 428 429 +f 429 438 772 +f 772 438 773 +f 773 438 774 +f 774 438 439 +f 774 439 775 +f 775 439 457 +f 775 457 776 +f 776 457 473 +f 489 777 779 +f 778 489 779 +f 488 489 778 +f 490 488 780 +f 780 488 778 +f 781 783 782 +f 782 784 785 +f 776 473 786 +f 787 473 491 +f 779 777 788 +f 789 507 780 +f 780 507 490 +f 790 509 789 +f 789 509 507 +f 791 511 790 +f 790 511 509 +f 792 513 791 +f 791 513 511 +f 793 515 792 +f 792 515 513 +f 794 517 793 +f 793 517 515 +f 795 519 794 +f 794 519 517 +f 796 521 795 +f 795 521 519 +f 797 523 796 +f 796 523 521 +f 798 525 797 +f 797 525 523 +f 800 799 526 +f 525 800 526 +f 798 800 525 +f 528 529 799 +f 800 528 799 +f 801 528 800 +f 802 803 801 +f 801 804 528 +f 805 536 806 +f 807 536 531 +f 808 538 805 +f 805 538 536 +f 782 809 808 +f 808 810 538 +f 577 526 799 +f 799 529 577 +f 811 728 812 +f 812 728 729 +f 813 730 814 +f 814 730 731 +f 815 732 813 +f 813 732 730 +f 812 729 815 +f 815 729 732 +f 816 733 734 +f 733 816 818 +f 817 733 818 +f 735 733 817 +f 819 736 817 +f 817 736 735 +f 820 737 821 +f 822 737 823 +f 824 740 820 +f 820 740 737 +f 825 744 824 +f 824 744 740 +f 826 746 825 +f 825 746 744 +f 827 747 826 +f 826 747 746 +f 828 748 827 +f 827 748 747 +f 829 749 828 +f 828 749 748 +f 830 750 829 +f 829 750 749 +f 831 751 830 +f 830 751 750 +f 814 731 831 +f 831 731 751 +f 832 752 833 +f 833 752 753 +f 834 816 734 +f 752 834 734 +f 832 834 752 +f 818 816 834 +f 835 754 755 +f 753 754 835 +f 836 753 835 +f 833 753 836 +f 838 837 835 +f 755 838 835 +f 757 838 755 +f 836 835 837 +f 839 758 759 +f 757 758 839 +f 840 757 839 +f 838 757 840 +f 839 759 841 +f 841 759 760 +f 840 839 842 +f 842 839 841 +f 841 760 843 +f 843 760 761 +f 842 841 844 +f 844 841 843 +f 843 761 845 +f 845 761 762 +f 844 843 846 +f 846 843 845 +f 845 762 764 +f 846 845 764 +f 765 846 764 +f 847 846 765 +f 847 765 848 +f 850 849 766 +f 852 766 851 +f 851 766 770 +f 770 771 851 +f 851 771 853 +f 853 771 854 +f 854 771 772 +f 772 773 856 +f 855 772 856 +f 854 772 855 +f 856 773 774 +f 855 856 857 +f 858 857 856 +f 774 858 856 +f 775 858 774 +f 860 859 861 +f 776 859 860 +f 858 776 860 +f 775 776 858 +f 862 778 779 +f 780 778 862 +f 861 859 864 +f 782 865 781 +f 863 866 782 +f 859 776 867 +f 868 862 779 +f 788 868 779 +f 869 868 788 +f 789 780 862 +f 868 789 862 +f 870 789 868 +f 871 790 870 +f 870 790 789 +f 872 791 871 +f 871 791 790 +f 873 792 872 +f 872 792 791 +f 874 793 873 +f 873 793 792 +f 875 794 874 +f 874 794 793 +f 876 795 875 +f 875 795 794 +f 877 796 876 +f 876 796 795 +f 878 797 877 +f 877 797 796 +f 879 798 878 +f 878 798 797 +f 880 800 879 +f 879 800 798 +f 881 801 880 +f 880 801 800 +f 882 802 881 +f 881 802 801 +f 883 805 884 +f 885 805 886 +f 887 808 883 +f 883 808 805 +f 863 782 887 +f 887 782 808 +f 888 811 812 +f 889 813 814 +f 813 889 891 +f 890 813 891 +f 815 813 890 +f 892 888 812 +f 815 892 812 +f 890 892 815 +f 893 817 818 +f 817 893 895 +f 894 817 895 +f 819 817 894 +f 896 897 894 +f 894 898 819 +f 899 824 900 +f 901 824 820 +f 902 903 904 +f 899 825 824 +f 905 826 906 +f 907 826 825 +f 908 827 905 +f 905 827 826 +f 909 828 908 +f 908 828 827 +f 910 829 909 +f 909 829 828 +f 911 830 910 +f 910 830 829 +f 912 831 911 +f 911 831 830 +f 913 889 814 +f 831 913 814 +f 912 913 831 +f 891 889 913 +f 914 832 833 +f 832 914 916 +f 915 832 916 +f 834 832 915 +f 917 893 818 +f 834 917 818 +f 915 917 834 +f 895 893 917 +f 919 918 914 +f 833 919 914 +f 836 919 833 +f 916 914 918 +f 920 837 838 +f 836 837 920 +f 921 836 920 +f 919 836 921 +f 923 922 920 +f 838 923 920 +f 840 923 838 +f 921 920 922 +f 923 840 924 +f 924 840 842 +f 924 842 925 +f 925 842 844 +f 925 844 926 +f 926 844 846 +f 926 846 927 +f 927 846 847 +f 930 929 928 +f 928 931 932 +f 928 934 933 +f 933 935 851 +f 851 853 933 +f 933 853 936 +f 936 853 937 +f 937 853 854 +f 937 854 938 +f 938 854 855 +f 855 857 938 +f 938 857 939 +f 939 857 940 +f 940 857 858 +f 941 860 942 +f 942 860 861 +f 940 858 941 +f 941 858 860 +f 945 944 943 +f 943 946 863 +f 947 868 948 +f 948 868 869 +f 949 870 947 +f 947 870 868 +f 950 871 949 +f 949 871 870 +f 951 872 950 +f 950 872 871 +f 952 953 954 +f 956 955 957 +f 958 874 959 +f 952 960 961 +f 962 875 958 +f 958 875 874 +f 963 876 962 +f 962 876 875 +f 964 877 963 +f 963 877 876 +f 965 878 964 +f 964 878 877 +f 966 879 965 +f 965 879 878 +f 966 967 968 +f 880 966 968 +f 879 966 880 +f 880 968 970 +f 969 880 970 +f 881 880 969 +f 971 882 969 +f 969 882 881 +f 972 883 973 +f 974 883 975 +f 976 887 972 +f 972 887 883 +f 943 863 976 +f 976 863 887 +f 977 968 967 +f 970 968 977 +f 978 890 979 +f 979 890 891 +f 980 892 978 +f 978 892 890 +f 981 894 895 +f 896 894 982 +f 982 894 981 +f 984 896 983 +f 983 896 982 +f 902 986 985 +f 985 987 983 +f 989 902 988 +f 988 902 985 +f 992 988 991 +f 990 993 991 +f 995 994 990 +f 996 997 990 +f 990 998 999 +f 1000 1001 996 +f 996 1002 1003 +f 1004 911 1005 +f 1006 911 910 +f 1007 912 1004 +f 1004 912 911 +f 1008 913 1007 +f 1007 913 912 +f 979 891 1008 +f 1008 891 913 +f 1009 915 916 +f 915 1009 1011 +f 1010 915 1011 +f 917 915 1010 +f 1012 981 895 +f 917 1012 895 +f 1010 1012 917 +f 1013 982 1012 +f 1012 982 981 +f 1014 983 1013 +f 1013 983 982 +f 1015 985 1014 +f 1014 985 983 +f 1016 988 1015 +f 1015 988 985 +f 991 988 1016 +f 1017 918 919 +f 1018 1017 1019 +f 1009 1017 1018 +f 918 1017 1009 +f 916 918 1009 +f 1011 1009 1018 +f 1021 1020 1017 +f 919 1021 1017 +f 921 1021 919 +f 1019 1017 1020 +f 1022 922 923 +f 921 922 1022 +f 1023 921 1022 +f 1021 921 1023 +f 1025 1024 1022 +f 923 1025 1022 +f 924 1025 923 +f 1023 1022 1024 +f 1025 924 1026 +f 1026 924 925 +f 1026 925 1027 +f 1027 925 926 +f 1027 926 1028 +f 1028 926 927 +f 1028 927 1029 +f 1031 1030 928 +f 933 1032 1033 +f 1034 933 1033 +f 928 933 1035 +f 1033 1032 1036 +f 1032 933 936 +f 1036 1032 936 +f 937 1036 936 +f 1037 1036 937 +f 938 1038 1039 +f 1037 938 1039 +f 937 938 1037 +f 1039 1038 1040 +f 1038 938 939 +f 1040 1038 939 +f 940 1040 939 +f 1041 1040 940 +f 1042 941 942 +f 940 941 1042 +f 1043 940 1042 +f 1041 940 1043 +f 1045 1044 1042 +f 942 1045 1042 +f 943 1046 1047 +f 1043 1042 1044 +f 1048 947 1049 +f 1049 947 948 +f 1050 949 1048 +f 1048 949 947 +f 1051 950 1050 +f 1050 950 949 +f 1052 951 1051 +f 1051 951 950 +f 1053 1054 1052 +f 1052 1055 951 +f 1053 1056 1057 +f 958 1053 1057 +f 1058 1053 958 +f 958 1057 1060 +f 1059 958 1060 +f 962 958 1059 +f 1061 963 1059 +f 1059 963 962 +f 1062 964 1061 +f 1061 964 963 +f 1062 1063 1064 +f 965 1062 1064 +f 964 1062 965 +f 966 965 1065 +f 1065 965 1064 +f 967 966 1065 +f 1066 969 970 +f 971 969 1067 +f 1067 969 1066 +f 972 1069 1068 +f 1068 1070 1071 +f 972 1068 1073 +f 1072 972 1073 +f 976 972 1072 +f 1074 943 1072 +f 1072 943 976 +f 1075 1057 1056 +f 1060 1057 1075 +f 1076 1064 1063 +f 1077 1065 1076 +f 1076 1065 1064 +f 977 967 1065 +f 1077 977 1065 +f 1078 977 1077 +f 1079 1066 970 +f 977 1079 970 +f 1078 1079 977 +f 1080 1067 1079 +f 1079 1067 1066 +f 1081 1068 1082 +f 1083 1068 1084 +f 1073 1068 1081 +f 1085 978 979 +f 978 1085 1087 +f 1086 978 1087 +f 980 978 1086 +f 1088 990 991 +f 996 990 1089 +f 1089 990 1088 +f 1000 996 1090 +f 1090 996 1089 +f 1000 1090 1092 +f 1091 1000 1092 +f 1093 1000 1091 +f 1094 1007 1095 +f 1096 1007 1004 +f 1097 1008 1094 +f 1094 1008 1007 +f 1098 1085 979 +f 1008 1098 979 +f 1097 1098 1008 +f 446 1099 1101 +f 1100 446 1101 +f 445 446 1100 +f 1102 1010 1103 +f 1103 1010 1011 +f 1104 1012 1102 +f 1102 1012 1010 +f 1105 1013 1104 +f 1104 1013 1012 +f 1106 1014 1105 +f 1105 1014 1013 +f 1107 1015 1106 +f 1106 1015 1014 +f 1108 1016 1107 +f 1107 1016 1015 +f 1109 1088 991 +f 1016 1109 991 +f 1108 1109 1016 +f 1110 1089 1109 +f 1109 1089 1088 +f 1111 1090 1110 +f 1110 1090 1089 +f 1092 1090 1111 +f 1112 1018 1113 +f 1113 1018 1019 +f 1103 1011 1112 +f 1112 1011 1018 +f 1114 1020 1115 +f 1115 1020 1021 +f 1113 1019 1114 +f 1114 1019 1020 +f 1115 1021 1116 +f 1116 1021 1023 +f 1117 1024 1025 +f 1023 1024 1117 +f 1118 1023 1117 +f 1116 1023 1118 +f 1117 1025 1119 +f 1119 1025 1026 +f 1118 1117 1120 +f 1120 1117 1119 +f 1122 1121 1119 +f 1026 1122 1119 +f 1027 1122 1026 +f 1120 1119 1121 +f 1122 1027 1123 +f 1123 1027 1028 +f 1123 1028 1124 +f 1124 1028 1029 +f 1126 1033 1127 +f 1128 1033 1125 +f 1125 1033 1129 +f 1129 1033 1036 +f 1129 1036 1130 +f 1130 1036 1037 +f 1037 1039 1130 +f 1130 1039 1131 +f 1131 1039 1132 +f 1132 1039 1040 +f 1132 1040 1133 +f 1133 1040 1041 +f 1133 1041 1134 +f 1134 1041 1043 +f 1135 1137 1136 +f 1136 1138 1139 +f 1134 1043 1140 +f 1141 1043 1044 +f 1143 1142 1144 +f 1048 1143 1144 +f 1049 1143 1048 +f 1050 1048 1145 +f 1145 1048 1144 +f 1051 1050 1146 +f 1146 1050 1145 +f 1150 1149 1148 +f 1147 1051 1151 +f 1052 1051 1147 +f 1147 1152 1153 +f 1053 1147 1153 +f 1052 1147 1053 +f 1056 1053 1153 +f 1154 1059 1155 +f 1155 1059 1060 +f 1156 1061 1154 +f 1154 1061 1059 +f 1157 1062 1156 +f 1156 1062 1061 +f 1063 1062 1158 +f 1158 1062 1157 +f 1159 1072 1160 +f 1160 1072 1073 +f 1136 1161 1159 +f 1159 1162 1072 +f 1163 1144 1142 +f 1164 1145 1163 +f 1163 1145 1144 +f 1165 1166 1167 +f 1164 1146 1145 +f 1148 1168 1165 +f 1169 1153 1152 +f 1075 1056 1153 +f 1169 1075 1153 +f 1170 1075 1169 +f 1155 1060 1170 +f 1170 1060 1075 +f 1171 1076 1158 +f 1158 1076 1063 +f 1172 1077 1171 +f 1171 1077 1076 +f 1173 1078 1172 +f 1172 1078 1077 +f 1174 1079 1173 +f 1173 1079 1078 +f 1175 1080 1174 +f 1174 1080 1079 +f 1176 1081 1177 +f 1178 1081 1179 +f 1160 1073 1176 +f 1176 1073 1081 +f 1181 1180 1182 +f 1086 1087 1180 +f 1181 1086 1180 +f 1183 1086 1181 +f 1185 1184 1186 +f 1187 1184 1188 +f 1188 1184 1185 +f 1189 1187 1190 +f 1190 1187 1188 +f 1191 1189 1192 +f 1192 1189 1190 +f 1193 1191 1194 +f 1194 1191 1192 +f 1091 1092 1193 +f 1194 1091 1193 +f 1195 1091 1194 +f 1196 1094 1197 +f 1195 1198 1091 +f 1199 1097 1196 +f 1196 1097 1094 +f 1199 1182 1180 +f 1098 1199 1180 +f 1097 1199 1098 +f 1100 1101 1202 +f 1201 1100 1202 +f 1200 1100 1201 +f 1203 1102 1204 +f 1204 1102 1103 +f 1205 1104 1203 +f 1203 1104 1102 +f 1206 1105 1205 +f 1205 1105 1104 +f 1207 1106 1206 +f 1206 1106 1105 +f 1207 1186 1184 +f 1107 1207 1184 +f 1106 1207 1107 +f 1108 1107 1187 +f 1187 1107 1184 +f 1109 1108 1189 +f 1189 1108 1187 +f 1110 1109 1191 +f 1191 1109 1189 +f 1111 1110 1193 +f 1193 1110 1191 +f 1193 1092 1111 +f 1208 1112 1209 +f 1209 1112 1113 +f 1204 1103 1208 +f 1208 1103 1112 +f 1210 1114 1211 +f 1211 1114 1115 +f 1209 1113 1210 +f 1210 1113 1114 +f 1213 1212 1214 +f 1116 1212 1213 +f 1211 1116 1213 +f 1115 1116 1211 +f 1214 1212 1215 +f 1215 1212 1216 +f 1216 1212 1118 +f 1118 1212 1116 +f 1215 1216 1217 +f 1217 1216 1218 +f 1218 1216 1120 +f 1120 1216 1118 +f 1217 1218 1121 +f 1122 1217 1121 +f 1219 1217 1122 +f 1218 1120 1121 +f 1219 1122 1220 +f 1220 1122 1123 +f 1220 1123 1221 +f 1221 1123 1124 +f 1223 1125 1224 +f 1225 1125 1222 +f 1222 1125 1226 +f 1226 1125 1129 +f 1226 1129 1227 +f 1227 1129 1130 +f 1130 1131 1227 +f 1227 1131 1228 +f 1228 1131 1229 +f 1229 1131 1132 +f 1229 1132 1230 +f 1230 1132 1133 +f 1230 1133 1231 +f 1231 1133 1134 +f 1232 1135 1136 +f 1234 1135 1232 +f 1233 1235 1232 +f 1231 1134 1236 +f 1238 1237 1142 +f 1143 1238 1142 +f 1239 1238 1143 +f 1240 1237 1238 +f 1242 1241 1243 +f 1147 1245 1241 +f 1242 1147 1241 +f 1244 1147 1242 +f 1247 1246 1152 +f 1147 1247 1152 +f 1244 1247 1147 +f 1248 1246 1249 +f 1249 1246 1247 +f 1154 1155 1248 +f 1249 1154 1248 +f 1250 1154 1249 +f 1251 1156 1250 +f 1250 1156 1154 +f 1252 1157 1251 +f 1251 1157 1156 +f 1158 1157 1253 +f 1253 1157 1252 +f 1254 1159 1160 +f 1255 1254 1256 +f 1232 1254 1255 +f 1159 1254 1232 +f 1136 1159 1232 +f 1233 1232 1255 +f 1163 1142 1237 +f 1163 1237 1240 +f 1257 1163 1240 +f 1164 1163 1257 +f 1257 1243 1241 +f 1165 1258 1259 +f 1261 1260 1165 +f 1262 1148 1165 +f 1169 1152 1246 +f 1170 1169 1248 +f 1248 1169 1246 +f 1248 1155 1170 +f 1263 1171 1253 +f 1253 1171 1158 +f 1264 1172 1263 +f 1263 1172 1171 +f 1265 1173 1264 +f 1264 1173 1172 +f 1266 1174 1265 +f 1265 1174 1173 +f 1267 1268 1269 +f 1266 1175 1174 +f 1270 1176 1267 +f 1267 1176 1271 +f 1272 1254 1160 +f 1176 1272 1160 +f 1270 1272 1176 +f 1274 1273 1201 +f 1201 1273 1200 +f 1276 1275 1277 +f 1181 1182 1275 +f 1276 1181 1275 +f 1278 1181 1276 +f 1279 1183 1278 +f 1278 1183 1181 +f 1281 1280 1282 +f 1185 1186 1280 +f 1281 1185 1280 +f 1283 1185 1281 +f 1284 1188 1283 +f 1283 1188 1185 +f 1285 1190 1284 +f 1284 1190 1188 +f 1286 1192 1285 +f 1285 1192 1190 +f 1287 1194 1286 +f 1286 1194 1192 +f 1288 1195 1287 +f 1287 1195 1194 +f 1289 1196 1290 +f 1291 1196 1292 +f 1289 1277 1275 +f 1199 1289 1275 +f 1196 1289 1199 +f 1275 1182 1199 +f 1293 1203 1294 +f 1294 1203 1204 +f 1295 1205 1293 +f 1293 1205 1203 +f 1296 1206 1295 +f 1295 1206 1205 +f 1296 1282 1280 +f 1207 1296 1280 +f 1206 1296 1207 +f 1280 1186 1207 +f 1297 1208 1298 +f 1298 1208 1209 +f 1294 1204 1297 +f 1297 1204 1208 +f 1299 1210 1300 +f 1300 1210 1211 +f 1298 1209 1299 +f 1299 1209 1210 +f 1301 1213 1302 +f 1302 1213 1214 +f 1300 1211 1301 +f 1301 1211 1213 +f 1302 1214 1303 +f 1303 1214 1215 +f 1303 1215 1304 +f 1304 1215 1217 +f 1304 1217 1305 +f 1305 1217 1219 +f 1220 1306 1307 +f 1305 1220 1307 +f 1219 1220 1305 +f 1307 1306 1308 +f 1306 1220 1309 +f 1309 1220 1221 +f 1308 1306 1310 +f 1310 1306 1309 +f 1312 1311 1222 +f 1315 1314 1222 +f 1226 1316 1222 +f 1313 1317 1226 +f 1227 1318 1319 +f 1313 1227 1319 +f 1226 1227 1313 +f 1319 1318 1320 +f 1318 1227 1228 +f 1320 1318 1228 +f 1229 1320 1228 +f 1321 1320 1229 +f 1321 1229 1322 +f 1322 1229 1230 +f 1322 1230 1323 +f 1323 1230 1231 +f 1323 1231 1324 +f 1324 1231 1325 +f 1326 1238 1327 +f 1327 1238 1239 +f 1329 1328 1240 +f 1238 1329 1240 +f 1326 1329 1238 +f 1242 1243 1328 +f 1329 1242 1328 +f 1330 1242 1329 +f 1331 1244 1330 +f 1330 1244 1242 +f 1332 1247 1331 +f 1331 1247 1244 +f 1333 1249 1332 +f 1332 1249 1247 +f 1334 1250 1333 +f 1333 1250 1249 +f 1335 1251 1334 +f 1334 1251 1250 +f 1336 1252 1335 +f 1335 1252 1251 +f 1338 1337 1253 +f 1252 1338 1253 +f 1336 1338 1252 +f 1339 1337 1338 +f 1341 1340 1342 +f 1343 1340 1341 +f 1344 1255 1345 +f 1345 1255 1256 +f 1346 1233 1344 +f 1344 1233 1255 +f 1257 1240 1328 +f 1328 1243 1257 +f 1263 1253 1337 +f 1263 1337 1339 +f 1347 1263 1339 +f 1264 1263 1347 +f 1348 1265 1347 +f 1347 1265 1264 +f 1349 1266 1348 +f 1348 1266 1265 +f 1350 1351 1349 +f 1349 1352 1266 +f 1353 1342 1340 +f 1270 1354 1340 +f 1267 1355 1270 +f 1270 1340 1343 +f 1356 1270 1343 +f 1272 1270 1356 +f 1345 1256 1356 +f 1356 1256 1272 +f 1358 1357 1359 +f 1361 1360 1362 +f 1276 1277 1360 +f 1361 1276 1360 +f 1363 1276 1361 +f 1364 1278 1363 +f 1363 1278 1276 +f 1364 1359 1357 +f 1279 1364 1357 +f 1278 1364 1279 +f 1366 1365 1367 +f 1281 1282 1365 +f 1366 1281 1365 +f 1368 1281 1366 +f 1369 1283 1368 +f 1368 1283 1281 +f 1370 1284 1369 +f 1369 1284 1283 +f 1371 1285 1370 +f 1370 1285 1284 +f 1372 1286 1371 +f 1371 1286 1285 +f 1373 1287 1372 +f 1372 1287 1286 +f 1374 1288 1373 +f 1373 1288 1287 +f 1375 1362 1360 +f 1289 1376 1360 +f 1288 1374 1377 +f 1360 1277 1289 +f 1378 1293 1379 +f 1379 1293 1294 +f 1380 1295 1378 +f 1378 1295 1293 +f 1380 1367 1365 +f 1296 1380 1365 +f 1295 1380 1296 +f 1365 1282 1296 +f 1381 1383 1382 +f 1382 1384 1385 +f 1379 1294 1386 +f 1387 1294 1297 +f 1388 1299 1389 +f 1389 1299 1300 +f 1382 1390 1391 +f 1388 1298 1299 +f 1392 1301 1302 +f 1300 1301 1392 +f 1393 1300 1392 +f 1389 1300 1393 +f 1392 1302 1394 +f 1394 1302 1303 +f 1393 1392 1395 +f 1395 1392 1394 +f 1394 1303 1396 +f 1396 1303 1304 +f 1395 1394 1397 +f 1397 1394 1396 +f 1396 1304 1398 +f 1398 1304 1305 +f 1397 1396 1399 +f 1399 1396 1398 +f 1398 1305 1307 +f 1399 1398 1307 +f 1308 1399 1307 +f 1400 1399 1308 +f 1400 1308 1401 +f 1401 1308 1310 +f 1313 1402 1403 +f 1404 1313 1403 +f 1405 1313 1406 +f 1403 1402 1407 +f 1402 1313 1319 +f 1407 1402 1319 +f 1320 1407 1319 +f 1408 1407 1320 +f 1408 1320 1409 +f 1409 1320 1321 +f 1409 1321 1410 +f 1410 1321 1322 +f 1410 1322 1411 +f 1411 1322 1323 +f 1411 1323 1412 +f 1412 1323 1324 +f 1413 1326 1414 +f 1414 1326 1327 +f 1415 1329 1413 +f 1413 1329 1326 +f 1416 1330 1415 +f 1415 1330 1329 +f 1417 1331 1416 +f 1416 1331 1330 +f 1418 1332 1417 +f 1417 1332 1331 +f 1419 1333 1418 +f 1418 1333 1332 +f 1420 1334 1419 +f 1419 1334 1333 +f 1421 1335 1420 +f 1420 1335 1334 +f 1422 1336 1421 +f 1421 1336 1335 +f 1423 1338 1422 +f 1422 1338 1336 +f 1339 1338 1424 +f 1424 1338 1423 +f 1425 1341 1426 +f 1426 1341 1342 +f 1428 1427 1343 +f 1341 1428 1343 +f 1425 1428 1341 +f 1344 1345 1427 +f 1428 1344 1427 +f 1429 1430 1431 +f 1412 1324 1429 +f 1429 1324 1432 +f 1433 1347 1424 +f 1424 1347 1339 +f 1434 1348 1433 +f 1433 1348 1347 +f 1435 1349 1434 +f 1434 1349 1348 +f 1436 1350 1435 +f 1435 1350 1349 +f 1426 1342 1437 +f 1438 1342 1439 +f 1356 1343 1427 +f 1427 1345 1356 +f 1440 1358 1441 +f 1441 1358 1359 +f 1442 1361 1362 +f 1361 1442 1444 +f 1443 1361 1444 +f 1363 1361 1443 +f 1445 1364 1443 +f 1443 1364 1363 +f 1441 1359 1445 +f 1445 1359 1364 +f 1447 1446 1448 +f 1449 1451 1450 +f 1450 1452 1453 +f 1366 1367 1455 +f 1450 1456 1449 +f 1454 1457 1450 +f 1458 1459 1454 +f 1454 1460 1461 +f 1462 1463 1458 +f 1458 1464 1465 +f 1466 1467 1462 +f 1462 1468 1469 +f 1470 1371 1471 +f 1472 1371 1370 +f 1473 1372 1470 +f 1470 1372 1371 +f 1474 1373 1473 +f 1473 1373 1372 +f 1475 1374 1474 +f 1474 1374 1373 +f 1476 1442 1362 +f 1477 1476 1362 +f 1478 1476 1479 +f 1444 1442 1476 +f 1481 1480 1482 +f 1483 1378 1379 +f 1481 1484 1480 +f 1486 1485 1481 +f 1488 1487 1481 +f 1380 1378 1489 +f 1490 1378 1446 +f 1491 1367 1380 +f 1493 1492 1494 +f 1495 1381 1382 +f 1493 1496 1492 +f 1498 1497 1493 +f 1482 1480 1499 +f 1500 1379 1501 +f 1494 1492 1388 +f 1389 1494 1388 +f 1502 1503 1504 +f 1505 1382 1506 +f 1502 1508 1507 +f 1507 1509 1510 +f 1507 1512 1511 +f 1511 1513 1514 +f 1511 1516 1515 +f 1517 1395 1397 +f 1519 1397 1518 +f 1518 1397 1399 +f 1518 1399 1520 +f 1520 1399 1400 +f 1520 1400 1521 +f 1521 1400 1401 +f 1523 1403 1524 +f 1525 1403 1522 +f 1522 1403 1526 +f 1526 1403 1407 +f 1526 1407 1527 +f 1527 1407 1408 +f 1527 1408 1528 +f 1528 1408 1409 +f 1410 1529 1530 +f 1528 1410 1530 +f 1409 1410 1528 +f 1530 1529 1531 +f 1533 1532 1529 +f 1410 1533 1529 +f 1411 1533 1410 +f 1531 1529 1532 +f 1533 1411 1534 +f 1534 1411 1412 +f 1535 1413 1536 +f 1536 1413 1414 +f 1537 1415 1535 +f 1535 1415 1413 +f 1538 1416 1537 +f 1537 1416 1415 +f 1538 1539 1540 +f 1417 1538 1540 +f 1416 1538 1417 +f 1418 1417 1541 +f 1541 1417 1540 +f 1418 1541 1543 +f 1542 1418 1543 +f 1419 1418 1542 +f 1544 1420 1542 +f 1542 1420 1419 +f 1544 1545 1546 +f 1421 1544 1546 +f 1420 1544 1421 +f 1422 1421 1547 +f 1547 1421 1546 +f 1423 1422 1548 +f 1548 1422 1547 +f 1424 1423 1548 +f 1549 1425 1550 +f 1550 1425 1426 +f 1549 1551 1552 +f 1428 1549 1552 +f 1425 1549 1428 +f 1428 1552 1554 +f 1553 1428 1554 +f 1429 1555 1556 +f 1534 1412 1557 +f 1558 1412 1429 +f 1559 1540 1539 +f 1560 1541 1559 +f 1559 1541 1540 +f 1543 1541 1560 +f 1561 1546 1545 +f 1562 1547 1561 +f 1561 1547 1546 +f 1563 1548 1562 +f 1562 1548 1547 +f 1433 1424 1548 +f 1563 1433 1548 +f 1564 1433 1563 +f 1565 1434 1564 +f 1564 1434 1433 +f 1566 1435 1565 +f 1565 1435 1434 +f 1567 1436 1566 +f 1566 1436 1435 +f 1550 1426 1568 +f 1569 1426 1570 +f 1571 1552 1551 +f 1554 1552 1571 +f 1572 1440 1573 +f 1573 1440 1441 +f 1575 1574 1576 +f 1443 1444 1574 +f 1575 1443 1574 +f 1577 1443 1575 +f 1578 1445 1577 +f 1577 1445 1443 +f 1573 1441 1578 +f 1578 1441 1445 +f 1580 1579 1581 +f 1584 1583 1579 +f 1580 1585 1579 +f 1582 1586 1580 +f 1587 1450 1582 +f 1582 1450 1588 +f 1589 1454 1587 +f 1587 1454 1450 +f 1590 1458 1589 +f 1589 1458 1454 +f 1591 1462 1590 +f 1590 1462 1458 +f 1592 1466 1591 +f 1591 1466 1462 +f 1593 1594 1592 +f 1592 1595 1466 +f 1596 1597 1593 +f 1593 1598 1599 +f 1600 1474 1601 +f 1602 1474 1473 +f 1603 1475 1600 +f 1600 1475 1474 +f 1604 1576 1574 +f 1476 1605 1574 +f 1607 1606 1476 +f 1574 1444 1476 +f 1609 1608 1610 +f 1608 1481 1482 +f 1609 1481 1608 +f 1579 1481 1609 +f 1581 1579 1609 +f 1579 1611 1481 +f 1610 1608 1613 +f 1614 1610 1615 +f 1612 1610 1616 +f 1608 1482 1617 +f 1619 1618 1620 +f 1502 1618 1619 +f 1612 1502 1619 +f 1621 1502 1612 +f 1620 1618 1622 +f 1622 1618 1623 +f 1623 1618 1507 +f 1507 1618 1502 +f 1622 1623 1624 +f 1625 1624 1623 +f 1507 1625 1623 +f 1511 1625 1507 +f 1625 1511 1626 +f 1626 1511 1515 +f 1626 1515 1627 +f 1627 1515 1628 +f 1627 1630 1629 +f 1629 1631 1632 +f 1629 1634 1633 +f 1633 1635 1636 +f 1639 1522 1638 +f 1637 1640 1638 +f 1633 1641 1637 +f 1638 1522 1526 +f 1637 1638 1642 +f 1643 1642 1638 +f 1526 1643 1638 +f 1527 1643 1526 +f 1643 1527 1644 +f 1644 1527 1528 +f 1528 1530 1646 +f 1645 1528 1646 +f 1644 1528 1645 +f 1646 1530 1531 +f 1645 1646 1532 +f 1533 1645 1532 +f 1647 1645 1533 +f 1646 1531 1532 +f 1647 1533 1648 +f 1650 1649 1651 +f 1652 1535 1653 +f 1653 1535 1536 +f 1654 1537 1652 +f 1652 1537 1535 +f 1654 1655 1656 +f 1538 1654 1656 +f 1537 1654 1538 +f 1539 1538 1656 +f 1657 1542 1658 +f 1658 1542 1543 +f 1659 1544 1657 +f 1657 1544 1542 +f 1545 1544 1660 +f 1660 1544 1659 +f 1661 1549 1550 +f 1551 1549 1661 +f 1662 1553 1663 +f 1663 1553 1554 +f 1665 1664 1662 +f 1662 1666 1553 +f 1667 1656 1655 +f 1559 1539 1656 +f 1667 1559 1656 +f 1668 1559 1667 +f 1669 1560 1668 +f 1668 1560 1559 +f 1658 1543 1669 +f 1669 1543 1560 +f 1670 1561 1660 +f 1660 1561 1545 +f 1671 1562 1670 +f 1670 1562 1561 +f 1672 1563 1671 +f 1671 1563 1562 +f 1673 1564 1672 +f 1672 1564 1563 +f 1674 1565 1673 +f 1673 1565 1564 +f 1675 1566 1674 +f 1674 1566 1565 +f 1676 1567 1675 +f 1675 1567 1566 +f 1677 1661 1550 +f 1678 1677 1550 +f 1679 1677 1680 +f 1571 1551 1661 +f 1677 1571 1661 +f 1681 1571 1677 +f 1663 1554 1681 +f 1681 1554 1571 +f 1682 1572 1573 +f 1683 1575 1576 +f 1577 1575 1684 +f 1684 1575 1683 +f 1577 1684 1686 +f 1685 1577 1686 +f 1578 1577 1685 +f 1687 1682 1573 +f 1578 1687 1573 +f 1685 1687 1578 +f 1688 1580 1581 +f 1582 1580 1689 +f 1689 1580 1688 +f 1587 1582 1690 +f 1690 1582 1689 +f 1589 1587 1691 +f 1691 1587 1690 +f 1590 1589 1692 +f 1692 1589 1691 +f 1591 1590 1693 +f 1693 1590 1692 +f 1592 1591 1694 +f 1694 1591 1693 +f 1592 1694 1696 +f 1695 1592 1696 +f 1593 1592 1695 +f 1697 1596 1695 +f 1695 1596 1593 +f 1698 1699 1697 +f 1697 1700 1596 +f 1701 1702 1698 +f 1698 1703 1704 +f 1705 1706 1707 +f 1603 1705 1708 +f 1709 1705 1603 +f 1710 1684 1711 +f 1712 1684 1683 +f 1686 1684 1710 +f 1713 1609 1610 +f 1714 1713 1715 +f 1688 1713 1714 +f 1609 1713 1688 +f 1581 1609 1688 +f 1688 1714 1717 +f 1716 1688 1717 +f 1689 1688 1716 +f 1690 1689 1718 +f 1718 1689 1716 +f 1691 1690 1719 +f 1719 1690 1718 +f 1692 1691 1720 +f 1720 1691 1719 +f 1720 1721 1722 +f 1693 1720 1722 +f 1692 1720 1693 +f 1723 1694 1722 +f 1722 1694 1693 +f 1696 1694 1723 +f 1713 1610 1724 +f 1724 1610 1612 +f 1715 1713 1725 +f 1725 1713 1724 +f 1726 1716 1727 +f 1727 1716 1717 +f 1718 1716 1728 +f 1728 1716 1726 +f 1728 1729 1730 +f 1719 1728 1730 +f 1718 1728 1719 +f 1731 1720 1730 +f 1730 1720 1719 +f 1721 1720 1731 +f 1732 1619 1620 +f 1724 1612 1619 +f 1732 1724 1619 +f 1733 1724 1732 +f 1735 1734 1725 +f 1724 1735 1725 +f 1733 1735 1724 +f 1734 1735 1727 +f 1727 1735 1726 +f 1726 1735 1736 +f 1739 1738 1737 +f 1740 1728 1736 +f 1736 1728 1726 +f 1729 1728 1740 +f 1732 1620 1741 +f 1741 1620 1622 +f 1733 1732 1742 +f 1742 1732 1741 +f 1742 1743 1744 +f 1735 1742 1744 +f 1733 1742 1735 +f 1745 1735 1744 +f 1741 1622 1624 +f 1741 1624 1625 +f 1746 1741 1625 +f 1742 1741 1746 +f 1743 1742 1747 +f 1747 1742 1746 +f 1746 1625 1748 +f 1748 1625 1626 +f 1747 1746 1749 +f 1749 1746 1748 +f 1751 1750 1748 +f 1626 1751 1748 +f 1627 1751 1626 +f 1749 1748 1750 +f 1751 1627 1752 +f 1752 1627 1629 +f 1752 1629 1753 +f 1753 1629 1633 +f 1753 1633 1754 +f 1754 1633 1637 +f 1637 1642 1756 +f 1755 1637 1756 +f 1754 1637 1755 +f 1756 1642 1643 +f 1755 1756 1757 +f 1758 1757 1756 +f 1643 1758 1756 +f 1644 1758 1643 +f 1758 1644 1759 +f 1759 1644 1645 +f 1759 1645 1760 +f 1760 1645 1647 +f 1760 1647 1761 +f 1761 1647 1648 +f 1652 1653 1762 +f 1762 1653 1763 +f 1654 1652 1764 +f 1764 1652 1762 +f 1655 1654 1764 +f 1765 1657 1658 +f 1659 1657 1766 +f 1766 1657 1765 +f 1660 1659 1766 +f 1767 1662 1768 +f 1768 1662 1663 +f 1770 1769 1767 +f 1767 1771 1662 +f 1772 1762 1773 +f 1773 1762 1763 +f 1774 1764 1772 +f 1772 1764 1762 +f 1667 1655 1764 +f 1774 1667 1764 +f 1775 1667 1774 +f 1776 1668 1775 +f 1775 1668 1667 +f 1777 1669 1776 +f 1776 1669 1668 +f 1778 1765 1658 +f 1669 1778 1658 +f 1777 1778 1669 +f 1779 1766 1778 +f 1778 1766 1765 +f 1670 1660 1766 +f 1779 1670 1766 +f 1780 1670 1779 +f 1781 1671 1780 +f 1780 1671 1670 +f 1782 1672 1781 +f 1781 1672 1671 +f 1783 1673 1782 +f 1782 1673 1672 +f 1784 1674 1783 +f 1783 1674 1673 +f 1785 1675 1784 +f 1784 1675 1674 +f 1786 1676 1785 +f 1785 1676 1675 +f 1787 1677 1788 +f 1789 1677 1790 +f 1791 1681 1787 +f 1787 1681 1677 +f 1768 1663 1791 +f 1791 1663 1681 +f 1792 1685 1793 +f 1793 1685 1686 +f 1794 1687 1792 +f 1792 1687 1685 +f 1795 1695 1696 +f 1697 1695 1796 +f 1796 1695 1795 +f 1697 1796 1798 +f 1797 1697 1798 +f 1698 1697 1797 +f 1799 1701 1797 +f 1797 1701 1698 +f 1800 1801 1799 +f 1799 1802 1701 +f 1803 1710 1800 +f 1800 1710 1804 +f 1793 1686 1803 +f 1803 1686 1710 +f 1805 1714 1715 +f 1717 1714 1805 +f 1806 1722 1721 +f 1723 1722 1807 +f 1807 1722 1806 +f 1795 1696 1723 +f 1807 1795 1723 +f 1808 1795 1807 +f 1808 1809 1810 +f 1796 1808 1810 +f 1795 1808 1796 +f 1798 1796 1810 +f 1805 1715 1811 +f 1811 1715 1725 +f 1717 1805 1727 +f 1727 1805 1811 +f 1812 1730 1729 +f 1731 1730 1813 +f 1813 1730 1812 +f 1806 1721 1731 +f 1813 1806 1731 +f 1814 1806 1813 +f 1807 1806 1815 +f 1815 1806 1814 +f 1815 1816 1817 +f 1808 1815 1817 +f 1807 1815 1808 +f 1809 1808 1817 +f 1811 1725 1734 +f 1734 1727 1811 +f 1819 1737 1818 +f 1740 1736 1820 +f 1822 1821 1818 +f 1812 1729 1740 +f 1820 1812 1740 +f 1823 1812 1820 +f 1813 1812 1824 +f 1824 1812 1823 +f 1827 1825 1826 +f 1814 1824 1828 +f 1813 1824 1814 +f 1829 1815 1830 +f 1831 1815 1814 +f 1816 1815 1829 +f 1832 1744 1743 +f 1835 1834 1744 +f 1832 1836 1744 +f 1833 1837 1832 +f 1839 1818 1838 +f 1838 1818 1840 +f 1843 1842 1841 +f 1841 1844 1838 +f 1841 1845 1846 +f 1847 1841 1846 +f 1848 1841 1849 +f 1825 1850 1846 +f 1832 1743 1851 +f 1851 1743 1747 +f 1833 1832 1852 +f 1852 1832 1851 +f 1838 1854 1853 +f 1853 1855 1856 +f 1853 1857 1858 +f 1841 1853 1858 +f 1838 1853 1841 +f 1845 1841 1858 +f 1851 1747 1859 +f 1859 1747 1749 +f 1859 1860 1861 +f 1852 1859 1861 +f 1851 1859 1852 +f 1862 1853 1863 +f 1864 1853 1865 +f 1857 1853 1862 +f 1866 1750 1751 +f 1859 1749 1750 +f 1866 1859 1750 +f 1867 1859 1866 +f 1860 1859 1868 +f 1868 1859 1867 +f 1866 1751 1869 +f 1869 1751 1752 +f 1869 1870 1871 +f 1867 1869 1871 +f 1866 1869 1867 +f 1868 1867 1871 +f 1873 1872 1869 +f 1752 1873 1869 +f 1753 1873 1752 +f 1870 1869 1872 +f 1873 1753 1874 +f 1874 1753 1754 +f 1874 1754 1875 +f 1875 1754 1755 +f 1755 1757 1875 +f 1875 1757 1876 +f 1876 1757 1877 +f 1877 1757 1758 +f 1877 1758 1878 +f 1878 1758 1759 +f 1878 1759 1879 +f 1879 1759 1760 +f 1879 1760 1880 +f 1880 1760 1761 +f 1881 1767 1882 +f 1882 1767 1768 +f 1884 1883 1881 +f 1881 1885 1767 +f 1886 1772 1887 +f 1887 1772 1773 +f 1888 1774 1886 +f 1886 1774 1772 +f 1889 1775 1888 +f 1888 1775 1774 +f 1890 1776 1889 +f 1889 1776 1775 +f 1891 1777 1890 +f 1890 1777 1776 +f 1892 1778 1891 +f 1891 1778 1777 +f 1893 1779 1892 +f 1892 1779 1778 +f 1894 1780 1893 +f 1893 1780 1779 +f 1895 1781 1894 +f 1894 1781 1780 +f 1896 1782 1895 +f 1895 1782 1781 +f 1897 1783 1896 +f 1896 1783 1782 +f 1897 1898 1899 +f 1784 1897 1899 +f 1783 1897 1784 +f 1784 1899 1901 +f 1900 1784 1901 +f 1785 1784 1900 +f 1902 1786 1900 +f 1900 1786 1785 +f 1903 1787 1904 +f 1905 1787 1906 +f 1907 1791 1903 +f 1903 1791 1787 +f 1882 1768 1907 +f 1907 1768 1791 +f 1908 1899 1898 +f 1901 1899 1908 +f 1910 1909 1911 +f 1792 1793 1909 +f 1910 1792 1909 +f 1912 1792 1910 +f 1913 1794 1912 +f 1912 1794 1792 +f 1914 1797 1798 +f 1797 1914 1916 +f 1915 1797 1916 +f 1799 1797 1915 +f 1917 1800 1915 +f 1915 1800 1799 +f 1917 1911 1909 +f 1803 1917 1909 +f 1800 1917 1803 +f 1909 1793 1803 +f 1918 1810 1809 +f 1919 1918 1920 +f 1914 1918 1919 +f 1810 1918 1914 +f 1798 1810 1914 +f 445 1921 448 +f 448 1921 1922 +f 1923 1817 1816 +f 1918 1809 1817 +f 1923 1918 1817 +f 1924 1918 1923 +f 1920 1918 1925 +f 1925 1918 1924 +f 1926 1826 1825 +f 1829 1928 1927 +f 1929 1826 1926 +f 1923 1816 1829 +f 1927 1923 1829 +f 1930 1923 1927 +f 1924 1923 1931 +f 1931 1923 1930 +f 1925 1924 1932 +f 1932 1924 1931 +f 1933 1846 1845 +f 1926 1825 1846 +f 1933 1926 1846 +f 1934 1926 1933 +f 1936 1926 1935 +f 1935 1926 1934 +f 1939 1938 1937 +f 1937 1940 1935 +f 1937 1941 1942 +f 1943 1937 1942 +f 1944 1937 1945 +f 1947 1946 1942 +f 1948 1858 1857 +f 1949 1948 1950 +f 1933 1948 1949 +f 1858 1948 1933 +f 1845 1858 1933 +f 1951 1934 1949 +f 1949 1934 1933 +f 1952 1935 1951 +f 1951 1935 1934 +f 1953 1937 1952 +f 1952 1937 1935 +f 1941 1937 1953 +f 1954 1955 1956 +f 1862 1958 1957 +f 1957 1959 1954 +f 1948 1857 1862 +f 1957 1948 1862 +f 1960 1948 1957 +f 1950 1948 1961 +f 1961 1948 1960 +f 1963 1860 1962 +f 1962 1860 1868 +f 1957 1954 1964 +f 1966 1965 1962 +f 1964 1967 1968 +f 1960 1964 1968 +f 1957 1964 1960 +f 1961 1960 1968 +f 1969 1871 1870 +f 1962 1868 1871 +f 1969 1962 1871 +f 1970 1962 1969 +f 1970 1971 1972 +f 1973 1970 1972 +f 1962 1970 1974 +f 1967 1964 1975 +f 1976 1872 1873 +f 1969 1870 1872 +f 1976 1969 1872 +f 1977 1969 1976 +f 1977 1978 1979 +f 1970 1977 1979 +f 1969 1977 1970 +f 1971 1970 1979 +f 1976 1873 1980 +f 1980 1873 1874 +f 1977 1976 1981 +f 1981 1976 1980 +f 1978 1977 1982 +f 1982 1977 1981 +f 1980 1874 1983 +f 1983 1874 1875 +f 1983 1984 1985 +f 1981 1983 1985 +f 1980 1983 1981 +f 1982 1981 1985 +f 1983 1875 1876 +f 1984 1983 1876 +f 1877 1984 1876 +f 1986 1984 1877 +f 1986 1877 1987 +f 1987 1877 1878 +f 1987 1878 1988 +f 1988 1878 1879 +f 1988 1879 1989 +f 1989 1879 1880 +f 1990 1881 1882 +f 1992 1881 1990 +f 1991 1993 1990 +f 1989 1880 1994 +f 1996 1995 1997 +f 1886 1996 1997 +f 1887 1996 1886 +f 1888 1886 1998 +f 1998 1886 1997 +f 1889 1888 1999 +f 1999 1888 1998 +f 1890 1889 2000 +f 2000 1889 1999 +f 1891 1890 2001 +f 2001 1890 2000 +f 1892 1891 2002 +f 2002 1891 2001 +f 1893 1892 2003 +f 2003 1892 2002 +f 1894 1893 2004 +f 2004 1893 2003 +f 1895 1894 2005 +f 2005 1894 2004 +f 1896 1895 2006 +f 2006 1895 2005 +f 1897 1896 2007 +f 2007 1896 2006 +f 1898 1897 2007 +f 2008 1900 1901 +f 1902 1900 2009 +f 2009 1900 2008 +f 1903 2011 2010 +f 2010 2012 2013 +f 1907 1903 2014 +f 2014 1903 2010 +f 2015 2014 2016 +f 1990 2014 2015 +f 1907 2014 1990 +f 1882 1907 1990 +f 1991 1990 2015 +f 2017 1997 1995 +f 2018 1998 2017 +f 2017 1998 1997 +f 2019 1999 2018 +f 2018 1999 1998 +f 2020 2000 2019 +f 2019 2000 1999 +f 2021 2001 2020 +f 2020 2001 2000 +f 2022 2002 2021 +f 2021 2002 2001 +f 2023 2003 2022 +f 2022 2003 2002 +f 2024 2004 2023 +f 2023 2004 2003 +f 2025 2005 2024 +f 2024 2005 2004 +f 2026 2006 2025 +f 2025 2006 2005 +f 2027 2007 2026 +f 2026 2007 2006 +f 1908 1898 2007 +f 2027 1908 2007 +f 2028 1908 2027 +f 2029 2008 1901 +f 1908 2029 1901 +f 2028 2029 1908 +f 2030 2009 2029 +f 2029 2009 2008 +f 2031 2010 2032 +f 2033 2010 2034 +f 2035 2014 2031 +f 2031 2014 2010 +f 2016 2014 2035 +f 2037 2036 2038 +f 1910 1911 2036 +f 2037 1910 2036 +f 2039 1910 2037 +f 2040 1912 2039 +f 2039 1912 1910 +f 2041 1913 2040 +f 2040 1913 1912 +f 2043 2042 2044 +f 1915 1916 2042 +f 2043 1915 2042 +f 2045 1915 2043 +f 2045 2038 2036 +f 1917 2045 2036 +f 1915 2045 1917 +f 2036 1911 1917 +f 1919 1920 2046 +f 2044 2042 2047 +f 2042 1916 2047 +f 2047 1916 2048 +f 2048 1916 2046 +f 2046 1916 1919 +f 2046 1920 2049 +f 2049 1920 1925 +f 2048 2046 2050 +f 2050 2046 2049 +f 2049 1925 2051 +f 2051 1925 1932 +f 2050 2049 2052 +f 2052 2049 2051 +f 2053 1942 1941 +f 2056 2055 1942 +f 2053 2057 1942 +f 2054 2051 2058 +f 2052 2051 2059 +f 2059 2051 2054 +f 2060 1949 1950 +f 1951 1949 2061 +f 2061 1949 2060 +f 1952 1951 2062 +f 2062 1951 2061 +f 1953 1952 2063 +f 2063 1952 2062 +f 2053 1941 1953 +f 2063 2053 1953 +f 2064 2065 2066 +f 2064 2067 2068 +f 2054 2064 2068 +f 2069 2064 2054 +f 2059 2054 2068 +f 2060 1950 2070 +f 2070 1950 1961 +f 2061 2060 2071 +f 2071 2060 2070 +f 2062 2061 2072 +f 2072 2061 2071 +f 2075 2074 2073 +f 2073 2076 2077 +f 2073 2078 2079 +f 2064 2073 2079 +f 2080 2073 2064 +f 2067 2064 2079 +f 2081 1968 1967 +f 2070 1961 1968 +f 2081 2070 1968 +f 2082 2083 2084 +f 2087 2086 2085 +f 2085 2088 2082 +f 2085 2089 2090 +f 2091 2085 2090 +f 2092 2085 2093 +f 2094 2073 2090 +f 2090 2073 2095 +f 2078 2073 2094 +f 2096 2097 2098 +f 2081 1967 2100 +f 2096 2081 2101 +f 2099 2081 2096 +f 2082 2103 2102 +f 2102 2104 2105 +f 2102 2106 2107 +f 2085 2102 2107 +f 2082 2102 2085 +f 2089 2085 2107 +f 1100 2109 445 +f 445 2109 1921 +f 2111 1971 1979 +f 2108 2112 1979 +f 2110 2113 2108 +f 2099 2096 2114 +f 2116 2115 2110 +f 2102 2118 2117 +f 2117 2119 2120 +f 2106 2102 2121 +f 2121 2102 2117 +f 2108 1978 2122 +f 2122 1978 1982 +f 2110 2108 2123 +f 2123 2108 2122 +f 2125 2110 2124 +f 2124 2110 2123 +f 2124 2126 2127 +f 2117 2124 2127 +f 2128 2124 2117 +f 2121 2117 2127 +f 2129 1985 1984 +f 2122 1982 1985 +f 2129 2122 1985 +f 2130 2122 2129 +f 2123 2122 2131 +f 2131 2122 2130 +f 2131 2132 2133 +f 2124 2131 2133 +f 2123 2131 2124 +f 2126 2124 2133 +f 2129 1984 2134 +f 2134 1984 1986 +f 2134 2135 2136 +f 2130 2134 2136 +f 2129 2134 2130 +f 2137 2131 2136 +f 2136 2131 2130 +f 2132 2131 2137 +f 2134 1986 2138 +f 2138 1986 1987 +f 2135 2134 2139 +f 2139 2134 2138 +f 2138 1987 2140 +f 2140 1987 1988 +f 2142 2141 2139 +f 2138 2142 2139 +f 2140 2142 2138 +f 2141 2142 2143 +f 2140 1988 2144 +f 2144 1988 1989 +f 2142 2140 2145 +f 2145 2140 2144 +f 2147 2146 2143 +f 2142 2147 2143 +f 2145 2147 2142 +f 2146 2147 2148 +f 2144 1989 2149 +f 2149 1989 2150 +f 2145 2144 2151 +f 2151 2144 2149 +f 2151 2152 2153 +f 2147 2151 2153 +f 2145 2151 2147 +f 2148 2147 2153 +f 1995 1996 2154 +f 2155 2015 2016 +f 2149 2157 2158 +f 2159 2149 2160 +f 2156 2149 2161 +f 2151 2149 2162 +f 2162 2149 2156 +f 2152 2151 2163 +f 2163 2151 2162 +f 2166 1995 2154 +f 2165 1995 2166 +f 2017 1995 2165 +f 2164 2017 2165 +f 2018 2017 2167 +f 2167 2017 2164 +f 2019 2018 2168 +f 2168 2018 2167 +f 2020 2019 2169 +f 2169 2019 2168 +f 2021 2020 2170 +f 2170 2020 2169 +f 2022 2021 2171 +f 2171 2021 2170 +f 2023 2022 2172 +f 2172 2022 2171 +f 2024 2023 2173 +f 2173 2023 2172 +f 2025 2024 2174 +f 2174 2024 2173 +f 2026 2025 2175 +f 2175 2025 2174 +f 2027 2026 2176 +f 2176 2026 2175 +f 2028 2027 2177 +f 2177 2027 2176 +f 2029 2028 2178 +f 2178 2028 2177 +f 2030 2029 2179 +f 2179 2029 2178 +f 2031 2181 2180 +f 2180 2182 2183 +f 2035 2031 2184 +f 2184 2031 2180 +f 2155 2016 2035 +f 2184 2155 2035 +f 2185 2155 2184 +f 2185 2186 2187 +f 2188 2185 2187 +f 2155 2185 2189 +f 2190 2191 2187 +f 2187 2192 2193 +f 2195 2194 2190 +f 2196 2164 2197 +f 2197 2164 2165 +f 2167 2164 2198 +f 2198 2164 2196 +f 2168 2167 2199 +f 2199 2167 2198 +f 2169 2168 2200 +f 2200 2168 2199 +f 2170 2169 2201 +f 2201 2169 2200 +f 2171 2170 2202 +f 2202 2170 2201 +f 2172 2171 2203 +f 2203 2171 2202 +f 2173 2172 2204 +f 2204 2172 2203 +f 2174 2173 2205 +f 2205 2173 2204 +f 2175 2174 2206 +f 2206 2174 2205 +f 2176 2175 2207 +f 2207 2175 2206 +f 2177 2176 2208 +f 2208 2176 2207 +f 2178 2177 2209 +f 2209 2177 2208 +f 2179 2178 2210 +f 2210 2178 2209 +f 2180 2212 2211 +f 2211 2213 2214 +f 2184 2180 2215 +f 2215 2180 2211 +f 2185 2184 2216 +f 2216 2184 2215 +f 2186 2185 2217 +f 2217 2185 2216 +f 2218 2196 2197 +f 2196 2218 2220 +f 2219 2196 2220 +f 2198 2196 2219 +f 2199 2198 2221 +f 2221 2198 2219 +f 2200 2199 2222 +f 2222 2199 2221 +f 2201 2200 2223 +f 2223 2200 2222 +f 2202 2201 2224 +f 2224 2201 2223 +f 2224 2225 2226 +f 2203 2224 2226 +f 2202 2224 2203 +f 2203 2226 2228 +f 2227 2203 2228 +f 2204 2203 2227 +f 2205 2204 2229 +f 2229 2204 2227 +f 2206 2205 2230 +f 2230 2205 2229 +f 2207 2206 2231 +f 2231 2206 2230 +f 2208 2207 2232 +f 2232 2207 2231 +f 2209 2208 2233 +f 2233 2208 2232 +f 2210 2209 2234 +f 2234 2209 2233 +f 2237 2235 2236 +f 2211 2238 2236 +f 2240 2239 2211 +f 2211 2236 2242 +f 2241 2211 2242 +f 2215 2211 2241 +f 2216 2215 2243 +f 2243 2215 2241 +f 2217 2216 2244 +f 2244 2216 2243 +f 2245 2037 2038 +f 2248 2247 2246 +f 2246 2249 2250 +f 2040 2039 2251 +f 2251 2039 2252 +f 2041 2040 2253 +f 2253 2040 2251 +f 1200 2255 1100 +f 1100 2255 2109 +f 2045 2043 2256 +f 2256 2043 2254 +f 2245 2038 2045 +f 2256 2245 2045 +f 2257 2245 2256 +f 2259 2245 2258 +f 2258 2245 2257 +f 2251 2261 2260 +f 2260 2262 2258 +f 2260 2263 2264 +f 2253 2260 2264 +f 2251 2260 2253 +f 1273 2265 1200 +f 1200 2265 2255 +f 2254 2047 2048 +f 2266 2254 2048 +f 2256 2254 2266 +f 2257 2256 2267 +f 2267 2256 2266 +f 2258 2257 2268 +f 2268 2257 2267 +f 2260 2258 2269 +f 2269 2258 2268 +f 2263 2260 2270 +f 2270 2260 2269 +f 2266 2048 2271 +f 2271 2048 2050 +f 2267 2266 2272 +f 2272 2266 2271 +f 2268 2267 2273 +f 2273 2267 2272 +f 2269 2268 2274 +f 2274 2268 2273 +f 2270 2269 2275 +f 2275 2269 2274 +f 2271 2050 2276 +f 2276 2050 2052 +f 2272 2271 2277 +f 2277 2271 2276 +f 2273 2272 2278 +f 2278 2272 2277 +f 2274 2273 2279 +f 2279 2273 2278 +f 2275 2274 2280 +f 2280 2274 2279 +f 2276 2052 2281 +f 2281 2052 2059 +f 2277 2276 2282 +f 2282 2276 2281 +f 2278 2277 2283 +f 2283 2277 2282 +f 2279 2278 2284 +f 2284 2278 2283 +f 2286 2285 2280 +f 2279 2286 2280 +f 2284 2286 2279 +f 2287 2068 2067 +f 2281 2059 2068 +f 2287 2281 2068 +f 2288 2281 2287 +f 2282 2281 2289 +f 2289 2281 2288 +f 2283 2282 2290 +f 2290 2282 2289 +f 2284 2283 2291 +f 2291 2283 2290 +f 2286 2284 2292 +f 2292 2284 2291 +f 2293 2079 2078 +f 2287 2067 2079 +f 2293 2287 2079 +f 2294 2287 2293 +f 2288 2287 2295 +f 2295 2287 2294 +f 2289 2288 2296 +f 2296 2288 2295 +f 2290 2289 2297 +f 2297 2289 2296 +f 2291 2290 2298 +f 2298 2290 2297 +f 2292 2291 2299 +f 2299 2291 2298 +f 2300 2090 2089 +f 2094 2090 2301 +f 2301 2090 2300 +f 2293 2078 2094 +f 2301 2293 2094 +f 2302 2293 2301 +f 2294 2293 2303 +f 2303 2293 2302 +f 2295 2294 2304 +f 2304 2294 2303 +f 2296 2295 2305 +f 2305 2295 2304 +f 2297 2296 2306 +f 2306 2296 2305 +f 2298 2297 2307 +f 2307 2297 2306 +f 2299 2298 2308 +f 2308 2298 2307 +f 2309 2107 2106 +f 2300 2089 2107 +f 2309 2300 2107 +f 2310 2300 2309 +f 2301 2300 2311 +f 2311 2300 2310 +f 2302 2301 2312 +f 2312 2301 2311 +f 2303 2302 2313 +f 2313 2302 2312 +f 2304 2303 2314 +f 2314 2303 2313 +f 2305 2304 2315 +f 2315 2304 2314 +f 2306 2305 2316 +f 2316 2305 2315 +f 2307 2306 2317 +f 2317 2306 2316 +f 2308 2307 2318 +f 2318 2307 2317 +f 2309 2106 2319 +f 2319 2106 2121 +f 2310 2309 2320 +f 2320 2309 2319 +f 2311 2310 2321 +f 2321 2310 2320 +f 2312 2311 2322 +f 2322 2311 2321 +f 2313 2312 2323 +f 2323 2312 2322 +f 2314 2313 2324 +f 2324 2313 2323 +f 2315 2314 2325 +f 2325 2314 2324 +f 2316 2315 2326 +f 2326 2315 2325 +f 2317 2316 2327 +f 2327 2316 2326 +f 2318 2317 2328 +f 2328 2317 2327 +f 2329 2127 2126 +f 2319 2121 2127 +f 2329 2319 2127 +f 2330 2319 2329 +f 2320 2319 2331 +f 2331 2319 2330 +f 2321 2320 2332 +f 2332 2320 2331 +f 2322 2321 2333 +f 2333 2321 2332 +f 2323 2322 2334 +f 2334 2322 2333 +f 2324 2323 2335 +f 2335 2323 2334 +f 2325 2324 2336 +f 2336 2324 2335 +f 2326 2325 2337 +f 2337 2325 2336 +f 2327 2326 2338 +f 2338 2326 2337 +f 2328 2327 2339 +f 2339 2327 2338 +f 2340 2133 2132 +f 2329 2126 2133 +f 2340 2329 2133 +f 2341 2329 2340 +f 2330 2329 2342 +f 2342 2329 2341 +f 2331 2330 2343 +f 2343 2330 2342 +f 2332 2331 2344 +f 2344 2331 2343 +f 2333 2332 2345 +f 2345 2332 2344 +f 2334 2333 2346 +f 2346 2333 2345 +f 2335 2334 2347 +f 2347 2334 2346 +f 2336 2335 2348 +f 2348 2335 2347 +f 2337 2336 2349 +f 2349 2336 2348 +f 2338 2337 2350 +f 2350 2337 2349 +f 2339 2338 2351 +f 2351 2338 2350 +f 2352 2136 2135 +f 2137 2136 2353 +f 2353 2136 2352 +f 2340 2132 2137 +f 2353 2340 2137 +f 2354 2340 2353 +f 2341 2340 2355 +f 2355 2340 2354 +f 2342 2341 2356 +f 2356 2341 2355 +f 2343 2342 2357 +f 2357 2342 2356 +f 2344 2343 2358 +f 2358 2343 2357 +f 2345 2344 2359 +f 2359 2344 2358 +f 2346 2345 2360 +f 2360 2345 2359 +f 2347 2346 2361 +f 2361 2346 2360 +f 2348 2347 2362 +f 2362 2347 2361 +f 2349 2348 2363 +f 2363 2348 2362 +f 2350 2349 2364 +f 2364 2349 2363 +f 2351 2350 2365 +f 2365 2350 2364 +f 2352 2135 2366 +f 2366 2135 2139 +f 2353 2352 2367 +f 2367 2352 2366 +f 2354 2353 2368 +f 2368 2353 2367 +f 2355 2354 2369 +f 2369 2354 2368 +f 2356 2355 2370 +f 2370 2355 2369 +f 2357 2356 2371 +f 2371 2356 2370 +f 2358 2357 2372 +f 2372 2357 2371 +f 2359 2358 2373 +f 2373 2358 2372 +f 2360 2359 2374 +f 2374 2359 2373 +f 2361 2360 2375 +f 2375 2360 2374 +f 2362 2361 2376 +f 2376 2361 2375 +f 2363 2362 2377 +f 2377 2362 2376 +f 2364 2363 2378 +f 2378 2363 2377 +f 2381 2380 2379 +f 2379 2382 2383 +f 2366 2139 2141 +f 2366 2141 2143 +f 2384 2366 2143 +f 2367 2366 2384 +f 2368 2367 2385 +f 2385 2367 2384 +f 2369 2368 2386 +f 2386 2368 2385 +f 2370 2369 2387 +f 2387 2369 2386 +f 2371 2370 2388 +f 2388 2370 2387 +f 2372 2371 2389 +f 2389 2371 2388 +f 2373 2372 2390 +f 2390 2372 2389 +f 2374 2373 2391 +f 2391 2373 2390 +f 2375 2374 2392 +f 2392 2374 2391 +f 2392 2393 2394 +f 2376 2392 2394 +f 2375 2392 2376 +f 2376 2394 2396 +f 2395 2376 2396 +f 2377 2376 2395 +f 2399 2398 2397 +f 2397 2400 2401 +f 2397 2402 2403 +f 2379 2397 2403 +f 2404 2397 2379 +f 2384 2143 2146 +f 2384 2146 2148 +f 2405 2384 2148 +f 2385 2384 2405 +f 2386 2385 2406 +f 2406 2385 2405 +f 2387 2386 2407 +f 2407 2386 2406 +f 2388 2387 2408 +f 2408 2387 2407 +f 2389 2388 2409 +f 2409 2388 2408 +f 2390 2389 2410 +f 2410 2389 2409 +f 2410 2411 2412 +f 2391 2410 2412 +f 2390 2410 2391 +f 2413 2392 2412 +f 2412 2392 2391 +f 2393 2392 2414 +f 2414 2392 2415 +f 2415 2392 2416 +f 2416 2392 2413 +f 2419 2418 2420 +f 2422 2421 2423 +f 2417 2424 2425 +f 2397 2427 2426 +f 2426 2428 2417 +f 2402 2397 2429 +f 2429 2397 2426 +f 2430 2153 2152 +f 2405 2148 2153 +f 2430 2405 2153 +f 2431 2405 2430 +f 2406 2405 2432 +f 2432 2405 2431 +f 2407 2406 2433 +f 2433 2406 2432 +f 2408 2407 2434 +f 2434 2407 2433 +f 2409 2408 2435 +f 2435 2408 2434 +f 2410 2409 2436 +f 2436 2409 2435 +f 2411 2410 2437 +f 2437 2410 2436 +f 2438 2440 2439 +f 2439 2441 2442 +f 2417 2444 2443 +f 2443 2445 2438 +f 2426 2417 2446 +f 2446 2417 2443 +f 2429 2426 2447 +f 2447 2426 2446 +f 2430 2152 2448 +f 2448 2152 2163 +f 2431 2430 2449 +f 2449 2430 2448 +f 2432 2431 2450 +f 2450 2431 2449 +f 2433 2432 2451 +f 2451 2432 2450 +f 2434 2433 2452 +f 2452 2433 2451 +f 2435 2434 2453 +f 2453 2434 2452 +f 2436 2435 2454 +f 2454 2435 2453 +f 2457 2456 2455 +f 2455 2458 2459 +f 2460 2438 2461 +f 2461 2438 2439 +f 2443 2438 2462 +f 2462 2438 2460 +f 2462 2463 2464 +f 2446 2462 2464 +f 2443 2462 2446 +f 2447 2446 2464 +f 2165 2166 2465 +f 2466 2187 2186 +f 2190 2187 2467 +f 2467 2187 2466 +f 2448 2163 2469 +f 2470 2448 2471 +f 2468 2448 2472 +f 2449 2448 2473 +f 2473 2448 2468 +f 2450 2449 2474 +f 2474 2449 2473 +f 2451 2450 2475 +f 2475 2450 2474 +f 2452 2451 2476 +f 2476 2451 2475 +f 2479 2478 2477 +f 2477 2480 2481 +f 2484 2483 2482 +f 2482 2485 2477 +f 2487 2486 2455 +f 2488 2487 2455 +f 2482 2487 2489 +f 2486 2487 2490 +f 2490 2487 2491 +f 2460 2461 2490 +f 2491 2460 2490 +f 2492 2460 2491 +f 2492 2493 2494 +f 2462 2492 2494 +f 2460 2492 2462 +f 2463 2462 2494 +f 2165 2465 2197 +f 2197 2465 2495 +f 2466 2186 2496 +f 2496 2186 2217 +f 2467 2466 2497 +f 2497 2466 2496 +f 2499 2467 2498 +f 2498 2467 2497 +f 2473 2468 2500 +f 2500 2468 2501 +f 2474 2473 2502 +f 2502 2473 2500 +f 2475 2474 2503 +f 2503 2474 2502 +f 2506 2505 2504 +f 2504 2507 2508 +f 2477 2510 2509 +f 2509 2511 2504 +f 2482 2477 2512 +f 2512 2477 2509 +f 2487 2482 2513 +f 2513 2482 2512 +f 2513 2514 2515 +f 2491 2513 2515 +f 2487 2513 2491 +f 2516 2492 2515 +f 2515 2492 2491 +f 2493 2492 2516 +f 2517 2218 2197 +f 2495 2517 2197 +f 2518 2517 2495 +f 2220 2218 2517 +f 2519 2226 2225 +f 2228 2226 2519 +f 2520 2236 2235 +f 2242 2236 2520 +f 2496 2217 2521 +f 2521 2217 2244 +f 2497 2496 2522 +f 2522 2496 2521 +f 2525 2524 2523 +f 2523 2526 2527 +f 2500 2529 2528 +f 2528 2530 2523 +f 2502 2500 2531 +f 2531 2500 2528 +f 2503 2502 2532 +f 2532 2502 2531 +f 2504 2534 2533 +f 2533 2535 2536 +f 2509 2504 2537 +f 2537 2504 2533 +f 2512 2509 2538 +f 2538 2509 2537 +f 2513 2512 2539 +f 2539 2512 2538 +f 2541 2540 2514 +f 2513 2541 2514 +f 2539 2541 2513 +f 2540 2541 2542 +f 2544 2543 2545 +f 2545 2543 2546 +f 2547 2264 2263 +f 2547 2263 2548 +f 2548 2263 2270 +f 2548 2270 2549 +f 2549 2270 2275 +f 2549 2275 2550 +f 2550 2275 2280 +f 2550 2280 2285 +f 2551 2552 2553 +f 2555 2554 2551 +f 2556 2403 2402 +f 2557 2558 2559 +f 2562 2561 2560 +f 2560 2563 2557 +f 2551 2564 2565 +f 2567 2566 2560 +f 2569 2568 2551 +f 2571 2570 2556 +f 2402 2571 2556 +f 2429 2571 2402 +f 2557 2573 2572 +f 2572 2574 2575 +f 2560 2557 2576 +f 2576 2557 2572 +f 2577 2560 2439 +f 2439 2560 2576 +f 2571 2429 2578 +f 2578 2429 2447 +f 2572 2580 2579 +f 2579 2581 2455 +f 2576 2572 2582 +f 2582 2572 2579 +f 2439 2576 2461 +f 2461 2576 2582 +f 2583 2464 2463 +f 2447 2464 2583 +f 2584 2447 2583 +f 2578 2447 2584 +f 2579 2455 2486 +f 2579 2486 2582 +f 2582 2486 2490 +f 2490 2461 2582 +f 2585 2494 2493 +f 2583 2463 2494 +f 2585 2583 2494 +f 2586 2583 2585 +f 2584 2583 2587 +f 2587 2583 2586 +f 2588 2515 2514 +f 2516 2515 2589 +f 2589 2515 2588 +f 2585 2493 2516 +f 2589 2585 2516 +f 2590 2585 2589 +f 2586 2585 2591 +f 2591 2585 2590 +f 2587 2586 2592 +f 2592 2586 2591 +f 2588 2514 2540 +f 2588 2540 2542 +f 2593 2588 2542 +f 2589 2588 2593 +f 2593 2544 2545 +f 2590 2593 2545 +f 2589 2593 2590 +f 2590 2545 2546 +f 2594 2590 2546 +f 2591 2590 2594 +f 2592 2591 2595 +f 2595 2591 2594 +f 2596 2570 2571 +f 2598 2597 2596 +f 2571 2598 2596 +f 2578 2598 2571 +f 2598 2578 2599 +f 2599 2578 2584 +f 2599 2584 2600 +f 2600 2584 2587 +f 2600 2587 2601 +f 2601 2587 2592 +f 2601 2592 2602 +f 2602 2592 2595 +f 2603 2597 2604 +f 2604 2597 2598 +f 2604 2598 2605 +f 2605 2598 2599 +f 2605 2599 2606 +f 2606 2599 2600 +f 2606 2600 2607 +f 2607 2600 2601 +f 2607 2601 2608 +f 2608 2601 2602 +f 2609 2603 2610 +f 2610 2603 2604 +f 2610 2604 2611 +f 2611 2604 2605 +f 2611 2605 2612 +f 2612 2605 2606 +f 2612 2606 2613 +f 2613 2606 2607 +f 2613 2607 2614 +f 2614 2607 2608 +f 2615 2617 2616 +f 2616 2618 2619 +f 2616 2621 2620 +f 2620 2622 2623 +f 2620 2625 2624 +f 2624 2626 2627 +f 2624 2629 2628 +f 2628 2630 2631 +f 2628 2633 2632 +f 2634 2613 2614 +f 2635 2615 2616 +f 2255 2265 2635 +f 2616 2255 2635 +f 2620 2255 2616 +f 2255 2620 2109 +f 2109 2620 2624 +f 2109 2624 1921 +f 1921 2624 2628 +f 1921 2628 1922 +f 1922 2628 2632 diff --git a/data/meshes/voxel_mesh_03.obj b/data/meshes/voxel_mesh_03.obj new file mode 100644 index 0000000..61c8e35 --- /dev/null +++ b/data/meshes/voxel_mesh_03.obj @@ -0,0 +1,4373 @@ +# voxel +v 1700.000000000 0.000000000 197.653961182 +v 1666.644653320 0.000000000 200.000000000 +v 1800.000000000 0.000000000 190.620483398 +v 1900.000000000 0.000000000 182.817306519 +v 2000.000000000 0.000000000 174.987609863 +v 2100.000000000 0.000000000 167.184417725 +v 2200.000000000 0.000000000 159.381240845 +v 2300.000000000 0.000000000 151.551513672 +v 2400.000000000 0.000000000 142.978637695 +v 2500.000000000 0.000000000 135.148910522 +v 2600.000000000 0.000000000 127.345741272 +v 2700.000000000 0.000000000 120.312263489 +v 2800.000000000 0.000000000 113.278785706 +v 2900.000000000 0.000000000 107.041549683 +v 3000.000000000 0.000000000 103.113410950 +v 3100.000000000 0.000000000 100.008071899 +v 3200.000000000 100.000000000 100.008071899 +v 3200.000000000 0.000000000 100.008071899 +v 3200.000000000 200.000000000 103.113410950 +v 3200.000000000 300.000000000 107.811264038 +v 3200.000000000 400.000000000 113.278785706 +v 3200.000000000 500.000000000 121.081962585 +v 3200.000000000 600.000000000 128.911682129 +v 3200.000000000 700.000000000 139.050506592 +v 3200.000000000 800.000000000 150.012115479 +v 3200.000000000 900.000000000 160.947174072 +v 3200.000000000 1000.000000000 174.217895508 +v 3200.000000000 1100.000000000 186.718902588 +v 3200.000000000 1194.413452148 200.000000000 +v 500.000000000 0.000000000 296.096099854 +v 475.027648926 0.000000000 300.000000000 +v 600.000000000 0.000000000 282.029144287 +v 700.000000000 0.000000000 273.429718018 +v 800.000000000 0.000000000 263.290893555 +v 900.000000000 0.000000000 255.461166382 +v 1000.000000000 0.000000000 248.427703857 +v 1100.000000000 0.000000000 240.624526978 +v 1200.000000000 0.000000000 232.821350098 +v 1300.000000000 0.000000000 225.787872314 +v 1400.000000000 0.000000000 217.958145142 +v 1500.000000000 0.000000000 210.924667358 +v 1600.000000000 0.000000000 204.687423706 +v 3200.000000000 1200.000000000 200.785858154 +v 3200.000000000 1300.000000000 215.622528076 +v 3200.000000000 1400.000000000 230.459167480 +v 3200.000000000 1500.000000000 246.861740112 +v 3200.000000000 1600.000000000 263.290893555 +v 3200.000000000 1700.000000000 279.693481445 +v 3200.000000000 1800.000000000 296.865783691 +v 3200.000000000 1816.044677734 300.000000000 +v 100.000000000 0.000000000 364.838378906 +v 0.000000000 0.000000000 387.504760742 +v 0.000000000 53.316284180 400.000000000 +v 200.000000000 0.000000000 346.100128174 +v 300.000000000 0.000000000 328.131591797 +v 400.000000000 0.000000000 311.729003906 +v 3200.000000000 1900.000000000 316.400268555 +v 3200.000000000 2000.000000000 335.934753418 +v 3200.000000000 2100.000000000 356.238952637 +v 3200.000000000 2200.000000000 375.773437500 +v 3200.000000000 2300.000000000 396.104156494 +v 3200.000000000 2320.790771484 400.000000000 +v 0.000000000 100.000000000 410.940826416 +v 0.000000000 200.000000000 437.508789062 +v 0.000000000 300.000000000 464.050201416 +v 0.000000000 400.000000000 489.052185059 +v 0.000000000 445.178405762 500.000000000 +v 3200.000000000 2400.000000000 414.842407227 +v 3200.000000000 2500.000000000 434.376892090 +v 3200.000000000 2600.000000000 450.779541016 +v 3200.000000000 2700.000000000 468.748046875 +v 3200.000000000 2800.000000000 487.512817383 +v 3200.000000000 2884.164306641 500.000000000 +v 0.000000000 500.000000000 513.284545898 +v 0.000000000 600.000000000 535.924377441 +v 0.000000000 700.000000000 557.821044922 +v 0.000000000 800.000000000 578.894958496 +v 0.000000000 896.384704590 600.000000000 +v 3200.000000000 2900.000000000 502.349487305 +v 3200.000000000 3000.000000000 517.955810547 +v 3200.000000000 3100.000000000 533.588745117 +v 2919.065673828 3200.000000000 600.000000000 +v 3000.000000000 3200.000000000 586.724670410 +v 3100.000000000 3200.000000000 568.756103516 +v 3200.000000000 3200.000000000 549.221618652 +v 0.000000000 900.000000000 600.791625977 +v 0.000000000 1000.000000000 621.095825195 +v 0.000000000 1100.000000000 641.399963379 +v 0.000000000 1200.000000000 660.164794922 +v 0.000000000 1300.000000000 678.903015137 +v 0.000000000 1396.464965820 700.000000000 +v 2116.750732422 3200.000000000 700.000000000 +v 2200.000000000 3200.000000000 692.200256348 +v 2300.000000000 3200.000000000 682.034912109 +v 2400.000000000 3200.000000000 670.303588867 +v 2500.000000000 3200.000000000 658.598815918 +v 2600.000000000 3200.000000000 646.097839355 +v 2700.000000000 3200.000000000 632.030883789 +v 2800.000000000 3200.000000000 617.963928223 +v 2900.000000000 3200.000000000 603.127258301 +v 0.000000000 1400.000000000 700.773132324 +v 0.000000000 1500.000000000 722.643249512 +v 0.000000000 1600.000000000 743.743713379 +v 0.000000000 1700.000000000 765.613830566 +v 0.000000000 1800.000000000 787.510498047 +v 0.000000000 1857.107543945 800.000000000 +v 1044.421630859 3200.000000000 800.000000000 +v 1100.000000000 3200.000000000 792.181823730 +v 1200.000000000 3200.000000000 782.812683105 +v 1300.000000000 3200.000000000 773.443542480 +v 1400.000000000 3200.000000000 764.844116211 +v 1500.000000000 3200.000000000 756.244689941 +v 1600.000000000 3200.000000000 747.645263672 +v 1700.000000000 3200.000000000 738.276184082 +v 1800.000000000 3200.000000000 729.676757812 +v 1900.000000000 3200.000000000 720.307617188 +v 2000.000000000 3200.000000000 710.938537598 +v 2100.000000000 3200.000000000 701.569396973 +v 0.000000000 1900.000000000 809.380615234 +v 0.000000000 2000.000000000 832.020446777 +v 0.000000000 2100.000000000 854.686828613 +v 0.000000000 2200.000000000 877.353210449 +v 0.000000000 2296.632080078 900.000000000 +v 587.488464355 3200.000000000 900.000000000 +v 600.000000000 3200.000000000 896.091430664 +v 700.000000000 3200.000000000 868.753784180 +v 800.000000000 3200.000000000 844.521545410 +v 900.000000000 3200.000000000 822.651367188 +v 1000.000000000 3200.000000000 806.248779297 +v 0.000000000 2300.000000000 900.789245605 +v 0.000000000 2400.000000000 924.225341797 +v 0.000000000 2500.000000000 947.661376953 +v 0.000000000 2600.000000000 971.097534180 +v 0.000000000 2700.000000000 995.303222656 +v 0.000000000 2720.040527344 1000.000000000 +v 302.014007568 3200.000000000 1000.000000000 +v 400.000000000 3200.000000000 962.498107910 +v 500.000000000 3200.000000000 927.330688477 +v 0.000000000 2800.000000000 1018.739440918 +v 0.000000000 2900.000000000 1046.103515625 +v 0.000000000 3000.000000000 1072.645019531 +v 0.000000000 3100.000000000 1099.213012695 +v 59.996593475 3200.000000000 1100.000000000 +v 100.000000000 3200.000000000 1082.810302734 +v 0.000000000 3102.962158203 1100.000000000 +v 200.000000000 3200.000000000 1039.839843750 +v 300.000000000 3200.000000000 1000.770874023 +v 0.000000000 3200.000000000 1125.780883789 +v 800.000000000 200.000000000 296.865783691 +v 900.000000000 200.000000000 288.292907715 +v 1000.000000000 200.000000000 281.259429932 +v 1100.000000000 200.000000000 274.995666504 +v 1200.000000000 200.000000000 268.758422852 +v 1300.000000000 200.000000000 260.928710938 +v 1400.000000000 200.000000000 254.691482544 +v 1500.000000000 200.000000000 246.861740112 +v 1600.000000000 200.000000000 239.058593750 +v 1700.000000000 200.000000000 231.255386353 +v 1800.000000000 200.000000000 223.425704956 +v 1900.000000000 200.000000000 215.622528076 +v 2000.000000000 200.000000000 207.023101807 +v 800.000000000 214.313644409 300.000000000 +v 900.000000000 257.658477783 300.000000000 +v 1000.000000000 295.935821533 300.000000000 +v 1012.674682617 300.000000000 300.000000000 +v 1100.000000000 300.000000000 294.530151367 +v 1200.000000000 300.000000000 288.292907715 +v 1300.000000000 300.000000000 281.259429932 +v 1400.000000000 300.000000000 273.429718018 +v 1500.000000000 300.000000000 265.626556396 +v 1600.000000000 300.000000000 257.823364258 +v 1700.000000000 300.000000000 249.223953247 +v 1800.000000000 300.000000000 241.394226074 +v 1900.000000000 300.000000000 232.821350098 +v 2000.000000000 300.000000000 223.425704956 +v 2100.000000000 300.000000000 214.056564331 +v 2200.000000000 300.000000000 203.917739868 +v 1100.000000000 324.131988525 300.000000000 +v 1200.000000000 355.552612305 300.000000000 +v 1300.000000000 392.298980713 300.000000000 +v 1320.038330078 400.000000000 300.000000000 +v 1400.000000000 400.000000000 293.760437012 +v 1500.000000000 400.000000000 285.930725098 +v 1600.000000000 400.000000000 277.331298828 +v 1700.000000000 400.000000000 269.528137207 +v 1800.000000000 400.000000000 260.928710938 +v 1900.000000000 400.000000000 251.559585571 +v 2000.000000000 400.000000000 240.624526978 +v 2100.000000000 400.000000000 230.459167480 +v 2200.000000000 400.000000000 219.524093628 +v 2300.000000000 400.000000000 208.589035034 +v 1400.000000000 428.530029297 300.000000000 +v 1500.000000000 464.330963135 300.000000000 +v 1583.261352539 500.000000000 300.000000000 +v 1600.000000000 500.000000000 298.431732178 +v 1700.000000000 500.000000000 289.832305908 +v 1800.000000000 500.000000000 280.463195801 +v 1900.000000000 500.000000000 270.324371338 +v 2000.000000000 500.000000000 259.362762451 +v 2100.000000000 500.000000000 247.658020020 +v 2200.000000000 500.000000000 235.926696777 +v 2300.000000000 500.000000000 224.221923828 +v 2400.000000000 500.000000000 211.720916748 +v 1600.000000000 507.170806885 300.000000000 +v 1700.000000000 548.187133789 300.000000000 +v 1799.978881836 600.000000000 300.000000000 +v 1800.000000000 600.000000000 299.997680664 +v 1900.000000000 600.000000000 289.062622070 +v 2000.000000000 600.000000000 277.331298828 +v 2100.000000000 600.000000000 265.626556396 +v 2200.000000000 600.000000000 253.125518799 +v 2300.000000000 600.000000000 240.624526978 +v 2400.000000000 600.000000000 227.353805542 +v 2500.000000000 600.000000000 214.056564331 +v 2600.000000000 600.000000000 200.785858154 +v 1800.000000000 600.011474609 300.000000000 +v 1900.000000000 655.990112305 300.000000000 +v 1968.771362305 700.000000000 300.000000000 +v 2000.000000000 700.000000000 296.096099854 +v 2100.000000000 700.000000000 283.595092773 +v 2200.000000000 700.000000000 270.324371338 +v 2300.000000000 700.000000000 257.823364258 +v 2400.000000000 700.000000000 243.756408691 +v 2500.000000000 700.000000000 230.459167480 +v 2600.000000000 700.000000000 216.418746948 +v 2700.000000000 700.000000000 202.351791382 +v 2000.000000000 720.833862305 300.000000000 +v 2100.000000000 791.297973633 300.000000000 +v 2111.782470703 800.000000000 300.000000000 +v 2200.000000000 800.000000000 288.292907715 +v 2300.000000000 800.000000000 274.995666504 +v 2400.000000000 800.000000000 260.928710938 +v 2500.000000000 800.000000000 246.092056274 +v 2600.000000000 800.000000000 232.025100708 +v 2700.000000000 800.000000000 217.188446045 +v 2800.000000000 800.000000000 203.121490479 +v 2200.000000000 862.476989746 300.000000000 +v 2249.983642578 900.000000000 300.000000000 +v 2300.000000000 900.000000000 292.964202881 +v 2400.000000000 900.000000000 278.127563477 +v 2500.000000000 900.000000000 263.290893555 +v 2600.000000000 900.000000000 248.427703857 +v 2700.000000000 900.000000000 232.821350098 +v 2800.000000000 900.000000000 217.958145142 +v 2900.000000000 900.000000000 203.121490479 +v 2300.000000000 939.156250000 300.000000000 +v 2373.687255859 1000.000000000 300.000000000 +v 2400.000000000 1000.000000000 296.096099854 +v 2500.000000000 1000.000000000 280.463195801 +v 2600.000000000 1000.000000000 265.626556396 +v 2700.000000000 1000.000000000 249.993652344 +v 2800.000000000 1000.000000000 233.591049194 +v 2900.000000000 1000.000000000 218.754394531 +v 3000.000000000 1000.000000000 203.121490479 +v 2400.000000000 1021.726318359 300.000000000 +v 2489.968017578 1100.000000000 300.000000000 +v 2500.000000000 1100.000000000 298.431732178 +v 2600.000000000 1100.000000000 282.029144287 +v 2700.000000000 1100.000000000 266.396240234 +v 2800.000000000 1100.000000000 250.789886475 +v 2900.000000000 1100.000000000 234.387283325 +v 3000.000000000 1100.000000000 218.754394531 +v 3100.000000000 1100.000000000 203.121490479 +v 2500.000000000 1109.118408203 300.000000000 +v 2599.985107422 1200.000000000 300.000000000 +v 2600.000000000 1200.000000000 299.997680664 +v 2700.000000000 1200.000000000 283.595092773 +v 2800.000000000 1200.000000000 267.192474365 +v 2900.000000000 1200.000000000 250.789886475 +v 3000.000000000 1200.000000000 233.591049194 +v 3100.000000000 1200.000000000 217.188446045 +v 2600.000000000 200.000000000 148.446166992 +v 2600.000000000 1200.012817383 300.000000000 +v 2700.000000000 1291.297851562 300.000000000 +v 2709.091552734 1300.000000000 300.000000000 +v 2800.000000000 1300.000000000 284.364776611 +v 2900.000000000 1300.000000000 267.962188721 +v 3000.000000000 1300.000000000 249.993652344 +v 3100.000000000 1300.000000000 232.821350098 +v 2700.000000000 200.000000000 139.050506592 +v 2800.000000000 1387.014282227 300.000000000 +v 2813.587646484 1400.000000000 300.000000000 +v 2900.000000000 1400.000000000 285.161041260 +v 3000.000000000 1400.000000000 267.192474365 +v 3100.000000000 1400.000000000 249.993652344 +v 2800.000000000 200.000000000 129.681381226 +v 2900.000000000 1486.412109375 300.000000000 +v 2912.985595703 1500.000000000 300.000000000 +v 3000.000000000 1500.000000000 284.364776611 +v 3100.000000000 1500.000000000 265.626556396 +v 2900.000000000 200.000000000 121.081962585 +v 3000.000000000 1590.908569336 300.000000000 +v 3008.344726562 1600.000000000 300.000000000 +v 3100.000000000 1600.000000000 282.825378418 +v 3000.000000000 200.000000000 113.278785706 +v 3099.988281250 1700.000000000 300.000000000 +v 3100.000000000 1700.000000000 299.997680664 +v 3100.000000000 200.000000000 107.811264038 +v 3100.000000000 1700.012939453 300.000000000 +v 3185.146240234 1800.000000000 300.000000000 +v 2500.000000000 100.000000000 146.083984375 +v 2100.000000000 214.302856445 200.000000000 +v 48.268959045 100.000000000 400.000000000 +v 100.000000000 100.000000000 388.274444580 +v 2200.000000000 274.939147949 200.000000000 +v 2235.740478516 300.000000000 200.000000000 +v 2300.000000000 300.000000000 192.956130981 +v 200.000000000 100.000000000 366.404327393 +v 2400.000000000 300.000000000 181.251358032 +v 300.000000000 100.000000000 347.666076660 +v 2500.000000000 300.000000000 171.085998535 +v 400.000000000 100.000000000 330.467224121 +v 2600.000000000 300.000000000 160.150939941 +v 500.000000000 100.000000000 314.834350586 +v 600.000000000 100.000000000 300.793914795 +v 100.000000000 146.898437500 400.000000000 +v 158.642028809 200.000000000 400.000000000 +v 200.000000000 200.000000000 390.636627197 +v 300.000000000 200.000000000 370.305908203 +v 400.000000000 200.000000000 352.337371826 +v 500.000000000 200.000000000 335.934753418 +v 600.000000000 200.000000000 321.098114014 +v 700.000000000 200.000000000 307.800872803 +v 200.000000000 237.490249634 400.000000000 +v 276.891082764 300.000000000 400.000000000 +v 300.000000000 300.000000000 395.307922363 +v 400.000000000 300.000000000 375.003753662 +v 500.000000000 300.000000000 358.601135254 +v 600.000000000 300.000000000 342.968231201 +v 700.000000000 300.000000000 329.697540283 +v 800.000000000 300.000000000 318.762481689 +v 900.000000000 300.000000000 308.597106934 +v 1000.000000000 300.000000000 300.793914795 +v 300.000000000 318.766815186 400.000000000 +v 400.000000000 399.976928711 400.000000000 +v 400.030761719 400.000000000 400.000000000 +v 500.000000000 400.000000000 381.240966797 +v 600.000000000 400.000000000 365.634613037 +v 700.000000000 400.000000000 352.337371826 +v 800.000000000 400.000000000 341.402313232 +v 900.000000000 400.000000000 332.033172607 +v 1000.000000000 400.000000000 324.230010986 +v 1100.000000000 400.000000000 317.196533203 +v 1200.000000000 400.000000000 309.366790771 +v 1300.000000000 400.000000000 301.563629150 +v 500.000000000 472.714294434 400.000000000 +v 542.915405273 500.000000000 400.000000000 +v 600.000000000 500.000000000 390.636627197 +v 700.000000000 500.000000000 377.339385986 +v 800.000000000 500.000000000 365.634613037 +v 900.000000000 500.000000000 356.238952637 +v 1000.000000000 500.000000000 347.666076660 +v 1100.000000000 500.000000000 339.836364746 +v 1200.000000000 500.000000000 331.236938477 +v 1300.000000000 500.000000000 323.433746338 +v 1400.000000000 500.000000000 315.630584717 +v 1500.000000000 500.000000000 307.800872803 +v 600.000000000 535.278320312 400.000000000 +v 700.000000000 587.837768555 400.000000000 +v 726.745849609 600.000000000 400.000000000 +v 800.000000000 600.000000000 391.406341553 +v 900.000000000 600.000000000 382.037231445 +v 1000.000000000 600.000000000 373.437805176 +v 1100.000000000 600.000000000 365.634613037 +v 1200.000000000 600.000000000 357.035186768 +v 1300.000000000 600.000000000 348.435791016 +v 1400.000000000 600.000000000 339.066650391 +v 1500.000000000 600.000000000 329.697540283 +v 1600.000000000 600.000000000 320.301879883 +v 1700.000000000 600.000000000 310.932739258 +v 800.000000000 632.345947266 400.000000000 +v 900.000000000 667.610656738 400.000000000 +v 1000.000000000 699.978332520 400.000000000 +v 1000.067016602 700.000000000 400.000000000 +v 1100.000000000 700.000000000 391.406341553 +v 1200.000000000 700.000000000 382.037231445 +v 1300.000000000 700.000000000 372.668090820 +v 1400.000000000 700.000000000 362.502716064 +v 1500.000000000 700.000000000 353.133605957 +v 1600.000000000 700.000000000 343.737945557 +v 1700.000000000 700.000000000 332.033172607 +v 1800.000000000 700.000000000 320.301879883 +v 1900.000000000 700.000000000 308.597106934 +v 1100.000000000 732.345947266 400.000000000 +v 1200.000000000 769.699584961 400.000000000 +v 1271.411865234 800.000000000 400.000000000 +v 1300.000000000 800.000000000 396.873870850 +v 1400.000000000 800.000000000 386.708496094 +v 1500.000000000 800.000000000 376.569671631 +v 1600.000000000 800.000000000 365.634613037 +v 1700.000000000 800.000000000 353.133605957 +v 1800.000000000 800.000000000 340.632598877 +v 1900.000000000 800.000000000 328.131591797 +v 2000.000000000 800.000000000 314.834350586 +v 2100.000000000 800.000000000 301.563629150 +v 1300.000000000 812.503540039 400.000000000 +v 1300.000000000 800.000000000 396.873870850 +v 1271.411865234 800.000000000 400.000000000 +v 1400.000000000 856.713745117 400.000000000 +v 1400.000000000 800.000000000 386.708496094 +v 1300.000000000 800.000000000 396.873870850 +v 1400.000000000 800.000000000 386.708496094 +v 1492.770996094 900.000000000 400.000000000 +v 1500.000000000 900.000000000 399.209503174 +v 1400.000000000 800.000000000 386.708496094 +v 1500.000000000 900.000000000 399.209503174 +v 1600.000000000 900.000000000 388.274444580 +v 1500.000000000 900.000000000 399.209503174 +v 1700.000000000 900.000000000 375.003753662 +v 1800.000000000 900.000000000 361.706481934 +v 1900.000000000 900.000000000 348.435791016 +v 2000.000000000 900.000000000 334.368835449 +v 2100.000000000 900.000000000 321.098114014 +v 2200.000000000 900.000000000 307.031158447 +v 1500.000000000 903.372924805 400.000000000 +v 1500.000000000 900.000000000 399.209503174 +v 1492.770996094 900.000000000 400.000000000 +v 1600.000000000 955.570190430 400.000000000 +v 1500.000000000 900.000000000 399.209503174 +v 1600.000000000 900.000000000 388.274444580 +v 1500.000000000 903.372924805 400.000000000 +v 1666.644653320 1000.000000000 400.000000000 +v 1700.000000000 1000.000000000 395.307922363 +v 1600.000000000 900.000000000 388.274444580 +v 1700.000000000 900.000000000 375.003753662 +v 1600.000000000 900.000000000 388.274444580 +v 1800.000000000 1000.000000000 382.806915283 +v 1700.000000000 900.000000000 375.003753662 +v 1800.000000000 1000.000000000 382.806915283 +v 1900.000000000 1000.000000000 368.739959717 +v 1800.000000000 1000.000000000 382.806915283 +v 2000.000000000 1000.000000000 354.699554443 +v 2100.000000000 1000.000000000 339.836364746 +v 2200.000000000 1000.000000000 325.769409180 +v 2300.000000000 1000.000000000 310.932739258 +v 1700.000000000 1020.700622559 400.000000000 +v 1800.000000000 1081.482177734 400.000000000 +v 1826.335693359 1100.000000000 400.000000000 +v 1900.000000000 1100.000000000 389.070678711 +v 1900.000000000 1100.000000000 389.070678711 +v 1800.000000000 1000.000000000 382.806915283 +v 2000.000000000 1100.000000000 375.003753662 +v 1900.000000000 1100.000000000 389.070678711 +v 2100.000000000 1100.000000000 359.370849609 +v 2200.000000000 1100.000000000 344.534179688 +v 2300.000000000 1100.000000000 328.901306152 +v 2400.000000000 1100.000000000 314.064636230 +v 1900.000000000 1153.827880859 400.000000000 +v 1963.187377930 1200.000000000 400.000000000 +v 2000.000000000 1200.000000000 394.538238525 +v 2000.000000000 1100.000000000 375.003753662 +v 2100.000000000 1200.000000000 378.905334473 +v 2000.000000000 1100.000000000 375.003753662 +v 2100.000000000 1200.000000000 378.905334473 +v 2200.000000000 1200.000000000 363.272430420 +v 2100.000000000 1200.000000000 378.905334473 +v 2300.000000000 1200.000000000 347.666076660 +v 2400.000000000 1200.000000000 332.033172607 +v 2500.000000000 1200.000000000 315.630584717 +v 2000.000000000 1229.147705078 400.000000000 +v 2084.926513672 1300.000000000 400.000000000 +v 2100.000000000 1300.000000000 397.643585205 +v 2200.000000000 1300.000000000 382.037231445 +v 2100.000000000 1200.000000000 378.905334473 +v 2200.000000000 1300.000000000 382.037231445 +v 2300.000000000 1300.000000000 365.634613037 +v 2200.000000000 1300.000000000 382.037231445 +v 2400.000000000 1300.000000000 350.001708984 +v 2500.000000000 1300.000000000 334.368835449 +v 2600.000000000 1300.000000000 317.966217041 +v 2700.000000000 1300.000000000 301.563629150 +v 2100.000000000 1312.062866211 400.000000000 +v 2200.000000000 1395.861572266 400.000000000 +v 2204.727539062 1400.000000000 400.000000000 +v 2300.000000000 1400.000000000 384.372863770 +v 2300.000000000 1400.000000000 384.372863770 +v 2200.000000000 1300.000000000 382.037231445 +v 2400.000000000 1400.000000000 368.739959717 +v 2300.000000000 1400.000000000 384.372863770 +v 2500.000000000 1400.000000000 352.337371826 +v 2600.000000000 1400.000000000 335.934753418 +v 2700.000000000 1400.000000000 319.532165527 +v 2800.000000000 1400.000000000 302.333343506 +v 2300.000000000 1479.997680664 400.000000000 +v 2323.821533203 1500.000000000 400.000000000 +v 2400.000000000 1500.000000000 387.504760742 +v 2400.000000000 1500.000000000 387.504760742 +v 2300.000000000 1400.000000000 384.372863770 +v 2500.000000000 1500.000000000 371.871856689 +v 2400.000000000 1500.000000000 387.504760742 +v 2600.000000000 1500.000000000 354.699554443 +v 2700.000000000 1500.000000000 337.500701904 +v 2800.000000000 1500.000000000 320.301879883 +v 2900.000000000 1500.000000000 302.333343506 +v 2400.000000000 1566.683227539 400.000000000 +v 2442.078125000 1600.000000000 400.000000000 +v 2500.000000000 1600.000000000 391.406341553 +v 2500.000000000 1600.000000000 391.406341553 +v 2400.000000000 1500.000000000 387.504760742 +v 2600.000000000 1600.000000000 374.207489014 +v 2500.000000000 1600.000000000 391.406341553 +v 2700.000000000 1600.000000000 357.035186768 +v 2800.000000000 1600.000000000 338.270416260 +v 2900.000000000 1600.000000000 320.301879883 +v 3000.000000000 1600.000000000 301.563629150 +v 2500.000000000 1645.861572266 400.000000000 +v 2565.002929688 1700.000000000 400.000000000 +v 2600.000000000 1700.000000000 394.538238525 +v 2500.000000000 1645.861572266 400.000000000 +v 2500.000000000 1600.000000000 391.406341553 +v 2500.000000000 1645.861572266 400.000000000 +v 2500.000000000 1600.000000000 391.406341553 +v 2700.000000000 1700.000000000 376.569671631 +v 2800.000000000 1700.000000000 357.804901123 +v 2900.000000000 1700.000000000 339.066650391 +v 3000.000000000 1700.000000000 319.532165527 +v 2600.000000000 1729.147705078 400.000000000 +v 2677.313232422 1800.000000000 400.000000000 +v 2700.000000000 1800.000000000 396.104156494 +v 2800.000000000 1800.000000000 377.339385986 +v 2900.000000000 1800.000000000 358.601135254 +v 3000.000000000 1800.000000000 339.066650391 +v 3100.000000000 1800.000000000 317.966217041 +v 2700.000000000 1819.970458984 400.000000000 +v 2783.316894531 1900.000000000 400.000000000 +v 2800.000000000 1900.000000000 396.873870850 +v 2900.000000000 1900.000000000 378.905334473 +v 3000.000000000 1900.000000000 358.601135254 +v 3100.000000000 1900.000000000 337.500701904 +v 2700.000000000 300.000000000 150.012115479 +v 2800.000000000 1915.396484375 400.000000000 +v 2891.673828125 2000.000000000 400.000000000 +v 2900.000000000 2000.000000000 398.439819336 +v 3000.000000000 2000.000000000 378.135620117 +v 3100.000000000 2000.000000000 357.804901123 +v 2800.000000000 300.000000000 139.846740723 +v 2900.000000000 2007.684082031 400.000000000 +v 2992.316162109 2100.000000000 400.000000000 +v 3000.000000000 2100.000000000 398.439819336 +v 3100.000000000 2100.000000000 378.135620117 +v 2900.000000000 300.000000000 129.681381226 +v 3000.000000000 2107.684082031 400.000000000 +v 3088.832275391 2200.000000000 400.000000000 +v 3100.000000000 2200.000000000 397.643585205 +v 3000.000000000 300.000000000 120.312263489 +v 3100.000000000 2211.167724609 400.000000000 +v 3182.791992188 2300.000000000 400.000000000 +v 3100.000000000 300.000000000 113.278785706 +v 1800.000000000 57.183097839 200.000000000 +v 2300.000000000 345.057952881 200.000000000 +v 2368.706787109 400.000000000 200.000000000 +v 100.000000000 200.000000000 413.276489258 +v 2400.000000000 400.000000000 196.087997437 +v 100.000000000 300.000000000 439.074768066 +v 200.000000000 300.000000000 415.612121582 +v 2500.000000000 400.000000000 184.383255005 +v 100.000000000 400.000000000 464.846435547 +v 200.000000000 400.000000000 441.410339355 +v 300.000000000 400.000000000 420.309936523 +v 400.000000000 400.000000000 400.005767822 +v 54.821578979 500.000000000 500.000000000 +v 100.000000000 500.000000000 489.052185059 +v 2600.000000000 400.000000000 172.651947021 +v 200.000000000 500.000000000 466.412414551 +v 300.000000000 500.000000000 445.311920166 +v 400.000000000 500.000000000 425.777496338 +v 500.000000000 500.000000000 407.039245605 +v 100.000000000 545.178405762 500.000000000 +v 100.000000000 500.000000000 489.052185059 +v 54.821578979 500.000000000 500.000000000 +v 162.958648682 600.000000000 500.000000000 +v 200.000000000 600.000000000 492.184112549 +v 100.000000000 500.000000000 489.052185059 +v 200.000000000 500.000000000 466.412414551 +v 100.000000000 500.000000000 489.052185059 +v 300.000000000 600.000000000 471.879913330 +v 200.000000000 500.000000000 466.412414551 +v 200.000000000 500.000000000 466.412414551 +v 300.000000000 500.000000000 445.311920166 +v 400.000000000 600.000000000 452.345428467 +v 300.000000000 500.000000000 445.311920166 +v 400.000000000 600.000000000 452.345428467 +v 500.000000000 600.000000000 433.580627441 +v 400.000000000 600.000000000 452.345428467 +v 600.000000000 600.000000000 417.178070068 +v 700.000000000 600.000000000 403.137634277 +v 200.000000000 630.327392578 500.000000000 +v 295.824523926 700.000000000 500.000000000 +v 300.000000000 700.000000000 499.217590332 +v 400.000000000 700.000000000 479.683105469 +v 500.000000000 700.000000000 460.944854736 +v 500.000000000 600.000000000 433.580627441 +v 600.000000000 700.000000000 444.542266846 +v 500.000000000 600.000000000 433.580627441 +v 500.000000000 600.000000000 433.580627441 +v 600.000000000 600.000000000 417.178070068 +v 700.000000000 700.000000000 429.679046631 +v 600.000000000 600.000000000 417.178070068 +v 600.000000000 600.000000000 417.178070068 +v 700.000000000 600.000000000 403.137634277 +v 800.000000000 700.000000000 417.974273682 +v 700.000000000 600.000000000 403.137634277 +v 800.000000000 700.000000000 417.974273682 +v 900.000000000 700.000000000 408.605194092 +v 1000.000000000 700.000000000 400.005767822 +v 300.000000000 702.944946289 500.000000000 +v 400.000000000 770.291931152 500.000000000 +v 447.787414551 800.000000000 500.000000000 +v 500.000000000 800.000000000 490.618194580 +v 600.000000000 800.000000000 474.215606689 +v 700.000000000 800.000000000 458.582702637 +v 800.000000000 800.000000000 446.877899170 +v 800.000000000 700.000000000 417.974273682 +v 900.000000000 800.000000000 436.712554932 +v 800.000000000 700.000000000 417.974273682 +v 800.000000000 700.000000000 417.974273682 +v 900.000000000 700.000000000 408.605194092 +v 1000.000000000 800.000000000 428.113128662 +v 900.000000000 700.000000000 408.605194092 +v 900.000000000 700.000000000 408.605194092 +v 1000.000000000 700.000000000 400.005767822 +v 1100.000000000 800.000000000 417.974273682 +v 1000.000000000 700.000000000 400.005767822 +v 1100.000000000 732.345947266 400.000000000 +v 1000.000000000 700.000000000 400.005767822 +v 1200.000000000 800.000000000 407.808929443 +v 1100.000000000 732.345947266 400.000000000 +v 1200.000000000 800.000000000 407.808929443 +v 1200.000000000 800.000000000 407.808929443 +v 500.000000000 833.347045898 500.000000000 +v 600.000000000 889.208435059 500.000000000 +v 619.986511230 900.000000000 500.000000000 +v 700.000000000 900.000000000 487.512817383 +v 800.000000000 900.000000000 476.551208496 +v 900.000000000 900.000000000 466.412414551 +v 1000.000000000 900.000000000 455.477325439 +v 1100.000000000 900.000000000 443.746032715 +v 1200.000000000 900.000000000 432.810913086 +v 1300.000000000 900.000000000 421.875915527 +v 1271.411865234 800.000000000 400.000000000 +v 1400.000000000 900.000000000 410.144622803 +v 700.000000000 942.082092285 500.000000000 +v 700.000000000 900.000000000 487.512817383 +v 619.986511230 900.000000000 500.000000000 +v 800.000000000 981.053161621 500.000000000 +v 800.000000000 900.000000000 476.551208496 +v 700.000000000 900.000000000 487.512817383 +v 800.000000000 900.000000000 476.551208496 +v 853.921997070 1000.000000000 500.000000000 +v 900.000000000 1000.000000000 495.316040039 +v 800.000000000 981.053161621 500.000000000 +v 800.000000000 981.053161621 500.000000000 +v 1000.000000000 1000.000000000 482.018768311 +v 1100.000000000 1000.000000000 468.748046875 +v 1200.000000000 1000.000000000 459.378906250 +v 1300.000000000 1000.000000000 447.647613525 +v 1400.000000000 1000.000000000 435.146606445 +v 1500.000000000 1000.000000000 422.645629883 +v 1500.000000000 903.372924805 400.000000000 +v 1500.000000000 903.372924805 400.000000000 +v 1600.000000000 1000.000000000 409.374847412 +v 1500.000000000 903.372924805 400.000000000 +v 1500.000000000 903.372924805 400.000000000 +v 900.000000000 1019.350708008 500.000000000 +v 1000.000000000 1071.919189453 500.000000000 +v 1064.204101562 1100.000000000 500.000000000 +v 1100.000000000 1100.000000000 496.085693359 +v 1200.000000000 1100.000000000 484.380950928 +v 1300.000000000 1100.000000000 471.879913330 +v 1400.000000000 1100.000000000 458.582702637 +v 1500.000000000 1100.000000000 445.311920166 +v 1600.000000000 1100.000000000 431.245056152 +v 1700.000000000 1100.000000000 417.974273682 +v 1800.000000000 1100.000000000 403.907348633 +v 1100.000000000 1117.269287109 500.000000000 +v 1200.000000000 1168.989257812 500.000000000 +v 1250.004028320 1200.000000000 500.000000000 +v 1300.000000000 1200.000000000 492.980346680 +v 1400.000000000 1200.000000000 482.018768311 +v 1500.000000000 1200.000000000 467.978332520 +v 1600.000000000 1200.000000000 453.115142822 +v 1700.000000000 1200.000000000 439.074768066 +v 1800.000000000 1200.000000000 425.007781982 +v 1900.000000000 1200.000000000 409.374847412 +v 1300.000000000 1234.572387695 500.000000000 +v 1399.904541016 1300.000000000 500.000000000 +v 1400.000000000 1300.000000000 499.987304688 +v 1500.000000000 1300.000000000 488.282531738 +v 1600.000000000 1300.000000000 474.215606689 +v 1700.000000000 1300.000000000 459.378906250 +v 1800.000000000 1300.000000000 443.746032715 +v 1900.000000000 1300.000000000 428.909362793 +v 2000.000000000 1300.000000000 413.276489258 +v 1400.000000000 1300.073852539 500.000000000 +v 1500.000000000 1371.436645508 500.000000000 +v 1540.027465820 1400.000000000 500.000000000 +v 1600.000000000 1400.000000000 492.980346680 +v 1700.000000000 1400.000000000 479.683105469 +v 1800.000000000 1400.000000000 464.846435547 +v 1900.000000000 1400.000000000 449.213562012 +v 2000.000000000 1400.000000000 432.810913086 +v 2100.000000000 1400.000000000 417.178070068 +v 2200.000000000 1400.000000000 400.775421143 +v 1600.000000000 1442.795898438 500.000000000 +v 1675.057617188 1500.000000000 500.000000000 +v 1700.000000000 1500.000000000 496.881958008 +v 1800.000000000 1500.000000000 484.380950928 +v 1900.000000000 1500.000000000 468.748046875 +v 2000.000000000 1500.000000000 452.345428467 +v 2100.000000000 1500.000000000 436.712554932 +v 2200.000000000 1500.000000000 420.309936523 +v 2300.000000000 1500.000000000 403.907348633 +v 1700.000000000 1519.979370117 500.000000000 +v 1799.898559570 1600.000000000 500.000000000 +v 1800.000000000 1600.000000000 499.987304688 +v 1900.000000000 1600.000000000 488.282531738 +v 2000.000000000 1600.000000000 471.879913330 +v 2100.000000000 1600.000000000 455.477325439 +v 2200.000000000 1600.000000000 439.844421387 +v 2300.000000000 1600.000000000 423.441833496 +v 2400.000000000 1600.000000000 406.242980957 +v 1800.000000000 1600.077270508 500.000000000 +v 1900.000000000 1674.953857422 500.000000000 +v 1931.320922852 1700.000000000 500.000000000 +v 2000.000000000 1700.000000000 491.414398193 +v 2100.000000000 1700.000000000 475.011840820 +v 2200.000000000 1700.000000000 458.582702637 +v 2300.000000000 1700.000000000 442.180053711 +v 2400.000000000 1700.000000000 425.777496338 +v 2500.000000000 1700.000000000 410.144622803 +v 2500.000000000 1645.861572266 400.000000000 +v 2500.000000000 1700.000000000 410.144622803 +v 2000.000000000 1755.013427734 500.000000000 +v 2050.003906250 1800.000000000 500.000000000 +v 2100.000000000 1800.000000000 492.980346680 +v 2200.000000000 1800.000000000 476.551208496 +v 2300.000000000 1800.000000000 460.944854736 +v 2400.000000000 1800.000000000 445.311920166 +v 2500.000000000 1800.000000000 428.113128662 +v 2600.000000000 1800.000000000 413.276489258 +v 2500.000000000 1700.000000000 410.144622803 +v 2500.000000000 1700.000000000 410.144622803 +v 2600.000000000 1800.000000000 413.276489258 +v 2100.000000000 1842.795898438 500.000000000 +v 2166.702148438 1900.000000000 500.000000000 +v 2200.000000000 1900.000000000 495.316040039 +v 2300.000000000 1900.000000000 479.683105469 +v 2400.000000000 1900.000000000 463.280548096 +v 2500.000000000 1900.000000000 447.647613525 +v 2600.000000000 1900.000000000 430.475341797 +v 2600.000000000 1800.000000000 413.276489258 +v 2700.000000000 1900.000000000 415.612121582 +v 2600.000000000 1900.000000000 430.475341797 +v 2200.000000000 1926.067749023 500.000000000 +v 2284.978027344 2000.000000000 500.000000000 +v 2300.000000000 2000.000000000 497.651611328 +v 2400.000000000 2000.000000000 482.018768311 +v 2500.000000000 2000.000000000 467.182098389 +v 2600.000000000 2000.000000000 450.779541016 +v 2700.000000000 2000.000000000 435.942840576 +v 2600.000000000 1900.000000000 430.475341797 +v 2700.000000000 2000.000000000 435.942840576 +v 2800.000000000 2000.000000000 417.178070068 +v 2700.000000000 2000.000000000 435.942840576 +v 2300.000000000 2013.069335938 500.000000000 +v 2399.918701172 2100.000000000 500.000000000 +v 2400.000000000 2100.000000000 499.987304688 +v 2500.000000000 2100.000000000 485.150634766 +v 2600.000000000 2100.000000000 469.544281006 +v 2700.000000000 2100.000000000 454.681121826 +v 2800.000000000 2100.000000000 437.508789062 +v 2700.000000000 2000.000000000 435.942840576 +v 2700.000000000 2100.000000000 454.681121826 +v 2700.000000000 2000.000000000 435.942840576 +v 2900.000000000 2100.000000000 418.743988037 +v 2400.000000000 2100.070556641 500.000000000 +v 2500.000000000 2182.640869141 500.000000000 +v 2521.023437500 2200.000000000 500.000000000 +v 2600.000000000 2200.000000000 488.282531738 +v 2700.000000000 2200.000000000 471.879913330 +v 2800.000000000 2200.000000000 456.247039795 +v 2700.000000000 2100.000000000 454.681121826 +v 2800.000000000 2200.000000000 456.247039795 +v 2900.000000000 2200.000000000 438.278472900 +v 2800.000000000 2200.000000000 456.247039795 +v 3000.000000000 2200.000000000 418.743988037 +v 2600.000000000 2268.129638672 500.000000000 +v 2635.062988281 2300.000000000 500.000000000 +v 2700.000000000 2300.000000000 489.848480225 +v 2800.000000000 2300.000000000 474.215606689 +v 2900.000000000 2300.000000000 458.582702637 +v 2800.000000000 2200.000000000 456.247039795 +v 2800.000000000 2300.000000000 474.215606689 +v 2800.000000000 2200.000000000 456.247039795 +v 3000.000000000 2300.000000000 439.844421387 +v 3100.000000000 2300.000000000 418.743988037 +v 2700.000000000 2359.115722656 500.000000000 +v 2744.986572266 2400.000000000 500.000000000 +v 2800.000000000 2400.000000000 491.414398193 +v 2900.000000000 2400.000000000 475.011840820 +v 2800.000000000 2300.000000000 474.215606689 +v 2800.000000000 2400.000000000 491.414398193 +v 2800.000000000 2300.000000000 474.215606689 +v 3000.000000000 2400.000000000 457.812988281 +v 3100.000000000 2400.000000000 438.278472900 +v 2700.000000000 400.000000000 161.716873169 +v 2800.000000000 2452.342773438 500.000000000 +v 2847.657226562 2500.000000000 500.000000000 +v 2900.000000000 2500.000000000 491.414398193 +v 2800.000000000 2452.342773438 500.000000000 +v 2800.000000000 2400.000000000 491.414398193 +v 2800.000000000 2452.342773438 500.000000000 +v 2800.000000000 2400.000000000 491.414398193 +v 3000.000000000 2500.000000000 474.215606689 +v 3100.000000000 2500.000000000 455.477325439 +v 2800.000000000 400.000000000 150.012115479 +v 2900.000000000 2549.996826172 500.000000000 +v 2947.787597656 2600.000000000 500.000000000 +v 3000.000000000 2600.000000000 490.618194580 +v 3100.000000000 2600.000000000 471.083679199 +v 2900.000000000 400.000000000 139.050506592 +v 3000.000000000 2652.212402344 500.000000000 +v 3043.956542969 2700.000000000 500.000000000 +v 3100.000000000 2700.000000000 489.052185059 +v 3000.000000000 400.000000000 129.681381226 +v 3100.000000000 2763.654052734 500.000000000 +v 3133.359863281 2800.000000000 500.000000000 +v 3100.000000000 400.000000000 121.081962585 +v 2600.000000000 100.000000000 136.714859009 +v 2400.000000000 425.024078369 200.000000000 +v 2493.759765625 500.000000000 200.000000000 +v 100.000000000 600.000000000 513.284545898 +v 54.821578979 500.000000000 500.000000000 +v 0.000000000 500.000000000 513.284545898 +v 0.000000000 500.000000000 513.284545898 +v 0.000000000 500.000000000 513.284545898 +v 2500.000000000 500.000000000 199.219924927 +v 100.000000000 700.000000000 537.490295410 +v 0.000000000 600.000000000 535.924377441 +v 100.000000000 700.000000000 537.490295410 +v 200.000000000 700.000000000 517.955810547 +v 100.000000000 700.000000000 537.490295410 +v 2600.000000000 500.000000000 186.718902588 +v 100.000000000 800.000000000 560.926391602 +v 200.000000000 800.000000000 542.957824707 +v 100.000000000 700.000000000 537.490295410 +v 200.000000000 800.000000000 542.957824707 +v 300.000000000 800.000000000 525.785583496 +v 200.000000000 800.000000000 542.957824707 +v 400.000000000 800.000000000 508.586700439 +v 4.818426609 900.000000000 600.000000000 +v 100.000000000 900.000000000 584.362487793 +v 2700.000000000 500.000000000 174.217895508 +v 200.000000000 900.000000000 566.393920898 +v 300.000000000 900.000000000 549.991333008 +v 200.000000000 800.000000000 542.957824707 +v 200.000000000 900.000000000 566.393920898 +v 200.000000000 800.000000000 542.957824707 +v 400.000000000 900.000000000 534.384948730 +v 500.000000000 900.000000000 518.752075195 +v 600.000000000 900.000000000 503.119171143 +v 100.000000000 976.915832520 600.000000000 +v 130.021209717 1000.000000000 600.000000000 +v 200.000000000 1000.000000000 589.060302734 +v 300.000000000 1000.000000000 573.427429199 +v 300.000000000 900.000000000 549.991333008 +v 400.000000000 1000.000000000 558.590759277 +v 300.000000000 900.000000000 549.991333008 +v 300.000000000 900.000000000 549.991333008 +v 400.000000000 900.000000000 534.384948730 +v 500.000000000 1000.000000000 544.523803711 +v 400.000000000 900.000000000 534.384948730 +v 400.000000000 900.000000000 534.384948730 +v 500.000000000 900.000000000 518.752075195 +v 600.000000000 1000.000000000 530.456848145 +v 500.000000000 900.000000000 518.752075195 +v 500.000000000 900.000000000 518.752075195 +v 600.000000000 900.000000000 503.119171143 +v 700.000000000 1000.000000000 517.186157227 +v 619.986511230 900.000000000 500.000000000 +v 600.000000000 900.000000000 503.119171143 +v 600.000000000 900.000000000 503.119171143 +v 600.000000000 900.000000000 503.119171143 +v 800.000000000 1000.000000000 505.481323242 +v 800.000000000 981.053161621 500.000000000 +v 800.000000000 1000.000000000 505.481323242 +v 200.000000000 1053.879028320 600.000000000 +v 263.117279053 1100.000000000 600.000000000 +v 300.000000000 1100.000000000 594.527832031 +v 400.000000000 1100.000000000 580.460876465 +v 500.000000000 1100.000000000 566.393920898 +v 600.000000000 1100.000000000 553.123229980 +v 700.000000000 1100.000000000 541.418457031 +v 800.000000000 1100.000000000 529.687133789 +v 900.000000000 1100.000000000 519.521789551 +v 800.000000000 1000.000000000 505.481323242 +v 800.000000000 1000.000000000 505.481323242 +v 800.000000000 1000.000000000 505.481323242 +v 800.000000000 1100.000000000 529.687133789 +v 1000.000000000 1100.000000000 507.020751953 +v 300.000000000 1128.012817383 600.000000000 +v 399.967041016 1200.000000000 600.000000000 +v 400.000000000 1200.000000000 599.995361328 +v 500.000000000 1200.000000000 586.724670410 +v 600.000000000 1200.000000000 574.223632812 +v 700.000000000 1200.000000000 563.288574219 +v 800.000000000 1200.000000000 552.353515625 +v 900.000000000 1200.000000000 540.622192383 +v 800.000000000 1100.000000000 529.687133789 +v 900.000000000 1200.000000000 540.622192383 +v 1000.000000000 1200.000000000 530.456848145 +v 900.000000000 1200.000000000 540.622192383 +v 1100.000000000 1200.000000000 518.752075195 +v 1200.000000000 1200.000000000 507.020751953 +v 400.000000000 1200.024658203 600.000000000 +v 500.000000000 1270.846313477 600.000000000 +v 546.672363281 1300.000000000 600.000000000 +v 600.000000000 1300.000000000 593.758117676 +v 700.000000000 1300.000000000 582.026855469 +v 800.000000000 1300.000000000 571.888000488 +v 900.000000000 1300.000000000 560.156677246 +v 1000.000000000 1300.000000000 549.991333008 +v 900.000000000 1200.000000000 540.622192383 +v 900.000000000 1300.000000000 560.156677246 +v 900.000000000 1200.000000000 540.622192383 +v 1100.000000000 1300.000000000 537.490295410 +v 1200.000000000 1300.000000000 526.555236816 +v 1300.000000000 1300.000000000 513.284545898 +v 600.000000000 1338.054321289 600.000000000 +v 699.954345703 1400.000000000 600.000000000 +v 700.000000000 1400.000000000 599.995361328 +v 800.000000000 1400.000000000 589.856567383 +v 900.000000000 1400.000000000 578.894958496 +v 1000.000000000 1400.000000000 564.058288574 +v 900.000000000 1300.000000000 560.156677246 +v 900.000000000 1400.000000000 578.894958496 +v 900.000000000 1300.000000000 560.156677246 +v 1100.000000000 1400.000000000 553.123229980 +v 1200.000000000 1400.000000000 542.957824707 +v 1300.000000000 1400.000000000 530.456848145 +v 1400.000000000 1400.000000000 517.186157227 +v 1500.000000000 1400.000000000 504.685119629 +v 700.000000000 1400.031250000 600.000000000 +v 800.000000000 1468.367553711 600.000000000 +v 800.000000000 1400.000000000 589.856567383 +v 700.000000000 1400.000000000 599.995361328 +v 800.000000000 1400.000000000 589.856567383 +v 842.918579102 1500.000000000 600.000000000 +v 900.000000000 1500.000000000 593.758117676 +v 800.000000000 1400.000000000 589.856567383 +v 900.000000000 1500.000000000 593.758117676 +v 900.000000000 1400.000000000 578.894958496 +v 800.000000000 1400.000000000 589.856567383 +v 1000.000000000 1500.000000000 578.125244141 +v 900.000000000 1400.000000000 578.894958496 +v 900.000000000 1500.000000000 593.758117676 +v 900.000000000 1400.000000000 578.894958496 +v 1100.000000000 1500.000000000 567.959899902 +v 1200.000000000 1500.000000000 557.024780273 +v 1300.000000000 1500.000000000 546.089721680 +v 1400.000000000 1500.000000000 534.384948730 +v 1500.000000000 1500.000000000 521.087707520 +v 1600.000000000 1500.000000000 509.382965088 +v 900.000000000 1557.081420898 600.000000000 +v 933.363159180 1600.000000000 600.000000000 +v 1000.000000000 1600.000000000 590.626220703 +v 1000.000000000 1500.000000000 578.125244141 +v 1100.000000000 1600.000000000 579.691162109 +v 1000.000000000 1500.000000000 578.125244141 +v 1000.000000000 1500.000000000 578.125244141 +v 1100.000000000 1500.000000000 567.959899902 +v 1200.000000000 1600.000000000 570.322082520 +v 1100.000000000 1500.000000000 567.959899902 +v 1200.000000000 1600.000000000 570.322082520 +v 1300.000000000 1600.000000000 560.156677246 +v 1200.000000000 1600.000000000 570.322082520 +v 1400.000000000 1600.000000000 549.221618652 +v 1500.000000000 1600.000000000 537.490295410 +v 1600.000000000 1600.000000000 524.989318848 +v 1700.000000000 1600.000000000 512.488281250 +v 1000.000000000 1680.085205078 600.000000000 +v 1021.316711426 1700.000000000 600.000000000 +v 1100.000000000 1700.000000000 591.395935059 +v 1200.000000000 1700.000000000 582.026855469 +v 1300.000000000 1700.000000000 572.657714844 +v 1200.000000000 1600.000000000 570.322082520 +v 1300.000000000 1700.000000000 572.657714844 +v 1400.000000000 1700.000000000 562.492309570 +v 1300.000000000 1700.000000000 572.657714844 +v 1500.000000000 1700.000000000 551.557250977 +v 1600.000000000 1700.000000000 540.622192383 +v 1700.000000000 1700.000000000 528.121215820 +v 1800.000000000 1700.000000000 516.416442871 +v 1900.000000000 1700.000000000 503.915466309 +v 1100.000000000 1773.342651367 600.000000000 +v 1133.378295898 1800.000000000 600.000000000 +v 1200.000000000 1800.000000000 593.758117676 +v 1300.000000000 1800.000000000 585.158691406 +v 1400.000000000 1800.000000000 575.789611816 +v 1400.000000000 1700.000000000 562.492309570 +v 1500.000000000 1800.000000000 565.624206543 +v 1400.000000000 1700.000000000 562.492309570 +v 1500.000000000 1800.000000000 565.624206543 +v 1600.000000000 1800.000000000 554.689147949 +v 1500.000000000 1800.000000000 565.624206543 +v 1700.000000000 1800.000000000 543.754089355 +v 1800.000000000 1800.000000000 532.022766113 +v 1900.000000000 1800.000000000 519.521789551 +v 2000.000000000 1800.000000000 507.020751953 +v 1200.000000000 1853.327758789 600.000000000 +v 1263.526245117 1900.000000000 600.000000000 +v 1300.000000000 1900.000000000 596.863464355 +v 1400.000000000 1900.000000000 588.290588379 +v 1500.000000000 1900.000000000 578.894958496 +v 1600.000000000 1900.000000000 568.756103516 +v 1500.000000000 1800.000000000 565.624206543 +v 1600.000000000 1900.000000000 568.756103516 +v 1700.000000000 1900.000000000 557.821044922 +v 1600.000000000 1900.000000000 568.756103516 +v 1800.000000000 1900.000000000 546.885986328 +v 1900.000000000 1900.000000000 535.154663086 +v 2000.000000000 1900.000000000 522.653686523 +v 2100.000000000 1900.000000000 509.382965088 +v 1300.000000000 1926.736450195 600.000000000 +v 1399.946044922 2000.000000000 600.000000000 +v 1400.000000000 2000.000000000 599.995361328 +v 1500.000000000 2000.000000000 591.395935059 +v 1600.000000000 2000.000000000 582.026855469 +v 1700.000000000 2000.000000000 571.888000488 +v 1600.000000000 1900.000000000 568.756103516 +v 1700.000000000 2000.000000000 571.888000488 +v 1800.000000000 2000.000000000 560.926391602 +v 1700.000000000 2000.000000000 571.888000488 +v 1900.000000000 2000.000000000 549.991333008 +v 2000.000000000 2000.000000000 538.286560059 +v 2100.000000000 2000.000000000 526.555236816 +v 2200.000000000 2000.000000000 513.284545898 +v 1400.000000000 2000.037231445 600.000000000 +v 1500.000000000 2068.826904297 600.000000000 +v 1545.457031250 2100.000000000 600.000000000 +v 1600.000000000 2100.000000000 595.324096680 +v 1700.000000000 2100.000000000 585.928405762 +v 1800.000000000 2100.000000000 574.993347168 +v 1700.000000000 2000.000000000 571.888000488 +v 1800.000000000 2100.000000000 574.993347168 +v 1900.000000000 2100.000000000 564.058288574 +v 1800.000000000 2100.000000000 574.993347168 +v 2000.000000000 2100.000000000 552.353515625 +v 2100.000000000 2100.000000000 540.622192383 +v 2200.000000000 2100.000000000 528.121215820 +v 2300.000000000 2100.000000000 515.620178223 +v 1600.000000000 2137.404296875 600.000000000 +v 1676.977905273 2200.000000000 600.000000000 +v 1700.000000000 2200.000000000 597.659729004 +v 1800.000000000 2200.000000000 587.494384766 +v 1900.000000000 2200.000000000 577.355529785 +v 1800.000000000 2100.000000000 574.993347168 +v 1900.000000000 2200.000000000 577.355529785 +v 2000.000000000 2200.000000000 567.190185547 +v 1900.000000000 2200.000000000 577.355529785 +v 2100.000000000 2200.000000000 555.458862305 +v 2200.000000000 2200.000000000 545.320068359 +v 2300.000000000 2200.000000000 532.819030762 +v 2400.000000000 2200.000000000 517.955810547 +v 2500.000000000 2200.000000000 503.119171143 +v 1700.000000000 2217.635009766 600.000000000 +v 1800.000000000 2294.046875000 600.000000000 +v 1807.787475586 2300.000000000 600.000000000 +v 1900.000000000 2300.000000000 590.626220703 +v 2000.000000000 2300.000000000 579.691162109 +v 1900.000000000 2200.000000000 577.355529785 +v 2000.000000000 2300.000000000 579.691162109 +v 2100.000000000 2300.000000000 568.756103516 +v 2000.000000000 2300.000000000 579.691162109 +v 2200.000000000 2300.000000000 558.590759277 +v 2300.000000000 2300.000000000 546.089721680 +v 2400.000000000 2300.000000000 535.154663086 +v 2500.000000000 2300.000000000 520.317993164 +v 2600.000000000 2300.000000000 505.481323242 +v 1900.000000000 2370.634765625 600.000000000 +v 1938.435913086 2400.000000000 600.000000000 +v 2000.000000000 2400.000000000 593.758117676 +v 2100.000000000 2400.000000000 584.362487793 +v 2000.000000000 2300.000000000 579.691162109 +v 2000.000000000 2400.000000000 593.758117676 +v 2000.000000000 2300.000000000 579.691162109 +v 2200.000000000 2400.000000000 572.657714844 +v 2300.000000000 2400.000000000 560.926391602 +v 2400.000000000 2400.000000000 549.221618652 +v 2500.000000000 2400.000000000 536.720642090 +v 2600.000000000 2400.000000000 521.883972168 +v 2700.000000000 2400.000000000 507.020751953 +v 2000.000000000 2444.372802734 600.000000000 +v 2071.386230469 2500.000000000 600.000000000 +v 2100.000000000 2500.000000000 596.863464355 +v 2100.000000000 2500.000000000 596.863464355 +v 2000.000000000 2400.000000000 593.758117676 +v 2200.000000000 2500.000000000 587.494384766 +v 2100.000000000 2500.000000000 596.863464355 +v 2300.000000000 2500.000000000 575.789611816 +v 2400.000000000 2500.000000000 564.058288574 +v 2500.000000000 2500.000000000 551.557250977 +v 2600.000000000 2500.000000000 539.056274414 +v 2700.000000000 2500.000000000 524.219604492 +v 2800.000000000 2500.000000000 507.817016602 +v 2800.000000000 2452.342773438 500.000000000 +v 2800.000000000 2500.000000000 507.817016602 +v 2100.000000000 2521.102783203 600.000000000 +v 2200.000000000 2594.046875000 600.000000000 +v 2100.000000000 2500.000000000 596.863464355 +v 2100.000000000 2521.102783203 600.000000000 +v 2100.000000000 2521.102783203 600.000000000 +v 2206.748046875 2600.000000000 600.000000000 +v 2300.000000000 2600.000000000 589.060302734 +v 2400.000000000 2600.000000000 578.125244141 +v 2500.000000000 2600.000000000 566.393920898 +v 2600.000000000 2600.000000000 553.919433594 +v 2700.000000000 2600.000000000 540.622192383 +v 2800.000000000 2600.000000000 524.989318848 +v 2900.000000000 2600.000000000 508.586700439 +v 2800.000000000 2500.000000000 507.817016602 +v 2800.000000000 2500.000000000 507.817016602 +v 2800.000000000 2500.000000000 507.817016602 +v 2800.000000000 2600.000000000 524.989318848 +v 2300.000000000 2677.768798828 600.000000000 +v 2326.657226562 2700.000000000 600.000000000 +v 2400.000000000 2700.000000000 591.395935059 +v 2500.000000000 2700.000000000 580.460876465 +v 2600.000000000 2700.000000000 567.959899902 +v 2700.000000000 2700.000000000 554.689147949 +v 2800.000000000 2700.000000000 540.622192383 +v 2900.000000000 2700.000000000 524.989318848 +v 2800.000000000 2600.000000000 524.989318848 +v 2900.000000000 2700.000000000 524.989318848 +v 3000.000000000 2700.000000000 508.586700439 +v 2900.000000000 2700.000000000 524.989318848 +v 2400.000000000 2755.038085938 600.000000000 +v 2456.226318359 2800.000000000 600.000000000 +v 2500.000000000 2800.000000000 594.527832031 +v 2600.000000000 2800.000000000 582.026855469 +v 2700.000000000 2800.000000000 569.525817871 +v 2800.000000000 2800.000000000 555.458862305 +v 2900.000000000 2800.000000000 539.852478027 +v 3000.000000000 2800.000000000 523.449890137 +v 2900.000000000 2700.000000000 524.989318848 +v 3000.000000000 2800.000000000 523.449890137 +v 3100.000000000 2800.000000000 506.251037598 +v 3000.000000000 2800.000000000 523.449890137 +v 2500.000000000 2835.004150391 600.000000000 +v 2581.279296875 2900.000000000 600.000000000 +v 2600.000000000 2900.000000000 597.659729004 +v 2700.000000000 2900.000000000 584.362487793 +v 2800.000000000 2900.000000000 570.322082520 +v 2900.000000000 2900.000000000 554.689147949 +v 3000.000000000 2900.000000000 539.056274414 +v 3100.000000000 2900.000000000 521.883972168 +v 3000.000000000 2800.000000000 523.449890137 +v 3100.000000000 2900.000000000 521.883972168 +v 2800.000000000 500.000000000 161.716873169 +v 3100.000000000 2900.000000000 521.883972168 +v 2600.000000000 2914.970214844 600.000000000 +v 2694.495117188 3000.000000000 600.000000000 +v 2700.000000000 3000.000000000 599.225646973 +v 2800.000000000 3000.000000000 585.158691406 +v 2900.000000000 3000.000000000 570.322082520 +v 3000.000000000 3000.000000000 553.919433594 +v 3100.000000000 3000.000000000 536.720642090 +v 2900.000000000 500.000000000 150.012115479 +v 3100.000000000 2900.000000000 521.883972168 +v 3200.000000000 3000.000000000 517.955810547 +v 2700.000000000 3004.720947266 600.000000000 +v 2800.000000000 3090.481201172 600.000000000 +v 2810.523681641 3100.000000000 600.000000000 +v 2900.000000000 3100.000000000 586.724670410 +v 3000.000000000 3100.000000000 570.322082520 +v 3100.000000000 3100.000000000 552.353515625 +v 3000.000000000 500.000000000 139.846740723 +v 2900.000000000 3180.934326172 600.000000000 +v 3100.000000000 500.000000000 129.681381226 +v 2100.000000000 100.000000000 182.021072388 +v 2500.000000000 505.257843018 200.000000000 +v 2600.000000000 594.413452148 200.000000000 +v 2606.286376953 600.000000000 200.000000000 +v 2700.000000000 600.000000000 188.284835815 +v 100.000000000 1000.000000000 604.693176270 +v 2800.000000000 600.000000000 174.987609863 +v 100.000000000 1100.000000000 625.793640137 +v 200.000000000 1100.000000000 609.364501953 +v 2900.000000000 600.000000000 162.513122559 +v 100.000000000 1200.000000000 645.301574707 +v 200.000000000 1200.000000000 629.695190430 +v 300.000000000 1200.000000000 614.062316895 +v 3000.000000000 600.000000000 150.781829834 +v 100.000000000 1300.000000000 663.270141602 +v 200.000000000 1300.000000000 648.433471680 +v 300.000000000 1300.000000000 633.596801758 +v 400.000000000 1300.000000000 618.760131836 +v 500.000000000 1300.000000000 605.462890625 +v 4.302708149 1400.000000000 700.000000000 +v 100.000000000 1400.000000000 682.804626465 +v 3100.000000000 600.000000000 139.846740723 +v 200.000000000 1400.000000000 667.198242188 +v 300.000000000 1400.000000000 652.335021973 +v 400.000000000 1400.000000000 637.498413086 +v 500.000000000 1400.000000000 623.431457520 +v 600.000000000 1400.000000000 610.160705566 +v 100.000000000 1484.578369141 700.000000000 +v 118.229797363 1500.000000000 700.000000000 +v 200.000000000 1500.000000000 685.936462402 +v 100.000000000 1484.578369141 700.000000000 +v 100.000000000 1400.000000000 682.804626465 +v 100.000000000 1484.578369141 700.000000000 +v 200.000000000 1400.000000000 667.198242188 +v 100.000000000 1400.000000000 682.804626465 +v 300.000000000 1500.000000000 670.303588867 +v 200.000000000 1400.000000000 667.198242188 +v 200.000000000 1400.000000000 667.198242188 +v 300.000000000 1400.000000000 652.335021973 +v 400.000000000 1500.000000000 655.466918945 +v 300.000000000 1400.000000000 652.335021973 +v 300.000000000 1400.000000000 652.335021973 +v 400.000000000 1400.000000000 637.498413086 +v 500.000000000 1500.000000000 641.399963379 +v 400.000000000 1400.000000000 637.498413086 +v 400.000000000 1400.000000000 637.498413086 +v 500.000000000 1400.000000000 623.431457520 +v 600.000000000 1500.000000000 627.333007812 +v 500.000000000 1400.000000000 623.431457520 +v 500.000000000 1400.000000000 623.431457520 +v 600.000000000 1400.000000000 610.160705566 +v 700.000000000 1500.000000000 614.832031250 +v 699.954345703 1400.000000000 600.000000000 +v 600.000000000 1400.000000000 610.160705566 +v 600.000000000 1400.000000000 610.160705566 +v 600.000000000 1400.000000000 610.160705566 +v 800.000000000 1500.000000000 604.693176270 +v 200.000000000 1571.993408203 700.000000000 +v 230.447433472 1600.000000000 700.000000000 +v 300.000000000 1600.000000000 687.502441406 +v 400.000000000 1600.000000000 671.869506836 +v 500.000000000 1600.000000000 657.032897949 +v 600.000000000 1600.000000000 642.965942383 +v 700.000000000 1600.000000000 629.695190430 +v 800.000000000 1600.000000000 617.194213867 +v 900.000000000 1600.000000000 604.693176270 +v 300.000000000 1666.695556641 700.000000000 +v 333.304443359 1700.000000000 700.000000000 +v 400.000000000 1700.000000000 687.502441406 +v 500.000000000 1700.000000000 671.099853516 +v 600.000000000 1700.000000000 657.032897949 +v 700.000000000 1700.000000000 643.762145996 +v 800.000000000 1700.000000000 630.464904785 +v 900.000000000 1700.000000000 614.832031250 +v 1000.000000000 1700.000000000 602.330993652 +v 400.000000000 1776.192626953 700.000000000 +v 422.705169678 1800.000000000 700.000000000 +v 500.000000000 1800.000000000 686.706176758 +v 600.000000000 1800.000000000 669.533874512 +v 700.000000000 1800.000000000 654.697265625 +v 800.000000000 1800.000000000 640.630310059 +v 900.000000000 1800.000000000 625.793640137 +v 1000.000000000 1800.000000000 613.292602539 +v 1100.000000000 1800.000000000 603.127258301 +v 500.000000000 1889.441162109 700.000000000 +v 508.734130859 1900.000000000 700.000000000 +v 600.000000000 1900.000000000 683.600830078 +v 700.000000000 1900.000000000 667.198242188 +v 800.000000000 1900.000000000 650.769104004 +v 900.000000000 1900.000000000 635.932434082 +v 1000.000000000 1900.000000000 624.227661133 +v 1100.000000000 1900.000000000 613.292602539 +v 1200.000000000 1900.000000000 605.462890625 +v 588.044799805 2000.000000000 700.000000000 +v 600.000000000 2000.000000000 697.667785645 +v 700.000000000 2000.000000000 678.903015137 +v 800.000000000 2000.000000000 660.934448242 +v 900.000000000 2000.000000000 646.097839355 +v 1000.000000000 2000.000000000 633.596801758 +v 1100.000000000 2000.000000000 624.227661133 +v 1200.000000000 2000.000000000 616.397949219 +v 1300.000000000 2000.000000000 608.594787598 +v 600.000000000 2019.925292969 700.000000000 +v 647.979553223 2100.000000000 700.000000000 +v 700.000000000 2100.000000000 689.838073730 +v 800.000000000 2100.000000000 671.869506836 +v 900.000000000 2100.000000000 655.466918945 +v 1000.000000000 2100.000000000 642.965942383 +v 1100.000000000 2100.000000000 635.162780762 +v 1200.000000000 2100.000000000 628.129272461 +v 1300.000000000 2100.000000000 620.299560547 +v 1400.000000000 2100.000000000 612.496398926 +v 1500.000000000 2100.000000000 603.896972656 +v 700.000000000 2186.622314453 700.000000000 +v 708.363525391 2200.000000000 700.000000000 +v 800.000000000 2200.000000000 682.804626465 +v 900.000000000 2200.000000000 665.632324219 +v 1000.000000000 2200.000000000 652.335021973 +v 1100.000000000 2200.000000000 645.301574707 +v 1200.000000000 2200.000000000 639.834045410 +v 1300.000000000 2200.000000000 632.800537109 +v 1400.000000000 2200.000000000 624.997375488 +v 1500.000000000 2200.000000000 617.194213867 +v 1600.000000000 2200.000000000 607.825073242 +v 766.682983398 2300.000000000 700.000000000 +v 800.000000000 2300.000000000 692.969970703 +v 900.000000000 2300.000000000 675.001403809 +v 1000.000000000 2300.000000000 664.066345215 +v 1100.000000000 2300.000000000 658.598815918 +v 1200.000000000 2300.000000000 652.335021973 +v 1300.000000000 2300.000000000 645.301574707 +v 1400.000000000 2300.000000000 637.498413086 +v 1500.000000000 2300.000000000 629.695190430 +v 1600.000000000 2300.000000000 620.299560547 +v 1700.000000000 2300.000000000 610.930419922 +v 1800.000000000 2300.000000000 600.791625977 +v 800.000000000 2360.061279297 700.000000000 +v 827.222534180 2400.000000000 700.000000000 +v 900.000000000 2400.000000000 687.502441406 +v 1000.000000000 2400.000000000 677.337097168 +v 1100.000000000 2400.000000000 671.099853516 +v 1200.000000000 2400.000000000 665.632324219 +v 1300.000000000 2400.000000000 658.598815918 +v 1400.000000000 2400.000000000 650.769104004 +v 1500.000000000 2400.000000000 642.196228027 +v 1600.000000000 2400.000000000 632.800537109 +v 1700.000000000 2400.000000000 623.431457520 +v 1800.000000000 2400.000000000 613.292602539 +v 1900.000000000 2400.000000000 603.896972656 +v 900.000000000 2488.843261719 700.000000000 +v 915.438659668 2500.000000000 700.000000000 +v 1000.000000000 2500.000000000 691.403991699 +v 1100.000000000 2500.000000000 684.370544434 +v 1200.000000000 2500.000000000 678.903015137 +v 1300.000000000 2500.000000000 671.869506836 +v 1400.000000000 2500.000000000 663.270141602 +v 1500.000000000 2500.000000000 655.466918945 +v 1600.000000000 2500.000000000 646.867492676 +v 1700.000000000 2500.000000000 637.498413086 +v 1800.000000000 2500.000000000 627.333007812 +v 1900.000000000 2500.000000000 617.963928223 +v 2000.000000000 2500.000000000 607.825073242 +v 1000.000000000 2557.937500000 700.000000000 +v 1079.976074219 2600.000000000 700.000000000 +v 1100.000000000 2600.000000000 698.437500000 +v 1200.000000000 2600.000000000 692.200256348 +v 1300.000000000 2600.000000000 685.166809082 +v 1400.000000000 2600.000000000 677.337097168 +v 1500.000000000 2600.000000000 668.737670898 +v 1600.000000000 2600.000000000 660.164794922 +v 1700.000000000 2600.000000000 651.565368652 +v 1800.000000000 2600.000000000 642.196228027 +v 1900.000000000 2600.000000000 632.030883789 +v 2000.000000000 2600.000000000 621.865478516 +v 2100.000000000 2600.000000000 611.726684570 +v 2200.000000000 2600.000000000 600.791625977 +v 2100.000000000 2521.102783203 600.000000000 +v 2100.000000000 2600.000000000 611.726684570 +v 2100.000000000 2521.102783203 600.000000000 +v 1100.000000000 2611.107666016 700.000000000 +v 1200.000000000 2655.552001953 700.000000000 +v 1279.976074219 2700.000000000 700.000000000 +v 1300.000000000 2700.000000000 698.437500000 +v 1400.000000000 2700.000000000 690.634338379 +v 1500.000000000 2700.000000000 682.804626465 +v 1600.000000000 2700.000000000 674.231750488 +v 1700.000000000 2700.000000000 664.836059570 +v 1800.000000000 2700.000000000 655.466918945 +v 1900.000000000 2700.000000000 646.097839355 +v 2000.000000000 2700.000000000 635.932434082 +v 2100.000000000 2700.000000000 625.793640137 +v 2200.000000000 2700.000000000 614.832031250 +v 2100.000000000 2600.000000000 611.726684570 +v 2100.000000000 2700.000000000 625.793640137 +v 2100.000000000 2600.000000000 611.726684570 +v 2300.000000000 2700.000000000 603.127258301 +v 1300.000000000 2710.531494141 700.000000000 +v 1400.000000000 2763.125488281 700.000000000 +v 1463.620361328 2800.000000000 700.000000000 +v 1500.000000000 2800.000000000 696.871582031 +v 1600.000000000 2800.000000000 688.272155762 +v 1700.000000000 2800.000000000 679.699279785 +v 1800.000000000 2800.000000000 670.303588867 +v 1900.000000000 2800.000000000 660.934448242 +v 2000.000000000 2800.000000000 650.769104004 +v 2100.000000000 2800.000000000 640.630310059 +v 2200.000000000 2800.000000000 629.695190430 +v 2100.000000000 2700.000000000 625.793640137 +v 2200.000000000 2800.000000000 629.695190430 +v 2300.000000000 2800.000000000 618.760131836 +v 2200.000000000 2800.000000000 629.695190430 +v 2400.000000000 2800.000000000 607.028869629 +v 1500.000000000 2821.085693359 700.000000000 +v 1600.000000000 2878.905517578 700.000000000 +v 1633.369995117 2900.000000000 700.000000000 +v 1700.000000000 2900.000000000 693.739685059 +v 1800.000000000 2900.000000000 684.370544434 +v 1900.000000000 2900.000000000 675.001403809 +v 2000.000000000 2900.000000000 665.632324219 +v 2100.000000000 2900.000000000 655.466918945 +v 2200.000000000 2900.000000000 644.531860352 +v 2300.000000000 2900.000000000 633.596801758 +v 2200.000000000 2800.000000000 629.695190430 +v 2200.000000000 2900.000000000 644.531860352 +v 2200.000000000 2800.000000000 629.695190430 +v 2400.000000000 2900.000000000 622.661743164 +v 2500.000000000 2900.000000000 610.160705566 +v 1700.000000000 2942.119628906 700.000000000 +v 1791.562255859 3000.000000000 700.000000000 +v 1800.000000000 3000.000000000 699.207214355 +v 1900.000000000 3000.000000000 689.838073730 +v 2000.000000000 3000.000000000 680.468933105 +v 2100.000000000 3000.000000000 670.303588867 +v 2200.000000000 3000.000000000 660.164794922 +v 2300.000000000 3000.000000000 649.229675293 +v 2200.000000000 2900.000000000 644.531860352 +v 2200.000000000 3000.000000000 660.164794922 +v 2200.000000000 2900.000000000 644.531860352 +v 2400.000000000 3000.000000000 638.268066406 +v 2500.000000000 3000.000000000 626.563354492 +v 2600.000000000 3000.000000000 613.292602539 +v 1800.000000000 3005.071289062 700.000000000 +v 1900.000000000 3065.003662109 700.000000000 +v 1958.393676758 3100.000000000 700.000000000 +v 2000.000000000 3100.000000000 696.101867676 +v 2100.000000000 3100.000000000 685.936462402 +v 2200.000000000 3100.000000000 676.567382812 +v 2300.000000000 3100.000000000 665.632324219 +v 2200.000000000 3000.000000000 660.164794922 +v 2300.000000000 3100.000000000 665.632324219 +v 2400.000000000 3100.000000000 654.697265625 +v 2300.000000000 3100.000000000 665.632324219 +v 2500.000000000 3100.000000000 642.196228027 +v 2600.000000000 3100.000000000 629.695190430 +v 2700.000000000 3100.000000000 615.628234863 +v 2800.000000000 3100.000000000 601.561340332 +v 2000.000000000 3126.273681641 700.000000000 +v 2100.000000000 3189.960937500 700.000000000 +v 2700.000000000 100.000000000 128.911682129 +v 2700.000000000 683.281433105 200.000000000 +v 2716.718505859 700.000000000 200.000000000 +v 2800.000000000 700.000000000 188.284835815 +v 2300.000000000 3100.000000000 665.632324219 +v 2300.000000000 3200.000000000 682.034912109 +v 2300.000000000 3100.000000000 665.632324219 +v 2900.000000000 700.000000000 174.987609863 +v 3000.000000000 700.000000000 162.513122559 +v 3100.000000000 700.000000000 150.781829834 +v 1890.002807617 100.000000000 200.000000000 +v 2800.000000000 778.960937500 200.000000000 +v 2822.190185547 800.000000000 200.000000000 +v 2900.000000000 800.000000000 189.054550171 +v 100.000000000 1500.000000000 703.135314941 +v 100.000000000 1484.578369141 700.000000000 +v 100.000000000 1500.000000000 703.135314941 +v 3000.000000000 800.000000000 174.987609863 +v 100.000000000 1600.000000000 724.209228516 +v 0.000000000 1500.000000000 722.643249512 +v 0.000000000 1500.000000000 722.643249512 +v 100.000000000 1500.000000000 703.135314941 +v 200.000000000 1600.000000000 705.470947266 +v 100.000000000 1500.000000000 703.135314941 +v 100.000000000 1500.000000000 703.135314941 +v 100.000000000 1500.000000000 703.135314941 +v 3100.000000000 800.000000000 161.716873169 +v 100.000000000 1700.000000000 744.539916992 +v 200.000000000 1700.000000000 725.005432129 +v 300.000000000 1700.000000000 706.240661621 +v 2800.000000000 100.000000000 121.081962585 +v 100.000000000 1800.000000000 765.613830566 +v 200.000000000 1800.000000000 743.743713379 +v 300.000000000 1800.000000000 723.439514160 +v 400.000000000 1800.000000000 703.905029297 +v 40.026458740 1900.000000000 800.000000000 +v 100.000000000 1900.000000000 785.944580078 +v 2900.000000000 877.809692383 200.000000000 +v 200.000000000 1900.000000000 762.508483887 +v 300.000000000 1900.000000000 741.408081055 +v 400.000000000 1900.000000000 721.103881836 +v 500.000000000 1900.000000000 701.569396973 +v 100.000000000 1969.224121094 800.000000000 +v 125.815200806 2000.000000000 800.000000000 +v 200.000000000 2000.000000000 782.042968750 +v 300.000000000 2000.000000000 759.376586914 +v 400.000000000 2000.000000000 736.710205078 +v 500.000000000 2000.000000000 717.175720215 +v 200.000000000 2092.049804688 800.000000000 +v 206.209701538 2100.000000000 800.000000000 +v 300.000000000 2100.000000000 776.575439453 +v 400.000000000 2100.000000000 753.112854004 +v 500.000000000 2100.000000000 730.473022461 +v 600.000000000 2100.000000000 709.372558594 +v 279.443450928 2200.000000000 800.000000000 +v 300.000000000 2200.000000000 794.544006348 +v 400.000000000 2200.000000000 768.745727539 +v 500.000000000 2200.000000000 745.309631348 +v 600.000000000 2200.000000000 722.643249512 +v 700.000000000 2200.000000000 701.569396973 +v 300.000000000 2230.364257812 800.000000000 +v 347.096313477 2300.000000000 800.000000000 +v 400.000000000 2300.000000000 785.944580078 +v 500.000000000 2300.000000000 760.146301270 +v 600.000000000 2300.000000000 736.710205078 +v 700.000000000 2300.000000000 714.070373535 +v 400.000000000 2381.849365234 800.000000000 +v 411.401428223 2400.000000000 800.000000000 +v 500.000000000 2400.000000000 775.779174805 +v 600.000000000 2400.000000000 750.777160645 +v 700.000000000 2400.000000000 726.571411133 +v 800.000000000 2400.000000000 704.674743652 +v 472.210845947 2500.000000000 800.000000000 +v 500.000000000 2500.000000000 792.181823730 +v 600.000000000 2500.000000000 764.844116211 +v 700.000000000 2500.000000000 739.072387695 +v 800.000000000 2500.000000000 716.406066895 +v 900.000000000 2500.000000000 701.569396973 +v 500.000000000 2547.664306641 800.000000000 +v 529.700134277 2600.000000000 800.000000000 +v 600.000000000 2600.000000000 779.680786133 +v 700.000000000 2600.000000000 753.112854004 +v 800.000000000 2600.000000000 732.038940430 +v 900.000000000 2600.000000000 716.406066895 +v 1000.000000000 2600.000000000 706.240661621 +v 586.812622070 2700.000000000 800.000000000 +v 600.000000000 2700.000000000 796.083374023 +v 700.000000000 2700.000000000 769.541992188 +v 800.000000000 2700.000000000 749.211242676 +v 900.000000000 2700.000000000 732.038940430 +v 1000.000000000 2700.000000000 721.103881836 +v 1100.000000000 2700.000000000 712.504455566 +v 1200.000000000 2700.000000000 706.240661621 +v 600.000000000 2722.772705078 800.000000000 +v 649.993469238 2800.000000000 800.000000000 +v 700.000000000 2800.000000000 786.714294434 +v 800.000000000 2800.000000000 766.410095215 +v 900.000000000 2800.000000000 749.211242676 +v 1000.000000000 2800.000000000 736.710205078 +v 1100.000000000 2800.000000000 728.137329102 +v 1200.000000000 2800.000000000 721.103881836 +v 1300.000000000 2800.000000000 713.274169922 +v 1400.000000000 2800.000000000 705.470947266 +v 700.000000000 2868.011474609 800.000000000 +v 730.775756836 2900.000000000 800.000000000 +v 800.000000000 2900.000000000 785.944580078 +v 900.000000000 2900.000000000 767.179809570 +v 1000.000000000 2900.000000000 752.343139648 +v 1100.000000000 2900.000000000 743.743713379 +v 1200.000000000 2900.000000000 735.940551758 +v 1300.000000000 2900.000000000 728.137329102 +v 1400.000000000 2900.000000000 720.307617188 +v 1500.000000000 2900.000000000 711.708190918 +v 1600.000000000 2900.000000000 703.135314941 +v 800.000000000 2975.009277344 800.000000000 +v 824.990661621 3000.000000000 800.000000000 +v 900.000000000 3000.000000000 785.944580078 +v 1000.000000000 3000.000000000 770.311645508 +v 1100.000000000 3000.000000000 759.376586914 +v 1200.000000000 3000.000000000 751.573425293 +v 1300.000000000 3000.000000000 742.973999023 +v 1400.000000000 3000.000000000 734.374572754 +v 1500.000000000 3000.000000000 726.571411133 +v 1600.000000000 3000.000000000 717.971984863 +v 1700.000000000 3000.000000000 708.602844238 +v 900.000000000 3078.222412109 800.000000000 +v 925.031066895 3100.000000000 800.000000000 +v 1000.000000000 3100.000000000 788.280212402 +v 1100.000000000 3100.000000000 775.779174805 +v 1200.000000000 3100.000000000 767.179809570 +v 1300.000000000 3100.000000000 758.606872559 +v 1400.000000000 3100.000000000 750.007507324 +v 1500.000000000 3100.000000000 741.408081055 +v 1600.000000000 3100.000000000 732.038940430 +v 1700.000000000 3100.000000000 723.439514160 +v 1800.000000000 3100.000000000 714.840087891 +v 1900.000000000 3100.000000000 705.470947266 +v 1000.000000000 3165.223876953 800.000000000 +v 2921.039062500 900.000000000 200.000000000 +v 3000.000000000 900.000000000 188.284835815 +v 3100.000000000 900.000000000 174.987609863 +v 2200.000000000 100.000000000 172.651947021 +v 3000.000000000 978.960998535 200.000000000 +v 3021.039062500 1000.000000000 200.000000000 +v 3100.000000000 1000.000000000 188.284835815 +v 2900.000000000 100.000000000 113.278785706 +v 3100.000000000 1078.960937500 200.000000000 +v 3119.030273438 1100.000000000 200.000000000 +v 1900.000000000 100.000000000 199.219924927 +v 3000.000000000 100.000000000 107.041549683 +v 2300.000000000 100.000000000 164.052520752 +v 3100.000000000 100.000000000 103.113410950 +v 100.000000000 2000.000000000 806.248779297 +v 500.000000000 20.833856583 300.000000000 +v 100.000000000 2100.000000000 828.118896484 +v 200.000000000 2100.000000000 801.550842285 +v 1700.000000000 14.302844048 200.000000000 +v 100.000000000 2200.000000000 849.219299316 +v 200.000000000 2200.000000000 821.085327148 +v 2.590477467 2300.000000000 900.000000000 +v 100.000000000 2300.000000000 870.319763184 +v 600.000000000 95.769119263 300.000000000 +v 200.000000000 2300.000000000 841.416137695 +v 300.000000000 2300.000000000 812.512512207 +v 75.620391846 2400.000000000 900.000000000 +v 100.000000000 2400.000000000 892.189880371 +v 200.000000000 2400.000000000 861.720397949 +v 300.000000000 2400.000000000 831.250732422 +v 400.000000000 2400.000000000 803.116882324 +v 100.000000000 2435.711181641 900.000000000 +v 143.888854980 2500.000000000 900.000000000 +v 200.000000000 2500.000000000 882.024597168 +v 300.000000000 2500.000000000 850.785278320 +v 400.000000000 2500.000000000 820.315734863 +v 200.000000000 2585.190185547 900.000000000 +v 209.300018311 2600.000000000 900.000000000 +v 300.000000000 2600.000000000 869.523498535 +v 400.000000000 2600.000000000 838.284179688 +v 500.000000000 2600.000000000 808.584411621 +v 272.721038818 2700.000000000 900.000000000 +v 300.000000000 2700.000000000 890.623840332 +v 400.000000000 2700.000000000 857.022460938 +v 500.000000000 2700.000000000 825.783264160 +v 300.000000000 2746.177978516 900.000000000 +v 331.794403076 2800.000000000 900.000000000 +v 400.000000000 2800.000000000 876.556945801 +v 500.000000000 2800.000000000 843.751831055 +v 600.000000000 2800.000000000 813.282226562 +v 391.143341064 2900.000000000 900.000000000 +v 400.000000000 2900.000000000 896.887695312 +v 500.000000000 2900.000000000 863.286193848 +v 600.000000000 2900.000000000 832.816711426 +v 700.000000000 2900.000000000 806.248779297 +v 400.000000000 2914.768554688 900.000000000 +v 452.257812500 3000.000000000 900.000000000 +v 500.000000000 3000.000000000 883.590393066 +v 600.000000000 3000.000000000 853.120910645 +v 700.000000000 3000.000000000 826.552978516 +v 800.000000000 3000.000000000 804.682800293 +v 500.000000000 3077.768798828 900.000000000 +v 515.395202637 3100.000000000 900.000000000 +v 600.000000000 3100.000000000 874.221313477 +v 700.000000000 3100.000000000 847.653381348 +v 800.000000000 3100.000000000 824.217346191 +v 900.000000000 3100.000000000 803.913085938 +v 606.767517090 100.000000000 300.000000000 +v 700.000000000 100.000000000 289.062622070 +v 2400.000000000 100.000000000 154.683395386 +v 800.000000000 100.000000000 278.897247314 +v 2000.000000000 100.000000000 190.620483398 +v 900.000000000 100.000000000 271.094085693 +v 1900.000000000 104.755889893 200.000000000 +v 1000.000000000 100.000000000 264.060607910 +v 2000.000000000 157.183105469 200.000000000 +v 100.000000000 2500.000000000 914.059997559 +v 1100.000000000 100.000000000 256.257415771 +v 100.000000000 2600.000000000 936.726379395 +v 200.000000000 2600.000000000 903.124877930 +v 2074.959960938 200.000000000 200.000000000 +v 100.000000000 2700.000000000 959.366210938 +v 200.000000000 2700.000000000 924.995056152 +v 52.144981384 2800.000000000 1000.000000000 +v 100.000000000 2800.000000000 982.802307129 +v 1200.000000000 100.000000000 249.223953247 +v 200.000000000 2800.000000000 946.865173340 +v 300.000000000 2800.000000000 910.928039551 +v 100.000000000 2875.873291016 1000.000000000 +v 114.581993103 2900.000000000 1000.000000000 +v 200.000000000 2900.000000000 967.965576172 +v 300.000000000 2900.000000000 932.028564453 +v 177.374542236 3000.000000000 1000.000000000 +v 200.000000000 3000.000000000 990.632080078 +v 300.000000000 3000.000000000 953.129028320 +v 400.000000000 3000.000000000 917.961608887 +v 200.000000000 3037.468994141 1000.000000000 +v 240.016510010 3100.000000000 1000.000000000 +v 300.000000000 3100.000000000 976.565063477 +v 400.000000000 3100.000000000 939.062011719 +v 500.000000000 3100.000000000 904.690856934 +v 300.000000000 3196.815429688 1000.000000000 +v 2100.000000000 200.000000000 197.653961182 +v 1300.000000000 100.000000000 242.960174561 +v 2200.000000000 200.000000000 188.284835815 +v 1400.000000000 100.000000000 235.926696777 +v 2300.000000000 200.000000000 178.119476318 +v 100.000000000 2900.000000000 1005.468627930 +v 1500.000000000 100.000000000 228.893234253 +v 100.000000000 3000.000000000 1032.036621094 +v 2400.000000000 200.000000000 167.980651855 +v 100.000000000 3100.000000000 1057.808349609 +v 200.000000000 3100.000000000 1015.634033203 +v 1600.000000000 100.000000000 221.886276245 +v 2500.000000000 200.000000000 157.815292358 +v 1700.000000000 100.000000000 214.056564331 +v 1800.000000000 100.000000000 207.023101807 +v 700.000000000 158.369262695 300.000000000 +v 771.338012695 200.000000000 300.000000000 +f 2 1 1594 +f 1 3 1594 +f 1594 3 549 +f 1586 1448 549 +f 3 1586 549 +f 4 1586 3 +f 1586 4 1647 +f 1647 4 5 +f 1647 5 1180 +f 1180 5 6 +f 1180 6 1579 +f 1579 6 7 +f 1579 7 1588 +f 1588 7 8 +f 1588 8 1645 +f 1645 8 9 +f 1645 9 301 +f 301 9 10 +f 301 10 829 +f 829 10 11 +f 829 11 1438 +f 1438 11 12 +f 1438 12 1468 +f 1468 12 13 +f 1468 13 1583 +f 1583 13 14 +f 1583 14 1587 +f 1587 14 15 +f 1587 15 1589 +f 1589 15 16 +f 1589 16 17 +f 17 16 18 +f 1448 1586 1649 +f 1586 1647 1649 +f 1649 1647 1651 +f 1678 1656 1651 +f 1647 1678 1651 +f 1180 1678 1647 +f 1678 1180 1680 +f 1680 1180 1579 +f 1680 1579 1682 +f 1682 1579 1588 +f 1682 1588 1686 +f 1686 1588 1645 +f 1686 1645 1690 +f 1690 1645 301 +f 1690 301 272 +f 272 301 829 +f 272 829 280 +f 280 829 1438 +f 280 1438 286 +f 286 1438 1468 +f 286 1468 291 +f 291 1468 1583 +f 291 1583 295 +f 295 1583 1587 +f 295 1587 298 +f 298 1587 1589 +f 298 1589 19 +f 19 1589 17 +f 1656 1678 302 +f 1678 1680 302 +f 302 1680 305 +f 307 306 305 +f 1680 307 305 +f 1682 307 1680 +f 307 1682 309 +f 309 1682 1686 +f 309 1686 311 +f 311 1686 1690 +f 311 1690 313 +f 313 1690 272 +f 313 272 530 +f 530 272 280 +f 530 280 536 +f 536 280 286 +f 536 286 541 +f 541 286 291 +f 541 291 545 +f 545 291 295 +f 545 295 548 +f 548 295 298 +f 548 298 20 +f 20 298 19 +f 306 307 550 +f 553 551 550 +f 307 553 550 +f 309 553 307 +f 553 309 556 +f 556 309 311 +f 556 311 563 +f 563 311 313 +f 563 313 806 +f 806 313 530 +f 806 530 816 +f 816 530 536 +f 816 536 821 +f 821 536 541 +f 821 541 825 +f 825 541 545 +f 825 545 828 +f 828 545 548 +f 828 548 21 +f 21 548 20 +f 551 553 830 +f 837 831 830 +f 553 837 830 +f 556 837 553 +f 837 556 843 +f 843 556 563 +f 843 563 853 +f 853 563 806 +f 853 806 1159 +f 1159 806 816 +f 1159 816 1168 +f 1168 816 821 +f 1168 821 1177 +f 1177 821 825 +f 1177 825 1179 +f 1179 825 828 +f 1179 828 22 +f 22 828 21 +f 831 837 1181 +f 837 843 1181 +f 1181 843 1182 +f 1184 1183 1182 +f 843 1184 1182 +f 853 1184 843 +f 1184 853 1186 +f 1186 853 1159 +f 1186 1159 1189 +f 1189 1159 1168 +f 1189 1168 1193 +f 1193 1168 1177 +f 1193 1177 1201 +f 1201 1177 1179 +f 1201 1179 23 +f 23 1179 22 +f 1183 1184 1439 +f 1441 1440 1439 +f 1184 1441 1439 +f 1186 1441 1184 +f 1441 1186 1445 +f 1445 1186 1189 +f 1445 1189 1446 +f 1446 1189 1193 +f 1446 1193 1447 +f 1447 1193 1201 +f 1447 1201 24 +f 24 1201 23 +f 1440 1441 1449 +f 1451 1450 1449 +f 1441 1451 1449 +f 1445 1451 1441 +f 1451 1445 1455 +f 1455 1445 1446 +f 1455 1446 1464 +f 1464 1446 1447 +f 1464 1447 25 +f 25 1447 24 +f 1450 1451 1475 +f 1577 1576 1475 +f 1451 1577 1475 +f 1455 1577 1451 +f 1577 1455 1578 +f 1578 1455 1464 +f 1578 1464 26 +f 26 1464 25 +f 1576 1577 1580 +f 1582 1581 1580 +f 1577 1582 1580 +f 1578 1582 1577 +f 1582 1578 27 +f 27 1578 26 +f 1581 1582 1584 +f 28 1585 1584 +f 1582 28 1584 +f 27 28 1582 +f 1585 28 29 +f 31 30 1591 +f 30 32 1591 +f 1591 32 1599 +f 1644 1643 1599 +f 32 1644 1599 +f 33 1644 32 +f 1644 33 1646 +f 1646 33 34 +f 1646 34 1648 +f 1648 34 35 +f 1648 35 1650 +f 1650 35 36 +f 1650 36 1653 +f 1653 36 37 +f 1653 37 1661 +f 1661 37 38 +f 1661 38 1679 +f 1679 38 39 +f 1679 39 1681 +f 1681 39 40 +f 1681 40 1684 +f 1684 40 41 +f 1684 41 1689 +f 1689 41 42 +f 42 2 1594 +f 1691 42 1594 +f 1689 42 1691 +f 1691 1594 1692 +f 1692 1594 549 +f 1692 549 1448 +f 1643 1644 1693 +f 149 1694 1693 +f 1644 149 1693 +f 1646 149 1644 +f 149 1646 150 +f 150 1646 1648 +f 150 1648 151 +f 151 1648 1650 +f 151 1650 152 +f 152 1650 1653 +f 152 1653 153 +f 153 1653 1661 +f 153 1661 154 +f 154 1661 1679 +f 154 1679 155 +f 155 1679 1681 +f 155 1681 156 +f 156 1681 1684 +f 156 1684 157 +f 157 1684 1689 +f 157 1689 158 +f 158 1689 1691 +f 158 1691 159 +f 159 1691 1692 +f 1692 1448 1649 +f 160 1692 1649 +f 159 1692 160 +f 160 1649 161 +f 161 1649 1651 +f 161 1651 1656 +f 1694 149 162 +f 149 150 162 +f 162 150 163 +f 150 151 163 +f 163 151 164 +f 166 165 164 +f 151 166 164 +f 152 166 151 +f 166 152 167 +f 167 152 153 +f 167 153 168 +f 168 153 154 +f 168 154 169 +f 169 154 155 +f 169 155 170 +f 170 155 156 +f 170 156 171 +f 171 156 157 +f 171 157 172 +f 172 157 158 +f 172 158 173 +f 173 158 159 +f 173 159 174 +f 174 159 160 +f 174 160 175 +f 175 160 161 +f 161 1656 302 +f 176 161 302 +f 175 161 176 +f 176 302 177 +f 177 302 305 +f 177 305 306 +f 165 166 178 +f 166 167 178 +f 178 167 179 +f 167 168 179 +f 179 168 180 +f 182 181 180 +f 168 182 180 +f 169 182 168 +f 182 169 183 +f 183 169 170 +f 183 170 184 +f 184 170 171 +f 184 171 185 +f 185 171 172 +f 185 172 186 +f 186 172 173 +f 186 173 187 +f 187 173 174 +f 187 174 188 +f 188 174 175 +f 188 175 189 +f 189 175 176 +f 189 176 190 +f 190 176 177 +f 177 306 550 +f 191 177 550 +f 190 177 191 +f 191 550 551 +f 181 182 192 +f 182 183 192 +f 192 183 193 +f 195 194 193 +f 183 195 193 +f 184 195 183 +f 195 184 196 +f 196 184 185 +f 196 185 197 +f 197 185 186 +f 197 186 198 +f 198 186 187 +f 198 187 199 +f 199 187 188 +f 199 188 200 +f 200 188 189 +f 200 189 201 +f 201 189 190 +f 201 190 202 +f 202 190 191 +f 191 551 830 +f 203 191 830 +f 202 191 203 +f 203 830 831 +f 194 195 204 +f 195 196 204 +f 204 196 205 +f 196 207 205 +f 197 207 196 +f 207 197 208 +f 208 197 198 +f 208 198 209 +f 209 198 199 +f 209 199 210 +f 210 199 200 +f 210 200 211 +f 211 200 201 +f 211 201 212 +f 212 201 202 +f 212 202 213 +f 213 202 203 +f 203 831 1181 +f 214 203 1181 +f 213 203 214 +f 214 1181 215 +f 215 1181 1182 +f 215 1182 1183 +f 216 208 217 +f 219 218 217 +f 208 219 217 +f 209 219 208 +f 219 209 220 +f 220 209 210 +f 220 210 221 +f 221 210 211 +f 221 211 222 +f 222 211 212 +f 222 212 223 +f 223 212 213 +f 223 213 224 +f 224 213 214 +f 224 214 225 +f 225 214 215 +f 215 1183 1439 +f 226 215 1439 +f 225 215 226 +f 226 1439 1440 +f 218 219 227 +f 219 220 227 +f 227 220 228 +f 230 229 228 +f 220 230 228 +f 221 230 220 +f 230 221 231 +f 231 221 222 +f 231 222 232 +f 232 222 223 +f 232 223 233 +f 233 223 224 +f 233 224 234 +f 234 224 225 +f 234 225 235 +f 235 225 226 +f 226 1440 1449 +f 236 226 1449 +f 235 226 236 +f 236 1449 1450 +f 229 230 237 +f 239 238 237 +f 230 239 237 +f 231 239 230 +f 239 231 240 +f 240 231 232 +f 240 232 241 +f 241 232 233 +f 241 233 242 +f 242 233 234 +f 242 234 243 +f 243 234 235 +f 243 235 244 +f 244 235 236 +f 236 1450 1475 +f 245 236 1475 +f 244 236 245 +f 245 1475 1576 +f 238 239 246 +f 248 247 246 +f 239 248 246 +f 240 248 239 +f 248 240 249 +f 249 240 241 +f 249 241 250 +f 250 241 242 +f 250 242 251 +f 251 242 243 +f 251 243 252 +f 252 243 244 +f 252 244 253 +f 253 244 245 +f 245 1576 1580 +f 254 245 1580 +f 253 245 254 +f 254 1580 1581 +f 247 248 255 +f 257 256 255 +f 248 257 255 +f 249 257 248 +f 257 249 258 +f 258 249 250 +f 258 250 259 +f 259 250 251 +f 259 251 260 +f 260 251 252 +f 260 252 261 +f 261 252 253 +f 261 253 262 +f 262 253 254 +f 254 1581 1584 +f 263 254 1584 +f 262 254 263 +f 263 1584 1585 +f 256 257 264 +f 257 266 264 +f 258 266 257 +f 266 258 267 +f 267 258 259 +f 267 259 268 +f 268 259 260 +f 268 260 269 +f 269 260 261 +f 269 261 270 +f 270 261 262 +f 270 262 271 +f 271 262 263 +f 263 1585 29 +f 43 263 29 +f 271 263 43 +f 273 267 274 +f 276 275 274 +f 267 276 274 +f 268 276 267 +f 276 268 277 +f 277 268 269 +f 277 269 278 +f 278 269 270 +f 278 270 279 +f 279 270 271 +f 279 271 44 +f 44 271 43 +f 275 276 281 +f 283 282 281 +f 276 283 281 +f 277 283 276 +f 283 277 284 +f 284 277 278 +f 284 278 285 +f 285 278 279 +f 285 279 45 +f 45 279 44 +f 282 283 287 +f 289 288 287 +f 283 289 287 +f 284 289 283 +f 289 284 290 +f 290 284 285 +f 290 285 46 +f 46 285 45 +f 288 289 292 +f 294 293 292 +f 289 294 292 +f 290 294 289 +f 294 290 47 +f 47 290 46 +f 293 294 296 +f 297 294 48 +f 48 294 47 +f 49 300 299 +f 48 49 297 +f 300 49 50 +f 304 303 53 +f 52 304 53 +f 51 304 52 +f 304 51 308 +f 308 51 54 +f 308 54 310 +f 310 54 55 +f 310 55 312 +f 312 55 56 +f 56 31 1591 +f 314 56 1591 +f 312 56 314 +f 314 1591 315 +f 315 1591 1599 +f 315 1599 1643 +f 303 304 316 +f 318 317 316 +f 304 318 316 +f 308 318 304 +f 318 308 319 +f 319 308 310 +f 319 310 320 +f 320 310 312 +f 320 312 321 +f 321 312 314 +f 321 314 322 +f 322 314 315 +f 315 1643 1693 +f 323 315 1693 +f 322 315 323 +f 323 1693 1694 +f 317 318 324 +f 326 325 324 +f 318 326 324 +f 319 326 318 +f 326 319 327 +f 327 319 320 +f 327 320 328 +f 328 320 321 +f 328 321 329 +f 329 321 322 +f 329 322 330 +f 330 322 323 +f 323 1694 162 +f 331 323 162 +f 330 323 331 +f 331 162 332 +f 332 162 163 +f 332 163 333 +f 333 163 164 +f 333 164 165 +f 325 326 334 +f 326 327 334 +f 334 327 335 +f 337 336 335 +f 327 337 335 +f 328 337 327 +f 337 328 338 +f 338 328 329 +f 338 329 339 +f 339 329 330 +f 339 330 340 +f 340 330 331 +f 340 331 341 +f 341 331 332 +f 341 332 342 +f 342 332 333 +f 333 165 178 +f 343 333 178 +f 342 333 343 +f 343 178 344 +f 344 178 179 +f 344 179 345 +f 345 179 180 +f 345 180 181 +f 336 337 346 +f 348 347 346 +f 337 348 346 +f 338 348 337 +f 348 338 349 +f 349 338 339 +f 349 339 350 +f 350 339 340 +f 350 340 351 +f 351 340 341 +f 351 341 352 +f 352 341 342 +f 352 342 353 +f 353 342 343 +f 353 343 354 +f 354 343 344 +f 354 344 355 +f 355 344 345 +f 345 181 192 +f 356 345 192 +f 355 345 356 +f 356 192 357 +f 357 192 193 +f 357 193 194 +f 347 348 358 +f 348 349 358 +f 358 349 359 +f 361 360 359 +f 349 361 359 +f 350 361 349 +f 361 350 362 +f 362 350 351 +f 362 351 363 +f 363 351 352 +f 363 352 364 +f 364 352 353 +f 364 353 365 +f 365 353 354 +f 365 354 366 +f 366 354 355 +f 366 355 367 +f 367 355 356 +f 367 356 368 +f 368 356 357 +f 357 194 204 +f 369 357 204 +f 368 357 369 +f 369 204 370 +f 370 204 205 +f 370 205 206 +f 360 361 371 +f 361 362 371 +f 371 362 372 +f 362 363 372 +f 372 363 373 +f 375 374 373 +f 363 375 373 +f 364 375 363 +f 375 364 376 +f 376 364 365 +f 376 365 377 +f 377 365 366 +f 377 366 378 +f 378 366 367 +f 378 367 379 +f 379 367 368 +f 379 368 380 +f 380 368 369 +f 380 369 381 +f 381 369 370 +f 382 370 216 +f 381 370 382 +f 382 216 383 +f 383 216 217 +f 383 217 218 +f 374 375 384 +f 375 376 384 +f 384 376 385 +f 387 386 385 +f 376 387 385 +f 377 387 376 +f 387 377 388 +f 388 377 378 +f 388 378 389 +f 389 378 379 +f 389 379 390 +f 390 379 380 +f 390 380 391 +f 391 380 381 +f 391 381 392 +f 392 381 382 +f 392 382 393 +f 393 382 383 +f 383 218 227 +f 394 383 227 +f 393 383 394 +f 394 227 395 +f 395 227 228 +f 395 228 229 +f 398 397 396 +f 401 400 396 +f 396 402 399 +f 404 403 399 +f 405 404 399 +f 389 406 388 +f 408 389 407 +f 407 389 390 +f 407 390 409 +f 409 390 391 +f 409 391 410 +f 410 391 392 +f 410 392 411 +f 411 392 393 +f 411 393 412 +f 412 393 394 +f 412 394 413 +f 413 394 395 +f 395 229 237 +f 414 395 237 +f 413 395 414 +f 414 237 238 +f 417 416 415 +f 419 407 415 +f 421 420 418 +f 423 422 418 +f 424 423 418 +f 425 423 426 +f 423 428 427 +f 429 409 410 +f 431 410 430 +f 430 410 411 +f 430 411 432 +f 432 411 412 +f 432 412 433 +f 433 412 413 +f 433 413 434 +f 434 413 414 +f 414 238 246 +f 435 414 246 +f 434 414 435 +f 435 246 247 +f 422 423 436 +f 423 427 436 +f 436 427 437 +f 439 438 437 +f 427 439 437 +f 430 440 441 +f 443 430 442 +f 442 430 432 +f 442 432 444 +f 444 432 433 +f 444 433 445 +f 445 433 434 +f 445 434 446 +f 446 434 435 +f 435 247 255 +f 447 435 255 +f 446 435 447 +f 447 255 256 +f 438 439 448 +f 450 449 448 +f 439 450 448 +f 451 450 439 +f 450 453 452 +f 454 442 444 +f 456 444 455 +f 455 444 445 +f 455 445 457 +f 457 445 446 +f 457 446 458 +f 458 446 447 +f 447 256 264 +f 459 447 264 +f 458 447 459 +f 459 264 265 +f 449 450 460 +f 462 461 460 +f 450 462 460 +f 452 462 450 +f 462 452 463 +f 465 464 455 +f 467 455 466 +f 466 455 457 +f 466 457 468 +f 468 457 458 +f 468 458 469 +f 469 458 459 +f 470 459 273 +f 469 459 470 +f 470 273 471 +f 471 273 274 +f 471 274 275 +f 461 462 472 +f 462 463 472 +f 472 463 473 +f 475 474 473 +f 463 475 473 +f 466 476 477 +f 479 466 478 +f 478 466 468 +f 478 468 480 +f 480 468 469 +f 480 469 481 +f 481 469 470 +f 481 470 482 +f 482 470 471 +f 471 275 281 +f 483 471 281 +f 482 471 483 +f 483 281 282 +f 474 475 484 +f 486 485 484 +f 475 486 484 +f 478 487 488 +f 490 478 489 +f 489 478 480 +f 489 480 491 +f 491 480 481 +f 491 481 492 +f 492 481 482 +f 492 482 493 +f 493 482 483 +f 483 282 287 +f 494 483 287 +f 493 483 494 +f 494 287 288 +f 485 486 495 +f 497 496 495 +f 486 497 495 +f 489 498 499 +f 501 489 500 +f 500 489 491 +f 500 491 502 +f 502 491 492 +f 502 492 503 +f 503 492 493 +f 503 493 504 +f 504 493 494 +f 494 288 292 +f 505 494 292 +f 504 494 505 +f 505 292 293 +f 496 497 506 +f 508 507 509 +f 510 508 511 +f 500 508 512 +f 508 500 513 +f 513 500 502 +f 513 502 514 +f 514 502 503 +f 514 503 515 +f 515 503 504 +f 515 504 516 +f 516 504 505 +f 516 505 296 +f 296 505 293 +f 507 508 517 +f 519 518 517 +f 508 519 517 +f 513 519 508 +f 519 513 520 +f 520 513 514 +f 520 514 521 +f 521 514 515 +f 521 515 522 +f 522 515 516 +f 523 516 299 +f 522 516 523 +f 523 299 300 +f 518 519 524 +f 526 525 524 +f 519 526 524 +f 520 526 519 +f 526 520 527 +f 527 520 521 +f 527 521 528 +f 528 521 522 +f 528 522 529 +f 529 522 523 +f 523 300 50 +f 57 523 50 +f 529 523 57 +f 525 526 531 +f 533 532 531 +f 526 533 531 +f 527 533 526 +f 533 527 534 +f 534 527 528 +f 534 528 535 +f 535 528 529 +f 535 529 58 +f 58 529 57 +f 532 533 537 +f 539 538 537 +f 533 539 537 +f 534 539 533 +f 539 534 540 +f 540 534 535 +f 540 535 59 +f 59 535 58 +f 538 539 542 +f 544 543 542 +f 539 544 542 +f 540 544 539 +f 544 540 60 +f 60 540 59 +f 543 544 546 +f 61 547 546 +f 544 61 546 +f 60 61 544 +f 547 61 62 +f 63 53 303 +f 63 303 316 +f 552 63 316 +f 64 63 552 +f 552 316 317 +f 65 64 554 +f 554 64 552 +f 552 317 324 +f 555 552 324 +f 554 552 555 +f 555 324 325 +f 66 65 557 +f 557 65 554 +f 557 554 558 +f 558 554 555 +f 555 325 334 +f 559 555 334 +f 558 555 559 +f 559 334 560 +f 560 334 335 +f 562 561 67 +f 66 562 67 +f 557 562 66 +f 562 557 564 +f 564 557 558 +f 564 558 565 +f 565 558 559 +f 565 559 566 +f 566 559 560 +f 560 336 346 +f 567 560 346 +f 566 560 567 +f 567 346 347 +f 570 569 568 +f 572 571 568 +f 573 572 568 +f 574 572 575 +f 572 577 576 +f 576 578 579 +f 576 581 580 +f 582 565 566 +f 584 566 583 +f 583 566 567 +f 567 347 358 +f 585 567 358 +f 583 567 585 +f 585 358 586 +f 586 358 359 +f 586 359 360 +f 571 572 587 +f 589 588 587 +f 572 589 587 +f 576 589 572 +f 589 576 590 +f 590 576 580 +f 590 580 591 +f 591 580 592 +f 591 594 593 +f 593 595 596 +f 593 598 597 +f 597 599 600 +f 586 360 371 +f 601 586 371 +f 597 602 603 +f 601 371 604 +f 604 371 372 +f 604 372 605 +f 605 372 373 +f 588 589 606 +f 589 590 606 +f 606 590 607 +f 609 608 607 +f 590 609 607 +f 591 609 590 +f 609 591 610 +f 610 591 593 +f 610 593 611 +f 611 593 597 +f 611 597 612 +f 612 597 613 +f 612 615 614 +f 614 616 617 +f 614 619 618 +f 618 620 621 +f 605 374 384 +f 622 623 624 +f 618 625 622 +f 622 627 626 +f 628 384 385 +f 629 385 386 +f 608 609 630 +f 609 610 630 +f 630 610 631 +f 633 632 631 +f 610 633 631 +f 611 633 610 +f 633 611 634 +f 634 611 612 +f 634 612 635 +f 635 612 614 +f 635 614 636 +f 636 614 618 +f 636 618 637 +f 637 618 622 +f 637 622 638 +f 638 622 626 +f 626 640 396 +f 639 626 396 +f 638 626 639 +f 639 396 641 +f 641 396 399 +f 641 399 403 +f 644 643 642 +f 647 646 642 +f 642 648 645 +f 650 649 651 +f 634 650 652 +f 635 650 634 +f 650 635 653 +f 653 635 636 +f 653 636 654 +f 654 636 637 +f 654 637 655 +f 655 637 638 +f 655 638 656 +f 656 638 639 +f 656 639 657 +f 657 639 641 +f 641 403 659 +f 658 641 660 +f 657 641 658 +f 658 662 661 +f 661 663 418 +f 661 418 422 +f 649 650 664 +f 650 653 664 +f 664 653 665 +f 667 666 665 +f 653 667 665 +f 654 667 653 +f 667 654 668 +f 668 654 655 +f 668 655 669 +f 669 655 656 +f 669 656 670 +f 670 656 657 +f 670 657 671 +f 671 657 658 +f 671 658 672 +f 672 658 661 +f 661 422 436 +f 673 661 436 +f 672 661 673 +f 673 436 674 +f 674 436 437 +f 674 437 438 +f 666 667 675 +f 667 668 675 +f 675 668 676 +f 678 677 676 +f 668 678 676 +f 669 678 668 +f 678 669 679 +f 679 669 670 +f 679 670 680 +f 680 670 671 +f 680 671 681 +f 681 671 672 +f 681 672 682 +f 682 672 673 +f 682 673 683 +f 683 673 674 +f 674 438 448 +f 684 674 448 +f 683 674 684 +f 684 448 449 +f 677 678 685 +f 687 686 685 +f 678 687 685 +f 679 687 678 +f 687 679 688 +f 688 679 680 +f 688 680 689 +f 689 680 681 +f 689 681 690 +f 690 681 682 +f 690 682 691 +f 691 682 683 +f 691 683 692 +f 692 683 684 +f 684 449 460 +f 693 684 460 +f 692 684 693 +f 693 460 461 +f 687 688 694 +f 694 688 695 +f 697 696 695 +f 688 697 695 +f 689 697 688 +f 697 689 698 +f 698 689 690 +f 698 690 699 +f 699 690 691 +f 699 691 700 +f 700 691 692 +f 700 692 701 +f 701 692 693 +f 693 461 472 +f 702 693 472 +f 701 693 702 +f 702 472 703 +f 703 472 473 +f 703 473 474 +f 696 697 704 +f 706 705 704 +f 697 706 704 +f 698 706 697 +f 706 698 707 +f 707 698 699 +f 707 699 708 +f 708 699 700 +f 708 700 709 +f 709 700 701 +f 709 701 710 +f 710 701 702 +f 710 702 711 +f 711 702 703 +f 703 474 484 +f 712 703 484 +f 711 703 712 +f 712 484 485 +f 705 706 713 +f 715 714 713 +f 706 715 713 +f 707 715 706 +f 715 707 716 +f 716 707 708 +f 716 708 717 +f 717 708 709 +f 717 709 718 +f 718 709 710 +f 718 710 719 +f 719 710 711 +f 719 711 720 +f 720 711 712 +f 712 485 495 +f 721 712 495 +f 720 712 721 +f 721 495 496 +f 715 716 722 +f 722 716 723 +f 725 724 723 +f 716 725 723 +f 717 725 716 +f 725 717 726 +f 726 717 718 +f 726 718 727 +f 727 718 719 +f 727 719 728 +f 728 719 720 +f 728 720 729 +f 729 720 721 +f 721 496 506 +f 730 721 506 +f 729 721 730 +f 732 731 507 +f 724 725 733 +f 735 734 733 +f 725 735 733 +f 726 735 725 +f 735 726 736 +f 736 726 727 +f 736 727 737 +f 737 727 728 +f 737 728 738 +f 738 728 729 +f 738 729 739 +f 739 729 730 +f 741 507 517 +f 740 742 517 +f 739 730 743 +f 740 517 518 +f 734 735 744 +f 746 745 744 +f 735 746 744 +f 736 746 735 +f 746 736 747 +f 747 736 737 +f 747 737 748 +f 748 737 738 +f 748 738 749 +f 749 738 739 +f 749 739 750 +f 750 739 751 +f 740 518 524 +f 752 740 524 +f 753 740 752 +f 752 524 525 +f 745 746 754 +f 756 755 754 +f 746 756 754 +f 747 756 746 +f 756 747 757 +f 757 747 748 +f 757 748 758 +f 758 748 749 +f 758 749 759 +f 759 749 750 +f 759 750 760 +f 762 761 752 +f 752 525 531 +f 763 752 531 +f 764 752 763 +f 763 531 532 +f 755 756 765 +f 767 766 765 +f 756 767 765 +f 757 767 756 +f 767 757 768 +f 768 757 758 +f 768 758 769 +f 769 758 759 +f 769 759 770 +f 770 759 760 +f 773 772 771 +f 771 774 763 +f 763 532 537 +f 775 763 537 +f 771 763 775 +f 775 537 538 +f 767 768 776 +f 776 768 777 +f 779 778 777 +f 768 779 777 +f 769 779 768 +f 779 769 780 +f 780 769 770 +f 780 770 781 +f 783 782 771 +f 785 771 784 +f 784 771 775 +f 775 538 542 +f 786 775 542 +f 784 775 786 +f 786 542 543 +f 778 779 787 +f 789 788 787 +f 779 789 787 +f 780 789 779 +f 789 780 790 +f 790 780 781 +f 793 792 791 +f 791 794 784 +f 791 784 795 +f 795 784 786 +f 786 543 546 +f 796 786 546 +f 795 786 796 +f 796 546 547 +f 788 789 797 +f 799 798 797 +f 789 799 797 +f 790 799 789 +f 802 801 800 +f 800 803 791 +f 800 791 804 +f 804 791 795 +f 804 795 805 +f 805 795 796 +f 796 547 62 +f 68 796 62 +f 805 796 68 +f 798 799 807 +f 809 808 810 +f 811 809 812 +f 800 809 813 +f 809 800 814 +f 814 800 804 +f 814 804 815 +f 815 804 805 +f 815 805 69 +f 69 805 68 +f 808 809 817 +f 819 818 817 +f 809 819 817 +f 814 819 809 +f 819 814 820 +f 820 814 815 +f 820 815 70 +f 70 815 69 +f 818 819 822 +f 824 823 822 +f 819 824 822 +f 820 824 819 +f 824 820 71 +f 71 820 70 +f 823 824 826 +f 72 827 826 +f 824 72 826 +f 71 72 824 +f 827 72 73 +f 74 67 561 +f 834 833 568 +f 832 835 568 +f 75 836 832 +f 832 568 571 +f 76 839 838 +f 840 75 832 +f 832 571 587 +f 841 832 587 +f 842 832 841 +f 841 587 588 +f 77 76 844 +f 844 76 838 +f 844 838 845 +f 847 846 841 +f 841 588 606 +f 848 841 606 +f 849 841 848 +f 848 606 850 +f 850 606 607 +f 850 607 608 +f 852 851 78 +f 77 852 78 +f 844 852 77 +f 852 844 854 +f 854 844 845 +f 857 856 855 +f 855 858 848 +f 855 848 859 +f 859 848 850 +f 850 608 630 +f 860 850 630 +f 859 850 860 +f 860 630 861 +f 861 630 631 +f 861 631 632 +f 851 852 862 +f 864 863 862 +f 852 864 862 +f 854 864 852 +f 864 854 865 +f 865 854 866 +f 865 868 867 +f 867 869 870 +f 867 872 871 +f 871 873 874 +f 871 876 875 +f 875 877 878 +f 881 880 642 +f 879 882 642 +f 875 883 879 +f 879 642 884 +f 884 642 645 +f 886 885 649 +f 863 864 887 +f 889 888 887 +f 864 889 887 +f 865 889 864 +f 889 865 890 +f 890 865 867 +f 890 867 891 +f 891 867 871 +f 891 871 892 +f 892 871 875 +f 892 875 893 +f 893 875 879 +f 893 879 894 +f 894 879 884 +f 896 649 664 +f 895 897 664 +f 899 898 895 +f 895 664 900 +f 900 664 665 +f 900 665 666 +f 888 889 901 +f 903 902 901 +f 889 903 901 +f 890 903 889 +f 903 890 904 +f 904 890 891 +f 904 891 905 +f 905 891 892 +f 905 892 906 +f 906 892 893 +f 906 893 907 +f 907 893 894 +f 907 894 908 +f 910 909 895 +f 912 895 911 +f 911 895 900 +f 900 666 675 +f 913 900 675 +f 911 900 913 +f 913 675 914 +f 914 675 676 +f 914 676 677 +f 903 904 915 +f 915 904 916 +f 918 917 916 +f 904 918 916 +f 905 918 904 +f 918 905 919 +f 919 905 906 +f 919 906 920 +f 920 906 907 +f 920 907 921 +f 921 907 908 +f 924 923 922 +f 922 925 911 +f 922 911 926 +f 926 911 913 +f 926 913 927 +f 927 913 914 +f 914 677 685 +f 928 914 685 +f 927 914 928 +f 928 685 686 +f 917 918 929 +f 931 930 929 +f 918 931 929 +f 919 931 918 +f 931 919 932 +f 932 919 920 +f 932 920 933 +f 933 920 921 +f 936 935 934 +f 934 937 922 +f 934 922 938 +f 938 922 926 +f 938 926 939 +f 939 926 927 +f 939 927 940 +f 940 927 928 +f 928 686 694 +f 941 928 694 +f 940 928 941 +f 941 694 942 +f 942 694 695 +f 942 695 696 +f 946 945 943 +f 943 947 944 +f 949 948 944 +f 950 949 944 +f 952 951 953 +f 956 955 954 +f 954 957 934 +f 954 934 958 +f 958 934 938 +f 958 938 959 +f 959 938 939 +f 959 939 960 +f 960 939 940 +f 960 940 961 +f 961 940 941 +f 961 941 962 +f 962 941 942 +f 942 696 704 +f 963 942 704 +f 962 942 963 +f 963 704 705 +f 948 949 964 +f 966 965 964 +f 949 966 964 +f 967 966 949 +f 966 969 968 +f 968 970 971 +f 968 973 972 +f 974 958 959 +f 976 959 975 +f 975 959 960 +f 975 960 977 +f 977 960 961 +f 977 961 978 +f 978 961 962 +f 978 962 979 +f 979 962 963 +f 963 705 713 +f 980 963 713 +f 979 963 980 +f 980 713 714 +f 965 966 981 +f 983 982 981 +f 966 983 981 +f 968 983 966 +f 983 968 984 +f 984 968 972 +f 984 972 985 +f 987 986 975 +f 989 975 988 +f 988 975 977 +f 988 977 990 +f 990 977 978 +f 990 978 991 +f 991 978 979 +f 991 979 992 +f 992 979 980 +f 980 714 722 +f 993 980 722 +f 992 980 993 +f 993 722 994 +f 994 722 723 +f 994 723 724 +f 982 983 995 +f 997 996 995 +f 983 997 995 +f 984 997 983 +f 997 984 998 +f 998 984 985 +f 998 985 999 +f 999 985 1000 +f 999 1002 1001 +f 1003 988 990 +f 1005 990 1004 +f 1004 990 991 +f 1004 991 1006 +f 1006 991 992 +f 1006 992 1007 +f 1007 992 993 +f 1007 993 1008 +f 1008 993 994 +f 994 724 733 +f 1009 994 733 +f 1008 994 1009 +f 1009 733 734 +f 996 997 1010 +f 1012 1011 1010 +f 997 1012 1010 +f 998 1012 997 +f 1012 998 1013 +f 1013 998 999 +f 1013 999 1014 +f 1014 999 1001 +f 1014 1001 1015 +f 1017 1016 1004 +f 1019 1004 1018 +f 1018 1004 1006 +f 1018 1006 1020 +f 1020 1006 1007 +f 1020 1007 1021 +f 1021 1007 1008 +f 1021 1008 1022 +f 1022 1008 1009 +f 1009 734 744 +f 1023 1009 744 +f 1022 1009 1023 +f 1023 744 745 +f 1011 1012 1024 +f 1026 1025 1024 +f 1012 1026 1024 +f 1013 1026 1012 +f 1026 1013 1027 +f 1027 1013 1014 +f 1027 1014 1028 +f 1028 1014 1015 +f 1028 1015 1029 +f 1031 1030 1018 +f 1033 1018 1032 +f 1032 1018 1020 +f 1032 1020 1034 +f 1034 1020 1021 +f 1034 1021 1035 +f 1035 1021 1022 +f 1035 1022 1036 +f 1036 1022 1023 +f 1023 745 754 +f 1037 1023 754 +f 1036 1023 1037 +f 1037 754 755 +f 1026 1027 1038 +f 1038 1027 1039 +f 1041 1040 1039 +f 1027 1041 1039 +f 1028 1041 1027 +f 1041 1028 1042 +f 1042 1028 1029 +f 1042 1029 1043 +f 1045 1044 1032 +f 1047 1032 1046 +f 1046 1032 1034 +f 1046 1034 1048 +f 1048 1034 1035 +f 1048 1035 1049 +f 1049 1035 1036 +f 1049 1036 1050 +f 1050 1036 1037 +f 1037 755 765 +f 1051 1037 765 +f 1050 1037 1051 +f 1051 765 766 +f 1040 1041 1052 +f 1054 1053 1052 +f 1041 1054 1052 +f 1042 1054 1041 +f 1054 1042 1055 +f 1055 1042 1043 +f 1055 1043 1056 +f 1058 1057 1046 +f 1060 1046 1059 +f 1059 1046 1048 +f 1059 1048 1061 +f 1061 1048 1049 +f 1061 1049 1062 +f 1062 1049 1050 +f 1062 1050 1063 +f 1063 1050 1051 +f 1051 766 776 +f 1064 1051 776 +f 1063 1051 1064 +f 1064 776 1065 +f 1065 776 777 +f 1065 777 778 +f 1053 1054 1066 +f 1054 1055 1066 +f 1066 1055 1067 +f 1069 1068 1067 +f 1055 1069 1067 +f 1056 1069 1055 +f 1069 1056 1070 +f 1072 1071 1059 +f 1074 1059 1073 +f 1073 1059 1061 +f 1073 1061 1075 +f 1075 1061 1062 +f 1075 1062 1076 +f 1076 1062 1063 +f 1076 1063 1077 +f 1077 1063 1064 +f 1077 1064 1078 +f 1078 1064 1065 +f 1065 778 787 +f 1079 1065 787 +f 1078 1065 1079 +f 1079 787 788 +f 1068 1069 1080 +f 1082 1081 1080 +f 1069 1082 1080 +f 1070 1082 1069 +f 1085 1084 1083 +f 1083 1086 1073 +f 1083 1073 1087 +f 1087 1073 1075 +f 1087 1075 1088 +f 1088 1075 1076 +f 1088 1076 1089 +f 1089 1076 1077 +f 1089 1077 1090 +f 1090 1077 1078 +f 1090 1078 1091 +f 1091 1078 1079 +f 1079 788 797 +f 1092 1079 797 +f 1091 1079 1092 +f 1092 797 798 +f 1081 1082 1093 +f 1095 1094 1093 +f 1082 1095 1093 +f 1083 1096 1097 +f 1099 1083 1098 +f 1098 1083 1087 +f 1098 1087 1100 +f 1100 1087 1088 +f 1100 1088 1101 +f 1101 1088 1089 +f 1101 1089 1102 +f 1102 1089 1090 +f 1102 1090 1103 +f 1103 1090 1091 +f 1103 1091 1104 +f 1104 1091 1092 +f 1092 798 807 +f 1105 1092 807 +f 1104 1092 1105 +f 1107 1106 808 +f 1094 1095 1108 +f 1110 1098 1111 +f 1112 1098 1109 +f 1114 1113 1109 +f 1098 1114 1109 +f 1100 1114 1098 +f 1114 1100 1115 +f 1115 1100 1101 +f 1115 1101 1116 +f 1116 1101 1102 +f 1116 1102 1117 +f 1117 1102 1103 +f 1117 1103 1118 +f 1118 1103 1104 +f 1118 1104 1119 +f 1119 1104 1105 +f 1121 808 817 +f 1120 1122 817 +f 1124 1123 1120 +f 1120 817 818 +f 1113 1114 1125 +f 1127 1126 1125 +f 1114 1127 1125 +f 1115 1127 1114 +f 1127 1115 1128 +f 1128 1115 1116 +f 1128 1116 1129 +f 1129 1116 1117 +f 1129 1117 1130 +f 1130 1117 1118 +f 1130 1118 1131 +f 1131 1118 1119 +f 1131 1119 1132 +f 1134 1133 1120 +f 1120 818 822 +f 1135 1120 822 +f 1136 1120 1135 +f 1135 822 823 +f 1126 1127 1137 +f 1139 1138 1137 +f 1127 1139 1137 +f 1128 1139 1127 +f 1139 1128 1140 +f 1140 1128 1129 +f 1140 1129 1141 +f 1141 1129 1130 +f 1141 1130 1142 +f 1142 1130 1131 +f 1142 1131 1143 +f 1143 1131 1132 +f 1143 1132 1144 +f 1146 1145 1135 +f 1135 823 826 +f 1147 1135 826 +f 1148 1135 1147 +f 1147 826 827 +f 1138 1139 1149 +f 1151 1150 1149 +f 1139 1151 1149 +f 1140 1151 1139 +f 1151 1140 1152 +f 1152 1140 1141 +f 1152 1141 1153 +f 1153 1141 1142 +f 1153 1142 1154 +f 1154 1142 1143 +f 1154 1143 1155 +f 1155 1143 1144 +f 1155 1144 1156 +f 1158 1157 1147 +f 1147 827 73 +f 79 1147 73 +f 1160 1147 79 +f 1150 1151 1161 +f 1163 1162 1161 +f 1151 1163 1161 +f 1152 1163 1151 +f 1163 1152 1164 +f 1164 1152 1153 +f 1164 1153 1165 +f 1165 1153 1154 +f 1165 1154 1166 +f 1166 1154 1155 +f 1166 1155 1167 +f 1167 1155 1156 +f 1167 1156 80 +f 1170 1169 79 +f 1162 1163 1171 +f 1163 1164 1171 +f 1171 1164 1172 +f 1174 1173 1172 +f 1164 1174 1172 +f 1165 1174 1164 +f 1174 1165 1175 +f 1175 1165 1166 +f 1175 1166 1176 +f 1176 1166 1167 +f 1176 1167 81 +f 81 1167 80 +f 1173 1174 1178 +f 83 82 1178 +f 1174 83 1178 +f 1175 83 1174 +f 83 1175 84 +f 84 1175 1176 +f 84 1176 85 +f 85 1176 81 +f 86 78 851 +f 86 851 862 +f 1185 86 862 +f 87 86 1185 +f 1185 862 863 +f 88 87 1187 +f 1187 87 1185 +f 1185 863 887 +f 1188 1185 887 +f 1187 1185 1188 +f 1188 887 888 +f 89 88 1190 +f 1190 88 1187 +f 1190 1187 1191 +f 1191 1187 1188 +f 1188 888 901 +f 1192 1188 901 +f 1191 1188 1192 +f 1192 901 902 +f 90 89 1194 +f 1194 89 1190 +f 1194 1190 1195 +f 1195 1190 1191 +f 1195 1191 1196 +f 1196 1191 1192 +f 1192 902 915 +f 1197 1192 915 +f 1196 1192 1197 +f 1197 915 1198 +f 1198 915 916 +f 1198 916 917 +f 1200 1199 91 +f 90 1200 91 +f 1194 1200 90 +f 1200 1194 1202 +f 1202 1194 1195 +f 1202 1195 1203 +f 1203 1195 1196 +f 1203 1196 1204 +f 1204 1196 1197 +f 1204 1197 1205 +f 1205 1197 1198 +f 1198 917 929 +f 1206 1198 929 +f 1205 1198 1206 +f 1206 929 930 +f 1199 1200 1207 +f 1209 1208 1210 +f 1211 1209 1212 +f 1213 1209 1214 +f 1209 1216 1215 +f 1215 1217 1218 +f 1215 1220 1219 +f 1219 1221 1222 +f 1219 1224 1223 +f 1223 1225 1226 +f 1223 1228 1227 +f 1227 1229 1230 +f 1233 1232 943 +f 1231 1234 943 +f 1227 1235 1231 +f 1231 943 1236 +f 1236 943 944 +f 1236 944 948 +f 1208 1209 1237 +f 1239 1238 1237 +f 1209 1239 1237 +f 1215 1239 1209 +f 1239 1215 1240 +f 1240 1215 1219 +f 1240 1219 1241 +f 1241 1219 1223 +f 1241 1223 1242 +f 1242 1223 1227 +f 1242 1227 1243 +f 1243 1227 1231 +f 1243 1231 1244 +f 1244 1231 1236 +f 1236 948 964 +f 1245 1236 964 +f 1244 1236 1245 +f 1245 964 965 +f 1238 1239 1246 +f 1248 1247 1246 +f 1239 1248 1246 +f 1240 1248 1239 +f 1248 1240 1249 +f 1249 1240 1241 +f 1249 1241 1250 +f 1250 1241 1242 +f 1250 1242 1251 +f 1251 1242 1243 +f 1251 1243 1252 +f 1252 1243 1244 +f 1252 1244 1253 +f 1253 1244 1245 +f 1245 965 981 +f 1254 1245 981 +f 1253 1245 1254 +f 1254 981 982 +f 1247 1248 1255 +f 1257 1256 1255 +f 1248 1257 1255 +f 1249 1257 1248 +f 1257 1249 1258 +f 1258 1249 1250 +f 1258 1250 1259 +f 1259 1250 1251 +f 1259 1251 1260 +f 1260 1251 1252 +f 1260 1252 1261 +f 1261 1252 1253 +f 1261 1253 1262 +f 1262 1253 1254 +f 1254 982 995 +f 1263 1254 995 +f 1262 1254 1263 +f 1263 995 996 +f 1256 1257 1264 +f 1266 1265 1264 +f 1257 1266 1264 +f 1258 1266 1257 +f 1266 1258 1267 +f 1267 1258 1259 +f 1267 1259 1268 +f 1268 1259 1260 +f 1268 1260 1269 +f 1269 1260 1261 +f 1269 1261 1270 +f 1270 1261 1262 +f 1270 1262 1271 +f 1271 1262 1263 +f 1263 996 1010 +f 1272 1263 1010 +f 1271 1263 1272 +f 1272 1010 1011 +f 1265 1266 1273 +f 1273 1266 1274 +f 1274 1266 1275 +f 1275 1266 1267 +f 1275 1267 1276 +f 1276 1267 1268 +f 1276 1268 1277 +f 1277 1268 1269 +f 1277 1269 1278 +f 1278 1269 1270 +f 1278 1270 1279 +f 1279 1270 1271 +f 1279 1271 1280 +f 1280 1271 1272 +f 1272 1011 1024 +f 1281 1272 1024 +f 1280 1272 1281 +f 1281 1024 1025 +f 1273 1274 1282 +f 1284 1283 1282 +f 1274 1284 1282 +f 1275 1284 1274 +f 1284 1275 1285 +f 1285 1275 1276 +f 1285 1276 1286 +f 1286 1276 1277 +f 1286 1277 1287 +f 1287 1277 1278 +f 1287 1278 1288 +f 1288 1278 1279 +f 1288 1279 1289 +f 1289 1279 1280 +f 1289 1280 1290 +f 1290 1280 1281 +f 1281 1025 1038 +f 1291 1281 1038 +f 1290 1281 1291 +f 1291 1038 1292 +f 1292 1038 1039 +f 1292 1039 1040 +f 1283 1284 1293 +f 1295 1294 1293 +f 1284 1295 1293 +f 1285 1295 1284 +f 1295 1285 1296 +f 1296 1285 1286 +f 1296 1286 1297 +f 1297 1286 1287 +f 1297 1287 1298 +f 1298 1287 1288 +f 1298 1288 1299 +f 1299 1288 1289 +f 1299 1289 1300 +f 1300 1289 1290 +f 1300 1290 1301 +f 1301 1290 1291 +f 1301 1291 1302 +f 1302 1291 1292 +f 1292 1040 1052 +f 1303 1292 1052 +f 1302 1292 1303 +f 1303 1052 1053 +f 1294 1295 1304 +f 1304 1295 1305 +f 1305 1295 1306 +f 1306 1295 1296 +f 1306 1296 1307 +f 1307 1296 1297 +f 1307 1297 1308 +f 1308 1297 1298 +f 1308 1298 1309 +f 1309 1298 1299 +f 1309 1299 1310 +f 1310 1299 1300 +f 1310 1300 1311 +f 1311 1300 1301 +f 1311 1301 1312 +f 1312 1301 1302 +f 1312 1302 1313 +f 1313 1302 1303 +f 1303 1053 1066 +f 1314 1303 1066 +f 1313 1303 1314 +f 1314 1066 1315 +f 1315 1066 1067 +f 1315 1067 1068 +f 1304 1305 1316 +f 1318 1317 1316 +f 1305 1318 1316 +f 1306 1318 1305 +f 1318 1306 1319 +f 1319 1306 1307 +f 1319 1307 1320 +f 1320 1307 1308 +f 1320 1308 1321 +f 1321 1308 1309 +f 1321 1309 1322 +f 1322 1309 1310 +f 1322 1310 1323 +f 1323 1310 1311 +f 1323 1311 1324 +f 1324 1311 1312 +f 1324 1312 1325 +f 1325 1312 1313 +f 1325 1313 1326 +f 1326 1313 1314 +f 1326 1314 1327 +f 1327 1314 1315 +f 1315 1068 1080 +f 1328 1315 1080 +f 1327 1315 1328 +f 1328 1080 1081 +f 1317 1318 1329 +f 1331 1330 1329 +f 1318 1331 1329 +f 1319 1331 1318 +f 1331 1319 1332 +f 1332 1319 1320 +f 1332 1320 1333 +f 1333 1320 1321 +f 1333 1321 1334 +f 1334 1321 1322 +f 1334 1322 1335 +f 1335 1322 1323 +f 1335 1323 1336 +f 1336 1323 1324 +f 1336 1324 1337 +f 1337 1324 1325 +f 1337 1325 1338 +f 1338 1325 1326 +f 1338 1326 1339 +f 1339 1326 1327 +f 1339 1327 1340 +f 1340 1327 1328 +f 1328 1081 1093 +f 1341 1328 1093 +f 1340 1328 1341 +f 1341 1093 1094 +f 1330 1331 1342 +f 1344 1343 1342 +f 1331 1344 1342 +f 1332 1344 1331 +f 1344 1332 1345 +f 1345 1332 1333 +f 1345 1333 1346 +f 1346 1333 1334 +f 1346 1334 1347 +f 1347 1334 1335 +f 1347 1335 1348 +f 1348 1335 1336 +f 1348 1336 1349 +f 1349 1336 1337 +f 1349 1337 1350 +f 1350 1337 1338 +f 1350 1338 1351 +f 1351 1338 1339 +f 1351 1339 1352 +f 1352 1339 1340 +f 1352 1340 1353 +f 1353 1340 1341 +f 1341 1094 1108 +f 1354 1341 1108 +f 1353 1341 1354 +f 1357 1356 1355 +f 1355 1358 1109 +f 1355 1109 1113 +f 1343 1344 1359 +f 1344 1345 1359 +f 1359 1345 1360 +f 1362 1361 1360 +f 1345 1362 1360 +f 1346 1362 1345 +f 1362 1346 1363 +f 1363 1346 1347 +f 1363 1347 1364 +f 1364 1347 1348 +f 1364 1348 1365 +f 1365 1348 1349 +f 1365 1349 1366 +f 1366 1349 1350 +f 1366 1350 1367 +f 1367 1350 1351 +f 1367 1351 1368 +f 1368 1351 1352 +f 1368 1352 1369 +f 1369 1352 1353 +f 1369 1353 1370 +f 1370 1353 1354 +f 1373 1372 1371 +f 1371 1374 1355 +f 1355 1113 1125 +f 1375 1355 1125 +f 1371 1355 1375 +f 1375 1125 1126 +f 1361 1362 1376 +f 1362 1363 1376 +f 1376 1363 1377 +f 1379 1378 1377 +f 1363 1379 1377 +f 1364 1379 1363 +f 1379 1364 1380 +f 1380 1364 1365 +f 1380 1365 1381 +f 1381 1365 1366 +f 1381 1366 1382 +f 1382 1366 1367 +f 1382 1367 1383 +f 1383 1367 1368 +f 1383 1368 1384 +f 1384 1368 1369 +f 1384 1369 1385 +f 1385 1369 1370 +f 1385 1370 1386 +f 1388 1387 1371 +f 1390 1371 1389 +f 1389 1371 1375 +f 1375 1126 1137 +f 1391 1375 1137 +f 1389 1375 1391 +f 1391 1137 1138 +f 1378 1379 1392 +f 1379 1380 1392 +f 1392 1380 1393 +f 1395 1394 1393 +f 1380 1395 1393 +f 1381 1395 1380 +f 1395 1381 1396 +f 1396 1381 1382 +f 1396 1382 1397 +f 1397 1382 1383 +f 1397 1383 1398 +f 1398 1383 1384 +f 1398 1384 1399 +f 1399 1384 1385 +f 1399 1385 1400 +f 1400 1385 1386 +f 1403 1402 1401 +f 1401 1404 1389 +f 1401 1389 1405 +f 1405 1389 1391 +f 1391 1138 1149 +f 1406 1391 1149 +f 1405 1391 1406 +f 1406 1149 1150 +f 1394 1395 1407 +f 1409 1408 1407 +f 1395 1409 1407 +f 1396 1409 1395 +f 1409 1396 1410 +f 1410 1396 1397 +f 1410 1397 1411 +f 1411 1397 1398 +f 1411 1398 1412 +f 1412 1398 1399 +f 1412 1399 1413 +f 1413 1399 1400 +f 1416 1415 1414 +f 1414 1417 1401 +f 1414 1401 1418 +f 1418 1401 1405 +f 1418 1405 1419 +f 1419 1405 1406 +f 1406 1150 1161 +f 1420 1406 1161 +f 1419 1406 1420 +f 1420 1161 1162 +f 1408 1409 1421 +f 1409 1410 1421 +f 1421 1410 1422 +f 1424 1423 1422 +f 1410 1424 1422 +f 1411 1424 1410 +f 1424 1411 1425 +f 1425 1411 1412 +f 1425 1412 1426 +f 1426 1412 1413 +f 1426 1413 1427 +f 1429 1428 1414 +f 1431 1414 1430 +f 1430 1414 1418 +f 1430 1418 1432 +f 1432 1418 1419 +f 1432 1419 1433 +f 1433 1419 1420 +f 1420 1162 1171 +f 1434 1420 1171 +f 1433 1420 1434 +f 1434 1171 1435 +f 1435 1171 1172 +f 1435 1172 1173 +f 1423 1424 1436 +f 1424 1425 1436 +f 1436 1425 1437 +f 93 92 1437 +f 1425 93 1437 +f 1426 93 1425 +f 93 1426 94 +f 94 1426 1427 +f 1443 1442 95 +f 95 1444 1430 +f 95 1430 96 +f 96 1430 1432 +f 96 1432 97 +f 97 1432 1433 +f 97 1433 98 +f 98 1433 1434 +f 98 1434 99 +f 99 1434 1435 +f 1435 1173 1178 +f 100 1435 1178 +f 99 1435 100 +f 100 1178 82 +f 101 91 1199 +f 101 1199 1207 +f 1452 101 1207 +f 102 101 1452 +f 1454 1453 1208 +f 103 1457 1456 +f 1456 1458 1459 +f 1461 1208 1237 +f 1460 1462 1237 +f 1456 1463 1460 +f 1460 1237 1238 +f 104 103 1465 +f 1465 103 1456 +f 1465 1456 1466 +f 1466 1456 1460 +f 1460 1238 1246 +f 1467 1460 1246 +f 1466 1460 1467 +f 1467 1246 1247 +f 105 104 1469 +f 1469 104 1465 +f 1469 1465 1470 +f 1470 1465 1466 +f 1470 1466 1471 +f 1471 1466 1467 +f 1467 1247 1255 +f 1472 1467 1255 +f 1471 1467 1472 +f 1472 1255 1256 +f 1474 1473 106 +f 105 1474 106 +f 1469 1474 105 +f 1474 1469 1476 +f 1476 1469 1470 +f 1476 1470 1477 +f 1477 1470 1471 +f 1477 1471 1478 +f 1478 1471 1472 +f 1472 1256 1264 +f 1479 1472 1264 +f 1478 1472 1479 +f 1479 1264 1265 +f 1473 1474 1480 +f 1482 1481 1480 +f 1474 1482 1480 +f 1476 1482 1474 +f 1482 1476 1483 +f 1483 1476 1477 +f 1483 1477 1484 +f 1484 1477 1478 +f 1484 1478 1485 +f 1485 1478 1479 +f 1485 1479 1273 +f 1273 1479 1265 +f 1481 1482 1486 +f 1488 1487 1486 +f 1482 1488 1486 +f 1483 1488 1482 +f 1488 1483 1489 +f 1489 1483 1484 +f 1489 1484 1490 +f 1490 1484 1485 +f 1485 1273 1282 +f 1491 1485 1282 +f 1490 1485 1491 +f 1491 1282 1283 +f 1487 1488 1492 +f 1492 1488 1493 +f 1493 1488 1494 +f 1494 1488 1489 +f 1494 1489 1495 +f 1495 1489 1490 +f 1495 1490 1496 +f 1496 1490 1491 +f 1491 1283 1293 +f 1497 1491 1293 +f 1496 1491 1497 +f 1497 1293 1294 +f 1492 1493 1498 +f 1500 1499 1498 +f 1493 1500 1498 +f 1494 1500 1493 +f 1500 1494 1501 +f 1501 1494 1495 +f 1501 1495 1502 +f 1502 1495 1496 +f 1502 1496 1503 +f 1503 1496 1497 +f 1503 1497 1304 +f 1304 1497 1294 +f 1499 1500 1504 +f 1506 1505 1504 +f 1500 1506 1504 +f 1501 1506 1500 +f 1506 1501 1507 +f 1507 1501 1502 +f 1507 1502 1508 +f 1508 1502 1503 +f 1503 1304 1316 +f 1509 1503 1316 +f 1508 1503 1509 +f 1509 1316 1317 +f 1505 1506 1510 +f 1510 1506 1511 +f 1511 1506 1512 +f 1512 1506 1507 +f 1512 1507 1513 +f 1513 1507 1508 +f 1513 1508 1514 +f 1514 1508 1509 +f 1509 1317 1329 +f 1515 1509 1329 +f 1514 1509 1515 +f 1515 1329 1330 +f 1510 1511 1516 +f 1518 1517 1516 +f 1511 1518 1516 +f 1512 1518 1511 +f 1518 1512 1519 +f 1519 1512 1513 +f 1519 1513 1520 +f 1520 1513 1514 +f 1520 1514 1521 +f 1521 1514 1515 +f 1515 1330 1342 +f 1522 1515 1342 +f 1521 1515 1522 +f 1522 1342 1343 +f 1517 1518 1523 +f 1523 1518 1524 +f 1524 1518 1525 +f 1525 1518 1519 +f 1525 1519 1526 +f 1526 1519 1520 +f 1526 1520 1527 +f 1527 1520 1521 +f 1527 1521 1528 +f 1528 1521 1522 +f 1522 1343 1359 +f 1529 1522 1359 +f 1528 1522 1529 +f 1529 1359 1530 +f 1530 1359 1360 +f 1530 1360 1361 +f 1523 1524 1531 +f 1533 1532 1531 +f 1524 1533 1531 +f 1525 1533 1524 +f 1533 1525 1534 +f 1534 1525 1526 +f 1534 1526 1535 +f 1535 1526 1527 +f 1535 1527 1536 +f 1536 1527 1528 +f 1536 1528 1537 +f 1537 1528 1529 +f 1537 1529 1538 +f 1538 1529 1530 +f 1530 1361 1376 +f 1539 1530 1376 +f 1538 1530 1539 +f 1539 1376 1540 +f 1540 1376 1377 +f 1540 1377 1378 +f 1532 1533 1541 +f 1543 1542 1541 +f 1533 1543 1541 +f 1534 1543 1533 +f 1543 1534 1544 +f 1544 1534 1535 +f 1544 1535 1545 +f 1545 1535 1536 +f 1545 1536 1546 +f 1546 1536 1537 +f 1546 1537 1547 +f 1547 1537 1538 +f 1547 1538 1548 +f 1548 1538 1539 +f 1548 1539 1549 +f 1549 1539 1540 +f 1540 1378 1392 +f 1550 1540 1392 +f 1549 1540 1550 +f 1550 1392 1551 +f 1551 1392 1393 +f 1551 1393 1394 +f 1542 1543 1552 +f 1554 1553 1552 +f 1543 1554 1552 +f 1544 1554 1543 +f 1554 1544 1555 +f 1555 1544 1545 +f 1555 1545 1556 +f 1556 1545 1546 +f 1556 1546 1557 +f 1557 1546 1547 +f 1557 1547 1558 +f 1558 1547 1548 +f 1558 1548 1559 +f 1559 1548 1549 +f 1559 1549 1560 +f 1560 1549 1550 +f 1560 1550 1561 +f 1561 1550 1551 +f 1551 1394 1407 +f 1562 1551 1407 +f 1561 1551 1562 +f 1562 1407 1408 +f 1553 1554 1563 +f 1565 1564 1563 +f 1554 1565 1563 +f 1555 1565 1554 +f 1565 1555 1566 +f 1566 1555 1556 +f 1566 1556 1567 +f 1567 1556 1557 +f 1567 1557 1568 +f 1568 1557 1558 +f 1568 1558 1569 +f 1569 1558 1559 +f 1569 1559 1570 +f 1570 1559 1560 +f 1570 1560 1571 +f 1571 1560 1561 +f 1571 1561 1572 +f 1572 1561 1562 +f 1562 1408 1421 +f 1573 1562 1421 +f 1572 1562 1573 +f 1573 1421 1574 +f 1574 1421 1422 +f 1574 1422 1423 +f 1564 1565 1575 +f 108 107 1575 +f 1565 108 1575 +f 1566 108 1565 +f 108 1566 109 +f 109 1566 1567 +f 109 1567 110 +f 110 1567 1568 +f 110 1568 111 +f 111 1568 1569 +f 111 1569 112 +f 112 1569 1570 +f 112 1570 113 +f 113 1570 1571 +f 113 1571 114 +f 114 1571 1572 +f 114 1572 115 +f 115 1572 1573 +f 115 1573 116 +f 116 1573 1574 +f 1574 1423 1436 +f 117 1574 1436 +f 116 1574 117 +f 117 1436 118 +f 118 1436 1437 +f 118 1437 92 +f 119 106 1473 +f 119 1473 1480 +f 1590 119 1480 +f 120 119 1590 +f 1590 1480 1481 +f 121 120 1592 +f 1592 120 1590 +f 1590 1481 1486 +f 1593 1590 1486 +f 1592 1590 1593 +f 1593 1486 1487 +f 122 121 1595 +f 1595 121 1592 +f 1595 1592 1596 +f 1596 1592 1593 +f 1596 1593 1492 +f 1492 1593 1487 +f 1598 1597 123 +f 122 1598 123 +f 1595 1598 122 +f 1598 1595 1600 +f 1600 1595 1596 +f 1596 1492 1498 +f 1601 1596 1498 +f 1600 1596 1601 +f 1601 1498 1499 +f 1597 1598 1602 +f 1602 1598 1603 +f 1603 1598 1604 +f 1604 1598 1600 +f 1604 1600 1605 +f 1605 1600 1601 +f 1601 1499 1504 +f 1606 1601 1504 +f 1605 1601 1606 +f 1606 1504 1505 +f 1602 1603 1607 +f 1609 1608 1607 +f 1603 1609 1607 +f 1604 1609 1603 +f 1609 1604 1610 +f 1610 1604 1605 +f 1610 1605 1611 +f 1611 1605 1606 +f 1611 1606 1510 +f 1510 1606 1505 +f 1608 1609 1612 +f 1614 1613 1612 +f 1609 1614 1612 +f 1610 1614 1609 +f 1614 1610 1615 +f 1615 1610 1611 +f 1611 1510 1516 +f 1616 1611 1516 +f 1615 1611 1616 +f 1616 1516 1517 +f 1613 1614 1617 +f 1617 1614 1618 +f 1618 1614 1619 +f 1619 1614 1615 +f 1619 1615 1620 +f 1620 1615 1616 +f 1620 1616 1523 +f 1523 1616 1517 +f 1617 1618 1621 +f 1623 1622 1621 +f 1618 1623 1621 +f 1619 1623 1618 +f 1623 1619 1624 +f 1624 1619 1620 +f 1620 1523 1531 +f 1625 1620 1531 +f 1624 1620 1625 +f 1625 1531 1532 +f 1622 1623 1626 +f 1626 1623 1627 +f 1627 1623 1628 +f 1628 1623 1624 +f 1628 1624 1629 +f 1629 1624 1625 +f 1625 1532 1541 +f 1630 1625 1541 +f 1629 1625 1630 +f 1630 1541 1542 +f 1626 1627 1631 +f 1633 1632 1631 +f 1627 1633 1631 +f 1628 1633 1627 +f 1633 1628 1634 +f 1634 1628 1629 +f 1634 1629 1635 +f 1635 1629 1630 +f 1630 1542 1552 +f 1636 1630 1552 +f 1635 1630 1636 +f 1636 1552 1553 +f 1632 1633 1637 +f 1639 1638 1637 +f 1633 1639 1637 +f 1634 1639 1633 +f 1639 1634 1640 +f 1640 1634 1635 +f 1640 1635 1641 +f 1641 1635 1636 +f 1636 1553 1563 +f 1642 1636 1563 +f 1641 1636 1642 +f 1642 1563 1564 +f 1638 1639 124 +f 124 1639 125 +f 125 1639 126 +f 126 1639 1640 +f 126 1640 127 +f 127 1640 1641 +f 127 1641 128 +f 128 1641 1642 +f 1642 1564 1575 +f 129 1642 1575 +f 128 1642 129 +f 129 1575 107 +f 130 123 1597 +f 131 130 1602 +f 1602 130 1597 +f 131 1602 1607 +f 1652 131 1607 +f 132 131 1652 +f 1652 1607 1608 +f 133 132 1654 +f 1654 132 1652 +f 1652 1608 1612 +f 1655 1652 1612 +f 1654 1652 1655 +f 1655 1612 1613 +f 134 133 1657 +f 1657 133 1654 +f 1657 1654 1658 +f 1658 1654 1655 +f 1658 1655 1617 +f 1617 1655 1613 +f 1660 1659 135 +f 134 1660 135 +f 1657 1660 134 +f 1660 1657 1662 +f 1662 1657 1658 +f 1658 1617 1621 +f 1663 1658 1621 +f 1662 1658 1663 +f 1663 1621 1622 +f 1659 1660 1664 +f 1666 1665 1664 +f 1660 1666 1664 +f 1662 1666 1660 +f 1666 1662 1667 +f 1667 1662 1663 +f 1667 1663 1626 +f 1626 1663 1622 +f 1665 1666 1668 +f 1668 1666 1669 +f 1669 1666 1670 +f 1670 1666 1667 +f 1667 1626 1631 +f 1671 1667 1631 +f 1670 1667 1671 +f 1671 1631 1632 +f 1668 1669 1672 +f 1674 1673 1672 +f 1669 1674 1672 +f 1670 1674 1669 +f 1674 1670 1675 +f 1675 1670 1671 +f 1671 1632 1637 +f 1676 1671 1637 +f 1675 1671 1676 +f 1676 1637 1638 +f 1673 1674 1677 +f 137 136 1677 +f 1674 137 1677 +f 1675 137 1674 +f 137 1675 138 +f 138 1675 1676 +f 138 1676 124 +f 124 1676 1638 +f 139 135 1659 +f 139 1659 1664 +f 1683 139 1664 +f 140 139 1683 +f 1683 1664 1665 +f 141 140 1685 +f 1685 140 1683 +f 1685 1683 1668 +f 1668 1683 1665 +f 142 141 1687 +f 1687 141 1685 +f 1685 1668 1672 +f 1688 1685 1672 +f 1687 1685 1688 +f 1688 1672 1673 +f 144 143 145 +f 142 144 145 +f 1687 144 142 +f 144 1687 146 +f 146 1687 1688 +f 1688 1673 1677 +f 147 1688 1677 +f 146 1688 147 +f 147 1677 136 +f 148 145 143 diff --git a/data/meshes/voxel_mesh_04.obj b/data/meshes/voxel_mesh_04.obj new file mode 100644 index 0000000..f7cd42b --- /dev/null +++ b/data/meshes/voxel_mesh_04.obj @@ -0,0 +1,3358 @@ +# voxel +v 0.000000000 0.000000000 100.008071899 +v 0.000000000 100.000000000 100.008071899 +v 100.000000000 0.000000000 100.008071899 +v 200.000000000 0.000000000 100.008071899 +v 300.000000000 0.000000000 100.008071899 +v 400.000000000 0.000000000 100.008071899 +v 500.000000000 0.000000000 100.008071899 +v 600.000000000 0.000000000 100.008071899 +v 700.000000000 0.000000000 100.008071899 +v 800.000000000 0.000000000 100.008071899 +v 900.000000000 0.000000000 100.008071899 +v 1000.000000000 0.000000000 100.008071899 +v 1100.000000000 0.000000000 100.008071899 +v 1200.000000000 0.000000000 100.008071899 +v 1300.000000000 0.000000000 100.008071899 +v 1400.000000000 0.000000000 100.008071899 +v 1500.000000000 0.000000000 100.008071899 +v 1600.000000000 0.000000000 100.008071899 +v 1700.000000000 0.000000000 100.008071899 +v 1800.000000000 0.000000000 100.008071899 +v 1900.000000000 0.000000000 100.008071899 +v 2000.000000000 0.000000000 100.008071899 +v 2100.000000000 0.000000000 100.008071899 +v 2200.000000000 0.000000000 100.008071899 +v 2300.000000000 0.000000000 100.008071899 +v 2400.000000000 0.000000000 100.008071899 +v 2500.000000000 0.000000000 100.008071899 +v 2600.000000000 0.000000000 100.008071899 +v 2700.000000000 0.000000000 100.008071899 +v 2800.000000000 0.000000000 100.008071899 +v 2900.000000000 0.000000000 100.008071899 +v 3000.000000000 0.000000000 100.008071899 +v 3100.000000000 0.000000000 100.008071899 +v 3200.000000000 100.000000000 100.008071899 +v 3200.000000000 0.000000000 100.008071899 +v 0.000000000 200.000000000 103.113410950 +v 3200.000000000 200.000000000 100.008071899 +v 0.000000000 300.000000000 107.811264038 +v 3200.000000000 300.000000000 100.008071899 +v 0.000000000 400.000000000 113.278785706 +v 3200.000000000 400.000000000 100.008071899 +v 0.000000000 500.000000000 121.081962585 +v 3200.000000000 500.000000000 100.008071899 +v 0.000000000 600.000000000 128.911682129 +v 3200.000000000 600.000000000 100.008071899 +v 0.000000000 700.000000000 139.050506592 +v 3200.000000000 700.000000000 100.008071899 +v 0.000000000 800.000000000 150.012115479 +v 3200.000000000 800.000000000 100.008071899 +v 0.000000000 900.000000000 160.947174072 +v 3200.000000000 900.000000000 100.008071899 +v 0.000000000 1000.000000000 174.217895508 +v 3200.000000000 1000.000000000 100.008071899 +v 0.000000000 1100.000000000 186.718902588 +v 3200.000000000 1100.000000000 100.008071899 +v 0.000000000 1194.413452148 200.000000000 +v 3200.000000000 1200.000000000 100.008071899 +v 3200.000000000 1300.000000000 100.008071899 +v 3200.000000000 1400.000000000 100.008071899 +v 3200.000000000 1500.000000000 100.008071899 +v 3200.000000000 1600.000000000 100.008071899 +v 3200.000000000 1700.000000000 100.008071899 +v 3200.000000000 1800.000000000 100.008071899 +v 3200.000000000 1900.000000000 100.008071899 +v 3200.000000000 2000.000000000 100.008071899 +v 3200.000000000 2100.000000000 100.008071899 +v 3200.000000000 2200.000000000 100.008071899 +v 3200.000000000 2300.000000000 100.008071899 +v 3200.000000000 2400.000000000 100.008071899 +v 3200.000000000 2500.000000000 100.008071899 +v 3200.000000000 2600.000000000 100.008071899 +v 3200.000000000 2700.000000000 100.008071899 +v 3200.000000000 2800.000000000 100.008071899 +v 3200.000000000 2900.000000000 100.008071899 +v 3200.000000000 3000.000000000 100.008071899 +v 3200.000000000 3100.000000000 100.008071899 +v 935.195556641 3200.000000000 200.000000000 +v 1000.000000000 3200.000000000 172.651947021 +v 1100.000000000 3200.000000000 135.148910522 +v 1200.000000000 3200.000000000 112.509086609 +v 1300.000000000 3200.000000000 101.574012756 +v 1400.000000000 3200.000000000 100.008071899 +v 1500.000000000 3200.000000000 100.008071899 +v 1600.000000000 3200.000000000 100.008071899 +v 1700.000000000 3200.000000000 100.008071899 +v 1800.000000000 3200.000000000 100.008071899 +v 1900.000000000 3200.000000000 100.008071899 +v 2000.000000000 3200.000000000 100.008071899 +v 2100.000000000 3200.000000000 100.008071899 +v 2200.000000000 3200.000000000 100.008071899 +v 2300.000000000 3200.000000000 100.008071899 +v 2400.000000000 3200.000000000 100.008071899 +v 2500.000000000 3200.000000000 100.008071899 +v 2600.000000000 3200.000000000 100.008071899 +v 2700.000000000 3200.000000000 100.008071899 +v 2800.000000000 3200.000000000 100.008071899 +v 2900.000000000 3200.000000000 100.008071899 +v 3000.000000000 3200.000000000 100.008071899 +v 3100.000000000 3200.000000000 100.008071899 +v 3200.000000000 3200.000000000 100.008071899 +v 0.000000000 1200.000000000 200.785858154 +v 0.000000000 1300.000000000 215.622528076 +v 0.000000000 1400.000000000 230.459167480 +v 0.000000000 1500.000000000 246.861740112 +v 0.000000000 1600.000000000 263.290893555 +v 0.000000000 1700.000000000 279.693481445 +v 0.000000000 1800.000000000 296.865783691 +v 0.000000000 1816.044677734 300.000000000 +v 714.059143066 3200.000000000 300.000000000 +v 800.000000000 3200.000000000 261.724945068 +v 900.000000000 3200.000000000 214.852813721 +v 0.000000000 1900.000000000 316.400268555 +v 0.000000000 2000.000000000 335.934753418 +v 0.000000000 2100.000000000 356.238952637 +v 0.000000000 2200.000000000 375.773437500 +v 0.000000000 2300.000000000 396.104156494 +v 0.000000000 2320.790771484 400.000000000 +v 477.546264648 3200.000000000 400.000000000 +v 500.000000000 3200.000000000 391.406341553 +v 600.000000000 3200.000000000 349.205474854 +v 700.000000000 3200.000000000 306.261444092 +v 0.000000000 2400.000000000 414.842407227 +v 0.000000000 2500.000000000 434.376892090 +v 0.000000000 2600.000000000 450.779541016 +v 0.000000000 2700.000000000 468.748046875 +v 0.000000000 2800.000000000 487.512817383 +v 0.000000000 2884.164306641 500.000000000 +v 186.457382202 3200.000000000 500.000000000 +v 200.000000000 3200.000000000 496.085693359 +v 300.000000000 3200.000000000 464.050201416 +v 400.000000000 3200.000000000 429.679046631 +v 0.000000000 2900.000000000 502.349487305 +v 0.000000000 3000.000000000 517.955810547 +v 0.000000000 3100.000000000 533.588745117 +v 0.000000000 3200.000000000 549.221618652 +v 100.000000000 3200.000000000 524.989318848 +v 400.000000000 400.000000000 100.008071899 +v 500.000000000 400.000000000 100.008071899 +v 600.000000000 400.000000000 100.008071899 +v 700.000000000 400.000000000 100.008071899 +v 800.000000000 400.000000000 100.008071899 +v 900.000000000 400.000000000 100.008071899 +v 1000.000000000 400.000000000 100.008071899 +v 1100.000000000 400.000000000 100.008071899 +v 1200.000000000 400.000000000 100.008071899 +v 1300.000000000 400.000000000 100.008071899 +v 1400.000000000 400.000000000 100.008071899 +v 1500.000000000 400.000000000 100.008071899 +v 1600.000000000 400.000000000 100.008071899 +v 1700.000000000 400.000000000 100.008071899 +v 1800.000000000 400.000000000 100.008071899 +v 1900.000000000 400.000000000 100.008071899 +v 2000.000000000 400.000000000 100.008071899 +v 2100.000000000 400.000000000 100.008071899 +v 2200.000000000 400.000000000 100.008071899 +v 2300.000000000 400.000000000 100.008071899 +v 2400.000000000 400.000000000 100.008071899 +v 2500.000000000 400.000000000 100.008071899 +v 2600.000000000 400.000000000 100.008071899 +v 2700.000000000 400.000000000 100.008071899 +v 2800.000000000 400.000000000 100.008071899 +v 2900.000000000 400.000000000 100.008071899 +v 3000.000000000 400.000000000 100.008071899 +v 3100.000000000 400.000000000 100.008071899 +v 2000.000000000 100.000000000 100.008071899 +v 300.000000000 100.000000000 100.008071899 +v 100.000000000 500.000000000 113.278785706 +v 200.000000000 500.000000000 107.811264038 +v 300.000000000 500.000000000 103.113410950 +v 400.000000000 500.000000000 100.008071899 +v 500.000000000 500.000000000 100.008071899 +v 600.000000000 500.000000000 100.008071899 +v 700.000000000 500.000000000 100.008071899 +v 800.000000000 500.000000000 100.008071899 +v 900.000000000 500.000000000 100.008071899 +v 1000.000000000 500.000000000 100.008071899 +v 1100.000000000 500.000000000 100.008071899 +v 1200.000000000 500.000000000 100.008071899 +v 1300.000000000 500.000000000 100.008071899 +v 1400.000000000 500.000000000 100.008071899 +v 1500.000000000 500.000000000 100.008071899 +v 1600.000000000 500.000000000 100.008071899 +v 1700.000000000 500.000000000 100.008071899 +v 1800.000000000 500.000000000 100.008071899 +v 1900.000000000 500.000000000 100.008071899 +v 2000.000000000 500.000000000 100.008071899 +v 2100.000000000 500.000000000 100.008071899 +v 2200.000000000 500.000000000 100.008071899 +v 2300.000000000 500.000000000 100.008071899 +v 2400.000000000 500.000000000 100.008071899 +v 2500.000000000 500.000000000 100.008071899 +v 2600.000000000 500.000000000 100.008071899 +v 2700.000000000 500.000000000 100.008071899 +v 2800.000000000 500.000000000 100.008071899 +v 2900.000000000 500.000000000 100.008071899 +v 3000.000000000 500.000000000 100.008071899 +v 3100.000000000 500.000000000 100.008071899 +v 2100.000000000 100.000000000 100.008071899 +v 1100.000000000 100.000000000 100.008071899 +v 100.000000000 600.000000000 121.081962585 +v 200.000000000 600.000000000 112.509086609 +v 300.000000000 600.000000000 107.811264038 +v 400.000000000 600.000000000 103.113410950 +v 500.000000000 600.000000000 100.008071899 +v 600.000000000 600.000000000 100.008071899 +v 700.000000000 600.000000000 100.008071899 +v 800.000000000 600.000000000 100.008071899 +v 900.000000000 600.000000000 100.008071899 +v 1000.000000000 600.000000000 100.008071899 +v 1100.000000000 600.000000000 100.008071899 +v 1200.000000000 600.000000000 100.008071899 +v 1300.000000000 600.000000000 100.008071899 +v 1400.000000000 600.000000000 100.008071899 +v 1500.000000000 600.000000000 100.008071899 +v 1600.000000000 600.000000000 100.008071899 +v 1700.000000000 600.000000000 100.008071899 +v 1800.000000000 600.000000000 100.008071899 +v 1900.000000000 600.000000000 100.008071899 +v 2000.000000000 600.000000000 100.008071899 +v 2100.000000000 600.000000000 100.008071899 +v 2200.000000000 600.000000000 100.008071899 +v 2300.000000000 600.000000000 100.008071899 +v 2400.000000000 600.000000000 100.008071899 +v 2500.000000000 600.000000000 100.008071899 +v 2600.000000000 600.000000000 100.008071899 +v 2700.000000000 600.000000000 100.008071899 +v 2800.000000000 600.000000000 100.008071899 +v 2900.000000000 600.000000000 100.008071899 +v 3000.000000000 600.000000000 100.008071899 +v 3100.000000000 600.000000000 100.008071899 +v 2200.000000000 100.000000000 100.008071899 +v 600.000000000 100.000000000 100.008071899 +v 100.000000000 700.000000000 129.681381226 +v 200.000000000 700.000000000 120.312263489 +v 300.000000000 700.000000000 113.278785706 +v 400.000000000 700.000000000 106.245300293 +v 500.000000000 700.000000000 102.343711853 +v 600.000000000 700.000000000 100.008071899 +v 700.000000000 700.000000000 100.008071899 +v 800.000000000 700.000000000 100.008071899 +v 900.000000000 700.000000000 100.008071899 +v 1000.000000000 700.000000000 100.008071899 +v 1100.000000000 700.000000000 100.008071899 +v 1200.000000000 700.000000000 100.008071899 +v 1300.000000000 700.000000000 100.008071899 +v 1400.000000000 700.000000000 100.008071899 +v 1500.000000000 700.000000000 100.008071899 +v 1600.000000000 700.000000000 100.008071899 +v 1700.000000000 700.000000000 100.008071899 +v 1800.000000000 700.000000000 100.008071899 +v 1900.000000000 700.000000000 100.008071899 +v 2000.000000000 700.000000000 100.008071899 +v 2100.000000000 700.000000000 100.008071899 +v 2200.000000000 700.000000000 100.008071899 +v 2300.000000000 700.000000000 100.008071899 +v 2400.000000000 700.000000000 100.008071899 +v 2500.000000000 700.000000000 100.008071899 +v 2600.000000000 700.000000000 100.008071899 +v 2700.000000000 700.000000000 100.008071899 +v 2800.000000000 700.000000000 100.008071899 +v 2900.000000000 700.000000000 100.008071899 +v 3000.000000000 700.000000000 100.008071899 +v 3100.000000000 700.000000000 100.008071899 +v 2300.000000000 100.000000000 100.008071899 +v 1200.000000000 100.000000000 100.008071899 +v 100.000000000 800.000000000 138.280807495 +v 200.000000000 800.000000000 128.911682129 +v 300.000000000 800.000000000 119.542564392 +v 400.000000000 800.000000000 113.278785706 +v 500.000000000 800.000000000 105.475601196 +v 600.000000000 800.000000000 100.777778625 +v 700.000000000 800.000000000 100.008071899 +v 800.000000000 800.000000000 100.008071899 +v 900.000000000 800.000000000 100.008071899 +v 1000.000000000 800.000000000 100.008071899 +v 1100.000000000 800.000000000 100.008071899 +v 1200.000000000 800.000000000 100.008071899 +v 1300.000000000 800.000000000 100.008071899 +v 1400.000000000 800.000000000 100.008071899 +v 1500.000000000 800.000000000 100.008071899 +v 1600.000000000 800.000000000 100.008071899 +v 1700.000000000 800.000000000 100.008071899 +v 1800.000000000 800.000000000 100.008071899 +v 1900.000000000 800.000000000 100.008071899 +v 2000.000000000 800.000000000 100.008071899 +v 2100.000000000 800.000000000 100.008071899 +v 2200.000000000 800.000000000 100.008071899 +v 2300.000000000 800.000000000 100.008071899 +v 2400.000000000 800.000000000 100.008071899 +v 2500.000000000 800.000000000 100.008071899 +v 2600.000000000 800.000000000 100.008071899 +v 2700.000000000 800.000000000 100.008071899 +v 2800.000000000 800.000000000 100.008071899 +v 2900.000000000 800.000000000 100.008071899 +v 3000.000000000 800.000000000 100.008071899 +v 3100.000000000 800.000000000 100.008071899 +v 2400.000000000 100.000000000 100.008071899 +v 200.000000000 100.000000000 100.008071899 +v 100.000000000 900.000000000 149.215866089 +v 200.000000000 900.000000000 138.280807495 +v 300.000000000 900.000000000 127.345741272 +v 400.000000000 900.000000000 118.746315002 +v 500.000000000 900.000000000 110.943138123 +v 600.000000000 900.000000000 104.679367065 +v 700.000000000 900.000000000 100.008071899 +v 800.000000000 900.000000000 100.008071899 +v 900.000000000 900.000000000 100.008071899 +v 1000.000000000 900.000000000 100.008071899 +v 1100.000000000 900.000000000 100.008071899 +v 1200.000000000 900.000000000 100.008071899 +v 1300.000000000 900.000000000 100.008071899 +v 1400.000000000 900.000000000 100.008071899 +v 1500.000000000 900.000000000 100.008071899 +v 1600.000000000 900.000000000 100.008071899 +v 1700.000000000 900.000000000 100.008071899 +v 1800.000000000 900.000000000 100.008071899 +v 1900.000000000 900.000000000 100.008071899 +v 2000.000000000 900.000000000 100.008071899 +v 2100.000000000 900.000000000 100.008071899 +v 2200.000000000 900.000000000 100.008071899 +v 2300.000000000 900.000000000 100.008071899 +v 2400.000000000 900.000000000 100.008071899 +v 2500.000000000 900.000000000 100.008071899 +v 2600.000000000 900.000000000 100.008071899 +v 2700.000000000 900.000000000 100.008071899 +v 2800.000000000 900.000000000 100.008071899 +v 2900.000000000 900.000000000 100.008071899 +v 3000.000000000 900.000000000 100.008071899 +v 3100.000000000 900.000000000 100.008071899 +v 2500.000000000 100.000000000 100.008071899 +v 1300.000000000 100.000000000 100.008071899 +v 100.000000000 1000.000000000 160.150939941 +v 200.000000000 1000.000000000 146.880218506 +v 300.000000000 1000.000000000 135.945159912 +v 400.000000000 1000.000000000 125.779792786 +v 500.000000000 1000.000000000 115.614440918 +v 600.000000000 1000.000000000 109.377197266 +v 700.000000000 1000.000000000 103.909660339 +v 800.000000000 1000.000000000 100.008071899 +v 900.000000000 1000.000000000 100.008071899 +v 1000.000000000 1000.000000000 100.008071899 +v 1100.000000000 1000.000000000 100.008071899 +v 1200.000000000 1000.000000000 100.008071899 +v 1300.000000000 1000.000000000 100.008071899 +v 1400.000000000 1000.000000000 100.008071899 +v 1500.000000000 1000.000000000 100.008071899 +v 1600.000000000 1000.000000000 100.008071899 +v 1700.000000000 1000.000000000 100.008071899 +v 1800.000000000 1000.000000000 100.008071899 +v 1900.000000000 1000.000000000 100.008071899 +v 2000.000000000 1000.000000000 100.008071899 +v 2100.000000000 1000.000000000 100.008071899 +v 2200.000000000 1000.000000000 100.008071899 +v 2300.000000000 1000.000000000 100.008071899 +v 2400.000000000 1000.000000000 100.008071899 +v 2500.000000000 1000.000000000 100.008071899 +v 2600.000000000 1000.000000000 100.008071899 +v 2700.000000000 1000.000000000 100.008071899 +v 2800.000000000 1000.000000000 100.008071899 +v 2900.000000000 1000.000000000 100.008071899 +v 3000.000000000 1000.000000000 100.008071899 +v 3100.000000000 1000.000000000 100.008071899 +v 2600.000000000 100.000000000 100.008071899 +v 700.000000000 100.000000000 100.008071899 +v 100.000000000 1100.000000000 172.651947021 +v 200.000000000 1100.000000000 158.585006714 +v 300.000000000 1100.000000000 145.314285278 +v 400.000000000 1100.000000000 133.582977295 +v 500.000000000 1100.000000000 122.647903442 +v 600.000000000 1100.000000000 113.278785706 +v 700.000000000 1100.000000000 107.041549683 +v 800.000000000 1100.000000000 100.777778625 +v 900.000000000 1100.000000000 100.008071899 +v 1000.000000000 1100.000000000 100.008071899 +v 1100.000000000 1100.000000000 100.008071899 +v 1200.000000000 1100.000000000 100.008071899 +v 1300.000000000 1100.000000000 100.008071899 +v 1400.000000000 1100.000000000 100.008071899 +v 1500.000000000 1100.000000000 100.008071899 +v 1600.000000000 1100.000000000 100.008071899 +v 1700.000000000 1100.000000000 100.008071899 +v 1800.000000000 1100.000000000 100.008071899 +v 1900.000000000 1100.000000000 100.008071899 +v 2000.000000000 1100.000000000 100.008071899 +v 2100.000000000 1100.000000000 100.008071899 +v 2200.000000000 1100.000000000 100.008071899 +v 2300.000000000 1100.000000000 100.008071899 +v 2400.000000000 1100.000000000 100.008071899 +v 2500.000000000 1100.000000000 100.008071899 +v 2600.000000000 1100.000000000 100.008071899 +v 2700.000000000 1100.000000000 100.008071899 +v 2800.000000000 1100.000000000 100.008071899 +v 2900.000000000 1100.000000000 100.008071899 +v 3000.000000000 1100.000000000 100.008071899 +v 3100.000000000 1100.000000000 100.008071899 +v 2700.000000000 100.000000000 100.008071899 +v 5.296733856 1200.000000000 200.000000000 +v 100.000000000 1200.000000000 185.949203491 +v 1400.000000000 100.000000000 100.008071899 +v 200.000000000 1200.000000000 170.316284180 +v 300.000000000 1200.000000000 155.479644775 +v 400.000000000 1200.000000000 142.182388306 +v 500.000000000 1200.000000000 130.477630615 +v 600.000000000 1200.000000000 119.542564392 +v 700.000000000 1200.000000000 110.943138123 +v 800.000000000 1200.000000000 103.909660339 +v 900.000000000 1200.000000000 100.008071899 +v 1000.000000000 1200.000000000 100.008071899 +v 1100.000000000 1200.000000000 100.008071899 +v 1200.000000000 1200.000000000 100.008071899 +v 1300.000000000 1200.000000000 100.008071899 +v 1400.000000000 1200.000000000 100.008071899 +v 1500.000000000 1200.000000000 100.008071899 +v 1600.000000000 1200.000000000 100.008071899 +v 1700.000000000 1200.000000000 100.008071899 +v 1800.000000000 1200.000000000 100.008071899 +v 1900.000000000 1200.000000000 100.008071899 +v 2000.000000000 1200.000000000 100.008071899 +v 2100.000000000 1200.000000000 100.008071899 +v 2200.000000000 1200.000000000 100.008071899 +v 2300.000000000 1200.000000000 100.008071899 +v 2400.000000000 1200.000000000 100.008071899 +v 2500.000000000 1200.000000000 100.008071899 +v 2600.000000000 1200.000000000 100.008071899 +v 2700.000000000 1200.000000000 100.008071899 +v 2800.000000000 1200.000000000 100.008071899 +v 2900.000000000 1200.000000000 100.008071899 +v 3000.000000000 1200.000000000 100.008071899 +v 3100.000000000 1200.000000000 100.008071899 +v 2800.000000000 100.000000000 100.008071899 +v 90.975067139 1300.000000000 200.000000000 +v 100.000000000 1300.000000000 198.450210571 +v 200.000000000 1300.000000000 182.021072388 +v 300.000000000 1300.000000000 166.414703369 +v 400.000000000 1300.000000000 151.551513672 +v 500.000000000 1300.000000000 137.511108398 +v 600.000000000 1300.000000000 125.779792786 +v 700.000000000 1300.000000000 114.844726562 +v 800.000000000 1300.000000000 106.245300293 +v 900.000000000 1300.000000000 100.008071899 +v 1000.000000000 1300.000000000 100.008071899 +v 1100.000000000 1300.000000000 100.008071899 +v 1200.000000000 1300.000000000 100.008071899 +v 1300.000000000 1300.000000000 100.008071899 +v 1400.000000000 1300.000000000 100.008071899 +v 1500.000000000 1300.000000000 100.008071899 +v 1600.000000000 1300.000000000 100.008071899 +v 1700.000000000 1300.000000000 100.008071899 +v 1800.000000000 1300.000000000 100.008071899 +v 1900.000000000 1300.000000000 100.008071899 +v 2000.000000000 1300.000000000 100.008071899 +v 2100.000000000 1300.000000000 100.008071899 +v 2200.000000000 1300.000000000 100.008071899 +v 2300.000000000 1300.000000000 100.008071899 +v 2400.000000000 1300.000000000 100.008071899 +v 2500.000000000 1300.000000000 100.008071899 +v 2600.000000000 1300.000000000 100.008071899 +v 2700.000000000 1300.000000000 100.008071899 +v 2800.000000000 1300.000000000 100.008071899 +v 2900.000000000 1300.000000000 100.008071899 +v 3000.000000000 1300.000000000 100.008071899 +v 3100.000000000 1300.000000000 100.008071899 +v 400.000000000 100.000000000 100.008071899 +v 100.000000000 1311.038085938 200.000000000 +v 172.736984253 1400.000000000 200.000000000 +v 200.000000000 1400.000000000 195.318313599 +v 300.000000000 1400.000000000 178.119476318 +v 400.000000000 1400.000000000 161.716873169 +v 500.000000000 1400.000000000 146.083984375 +v 600.000000000 1400.000000000 132.043563843 +v 700.000000000 1400.000000000 120.312263489 +v 800.000000000 1400.000000000 110.146888733 +v 900.000000000 1400.000000000 102.343711853 +v 1000.000000000 1400.000000000 100.008071899 +v 1100.000000000 1400.000000000 100.008071899 +v 1200.000000000 1400.000000000 100.008071899 +v 1300.000000000 1400.000000000 100.008071899 +v 1400.000000000 1400.000000000 100.008071899 +v 1500.000000000 1400.000000000 100.008071899 +v 1600.000000000 1400.000000000 100.008071899 +v 1700.000000000 1400.000000000 100.008071899 +v 1800.000000000 1400.000000000 100.008071899 +v 1900.000000000 1400.000000000 100.008071899 +v 2000.000000000 1400.000000000 100.008071899 +v 2100.000000000 1400.000000000 100.008071899 +v 2200.000000000 1400.000000000 100.008071899 +v 2300.000000000 1400.000000000 100.008071899 +v 2400.000000000 1400.000000000 100.008071899 +v 2500.000000000 1400.000000000 100.008071899 +v 2600.000000000 1400.000000000 100.008071899 +v 2700.000000000 1400.000000000 100.008071899 +v 2800.000000000 1400.000000000 100.008071899 +v 2900.000000000 1400.000000000 100.008071899 +v 3000.000000000 1400.000000000 100.008071899 +v 3100.000000000 1400.000000000 100.008071899 +v 2900.000000000 100.000000000 100.008071899 +v 200.000000000 1435.278320312 200.000000000 +v 247.800369263 1500.000000000 200.000000000 +v 300.000000000 1500.000000000 190.620483398 +v 400.000000000 1500.000000000 171.882247925 +v 500.000000000 1500.000000000 154.683395386 +v 600.000000000 1500.000000000 138.280807495 +v 700.000000000 1500.000000000 125.010093689 +v 800.000000000 1500.000000000 113.278785706 +v 900.000000000 1500.000000000 104.679367065 +v 1000.000000000 1500.000000000 100.008071899 +v 1100.000000000 1500.000000000 100.008071899 +v 1200.000000000 1500.000000000 100.008071899 +v 1300.000000000 1500.000000000 100.008071899 +v 1400.000000000 1500.000000000 100.008071899 +v 1500.000000000 1500.000000000 100.008071899 +v 1600.000000000 1500.000000000 100.008071899 +v 1700.000000000 1500.000000000 100.008071899 +v 1800.000000000 1500.000000000 100.008071899 +v 1900.000000000 1500.000000000 100.008071899 +v 2000.000000000 1500.000000000 100.008071899 +v 2100.000000000 1500.000000000 100.008071899 +v 2200.000000000 1500.000000000 100.008071899 +v 2300.000000000 1500.000000000 100.008071899 +v 2400.000000000 1500.000000000 100.008071899 +v 2500.000000000 1500.000000000 100.008071899 +v 2600.000000000 1500.000000000 100.008071899 +v 2700.000000000 1500.000000000 100.008071899 +v 2800.000000000 1500.000000000 100.008071899 +v 2900.000000000 1500.000000000 100.008071899 +v 3000.000000000 1500.000000000 100.008071899 +v 3100.000000000 1500.000000000 100.008071899 +v 1500.000000000 100.000000000 100.008071899 +v 300.000000000 1570.537231445 200.000000000 +v 319.270050049 1600.000000000 200.000000000 +v 400.000000000 1600.000000000 183.587005615 +v 500.000000000 1600.000000000 164.052520752 +v 600.000000000 1600.000000000 146.083984375 +v 700.000000000 1600.000000000 130.477630615 +v 800.000000000 1600.000000000 116.410675049 +v 900.000000000 1600.000000000 105.475601196 +v 1000.000000000 1600.000000000 100.008071899 +v 1100.000000000 1600.000000000 100.008071899 +v 1200.000000000 1600.000000000 100.008071899 +v 1300.000000000 1600.000000000 100.008071899 +v 1400.000000000 1600.000000000 100.008071899 +v 1500.000000000 1600.000000000 100.008071899 +v 1600.000000000 1600.000000000 100.008071899 +v 1700.000000000 1600.000000000 100.008071899 +v 1800.000000000 1600.000000000 100.008071899 +v 1900.000000000 1600.000000000 100.008071899 +v 2000.000000000 1600.000000000 100.008071899 +v 2100.000000000 1600.000000000 100.008071899 +v 2200.000000000 1600.000000000 100.008071899 +v 2300.000000000 1600.000000000 100.008071899 +v 2400.000000000 1600.000000000 100.008071899 +v 2500.000000000 1600.000000000 100.008071899 +v 2600.000000000 1600.000000000 100.008071899 +v 2700.000000000 1600.000000000 100.008071899 +v 2800.000000000 1600.000000000 100.008071899 +v 2900.000000000 1600.000000000 100.008071899 +v 3000.000000000 1600.000000000 100.008071899 +v 3100.000000000 1600.000000000 100.008071899 +v 3000.000000000 100.000000000 100.008071899 +v 378.593261719 1700.000000000 200.000000000 +v 400.000000000 1700.000000000 195.318313599 +v 500.000000000 1700.000000000 174.217895508 +v 600.000000000 1700.000000000 154.683395386 +v 700.000000000 1700.000000000 135.148910522 +v 800.000000000 1700.000000000 119.542564392 +v 900.000000000 1700.000000000 106.245300293 +v 1000.000000000 1700.000000000 100.008071899 +v 1100.000000000 1700.000000000 100.008071899 +v 1200.000000000 1700.000000000 100.008071899 +v 1300.000000000 1700.000000000 100.008071899 +v 1400.000000000 1700.000000000 100.008071899 +v 1500.000000000 1700.000000000 100.008071899 +v 1600.000000000 1700.000000000 100.008071899 +v 1700.000000000 1700.000000000 100.008071899 +v 1800.000000000 1700.000000000 100.008071899 +v 1900.000000000 1700.000000000 100.008071899 +v 2000.000000000 1700.000000000 100.008071899 +v 2100.000000000 1700.000000000 100.008071899 +v 2200.000000000 1700.000000000 100.008071899 +v 2300.000000000 1700.000000000 100.008071899 +v 2400.000000000 1700.000000000 100.008071899 +v 2500.000000000 1700.000000000 100.008071899 +v 2600.000000000 1700.000000000 100.008071899 +v 2700.000000000 1700.000000000 100.008071899 +v 2800.000000000 1700.000000000 100.008071899 +v 2900.000000000 1700.000000000 100.008071899 +v 3000.000000000 1700.000000000 100.008071899 +v 3100.000000000 1700.000000000 100.008071899 +v 800.000000000 100.000000000 100.008071899 +v 400.000000000 1735.278320312 200.000000000 +v 436.648742676 1800.000000000 200.000000000 +v 500.000000000 1800.000000000 185.152954102 +v 600.000000000 1800.000000000 163.282821655 +v 700.000000000 1800.000000000 141.412689209 +v 800.000000000 1800.000000000 122.647903442 +v 900.000000000 1800.000000000 107.811264038 +v 1000.000000000 1800.000000000 100.008071899 +v 1100.000000000 1800.000000000 100.008071899 +v 1200.000000000 1800.000000000 100.008071899 +v 1300.000000000 1800.000000000 100.008071899 +v 1400.000000000 1800.000000000 100.008071899 +v 1500.000000000 1800.000000000 100.008071899 +v 1600.000000000 1800.000000000 100.008071899 +v 1700.000000000 1800.000000000 100.008071899 +v 1800.000000000 1800.000000000 100.008071899 +v 1900.000000000 1800.000000000 100.008071899 +v 2000.000000000 1800.000000000 100.008071899 +v 2100.000000000 1800.000000000 100.008071899 +v 2200.000000000 1800.000000000 100.008071899 +v 2300.000000000 1800.000000000 100.008071899 +v 2400.000000000 1800.000000000 100.008071899 +v 2500.000000000 1800.000000000 100.008071899 +v 2600.000000000 1800.000000000 100.008071899 +v 2700.000000000 1800.000000000 100.008071899 +v 2800.000000000 1800.000000000 100.008071899 +v 2900.000000000 1800.000000000 100.008071899 +v 3000.000000000 1800.000000000 100.008071899 +v 3100.000000000 1800.000000000 100.008071899 +v 3100.000000000 100.000000000 100.008071899 +v 490.318542480 1900.000000000 200.000000000 +v 500.000000000 1900.000000000 197.653961182 +v 600.000000000 1900.000000000 172.651947021 +v 700.000000000 1900.000000000 148.446166992 +v 800.000000000 1900.000000000 125.010093689 +v 900.000000000 1900.000000000 107.811264038 +v 1000.000000000 1900.000000000 100.008071899 +v 1100.000000000 1900.000000000 100.008071899 +v 1200.000000000 1900.000000000 100.008071899 +v 1300.000000000 1900.000000000 100.008071899 +v 1400.000000000 1900.000000000 100.008071899 +v 1500.000000000 1900.000000000 100.008071899 +v 1600.000000000 1900.000000000 100.008071899 +v 1700.000000000 1900.000000000 100.008071899 +v 1800.000000000 1900.000000000 100.008071899 +v 1900.000000000 1900.000000000 100.008071899 +v 2000.000000000 1900.000000000 100.008071899 +v 2100.000000000 1900.000000000 100.008071899 +v 2200.000000000 1900.000000000 100.008071899 +v 2300.000000000 1900.000000000 100.008071899 +v 2400.000000000 1900.000000000 100.008071899 +v 2500.000000000 1900.000000000 100.008071899 +v 2600.000000000 1900.000000000 100.008071899 +v 2700.000000000 1900.000000000 100.008071899 +v 2800.000000000 1900.000000000 100.008071899 +v 2900.000000000 1900.000000000 100.008071899 +v 3000.000000000 1900.000000000 100.008071899 +v 3100.000000000 1900.000000000 100.008071899 +v 1600.000000000 100.000000000 100.008071899 +v 500.000000000 1918.766845703 200.000000000 +v 538.222595215 2000.000000000 200.000000000 +v 600.000000000 2000.000000000 183.587005615 +v 700.000000000 2000.000000000 156.249343872 +v 800.000000000 2000.000000000 128.115432739 +v 900.000000000 2000.000000000 108.580955505 +v 1000.000000000 2000.000000000 100.008071899 +v 1100.000000000 2000.000000000 100.008071899 +v 1200.000000000 2000.000000000 100.008071899 +v 1300.000000000 2000.000000000 100.008071899 +v 1400.000000000 2000.000000000 100.008071899 +v 1500.000000000 2000.000000000 100.008071899 +v 1600.000000000 2000.000000000 100.008071899 +v 1700.000000000 2000.000000000 100.008071899 +v 1800.000000000 2000.000000000 100.008071899 +v 1900.000000000 2000.000000000 100.008071899 +v 2000.000000000 2000.000000000 100.008071899 +v 2100.000000000 2000.000000000 100.008071899 +v 2200.000000000 2000.000000000 100.008071899 +v 2300.000000000 2000.000000000 100.008071899 +v 2400.000000000 2000.000000000 100.008071899 +v 2500.000000000 2000.000000000 100.008071899 +v 2600.000000000 2000.000000000 100.008071899 +v 2700.000000000 2000.000000000 100.008071899 +v 2800.000000000 2000.000000000 100.008071899 +v 2900.000000000 2000.000000000 100.008071899 +v 3000.000000000 2000.000000000 100.008071899 +v 3100.000000000 2000.000000000 100.008071899 +v 100.000000000 100.000000000 100.008071899 +v 581.047607422 2100.000000000 200.000000000 +v 600.000000000 2100.000000000 194.522064209 +v 700.000000000 2100.000000000 164.848770142 +v 800.000000000 2100.000000000 134.379211426 +v 900.000000000 2100.000000000 112.509086609 +v 1000.000000000 2100.000000000 100.008071899 +v 1100.000000000 2100.000000000 100.008071899 +v 1200.000000000 2100.000000000 100.008071899 +v 1300.000000000 2100.000000000 100.008071899 +v 1400.000000000 2100.000000000 100.008071899 +v 1500.000000000 2100.000000000 100.008071899 +v 1600.000000000 2100.000000000 100.008071899 +v 1700.000000000 2100.000000000 100.008071899 +v 1800.000000000 2100.000000000 100.008071899 +v 1900.000000000 2100.000000000 100.008071899 +v 2000.000000000 2100.000000000 100.008071899 +v 2100.000000000 2100.000000000 100.008071899 +v 2200.000000000 2100.000000000 100.008071899 +v 2300.000000000 2100.000000000 100.008071899 +v 2400.000000000 2100.000000000 100.008071899 +v 2500.000000000 2100.000000000 100.008071899 +v 2600.000000000 2100.000000000 100.008071899 +v 2700.000000000 2100.000000000 100.008071899 +v 2800.000000000 2100.000000000 100.008071899 +v 2900.000000000 2100.000000000 100.008071899 +v 3000.000000000 2100.000000000 100.008071899 +v 3100.000000000 2100.000000000 100.008071899 +v 1700.000000000 100.000000000 100.008071899 +v 600.000000000 2146.694824219 200.000000000 +v 620.000732422 2200.000000000 200.000000000 +v 700.000000000 2200.000000000 174.987609863 +v 800.000000000 2200.000000000 143.748336792 +v 900.000000000 2200.000000000 117.180374146 +v 1000.000000000 2200.000000000 103.113410950 +v 1100.000000000 2200.000000000 100.008071899 +v 1200.000000000 2200.000000000 100.008071899 +v 1300.000000000 2200.000000000 100.008071899 +v 1400.000000000 2200.000000000 100.008071899 +v 1500.000000000 2200.000000000 100.008071899 +v 1600.000000000 2200.000000000 100.008071899 +v 1700.000000000 2200.000000000 100.008071899 +v 1800.000000000 2200.000000000 100.008071899 +v 1900.000000000 2200.000000000 100.008071899 +v 2000.000000000 2200.000000000 100.008071899 +v 2100.000000000 2200.000000000 100.008071899 +v 2200.000000000 2200.000000000 100.008071899 +v 2300.000000000 2200.000000000 100.008071899 +v 2400.000000000 2200.000000000 100.008071899 +v 2500.000000000 2200.000000000 100.008071899 +v 2600.000000000 2200.000000000 100.008071899 +v 2700.000000000 2200.000000000 100.008071899 +v 2800.000000000 2200.000000000 100.008071899 +v 2900.000000000 2200.000000000 100.008071899 +v 3000.000000000 2200.000000000 100.008071899 +v 3100.000000000 2200.000000000 100.008071899 +v 900.000000000 100.000000000 100.008071899 +v 661.892395020 2300.000000000 200.000000000 +v 700.000000000 2300.000000000 187.488601685 +v 800.000000000 2300.000000000 153.913696289 +v 900.000000000 2300.000000000 125.010093689 +v 1000.000000000 2300.000000000 107.811264038 +v 1100.000000000 2300.000000000 100.008071899 +v 1200.000000000 2300.000000000 100.008071899 +v 1300.000000000 2300.000000000 100.008071899 +v 1400.000000000 2300.000000000 100.008071899 +v 1500.000000000 2300.000000000 100.008071899 +v 1600.000000000 2300.000000000 100.008071899 +v 1700.000000000 2300.000000000 100.008071899 +v 1800.000000000 2300.000000000 100.008071899 +v 1900.000000000 2300.000000000 100.008071899 +v 2000.000000000 2300.000000000 100.008071899 +v 2100.000000000 2300.000000000 100.008071899 +v 2200.000000000 2300.000000000 100.008071899 +v 2300.000000000 2300.000000000 100.008071899 +v 2400.000000000 2300.000000000 100.008071899 +v 2500.000000000 2300.000000000 100.008071899 +v 2600.000000000 2300.000000000 100.008071899 +v 2700.000000000 2300.000000000 100.008071899 +v 2800.000000000 2300.000000000 100.008071899 +v 2900.000000000 2300.000000000 100.008071899 +v 3000.000000000 2300.000000000 100.008071899 +v 3100.000000000 2300.000000000 100.008071899 +v 100.000000000 200.000000000 100.008071899 +v 700.000000000 2394.090087891 200.000000000 +v 702.286376953 2400.000000000 200.000000000 +v 800.000000000 2400.000000000 166.414703369 +v 900.000000000 2400.000000000 133.582977295 +v 1000.000000000 2400.000000000 111.712852478 +v 1100.000000000 2400.000000000 100.008071899 +v 1200.000000000 2400.000000000 100.008071899 +v 1300.000000000 2400.000000000 100.008071899 +v 1400.000000000 2400.000000000 100.008071899 +v 1500.000000000 2400.000000000 100.008071899 +v 1600.000000000 2400.000000000 100.008071899 +v 1700.000000000 2400.000000000 100.008071899 +v 1800.000000000 2400.000000000 100.008071899 +v 1900.000000000 2400.000000000 100.008071899 +v 2000.000000000 2400.000000000 100.008071899 +v 2100.000000000 2400.000000000 100.008071899 +v 2200.000000000 2400.000000000 100.008071899 +v 2300.000000000 2400.000000000 100.008071899 +v 2400.000000000 2400.000000000 100.008071899 +v 2500.000000000 2400.000000000 100.008071899 +v 2600.000000000 2400.000000000 100.008071899 +v 2700.000000000 2400.000000000 100.008071899 +v 2800.000000000 2400.000000000 100.008071899 +v 2900.000000000 2400.000000000 100.008071899 +v 3000.000000000 2400.000000000 100.008071899 +v 3100.000000000 2400.000000000 100.008071899 +v 200.000000000 200.000000000 100.008071899 +v 736.972595215 2500.000000000 200.000000000 +v 800.000000000 2500.000000000 177.349777222 +v 900.000000000 2500.000000000 142.182388306 +v 1000.000000000 2500.000000000 117.976615906 +v 1100.000000000 2500.000000000 104.679367065 +v 1200.000000000 2500.000000000 100.008071899 +v 1300.000000000 2500.000000000 100.008071899 +v 1400.000000000 2500.000000000 100.008071899 +v 1500.000000000 2500.000000000 100.008071899 +v 1600.000000000 2500.000000000 100.008071899 +v 1700.000000000 2500.000000000 100.008071899 +v 1800.000000000 2500.000000000 100.008071899 +v 1900.000000000 2500.000000000 100.008071899 +v 2000.000000000 2500.000000000 100.008071899 +v 2100.000000000 2500.000000000 100.008071899 +v 2200.000000000 2500.000000000 100.008071899 +v 2300.000000000 2500.000000000 100.008071899 +v 2400.000000000 2500.000000000 100.008071899 +v 2500.000000000 2500.000000000 100.008071899 +v 2600.000000000 2500.000000000 100.008071899 +v 2700.000000000 2500.000000000 100.008071899 +v 2800.000000000 2500.000000000 100.008071899 +v 2900.000000000 2500.000000000 100.008071899 +v 3000.000000000 2500.000000000 100.008071899 +v 3100.000000000 2500.000000000 100.008071899 +v 300.000000000 200.000000000 100.008071899 +v 771.421264648 2600.000000000 200.000000000 +v 800.000000000 2600.000000000 189.054550171 +v 900.000000000 2600.000000000 151.551513672 +v 1000.000000000 2600.000000000 122.647903442 +v 1100.000000000 2600.000000000 107.041549683 +v 1200.000000000 2600.000000000 100.008071899 +v 1300.000000000 2600.000000000 100.008071899 +v 1400.000000000 2600.000000000 100.008071899 +v 1500.000000000 2600.000000000 100.008071899 +v 1600.000000000 2600.000000000 100.008071899 +v 1700.000000000 2600.000000000 100.008071899 +v 1800.000000000 2600.000000000 100.008071899 +v 1900.000000000 2600.000000000 100.008071899 +v 2000.000000000 2600.000000000 100.008071899 +v 2100.000000000 2600.000000000 100.008071899 +v 2200.000000000 2600.000000000 100.008071899 +v 2300.000000000 2600.000000000 100.008071899 +v 2400.000000000 2600.000000000 100.008071899 +v 2500.000000000 2600.000000000 100.008071899 +v 2600.000000000 2600.000000000 100.008071899 +v 2700.000000000 2600.000000000 100.008071899 +v 2800.000000000 2600.000000000 100.008071899 +v 2900.000000000 2600.000000000 100.008071899 +v 3000.000000000 2600.000000000 100.008071899 +v 3100.000000000 2600.000000000 100.008071899 +v 400.000000000 200.000000000 100.008071899 +v 800.000000000 2693.301269531 200.000000000 +v 802.011474609 2700.000000000 200.000000000 +v 900.000000000 2700.000000000 161.716873169 +v 1000.000000000 2700.000000000 130.477630615 +v 1100.000000000 2700.000000000 110.146888733 +v 1200.000000000 2700.000000000 102.343711853 +v 1300.000000000 2700.000000000 100.008071899 +v 1400.000000000 2700.000000000 100.008071899 +v 1500.000000000 2700.000000000 100.008071899 +v 1600.000000000 2700.000000000 100.008071899 +v 1700.000000000 2700.000000000 100.008071899 +v 1800.000000000 2700.000000000 100.008071899 +v 1900.000000000 2700.000000000 100.008071899 +v 2000.000000000 2700.000000000 100.008071899 +v 2100.000000000 2700.000000000 100.008071899 +v 2200.000000000 2700.000000000 100.008071899 +v 2300.000000000 2700.000000000 100.008071899 +v 2400.000000000 2700.000000000 100.008071899 +v 2500.000000000 2700.000000000 100.008071899 +v 2600.000000000 2700.000000000 100.008071899 +v 2700.000000000 2700.000000000 100.008071899 +v 2800.000000000 2700.000000000 100.008071899 +v 2900.000000000 2700.000000000 100.008071899 +v 3000.000000000 2700.000000000 100.008071899 +v 3100.000000000 2700.000000000 100.008071899 +v 500.000000000 200.000000000 100.008071899 +v 832.090270996 2800.000000000 200.000000000 +v 900.000000000 2800.000000000 171.882247925 +v 1000.000000000 2800.000000000 137.511108398 +v 1100.000000000 2800.000000000 114.844726562 +v 1200.000000000 2800.000000000 104.679367065 +v 1300.000000000 2800.000000000 100.008071899 +v 1400.000000000 2800.000000000 100.008071899 +v 1500.000000000 2800.000000000 100.008071899 +v 1600.000000000 2800.000000000 100.008071899 +v 1700.000000000 2800.000000000 100.008071899 +v 1800.000000000 2800.000000000 100.008071899 +v 1900.000000000 2800.000000000 100.008071899 +v 2000.000000000 2800.000000000 100.008071899 +v 2100.000000000 2800.000000000 100.008071899 +v 2200.000000000 2800.000000000 100.008071899 +v 2300.000000000 2800.000000000 100.008071899 +v 2400.000000000 2800.000000000 100.008071899 +v 2500.000000000 2800.000000000 100.008071899 +v 2600.000000000 2800.000000000 100.008071899 +v 2700.000000000 2800.000000000 100.008071899 +v 2800.000000000 2800.000000000 100.008071899 +v 2900.000000000 2800.000000000 100.008071899 +v 3000.000000000 2800.000000000 100.008071899 +v 3100.000000000 2800.000000000 100.008071899 +v 600.000000000 200.000000000 100.008071899 +v 858.159912109 2900.000000000 200.000000000 +v 900.000000000 2900.000000000 182.021072388 +v 1000.000000000 2900.000000000 145.314285278 +v 1100.000000000 2900.000000000 118.746315002 +v 1200.000000000 2900.000000000 105.475601196 +v 1300.000000000 2900.000000000 100.008071899 +v 1400.000000000 2900.000000000 100.008071899 +v 1500.000000000 2900.000000000 100.008071899 +v 1600.000000000 2900.000000000 100.008071899 +v 1700.000000000 2900.000000000 100.008071899 +v 1800.000000000 2900.000000000 100.008071899 +v 1900.000000000 2900.000000000 100.008071899 +v 2000.000000000 2900.000000000 100.008071899 +v 2100.000000000 2900.000000000 100.008071899 +v 2200.000000000 2900.000000000 100.008071899 +v 2300.000000000 2900.000000000 100.008071899 +v 2400.000000000 2900.000000000 100.008071899 +v 2500.000000000 2900.000000000 100.008071899 +v 2600.000000000 2900.000000000 100.008071899 +v 2700.000000000 2900.000000000 100.008071899 +v 2800.000000000 2900.000000000 100.008071899 +v 2900.000000000 2900.000000000 100.008071899 +v 3000.000000000 2900.000000000 100.008071899 +v 3100.000000000 2900.000000000 100.008071899 +v 700.000000000 200.000000000 100.008071899 +v 884.184082031 3000.000000000 200.000000000 +v 900.000000000 3000.000000000 192.956130981 +v 1000.000000000 3000.000000000 153.913696289 +v 1100.000000000 3000.000000000 124.213851929 +v 1200.000000000 3000.000000000 106.245300293 +v 1300.000000000 3000.000000000 100.008071899 +v 1400.000000000 3000.000000000 100.008071899 +v 1500.000000000 3000.000000000 100.008071899 +v 1600.000000000 3000.000000000 100.008071899 +v 1700.000000000 3000.000000000 100.008071899 +v 1800.000000000 3000.000000000 100.008071899 +v 1900.000000000 3000.000000000 100.008071899 +v 2000.000000000 3000.000000000 100.008071899 +v 2100.000000000 3000.000000000 100.008071899 +v 2200.000000000 3000.000000000 100.008071899 +v 2300.000000000 3000.000000000 100.008071899 +v 2400.000000000 3000.000000000 100.008071899 +v 2500.000000000 3000.000000000 100.008071899 +v 2600.000000000 3000.000000000 100.008071899 +v 2700.000000000 3000.000000000 100.008071899 +v 2800.000000000 3000.000000000 100.008071899 +v 2900.000000000 3000.000000000 100.008071899 +v 3000.000000000 3000.000000000 100.008071899 +v 3100.000000000 3000.000000000 100.008071899 +v 800.000000000 200.000000000 100.008071899 +v 900.000000000 3064.259521484 200.000000000 +v 909.462097168 3100.000000000 200.000000000 +v 1000.000000000 3100.000000000 162.513122559 +v 1100.000000000 3100.000000000 128.911682129 +v 1200.000000000 3100.000000000 108.580955505 +v 1300.000000000 3100.000000000 100.008071899 +v 1400.000000000 3100.000000000 100.008071899 +v 1500.000000000 3100.000000000 100.008071899 +v 1600.000000000 3100.000000000 100.008071899 +v 1700.000000000 3100.000000000 100.008071899 +v 1800.000000000 3100.000000000 100.008071899 +v 1900.000000000 3100.000000000 100.008071899 +v 2000.000000000 3100.000000000 100.008071899 +v 2100.000000000 3100.000000000 100.008071899 +v 2200.000000000 3100.000000000 100.008071899 +v 2300.000000000 3100.000000000 100.008071899 +v 2400.000000000 3100.000000000 100.008071899 +v 2500.000000000 3100.000000000 100.008071899 +v 2600.000000000 3100.000000000 100.008071899 +v 2700.000000000 3100.000000000 100.008071899 +v 2800.000000000 3100.000000000 100.008071899 +v 2900.000000000 3100.000000000 100.008071899 +v 3000.000000000 3100.000000000 100.008071899 +v 3100.000000000 3100.000000000 100.008071899 +v 900.000000000 200.000000000 100.008071899 +v 1000.000000000 200.000000000 100.008071899 +v 1100.000000000 200.000000000 100.008071899 +v 1200.000000000 200.000000000 100.008071899 +v 1300.000000000 200.000000000 100.008071899 +v 1400.000000000 200.000000000 100.008071899 +v 1500.000000000 200.000000000 100.008071899 +v 1600.000000000 200.000000000 100.008071899 +v 1700.000000000 200.000000000 100.008071899 +v 1800.000000000 200.000000000 100.008071899 +v 1900.000000000 200.000000000 100.008071899 +v 2000.000000000 200.000000000 100.008071899 +v 2100.000000000 200.000000000 100.008071899 +v 2200.000000000 200.000000000 100.008071899 +v 2300.000000000 200.000000000 100.008071899 +v 2400.000000000 200.000000000 100.008071899 +v 2500.000000000 200.000000000 100.008071899 +v 2600.000000000 200.000000000 100.008071899 +v 2700.000000000 200.000000000 100.008071899 +v 2800.000000000 200.000000000 100.008071899 +v 2900.000000000 200.000000000 100.008071899 +v 3000.000000000 200.000000000 100.008071899 +v 3100.000000000 200.000000000 100.008071899 +v 1800.000000000 100.000000000 100.008071899 +v 500.000000000 100.000000000 100.008071899 +v 100.000000000 300.000000000 103.113410950 +v 200.000000000 300.000000000 100.008071899 +v 300.000000000 300.000000000 100.008071899 +v 100.000000000 1400.000000000 212.490600586 +v 400.000000000 300.000000000 100.008071899 +v 100.000000000 1500.000000000 228.123519897 +v 200.000000000 1500.000000000 208.589035034 +v 500.000000000 300.000000000 100.008071899 +v 100.000000000 1600.000000000 243.756408691 +v 200.000000000 1600.000000000 223.425704956 +v 300.000000000 1600.000000000 203.917739868 +v 600.000000000 300.000000000 100.008071899 +v 100.000000000 1700.000000000 259.362762451 +v 200.000000000 1700.000000000 238.288879395 +v 300.000000000 1700.000000000 217.188446045 +v 700.000000000 300.000000000 100.008071899 +v 100.000000000 1800.000000000 275.791900635 +v 200.000000000 1800.000000000 253.125518799 +v 300.000000000 1800.000000000 231.255386353 +v 400.000000000 1800.000000000 208.589035034 +v 69.978759766 1900.000000000 300.000000000 +v 100.000000000 1900.000000000 292.964202881 +v 800.000000000 300.000000000 100.008071899 +v 200.000000000 1900.000000000 270.324371338 +v 300.000000000 1900.000000000 246.092056274 +v 400.000000000 1900.000000000 221.886276245 +v 100.000000000 1937.494628906 300.000000000 +v 148.402297974 2000.000000000 300.000000000 +v 200.000000000 2000.000000000 287.496673584 +v 300.000000000 2000.000000000 262.494659424 +v 400.000000000 2000.000000000 235.926696777 +v 500.000000000 2000.000000000 210.154968262 +v 200.000000000 2069.584472656 300.000000000 +v 220.570678711 2100.000000000 300.000000000 +v 300.000000000 2100.000000000 278.897247314 +v 400.000000000 2100.000000000 251.559585571 +v 500.000000000 2100.000000000 223.425704956 +v 291.447875977 2200.000000000 300.000000000 +v 300.000000000 2200.000000000 297.662048340 +v 400.000000000 2200.000000000 267.192474365 +v 500.000000000 2200.000000000 237.492630005 +v 600.000000000 2200.000000000 206.253387451 +v 300.000000000 2212.476806641 300.000000000 +v 351.194061279 2300.000000000 300.000000000 +v 400.000000000 2300.000000000 284.364776611 +v 500.000000000 2300.000000000 252.355834961 +v 600.000000000 2300.000000000 220.320343018 +v 400.000000000 2387.014404297 300.000000000 +v 406.949676514 2400.000000000 300.000000000 +v 500.000000000 2400.000000000 268.758422852 +v 600.000000000 2400.000000000 235.156982422 +v 700.000000000 2400.000000000 200.785858154 +v 456.827270508 2500.000000000 300.000000000 +v 500.000000000 2500.000000000 285.161041260 +v 600.000000000 2500.000000000 249.993652344 +v 700.000000000 2500.000000000 213.286880493 +v 500.000000000 2590.467285156 300.000000000 +v 504.259765625 2600.000000000 300.000000000 +v 600.000000000 2600.000000000 264.856842041 +v 700.000000000 2600.000000000 227.353805542 +v 548.989135742 2700.000000000 300.000000000 +v 600.000000000 2700.000000000 280.463195801 +v 700.000000000 2700.000000000 242.190475464 +v 800.000000000 2700.000000000 200.785858154 +v 584.337951660 2800.000000000 300.000000000 +v 600.000000000 2800.000000000 293.760437012 +v 700.000000000 2800.000000000 254.691482544 +v 800.000000000 2800.000000000 213.286880493 +v 600.000000000 2847.017578125 300.000000000 +v 617.303222656 2900.000000000 300.000000000 +v 700.000000000 2900.000000000 266.396240234 +v 800.000000000 2900.000000000 224.991638184 +v 651.851013184 3000.000000000 300.000000000 +v 700.000000000 3000.000000000 279.693481445 +v 800.000000000 3000.000000000 237.492630005 +v 683.626464844 3100.000000000 300.000000000 +v 700.000000000 3100.000000000 292.964202881 +v 800.000000000 3100.000000000 249.223953247 +v 900.000000000 3100.000000000 203.917739868 +v 700.000000000 3152.911865234 300.000000000 +v 900.000000000 300.000000000 100.008071899 +v 1000.000000000 300.000000000 100.008071899 +v 1100.000000000 300.000000000 100.008071899 +v 1200.000000000 300.000000000 100.008071899 +v 1300.000000000 300.000000000 100.008071899 +v 100.000000000 2000.000000000 311.729003906 +v 1400.000000000 300.000000000 100.008071899 +v 100.000000000 2100.000000000 331.236938477 +v 200.000000000 2100.000000000 305.465209961 +v 1500.000000000 300.000000000 100.008071899 +v 100.000000000 2200.000000000 351.567657471 +v 200.000000000 2200.000000000 324.999694824 +v 1600.000000000 300.000000000 100.008071899 +v 100.000000000 2300.000000000 371.102142334 +v 200.000000000 2300.000000000 344.534179688 +v 300.000000000 2300.000000000 316.400268555 +v 59.364845276 2400.000000000 400.000000000 +v 100.000000000 2400.000000000 389.840393066 +v 1700.000000000 300.000000000 100.008071899 +v 200.000000000 2400.000000000 363.272430420 +v 300.000000000 2400.000000000 334.368835449 +v 400.000000000 2400.000000000 302.333343506 +v 100.000000000 2454.141845703 400.000000000 +v 132.389373779 2500.000000000 400.000000000 +v 200.000000000 2500.000000000 382.037231445 +v 300.000000000 2500.000000000 353.133605957 +v 400.000000000 2500.000000000 319.532165527 +v 194.292922974 2600.000000000 400.000000000 +v 200.000000000 2600.000000000 398.439819336 +v 300.000000000 2600.000000000 369.536193848 +v 400.000000000 2600.000000000 337.500701904 +v 500.000000000 2600.000000000 301.563629150 +v 200.000000000 2609.511718750 400.000000000 +v 251.351425171 2700.000000000 400.000000000 +v 300.000000000 2700.000000000 385.938812256 +v 400.000000000 2700.000000000 353.903320312 +v 500.000000000 2700.000000000 318.762481689 +v 300.000000000 2781.756835938 400.000000000 +v 309.794250488 2800.000000000 400.000000000 +v 400.000000000 2800.000000000 371.102142334 +v 500.000000000 2800.000000000 333.599121094 +v 356.107482910 2900.000000000 400.000000000 +v 400.000000000 2900.000000000 385.938812256 +v 500.000000000 2900.000000000 347.666076660 +v 600.000000000 2900.000000000 307.031158447 +v 400.000000000 2999.958984375 400.000000000 +v 400.015411377 3000.000000000 400.000000000 +v 500.000000000 3000.000000000 362.502716064 +v 600.000000000 3000.000000000 321.867828369 +v 438.780639648 3100.000000000 400.000000000 +v 500.000000000 3100.000000000 376.569671631 +v 600.000000000 3100.000000000 335.934753418 +v 1800.000000000 300.000000000 100.008071899 +v 1900.000000000 300.000000000 100.008071899 +v 2000.000000000 300.000000000 100.008071899 +v 2100.000000000 300.000000000 100.008071899 +v 2200.000000000 300.000000000 100.008071899 +v 2300.000000000 300.000000000 100.008071899 +v 100.000000000 2500.000000000 408.605194092 +v 2400.000000000 300.000000000 100.008071899 +v 100.000000000 2600.000000000 425.777496338 +v 2500.000000000 300.000000000 100.008071899 +v 100.000000000 2700.000000000 443.746032715 +v 200.000000000 2700.000000000 414.842407227 +v 2600.000000000 300.000000000 100.008071899 +v 100.000000000 2800.000000000 462.510772705 +v 200.000000000 2800.000000000 433.580627441 +v 300.000000000 2800.000000000 403.137634277 +v 9.695672035 2900.000000000 500.000000000 +v 100.000000000 2900.000000000 478.117187500 +v 2700.000000000 300.000000000 100.008071899 +v 200.000000000 2900.000000000 449.213562012 +v 300.000000000 2900.000000000 417.974273682 +v 74.179939270 3000.000000000 500.000000000 +v 100.000000000 3000.000000000 493.750061035 +v 200.000000000 3000.000000000 464.846435547 +v 300.000000000 3000.000000000 433.580627441 +v 400.000000000 3000.000000000 400.005767822 +v 100.000000000 3039.979248047 500.000000000 +v 132.462936401 3100.000000000 500.000000000 +v 200.000000000 3100.000000000 480.479339600 +v 100.000000000 3039.979248047 500.000000000 +v 200.000000000 3100.000000000 480.479339600 +v 200.000000000 3100.000000000 480.479339600 +v 300.000000000 3100.000000000 448.443847656 +v 200.000000000 3100.000000000 480.479339600 +v 400.000000000 3100.000000000 414.842407227 +v 2800.000000000 300.000000000 100.008071899 +v 2900.000000000 300.000000000 100.008071899 +v 3000.000000000 300.000000000 100.008071899 +v 200.000000000 3100.000000000 480.479339600 +v 300.000000000 3200.000000000 464.050201416 +v 3100.000000000 300.000000000 100.008071899 +v 300.000000000 3200.000000000 464.050201416 +v 1900.000000000 100.000000000 100.008071899 +v 1000.000000000 100.000000000 100.008071899 +v 100.000000000 400.000000000 107.811264038 +v 100.000000000 3100.000000000 509.382965088 +v 0.000000000 3000.000000000 517.955810547 +v 100.000000000 3039.979248047 500.000000000 +v 0.000000000 3000.000000000 517.955810547 +v 100.000000000 3039.979248047 500.000000000 +v 200.000000000 400.000000000 103.909660339 +v 300.000000000 400.000000000 100.008071899 +f 2 1 677 +f 677 1 3 +f 677 3 298 +f 298 3 4 +f 298 4 166 +f 166 4 5 +f 166 5 463 +f 463 5 6 +f 463 6 989 +f 989 6 7 +f 989 7 232 +f 232 7 8 +f 232 8 364 +f 364 8 9 +f 364 9 589 +f 589 9 10 +f 589 10 733 +f 733 10 11 +f 733 11 1165 +f 1165 11 12 +f 1165 12 199 +f 199 12 13 +f 199 13 265 +f 265 13 14 +f 265 14 331 +f 331 14 15 +f 331 15 399 +f 399 15 16 +f 399 16 528 +f 528 16 17 +f 528 17 648 +f 648 17 18 +f 648 18 705 +f 705 18 19 +f 705 19 988 +f 988 19 20 +f 988 20 1164 +f 1164 20 21 +f 1164 21 165 +f 165 21 22 +f 165 22 198 +f 198 22 23 +f 198 23 231 +f 231 23 24 +f 231 24 264 +f 264 24 25 +f 264 25 297 +f 297 25 26 +f 297 26 330 +f 330 26 27 +f 330 27 363 +f 363 27 28 +f 363 28 396 +f 396 28 29 +f 396 29 430 +f 430 29 30 +f 430 30 496 +f 496 30 31 +f 496 31 559 +f 559 31 32 +f 559 32 619 +f 619 32 33 +f 619 33 34 +f 34 33 35 +f 36 2 760 +f 760 2 677 +f 760 677 787 +f 787 677 298 +f 787 298 813 +f 813 298 166 +f 813 166 839 +f 839 166 463 +f 839 463 865 +f 865 463 989 +f 865 989 890 +f 890 989 232 +f 890 232 915 +f 915 232 364 +f 915 364 940 +f 940 364 589 +f 940 589 965 +f 965 589 733 +f 965 733 966 +f 966 733 1165 +f 966 1165 967 +f 967 1165 199 +f 967 199 968 +f 968 199 265 +f 968 265 969 +f 969 265 331 +f 969 331 970 +f 970 331 399 +f 970 399 971 +f 971 399 528 +f 971 528 972 +f 972 528 648 +f 972 648 973 +f 973 648 705 +f 973 705 974 +f 974 705 988 +f 974 988 975 +f 975 988 1164 +f 975 1164 976 +f 976 1164 165 +f 976 165 977 +f 977 165 198 +f 977 198 978 +f 978 198 231 +f 978 231 979 +f 979 231 264 +f 979 264 980 +f 980 264 297 +f 980 297 981 +f 981 297 330 +f 981 330 982 +f 982 330 363 +f 982 363 983 +f 983 363 396 +f 983 396 984 +f 984 396 430 +f 984 430 985 +f 985 430 496 +f 985 496 986 +f 986 496 559 +f 986 559 987 +f 987 559 619 +f 987 619 37 +f 37 619 34 +f 38 36 990 +f 990 36 760 +f 990 760 991 +f 991 760 787 +f 991 787 992 +f 992 787 813 +f 992 813 994 +f 994 813 839 +f 994 839 997 +f 997 839 865 +f 997 865 1001 +f 1001 865 890 +f 1001 890 1005 +f 1005 890 915 +f 1005 915 1012 +f 1012 915 940 +f 1012 940 1070 +f 1070 940 965 +f 1070 965 1071 +f 1071 965 966 +f 1071 966 1072 +f 1072 966 967 +f 1072 967 1073 +f 1073 967 968 +f 1073 968 1074 +f 1074 968 969 +f 1074 969 1076 +f 1076 969 970 +f 1076 970 1079 +f 1079 970 971 +f 1079 971 1082 +f 1082 971 972 +f 1082 972 1088 +f 1088 972 973 +f 1088 973 1122 +f 1122 973 974 +f 1122 974 1123 +f 1123 974 975 +f 1123 975 1124 +f 1124 975 976 +f 1124 976 1125 +f 1125 976 977 +f 1125 977 1126 +f 1126 977 978 +f 1126 978 1127 +f 1127 978 979 +f 1127 979 1129 +f 1129 979 980 +f 1129 980 1131 +f 1131 980 981 +f 1131 981 1134 +f 1134 981 982 +f 1134 982 1140 +f 1140 982 983 +f 1140 983 1157 +f 1157 983 984 +f 1157 984 1158 +f 1158 984 985 +f 1158 985 1159 +f 1159 985 986 +f 1159 986 1162 +f 1162 986 987 +f 1162 987 39 +f 39 987 37 +f 40 38 1166 +f 1166 38 990 +f 1166 990 1172 +f 1172 990 991 +f 1172 991 1173 +f 1173 991 992 +f 1173 992 137 +f 137 992 994 +f 137 994 138 +f 138 994 997 +f 138 997 139 +f 139 997 1001 +f 139 1001 140 +f 140 1001 1005 +f 140 1005 141 +f 141 1005 1012 +f 141 1012 142 +f 142 1012 1070 +f 142 1070 143 +f 143 1070 1071 +f 143 1071 144 +f 144 1071 1072 +f 144 1072 145 +f 145 1072 1073 +f 145 1073 146 +f 146 1073 1074 +f 146 1074 147 +f 147 1074 1076 +f 147 1076 148 +f 148 1076 1079 +f 148 1079 149 +f 149 1079 1082 +f 149 1082 150 +f 150 1082 1088 +f 150 1088 151 +f 151 1088 1122 +f 151 1122 152 +f 152 1122 1123 +f 152 1123 153 +f 153 1123 1124 +f 153 1124 154 +f 154 1124 1125 +f 154 1125 155 +f 155 1125 1126 +f 155 1126 156 +f 156 1126 1127 +f 156 1127 157 +f 157 1127 1129 +f 157 1129 158 +f 158 1129 1131 +f 158 1131 159 +f 159 1131 1134 +f 159 1134 160 +f 160 1134 1140 +f 160 1140 161 +f 161 1140 1157 +f 161 1157 162 +f 162 1157 1158 +f 162 1158 163 +f 163 1158 1159 +f 163 1159 164 +f 164 1159 1162 +f 164 1162 41 +f 41 1162 39 +f 42 40 167 +f 167 40 1166 +f 167 1166 168 +f 168 1166 1172 +f 168 1172 169 +f 169 1172 1173 +f 169 1173 170 +f 170 1173 137 +f 170 137 171 +f 171 137 138 +f 171 138 172 +f 172 138 139 +f 172 139 173 +f 173 139 140 +f 173 140 174 +f 174 140 141 +f 174 141 175 +f 175 141 142 +f 175 142 176 +f 176 142 143 +f 176 143 177 +f 177 143 144 +f 177 144 178 +f 178 144 145 +f 178 145 179 +f 179 145 146 +f 179 146 180 +f 180 146 147 +f 180 147 181 +f 181 147 148 +f 181 148 182 +f 182 148 149 +f 182 149 183 +f 183 149 150 +f 183 150 184 +f 184 150 151 +f 184 151 185 +f 185 151 152 +f 185 152 186 +f 186 152 153 +f 186 153 187 +f 187 153 154 +f 187 154 188 +f 188 154 155 +f 188 155 189 +f 189 155 156 +f 189 156 190 +f 190 156 157 +f 190 157 191 +f 191 157 158 +f 191 158 192 +f 192 158 159 +f 192 159 193 +f 193 159 160 +f 193 160 194 +f 194 160 161 +f 194 161 195 +f 195 161 162 +f 195 162 196 +f 196 162 163 +f 196 163 197 +f 197 163 164 +f 197 164 43 +f 43 164 41 +f 44 42 200 +f 200 42 167 +f 200 167 201 +f 201 167 168 +f 201 168 202 +f 202 168 169 +f 202 169 203 +f 203 169 170 +f 203 170 204 +f 204 170 171 +f 204 171 205 +f 205 171 172 +f 205 172 206 +f 206 172 173 +f 206 173 207 +f 207 173 174 +f 207 174 208 +f 208 174 175 +f 208 175 209 +f 209 175 176 +f 209 176 210 +f 210 176 177 +f 210 177 211 +f 211 177 178 +f 211 178 212 +f 212 178 179 +f 212 179 213 +f 213 179 180 +f 213 180 214 +f 214 180 181 +f 214 181 215 +f 215 181 182 +f 215 182 216 +f 216 182 183 +f 216 183 217 +f 217 183 184 +f 217 184 218 +f 218 184 185 +f 218 185 219 +f 219 185 186 +f 219 186 220 +f 220 186 187 +f 220 187 221 +f 221 187 188 +f 221 188 222 +f 222 188 189 +f 222 189 223 +f 223 189 190 +f 223 190 224 +f 224 190 191 +f 224 191 225 +f 225 191 192 +f 225 192 226 +f 226 192 193 +f 226 193 227 +f 227 193 194 +f 227 194 228 +f 228 194 195 +f 228 195 229 +f 229 195 196 +f 229 196 230 +f 230 196 197 +f 230 197 45 +f 45 197 43 +f 46 44 233 +f 233 44 200 +f 233 200 234 +f 234 200 201 +f 234 201 235 +f 235 201 202 +f 235 202 236 +f 236 202 203 +f 236 203 237 +f 237 203 204 +f 237 204 238 +f 238 204 205 +f 238 205 239 +f 239 205 206 +f 239 206 240 +f 240 206 207 +f 240 207 241 +f 241 207 208 +f 241 208 242 +f 242 208 209 +f 242 209 243 +f 243 209 210 +f 243 210 244 +f 244 210 211 +f 244 211 245 +f 245 211 212 +f 245 212 246 +f 246 212 213 +f 246 213 247 +f 247 213 214 +f 247 214 248 +f 248 214 215 +f 248 215 249 +f 249 215 216 +f 249 216 250 +f 250 216 217 +f 250 217 251 +f 251 217 218 +f 251 218 252 +f 252 218 219 +f 252 219 253 +f 253 219 220 +f 253 220 254 +f 254 220 221 +f 254 221 255 +f 255 221 222 +f 255 222 256 +f 256 222 223 +f 256 223 257 +f 257 223 224 +f 257 224 258 +f 258 224 225 +f 258 225 259 +f 259 225 226 +f 259 226 260 +f 260 226 227 +f 260 227 261 +f 261 227 228 +f 261 228 262 +f 262 228 229 +f 262 229 263 +f 263 229 230 +f 263 230 47 +f 47 230 45 +f 48 46 266 +f 266 46 233 +f 266 233 267 +f 267 233 234 +f 267 234 268 +f 268 234 235 +f 268 235 269 +f 269 235 236 +f 269 236 270 +f 270 236 237 +f 270 237 271 +f 271 237 238 +f 271 238 272 +f 272 238 239 +f 272 239 273 +f 273 239 240 +f 273 240 274 +f 274 240 241 +f 274 241 275 +f 275 241 242 +f 275 242 276 +f 276 242 243 +f 276 243 277 +f 277 243 244 +f 277 244 278 +f 278 244 245 +f 278 245 279 +f 279 245 246 +f 279 246 280 +f 280 246 247 +f 280 247 281 +f 281 247 248 +f 281 248 282 +f 282 248 249 +f 282 249 283 +f 283 249 250 +f 283 250 284 +f 284 250 251 +f 284 251 285 +f 285 251 252 +f 285 252 286 +f 286 252 253 +f 286 253 287 +f 287 253 254 +f 287 254 288 +f 288 254 255 +f 288 255 289 +f 289 255 256 +f 289 256 290 +f 290 256 257 +f 290 257 291 +f 291 257 258 +f 291 258 292 +f 292 258 259 +f 292 259 293 +f 293 259 260 +f 293 260 294 +f 294 260 261 +f 294 261 295 +f 295 261 262 +f 295 262 296 +f 296 262 263 +f 296 263 49 +f 49 263 47 +f 50 48 299 +f 299 48 266 +f 299 266 300 +f 300 266 267 +f 300 267 301 +f 301 267 268 +f 301 268 302 +f 302 268 269 +f 302 269 303 +f 303 269 270 +f 303 270 304 +f 304 270 271 +f 304 271 305 +f 305 271 272 +f 305 272 306 +f 306 272 273 +f 306 273 307 +f 307 273 274 +f 307 274 308 +f 308 274 275 +f 308 275 309 +f 309 275 276 +f 309 276 310 +f 310 276 277 +f 310 277 311 +f 311 277 278 +f 311 278 312 +f 312 278 279 +f 312 279 313 +f 313 279 280 +f 313 280 314 +f 314 280 281 +f 314 281 315 +f 315 281 282 +f 315 282 316 +f 316 282 283 +f 316 283 317 +f 317 283 284 +f 317 284 318 +f 318 284 285 +f 318 285 319 +f 319 285 286 +f 319 286 320 +f 320 286 287 +f 320 287 321 +f 321 287 288 +f 321 288 322 +f 322 288 289 +f 322 289 323 +f 323 289 290 +f 323 290 324 +f 324 290 291 +f 324 291 325 +f 325 291 292 +f 325 292 326 +f 326 292 293 +f 326 293 327 +f 327 293 294 +f 327 294 328 +f 328 294 295 +f 328 295 329 +f 329 295 296 +f 329 296 51 +f 51 296 49 +f 52 50 332 +f 332 50 299 +f 332 299 333 +f 333 299 300 +f 333 300 334 +f 334 300 301 +f 334 301 335 +f 335 301 302 +f 335 302 336 +f 336 302 303 +f 336 303 337 +f 337 303 304 +f 337 304 338 +f 338 304 305 +f 338 305 339 +f 339 305 306 +f 339 306 340 +f 340 306 307 +f 340 307 341 +f 341 307 308 +f 341 308 342 +f 342 308 309 +f 342 309 343 +f 343 309 310 +f 343 310 344 +f 344 310 311 +f 344 311 345 +f 345 311 312 +f 345 312 346 +f 346 312 313 +f 346 313 347 +f 347 313 314 +f 347 314 348 +f 348 314 315 +f 348 315 349 +f 349 315 316 +f 349 316 350 +f 350 316 317 +f 350 317 351 +f 351 317 318 +f 351 318 352 +f 352 318 319 +f 352 319 353 +f 353 319 320 +f 353 320 354 +f 354 320 321 +f 354 321 355 +f 355 321 322 +f 355 322 356 +f 356 322 323 +f 356 323 357 +f 357 323 324 +f 357 324 358 +f 358 324 325 +f 358 325 359 +f 359 325 326 +f 359 326 360 +f 360 326 327 +f 360 327 361 +f 361 327 328 +f 361 328 362 +f 362 328 329 +f 362 329 53 +f 53 329 51 +f 54 52 365 +f 365 52 332 +f 365 332 366 +f 366 332 333 +f 366 333 367 +f 367 333 334 +f 367 334 368 +f 368 334 335 +f 368 335 369 +f 369 335 336 +f 369 336 370 +f 370 336 337 +f 370 337 371 +f 371 337 338 +f 371 338 372 +f 372 338 339 +f 372 339 373 +f 373 339 340 +f 373 340 374 +f 374 340 341 +f 374 341 375 +f 375 341 342 +f 375 342 376 +f 376 342 343 +f 376 343 377 +f 377 343 344 +f 377 344 378 +f 378 344 345 +f 378 345 379 +f 379 345 346 +f 379 346 380 +f 380 346 347 +f 380 347 381 +f 381 347 348 +f 381 348 382 +f 382 348 349 +f 382 349 383 +f 383 349 350 +f 383 350 384 +f 384 350 351 +f 384 351 385 +f 385 351 352 +f 385 352 386 +f 386 352 353 +f 386 353 387 +f 387 353 354 +f 387 354 388 +f 388 354 355 +f 388 355 389 +f 389 355 356 +f 389 356 390 +f 390 356 357 +f 390 357 391 +f 391 357 358 +f 391 358 392 +f 392 358 359 +f 392 359 393 +f 393 359 360 +f 393 360 394 +f 394 360 361 +f 394 361 395 +f 395 361 362 +f 395 362 55 +f 55 362 53 +f 398 397 56 +f 54 398 56 +f 365 398 54 +f 398 365 400 +f 400 365 366 +f 400 366 401 +f 401 366 367 +f 401 367 402 +f 402 367 368 +f 402 368 403 +f 403 368 369 +f 403 369 404 +f 404 369 370 +f 404 370 405 +f 405 370 371 +f 405 371 406 +f 406 371 372 +f 406 372 407 +f 407 372 373 +f 407 373 408 +f 408 373 374 +f 408 374 409 +f 409 374 375 +f 409 375 410 +f 410 375 376 +f 410 376 411 +f 411 376 377 +f 411 377 412 +f 412 377 378 +f 412 378 413 +f 413 378 379 +f 413 379 414 +f 414 379 380 +f 414 380 415 +f 415 380 381 +f 415 381 416 +f 416 381 382 +f 416 382 417 +f 417 382 383 +f 417 383 418 +f 418 383 384 +f 418 384 419 +f 419 384 385 +f 419 385 420 +f 420 385 386 +f 420 386 421 +f 421 386 387 +f 421 387 422 +f 422 387 388 +f 422 388 423 +f 423 388 389 +f 423 389 424 +f 424 389 390 +f 424 390 425 +f 425 390 391 +f 425 391 426 +f 426 391 392 +f 426 392 427 +f 427 392 393 +f 427 393 428 +f 428 393 394 +f 428 394 429 +f 429 394 395 +f 429 395 57 +f 57 395 55 +f 397 398 431 +f 431 398 432 +f 432 398 433 +f 433 398 400 +f 433 400 434 +f 434 400 401 +f 434 401 435 +f 435 401 402 +f 435 402 436 +f 436 402 403 +f 436 403 437 +f 437 403 404 +f 437 404 438 +f 438 404 405 +f 438 405 439 +f 439 405 406 +f 439 406 440 +f 440 406 407 +f 440 407 441 +f 441 407 408 +f 441 408 442 +f 442 408 409 +f 442 409 443 +f 443 409 410 +f 443 410 444 +f 444 410 411 +f 444 411 445 +f 445 411 412 +f 445 412 446 +f 446 412 413 +f 446 413 447 +f 447 413 414 +f 447 414 448 +f 448 414 415 +f 448 415 449 +f 449 415 416 +f 449 416 450 +f 450 416 417 +f 450 417 451 +f 451 417 418 +f 451 418 452 +f 452 418 419 +f 452 419 453 +f 453 419 420 +f 453 420 454 +f 454 420 421 +f 454 421 455 +f 455 421 422 +f 455 422 456 +f 456 422 423 +f 456 423 457 +f 457 423 424 +f 457 424 458 +f 458 424 425 +f 458 425 459 +f 459 425 426 +f 459 426 460 +f 460 426 427 +f 460 427 461 +f 461 427 428 +f 461 428 462 +f 462 428 429 +f 462 429 58 +f 58 429 57 +f 431 432 464 +f 466 465 464 +f 432 466 464 +f 433 466 432 +f 466 433 467 +f 467 433 434 +f 467 434 468 +f 468 434 435 +f 468 435 469 +f 469 435 436 +f 469 436 470 +f 470 436 437 +f 470 437 471 +f 471 437 438 +f 471 438 472 +f 472 438 439 +f 472 439 473 +f 473 439 440 +f 473 440 474 +f 474 440 441 +f 474 441 475 +f 475 441 442 +f 475 442 476 +f 476 442 443 +f 476 443 477 +f 477 443 444 +f 477 444 478 +f 478 444 445 +f 478 445 479 +f 479 445 446 +f 479 446 480 +f 480 446 447 +f 480 447 481 +f 481 447 448 +f 481 448 482 +f 482 448 449 +f 482 449 483 +f 483 449 450 +f 483 450 484 +f 484 450 451 +f 484 451 485 +f 485 451 452 +f 485 452 486 +f 486 452 453 +f 486 453 487 +f 487 453 454 +f 487 454 488 +f 488 454 455 +f 488 455 489 +f 489 455 456 +f 489 456 490 +f 490 456 457 +f 490 457 491 +f 491 457 458 +f 491 458 492 +f 492 458 459 +f 492 459 493 +f 493 459 460 +f 493 460 494 +f 494 460 461 +f 494 461 495 +f 495 461 462 +f 495 462 59 +f 59 462 58 +f 465 466 497 +f 499 498 497 +f 466 499 497 +f 467 499 466 +f 499 467 500 +f 500 467 468 +f 500 468 501 +f 501 468 469 +f 501 469 502 +f 502 469 470 +f 502 470 503 +f 503 470 471 +f 503 471 504 +f 504 471 472 +f 504 472 505 +f 505 472 473 +f 505 473 506 +f 506 473 474 +f 506 474 507 +f 507 474 475 +f 507 475 508 +f 508 475 476 +f 508 476 509 +f 509 476 477 +f 509 477 510 +f 510 477 478 +f 510 478 511 +f 511 478 479 +f 511 479 512 +f 512 479 480 +f 512 480 513 +f 513 480 481 +f 513 481 514 +f 514 481 482 +f 514 482 515 +f 515 482 483 +f 515 483 516 +f 516 483 484 +f 516 484 517 +f 517 484 485 +f 517 485 518 +f 518 485 486 +f 518 486 519 +f 519 486 487 +f 519 487 520 +f 520 487 488 +f 520 488 521 +f 521 488 489 +f 521 489 522 +f 522 489 490 +f 522 490 523 +f 523 490 491 +f 523 491 524 +f 524 491 492 +f 524 492 525 +f 525 492 493 +f 525 493 526 +f 526 493 494 +f 526 494 527 +f 527 494 495 +f 527 495 60 +f 60 495 59 +f 498 499 529 +f 531 530 529 +f 499 531 529 +f 500 531 499 +f 531 500 532 +f 532 500 501 +f 532 501 533 +f 533 501 502 +f 533 502 534 +f 534 502 503 +f 534 503 535 +f 535 503 504 +f 535 504 536 +f 536 504 505 +f 536 505 537 +f 537 505 506 +f 537 506 538 +f 538 506 507 +f 538 507 539 +f 539 507 508 +f 539 508 540 +f 540 508 509 +f 540 509 541 +f 541 509 510 +f 541 510 542 +f 542 510 511 +f 542 511 543 +f 543 511 512 +f 543 512 544 +f 544 512 513 +f 544 513 545 +f 545 513 514 +f 545 514 546 +f 546 514 515 +f 546 515 547 +f 547 515 516 +f 547 516 548 +f 548 516 517 +f 548 517 549 +f 549 517 518 +f 549 518 550 +f 550 518 519 +f 550 519 551 +f 551 519 520 +f 551 520 552 +f 552 520 521 +f 552 521 553 +f 553 521 522 +f 553 522 554 +f 554 522 523 +f 554 523 555 +f 555 523 524 +f 555 524 556 +f 556 524 525 +f 556 525 557 +f 557 525 526 +f 557 526 558 +f 558 526 527 +f 558 527 61 +f 61 527 60 +f 530 531 560 +f 560 531 561 +f 561 531 562 +f 562 531 532 +f 562 532 563 +f 563 532 533 +f 563 533 564 +f 564 533 534 +f 564 534 565 +f 565 534 535 +f 565 535 566 +f 566 535 536 +f 566 536 567 +f 567 536 537 +f 567 537 568 +f 568 537 538 +f 568 538 569 +f 569 538 539 +f 569 539 570 +f 570 539 540 +f 570 540 571 +f 571 540 541 +f 571 541 572 +f 572 541 542 +f 572 542 573 +f 573 542 543 +f 573 543 574 +f 574 543 544 +f 574 544 575 +f 575 544 545 +f 575 545 576 +f 576 545 546 +f 576 546 577 +f 577 546 547 +f 577 547 578 +f 578 547 548 +f 578 548 579 +f 579 548 549 +f 579 549 580 +f 580 549 550 +f 580 550 581 +f 581 550 551 +f 581 551 582 +f 582 551 552 +f 582 552 583 +f 583 552 553 +f 583 553 584 +f 584 553 554 +f 584 554 585 +f 585 554 555 +f 585 555 586 +f 586 555 556 +f 586 556 587 +f 587 556 557 +f 587 557 588 +f 588 557 558 +f 588 558 62 +f 62 558 61 +f 560 561 590 +f 592 591 590 +f 561 592 590 +f 562 592 561 +f 592 562 593 +f 593 562 563 +f 593 563 594 +f 594 563 564 +f 594 564 595 +f 595 564 565 +f 595 565 596 +f 596 565 566 +f 596 566 597 +f 597 566 567 +f 597 567 598 +f 598 567 568 +f 598 568 599 +f 599 568 569 +f 599 569 600 +f 600 569 570 +f 600 570 601 +f 601 570 571 +f 601 571 602 +f 602 571 572 +f 602 572 603 +f 603 572 573 +f 603 573 604 +f 604 573 574 +f 604 574 605 +f 605 574 575 +f 605 575 606 +f 606 575 576 +f 606 576 607 +f 607 576 577 +f 607 577 608 +f 608 577 578 +f 608 578 609 +f 609 578 579 +f 609 579 610 +f 610 579 580 +f 610 580 611 +f 611 580 581 +f 611 581 612 +f 612 581 582 +f 612 582 613 +f 613 582 583 +f 613 583 614 +f 614 583 584 +f 614 584 615 +f 615 584 585 +f 615 585 616 +f 616 585 586 +f 616 586 617 +f 617 586 587 +f 617 587 618 +f 618 587 588 +f 618 588 63 +f 63 588 62 +f 591 592 620 +f 620 592 621 +f 621 592 622 +f 622 592 593 +f 622 593 623 +f 623 593 594 +f 623 594 624 +f 624 594 595 +f 624 595 625 +f 625 595 596 +f 625 596 626 +f 626 596 597 +f 626 597 627 +f 627 597 598 +f 627 598 628 +f 628 598 599 +f 628 599 629 +f 629 599 600 +f 629 600 630 +f 630 600 601 +f 630 601 631 +f 631 601 602 +f 631 602 632 +f 632 602 603 +f 632 603 633 +f 633 603 604 +f 633 604 634 +f 634 604 605 +f 634 605 635 +f 635 605 606 +f 635 606 636 +f 636 606 607 +f 636 607 637 +f 637 607 608 +f 637 608 638 +f 638 608 609 +f 638 609 639 +f 639 609 610 +f 639 610 640 +f 640 610 611 +f 640 611 641 +f 641 611 612 +f 641 612 642 +f 642 612 613 +f 642 613 643 +f 643 613 614 +f 643 614 644 +f 644 614 615 +f 644 615 645 +f 645 615 616 +f 645 616 646 +f 646 616 617 +f 646 617 647 +f 647 617 618 +f 647 618 64 +f 64 618 63 +f 620 621 649 +f 651 650 649 +f 621 651 649 +f 622 651 621 +f 651 622 652 +f 652 622 623 +f 652 623 653 +f 653 623 624 +f 653 624 654 +f 654 624 625 +f 654 625 655 +f 655 625 626 +f 655 626 656 +f 656 626 627 +f 656 627 657 +f 657 627 628 +f 657 628 658 +f 658 628 629 +f 658 629 659 +f 659 629 630 +f 659 630 660 +f 660 630 631 +f 660 631 661 +f 661 631 632 +f 661 632 662 +f 662 632 633 +f 662 633 663 +f 663 633 634 +f 663 634 664 +f 664 634 635 +f 664 635 665 +f 665 635 636 +f 665 636 666 +f 666 636 637 +f 666 637 667 +f 667 637 638 +f 667 638 668 +f 668 638 639 +f 668 639 669 +f 669 639 640 +f 669 640 670 +f 670 640 641 +f 670 641 671 +f 671 641 642 +f 671 642 672 +f 672 642 643 +f 672 643 673 +f 673 643 644 +f 673 644 674 +f 674 644 645 +f 674 645 675 +f 675 645 646 +f 675 646 676 +f 676 646 647 +f 676 647 65 +f 65 647 64 +f 650 651 678 +f 678 651 679 +f 679 651 680 +f 680 651 652 +f 680 652 681 +f 681 652 653 +f 681 653 682 +f 682 653 654 +f 682 654 683 +f 683 654 655 +f 683 655 684 +f 684 655 656 +f 684 656 685 +f 685 656 657 +f 685 657 686 +f 686 657 658 +f 686 658 687 +f 687 658 659 +f 687 659 688 +f 688 659 660 +f 688 660 689 +f 689 660 661 +f 689 661 690 +f 690 661 662 +f 690 662 691 +f 691 662 663 +f 691 663 692 +f 692 663 664 +f 692 664 693 +f 693 664 665 +f 693 665 694 +f 694 665 666 +f 694 666 695 +f 695 666 667 +f 695 667 696 +f 696 667 668 +f 696 668 697 +f 697 668 669 +f 697 669 698 +f 698 669 670 +f 698 670 699 +f 699 670 671 +f 699 671 700 +f 700 671 672 +f 700 672 701 +f 701 672 673 +f 701 673 702 +f 702 673 674 +f 702 674 703 +f 703 674 675 +f 703 675 704 +f 704 675 676 +f 704 676 66 +f 66 676 65 +f 678 679 706 +f 708 707 706 +f 679 708 706 +f 680 708 679 +f 708 680 709 +f 709 680 681 +f 709 681 710 +f 710 681 682 +f 710 682 711 +f 711 682 683 +f 711 683 712 +f 712 683 684 +f 712 684 713 +f 713 684 685 +f 713 685 714 +f 714 685 686 +f 714 686 715 +f 715 686 687 +f 715 687 716 +f 716 687 688 +f 716 688 717 +f 717 688 689 +f 717 689 718 +f 718 689 690 +f 718 690 719 +f 719 690 691 +f 719 691 720 +f 720 691 692 +f 720 692 721 +f 721 692 693 +f 721 693 722 +f 722 693 694 +f 722 694 723 +f 723 694 695 +f 723 695 724 +f 724 695 696 +f 724 696 725 +f 725 696 697 +f 725 697 726 +f 726 697 698 +f 726 698 727 +f 727 698 699 +f 727 699 728 +f 728 699 700 +f 728 700 729 +f 729 700 701 +f 729 701 730 +f 730 701 702 +f 730 702 731 +f 731 702 703 +f 731 703 732 +f 732 703 704 +f 732 704 67 +f 67 704 66 +f 707 708 734 +f 734 708 735 +f 735 708 736 +f 736 708 709 +f 736 709 737 +f 737 709 710 +f 737 710 738 +f 738 710 711 +f 738 711 739 +f 739 711 712 +f 739 712 740 +f 740 712 713 +f 740 713 741 +f 741 713 714 +f 741 714 742 +f 742 714 715 +f 742 715 743 +f 743 715 716 +f 743 716 744 +f 744 716 717 +f 744 717 745 +f 745 717 718 +f 745 718 746 +f 746 718 719 +f 746 719 747 +f 747 719 720 +f 747 720 748 +f 748 720 721 +f 748 721 749 +f 749 721 722 +f 749 722 750 +f 750 722 723 +f 750 723 751 +f 751 723 724 +f 751 724 752 +f 752 724 725 +f 752 725 753 +f 753 725 726 +f 753 726 754 +f 754 726 727 +f 754 727 755 +f 755 727 728 +f 755 728 756 +f 756 728 729 +f 756 729 757 +f 757 729 730 +f 757 730 758 +f 758 730 731 +f 758 731 759 +f 759 731 732 +f 759 732 68 +f 68 732 67 +f 734 735 761 +f 763 762 761 +f 735 763 761 +f 736 763 735 +f 763 736 764 +f 764 736 737 +f 764 737 765 +f 765 737 738 +f 765 738 766 +f 766 738 739 +f 766 739 767 +f 767 739 740 +f 767 740 768 +f 768 740 741 +f 768 741 769 +f 769 741 742 +f 769 742 770 +f 770 742 743 +f 770 743 771 +f 771 743 744 +f 771 744 772 +f 772 744 745 +f 772 745 773 +f 773 745 746 +f 773 746 774 +f 774 746 747 +f 774 747 775 +f 775 747 748 +f 775 748 776 +f 776 748 749 +f 776 749 777 +f 777 749 750 +f 777 750 778 +f 778 750 751 +f 778 751 779 +f 779 751 752 +f 779 752 780 +f 780 752 753 +f 780 753 781 +f 781 753 754 +f 781 754 782 +f 782 754 755 +f 782 755 783 +f 783 755 756 +f 783 756 784 +f 784 756 757 +f 784 757 785 +f 785 757 758 +f 785 758 786 +f 786 758 759 +f 786 759 69 +f 69 759 68 +f 762 763 788 +f 788 763 789 +f 789 763 790 +f 790 763 764 +f 790 764 791 +f 791 764 765 +f 791 765 792 +f 792 765 766 +f 792 766 793 +f 793 766 767 +f 793 767 794 +f 794 767 768 +f 794 768 795 +f 795 768 769 +f 795 769 796 +f 796 769 770 +f 796 770 797 +f 797 770 771 +f 797 771 798 +f 798 771 772 +f 798 772 799 +f 799 772 773 +f 799 773 800 +f 800 773 774 +f 800 774 801 +f 801 774 775 +f 801 775 802 +f 802 775 776 +f 802 776 803 +f 803 776 777 +f 803 777 804 +f 804 777 778 +f 804 778 805 +f 805 778 779 +f 805 779 806 +f 806 779 780 +f 806 780 807 +f 807 780 781 +f 807 781 808 +f 808 781 782 +f 808 782 809 +f 809 782 783 +f 809 783 810 +f 810 783 784 +f 810 784 811 +f 811 784 785 +f 811 785 812 +f 812 785 786 +f 812 786 70 +f 70 786 69 +f 788 789 814 +f 814 789 815 +f 815 789 816 +f 816 789 790 +f 816 790 817 +f 817 790 791 +f 817 791 818 +f 818 791 792 +f 818 792 819 +f 819 792 793 +f 819 793 820 +f 820 793 794 +f 820 794 821 +f 821 794 795 +f 821 795 822 +f 822 795 796 +f 822 796 823 +f 823 796 797 +f 823 797 824 +f 824 797 798 +f 824 798 825 +f 825 798 799 +f 825 799 826 +f 826 799 800 +f 826 800 827 +f 827 800 801 +f 827 801 828 +f 828 801 802 +f 828 802 829 +f 829 802 803 +f 829 803 830 +f 830 803 804 +f 830 804 831 +f 831 804 805 +f 831 805 832 +f 832 805 806 +f 832 806 833 +f 833 806 807 +f 833 807 834 +f 834 807 808 +f 834 808 835 +f 835 808 809 +f 835 809 836 +f 836 809 810 +f 836 810 837 +f 837 810 811 +f 837 811 838 +f 838 811 812 +f 838 812 71 +f 71 812 70 +f 814 815 840 +f 842 841 840 +f 815 842 840 +f 816 842 815 +f 842 816 843 +f 843 816 817 +f 843 817 844 +f 844 817 818 +f 844 818 845 +f 845 818 819 +f 845 819 846 +f 846 819 820 +f 846 820 847 +f 847 820 821 +f 847 821 848 +f 848 821 822 +f 848 822 849 +f 849 822 823 +f 849 823 850 +f 850 823 824 +f 850 824 851 +f 851 824 825 +f 851 825 852 +f 852 825 826 +f 852 826 853 +f 853 826 827 +f 853 827 854 +f 854 827 828 +f 854 828 855 +f 855 828 829 +f 855 829 856 +f 856 829 830 +f 856 830 857 +f 857 830 831 +f 857 831 858 +f 858 831 832 +f 858 832 859 +f 859 832 833 +f 859 833 860 +f 860 833 834 +f 860 834 861 +f 861 834 835 +f 861 835 862 +f 862 835 836 +f 862 836 863 +f 863 836 837 +f 863 837 864 +f 864 837 838 +f 864 838 72 +f 72 838 71 +f 841 842 866 +f 866 842 867 +f 867 842 868 +f 868 842 843 +f 868 843 869 +f 869 843 844 +f 869 844 870 +f 870 844 845 +f 870 845 871 +f 871 845 846 +f 871 846 872 +f 872 846 847 +f 872 847 873 +f 873 847 848 +f 873 848 874 +f 874 848 849 +f 874 849 875 +f 875 849 850 +f 875 850 876 +f 876 850 851 +f 876 851 877 +f 877 851 852 +f 877 852 878 +f 878 852 853 +f 878 853 879 +f 879 853 854 +f 879 854 880 +f 880 854 855 +f 880 855 881 +f 881 855 856 +f 881 856 882 +f 882 856 857 +f 882 857 883 +f 883 857 858 +f 883 858 884 +f 884 858 859 +f 884 859 885 +f 885 859 860 +f 885 860 886 +f 886 860 861 +f 886 861 887 +f 887 861 862 +f 887 862 888 +f 888 862 863 +f 888 863 889 +f 889 863 864 +f 889 864 73 +f 73 864 72 +f 866 867 891 +f 891 867 892 +f 892 867 893 +f 893 867 868 +f 893 868 894 +f 894 868 869 +f 894 869 895 +f 895 869 870 +f 895 870 896 +f 896 870 871 +f 896 871 897 +f 897 871 872 +f 897 872 898 +f 898 872 873 +f 898 873 899 +f 899 873 874 +f 899 874 900 +f 900 874 875 +f 900 875 901 +f 901 875 876 +f 901 876 902 +f 902 876 877 +f 902 877 903 +f 903 877 878 +f 903 878 904 +f 904 878 879 +f 904 879 905 +f 905 879 880 +f 905 880 906 +f 906 880 881 +f 906 881 907 +f 907 881 882 +f 907 882 908 +f 908 882 883 +f 908 883 909 +f 909 883 884 +f 909 884 910 +f 910 884 885 +f 910 885 911 +f 911 885 886 +f 911 886 912 +f 912 886 887 +f 912 887 913 +f 913 887 888 +f 913 888 914 +f 914 888 889 +f 914 889 74 +f 74 889 73 +f 891 892 916 +f 916 892 917 +f 917 892 918 +f 918 892 893 +f 918 893 919 +f 919 893 894 +f 919 894 920 +f 920 894 895 +f 920 895 921 +f 921 895 896 +f 921 896 922 +f 922 896 897 +f 922 897 923 +f 923 897 898 +f 923 898 924 +f 924 898 899 +f 924 899 925 +f 925 899 900 +f 925 900 926 +f 926 900 901 +f 926 901 927 +f 927 901 902 +f 927 902 928 +f 928 902 903 +f 928 903 929 +f 929 903 904 +f 929 904 930 +f 930 904 905 +f 930 905 931 +f 931 905 906 +f 931 906 932 +f 932 906 907 +f 932 907 933 +f 933 907 908 +f 933 908 934 +f 934 908 909 +f 934 909 935 +f 935 909 910 +f 935 910 936 +f 936 910 911 +f 936 911 937 +f 937 911 912 +f 937 912 938 +f 938 912 913 +f 938 913 939 +f 939 913 914 +f 939 914 75 +f 75 914 74 +f 916 917 941 +f 943 942 941 +f 917 943 941 +f 918 943 917 +f 943 918 944 +f 944 918 919 +f 944 919 945 +f 945 919 920 +f 945 920 946 +f 946 920 921 +f 946 921 947 +f 947 921 922 +f 947 922 948 +f 948 922 923 +f 948 923 949 +f 949 923 924 +f 949 924 950 +f 950 924 925 +f 950 925 951 +f 951 925 926 +f 951 926 952 +f 952 926 927 +f 952 927 953 +f 953 927 928 +f 953 928 954 +f 954 928 929 +f 954 929 955 +f 955 929 930 +f 955 930 956 +f 956 930 931 +f 956 931 957 +f 957 931 932 +f 957 932 958 +f 958 932 933 +f 958 933 959 +f 959 933 934 +f 959 934 960 +f 960 934 935 +f 960 935 961 +f 961 935 936 +f 961 936 962 +f 962 936 937 +f 962 937 963 +f 963 937 938 +f 963 938 964 +f 964 938 939 +f 964 939 76 +f 76 939 75 +f 942 943 77 +f 77 943 78 +f 78 943 79 +f 79 943 944 +f 79 944 80 +f 80 944 945 +f 80 945 81 +f 81 945 946 +f 81 946 82 +f 82 946 947 +f 82 947 83 +f 83 947 948 +f 83 948 84 +f 84 948 949 +f 84 949 85 +f 85 949 950 +f 85 950 86 +f 86 950 951 +f 86 951 87 +f 87 951 952 +f 87 952 88 +f 88 952 953 +f 88 953 89 +f 89 953 954 +f 89 954 90 +f 90 954 955 +f 90 955 91 +f 91 955 956 +f 91 956 92 +f 92 956 957 +f 92 957 93 +f 93 957 958 +f 93 958 94 +f 94 958 959 +f 94 959 95 +f 95 959 960 +f 95 960 96 +f 96 960 961 +f 96 961 97 +f 97 961 962 +f 97 962 98 +f 98 962 963 +f 98 963 99 +f 99 963 964 +f 99 964 100 +f 100 964 76 +f 101 56 397 +f 102 101 431 +f 431 101 397 +f 102 431 464 +f 993 102 464 +f 103 102 993 +f 993 464 465 +f 104 103 995 +f 995 103 993 +f 993 465 497 +f 996 993 497 +f 995 993 996 +f 996 497 498 +f 105 104 998 +f 998 104 995 +f 998 995 999 +f 999 995 996 +f 996 498 529 +f 1000 996 529 +f 999 996 1000 +f 1000 529 530 +f 106 105 1002 +f 1002 105 998 +f 1002 998 1003 +f 1003 998 999 +f 1003 999 1004 +f 1004 999 1000 +f 1004 1000 560 +f 560 1000 530 +f 107 106 1006 +f 1006 106 1002 +f 1006 1002 1007 +f 1007 1002 1003 +f 1007 1003 1008 +f 1008 1003 1004 +f 1004 560 590 +f 1009 1004 590 +f 1008 1004 1009 +f 1009 590 591 +f 1011 1010 108 +f 107 1011 108 +f 1006 1011 107 +f 1011 1006 1013 +f 1013 1006 1007 +f 1013 1007 1014 +f 1014 1007 1008 +f 1014 1008 1015 +f 1015 1008 1009 +f 1015 1009 620 +f 620 1009 591 +f 1010 1011 1016 +f 1018 1017 1016 +f 1011 1018 1016 +f 1013 1018 1011 +f 1018 1013 1019 +f 1019 1013 1014 +f 1019 1014 1020 +f 1020 1014 1015 +f 1015 620 649 +f 1021 1015 649 +f 1020 1015 1021 +f 1021 649 650 +f 1017 1018 1022 +f 1024 1023 1022 +f 1018 1024 1022 +f 1019 1024 1018 +f 1024 1019 1025 +f 1025 1019 1020 +f 1025 1020 1026 +f 1026 1020 1021 +f 1026 1021 678 +f 678 1021 650 +f 1023 1024 1027 +f 1027 1024 1028 +f 1028 1024 1029 +f 1029 1024 1025 +f 1029 1025 1030 +f 1030 1025 1026 +f 1026 678 706 +f 1031 1026 706 +f 1030 1026 1031 +f 1031 706 707 +f 1027 1028 1032 +f 1034 1033 1032 +f 1028 1034 1032 +f 1029 1034 1028 +f 1034 1029 1035 +f 1035 1029 1030 +f 1035 1030 1036 +f 1036 1030 1031 +f 1036 1031 734 +f 734 1031 707 +f 1033 1034 1037 +f 1039 1038 1037 +f 1034 1039 1037 +f 1035 1039 1034 +f 1039 1035 1040 +f 1040 1035 1036 +f 1036 734 761 +f 1041 1036 761 +f 1040 1036 1041 +f 1041 761 762 +f 1038 1039 1042 +f 1042 1039 1043 +f 1043 1039 1044 +f 1044 1039 1040 +f 1044 1040 1045 +f 1045 1040 1041 +f 1045 1041 788 +f 788 1041 762 +f 1042 1043 1046 +f 1048 1047 1046 +f 1043 1048 1046 +f 1044 1048 1043 +f 1048 1044 1049 +f 1049 1044 1045 +f 1049 1045 814 +f 814 1045 788 +f 1047 1048 1050 +f 1050 1048 1051 +f 1051 1048 1052 +f 1052 1048 1049 +f 1049 814 840 +f 1053 1049 840 +f 1052 1049 1053 +f 1053 840 841 +f 1050 1051 1054 +f 1054 1051 1055 +f 1055 1051 1056 +f 1056 1051 1052 +f 1056 1052 1057 +f 1057 1052 1053 +f 1057 1053 866 +f 866 1053 841 +f 1054 1055 1058 +f 1060 1059 1058 +f 1055 1060 1058 +f 1056 1060 1055 +f 1060 1056 1061 +f 1061 1056 1057 +f 1061 1057 891 +f 891 1057 866 +f 1059 1060 1062 +f 1062 1060 1063 +f 1063 1060 1064 +f 1064 1060 1061 +f 1064 1061 916 +f 916 1061 891 +f 1062 1063 1065 +f 1065 1063 1066 +f 1066 1063 1067 +f 1067 1063 1064 +f 1064 916 941 +f 1068 1064 941 +f 1067 1064 1068 +f 1068 941 942 +f 1065 1066 1069 +f 110 109 1069 +f 1066 110 1069 +f 1067 110 1066 +f 110 1067 111 +f 111 1067 1068 +f 111 1068 77 +f 77 1068 942 +f 112 108 1010 +f 112 1010 1016 +f 1075 112 1016 +f 113 112 1075 +f 1075 1016 1017 +f 114 113 1077 +f 1077 113 1075 +f 1075 1017 1022 +f 1078 1075 1022 +f 1077 1075 1078 +f 1078 1022 1023 +f 115 114 1080 +f 1080 114 1077 +f 1080 1077 1081 +f 1081 1077 1078 +f 1081 1078 1027 +f 1027 1078 1023 +f 116 115 1083 +f 1083 115 1080 +f 1083 1080 1084 +f 1084 1080 1081 +f 1081 1027 1032 +f 1085 1081 1032 +f 1084 1081 1085 +f 1085 1032 1033 +f 1087 1086 117 +f 116 1087 117 +f 1083 1087 116 +f 1087 1083 1089 +f 1089 1083 1084 +f 1089 1084 1090 +f 1090 1084 1085 +f 1085 1033 1037 +f 1091 1085 1037 +f 1090 1085 1091 +f 1091 1037 1038 +f 1086 1087 1092 +f 1094 1093 1092 +f 1087 1094 1092 +f 1089 1094 1087 +f 1094 1089 1095 +f 1095 1089 1090 +f 1095 1090 1096 +f 1096 1090 1091 +f 1096 1091 1042 +f 1042 1091 1038 +f 1093 1094 1097 +f 1097 1094 1098 +f 1098 1094 1099 +f 1099 1094 1095 +f 1099 1095 1100 +f 1100 1095 1096 +f 1096 1042 1046 +f 1101 1096 1046 +f 1100 1096 1101 +f 1101 1046 1047 +f 1097 1098 1102 +f 1104 1103 1102 +f 1098 1104 1102 +f 1099 1104 1098 +f 1104 1099 1105 +f 1105 1099 1100 +f 1105 1100 1106 +f 1106 1100 1101 +f 1106 1101 1050 +f 1050 1101 1047 +f 1103 1104 1107 +f 1109 1108 1107 +f 1104 1109 1107 +f 1105 1109 1104 +f 1109 1105 1110 +f 1110 1105 1106 +f 1110 1106 1054 +f 1054 1106 1050 +f 1108 1109 1111 +f 1111 1109 1112 +f 1112 1109 1113 +f 1113 1109 1110 +f 1110 1054 1058 +f 1114 1110 1058 +f 1113 1110 1114 +f 1114 1058 1059 +f 1111 1112 1115 +f 1117 1116 1115 +f 1112 1117 1115 +f 1113 1117 1112 +f 1117 1113 1118 +f 1118 1113 1114 +f 1118 1114 1062 +f 1062 1114 1059 +f 1116 1117 1119 +f 1119 1117 1120 +f 1120 1117 1121 +f 1121 1117 1118 +f 1121 1118 1065 +f 1065 1118 1062 +f 1119 1120 118 +f 118 1120 119 +f 119 1120 120 +f 120 1120 1121 +f 1121 1065 1069 +f 121 1121 1069 +f 120 1121 121 +f 121 1069 109 +f 122 117 1086 +f 122 1086 1092 +f 1128 122 1092 +f 123 122 1128 +f 1128 1092 1093 +f 124 123 1130 +f 1130 123 1128 +f 1130 1128 1097 +f 1097 1128 1093 +f 125 124 1132 +f 1132 124 1130 +f 1130 1097 1102 +f 1133 1130 1102 +f 1132 1130 1133 +f 1133 1102 1103 +f 126 125 1135 +f 1135 125 1132 +f 1135 1132 1136 +f 1136 1132 1133 +f 1133 1103 1107 +f 1137 1133 1107 +f 1136 1133 1137 +f 1137 1107 1108 +f 1139 1138 127 +f 126 1139 127 +f 1135 1139 126 +f 1139 1135 1141 +f 1141 1135 1136 +f 1141 1136 1142 +f 1142 1136 1137 +f 1142 1137 1111 +f 1111 1137 1108 +f 1138 1139 1143 +f 1143 1139 1144 +f 1144 1139 1145 +f 1145 1139 1141 +f 1145 1141 1146 +f 1146 1141 1142 +f 1142 1111 1115 +f 1147 1142 1115 +f 1146 1142 1147 +f 1143 1144 1148 +f 1150 1149 1151 +f 1144 1152 1148 +f 1145 1153 1144 +f 1155 1145 1154 +f 1154 1145 1146 +f 1154 1146 1156 +f 1156 1146 1147 +f 1156 1147 1119 +f 1149 1150 128 +f 128 1150 129 +f 129 1150 130 +f 1161 1160 1154 +f 1163 1154 131 +f 131 1154 1156 +f 131 1156 118 +f 118 1156 1119 +f 132 127 1138 +f 133 132 1143 +f 1143 132 1138 +f 133 1143 1148 +f 1167 1168 1169 +f 134 1170 1167 +f 1167 1171 1149 +f 135 134 136 +f 136 134 1167 +f 136 1167 128 +f 128 1167 1149 diff --git a/data/trees/bounds01.txt b/data/trees/bounds01.txt new file mode 100644 index 0000000..93b46b4 --- /dev/null +++ b/data/trees/bounds01.txt @@ -0,0 +1,288 @@ +-90.039993286 -0.039999999 -90.039993286 -74.960006714 0.039999999 -74.960006714 +-87.289993286 -4.789999962 -83.539993286 -77.710006714 4.789999962 -81.460006714 +-90.039993286 -0.039999999 -75.039993286 -74.960006714 0.039999999 -59.959999084 +-87.289993286 -4.789999962 -68.539993286 -77.710006714 4.789999962 -66.460006714 +-90.039993286 -0.039999999 -60.040000916 -74.960006714 0.039999999 -44.959999084 +-87.289993286 -4.789999962 -53.540000916 -77.710006714 4.789999962 -51.459999084 +-90.039993286 -0.039999999 -45.040000916 -74.960006714 0.039999999 -29.959999084 +-87.289993286 -4.789999962 -38.540000916 -77.710006714 4.789999962 -36.459999084 +-90.039993286 -0.039999999 -30.040000916 -74.960006714 0.039999999 -14.959999084 +-87.289993286 -4.789999962 -23.540000916 -77.710006714 4.789999962 -21.459999084 +-90.039993286 -0.039999999 -15.040000916 -74.960006714 0.039999999 0.039999999 +-87.289993286 -4.789999962 -8.540000916 -77.710006714 4.789999962 -6.460000038 +-90.039993286 -0.039999999 -0.039999999 -74.960006714 0.039999999 15.040000916 +-87.289993286 -4.789999962 6.460000038 -77.710006714 4.789999962 8.540000916 +-90.039993286 -0.039999999 14.959999084 -74.960006714 0.039999999 30.040000916 +-87.289993286 -4.789999962 21.459999084 -77.710006714 4.789999962 23.540000916 +-90.039993286 -0.039999999 29.959999084 -74.960006714 0.039999999 45.040000916 +-87.289993286 -4.789999962 36.459999084 -77.710006714 4.789999962 38.540000916 +-90.039993286 -0.039999999 44.959999084 -74.960006714 0.039999999 60.040000916 +-87.289993286 -4.789999962 51.459999084 -77.710006714 4.789999962 53.540000916 +-90.039993286 -0.039999999 59.959999084 -74.960006714 0.039999999 75.039993286 +-87.289993286 -4.789999962 66.460006714 -77.710006714 4.789999962 68.539993286 +-90.039993286 -0.039999999 74.960006714 -74.960006714 0.039999999 90.039993286 +-87.289993286 -4.789999962 81.460006714 -77.710006714 4.789999962 83.539993286 +-75.039993286 -0.039999999 -90.039993286 -59.959999084 0.039999999 -74.960006714 +-72.289993286 -4.789999962 -83.539993286 -62.709999084 4.789999962 -81.460006714 +-75.039993286 -0.039999999 -75.039993286 -59.959999084 0.039999999 -59.959999084 +-72.289993286 -4.789999962 -68.539993286 -62.709999084 4.789999962 -66.460006714 +-75.039993286 -0.039999999 -60.040000916 -59.959999084 0.039999999 -44.959999084 +-72.289993286 -4.789999962 -53.540000916 -62.709999084 4.789999962 -51.459999084 +-75.039993286 -0.039999999 -45.040000916 -59.959999084 0.039999999 -29.959999084 +-72.289993286 -4.789999962 -38.540000916 -62.709999084 4.789999962 -36.459999084 +-75.039993286 -0.039999999 -30.040000916 -59.959999084 0.039999999 -14.959999084 +-72.289993286 -4.789999962 -23.540000916 -62.709999084 4.789999962 -21.459999084 +-75.039993286 -0.039999999 -15.040000916 -59.959999084 0.039999999 0.039999999 +-72.289993286 -4.789999962 -8.540000916 -62.709999084 4.789999962 -6.460000038 +-75.039993286 -0.039999999 -0.039999999 -59.959999084 0.039999999 15.040000916 +-72.289993286 -4.789999962 6.460000038 -62.709999084 4.789999962 8.540000916 +-75.039993286 -0.039999999 14.959999084 -59.959999084 0.039999999 30.040000916 +-72.289993286 -4.789999962 21.459999084 -62.709999084 4.789999962 23.540000916 +-75.039993286 -0.039999999 29.959999084 -59.959999084 0.039999999 45.040000916 +-72.289993286 -4.789999962 36.459999084 -62.709999084 4.789999962 38.540000916 +-75.039993286 -0.039999999 44.959999084 -59.959999084 0.039999999 60.040000916 +-72.289993286 -4.789999962 51.459999084 -62.709999084 4.789999962 53.540000916 +-75.039993286 -0.039999999 59.959999084 -59.959999084 0.039999999 75.039993286 +-72.289993286 -4.789999962 66.460006714 -62.709999084 4.789999962 68.539993286 +-75.039993286 -0.039999999 74.960006714 -59.959999084 0.039999999 90.039993286 +-72.289993286 -4.789999962 81.460006714 -62.709999084 4.789999962 83.539993286 +-60.040000916 -0.039999999 -90.039993286 -44.959999084 0.039999999 -74.960006714 +-57.290000916 -4.789999962 -83.539993286 -47.709999084 4.789999962 -81.460006714 +-60.040000916 -0.039999999 -75.039993286 -44.959999084 0.039999999 -59.959999084 +-57.290000916 -4.789999962 -68.539993286 -47.709999084 4.789999962 -66.460006714 +-60.040000916 -0.039999999 -60.040000916 -44.959999084 0.039999999 -44.959999084 +-57.290000916 -4.789999962 -53.540000916 -47.709999084 4.789999962 -51.459999084 +-60.040000916 -0.039999999 -45.040000916 -44.959999084 0.039999999 -29.959999084 +-57.290000916 -4.789999962 -38.540000916 -47.709999084 4.789999962 -36.459999084 +-60.040000916 -0.039999999 -30.040000916 -44.959999084 0.039999999 -14.959999084 +-57.290000916 -4.789999962 -23.540000916 -47.709999084 4.789999962 -21.459999084 +-60.040000916 -0.039999999 -15.040000916 -44.959999084 0.039999999 0.039999999 +-57.290000916 -4.789999962 -8.540000916 -47.709999084 4.789999962 -6.460000038 +-60.040000916 -0.039999999 -0.039999999 -44.959999084 0.039999999 15.040000916 +-57.290000916 -4.789999962 6.460000038 -47.709999084 4.789999962 8.540000916 +-60.040000916 -0.039999999 14.959999084 -44.959999084 0.039999999 30.040000916 +-57.290000916 -4.789999962 21.459999084 -47.709999084 4.789999962 23.540000916 +-60.040000916 -0.039999999 29.959999084 -44.959999084 0.039999999 45.040000916 +-57.290000916 -4.789999962 36.459999084 -47.709999084 4.789999962 38.540000916 +-60.040000916 -0.039999999 44.959999084 -44.959999084 0.039999999 60.040000916 +-57.290000916 -4.789999962 51.459999084 -47.709999084 4.789999962 53.540000916 +-60.040000916 -0.039999999 59.959999084 -44.959999084 0.039999999 75.039993286 +-57.290000916 -4.789999962 66.460006714 -47.709999084 4.789999962 68.539993286 +-60.040000916 -0.039999999 74.960006714 -44.959999084 0.039999999 90.039993286 +-57.290000916 -4.789999962 81.460006714 -47.709999084 4.789999962 83.539993286 +-45.040000916 -0.039999999 -90.039993286 -29.959999084 0.039999999 -74.960006714 +-42.290000916 -4.789999962 -83.539993286 -32.709999084 4.789999962 -81.460006714 +-45.040000916 -0.039999999 -75.039993286 -29.959999084 0.039999999 -59.959999084 +-42.290000916 -4.789999962 -68.539993286 -32.709999084 4.789999962 -66.460006714 +-45.040000916 -0.039999999 -60.040000916 -29.959999084 0.039999999 -44.959999084 +-42.290000916 -4.789999962 -53.540000916 -32.709999084 4.789999962 -51.459999084 +-45.040000916 -0.039999999 -45.040000916 -29.959999084 0.039999999 -29.959999084 +-42.290000916 -4.789999962 -38.540000916 -32.709999084 4.789999962 -36.459999084 +-45.040000916 -0.039999999 -30.040000916 -29.959999084 0.039999999 -14.959999084 +-42.290000916 -4.789999962 -23.540000916 -32.709999084 4.789999962 -21.459999084 +-45.040000916 -0.039999999 -15.040000916 -29.959999084 0.039999999 0.039999999 +-42.290000916 -4.789999962 -8.540000916 -32.709999084 4.789999962 -6.460000038 +-45.040000916 -0.039999999 -0.039999999 -29.959999084 0.039999999 15.040000916 +-42.290000916 -4.789999962 6.460000038 -32.709999084 4.789999962 8.540000916 +-45.040000916 -0.039999999 14.959999084 -29.959999084 0.039999999 30.040000916 +-42.290000916 -4.789999962 21.459999084 -32.709999084 4.789999962 23.540000916 +-45.040000916 -0.039999999 29.959999084 -29.959999084 0.039999999 45.040000916 +-42.290000916 -4.789999962 36.459999084 -32.709999084 4.789999962 38.540000916 +-45.040000916 -0.039999999 44.959999084 -29.959999084 0.039999999 60.040000916 +-42.290000916 -4.789999962 51.459999084 -32.709999084 4.789999962 53.540000916 +-45.040000916 -0.039999999 59.959999084 -29.959999084 0.039999999 75.039993286 +-42.290000916 -4.789999962 66.460006714 -32.709999084 4.789999962 68.539993286 +-45.040000916 -0.039999999 74.960006714 -29.959999084 0.039999999 90.039993286 +-42.290000916 -4.789999962 81.460006714 -32.709999084 4.789999962 83.539993286 +-30.040000916 -0.039999999 -90.039993286 -14.959999084 0.039999999 -74.960006714 +-27.290000916 -4.789999962 -83.539993286 -17.709999084 4.789999962 -81.460006714 +-30.040000916 -0.039999999 -75.039993286 -14.959999084 0.039999999 -59.959999084 +-27.290000916 -4.789999962 -68.539993286 -17.709999084 4.789999962 -66.460006714 +-30.040000916 -0.039999999 -60.040000916 -14.959999084 0.039999999 -44.959999084 +-27.290000916 -4.789999962 -53.540000916 -17.709999084 4.789999962 -51.459999084 +-30.040000916 -0.039999999 -45.040000916 -14.959999084 0.039999999 -29.959999084 +-27.290000916 -4.789999962 -38.540000916 -17.709999084 4.789999962 -36.459999084 +-30.040000916 -0.039999999 -30.040000916 -14.959999084 0.039999999 -14.959999084 +-27.290000916 -4.789999962 -23.540000916 -17.709999084 4.789999962 -21.459999084 +-30.040000916 -0.039999999 -15.040000916 -14.959999084 0.039999999 0.039999999 +-27.290000916 -4.789999962 -8.540000916 -17.709999084 4.789999962 -6.460000038 +-30.040000916 -0.039999999 -0.039999999 -14.959999084 0.039999999 15.040000916 +-27.290000916 -4.789999962 6.460000038 -17.709999084 4.789999962 8.540000916 +-30.040000916 -0.039999999 14.959999084 -14.959999084 0.039999999 30.040000916 +-27.290000916 -4.789999962 21.459999084 -17.709999084 4.789999962 23.540000916 +-30.040000916 -0.039999999 29.959999084 -14.959999084 0.039999999 45.040000916 +-27.290000916 -4.789999962 36.459999084 -17.709999084 4.789999962 38.540000916 +-30.040000916 -0.039999999 44.959999084 -14.959999084 0.039999999 60.040000916 +-27.290000916 -4.789999962 51.459999084 -17.709999084 4.789999962 53.540000916 +-30.040000916 -0.039999999 59.959999084 -14.959999084 0.039999999 75.039993286 +-27.290000916 -4.789999962 66.460006714 -17.709999084 4.789999962 68.539993286 +-30.040000916 -0.039999999 74.960006714 -14.959999084 0.039999999 90.039993286 +-27.290000916 -4.789999962 81.460006714 -17.709999084 4.789999962 83.539993286 +-15.040000916 -0.039999999 -90.039993286 0.039999999 0.039999999 -74.960006714 +-12.290000916 -4.789999962 -83.539993286 -2.710000038 4.789999962 -81.460006714 +-15.040000916 -0.039999999 -75.039993286 0.039999999 0.039999999 -59.959999084 +-12.290000916 -4.789999962 -68.539993286 -2.710000038 4.789999962 -66.460006714 +-15.040000916 -0.039999999 -60.040000916 0.039999999 0.039999999 -44.959999084 +-12.290000916 -4.789999962 -53.540000916 -2.710000038 4.789999962 -51.459999084 +-15.040000916 -0.039999999 -45.040000916 0.039999999 0.039999999 -29.959999084 +-12.290000916 -4.789999962 -38.540000916 -2.710000038 4.789999962 -36.459999084 +-15.040000916 -0.039999999 -30.040000916 0.039999999 0.039999999 -14.959999084 +-12.290000916 -4.789999962 -23.540000916 -2.710000038 4.789999962 -21.459999084 +-15.040000916 -0.039999999 -15.040000916 0.039999999 0.039999999 0.039999999 +-12.290000916 -4.789999962 -8.540000916 -2.710000038 4.789999962 -6.460000038 +-15.040000916 -0.039999999 -0.039999999 0.039999999 0.039999999 15.040000916 +-12.290000916 -4.789999962 6.460000038 -2.710000038 4.789999962 8.540000916 +-15.040000916 -0.039999999 14.959999084 0.039999999 0.039999999 30.040000916 +-12.290000916 -4.789999962 21.459999084 -2.710000038 4.789999962 23.540000916 +-15.040000916 -0.039999999 29.959999084 0.039999999 0.039999999 45.040000916 +-12.290000916 -4.789999962 36.459999084 -2.710000038 4.789999962 38.540000916 +-15.040000916 -0.039999999 44.959999084 0.039999999 0.039999999 60.040000916 +-12.290000916 -4.789999962 51.459999084 -2.710000038 4.789999962 53.540000916 +-15.040000916 -0.039999999 59.959999084 0.039999999 0.039999999 75.039993286 +-12.290000916 -4.789999962 66.460006714 -2.710000038 4.789999962 68.539993286 +-15.040000916 -0.039999999 74.960006714 0.039999999 0.039999999 90.039993286 +-12.290000916 -4.789999962 81.460006714 -2.710000038 4.789999962 83.539993286 +-0.039999999 -0.039999999 -90.039993286 15.040000916 0.039999999 -74.960006714 +2.710000038 -4.789999962 -83.539993286 12.290000916 4.789999962 -81.460006714 +-0.039999999 -0.039999999 -75.039993286 15.040000916 0.039999999 -59.959999084 +2.710000038 -4.789999962 -68.539993286 12.290000916 4.789999962 -66.460006714 +-0.039999999 -0.039999999 -60.040000916 15.040000916 0.039999999 -44.959999084 +2.710000038 -4.789999962 -53.540000916 12.290000916 4.789999962 -51.459999084 +-0.039999999 -0.039999999 -45.040000916 15.040000916 0.039999999 -29.959999084 +2.710000038 -4.789999962 -38.540000916 12.290000916 4.789999962 -36.459999084 +-0.039999999 -0.039999999 -30.040000916 15.040000916 0.039999999 -14.959999084 +2.710000038 -4.789999962 -23.540000916 12.290000916 4.789999962 -21.459999084 +-0.039999999 -0.039999999 -15.040000916 15.040000916 0.039999999 0.039999999 +2.710000038 -4.789999962 -8.540000916 12.290000916 4.789999962 -6.460000038 +-0.039999999 -0.039999999 -0.039999999 15.040000916 0.039999999 15.040000916 +2.710000038 -4.789999962 6.460000038 12.290000916 4.789999962 8.540000916 +-0.039999999 -0.039999999 14.959999084 15.040000916 0.039999999 30.040000916 +2.710000038 -4.789999962 21.459999084 12.290000916 4.789999962 23.540000916 +-0.039999999 -0.039999999 29.959999084 15.040000916 0.039999999 45.040000916 +2.710000038 -4.789999962 36.459999084 12.290000916 4.789999962 38.540000916 +-0.039999999 -0.039999999 44.959999084 15.040000916 0.039999999 60.040000916 +2.710000038 -4.789999962 51.459999084 12.290000916 4.789999962 53.540000916 +-0.039999999 -0.039999999 59.959999084 15.040000916 0.039999999 75.039993286 +2.710000038 -4.789999962 66.460006714 12.290000916 4.789999962 68.539993286 +-0.039999999 -0.039999999 74.960006714 15.040000916 0.039999999 90.039993286 +2.710000038 -4.789999962 81.460006714 12.290000916 4.789999962 83.539993286 +14.959999084 -0.039999999 -90.039993286 30.040000916 0.039999999 -74.960006714 +17.709999084 -4.789999962 -83.539993286 27.290000916 4.789999962 -81.460006714 +14.959999084 -0.039999999 -75.039993286 30.040000916 0.039999999 -59.959999084 +17.709999084 -4.789999962 -68.539993286 27.290000916 4.789999962 -66.460006714 +14.959999084 -0.039999999 -60.040000916 30.040000916 0.039999999 -44.959999084 +17.709999084 -4.789999962 -53.540000916 27.290000916 4.789999962 -51.459999084 +14.959999084 -0.039999999 -45.040000916 30.040000916 0.039999999 -29.959999084 +17.709999084 -4.789999962 -38.540000916 27.290000916 4.789999962 -36.459999084 +14.959999084 -0.039999999 -30.040000916 30.040000916 0.039999999 -14.959999084 +17.709999084 -4.789999962 -23.540000916 27.290000916 4.789999962 -21.459999084 +14.959999084 -0.039999999 -15.040000916 30.040000916 0.039999999 0.039999999 +17.709999084 -4.789999962 -8.540000916 27.290000916 4.789999962 -6.460000038 +14.959999084 -0.039999999 -0.039999999 30.040000916 0.039999999 15.040000916 +17.709999084 -4.789999962 6.460000038 27.290000916 4.789999962 8.540000916 +14.959999084 -0.039999999 14.959999084 30.040000916 0.039999999 30.040000916 +17.709999084 -4.789999962 21.459999084 27.290000916 4.789999962 23.540000916 +14.959999084 -0.039999999 29.959999084 30.040000916 0.039999999 45.040000916 +17.709999084 -4.789999962 36.459999084 27.290000916 4.789999962 38.540000916 +14.959999084 -0.039999999 44.959999084 30.040000916 0.039999999 60.040000916 +17.709999084 -4.789999962 51.459999084 27.290000916 4.789999962 53.540000916 +14.959999084 -0.039999999 59.959999084 30.040000916 0.039999999 75.039993286 +17.709999084 -4.789999962 66.460006714 27.290000916 4.789999962 68.539993286 +14.959999084 -0.039999999 74.960006714 30.040000916 0.039999999 90.039993286 +17.709999084 -4.789999962 81.460006714 27.290000916 4.789999962 83.539993286 +29.959999084 -0.039999999 -90.039993286 45.040000916 0.039999999 -74.960006714 +32.709999084 -4.789999962 -83.539993286 42.290000916 4.789999962 -81.460006714 +29.959999084 -0.039999999 -75.039993286 45.040000916 0.039999999 -59.959999084 +32.709999084 -4.789999962 -68.539993286 42.290000916 4.789999962 -66.460006714 +29.959999084 -0.039999999 -60.040000916 45.040000916 0.039999999 -44.959999084 +32.709999084 -4.789999962 -53.540000916 42.290000916 4.789999962 -51.459999084 +29.959999084 -0.039999999 -45.040000916 45.040000916 0.039999999 -29.959999084 +32.709999084 -4.789999962 -38.540000916 42.290000916 4.789999962 -36.459999084 +29.959999084 -0.039999999 -30.040000916 45.040000916 0.039999999 -14.959999084 +32.709999084 -4.789999962 -23.540000916 42.290000916 4.789999962 -21.459999084 +29.959999084 -0.039999999 -15.040000916 45.040000916 0.039999999 0.039999999 +32.709999084 -4.789999962 -8.540000916 42.290000916 4.789999962 -6.460000038 +29.959999084 -0.039999999 -0.039999999 45.040000916 0.039999999 15.040000916 +32.709999084 -4.789999962 6.460000038 42.290000916 4.789999962 8.540000916 +29.959999084 -0.039999999 14.959999084 45.040000916 0.039999999 30.040000916 +32.709999084 -4.789999962 21.459999084 42.290000916 4.789999962 23.540000916 +29.959999084 -0.039999999 29.959999084 45.040000916 0.039999999 45.040000916 +32.709999084 -4.789999962 36.459999084 42.290000916 4.789999962 38.540000916 +29.959999084 -0.039999999 44.959999084 45.040000916 0.039999999 60.040000916 +32.709999084 -4.789999962 51.459999084 42.290000916 4.789999962 53.540000916 +29.959999084 -0.039999999 59.959999084 45.040000916 0.039999999 75.039993286 +32.709999084 -4.789999962 66.460006714 42.290000916 4.789999962 68.539993286 +29.959999084 -0.039999999 74.960006714 45.040000916 0.039999999 90.039993286 +32.709999084 -4.789999962 81.460006714 42.290000916 4.789999962 83.539993286 +44.959999084 -0.039999999 -90.039993286 60.040000916 0.039999999 -74.960006714 +47.709999084 -4.789999962 -83.539993286 57.290000916 4.789999962 -81.460006714 +44.959999084 -0.039999999 -75.039993286 60.040000916 0.039999999 -59.959999084 +47.709999084 -4.789999962 -68.539993286 57.290000916 4.789999962 -66.460006714 +44.959999084 -0.039999999 -60.040000916 60.040000916 0.039999999 -44.959999084 +47.709999084 -4.789999962 -53.540000916 57.290000916 4.789999962 -51.459999084 +44.959999084 -0.039999999 -45.040000916 60.040000916 0.039999999 -29.959999084 +47.709999084 -4.789999962 -38.540000916 57.290000916 4.789999962 -36.459999084 +44.959999084 -0.039999999 -30.040000916 60.040000916 0.039999999 -14.959999084 +47.709999084 -4.789999962 -23.540000916 57.290000916 4.789999962 -21.459999084 +44.959999084 -0.039999999 -15.040000916 60.040000916 0.039999999 0.039999999 +47.709999084 -4.789999962 -8.540000916 57.290000916 4.789999962 -6.460000038 +44.959999084 -0.039999999 -0.039999999 60.040000916 0.039999999 15.040000916 +47.709999084 -4.789999962 6.460000038 57.290000916 4.789999962 8.540000916 +44.959999084 -0.039999999 14.959999084 60.040000916 0.039999999 30.040000916 +47.709999084 -4.789999962 21.459999084 57.290000916 4.789999962 23.540000916 +44.959999084 -0.039999999 29.959999084 60.040000916 0.039999999 45.040000916 +47.709999084 -4.789999962 36.459999084 57.290000916 4.789999962 38.540000916 +44.959999084 -0.039999999 44.959999084 60.040000916 0.039999999 60.040000916 +47.709999084 -4.789999962 51.459999084 57.290000916 4.789999962 53.540000916 +44.959999084 -0.039999999 59.959999084 60.040000916 0.039999999 75.039993286 +47.709999084 -4.789999962 66.460006714 57.290000916 4.789999962 68.539993286 +44.959999084 -0.039999999 74.960006714 60.040000916 0.039999999 90.039993286 +47.709999084 -4.789999962 81.460006714 57.290000916 4.789999962 83.539993286 +59.959999084 -0.039999999 -90.039993286 75.039993286 0.039999999 -74.960006714 +62.709999084 -4.789999962 -83.539993286 72.289993286 4.789999962 -81.460006714 +59.959999084 -0.039999999 -75.039993286 75.039993286 0.039999999 -59.959999084 +62.709999084 -4.789999962 -68.539993286 72.289993286 4.789999962 -66.460006714 +59.959999084 -0.039999999 -60.040000916 75.039993286 0.039999999 -44.959999084 +62.709999084 -4.789999962 -53.540000916 72.289993286 4.789999962 -51.459999084 +59.959999084 -0.039999999 -45.040000916 75.039993286 0.039999999 -29.959999084 +62.709999084 -4.789999962 -38.540000916 72.289993286 4.789999962 -36.459999084 +59.959999084 -0.039999999 -30.040000916 75.039993286 0.039999999 -14.959999084 +62.709999084 -4.789999962 -23.540000916 72.289993286 4.789999962 -21.459999084 +59.959999084 -0.039999999 -15.040000916 75.039993286 0.039999999 0.039999999 +62.709999084 -4.789999962 -8.540000916 72.289993286 4.789999962 -6.460000038 +59.959999084 -0.039999999 -0.039999999 75.039993286 0.039999999 15.040000916 +62.709999084 -4.789999962 6.460000038 72.289993286 4.789999962 8.540000916 +59.959999084 -0.039999999 14.959999084 75.039993286 0.039999999 30.040000916 +62.709999084 -4.789999962 21.459999084 72.289993286 4.789999962 23.540000916 +59.959999084 -0.039999999 29.959999084 75.039993286 0.039999999 45.040000916 +62.709999084 -4.789999962 36.459999084 72.289993286 4.789999962 38.540000916 +59.959999084 -0.039999999 44.959999084 75.039993286 0.039999999 60.040000916 +62.709999084 -4.789999962 51.459999084 72.289993286 4.789999962 53.540000916 +59.959999084 -0.039999999 59.959999084 75.039993286 0.039999999 75.039993286 +62.709999084 -4.789999962 66.460006714 72.289993286 4.789999962 68.539993286 +59.959999084 -0.039999999 74.960006714 75.039993286 0.039999999 90.039993286 +62.709999084 -4.789999962 81.460006714 72.289993286 4.789999962 83.539993286 +74.960006714 -0.039999999 -90.039993286 90.039993286 0.039999999 -74.960006714 +77.710006714 -4.789999962 -83.539993286 87.289993286 4.789999962 -81.460006714 +74.960006714 -0.039999999 -75.039993286 90.039993286 0.039999999 -59.959999084 +77.710006714 -4.789999962 -68.539993286 87.289993286 4.789999962 -66.460006714 +74.960006714 -0.039999999 -60.040000916 90.039993286 0.039999999 -44.959999084 +77.710006714 -4.789999962 -53.540000916 87.289993286 4.789999962 -51.459999084 +74.960006714 -0.039999999 -45.040000916 90.039993286 0.039999999 -29.959999084 +77.710006714 -4.789999962 -38.540000916 87.289993286 4.789999962 -36.459999084 +74.960006714 -0.039999999 -30.040000916 90.039993286 0.039999999 -14.959999084 +77.710006714 -4.789999962 -23.540000916 87.289993286 4.789999962 -21.459999084 +74.960006714 -0.039999999 -15.040000916 90.039993286 0.039999999 0.039999999 +77.710006714 -4.789999962 -8.540000916 87.289993286 4.789999962 -6.460000038 +74.960006714 -0.039999999 -0.039999999 90.039993286 0.039999999 15.040000916 +77.710006714 -4.789999962 6.460000038 87.289993286 4.789999962 8.540000916 +74.960006714 -0.039999999 14.959999084 90.039993286 0.039999999 30.040000916 +77.710006714 -4.789999962 21.459999084 87.289993286 4.789999962 23.540000916 +74.960006714 -0.039999999 29.959999084 90.039993286 0.039999999 45.040000916 +77.710006714 -4.789999962 36.459999084 87.289993286 4.789999962 38.540000916 +74.960006714 -0.039999999 44.959999084 90.039993286 0.039999999 60.040000916 +77.710006714 -4.789999962 51.459999084 87.289993286 4.789999962 53.540000916 +74.960006714 -0.039999999 59.959999084 90.039993286 0.039999999 75.039993286 +77.710006714 -4.789999962 66.460006714 87.289993286 4.789999962 68.539993286 +74.960006714 -0.039999999 74.960006714 90.039993286 0.039999999 90.039993286 +77.710006714 -4.789999962 81.460006714 87.289993286 4.789999962 83.539993286 diff --git a/data/trees/bounds02.txt b/data/trees/bounds02.txt new file mode 100644 index 0000000..2f6a887 --- /dev/null +++ b/data/trees/bounds02.txt @@ -0,0 +1,4221 @@ +-40.3459 8.78819 44.5244 -35.5575 11.9663 49.301 +-16.2893 12.3941 50.043 -7.11812 18.4668 59.2102 +18.6076 -4.10024 34.6719 19.3566 -2.80068 35.7563 +9.6608 4.85883 51.2022 13.5766 9.64647 58.2644 +-38.2207 0.556023 139.593 -35.5309 0.962231 141.331 +-110.679 2.07507 94.4778 -108.04 2.48128 95.9674 +-98.832 5.09821 97.7104 -96.1286 5.50442 99.5956 +48.1233 2.15038 79.3845 49.2842 2.67738 80.4093 +47.9565 2.30649 79.4433 48.6222 3.48498 80.4902 +48.6207 1.87615 79.3977 49.1191 2.45912 79.8711 +48.6846 1.87615 79.9292 49.1828 2.45912 80.4014 +48.122 1.87581 79.933 48.6271 2.42083 80.4336 +48.0838 1.87582 79.5141 48.5861 2.42083 79.9824 +-90.0587 -1.35708 114.628 -89.1646 -0.520767 115.451 +21.8139 -4.21 -11.2181 22.5303 -2.87039 -10.5017 +21.8077 -4.21243 -11.2282 22.5412 -2.70133 -10.491 +-27.3093 -3.07072 -3.49667 -26.7983 -2.11467 -2.99302 +-27.1534 -2.25642 -3.41966 -26.9334 -2.03642 -3.19966 +-101.079 -2.4877 101.827 -98.7902 0.025119 102.925 +-24.5287 0.178615 114.504 -23.3992 1.6917 115.621 +-24.5256 0.178479 114.505 -23.4016 1.68942 115.618 +-108.394 -4.48499 109.689 -107.689 -2.97487 111.963 +-110.054 -4.48499 101.919 -109.358 -2.75048 102.615 +-49.4784 0.926304 117.356 -48.562 1.56226 118.265 +-127.286 4.05609 86.1214 -125.788 5.36098 86.9985 +-2.5166 -4.12372 -32.4902 -1.88047 -3.68265 -31.5927 +-1.99021 -4.10259 -32.5584 -1.37455 -3.63443 -31.4401 +-2.82242 -3.55519 -32.2122 -1.64844 -3.04669 -31.6421 +-2.66561 -3.49718 -32.4714 -1.71959 -3.03914 -31.9825 +-2.26386 -3.74915 -32.6319 -1.71008 -3.24014 -31.5194 +-2.5207 -3.74275 -32.7381 -1.91713 -3.22362 -31.518 +-2.73771 -3.68852 -32.5939 -2.15953 -3.21275 -31.6379 +-2.59522 -3.89221 -32.6044 -1.47532 -3.45722 -32.1602 +-1.99853 -4.09329 -32.4139 -1.16975 -3.3748 -31.9343 +-2.26826 -4.13333 -32.2185 -1.40968 -3.44422 -31.4227 +-2.78139 -3.94519 -32.1248 -1.82532 -3.41742 -31.6255 +-2.73672 -4.10409 -32.643 -2.2751 -3.64678 -31.4732 +-127.188 -0.257597 101.875 -126.426 0.674344 102.623 +13.247 -3.82577 -28.1954 14.3669 -3.29877 -27.2186 +13.0807 -3.66966 -28.266 13.7139 -2.49117 -27.2321 +13.776 -4.1 -28.2119 14.2634 -3.51703 -27.7511 +13.7555 -4.1 -27.6769 14.2427 -3.51703 -27.2173 +13.1978 -4.10034 -27.7613 13.6909 -3.55532 -27.2738 +13.2277 -4.10033 -28.1812 13.7193 -3.55532 -27.7256 +-136.487 4.05609 85.5335 -134.989 5.36098 86.4106 +-114.342 -0.339987 105.867 -113.537 0.636449 106.669 +-129.729 -0.262597 110.211 -128.828 0.847328 111.12 +-118.285 -4.35449 121.225 -117.39 -3.51817 122.044 +-127.628 -0.26044 101.695 -126.973 0.909379 102.35 +-140.487 1.64216 84.6851 -139.65 2.81198 85.5224 +-117.242 -2.36044 140.005 -116.433 -1.19062 140.813 +54.3078 2.15038 69.8093 55.3128 2.67738 70.9544 +54.2312 2.30649 69.6438 55.2736 3.48498 70.2943 +54.8347 1.87615 70.3091 55.3022 2.45912 70.8024 +54.3029 1.87615 70.3595 54.7692 2.45912 70.8526 +54.2849 1.87581 69.797 54.7796 2.42083 70.2963 +54.7371 1.87582 69.7695 55.1993 2.42083 70.2667 +-110.588 3.59719 94.1164 -107.886 4.0034 95.98 +-114.681 -0.357085 108.856 -113.786 0.479233 109.661 +-138.408 5.55609 84.9761 -136.909 6.86098 85.8532 +-127.891 -0.257086 105.923 -126.996 0.579232 106.746 +19.0075 -2.94359 -48.3136 19.2975 -2.65359 -48.0236 +15.4365 -3.82577 -30.2875 16.6175 -3.29877 -29.237 +16.1004 -3.66966 -30.3739 16.786 -2.49117 -29.3219 +15.6189 -4.1 -29.7348 16.1238 -3.51703 -29.2537 +15.5372 -4.1 -30.2626 16.0421 -3.51703 -29.7827 +16.0916 -4.10034 -30.3137 16.6042 -3.55532 -29.8054 +16.1478 -4.10033 -29.8641 16.6564 -3.55532 -29.3881 +-28.8363 -0.218646 144.735 -27.9592 1.08624 146.234 +-106.654 -3.48768 121.034 -104.365 -0.974863 122.132 +16.2596 0.709034 39.7156 16.6676 1.11703 40.1236 +16.1148 0.881124 39.6456 16.7464 2.04983 40.2683 +20.6177 -3.09237 -32.2633 21.1284 -2.13632 -31.7587 +20.7037 -2.27807 -32.1165 20.9237 -2.05807 -31.8965 +-136.764 0.538727 98.7955 -136.049 1.51458 99.5106 +-48.3329 1.8356 117.386 -47.9085 2.23751 117.836 +-129.391 1.63716 86.8194 -128.657 2.80698 87.5538 +-3.14502 -1.20383 -59.145 -2.85502 -0.913826 -58.855 +22.7263 -3.07819 -26.5717 24.4641 -1.55946 -25.103 +22.7083 -2.66137 -25.9973 23.0733 -2.34137 -25.6773 +24.022 6.84929 -12.9706 24.3866 7.21389 -12.6059 +-137.643 0.64 98.6448 -136.882 1.57194 99.4027 +27.1137 -3.83577 29.3155 28.1602 -3.30877 30.4942 +27.2006 -3.67966 29.1447 28.25 -2.50117 29.8314 +27.6515 -4.11 29.8852 28.134 -3.52703 30.3914 +27.1221 -4.11 29.8148 27.6034 -3.52703 30.3208 +27.23 -4.11034 29.2649 27.7394 -3.56532 29.7792 +27.677 -4.11033 29.3369 28.1547 -3.56532 29.8467 +22.513 -2.94359 -48.3475 22.803 -2.65359 -48.0575 +-30.7874 1.28135 151.458 -29.9103 2.58624 152.956 +-112.137 -1.36943 127.713 -111.467 -0.393579 128.382 +-95.9698 -1.36159 143.515 -94.5789 -0.1341 144.906 +-95.7564 -1.33544 143.714 -94.7891 -1.0226 144.704 +-2.43222 -4.10104 -37.185 -0.137221 -2.72564 -36.815 +-2.35722 -4.10104 -37.2184 -0.137222 -2.88104 -36.7815 +-121.826 -2.36044 138.863 -121.134 -1.19062 139.556 +-130.803 1.09235 153.529 -128.12 1.49856 155.221 +22.3111 -3.07819 -30.3541 24.0488 -1.55946 -28.8854 +22.2931 -2.66137 -29.7798 22.6581 -2.34137 -29.4598 +-102.209 -1.36468 126.382 -101.507 -0.388826 127.084 +-115.76 -2.36044 139.838 -115.07 -1.19062 140.528 +-144.909 0.640587 96.479 -143.557 3.24452 97.8371 +-144.91 0.64 96.4822 -143.713 3.16093 97.6908 +8.08548 -3.19404 -28.916 8.50645 -2.93286 -28.5219 +-29.3241 2.78135 146.416 -28.447 4.08624 147.914 +-104.733 -2.48768 121.592 -102.444 0.0251367 122.69 +19.4799 -1.20382 -59.3292 19.7699 -0.913825 -59.0392 +50.2617 2.15038 79.2046 51.4484 2.67738 80.2625 +50.926 2.30649 79.1165 51.6173 3.48498 80.1698 +50.4491 1.87615 79.7615 50.9559 2.45912 80.2448 +50.3622 1.87615 79.2345 50.8688 2.45912 79.7166 +50.916 1.87581 79.1778 51.4307 2.42083 79.6883 +50.9767 1.87582 79.6268 51.4872 2.42083 80.1051 +-47.6639 1.8356 116.587 -47.2395 2.23751 117.037 +-147.244 0.640587 104.842 -146.103 3.24452 106.046 +-147.268 0.64 104.868 -146.287 3.16093 105.975 +-106.816 -2.485 100.162 -104.552 -0.974881 101.253 +-110.936 6.59668 94.1221 -108.246 7.00289 95.8596 +-144.252 2.72758 96.708 -143.955 3.10242 97.0051 +-144.352 2.87691 96.8181 -144.055 3.25175 97.1152 +-144.568 2.85803 97.0562 -144.27 3.23287 97.3534 +-144.667 2.74666 97.1588 -144.37 3.1215 97.4559 +-146.861 2.72758 104.97 -146.564 3.10242 105.267 +-146.892 2.87691 105.115 -146.595 3.25175 105.412 +-146.96 2.85803 105.429 -146.663 3.23287 105.726 +-146.995 2.74666 105.567 -146.698 3.1215 105.865 +-112.34 -1.36283 128.893 -111.553 -0.193008 129.681 +-83.3519 -1.359 106.446 -81.9545 -0.131506 107.844 +-83.1291 -1.33285 106.657 -82.1618 -1.02 107.634 +28.815 -0.870313 30.89 29.185 1.2654 33.185 +28.7815 -1.11 30.89 29.2185 1.11 33.11 +-130.848 1.515 99.4346 -128.584 3.02512 100.525 +-30.2997 -1.71865 149.778 -29.4225 -0.413757 151.276 +-40.1143 -4.09808 -10.65 -38.6779 -1.51965 -9.43531 +-40.0867 -4.08526 -10.643 -38.6797 -1.63461 -9.45337 +21.3382 -3.20353 33.1349 22.1476 -2.51369 33.9792 +24.1571 -3.15503 32.6255 24.6588 -2.19897 33.137 +24.2892 -2.34072 32.7136 24.5092 -2.12073 32.9336 +-129.379 -0.358869 115.753 -128.793 0.616986 116.339 +-99.1334 -1.485 102.393 -96.8699 0.025119 103.484 +-88.1475 -1.3676 125.309 -87.2503 -0.25767 126.207 +-89.7511 -1.35941 101.351 -88.5201 1.24452 102.523 +-89.6717 -1.36 101.328 -88.5443 1.16093 102.34 +-132.523 0.640523 100.059 -131.628 1.47684 100.882 +28.0342 2.71983 37.8031 30.6708 4.3291 38.9314 +28.0342 2.71983 37.8076 30.6708 4.65887 39.0442 +-99.073 6.59668 97.649 -96.3832 7.00289 99.3865 +-29.185 -2.87031 2.565 -26.89 -0.7346 2.93499 +-29.11 -3.11 2.53154 -26.89 -0.89 2.96845 +-146.166 0.640587 100.912 -144.883 3.24452 102.231 +-146.18 0.64 100.927 -145.059 3.16093 102.118 +-115.213 -0.360438 104.171 -114.532 0.809381 104.851 +-87.9292 -1.36537 125.868 -87.0863 -0.195547 126.711 +-44.5224 -2.36 150.125 -42.5133 -0.984609 152.103 +-44.5248 -2.36 150.125 -42.5151 -0.984609 152.103 +13.5037 -3.82577 -30.1883 14.6495 -3.29877 -29.1824 +13.3381 -3.66966 -30.1482 13.9893 -2.49117 -29.1056 +14.0034 -4.1 -30.1776 14.4969 -3.51703 -29.7098 +14.0544 -4.1 -29.6447 14.5478 -3.51703 -29.1781 +13.4919 -4.10034 -29.6545 13.9915 -3.55532 -29.1595 +13.4639 -4.10033 -30.0741 13.9614 -3.55532 -29.6116 +-123.545 0.0949815 96.8518 -122.98 1.07084 97.4162 +-88.9569 0.727581 101.766 -88.6597 1.10242 102.063 +-89.1004 0.876911 101.727 -88.8032 1.25175 102.024 +-89.4108 0.85803 101.644 -89.1137 1.23287 101.941 +-89.5474 0.746663 101.602 -89.2502 1.1215 101.9 +-145.626 2.72758 101.098 -145.329 3.10242 101.395 +-145.694 2.87691 101.23 -145.397 3.25175 101.527 +-145.841 2.85803 101.516 -145.544 3.23287 101.813 +-145.91 2.74666 101.641 -145.613 3.1215 101.938 +-7.20754 8.92746 -47.306 10.413 26.548 -29.6855 +9.93692 -4.70077 -39.9849 11.0679 -4.17377 -38.9974 +9.77262 -4.54466 -39.9627 10.4098 -3.36617 -38.9245 +10.4385 -4.975 -39.9766 10.9272 -4.39203 -39.5143 +10.4772 -4.975 -39.4427 10.9658 -4.39203 -38.9816 +9.91507 -4.97534 -39.4652 10.4093 -4.43032 -38.9758 +9.89677 -4.97533 -39.8854 10.3896 -4.43032 -39.4285 +-115.3 -0.360438 104.719 -114.495 0.809381 105.525 +7.15252 -3.82577 -29.969 8.24365 -3.29877 -28.9915 +6.97231 -3.66966 -29.9922 7.59237 -2.49117 -28.9641 +7.65783 -4.1 -29.9667 8.13364 -3.51703 -29.519 +7.66521 -4.1 -29.4315 8.14101 -3.51703 -28.9849 +7.10534 -4.10034 -29.4867 7.58547 -3.55532 -29.012 +7.1116 -4.10033 -29.9074 7.59191 -3.55532 -29.4651 +54.1312 2.15038 72.0009 55.1245 2.67738 73.1365 +54.159 2.30649 72.6597 55.1987 3.48498 73.3013 +54.1403 1.87615 72.1453 54.6043 2.45912 72.6355 +54.6739 1.87615 72.1028 55.1367 2.45912 72.593 +54.6553 1.87581 72.6594 55.1465 2.42083 73.1553 +54.2354 1.87582 72.6823 54.694 2.42083 73.1766 +-136.487 2.58581 85.5335 -134.989 3.8907 86.4106 +-104.733 -0.802517 96.0464 -102.043 -0.396308 97.7839 +-141.919 1.59296 139.92 -140.421 2.89785 140.797 +14.9753 -1.04662 -11.0322 15.2806 -0.741318 -10.7269 +-2.21013 -5.00757 -42.2289 -0.8771 -3.8465 -41.0607 +-1.18762 -4.61044 -41.6453 -0.866617 -4.32243 -41.3573 +-110.08 -4.48499 115.426 -108.752 -2.97487 117.638 +-137.863 0.637156 98.0864 -137.019 1.80698 98.9303 +-93.6852 -1.3676 134.391 -92.788 -0.25767 135.288 +-118.12 -0.362007 118.138 -117.183 1.00178 119.075 +-104.548 3.55826 96.1703 -101.886 3.96447 97.7535 +-2.31785 -3.64887 -29.1188 -1.43213 -3.2078 -28.5134 +-2.41196 -3.62774 -29.621 -1.30369 -3.15958 -29.0451 +-2.06566 -3.08035 -29.3762 -1.45254 -2.57184 -28.1992 +-2.2892 -3.02233 -29.2837 -1.83184 -2.56429 -28.3349 +-2.47277 -3.27431 -29.2823 -1.3624 -2.76529 -28.7688 +-2.56842 -3.2679 -29.0708 -1.35644 -2.74878 -28.5124 +-2.41087 -3.21368 -28.8366 -1.46401 -2.7379 -28.2903 +-2.42387 -3.41736 -29.52 -2.02111 -2.98237 -28.3996 +-2.28799 -3.61844 -29.8317 -1.7841 -2.89996 -29.0136 +-2.07801 -3.65848 -29.6103 -1.26428 -2.96937 -28.7612 +-1.96959 -3.47034 -29.1988 -1.43737 -2.94257 -28.2368 +-2.45939 -3.62924 -28.7182 -1.28856 -3.17194 -28.2993 +-98.8879 3.59944 97.7517 -96.2157 4.00565 99.3838 +-2.21013 -3.77036 -44.82 -0.8771 -2.63467 -43.6476 +-1.18762 -3.34651 -44.5117 -0.866617 -3.05851 -44.2237 +-113.036 -4.21 105.644 -112.283 -3.27806 106.403 +-22.6322 1.99794 72.5578 -20.7526 2.69 74.4477 +-22.7158 2.40859 72.4772 -20.6774 3.29384 74.5354 +-129.518 1.61873 87.2736 -128.89 2.59458 87.9012 +-17.248 5.12972 54.915 -15.4464 7.26543 56.7166 +-17.2716 4.89003 54.8914 -15.4758 7.11003 56.6873 +-29.8119 -0.218646 148.097 -28.9348 1.08624 149.595 +-116.73 -2.36259 140.086 -115.844 -1.25267 140.98 +-47.6037 1.03636 116.675 -47.1793 1.43827 117.125 +-127.286 5.55609 86.1214 -125.788 6.86098 86.9985 +-126.782 1.515 95.4084 -124.519 3.02512 96.4989 +-119.19 -4.359 121.326 -117.799 -3.13151 122.717 +-118.977 -4.33285 121.524 -118.009 -4.02 122.515 +-47.6639 1.23532 116.587 -47.2395 1.63723 117.037 +23.2437 1.891 72.2133 24.8544 2.58306 73.691 +23.1433 2.30165 72.1689 24.953 3.1869 73.7208 +25.14 9.84363 28.4145 26.24 10.9436 29.5145 +-7.15154 -4.24207 -33.3851 -3.51906 -0.609587 -29.7526 +24.0271 6.82674 -1.41392 24.4001 7.19972 -1.04094 +-4.92664 5.88899 53.7331 -3.12506 7.26439 55.5346 +-4.89727 5.88899 53.7094 -3.1014 7.10899 55.5053 +-113.752 -3.35999 102.478 -112.999 -2.42805 103.237 +-29.185 -2.11104 -1.435 -28.815 -0.735644 0.859994 +-29.2185 -2.11104 -1.36001 -28.7815 -0.891043 0.859994 +19.4799 -1.20383 -71.0825 19.7699 -0.913827 -70.7925 +11.4722 15.1795 -37.361 27.9531 31.6603 -20.8802 +-124.861 1.515 95.9658 -122.598 3.02512 97.0564 +-110.094 -1.3568 123.927 -108.887 1.24713 125.071 +-110.068 -1.35739 124.111 -108.959 1.16354 125.095 +-132.476 0.640013 99.4995 -131.714 1.57195 100.247 +-132.805 2.59587 91.2157 -132.446 3.13706 91.5761 +54.0312 2.15038 74.1229 55.1435 2.67738 75.3505 +53.9312 2.30649 73.9511 54.9919 3.48498 74.6852 +54.6186 1.87615 74.6044 55.118 2.45912 75.1248 +54.0999 1.87615 74.7318 54.598 2.45912 75.2519 +54.0005 1.87581 74.1738 54.527 2.42083 74.704 +54.4435 1.87582 74.0855 54.9382 2.42083 74.609 +-10.5835 5.89003 44.609 -10.1431 7.26543 45.0494 +-10.6215 5.89003 44.571 -10.1067 7.15666 45.0858 +-0.432215 -5.1 -39.185 -0.0622277 -3.7246 -38.815 +-0.465675 -5.1 -39.2053 -0.028767 -3.83337 -38.797 +-16.6538 -4.21 -11.1976 -15.9348 -2.87039 -10.4786 +-16.6647 -4.21243 -11.2083 -15.9286 -2.70133 -10.4685 +22.3641 -3.3502 -24.5833 22.7721 -2.9422 -24.1753 +22.232 -3.18513 -24.6506 22.9122 -2.00976 -24.0689 +-79.4508 33.7629 120.748 -78.5215 34.6922 121.678 +-122.486 -0.35887 97.6424 -121.922 0.616986 98.2067 +0.982275 9.37676 79.6178 1.29027 9.68476 79.9258 +-89.0537 -0.357844 150.597 -88.2108 0.811975 151.44 +-117.388 -0.359414 116.776 -116.043 2.24452 118.133 +-117.226 -0.360001 116.916 -116.039 2.16093 118.127 +-127 -0.262597 101.247 -126.102 0.847328 102.126 +-125.365 7.08581 86.6789 -123.867 8.3907 87.556 +-109.965 0.730193 124.387 -109.668 1.10503 124.685 +-109.82 0.879523 124.42 -109.522 1.25436 124.717 +-109.506 0.860643 124.489 -109.209 1.23548 124.786 +-109.368 0.749275 124.524 -109.07 1.12411 124.822 +-116.977 1.72758 117.613 -116.68 2.10242 117.911 +-116.883 1.87691 117.498 -116.586 2.25175 117.795 +-116.68 1.85803 117.249 -116.383 2.23287 117.547 +-116.586 1.74666 117.142 -116.289 2.1215 117.439 +15.044 -3.04422 -14.1001 15.9537 -2.35438 -13.2188 +24.815 -4.11 28.815 25.185 -2.7346 29.185 +24.7947 -4.11 28.7815 25.203 -2.84337 29.2185 +-108.575 -4.48768 120.477 -106.285 -1.97486 121.575 +-115.562 -0.362595 113.638 -114.669 0.74733 114.537 +2.86807 -5.1 -48.4105 4.53841 -3.72461 -46.7859 +2.86998 -5.1 -48.4105 4.54083 -3.72461 -46.7859 +19.5338 5.889 55.6681 20.6996 7.2644 57.8662 +19.5029 5.889 55.6552 20.7015 7.109 57.8099 +52.4465 2.15038 66.4287 53.5377 2.67738 67.4062 +52.2663 2.30649 66.4056 52.8864 3.48498 67.4337 +52.9518 1.87615 66.431 53.4277 2.45912 66.8788 +52.9592 1.87615 66.9663 53.435 2.45912 67.4128 +52.3994 1.87581 66.9111 52.8795 2.42083 67.3858 +52.4056 1.87582 66.4903 52.8859 2.42083 66.9327 +7.02975 -3.82577 -28.2551 8.12088 -3.29877 -27.2776 +6.84953 -3.66966 -28.2783 7.4696 -2.49117 -27.2502 +7.53506 -4.1 -28.2528 8.01086 -3.51703 -27.8051 +7.54243 -4.1 -27.7176 8.01824 -3.51703 -27.271 +6.98256 -4.10034 -27.7728 7.4627 -3.55532 -27.2981 +6.98883 -4.10033 -28.1935 7.46914 -3.55532 -27.7512 +-48.5959 1.23532 117.699 -48.1715 1.63723 118.149 +-92.775 0.0906666 137.327 -90.8259 0.496875 140.032 +-63.0996 1.80108 131.751 -62.6999 2.34227 132.152 +-118.791 18.4129 132.974 -117.841 19.3629 133.924 +-132.963 2.59587 91.4034 -132.578 3.13706 91.7874 +23.42 -3.16723 33.0813 24.1935 -2.47739 33.8924 +-106.849 -1.36498 125.609 -105.959 -0.255058 126.507 +-136.45 0.537158 98.5081 -135.606 1.70698 99.352 +-9.16928 5.88899 57.9757 -7.3677 7.26439 59.7773 +-9.13991 5.88899 57.952 -7.34404 7.10899 59.7479 +-131.956 0.64217 99.6317 -131.301 1.81199 100.287 +-133.522 0.642169 103.219 -132.867 1.81199 103.874 +38.4931 2.15038 72.8795 39.5842 2.67738 73.857 +39.1444 2.30649 72.852 39.7645 3.48498 73.8801 +38.6031 1.87615 73.407 39.0789 2.45912 73.8547 +38.5958 1.87615 72.8729 39.0716 2.45912 73.3194 +39.1513 1.87581 72.8999 39.6314 2.42083 73.3747 +39.1449 1.87582 73.3531 39.6252 2.42083 73.7954 +-29.185 -2.11104 -3.435 -28.815 -0.735644 -1.14001 +-29.2185 -2.11104 -3.36001 -28.7815 -0.891043 -1.14001 +-49.4036 2.96106 118.388 -49.1136 3.25106 118.678 +-103.333 0.639992 89.6135 -101.333 2.01538 91.6429 +-103.332 0.639992 89.6112 -101.333 2.01538 91.6411 +-87.1038 -1.35682 105.473 -85.9706 1.24711 106.532 +-87.0734 -1.35741 105.444 -86.0225 1.16352 106.349 +-127.286 2.58581 86.1214 -125.788 3.8907 86.9985 +-114.215 -0.358869 108.146 -113.527 0.616987 108.834 +-86.3878 0.730176 105.716 -86.0907 1.10502 106.014 +-86.5356 0.879505 105.731 -86.2385 1.25435 106.028 +-86.8554 0.860625 105.764 -86.5583 1.23546 106.061 +-86.9978 0.749257 105.773 -86.7007 1.1241 106.07 +-83.0079 6.46659 97.8077 -81.0084 7.84198 99.8372 +-83.0073 6.46659 97.8054 -81.0077 7.84198 99.8354 +-20.4703 0.843178 62.9939 -20.1268 1.2029 63.3327 +-20.4081 0.861635 63.027 -20.1527 1.30752 63.3221 +-20.4352 0.861935 63.0037 -20.1727 1.30514 63.3034 +-20.472 0.860546 63.0361 -20.1708 1.30923 63.2803 +-119.099 -2.36259 139.446 -118.211 -1.25267 140.338 +-83.4123 34.6137 121.428 -82.483 35.543 122.358 +-129.127 -0.258871 110.764 -128.563 0.716984 111.329 +-87.4177 31.379 115.908 -86.4885 32.3083 116.838 +-141.294 1.64216 85.2968 -140.457 2.81198 86.1341 +13.3676 -3.82577 -29.2043 14.4733 -3.29877 -28.2271 +13.1955 -3.66966 -29.2112 13.8193 -2.49117 -28.1812 +13.8717 -4.1 -29.1999 14.3522 -3.51703 -28.7468 +13.8904 -4.1 -28.6649 14.3708 -3.51703 -28.213 +13.3294 -4.10034 -28.7084 13.8145 -3.55532 -28.2283 +13.3269 -4.10033 -29.1289 13.8118 -3.55532 -28.6815 +-127.286 7.08581 86.1214 -125.788 8.3907 86.9985 +-121.814 -2.36044 137.921 -121.121 -1.19062 138.613 +53.9817 2.15038 76.0102 55.023 2.67738 77.1846 +53.8931 2.30649 76.6724 54.9416 3.48498 77.3552 +54.0044 1.87615 76.113 54.4854 2.45912 76.6179 +54.5356 1.87615 76.1798 55.0153 2.45912 76.6845 +54.4034 1.87581 76.7223 54.9112 2.42083 77.2352 +53.9876 1.87582 76.6578 54.4638 2.42083 77.1663 +2.53287 3.50262 -29.2607 3.51287 4.48262 -28.2807 +-14.8502 2.734 77.2138 -14.4422 3.142 77.6217 +-14.9937 2.90609 77.1464 -14.3345 4.07479 77.7281 +-106.923 -1.36283 124.854 -106.16 -0.193007 125.617 +-48.3329 1.23532 117.386 -47.9085 1.63723 117.836 +-52.1011 0.676704 89.358 -51.6801 0.937878 89.752 +-73.6291 -0.359363 174.28 -72.5955 2.24457 175.391 +-73.4465 -0.35995 174.327 -72.5652 2.16098 175.36 +-132.896 0.642169 99.6992 -132.241 1.81199 100.355 +-117.903 -0.360438 117.27 -117.093 0.809381 118.08 +-113.931 -0.362007 108.96 -113.185 1.00178 109.706 +14.6225 -3.20015 -35.8359 15.1201 -2.24409 -35.324 +14.7133 -2.38584 -35.6457 14.9333 -2.16584 -35.4257 +-73.1758 1.72763 175.004 -72.8786 2.10247 175.301 +-73.1656 1.87696 174.856 -72.8684 2.2518 175.153 +-73.1435 1.85808 174.535 -72.8463 2.23292 174.832 +-73.1289 1.74671 174.393 -72.8317 2.12155 174.69 +-28.8363 1.28135 144.735 -27.9592 2.58624 146.234 +17.6593 -6.1 -50.18 18.3583 -4.7604 -49.481 +17.6487 -6.10243 -50.1859 18.368 -4.59133 -49.4705 +-99.5128 47.3123 112.602 -98.5835 48.2416 113.531 +-14.4403 5.89003 57.7242 -13.9999 7.26543 58.1646 +-14.4783 5.89003 57.6862 -13.9635 7.15666 58.201 +-13.6053 4.1629 4.99147 -13.2901 4.4781 5.30667 +-62.9822 1.80108 131.507 -62.5823 2.34227 131.907 +-72.3931 0.591607 162.752 -71.2851 1.50464 163.734 +-72.3931 0.591607 162.752 -71.2851 1.50464 163.734 +-71.972 0.721464 163.112 -71.3971 1.17719 163.676 +-72.3189 0.721464 163.028 -71.7692 1.17719 163.555 +9.63087 11.6671 -33.4989 13.8509 15.8871 -29.2789 +-93.3192 -1.36544 133.664 -92.4762 -0.195619 134.507 +-73.5677 0.916573 172.479 -72.7737 1.74386 174.181 +-73.2162 1.03558 172.494 -72.8257 1.62506 172.866 +-73.2208 1.39073 172.511 -72.7959 1.74196 173.315 +-73.3713 1.39073 172.918 -72.8958 1.74236 173.843 +-73.3344 0.923484 172.482 -72.9137 1.27602 173.198 +-73.5635 0.923386 173.33 -73.1379 1.27463 174.146 +-73.457 0.923465 172.801 -72.9986 1.2751 173.746 +-73.2879 0.973395 172.545 -72.8549 1.52206 173.37 +-73.5375 0.97303 172.897 -72.9823 1.64169 174.17 +-73.4516 1.21934 173.487 -73.0132 1.74393 174.179 +21.0785 5.889 59.3578 22.2443 7.2644 61.5559 +21.0476 5.889 59.3449 22.2462 7.109 61.4997 +-74.1501 0.665229 103.318 -73.2067 2.17831 104.219 +-74.1475 0.665093 103.319 -73.2095 2.17603 104.217 +-93.7918 -1.46544 135.061 -92.9489 -0.295617 135.904 +-115.645 -0.362007 114.302 -114.762 1.00178 115.185 +-108.3 -4.48499 107.731 -107.678 -2.97487 109.996 +-116.707 -0.358869 100.058 -116.142 0.616986 100.623 +-29.8119 -1.71865 148.097 -28.9348 -0.413757 149.595 +-1.56782 -4.15896 -18.472 -0.299244 -1.58053 -17.6271 +-1.54126 -4.14614 -18.4637 -0.297706 -1.69549 -17.6354 +-10.4164 -0.280942 104.369 -10.0084 0.127058 104.777 +-10.5227 -0.108852 104.226 -9.93908 1.05985 104.886 +-45.9414 -2.36 149.714 -43.9323 -0.984609 151.691 +-45.9437 -2.36 149.713 -43.9341 -0.984609 151.691 +-78.1481 0.78627 140.756 -76.913 2.01376 141.991 +-78.0116 0.812423 140.878 -77.0404 1.12527 141.861 +-63.055 2.38726 131.228 -62.5946 3.08957 131.688 +-118.494 -0.362595 117.626 -117.591 0.74733 118.534 +-28.8363 -1.71865 144.735 -27.9592 -0.413757 146.234 +-87.3404 3.19262 87.1968 -85.8366 4.7858 89.8759 +-87.3354 3.19262 87.1984 -85.6951 5.14294 89.8762 +-13.7701 -1.20383 -71.0825 -13.4801 -0.913827 -70.7925 +38.6211 2.15038 83.3233 39.7122 2.67738 84.3008 +39.2724 2.30649 83.2959 39.8924 3.48498 84.324 +38.7311 1.87615 83.8508 39.2069 2.45912 84.2985 +38.7237 1.87615 83.3167 39.1995 2.45912 83.7633 +39.2793 1.87581 83.3438 39.7594 2.42083 83.8185 +39.2728 1.87582 83.7969 39.7531 2.42083 84.2392 +-108.737 -2.485 99.6046 -106.473 -0.974881 100.695 +-47.8954 1.03636 117.023 -47.471 1.43827 117.473 +-47.6037 1.63951 116.675 -47.1793 2.04142 117.125 +-130.672 2.23971 153.538 -127.981 2.64592 155.284 +-101.433 -1.35653 126.35 -100.472 -0.458584 127.234 +9.27682 -3.82577 -28.1286 10.3679 -3.29877 -27.1511 +9.92809 -3.66966 -28.1561 10.5482 -2.49117 -27.128 +9.38683 -4.1 -27.6012 9.86264 -3.51703 -27.1534 +9.37945 -4.1 -28.1352 9.85526 -3.51703 -27.6887 +9.93499 -4.10034 -28.1082 10.4151 -3.55532 -27.6335 +9.92855 -4.10033 -27.6551 10.4089 -3.55532 -27.2127 +-91.0959 -1.36625 114.716 -90.2529 -0.196431 115.559 +-114.655 -0.359414 106.648 -113.464 2.24452 107.895 +-114.472 -0.360001 106.671 -113.442 2.16093 107.81 +-2.24611 -4.1 -34.8769 -0.848447 -3.40794 -33.3344 +-2.28479 -3.68935 -34.9805 -0.824718 -2.8041 -33.2357 +-156.885 1.42001 107.875 -156.477 1.82801 108.283 +-156.987 1.5921 107.742 -156.423 2.76081 108.419 +-29.3241 1.28135 146.416 -28.447 2.58624 147.914 +-111.142 -1.37326 124.156 -110.54 -0.397402 124.758 +-7.75507 5.88899 56.5615 -5.95349 7.26439 58.3631 +-7.7257 5.88899 56.5378 -5.92983 7.10899 58.3337 +11.9537 -4.70077 -40.1379 13.0508 -4.17377 -39.1605 +12.6061 -4.54466 -40.172 13.2277 -3.36617 -39.1439 +12.0682 -4.975 -39.6135 12.5459 -4.39203 -39.1636 +12.0563 -4.975 -40.1475 12.534 -4.39203 -39.6988 +12.6124 -4.97534 -40.1252 13.0943 -4.43032 -39.6484 +12.6094 -4.97533 -39.672 13.0916 -4.43032 -39.2278 +-128.421 -0.26044 106.235 -127.657 0.909379 106.998 +6.06779 -4.86031 -39.11 6.43777 -2.7246 -36.815 +6.03432 -5.1 -39.11 6.47123 -2.88 -36.89 +-98.3143 -1.48498 111.261 -97.2238 0.0251353 113.525 +-123.445 2.58581 87.2363 -121.946 3.8907 88.1134 +54.3596 2.15038 79.4219 55.5464 2.67738 80.4799 +55.0239 2.30649 79.3338 55.7153 3.48498 80.3872 +54.547 1.87615 79.9789 55.0539 2.45912 80.4622 +54.4601 1.87615 79.4519 54.9668 2.45912 79.934 +55.0139 1.87581 79.3951 55.5287 2.42083 79.9057 +55.0747 1.87582 79.8441 55.5851 2.42083 80.3225 +-114.017 1.72758 107.389 -113.719 2.10242 107.686 +-114.059 1.87691 107.247 -113.762 2.25175 107.544 +-114.152 1.85803 106.939 -113.855 2.23287 107.236 +-114.189 1.74666 106.801 -113.891 2.1215 107.098 +-142.566 0.64113 130.346 -141.98 1.61699 130.932 +-108.654 -4.48499 105.777 -107.772 -2.97487 108.056 +-117.454 -0.362595 100.158 -116.553 0.74733 101.066 +-96.0844 -1.48498 103.578 -94.9939 0.0251353 105.842 +-144.734 1.65093 135.571 -144.375 2.19212 135.931 +-102.901 0.639992 88.2378 -100.901 2.01538 90.2673 +-102.9 0.639992 88.2355 -100.901 2.01538 90.2655 +-136.487 5.55609 85.5335 -134.989 6.86098 86.4106 +-99.2086 2.09829 97.6856 -96.5362 2.50449 99.3188 +-62.8818 2.50921 130.233 -62.3376 2.76077 131.049 +-118.765 -4.35628 122.291 -118.163 -3.38042 122.893 +-104.733 5.07165 96.0464 -102.043 5.47786 97.7839 +-97.7568 -1.48498 109.34 -96.6663 0.0251353 111.604 +-86.9699 1.67731 87.3131 -85.6776 3.31371 89.8633 +-86.9699 1.67732 87.3131 -85.6771 3.48824 89.8665 +-97.2127 -1.485 102.951 -94.9491 0.025119 104.041 +-47.9691 1.8356 116.952 -47.5447 2.23751 117.401 +-49.5995 -0.275207 67.4449 -48.5902 1.23788 68.4859 +-49.5971 -0.275343 67.4476 -48.5912 1.2356 68.4828 +-75.0362 0.621876 163.981 -74.6795 0.981594 164.333 +-75.0113 0.640333 164 -74.7499 1.08621 164.297 +-74.9886 0.640633 164.017 -74.7129 1.08383 164.315 +-74.9847 0.639243 164.028 -74.684 1.08792 164.286 +-2.87074 7.27308 95.8495 -2.56184 7.58198 96.1584 +-2.24369 -0.0745578 51.796 -1.34815 0.366178 52.4254 +-2.33943 -0.00562347 52.3489 -1.23442 0.474614 52.8984 +-2.24099 0.53561 51.4286 -1.59048 0.946636 52.6208 +-1.85552 0.539636 51.5454 -1.37003 1.01063 52.4939 +-2.30145 0.315723 52.0328 -1.19234 0.826025 52.5144 +-2.31525 0.305833 51.7685 -1.10797 0.81295 52.3073 +-2.22221 0.332161 51.5584 -1.27726 0.795468 52.0714 +-1.66304 0.12062 51.6429 -1.22363 0.650849 52.773 +-1.87512 0.0430032 52.2614 -1.34642 0.710541 53.1003 +-2.39856 -0.068348 52.0701 -1.57143 0.664627 52.865 +-2.25291 0.125447 51.5057 -1.69226 0.580992 52.4631 +-2.39794 -0.101051 51.5825 -1.22796 0.375138 52.0343 +-89.3532 -0.365002 129.543 -88.456 0.744923 130.44 +-141.919 4.59034 139.92 -140.421 5.89523 140.797 +-13.7701 -1.20382 -59.3292 -13.4801 -0.913825 -59.0392 +-18.6622 4.12972 53.5008 -16.8606 6.26543 55.3024 +-18.6859 3.89003 53.4772 -16.89 6.11003 55.273 +-119.687 -0.357085 118.178 -118.792 0.479233 118.997 +-98.8718 -1.48498 113.182 -97.7812 0.0251353 115.445 +-121.727 -2.36259 138.379 -120.972 -1.43065 139.137 +-143.839 1.59296 139.362 -142.341 2.89785 140.24 +-29.185 -2.11104 0.565001 -28.815 -0.735644 2.85999 +-29.2185 -2.11104 0.639995 -28.7815 -0.891043 2.85999 +-29.8119 2.78135 148.097 -28.9348 4.08624 149.595 +-31.6999 -2.06701 -3.56173 -30.0387 -1.37495 -2.02336 +-31.7973 -1.65636 -3.61056 -29.9405 -0.771113 -1.98871 +-114.104 -0.362595 109.539 -113.207 0.74733 110.419 +-88.6113 -1.36159 101.707 -87.3015 -0.1341 103.017 +-88.4347 -1.33544 101.874 -87.4726 -1.0226 102.837 +-62.8255 3.7985 132.62 -62.5355 4.0885 132.91 +-114.138 -0.360438 110.135 -113.343 0.809381 110.929 +-114.382 -3.38127 101.481 -113.797 -2.40541 102.067 +21.935 -1.4779 -24.5914 23.0633 0.131377 -21.9548 +21.9394 -1.47789 -24.5914 23.1761 0.461147 -21.9548 +-29.3241 -0.218646 146.416 -28.447 1.08624 147.914 +33.8907 2.15038 83.3145 34.9818 2.67738 84.292 +33.7105 2.30649 83.2914 34.3305 3.48498 84.3195 +34.396 1.87615 83.3168 34.8718 2.45912 83.7645 +34.4034 1.87615 83.8521 34.8792 2.45912 84.2986 +33.8435 1.87581 83.7968 34.3236 2.42083 84.2716 +33.8498 1.87582 83.3761 34.3301 2.42083 83.8184 +-143.839 3.06324 139.362 -142.341 4.36813 140.24 +-80.6858 32.2763 125.788 -79.7565 33.2056 126.717 +-116.079 4.63896 145.49 -115.132 6.01436 147.749 +-116.09 4.63896 145.481 -115.1 5.85896 147.687 +-109.211 -4.48499 103.905 -108.117 -2.97487 106.168 +-123.445 5.55609 87.2363 -121.946 6.86098 88.1134 +-88.5077 -1.36468 125.292 -87.8061 -0.388826 125.994 +-96.5391 -1.36024 144.19 -95.3512 -0.286871 145.378 +-96.3815 -1.33951 144.356 -95.5125 -1.0406 145.208 +-72.0424 -0.357793 170.275 -71.1995 0.812027 171.118 +-8.9817 4.95685 72.5604 -8.6773 5.26125 72.8648 +-174.771 2.49108 97.468 -174.363 2.89908 97.876 +-174.906 2.66317 97.3664 -174.229 3.83187 97.9302 +-88.9168 -0.359002 147.529 -87.5249 0.868493 148.921 +-88.706 -0.332849 147.731 -87.7382 -0.020003 148.721 +-36.8744 -2.36 152.345 -34.8653 -0.984609 154.323 +-36.8767 -2.36 152.344 -34.8671 -0.984609 154.322 +15.4061 -3.82577 -28.9962 16.5462 -3.29877 -27.9983 +16.0629 -3.66966 -28.9585 16.7141 -2.49117 -27.9187 +15.5095 -4.1 -28.4614 16.0033 -3.51703 -27.9933 +15.5466 -4.1 -28.9943 16.0402 -3.51703 -28.5273 +16.0956 -4.10034 -28.9209 16.5959 -3.55532 -28.4258 +16.0543 -4.10033 -28.4702 16.5521 -3.55532 -28.0071 +-13.7701 -1.20383 -83.0825 -13.4801 -0.913827 -82.7925 +-141.56 12.5988 104.595 -140.88 13.2788 105.275 +-62.6037 2.03265 130.562 -62.2589 2.43457 131.043 +-85.8764 3.19262 91.59 -83.1974 4.7858 93.0938 +-85.8749 3.19262 91.4485 -83.1971 5.14294 93.0888 +-54.447 -0.320558 84.1729 -53.3074 1.19253 85.3071 +-54.4438 -0.320694 84.1748 -53.3096 1.19025 85.3041 +4.92234 9.35806 79.7031 5.23574 9.67146 80.0165 +-29.8119 1.28135 148.097 -28.9348 2.58624 149.595 +-116.443 -2.35887 139.732 -115.755 -1.38301 140.42 +1.36807 -5.1 -48.4105 3.03841 -3.72461 -46.7859 +1.36998 -5.1 -48.4105 3.04083 -3.72461 -46.7859 +-3.67917 1.57673 -17.1296 -3.36757 1.88833 -16.818 +-29.5345 -2.35941 143.358 -28.2888 0.24452 144.649 +-29.3547 -2.36 143.377 -28.2715 0.16093 144.548 +-28.8431 -0.272417 144.101 -28.546 0.102423 144.398 +-28.8999 -0.123087 143.963 -28.6028 0.251753 144.26 +-29.0227 -0.141967 143.666 -28.7255 0.232873 143.963 +-29.0728 -0.253335 143.533 -28.7756 0.121505 143.83 +-37.4494 2.86709 78.933 -37.1594 3.15709 79.223 +-78.2501 10.9319 136.432 -77.3208 11.8612 137.362 +20.3061 5.889 57.5129 21.4719 7.2644 59.7111 +20.2753 5.889 57.5 21.4738 7.109 59.6548 +-62.9582 2.38726 131.489 -62.4985 3.08957 131.948 +9.24592 1.8204 81.4171 9.92837 2.26794 82.3392 +9.80706 1.85392 81.2645 10.4004 2.32797 82.3721 +8.96993 2.40061 81.6322 10.1574 2.89321 82.3521 +9.05976 2.45352 81.4199 10.0117 2.89809 81.9595 +9.5489 2.20694 81.2449 10.0119 2.70623 82.3642 +9.28332 2.20916 81.1816 9.85761 2.72589 82.4009 +9.06249 2.25821 81.3861 9.58082 2.72364 82.3263 +9.1156 2.04447 81.2595 10.2361 2.49753 81.768 +9.75179 1.86924 81.3582 10.5677 2.57686 81.9276 +9.57012 1.82048 81.6062 10.3803 2.51436 82.4623 +9.0156 2.00879 81.7523 9.98439 2.52335 82.3663 +9.01778 1.83036 81.331 9.54474 2.29931 82.5053 +-3.52782 2.93043 -37.361 12.9531 19.4113 -20.8802 +-97.205 5.59588 150.849 -96.8458 6.13707 151.21 +-15.8868 5.88899 57.7435 -14.0852 7.26439 59.5451 +-15.8574 5.88899 57.7198 -14.0616 7.10899 59.5157 +-0.131927 -5.1 -48.4105 1.53841 -3.72461 -46.7859 +-0.130019 -5.1 -48.4105 1.54083 -3.72461 -46.7859 +-0.516664 -0.0914472 -47.584 6.37777 3.26823 -47.166 +-48.2491 1.03636 117.445 -47.8247 1.43827 117.895 +-118.857 -0.358869 117.95 -118.148 0.616987 118.66 +-145.76 4.59034 138.805 -144.262 5.89523 139.682 +14.4418 -3.82577 -26.9851 15.4193 -3.29877 -25.894 +14.4187 -3.66966 -26.3339 15.4468 -2.49117 -25.7138 +14.4441 -4.1 -26.8751 14.8918 -3.51703 -26.3993 +14.9794 -4.1 -26.8825 15.4259 -3.51703 -26.4067 +14.9241 -4.10034 -26.327 15.3989 -3.55532 -25.8468 +14.5034 -4.10033 -26.3334 14.9457 -3.55532 -25.8531 +-48.5297 1.63951 117.78 -48.1054 2.04142 118.23 +-117.418 -0.358869 116.552 -116.826 0.616986 117.144 +-63.1445 2.38726 131.736 -62.6735 3.08957 132.207 +-114.201 -2.3676 129.869 -113.303 -1.25767 130.748 +-79.4516 38.0424 122.046 -78.5224 38.9717 122.975 +-19.7653 -3.06444 2.93689 -19.0533 -2.41133 3.6849 +-7.15154 -0.928769 -33.3851 -3.51906 2.70371 -29.7526 +-138.783 0.640586 141.423 -137.542 3.24452 142.608 +-138.76 0.639999 141.606 -137.624 3.16093 142.63 +26.815 -0.111044 32.815 29.11 1.26436 33.185 +26.89 -0.111044 32.7816 29.11 1.10896 33.2185 +-115.518 4.63896 143.558 -114.571 6.01436 145.817 +-115.53 4.63896 143.548 -114.539 5.85896 145.754 +-107.818 -1.3568 124.685 -106.601 1.24713 125.84 +-107.743 -1.35739 124.661 -106.626 1.16354 125.656 +-18.6829 3.89003 53.4816 -18.2425 5.26543 53.922 +-18.7209 3.89003 53.4436 -18.2061 5.15666 53.9584 +-115.81 -0.360438 103.602 -115.154 0.809381 104.258 +-63.0792 1.64401 132.511 -62.3703 2.19713 133.238 +52.1656 2.15038 79.73 53.2567 2.67738 80.7075 +51.9853 2.30649 79.7069 52.6054 3.48498 80.735 +52.6709 1.87615 79.7323 53.1467 2.45912 80.18 +52.6782 1.87615 80.2676 53.154 2.45912 80.7141 +52.1184 1.87581 80.2123 52.5985 2.42083 80.6871 +52.1246 1.87582 79.7916 52.6049 2.42083 80.2339 +-25.5132 5.9156 0.398232 -24.4132 7.0156 1.49823 +11.4795 -3.82577 -36.0256 12.5766 -3.29877 -35.0482 +12.1319 -3.66966 -36.0597 12.7536 -2.49117 -35.0317 +11.594 -4.1 -35.5013 12.0717 -3.51703 -35.0514 +11.5821 -4.1 -36.0353 12.0598 -3.51703 -35.5866 +12.1383 -4.10034 -36.013 12.6201 -3.55532 -35.5361 +12.1353 -4.10033 -35.5598 12.6174 -3.55532 -35.1156 +-111.101 -4.48499 117.202 -109.555 -2.97487 119.329 +-111.622 -1.34947 124.516 -110.784 -0.513155 125.407 +22.7263 -3.07819 -27.8058 24.4641 -1.55946 -26.3372 +22.7083 -2.66137 -27.2315 23.0733 -2.34137 -26.9115 +-141.685 1.64216 85.049 -140.848 2.81198 85.8864 +-32.298 -2.35941 152.533 -30.953 0.24452 153.854 +-32.1702 -2.36 152.702 -30.9632 0.16093 153.863 +-112.574 -4.35449 104.828 -111.736 -3.51817 105.719 +-7.15154 5.59766 -33.3851 -3.51906 9.23014 -29.7526 +-129.735 0.640586 143.685 -128.473 3.24452 144.894 +-129.646 0.639999 143.867 -128.495 3.16093 144.915 +-138.639 2.72758 141.883 -138.341 3.10242 142.18 +-138.496 2.87691 141.924 -138.199 3.25175 142.221 +-138.187 2.85803 142.014 -137.89 3.23287 142.311 +-138.052 2.74666 142.058 -137.755 3.1215 142.355 +-107.031 0.730193 125.082 -106.734 1.10503 125.379 +-107.176 0.879523 125.048 -106.879 1.25436 125.345 +-107.488 0.860643 124.973 -107.191 1.23548 125.27 +-107.626 0.749275 124.935 -107.329 1.12411 125.232 +-31.9741 -0.272417 153.305 -31.677 0.102423 153.602 +-31.8502 -0.123087 153.223 -31.5531 0.251753 153.52 +-31.582 -0.141967 153.046 -31.2849 0.232873 153.343 +-31.4604 -0.253335 152.971 -31.1632 0.121505 153.268 +-129.513 2.72758 144.341 -129.216 3.10242 144.638 +-129.372 2.87691 144.294 -129.075 3.25175 144.591 +-129.068 2.85803 144.191 -128.77 3.23287 144.489 +-128.931 2.74666 144.151 -128.634 3.1215 144.448 +-108.916 -2.485 99.531 -108.245 -0.750488 100.202 +-7.70204 5.88899 47.4904 -5.90046 7.26439 49.292 +-7.7257 5.88899 47.4668 -5.92983 7.10899 49.2626 +-138.408 2.58581 84.9761 -136.909 3.8907 85.8532 +47.8092 2.15038 66.3272 48.9003 2.67738 67.3047 +47.629 2.30649 66.3041 48.249 3.48498 67.3322 +48.3145 1.87615 66.3295 48.7903 2.45912 66.7772 +48.3219 1.87615 66.8648 48.7977 2.45912 67.3113 +47.762 1.87581 66.8095 48.2421 2.42083 67.2843 +47.7683 1.87582 66.3888 48.2486 2.42083 66.8311 +-117.016 -0.360438 116.425 -116.323 0.809381 117.119 +-110.715 0.590635 94.1778 -108.025 0.996844 95.9153 +-2.21013 -4.99488 -46.04 -0.8771 -3.85919 -44.8676 +-1.18762 -4.57104 -45.7316 -0.866617 -4.28304 -45.4436 +-126.349 -0.360438 100.963 -125.693 0.809381 101.618 +-127.794 1.63716 86.5697 -127.122 2.80698 87.2413 +-141.919 3.06324 139.92 -140.421 4.36813 140.797 +-29.3241 -1.71865 146.416 -28.447 -0.413757 147.914 +-114.83 -0.360438 113.798 -114.055 0.809381 114.572 +-9.13846 4.9566 76.0779 -8.82866 5.26639 76.3877 +-3.14502 -1.20383 -71.145 -2.85502 -0.913828 -70.855 +-106.898 -1.38126 126.129 -106.247 -0.405403 126.779 +8.0027 -3.82577 -27.2319 8.98016 -3.29877 -26.1391 +7.98138 -3.66966 -26.5803 9.00946 -2.49117 -25.9598 +8.00523 -4.1 -27.1206 8.45355 -3.51703 -26.6443 +8.54048 -4.1 -27.1293 8.98761 -3.51703 -26.6529 +8.48662 -4.10034 -26.5733 8.96189 -3.55532 -26.0929 +8.06612 -4.10033 -26.579 8.50874 -3.55532 -26.0983 +54.3836 2.15038 66.6543 55.5644 2.67738 67.7036 +55.0466 2.30649 66.7441 55.7354 3.48498 67.794 +54.4864 1.87615 67.1923 54.9932 2.45912 67.6756 +54.5589 1.87615 66.663 55.0656 2.45912 67.1452 +55.1 1.87581 66.773 55.6151 2.42083 67.2832 +55.0309 1.87582 67.2197 55.5414 2.42083 67.6983 +-119.251 -4.3316 122.188 -118.549 -3.16178 122.89 +-2.21013 -4.37639 -45.4484 -0.8771 -3.2407 -44.276 +-1.18762 -3.95255 -45.14 -0.866616 -3.66455 -44.852 +-1.31184 7.00563 63.7765 -0.966046 7.35142 64.1223 +-105.018 2.04384 95.9656 -102.328 2.45005 97.7031 +44.7874 -2.7906 -5.27459 45.5576 -1.451 -4.50445 +44.7761 -2.79303 -5.28188 45.5688 -1.28193 -4.49243 +-13.9798 4.41724 33.1913 -13.5032 5.29803 37.9409 +-128.383 -0.262597 105.45 -127.482 0.847328 106.359 +17.4262 -0.11 30.5779 18.8517 0.582058 32.1443 +17.3856 0.300652 30.4753 18.8775 1.1859 32.243 +24.89 -3.87031 28.815 27.185 -1.7346 29.185 +24.89 -4.11 28.7815 27.11 -1.89 29.2185 +-143.839 4.59034 139.362 -142.341 5.89523 140.24 +-86.2119 0.338897 173.44 -85.0535 0.633679 175.231 +-85.7791 0.357357 173.474 -85.1735 0.63268 173.899 +-85.5281 0.358085 173.557 -85.0553 0.633408 174.376 +-85.665 0.358085 173.97 -85.1553 0.635282 174.894 +-85.9814 0.358029 173.443 -85.5236 0.635533 174.151 +-86.2102 0.358085 174.296 -85.7374 0.633408 175.115 +-86.1102 0.358085 173.778 -85.6005 0.635282 174.703 +-85.9193 0.338615 173.508 -85.2953 0.604176 174.37 +-86.1421 0.337116 173.878 -85.426 0.639426 175.203 +-85.8246 0.330543 174.517 -85.2888 0.641625 175.229 +-23.4851 2.14987 72.0393 -22.1744 2.67687 73.3806 +-23.6365 2.30598 72.641 -22.629 3.48447 73.5497 +-23.2165 1.87564 72.1229 -22.6602 2.45861 72.6844 +-22.7868 1.87564 72.4423 -22.2315 2.45861 73.0031 +-23.1709 1.8753 72.85 -22.5911 2.42032 73.4313 +-23.5012 1.87531 72.5894 -22.9465 2.42032 73.151 +-47.9691 1.23532 116.952 -47.5447 1.63723 117.401 +-114.568 -0.360438 110.04 -113.904 0.809381 110.703 +0.640972 -0.710183 -18.6418 5.52247 1.69942 -18.2894 +-25.185 -4.11 2.565 -24.815 -2.7346 2.93499 +-25.203 -4.11 2.53154 -24.7947 -2.84337 2.96845 +-112.03 -1.35941 147.796 -110.813 1.24452 148.951 +-111.955 -1.36 147.772 -110.839 1.16093 148.767 +-70.0163 -0.275207 89.8088 -69.0597 1.23788 90.8028 +-70.0142 -0.275343 89.8117 -69.0605 1.2356 90.8001 +27.3262 1.89 46.2891 29.4081 3.26539 48.3955 +27.3253 1.89 46.2869 29.4073 3.26539 48.3937 +-127.286 10.0561 86.1214 -125.788 11.361 86.9985 +-128.796 -0.26044 104.524 -128.14 0.909379 105.179 +21.8508 5.889 61.2027 23.0166 7.2644 63.4008 +21.8199 5.889 61.1897 23.0185 7.109 63.3445 +-125.365 4.05609 86.6789 -123.867 5.36098 87.556 +-132.609 2.59587 91.8589 -132.201 3.13706 92.2667 +-111.244 0.727581 148.193 -110.946 1.10242 148.49 +-111.388 0.876911 148.158 -111.091 1.25175 148.455 +-111.701 0.858031 148.084 -111.403 1.23287 148.381 +-111.838 0.746663 148.046 -111.541 1.1215 148.343 +14.3679 -2.46032 -11.7407 14.8831 -2.1889 -11.2785 +-116.961 -0.360983 100.737 -115.932 0.598599 101.681 +-2.21013 -4.41302 -42.8461 -0.8771 -3.24062 -41.7104 +-1.18762 -4.10468 -42.4222 -0.866616 -3.81668 -42.1342 +-48.5617 -0.22766 124.31 -47.7393 1.11195 125.132 +-48.5748 -0.230086 124.301 -47.7283 1.28101 125.145 +-126.403 -0.35887 101.436 -125.838 0.616986 102.001 +-134.275 0.641625 103.022 -133.246 1.60121 103.966 +-30.2997 -0.218646 149.778 -29.4225 1.08624 151.276 +-30.2997 1.28135 149.778 -29.4225 2.58624 151.276 +-130.734 1.67259 153.514 -128.041 2.0788 155.276 +-48.5959 1.8356 117.699 -48.1715 2.23751 118.149 +-99.9867 -1.48498 117.023 -98.8962 0.0251353 119.287 +11.4722 2.93043 -37.361 27.9531 19.4113 -20.8802 +-13.6427 -0.212952 38.9273 -12.7569 0.228122 39.5327 +-13.7368 -0.191817 38.4252 -12.6285 0.276345 39.001 +-13.3905 0.355576 38.6699 -12.7773 0.864085 39.8469 +-13.614 0.413593 38.7625 -13.1566 0.87163 39.7112 +-13.7976 0.161617 38.7638 -12.6872 0.670633 39.2774 +-13.8932 0.168018 38.9753 -12.6812 0.687147 39.5337 +-13.7357 0.222247 39.2095 -12.7888 0.698022 39.7558 +-13.7487 0.0185635 38.5262 -13.3459 0.453548 39.6466 +-13.6128 -0.182518 38.2144 -13.1089 0.535967 39.0325 +-13.4028 -0.222556 38.4358 -12.5891 0.466553 39.2849 +-13.2944 -0.0344165 38.8473 -12.7622 0.493352 39.8093 +-13.7842 -0.193322 39.328 -12.6134 0.263987 39.7468 +-2.21013 -4.99488 -43.5361 -0.8771 -3.85919 -42.3637 +-1.18762 -4.57104 -43.2277 -0.866616 -4.28304 -42.9397 +-116.041 -2.36201 140.274 -115.263 -0.998223 141.053 +-144.982 0.640135 119.888 -143.981 2.15322 120.921 +-144.981 0.64 119.891 -143.984 2.15094 120.918 +-84.5663 -0.359901 169.494 -83.2754 2.24403 170.818 +-84.3912 -0.360488 169.508 -83.2627 2.16044 170.703 +-29.185 -2.11104 -1.435 -28.815 -0.735644 0.859994 +-29.2185 -2.11104 -1.36001 -28.7815 -0.891043 0.859994 +-84.8906 -0.359489 168.331 -83.4988 0.868006 169.723 +-84.6799 -0.333335 168.534 -83.7121 -0.0204899 169.524 +-116.188 -0.358187 114.694 -115.439 0.354868 115.427 +-111.629 -1.35283 124.053 -110.926 -0.183007 124.755 +-45.1273 -0.36736 143.629 -44.2502 0.937529 145.127 +-62.7488 1.8079 130.517 -62.4039 2.20982 130.998 +-109.298 -4.48499 113.553 -108.208 -2.97487 115.816 +-125.365 5.55609 86.6789 -123.867 6.86098 87.556 +-83.8285 1.72709 170.23 -83.5313 2.10193 170.527 +-83.8989 1.87642 170.099 -83.6017 2.25126 170.396 +-84.0512 1.85754 169.816 -83.754 2.23238 170.113 +-84.1146 1.74618 169.688 -83.8174 2.12102 169.985 +-100.548 18.3692 138.305 -99.5977 19.3192 139.255 +-145.76 1.59296 138.805 -144.262 2.89785 139.682 +28.6797 1.89 49.5168 30.7615 3.26539 51.6232 +28.6787 1.89 49.5146 30.7608 3.26539 51.6215 +20.4458 1.8356 73.6618 21.328 4.41403 74.9525 +20.4549 1.84842 73.6887 21.3198 4.29907 74.9538 +-106.57 -1.36283 126.286 -105.807 -0.193007 127.049 +-49.3614 0.693129 89.5077 -48.6029 1.32909 90.2959 +-9.11625 5.88899 46.0762 -7.31467 7.26439 47.8778 +-9.13992 5.88899 46.0526 -7.34404 7.10899 47.8484 +-114.566 -0.359414 111.51 -113.321 2.24452 112.8 +-114.387 -0.360001 111.61 -113.304 2.16093 112.782 +6.93036 7.02621 63.7864 7.26223 7.35808 64.1183 +24.815 -0.111044 32.815 27.11 1.26436 33.185 +24.89 -0.111044 32.7816 27.11 1.10896 33.2185 +-114.33 -3.36499 102.199 -113.444 -2.25507 103.093 +-123.445 8.55609 87.2363 -121.946 9.86098 88.1134 +-107.257 -1.35998 125.274 -106.501 -0.428043 126.037 +-122.222 -0.367595 97.3034 -121.189 0.920315 98.3149 +-114.112 1.72758 112.334 -113.815 2.10242 112.631 +-114.055 1.87691 112.197 -113.758 2.25175 112.494 +-113.933 1.85803 111.9 -113.636 2.23287 112.197 +-113.874 1.74666 111.77 -113.577 2.1215 112.067 +29.1949 1.89 50.7476 31.2767 3.26539 52.854 +29.194 1.89 50.7454 31.276 3.26539 52.8522 +-137.126 0.635 98.3756 -136.23 1.74492 99.2679 +-93.7986 -1.3626 133.866 -93.0368 -0.430655 134.628 +-63.319 1.80108 131.841 -62.9121 2.34227 132.248 +-88.2867 -0.359001 145.827 -87.0643 0.868493 147.049 +-88.1673 -0.332848 145.951 -87.1958 -0.0200025 146.933 +-85.3533 34.4937 120.806 -84.424 35.423 121.735 +33.9834 2.15038 72.8584 35.0926 2.67738 73.8355 +33.8133 2.30649 72.8555 34.438 3.48498 73.8866 +34.4873 1.87615 72.8634 34.9689 2.45912 73.3177 +34.5086 1.87615 73.3983 34.9902 2.45912 73.8514 +33.9475 1.87581 73.3576 34.4338 2.42083 73.839 +33.9429 1.87582 72.9371 34.4288 2.42083 73.3858 +-133.062 0.64217 99.2669 -132.406 1.81199 99.9223 +-84.8192 -0.359901 169.309 -83.6366 2.24403 170.548 +-84.8413 -0.360488 169.332 -83.8196 2.16044 170.466 +-123.445 4.05609 87.2363 -121.946 5.36098 88.1134 +-105.964 -0.40412 152.562 -105.605 0.13707 152.922 +-110.434 -0.802517 94.4305 -107.744 -0.396308 96.168 +14.9239 -1.04952 -14.6106 15.2328 -0.740618 -14.3017 +-94.457 -0.359414 159.087 -93.4234 2.24452 160.198 +-94.2745 -0.360001 159.133 -93.3932 2.16093 160.166 +-136.054 1.641 85.9884 -134.664 2.86849 87.3784 +-135.837 1.66715 86.2003 -134.867 1.98 87.1673 +-84.3938 1.72709 169.452 -84.0966 2.10193 169.749 +-84.4346 1.87642 169.595 -84.1375 2.25126 169.892 +-84.5229 1.85754 169.904 -84.2257 2.23238 170.201 +-84.5667 1.74618 170.04 -84.2695 2.12102 170.337 +-94.0037 1.72758 159.81 -93.7066 2.10242 160.108 +-93.9935 1.87691 159.662 -93.6964 2.25175 159.959 +-93.9714 1.85803 159.342 -93.6743 2.23287 159.639 +-93.9568 1.74666 159.2 -93.6597 2.1215 159.497 +-118.572 -2.35708 138.926 -117.748 -1.52077 139.82 +-3.47722 5.88899 51.7902 -3.10723 7.26439 54.0852 +-3.51068 5.88899 51.7902 -3.07377 7.10899 54.0102 +-47.2694 2.94526 115.858 -46.9794 3.23526 116.148 +21.935 -1.4779 -35.9911 23.0633 0.131377 -33.3545 +21.9394 -1.47789 -35.9911 23.1761 0.461146 -33.3545 +-112.899 -4.20628 106.178 -112.314 -3.23042 106.763 +-30.2997 2.78135 149.778 -29.4225 4.08624 151.276 +-62.7386 2.03265 131 -62.3938 2.43457 131.48 +-142.779 0.638405 130.604 -141.508 1.8659 131.875 +-142.639 0.664558 130.755 -141.655 0.977404 131.724 +-101.102 -1.48498 120.865 -100.011 0.0251353 123.128 +-2.21013 -4.99488 -44.8198 -0.8771 -3.82248 -43.6841 +-1.18762 -4.41882 -44.396 -0.866616 -4.13082 -44.108 +-48.2491 1.63951 117.445 -47.8247 2.04142 117.895 +-116.295 4.63896 147.28 -114.035 6.01436 148.227 +-116.304 4.63896 147.247 -114.098 5.85896 148.238 +-94.9086 47.3123 122.029 -93.9793 48.2416 122.959 +-85.7601 1.67731 91.431 -83.21 3.31371 92.7233 +-85.7601 1.67732 91.4305 -83.2068 3.48824 92.7233 +-99.4293 -1.48498 115.103 -98.3387 0.0251353 117.366 +-140.627 1.64051 85.3294 -139.803 2.47683 86.2235 +-83.1468 -1.359 107.455 -82.0516 -0.131506 108.55 +-83.0962 -1.33285 107.521 -82.1084 -1.02 108.479 +-18.7152 5.88899 59.1047 -16.9136 7.26439 60.9062 +-18.6859 5.88899 59.134 -16.89 7.10899 60.9299 +19.4514 -3.16723 33.0696 20.2249 -2.47739 33.8807 +-108.742 -4.48499 111.631 -107.815 -2.97487 113.909 +-39.0294 8.10124 145.893 -38.4094 8.72124 146.513 +-148.599 0.640587 109.253 -147.425 3.24452 110.486 +-148.621 0.64 109.277 -147.608 3.16093 110.406 +-21.5444 5.88899 56.277 -19.7428 7.26439 58.0785 +-21.515 5.88899 56.3063 -19.7191 7.10899 58.1022 +-148.182 2.72758 109.393 -147.885 3.10242 109.691 +-148.221 2.87691 109.537 -147.924 3.25175 109.834 +-148.305 2.85803 109.847 -148.008 3.23287 110.144 +-148.347 2.74666 109.983 -148.05 3.1215 110.281 +-7.15154 2.28842 -33.3851 -3.51906 5.9209 -29.7526 +-107.034 -0.40412 153.931 -106.675 0.13707 154.292 +-21.8227 -0.109858 63.496 -20.6825 1.40323 64.6359 +-21.8206 -0.109994 63.4981 -20.6856 1.40095 64.6329 +-84.7151 1.68041 80.2405 -84.3072 2.08841 80.6485 +-84.8458 1.8525 80.1866 -84.169 3.0212 80.7482 +6.14278 -4.10104 -37.185 8.43777 -2.72564 -36.815 +6.14278 -4.10104 -37.2184 8.36278 -2.88104 -36.7815 +-38.2934 -2.36 151.933 -36.2842 -0.984609 153.911 +-38.2957 -2.36 151.933 -36.2861 -0.984609 153.911 +-112.462 -1.36498 128.008 -111.564 -0.255059 128.905 +-96.6419 -1.48498 105.499 -95.5513 0.0251353 107.762 +-132.769 1.515 98.8772 -130.505 3.02512 99.9677 +-20.1302 5.88899 57.6912 -18.3286 7.26439 59.4927 +-20.1008 5.88899 57.7205 -18.3049 7.10899 59.5164 +-115.733 -0.357085 114.914 -114.855 0.479233 115.78 +-126.962 1.515 95.3348 -126.291 3.24951 96.006 +-98.2142 4.64059 151.605 -96.9825 7.24452 152.885 +-98.2327 4.64 151.625 -97.1634 7.16093 152.789 +28.5089 10.9699 78.2415 29.6089 12.0699 79.3415 +-63.1228 1.80108 131.392 -62.7229 2.34227 131.793 +-97.736 6.72758 151.769 -97.4389 7.10242 152.066 +-97.789 6.87691 151.907 -97.4918 7.25175 152.205 +-97.9035 6.85803 152.208 -97.6064 7.23287 152.505 +-97.9589 6.74666 152.339 -97.6617 7.1215 152.636 +-0.432215 -4.86031 -39.11 -0.0622273 -2.7246 -36.815 +-0.465676 -5.1 -39.11 -0.0287666 -2.88 -36.89 +-82.5037 6.46659 96.2015 -80.5042 7.84198 98.2309 +-82.5032 6.46659 96.1991 -80.5035 7.84198 98.2291 +-116.313 -0.360438 100.339 -115.633 0.809381 101.019 +-136.071 18.3347 127.978 -135.121 19.2847 128.928 +-3.95956 -0.143365 48.8822 -2.54688 2.43506 50.2926 +-3.95485 -0.130547 48.8869 -2.57154 2.3201 50.268 +-40.6878 -2.36 151.238 -38.6787 -0.984609 153.216 +-40.6901 -2.36 151.238 -38.6805 -0.984609 153.216 +-112.571 -1.36283 127.437 -111.783 -0.193008 128.224 +-99.0886 0.590635 97.6446 -96.3988 0.996844 99.3821 +-93.8754 -0.359414 159.246 -92.6074 2.24452 160.463 +-93.8543 -0.360001 159.226 -92.6991 2.16093 160.281 +-148.836 1.42001 115.544 -148.428 1.82801 115.952 +-148.891 1.5921 115.408 -148.327 2.76081 116.084 +14.5329 3.17034 -29.5078 15.5129 4.15034 -28.5278 +-140.328 2.58581 84.4186 -138.83 3.8907 85.2957 +-104.895 -2.485 100.719 -102.632 -0.974881 101.81 +-114.727 -0.358869 113.455 -114.108 0.616987 114.074 +-117.469 -1.35941 146.474 -116.253 1.24452 147.629 +-117.394 -1.36 146.45 -116.278 1.16093 147.445 +10.1728 -3.82577 -23.0738 11.264 -3.29877 -22.0963 +9.99262 -3.66966 -23.0969 10.6127 -2.49117 -22.0688 +10.6781 -4.1 -23.0715 11.1539 -3.51703 -22.6237 +10.6855 -4.1 -22.5362 11.1613 -3.51703 -22.0897 +10.1256 -4.10034 -22.5914 10.6058 -3.55532 -22.1167 +10.1319 -4.10033 -23.0122 10.6122 -3.55532 -22.5698 +-52.1319 0.880716 90.6155 -51.0463 1.79375 91.5623 +-52.1319 0.880716 90.6155 -51.0463 1.79375 91.5623 +-52.0393 1.01057 90.6653 -51.4624 1.4663 91.2254 +-51.6649 1.01057 90.7603 -51.1077 1.4663 91.2893 +-127.946 -0.26044 106.404 -127.105 0.90938 107.246 +-127.286 8.55609 86.1214 -125.788 9.86098 86.9985 +-93.1325 1.72758 159.502 -92.8354 2.10242 159.799 +-93.2727 1.87691 159.551 -92.9756 2.25175 159.848 +-93.5759 1.85803 159.658 -93.2788 2.23287 159.955 +-93.7121 1.74666 159.701 -93.415 2.1215 159.998 +-116.683 0.727581 146.871 -116.386 1.10242 147.168 +-116.827 0.876911 146.836 -116.53 1.25175 147.134 +-117.14 0.858031 146.762 -116.843 1.23287 147.059 +-117.278 0.746663 146.724 -116.981 1.1215 147.021 +-96.1603 -0.356735 158.382 -94.4561 0.470556 158.998 +-94.8224 -0.237724 158.567 -94.4655 0.351756 158.946 +-95.2856 0.117417 158.614 -94.4716 0.468654 158.976 +-95.8292 0.117417 158.541 -94.8842 0.469056 158.928 +-95.1783 -0.349824 158.495 -94.4583 0.00271235 158.856 +-96.144 -0.349923 158.386 -95.3239 0.00132515 158.746 +-95.7375 -0.349843 158.436 -94.7799 0.00179625 158.815 +-95.3419 -0.299913 158.544 -94.5163 0.248754 158.924 +-96.1541 -0.300278 158.405 -94.873 0.368384 158.86 +-96.1591 -0.0539711 158.5 -95.4582 0.470622 158.881 +-123.445 10.0561 87.2363 -121.946 11.361 88.1134 +-130.812 1.64318 91.0589 -129.624 4.24711 92.3033 +-130.834 1.64259 91.082 -129.807 4.16352 92.2195 +-90.6689 -1.3676 114.383 -89.7717 -0.25767 115.281 +-42.1068 -2.36 150.826 -40.0976 -0.984609 152.804 +-42.1091 -2.36 150.826 -40.0995 -0.984609 152.804 +-11.9238 -0.156827 98.4617 -11.5692 0.20289 98.812 +-11.8987 -0.13837 98.479 -11.6395 0.30751 98.7761 +-11.8764 -0.13807 98.4968 -11.6031 0.30513 98.7953 +-11.8736 -0.13946 98.5101 -11.5726 0.309221 98.7659 +-63.17 1.80108 131.981 -62.766 2.34227 132.386 +-109.963 -4.48499 102.094 -108.665 -2.97487 104.315 +-48.5297 1.03636 117.78 -48.1054 1.43827 118.23 +8.85498 -1.20383 -59.145 9.14498 -0.913829 -58.855 +-100.544 -1.48498 118.944 -99.4536 0.0251353 121.208 +-29.9145 -2.359 142.708 -28.5236 -1.1315 144.099 +-29.7011 -2.33284 142.907 -28.7338 -2.02 143.897 +-45.1273 -1.71865 143.629 -44.2502 -0.413757 145.127 +-2.82931 7.27218 105.572 -2.51861 7.58288 105.882 +28.815 -1.87031 28.89 29.185 0.265399 31.185 +28.7815 -2.11 28.89 29.2185 0.11 31.11 +-140.328 5.55609 84.4186 -138.83 6.86098 85.2957 +-85.311 -0.357793 173.456 -84.4681 0.812026 174.299 +27.2797 -3.83577 31.1984 28.4797 -3.30877 32.4858 +27.5379 -3.67966 31.8549 28.5992 -2.50117 32.6601 +27.3192 -4.11 31.4913 27.8439 -3.52703 32.032 +27.8158 -4.11 31.2917 28.3393 -3.52703 31.832 +27.9647 -4.11034 31.8201 28.5161 -3.56532 32.3741 +27.5703 -4.11033 31.9771 28.0912 -3.56532 32.52 +-30.7874 -0.218646 151.458 -29.9103 1.08624 152.956 +-130.381 3.73018 91.2047 -130.084 4.10502 91.5019 +-130.423 3.87951 91.3472 -130.126 4.25435 91.6443 +-130.514 3.86063 91.6553 -130.217 4.23547 91.9525 +-130.559 3.74926 91.7908 -130.262 4.1241 92.0879 +-77.5463 7.70388 130.982 -76.617 8.63317 131.911 +-6.28783 5.88899 48.9046 -4.48624 7.26439 50.7062 +-6.31149 5.88899 48.881 -4.51561 7.10899 50.6768 +-6.34086 5.88899 55.1473 -4.53927 7.26439 56.9489 +-6.31149 5.88899 55.1236 -4.51561 7.10899 56.9195 +-17.301 5.88899 59.1577 -15.4994 7.26439 60.9593 +-17.2716 5.88899 59.134 -15.4758 7.10899 60.9299 +-140.899 1.64 84.8844 -140.131 2.57194 85.6505 +-107.549 -1.35941 154.817 -106.29 1.24452 156.118 +-107.37 -1.36 154.921 -106.274 1.16093 156.1 +-88.5353 -0.359001 146.86 -87.4489 0.868493 147.947 +-88.4676 -0.332848 146.916 -87.5074 -0.0200025 147.902 +-102.974 -2.485 101.277 -100.711 -0.974881 102.368 +12.526 -3.82577 -23.0649 13.6171 -3.29877 -22.0875 +13.1773 -3.66966 -23.0924 13.7973 -2.49117 -22.0643 +12.636 -4.1 -22.5375 13.1118 -3.51703 -22.0897 +12.6286 -4.1 -23.0715 13.1044 -3.51703 -22.625 +13.1842 -4.10034 -23.0445 13.6643 -3.55532 -22.5698 +13.1777 -4.10033 -22.5914 13.658 -3.55532 -22.149 +26.89 -2.87031 28.815 29.185 -0.734601 29.185 +26.89 -3.11 28.7815 29.11 -0.89 29.2185 +-47.8954 1.63951 117.023 -47.471 2.04142 117.473 +-114.852 -3.36284 101.308 -114.17 -2.19302 101.99 +-10.5305 5.88899 44.662 -8.72888 7.26439 46.4636 +-10.5541 5.88899 44.6383 -8.75825 7.10899 46.4342 +-15.8829 5.89071 56.2828 -14.0813 7.26611 58.0843 +-15.8535 5.89071 56.3121 -14.0576 7.11071 58.108 +-106.288 -0.40412 152.523 -105.865 0.13707 152.947 +-107.097 0.727581 155.646 -106.8 1.10242 155.943 +-107.037 0.876911 155.51 -106.74 1.25175 155.807 +-106.906 0.858031 155.216 -106.609 1.23287 155.514 +-106.844 0.746663 155.088 -106.547 1.1215 155.385 +49.784 2.15038 66.3306 50.9851 2.67738 67.4072 +50.4491 2.30649 66.2384 51.155 3.48498 67.2947 +49.9844 1.87615 66.898 50.4959 2.45912 67.3869 +49.8839 1.87615 66.3734 50.3953 2.45912 66.8611 +50.4361 1.87581 66.3024 50.9562 2.42083 66.8185 +50.5084 1.87582 66.7497 51.0234 2.42083 67.2337 +-114.455 -0.358869 109.476 -113.779 0.616986 110.153 +-63.1882 1.80108 131.647 -62.8063 2.34227 132.03 +-91.0392 -1.36311 114.314 -90.4534 -0.581221 114.9 +20.6566 -3.11081 -26.7151 21.5971 -2.29851 -25.8232 +-30.7874 2.78135 151.458 -29.9103 4.08624 152.956 +28.6345 -2.94359 -48.4065 28.9245 -2.65359 -48.1165 +-97.1994 -1.48498 107.42 -96.1088 0.0251353 109.683 +25.0992 -2.94359 -48.3724 25.3892 -2.65359 -48.0824 +20.6113 -3.12022 -28.3182 21.0322 -2.85905 -27.9242 +-31.4958 -1.15683 21.636 -31.1392 -0.797108 21.9885 +-31.4709 -1.13837 21.6548 -31.2096 -0.692489 21.9521 +-31.4482 -1.13807 21.6724 -31.1726 -0.694869 21.9703 +-31.4444 -1.13946 21.6833 -31.1437 -0.690778 21.9416 +-110.546 5.09469 94.3046 -107.856 5.5009 96.0421 +-27.185 -3.87031 2.565 -24.89 -1.7346 2.93499 +-27.11 -4.11 2.53154 -24.89 -1.89 2.96845 +8.15699 -3.82577 -31.7469 9.13447 -3.29877 -30.6558 +8.12953 -3.66966 -31.9271 9.15761 -2.49117 -31.3071 +8.68446 -4.1 -31.2416 9.13218 -3.51703 -30.7658 +8.15038 -4.1 -31.2342 8.59691 -3.51703 -30.7584 +8.17742 -4.10034 -31.7941 8.65216 -3.55532 -31.314 +8.63056 -4.10033 -31.7878 9.07288 -3.55532 -31.3075 +-129.02 -0.258739 110.35 -128.328 0.392683 110.993 +-128.64 1.635 86.8289 -127.742 2.74493 87.7131 +-86.9018 31.3371 115.909 -85.9725 32.2664 116.838 +-28.1574 -1.03076 16.716 -27.7494 -0.622764 17.124 +-28.2256 -0.858674 16.6085 -27.6431 0.310032 17.2675 +-125.365 10.0561 86.6789 -123.867 11.361 87.556 +-124.922 -2.36044 137.929 -124.23 -1.19062 138.621 +-113.787 -2.35887 129.362 -113.223 -1.38302 129.927 +8.85499 -1.20383 -71.145 9.14499 -0.913829 -70.855 +-61.9079 3.8052 129.52 -61.6179 4.0952 129.81 +19.9758 2.20954 25.0983 22.6124 3.81881 26.2266 +19.9758 2.20955 24.9855 22.6124 4.14858 26.2222 +-129.857 -0.257086 110.843 -128.963 0.579232 111.666 +-4.87361 5.88899 50.3189 -3.07203 7.26439 52.1204 +-4.89727 5.88899 50.2952 -3.1014 7.10899 52.0911 +4.36807 -5.1 -48.4105 6.03841 -3.72461 -46.7859 +4.36998 -5.1 -48.4105 6.04083 -3.72461 -46.7859 +-62.636 2.50921 129.785 -62.0918 2.76077 130.6 +-8.89635 2.95269 73.0869 -8.07739 3.64253 73.8689 +-2.21013 -4.38893 -44.1707 -0.8771 -3.25324 -42.9983 +-1.18762 -3.96508 -43.5946 -0.866616 -3.67708 -43.3066 +-93.9366 -1.46387 134.738 -93.2223 -0.488013 135.453 +9.35165 -3.82577 -30.4746 10.5507 -3.29877 -29.4006 +10.0166 -3.66966 -30.5662 10.7206 -2.49117 -29.5103 +9.55019 -4.1 -29.9086 10.0611 -3.51703 -29.4205 +9.45165 -4.1 -30.4336 9.96238 -3.51703 -29.9467 +10.0041 -4.10034 -30.5026 10.5235 -3.55532 -29.9872 +10.0747 -4.10033 -30.055 10.5891 -3.55532 -29.5718 +-97.2569 4.64059 147.724 -96.1027 7.24452 148.939 +-97.0733 4.64 147.798 -96.0787 7.16093 148.914 +-119.052 -2.35887 138.911 -118.375 -1.38301 139.589 +-96.7964 6.72758 148.509 -96.4993 7.10242 148.807 +-96.762 6.87691 148.365 -96.4649 7.25175 148.662 +-96.6876 6.85803 148.052 -96.3905 7.23287 148.349 +-96.6499 6.74666 147.915 -96.3528 7.1215 148.212 +-82.6592 1.56955 93.2976 -82.2513 1.97755 93.7056 +-82.7131 1.74164 93.1594 -82.1516 2.91035 93.8363 +-89.4833 -1.36159 101.76 -88.0964 -0.1341 103.147 +-89.2697 -1.33544 101.956 -88.3044 -1.0226 102.947 +-58.493 0.78627 144.543 -57.2191 2.01376 145.817 +-58.3408 0.812423 144.685 -57.3723 1.12527 145.669 +14.687 -2.46393 -12.3362 14.9584 -2.06202 -11.8594 +14.687 -2.46393 -11.9958 14.9584 -2.06202 -11.519 +21.6546 -1.17689 93.8883 23.2668 -0.484833 95.6093 +21.6136 -0.766239 93.7911 23.3214 0.119008 95.7065 +-122.377 -2.36208 138.531 -121.531 -1.52577 139.42 +8.55684 -3.06072 -22.1274 9.05851 -2.10466 -21.6159 +8.68889 -2.24642 -22.0393 8.9089 -2.02642 -21.8193 +-140.328 4.05609 84.4186 -138.83 5.36098 85.2957 +20.6634 -3.06886 -32.9658 21.0844 -2.80768 -32.5717 +-71.6084 -0.360816 162.967 -70.5791 1.15227 163.963 +-71.6058 -0.360952 162.969 -70.5821 1.14999 163.962 +-114.363 4.63896 147.84 -112.103 6.01436 148.788 +-114.372 4.63896 147.808 -112.166 5.85896 148.799 +15.6993 -4.70077 -39.8551 16.7964 -4.17377 -38.8777 +16.3517 -4.54466 -39.8892 16.9733 -3.36617 -38.8612 +15.8138 -4.975 -39.3308 16.2915 -4.39203 -38.8809 +15.8019 -4.975 -39.8648 16.2795 -4.39203 -39.4161 +16.358 -4.97534 -39.8425 16.8399 -4.43032 -39.3656 +16.355 -4.97533 -39.3893 16.8371 -4.43032 -38.9451 +-125.365 8.55609 86.6789 -123.867 9.86098 87.556 +-139.723 0.640577 120.343 -138.548 3.24451 121.575 +-139.745 0.63999 120.367 -138.732 3.16092 121.495 +27.8655 1.89 47.5772 29.9473 3.26539 49.6836 +27.8645 1.89 47.575 29.9466 3.26539 49.6818 +-11.9628 -0.160001 97.238 -11.156 0.753029 98.2304 +-11.9628 -0.160001 97.238 -11.156 0.753029 98.2304 +-11.7207 -0.0301448 97.2569 -11.1842 0.425582 97.8307 +-11.717 -0.0301448 97.6285 -11.1789 0.425582 98.2034 +-113.997 -3.36284 102.839 -113.314 -2.19302 103.521 +30.9454 1.03974 37.8972 31.8465 1.48728 38.5402 +30.8829 1.07326 37.3896 32.0046 1.54731 38.0165 +31.2233 1.61995 37.6809 31.7832 2.11256 38.8554 +30.9558 1.67287 37.7518 31.4523 2.11744 38.6961 +30.8033 1.42628 37.7322 31.9152 1.92558 38.2964 +30.6931 1.42851 37.9403 31.9153 1.94523 38.5551 +30.8356 1.47755 38.183 31.7934 1.94299 38.7681 +30.8282 1.26381 37.4952 31.2818 1.71687 38.6183 +31.023 1.08859 37.1887 31.5126 1.79621 38.0248 +31.2215 1.03983 37.4384 32.0162 1.73371 38.2917 +31.3128 1.22814 37.8543 31.8048 1.74269 38.8079 +30.7896 1.04971 38.2897 31.9588 1.51866 38.7608 +-80.8622 33.1887 124.31 -79.9329 34.118 125.24 +-128.337 1.64 86.3233 -127.575 2.57194 87.0746 +-139.306 2.72757 120.483 -139.009 3.10241 120.78 +-139.345 2.8769 120.626 -139.048 3.25174 120.924 +-139.429 2.85802 120.937 -139.132 3.23286 121.234 +-139.471 2.74665 121.073 -139.174 3.12149 121.37 +-98.8497 -0.802517 97.7107 -96.1599 -0.396308 99.4481 +-28.8363 2.78135 144.735 -27.9592 4.08624 146.234 +-125.365 2.58581 86.6789 -123.867 3.8907 87.556 +-102.822 -1.48065 122.133 -100.558 0.0294658 123.224 +-30.7874 -1.71865 151.458 -29.9103 -0.413757 152.956 +-123.445 7.08581 87.2363 -121.946 8.3907 88.1134 +-3.52782 15.1795 -37.361 12.9531 31.6603 -20.8802 +-62.8837 1.8079 130.955 -62.5389 2.20982 131.435 +-105.021 6.59668 95.9631 -102.332 7.00289 97.7006 +-110.47 -4.48498 119.927 -108.206 -2.97486 121.017 +6.06779 -5.1 -39.185 6.43777 -3.7246 -38.815 +6.03432 -5.1 -39.2053 6.47123 -3.83337 -38.797 +-156.719 1.42001 92.7364 -156.311 1.82801 93.1444 +-156.773 1.5921 92.5982 -156.212 2.76081 93.2751 +19.4799 -1.20383 -83.0825 19.7699 -0.913827 -82.7925 +-145.76 3.06324 138.805 -144.262 4.36813 139.682 +22.7263 -3.07819 -29.0418 24.4641 -1.55946 -27.5731 +22.7083 -2.66137 -28.4674 23.0733 -2.34137 -28.1474 +-111.955 -1.35998 128.517 -111.193 -0.428043 129.279 +-129.076 1.515 99.9276 -128.405 3.24951 100.599 +-138.408 4.05609 84.9761 -136.909 5.36098 85.8532 +2.65516 -1.14476 109.001 9.12624 14.6828 110.727 +-16.8339 3.52895 4.7826 -13.0401 4.4187 5.48303 +-16.8339 3.52895 4.7826 -13.0401 4.44185 5.48303 +-54.7966 1.38442 -5.21861 -53.8962 2.27417 -1.40248 +-54.7966 1.38442 -5.21861 -53.8962 2.29732 -1.40248 +59.3521 2.4352 -17.4181 61.186 3.32495 -13.6552 +59.3521 2.4352 -17.4181 61.186 3.3481 -13.6552 +-76.3605 0.642229 157.025 -68.3679 8.79401 159.979 +-92.8412 -1.27378 160.335 -85.2642 6.4539 163.142 +-148.298 -1.0984 115.177 -142.903 4.40279 117.213 +-41.2476 1.38442 -10.4019 -39.21 2.27417 -6.69016 +-41.2476 1.38442 -10.4019 -39.21 2.29732 -6.69016 +-144.855 0.804289 88.3203 -142.268 7.89583 95.274 +-0.280711 -4.81855 -20.7746 6.28071 1.74287 -20.1269 +-82.3874 -1.66308 92.759 -80.9267 6.48869 100.929 +14.9725 -4.78576 -21.1768 21.0038 1.24555 -20.5664 +-86.1224 -0.211343 80.4634 -83.9788 5.28984 85.833 +-3.81506 0.931298 -20.4706 -3.11463 1.82104 -16.6768 +-3.81506 0.931298 -20.4706 -3.11463 1.84419 -16.6768 +1.11763 -1.2259 83.8106 5.13066 4.60261 88.3472 +0.695546 -1.24631 86.2919 5.57701 4.06615 88.7379 +0.695546 -1.24631 82.0266 5.5768 3.85657 88.7379 +0.562371 1.36354 82.0926 5.67245 4.57189 88.737 +1.91498 -12.7676 -21.5872 6.25883 -7.77541 -19.2573 +-0.302501 -12.7676 -21.6114 4.04135 -7.77541 -19.2331 +15.465 -12.8301 -22.1114 20.5506 -7.68294 -19.7328 +5.95466 -2.01785 107.576 10.4692 2.88491 112.154 +-36.8012 8.89595 84.1335 -23.6684 16.1898 97.4718 +-36.766 8.92529 84.1405 -23.652 16.2132 97.4602 +-16.7002 0.71968 3.84699 -12.15 4.2987 6.40584 +-55.7188 -1.42485 -6.10511 -53.0371 2.15417 -1.53741 +-41.7385 -1.42485 -10.328 -38.3243 2.15417 -5.82291 +58.4595 -0.37407 -18.2887 61.7444 3.20495 -13.7496 +-51.7015 -1.23436 134.282 -46.8035 3.77023 137.38 +31.6803 0.969623 64.7107 34.1842 6.96104 70.6268 +-90.012 0.183281 97.4255 -87.652 2.54328 99.7855 +-87.8792 0.167656 98.0973 -85.5192 2.52766 100.457 +-87.68 0.22625 99.07 -85.32 2.58625 101.43 +-90.4808 0.167656 97.3278 -88.1208 2.52766 99.6878 +-89.5394 0.16375 97.652 -87.1794 2.52375 100.012 +-88.473 0.175469 97.9255 -86.113 2.53547 100.285 +-26.2563 8.95895 119.972 -26.0349 9.19021 120.196 +-26.8346 8.4024 119.518 -25.4387 9.82793 121.307 +-25.7901 8.89098 119.742 -25.4823 9.75764 120.707 +-26.3626 9.27621 119.672 -25.9199 10.1507 120.588 +-26.8272 8.89071 119.806 -26.4738 9.75762 120.769 +-26.0381 8.6344 120.108 -25.628 9.41334 121.091 +-26.5706 8.6358 120.144 -26.1817 9.41441 121.134 +-33.3687 9.4456 72.4523 -32.9854 9.67136 72.6818 +-33.8318 8.9515 71.8541 -31.8727 10.3635 73.2584 +-33.7156 9.3072 72.5602 -32.5747 10.1366 72.8741 +-33.6311 9.74579 72.3461 -32.5373 10.5947 72.7956 +-33.7359 9.30721 72.2487 -32.5951 10.1367 72.6053 +-33.2122 9.08509 72.0611 -32.0784 9.87785 72.4728 +-33.1788 9.08508 72.61 -32.0427 9.87775 73.0048 +2.03607 1.01302 80.0456 6.37993 6.00518 82.3755 +-0.181407 1.01302 80.0215 4.16245 6.00518 82.3997 +-18.5232 8.60914 105.789 -18.3023 8.84924 106.01 +-19.0155 8.05285 105.205 -17.2426 9.47317 106.566 +-18.8315 8.51558 105.207 -17.9519 9.43771 105.578 +-18.8577 8.78591 105.682 -17.9952 9.71918 106.17 +-18.6228 8.4914 106.159 -17.7496 9.41708 106.594 +-18.4212 8.28773 105.253 -17.4176 9.02808 105.745 +-18.3015 8.37429 105.848 -17.276 9.11951 106.273 +-32.1952 2.4223 123.028 -31.9737 2.65432 123.251 +-32.7475 1.8586 122.533 -31.4458 3.29786 124.24 +-31.9575 2.26953 123.099 -31.413 3.17145 123.951 +-32.3041 2.60435 122.75 -31.7097 3.52517 123.615 +-32.7919 2.38341 122.619 -32.3058 3.28328 123.484 +-32.4376 2.04511 123.327 -31.8096 2.7994 124.256 +-32.9832 2.12041 123.061 -32.2999 2.84981 123.951 +-29.1389 9.41131 73.4766 -28.788 9.63258 73.7837 +-29.6381 8.91673 72.9812 -27.8402 10.3258 74.4457 +-29.5296 9.26575 73.3969 -28.5748 10.1158 74.1502 +-29.4139 9.70515 73.2518 -28.4328 10.5727 74.0357 +-29.3462 9.26581 73.1427 -28.3702 10.1158 73.8458 +-28.8445 9.08816 73.332 -27.8288 9.85717 74.0552 +-29.1466 9.08803 73.7996 -28.179 9.85717 74.575 +-35.4716 7.25842 118.988 -35.2512 7.48805 119.209 +-36.2302 6.68171 118.52 -34.7829 8.11163 120.076 +-35.4778 7.25129 119.133 -34.7378 8.15267 119.857 +-35.7841 7.44964 118.687 -35.0209 8.35217 119.466 +-36.2009 7.15607 118.515 -35.4992 8.04197 119.259 +-35.8337 7.00647 119.288 -35.1506 7.76027 120.167 +-36.3108 6.94795 118.938 -35.5722 7.72061 119.765 +-57.9089 -0.260602 137.539 -54.0863 5.79449 144.723 +-27.2953 9.41131 74.8501 -26.9503 9.63258 75.1728 +-27.7868 8.91673 74.3913 -26.0629 10.3258 75.9186 +-27.6783 9.26575 74.7388 -26.7742 10.1158 75.5585 +-27.5613 9.70515 74.6086 -26.6165 10.5727 75.4551 +-27.467 9.26581 74.4965 -26.5406 10.1158 75.2757 +-26.9885 9.08816 74.743 -26.0211 9.85717 75.5359 +-27.3365 9.08803 75.1706 -26.4201 9.85717 76.0176 +-37.552 7.06198 101.522 -37.2747 7.38373 101.859 +-38.1396 6.54889 101.002 -36.7797 7.91735 102.785 +-37.9775 6.9457 101.181 -37.2488 7.58366 102.318 +-37.9607 7.39472 101.506 -37.217 8.04392 102.639 +-37.6467 6.9457 101.331 -36.9936 7.58371 102.477 +-37.6636 6.22805 101.728 -37.0428 7.34965 102.576 +-38.0906 6.22804 101.486 -37.5274 7.34958 102.396 +38.89 1.00911 77.5474 41.2367 6.00128 81.8931 +38.8491 1.00911 75.3298 41.2441 6.00128 79.6759 +-64.2931 12.8437 106.495 -64.0393 13.0955 106.872 +-64.8748 12.3578 105.461 -63.4804 13.7784 107.381 +-64.1977 12.6675 106.176 -63.8018 13.6404 107.173 +-64.383 13.1011 106.249 -63.8711 14.0827 107.244 +-64.5308 12.6675 106.253 -64.0756 13.6404 107.243 +-64.8269 12.7037 105.601 -64.2961 13.4451 106.777 +-64.2278 12.7036 105.466 -63.7742 13.4451 106.661 +-31.1041 9.41131 72.4946 -30.745 9.63258 72.7556 +-31.5939 8.91673 71.9193 -29.6759 10.3258 73.3277 +-31.4926 9.26575 72.5151 -30.4375 10.1158 73.0476 +-31.3884 9.70515 72.3301 -30.3466 10.5727 72.9106 +-31.4051 9.26581 72.2418 -30.3265 10.1158 72.6981 +-30.8668 9.08816 72.2448 -29.7517 9.85717 72.7705 +-31.0109 9.08803 72.7791 -29.9439 9.85717 73.3558 +-4.73787 -1.87798 -20.3369 -2.17902 1.70105 -15.7867 +-57.7329 4.39998 85.5597 -42.5638 23.1099 100.729 +-57.2338 6.00324 85.7789 -43.0629 23.1305 100.51 +-25.1375 2.41308 38.5038 -18.9069 7.62886 44.732 +-25.4166 2.98678 38.7445 -20.7027 6.37643 43.2607 +-23.6624 3.02311 39.941 -19.7673 6.72178 43.7473 +-30.5666 -0.900625 52.2973 -24.185 3.10189 58.5054 +-29.4643 -0.900625 52.6535 -24.5176 2.64883 57.534 +-29.9162 -0.900625 53.8012 -25.8272 2.94399 57.8138 +-24.3998 5.00483 60.5539 -18.4907 8.84286 66.4823 +-23.5633 5.01376 61.3995 -18.8951 8.40935 66.0791 +-24.1692 5.0298 60.8054 -20.2356 8.70142 64.7201 +2.9 -5.0502 -44.1 4.1 -2.8502 -42.9 +-53.3698 -0.25861 69.8993 -52.3028 0.553373 70.3898 +-16.3587 4.19272 70.8277 -15.7856 4.89825 71.4004 +14.0753 -3.21167 -30.1432 14.5902 -2.85029 -29.5858 +-72.7361 1.56735 89.042 -72.1457 2.40435 89.6596 +-73.2448 0.93727 84.1827 -72.3662 1.44024 85.0756 +-63.5237 2.75335 155.875 -62.8338 3.1715 156.65 +-33.0905 1.4645 61.7845 -32.2885 2.22656 62.5118 +-24.2353 1.19907 114.613 -23.5408 1.68201 115.296 +-57.4102 1.43749 71.1328 -56.6497 2.30949 71.8177 +-79.9612 1.91512 152.941 -79.2002 2.33326 153.599 +-109.185 1.64569 149.706 -108.7 2.42755 150.402 +-6.84726 1.19269 97.3663 -6.45944 1.89822 97.9312 +-103.6 7.63938 151.325 -103.087 8.38639 151.985 +-11.9799 -0.160001 99.4812 -11.3924 0.365486 100.394 +-68.0917 2.76071 147.452 -67.4647 3.17885 148.196 +-119.711 -0.611204 146.479 -119.258 0.200321 147.165 +-49.4682 0.925208 117.368 -48.5634 1.5084 118.252 +-49.1674 1.12995 117.602 -48.582 1.55718 118.254 +-22.705 -2.78204 5.42412 -22.2831 -2.4421 5.85267 +-22.6653 -2.78084 5.43113 -22.2918 -2.52866 5.80436 +-22.6815 -2.73607 5.42082 -22.3439 -2.44243 5.73942 +-22.6974 -2.78807 5.50638 -22.3262 -2.43609 5.84631 +-80.4791 3.21535 154.734 -79.7181 3.6335 155.392 +-32.9677 2.09307 60.4956 -32.1002 2.75533 60.9881 +-83.7855 -0.604885 105.549 -83.3326 0.20664 106.236 +-134.582 2.58519 90.8109 -133.837 2.95677 91.6365 +-126.905 4.36291 86.5696 -126.306 4.86266 86.9423 +37.3779 2.78454 72.6271 38.4724 3.59652 73.4311 +-148.623 0.726823 98.4159 -147.465 2.4392 99.5841 +30.2942 2.51524 79.5788 30.6347 2.81488 79.9598 +30.1118 1.86341 79.435 30.8014 2.62181 80.1127 +-80.7817 0.672165 99.5184 -79.888 1.52497 100.424 +-80.7971 1.22297 99.3109 -79.9814 2.11264 99.8782 +-103.839 6.88741 151.258 -103.386 7.69893 151.944 +-26.6101 0.192687 16.8349 -26.2159 0.898219 17.4034 +-116.289 2.38653 159.992 -115.837 3.19805 160.679 +25.8418 -4.3649 -47.8179 26.9708 -3.84358 -47.5367 +-99.5269 4.63514 149.439 -99.1941 5.25749 149.974 +-98.8438 4.96437 149.592 -98.4851 5.30239 150.395 +-98.7967 4.63514 150.077 -98.4639 5.25749 150.612 +-98.8649 4.63514 149.375 -98.5321 5.25749 149.91 +-99.4587 4.63514 150.141 -99.1259 5.25749 150.676 +-99.5058 4.96437 149.657 -99.1471 5.30239 150.459 +-99.3632 5.38471 150.226 -98.4355 5.71948 150.624 +-99.4557 5.11181 150.156 -99.1303 5.69493 150.614 +-99.5467 5.31335 149.557 -99.1432 5.60539 150.557 +-99.5027 5.08239 149.572 -98.4836 5.42338 150.476 +-99.5193 5.11181 149.501 -99.1939 5.69493 149.96 +-99.4433 5.38471 149.398 -98.5155 5.71948 149.798 +-99.566 5.47493 149.501 -99.1303 5.94646 150.615 +-98.8581 5.11181 149.446 -98.5335 5.61688 149.896 +-98.7953 5.11181 150.091 -98.4708 5.61688 150.541 +22.7655 -1.49201 -31.5906 23.2594 -0.740215 -31.0954 +48.5854 2.79258 66.9572 48.9664 3.12747 67.2871 +48.6931 2.79404 66.6357 49.0739 3.12989 66.9671 +48.5305 2.78674 66.6628 49.1298 3.04484 67.2615 +48.5045 2.79274 66.8688 48.8587 3.12684 67.2414 +48.5048 2.79347 66.7165 48.8354 3.12925 67.097 +48.8248 2.79289 66.8241 49.1549 3.12631 67.207 +48.549 2.79414 66.6353 48.9234 3.12991 66.9908 +48.8012 2.7934 66.6798 49.1553 3.12865 67.0556 +48.7367 2.79252 66.9336 49.1107 3.12726 67.287 +-136.105 4.36291 85.9818 -135.506 4.86266 86.3544 +-1.44223 -0.681505 -27.6228 -1.09996 -0.358105 -27.2625 +-1.70592 -0.680196 -27.8011 -1.36223 -0.355924 -27.4408 +-1.68176 -0.686761 -27.8116 -1.12273 -0.432469 -27.2522 +-1.54639 -0.681359 -27.5448 -1.1801 -0.358673 -27.2296 +-1.67275 -0.68071 -27.572 -1.31123 -0.356504 -27.2296 +-1.49316 -0.68123 -27.8344 -1.13253 -0.359149 -27.4916 +-1.70599 -0.680104 -27.6746 -1.38926 -0.355906 -27.3084 +-1.62733 -0.680774 -27.8344 -1.26036 -0.357045 -27.5185 +-1.41524 -0.681559 -27.7554 -1.10031 -0.358293 -27.3891 +-23.917 -0.109162 54.8217 -23.4287 0.642635 55.3091 +-4.18262 1.28217 48.852 -3.66262 2.23417 49.372 +23.24 0.387793 42.1347 23.5942 0.836901 42.4889 +-69.9263 3.84508 146.664 -68.943 4.60714 147.641 +-115.717 3.13817 160.225 -115.264 3.9497 160.912 +-83.4847 -0.604885 105.509 -82.9713 0.142122 106.169 +25.6597 -0.10192 38.3604 26.331 0.587098 39.0316 +27.6314 -3.25533 30.6841 28.1114 -2.39733 31.1641 +-62.7112 2.55977 152.919 -61.9839 3.32183 153.722 +-151.175 0.726823 105.854 -150.045 2.4392 107.031 +-77.0773 1.6416 104.064 -76.7179 2.09071 104.423 +-22.758 -3.22461 -2.57743 -22.1309 -2.75276 -1.89498 +-62.1001 2.16642 129.378 -61.5689 2.56722 129.795 +-62.1078 1.95994 129.38 -61.5672 2.37199 129.796 +-62.0263 2.02737 129.562 -61.7869 2.51298 129.812 +-61.9344 2.02874 129.582 -61.695 2.51434 129.832 +-61.9718 2.36102 129.514 -61.7218 2.61102 129.764 +22.8345 -1.49536 -30.9437 23.4781 -0.51889 -30.3065 +-109.368 1.64569 149.651 -108.855 2.3927 150.311 +-54.0418 -0.359893 69.115 -52.9877 0.157329 70.1787 +21.0513 -4.73604 -47.9173 21.5834 -4.33308 -47.5066 +21.0428 -4.94246 -47.918 21.5846 -4.52757 -47.5087 +21.2212 -4.87365 -47.958 21.4619 -4.3881 -47.7078 +21.1289 -4.87145 -47.9395 21.3696 -4.3859 -47.6893 +21.1832 -4.5398 -47.8897 21.4332 -4.2898 -47.6397 +-98.24 5.47152 147.607 -97.3282 5.80739 148.586 +-33.0905 0.166709 60.3147 -32.2885 0.92877 61.042 +22.915 -0.238561 -27.9942 23.5585 0.737909 -27.357 +-79.8094 -0.365773 132.733 -79.2184 1.24068 133.415 +-28.6161 -3.24412 0.0554479 -28.1361 -2.38612 0.535448 +10.6873 -5.35451 -45.9166 11.0774 -5.05851 -45.6012 +10.5407 -5.99705 -46.0988 11.2283 -5.26028 -45.419 +-63.0316 2.55977 153.929 -62.1161 3.32183 154.797 +-28.8153 -3.18655 0.411381 -27.6834 -2.798 1.69871 +-138.026 5.86291 85.4243 -137.427 6.36266 85.7969 +-57.8817 0.782944 71.3407 -57.348 1.18374 71.7777 +-57.8837 0.576459 71.3436 -57.3406 0.988511 71.7793 +-57.7482 0.643893 71.5571 -57.5082 1.1295 71.8066 +-57.6584 0.645257 71.5286 -57.4185 1.13086 71.7781 +-57.7255 0.977545 71.4855 -57.4755 1.22755 71.7355 +-71.5135 0.618702 166.567 -71.0871 1.22231 166.997 +-68.2675 2.56712 158.402 -67.4061 3.32918 159.312 +-80.4011 3.2137 154.07 -79.4908 3.97576 154.931 +18.8227 -2.91359 -48.4813 19.2675 -1.33175 -48.0536 +18.7449 -1.72672 -48.7009 19.3221 -1.16614 -48.1294 +18.7467 -1.9883 -48.5605 19.2227 -1.5123 -48.0845 +19.0375 -2.91359 -48.2836 19.588 -1.44706 -48.0144 +19.0741 -1.84955 -48.5323 19.6813 -1.24846 -47.9279 +19.1536 -2.13144 -48.3782 19.6296 -1.65544 -47.9022 +18.7917 -2.91455 -48.2886 19.2611 -1.12837 -48.0491 +18.6348 -1.50672 -48.4661 19.2471 -0.90514 -47.8566 +18.6919 -1.7202 -48.4122 19.1746 -1.24308 -47.936 +18.9358 -2.91407 -48.2818 19.2652 -1.38326 -47.8356 +18.7782 -1.76274 -48.2466 19.3641 -1.18225 -47.6658 +18.8178 -1.95494 -48.2184 19.2943 -1.47879 -47.7418 +19.0375 -2.91359 -48.2836 19.4884 -1.05246 -47.79 +19.0232 -1.42094 -48.3062 19.6345 -0.818782 -47.6966 +18.9997 -1.64924 -48.2777 19.4796 -1.17311 -47.8005 +19.0375 -2.91359 -48.4479 19.4517 -0.978363 -48.0536 +18.8199 -1.38699 -48.7284 19.4616 -0.74685 -48.0873 +18.9652 -1.62492 -48.6141 19.4484 -1.14885 -48.1368 +19.018 -2.91359 -48.2836 19.2675 -0.67254 -47.9949 +18.8127 -1.05805 -48.4287 19.4527 -0.418048 -47.7887 +18.8979 -1.26093 -48.3546 19.3739 -0.784927 -47.8786 +-161.181 0.64 96.8658 -160.527 1.33856 97.5969 +-21.6945 -4.21 -4.82988 -21.3382 -3.76089 -4.4735 +-46.0231 -0.316696 85.7673 -45.0515 0.53611 86.7293 +-45.483 0.23411 85.9177 -44.8478 1.12378 86.7593 +-80.8197 1.64535 100.57 -80.3991 2.21215 101 +-28.7801 0.0881764 145.117 -28.4074 0.587928 145.716 +-66.0934 3.8576 148.181 -65.5537 4.39925 148.908 +-21.8805 -4.11 2.613 -20.794 -3.29802 3.18942 +-15.5814 6.54551 51.1221 -15.2822 6.84151 51.5141 +-15.76 5.90296 50.98 -15.1039 6.63973 51.6559 +-9.64252 2.95108 73.1334 -8.92714 3.4683 74.0686 +-25.5074 -2.58924 -3.7901 -24.9721 -2.18844 -3.30435 +-25.5139 -2.79572 -3.79355 -24.9781 -2.38367 -3.30934 +-25.3785 -2.72829 -3.79247 -25.1354 -2.24268 -3.54433 +-25.4586 -2.72692 -3.74308 -25.2155 -2.24132 -3.49494 +-25.3915 -2.39464 -3.71746 -25.1415 -2.14464 -3.46746 +-53.2368 -0.316696 84.5256 -52.2652 0.53611 85.4876 +-53.4405 0.23411 84.4956 -52.8053 1.12378 85.3371 +-120.195 -0.611204 146.388 -119.682 0.135803 147.048 +-134.505 2.84879 90.8327 -134.265 3.31879 91.0727 +-134.546 3.24835 90.7922 -134.225 3.64645 91.1131 +-134.705 2.61716 90.6327 -134.065 3.10437 91.2727 +-134.712 3.30214 90.8121 -134.43 3.65905 91.0931 +-134.525 3.30351 90.627 -134.246 3.65224 90.9067 +-134.524 3.43985 90.8145 -134.247 3.79984 91.0909 +-134.526 3.30736 90.9982 -134.245 3.59669 91.2792 +-134.339 3.3049 90.8129 -134.055 3.61864 91.0921 +-134.733 3.08953 90.6053 -134.038 3.46321 91.3 +-134.728 3.24278 90.7962 -134.414 3.51443 91.1091 +-134.542 3.24278 90.6101 -134.229 3.51443 90.9236 +-134.542 3.24278 90.9817 -134.229 3.51443 91.2952 +-134.356 3.24278 90.7962 -134.043 3.51443 91.1091 +-21.308 -0.0955454 61.7134 -20.3538 0.826693 62.6678 +-97.5562 5.01509 146.989 -96.6001 5.35095 147.985 +21.4873 -5.22097 12.2306 21.8451 -4.77187 12.5885 +-29.0447 6.57589 62.6569 -28.6527 6.87361 62.9551 +-29.1895 5.93105 62.4791 -28.5143 6.67506 63.1335 +-74.4721 0.924516 90.2419 -73.4098 1.44174 91.2043 +-48.4319 0.926543 116.857 -47.9928 1.53015 117.282 +-75.8357 -0.36095 164.107 -74.738 0.491857 165.204 +-75.98 0.189857 164.501 -75.1618 1.07952 165.34 +-95.7436 1.54819 96.0109 -95.3766 1.79966 96.3779 +-97.3557 1.5494 95.5049 -96.9512 1.80572 95.9094 +-95.5866 1.5445 96.0533 -95.1821 1.80082 96.4578 +19.536 -4.1 -33.2528 20.5243 -3.40776 -32.3534 +-79.9617 2.10883 152.987 -79.217 2.52698 153.614 +54.326 2.72968 75.5223 54.806 3.58768 76.0023 +-48.3066 1.84103 117.405 -47.9195 2.24295 117.823 +-48.3235 1.83816 117.405 -47.9311 2.25179 117.83 +-48.3256 1.84103 117.389 -47.9385 2.24295 117.807 +-48.2983 1.84103 117.412 -47.9112 2.24295 117.83 +-91.2321 -1.37266 101.531 -89.9118 -0.137269 102.272 +-90.7795 -0.998398 101.188 -89.8714 0.508637 101.681 +-90.9762 -0.512327 101.185 -89.3748 -0.120261 101.874 +-91.0456 -0.771091 101.366 -89.4441 -0.379022 102.055 +-3.12339 -1.17403 -59.3628 -2.71693 0.409408 -58.8918 +-3.12333 0.00894677 -59.5296 -2.55332 0.570778 -58.9527 +-3.18881 -0.248538 -59.4603 -2.71281 0.227462 -58.9843 +-3.11502 -1.17383 -59.115 -2.75862 0.292707 -58.5878 +-3.15316 -0.109956 -59.1284 -2.54998 0.491812 -58.5135 +-3.10927 -0.376974 -59.1192 -2.63217 0.0993431 -58.6392 +-3.35004 -1.17536 -59.3186 -2.89281 0.59853 -58.8882 +-3.53439 0.216972 -59.5097 -2.93205 0.817192 -58.9088 +-3.34722 0.0224848 -59.411 -2.8712 0.500194 -58.9214 +-3.45641 -1.17383 -59.115 -2.88502 0.314801 -58.6682 +-3.54462 -0.034265 -59.1756 -2.95773 0.548705 -58.5779 +-3.43839 -0.216784 -59.1588 -2.95699 0.261117 -58.6729 +-3.23279 -1.17383 -59.115 -2.88502 0.687304 -58.5618 +-3.48319 0.31427 -59.0906 -2.88048 0.914711 -58.4895 +-3.29885 0.0860082 -59.0689 -2.81873 0.563844 -58.5798 +-3.10627 -1.17476 -59.217 -2.64658 0.759873 -58.8728 +-3.18474 0.362089 -59.3962 -2.54052 1.00249 -58.7545 +-3.1434 0.126777 -59.2908 -2.66686 0.602828 -58.8144 +-3.27751 -1.17318 -59.1186 -2.87721 1.06194 -58.8871 +-3.48234 0.676297 -59.3255 -2.83729 1.31669 -58.6837 +-3.39185 0.473023 -59.2363 -2.91301 0.949269 -58.7591 +-71.8548 1.77313 69.5804 -71.0969 2.57993 70.3214 +-84.678 1.64055 105.116 -84.2251 2.45208 105.803 +24.086 6.90199 -12.9078 24.8135 9.64214 -12.5506 +24.2636 9.07709 -13.1833 25.1225 9.93607 -12.3002 +24.2298 8.60324 -13.0916 24.9379 9.30807 -12.3668 +23.5298 6.90416 -12.9157 24.3317 9.40928 -12.3438 +23.4105 8.85122 -12.9809 24.368 9.78644 -12.0488 +23.6566 8.36353 -12.8955 24.3634 9.06853 -12.1877 +24.0863 6.90293 -13.3173 24.5483 10.0014 -12.6666 +23.9164 9.46967 -13.6668 24.8732 10.4019 -12.7273 +23.9992 9.09188 -13.4857 24.7251 9.79725 -12.7745 +23.7732 6.8997 -13.3864 24.3227 9.514 -12.6766 +23.4528 8.97874 -13.7128 24.3688 9.87683 -12.8156 +23.6517 8.64879 -13.5207 24.365 9.35544 -12.8108 +23.6533 6.90406 -13.046 24.3362 10.1772 -12.678 +23.324 9.63793 -13.3748 24.2633 10.5708 -12.4365 +23.4561 9.19884 -13.2631 24.1801 9.90668 -12.5561 +24.08 6.90244 -12.8987 24.548 10.2892 -12.3542 +23.8734 9.70628 -12.9854 24.9012 10.712 -11.98 +23.9433 9.27535 -12.8856 24.6751 9.98054 -12.1738 +23.9047 6.90416 -13.0806 24.3317 10.8311 -12.6608 +23.617 10.2943 -13.4737 24.635 11.2994 -12.4674 +23.788 9.92424 -13.2939 24.5062 10.6293 -12.5864 +-2.21334 1.91208 88.6723 -1.62982 2.33798 89.2125 +11.5751 -3.164 -23.4726 11.8745 -2.82911 -23.0853 +11.2507 -3.16254 -23.4649 11.5521 -2.82669 -23.078 +11.2757 -3.16984 -23.564 11.8519 -2.91174 -22.988 +11.5072 -3.16384 -23.338 11.874 -2.82974 -22.9662 +11.3725 -3.16311 -23.2643 11.7592 -2.82733 -22.9635 +11.3653 -3.16369 -23.5875 11.7542 -2.83027 -23.2873 +11.2534 -3.16244 -23.3322 11.6258 -2.82667 -22.9634 +11.2505 -3.16319 -23.5845 11.62 -2.82793 -23.2136 +11.5016 -3.16406 -23.5874 11.8722 -2.82932 -23.2195 +-80.2216 1.90208 154.205 -79.3677 2.52413 154.825 +-33.0253 2.11783 59.8754 -32.3344 2.53597 60.4171 +-66.6439 3.21535 147.872 -65.9863 3.6335 148.633 +-68.5987 1.86766 63.7669 -67.9188 2.33951 64.5019 +-2.40774 -4.10251 -33.5757 -1.76416 -3.12604 -32.9385 +-50.4882 1.14522 91.1003 -50.0258 1.42974 91.541 +-50.4873 1.13129 90.9694 -50.0247 1.38347 91.6107 +22.543 -2.91359 -48.3175 22.9318 -1.33175 -47.8425 +22.3313 -1.73006 -48.195 22.8919 -1.17004 -47.6349 +22.4436 -1.99008 -48.206 22.923 -1.51402 -47.7299 +22.2423 -2.91359 -48.4353 22.773 -1.44706 -48.0875 +22.0476 -1.86585 -48.5004 22.6491 -1.26548 -47.9001 +22.1955 -2.13144 -48.5276 22.6715 -1.65544 -48.0516 +22.543 -2.91359 -48.3843 22.9372 -1.12062 -48.0875 +22.4862 -1.4981 -48.4497 23.089 -0.897849 -47.8491 +22.5094 -1.70516 -48.402 22.9865 -1.22909 -47.9258 +22.543 -2.91359 -48.713 22.8573 -1.42496 -48.0875 +22.4734 -1.76239 -48.6912 23.0582 -1.1819 -48.1105 +22.4938 -1.96283 -48.6785 22.9738 -1.48518 -48.1937 +22.3947 -2.91359 -48.6278 22.773 -1.05246 -48.0875 +22.1634 -1.42366 -48.6867 22.7669 -0.823155 -48.0859 +22.2545 -1.65886 -48.5944 22.7329 -1.18251 -48.1178 +22.3264 -2.91328 -48.3128 22.78 -0.989006 -47.8587 +22.1079 -1.40081 -48.2938 22.7509 -0.760498 -47.6531 +22.2169 -1.63521 -48.2577 22.6943 -1.15904 -47.7815 +22.4404 -2.91393 -48.3262 22.7651 -0.673976 -48.0828 +22.268 -1.05825 -48.5239 22.9128 -0.418089 -47.8831 +22.3468 -1.26157 -48.4438 22.8268 -0.785407 -47.967 +-1.73709 1.88538 89.6985 -1.38418 2.33448 90.0514 +-70.7982 1.9 146.547 -70.1473 2.65279 147.561 +-30.7312 1.58818 151.84 -30.3585 2.08793 152.439 +-64.0078 2.55623 157.124 -63.2191 2.97438 157.888 +49.9175 2.09917 67.1866 50.4506 2.49996 67.6208 +49.91 1.89268 67.1851 50.4531 2.30474 67.6181 +50.079 1.96012 67.1564 50.3188 2.44572 67.4059 +49.9889 1.96148 67.1838 50.2287 2.44709 67.4333 +50.0453 2.29377 67.2272 50.2953 2.54377 67.4772 +-94.5232 1.08332 89.1903 -94.1892 1.41732 89.5243 +-66.7221 2.10883 147.854 -66.0951 2.52698 148.598 +-94.5995 1.04784 89.4574 -94.2655 1.38184 89.7914 +-35.7368 5.55874 44.6636 -35.3498 5.85645 44.9901 +-35.8867 4.91389 44.4842 -35.1985 5.6579 45.1727 +-118.245 0.1388 147.042 -117.803 0.921573 147.706 +-63.53 2.55399 155.516 -62.8019 3.09564 156.063 +-62.9158 2.10147 154.063 -62.2448 2.51962 154.83 +-85.1888 0.888483 104.968 -84.6139 1.68678 105.69 +-98.1991 5.09006 147.54 -97.4438 5.53755 148.432 +-32.94 0.359627 61.9621 -32.3614 0.777775 62.6746 +23.035 -0.235213 -26.7732 23.5289 0.516584 -26.278 +34.3991 2.82017 83.9245 34.78 3.15506 84.2544 +34.5067 2.82163 83.6031 34.8876 3.15749 83.9344 +34.3442 2.81433 83.6301 34.9434 3.07243 84.2289 +34.3182 2.82034 83.8361 34.6723 3.15443 84.2087 +34.3184 2.82106 83.6838 34.649 3.15684 84.0644 +34.6385 2.82048 83.7914 34.9686 3.1539 84.1743 +34.3626 2.82173 83.6027 34.737 3.15751 83.9581 +34.6149 2.82099 83.6471 34.9689 3.15624 84.0229 +34.5504 2.82011 83.9009 34.9244 3.15485 84.2543 +-68.1338 1.8676 63.6514 -67.481 2.33945 64.3628 +7.41303 -5.1 -41.5084 8.50318 -4.28802 -40.918 +-72.384 2.75306 146.232 -71.7591 3.17121 146.976 +-29.2679 3.08818 146.798 -28.8952 3.58793 147.397 +-73.7698 -0.362751 172.374 -73.3894 0.259598 172.913 +-74.5383 -0.0335257 172.076 -74.0884 0.304496 172.874 +-74.5949 -0.362751 171.865 -74.2145 0.259598 172.404 +-74.4122 -0.362751 172.546 -74.0319 0.259598 173.086 +-73.9524 -0.362751 171.692 -73.5721 0.259598 172.232 +-73.8958 -0.0335257 171.903 -73.446 0.304496 172.702 +-74.617 0.386819 171.757 -73.6927 0.721588 172.262 +-73.9379 0.113921 171.753 -73.5774 0.697037 172.218 +-73.9162 0.315455 171.811 -73.4204 0.607501 172.798 +-74.5421 0.084496 171.897 -73.4515 0.425484 172.891 +-73.7677 0.113921 172.388 -73.4071 0.697037 172.854 +-74.4028 0.386819 172.558 -73.478 0.721588 173.067 +-73.9379 0.477037 171.751 -73.3984 0.948567 172.854 +-74.4085 0.113921 172.56 -74.0503 0.618986 173.017 +-74.5765 0.113921 171.933 -74.2182 0.618986 172.39 +19.5099 -1.17383 -59.2992 19.8964 0.408012 -58.8227 +19.3994 0.0178343 -59.2253 19.9809 0.57798 -58.6603 +19.4084 -0.250031 -59.1889 19.8862 0.226067 -58.7126 +19.2104 -1.17383 -59.4199 19.7399 0.292708 -59.0692 +19.1174 -0.104751 -59.5 19.7202 0.495783 -58.8923 +19.1633 -0.39168 -59.5114 19.6394 0.0843202 -59.0354 +19.5099 -1.17383 -59.3644 19.9048 0.619149 -59.0692 +19.5578 0.229394 -59.4516 20.1645 0.830605 -58.8421 +19.5817 0.0226728 -59.3775 20.0612 0.499081 -58.8983 +19.5099 -1.17383 -59.6939 19.828 0.314801 -59.0692 +19.4228 -0.0400296 -59.7738 20.0066 0.540972 -59.1879 +19.4683 -0.221957 -59.6527 19.9491 0.255558 -59.1678 +19.3647 -1.17383 -59.611 19.7399 0.687305 -59.0692 +19.2374 0.319221 -59.7159 19.8441 0.921314 -59.1028 +19.3233 0.0878445 -59.5895 19.8002 0.564494 -59.1077 +19.3017 -1.17368 -59.2938 19.7463 0.752452 -58.8491 +19.1745 0.353903 -59.3222 19.8205 0.994921 -58.6687 +19.2883 0.114634 -59.2333 19.7685 0.591229 -58.755 +19.5099 -1.17383 -59.3509 19.7739 1.06722 -59.0692 +19.2382 0.681596 -59.5154 19.8798 1.32165 -58.875 +19.316 0.478256 -59.4331 19.7925 0.954275 -58.9571 +-23.1054 -3.21191 -2.59909 -22.493 -2.74532 -1.94401 +-79.4712 0.672161 103.727 -78.5413 1.52497 104.646 +-78.9258 1.22297 103.832 -78.3338 2.11264 104.658 +-47.6375 1.84103 116.607 -47.2504 2.24295 117.025 +-47.6544 1.83816 116.607 -47.2621 2.25179 117.032 +-47.6565 1.84103 116.591 -47.2694 2.24295 117.009 +-47.6292 1.84103 116.613 -47.2421 2.24295 117.032 +31.8014 0.578613 36.9359 32.1777 0.874613 37.2845 +31.6617 -0.063928 36.7677 32.3317 0.672841 37.4522 +-48.9842 1.51455 116.657 -48.2175 2.32135 117.541 +-117.317 2.38653 159.743 -116.804 3.13353 160.403 +-80.6948 1.65095 100.792 -80.3778 2.21509 101.109 +20.6453 -3.09917 -30.891 21.1393 -2.34737 -30.3958 +-68.4258 4.06074 147.459 -67.6507 4.47889 148.148 +-72.2842 -0.361046 171.97 -71.8902 0.261303 172.509 +-72.8501 -0.0318207 171.303 -72.3738 0.306201 172.097 +-72.7007 -0.361046 171.095 -72.3067 0.261303 171.634 +-72.9172 -0.361046 171.766 -72.5232 0.261303 172.305 +-72.0677 -0.361046 171.299 -71.6737 0.261303 171.838 +-72.2171 -0.0318207 171.507 -71.7407 0.306201 172.301 +-72.6834 0.388524 171.112 -71.7633 0.723293 171.652 +-72.0648 0.115626 171.357 -71.6944 0.698742 171.824 +-72.2424 0.31716 171.413 -71.7223 0.609206 172.391 +-72.8547 0.086201 171.286 -71.747 0.427189 172.304 +-72.2666 0.115626 171.983 -71.8962 0.698742 172.45 +-72.9372 0.388524 171.904 -72.0178 0.723293 172.442 +-72.2666 0.478742 171.357 -71.6858 0.950272 172.452 +-72.8954 0.115626 171.78 -72.5276 0.620691 172.238 +-72.6963 0.115626 171.162 -72.3285 0.620691 171.62 +-30.2434 -1.41182 150.159 -29.8708 -0.912072 150.758 +21.3455 -3.20353 33.1064 22.1437 -2.57544 33.9678 +21.3979 -2.97348 33.1509 22.1442 -2.52064 33.5636 +-50.5181 2.4529 91.0592 -49.662 3.2597 91.6415 +-120.389 -0.611204 146.334 -119.904 0.170659 147.03 +-96.884 1.04784 88.7425 -96.55 1.38184 89.0765 +-79.8473 4.06074 152.586 -79.1026 4.47889 153.213 +-84.9471 0.145278 105.038 -84.4943 0.956802 105.725 +-161.478 1.4002 94.6716 -160.362 3.11258 95.8493 +-75.0245 0.643778 90.4725 -74.2316 1.40584 91.3265 +-93.1739 0.205707 141.498 -92.3591 0.967768 142.371 +49.6418 2.76135 66.2827 50.2493 3.33873 66.789 +14.1544 -3.04914 -13.3179 14.9251 -2.35556 -12.4208 +-69.3792 1.89977 147.042 -68.4682 2.66183 147.905 +-44.0553 -1.51663 150.868 -43.3152 -1.25372 151.268 +-44.1109 -1.92942 150.899 -43.7185 -1.28844 151.454 +-44.0839 -1.92469 150.636 -43.5492 -1.28796 151.077 +1.36801 7.16848 78.793 2.0011 8.14495 79.4268 +-52.303 0.656493 85.2668 -51.8614 1.22329 85.6996 +-109.966 0.893715 149.48 -109.513 1.70524 150.166 +-27.1436 -0.095538 55.9549 -26.1654 0.429949 56.6944 +14.1857 -3.04914 -13.6631 14.9564 -2.35556 -12.7659 +21.6495 -4.68379 10.6577 22.2421 -4.39635 11.3333 +-149.316 0.726823 100.249 -148.152 2.4392 101.416 +-132.744 2.79296 91.1784 -131.775 3.16356 92.1136 +-76.6869 0.672161 103.3 -75.6646 1.52497 104.315 +-76.1664 1.22297 103.232 -75.4738 2.11264 104.088 +-116.331 3.88995 160.047 -115.847 4.67181 160.743 +-110.77 -0.599745 149.244 -110.257 0.147262 149.904 +-32.9521 0.165915 61.974 -32.4104 0.584064 62.665 +-119.837 -0.611204 146.442 -119.384 0.200321 147.129 +28.801 2.42021 53.0278 29.7787 3.10361 53.5976 +28.0579 2.42291 53.3056 29.1152 2.69891 53.9087 +27.3856 2.42526 53.6068 28.3957 3.11516 54.1901 +27.1546 1.89 53.7643 27.771 3.18992 54.3814 +29.4242 1.89 52.8142 30.0406 3.18992 53.4313 +-32.8088 -0.0356273 3.94529 -32.2455 0.905063 4.6978 +-32.7348 -0.022919 3.04546 -32.3195 0.603218 4.30137 +-63.5074 2.55964 155.884 -62.7932 2.97779 156.668 +-141.634 1.88903 87.7472 -140.889 2.31429 88.6035 +-118.807 1.6388 146.955 -118.311 2.44407 147.671 +14.2483 -3.19543 -35.1498 14.6048 -2.74632 -34.7934 +-165.71 1.7066 91.2569 -164.526 3.41897 92.428 +-46.5889 5.80945 86.015 -46.1501 6.37624 86.4448 +-72.659 1.56735 88.6055 -72.1343 2.40435 89.1722 +7.85426 -3.17533 -30.3134 8.21068 -2.72622 -29.957 +-136.105 2.89263 85.9818 -135.506 3.39238 86.3544 +16.284 -4.0848 -36.7751 17.3727 -3.27282 -36.1883 +-84.0978 -0.604885 105.458 -83.6131 0.176978 106.154 +-27.8284 -4.11 -1.0163 -26.8525 -3.41776 0.0316597 +-141.401 1.89978 139.976 -140.802 2.39953 140.349 +45.924 1.8939 79.4255 46.6019 2.58292 80.1033 +15.0224 -1.0135 -10.9985 15.5297 0.813926 -10.6618 +15.1447 0.374164 -11.13 15.7696 0.995915 -10.5037 +15.0954 0.0762105 -11.0694 15.6204 0.599442 -10.5452 +14.6604 -1.01152 -10.9971 15.2455 0.663079 -10.5592 +14.667 0.246909 -11.0694 15.3471 0.915738 -10.3998 +14.7047 -0.0788943 -11.0157 15.2466 0.447016 -10.49 +15.0138 -1.01207 -11.2834 15.3574 1.03979 -10.7644 +14.9614 0.620928 -11.4972 15.6488 1.29121 -10.8266 +14.9382 0.385027 -11.382 15.4854 0.9092 -10.8584 +14.6186 -1.01152 -11.3485 15.2455 0.67805 -10.762 +14.6085 0.311656 -11.5283 15.2785 0.958741 -10.881 +14.7506 0.10059 -11.4099 15.2821 0.624872 -10.8841 +14.5464 -1.01152 -11.072 15.2455 1.1165 -10.762 +14.5166 0.733234 -11.3384 15.2019 1.40354 -10.6694 +14.5658 0.447506 -11.2371 15.1135 0.974627 -10.7102 +15.0237 -1.0126 -10.9909 15.347 1.23018 -10.5797 +14.8704 0.783009 -11.0701 15.6155 1.49869 -10.3456 +14.9751 0.504992 -11.0076 15.516 1.02901 -10.4826 +14.9002 -1.01152 -11.1026 15.2455 1.57266 -10.762 +14.7496 1.15601 -11.3845 15.4815 1.87091 -10.6692 +14.8624 0.919307 -11.2662 15.3977 1.44233 -10.7417 +-43.7779 1.63102 55.5965 -43.3631 1.97096 56.0365 +-43.7359 1.63222 55.6519 -43.3693 1.8844 56.0246 +-43.6676 1.67699 55.6363 -43.3607 1.97063 55.9766 +-43.7719 1.62499 55.5991 -43.4317 1.97697 55.9747 +-109.381 0.150417 149.649 -108.928 0.961942 150.336 +-116.2 2.38653 160.131 -115.715 3.16839 160.827 +27.6488 2.10017 84.3408 28.1801 2.50096 84.7619 +27.6412 1.89368 84.3439 28.1824 2.30574 84.7633 +27.7215 1.96112 84.526 27.9611 2.44672 84.7756 +27.813 1.96248 84.548 28.0526 2.44809 84.7976 +27.7769 2.29477 84.479 28.0269 2.54477 84.729 +-73.933 1.63484 162.552 -73.6171 2.19897 162.868 +-46.2024 0.868428 92.1164 -45.7764 1.43522 92.5523 +-115.453 3.88995 160.302 -115.001 4.70148 160.989 +-134.126 2.58519 90.6961 -133.542 2.95677 91.5717 +-23.021 -2.78204 5.43057 -22.5797 -2.4421 5.85361 +-22.9619 -2.78084 5.44563 -22.5885 -2.52866 5.80582 +-22.9125 -2.73607 5.42792 -22.5734 -2.44243 5.75137 +-23.0268 -2.78807 5.44242 -22.6781 -2.43609 5.81284 +-115.781 4.64039 160.264 -115.268 5.38739 160.924 +14.3203 -2.47353 -13.9303 14.9616 -1.9522 -12.8658 +24.3454 0.372029 28.7318 24.7051 0.821137 29.0915 +-67.8774 3.86703 147.584 -67.0935 4.28517 148.297 +-9.09104 3.28346 72.6561 -8.55508 3.70434 73.026 +-9.10146 3.07948 72.6558 -8.55979 3.51716 73.025 +-9.00586 3.16348 72.8284 -8.74664 3.64805 73.0775 +-8.91202 3.1564 72.8321 -8.6528 3.64097 73.0812 +-8.93186 3.49146 72.771 -8.68186 3.74146 73.021 +-95.6573 1.08332 88.8196 -95.3233 1.41732 89.1536 +-114.804 3.88995 160.491 -114.319 4.67181 161.186 +-80.278 2.76071 154.047 -79.5333 3.17885 154.674 +-163.992 1.41757 105.668 -163.262 2.11613 106.278 +-1.67548 -2.98948 -35.6027 -1.19548 -2.13148 -35.1227 +-118.782 0.1388 147.013 -118.291 0.932371 147.719 +-72.4766 -0.358784 170.569 -71.4938 0.403277 171.541 +-29.7556 0.0881764 148.478 -29.383 0.587928 149.077 +-47.5773 1.04179 116.694 -47.1902 1.44371 117.113 +-47.5942 1.03892 116.695 -47.2018 1.45255 117.12 +-47.5963 1.04179 116.679 -47.2092 1.44371 117.097 +-47.569 1.04179 116.701 -47.1819 1.44371 117.12 +-126.905 5.86291 86.5696 -126.306 6.36266 86.9423 +-69.7664 2.55677 147.144 -68.7671 3.07399 147.96 +22.2604 -3.44451 -22.7068 22.6245 -3.14851 -22.3432 +22.1124 -4.08705 -22.8546 22.7728 -3.35028 -22.1946 +-74.3646 1.21077 90.176 -73.3104 1.72799 91.2397 +-22.0595 -4.11 -3.558 -20.9475 -3.41776 -2.42506 +8.2975 -3.11091 -30.2173 8.7286 -2.65435 -29.7516 +8.38382 -3.09669 -29.5087 8.76963 -2.63544 -29.1352 +8.26063 -3.17937 -30.3323 9.36166 -2.85526 -29.0223 +8.85533 -3.09996 -30.237 9.24292 -2.56595 -29.8408 +8.90946 -3.0944 -29.5498 9.2912 -2.65146 -29.1665 +-49.4511 1.75446 91.384 -49.0203 2.35807 91.8219 +27.7446 2.36855 84.6765 28.102 2.81766 85.0339 +-84.1434 0.888575 105.317 -83.6301 1.63558 105.978 +-50.6557 0.647872 57.2388 -49.6988 1.50068 58.1856 +-50.1158 1.19868 57.2023 -49.4962 2.08835 58.0387 +-132.76 2.59758 91.2076 -131.85 3.01369 92.0794 +0.0076291 -0.457125 94.3319 0.374769 -0.161125 94.6924 +-0.139382 -1.09967 94.1782 0.521998 -0.362898 94.8453 +-25.8921 -2.58924 -3.79012 -25.3568 -2.18844 -3.30433 +-25.8986 -2.79572 -3.79357 -25.3629 -2.38367 -3.30932 +-25.7632 -2.72829 -3.79247 -25.5201 -2.24268 -3.54433 +-25.8434 -2.72692 -3.74306 -25.6003 -2.24132 -3.49492 +-25.7762 -2.39464 -3.71746 -25.5262 -2.14464 -3.46746 +-50.8035 1.75624 90.9725 -50.3718 2.09618 91.4286 +-50.7497 1.75744 91.0336 -50.3949 2.00961 91.4065 +-50.6815 1.8022 91.0675 -50.3702 2.09584 91.4144 +-50.7682 1.75021 90.9585 -50.3973 2.10219 91.3131 +-47.6375 1.24076 116.607 -47.2504 1.64267 117.025 +-47.6544 1.23788 116.607 -47.2621 1.65151 117.032 +-47.6565 1.24076 116.591 -47.2694 1.64267 117.009 +-47.6292 1.24076 116.613 -47.2421 1.64267 117.032 +-107.237 -0.248024 154.097 -106.367 0.102497 154.942 +21.7303 -4.74219 -48.0524 22.2623 -4.33923 -47.6417 +21.7217 -4.94861 -48.0531 22.2635 -4.53371 -47.6438 +21.9001 -4.8798 -48.0931 22.1409 -4.39425 -47.8429 +21.8078 -4.8776 -48.0746 22.0486 -4.39205 -47.8244 +21.8622 -4.54595 -48.0248 22.1122 -4.29595 -47.7748 +-106.508 -1.23896 151.52 -105.714 -0.897685 152.444 +27.4582 5.89084 64.7933 27.9465 6.64263 65.2807 +15.5078 -3.16873 -13.4482 16.145 -2.22914 -12.655 +15.6447 -3.14317 -13.0375 16.2059 -2.52813 -11.7837 +11.3759 -3.19559 -35.8936 11.7587 -2.96099 -35.5507 +-49.4244 1.21736 118.163 -48.899 1.61815 118.672 +-49.4202 1.01087 118.159 -48.8934 1.42292 118.665 +-49.176 1.07831 118.239 -48.9308 1.56391 118.486 +-49.2483 1.07967 118.179 -49.003 1.56527 118.425 +-49.2535 1.41196 118.252 -49.0035 1.66196 118.502 +-8.38832 2.86978 72.8957 -8.0313 3.31889 73.2527 +-49.4916 0.664679 84.9697 -49.0672 1.26829 85.3979 +25.5075 8.42928 28.782 25.8725 10.2943 29.147 +23.3514 6.12502 26.6606 27.9509 8.8271 31.1854 +-79.5047 2.10883 151.53 -78.8777 2.52698 152.274 +-67.7867 3.40906 147.538 -67.1598 3.82721 148.283 +23.729 6.8844 -1.35626 24.3424 9.73781 -0.650529 +23.3473 9.16697 -1.37073 24.2437 10.0604 -0.471627 +23.5078 8.66509 -1.33902 24.2414 9.39666 -0.603846 +23.9294 6.8844 -2.0128 24.3424 9.50384 -1.0986 +23.5232 8.93052 -2.11133 24.4938 9.89991 -1.13795 +23.7035 8.39971 -1.98417 24.4363 9.13167 -1.24603 +24.0848 6.88312 -1.34665 24.4716 10.1372 -0.699678 +23.838 9.57422 -1.21384 24.8073 10.5433 -0.243231 +23.9483 9.18752 -1.24597 24.6805 9.91882 -0.508844 +24.0847 6.8844 -1.61732 25.0066 9.58059 -1.0986 +24.2004 9.09326 -1.62655 25.1312 10.0237 -0.694673 +24.2508 8.72675 -1.63443 24.9853 9.45813 -0.896504 +24.1055 6.88235 -1.6424 24.5669 10.3257 -1.1067 +23.9603 9.76782 -2.00115 24.9293 10.7371 -1.02706 +24.0477 9.3083 -1.87976 24.7801 10.0395 -1.14389 +23.5973 6.88177 -1.37561 24.3243 10.4176 -1.09946 +23.194 9.81331 -1.77023 24.2402 10.859 -0.717476 +23.4388 9.36105 -1.55209 24.1697 10.0915 -0.81995 +24.0679 6.88509 -1.3708 24.3863 11.0076 -0.995194 +23.7349 10.451 -1.65197 24.7808 11.4968 -0.602011 +23.8865 10.0618 -1.54804 24.6179 10.7924 -0.81049 +20.0515 -4.74295 -48.0202 20.5874 -4.33999 -47.6347 +20.052 -4.94937 -48.0211 20.5877 -4.53448 -47.6361 +20.2608 -4.88057 -48.0618 20.4972 -4.39502 -47.8108 +20.1671 -4.87837 -48.0711 20.4035 -4.39282 -47.8201 +20.2023 -4.54672 -48.0058 20.4523 -4.29672 -47.7558 +-92.0427 1.56594 97.1582 -91.6757 1.81741 97.5252 +-93.6548 1.56715 96.6521 -93.2503 1.82348 97.0566 +-91.8857 1.56225 97.2005 -91.4812 1.81857 97.605 +-73.0584 3.86888 146.01 -72.1991 4.63094 146.918 +-62.1001 2.66147 129.378 -61.5689 3.06226 129.795 +-62.1078 2.45499 129.38 -61.5672 2.86704 129.796 +-62.0263 2.52242 129.562 -61.7869 3.00802 129.812 +-61.9344 2.52378 129.582 -61.695 3.00939 129.832 +-61.9718 2.85607 129.514 -61.7218 3.10607 129.764 +-21.1627 0.840004 63.0134 -20.1672 1.36549 63.9301 +-73.7359 2.76573 71.8127 -73.2046 3.16653 72.3079 +-73.7321 2.55925 71.8087 -73.1985 2.9713 72.3004 +-73.4902 2.62668 71.8707 -73.246 3.11229 72.1181 +-73.5679 2.62805 71.8175 -73.3237 3.11365 72.0649 +-73.5663 2.96034 71.8915 -73.3163 3.21034 72.1415 +-68.7173 3.21535 158.311 -68.0597 3.6335 159.072 +-68.077 2.56699 147.452 -67.4194 2.98514 148.213 +-43.5517 1.62106 55.1435 -43.0867 2.18786 55.6015 +-33.1136 0.817922 59.7466 -32.2474 1.57998 60.6604 +-28.4551 -3.19904 -0.895937 -27.9612 -2.44724 -0.400765 +-21.6 -3.08559 4.88508 -21.0821 -1.99737 5.43266 +-31.696 -2.11941 -2.18793 -31.1671 -1.01657 -1.64321 +15.1658 -2.27155 -12.6585 15.6309 -1.87075 -12.1239 +15.163 -2.47803 -12.6654 15.6254 -2.06598 -12.1248 +15.1914 -2.4106 -12.6017 15.44 -1.92499 -12.3595 +15.1519 -2.40923 -12.5162 15.4005 -1.92363 -12.274 +15.2247 -2.07695 -12.537 15.4747 -1.82695 -12.287 +22.8324 -1.49536 -26.8378 23.4864 -0.51889 -26.1747 +-104.306 5.37672 150.904 -103.791 5.7483 151.78 +19.224 -1.17383 -71.0525 19.7399 0.40801 -70.7636 +19.102 0.0189565 -71.2639 19.6649 0.579012 -70.6826 +19.1988 -0.241349 -71.2304 19.6789 0.234665 -70.7377 +19.5099 -1.17383 -71.2897 19.959 0.292706 -70.8225 +19.4284 -0.110746 -71.4505 20.0387 0.490534 -70.8482 +19.4497 -0.376831 -71.3397 19.9277 0.0994826 -70.8628 +19.3976 -1.17492 -71.0471 19.7341 0.615064 -70.6331 +19.222 0.233674 -71.0534 19.8378 0.834935 -70.4505 +19.2799 0.023838 -71.0154 19.7659 0.50108 -70.5354 +19.5099 -1.17383 -71.0525 20.0777 0.3148 -70.6001 +19.4703 -0.0239646 -71.0406 20.0568 0.55649 -70.459 +19.5622 -0.219476 -71.0349 20.0486 0.258284 -70.5586 +19.5099 -1.17383 -71.0777 20.083 0.687303 -70.8225 +19.5651 0.318041 -71.2659 20.179 0.920133 -70.6626 +19.5748 0.0849516 -71.1951 20.0617 0.562519 -70.7157 +19.377 -1.17443 -71.2505 19.7428 0.763691 -70.8283 +19.172 0.352597 -71.4613 19.8256 0.99339 -70.8193 +19.26 0.116465 -71.3373 19.7447 0.592834 -70.8577 +19.5099 -1.17383 -71.0525 19.7762 1.06722 -70.7724 +19.342 0.681715 -71.2064 19.982 1.32171 -70.5664 +19.4195 0.478836 -71.1316 19.8955 0.954836 -70.6556 +-48.9954 0.664679 85.62 -48.6794 1.22881 85.9361 +38.4082 2.79281 82.8819 38.9493 3.37019 83.474 +18.7069 -4.10139 35.5002 19.5089 -3.33933 36.2281 +20.4652 -4.74665 -47.9789 21.0011 -4.34369 -47.5934 +20.4657 -4.95306 -47.9798 21.0014 -4.53817 -47.5948 +20.6745 -4.88426 -48.0205 20.9109 -4.39871 -47.7696 +20.5808 -4.88206 -48.0298 20.8172 -4.39651 -47.7788 +20.6159 -4.55041 -47.9645 20.8659 -4.30041 -47.7145 +49.0761 2.72828 66.6117 49.5561 3.58628 67.0917 +-51.1793 1.13083 91.1219 -50.6777 1.40498 91.4554 +-51.1493 1.13083 91.0126 -50.6477 1.40498 91.3461 +-51.1331 1.13083 90.9136 -50.6315 1.40498 91.2472 +-51.2033 1.11735 90.8558 -50.6117 1.36953 91.5086 +23.0136 -0.235213 -32.2558 23.5075 0.516584 -31.7607 +-79.9612 3.21535 152.941 -79.2002 3.6335 153.599 +-54.3024 0.782944 70.3934 -53.7695 1.18374 70.8264 +-54.3051 0.576459 70.3961 -53.7621 0.988511 70.8279 +-54.1713 0.643893 70.6076 -53.9316 1.1295 70.8572 +-54.0811 0.645257 70.5807 -53.8414 1.13086 70.8302 +-54.1475 0.977545 70.5365 -53.8975 1.22755 70.7865 +0.648601 9.4099 79.6567 1.242 11.2667 79.9768 +0.379117 10.8056 79.5783 1.01488 11.4388 80.212 +0.574237 10.5158 79.5756 1.11159 11.0486 80.1098 +0.917153 9.41209 79.3769 1.26051 11.1543 79.8826 +0.682565 10.6927 79.1883 1.36689 11.3727 79.8702 +0.83837 10.3653 79.2762 1.37551 10.8969 79.8102 +0.914747 9.41168 79.6598 1.25083 11.513 80.1748 +0.686993 11.0938 79.7165 1.37584 11.775 80.4012 +0.745602 10.8412 79.7629 1.28107 11.3731 80.2961 +1.0222 9.41157 79.6633 1.43436 11.2195 80.027 +0.978643 10.8017 79.5844 1.63942 11.458 80.2427 +1.06675 10.569 79.5939 1.60679 11.1013 80.1288 +1.01827 9.41276 79.4335 1.60334 11.6061 79.8898 +0.931399 11.2176 79.3105 1.61824 11.8983 79.9941 +0.954525 10.9361 79.4228 1.49001 11.4676 79.956 +0.645402 9.41118 79.5479 1.24726 11.6808 79.8842 +0.394548 11.2274 79.2961 1.12871 11.9563 80.0272 +0.530829 10.9428 79.4309 1.06558 11.4746 79.9636 +0.914208 9.41303 79.6423 1.25224 12.0604 79.9554 +0.629882 11.6351 79.4893 1.36247 12.3634 80.2192 +0.72788 11.3909 79.5814 1.26177 11.9222 80.1129 +-53.2255 0.621673 90.2279 -52.7728 0.994528 90.6862 +-53.0993 0.633143 90.2886 -52.6424 0.917663 90.7413 +-53.3002 0.619209 90.1134 -52.5553 0.871389 90.8551 +9.04502 2.66753 65.2497 9.81501 3.53504 65.9847 +-33.0281 1.46615 61.7192 -32.3371 1.8843 62.2608 +-124.984 7.39263 87.1271 -124.385 7.89238 87.4997 +-50.3076 4.59298 100.574 -49.4186 5.51522 101.464 +14.1603 -2.92247 -12.4276 15.1638 -2.56762 -11.3378 +-17.8522 -3.64578 -3.29852 -16.96 -2.81744 -2.22523 +15.0227 -3.04421 -14.095 15.94 -2.41613 -13.2319 +15.0595 -2.81416 -13.9903 15.5417 -2.36132 -13.2385 +-79.8327 2.10883 152.526 -79.088 2.52698 153.153 +11.5915 -3.99933 -39.2801 12.026 -3.54277 -38.813 +11.577 -3.98511 -39.8976 11.9634 -3.52386 -39.5267 +10.9904 -4.06779 -40.0069 12.0553 -3.74368 -38.7243 +11.0798 -3.98839 -39.2097 11.4638 -3.45437 -38.8164 +11.0524 -3.98282 -39.8893 11.4388 -3.53988 -39.5013 +3.49693 -4.25663 -47.7303 4.25692 -3.99373 -47.4703 +3.83221 -4.66942 -48.022 4.30176 -4.02844 -47.5152 +3.82518 -4.66469 -47.689 4.29863 -4.02797 -47.1789 +-52.6751 2.45499 91.0113 -51.8223 3.26179 91.8514 +15.2491 -2.25319 -13.0689 15.662 -1.85239 -12.5368 +15.2484 -2.45967 -13.0705 15.6601 -2.04762 -12.5291 +15.2096 -2.39224 -12.9456 15.4594 -1.90663 -12.7071 +15.2288 -2.39087 -12.8534 15.4787 -1.90527 -12.6149 +15.2777 -2.05858 -12.9166 15.5277 -1.80858 -12.6666 +-48.5695 1.24076 117.718 -48.1824 1.64267 118.137 +-48.5864 1.23788 117.719 -48.1941 1.65151 118.144 +-48.5885 1.24076 117.703 -48.2014 1.64267 118.121 +-48.5612 1.24076 117.725 -48.1741 1.64267 118.144 +-51.7375 1.75626 90.8397 -51.2769 2.0962 91.2541 +-51.72 1.75746 90.8811 -51.3486 2.00964 91.2432 +-51.6949 1.80223 90.9717 -51.3479 2.09587 91.2539 +-51.6419 1.75023 90.851 -51.2691 2.10221 91.2123 +-55.3563 0.782944 70.7132 -54.8229 1.18374 71.1156 +-55.3568 0.576459 70.7147 -54.8171 0.988511 71.116 +-55.2367 0.643893 70.9096 -54.9987 1.1295 71.1595 +-55.1438 0.645257 70.8941 -54.9058 1.13086 71.144 +-55.2052 0.977545 70.8428 -54.9552 1.22755 71.0928 +-80.065 4.06074 153.349 -79.3203 4.47889 153.976 +-64.142 2.55636 157.681 -63.4137 3.31842 158.483 +-118.541 18.2444 133.224 -118.091 18.7569 133.674 +-120.601 9.41158 131.155 -116.037 13.5001 135.748 +-1.68543 -0.770112 -30.9262 -1.01835 -0.081094 -30.2589 +-63.1597 3.85967 154.678 -62.3958 4.27782 155.342 +23.4267 -3.16723 33.0487 24.1923 -2.53914 33.8814 +23.4355 -2.93718 33.0951 24.1783 -2.48434 33.4775 +27.2526 -3.18016 30.0126 27.927 -2.89273 30.6068 +-1.65968 -0.774546 -31.369 -1.01611 0.201924 -30.7318 +-64.79 1.9 159.329 -63.8077 2.65279 159.797 +8.08241 -3.18433 -29.7091 8.45517 -2.95642 -29.3828 +-53.2177 -0.358223 68.9478 -52.3665 0.403838 69.7371 +-106.669 -0.700462 151.296 -105.641 -0.305767 152.375 +-53.2832 5.91149 100.821 -52.8295 6.47829 101.267 +-74.5006 -0.362751 172.881 -74.1413 0.259598 173.419 +-73.9376 -0.0335257 173.219 -73.5285 0.304496 174.021 +-73.9783 -0.362751 173.698 -73.619 0.259598 174.236 +-73.8471 -0.362751 173.004 -73.4878 0.259598 173.543 +-74.6318 -0.362751 173.574 -74.2725 0.259598 174.113 +-74.5912 -0.0335257 173.095 -74.182 0.304496 173.898 +-74.5452 0.386819 173.755 -73.6166 0.721588 174.215 +-74.6186 0.113921 173.588 -74.2736 0.697037 174.052 +-74.6147 0.315455 173 -74.169 0.607501 173.995 +-74.5867 0.084496 173.084 -73.5257 0.425484 174.039 +-74.4963 0.113921 172.942 -74.1513 0.697037 173.405 +-74.391 0.386819 172.94 -73.4628 0.721588 173.397 +-74.6352 0.477037 172.94 -74.1513 0.948567 174.052 +-73.8444 0.113921 173.074 -73.501 0.618986 173.529 +-73.9651 0.113921 173.712 -73.6217 0.618986 174.166 +-52.7938 1.4681 93.04 -52.3549 1.8689 93.5726 +-52.7897 1.26162 93.0375 -52.353 1.67367 93.5799 +-52.6055 1.32905 93.265 -52.3562 1.81466 93.5056 +-52.5767 1.33042 93.1753 -52.3274 1.81602 93.416 +-52.648 1.6627 93.1964 -52.398 1.9127 93.4464 +-149.907 0.726823 102.358 -148.692 2.4392 103.599 +-99.5285 4.64429 151.288 -98.7247 5.09178 152.215 +-115.425 3.13817 160.308 -114.911 3.88518 160.968 +22.951 -0.235213 -30.6496 23.4449 0.516584 -30.1544 +-49.5967 2.98923 118.427 -49.1473 4.57448 118.849 +-49.8256 4.14822 118.519 -49.2619 4.70984 119.083 +-49.6622 3.91732 118.436 -49.1768 4.396 118.921 +-49.6396 2.99052 118.261 -49.1449 4.46212 118.645 +-49.7447 4.04832 118.028 -49.1345 4.64852 118.639 +-49.674 3.77764 118.154 -49.1934 4.25395 118.634 +-49.3705 2.99054 118.422 -49.1269 4.77871 118.874 +-49.5379 4.39802 118.441 -48.9307 4.99901 119.049 +-49.5032 4.18705 118.497 -49.0226 4.66379 118.978 +-49.3736 2.99106 118.186 -48.8408 4.48676 118.648 +-49.4134 4.15367 118.207 -48.8278 4.7344 118.793 +-49.3139 3.94751 118.188 -48.8247 4.42721 118.679 +-49.3736 2.99106 118.069 -49.0748 4.84968 118.648 +-49.6095 4.49279 118.059 -49.0034 5.09323 118.665 +-49.4858 4.25034 118.1 -49 4.7275 118.583 +-49.7492 2.98944 118.413 -49.1524 4.90103 118.75 +-49.9234 4.49878 118.267 -49.276 5.14052 118.915 +-49.8132 4.25765 118.377 -49.3333 4.73479 118.857 +-49.503 2.99043 118.423 -49.1522 5.22859 118.707 +-49.7055 4.84299 118.26 -49.0592 5.48353 118.907 +-49.6208 4.63917 118.352 -49.141 5.11559 118.833 +-102.488 1.48336 90.0934 -102.078 1.74627 90.8304 +-102.666 1.07057 90.0371 -102.108 1.71155 90.4231 +-102.286 1.07531 90.0659 -101.852 1.71203 90.6045 +-109.276 0.893715 149.68 -108.791 1.67558 150.376 +-72.1947 -0.36095 165.319 -71.1254 0.491857 166.393 +-72.2979 0.189857 165.148 -71.4387 1.07952 165.911 +34.7129 1.84179 82.0503 35.5975 2.59793 82.7853 +34.9426 2.19303 82.3066 35.3598 3.36791 83.2054 +-52.8623 2.0428 93.8771 -52.3437 2.8798 94.4387 +37.1991 2.79008 83.1964 37.58 3.12497 83.5263 +37.3067 2.79154 82.8749 37.6876 3.1274 83.2062 +37.1442 2.78424 82.902 37.7434 3.04235 83.5007 +37.1182 2.79025 83.108 37.4723 3.12434 83.4805 +37.1184 2.79097 82.9556 37.449 3.12675 83.3362 +37.4385 2.79039 83.0633 37.7686 3.12381 83.4462 +37.1626 2.79164 82.8745 37.537 3.12742 83.2299 +37.4149 2.7909 82.9189 37.7689 3.12615 83.2947 +37.3504 2.79002 83.1727 37.7244 3.12476 83.5261 +-126.905 2.89263 86.5696 -126.306 3.39238 86.9423 +-82.163 7.30996 98.2876 -81.7533 7.57286 99.0247 +-82.341 6.89717 98.2314 -81.7827 7.53815 98.6174 +-81.9613 6.9019 98.2602 -81.5267 7.53862 98.7987 +9.23782 -3.17476 -29.8165 9.60996 -2.94684 -29.4913 +11.3718 -3.17373 -35.7537 11.744 -2.94581 -35.4285 +36.3936 2.7347 83.6452 36.8736 3.5927 84.1252 +-98.8398 4.63835 151.012 -97.8658 4.97962 152.039 +-109.247 0.150417 149.688 -108.794 0.961942 150.375 +-73.7946 1.62924 162.529 -73.3469 2.19604 162.968 +15.2136 -2.25319 -13.4414 15.6946 -1.85239 -12.9052 +15.2104 -2.45967 -13.4355 15.6898 -2.04762 -12.8986 +15.2082 -2.39224 -13.281 15.4566 -1.90663 -13.0382 +15.2554 -2.39087 -13.1995 15.5037 -1.90527 -12.9567 +15.283 -2.05858 -13.273 15.533 -1.80858 -13.023 +-67.6264 1.64093 158.078 -66.8708 2.05908 158.725 +-129.505 1.62993 88.6052 -128.761 2.86533 89.9247 +-129.847 2.0042 88.5633 -129.353 3.51123 89.4708 +-129.85 2.49027 88.0673 -129.158 2.88233 89.6678 +-129.67 2.2315 88.1369 -128.978 2.62357 89.7375 +-66.7221 4.06074 147.854 -66.0951 4.47889 148.598 +-126.905 7.39263 86.5696 -126.306 7.89238 86.9423 +-8.71951 3.74673 75.14 -8.28129 4.14753 75.6726 +-8.72144 3.54025 75.1326 -8.28531 3.9523 75.675 +-8.71873 3.60768 75.2072 -8.46945 4.09329 75.4478 +-8.74732 3.60905 75.2969 -8.49804 4.09465 75.5375 +-8.67682 3.94133 75.2663 -8.42682 4.19133 75.5163 +-73.4115 2.42669 90.3943 -72.6732 3.23349 91.2805 +2.85137 2.27685 -28.9422 3.19437 3.91985 -28.5992 +0.981421 0.27849 -30.782 4.99697 2.64963 -26.8313 +-33.0905 2.11669 61.3662 -32.2885 2.87875 62.0935 +-28.8043 -3.03979 0.334067 -27.6724 -2.65123 1.6214 +-68.2675 3.86589 158.402 -67.4061 4.62795 159.312 +-53.012 5.91709 100.932 -52.6955 6.48123 101.249 +15.787 -3.17526 -30.3309 16.0896 -2.84037 -29.9437 +15.462 -3.1738 -30.3132 15.7667 -2.83795 -29.9265 +15.4873 -3.1811 -30.4191 16.0668 -2.923 -29.8397 +15.7235 -3.1751 -30.1945 16.0892 -2.841 -29.8217 +15.5908 -3.17437 -30.119 15.9773 -2.83859 -29.815 +15.5736 -3.17495 -30.4428 15.9624 -2.84153 -30.1393 +15.4688 -3.1737 -30.1825 15.8422 -2.83793 -29.8148 +15.4619 -3.17444 -30.4356 15.8302 -2.83919 -30.0639 +15.7117 -3.17532 -30.4427 16.0832 -2.84058 -30.0759 +-63.0729 2.75335 154.433 -62.3246 3.1715 155.066 +-79.5839 3.86703 151.508 -78.8228 4.28517 152.166 +-64.5409 3.20236 158.633 -63.6357 3.96443 159.488 +-48.3066 1.24076 117.405 -47.9195 1.64267 117.823 +-48.3235 1.23788 117.405 -47.9311 1.65151 117.83 +-48.3256 1.24076 117.389 -47.9385 1.64267 117.807 +-48.2983 1.24076 117.412 -47.9112 1.64267 117.83 +-48.8688 4.60829 86.1204 -48.0743 5.53053 86.9159 +-33.0253 0.165916 59.8754 -32.3344 0.584065 60.4171 +-46.1537 0.66645 85.5793 -45.7384 1.00639 86.0201 +-46.1154 0.667651 85.6362 -45.75 0.919828 86.0121 +-46.0615 0.712419 85.6908 -45.7335 1.00606 86.0249 +-46.1116 0.660424 85.5768 -45.7445 1.0124 85.9204 +27.4824 -5.06932 -47.7796 28.2975 -4.12863 -47.1074 +26.638 -5.05661 -47.897 27.882 -4.43048 -47.2721 +-73.7576 1.97442 71.7879 -73.2468 2.37521 72.313 +-73.7527 1.76793 71.7823 -73.2421 2.17999 72.3062 +-73.5098 1.83537 71.8897 -73.2631 2.32097 72.1348 +-73.5723 1.83673 71.8192 -73.3256 2.32234 72.0643 +-73.5879 2.16902 71.8909 -73.3379 2.41902 72.1409 +24.091 -2.74207 36.8012 24.8433 -2.22485 37.7608 +-0.758548 5.89807 88.1459 -0.0871986 6.58709 88.8171 +-23.2707 -2.76955 5.46035 -22.9149 -2.43466 5.83618 +-23.5637 -2.76809 5.26224 -23.2063 -2.43224 5.63806 +-23.5369 -2.77539 5.25056 -22.9402 -2.51729 5.8476 +-23.3865 -2.76938 5.54695 -23.0039 -2.43529 5.87272 +-23.5269 -2.76866 5.5167 -23.1496 -2.43288 5.87272 +-23.3273 -2.76924 5.22517 -22.9511 -2.43582 5.58167 +-23.5638 -2.76799 5.40279 -23.2363 -2.43221 5.78522 +-23.4764 -2.76873 5.22524 -23.0931 -2.43348 5.55172 +-23.2407 -2.76961 5.313 -22.9153 -2.43487 5.69547 +-63.0523 3.85854 153.997 -62.1368 4.6206 154.865 +-80.4048 1.65354 100.895 -79.9762 2.25715 101.316 +-48.3926 0.647872 56.4615 -47.4358 1.50068 57.4083 +-48.5952 1.19868 56.6084 -47.9756 2.08835 57.4448 +-105.429 -1.36486 154.763 -104.943 -0.742508 155.27 +-105.784 -1.03563 153.958 -105.12 -0.697611 154.666 +-105.462 -1.36486 153.794 -104.975 -0.742508 154.301 +-105.928 -1.36486 154.324 -105.442 -0.742508 154.83 +-104.963 -1.36486 154.234 -104.476 -0.742508 154.741 +-105.285 -1.03563 154.398 -104.621 -0.697611 155.106 +-105.383 -0.615288 153.798 -104.566 -0.280519 154.561 +-104.954 -0.888186 154.28 -104.519 -0.30507 154.729 +-105.347 -0.686652 154.327 -104.569 -0.394606 155.169 +-105.793 -0.917611 153.947 -104.632 -0.576622 155.093 +-105.389 -0.888186 154.773 -104.953 -0.30507 155.222 +-105.93 -0.615288 154.419 -105.114 -0.280519 155.183 +-105.389 -0.52507 154.28 -104.512 -0.0535401 155.228 +-105.881 -0.888186 154.334 -105.451 -0.383121 154.777 +-105.452 -0.888186 153.848 -105.022 -0.383121 154.29 +21.5445 -4.35412 -48.0217 22.0257 -3.60233 -47.5422 +-80.1852 1.65095 104.328 -79.869 2.21508 104.644 +20.1271 1.87795 81.3501 20.7106 2.30385 81.8903 +-98.2583 5.5985 149.296 -96.7525 6.02037 151.136 +-26.1857 -2.07966 -3.81518 -25.0567 -1.55833 -3.53398 +-31.7099 -2.12009 -2.10891 -31.156 -1.03187 -1.53818 +-28.7801 1.58818 145.117 -28.4074 2.08793 145.716 +-46.7331 5.81504 86.0465 -46.4183 6.37918 86.3613 +22.3818 1.89047 84.2628 23.0336 2.86694 84.9284 +17.9966 -3.17568 -36.2383 18.3947 -2.94743 -35.8411 +-118.997 0.888795 146.856 -118.501 1.69407 147.571 +-49.2226 1.75446 91.3529 -48.7918 2.35807 91.7769 +-13.7176 4.19828 5.0426 -13.3331 6.16557 5.63671 +-13.9112 5.7153 5.16722 -13.2473 6.37718 5.83219 +-13.8619 5.37578 5.17655 -13.3075 5.92922 5.72999 +-13.8686 4.2013 4.67292 -13.3285 6.00733 5.26827 +-14.0761 5.56327 4.65904 -13.3615 6.2755 5.37347 +-13.912 5.21715 4.70721 -13.3557 5.77071 5.26605 +-13.5602 4.20062 5.03094 -13.1478 6.43227 5.49737 +-13.6229 5.99989 5.02269 -12.9077 6.71195 5.73779 +-13.5235 5.73722 4.96752 -12.9616 6.29067 5.5349 +-13.5669 4.2013 4.62738 -13.0256 6.05513 5.26827 +-13.499 5.661 4.59752 -12.8081 6.34975 5.29704 +-13.5125 5.4327 4.74639 -12.9566 5.98666 5.30282 +-13.5904 4.2013 4.55635 -13.3285 6.5201 5.26827 +-13.786 6.11681 4.5087 -13.0697 6.8295 5.22569 +-13.6679 5.80396 4.56927 -13.1117 6.35952 5.1355 +-13.9037 4.20127 5.04174 -13.3223 6.61042 5.46892 +-14.1355 6.14907 4.9313 -13.3685 6.91312 5.69888 +-13.9401 5.85635 4.95474 -13.3835 6.41045 5.51639 +-13.5818 4.2013 4.95149 -13.3285 7.0138 5.26827 +-13.8098 6.57753 4.76507 -13.042 7.34076 5.53447 +-13.7358 6.31757 4.89995 -13.179 6.8709 5.45614 +-72.9638 2.4267 89.644 -72.2018 3.2335 90.5286 +17.7817 -3.15846 -35.9432 18.1251 -2.92951 -35.5595 +-98.9519 4.88643 151.106 -98.0606 5.31169 152.044 +-64.0984 1.90515 157.201 -63.187 2.66721 158.064 +-32.7125 -0.550184 2.83058 -32.1877 -0.14939 3.34189 +-32.7181 -0.756669 2.82589 -32.1945 -0.344617 3.33701 +-32.6114 -0.689235 2.8473 -32.3663 -0.20363 3.094 +-32.6816 -0.687871 2.91006 -32.4365 -0.202266 3.15676 +-32.6098 -0.355582 2.92208 -32.3598 -0.105582 3.17208 +-118.855 0.1388 146.865 -118.414 0.921573 147.529 +45.2888 1.88195 66.7016 45.9797 2.57097 67.3926 +-64.1606 4.04997 157.795 -63.4151 4.46812 158.423 +-93.3765 1.08332 89.5368 -93.0425 1.41732 89.8708 +-42.2063 -1.8298 149.783 -41.7182 -1.14639 150.79 +-42.0058 -1.82709 149.01 -41.4937 -1.55109 150.099 +-41.7884 -1.82474 148.31 -41.2906 -1.13484 149.35 +-41.7212 -2.36 148.058 -41.0713 -1.06009 148.668 +-42.407 -2.36 150.421 -41.7571 -1.06009 151.031 +-169.101 1.7066 102.578 -167.912 3.41897 103.802 +-74.8256 -0.36095 163.219 -73.7279 0.491857 164.316 +-74.4018 0.189857 163.083 -73.5837 1.07952 163.922 +-74.0009 1.68569 103.348 -73.3826 2.16863 103.931 +-20.0946 -4.11 5.26835 -19.3893 -3.41144 5.80842 +-66.9136 1.91591 158.788 -66.0522 2.67797 159.698 +-71.9042 0.620587 166.057 -71.4743 0.960528 166.515 +-71.8536 0.621789 166.119 -71.5006 0.873965 166.494 +-71.7758 0.666556 166.144 -71.4732 0.960196 166.491 +-71.8734 0.614561 166.041 -71.5057 0.966541 166.398 +-32.9582 1.46615 59.6483 -32.3688 1.8843 60.3676 +-29.7556 -1.41182 148.478 -29.383 -0.912072 149.077 +-106.551 -0.414801 154.196 -105.682 -0.0432253 154.83 +-32.6876 -1.08052 0.0341356 -31.7398 -0.325424 0.948243 +-32.4103 -1.96717 -0.0123872 -31.9003 -0.714317 0.658421 +-74.8676 0.620473 163.574 -74.4359 0.960415 164.03 +-74.8138 0.621675 163.635 -74.459 0.873852 164.008 +-74.7455 0.666443 163.669 -74.4343 0.960083 164.016 +-74.8323 0.614447 163.56 -74.4613 0.966427 163.914 +-63.423 3.208 155.547 -62.6591 3.62614 156.211 +-0.969791 -4.45451 -41.4713 -0.63496 -4.15851 -41.0875 +-1.14815 -5.09705 -41.6269 -0.472774 -4.36028 -40.9313 +-163.674 1.4002 102.357 -162.464 3.11258 103.596 +-45.4743 -1.51663 150.456 -44.7341 -1.25372 150.856 +-45.5299 -1.92942 150.487 -45.1374 -1.28844 151.042 +-45.5028 -1.92469 150.224 -44.9682 -1.28796 150.665 +-114.859 3.13817 160.423 -114.406 3.9497 161.109 +-68.4525 2.56699 147.345 -67.7949 2.98514 148.106 +-51.6563 5.81504 85.2801 -51.3404 6.37918 85.596 +14.828 -4.06402 -39.7033 15.1839 -3.72913 -39.3274 +14.535 -4.06256 -39.9014 14.8925 -3.72671 -39.5256 +14.5619 -4.06986 -39.9131 15.1586 -3.81176 -39.316 +14.7123 -4.06386 -39.6167 15.0948 -3.72976 -39.2909 +14.5719 -4.06314 -39.6469 14.9491 -3.72735 -39.2909 +14.7714 -4.06371 -39.9384 15.1477 -3.73029 -39.5819 +14.535 -4.06246 -39.7608 14.8624 -3.72669 -39.3784 +14.6224 -4.06321 -39.9384 15.0057 -3.72795 -39.6119 +14.858 -4.06408 -39.8506 15.1835 -3.72934 -39.4681 +-80.4791 1.91512 154.734 -79.7181 2.33326 155.392 +3.22174 6.86481 79.4335 3.99189 7.73231 80.1681 +22.8766 -1.49201 -27.5957 23.3705 -0.740215 -27.1006 +-56.6703 0.782944 70.9909 -56.1331 1.18374 71.3604 +-56.6664 0.576459 70.9914 -56.1365 0.988511 71.3598 +-56.5729 0.643893 71.1628 -56.336 1.1295 71.4128 +-56.4788 0.645257 71.1664 -56.2419 1.13086 71.4165 +-56.5292 0.977545 71.105 -56.2792 1.22755 71.355 +-28.7801 -1.41182 145.117 -28.4074 -0.912072 145.716 +21.7165 -4.70229 10.7106 22.2615 -4.34091 11.2573 +-56.9987 0.573658 71.2215 -56.4538 0.932932 71.7034 +-57.0756 0.575645 71.0404 -56.4985 0.933046 71.5558 +-56.9589 0.514594 71.1778 -56.6212 0.764647 71.6418 +-56.8723 0.514701 71.1408 -56.5346 0.764754 71.6048 +-56.7836 0.574322 71.4626 -56.5336 0.824322 71.7126 +-141.584 1.76364 87.791 -140.774 2.10491 88.7252 +-71.1013 1.89976 146.57 -70.5025 2.3179 147.298 +-49.959 1.14522 91.0672 -49.5644 1.48462 91.4751 +-49.9801 1.14522 91.2314 -49.571 1.48462 91.6359 +-50.1438 1.14522 91.0564 -49.7347 1.48462 91.4608 +-50.1739 1.14522 91.2054 -49.7752 1.48462 91.6143 +-50.1895 1.13129 91.0511 -49.5367 1.38347 91.6427 +12.1012 -3.19669 -22.7506 12.4777 -2.95765 -22.4187 +-70.0368 3.49418 146.934 -69.112 3.96682 147.744 +54.5555 2.73129 71.2435 55.0355 3.58929 71.7235 +-63.9274 2.7465 157.139 -63.1999 3.28814 157.68 +-14.026 -1.17383 -71.0525 -13.5101 0.40801 -70.7636 +-14.1427 0.0197372 -71.2712 -13.5791 0.579796 -70.6896 +-14.0466 -0.240772 -71.2361 -13.5659 0.235263 -70.7432 +-13.7401 -1.17383 -71.2897 -13.291 0.292706 -70.8225 +-13.8287 -0.110325 -71.4514 -13.2181 0.4911 -70.8481 +-13.8009 -0.376354 -71.3377 -13.3241 0.0998503 -70.8609 +-13.8501 -1.1748 -71.0477 -13.5159 0.615732 -70.6369 +-14.0252 0.234352 -71.0579 -13.409 0.835643 -70.4547 +-13.9686 0.024347 -71.0187 -13.4821 0.501636 -70.5385 +-13.7401 -1.17383 -71.0525 -13.1723 0.3148 -70.6001 +-13.7794 -0.0238008 -71.0424 -13.1924 0.556636 -70.4603 +-13.6856 -0.219447 -71.0382 -13.1993 0.258273 -70.5616 +-13.7401 -1.17383 -71.0777 -13.167 0.687303 -70.8225 +-13.6795 0.317085 -71.271 -13.0654 0.919275 -70.6673 +-13.6785 0.0859019 -71.195 -13.1949 0.563005 -70.7164 +-13.8707 -1.17438 -71.2557 -13.5029 0.763207 -70.83 +-14.0757 0.35217 -71.4666 -13.4221 0.992894 -70.8243 +-13.9872 0.116285 -71.3412 -13.5029 0.592571 -70.8613 +-13.7401 -1.17383 -71.0525 -13.4738 1.06722 -70.7724 +-13.908 0.681715 -71.2064 -13.268 1.32171 -70.5664 +-13.8305 0.478836 -71.1316 -13.3545 0.954836 -70.6556 +-9.04228 2.93297 74.6422 -8.14369 3.53093 75.336 +-8.79069 2.92647 73.6953 -8.3293 3.4234 74.955 +45.7237 1.87752 66.6018 46.388 2.85399 67.2562 +-63.4633 2.10147 155.721 -62.715 2.51962 156.355 +-93.4555 1.04784 89.8132 -93.1215 1.38184 90.1472 +-79.8495 1.91512 152.54 -79.0885 2.33326 153.198 +-103.691 6.88741 151.299 -103.177 7.63441 151.959 +22.7401 -0.234127 -27.5615 23.4162 0.454891 -26.8856 +-66.3037 1.91591 147.916 -65.4423 2.67797 148.826 +-161.104 1.4002 92.6462 -159.941 3.11258 93.8242 +-47.869 1.04179 117.042 -47.4819 1.44371 117.461 +-47.8859 1.03892 117.043 -47.4935 1.45255 117.468 +-47.888 1.04179 117.027 -47.5009 1.44371 117.445 +-47.8607 1.04179 117.049 -47.4736 1.44371 117.468 +-47.5773 1.64494 116.694 -47.1902 2.04686 117.113 +-47.5942 1.64207 116.695 -47.2018 2.0557 117.12 +-47.5963 1.64494 116.679 -47.2092 2.04686 117.097 +-47.569 1.64494 116.701 -47.1819 2.04686 117.12 +-103.507 6.88741 151.354 -103.023 7.66927 152.05 +-62.5565 3.20049 152.492 -61.9887 3.74213 153.222 +7.30501 -3.87656 -30.5614 7.83549 -3.47485 -30.06 +7.31077 -4.08292 -30.5571 7.84135 -3.66867 -30.0559 +7.47872 -4.01522 -30.3155 7.72088 -3.52951 -30.0691 +7.55349 -4.01426 -30.3727 7.79565 -3.52855 -30.1264 +7.47845 -3.68123 -30.393 7.72845 -3.43123 -30.143 +-79.3708 2.56424 151.881 -78.9329 3.16785 152.312 +-72.4295 3.85939 146.215 -71.7736 4.27753 146.975 +-3.34362 -0.0789573 49.7811 -2.69529 0.897513 50.4255 +-165.576 1.71107 94.7852 -165.216 2.16018 95.145 +-66.3558 2.5585 148.05 -65.7361 3.18055 148.904 +-22.6566 -3.00428 -3.02379 -22.1207 -2.60132 -2.63833 +-22.6561 -3.2107 -3.02476 -22.1204 -2.7958 -2.63969 +-22.4473 -3.14189 -3.06544 -22.2109 -2.65634 -2.81447 +-22.541 -3.13969 -3.07468 -22.3046 -2.65414 -2.82371 +-22.5058 -2.80804 -3.00943 -22.2558 -2.55804 -2.75943 +-69.1996 3.85651 147.143 -68.5326 4.27466 147.909 +8.81917 -3.11091 -27.7031 9.25789 -2.65435 -27.2347 +8.84191 -3.09669 -28.3209 9.22878 -2.63544 -27.9539 +8.25106 -3.17937 -28.4354 9.28999 -2.85526 -27.1728 +8.31225 -3.09996 -27.6593 8.69095 -2.56595 -27.2705 +8.31428 -3.0944 -28.3447 8.70696 -2.65146 -27.9506 +-80.4829 3.86703 154.668 -79.7171 4.28517 155.456 +-85.0763 0.145278 105 -84.6235 0.956802 105.687 +-67.6366 1.87667 63.2319 -66.9881 2.26366 63.9429 +-33.0467 1.00806 60.7023 -32.3558 1.5497 61.1205 +14.8 -3.18657 -29.5714 15.2939 -2.43477 -29.0762 +-119.757 0.888795 146.635 -119.261 1.69407 147.351 +-23.0239 -3.001 -3.06045 -22.488 -2.59804 -2.67499 +-23.0234 -3.20742 -3.06143 -22.4877 -2.79253 -2.67636 +-22.8146 -3.13861 -3.1021 -22.5782 -2.65306 -2.85113 +-22.9083 -3.13641 -3.11134 -22.6719 -2.65086 -2.86037 +-22.8731 -2.80476 -3.04609 -22.6231 -2.55476 -2.79609 +-32.7261 -0.550184 4.04966 -32.2451 -0.14939 4.58578 +-32.7294 -0.756669 4.05558 -32.2499 -0.344617 4.59239 +-32.7315 -0.689235 4.21011 -32.4832 -0.20363 4.45286 +-32.6843 -0.687871 4.2916 -32.436 -0.202266 4.53436 +-32.6567 -0.355582 4.21811 -32.4067 -0.105582 4.46811 +-20.8399 0.839629 62.5596 -20.1446 1.16091 63.2267 +-48.6204 0.926543 117.005 -48.1811 1.53015 117.43 +15.3403 -3.17792 -28.1186 15.7213 -2.84303 -27.7887 +15.448 -3.17647 -28.44 15.8288 -2.84061 -28.1087 +15.2854 -3.18376 -28.413 15.8847 -2.92566 -27.8142 +15.2594 -3.17776 -28.207 15.6136 -2.84366 -27.8344 +15.2597 -3.17704 -28.3593 15.5903 -2.84125 -27.9787 +15.5797 -3.17761 -28.2517 15.9098 -2.84419 -27.8688 +15.3039 -3.17636 -28.4404 15.6783 -2.84059 -28.085 +15.5561 -3.17711 -28.396 15.9102 -2.84185 -28.0202 +15.4916 -3.17798 -28.1422 15.8656 -2.84324 -27.7888 +-107.249 -0.403347 154.101 -106.28 -0.0327467 155.069 +-117.068 2.38653 159.818 -116.615 3.19805 160.504 +-73.4366 0.915548 85.5742 -72.3624 1.72753 86.4542 +-79.5123 3.21535 151.248 -78.7512 3.6335 151.905 +-62.5667 2.55964 152.368 -61.7785 2.97779 153.133 +-79.55 1.91512 151.513 -78.8924 2.33326 152.274 +-29.2679 1.58818 146.798 -28.8952 2.08793 147.397 +53.9483 2.73094 66.9104 54.4283 3.58894 67.3904 +-9.72118 3.55881 74.6391 -8.98955 4.07603 75.5852 +-106.311 -0.423724 151.298 -105.796 -0.0521481 152.174 +-109.983 -0.599745 149.34 -109.498 0.182118 150.036 +-63.406 3.40171 155.532 -62.6577 3.81986 156.166 +-52.8398 0.633143 90.0933 -52.4414 0.972538 90.4901 +-52.9706 0.633143 89.971 -52.5722 0.972538 90.3677 +-53.0431 0.619209 89.9328 -52.3865 0.871389 90.5801 +-83.1219 -0.604885 105.614 -82.6085 0.142122 106.274 +-123.063 2.89263 87.6846 -122.464 3.39238 88.0572 +-64.6464 1.9 158.859 -63.6329 2.65279 159.509 +28.084 1.891 84.2809 29.1786 2.70299 85.0848 +-27.5347 0.189996 16.8415 -26.6218 0.715483 17.4291 +14.1041 -4.08597 -22.0723 14.596 -3.33417 -21.5796 +14.2496 -3.04197 -12.2525 15.1256 -2.68713 -11.2511 +22.0723 -4.51389 10.8279 22.5358 -4.07177 11.3593 +21.9891 -4.69505 10.8184 22.4798 -4.22378 11.3663 +22.195 -4.6452 11.0489 22.5279 -4.17875 11.2893 +22.2198 -4.65224 10.9583 22.5526 -4.18579 11.1987 +22.2914 -4.32152 10.9892 22.5414 -4.07152 11.2392 +8.56413 -3.22965 -28.9192 9.04414 -2.37165 -28.4392 +49.7079 2.79553 67.0433 50.0782 3.13041 67.412 +49.9586 2.79698 66.7901 50.3294 3.13284 67.1604 +49.7319 2.78968 66.8153 50.3052 3.04779 67.3884 +49.7089 2.79569 66.9067 50.0059 3.12978 67.2936 +49.7087 2.79641 66.7898 50.0771 3.13219 67.1617 +49.9597 2.79583 67.042 50.3293 3.12925 67.4129 +49.8256 2.79708 66.7903 50.2124 3.13286 67.0892 +50.0306 2.79634 66.9069 50.3289 3.13159 67.2946 +49.825 2.79546 67.1144 50.2117 3.1302 67.4114 +-106.326 -1.36725 155.31 -105.449 -0.941979 156.086 +-8.6243 3.74673 73.6201 -8.1564 4.14753 74.1571 +-8.62701 3.54025 73.6242 -8.16055 3.9523 74.164 +-8.63739 3.60768 73.7726 -8.38861 4.09329 74.0144 +-8.59612 3.60905 73.8572 -8.34734 4.09465 74.0991 +-8.56337 3.94133 73.7855 -8.31337 4.19133 74.0355 +-63.4803 1.90776 155.736 -62.7164 2.32591 156.4 +-73.3159 1.20369 85.0024 -72.4152 1.96575 85.8521 +-71.5278 -0.36095 166.492 -70.4584 0.491857 167.566 +-71.2144 0.189857 166.974 -70.3552 1.07952 167.737 +-54.9736 0.782944 70.5581 -54.4367 1.18374 71.0307 +-54.9684 0.576459 70.5624 -54.4299 0.988511 71.0336 +-54.8182 0.643893 70.7925 -54.576 1.1295 71.0411 +-54.7346 0.645257 70.7491 -54.4924 1.13086 70.9977 +-54.807 0.977545 70.7168 -54.557 1.22755 70.9668 +-39.5272 1.62925 55.0506 -39.2122 2.19338 55.3655 +-49.5095 1.14522 91.1391 -49.1207 1.48462 91.5448 +-49.5451 1.14522 91.3037 -49.1358 1.48462 91.7046 +-49.6957 1.14522 91.1174 -49.2864 1.48462 91.5182 +-49.7343 1.14522 91.2611 -49.3405 1.48462 91.6688 +-49.7587 1.13129 91.1021 -49.0855 1.38347 91.7195 +-59.2101 -0.251772 71.1434 -57.8624 0.136785 72.4066 +-62.7902 3.83492 152.434 -61.8715 4.49717 153.103 +19.4859 -4.1 -27.8419 20.4117 -3.40776 -26.8326 +-64.0573 3.3983 157.784 -63.4727 3.81645 158.503 +-102.056 1.48336 88.7177 -101.646 1.74627 89.4548 +-102.234 1.07057 88.6615 -101.676 1.71155 89.0475 +-101.854 1.07531 88.6903 -101.42 1.71203 89.2288 +-136.105 5.86291 85.9818 -135.506 6.36266 86.3544 +-106.441 -1.36165 151.495 -105.647 -1.02038 152.419 +-71.0614 2.75546 71.6157 -70.5713 3.15625 72.1483 +-71.0653 2.54898 71.6095 -70.5785 2.96103 72.1447 +-71.0094 2.61641 71.6601 -70.7618 3.10201 71.9039 +-71.0602 2.61777 71.7394 -70.8125 3.10338 71.9832 +-70.9862 2.95006 71.7295 -70.7362 3.20006 71.9795 +-55.2305 -0.358224 69.4038 -54.3808 0.403837 70.3046 +-9.92473 2.95108 74.8352 -8.96151 3.4683 75.593 +-43.1887 0.647872 55.1635 -42.2319 1.50068 56.1102 +-42.6489 1.19868 55.127 -42.0293 2.08835 55.9633 +-47.3587 -0.316696 85.4798 -46.3871 0.53611 86.4418 +-47.5624 0.23411 85.4498 -46.9272 1.12378 86.2914 +-13.1224 2.92723 57.3992 -12.6341 3.67902 57.8865 +-68.3506 3.20784 158.265 -67.8109 3.74949 158.992 +24.082 -1.98935 33.9031 24.8342 -1.47213 34.8627 +-67.4659 3.2137 158.608 -66.4838 3.97576 159.589 +-32.0162 -2.1328 -1.08709 -31.3735 -1.44986 -0.192338 +-32.0635 -1.76129 -0.845613 -31.5107 -0.501779 -0.423498 +-47.9427 1.84103 116.971 -47.5556 2.24295 117.389 +-47.9596 1.83816 116.971 -47.5672 2.25179 117.396 +-47.9617 1.84103 116.955 -47.5746 2.24295 117.373 +-47.9344 1.84103 116.978 -47.5473 2.24295 117.396 +-110.143 -0.599745 149.293 -109.659 0.182118 149.989 +-58.8841 0.782944 71.6576 -58.3504 1.18374 72.0946 +-58.8861 0.576459 71.6604 -58.343 0.988511 72.0961 +-58.7506 0.643893 71.874 -58.5107 1.1295 72.1235 +-58.6608 0.645257 71.8455 -58.4209 1.13086 72.095 +-58.728 0.977545 71.8024 -58.478 1.22755 72.0524 +-49.2871 0.745251 67.596 -48.6533 1.22819 68.2572 +-33.035 2.31154 62.002 -32.3225 2.72969 62.5806 +-2.83444 7.30938 95.7142 -2.28938 9.18139 96.1221 +-2.78916 8.75862 95.6111 -2.14892 9.39498 96.2482 +-2.74274 8.42897 95.6027 -2.20878 8.96293 96.1366 +-3.0014 7.30938 95.8858 -2.59814 9.04187 96.4753 +-3.13061 8.59879 95.9158 -2.42924 9.28562 96.6121 +-3.11134 8.26375 95.9636 -2.57687 8.79778 96.4976 +-2.93376 7.30897 95.6124 -2.59391 9.42692 96.1176 +-3.13796 9.00749 95.3788 -2.44902 9.69154 96.0645 +-3.05009 8.75735 95.5006 -2.51201 9.29135 96.036 +-3.30499 7.30938 95.7515 -2.59814 9.0686 96.1221 +-3.41437 8.67469 95.5055 -2.74973 9.33543 96.167 +-3.2807 8.45578 95.6156 -2.73193 8.99227 96.1582 +-3.2213 7.30938 95.8858 -2.59814 9.51933 96.2755 +-3.46474 9.09504 95.7553 -2.77505 9.78027 96.4412 +-3.31742 8.81473 95.8115 -2.77878 9.3497 96.347 +-2.81858 7.30787 95.8836 -2.36588 9.61367 96.2832 +-2.99599 9.16879 95.7939 -2.2576 9.90128 96.5283 +-2.90914 8.8817 95.8638 -2.37104 9.41573 96.3992 +-2.99972 7.31009 95.8199 -2.59128 9.97417 96.1304 +-3.3446 9.54171 95.6027 -2.61072 10.2743 96.3354 +-3.14134 9.30373 95.6848 -2.60136 9.83807 96.2209 +-68.7173 2.56699 158.311 -68.0597 2.98514 159.072 +-46.0838 0.659083 86.2088 -45.6539 1.22588 86.6284 +15.4359 -4.17696 -14.3012 15.7929 -3.72785 -13.9442 +-80.2078 2.76362 154.424 -79.4779 3.30526 154.987 +22.7817 -0.11 26.3749 23.8833 0.701983 27.0731 +-103.76 6.14411 151.281 -103.307 6.95563 151.967 +-98.4246 4.63835 147.472 -97.4789 4.97962 148.488 +19.1926 -4.1 -36.1653 20.1515 -3.40776 -35.3019 +24.2061 -2.01545 35.7825 24.7963 -1.07476 36.5518 +24.3036 -2.00275 36.1851 24.7669 -1.37661 37.4427 +-66.7074 1.91512 147.854 -66.0498 2.33326 148.615 +-141.401 4.89716 139.976 -140.802 5.39691 140.349 +-105.769 -1.21636 151.701 -105.004 -0.841744 152.569 +-13.7401 -1.17383 -59.2992 -13.3536 0.408012 -58.8227 +-13.8649 0.0181649 -59.2244 -13.2837 0.579206 -58.663 +-13.7407 -0.248537 -59.2302 -13.2647 0.227463 -58.7542 +-14.0396 -1.17383 -59.4199 -13.5101 0.292708 -59.0692 +-14.1326 -0.104817 -59.5057 -13.5301 0.495698 -58.8972 +-14.0867 -0.39168 -59.5114 -13.6107 0.0843202 -59.0354 +-13.7401 -1.17383 -59.3644 -13.3452 0.619149 -59.0692 +-13.6823 0.228054 -59.45 -13.0775 0.829102 -58.8377 +-13.6564 0.020877 -59.3842 -13.1776 0.497643 -58.8995 +-13.7401 -1.17383 -59.6939 -13.422 0.314801 -59.0692 +-13.78 -0.0251419 -59.6742 -13.1993 0.555913 -59.0866 +-13.7803 -0.222514 -59.6546 -13.2994 0.255096 -59.1694 +-13.8853 -1.17383 -59.611 -13.5101 0.687305 -59.0692 +-14.0037 0.320772 -59.7078 -13.4012 0.922109 -59.0985 +-13.9235 0.0882203 -59.5871 -13.4468 0.564875 -59.1058 +-13.8454 -1.1744 -59.3016 -13.5228 0.763842 -58.8579 +-14.0783 0.356329 -59.3472 -13.4278 0.997164 -58.6904 +-14.0473 0.116074 -59.3318 -13.5713 0.592075 -58.8558 +-13.7401 -1.17383 -59.3509 -13.4761 1.06722 -59.0692 +-13.9104 0.681717 -59.5569 -13.2704 1.32172 -58.9169 +-13.8336 0.478838 -59.4682 -13.3576 0.954838 -58.9922 +-115.593 3.13817 160.262 -115.108 3.92004 160.957 +-78.6042 -0.36095 162.264 -77.5433 0.491857 163.319 +-78.7822 0.189857 162.551 -78.039 1.07952 163.412 +23.1294 -1.49201 -32.1254 23.6234 -0.740215 -31.6303 +-66.0803 2.56135 148.184 -65.5406 3.10299 148.912 +-6.69857 1.19269 97.368 -6.30437 1.89822 97.9366 +24.2788 -2.7389 34.0552 24.8588 -1.9019 34.5963 +-99.5937 4.85377 151.23 -98.7235 5.24846 152.209 +-22.7554 -3.22203 -2.82389 -22.1289 -2.83504 -2.12892 +-79.9304 2.56699 152.455 -79.0081 3.03468 153.283 +-33.0253 2.11783 61.99 -32.3343 2.53597 62.5316 +-143.322 1.89978 139.419 -142.723 2.39953 139.791 +-29.7556 3.08818 148.478 -29.383 3.58793 149.077 +26.5307 -0.095394 37.6563 27.0107 0.762606 38.1363 +-97.7002 0.665364 94.3924 -96.6113 1.47735 94.9803 +-58.2203 -0.0856447 70.8183 -56.8962 0.302912 72.0436 +-62.8036 3.82747 132.302 -62.4565 5.39563 132.874 +-63.0079 5.02095 132.243 -62.4477 5.58125 132.805 +-62.8607 4.73983 132.254 -62.3603 5.21816 132.733 +-62.7931 3.82806 132.653 -62.4779 5.32444 133.036 +-62.8997 4.90644 132.58 -62.2956 5.50662 133.185 +-62.8505 4.63261 132.64 -62.3728 5.10879 133.118 +-63.1257 3.8281 132.512 -62.5654 5.59091 132.875 +-63.312 5.20924 132.319 -62.7091 5.80947 132.923 +-63.1584 5.00897 132.361 -62.6771 5.4853 132.842 +-63.1165 3.8285 132.65 -62.5655 5.31191 133.151 +-63.2638 4.96305 132.567 -62.6788 5.54451 133.152 +-63.1519 4.78033 132.595 -62.671 5.25764 133.075 +-62.8864 3.8285 132.65 -62.5655 5.69312 133.194 +-63.1392 5.31668 132.687 -62.5335 5.91811 133.294 +-63.0463 5.08362 132.706 -62.5659 5.56066 133.186 +-62.7911 3.82666 132.421 -62.2988 5.75094 132.871 +-62.9479 5.36699 132.33 -62.304 6.00744 132.976 +-62.8102 5.11933 132.366 -62.3254 5.59682 132.849 +-62.9865 3.82849 132.636 -62.5664 6.06209 132.89 +-63.2302 5.67191 132.474 -62.5863 6.31242 133.12 +-63.1274 5.4689 132.58 -62.6512 5.9449 133.057 +-51.049 1.62106 57.2166 -50.5822 2.18786 57.6767 +-98.877 4.76104 151.073 -97.903 5.10231 152.1 +-106.727 -0.414801 153.949 -105.861 -0.0432253 154.391 +-72.9031 0.71153 89.2201 -72.1454 1.58353 90.0243 +-23.2891 -2.68456 5.46415 -22.9468 -2.36116 5.82439 +-23.5528 -2.68325 5.28585 -23.2091 -2.35898 5.64609 +-23.5286 -2.68982 5.27534 -22.9696 -2.43553 5.83467 +-23.3933 -2.68442 5.54209 -23.027 -2.36173 5.85728 +-23.5196 -2.68377 5.51486 -23.1581 -2.35956 5.85728 +-23.34 -2.68429 5.25248 -22.9794 -2.36221 5.59534 +-23.5529 -2.68316 5.41234 -23.2361 -2.35896 5.77853 +-23.4742 -2.68383 5.25255 -23.1072 -2.3601 5.56838 +-23.2621 -2.68462 5.33153 -22.9472 -2.36135 5.69775 +-27.6877 -4.11 0.466878 -26.6373 -3.41776 1.43988 +-29.2679 0.0881764 146.798 -28.8952 0.587928 147.397 +-13.8135 1.86468 57.6961 -13.04 2.73218 58.4183 +-48.2986 5.80945 85.7544 -47.8616 6.37624 86.1823 +-21.6796 -3.0755 4.78966 -20.9505 -2.26195 5.45057 +-53.083 2.0428 92.8484 -52.5065 2.8798 93.456 +24.1009 -0.115011 29.3354 24.5561 0.261286 29.8232 +17.3716 -4.975 -39.7131 18.3491 -4.28275 -38.6593 +-72.8821 2.42672 88.6618 -72.1438 3.23352 89.5481 +-110.298 -0.599745 149.248 -109.813 0.182118 149.944 +-68.4437 3.86703 147.476 -67.6599 4.28517 148.189 +-98.2277 4.88643 147.479 -97.3616 5.31169 148.408 +-131.85 2.58337 91.4266 -131.155 2.95456 92.2771 +-51.5663 2.4529 90.9261 -50.9905 3.2899 91.4619 +-31.7354 -1.70478 11.9872 -31.3767 -1.25567 12.3459 +-71.157 2.09347 146.516 -70.5078 2.56115 147.343 +-143.322 3.37006 139.419 -142.723 3.86981 139.791 +-24.0279 -2.77789 5.24494 -23.534 -2.0261 5.74012 +-71.5104 1.89976 146.45 -70.8583 2.3179 147.208 +-72.7308 1.90748 146.12 -71.7544 2.39993 147.119 +-49.71 2.4529 91.1807 -49.1342 3.2899 91.7166 +25.3409 -4.12553 32.1028 25.9845 -3.14906 32.74 +-123.063 5.86291 87.6846 -122.464 6.36266 88.0572 +-32.4848 -2.11545 -0.160075 -31.6389 -1.14002 0.685816 +-62.6611 1.90856 152.443 -61.7456 2.67062 153.311 +-22.4048 -3.23424 -2.54288 -21.7778 -2.76239 -1.86043 +-52.8285 0.883025 91.5371 -52.3376 1.44982 92.0274 +-70.9392 3.19999 146.603 -70.2871 3.61814 147.362 +-108.656 0.150417 149.86 -108.203 0.961942 150.547 +-48.4438 5.81504 85.7873 -48.1293 6.37918 86.1019 +46.944 4.45573 65.9135 47.4307 5.20753 66.3985 +-84.8139 0.145278 105.077 -84.361 0.956802 105.763 +-8.9345 4.99019 72.594 -8.50401 6.81465 72.9307 +-8.96192 6.3866 72.5146 -8.3407 7.00448 73.1339 +-8.92024 6.0792 72.5245 -8.39634 6.59977 73.0464 +-9.2939 4.99165 72.5952 -8.7121 6.65364 73.0311 +-9.39957 6.22381 72.5325 -8.71285 6.89194 73.2019 +-9.25056 5.91636 72.5743 -8.71114 6.43969 73.0983 +-8.94303 4.99105 72.3158 -8.59978 7.02771 72.8277 +-9.10468 6.61736 72.0986 -8.41036 7.28293 72.765 +-9.01752 6.37668 72.2173 -8.47312 6.89811 72.7378 +-9.33526 4.99165 72.2469 -8.7121 6.66848 72.83 +-9.34375 6.30372 72.0672 -8.67626 6.94681 72.7121 +-9.32151 6.08016 72.1956 -8.78244 6.60343 72.7172 +-9.40684 4.99165 72.521 -8.7121 7.10318 72.83 +-9.54001 6.70732 72.3305 -8.86983 7.37244 72.9975 +-9.38968 6.43792 72.3576 -8.84668 6.96188 72.8831 +-8.93423 4.99045 72.601 -8.58633 7.21551 72.9997 +-9.16241 6.76863 72.5826 -8.44503 7.47932 73.2964 +-9.06656 6.49718 72.6042 -8.51806 7.01757 73.1331 +-9.15809 4.99157 72.554 -8.71636 7.55078 72.8434 +-9.41074 7.13423 72.3201 -8.69789 7.84485 73.0314 +-9.28727 6.90004 72.423 -8.76549 7.42034 72.9438 +-64.1046 3.20459 157.768 -63.486 3.62274 158.508 +-28.7592 -2.87112 0.461476 -27.7373 -2.48256 1.65307 +-168.138 1.7066 100.514 -167.007 3.41897 101.691 +-88.5974 1.16742 148.901 -88.3574 1.63742 149.141 +-88.6379 1.56699 148.861 -88.317 1.96508 149.182 +-88.7974 0.935791 148.701 -88.1574 1.42301 149.341 +-88.8043 1.62078 148.881 -88.5225 1.97769 149.162 +-88.6171 1.62215 148.695 -88.3383 1.97088 148.975 +-88.6156 1.75848 148.883 -88.3393 2.11848 149.159 +-88.618 1.62599 149.067 -88.337 1.91533 149.348 +-88.4307 1.62353 148.881 -88.1472 1.93728 149.161 +-88.8248 1.40817 148.674 -88.1301 1.78184 149.369 +-88.82 1.56141 148.865 -88.5064 1.83307 149.178 +-88.6339 1.56141 148.679 -88.321 1.83307 148.992 +-88.6339 1.56141 149.05 -88.321 1.83307 149.364 +-88.4484 1.56141 148.865 -88.1349 1.83307 149.178 +-106.336 -0.984914 155.229 -105.34 -0.64905 156.194 +-103.35 6.14411 151.4 -102.897 6.95563 152.086 +-36.4073 -1.51663 153.088 -35.6671 -1.25372 153.487 +-36.4629 -1.92942 153.119 -36.0704 -1.28844 153.674 +-36.4358 -1.92469 152.856 -35.9012 -1.28796 153.297 +-141.516 1.64095 87.7676 -140.707 1.98222 88.7018 +23.9146 -0.11 29.8236 25.0178 0.701983 30.5345 +-53.9153 -0.258633 70.2488 -52.8483 0.55335 70.7393 +-115.579 3.88995 160.314 -115.126 4.70148 161.001 +22.7634 -0.1 41.2873 23.8451 0.711983 42.1573 +-13.7401 -1.17383 -83.0525 -13.3536 0.40801 -82.576 +-13.8626 0.018375 -82.9793 -13.2814 0.579429 -82.418 +-13.7407 -0.248539 -82.9835 -13.2647 0.227461 -82.5075 +-14.0395 -1.17383 -83.1732 -13.5101 0.292706 -82.8225 +-14.1293 -0.104183 -83.2518 -13.528 0.496087 -82.645 +-14.0866 -0.391682 -83.2647 -13.6106 0.0843182 -82.7887 +-13.7401 -1.17383 -83.1177 -13.3452 0.619147 -82.8225 +-13.6809 0.227921 -83.2053 -13.0761 0.828927 -82.5929 +-13.6525 0.0201915 -83.1301 -13.1747 0.496772 -82.6468 +-13.7401 -1.17383 -83.4472 -13.422 0.3148 -82.8225 +-13.7793 -0.0253902 -83.4286 -13.1987 0.555719 -82.8407 +-13.7795 -0.222863 -83.4091 -13.2986 0.254742 -82.924 +-13.8853 -1.17383 -83.3643 -13.5101 0.687303 -82.8225 +-14.0025 0.320488 -83.4636 -13.4001 0.92186 -82.8541 +-13.9228 0.0880708 -83.3419 -13.4462 0.564751 -82.8604 +-13.8426 -1.17437 -83.0548 -13.5231 0.763243 -82.6056 +-14.0771 0.356597 -83.1024 -13.4266 0.997431 -82.4455 +-14.0473 0.116073 -83.0851 -13.5713 0.592073 -82.6091 +-13.7401 -1.17383 -83.1041 -13.4761 1.06722 -82.8225 +-13.9104 0.681715 -83.3102 -13.2704 1.32171 -82.6702 +-13.8335 0.478836 -83.2215 -13.3575 0.954836 -82.7455 +-68.2821 1.64212 157.856 -67.4005 2.40418 158.682 +-141.4 12.491 104.755 -141.04 12.891 105.115 +-142.669 6.83441 103.48 -139.775 9.53026 106.392 +-52.2856 0.876814 90.7654 -51.8576 1.21676 91.214 +-52.2306 0.878016 90.8257 -51.8757 1.13019 91.1953 +-52.1752 0.922784 90.8699 -51.8553 1.21642 91.2129 +-52.2465 0.870788 90.7565 -51.8745 1.22277 91.1085 +-105.365 5.39395 150.813 -104.851 6.14095 151.473 +20.6525 -3.13223 -25.4256 21.2546 -2.55485 -24.9159 +-62.5889 2.03809 130.569 -62.2905 2.44 131.035 +-62.5783 2.03521 130.556 -62.2775 2.44884 131.031 +-62.5652 2.03809 130.576 -62.2668 2.44 131.043 +-62.5992 2.03809 130.566 -62.3009 2.44 131.032 +-24.6636 -3.18885 -3.73863 -23.4516 -2.80029 -2.67671 +-49.5354 0.765851 118.231 -49.1041 1.36946 118.655 +-84.666 0.145278 105.12 -84.2132 0.956802 105.806 +-48.3673 1.721 116.428 -47.9403 2.12179 116.959 +-48.3639 1.51452 116.425 -47.9388 1.92657 116.967 +-48.181 1.58195 116.649 -47.9315 2.06755 116.889 +-48.1567 1.58331 116.558 -47.9072 2.06892 116.798 +-48.2265 1.9156 116.582 -47.9765 2.1656 116.832 +18.2568 -3.18395 -35.0377 18.6165 -2.73485 -34.678 +11.1135 -3.13387 -35.6056 11.546 -2.67731 -35.1393 +11.0829 -3.11965 -36.2225 11.469 -2.6584 -35.85 +10.4929 -3.20233 -36.334 11.5799 -2.87822 -35.0346 +10.6001 -3.12292 -35.5238 10.9864 -2.58891 -35.1287 +10.5601 -3.11736 -36.2003 10.9437 -2.67442 -35.8151 +-72.0847 1.76798 72.1812 -71.2945 2.57478 73.0601 +-54.1385 0.6999 84.294 -53.4419 1.18284 84.9858 +55.0187 1.86947 68.2309 55.7708 2.36464 68.8877 +-50.6242 4.60829 85.8596 -49.8603 5.53053 86.6245 +-46.7806 4.60829 86.3742 -45.9203 5.53053 87.2353 +-52.6022 1.4681 94.1831 -52.0959 1.8689 94.7111 +-52.5971 1.26162 94.1773 -52.0915 1.67367 94.7044 +-52.3554 1.32905 94.2908 -52.1083 1.81466 94.5355 +-52.4153 1.33042 94.2181 -52.1682 1.81602 94.4628 +-52.4334 1.6627 94.2891 -52.1834 1.9127 94.5391 +-80.4796 3.40906 154.779 -79.7349 3.82721 155.406 +-95.6997 1.06675 88.9681 -95.3657 1.40075 89.3021 +4.83292 9.39586 79.3958 5.19794 11.337 79.9787 +4.6986 10.8871 79.1676 5.37745 11.5432 79.8356 +4.80293 10.5586 79.2855 5.37103 11.1075 79.8375 +4.96014 9.39586 79.7409 5.53474 11.1917 80.2069 +5.01206 10.7376 79.5126 5.7228 11.4429 80.2204 +5.0605 10.3903 79.6457 5.60921 10.9393 80.2098 +4.75158 9.39539 79.6299 5.19655 11.6033 79.9736 +4.47103 11.1617 79.3144 5.18495 11.8677 80.0264 +4.62768 10.9127 79.5115 5.18151 11.461 80.0823 +4.77085 9.39509 79.7491 5.19808 11.2816 80.1388 +4.57911 10.8409 79.7709 5.26148 11.5234 80.471 +4.67556 10.6105 79.7619 5.22559 11.1602 80.3253 +4.96014 9.39586 79.7409 5.29402 11.6889 80.4013 +4.83184 11.2862 79.7137 5.54232 11.9915 80.4275 +4.89838 10.9782 79.8261 5.44905 11.5286 80.3933 +4.9671 9.39384 79.4601 5.45319 11.7736 79.9712 +4.95826 11.3069 79.1998 5.71925 12.0628 79.972 +5.02734 11.0177 79.4138 5.58254 11.5666 79.9848 +4.90457 9.39586 79.7409 5.19794 12.1675 80.0333 +4.69773 11.7346 79.4315 5.46225 12.4891 80.1947 +4.78302 11.4785 79.5314 5.34036 12.0264 80.0829 +22.9131 6.57109 63.3077 23.237 6.87073 63.6954 +22.7262 5.91927 63.1579 23.4014 6.67766 63.8535 +-52.7467 1.75239 91.3676 -52.108 2.58939 92.0104 +-29.7556 1.58818 148.478 -29.383 2.08793 149.077 +21.9923 -4.10251 -22.4305 22.6359 -3.12604 -21.7932 +1.99693 -4.25663 -47.7303 2.75692 -3.99373 -47.4703 +2.33221 -4.66942 -48.022 2.80176 -4.02844 -47.5152 +2.32518 -4.66469 -47.689 2.79863 -4.02797 -47.1789 +19.5445 -4.1 -32.6258 20.6405 -3.28802 -31.8309 +-28.5509 -2.99751 -3.15523 -27.7764 -2.13 -2.43902 +49.8117 2.78348 79.3581 50.1715 3.23259 79.7179 +-3.79482 1.61149 -17.0799 -3.40834 3.53539 -16.5564 +-4.07317 3.06134 -16.9178 -3.42394 3.70882 -16.2684 +-3.91899 2.76341 -17.0088 -3.37099 3.30738 -16.4601 +-3.93425 1.61393 -17.4382 -3.40477 3.36978 -16.8552 +-4.20323 2.92133 -17.4383 -3.50416 3.61774 -16.7392 +-4.01092 2.59246 -17.4036 -3.46337 3.13493 -16.8558 +-3.63552 1.61354 -17.0919 -3.29009 3.78695 -16.64 +-3.73416 3.36287 -17.1372 -3.03163 4.05907 -16.4341 +-3.70677 3.10388 -17.0616 -3.16038 3.64637 -16.5151 +-3.64197 1.61393 -17.4823 -3.11135 3.41608 -16.8552 +-3.6313 3.03768 -17.4988 -2.95171 3.71103 -16.8189 +-3.64517 2.81468 -17.3609 -3.09901 3.3577 -16.8145 +-3.66479 1.61393 -17.5511 -3.40477 3.86652 -16.8552 +-3.93852 3.47034 -17.5855 -3.23613 4.16695 -16.883 +-3.87778 3.18051 -17.4327 -3.33208 3.72297 -16.8869 +-4.0476 1.6141 -17.0808 -3.39852 3.93959 -16.6464 +-4.225 3.49921 -17.2399 -3.47126 4.24655 -16.4847 +-4.10883 3.19729 -17.1001 -3.56217 3.74072 -16.5532 +-3.6761 1.61538 -17.2183 -3.29954 4.34211 -16.8659 +-3.9325 3.91558 -17.3844 -3.17856 4.66119 -16.6296 +-3.82742 3.66391 -17.2779 -3.27801 4.20614 -16.7277 +-70.9392 2.55163 146.603 -70.2871 2.96978 147.362 +20.8486 -3.5529 31.1091 21.1265 -2.86949 32.1459 +20.8504 -3.55019 30.3036 21.1285 -3.27419 31.4266 +20.8523 -3.54784 29.5748 21.1303 -2.85794 30.6466 +20.6881 -4.0831 29.3164 21.303 -2.78318 29.9517 +20.682 -4.0831 31.7768 21.2969 -2.78318 32.4121 +-72.3502 3.20751 146.145 -71.6925 3.9603 147.159 +-37.4194 2.89709 78.7505 -36.9892 4.47893 79.193 +-37.4844 4.10099 78.6607 -36.9209 4.66146 79.2229 +-37.3866 3.82238 78.6739 -36.9106 4.29838 79.1499 +-37.4623 2.89709 78.963 -37.1894 4.36362 79.513 +-37.6691 3.96557 78.9765 -37.0642 4.56628 79.5794 +-37.5941 3.69318 79.0117 -37.1149 4.16974 79.4897 +-37.5545 2.8969 78.6929 -37.1865 4.67163 79.1906 +-37.7543 4.29012 78.5116 -37.1469 4.89015 79.1154 +-37.6473 4.08516 78.6072 -37.1629 4.56121 79.0872 +-37.7482 2.89484 78.8804 -37.1984 4.40692 79.1925 +-37.91 4.02701 78.6951 -37.3215 4.60879 79.2788 +-37.7816 3.84982 78.8027 -37.2926 4.32826 79.2918 +-37.6856 2.89709 78.963 -37.1894 4.75822 79.4107 +-37.9064 4.37718 78.8897 -37.2989 4.97881 79.4938 +-37.7915 4.14461 78.9304 -37.3093 4.62195 79.4097 +-37.4092 2.89579 78.9566 -36.9255 4.83249 79.2173 +-37.5705 4.43854 78.808 -36.9253 5.0786 79.4514 +-37.4685 4.19947 78.8623 -36.9866 4.67573 79.3416 +-37.6804 2.89845 78.9366 -37.1794 5.12251 79.195 +-37.8919 4.73606 78.731 -37.2473 5.37661 79.3741 +-37.7022 4.54235 78.7743 -37.2177 5.01895 79.2545 +-63.2297 2.75335 154.751 -62.4814 3.1715 155.385 +-73.5622 1.63484 162.627 -73.2463 2.19897 162.943 +-51.5122 1.75624 90.8596 -51.0697 2.09618 91.2715 +-51.4998 1.75744 90.9004 -51.1276 2.00962 91.2655 +-51.4535 1.80221 90.9691 -51.1122 2.09585 91.2738 +-51.4475 1.75021 90.863 -51.0715 2.10219 91.2054 +22.7946 -1.49201 -31.9458 23.2885 -0.740215 -31.4506 +-32.8375 1.45864 60.3233 -32.3932 2.00028 61.0246 +-89.183 0.864804 148.754 -88.5956 1.18571 150.35 +-63.9936 3.19708 157.249 -63.4306 3.73872 157.979 +-120.01 -0.611204 146.505 -119.526 0.170659 147.201 +17.1912 -4.10961 -36.7773 17.7078 -3.01867 -36.2125 +7.35399 1.91947 80.8459 7.99762 2.89595 81.4874 +-47.037 1.62925 56.8436 -46.6284 1.96864 57.2405 +22.9893 -1.49201 -30.2158 23.4832 -0.740215 -29.7206 +-52.0057 0.647872 57.4657 -51.0488 1.50068 58.4125 +-52.2083 1.19868 57.6126 -51.5887 2.08835 58.4489 +-71.5618 2.55163 146.406 -70.7067 3.31369 147.311 +0.496927 -4.25663 -47.7303 1.25692 -3.99373 -47.4703 +0.832211 -4.66942 -48.022 1.30176 -4.02844 -47.5152 +0.825178 -4.66469 -47.689 1.29863 -4.02797 -47.1789 +-48.2227 1.04179 117.464 -47.8356 1.44371 117.883 +-48.2396 1.03892 117.465 -47.8472 1.45255 117.89 +-48.2417 1.04179 117.449 -47.8546 1.44371 117.867 +-48.2144 1.04179 117.471 -47.8273 1.44371 117.89 +-97.1271 5.59682 149.416 -96.2139 5.93809 150.416 +-64.1775 1.90435 157.81 -63.4158 2.3225 158.469 +20.9457 -3.09917 -30.7317 21.4396 -2.34737 -30.2365 +-145.242 4.89716 138.861 -144.643 5.39691 139.234 +-64.5759 1.9 158.596 -63.5625 2.65279 159.247 +-33.023 1.65986 59.7822 -32.3998 2.07801 60.5218 +-49.865 0.711883 89.568 -49.4563 1.05128 89.9739 +-49.8773 0.697948 89.4237 -49.4289 0.950128 90.0585 +-48.5034 1.64494 117.799 -48.1163 2.04686 118.218 +-48.5203 1.64207 117.8 -48.1279 2.0557 118.225 +-48.5224 1.64494 117.783 -48.1353 2.04686 118.202 +-48.4951 1.64494 117.806 -48.108 2.04686 118.225 +-39.2369 0.647872 55.2731 -38.2349 1.50068 56.2666 +-38.7043 1.19868 55.4604 -38.0355 2.08835 56.3114 +-73.2037 3.20751 145.906 -72.5461 3.9603 146.92 +-8.58555 3.74673 73.205 -8.13217 4.14753 73.7413 +-8.5877 3.54025 73.2062 -8.13569 3.9523 73.7484 +-8.60642 3.60768 73.3487 -8.35726 4.09329 73.5896 +-8.57132 3.60905 73.436 -8.32216 4.09465 73.677 +-8.53361 3.94133 73.3664 -8.28361 4.19133 73.6164 +-72.8524 3.20751 145.996 -72.2857 3.9603 147.001 +-79.9617 3.40906 152.987 -79.217 3.82721 153.614 +-31.6159 -1.16 20.8447 -30.8805 -0.634513 21.8216 +-62.4857 2.74991 152.381 -61.7575 3.29155 152.928 +-1.62726 -0.770112 -27.2939 -0.960168 -0.081094 -26.6266 +-19.7611 -3.06518 2.90441 -19.053 -2.4677 3.67598 +-19.7524 -2.85239 2.94855 -19.0522 -2.41701 3.30314 +-117.14 4.64039 159.928 -116.687 5.45191 160.614 +-165.359 1.69088 94.9007 -164.643 2.38943 95.4643 +-71.4662 1.76801 71.8611 -70.8675 2.54331 72.461 +-63.0742 1.64122 132.496 -62.3748 2.1554 133.232 +-62.974 1.80706 132.522 -62.373 2.19491 132.949 +-71.1047 1.76798 71.3182 -70.3557 2.57478 72.0292 +-25.1457 4.50125 0.765732 -24.7807 6.36625 1.13073 +-27.3018 2.19699 -1.35566 -22.7023 4.89907 3.16908 +-32.6486 -0.550184 3.4643 -32.222 -0.14939 3.99651 +-32.6498 -0.756669 3.46126 -32.2244 -0.344617 4.00403 +-32.6822 -0.689235 3.5923 -32.4326 -0.20363 3.83163 +-32.6578 -0.687871 3.68323 -32.4081 -0.202266 3.92256 +-32.6123 -0.355582 3.61777 -32.3623 -0.105582 3.86777 +-164.462 2.71255 92.7605 -163.811 3.1726 93.378 +-5.87032 1.92282 94.3159 -5.18058 2.61184 95.0059 +-77.8094 0.600196 162.467 -77.2456 0.961576 163.032 +-57.1322 -0.251691 70.4762 -55.7901 0.136865 71.7302 +-47.9583 1.721 115.909 -47.599 2.12179 116.447 +-47.9584 1.51452 115.914 -47.601 1.92657 116.443 +-47.79 1.58195 116.108 -47.5399 2.06755 116.344 +-47.7901 1.58331 116.014 -47.54 2.06892 116.25 +-47.8497 1.9156 116.053 -47.5997 2.1656 116.303 +-32.6695 -0.550184 2.55031 -32.1441 -0.14939 3.06079 +-32.6751 -0.756669 2.54567 -32.1509 -0.344617 3.05589 +-32.5672 -0.689235 2.5663 -32.3222 -0.20363 2.81306 +-32.6379 -0.687871 2.62857 -32.3928 -0.202266 2.87533 +-32.5662 -0.355582 2.64114 -32.3162 -0.105582 2.89114 +-39.4758 1.62106 55.1095 -38.9864 2.18786 55.5973 +-26.7588 0.192687 16.8332 -26.371 0.898219 17.3981 +8.11999 -3.18305 -29.5938 8.49282 -2.95514 -29.2675 +16.746 -3.92534 -36.463 17.2818 -3.50795 -36.0465 +16.7414 -4.1206 -36.423 17.2813 -3.67854 -35.9941 +16.9508 -4.07286 -36.4849 17.1942 -3.59314 -36.1937 +16.8572 -4.07068 -36.4945 17.1006 -3.59097 -36.2033 +16.9021 -3.73364 -36.4713 17.1521 -3.48364 -36.2213 +-47.1379 1.63233 56.5512 -46.6806 1.90648 57.0347 +-47.054 1.63233 56.4501 -46.5968 1.90648 56.9336 +-47.1794 1.61885 56.4105 -46.5545 1.87103 57.0895 +-115.305 3.88995 160.343 -114.792 4.63696 161.003 +-84.3705 -0.354132 171.329 -83.4228 0.407929 172.24 +-27.5434 -3.21287 0.540621 -26.8366 -2.82249 1.18396 +-109.459 0.893715 149.624 -108.946 1.64072 150.285 +-52.8955 0.619209 89.6806 -52.1506 0.871389 90.4223 +-52.7354 0.623152 89.8884 -52.3124 0.940885 90.3281 +-52.7523 0.631432 89.759 -52.3295 0.914077 90.1849 +-79.5191 1.91591 150.891 -78.6089 2.67797 151.752 +-52.7474 1.4681 93.4154 -52.2187 1.8689 93.9178 +-52.7433 1.26162 93.411 -52.2128 1.67367 93.9104 +-52.5 1.32905 93.4824 -52.2552 1.81466 93.7294 +-52.575 1.33042 93.4255 -52.3303 1.81602 93.6725 +-52.5769 1.6627 93.4994 -52.3269 1.9127 93.7494 +8.09892 -3.18059 -28.1561 8.49694 -2.95234 -27.7589 +-51.9212 0.676022 85.0192 -51.4581 0.960542 85.4559 +-51.9136 0.662088 84.8897 -51.4661 0.914268 85.5241 +-96.8106 1.30283 86.8971 -96.4766 1.63683 87.2311 +-115.579 4.64039 160.265 -115.065 5.38739 160.925 +14.7182 -3.23215 -29.1099 15.1982 -2.37415 -28.6299 +20.0103 -4.15673 -47.8729 20.546 -3.75593 -47.4848 +20.0084 -4.36321 -47.8729 20.5451 -3.95116 -47.4857 +20.1944 -4.29578 -47.9224 20.4316 -3.81017 -47.6724 +20.1008 -4.29441 -47.912 20.338 -3.80881 -47.662 +20.1469 -3.96212 -47.8578 20.3969 -3.71212 -47.6078 +19.1995 2.95744 82.622 19.5524 3.40654 82.9749 +-58.3018 0.782944 71.4632 -57.7653 1.18374 71.9204 +-58.3 0.576459 71.4669 -57.7582 0.988511 71.9227 +-58.1559 0.643893 71.6903 -57.9147 1.1295 71.9393 +-58.0692 0.645257 71.6535 -57.828 1.13086 71.9026 +-58.1394 0.977545 71.6162 -57.8894 1.22755 71.8662 +-74.3677 0.640065 90.1455 -73.3574 1.15729 91.2207 +-11.9588 -0.160376 98.0944 -11.2817 0.160904 98.7288 +-80.3279 3.86703 154.204 -79.5669 4.28517 154.862 +-138.026 2.89263 85.4243 -137.427 3.39238 85.7969 +-86.6623 0.605042 129.709 -86.2915 1.22739 130.248 +-86.1244 0.934267 130.072 -85.6929 1.27229 130.873 +-86.1737 0.605042 130.546 -85.8029 1.22739 131.086 +-86.0144 0.605042 129.859 -85.6435 1.22739 130.398 +-86.8217 0.605042 130.396 -86.4508 1.22739 130.936 +-86.7723 0.934267 129.922 -86.3408 1.27229 130.723 +-86.7339 1.35461 130.579 -85.8069 1.68938 131.066 +-86.806 1.08171 130.411 -86.4524 1.66483 130.875 +-86.7942 1.28325 129.828 -86.3238 1.57529 130.819 +-86.7673 1.05229 129.913 -85.6895 1.39328 130.89 +-86.6575 1.08171 129.77 -86.3039 1.66483 130.234 +-86.5466 1.35461 129.771 -85.6201 1.68938 130.254 +-86.8148 1.44483 129.768 -86.3039 1.91636 130.875 +-86.0111 1.08171 129.928 -85.6596 1.58678 130.384 +-86.1577 1.08171 130.56 -85.8061 1.58678 131.016 +8.22581 1.92971 67.8334 8.89716 2.61873 68.5047 +-68.7514 1.9135 158.151 -68.2117 2.45514 158.878 +24.1811 -1.98935 34.6857 24.803 -1.18255 35.5545 +-77.3207 0.620473 162.502 -76.8771 0.960415 162.927 +-77.3091 0.621675 162.552 -76.9365 0.873852 162.911 +-77.3249 0.666443 162.607 -76.9846 0.960083 162.929 +-77.2202 0.614447 162.543 -76.8704 0.966427 162.914 +7.78279 -3.15289 -27.072 8.21171 -2.54928 -26.633 +-71.4945 0.411889 68.4194 -70.5885 0.906572 69.268 +22.0097 0.638311 96.2839 22.4007 0.934311 96.5938 +21.8619 -0.00423029 96.1079 22.5488 0.732539 96.7757 +-51.1365 2.4529 90.9749 -50.4007 3.3249 91.6247 +-116.421 2.38653 159.954 -115.968 3.19805 160.64 +-44.5387 0.647872 55.3904 -43.5818 1.50068 56.3372 +-44.7413 1.19868 55.5373 -44.1217 2.08835 56.3736 +-67.7721 3.21535 147.539 -67.1145 3.6335 148.3 +-141.401 3.37006 139.976 -140.802 3.86981 140.349 +-29.2679 -1.41182 146.798 -28.8952 -0.912072 147.397 +18.6972 -1.9903 35.0526 19.4597 -1.1183 35.7403 +13.6802 -4.975 -40.0656 14.6501 -4.28275 -39.0222 +-9.43036 4.9907 76.1258 -8.87003 6.86963 76.5829 +-9.61518 6.43109 76.1292 -8.9709 7.07186 76.773 +-9.52093 6.10914 76.1569 -8.98156 6.64672 76.6956 +-9.30185 4.99232 75.8665 -8.86557 6.75663 76.3449 +-9.4515 6.28714 75.6017 -8.75555 6.97658 76.3009 +-9.37124 5.96021 75.7525 -8.83085 6.49711 76.2923 +-9.1025 4.99225 76.1235 -8.76731 7.13543 76.5686 +-9.33259 6.70326 76.1945 -8.64051 7.39169 76.8852 +-9.18926 6.45883 76.1499 -8.64431 6.99649 76.6976 +-9.10186 4.9932 75.9488 -8.44365 6.77768 76.3511 +-9.09606 6.40574 75.9362 -8.42989 7.06965 76.6014 +-9.00105 6.16229 75.9245 -8.45705 6.70067 76.4714 +-9.10186 4.9932 75.7411 -8.68511 7.2208 76.3511 +-9.26248 6.82787 75.7086 -8.57087 7.51618 76.3988 +-9.22058 6.54008 75.8211 -8.68366 7.07683 76.3583 +-9.5203 4.99163 76.1049 -8.87417 7.28988 76.3895 +-9.71531 6.84464 75.8574 -8.97344 7.58229 76.5985 +-9.59579 6.55049 75.9912 -9.05731 7.08756 76.5283 +-9.20891 4.99266 76.1169 -8.87756 7.68133 76.4134 +-9.4471 7.25553 75.9269 -8.70697 7.99247 76.665 +-9.25799 7.01018 75.9316 -8.72127 7.5469 76.4683 +-33.035 2.31154 59.8875 -32.3224 2.72969 60.4661 +-3.31261 -1.17383 -71.115 -2.88502 0.408009 -70.6701 +-3.4927 0.0204637 -71.1777 -2.92222 0.580493 -70.5986 +-3.41263 -0.240186 -71.1752 -2.92978 0.235869 -70.6834 +-3.11502 -1.17383 -71.4355 -2.84591 0.292706 -70.885 +-3.36232 -0.105081 -71.501 -2.76094 0.495107 -70.8994 +-3.20966 -0.391683 -71.477 -2.73366 0.0843173 -71.001 +-3.11716 -1.17486 -71.1081 -2.87997 0.610757 -70.6375 +-3.29797 0.229248 -71.0645 -2.69015 0.830574 -70.4555 +-3.24946 0.019808 -71.0186 -2.77256 0.496063 -70.5411 +-3.11502 -1.17383 -71.132 -2.48097 0.314799 -70.885 +-2.98622 -0.039258 -71.2966 -2.40116 0.541654 -70.7126 +-3.0081 -0.22085 -71.232 -2.52335 0.257042 -70.7494 +-3.11502 -1.17383 -71.336 -2.62144 0.687302 -70.885 +-3.13438 0.322708 -71.4412 -2.52764 0.923897 -70.8352 +-3.01628 0.0690164 -71.4234 -2.54028 0.545016 -70.9474 +-3.2794 -1.17383 -71.2991 -2.88502 0.761399 -70.885 +-3.54591 0.352622 -71.414 -2.89622 0.993336 -70.7639 +-3.43559 0.116185 -71.2982 -2.95348 0.592739 -70.8149 +-3.11502 -1.17383 -71.115 -2.8263 1.06722 -70.8655 +-3.26011 0.681714 -71.3002 -2.62011 1.32171 -70.6602 +-3.18593 0.478835 -71.2214 -2.70993 0.954835 -70.7454 +23.1762 -0.235213 -32.0061 23.6701 0.516584 -31.5109 +-106.616 -0.528478 151.296 -105.624 -0.192614 152.24 +-70.8936 2.74535 146.62 -70.2727 3.16349 147.361 +-102.887 6.14411 151.534 -102.434 6.95563 152.221 +-0.424202 -4.03398 -30.9043 0.626808 -3.34173 -29.7989 +-79.8468 3.86703 152.54 -79.0858 4.28517 153.198 +20.8501 -3.09917 -27.1277 21.344 -2.34737 -26.6325 +-36.5725 0.647872 56.5529 -35.474 1.50068 57.6513 +-36.7177 1.19868 56.4173 -35.888 2.08835 57.2472 +-1.68299 7.04966 63.419 -1.02778 9.46646 64.0623 +-1.9535 8.94409 63.1524 -1.16713 9.72757 63.9374 +-1.76577 8.53461 63.2974 -1.11384 9.18236 63.9456 +-1.26217 7.05387 63.716 -0.540837 9.31853 64.0716 +-1.33828 8.79495 63.3679 -0.485277 9.64358 64.2169 +-1.24355 8.35112 63.5042 -0.592189 8.9989 64.1518 +-1.80598 7.05197 63.8248 -1.02531 9.79388 64.1086 +-2.16828 9.28535 63.5821 -1.31898 10.1337 64.4316 +-1.92368 8.96784 63.6514 -1.27082 9.61622 64.3 +-1.45526 7.05215 63.835 -1.02013 9.40765 64.4235 +-1.71749 8.91605 63.8859 -0.896114 9.73225 64.7025 +-1.65569 8.60292 63.9345 -1.00742 9.25036 64.5827 +-1.26165 7.0527 63.8458 -0.919484 9.99367 64.2842 +-1.50716 9.49163 63.7596 -0.656209 10.3398 64.6098 +-1.3766 9.10794 63.8021 -0.723333 9.75516 64.4509 +-1.37072 7.05374 63.4002 -0.998435 10.0597 64.0662 +-1.73591 9.5194 63.0723 -0.817522 10.4323 63.9873 +-1.55711 9.13967 63.2766 -0.903849 9.78679 63.9254 +-1.4895 7.05457 63.8103 -1.01253 10.5548 64.1049 +-1.82705 10.0535 63.5226 -0.906647 10.9669 64.4377 +-1.68507 9.72405 63.6582 -1.03115 10.3717 64.3084 +-62.6745 3.208 153.008 -62.0508 3.62614 153.751 +-50.3144 -0.316696 84.8628 -49.3428 0.53611 85.8248 +-50.518 0.23411 84.8328 -49.8828 1.12378 85.6743 +-67.8594 4.06074 147.568 -67.0844 4.47889 148.256 +-66.7591 3.85761 158.903 -66.2194 4.39925 159.63 +-51.1995 4.59298 100.331 -50.3836 5.51522 101.148 +-74.8863 -0.36095 164.168 -73.7896 0.491857 165.265 +-74.4926 0.189857 164.591 -73.6531 1.07952 165.41 +-143.322 4.89716 139.419 -142.723 5.39691 139.791 +-95.737 1.04784 89.0986 -95.403 1.38184 89.4326 +-103.612 6.14411 151.324 -103.159 6.95563 152.01 +-73.4424 0.915526 84.9601 -72.4325 1.43275 85.7956 +9.23679 -3.16555 -30.0239 9.62009 -2.93104 -29.6814 +-31.4681 -1.16 21.659 -30.8431 -0.872565 22.301 +49.1506 2.79368 79.5845 49.5072 3.12857 79.9602 +48.8591 2.79514 79.3837 49.2173 3.131 79.7595 +48.8859 2.78784 79.3737 49.482 3.04594 79.97 +49.0338 2.79385 79.6705 49.4167 3.12794 79.9951 +48.8943 2.79457 79.6384 49.2715 3.13035 79.9951 +49.0965 2.79399 79.3483 49.4727 3.12741 79.7056 +48.8591 2.79524 79.5234 49.1854 3.13102 79.9062 +48.9479 2.7945 79.3484 49.3316 3.12975 79.6737 +49.1825 2.79362 79.4376 49.5068 3.12836 79.8204 +-62.729 2.10147 153.034 -61.9807 2.51962 153.668 +-71.7036 3.19979 146.304 -71.0527 3.95258 147.318 +-47.9427 1.24076 116.971 -47.5556 1.64267 117.389 +-47.9596 1.23788 116.971 -47.5672 1.65151 117.396 +-47.9617 1.24076 116.955 -47.5746 1.64267 117.373 +-47.9344 1.24076 116.978 -47.5473 1.64267 117.396 +-48.0294 0.926543 116.256 -47.602 1.53015 116.684 +-66.2826 3.2137 147.922 -65.4213 3.97576 148.832 +-43.1067 1.63102 55.5016 -42.675 1.97096 55.9577 +-43.0529 1.63222 55.5628 -42.6981 1.8844 55.9356 +-42.9847 1.67699 55.5966 -42.6734 1.97063 55.9435 +-43.0714 1.62499 55.4876 -42.7005 1.97697 55.8422 +-51.6215 4.60829 85.6423 -50.771 5.53053 86.4937 +-72.622 3.20751 146.069 -71.9644 3.9603 147.083 +-77.3642 0.618702 162.297 -76.955 0.958097 162.701 +-94.6709 1.14448 88.9442 -94.3369 1.47848 89.2782 +-69.715 0.745251 90.0109 -69.1059 1.22819 90.6513 +28.0716 2.73337 46.8223 28.5247 2.99628 47.5435 +27.8661 2.32059 46.7983 28.2729 2.96156 47.3469 +28.0936 2.32532 46.7679 28.6667 2.96204 47.1282 +-32.2198 -1.1786 -0.428799 -31.4063 -0.402988 0.563331 +-32.1757 -2.05921 -0.108964 -31.6209 -0.805625 0.530598 +-119.621 -0.611204 146.618 -119.136 0.170659 147.314 +-126.905 10.3629 86.5696 -126.306 10.8627 86.9423 +-80.8492 1.65354 100.827 -80.5322 2.21768 101.144 +21.3064 -4.36503 -48.0825 21.7877 -3.61323 -47.603 +48.5497 1.89 78.4832 49.6442 2.70198 79.2871 +-48.1477 1.721 116.17 -47.7884 2.12179 116.708 +-48.1478 1.51452 116.175 -47.7904 1.92657 116.704 +-47.9794 1.58195 116.369 -47.7294 2.06755 116.605 +-47.9795 1.58331 116.275 -47.7295 2.06892 116.511 +-48.0391 1.9156 116.314 -47.7891 2.1656 116.564 +-124.984 4.36291 87.1271 -124.385 4.86266 87.4997 +-89.2005 1.72395 97.4381 -88.768 2.32756 97.8656 +-1.45797 -4.1 -25.0772 -0.944517 -3.28802 -24.0067 +-78.0377 0.620587 162.087 -77.6065 0.960528 162.544 +-77.9856 0.621789 162.148 -77.6316 0.873965 162.523 +-77.9115 0.666556 162.177 -77.6052 0.960196 162.524 +-78.0045 0.614561 162.071 -77.6356 0.966541 162.425 +-66.9167 2.56712 158.808 -66.0117 3.32918 159.662 +-24.6964 -3.34494 -3.77458 -23.4081 -2.95639 -2.64153 +-119.079 0.144831 146.801 -118.512 0.979247 147.529 +-93.4154 1.06675 89.6729 -93.0814 1.40075 90.0069 +-71.9891 2.75546 72.5391 -71.4654 3.15625 73.0518 +-71.9946 2.54898 72.5343 -71.4723 2.96103 73.047 +-71.89 2.61641 72.5571 -71.6448 3.10201 72.8037 +-71.9595 2.61777 72.6207 -71.7142 3.10338 72.8672 +-71.8875 2.95006 72.6318 -71.6375 3.20006 72.8818 +14.3642 -2.4279 -11.736 14.8794 -2.20511 -11.2738 +14.3776 -2.43656 -11.7253 14.8874 -2.21377 -11.2727 +14.3642 -2.45269 -11.736 14.8794 -2.22989 -11.2738 +14.3642 -2.41708 -11.736 14.8794 -2.19429 -11.2738 +-96.8044 1.08332 88.4636 -96.4704 1.41732 88.7976 +22.4424 -3.09917 -26.6552 22.9363 -2.34737 -26.16 +-109.607 0.893715 149.584 -109.154 1.70524 150.27 +-2.93589 1.08844 54.8601 -2.44742 1.84024 55.3483 +-33.0905 0.166707 61.3662 -32.2885 0.928769 62.0935 +-23.1898 5.42022 48.5193 -22.3478 6.10363 49.3036 +-23.7892 5.42292 47.9811 -22.883 5.69892 48.823 +-24.3314 5.42528 47.4942 -23.4633 6.11518 48.3019 +-24.5458 4.89002 47.2416 -23.9272 6.18993 47.8775 +-22.7151 4.89002 48.8855 -22.0966 6.18993 49.5214 +-2.67355 -4.10251 -23.0103 -2.02997 -3.12604 -22.373 +-103.417 7.63938 151.38 -102.932 8.42124 152.076 +11.4309 -3.1816 -35.6383 11.803 -2.95367 -35.3131 +-79.7885 3.21535 152.462 -79.1308 3.6335 153.223 +8.52941 -4.74348 13.4227 8.88052 -4.29438 13.7738 +-22.5656 -2.78204 5.28436 -22.1371 -2.4421 5.70625 +-22.5586 -2.78084 5.29305 -22.1854 -2.52866 5.66663 +-22.5689 -2.73607 5.34519 -22.2503 -2.44243 5.68283 +-22.4834 -2.78807 5.32753 -22.1434 -2.43609 5.69871 +-106.561 -1.11357 151.478 -105.83 -0.688308 152.325 +-108.612 0.893715 149.872 -108.127 1.67558 150.568 +-6.94417 -0.108714 45.2466 -6.18769 0.758795 46.0031 +-109.118 0.150417 149.726 -108.665 0.961942 150.412 +-49.2089 0.659083 85.5945 -48.7784 1.22588 86.0153 +-66.6586 3.40906 147.872 -66.0316 3.82721 148.617 +37.1495 2.78616 83.5095 37.8328 3.47518 84.1926 +-72.384 4.0531 146.232 -71.7591 4.47125 146.976 +-30.2434 0.0881764 150.159 -29.8708 0.587928 150.758 +-30.2434 1.58818 150.159 -29.8708 2.08793 150.758 +37.2317 2.7868 74.1783 37.6127 3.12169 74.5082 +37.3394 2.78826 73.8568 37.7202 3.12412 74.1882 +37.1768 2.78096 73.8839 37.7761 3.03907 74.4826 +37.1508 2.78697 74.0899 37.505 3.12106 74.4625 +37.1511 2.78769 73.9376 37.4817 3.12347 74.3182 +37.4711 2.78711 74.0452 37.8012 3.12053 74.4281 +37.1953 2.78836 73.8565 37.5697 3.12414 74.2119 +37.4475 2.78762 73.9009 37.8016 3.12287 74.2767 +37.383 2.78674 74.1547 37.757 3.12148 74.5081 +-120.689 -0.611204 146.247 -120.236 0.200321 146.933 +-12.0484 1.70368 43.4827 -11.6584 1.99968 43.7984 +-12.1992 1.06113 43.3084 -11.5073 1.7979 43.9809 +-48.5695 1.84103 117.718 -48.1824 2.24295 118.137 +-48.5864 1.83816 117.719 -48.1941 2.25179 118.144 +-48.5885 1.84103 117.703 -48.2014 2.24295 118.121 +-48.5612 1.84103 117.725 -48.1741 2.24295 118.144 +-110.918 1.64569 149.203 -110.433 2.42755 149.899 +-63.4783 3.85967 155.769 -62.7144 4.27782 156.433 +-106.627 -0.909942 151.374 -105.672 -0.462451 152.387 +-93.3267 1.18755 88.7519 -92.9927 1.52155 89.0859 +-104.2 6.88741 151.153 -103.748 7.69893 151.84 +44.6607 1.89084 79.7925 45.1549 2.64263 80.2872 +-27.3091 -3.12789 -0.606332 -26.8704 -2.67198 -0.135995 +-27.2863 -3.10837 -1.22204 -26.8995 -2.64666 -0.855018 +-27.8772 -3.19962 -1.33932 -26.8382 -2.86491 -0.0767564 +-27.816 -3.11896 -0.560969 -27.4373 -2.58438 -0.172138 +-27.814 -3.10606 -1.2464 -27.4213 -2.66209 -0.852322 +-66.4426 3.8576 158.809 -65.9029 4.39925 159.536 +53.0781 2.79328 79.9365 53.459 3.12817 80.2664 +53.1857 2.79474 79.615 53.5666 3.1306 79.9464 +53.0232 2.78744 79.6421 53.6224 3.04555 80.2408 +52.9971 2.79345 79.8481 53.3513 3.12754 80.2206 +52.9974 2.79417 79.6958 53.328 3.12995 80.0763 +53.3175 2.79359 79.8034 53.6475 3.12701 80.1863 +53.0416 2.79484 79.6146 53.416 3.13062 79.97 +53.2939 2.7941 79.659 53.6479 3.12935 80.0349 +53.2293 2.79322 79.9129 53.6034 3.12796 80.2663 +-47.0426 0.647872 56.2346 -46.0858 1.50068 57.1814 +-46.5028 1.19868 56.1981 -45.8832 2.08835 57.0345 +-84.8867 1.64055 105.102 -84.3733 2.38756 105.762 +27.3941 5.86947 65.0933 28.1462 6.36464 65.7501 +-97.5443 4.8431 147.013 -96.473 5.2378 148.025 +-74.9513 0.618327 164.072 -74.28 0.939608 164.697 +-144.922 1.66059 120.04 -144.292 2.14353 120.697 +-106.377 -0.401396 152.778 -105.534 -0.0655315 153.479 +-96.3304 1.14939 88.4246 -95.9964 1.48339 88.7586 +-84.5873 0.888575 105.142 -84.1344 1.7001 105.829 +19.4872 -4.1 -29.5801 20.4615 -3.40776 -28.5287 +14.7025 -3.16779 -28.0986 15.346 -2.19132 -27.4614 +26.5807 -4.11 31.2208 27.3258 -3.29802 32.3239 +-118.66 0.888795 146.919 -118.164 1.69407 147.635 +-8.67717 3.74673 74.3717 -8.21208 4.14753 74.9063 +-8.68004 3.54025 74.3647 -8.21763 3.9523 74.9053 +-8.65163 3.60768 74.4285 -8.40301 4.09329 74.6707 +-8.69114 3.60905 74.5139 -8.44253 4.09465 74.7561 +-8.61831 3.94133 74.4931 -8.36831 4.19133 74.7431 +-52.4519 1.75239 91.0336 -51.8132 2.58939 91.6763 +-97.6646 5.6062 148.866 -96.859 6.03147 149.541 +-44.6791 -0.0605374 144.147 -44.3065 0.439214 144.746 +-79.7173 3.2137 151.586 -78.8071 3.97576 152.447 +-63.6962 1.90856 156.122 -62.7807 2.67062 156.99 +-32.6651 -0.550184 3.08128 -32.1742 -0.14939 3.61369 +-32.669 -0.756669 3.07502 -32.1814 -0.344617 3.61 +-32.6122 -0.689235 3.12514 -32.3645 -0.20363 3.36905 +-32.6633 -0.687871 3.20422 -32.4157 -0.202266 3.44813 +-32.5893 -0.355582 3.19476 -32.3393 -0.105582 3.44476 +-62.734 1.81334 130.524 -62.4356 2.21525 130.991 +-62.7234 1.81046 130.512 -62.4226 2.2241 130.986 +-62.7103 1.81334 130.532 -62.4119 2.21525 130.998 +-62.7443 1.81334 130.521 -62.446 2.21525 130.988 +-116.943 2.38653 159.854 -116.458 3.16839 160.55 +25.9627 -5.06932 -47.7206 26.7283 -4.12863 -47.1368 +26.364 -5.05661 -47.6282 27.6215 -4.43048 -47.177 +42.8899 2.4202 72.8615 43.1908 3.10361 73.8979 +42.9135 2.42291 72.0564 43.2172 2.69891 73.1789 +42.939 2.42526 71.328 43.241 3.11516 72.3994 +42.7994 1.89 71.0693 43.4196 3.18991 71.7034 +42.7189 1.89 73.5284 43.3391 3.18991 74.1625 +-53.064 0.47047 92.8616 -52.441 1.27727 93.7308 +-124.984 5.86291 87.1271 -124.385 6.36266 87.4997 +-100.298 18.2007 138.555 -99.8477 18.7132 139.005 +-102.276 9.36787 136.568 -97.8771 13.4564 140.994 +-51.9012 -0.316696 84.813 -50.9296 0.53611 85.775 +-51.3611 0.23411 84.9635 -50.7259 1.12378 85.8051 +-72.6845 0.71153 88.4505 -71.9991 1.58353 89.2114 +-67.7243 2.76071 147.556 -67.0974 3.17885 148.301 +15.8601 -4.1 -27.7339 16.8299 -3.40775 -26.6905 +-97.056 5.71952 149.408 -96.1429 6.06079 150.407 +-145.242 1.89978 138.861 -144.643 2.39953 139.234 +-63.6473 3.20635 156.139 -62.8605 3.96841 156.988 +37.4156 2.75793 84.2343 38.0026 3.33531 84.7831 +-66.7074 3.86703 147.854 -66.0498 4.28517 148.615 +-79.4396 3.40906 150.934 -78.7636 3.82721 151.701 +29.4251 2.73337 50.05 29.8782 2.99628 50.7712 +29.2195 2.32059 50.026 29.6264 2.96156 50.5746 +29.4471 2.32532 49.9956 30.0201 2.96204 50.3559 +-9.11494 3.76873 72.6551 -8.57779 4.17509 73.0246 +-9.11069 3.56252 72.6556 -8.57732 3.98159 73.0243 +-9.01951 3.6323 72.8269 -8.77855 4.11785 73.0771 +-8.92547 3.63587 72.8306 -8.68451 4.12141 73.0808 +-8.97882 3.96699 72.7691 -8.72882 4.21699 73.0191 +22.5632 2.36544 73.7088 22.9127 2.81454 74.0583 +-58.2384 -0.251734 70.7941 -56.9021 0.136822 72.0387 +21.4357 -4.73952 -47.9938 21.9678 -4.33656 -47.5831 +21.4272 -4.94594 -47.9945 21.969 -4.53105 -47.5852 +21.6056 -4.87713 -48.0345 21.8464 -4.39158 -47.7843 +21.5133 -4.87493 -48.016 21.754 -4.38938 -47.7658 +21.5677 -4.54328 -47.9662 21.8177 -4.29328 -47.7162 +-70.0181 3.20677 146.919 -69.0188 3.72399 147.736 +18.2414 -3.12972 -36.1253 18.6739 -2.67316 -35.659 +18.3184 -3.1155 -35.4146 18.7045 -2.65424 -35.0421 +18.2075 -3.19818 -36.23 19.2944 -2.87407 -34.9306 +18.801 -3.11877 -36.136 19.1873 -2.58475 -35.7408 +18.8437 -3.11321 -35.4495 19.2273 -2.67026 -35.0643 +12.1651 -3.19624 -22.8685 12.5534 -2.96186 -22.5172 +-94.5631 1.06675 89.3301 -94.2291 1.40075 89.6641 +-49.3554 0.692033 89.4829 -48.6061 1.27523 90.2866 +-49.2955 0.896776 89.5215 -48.6054 1.324 89.9277 +-23.6759 -2.05935 5.33627 -23.1959 -1.20135 5.81627 +-20.021 0.840004 62.0609 -19.4663 1.12744 62.7572 +20.7853 -4.15673 -47.9921 21.321 -3.75593 -47.6039 +20.7834 -4.36321 -47.9921 21.3201 -3.95116 -47.6049 +20.9694 -4.29578 -48.0415 21.2066 -3.81017 -47.7915 +20.8758 -4.29441 -48.0311 21.1131 -3.80881 -47.7811 +20.9219 -3.96212 -47.9769 21.1719 -3.71212 -47.7269 +6.61531 7.06678 63.843 7.20939 9.28755 64.3688 +6.37875 8.79763 63.8724 7.1084 9.52615 64.6044 +6.51208 8.41529 63.9038 7.11718 9.01971 64.5092 +6.78931 7.06873 63.4959 7.22184 9.14836 64.0628 +6.54631 8.62543 63.2269 7.33698 9.41259 64.0212 +6.65348 8.23302 63.4032 7.2597 8.83781 64.0108 +6.97531 7.06978 63.8327 7.27957 9.59062 64.4331 +6.76105 9.12451 63.9174 7.54821 9.91119 64.7076 +6.87499 8.82997 63.8781 7.48491 9.4352 64.4915 +6.97432 7.07017 63.6316 7.77646 9.15823 64.0743 +7.04046 8.75798 63.6194 7.79728 9.51482 64.3792 +7.08244 8.47829 63.6342 7.69046 9.08339 64.2441 +6.97432 7.07017 63.407 7.49155 9.70401 64.0743 +6.84264 9.26997 63.3321 7.63014 10.0566 64.1232 +6.94861 8.91279 63.3904 7.55691 9.51823 64.0007 +6.56323 7.06789 63.8294 7.20392 9.80505 64.1082 +6.25894 9.29724 63.5429 7.10589 10.1423 64.3937 +6.44929 8.95283 63.6902 7.05378 9.55725 64.2971 +6.97432 7.07017 63.8304 7.30887 10.2607 64.0761 +6.66507 9.78975 63.5803 7.51202 10.6346 64.4327 +6.8742 9.4916 63.6509 7.47859 10.096 64.2552 +17.4734 0.536815 32.0368 17.8343 0.832815 32.4036 +17.32 -0.105726 31.8907 17.9835 0.631043 32.551 +-23.7916 -2.77789 5.3337 -23.2967 -2.0261 5.82723 +22.9882 -1.49536 -27.2412 23.6318 -0.51889 -26.604 +-39.163 1.62925 55.1516 -38.847 2.19338 55.4676 +-68.6849 1.87672 63.5513 -68.0005 2.26371 64.2849 +12.3027 -3.19108 -23.4411 12.861 -2.6137 -22.8629 +-62.7459 3.85967 153.049 -61.982 4.27782 153.713 +49.3772 2.72972 79.6819 49.8572 3.58772 80.1618 +-123.063 8.86291 87.6846 -122.464 9.36266 88.0572 +-25.9213 0.195659 16.9059 -25.0929 0.671665 17.5414 +-50.7874 1.62925 57.1956 -50.4704 2.19338 57.5126 +-0.142018 -4.04372 -28.6124 0.866203 -3.35148 -27.5408 +-80.6176 0.672161 102.907 -79.6894 1.52497 103.846 +-80.6464 1.22297 102.703 -79.8169 2.11264 103.304 +-21.4918 -3.08491 4.85259 -20.9706 -1.98206 5.37167 +23.0091 -0.235213 -28.3099 23.503 0.516584 -27.8147 +-104.652 5.38216 150.83 -104.251 5.74583 151.691 +18.4236 -4.00449 -39.9349 18.8593 -3.54793 -39.4674 +18.477 -3.99027 -39.2195 18.8636 -3.52902 -38.8496 +18.3971 -4.07295 -40.0134 19.4478 -3.74885 -38.7417 +18.9872 -3.99355 -39.9226 19.3698 -3.45953 -39.5305 +19.001 -3.98799 -39.2389 19.3892 -3.54504 -38.8492 +55.3145 1.89084 67.9863 55.8011 2.64263 68.4713 +-83.3083 1.64055 105.514 -82.8236 2.42241 106.209 +-32.7256 -0.550184 3.77722 -32.2446 -0.14939 4.31333 +-32.7288 -0.756669 3.78314 -32.2493 -0.344617 4.31994 +-32.7309 -0.689235 3.93766 -32.4826 -0.20363 4.18042 +-32.6838 -0.687871 4.01916 -32.4354 -0.202266 4.26191 +-32.6561 -0.355582 3.94567 -32.4061 -0.105582 4.19567 +7.76547 -4.10251 -22.176 8.40905 -3.12604 -21.5387 +-4.93387 0.421953 47.4363 -4.11828 1.10536 48.2486 +-5.5052 0.424655 46.8684 -4.62847 0.700655 47.7415 +-6.02209 0.427011 46.3546 -5.18167 1.11691 47.1916 +-6.23617 -0.108249 46.1017 -5.61379 1.19166 46.7307 +-4.49111 -0.108249 47.8362 -3.86873 1.19166 48.4652 +7.87151 -3.17978 -27.863 8.21491 -2.95082 -27.4792 +-104.336 6.88741 151.113 -103.884 7.69893 151.8 +-50.8137 1.13083 91.1983 -50.3121 1.40498 91.5319 +-50.7836 1.13083 91.089 -50.2821 1.40498 91.4226 +-50.7674 1.13083 90.9901 -50.2659 1.40498 91.3236 +-50.8376 1.11735 90.9323 -50.2461 1.36953 91.5851 +29.9403 2.73337 51.2808 30.3934 2.99628 52.002 +29.7348 2.32059 51.2567 30.1416 2.96156 51.8054 +29.9623 2.32532 51.2263 30.5354 2.96204 51.5867 +-33.0253 1.46615 61.3644 -32.3343 1.8843 61.906 +-110.425 -0.599745 149.211 -109.972 0.21178 149.898 +9.11937 -3.22067 -29.5502 9.67763 -2.64329 -28.972 +-80.0967 3.85761 154.041 -79.3695 4.39925 154.581 +-9.2252 3.76188 75.818 -8.68861 4.17771 76.1872 +-9.23351 3.55635 75.8178 -8.69345 3.98755 76.1867 +-9.03015 3.6302 75.765 -8.77901 4.11531 76.0157 +-9.12396 3.63762 75.7613 -8.87282 4.12273 76.012 +-9.0659 3.96624 75.8236 -8.8159 4.21624 76.0736 +-73.2031 1.90748 146.066 -72.443 2.32562 146.722 +-74.3496 1.49826 90.2269 -73.2954 2.01548 91.2905 +-89.5395 -0.358331 150.615 -88.7594 0.40373 151.458 +17.9345 -4.975 -41.0069 18.9915 -4.28275 -40.0251 +-71.5618 3.86116 146.406 -70.7067 4.62322 147.311 +-49.6634 1.75446 91.3245 -49.2326 2.35807 91.7624 +-123.063 4.36291 87.6846 -122.464 4.86266 88.0572 +-83.9452 -0.604885 105.503 -83.4604 0.176978 106.198 +-18.6208 -4.11 2.76827 -18.1303 -3.29802 3.83523 +-84.7959 0.888575 105.128 -84.2826 1.63558 105.788 +-32.3889 -0.108325 59.6008 -31.4615 0.653736 60.5598 +14.7103 -1.01657 -14.5631 15.1901 0.839972 -13.9807 +14.5132 0.398547 -14.4176 15.1527 1.03534 -13.7794 +14.6467 0.0991996 -14.4675 15.1852 0.634456 -13.93 +14.575 -1.01496 -14.7063 15.1906 0.715169 -14.3426 +14.4094 0.260221 -14.9323 15.0981 0.944932 -14.2448 +14.5893 -0.0601914 -14.8748 15.1297 0.474404 -14.3362 +14.9679 -1.01385 -14.5713 15.2776 1.11279 -14.1215 +14.8216 0.693308 -14.5878 15.5116 1.37752 -13.8994 +14.858 0.440807 -14.5296 15.3955 0.974924 -13.9935 +14.9602 -1.01322 -14.9547 15.4828 0.750167 -14.338 +14.8641 0.395832 -14.8848 15.5257 1.0558 -14.2242 +14.9418 0.16055 -14.8307 15.4798 0.695155 -14.2938 +14.8361 -1.01454 -14.7958 15.1977 1.22448 -14.3512 +14.6676 0.796473 -15.069 15.3591 1.48099 -14.3792 +14.7271 0.513185 -14.9259 15.2664 1.04735 -14.3881 +14.5425 -1.01357 -14.5643 15.1989 1.25885 -14.1557 +14.3347 0.814907 -14.6823 15.0746 1.54904 -13.9441 +14.4487 0.519472 -14.5647 14.9852 1.0541 -14.0295 +14.8441 -1.01366 -14.5751 15.186 1.65504 -14.3083 +14.5863 1.22974 -14.7918 15.3255 1.96253 -14.0546 +14.695 0.984118 -14.6936 15.2354 1.51848 -14.1552 +-79.5191 3.86589 150.891 -78.6089 4.62795 151.752 +-109.12 -0.227369 124.311 -107.651 0.305579 125.457 +22.8214 -1.49093 -32.5089 23.4885 -0.801908 -31.8417 +-47.2295 2.97398 115.885 -46.7891 4.56734 116.221 +-47.1546 4.16463 115.787 -46.5893 4.72534 116.352 +-47.1909 3.90811 115.841 -46.7122 4.38435 116.32 +-47.5385 2.97526 115.888 -47.0094 4.4356 116.292 +-47.6099 4.03069 115.909 -47.0085 4.63109 116.51 +-47.4984 3.77514 115.845 -47.0028 4.25444 116.328 +-47.2342 2.97442 115.597 -46.8954 4.75112 116.115 +-47.296 4.37864 115.501 -46.6907 4.97972 116.106 +-47.286 4.17769 115.626 -46.807 4.65415 116.105 +-47.5742 2.97526 115.588 -47.0094 4.4484 116.118 +-47.585 4.11966 115.509 -47.0017 4.69969 116.092 +-47.5415 3.91488 115.529 -47.0454 4.39324 116.009 +-47.6359 2.97526 115.824 -47.0094 4.82315 116.118 +-47.6661 4.46834 115.645 -47.0602 5.069 116.25 +-47.6082 4.22659 115.761 -47.1291 4.70314 116.24 +-47.2452 2.97408 115.898 -46.9661 4.91262 116.349 +-47.3909 4.50338 115.901 -46.7455 5.14385 116.546 +-47.3076 4.26883 115.931 -46.8271 4.74517 116.411 +-47.3336 2.97526 115.798 -47.0094 5.21303 116.118 +-47.4882 4.83003 115.607 -46.8416 5.47012 116.253 +-47.4116 4.62743 115.711 -46.9299 5.10343 116.192 +-79.1635 1.66738 152.051 -78.299 2.42944 152.856 +-30.2434 3.08818 150.159 -29.8708 3.58793 150.758 +-51.3007 1.75623 90.8843 -50.8789 2.09618 91.314 +-51.2904 1.75744 90.9332 -50.9169 2.00961 91.3069 +-51.2381 1.8022 90.9977 -50.9007 2.09584 91.3174 +-51.2575 1.75021 90.8902 -50.8869 2.10219 91.2305 +-159.456 1.0776 105.37 -158.272 2.78997 106.541 +-52.5866 0.632154 89.5461 -52.1552 0.892003 89.9533 +-52.4772 0.634452 89.6195 -52.0818 0.924962 90.0545 +-52.4285 0.632411 89.6929 -52.0239 0.942573 90.1055 +-52.6261 0.61822 89.5035 -51.9695 0.8704 90.1508 +-62.7238 2.03809 131.007 -62.4254 2.44 131.473 +-62.7132 2.03521 130.994 -62.4125 2.44884 131.468 +-62.7001 2.03809 131.014 -62.4017 2.44 131.48 +-62.7341 2.03809 131.003 -62.4358 2.44 131.47 +36.4832 2.7347 73.2014 36.9632 3.5927 73.6814 +-23.1619 -2.78204 5.29656 -22.744 -2.4421 5.75803 +-23.1479 -2.78084 5.31475 -22.7871 -2.52866 5.68757 +-23.162 -2.73607 5.33638 -22.8778 -2.44243 5.68336 +-23.1216 -2.78807 5.39611 -22.7585 -2.43609 5.76725 +-75.4701 1.63841 162.041 -75.1416 2.23144 162.569 +15.3791 -4.1 -35.9492 16.241 -3.40776 -34.9916 +-103.479 6.14411 151.362 -103.026 6.95563 152.049 +-97.7265 5.5852 151.062 -96.8506 5.95677 151.667 +-48.2227 1.64494 117.464 -47.8356 2.04686 117.883 +-48.2396 1.64207 117.465 -47.8472 2.0557 117.89 +-48.2417 1.64494 117.449 -47.8546 2.04686 117.867 +-48.2144 1.64494 117.471 -47.8273 2.04686 117.89 +17.2488 -4.1 -35.9133 18.2371 -3.40776 -35.0139 +15.1319 -2.27155 -12.2644 15.6058 -1.87075 -11.7298 +15.1286 -2.47803 -12.2711 15.5997 -2.06598 -11.7324 +15.1663 -2.4106 -12.2116 15.4146 -1.92499 -11.9689 +15.123 -2.40923 -12.128 15.3713 -1.92363 -11.8853 +15.1963 -2.07695 -12.1452 15.4463 -1.82695 -11.8952 +15.1235 -2.27155 -11.8901 15.5617 -1.87075 -11.3576 +15.1216 -2.47803 -11.8975 15.5577 -2.06598 -11.3551 +15.1243 -2.4106 -11.823 15.3736 -1.92499 -11.5824 +15.0957 -2.40923 -11.7332 15.345 -1.92363 -11.4927 +15.1662 -2.07695 -11.7639 15.4162 -1.82695 -11.5139 +23.1025 -1.4873 -28.4459 23.4584 -1.15241 -28.0701 +22.8095 -1.48585 -28.644 23.167 -1.14999 -28.2682 +22.8364 -1.49314 -28.6557 23.4331 -1.23504 -28.0587 +22.9868 -1.48714 -28.3593 23.3693 -1.15304 -28.0335 +22.8464 -1.48642 -28.3896 23.2236 -1.15063 -28.0335 +23.0459 -1.487 -28.6811 23.4222 -1.15357 -28.3246 +22.8095 -1.48575 -28.5035 23.1369 -1.14997 -28.121 +22.8969 -1.48649 -28.681 23.2802 -1.15124 -28.3545 +23.1325 -1.48736 -28.5932 23.458 -1.15262 -28.2108 +-46.3585 5.81504 86.0989 -46.0437 6.37918 86.4137 +-71.409 2.74796 71.9763 -70.886 3.15624 72.4869 +-71.4134 2.54427 71.9732 -70.8774 2.97 72.5009 +-71.31 2.60365 71.9951 -71.0632 3.08916 72.2424 +-71.3796 2.60502 72.0585 -71.1328 3.09053 72.3058 +-71.3242 2.94281 72.0509 -71.0742 3.19281 72.3009 +-68.7676 3.86703 158.364 -68.0066 4.28517 159.022 +-64.8165 3.8848 159.541 -63.803 4.63758 160.22 +-68.672 2.76071 158.328 -68.0451 3.17885 159.073 +-20.2072 -3.5798 1.71355 -19.1705 -2.89639 2.00528 +-21.0125 -3.5771 1.6969 -19.8897 -3.3011 1.99041 +-21.7412 -3.57474 1.68183 -20.6695 -2.88484 1.97429 +-21.9998 -4.11 1.50555 -21.3651 -2.81009 2.1237 +-19.5399 -4.11 1.55642 -18.9052 -2.81009 2.17457 +-50.4095 1.76208 90.9813 -49.8939 2.01426 91.6426 +-47.5786 5.81504 86.0996 -47.1474 6.41865 86.5228 +5.16849 -5.12198 10.8167 5.5282 -4.67288 11.1764 +-7.31962 1.32851 45.9103 -6.83131 2.08031 46.3976 +-159.035 1.0776 103.373 -157.793 2.78997 104.62 +-33.0689 0.817794 60.4575 -32.291 1.23594 61.1532 +-23.1029 -3.21954 -2.85045 -22.4905 -2.83221 -2.17889 +-25.2918 -2.041 -3.81518 -24.1628 -1.51967 -3.53398 +-72.1156 1.56735 85.0934 -71.0145 2.37933 85.7793 +14.8495 -4.08319 -39.5064 15.3434 -3.33139 -39.0112 +-78.2945 -0.36095 161.356 -77.239 0.491857 162.417 +-78.3872 0.189857 161.178 -77.5268 1.07952 161.921 +-51.0939 1.75623 90.959 -50.672 2.09618 91.3875 +-51.0852 1.75744 91.0073 -50.7116 2.00961 91.3805 +-51.0331 1.8022 91.0723 -50.6954 2.09584 91.3908 +-51.0507 1.75021 90.9654 -50.6795 2.10219 91.3053 +19.4581 -3.16723 33.037 20.2237 -2.53914 33.8697 +19.4669 -2.93718 33.0834 20.2097 -2.48434 33.4658 +-80.094 1.9135 154.032 -79.3668 2.45514 154.571 +-49.2324 1.51455 117.37 -48.6308 2.35156 117.938 +-51.5179 5.80945 85.2564 -51.0702 6.37624 85.6959 +28.0284 1.89184 76.0582 28.5226 2.64363 76.553 +-38.8894 8.00691 146.033 -38.5494 8.38191 146.373 +-39.9294 3.05612 144.997 -37.5089 5.44249 147.403 +-5.58825 -0.802265 97.8905 -4.77802 -0.473802 98.4846 +-5.57625 -1.10774 97.9049 -4.79002 -0.568483 98.4702 +-5.01759 -1.07274 98.0556 -4.75964 -0.610903 98.5177 +-5.60983 -1.06883 98.0511 -5.34879 -0.610906 98.5089 +-5.59644 -1.10998 98.2463 -4.77299 -0.806035 98.5525 +-71.8594 1.56735 84.428 -70.7924 2.37933 84.9185 +-48.9787 -0.316696 85.1502 -48.0072 0.53611 86.1123 +-48.4387 0.23411 85.3007 -47.8035 1.12378 86.1423 +-23.1375 -2.04283 5.21041 -22.4704 -1.35381 5.87768 +18.676 -2.73889 36.358 19.472 -1.97683 37.2146 +-105.901 -1.06242 151.632 -104.936 -0.726554 152.628 +-98.3823 4.76104 147.414 -97.4367 5.10231 148.43 +29.7922 6.51047 67.4667 30.1306 6.80647 67.8488 +29.6164 5.86793 67.3226 30.3067 6.6047 68.0048 +-75.6805 1.63841 161.981 -75.2798 2.23144 162.506 +-102.619 1.13308 156.825 -102.379 1.60308 157.065 +-102.66 1.53265 156.785 -102.339 1.93074 157.106 +-102.819 0.901451 156.625 -102.179 1.38867 157.265 +-102.826 1.58644 156.805 -102.544 1.94335 157.086 +-102.639 1.58781 156.619 -102.36 1.93654 156.899 +-102.638 1.72414 156.807 -102.361 2.08414 157.083 +-102.64 1.59165 156.991 -102.359 1.88099 157.272 +-102.453 1.58919 156.805 -102.169 1.90294 157.085 +-102.847 1.37383 156.598 -102.152 1.7475 157.293 +-102.842 1.52707 156.789 -102.528 1.79872 157.102 +-102.656 1.52707 156.603 -102.343 1.79872 156.916 +-102.656 1.52707 156.974 -102.343 1.79872 157.288 +-102.47 1.52707 156.789 -102.157 1.79872 157.102 +14.2906 -3.04914 -13.9307 15.0613 -2.35556 -13.0336 +22.8387 -0.234127 -31.4636 23.5058 0.454891 -30.7963 +-21.6941 0.9106 63.6239 -20.9981 1.39354 64.3196 +-148.856 1.71319 104.136 -148.225 2.12468 104.703 +-37.8263 -1.51663 152.676 -37.0861 -1.25372 153.075 +-37.8818 -1.92942 152.707 -37.4894 -1.28844 153.262 +-37.8548 -1.92469 152.444 -37.3201 -1.28796 152.885 +-71.277 -0.36095 165.574 -70.2032 0.491857 166.644 +-70.7949 0.189857 165.471 -70.0319 1.07952 166.33 +-119.162 1.6388 146.849 -118.637 2.40777 147.528 +-67.465 2.56712 158.631 -66.6036 3.32918 159.541 +-68.4671 2.76071 147.344 -67.8401 3.17885 148.089 +-49.4244 1.70999 118.163 -48.899 2.11078 118.672 +-49.4202 1.5035 118.159 -48.8934 1.91556 118.665 +-49.176 1.57094 118.239 -48.9308 2.05654 118.486 +-49.2483 1.5723 118.179 -49.003 2.05791 118.425 +-49.2535 1.90459 118.252 -49.0035 2.15459 118.502 +-79.9848 1.9135 153.333 -79.2576 2.45514 153.873 +-1.42387 -0.766489 -27.6265 -1.06801 -0.4316 -27.2507 +-1.71686 -0.765034 -27.8247 -1.35942 -0.429177 -27.4488 +-1.69001 -0.772329 -27.8363 -1.09331 -0.514227 -27.2393 +-1.5396 -0.766326 -27.5399 -1.15706 -0.432231 -27.2142 +-1.68 -0.765606 -27.5702 -1.30276 -0.429821 -27.2142 +-1.48045 -0.766184 -27.8617 -1.1042 -0.43276 -27.5052 +-1.71694 -0.764932 -27.6841 -1.38945 -0.429157 -27.3017 +-1.62953 -0.765676 -27.8617 -1.24623 -0.430423 -27.5352 +-1.39388 -0.766549 -27.7739 -1.0684 -0.431809 -27.3914 +-104.459 5.35659 150.877 -103.97 5.75974 151.749 +26.4602 -4.3649 -47.9262 27.5891 -3.84358 -47.645 +-79.5844 4.06074 151.553 -78.8397 4.47889 152.18 +-89.9433 -0.358331 129.444 -89.0697 0.40373 130.363 +35.2378 2.78821 83.3293 35.7317 3.54001 83.8245 +-63.6407 3.85854 156.201 -62.8175 4.6206 156.957 +-52.417 0.662088 85.2841 -52.1008 1.22622 85.6003 +28.8764 9.55553 78.609 29.2414 11.4205 78.974 +26.798 7.25127 76.5676 31.3977 9.95336 81.0953 +-103.748 7.63938 151.284 -103.295 8.45091 151.971 +-48.2221 0.926543 116.358 -47.7995 1.53015 116.788 +-98.2016 5.29954 147.551 -97.3829 5.69423 148.49 +-76.9039 1.65354 103.901 -76.5879 2.21767 104.217 +-73.2034 2.10119 146.112 -72.4598 2.51934 146.737 +-71.7116 2.75546 72.2857 -71.1879 3.15625 72.7983 +-71.7171 2.54898 72.2809 -71.1948 2.96103 72.7935 +-71.6125 2.61641 72.3036 -71.3673 3.10201 72.5502 +-71.682 2.61777 72.3672 -71.4367 3.10338 72.6138 +-71.61 2.95006 72.3783 -71.36 3.20006 72.6283 +-96.8706 0.853393 94.7482 -96.3333 1.27309 95.1357 +-96.8662 0.652831 94.7112 -96.331 1.09537 95.1039 +-96.773 0.710436 94.9034 -96.5277 1.19401 95.1729 +-96.6789 0.715259 94.9047 -96.4337 1.19883 95.1742 +-96.7355 1.05209 94.896 -96.4855 1.30209 95.146 +25.9755 -0.0964843 38.9553 26.6117 0.879986 39.593 +52.8029 1.89 67.6684 53.8975 2.70198 68.4724 +8.69373 1.89083 66.4278 9.18067 2.64263 66.9146 +-115.364 4.64039 160.443 -114.911 5.45191 161.13 +-105.002 5.39395 150.918 -104.489 6.14095 151.578 +37.4668 2.76815 73.5192 38.0582 3.34553 74.0615 +-52.9293 2.0428 93.3519 -52.3528 2.8798 93.9595 +-81.6588 7.30996 96.6813 -81.2491 7.57286 97.4184 +-81.8368 6.89717 96.6251 -81.2785 7.53815 97.0111 +-81.4572 6.9019 96.6539 -81.0225 7.53862 97.1924 +-79.4123 3.21535 150.906 -78.6512 3.6335 151.564 +-62.7459 1.90776 153.049 -61.982 2.32591 153.713 +-53.3794 5.91709 100.842 -53.0629 6.48123 101.159 +-135.821 18.1663 128.228 -135.371 18.6788 128.678 +-137.578 9.33346 126.463 -133.624 13.422 130.441 +8.08555 -3.17861 -27.9549 8.47851 -2.95037 -27.595 +-72.9946 2.55548 145.988 -72.2087 3.30827 146.989 +-70.8936 4.04538 146.62 -70.2727 4.46353 147.361 +35.8339 2.7868 74.0928 36.2149 3.12169 74.4227 +35.9416 2.78826 73.7713 36.3224 3.12412 74.1027 +35.779 2.78096 73.7984 36.3783 3.03907 74.3971 +35.753 2.78697 74.0044 36.1071 3.12106 74.3769 +35.7533 2.78769 73.8521 36.0839 3.12347 74.2326 +36.0733 2.78711 73.9597 36.4034 3.12053 74.3426 +35.7975 2.78836 73.7709 36.1719 3.12414 74.1263 +36.0497 2.78762 73.8153 36.4038 3.12287 74.1911 +35.9852 2.78674 74.0692 36.3592 3.12148 74.4225 +-63.0898 2.55964 154.448 -62.3259 2.97779 155.111 +-110.916 -0.599745 149.069 -110.431 0.182118 149.765 +-77.8587 0.672161 103.652 -76.9986 1.52497 104.526 +-78.0687 1.22297 103.703 -77.5444 2.11264 104.513 +-40.2207 -1.51663 151.981 -39.4805 -1.25372 152.381 +-40.2763 -1.92942 152.012 -39.8838 -1.28844 152.567 +-40.2492 -1.92469 151.749 -39.7146 -1.28796 152.19 +12.1458 -3.19608 -22.6366 12.5242 -2.96816 -22.3013 +-71.444 3.19979 146.374 -70.7931 3.95258 147.387 +-68.1487 3.21535 147.432 -67.491 3.6335 148.193 +-80.064 2.76071 153.16 -79.3708 3.17885 153.937 +-63.3171 1.90615 154.814 -62.5889 2.44779 155.36 +14.8514 1.94457 -29.1893 15.1944 3.58757 -28.8463 +12.9814 -0.0537876 -31.0292 16.997 2.31735 -27.0784 +-80.2488 2.56699 154.38 -79.4943 2.98514 155.024 +-67.5147 1.91591 158.586 -66.572 2.67797 159.555 +-51.2855 5.81504 85.3546 -50.9696 6.37918 85.6705 +-139.947 2.89263 84.8668 -139.348 3.39238 85.2395 +-77.2343 1.6604 103.602 -76.7279 1.98064 104.148 +-33.035 0.359628 59.8875 -32.3224 0.777776 60.4661 +-19.5713 0.828071 62.0347 -19.2118 1.27718 62.3942 +54.4546 2.79458 71.988 54.8356 3.12947 72.3179 +54.5623 2.79604 71.6665 54.9431 3.1319 71.9979 +54.3997 2.78874 71.6936 54.999 3.04685 72.2923 +54.3737 2.79475 71.8996 54.7279 3.12884 72.2722 +54.374 2.79547 71.7473 54.7046 3.13125 72.1279 +54.694 2.79489 71.8549 55.0241 3.12831 72.2378 +54.4182 2.79614 71.6662 54.7926 3.13192 72.0216 +54.6704 2.7954 71.7106 55.0245 3.13065 72.0864 +54.6059 2.79452 71.9644 54.9799 3.12926 72.3178 +-72.6168 1.56735 88.1756 -72.0921 2.40435 88.7422 +19.4478 2.43072 76.2224 20.4826 3.11412 76.5533 +18.6443 2.43342 76.2743 19.7651 2.70942 76.6114 +17.9175 2.43578 76.3306 18.9872 3.12567 76.6639 +17.661 1.90052 76.2304 18.2976 3.20043 76.8306 +20.115 1.90052 76.053 20.7516 3.20043 76.6532 +-70.9392 3.85167 146.603 -70.2871 4.26981 147.362 +-77.3921 -0.36095 161.666 -76.3311 0.491857 162.721 +-76.8964 0.189857 161.573 -76.1532 1.07952 162.433 +-4.0087 1.86728 68.066 -3.4625 2.29748 68.6608 +17.6166 -1.09192 84.8779 18.288 -0.402903 85.5492 +-35.4267 1.62106 57.0799 -34.938 2.18786 57.5701 +-102.844 6.88741 151.547 -102.359 7.66927 152.242 +-79.8031 3.40906 152.462 -79.1761 3.82721 153.206 +-126.905 8.86291 86.5696 -126.306 9.36266 86.9423 +-7.83712 4.03027 96.1544 -7.35019 4.78207 96.6411 +-66.7506 3.20784 158.721 -66.2109 3.74949 159.448 +-22.2036 -4.11 2.96977 -21.1105 -3.29802 3.79769 +36.6923 2.78663 83.6172 37.335 3.7631 84.2757 +-109.516 1.64569 149.61 -109.063 2.45721 150.297 +-123.063 10.3629 87.6846 -122.464 10.8627 88.0572 +9.33004 -4.1 -36.2346 10.2503 -3.40775 -35.4196 +-22.7052 -2.03145 5.2287 -22.0617 -1.05498 5.86594 +-41.6397 -1.51663 151.569 -40.8995 -1.25372 151.969 +-41.6952 -1.92942 151.6 -41.3028 -1.28844 152.155 +-41.6682 -1.92469 151.337 -41.1335 -1.28796 151.778 +-50.7753 1.62925 57.3142 -50.4584 2.19338 57.6311 +-35.9573 1.62925 57.2013 -35.5337 2.23286 57.6323 +-50.1243 0.6921 89.5903 -49.6657 1.03204 89.9992 +-50.0512 0.693302 89.5968 -49.6823 0.945479 89.9603 +-50.0587 0.73807 89.5907 -49.7119 1.03171 89.8738 +-50.1302 0.686074 89.634 -49.7556 1.03805 89.9924 +-71.5384 0.138385 68.398 -70.6266 0.633067 69.1432 +-48.5034 1.04179 117.799 -48.1163 1.44371 118.218 +-48.5203 1.03892 117.8 -48.1279 1.45255 118.225 +-48.5224 1.04179 117.783 -48.1353 1.44371 118.202 +-48.4951 1.04179 117.806 -48.108 1.44371 118.225 +35.4274 2.78986 72.7825 35.8083 3.12475 73.1124 +35.535 2.79132 72.4611 35.9159 3.12717 72.7924 +35.3725 2.78402 72.4881 35.9717 3.04212 73.0869 +35.3464 2.79002 72.6941 35.7006 3.12412 73.0667 +35.3467 2.79075 72.5418 35.6773 3.12653 72.9224 +35.6668 2.79017 72.6494 35.9968 3.12359 73.0323 +35.3909 2.79142 72.4607 35.7653 3.12719 72.8161 +35.6432 2.79067 72.5051 35.9972 3.12593 72.8809 +35.5786 2.7898 72.7589 35.9527 3.12454 73.1123 +-166.357 1.7066 92.8729 -165.138 3.41897 94.116 +8.88498 -1.17383 -59.115 9.27142 0.408008 -58.6385 +8.75985 0.0181358 -59.04 9.34111 0.579176 -58.4786 +8.78429 -0.248723 -59.0103 9.26192 0.227294 -58.5343 +8.58549 -1.17383 -59.2357 9.11498 0.292704 -58.885 +8.49238 -0.104836 -59.3213 9.09483 0.495678 -58.7128 +8.5384 -0.391684 -59.3272 9.0144 0.0843159 -58.8512 +8.88498 -1.17383 -59.1802 9.27985 0.619145 -58.885 +8.94257 0.228067 -59.2656 9.54739 0.829118 -58.6533 +8.96853 0.0211835 -59.1998 9.44549 0.497653 -58.7156 +8.88498 -1.17383 -59.5097 9.20309 0.314797 -58.885 +8.84061 -0.0250154 -59.4903 9.42318 0.556259 -58.9035 +8.84466 -0.222477 -59.4703 9.3255 0.255133 -58.985 +8.73974 -1.17383 -59.4268 9.11498 0.6873 -58.885 +8.62121 0.320799 -59.5233 9.22369 0.922132 -58.914 +8.69768 0.0881433 -59.4029 9.17588 0.564627 -58.9219 +8.77935 -1.1744 -59.1176 9.10223 0.76381 -58.6738 +8.54655 0.356291 -59.1628 9.19709 0.997127 -58.5059 +8.57772 0.11607 -59.1476 9.05372 0.59207 -58.6716 +8.88498 -1.17383 -59.1667 9.14896 1.06722 -58.885 +8.71461 0.681712 -59.3727 9.35461 1.32171 -58.7327 +8.7915 0.478833 -59.284 9.2675 0.954834 -58.808 +-49.1528 0.883546 91.1535 -48.7252 1.13573 91.7781 +-53.462 0.661011 90.6803 -53.0307 0.92086 91.0876 +-53.5897 0.661011 90.5569 -53.1583 0.92086 90.9641 +-53.6389 0.647077 90.5036 -52.9823 0.899257 91.1508 +-1.4487 -4.73989 13.1113 -0.905466 -4.37865 13.5707 +-1.49579 -4.7368 13.279 -0.93055 -4.37676 13.767 +-1.2941 -4.79644 13.1992 -0.990211 -4.54852 13.6755 +-1.38432 -4.79597 13.1721 -1.08043 -4.54805 13.6485 +-1.25397 -4.73944 13.0912 -1.00397 -4.48944 13.3412 +54.0979 2.76075 74.9033 54.7113 3.33813 75.411 +-44.6791 -1.41182 144.147 -44.3065 -0.912072 144.746 +7.85089 -5.12593 -41.0735 8.50962 -4.48703 -40.1537 +7.96697 -4.76158 -40.8267 8.39354 -3.51208 -40.4002 +-80.0645 3.86703 153.304 -79.3035 4.28517 153.961 +-109.528 0.150417 149.607 -109.075 0.961942 150.293 +-68.2126 1.91512 147.497 -67.4694 2.33326 148.121 +45.5628 1.88946 79.6041 46.205 2.86594 80.2495 +-85.614 0.888575 104.844 -85.1293 1.67044 105.54 +-52.891 0.47047 93.6516 -52.2665 1.34247 94.3686 +-72.4295 2.55935 146.215 -71.7736 2.9775 146.975 +9.24008 -3.16595 -29.9307 9.61222 -2.93803 -29.6054 +-2.79241 7.30908 105.434 -2.24165 9.20872 105.846 +-2.71411 8.77713 105.328 -2.06727 9.4208 105.975 +-2.74066 8.46084 105.42 -2.19976 9.00059 105.961 +-2.96213 7.30908 105.609 -2.55551 9.0669 106.205 +-3.09955 8.62251 105.616 -2.38553 9.31828 106.326 +-2.98061 8.2943 105.631 -2.4242 8.83629 106.183 +-2.7927 7.30709 105.286 -2.53417 9.4566 105.833 +-3.01932 9.0317 105.061 -2.32277 9.72445 105.758 +-2.92419 8.77472 105.167 -2.3598 9.31636 105.723 +-3.04265 7.30784 105.366 -2.55999 9.13654 105.848 +-3.28156 8.71169 105.161 -2.59141 9.37943 105.846 +-3.15145 8.48304 105.255 -2.59557 9.02334 105.807 +-3.18566 7.30908 105.609 -2.55551 9.55225 106.002 +-3.33212 9.14323 105.438 -2.62714 9.83749 106.141 +-3.18863 8.85683 105.485 -2.62802 9.39961 106.043 +-2.7777 7.3076 105.609 -2.33199 9.64932 106.016 +-2.86487 9.19534 105.485 -2.11868 9.93665 106.231 +-2.78102 8.90005 105.577 -2.21863 9.43999 106.14 +-2.88805 7.30975 105.499 -2.54843 10.0167 105.854 +-3.14249 9.58847 105.245 -2.39475 10.3297 105.992 +-3.02783 9.33943 105.362 -2.48273 9.87892 105.907 +-62.6273 3.40171 153.024 -62.0372 3.81986 153.747 +27.3624 -3.19867 30.0588 27.9404 -2.83729 30.6137 +-139.947 5.86291 84.8668 -139.348 6.36266 85.2395 +23.015 -0.235213 -30.1758 23.5089 0.516584 -29.6806 +-63.1821 2.55964 154.761 -62.4181 2.97779 155.424 +19.4659 -4.1 -31.0226 20.3952 -3.40776 -30.0105 +-49.7708 4.60829 85.9389 -48.9312 5.53053 86.7794 +-30.7312 0.0881764 151.84 -30.3585 0.587928 152.439 +-105.877 -1.36604 151.705 -104.91 -0.991423 152.697 +11.1179 -3.1593 -22.1831 11.4776 -2.71019 -21.8234 +-133.056 2.31109 93.4595 -132.446 2.8395 93.9536 +-133.105 1.824 92.8617 -132.741 2.62094 93.2131 +-133.39 1.60545 92.8843 -132.78 2.13386 93.3784 +-133.39 2.31109 92.8843 -132.78 2.8395 93.3784 +-133.056 1.60545 93.4595 -132.446 2.13386 93.9536 +-132.771 1.82401 93.4369 -132.407 2.62094 93.7883 +-132.747 1.63067 92.6494 -132.086 1.98374 93.4869 +-132.644 1.66771 93.2384 -132.068 2.1195 93.7128 +-132.466 1.72357 93.2898 -132.11 2.72138 93.6728 +-133.003 1.80097 92.8312 -132.355 2.64397 93.7276 +-132.644 2.32545 93.2384 -132.068 2.77724 93.7128 +-132.747 2.4612 92.6494 -132.086 2.81428 93.4869 +-132.33 1.66771 93.1555 -131.811 2.77724 93.5985 +-132.977 2.32545 92.7038 -132.469 2.7684 93.1391 +-132.977 1.67654 92.7038 -132.469 2.11949 93.1391 +-53.4269 0.647077 90.4151 -52.9955 0.906926 90.8224 +-53.2849 0.647077 90.5378 -52.8693 0.906926 90.9449 +-53.4749 0.633143 90.3659 -52.8183 0.885323 91.0131 +14.2499 -2.46969 -13.314 14.8913 -1.94836 -12.2495 +-72.966 1.56735 90.0329 -72.3255 2.40435 90.6752 +27.9222 1.87047 76.418 28.6776 2.36564 76.9118 +-70.7697 2.75546 71.4253 -70.246 3.15625 71.938 +-70.7752 2.54898 71.4206 -70.2528 2.96103 71.9332 +-70.6706 2.61641 71.4433 -70.4253 3.10201 71.6899 +-70.74 2.61777 71.5069 -70.4948 3.10338 71.7535 +-70.6681 2.95006 71.518 -70.4181 3.20006 71.768 +53.1322 2.79383 67.0448 53.5132 3.12872 67.3747 +53.2399 2.79528 66.7233 53.6207 3.13114 67.0547 +53.0773 2.78799 66.7504 53.6766 3.04609 67.3491 +53.0513 2.79399 66.9564 53.4055 3.12809 67.329 +53.0516 2.79471 66.8041 53.3822 3.1305 67.1846 +53.3716 2.79414 66.9117 53.7017 3.12756 67.2946 +53.0958 2.79539 66.7229 53.4702 3.13116 67.0784 +53.348 2.79464 66.7674 53.7021 3.1299 67.1432 +53.2835 2.79377 67.0212 53.6575 3.12851 67.3746 +-62.5659 2.00753 129.614 -62.1567 2.40832 130.146 +-62.5642 1.80104 129.606 -62.1561 2.21309 130.147 +-62.3655 1.86848 129.786 -62.1156 2.35408 130.024 +-62.3834 1.86984 129.693 -62.1335 2.35544 129.932 +-62.4332 2.20213 129.744 -62.1832 2.45213 129.994 +-116.663 2.38653 159.996 -116.179 3.16839 160.692 +-167.311 2.70329 102.807 -166.679 3.09724 103.369 +-85.5388 0.145278 104.866 -85.086 0.956802 105.553 +-72.5916 0.596116 163.058 -72.1775 0.936057 163.518 +-72.5809 0.597318 163.075 -72.2188 0.849494 163.447 +-72.5914 0.642086 163.101 -72.3092 0.935725 163.448 +-72.5497 0.59009 163.153 -72.1885 0.94207 163.526 +-84.9505 0.888575 105.037 -84.4658 1.67044 105.733 +-45.9205 0.678613 85.8888 -45.5113 1.01801 86.2929 +-45.9752 0.664679 85.6977 -45.5097 0.916859 86.3401 +-68.672 3.40906 158.328 -68.0451 3.82721 159.073 +53.8864 2.73668 79.5003 54.3664 3.59468 79.9803 +-96.8443 1.06675 88.6034 -96.5103 1.40075 88.9374 +-52.0521 0.662088 85.3476 -51.7358 1.22622 85.6639 +-79.9002 3.20785 153.365 -79.173 3.74949 153.905 +-47.869 1.64494 117.042 -47.4819 2.04686 117.461 +-47.8859 1.64207 117.043 -47.4935 2.0557 117.468 +-47.888 1.64494 117.027 -47.5009 2.04686 117.445 +-47.8607 1.64494 117.049 -47.4736 2.04686 117.468 +-136.909 1.76761 105.649 -135.762 2.30056 107.118 +-67.5781 1.8676 63.4648 -66.9328 2.33945 64.1693 +-164.489 2.66657 92.6892 -163.827 3.08224 93.3011 +20.3864 -4.15673 -47.9241 20.9221 -3.75593 -47.5359 +20.3845 -4.36321 -47.924 20.9212 -3.95116 -47.5369 +20.5705 -4.29578 -47.9735 20.8077 -3.81017 -47.7235 +20.4769 -4.29441 -47.9631 20.7141 -3.80881 -47.7131 +20.523 -3.96212 -47.9089 20.773 -3.71212 -47.6589 +-79.7895 2.56135 152.987 -79.0623 3.10299 153.527 +-105.15 7.63938 150.877 -104.665 8.42124 151.573 +-115.765 3.88991 160.211 -115.24 4.68112 160.919 +-27.5326 -3.21287 0.958625 -26.8258 -2.82249 1.60196 +-63.6296 3.20049 155.845 -62.9015 3.74213 156.391 +27.2171 -4.3649 -47.9576 28.346 -3.84358 -47.6764 +-77.2809 1.66115 103.506 -76.6394 1.91333 104.197 +-63.526 3.85025 155.503 -62.7979 4.39189 156.05 +24.6295 1.88295 72.1163 25.3204 2.57197 72.8073 +-73.1024 1.56735 90.4678 -72.512 2.40435 91.0854 +22.9759 -1.49201 -28.1333 23.4698 -0.740215 -27.6381 +-67.6683 1.91512 147.569 -67.0107 2.33326 148.33 +-67.683 2.10883 147.568 -67.056 2.52698 148.313 +-25.024 0.788874 114.303 -24.5989 1.39248 114.732 +-22.9121 -2.78204 5.27433 -22.4551 -2.4421 5.70493 +-22.8515 -2.78084 5.30009 -22.4764 -2.52866 5.65356 +-22.8246 -2.73607 5.27318 -22.4773 -2.44243 5.57755 +-22.9291 -2.78807 5.30465 -22.5736 -2.43609 5.67263 +-135.98 1.62993 87.2818 -135.176 2.86533 88.5749 +-135.384 2.0042 87.7663 -134.861 3.51123 88.6569 +-135.621 2.49027 87.5652 -134.853 2.88233 89.1357 +-135.789 2.2315 87.4869 -135.021 2.62357 89.0575 +-118.958 1.6388 146.911 -118.463 2.44407 147.627 +-157.67 2.03404 104.805 -157.007 2.44602 105.417 +-71.222 0.107857 68.8134 -70.2838 0.869918 69.7116 +-83.3103 -0.604885 105.648 -82.8256 0.176978 106.344 +-116.762 2.38653 159.855 -116.309 3.19805 160.541 +-110.085 0.893715 149.445 -109.632 1.70524 150.132 +20.6162 -3.10831 -26.712 21.5816 -2.3782 -25.8325 +20.6758 -2.82075 -26.713 21.0777 -2.3097 -25.8441 +19.5465 -4.1 -26.698 20.3976 -3.40776 -25.7451 +-30.7312 3.08818 151.84 -30.3585 3.58793 152.439 +-120.527 1.6388 146.43 -120.086 2.42157 147.094 +28.3875 -2.91359 -48.3765 28.8945 -1.33175 -48.0545 +28.1627 -1.74069 -48.5455 28.7244 -1.18028 -47.9849 +28.3569 -1.98007 -48.5389 28.8355 -1.50402 -48.0459 +28.6645 -2.91359 -48.6378 29.0842 -1.44706 -48.1465 +28.552 -1.84971 -48.784 29.162 -1.24832 -48.1797 +28.5787 -2.11608 -48.6685 29.0589 -1.63965 -48.1911 +28.5552 -2.91455 -48.372 28.8886 -1.12677 -47.9373 +28.3895 -1.50671 -48.3683 29.0035 -0.905284 -47.7627 +28.4565 -1.71528 -48.3329 28.9428 -1.23801 -47.852 +28.6645 -2.91359 -48.3765 29.2561 -1.42496 -47.9654 +28.6525 -1.76447 -48.3866 29.2421 -1.18385 -47.8018 +28.6348 -1.94924 -48.3453 29.1117 -1.4732 -47.8691 +28.6645 -2.91359 -48.4419 29.2322 -1.05246 -48.1465 +28.7231 -1.42316 -48.6244 29.3369 -0.820913 -48.0191 +28.7222 -1.65414 -48.5405 29.2083 -1.17664 -48.0592 +28.5025 -2.91429 -48.5629 28.8989 -0.977195 -48.1562 +28.2968 -1.38807 -48.7737 28.9497 -0.747497 -48.1282 +28.3918 -1.62388 -48.6475 28.8763 -1.14756 -48.1662 +28.6645 -2.91359 -48.3765 28.9364 -0.67254 -48.1011 +28.4023 -1.05871 -48.5223 29.0437 -0.418663 -47.882 +28.579 -1.26093 -48.4598 29.055 -0.784927 -47.9838 +-85.0413 1.64055 105.011 -84.5565 2.42241 105.707 +15.2224 -2.25319 -13.8584 15.6901 -1.85239 -13.3214 +15.2197 -2.45967 -13.8544 15.686 -2.04762 -13.3145 +15.2092 -2.39224 -13.7061 15.458 -1.90663 -13.4642 +15.2504 -2.39087 -13.6214 15.4992 -1.90527 -13.3795 +15.2832 -2.05858 -13.6931 15.5332 -1.80858 -13.4431 +25.1292 -2.91359 -48.3883 25.6475 -1.33175 -48.1124 +25.1176 -1.70985 -48.4351 25.6816 -1.14941 -47.8751 +25.1303 -1.97291 -48.4085 25.6097 -1.49652 -47.9325 +24.8996 -2.91359 -48.3424 25.3592 -1.44706 -47.8854 +24.7273 -1.86191 -48.3287 25.3314 -1.26117 -47.7286 +24.8356 -2.13144 -48.2956 25.3116 -1.65544 -47.8196 +25.1348 -2.91474 -48.539 25.4709 -1.12533 -48.117 +24.9408 -1.50313 -48.7174 25.5461 -0.903103 -48.1171 +24.9976 -1.71096 -48.6237 25.4787 -1.23496 -48.1475 +24.8019 -2.91359 -48.5799 25.3592 -1.42496 -48.1124 +24.7237 -1.77797 -48.7177 25.3119 -1.19677 -48.1364 +24.8275 -1.96157 -48.6311 25.3141 -1.4838 -48.1548 +24.7854 -2.91359 -48.3424 25.3592 -1.05246 -48.1028 +24.5792 -1.44211 -48.5276 25.1844 -0.840968 -47.9275 +24.7051 -1.67332 -48.4668 25.1854 -1.19638 -47.9908 +25.1372 -2.91487 -48.3362 25.4773 -0.97432 -47.9203 +24.922 -1.3825 -48.3425 25.5685 -0.742465 -47.7022 +25.0025 -1.6187 -48.2978 25.4839 -1.14267 -47.8216 +24.9931 -2.9131 -48.3886 25.3635 -0.676148 -48.1042 +24.6844 -1.07156 -48.5931 25.3258 -0.431405 -47.9531 +24.8722 -1.26556 -48.5045 25.355 -0.789054 -48.0284 +22.8277 -1.49201 -31.2213 23.3216 -0.740215 -30.7261 +-80.3284 4.06074 154.249 -79.5837 4.47889 154.876 +-57.4624 0.782944 71.2267 -56.9281 1.18374 71.6246 +-57.4624 0.576459 71.228 -56.9236 0.988511 71.6249 +-57.3444 0.643893 71.4203 -57.1067 1.1295 71.6703 +-57.2513 0.645257 71.4065 -57.0135 1.13086 71.6564 +-57.3119 0.977545 71.3542 -57.0619 1.22755 71.6042 +-84.2456 -0.604885 105.415 -83.7609 0.176978 106.111 +-8.61253 3.74673 73.9905 -8.21763 4.14753 74.5252 +-8.61271 3.54025 73.9907 -8.21884 3.9523 74.5289 +-8.65937 3.60768 74.1073 -8.4094 4.09329 74.3449 +-8.64662 3.60905 74.2006 -8.39665 4.09465 74.4382 +-8.59379 3.94133 74.1405 -8.34379 4.19133 74.3905 +-67.7097 2.56699 147.557 -67.0521 2.98514 148.318 +-24.7792 0.178628 113.273 -23.6775 0.990611 113.975 +-2.64947 -3.37867 -24.9884 -1.09598 -2.89552 -23.49 +-23.2039 -3.21514 -3.67569 -22.4383 -2.27445 -3.09185 +-22.8026 -3.20243 -3.58327 -21.5451 -2.57629 -3.13206 +22.2848 6.54288 54.8839 22.6569 6.83888 55.2384 +22.1342 5.90034 54.7341 22.8087 6.6371 55.4006 +22.9803 -0.235213 -31.663 23.4742 0.516584 -31.1679 +-57.1294 -0.0856024 70.4946 -55.793 0.302954 71.7392 +-119.164 0.888735 146.805 -118.644 1.69321 147.501 +26.2065 2.42021 46.7532 27.1843 3.10361 47.3229 +25.4635 2.42291 47.0309 26.5208 2.69891 47.634 +24.7912 2.42526 47.3321 25.8013 3.11516 47.9154 +24.5602 1.89 47.4897 25.1766 3.18992 48.1067 +26.8297 1.89 46.5395 27.4461 3.18992 47.1566 +-47.2116 1.62925 56.8459 -46.7831 2.23286 57.2738 +-0.897276 -5.23564 13.0017 -0.248006 -4.42365 14.1001 +-72.3987 1.56728 86.8747 -71.5721 2.37408 87.7374 +-56.7811 1.43749 70.8593 -56.0206 2.30949 71.5442 +-19.9804 0.821498 62.1118 -19.4681 1.18288 62.6634 +-118.837 0.888795 146.902 -118.341 1.69407 147.618 +-124.984 10.3629 87.1271 -124.385 10.8627 87.4997 +-38.4193 -1.8298 150.882 -37.9312 -1.14639 151.889 +-38.2188 -1.82709 150.109 -37.7067 -1.55109 151.198 +-38.0014 -1.82474 149.409 -37.5036 -1.13484 150.449 +-37.9342 -2.36 149.157 -37.2843 -1.06009 149.768 +-38.62 -2.36 151.52 -37.9701 -1.06009 152.13 +19.6073 -4.975 -39.6982 20.5401 -4.28275 -38.6834 +8.63851 -1.17383 -71.115 9.11499 0.408008 -70.7285 +8.49795 0.0219557 -71.2317 9.06411 0.582039 -70.6506 +8.58423 -0.239023 -71.219 9.06325 0.237051 -70.7259 +8.88499 -1.17383 -71.4145 9.23572 0.292704 -70.885 +8.71012 -0.108572 -71.5292 9.31761 0.492683 -70.9227 +8.85125 -0.391684 -71.4616 9.32725 0.0843159 -70.9856 +8.88499 -1.17383 -71.115 9.18025 0.619145 -70.7201 +8.66025 0.23277 -71.0923 9.27436 0.834305 -70.4831 +8.70974 0.0229921 -71.0491 9.19495 0.500176 -70.5671 +8.88499 -1.17383 -71.115 9.50968 0.314797 -70.7969 +8.90521 -0.0241605 -71.1725 9.49419 0.556594 -70.5859 +8.98208 -0.220765 -71.1779 9.4684 0.257228 -70.6977 +8.88499 -1.17383 -71.2602 9.42677 0.6873 -70.885 +8.91728 0.317733 -71.4182 9.52888 0.919895 -70.809 +8.92049 0.0876084 -71.3137 9.402 0.564491 -70.8333 +8.66703 -1.17414 -71.2413 9.11961 0.761606 -70.8974 +8.46712 0.351337 -71.4597 9.11598 0.991767 -70.8115 +8.5708 0.115238 -71.3291 9.04778 0.591279 -70.8517 +8.88499 -1.17383 -71.115 9.16667 1.06722 -70.851 +8.73273 0.681712 -71.2854 9.37273 1.32171 -70.6454 +8.808 0.478833 -71.2085 9.284 0.954834 -70.7325 +-62.0953 3.83324 129.56 -61.6491 5.41029 130.024 +-62.2549 5.01168 129.624 -61.691 5.5729 130.188 +-62.1962 4.74638 129.635 -61.7191 5.2226 130.111 +-62.0403 3.8352 129.229 -61.6479 5.29168 129.78 +-62.2101 4.89777 129.164 -61.6015 5.49835 129.774 +-62.1503 4.62702 129.289 -61.6709 5.10316 129.767 +-61.8762 3.83443 129.557 -61.5134 5.62609 129.936 +-62.04 5.23864 129.605 -61.4381 5.83867 130.205 +-61.9041 5.03601 129.56 -61.4201 5.5125 130.046 +-61.8779 3.8352 129.318 -61.345 5.3309 129.78 +-61.8884 4.99489 129.345 -61.3053 5.57531 129.927 +-61.7936 4.78942 129.332 -61.3112 5.26753 129.818 +-61.8779 3.8352 129.201 -61.5791 5.69382 129.78 +-62.0675 5.33805 129.196 -61.4638 5.93824 129.798 +-61.939 5.09302 129.233 -61.4544 5.57039 129.716 +-62.1679 3.8352 129.439 -61.6479 5.76002 129.78 +-62.4095 5.34525 129.432 -61.7656 5.98611 130.074 +-62.199 5.12609 129.429 -61.715 5.60324 129.917 +-61.8845 3.8352 129.504 -61.6479 6.07667 129.78 +-62.1679 5.6893 129.397 -61.5247 6.32945 130.038 +-62.0068 5.48822 129.386 -61.5308 5.96422 129.862 +17.9833 -3.1737 -36.037 18.3762 -2.94546 -35.6771 +4.99693 -4.25663 -47.7303 5.75692 -3.99373 -47.4703 +5.33221 -4.66942 -48.022 5.80176 -4.02844 -47.5152 +5.32518 -4.66469 -47.689 5.79863 -4.02797 -47.1789 +-31.8466 -2.11 -2.09883 -31.1266 -1.29645 -1.39777 +23.6031 -4.11 37.7054 24.6896 -3.29802 38.2818 +-71.5008 0.929987 162.998 -70.8073 1.21742 163.571 +-80.2775 2.56699 154.001 -79.5165 2.98514 154.659 +-106.391 -1.1569 155.287 -105.437 -0.762203 156.125 +-24.7456 -2.82288 -3.77248 -24.2656 -1.96488 -3.29248 +-77.7889 0.618702 162.438 -77.1639 0.906138 163.08 +-80.0476 2.56699 153.17 -79.3305 2.98514 153.955 +-50.2035 1.76208 91.0307 -49.6879 2.01426 91.6921 +-8.92767 2.9527 73.0891 -8.08833 3.58078 73.8625 +-8.88148 3.18275 73.0892 -8.49305 3.63558 73.8315 +-75.774 -0.36095 163.158 -74.6773 0.491857 164.255 +-75.9105 0.189857 163.013 -75.071 1.07952 163.831 +-68.1965 2.10883 147.483 -67.4734 2.52698 148.074 +-49.2802 2.4529 91.2295 -48.5444 3.3249 91.8794 +-72.0189 1.56735 84.7068 -70.9178 2.37933 85.3927 +-91.5272 1.10298 164.265 -90.6613 1.86515 165.072 +-35.6275 0.647872 57.5092 -34.5291 1.50068 58.6077 +-35.2135 1.19868 57.9133 -34.3839 2.08835 58.7432 +-11.6464 2.43072 69.1594 -11.3594 3.11412 70.1961 +-11.6581 2.43342 68.3539 -11.3698 2.70942 69.4769 +-11.6687 2.43578 67.6252 -11.3812 3.12567 68.697 +-11.8351 1.90052 67.3671 -11.2234 3.20043 68.0029 +-11.7993 1.90052 69.8273 -11.1876 3.20043 70.4631 +-75.5859 1.63841 162.019 -75.1852 2.23144 162.545 +35.5961 2.79187 84.5056 35.9771 3.12676 84.8355 +35.7038 2.79332 84.1841 36.0846 3.12918 84.5154 +35.5412 2.78603 84.2112 36.1405 3.04413 84.8099 +35.5152 2.79203 84.4172 35.8694 3.12613 84.7897 +35.5155 2.79275 84.2648 35.8461 3.12854 84.6454 +35.8356 2.79217 84.3725 36.1656 3.1256 84.7554 +35.5597 2.79343 84.1837 35.9341 3.1292 84.5391 +35.812 2.79268 84.2281 36.166 3.12793 84.6039 +35.7474 2.79181 84.4819 36.1214 3.12655 84.8353 +-164.142 1.4002 104.493 -163.005 3.11258 105.669 +-12.5079 2.53529 65.1593 -12.1297 2.83129 65.5049 +-12.6622 1.89275 65.0087 -11.9745 2.62952 65.6762 +-103.359 6.88731 151.397 -102.785 7.68561 152.119 +-33.101 1.65986 61.3393 -32.3486 2.07801 62.1272 +14.5321 -3.16826 -28.5689 15.1992 -2.47924 -27.9016 +15.1646 -3.06633 -12.1041 16.115 -2.46837 -11.3136 +15.1557 -3.07283 -12.9768 15.8051 -2.5759 -11.7221 +-49.6029 0.692353 89.536 -49.1579 1.25915 89.9724 +9.04702 -3.1943 -30.4038 9.526 -2.82272 -29.5313 +23.0842 -1.40232 -28.4421 23.4264 -1.07892 -28.0819 +22.8205 -1.40101 -28.6204 23.1642 -1.07674 -28.2602 +22.8446 -1.40758 -28.6309 23.4037 -1.15328 -28.0716 +22.98 -1.40217 -28.3642 23.3463 -1.07949 -28.049 +22.8536 -1.40152 -28.3914 23.2152 -1.07732 -28.049 +23.0332 -1.40204 -28.6538 23.3939 -1.07996 -28.3109 +22.8204 -1.40092 -28.4939 23.1371 -1.07672 -28.1277 +22.8991 -1.40159 -28.6537 23.266 -1.07786 -28.3379 +23.1111 -1.40237 -28.5747 23.4261 -1.07911 -28.2085 +-80.6928 0.672165 100.892 -79.7992 1.52497 101.797 +-80.5995 1.22297 101.437 -79.7837 2.11264 102.005 +-63.1428 4.05338 154.664 -62.3945 4.47153 155.297 +-72.45 -0.36095 166.241 -71.3762 0.491857 167.311 +-72.6212 0.189857 166.555 -71.8582 1.07952 167.414 +-22.2918 -3.00753 -2.98737 -21.7559 -2.60457 -2.60191 +-22.2912 -3.21395 -2.98835 -21.7556 -2.79906 -2.60327 +-22.0825 -3.14515 -3.02902 -21.8461 -2.6596 -2.77805 +-22.1762 -3.14295 -3.03826 -21.9398 -2.6574 -2.78729 +-22.141 -2.8113 -2.97301 -21.891 -2.5613 -2.72301 +-71.5567 0.618702 165.919 -71.1475 0.958097 166.323 +14.7032 -2.4585 -12.3338 14.926 -2.05658 -11.857 +14.7118 -2.46137 -12.3498 14.9346 -2.04774 -11.8648 +14.728 -2.4585 -12.3338 14.9508 -2.05658 -11.857 +14.6924 -2.4585 -12.3338 14.9152 -2.05658 -11.857 +-52.8746 1.4681 92.6243 -52.3459 1.8689 93.1267 +-52.8705 1.26162 92.6199 -52.34 1.67367 93.1193 +-52.6272 1.32905 92.6913 -52.3825 1.81466 92.9383 +-52.7023 1.33042 92.6344 -52.4575 1.81602 92.8814 +-52.7041 1.6627 92.7083 -52.4541 1.9127 92.9583 +50.0868 2.79306 79.8316 50.4678 3.12795 80.1615 +50.1945 2.79452 79.5101 50.5753 3.13038 79.8414 +50.0319 2.78722 79.5372 50.6312 3.04533 80.1359 +50.0059 2.79323 79.7432 50.36 3.12732 80.1157 +50.0062 2.79395 79.5908 50.3368 3.12973 79.9714 +50.3262 2.79337 79.6985 50.6563 3.12679 80.0814 +50.0504 2.79462 79.5097 50.4248 3.1304 79.8651 +50.3026 2.79388 79.5541 50.6567 3.12913 79.9299 +50.2381 2.793 79.8079 50.6121 3.12774 80.1613 +14.7032 -2.4585 -11.9935 14.926 -2.05658 -11.5166 +14.7118 -2.46137 -12.0094 14.9346 -2.04774 -11.5244 +14.728 -2.4585 -11.9935 14.9508 -2.05658 -11.5166 +14.6924 -2.4585 -11.9935 14.9152 -2.05658 -11.5166 +-64.0798 3.84637 157.239 -63.1622 4.50863 157.9 +14.5887 -4.1 -35.1062 15.5841 -3.40776 -34.2034 +-22.4023 -3.22518 -2.78864 -21.7757 -2.83819 -2.09367 +-25.1453 -2.58924 -3.8075 -24.6183 -2.18844 -3.29956 +-25.151 -2.79572 -3.812 -24.625 -2.38367 -3.30454 +-25.0396 -2.72829 -3.79369 -24.7948 -2.24268 -3.54675 +-25.1115 -2.72692 -3.73288 -24.8667 -2.24132 -3.48594 +-25.0403 -2.39464 -3.71871 -24.7903 -2.14464 -3.46871 +8.0707 -3.1824 -29.5189 8.45441 -2.94959 -29.1755 +-80.567 2.56712 154.652 -79.6568 3.32918 155.513 +22.7609 -3.5529 31.1139 23.0388 -2.86949 32.1507 +22.7627 -3.55019 30.3083 23.0408 -3.27419 31.4313 +22.7646 -3.54784 29.5796 23.0426 -2.85794 30.6514 +22.6004 -4.0831 29.3212 23.2153 -2.78318 29.9565 +22.5943 -4.0831 31.7816 23.2092 -2.78318 32.4169 +-139.947 4.36291 84.8668 -139.348 4.86266 85.2395 +-64.1606 2.09806 157.795 -63.4151 2.51621 158.423 +-47.8486 0.926543 115.992 -47.4094 1.53015 116.417 +-71.4566 0.659642 163.276 -70.8009 1.14258 163.904 +-150.54 0.726823 104.475 -149.367 2.4392 105.633 +-124.984 8.86291 87.1271 -124.385 9.36266 87.4997 +-27.5703 -3.21287 0.138151 -26.8635 -2.82249 0.78149 +-62.958 1.90776 154.045 -62.2607 2.32591 154.824 +-68.1979 1.87666 63.4217 -67.5416 2.26366 64.1379 +28.6109 2.73337 48.1104 29.064 2.99628 48.8316 +28.4054 2.32059 48.0863 28.8122 2.96156 48.635 +28.6329 2.32532 48.0559 29.2059 2.96204 48.4163 +-64.1775 3.85626 157.81 -63.4158 4.27441 158.469 +-40.5434 0.647872 54.8903 -39.5414 1.50068 55.8838 +-40.7427 1.19868 54.8455 -40.0739 2.08835 55.6964 +-47.7747 4.60829 86.2379 -46.9803 5.53053 87.0334 +14.3088 -3.17526 -29.9608 14.6646 -2.84037 -29.585 +14.0158 -3.1738 -30.1589 14.3732 -2.83795 -29.7831 +14.0426 -3.1811 -30.1706 14.6393 -2.923 -29.5736 +14.193 -3.1751 -29.8742 14.5756 -2.841 -29.5485 +14.0526 -3.17437 -29.9045 14.4299 -2.83859 -29.5485 +14.2522 -3.17495 -30.196 14.6284 -2.84153 -29.8395 +14.0157 -3.1737 -30.0184 14.3432 -2.83793 -29.636 +14.1031 -3.17444 -30.1959 14.4864 -2.83919 -29.8695 +14.3388 -3.17532 -30.1082 14.6642 -2.84058 -29.7257 +-66.9315 3.20784 147.942 -66.3918 3.74949 148.669 +-8.71114 3.74673 74.7658 -8.23719 4.14753 75.3003 +-8.71435 3.54025 74.759 -8.24328 3.9523 75.2978 +-8.67669 3.60768 74.8185 -8.42837 4.09329 75.0613 +-8.72004 3.60905 74.9021 -8.47172 4.09465 75.1449 +-8.64666 3.94133 74.8849 -8.39666 4.19133 75.1349 +-47.3648 1.62106 56.2291 -46.8979 2.18786 56.6891 +-68.7682 4.06074 158.41 -68.0235 4.47889 159.037 +-2.13429 2.52174 87.9376 -1.70559 3.12902 88.3736 +-28.7801 3.08818 145.117 -28.4074 3.58793 145.716 +-124.984 2.89263 87.1271 -124.385 3.39238 87.4997 +-25.8718 0.449762 16.9784 -25.1406 0.858004 17.6086 +23.1167 -1.49201 -25.8457 23.6106 -0.740215 -25.3506 +20.5104 -3.13224 -29.4686 21.1121 -2.55486 -28.9585 +-133.75 2.59426 91.4009 -133.022 2.93012 92.2635 +53.1451 1.89 78.4689 54.2012 2.58225 79.4496 +-3.20586 -0.0745234 50.1454 -2.52567 0.614495 50.8257 +-96.9545 -1.37266 143.742 -95.6447 -0.137269 144.509 +-97.4287 -0.77109 143.955 -95.8392 -0.379022 144.67 +-97.5018 -0.512326 144.124 -95.9124 -0.120261 144.839 +-97.0123 -0.998398 144.34 -96.1111 0.508637 144.841 +-62.729 4.05338 153.034 -61.9807 4.47153 153.668 +11.8994 -3.12926 -22.4621 12.3381 -2.6727 -21.9936 +11.9221 -3.11503 -23.0799 12.309 -2.65378 -22.7129 +11.3313 -3.19771 -23.1944 12.3702 -2.87361 -21.9317 +11.3925 -3.11831 -22.4183 11.7712 -2.58429 -22.0295 +11.3945 -3.11275 -23.1036 11.7872 -2.6698 -22.7095 +-97.9616 5.5852 150.972 -97.085 5.95677 151.464 +-30.7312 -1.41182 151.84 -30.3585 -0.912072 152.439 +-48.0687 5.81504 85.8355 -47.7542 6.37918 86.1501 +19.6669 -4.73952 -48.0586 20.2027 -4.33656 -47.6731 +19.6674 -4.94594 -48.0595 20.203 -4.53105 -47.6745 +19.8761 -4.87713 -48.1002 20.1126 -4.39158 -47.8492 +19.7824 -4.87493 -48.1095 20.0189 -4.38938 -47.8585 +19.8176 -4.54328 -48.0442 20.0676 -4.29328 -47.7942 +-52.9413 4.59298 99.8445 -52.0989 5.51522 100.688 +-28.8669 -3.20239 -0.724206 -28.2233 -2.22592 -0.0869689 +-105.148 5.39395 150.743 -104.663 6.17581 151.439 +-8.44399 2.83057 74.9836 -7.80682 3.77016 75.7767 +-8.50483 2.85613 74.1122 -7.94367 3.47117 75.366 +-123.063 7.39263 87.6846 -122.464 7.89238 88.0572 +-62.8689 1.81334 130.962 -62.5705 2.21525 131.428 +-62.8583 1.81046 130.949 -62.5575 2.2241 131.423 +-62.8452 1.81334 130.969 -62.5468 2.21525 131.435 +-62.8792 1.81334 130.959 -62.5809 2.21525 131.425 +-9.24777 3.29128 75.8166 -8.71084 3.70188 76.1863 +-9.2437 3.08582 75.8173 -8.70979 3.51074 76.1862 +-9.05022 3.16153 75.7647 -8.80228 3.64688 76.0142 +-9.14429 3.15872 75.761 -8.89635 3.64407 76.0105 +-9.11104 3.49272 75.8218 -8.86104 3.74272 76.0718 +8.95291 -5.24504 13.6833 9.77608 -4.4889 14.6278 +9.24639 -4.8938 13.837 10.1479 -3.71892 14.3508 +-109.128 0.893622 149.723 -108.553 1.69192 150.445 +-64.6105 3.20236 159.191 -63.8311 3.96443 160.034 +-48.993 0.664679 85.7392 -48.677 1.22881 86.0552 +-80.4361 1.64535 104.247 -79.9946 2.21214 104.68 +-97.4593 4.63275 147.151 -96.6125 5.05802 147.882 +-63.4613 4.05338 155.755 -62.713 4.47153 156.388 +-0.959713 -3.44451 -34.9392 -0.618843 -3.14851 -34.5583 +-1.13386 -4.08705 -35.0823 -0.444297 -3.35028 -34.4026 +26.8307 -3.19592 31.07 27.2567 -2.59231 31.5094 +-118.189 0.888795 147.053 -117.664 1.65777 147.732 +18.4313 -0.10192 25.3851 19.1027 0.587098 26.0563 +-52.6568 1.4681 93.7608 -52.2179 1.8689 94.2934 +-52.6527 1.26162 93.7583 -52.216 1.67367 94.3008 +-52.4685 1.32905 93.9858 -52.2192 1.81466 94.2264 +-52.4397 1.33042 93.8961 -52.1904 1.81602 94.1368 +-52.511 1.6627 93.9172 -52.261 1.9127 94.1672 +19.5099 -1.17383 -83.0525 19.8964 0.40801 -82.576 +19.395 0.0174808 -82.9753 19.9767 0.577576 -82.4104 +19.5093 -0.248539 -82.9835 19.9853 0.227461 -82.5075 +19.2105 -1.17383 -83.1732 19.7399 0.292706 -82.8225 +19.1111 -0.105905 -83.2594 19.7157 0.495003 -82.6501 +19.1634 -0.391682 -83.2647 19.6394 0.0843182 -82.7887 +19.5099 -1.17383 -83.1177 19.9048 0.619147 -82.8225 +19.5486 0.230935 -83.2122 20.155 0.832066 -82.6011 +19.5866 0.022072 -83.1327 20.0645 0.49852 -82.652 +19.5099 -1.17383 -83.4472 19.8281 0.3148 -82.8225 +19.4682 -0.0245661 -83.4249 20.0486 0.555708 -82.8428 +19.4626 -0.222927 -83.4123 19.9426 0.254716 -82.9274 +19.3647 -1.17383 -83.3643 19.7399 0.687303 -82.8225 +19.2347 0.319748 -83.4641 19.8417 0.921799 -82.8513 +19.3244 0.0883127 -83.3389 19.8019 0.56504 -82.8572 +19.395 -1.17418 -83.0444 19.7486 0.7629 -82.6077 +19.1726 0.353334 -83.0714 19.8187 0.994339 -82.4181 +19.3015 0.115331 -82.9862 19.779 0.591784 -82.5063 +19.5099 -1.17383 -83.1041 19.7739 1.06722 -82.8225 +19.3396 0.681715 -83.3102 19.9796 1.32171 -82.6702 +19.4165 0.478836 -83.2215 19.8925 0.954836 -82.7455 +-145.242 3.37006 138.861 -144.643 3.86981 139.234 +-77.6964 -0.36095 162.568 -76.6409 0.491857 163.629 +-77.4086 0.189857 163.064 -76.5481 1.07952 163.807 +-62.7116 2.00753 129.955 -62.2976 2.40832 130.487 +-62.7097 1.80104 129.947 -62.2968 2.21309 130.489 +-62.5083 1.86848 130.125 -62.2585 2.35408 130.363 +-62.528 1.86984 130.033 -62.2782 2.35544 130.271 +-62.5767 2.20213 130.085 -62.3267 2.45213 130.335 +-111.133 -0.599745 149.139 -110.62 0.147262 149.799 +6.81897 -4.1 -30.3448 7.92184 -3.28802 -29.6449 +-75.1223 0.681512 95.1797 -74.0787 1.4935 96.1259 +-138.026 4.36291 85.4243 -137.427 4.86266 85.7969 +5.33008 2.48958 107.522 9.34429 7.76614 112.149 +5.39767 -1.37461 107.887 8.32295 2.43845 111.932 +7.3959 1.05914 108.6 10.8151 5.07559 111.169 +-14.4767 2.16159 4.08281 -12.3766 4.44159 6.18281 +4.41652 1.27044 109.843 7.89017 4.38824 113.321 +4.48402 1.31319 106.34 8.01941 4.43895 109.936 +5.17912 0.296239 107.284 9.82008 5.02065 112.358 +5.42557 4.06509 108.284 7.83544 6.66749 110.579 +5.41096 4.06509 109.114 7.82436 6.66749 111.401 +5.24033 6.43677 108.63 8.44497 9.667 111.071 +7.41749 6.09927 108.63 10.931 9.56796 111.11 +5.84488 4.93211 108.74 8.12616 7.80214 110.958 +5.88683 5.42501 108.244 9.48756 10.3068 111.554 +6.32405 8.37867 108.499 9.50327 11.9329 111.226 +6.40815 10.4652 108.501 9.58736 14.0194 111.227 +-14.4767 2.32387 4.08281 -12.3766 4.60386 6.18281 +-16.4947 2.32387 4.08281 -14.3947 4.60386 6.18281 +-16.4947 2.16159 4.08281 -14.3947 4.44159 6.18281 +-55.4808 0.0170624 -5.86851 -53.3808 2.29706 -3.76851 +-55.4808 0.179334 -5.86851 -53.3808 2.45933 -3.76851 +-55.3681 0.179334 -3.85364 -53.2681 2.45933 -1.75364 +-55.3681 0.0170624 -3.85364 -53.2681 2.29706 -1.75364 +58.7314 1.06784 -18.0161 60.8314 3.34784 -15.9161 +58.7314 1.23012 -18.0161 60.8314 3.51011 -15.9161 +59.383 1.23012 -16.1061 61.483 3.51011 -14.0061 +59.383 1.06784 -16.1061 61.483 3.34784 -14.0061 +-4.51484 -0.436063 -18.1134 -2.41484 1.84394 -16.0134 +-40.7008 0.0170624 -8.20066 -38.6008 2.29706 -6.10066 +-40.7008 0.179334 -8.20066 -38.6008 2.45933 -6.10066 +-41.4731 0.179334 -10.0651 -39.3731 2.45933 -7.96507 +-41.4731 0.0170624 -10.0651 -39.3731 2.29706 -7.96507 +-4.51484 -0.273791 -18.1134 -2.41484 2.00621 -16.0134 +-4.51484 -0.273791 -20.1314 -2.41484 2.00621 -18.0314 +-4.51484 -0.436063 -20.1314 -2.41484 1.84394 -18.0314 diff --git a/data/trees/bounds03.txt b/data/trees/bounds03.txt new file mode 100644 index 0000000..323a10d --- /dev/null +++ b/data/trees/bounds03.txt @@ -0,0 +1,268 @@ +-5600 9300 1800 -5400 9600 2100 +-5000 9300 1800 -4800 9600 2100 +-5300 8600 1800 -5100 8900 2100 +-4900 9300 1800 -4700 9600 2100 +-5300 9300 1800 -5100 9600 2100 +-5500 9300 1800 -5300 9600 2100 +-5700 9300 1800 -5500 9600 2100 +-5400 9300 1800 -5200 9600 2100 +-5200 9300 1800 -5000 9600 2100 +-5000 8200 1800 -4700 8600 2200 +-5100 9300 1800 -4900 9600 2100 +3200 -1500 5200 3400 -1300 5400 +3200 700 5200 3400 900 5400 +2100 700 5200 2300 900 5400 +1100 -900 5200 1300 -700 5400 +-1200 0 5200 -1000 200 5400 +-1900 800 5800 -1700 1000 6000 +-1900 -600 5800 -1700 -400 6000 +-1200 -1100 5600 -1000 -900 5800 +-1500 -600 4800 -1300 -400 5000 +-1500 500 4800 -1300 700 5000 +200 500 4800 400 700 5000 +200 -900 4800 400 -700 5000 +1500 -900 4800 1700 -700 5000 +1500 400 4800 1700 600 5000 +3700 -500 4400 3900 -300 4600 +3200 400 4400 3400 600 4600 +2300 200 4200 2500 400 4400 +800 -500 4200 1000 -300 4400 +-2300 -1000 4200 -2100 -800 4400 +-2300 -100 4200 -2100 100 4400 +-2300 800 4200 -2100 1000 4400 +-2300 800 3400 -2100 1000 3600 +-1200 800 3400 -1000 1000 3600 +-1200 -600 3400 -1000 -400 3600 +-2200 -1000 3400 -2000 -800 3600 +500 -100 3400 700 100 3600 +900 700 3400 1100 900 3600 +900 -1100 3400 1100 -900 3600 +900 -1100 3800 1100 -900 4000 +600 900 3800 800 1100 4000 +600 -100 3800 800 100 4000 +900 -1000 2800 1100 -800 3000 +900 0 2800 1100 200 3000 +900 800 2800 1100 1000 3000 +-500 900 2800 -300 1100 3000 +-2300 900 2800 -2100 1100 3000 +-2000 200 3000 -1800 400 3200 +-1500 -1100 3000 -1300 -900 3200 +-2300 -300 3000 -2100 -100 3200 +-3200 -300 3000 -3000 -100 3200 +-3200 -1500 3000 -3000 -1300 3200 +-2900 -2300 3000 -2700 -2100 3200 +-2800 -1100 3400 -2600 -900 3600 +-2700 100 3400 -2500 300 3600 +-2700 1400 3400 -2500 1600 3600 +-3800 1400 3400 -3600 1600 3600 +-3500 2500 3400 -3300 2700 3600 +-2200 1400 3400 -2000 1600 3600 +-1400 1400 3600 -1200 1600 3800 +-1400 2400 3600 -1200 2600 3800 +-1400 3200 3600 -1200 3400 3800 +-1800 3900 3400 -1600 4100 3600 +-2200 3700 3400 -2000 3900 3600 +-1900 4000 3000 -1700 4200 3200 +-1500 3300 3000 -1300 3500 3200 +-2300 3300 3000 -2100 3500 3200 +-2300 2100 2800 -2100 2300 3000 +-2300 1300 2800 -2100 1500 3000 +-3800 1300 3000 -3600 1500 3200 +-2700 1300 3000 -2500 1500 3200 +-2700 1300 2200 -2500 1500 2400 +-3700 1300 2200 -3500 1500 2400 +-3300 -300 2200 -3100 -100 2400 +-3300 -1500 2200 -3100 -1300 2400 +-4500 300 2200 -4300 500 2400 +-4500 -2100 2200 -4300 -1900 2400 +-4500 -3100 2200 -4300 -2900 2400 +-4500 -3300 1800 -4300 -3100 2000 +-3200 -4800 2300 -3000 -4600 2500 +-3200 -5800 2300 -3000 -5600 2500 +-2300 -6300 2300 -2100 -6100 2500 +-2300 -5300 2300 -2100 -5100 2500 +-3100 -5700 2700 -2900 -5500 2900 +-2800 -5700 3100 -2600 -5500 3300 +-2400 -7100 3100 -2200 -6900 3300 +-1600 -7100 3100 -1400 -6900 3300 +-1300 -6500 3100 -1100 -6300 3300 +-1300 -5100 3100 -1100 -4900 3300 +-1800 -4500 3100 -1600 -4300 3300 +-2600 -4500 3100 -2400 -4300 3300 +-600 -1600 3400 -400 -1400 3600 +300 -1700 3800 500 -1500 4000 +-200 -2000 4400 0 -1800 4600 +-6000 -1200 2200 -5800 -1000 2400 +-7000 -1200 2200 -6800 -1000 2400 +-6500 -1800 1800 -6300 -1600 2000 +-6500 600 1800 -6300 800 2000 +-6700 1400 1800 -6500 1600 2000 +-6300 2600 1800 -6100 2800 2000 +-6300 2600 2200 -6100 2800 2400 +-6800 2600 2200 -6600 2800 2400 +-6300 1000 2200 -6100 1200 2400 +-6400 3600 2200 -6200 3800 2400 +-6800 3900 2200 -6600 4100 2400 +-6800 4400 2200 -6600 4600 2400 +-6800 4400 1800 -6600 4600 2000 +-6900 3800 1800 -6700 4000 2000 +-7500 3800 1800 -7300 4000 2000 +-7500 3300 1400 -7300 3500 1600 +-4600 4500 1800 -4400 4700 2000 +-4600 4100 2200 -4400 4300 2400 +-4300 3600 1800 -4100 3800 2000 +-4500 2400 2200 -4300 2600 2400 +-4700 3600 2600 -4500 3800 2800 +-4000 3600 2800 -3800 3800 3000 +-2800 2600 2600 -2600 2800 2800 +-2000 4500 3000 -1800 4700 3200 +100 1400 4200 300 1600 4400 +3600 700 4400 3800 900 4600 +6200 -4600 6500 6400 -4400 6700 +100 200 6800 300 400 7000 +100 -400 6800 300 -200 7000 +300 -400 6000 500 -200 6200 +300 500 6000 500 700 6200 +1100 500 6000 1300 700 6200 +-2300 -1600 3400 -2100 -1400 3600 +-1200 -1600 3400 -1000 -1400 3600 +-1600 -4300 2300 -1400 -4100 2500 +-2900 -4300 2300 -2700 -4100 2500 +-3400 -7300 2300 -3200 -7100 2500 +-4700 -7300 1800 -4500 -7100 2000 +-4700 -6000 1800 -4500 -5800 2000 +-4700 -4700 1800 -4500 -4500 2000 +-5900 -4100 1800 -5700 -3900 2000 +-5900 -6100 1800 -5700 -5900 2000 +-5900 -7400 1800 -5700 -7200 2000 +-6900 -3000 1800 -6700 -2800 2000 +-6900 -100 1800 -6700 100 2000 +-6100 200 1800 -5900 400 2000 +-5800 900 1800 -5600 1100 2000 +-5800 1800 1800 -5600 2000 2000 +-5900 2800 1800 -5700 3000 2000 +-6100 4300 1800 -5900 4500 2000 +-6100 5900 1800 -5900 6100 2000 +-6100 7200 1800 -5900 7400 2000 +-4900 7200 1800 -4700 7400 2000 +-4800 6200 1800 -4600 6400 2000 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 +-100 -100 -100 100 100 100 diff --git a/extern/glad/include/KHR/khrplatform.h b/extern/glad/include/KHR/khrplatform.h new file mode 100644 index 0000000..0164644 --- /dev/null +++ b/extern/glad/include/KHR/khrplatform.h @@ -0,0 +1,311 @@ +#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_ */ diff --git a/extern/glad/include/glad/glad.h b/extern/glad/include/glad/glad.h new file mode 100644 index 0000000..e43afbd --- /dev/null +++ b/extern/glad/include/glad/glad.h @@ -0,0 +1,4133 @@ +/* + + OpenGL loader generated by glad 0.1.36 on Sat Apr 12 17:00:07 2025. + + Language/Generator: C/C++ + Specification: gl + APIs: gl=4.1 + Profile: compatibility + Extensions: + + Loader: True + Local files: False + Omit khrplatform: False + Reproducible: False + + Commandline: + --profile="compatibility" --api="gl=4.1" --generator="c" --spec="gl" --extensions="" + Online: + https://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&loader=on&api=gl%3D4.1 +*/ + + +#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 +#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 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/extern/glad/src/glad.c b/extern/glad/src/glad.c new file mode 100644 index 0000000..aeb93ce --- /dev/null +++ b/extern/glad/src/glad.c @@ -0,0 +1,2121 @@ +/* + + OpenGL loader generated by glad 0.1.36 on Sat Apr 12 17:00:07 2025. + + Language/Generator: C/C++ + Specification: gl + APIs: gl=4.1 + Profile: compatibility + Extensions: + + Loader: True + Local files: False + Omit khrplatform: False + Reproducible: False + + Commandline: + --profile="compatibility" --api="gl=4.1" --generator="c" --spec="gl" --extensions="" + Online: + https://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&loader=on&api=gl%3D4.1 +*/ + +#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 { + 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 < 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; +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; +PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation = NULL; +PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glad_glBindFragDataLocationIndexed = NULL; +PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer = NULL; +PFNGLBINDPROGRAMPIPELINEPROC glad_glBindProgramPipeline = NULL; +PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer = NULL; +PFNGLBINDSAMPLERPROC glad_glBindSampler = NULL; +PFNGLBINDTEXTUREPROC glad_glBindTexture = NULL; +PFNGLBINDTRANSFORMFEEDBACKPROC glad_glBindTransformFeedback = NULL; +PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray = 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; +PFNGLBUFFERDATAPROC glad_glBufferData = NULL; +PFNGLBUFFERSUBDATAPROC glad_glBufferSubData = NULL; +PFNGLCALLLISTPROC glad_glCallList = NULL; +PFNGLCALLLISTSPROC glad_glCallLists = NULL; +PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus = NULL; +PFNGLCLAMPCOLORPROC glad_glClampColor = NULL; +PFNGLCLEARPROC glad_glClear = NULL; +PFNGLCLEARACCUMPROC glad_glClearAccum = 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; +PFNGLCLEARSTENCILPROC glad_glClearStencil = NULL; +PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture = NULL; +PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync = 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; +PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData = 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; +PFNGLCREATEPROGRAMPROC glad_glCreateProgram = NULL; +PFNGLCREATESHADERPROC glad_glCreateShader = NULL; +PFNGLCREATESHADERPROGRAMVPROC glad_glCreateShaderProgramv = NULL; +PFNGLCULLFACEPROC glad_glCullFace = 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; +PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray = NULL; +PFNGLDISABLEIPROC glad_glDisablei = NULL; +PFNGLDRAWARRAYSPROC glad_glDrawArrays = NULL; +PFNGLDRAWARRAYSINDIRECTPROC glad_glDrawArraysIndirect = NULL; +PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced = 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; +PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex = NULL; +PFNGLDRAWPIXELSPROC glad_glDrawPixels = NULL; +PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements = NULL; +PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex = NULL; +PFNGLDRAWTRANSFORMFEEDBACKPROC glad_glDrawTransformFeedback = NULL; +PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC glad_glDrawTransformFeedbackStream = NULL; +PFNGLEDGEFLAGPROC glad_glEdgeFlag = NULL; +PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer = NULL; +PFNGLEDGEFLAGVPROC glad_glEdgeFlagv = NULL; +PFNGLENABLEPROC glad_glEnable = NULL; +PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState = 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; +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; +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; +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; +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; +PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v = NULL; +PFNGLGETINTEGER64VPROC glad_glGetInteger64v = NULL; +PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v = NULL; +PFNGLGETINTEGERVPROC glad_glGetIntegerv = 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; +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; +PFNGLGETPROGRAMPIPELINEINFOLOGPROC glad_glGetProgramPipelineInfoLog = NULL; +PFNGLGETPROGRAMPIPELINEIVPROC glad_glGetProgramPipelineiv = NULL; +PFNGLGETPROGRAMSTAGEIVPROC glad_glGetProgramStageiv = NULL; +PFNGLGETPROGRAMIVPROC glad_glGetProgramiv = 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; +PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying = 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; +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; +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; +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; +PFNGLMATERIALFPROC glad_glMaterialf = NULL; +PFNGLMATERIALFVPROC glad_glMaterialfv = NULL; +PFNGLMATERIALIPROC glad_glMateriali = NULL; +PFNGLMATERIALIVPROC glad_glMaterialiv = NULL; +PFNGLMATRIXMODEPROC glad_glMatrixMode = 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; +PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements = NULL; +PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex = 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; +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; +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; +PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple = NULL; +PFNGLPOPATTRIBPROC glad_glPopAttrib = NULL; +PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib = 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; +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; +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; +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; +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; +PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D = NULL; +PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D = NULL; +PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D = 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; +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; +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; +PFNGLVERTEXATTRIBDIVISORPROC glad_glVertexAttribDivisor = 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; +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; +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; +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 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; + if (GLVersion.major > 4 || (GLVersion.major >= 4 && GLVersion.minor >= 1)) { + max_loaded_major = 4; + max_loaded_minor = 1; + } +} + +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); + + if (!find_extensionsGL()) return 0; + return GLVersion.major != 0 || GLVersion.minor != 0; +} + diff --git a/extern/stb/stb_image.h b/extern/stb/stb_image.h new file mode 100644 index 0000000..5e807a0 --- /dev/null +++ b/extern/stb/stb_image.h @@ -0,0 +1,7987 @@ +/* stb_image - v2.28 - public domain image loader - http://nothings.org/stb + no warranty implied; use at your own risk + + Do this: + #define STB_IMAGE_IMPLEMENTATION + before you include this file in *one* C or C++ file to create the implementation. + + // i.e. it should look like this: + #include ... + #include ... + #include ... + #define STB_IMAGE_IMPLEMENTATION + #include "stb_image.h" + + You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. + And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free + + + QUICK NOTES: + Primarily of interest to game developers and other people who can + avoid problematic images and only need the trivial interface + + JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) + PNG 1/2/4/8/16-bit-per-channel + + TGA (not sure what subset, if a subset) + BMP non-1bpp, non-RLE + PSD (composited view only, no extra channels, 8/16 bit-per-channel) + + GIF (*comp always reports as 4-channel) + HDR (radiance rgbE format) + PIC (Softimage PIC) + PNM (PPM and PGM binary only) + + Animated GIF still needs a proper API, but here's one way to do it: + http://gist.github.com/urraka/685d9a6340b26b830d49 + + - decode from memory or through FILE (define STBI_NO_STDIO to remove code) + - decode from arbitrary I/O callbacks + - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) + + Full documentation under "DOCUMENTATION" below. + + +LICENSE + + See end of file for license information. + +RECENT REVISION HISTORY: + + 2.28 (2023-01-29) many error fixes, security errors, just tons of stuff + 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes + 2.26 (2020-07-13) many minor fixes + 2.25 (2020-02-02) fix warnings + 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically + 2.23 (2019-08-11) fix clang static analysis warning + 2.22 (2019-03-04) gif fixes, fix warnings + 2.21 (2019-02-25) fix typo in comment + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings + 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes + 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 + RGB-format JPEG; remove white matting in PSD; + allocate large structures on the stack; + correct channel count for PNG & BMP + 2.10 (2016-01-22) avoid warning introduced in 2.09 + 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED + + See end of file for full revision history. + + + ============================ Contributors ========================= + + Image formats Extensions, features + Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) + Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) + Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) + Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) + Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) + Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) + Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) + github:urraka (animated gif) Junggon Kim (PNM comments) + Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) + socks-the-fox (16-bit PNG) + Jeremy Sawicki (handle all ImageNet JPGs) + Optimizations & bugfixes Mikhail Morozov (1-bit BMP) + Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) + Arseny Kapoulkine Simon Breuss (16-bit PNM) + John-Mark Allen + Carmelo J Fdez-Aguera + + Bug & warning fixes + Marc LeBlanc David Woo Guillaume George Martins Mozeiko + Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski + Phil Jordan Dave Moore Roy Eltham + Hayaki Saito Nathan Reed Won Chun + Luke Graham Johan Duparc Nick Verigakis the Horde3D community + Thomas Ruf Ronny Chevalier github:rlyeh + Janez Zemva John Bartholomew Michal Cichon github:romigrou + Jonathan Blow Ken Hamada Tero Hanninen github:svdijk + Eugene Golushkov Laurent Gomila Cort Stratton github:snagar + Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex + Cass Everitt Ryamond Barbiero github:grim210 + Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw + Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus + Josh Tobin Neil Bickford Matthew Gregan github:poppolopoppo + Julian Raschke Gregory Mullen Christian Floisand github:darealshinji + Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007 + Brad Weinberger Matvey Cherevko github:mosra + Luca Sas Alexander Veselov Zack Middleton [reserved] + Ryan C. Gordon [reserved] [reserved] + DO NOT ADD YOUR NAME HERE + + Jacko Dirks + + To add your name to the credits, pick a random blank space in the middle and fill it. + 80% of merge conflicts on stb PRs are due to people adding their name at the end + of the credits. +*/ + +#ifndef STBI_INCLUDE_STB_IMAGE_H +#define STBI_INCLUDE_STB_IMAGE_H + +// DOCUMENTATION +// +// Limitations: +// - no 12-bit-per-channel JPEG +// - no JPEGs with arithmetic coding +// - GIF always returns *comp=4 +// +// Basic usage (see HDR discussion below for HDR usage): +// int x,y,n; +// unsigned char *data = stbi_load(filename, &x, &y, &n, 0); +// // ... process data if not NULL ... +// // ... x = width, y = height, n = # 8-bit components per pixel ... +// // ... replace '0' with '1'..'4' to force that many components per pixel +// // ... but 'n' will always be the number that it would have been if you said 0 +// stbi_image_free(data); +// +// Standard parameters: +// int *x -- outputs image width in pixels +// int *y -- outputs image height in pixels +// int *channels_in_file -- outputs # of image components in image file +// int desired_channels -- if non-zero, # of image components requested in result +// +// The return value from an image loader is an 'unsigned char *' which points +// to the pixel data, or NULL on an allocation failure or if the image is +// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, +// with each pixel consisting of N interleaved 8-bit components; the first +// pixel pointed to is top-left-most in the image. There is no padding between +// image scanlines or between pixels, regardless of format. The number of +// components N is 'desired_channels' if desired_channels is non-zero, or +// *channels_in_file otherwise. If desired_channels is non-zero, +// *channels_in_file has the number of components that _would_ have been +// output otherwise. E.g. if you set desired_channels to 4, you will always +// get RGBA output, but you can check *channels_in_file to see if it's trivially +// opaque because e.g. there were only 3 channels in the source image. +// +// An output image with N components has the following components interleaved +// in this order in each pixel: +// +// N=#comp components +// 1 grey +// 2 grey, alpha +// 3 red, green, blue +// 4 red, green, blue, alpha +// +// If image loading fails for any reason, the return value will be NULL, +// and *x, *y, *channels_in_file will be unchanged. The function +// stbi_failure_reason() can be queried for an extremely brief, end-user +// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS +// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly +// more user-friendly ones. +// +// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. +// +// To query the width, height and component count of an image without having to +// decode the full file, you can use the stbi_info family of functions: +// +// int x,y,n,ok; +// ok = stbi_info(filename, &x, &y, &n); +// // returns ok=1 and sets x, y, n if image is a supported format, +// // 0 otherwise. +// +// Note that stb_image pervasively uses ints in its public API for sizes, +// including sizes of memory buffers. This is now part of the API and thus +// hard to change without causing breakage. As a result, the various image +// loaders all have certain limits on image size; these differ somewhat +// by format but generally boil down to either just under 2GB or just under +// 1GB. When the decoded image would be larger than this, stb_image decoding +// will fail. +// +// Additionally, stb_image will reject image files that have any of their +// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS, +// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit, +// the only way to have an image with such dimensions load correctly +// is for it to have a rather extreme aspect ratio. Either way, the +// assumption here is that such larger images are likely to be malformed +// or malicious. If you do need to load an image with individual dimensions +// larger than that, and it still fits in the overall size limit, you can +// #define STBI_MAX_DIMENSIONS on your own to be something larger. +// +// =========================================================================== +// +// UNICODE: +// +// If compiling for Windows and you wish to use Unicode filenames, compile +// with +// #define STBI_WINDOWS_UTF8 +// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert +// Windows wchar_t filenames to utf8. +// +// =========================================================================== +// +// Philosophy +// +// stb libraries are designed with the following priorities: +// +// 1. easy to use +// 2. easy to maintain +// 3. good performance +// +// Sometimes I let "good performance" creep up in priority over "easy to maintain", +// and for best performance I may provide less-easy-to-use APIs that give higher +// performance, in addition to the easy-to-use ones. Nevertheless, it's important +// to keep in mind that from the standpoint of you, a client of this library, +// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. +// +// Some secondary priorities arise directly from the first two, some of which +// provide more explicit reasons why performance can't be emphasized. +// +// - Portable ("ease of use") +// - Small source code footprint ("easy to maintain") +// - No dependencies ("ease of use") +// +// =========================================================================== +// +// I/O callbacks +// +// I/O callbacks allow you to read from arbitrary sources, like packaged +// files or some other source. Data read from callbacks are processed +// through a small internal buffer (currently 128 bytes) to try to reduce +// overhead. +// +// The three functions you must define are "read" (reads some bytes of data), +// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). +// +// =========================================================================== +// +// SIMD support +// +// The JPEG decoder will try to automatically use SIMD kernels on x86 when +// supported by the compiler. For ARM Neon support, you must explicitly +// request it. +// +// (The old do-it-yourself SIMD API is no longer supported in the current +// code.) +// +// On x86, SSE2 will automatically be used when available based on a run-time +// test; if not, the generic C versions are used as a fall-back. On ARM targets, +// the typical path is to have separate builds for NEON and non-NEON devices +// (at least this is true for iOS and Android). Therefore, the NEON support is +// toggled by a build flag: define STBI_NEON to get NEON loops. +// +// If for some reason you do not want to use any of SIMD code, or if +// you have issues compiling it, you can disable it entirely by +// defining STBI_NO_SIMD. +// +// =========================================================================== +// +// HDR image support (disable by defining STBI_NO_HDR) +// +// stb_image supports loading HDR images in general, and currently the Radiance +// .HDR file format specifically. You can still load any file through the existing +// interface; if you attempt to load an HDR file, it will be automatically remapped +// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; +// both of these constants can be reconfigured through this interface: +// +// stbi_hdr_to_ldr_gamma(2.2f); +// stbi_hdr_to_ldr_scale(1.0f); +// +// (note, do not use _inverse_ constants; stbi_image will invert them +// appropriately). +// +// Additionally, there is a new, parallel interface for loading files as +// (linear) floats to preserve the full dynamic range: +// +// float *data = stbi_loadf(filename, &x, &y, &n, 0); +// +// If you load LDR images through this interface, those images will +// be promoted to floating point values, run through the inverse of +// constants corresponding to the above: +// +// stbi_ldr_to_hdr_scale(1.0f); +// stbi_ldr_to_hdr_gamma(2.2f); +// +// Finally, given a filename (or an open file or memory block--see header +// file for details) containing image data, you can query for the "most +// appropriate" interface to use (that is, whether the image is HDR or +// not), using: +// +// stbi_is_hdr(char *filename); +// +// =========================================================================== +// +// iPhone PNG support: +// +// We optionally support converting iPhone-formatted PNGs (which store +// premultiplied BGRA) back to RGB, even though they're internally encoded +// differently. To enable this conversion, call +// stbi_convert_iphone_png_to_rgb(1). +// +// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per +// pixel to remove any premultiplied alpha *only* if the image file explicitly +// says there's premultiplied data (currently only happens in iPhone images, +// and only if iPhone convert-to-rgb processing is on). +// +// =========================================================================== +// +// ADDITIONAL CONFIGURATION +// +// - You can suppress implementation of any of the decoders to reduce +// your code footprint by #defining one or more of the following +// symbols before creating the implementation. +// +// STBI_NO_JPEG +// STBI_NO_PNG +// STBI_NO_BMP +// STBI_NO_PSD +// STBI_NO_TGA +// STBI_NO_GIF +// STBI_NO_HDR +// STBI_NO_PIC +// STBI_NO_PNM (.ppm and .pgm) +// +// - You can request *only* certain decoders and suppress all other ones +// (this will be more forward-compatible, as addition of new decoders +// doesn't require you to disable them explicitly): +// +// STBI_ONLY_JPEG +// STBI_ONLY_PNG +// STBI_ONLY_BMP +// STBI_ONLY_PSD +// STBI_ONLY_TGA +// STBI_ONLY_GIF +// STBI_ONLY_HDR +// STBI_ONLY_PIC +// STBI_ONLY_PNM (.ppm and .pgm) +// +// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still +// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB +// +// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater +// than that size (in either width or height) without further processing. +// This is to let programs in the wild set an upper bound to prevent +// denial-of-service attacks on untrusted data, as one could generate a +// valid image of gigantic dimensions and force stb_image to allocate a +// huge block of memory and spend disproportionate time decoding it. By +// default this is set to (1 << 24), which is 16777216, but that's still +// very big. + +#ifndef STBI_NO_STDIO +#include +#endif // STBI_NO_STDIO + +#define STBI_VERSION 1 + +enum +{ + STBI_default = 0, // only used for desired_channels + + STBI_grey = 1, + STBI_grey_alpha = 2, + STBI_rgb = 3, + STBI_rgb_alpha = 4 +}; + +#include +typedef unsigned char stbi_uc; +typedef unsigned short stbi_us; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef STBIDEF +#ifdef STB_IMAGE_STATIC +#define STBIDEF static +#else +#define STBIDEF extern +#endif +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// PRIMARY API - works on images of any type +// + +// +// load image by filename, open file, or memory buffer +// + +typedef struct +{ + int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read + void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative + int (*eof) (void *user); // returns nonzero if we are at end of file/data +} stbi_io_callbacks; + +//////////////////////////////////// +// +// 8-bits-per-channel interface +// + +STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +// for stbi_load_from_file, file pointer is left pointing immediately after image +#endif + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +#endif + +#ifdef STBI_WINDOWS_UTF8 +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); +#endif + +//////////////////////////////////// +// +// 16-bits-per-channel interface +// + +STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +#endif + +//////////////////////////////////// +// +// float-per-channel interface +// +#ifndef STBI_NO_LINEAR + STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + + #ifndef STBI_NO_STDIO + STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); + #endif +#endif + +#ifndef STBI_NO_HDR + STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); + STBIDEF void stbi_hdr_to_ldr_scale(float scale); +#endif // STBI_NO_HDR + +#ifndef STBI_NO_LINEAR + STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); + STBIDEF void stbi_ldr_to_hdr_scale(float scale); +#endif // STBI_NO_LINEAR + +// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename); +STBIDEF int stbi_is_hdr_from_file(FILE *f); +#endif // STBI_NO_STDIO + + +// get a VERY brief reason for failure +// on most compilers (and ALL modern mainstream compilers) this is threadsafe +STBIDEF const char *stbi_failure_reason (void); + +// free the loaded image -- this is just free() +STBIDEF void stbi_image_free (void *retval_from_stbi_load); + +// get image dimensions & components without fully decoding +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit (char const *filename); +STBIDEF int stbi_is_16_bit_from_file(FILE *f); +#endif + + + +// for image formats that explicitly notate that they have premultiplied alpha, +// we just return the colors as stored in the file. set this flag to force +// unpremultiplication. results are undefined if the unpremultiply overflow. +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); + +// indicate whether we should process iphone images back to canonical format, +// or just pass them through "as-is" +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); + +// flip the image vertically, so the first pixel in the output array is the bottom left +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); + +// as above, but only applies to images loaded on the thread that calls the function +// this function is only available if your compiler supports thread-local variables; +// calling it will fail to link if your compiler doesn't +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply); +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert); +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); + +// ZLIB client - used by PNG, available for other purposes + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); +STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + +STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + + +#ifdef __cplusplus +} +#endif + +// +// +//// end header file ///////////////////////////////////////////////////// +#endif // STBI_INCLUDE_STB_IMAGE_H + +#ifdef STB_IMAGE_IMPLEMENTATION + +#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ + || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ + || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ + || defined(STBI_ONLY_ZLIB) + #ifndef STBI_ONLY_JPEG + #define STBI_NO_JPEG + #endif + #ifndef STBI_ONLY_PNG + #define STBI_NO_PNG + #endif + #ifndef STBI_ONLY_BMP + #define STBI_NO_BMP + #endif + #ifndef STBI_ONLY_PSD + #define STBI_NO_PSD + #endif + #ifndef STBI_ONLY_TGA + #define STBI_NO_TGA + #endif + #ifndef STBI_ONLY_GIF + #define STBI_NO_GIF + #endif + #ifndef STBI_ONLY_HDR + #define STBI_NO_HDR + #endif + #ifndef STBI_ONLY_PIC + #define STBI_NO_PIC + #endif + #ifndef STBI_ONLY_PNM + #define STBI_NO_PNM + #endif +#endif + +#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) +#define STBI_NO_ZLIB +#endif + + +#include +#include // ptrdiff_t on osx +#include +#include +#include + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +#include // ldexp, pow +#endif + +#ifndef STBI_NO_STDIO +#include +#endif + +#ifndef STBI_ASSERT +#include +#define STBI_ASSERT(x) assert(x) +#endif + +#ifdef __cplusplus +#define STBI_EXTERN extern "C" +#else +#define STBI_EXTERN extern +#endif + + +#ifndef _MSC_VER + #ifdef __cplusplus + #define stbi_inline inline + #else + #define stbi_inline + #endif +#else + #define stbi_inline __forceinline +#endif + +#ifndef STBI_NO_THREAD_LOCALS + #if defined(__cplusplus) && __cplusplus >= 201103L + #define STBI_THREAD_LOCAL thread_local + #elif defined(__GNUC__) && __GNUC__ < 5 + #define STBI_THREAD_LOCAL __thread + #elif defined(_MSC_VER) + #define STBI_THREAD_LOCAL __declspec(thread) + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) + #define STBI_THREAD_LOCAL _Thread_local + #endif + + #ifndef STBI_THREAD_LOCAL + #if defined(__GNUC__) + #define STBI_THREAD_LOCAL __thread + #endif + #endif +#endif + +#if defined(_MSC_VER) || defined(__SYMBIAN32__) +typedef unsigned short stbi__uint16; +typedef signed short stbi__int16; +typedef unsigned int stbi__uint32; +typedef signed int stbi__int32; +#else +#include +typedef uint16_t stbi__uint16; +typedef int16_t stbi__int16; +typedef uint32_t stbi__uint32; +typedef int32_t stbi__int32; +#endif + +// should produce compiler error if size is wrong +typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; + +#ifdef _MSC_VER +#define STBI_NOTUSED(v) (void)(v) +#else +#define STBI_NOTUSED(v) (void)sizeof(v) +#endif + +#ifdef _MSC_VER +#define STBI_HAS_LROTL +#endif + +#ifdef STBI_HAS_LROTL + #define stbi_lrot(x,y) _lrotl(x,y) +#else + #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31))) +#endif + +#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) +// ok +#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) +// ok +#else +#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." +#endif + +#ifndef STBI_MALLOC +#define STBI_MALLOC(sz) malloc(sz) +#define STBI_REALLOC(p,newsz) realloc(p,newsz) +#define STBI_FREE(p) free(p) +#endif + +#ifndef STBI_REALLOC_SIZED +#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) +#endif + +// x86/x64 detection +#if defined(__x86_64__) || defined(_M_X64) +#define STBI__X64_TARGET +#elif defined(__i386) || defined(_M_IX86) +#define STBI__X86_TARGET +#endif + +#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) +// gcc doesn't support sse2 intrinsics unless you compile with -msse2, +// which in turn means it gets to use SSE2 everywhere. This is unfortunate, +// but previous attempts to provide the SSE2 functions with runtime +// detection caused numerous issues. The way architecture extensions are +// exposed in GCC/Clang is, sadly, not really suited for one-file libs. +// New behavior: if compiled with -msse2, we use SSE2 without any +// detection; if not, we don't use it at all. +#define STBI_NO_SIMD +#endif + +#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) +// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET +// +// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the +// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. +// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not +// simultaneously enabling "-mstackrealign". +// +// See https://github.com/nothings/stb/issues/81 for more information. +// +// So default to no SSE2 on 32-bit MinGW. If you've read this far and added +// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. +#define STBI_NO_SIMD +#endif + +#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) +#define STBI_SSE2 +#include + +#ifdef _MSC_VER + +#if _MSC_VER >= 1400 // not VC6 +#include // __cpuid +static int stbi__cpuid3(void) +{ + int info[4]; + __cpuid(info,1); + return info[3]; +} +#else +static int stbi__cpuid3(void) +{ + int res; + __asm { + mov eax,1 + cpuid + mov res,edx + } + return res; +} +#endif + +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name + +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) +{ + int info3 = stbi__cpuid3(); + return ((info3 >> 26) & 1) != 0; +} +#endif + +#else // assume GCC-style if not VC++ +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) + +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) +{ + // If we're even attempting to compile this on GCC/Clang, that means + // -msse2 is on, which means the compiler is allowed to use SSE2 + // instructions at will, and so are we. + return 1; +} +#endif + +#endif +#endif + +// ARM NEON +#if defined(STBI_NO_SIMD) && defined(STBI_NEON) +#undef STBI_NEON +#endif + +#ifdef STBI_NEON +#include +#ifdef _MSC_VER +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name +#else +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) +#endif +#endif + +#ifndef STBI_SIMD_ALIGN +#define STBI_SIMD_ALIGN(type, name) type name +#endif + +#ifndef STBI_MAX_DIMENSIONS +#define STBI_MAX_DIMENSIONS (1 << 24) +#endif + +/////////////////////////////////////////////// +// +// stbi__context struct and start_xxx functions + +// stbi__context structure is our basic context used by all images, so it +// contains all the IO context, plus some basic image information +typedef struct +{ + stbi__uint32 img_x, img_y; + int img_n, img_out_n; + + stbi_io_callbacks io; + void *io_user_data; + + int read_from_callbacks; + int buflen; + stbi_uc buffer_start[128]; + int callback_already_read; + + stbi_uc *img_buffer, *img_buffer_end; + stbi_uc *img_buffer_original, *img_buffer_original_end; +} stbi__context; + + +static void stbi__refill_buffer(stbi__context *s); + +// initialize a memory-decode context +static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) +{ + s->io.read = NULL; + s->read_from_callbacks = 0; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; + s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; +} + +// initialize a callback-based context +static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) +{ + s->io = *c; + s->io_user_data = user; + s->buflen = sizeof(s->buffer_start); + s->read_from_callbacks = 1; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = s->buffer_start; + stbi__refill_buffer(s); + s->img_buffer_original_end = s->img_buffer_end; +} + +#ifndef STBI_NO_STDIO + +static int stbi__stdio_read(void *user, char *data, int size) +{ + return (int) fread(data,1,size,(FILE*) user); +} + +static void stbi__stdio_skip(void *user, int n) +{ + int ch; + fseek((FILE*) user, n, SEEK_CUR); + ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */ + if (ch != EOF) { + ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */ + } +} + +static int stbi__stdio_eof(void *user) +{ + return feof((FILE*) user) || ferror((FILE *) user); +} + +static stbi_io_callbacks stbi__stdio_callbacks = +{ + stbi__stdio_read, + stbi__stdio_skip, + stbi__stdio_eof, +}; + +static void stbi__start_file(stbi__context *s, FILE *f) +{ + stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); +} + +//static void stop_file(stbi__context *s) { } + +#endif // !STBI_NO_STDIO + +static void stbi__rewind(stbi__context *s) +{ + // conceptually rewind SHOULD rewind to the beginning of the stream, + // but we just rewind to the beginning of the initial buffer, because + // we only use it after doing 'test', which only ever looks at at most 92 bytes + s->img_buffer = s->img_buffer_original; + s->img_buffer_end = s->img_buffer_original_end; +} + +enum +{ + STBI_ORDER_RGB, + STBI_ORDER_BGR +}; + +typedef struct +{ + int bits_per_channel; + int num_channels; + int channel_order; +} stbi__result_info; + +#ifndef STBI_NO_JPEG +static int stbi__jpeg_test(stbi__context *s); +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNG +static int stbi__png_test(stbi__context *s); +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__png_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_BMP +static int stbi__bmp_test(stbi__context *s); +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_TGA +static int stbi__tga_test(stbi__context *s); +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s); +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__psd_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_HDR +static int stbi__hdr_test(stbi__context *s); +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_test(stbi__context *s); +static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_GIF +static int stbi__gif_test(stbi__context *s); +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNM +static int stbi__pnm_test(stbi__context *s); +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__pnm_is16(stbi__context *s); +#endif + +static +#ifdef STBI_THREAD_LOCAL +STBI_THREAD_LOCAL +#endif +const char *stbi__g_failure_reason; + +STBIDEF const char *stbi_failure_reason(void) +{ + return stbi__g_failure_reason; +} + +#ifndef STBI_NO_FAILURE_STRINGS +static int stbi__err(const char *str) +{ + stbi__g_failure_reason = str; + return 0; +} +#endif + +static void *stbi__malloc(size_t size) +{ + return STBI_MALLOC(size); +} + +// stb_image uses ints pervasively, including for offset calculations. +// therefore the largest decoded image size we can support with the +// current code, even on 64-bit targets, is INT_MAX. this is not a +// significant limitation for the intended use case. +// +// we do, however, need to make sure our size calculations don't +// overflow. hence a few helper functions for size calculations that +// multiply integers together, making sure that they're non-negative +// and no overflow occurs. + +// return 1 if the sum is valid, 0 on overflow. +// negative terms are considered invalid. +static int stbi__addsizes_valid(int a, int b) +{ + if (b < 0) return 0; + // now 0 <= b <= INT_MAX, hence also + // 0 <= INT_MAX - b <= INTMAX. + // And "a + b <= INT_MAX" (which might overflow) is the + // same as a <= INT_MAX - b (no overflow) + return a <= INT_MAX - b; +} + +// returns 1 if the product is valid, 0 on overflow. +// negative factors are considered invalid. +static int stbi__mul2sizes_valid(int a, int b) +{ + if (a < 0 || b < 0) return 0; + if (b == 0) return 1; // mul-by-0 is always safe + // portable way to check for no overflows in a*b + return a <= INT_MAX/b; +} + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow +static int stbi__mad2sizes_valid(int a, int b, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); +} +#endif + +// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow +static int stbi__mad3sizes_valid(int a, int b, int c, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__addsizes_valid(a*b*c, add); +} + +// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) +static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); +} +#endif + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// mallocs with size overflow checking +static void *stbi__malloc_mad2(int a, int b, int add) +{ + if (!stbi__mad2sizes_valid(a, b, add)) return NULL; + return stbi__malloc(a*b + add); +} +#endif + +static void *stbi__malloc_mad3(int a, int b, int c, int add) +{ + if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; + return stbi__malloc(a*b*c + add); +} + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) +static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) +{ + if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; + return stbi__malloc(a*b*c*d + add); +} +#endif + +// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow. +static int stbi__addints_valid(int a, int b) +{ + if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow + if (a < 0 && b < 0) return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0. + return a <= INT_MAX - b; +} + +// returns 1 if the product of two signed shorts is valid, 0 on overflow. +static int stbi__mul2shorts_valid(short a, short b) +{ + if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow + if ((a >= 0) == (b >= 0)) return a <= SHRT_MAX/b; // product is positive, so similar to mul2sizes_valid + if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN + return a >= SHRT_MIN / b; +} + +// stbi__err - error +// stbi__errpf - error returning pointer to float +// stbi__errpuc - error returning pointer to unsigned char + +#ifdef STBI_NO_FAILURE_STRINGS + #define stbi__err(x,y) 0 +#elif defined(STBI_FAILURE_USERMSG) + #define stbi__err(x,y) stbi__err(y) +#else + #define stbi__err(x,y) stbi__err(x) +#endif + +#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) +#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) + +STBIDEF void stbi_image_free(void *retval_from_stbi_load) +{ + STBI_FREE(retval_from_stbi_load); +} + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); +#endif + +#ifndef STBI_NO_HDR +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); +#endif + +static int stbi__vertically_flip_on_load_global = 0; + +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load_global = flag_true_if_should_flip; +} + +#ifndef STBI_THREAD_LOCAL +#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global +#else +static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; + +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load_local = flag_true_if_should_flip; + stbi__vertically_flip_on_load_set = 1; +} + +#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \ + ? stbi__vertically_flip_on_load_local \ + : stbi__vertically_flip_on_load_global) +#endif // STBI_THREAD_LOCAL + +static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields + ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed + ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order + ri->num_channels = 0; + + // test the formats with a very explicit header first (at least a FOURCC + // or distinctive magic number first) + #ifndef STBI_NO_PNG + if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_BMP + if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_GIF + if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PSD + if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc); + #else + STBI_NOTUSED(bpc); + #endif + #ifndef STBI_NO_PIC + if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri); + #endif + + // then the formats that can end up attempting to load with just 1 or 2 + // bytes matching expectations; these are prone to false positives, so + // try them later + #ifndef STBI_NO_JPEG + if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PNM + if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri); + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri); + return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); + } + #endif + + #ifndef STBI_NO_TGA + // test tga last because it's a crappy test! + if (stbi__tga_test(s)) + return stbi__tga_load(s,x,y,comp,req_comp, ri); + #endif + + return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); +} + +static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi_uc *reduced; + + reduced = (stbi_uc *) stbi__malloc(img_len); + if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling + + STBI_FREE(orig); + return reduced; +} + +static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi__uint16 *enlarged; + + enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); + if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff + + STBI_FREE(orig); + return enlarged; +} + +static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) +{ + int row; + size_t bytes_per_row = (size_t)w * bytes_per_pixel; + stbi_uc temp[2048]; + stbi_uc *bytes = (stbi_uc *)image; + + for (row = 0; row < (h>>1); row++) { + stbi_uc *row0 = bytes + row*bytes_per_row; + stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; + // swap row0 with row1 + size_t bytes_left = bytes_per_row; + while (bytes_left) { + size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); + memcpy(temp, row0, bytes_copy); + memcpy(row0, row1, bytes_copy); + memcpy(row1, temp, bytes_copy); + row0 += bytes_copy; + row1 += bytes_copy; + bytes_left -= bytes_copy; + } + } +} + +#ifndef STBI_NO_GIF +static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) +{ + int slice; + int slice_size = w * h * bytes_per_pixel; + + stbi_uc *bytes = (stbi_uc *)image; + for (slice = 0; slice < z; ++slice) { + stbi__vertical_flip(bytes, w, h, bytes_per_pixel); + bytes += slice_size; + } +} +#endif + +static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 8) { + result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 8; + } + + // @TODO: move stbi__convert_format to here + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); + } + + return (unsigned char *) result; +} + +static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 16) { + result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 16; + } + + // @TODO: move stbi__convert_format16 to here + // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); + } + + return (stbi__uint16 *) result; +} + +#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) +static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) +{ + if (stbi__vertically_flip_on_load && result != NULL) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); + } +} +#endif + +#ifndef STBI_NO_STDIO + +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) +STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); +STBI_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); +#endif + +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) +STBIDEF int stbi_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 *stbi__fopen(char const *filename, char const *mode) +{ + FILE *f; +#if defined(_WIN32) && defined(STBI_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; +} + + +STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + unsigned char *result; + if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__uint16 *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + stbi__uint16 *result; + if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file_16(f,x,y,comp,req_comp); + fclose(f); + return result; +} + + +#endif //!STBI_NO_STDIO + +STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +} + +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_mem(&s,buffer,len); + + result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); + if (stbi__vertically_flip_on_load) { + stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); + } + + return result; +} +#endif + +#ifndef STBI_NO_LINEAR +static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *data; + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + stbi__result_info ri; + float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri); + if (hdr_data) + stbi__float_postprocess(hdr_data,x,y,comp,req_comp); + return hdr_data; + } + #endif + data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); + if (data) + return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); + return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); +} + +STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_STDIO +STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + float *result; + FILE *f = stbi__fopen(filename, "rb"); + if (!f) return stbi__errpf("can't fopen", "Unable to open file"); + result = stbi_loadf_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_file(&s,f); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} +#endif // !STBI_NO_STDIO + +#endif // !STBI_NO_LINEAR + +// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is +// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always +// reports false! + +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(buffer); + STBI_NOTUSED(len); + return 0; + #endif +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result=0; + if (f) { + result = stbi_is_hdr_from_file(f); + fclose(f); + } + return result; +} + +STBIDEF int stbi_is_hdr_from_file(FILE *f) +{ + #ifndef STBI_NO_HDR + long pos = ftell(f); + int res; + stbi__context s; + stbi__start_file(&s,f); + res = stbi__hdr_test(&s); + fseek(f, pos, SEEK_SET); + return res; + #else + STBI_NOTUSED(f); + return 0; + #endif +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(clbk); + STBI_NOTUSED(user); + return 0; + #endif +} + +#ifndef STBI_NO_LINEAR +static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; + +STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } +STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } +#endif + +static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; + +STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } +STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } + + +////////////////////////////////////////////////////////////////////////////// +// +// Common code used by all image loaders +// + +enum +{ + STBI__SCAN_load=0, + STBI__SCAN_type, + STBI__SCAN_header +}; + +static void stbi__refill_buffer(stbi__context *s) +{ + int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); + s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original); + if (n == 0) { + // at end of file, treat same as if from memory, but need to handle case + // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file + s->read_from_callbacks = 0; + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start+1; + *s->img_buffer = 0; + } else { + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start + n; + } +} + +stbi_inline static stbi_uc stbi__get8(stbi__context *s) +{ + if (s->img_buffer < s->img_buffer_end) + return *s->img_buffer++; + if (s->read_from_callbacks) { + stbi__refill_buffer(s); + return *s->img_buffer++; + } + return 0; +} + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +stbi_inline static int stbi__at_eof(stbi__context *s) +{ + if (s->io.read) { + if (!(s->io.eof)(s->io_user_data)) return 0; + // if feof() is true, check if buffer = end + // special case: we've only got the special 0 character at the end + if (s->read_from_callbacks == 0) return 1; + } + + return s->img_buffer >= s->img_buffer_end; +} +#endif + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) +// nothing +#else +static void stbi__skip(stbi__context *s, int n) +{ + if (n == 0) return; // already there! + if (n < 0) { + s->img_buffer = s->img_buffer_end; + return; + } + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + s->img_buffer = s->img_buffer_end; + (s->io.skip)(s->io_user_data, n - blen); + return; + } + } + s->img_buffer += n; +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM) +// nothing +#else +static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) +{ + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + int res, count; + + memcpy(buffer, s->img_buffer, blen); + + count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); + res = (count == (n-blen)); + s->img_buffer = s->img_buffer_end; + return res; + } + } + + if (s->img_buffer+n <= s->img_buffer_end) { + memcpy(buffer, s->img_buffer, n); + s->img_buffer += n; + return 1; + } else + return 0; +} +#endif + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else +static int stbi__get16be(stbi__context *s) +{ + int z = stbi__get8(s); + return (z << 8) + stbi__get8(s); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else +static stbi__uint32 stbi__get32be(stbi__context *s) +{ + stbi__uint32 z = stbi__get16be(s); + return (z << 16) + stbi__get16be(s); +} +#endif + +#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) +// nothing +#else +static int stbi__get16le(stbi__context *s) +{ + int z = stbi__get8(s); + return z + (stbi__get8(s) << 8); +} +#endif + +#ifndef STBI_NO_BMP +static stbi__uint32 stbi__get32le(stbi__context *s) +{ + stbi__uint32 z = stbi__get16le(s); + z += (stbi__uint32)stbi__get16le(s) << 16; + return z; +} +#endif + +#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +////////////////////////////////////////////////////////////////////////////// +// +// generic converter from built-in img_n to req_comp +// individual types do this automatically as much as possible (e.g. jpeg +// does all cases internally since it needs to colorspace convert anyway, +// and it never has alpha, so very few cases ). png can automatically +// interleave an alpha=255 channel, but falls back to this for other cases +// +// assume data buffer is malloced, so malloc a new one and free that one +// only failure mode is malloc failing + +static stbi_uc stbi__compute_y(int r, int g, int b) +{ + return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + unsigned char *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0); + if (good == NULL) { + STBI_FREE(data); + return stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + unsigned char *src = data + j * x * img_n ; + unsigned char *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion"); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 stbi__compute_y_16(int r, int g, int b) +{ + return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + stbi__uint16 *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2); + if (good == NULL) { + STBI_FREE(data); + return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + stbi__uint16 *src = data + j * x * img_n ; + stbi__uint16 *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion"); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) +{ + int i,k,n; + float *output; + if (!data) return NULL; + output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); + } + } + if (n < comp) { + for (i=0; i < x*y; ++i) { + output[i*comp + n] = data[i*comp + n]/255.0f; + } + } + STBI_FREE(data); + return output; +} +#endif + +#ifndef STBI_NO_HDR +#define stbi__float2int(x) ((int) (x)) +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) +{ + int i,k,n; + stbi_uc *output; + if (!data) return NULL; + output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + if (k < comp) { + float z = data[i*comp+k] * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + } + STBI_FREE(data); + return output; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// "baseline" JPEG/JFIF decoder +// +// simple implementation +// - doesn't support delayed output of y-dimension +// - simple interface (only one output format: 8-bit interleaved RGB) +// - doesn't try to recover corrupt jpegs +// - doesn't allow partial loading, loading multiple at once +// - still fast on x86 (copying globals into locals doesn't help x86) +// - allocates lots of intermediate memory (full size of all components) +// - non-interleaved case requires this anyway +// - allows good upsampling (see next) +// high-quality +// - upsampled channels are bilinearly interpolated, even across blocks +// - quality integer IDCT derived from IJG's 'slow' +// performance +// - fast huffman; reasonable integer IDCT +// - some SIMD kernels for common paths on targets with SSE2/NEON +// - uses a lot of intermediate memory, could cache poorly + +#ifndef STBI_NO_JPEG + +// huffman decoding acceleration +#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache + +typedef struct +{ + stbi_uc fast[1 << FAST_BITS]; + // weirdly, repacking this into AoS is a 10% speed loss, instead of a win + stbi__uint16 code[256]; + stbi_uc values[256]; + stbi_uc size[257]; + unsigned int maxcode[18]; + int delta[17]; // old 'firstsymbol' - old 'firstcode' +} stbi__huffman; + +typedef struct +{ + stbi__context *s; + stbi__huffman huff_dc[4]; + stbi__huffman huff_ac[4]; + stbi__uint16 dequant[4][64]; + stbi__int16 fast_ac[4][1 << FAST_BITS]; + +// sizes for components, interleaved MCUs + int img_h_max, img_v_max; + int img_mcu_x, img_mcu_y; + int img_mcu_w, img_mcu_h; + +// definition of jpeg image component + struct + { + int id; + int h,v; + int tq; + int hd,ha; + int dc_pred; + + int x,y,w2,h2; + stbi_uc *data; + void *raw_data, *raw_coeff; + stbi_uc *linebuf; + short *coeff; // progressive only + int coeff_w, coeff_h; // number of 8x8 coefficient blocks + } img_comp[4]; + + stbi__uint32 code_buffer; // jpeg entropy-coded buffer + int code_bits; // number of valid bits + unsigned char marker; // marker seen while filling entropy buffer + int nomore; // flag if we saw a marker so must stop + + int progressive; + int spec_start; + int spec_end; + int succ_high; + int succ_low; + int eob_run; + int jfif; + int app14_color_transform; // Adobe APP14 tag + int rgb; + + int scan_n, order[4]; + int restart_interval, todo; + +// kernels + void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); + void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); + stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); +} stbi__jpeg; + +static int stbi__build_huffman(stbi__huffman *h, int *count) +{ + int i,j,k=0; + unsigned int code; + // build size list for each symbol (from JPEG spec) + for (i=0; i < 16; ++i) { + for (j=0; j < count[i]; ++j) { + h->size[k++] = (stbi_uc) (i+1); + if(k >= 257) return stbi__err("bad size list","Corrupt JPEG"); + } + } + h->size[k] = 0; + + // compute actual symbols (from jpeg spec) + code = 0; + k = 0; + for(j=1; j <= 16; ++j) { + // compute delta to add to code to compute symbol id + h->delta[j] = k - code; + if (h->size[k] == j) { + while (h->size[k] == j) + h->code[k++] = (stbi__uint16) (code++); + if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG"); + } + // compute largest code + 1 for this size, preshifted as needed later + h->maxcode[j] = code << (16-j); + code <<= 1; + } + h->maxcode[j] = 0xffffffff; + + // build non-spec acceleration table; 255 is flag for not-accelerated + memset(h->fast, 255, 1 << FAST_BITS); + for (i=0; i < k; ++i) { + int s = h->size[i]; + if (s <= FAST_BITS) { + int c = h->code[i] << (FAST_BITS-s); + int m = 1 << (FAST_BITS-s); + for (j=0; j < m; ++j) { + h->fast[c+j] = (stbi_uc) i; + } + } + } + return 1; +} + +// build a table that decodes both magnitude and value of small ACs in +// one go. +static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) +{ + int i; + for (i=0; i < (1 << FAST_BITS); ++i) { + stbi_uc fast = h->fast[i]; + fast_ac[i] = 0; + if (fast < 255) { + int rs = h->values[fast]; + int run = (rs >> 4) & 15; + int magbits = rs & 15; + int len = h->size[fast]; + + if (magbits && len + magbits <= FAST_BITS) { + // magnitude code followed by receive_extend code + int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); + int m = 1 << (magbits - 1); + if (k < m) k += (~0U << magbits) + 1; + // if the result is small enough, we can fit it in fast_ac table + if (k >= -128 && k <= 127) + fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); + } + } + } +} + +static void stbi__grow_buffer_unsafe(stbi__jpeg *j) +{ + do { + unsigned int b = j->nomore ? 0 : stbi__get8(j->s); + if (b == 0xff) { + int c = stbi__get8(j->s); + while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes + if (c != 0) { + j->marker = (unsigned char) c; + j->nomore = 1; + return; + } + } + j->code_buffer |= b << (24 - j->code_bits); + j->code_bits += 8; + } while (j->code_bits <= 24); +} + +// (1 << n) - 1 +static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; + +// decode a jpeg huffman value from the bitstream +stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) +{ + unsigned int temp; + int c,k; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + // look at the top FAST_BITS and determine what symbol ID it is, + // if the code is <= FAST_BITS + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + k = h->fast[c]; + if (k < 255) { + int s = h->size[k]; + if (s > j->code_bits) + return -1; + j->code_buffer <<= s; + j->code_bits -= s; + return h->values[k]; + } + + // naive test is to shift the code_buffer down so k bits are + // valid, then test against maxcode. To speed this up, we've + // preshifted maxcode left so that it has (16-k) 0s at the + // end; in other words, regardless of the number of bits, it + // wants to be compared against something shifted to have 16; + // that way we don't need to shift inside the loop. + temp = j->code_buffer >> 16; + for (k=FAST_BITS+1 ; ; ++k) + if (temp < h->maxcode[k]) + break; + if (k == 17) { + // error! code not found + j->code_bits -= 16; + return -1; + } + + if (k > j->code_bits) + return -1; + + // convert the huffman code to the symbol id + c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; + if(c < 0 || c >= 256) // symbol id out of bounds! + return -1; + STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); + + // convert the id to a symbol + j->code_bits -= k; + j->code_buffer <<= k; + return h->values[c]; +} + +// bias[n] = (-1<code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing + + sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative) + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k + (stbi__jbias[n] & (sgn - 1)); +} + +// get some unsigned bits +stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) +{ + unsigned int k; + if (j->code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k; +} + +stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) +{ + unsigned int k; + if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); + if (j->code_bits < 1) return 0; // ran out of bits from stream, return 0s intead of continuing + k = j->code_buffer; + j->code_buffer <<= 1; + --j->code_bits; + return k & 0x80000000; +} + +// given a value that's at position X in the zigzag stream, +// where does it appear in the 8x8 matrix coded as row-major? +static const stbi_uc stbi__jpeg_dezigzag[64+15] = +{ + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63, + // let corrupt input sample past end + 63, 63, 63, 63, 63, 63, 63, 63, + 63, 63, 63, 63, 63, 63, 63 +}; + +// decode one 64-entry block-- +static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) +{ + int diff,dc,k; + int t; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0 || t > 15) return stbi__err("bad huffman code","Corrupt JPEG"); + + // 0 all the ac values now so we can do it 32-bits at a time + memset(data,0,64*sizeof(data[0])); + + diff = t ? stbi__extend_receive(j, t) : 0; + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta","Corrupt JPEG"); + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + if (!stbi__mul2shorts_valid(dc, dequant[0])) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + data[0] = (short) (dc * dequant[0]); + + // decode AC components, see JPEG spec + k = 1; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); + j->code_buffer <<= s; + j->code_bits -= s; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) * dequant[zig]); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (rs != 0xf0) break; // end block + k += 16; + } else { + k += r; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]); + } + } + } while (k < 64); + return 1; +} + +static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) +{ + int diff,dc; + int t; + if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + if (j->succ_high == 0) { + // first scan for DC coefficient, must be first + memset(data,0,64*sizeof(data[0])); // 0 all the ac values now + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + diff = t ? stbi__extend_receive(j, t) : 0; + + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta", "Corrupt JPEG"); + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + data[0] = (short) (dc * (1 << j->succ_low)); + } else { + // refinement scan for DC coefficient + if (stbi__jpeg_get_bit(j)) + data[0] += (short) (1 << j->succ_low); + } + return 1; +} + +// @OPTIMIZE: store non-zigzagged during the decode passes, +// and only de-zigzag when dequantizing +static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) +{ + int k; + if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->succ_high == 0) { + int shift = j->succ_low; + + if (j->eob_run) { + --j->eob_run; + return 1; + } + + k = j->spec_start; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); + j->code_buffer <<= s; + j->code_bits -= s; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) * (1 << shift)); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r); + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + --j->eob_run; + break; + } + k += 16; + } else { + k += r; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift)); + } + } + } while (k <= j->spec_end); + } else { + // refinement scan for these AC coefficients + + short bit = (short) (1 << j->succ_low); + + if (j->eob_run) { + --j->eob_run; + for (k = j->spec_start; k <= j->spec_end; ++k) { + short *p = &data[stbi__jpeg_dezigzag[k]]; + if (*p != 0) + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } + } else { + k = j->spec_start; + do { + int r,s; + int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r) - 1; + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + r = 64; // force end of block + } else { + // r=15 s=0 should write 16 0s, so we just do + // a run of 15 0s and then write s (which is 0), + // so we don't have to do anything special here + } + } else { + if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); + // sign bit + if (stbi__jpeg_get_bit(j)) + s = bit; + else + s = -bit; + } + + // advance by r + while (k <= j->spec_end) { + short *p = &data[stbi__jpeg_dezigzag[k++]]; + if (*p != 0) { + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } else { + if (r == 0) { + *p = (short) s; + break; + } + --r; + } + } + } while (k <= j->spec_end); + } + } + return 1; +} + +// take a -128..127 value and stbi__clamp it and convert to 0..255 +stbi_inline static stbi_uc stbi__clamp(int x) +{ + // trick to use a single test to catch both cases + if ((unsigned int) x > 255) { + if (x < 0) return 0; + if (x > 255) return 255; + } + return (stbi_uc) x; +} + +#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) +#define stbi__fsh(x) ((x) * 4096) + +// derived from jidctint -- DCT_ISLOW +#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ + int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ + p2 = s2; \ + p3 = s6; \ + p1 = (p2+p3) * stbi__f2f(0.5411961f); \ + t2 = p1 + p3*stbi__f2f(-1.847759065f); \ + t3 = p1 + p2*stbi__f2f( 0.765366865f); \ + p2 = s0; \ + p3 = s4; \ + t0 = stbi__fsh(p2+p3); \ + t1 = stbi__fsh(p2-p3); \ + x0 = t0+t3; \ + x3 = t0-t3; \ + x1 = t1+t2; \ + x2 = t1-t2; \ + t0 = s7; \ + t1 = s5; \ + t2 = s3; \ + t3 = s1; \ + p3 = t0+t2; \ + p4 = t1+t3; \ + p1 = t0+t3; \ + p2 = t1+t2; \ + p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ + t0 = t0*stbi__f2f( 0.298631336f); \ + t1 = t1*stbi__f2f( 2.053119869f); \ + t2 = t2*stbi__f2f( 3.072711026f); \ + t3 = t3*stbi__f2f( 1.501321110f); \ + p1 = p5 + p1*stbi__f2f(-0.899976223f); \ + p2 = p5 + p2*stbi__f2f(-2.562915447f); \ + p3 = p3*stbi__f2f(-1.961570560f); \ + p4 = p4*stbi__f2f(-0.390180644f); \ + t3 += p1+p4; \ + t2 += p2+p3; \ + t1 += p2+p4; \ + t0 += p1+p3; + +static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) +{ + int i,val[64],*v=val; + stbi_uc *o; + short *d = data; + + // columns + for (i=0; i < 8; ++i,++d, ++v) { + // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing + if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 + && d[40]==0 && d[48]==0 && d[56]==0) { + // no shortcut 0 seconds + // (1|2|3|4|5|6|7)==0 0 seconds + // all separate -0.047 seconds + // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds + int dcterm = d[0]*4; + v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; + } else { + STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) + // constants scaled things up by 1<<12; let's bring them back + // down, but keep 2 extra bits of precision + x0 += 512; x1 += 512; x2 += 512; x3 += 512; + v[ 0] = (x0+t3) >> 10; + v[56] = (x0-t3) >> 10; + v[ 8] = (x1+t2) >> 10; + v[48] = (x1-t2) >> 10; + v[16] = (x2+t1) >> 10; + v[40] = (x2-t1) >> 10; + v[24] = (x3+t0) >> 10; + v[32] = (x3-t0) >> 10; + } + } + + for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { + // no fast case since the first 1D IDCT spread components out + STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) + // constants scaled things up by 1<<12, plus we had 1<<2 from first + // loop, plus horizontal and vertical each scale by sqrt(8) so together + // we've got an extra 1<<3, so 1<<17 total we need to remove. + // so we want to round that, which means adding 0.5 * 1<<17, + // aka 65536. Also, we'll end up with -128 to 127 that we want + // to encode as 0..255 by adding 128, so we'll add that before the shift + x0 += 65536 + (128<<17); + x1 += 65536 + (128<<17); + x2 += 65536 + (128<<17); + x3 += 65536 + (128<<17); + // tried computing the shifts into temps, or'ing the temps to see + // if any were out of range, but that was slower + o[0] = stbi__clamp((x0+t3) >> 17); + o[7] = stbi__clamp((x0-t3) >> 17); + o[1] = stbi__clamp((x1+t2) >> 17); + o[6] = stbi__clamp((x1-t2) >> 17); + o[2] = stbi__clamp((x2+t1) >> 17); + o[5] = stbi__clamp((x2-t1) >> 17); + o[3] = stbi__clamp((x3+t0) >> 17); + o[4] = stbi__clamp((x3-t0) >> 17); + } +} + +#ifdef STBI_SSE2 +// sse2 integer IDCT. not the fastest possible implementation but it +// produces bit-identical results to the generic C version so it's +// fully "transparent". +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + // This is constructed to match our regular (generic) integer IDCT exactly. + __m128i row0, row1, row2, row3, row4, row5, row6, row7; + __m128i tmp; + + // dot product constant: even elems=x, odd elems=y + #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) + + // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) + // out(1) = c1[even]*x + c1[odd]*y + #define dct_rot(out0,out1, x,y,c0,c1) \ + __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ + __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ + __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ + __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ + __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ + __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) + + // out = in << 12 (in 16-bit, out 32-bit) + #define dct_widen(out, in) \ + __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ + __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) + + // wide add + #define dct_wadd(out, a, b) \ + __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_add_epi32(a##_h, b##_h) + + // wide sub + #define dct_wsub(out, a, b) \ + __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) + + // butterfly a/b, add bias, then shift by "s" and pack + #define dct_bfly32o(out0, out1, a,b,bias,s) \ + { \ + __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ + __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ + dct_wadd(sum, abiased, b); \ + dct_wsub(dif, abiased, b); \ + out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ + out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ + } + + // 8-bit interleave step (for transposes) + #define dct_interleave8(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi8(a, b); \ + b = _mm_unpackhi_epi8(tmp, b) + + // 16-bit interleave step (for transposes) + #define dct_interleave16(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi16(a, b); \ + b = _mm_unpackhi_epi16(tmp, b) + + #define dct_pass(bias,shift) \ + { \ + /* even part */ \ + dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ + __m128i sum04 = _mm_add_epi16(row0, row4); \ + __m128i dif04 = _mm_sub_epi16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ + dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ + __m128i sum17 = _mm_add_epi16(row1, row7); \ + __m128i sum35 = _mm_add_epi16(row3, row5); \ + dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ + dct_wadd(x4, y0o, y4o); \ + dct_wadd(x5, y1o, y5o); \ + dct_wadd(x6, y2o, y5o); \ + dct_wadd(x7, y3o, y4o); \ + dct_bfly32o(row0,row7, x0,x7,bias,shift); \ + dct_bfly32o(row1,row6, x1,x6,bias,shift); \ + dct_bfly32o(row2,row5, x2,x5,bias,shift); \ + dct_bfly32o(row3,row4, x3,x4,bias,shift); \ + } + + __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); + __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f)); + __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); + __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); + __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f)); + __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f)); + __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f)); + __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f)); + + // rounding biases in column/row passes, see stbi__idct_block for explanation. + __m128i bias_0 = _mm_set1_epi32(512); + __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17)); + + // load + row0 = _mm_load_si128((const __m128i *) (data + 0*8)); + row1 = _mm_load_si128((const __m128i *) (data + 1*8)); + row2 = _mm_load_si128((const __m128i *) (data + 2*8)); + row3 = _mm_load_si128((const __m128i *) (data + 3*8)); + row4 = _mm_load_si128((const __m128i *) (data + 4*8)); + row5 = _mm_load_si128((const __m128i *) (data + 5*8)); + row6 = _mm_load_si128((const __m128i *) (data + 6*8)); + row7 = _mm_load_si128((const __m128i *) (data + 7*8)); + + // column pass + dct_pass(bias_0, 10); + + { + // 16bit 8x8 transpose pass 1 + dct_interleave16(row0, row4); + dct_interleave16(row1, row5); + dct_interleave16(row2, row6); + dct_interleave16(row3, row7); + + // transpose pass 2 + dct_interleave16(row0, row2); + dct_interleave16(row1, row3); + dct_interleave16(row4, row6); + dct_interleave16(row5, row7); + + // transpose pass 3 + dct_interleave16(row0, row1); + dct_interleave16(row2, row3); + dct_interleave16(row4, row5); + dct_interleave16(row6, row7); + } + + // row pass + dct_pass(bias_1, 17); + + { + // pack + __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 + __m128i p1 = _mm_packus_epi16(row2, row3); + __m128i p2 = _mm_packus_epi16(row4, row5); + __m128i p3 = _mm_packus_epi16(row6, row7); + + // 8bit 8x8 transpose pass 1 + dct_interleave8(p0, p2); // a0e0a1e1... + dct_interleave8(p1, p3); // c0g0c1g1... + + // transpose pass 2 + dct_interleave8(p0, p1); // a0c0e0g0... + dct_interleave8(p2, p3); // b0d0f0h0... + + // transpose pass 3 + dct_interleave8(p0, p2); // a0b0c0d0... + dct_interleave8(p1, p3); // a4b4c4d4... + + // store + _mm_storel_epi64((__m128i *) out, p0); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p2); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p1); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p3); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); + } + +#undef dct_const +#undef dct_rot +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_interleave8 +#undef dct_interleave16 +#undef dct_pass +} + +#endif // STBI_SSE2 + +#ifdef STBI_NEON + +// NEON integer IDCT. should produce bit-identical +// results to the generic C version. +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; + + int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); + int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); + int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f)); + int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f)); + int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); + int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); + int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); + int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); + int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f)); + int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f)); + int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f)); + int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f)); + +#define dct_long_mul(out, inq, coeff) \ + int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) + +#define dct_long_mac(out, acc, inq, coeff) \ + int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) + +#define dct_widen(out, inq) \ + int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ + int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) + +// wide add +#define dct_wadd(out, a, b) \ + int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vaddq_s32(a##_h, b##_h) + +// wide sub +#define dct_wsub(out, a, b) \ + int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vsubq_s32(a##_h, b##_h) + +// butterfly a/b, then shift using "shiftop" by "s" and pack +#define dct_bfly32o(out0,out1, a,b,shiftop,s) \ + { \ + dct_wadd(sum, a, b); \ + dct_wsub(dif, a, b); \ + out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ + out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ + } + +#define dct_pass(shiftop, shift) \ + { \ + /* even part */ \ + int16x8_t sum26 = vaddq_s16(row2, row6); \ + dct_long_mul(p1e, sum26, rot0_0); \ + dct_long_mac(t2e, p1e, row6, rot0_1); \ + dct_long_mac(t3e, p1e, row2, rot0_2); \ + int16x8_t sum04 = vaddq_s16(row0, row4); \ + int16x8_t dif04 = vsubq_s16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + int16x8_t sum15 = vaddq_s16(row1, row5); \ + int16x8_t sum17 = vaddq_s16(row1, row7); \ + int16x8_t sum35 = vaddq_s16(row3, row5); \ + int16x8_t sum37 = vaddq_s16(row3, row7); \ + int16x8_t sumodd = vaddq_s16(sum17, sum35); \ + dct_long_mul(p5o, sumodd, rot1_0); \ + dct_long_mac(p1o, p5o, sum17, rot1_1); \ + dct_long_mac(p2o, p5o, sum35, rot1_2); \ + dct_long_mul(p3o, sum37, rot2_0); \ + dct_long_mul(p4o, sum15, rot2_1); \ + dct_wadd(sump13o, p1o, p3o); \ + dct_wadd(sump24o, p2o, p4o); \ + dct_wadd(sump23o, p2o, p3o); \ + dct_wadd(sump14o, p1o, p4o); \ + dct_long_mac(x4, sump13o, row7, rot3_0); \ + dct_long_mac(x5, sump24o, row5, rot3_1); \ + dct_long_mac(x6, sump23o, row3, rot3_2); \ + dct_long_mac(x7, sump14o, row1, rot3_3); \ + dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ + dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ + dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ + dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ + } + + // load + row0 = vld1q_s16(data + 0*8); + row1 = vld1q_s16(data + 1*8); + row2 = vld1q_s16(data + 2*8); + row3 = vld1q_s16(data + 3*8); + row4 = vld1q_s16(data + 4*8); + row5 = vld1q_s16(data + 5*8); + row6 = vld1q_s16(data + 6*8); + row7 = vld1q_s16(data + 7*8); + + // add DC bias + row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); + + // column pass + dct_pass(vrshrn_n_s32, 10); + + // 16bit 8x8 transpose + { +// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. +// whether compilers actually get this is another story, sadly. +#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } +#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } + + // pass 1 + dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 + dct_trn16(row2, row3); + dct_trn16(row4, row5); + dct_trn16(row6, row7); + + // pass 2 + dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 + dct_trn32(row1, row3); + dct_trn32(row4, row6); + dct_trn32(row5, row7); + + // pass 3 + dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 + dct_trn64(row1, row5); + dct_trn64(row2, row6); + dct_trn64(row3, row7); + +#undef dct_trn16 +#undef dct_trn32 +#undef dct_trn64 + } + + // row pass + // vrshrn_n_s32 only supports shifts up to 16, we need + // 17. so do a non-rounding shift of 16 first then follow + // up with a rounding shift by 1. + dct_pass(vshrn_n_s32, 16); + + { + // pack and round + uint8x8_t p0 = vqrshrun_n_s16(row0, 1); + uint8x8_t p1 = vqrshrun_n_s16(row1, 1); + uint8x8_t p2 = vqrshrun_n_s16(row2, 1); + uint8x8_t p3 = vqrshrun_n_s16(row3, 1); + uint8x8_t p4 = vqrshrun_n_s16(row4, 1); + uint8x8_t p5 = vqrshrun_n_s16(row5, 1); + uint8x8_t p6 = vqrshrun_n_s16(row6, 1); + uint8x8_t p7 = vqrshrun_n_s16(row7, 1); + + // again, these can translate into one instruction, but often don't. +#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } +#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } + + // sadly can't use interleaved stores here since we only write + // 8 bytes to each scan line! + + // 8x8 8-bit transpose pass 1 + dct_trn8_8(p0, p1); + dct_trn8_8(p2, p3); + dct_trn8_8(p4, p5); + dct_trn8_8(p6, p7); + + // pass 2 + dct_trn8_16(p0, p2); + dct_trn8_16(p1, p3); + dct_trn8_16(p4, p6); + dct_trn8_16(p5, p7); + + // pass 3 + dct_trn8_32(p0, p4); + dct_trn8_32(p1, p5); + dct_trn8_32(p2, p6); + dct_trn8_32(p3, p7); + + // store + vst1_u8(out, p0); out += out_stride; + vst1_u8(out, p1); out += out_stride; + vst1_u8(out, p2); out += out_stride; + vst1_u8(out, p3); out += out_stride; + vst1_u8(out, p4); out += out_stride; + vst1_u8(out, p5); out += out_stride; + vst1_u8(out, p6); out += out_stride; + vst1_u8(out, p7); + +#undef dct_trn8_8 +#undef dct_trn8_16 +#undef dct_trn8_32 + } + +#undef dct_long_mul +#undef dct_long_mac +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_pass +} + +#endif // STBI_NEON + +#define STBI__MARKER_none 0xff +// if there's a pending marker from the entropy stream, return that +// otherwise, fetch from the stream and get a marker. if there's no +// marker, return 0xff, which is never a valid marker value +static stbi_uc stbi__get_marker(stbi__jpeg *j) +{ + stbi_uc x; + if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } + x = stbi__get8(j->s); + if (x != 0xff) return STBI__MARKER_none; + while (x == 0xff) + x = stbi__get8(j->s); // consume repeated 0xff fill bytes + return x; +} + +// in each scan, we'll have scan_n components, and the order +// of the components is specified by order[] +#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) + +// after a restart interval, stbi__jpeg_reset the entropy decoder and +// the dc prediction +static void stbi__jpeg_reset(stbi__jpeg *j) +{ + j->code_bits = 0; + j->code_buffer = 0; + j->nomore = 0; + j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; + j->marker = STBI__MARKER_none; + j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; + j->eob_run = 0; + // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, + // since we don't even allow 1<<30 pixels +} + +static int stbi__parse_entropy_coded_data(stbi__jpeg *z) +{ + stbi__jpeg_reset(z); + if (!z->progressive) { + if (z->scan_n == 1) { + int i,j; + STBI_SIMD_ALIGN(short, data[64]); + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + // if it's NOT a restart, then just bail, so we get corrupt data + // rather than no data + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + STBI_SIMD_ALIGN(short, data[64]); + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x)*8; + int y2 = (j*z->img_comp[n].v + y)*8; + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } else { + if (z->scan_n == 1) { + int i,j; + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + if (z->spec_start == 0) { + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } else { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) + return 0; + } + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x); + int y2 = (j*z->img_comp[n].v + y); + short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } +} + +static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) +{ + int i; + for (i=0; i < 64; ++i) + data[i] *= dequant[i]; +} + +static void stbi__jpeg_finish(stbi__jpeg *z) +{ + if (z->progressive) { + // dequantize and idct the data + int i,j,n; + for (n=0; n < z->s->img_n; ++n) { + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + } + } + } + } +} + +static int stbi__process_marker(stbi__jpeg *z, int m) +{ + int L; + switch (m) { + case STBI__MARKER_none: // no marker found + return stbi__err("expected marker","Corrupt JPEG"); + + case 0xDD: // DRI - specify restart interval + if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); + z->restart_interval = stbi__get16be(z->s); + return 1; + + case 0xDB: // DQT - define quantization table + L = stbi__get16be(z->s)-2; + while (L > 0) { + int q = stbi__get8(z->s); + int p = q >> 4, sixteen = (p != 0); + int t = q & 15,i; + if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); + if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); + + for (i=0; i < 64; ++i) + z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); + L -= (sixteen ? 129 : 65); + } + return L==0; + + case 0xC4: // DHT - define huffman table + L = stbi__get16be(z->s)-2; + while (L > 0) { + stbi_uc *v; + int sizes[16],i,n=0; + int q = stbi__get8(z->s); + int tc = q >> 4; + int th = q & 15; + if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); + for (i=0; i < 16; ++i) { + sizes[i] = stbi__get8(z->s); + n += sizes[i]; + } + if(n > 256) return stbi__err("bad DHT header","Corrupt JPEG"); // Loop over i < n would write past end of values! + L -= 17; + if (tc == 0) { + if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; + v = z->huff_dc[th].values; + } else { + if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; + v = z->huff_ac[th].values; + } + for (i=0; i < n; ++i) + v[i] = stbi__get8(z->s); + if (tc != 0) + stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); + L -= n; + } + return L==0; + } + + // check for comment block or APP blocks + if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { + L = stbi__get16be(z->s); + if (L < 2) { + if (m == 0xFE) + return stbi__err("bad COM len","Corrupt JPEG"); + else + return stbi__err("bad APP len","Corrupt JPEG"); + } + L -= 2; + + if (m == 0xE0 && L >= 5) { // JFIF APP0 segment + static const unsigned char tag[5] = {'J','F','I','F','\0'}; + int ok = 1; + int i; + for (i=0; i < 5; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 5; + if (ok) + z->jfif = 1; + } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment + static const unsigned char tag[6] = {'A','d','o','b','e','\0'}; + int ok = 1; + int i; + for (i=0; i < 6; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 6; + if (ok) { + stbi__get8(z->s); // version + stbi__get16be(z->s); // flags0 + stbi__get16be(z->s); // flags1 + z->app14_color_transform = stbi__get8(z->s); // color transform + L -= 6; + } + } + + stbi__skip(z->s, L); + return 1; + } + + return stbi__err("unknown marker","Corrupt JPEG"); +} + +// after we see SOS +static int stbi__process_scan_header(stbi__jpeg *z) +{ + int i; + int Ls = stbi__get16be(z->s); + z->scan_n = stbi__get8(z->s); + if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); + if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); + for (i=0; i < z->scan_n; ++i) { + int id = stbi__get8(z->s), which; + int q = stbi__get8(z->s); + for (which = 0; which < z->s->img_n; ++which) + if (z->img_comp[which].id == id) + break; + if (which == z->s->img_n) return 0; // no match + z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); + z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); + z->order[i] = which; + } + + { + int aa; + z->spec_start = stbi__get8(z->s); + z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 + aa = stbi__get8(z->s); + z->succ_high = (aa >> 4); + z->succ_low = (aa & 15); + if (z->progressive) { + if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) + return stbi__err("bad SOS", "Corrupt JPEG"); + } else { + if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG"); + if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG"); + z->spec_end = 63; + } + } + + return 1; +} + +static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) +{ + int i; + for (i=0; i < ncomp; ++i) { + if (z->img_comp[i].raw_data) { + STBI_FREE(z->img_comp[i].raw_data); + z->img_comp[i].raw_data = NULL; + z->img_comp[i].data = NULL; + } + if (z->img_comp[i].raw_coeff) { + STBI_FREE(z->img_comp[i].raw_coeff); + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].coeff = 0; + } + if (z->img_comp[i].linebuf) { + STBI_FREE(z->img_comp[i].linebuf); + z->img_comp[i].linebuf = NULL; + } + } + return why; +} + +static int stbi__process_frame_header(stbi__jpeg *z, int scan) +{ + stbi__context *s = z->s; + int Lf,p,i,q, h_max=1,v_max=1,c; + Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG + p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline + s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG + s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + c = stbi__get8(s); + if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG"); + s->img_n = c; + for (i=0; i < c; ++i) { + z->img_comp[i].data = NULL; + z->img_comp[i].linebuf = NULL; + } + + if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); + + z->rgb = 0; + for (i=0; i < s->img_n; ++i) { + static const unsigned char rgb[3] = { 'R', 'G', 'B' }; + z->img_comp[i].id = stbi__get8(s); + if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) + ++z->rgb; + q = stbi__get8(s); + z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); + z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); + z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); + } + + if (scan != STBI__SCAN_load) return 1; + + if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); + + for (i=0; i < s->img_n; ++i) { + if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; + if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; + } + + // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios + // and I've never seen a non-corrupted JPEG file actually use them + for (i=0; i < s->img_n; ++i) { + if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H","Corrupt JPEG"); + if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V","Corrupt JPEG"); + } + + // compute interleaved mcu info + z->img_h_max = h_max; + z->img_v_max = v_max; + z->img_mcu_w = h_max * 8; + z->img_mcu_h = v_max * 8; + // these sizes can't be more than 17 bits + z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; + z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; + + for (i=0; i < s->img_n; ++i) { + // number of effective pixels (e.g. for non-interleaved MCU) + z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; + z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; + // to simplify generation, we'll allocate enough memory to decode + // the bogus oversized data from using interleaved MCUs and their + // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't + // discard the extra data until colorspace conversion + // + // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) + // so these muls can't overflow with 32-bit ints (which we require) + z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; + z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; + z->img_comp[i].coeff = 0; + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].linebuf = NULL; + z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); + if (z->img_comp[i].raw_data == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); + // align blocks for idct using mmx/sse + z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); + if (z->progressive) { + // w2, h2 are multiples of 8 (see above) + z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; + z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; + z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); + if (z->img_comp[i].raw_coeff == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); + z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); + } + } + + return 1; +} + +// use comparisons since in some cases we handle more than one case (e.g. SOF) +#define stbi__DNL(x) ((x) == 0xdc) +#define stbi__SOI(x) ((x) == 0xd8) +#define stbi__EOI(x) ((x) == 0xd9) +#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) +#define stbi__SOS(x) ((x) == 0xda) + +#define stbi__SOF_progressive(x) ((x) == 0xc2) + +static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) +{ + int m; + z->jfif = 0; + z->app14_color_transform = -1; // valid values are 0,1,2 + z->marker = STBI__MARKER_none; // initialize cached marker to empty + m = stbi__get_marker(z); + if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); + if (scan == STBI__SCAN_type) return 1; + m = stbi__get_marker(z); + while (!stbi__SOF(m)) { + if (!stbi__process_marker(z,m)) return 0; + m = stbi__get_marker(z); + while (m == STBI__MARKER_none) { + // some files have extra padding after their blocks, so ok, we'll scan + if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); + m = stbi__get_marker(z); + } + } + z->progressive = stbi__SOF_progressive(m); + if (!stbi__process_frame_header(z, scan)) return 0; + return 1; +} + +static int stbi__skip_jpeg_junk_at_end(stbi__jpeg *j) +{ + // some JPEGs have junk at end, skip over it but if we find what looks + // like a valid marker, resume there + while (!stbi__at_eof(j->s)) { + int x = stbi__get8(j->s); + while (x == 255) { // might be a marker + if (stbi__at_eof(j->s)) return STBI__MARKER_none; + x = stbi__get8(j->s); + if (x != 0x00 && x != 0xff) { + // not a stuffed zero or lead-in to another marker, looks + // like an actual marker, return it + return x; + } + // stuffed zero has x=0 now which ends the loop, meaning we go + // back to regular scan loop. + // repeated 0xff keeps trying to read the next byte of the marker. + } + } + return STBI__MARKER_none; +} + +// decode image to YCbCr format +static int stbi__decode_jpeg_image(stbi__jpeg *j) +{ + int m; + for (m = 0; m < 4; m++) { + j->img_comp[m].raw_data = NULL; + j->img_comp[m].raw_coeff = NULL; + } + j->restart_interval = 0; + if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; + m = stbi__get_marker(j); + while (!stbi__EOI(m)) { + if (stbi__SOS(m)) { + if (!stbi__process_scan_header(j)) return 0; + if (!stbi__parse_entropy_coded_data(j)) return 0; + if (j->marker == STBI__MARKER_none ) { + j->marker = stbi__skip_jpeg_junk_at_end(j); + // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 + } + m = stbi__get_marker(j); + if (STBI__RESTART(m)) + m = stbi__get_marker(j); + } else if (stbi__DNL(m)) { + int Ld = stbi__get16be(j->s); + stbi__uint32 NL = stbi__get16be(j->s); + if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); + if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); + m = stbi__get_marker(j); + } else { + if (!stbi__process_marker(j, m)) return 1; + m = stbi__get_marker(j); + } + } + if (j->progressive) + stbi__jpeg_finish(j); + return 1; +} + +// static jfif-centered resampling (across block boundaries) + +typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, + int w, int hs); + +#define stbi__div4(x) ((stbi_uc) ((x) >> 2)) + +static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + STBI_NOTUSED(out); + STBI_NOTUSED(in_far); + STBI_NOTUSED(w); + STBI_NOTUSED(hs); + return in_near; +} + +static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples vertically for every one in input + int i; + STBI_NOTUSED(hs); + for (i=0; i < w; ++i) + out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); + return out; +} + +static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples horizontally for every one in input + int i; + stbi_uc *input = in_near; + + if (w == 1) { + // if only one sample, can't do any interpolation + out[0] = out[1] = input[0]; + return out; + } + + out[0] = input[0]; + out[1] = stbi__div4(input[0]*3 + input[1] + 2); + for (i=1; i < w-1; ++i) { + int n = 3*input[i]+2; + out[i*2+0] = stbi__div4(n+input[i-1]); + out[i*2+1] = stbi__div4(n+input[i+1]); + } + out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); + out[i*2+1] = input[w-1]; + + STBI_NOTUSED(in_far); + STBI_NOTUSED(hs); + + return out; +} + +#define stbi__div16(x) ((stbi_uc) ((x) >> 4)) + +static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i,t0,t1; + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + out[0] = stbi__div4(t1+2); + for (i=1; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i=0,t0,t1; + + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + // process groups of 8 pixels for as long as we can. + // note we can't handle the last pixel in a row in this loop + // because we need to handle the filter boundary conditions. + for (; i < ((w-1) & ~7); i += 8) { +#if defined(STBI_SSE2) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + __m128i zero = _mm_setzero_si128(); + __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); + __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); + __m128i farw = _mm_unpacklo_epi8(farb, zero); + __m128i nearw = _mm_unpacklo_epi8(nearb, zero); + __m128i diff = _mm_sub_epi16(farw, nearw); + __m128i nears = _mm_slli_epi16(nearw, 2); + __m128i curr = _mm_add_epi16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + __m128i prv0 = _mm_slli_si128(curr, 2); + __m128i nxt0 = _mm_srli_si128(curr, 2); + __m128i prev = _mm_insert_epi16(prv0, t1, 0); + __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + __m128i bias = _mm_set1_epi16(8); + __m128i curs = _mm_slli_epi16(curr, 2); + __m128i prvd = _mm_sub_epi16(prev, curr); + __m128i nxtd = _mm_sub_epi16(next, curr); + __m128i curb = _mm_add_epi16(curs, bias); + __m128i even = _mm_add_epi16(prvd, curb); + __m128i odd = _mm_add_epi16(nxtd, curb); + + // interleave even and odd pixels, then undo scaling. + __m128i int0 = _mm_unpacklo_epi16(even, odd); + __m128i int1 = _mm_unpackhi_epi16(even, odd); + __m128i de0 = _mm_srli_epi16(int0, 4); + __m128i de1 = _mm_srli_epi16(int1, 4); + + // pack and write output + __m128i outv = _mm_packus_epi16(de0, de1); + _mm_storeu_si128((__m128i *) (out + i*2), outv); +#elif defined(STBI_NEON) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + uint8x8_t farb = vld1_u8(in_far + i); + uint8x8_t nearb = vld1_u8(in_near + i); + int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); + int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); + int16x8_t curr = vaddq_s16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + int16x8_t prv0 = vextq_s16(curr, curr, 7); + int16x8_t nxt0 = vextq_s16(curr, curr, 1); + int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); + int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + int16x8_t curs = vshlq_n_s16(curr, 2); + int16x8_t prvd = vsubq_s16(prev, curr); + int16x8_t nxtd = vsubq_s16(next, curr); + int16x8_t even = vaddq_s16(curs, prvd); + int16x8_t odd = vaddq_s16(curs, nxtd); + + // undo scaling and round, then store with even/odd phases interleaved + uint8x8x2_t o; + o.val[0] = vqrshrun_n_s16(even, 4); + o.val[1] = vqrshrun_n_s16(odd, 4); + vst2_u8(out + i*2, o); +#endif + + // "previous" value for next iter + t1 = 3*in_near[i+7] + in_far[i+7]; + } + + t0 = t1; + t1 = 3*in_near[i] + in_far[i]; + out[i*2] = stbi__div16(3*t1 + t0 + 8); + + for (++i; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} +#endif + +static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // resample with nearest-neighbor + int i,j; + STBI_NOTUSED(in_far); + for (i=0; i < w; ++i) + for (j=0; j < hs; ++j) + out[i*hs+j] = in_near[i]; + return out; +} + +// this is a reduced-precision calculation of YCbCr-to-RGB introduced +// to make sure the code produces the same results in both SIMD and scalar +#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) +static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) +{ + int i; + for (i=0; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) +{ + int i = 0; + +#ifdef STBI_SSE2 + // step == 3 is pretty ugly on the final interleave, and i'm not convinced + // it's useful in practice (you wouldn't use it for textures, for example). + // so just accelerate step == 4 case. + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + __m128i signflip = _mm_set1_epi8(-0x80); + __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f)); + __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f)); + __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f)); + __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f)); + __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); + __m128i xw = _mm_set1_epi16(255); // alpha channel + + for (; i+7 < count; i += 8) { + // load + __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i)); + __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i)); + __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i)); + __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 + __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 + + // unpack to short (and left-shift cr, cb by 8) + __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); + __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); + __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); + + // color transform + __m128i yws = _mm_srli_epi16(yw, 4); + __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); + __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); + __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); + __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); + __m128i rws = _mm_add_epi16(cr0, yws); + __m128i gwt = _mm_add_epi16(cb0, yws); + __m128i bws = _mm_add_epi16(yws, cb1); + __m128i gws = _mm_add_epi16(gwt, cr1); + + // descale + __m128i rw = _mm_srai_epi16(rws, 4); + __m128i bw = _mm_srai_epi16(bws, 4); + __m128i gw = _mm_srai_epi16(gws, 4); + + // back to byte, set up for transpose + __m128i brb = _mm_packus_epi16(rw, bw); + __m128i gxb = _mm_packus_epi16(gw, xw); + + // transpose to interleave channels + __m128i t0 = _mm_unpacklo_epi8(brb, gxb); + __m128i t1 = _mm_unpackhi_epi8(brb, gxb); + __m128i o0 = _mm_unpacklo_epi16(t0, t1); + __m128i o1 = _mm_unpackhi_epi16(t0, t1); + + // store + _mm_storeu_si128((__m128i *) (out + 0), o0); + _mm_storeu_si128((__m128i *) (out + 16), o1); + out += 32; + } + } +#endif + +#ifdef STBI_NEON + // in this version, step=3 support would be easy to add. but is there demand? + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + uint8x8_t signflip = vdup_n_u8(0x80); + int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f)); + int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f)); + int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f)); + int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f)); + + for (; i+7 < count; i += 8) { + // load + uint8x8_t y_bytes = vld1_u8(y + i); + uint8x8_t cr_bytes = vld1_u8(pcr + i); + uint8x8_t cb_bytes = vld1_u8(pcb + i); + int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); + int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); + + // expand to s16 + int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); + int16x8_t crw = vshll_n_s8(cr_biased, 7); + int16x8_t cbw = vshll_n_s8(cb_biased, 7); + + // color transform + int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); + int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); + int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); + int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); + int16x8_t rws = vaddq_s16(yws, cr0); + int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); + int16x8_t bws = vaddq_s16(yws, cb1); + + // undo scaling, round, convert to byte + uint8x8x4_t o; + o.val[0] = vqrshrun_n_s16(rws, 4); + o.val[1] = vqrshrun_n_s16(gws, 4); + o.val[2] = vqrshrun_n_s16(bws, 4); + o.val[3] = vdup_n_u8(255); + + // store, interleaving r/g/b/a + vst4_u8(out, o); + out += 8*4; + } + } +#endif + + for (; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} +#endif + +// set up the kernels +static void stbi__setup_jpeg(stbi__jpeg *j) +{ + j->idct_block_kernel = stbi__idct_block; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; + +#ifdef STBI_SSE2 + if (stbi__sse2_available()) { + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; + } +#endif + +#ifdef STBI_NEON + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; +#endif +} + +// clean up the temporary component buffers +static void stbi__cleanup_jpeg(stbi__jpeg *j) +{ + stbi__free_jpeg_components(j, j->s->img_n, 0); +} + +typedef struct +{ + resample_row_func resample; + stbi_uc *line0,*line1; + int hs,vs; // expansion factor in each axis + int w_lores; // horizontal pixels pre-expansion + int ystep; // how far through vertical expansion we are + int ypos; // which pre-expansion row we're on +} stbi__resample; + +// fast 0..255 * 0..255 => 0..255 rounded multiplication +static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) +{ + unsigned int t = x*y + 128; + return (stbi_uc) ((t + (t >>8)) >> 8); +} + +static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) +{ + int n, decode_n, is_rgb; + z->s->img_n = 0; // make stbi__cleanup_jpeg safe + + // validate req_comp + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + + // load a jpeg image from whichever source, but leave in YCbCr format + if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } + + // determine actual number of components to generate + n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; + + is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); + + if (z->s->img_n == 3 && n < 3 && !is_rgb) + decode_n = 1; + else + decode_n = z->s->img_n; + + // nothing to do if no components requested; check this now to avoid + // accessing uninitialized coutput[0] later + if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; } + + // resample and color-convert + { + int k; + unsigned int i,j; + stbi_uc *output; + stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL }; + + stbi__resample res_comp[4]; + + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + + // allocate line buffer big enough for upsampling off the edges + // with upsample factor of 4 + z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); + if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + r->hs = z->img_h_max / z->img_comp[k].h; + r->vs = z->img_v_max / z->img_comp[k].v; + r->ystep = r->vs >> 1; + r->w_lores = (z->s->img_x + r->hs-1) / r->hs; + r->ypos = 0; + r->line0 = r->line1 = z->img_comp[k].data; + + if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; + else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; + else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; + else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; + else r->resample = stbi__resample_row_generic; + } + + // can't error after this so, this is safe + output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); + if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + // now go ahead and resample + for (j=0; j < z->s->img_y; ++j) { + stbi_uc *out = output + n * z->s->img_x * j; + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + int y_bot = r->ystep >= (r->vs >> 1); + coutput[k] = r->resample(z->img_comp[k].linebuf, + y_bot ? r->line1 : r->line0, + y_bot ? r->line0 : r->line1, + r->w_lores, r->hs); + if (++r->ystep >= r->vs) { + r->ystep = 0; + r->line0 = r->line1; + if (++r->ypos < z->img_comp[k].y) + r->line1 += z->img_comp[k].w2; + } + } + if (n >= 3) { + stbi_uc *y = coutput[0]; + if (z->s->img_n == 3) { + if (is_rgb) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = y[i]; + out[1] = coutput[1][i]; + out[2] = coutput[2][i]; + out[3] = 255; + out += n; + } + } else { + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else if (z->s->img_n == 4) { + if (z->app14_color_transform == 0) { // CMYK + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(coutput[0][i], m); + out[1] = stbi__blinn_8x8(coutput[1][i], m); + out[2] = stbi__blinn_8x8(coutput[2][i], m); + out[3] = 255; + out += n; + } + } else if (z->app14_color_transform == 2) { // YCCK + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(255 - out[0], m); + out[1] = stbi__blinn_8x8(255 - out[1], m); + out[2] = stbi__blinn_8x8(255 - out[2], m); + out += n; + } + } else { // YCbCr + alpha? Ignore the fourth channel for now + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else + for (i=0; i < z->s->img_x; ++i) { + out[0] = out[1] = out[2] = y[i]; + out[3] = 255; // not used if n==3 + out += n; + } + } else { + if (is_rgb) { + if (n == 1) + for (i=0; i < z->s->img_x; ++i) + *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + else { + for (i=0; i < z->s->img_x; ++i, out += 2) { + out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + out[1] = 255; + } + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); + stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); + stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); + out[0] = stbi__compute_y(r, g, b); + out[1] = 255; + out += n; + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); + out[1] = 255; + out += n; + } + } else { + stbi_uc *y = coutput[0]; + if (n == 1) + for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; + else + for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; } + } + } + } + stbi__cleanup_jpeg(z); + *out_x = z->s->img_x; + *out_y = z->s->img_y; + if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output + return output; + } +} + +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + unsigned char* result; + stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__errpuc("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + STBI_NOTUSED(ri); + j->s = s; + stbi__setup_jpeg(j); + result = load_jpeg_image(j, x,y,comp,req_comp); + STBI_FREE(j); + return result; +} + +static int stbi__jpeg_test(stbi__context *s) +{ + int r; + stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + stbi__setup_jpeg(j); + r = stbi__decode_jpeg_header(j, STBI__SCAN_type); + stbi__rewind(s); + STBI_FREE(j); + return r; +} + +static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) +{ + if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { + stbi__rewind( j->s ); + return 0; + } + if (x) *x = j->s->img_x; + if (y) *y = j->s->img_y; + if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; + return 1; +} + +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) +{ + int result; + stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg))); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + result = stbi__jpeg_info_raw(j, x, y, comp); + STBI_FREE(j); + return result; +} +#endif + +// public domain zlib decode v0.2 Sean Barrett 2006-11-18 +// simple implementation +// - all input must be provided in an upfront buffer +// - all output is written to a single output buffer (can malloc/realloc) +// performance +// - fast huffman + +#ifndef STBI_NO_ZLIB + +// fast-way is faster to check than jpeg huffman, but slow way is slower +#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables +#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) +#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet + +// zlib-style huffman encoding +// (jpegs packs from left, zlib from right, so can't share code) +typedef struct +{ + stbi__uint16 fast[1 << STBI__ZFAST_BITS]; + stbi__uint16 firstcode[16]; + int maxcode[17]; + stbi__uint16 firstsymbol[16]; + stbi_uc size[STBI__ZNSYMS]; + stbi__uint16 value[STBI__ZNSYMS]; +} stbi__zhuffman; + +stbi_inline static int stbi__bitreverse16(int n) +{ + n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); + n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); + n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); + n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); + return n; +} + +stbi_inline static int stbi__bit_reverse(int v, int bits) +{ + STBI_ASSERT(bits <= 16); + // to bit reverse n bits, reverse 16 and shift + // e.g. 11 bits, bit reverse and shift away 5 + return stbi__bitreverse16(v) >> (16-bits); +} + +static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) +{ + int i,k=0; + int code, next_code[16], sizes[17]; + + // DEFLATE spec for generating codes + memset(sizes, 0, sizeof(sizes)); + memset(z->fast, 0, sizeof(z->fast)); + for (i=0; i < num; ++i) + ++sizes[sizelist[i]]; + sizes[0] = 0; + for (i=1; i < 16; ++i) + if (sizes[i] > (1 << i)) + return stbi__err("bad sizes", "Corrupt PNG"); + code = 0; + for (i=1; i < 16; ++i) { + next_code[i] = code; + z->firstcode[i] = (stbi__uint16) code; + z->firstsymbol[i] = (stbi__uint16) k; + code = (code + sizes[i]); + if (sizes[i]) + if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG"); + z->maxcode[i] = code << (16-i); // preshift for inner loop + code <<= 1; + k += sizes[i]; + } + z->maxcode[16] = 0x10000; // sentinel + for (i=0; i < num; ++i) { + int s = sizelist[i]; + if (s) { + int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; + stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); + z->size [c] = (stbi_uc ) s; + z->value[c] = (stbi__uint16) i; + if (s <= STBI__ZFAST_BITS) { + int j = stbi__bit_reverse(next_code[s],s); + while (j < (1 << STBI__ZFAST_BITS)) { + z->fast[j] = fastv; + j += (1 << s); + } + } + ++next_code[s]; + } + } + return 1; +} + +// zlib-from-memory implementation for PNG reading +// because PNG allows splitting the zlib stream arbitrarily, +// and it's annoying structurally to have PNG call ZLIB call PNG, +// we require PNG read all the IDATs and combine them into a single +// memory buffer + +typedef struct +{ + stbi_uc *zbuffer, *zbuffer_end; + int num_bits; + stbi__uint32 code_buffer; + + char *zout; + char *zout_start; + char *zout_end; + int z_expandable; + + stbi__zhuffman z_length, z_distance; +} stbi__zbuf; + +stbi_inline static int stbi__zeof(stbi__zbuf *z) +{ + return (z->zbuffer >= z->zbuffer_end); +} + +stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) +{ + return stbi__zeof(z) ? 0 : *z->zbuffer++; +} + +static void stbi__fill_bits(stbi__zbuf *z) +{ + do { + if (z->code_buffer >= (1U << z->num_bits)) { + z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */ + return; + } + z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; + z->num_bits += 8; + } while (z->num_bits <= 24); +} + +stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) +{ + unsigned int k; + if (z->num_bits < n) stbi__fill_bits(z); + k = z->code_buffer & ((1 << n) - 1); + z->code_buffer >>= n; + z->num_bits -= n; + return k; +} + +static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s,k; + // not resolved by fast table, so compute it the slow way + // use jpeg approach, which requires MSbits at top + k = stbi__bit_reverse(a->code_buffer, 16); + for (s=STBI__ZFAST_BITS+1; ; ++s) + if (k < z->maxcode[s]) + break; + if (s >= 16) return -1; // invalid code! + // code size is s, so: + b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; + if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere! + if (z->size[b] != s) return -1; // was originally an assert, but report failure instead. + a->code_buffer >>= s; + a->num_bits -= s; + return z->value[b]; +} + +stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s; + if (a->num_bits < 16) { + if (stbi__zeof(a)) { + return -1; /* report error for unexpected end of data. */ + } + stbi__fill_bits(a); + } + b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; + if (b) { + s = b >> 9; + a->code_buffer >>= s; + a->num_bits -= s; + return b & 511; + } + return stbi__zhuffman_decode_slowpath(a, z); +} + +static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes +{ + char *q; + unsigned int cur, limit, old_limit; + z->zout = zout; + if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); + cur = (unsigned int) (z->zout - z->zout_start); + limit = old_limit = (unsigned) (z->zout_end - z->zout_start); + if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory"); + while (cur + n > limit) { + if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); + limit *= 2; + } + q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); + STBI_NOTUSED(old_limit); + if (q == NULL) return stbi__err("outofmem", "Out of memory"); + z->zout_start = q; + z->zout = q + cur; + z->zout_end = q + limit; + return 1; +} + +static const int stbi__zlength_base[31] = { + 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,0,0 }; + +static const int stbi__zlength_extra[31]= +{ 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,0,0 }; + +static const int stbi__zdist_base[32] = { 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,0,0}; + +static const int stbi__zdist_extra[32] = +{ 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}; + +static int stbi__parse_huffman_block(stbi__zbuf *a) +{ + char *zout = a->zout; + for(;;) { + int z = stbi__zhuffman_decode(a, &a->z_length); + if (z < 256) { + if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes + if (zout >= a->zout_end) { + if (!stbi__zexpand(a, zout, 1)) return 0; + zout = a->zout; + } + *zout++ = (char) z; + } else { + stbi_uc *p; + int len,dist; + if (z == 256) { + a->zout = zout; + return 1; + } + if (z >= 286) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data + z -= 257; + len = stbi__zlength_base[z]; + if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); + z = stbi__zhuffman_decode(a, &a->z_distance); + if (z < 0 || z >= 30) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data + dist = stbi__zdist_base[z]; + if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); + if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); + if (zout + len > a->zout_end) { + if (!stbi__zexpand(a, zout, len)) return 0; + zout = a->zout; + } + p = (stbi_uc *) (zout - dist); + if (dist == 1) { // run of one byte; common in images. + stbi_uc v = *p; + if (len) { do *zout++ = v; while (--len); } + } else { + if (len) { do *zout++ = *p++; while (--len); } + } + } + } +} + +static int stbi__compute_huffman_codes(stbi__zbuf *a) +{ + static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + stbi__zhuffman z_codelength; + stbi_uc lencodes[286+32+137];//padding for maximum single op + stbi_uc codelength_sizes[19]; + int i,n; + + int hlit = stbi__zreceive(a,5) + 257; + int hdist = stbi__zreceive(a,5) + 1; + int hclen = stbi__zreceive(a,4) + 4; + int ntot = hlit + hdist; + + memset(codelength_sizes, 0, sizeof(codelength_sizes)); + for (i=0; i < hclen; ++i) { + int s = stbi__zreceive(a,3); + codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; + } + if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; + + n = 0; + while (n < ntot) { + int c = stbi__zhuffman_decode(a, &z_codelength); + if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); + if (c < 16) + lencodes[n++] = (stbi_uc) c; + else { + stbi_uc fill = 0; + if (c == 16) { + c = stbi__zreceive(a,2)+3; + if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); + fill = lencodes[n-1]; + } else if (c == 17) { + c = stbi__zreceive(a,3)+3; + } else if (c == 18) { + c = stbi__zreceive(a,7)+11; + } else { + return stbi__err("bad codelengths", "Corrupt PNG"); + } + if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); + memset(lencodes+n, fill, c); + n += c; + } + } + if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG"); + if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; + return 1; +} + +static int stbi__parse_uncompressed_block(stbi__zbuf *a) +{ + stbi_uc header[4]; + int len,nlen,k; + if (a->num_bits & 7) + stbi__zreceive(a, a->num_bits & 7); // discard + // drain the bit-packed data into header + k = 0; + while (a->num_bits > 0) { + header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check + a->code_buffer >>= 8; + a->num_bits -= 8; + } + if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG"); + // now fill header the normal way + while (k < 4) + header[k++] = stbi__zget8(a); + len = header[1] * 256 + header[0]; + nlen = header[3] * 256 + header[2]; + if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); + if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); + if (a->zout + len > a->zout_end) + if (!stbi__zexpand(a, a->zout, len)) return 0; + memcpy(a->zout, a->zbuffer, len); + a->zbuffer += len; + a->zout += len; + return 1; +} + +static int stbi__parse_zlib_header(stbi__zbuf *a) +{ + int cmf = stbi__zget8(a); + int cm = cmf & 15; + /* int cinfo = cmf >> 4; */ + int flg = stbi__zget8(a); + if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec + if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec + if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png + if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png + // window = 1 << (8 + cinfo)... but who cares, we fully buffer output + return 1; +} + +static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] = +{ + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 +}; +static const stbi_uc stbi__zdefault_distance[32] = +{ + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 +}; +/* +Init algorithm: +{ + int i; // use <= to match clearly with spec + for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; + for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; + for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; + for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; + + for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; +} +*/ + +static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) +{ + int final, type; + if (parse_header) + if (!stbi__parse_zlib_header(a)) return 0; + a->num_bits = 0; + a->code_buffer = 0; + do { + final = stbi__zreceive(a,1); + type = stbi__zreceive(a,2); + if (type == 0) { + if (!stbi__parse_uncompressed_block(a)) return 0; + } else if (type == 3) { + return 0; + } else { + if (type == 1) { + // use fixed code lengths + if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , STBI__ZNSYMS)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; + } else { + if (!stbi__compute_huffman_codes(a)) return 0; + } + if (!stbi__parse_huffman_block(a)) return 0; + } + } while (!final); + return 1; +} + +static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) +{ + a->zout_start = obuf; + a->zout = obuf; + a->zout_end = obuf + olen; + a->z_expandable = exp; + + return stbi__parse_zlib(a, parse_header); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) +{ + return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) + return (int) (a.zout - a.zout_start); + else + return -1; +} + +STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(16384); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer+len; + if (stbi__do_zlib(&a, p, 16384, 1, 0)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) + return (int) (a.zout - a.zout_start); + else + return -1; +} +#endif + +// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 +// simple implementation +// - only 8-bit samples +// - no CRC checking +// - allocates lots of intermediate memory +// - avoids problem of streaming data between subsystems +// - avoids explicit window management +// performance +// - uses stb_zlib, a PD zlib implementation with fast huffman decoding + +#ifndef STBI_NO_PNG +typedef struct +{ + stbi__uint32 length; + stbi__uint32 type; +} stbi__pngchunk; + +static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) +{ + stbi__pngchunk c; + c.length = stbi__get32be(s); + c.type = stbi__get32be(s); + return c; +} + +static int stbi__check_png_header(stbi__context *s) +{ + static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; + int i; + for (i=0; i < 8; ++i) + if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); + return 1; +} + +typedef struct +{ + stbi__context *s; + stbi_uc *idata, *expanded, *out; + int depth; +} stbi__png; + + +enum { + STBI__F_none=0, + STBI__F_sub=1, + STBI__F_up=2, + STBI__F_avg=3, + STBI__F_paeth=4, + // synthetic filters used for first scanline to avoid needing a dummy row of 0s + STBI__F_avg_first, + STBI__F_paeth_first +}; + +static stbi_uc first_row_filter[5] = +{ + STBI__F_none, + STBI__F_sub, + STBI__F_none, + STBI__F_avg_first, + STBI__F_paeth_first +}; + +static int stbi__paeth(int a, int b, int c) +{ + int p = a + b - c; + int pa = abs(p-a); + int pb = abs(p-b); + int pc = abs(p-c); + if (pa <= pb && pa <= pc) return a; + if (pb <= pc) return b; + return c; +} + +static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; + +// create the png data from post-deflated data +static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) +{ + int bytes = (depth == 16? 2 : 1); + stbi__context *s = a->s; + stbi__uint32 i,j,stride = x*out_n*bytes; + stbi__uint32 img_len, img_width_bytes; + int k; + int img_n = s->img_n; // copy it into a local for later + + int output_bytes = out_n*bytes; + int filter_bytes = img_n*bytes; + int width = x; + + STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); + a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into + if (!a->out) return stbi__err("outofmem", "Out of memory"); + + if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); + img_width_bytes = (((img_n * x * depth) + 7) >> 3); + img_len = (img_width_bytes + 1) * y; + + // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, + // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), + // so just check for raw_len < img_len always. + if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); + + for (j=0; j < y; ++j) { + stbi_uc *cur = a->out + stride*j; + stbi_uc *prior; + int filter = *raw++; + + if (filter > 4) + return stbi__err("invalid filter","Corrupt PNG"); + + if (depth < 8) { + if (img_width_bytes > x) return stbi__err("invalid width","Corrupt PNG"); + cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place + filter_bytes = 1; + width = img_width_bytes; + } + prior = cur - stride; // bugfix: need to compute this after 'cur +=' computation above + + // if first row, use special filter that doesn't sample previous row + if (j == 0) filter = first_row_filter[filter]; + + // handle first byte explicitly + for (k=0; k < filter_bytes; ++k) { + switch (filter) { + case STBI__F_none : cur[k] = raw[k]; break; + case STBI__F_sub : cur[k] = raw[k]; break; + case STBI__F_up : cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; + case STBI__F_avg : cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); break; + case STBI__F_paeth : cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0,prior[k],0)); break; + case STBI__F_avg_first : cur[k] = raw[k]; break; + case STBI__F_paeth_first: cur[k] = raw[k]; break; + } + } + + if (depth == 8) { + if (img_n != out_n) + cur[img_n] = 255; // first pixel + raw += img_n; + cur += out_n; + prior += out_n; + } else if (depth == 16) { + if (img_n != out_n) { + cur[filter_bytes] = 255; // first pixel top byte + cur[filter_bytes+1] = 255; // first pixel bottom byte + } + raw += filter_bytes; + cur += output_bytes; + prior += output_bytes; + } else { + raw += 1; + cur += 1; + prior += 1; + } + + // this is a little gross, so that we don't switch per-pixel or per-component + if (depth < 8 || img_n == out_n) { + int nk = (width - 1)*filter_bytes; + #define STBI__CASE(f) \ + case f: \ + for (k=0; k < nk; ++k) + switch (filter) { + // "none" filter turns into a memcpy here; make that explicit. + case STBI__F_none: memcpy(cur, raw, nk); break; + STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); } break; + STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; + STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); } break; + STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); } break; + STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); } break; + STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); } break; + } + #undef STBI__CASE + raw += nk; + } else { + STBI_ASSERT(img_n+1 == out_n); + #define STBI__CASE(f) \ + case f: \ + for (i=x-1; i >= 1; --i, cur[filter_bytes]=255,raw+=filter_bytes,cur+=output_bytes,prior+=output_bytes) \ + for (k=0; k < filter_bytes; ++k) + switch (filter) { + STBI__CASE(STBI__F_none) { cur[k] = raw[k]; } break; + STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k- output_bytes]); } break; + STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; + STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k- output_bytes])>>1)); } break; + STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],prior[k],prior[k- output_bytes])); } break; + STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k- output_bytes] >> 1)); } break; + STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],0,0)); } break; + } + #undef STBI__CASE + + // the loop above sets the high byte of the pixels' alpha, but for + // 16 bit png files we also need the low byte set. we'll do that here. + if (depth == 16) { + cur = a->out + stride*j; // start at the beginning of the row again + for (i=0; i < x; ++i,cur+=output_bytes) { + cur[filter_bytes+1] = 255; + } + } + } + } + + // we make a separate pass to expand bits to pixels; for performance, + // this could run two scanlines behind the above code, so it won't + // intefere with filtering but will still be in the cache. + if (depth < 8) { + for (j=0; j < y; ++j) { + stbi_uc *cur = a->out + stride*j; + stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes; + // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit + // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop + stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range + + // note that the final byte might overshoot and write more data than desired. + // we can allocate enough data that this never writes out of memory, but it + // could also overwrite the next scanline. can it overwrite non-empty data + // on the next scanline? yes, consider 1-pixel-wide scanlines with 1-bit-per-pixel. + // so we need to explicitly clamp the final ones + + if (depth == 4) { + for (k=x*img_n; k >= 2; k-=2, ++in) { + *cur++ = scale * ((*in >> 4) ); + *cur++ = scale * ((*in ) & 0x0f); + } + if (k > 0) *cur++ = scale * ((*in >> 4) ); + } else if (depth == 2) { + for (k=x*img_n; k >= 4; k-=4, ++in) { + *cur++ = scale * ((*in >> 6) ); + *cur++ = scale * ((*in >> 4) & 0x03); + *cur++ = scale * ((*in >> 2) & 0x03); + *cur++ = scale * ((*in ) & 0x03); + } + if (k > 0) *cur++ = scale * ((*in >> 6) ); + if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03); + if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03); + } else if (depth == 1) { + for (k=x*img_n; k >= 8; k-=8, ++in) { + *cur++ = scale * ((*in >> 7) ); + *cur++ = scale * ((*in >> 6) & 0x01); + *cur++ = scale * ((*in >> 5) & 0x01); + *cur++ = scale * ((*in >> 4) & 0x01); + *cur++ = scale * ((*in >> 3) & 0x01); + *cur++ = scale * ((*in >> 2) & 0x01); + *cur++ = scale * ((*in >> 1) & 0x01); + *cur++ = scale * ((*in ) & 0x01); + } + if (k > 0) *cur++ = scale * ((*in >> 7) ); + if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01); + if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01); + if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01); + if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01); + if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01); + if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01); + } + if (img_n != out_n) { + int q; + // insert alpha = 255 + cur = a->out + stride*j; + if (img_n == 1) { + for (q=x-1; q >= 0; --q) { + cur[q*2+1] = 255; + cur[q*2+0] = cur[q]; + } + } else { + STBI_ASSERT(img_n == 3); + for (q=x-1; q >= 0; --q) { + cur[q*4+3] = 255; + cur[q*4+2] = cur[q*3+2]; + cur[q*4+1] = cur[q*3+1]; + cur[q*4+0] = cur[q*3+0]; + } + } + } + } + } else if (depth == 16) { + // force the image data from big-endian to platform-native. + // this is done in a separate pass due to the decoding relying + // on the data being untouched, but could probably be done + // per-line during decode if care is taken. + stbi_uc *cur = a->out; + stbi__uint16 *cur16 = (stbi__uint16*)cur; + + for(i=0; i < x*y*out_n; ++i,cur16++,cur+=2) { + *cur16 = (cur[0] << 8) | cur[1]; + } + } + + return 1; +} + +static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) +{ + int bytes = (depth == 16 ? 2 : 1); + int out_bytes = out_n * bytes; + stbi_uc *final; + int p; + if (!interlaced) + return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); + + // de-interlacing + final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); + if (!final) return stbi__err("outofmem", "Out of memory"); + for (p=0; p < 7; ++p) { + int xorig[] = { 0,4,0,2,0,1,0 }; + int yorig[] = { 0,0,4,0,2,0,1 }; + int xspc[] = { 8,8,4,4,2,2,1 }; + int yspc[] = { 8,8,8,4,4,2,2 }; + int i,j,x,y; + // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 + x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; + y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; + if (x && y) { + stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; + if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { + STBI_FREE(final); + return 0; + } + for (j=0; j < y; ++j) { + for (i=0; i < x; ++i) { + int out_y = j*yspc[p]+yorig[p]; + int out_x = i*xspc[p]+xorig[p]; + memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, + a->out + (j*x+i)*out_bytes, out_bytes); + } + } + STBI_FREE(a->out); + image_data += img_len; + image_data_len -= img_len; + } + } + a->out = final; + + return 1; +} + +static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + // compute color-based transparency, assuming we've + // already got 255 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i=0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 255); + p += 2; + } + } else { + for (i=0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi__uint16 *p = (stbi__uint16*) z->out; + + // compute color-based transparency, assuming we've + // already got 65535 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i = 0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 65535); + p += 2; + } + } else { + for (i = 0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) +{ + stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; + stbi_uc *p, *temp_out, *orig = a->out; + + p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0); + if (p == NULL) return stbi__err("outofmem", "Out of memory"); + + // between here and free(out) below, exitting would leak + temp_out = p; + + if (pal_img_n == 3) { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p += 3; + } + } else { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p[3] = palette[n+3]; + p += 4; + } + } + STBI_FREE(a->out); + a->out = temp_out; + + STBI_NOTUSED(len); + + return 1; +} + +static int stbi__unpremultiply_on_load_global = 0; +static int stbi__de_iphone_flag_global = 0; + +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag_global = flag_true_if_should_convert; +} + +#ifndef STBI_THREAD_LOCAL +#define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global +#define stbi__de_iphone_flag stbi__de_iphone_flag_global +#else +static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set; +static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set; + +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply; + stbi__unpremultiply_on_load_set = 1; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag_local = flag_true_if_should_convert; + stbi__de_iphone_flag_set = 1; +} + +#define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \ + ? stbi__unpremultiply_on_load_local \ + : stbi__unpremultiply_on_load_global) +#define stbi__de_iphone_flag (stbi__de_iphone_flag_set \ + ? stbi__de_iphone_flag_local \ + : stbi__de_iphone_flag_global) +#endif // STBI_THREAD_LOCAL + +static void stbi__de_iphone(stbi__png *z) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + if (s->img_out_n == 3) { // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 3; + } + } else { + STBI_ASSERT(s->img_out_n == 4); + if (stbi__unpremultiply_on_load) { + // convert bgr to rgb and unpremultiply + for (i=0; i < pixel_count; ++i) { + stbi_uc a = p[3]; + stbi_uc t = p[0]; + if (a) { + stbi_uc half = a / 2; + p[0] = (p[2] * 255 + half) / a; + p[1] = (p[1] * 255 + half) / a; + p[2] = ( t * 255 + half) / a; + } else { + p[0] = p[2]; + p[2] = t; + } + p += 4; + } + } else { + // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 4; + } + } + } +} + +#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) + +static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) +{ + stbi_uc palette[1024], pal_img_n=0; + stbi_uc has_trans=0, tc[3]={0}; + stbi__uint16 tc16[3]; + stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; + int first=1,k,interlace=0, color=0, is_iphone=0; + stbi__context *s = z->s; + + z->expanded = NULL; + z->idata = NULL; + z->out = NULL; + + if (!stbi__check_png_header(s)) return 0; + + if (scan == STBI__SCAN_type) return 1; + + for (;;) { + stbi__pngchunk c = stbi__get_chunk_header(s); + switch (c.type) { + case STBI__PNG_TYPE('C','g','B','I'): + is_iphone = 1; + stbi__skip(s, c.length); + break; + case STBI__PNG_TYPE('I','H','D','R'): { + int comp,filter; + if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); + first = 0; + if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); + s->img_x = stbi__get32be(s); + s->img_y = stbi__get32be(s); + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only"); + color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); + comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); + filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); + interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); + if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); + if (!pal_img_n) { + s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); + if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); + } else { + // if paletted, then pal_n is our final components, and + // img_n is # components to decompress/filter. + s->img_n = 1; + if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); + } + // even with SCAN_header, have to scan to see if we have a tRNS + break; + } + + case STBI__PNG_TYPE('P','L','T','E'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); + pal_len = c.length / 3; + if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); + for (i=0; i < pal_len; ++i) { + palette[i*4+0] = stbi__get8(s); + palette[i*4+1] = stbi__get8(s); + palette[i*4+2] = stbi__get8(s); + palette[i*4+3] = 255; + } + break; + } + + case STBI__PNG_TYPE('t','R','N','S'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); + if (pal_img_n) { + if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } + if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); + if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); + pal_img_n = 4; + for (i=0; i < c.length; ++i) + palette[i*4+3] = stbi__get8(s); + } else { + if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); + if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); + has_trans = 1; + // non-paletted with tRNS = constant alpha. if header-scanning, we can stop now. + if (scan == STBI__SCAN_header) { ++s->img_n; return 1; } + if (z->depth == 16) { + for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is + } else { + for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger + } + } + break; + } + + case STBI__PNG_TYPE('I','D','A','T'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); + if (scan == STBI__SCAN_header) { + // header scan definitely stops at first IDAT + if (pal_img_n) + s->img_n = pal_img_n; + return 1; + } + if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes"); + if ((int)(ioff + c.length) < (int)ioff) return 0; + if (ioff + c.length > idata_limit) { + stbi__uint32 idata_limit_old = idata_limit; + stbi_uc *p; + if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; + while (ioff + c.length > idata_limit) + idata_limit *= 2; + STBI_NOTUSED(idata_limit_old); + p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); + z->idata = p; + } + if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); + ioff += c.length; + break; + } + + case STBI__PNG_TYPE('I','E','N','D'): { + stbi__uint32 raw_len, bpl; + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (scan != STBI__SCAN_load) return 1; + if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); + // initial guess for decoded data size to avoid unnecessary reallocs + bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component + raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; + z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); + if (z->expanded == NULL) return 0; // zlib should set error + STBI_FREE(z->idata); z->idata = NULL; + if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) + s->img_out_n = s->img_n+1; + else + s->img_out_n = s->img_n; + if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; + if (has_trans) { + if (z->depth == 16) { + if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; + } else { + if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; + } + } + if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) + stbi__de_iphone(z); + if (pal_img_n) { + // pal_img_n == 3 or 4 + s->img_n = pal_img_n; // record the actual colors we had + s->img_out_n = pal_img_n; + if (req_comp >= 3) s->img_out_n = req_comp; + if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) + return 0; + } else if (has_trans) { + // non-paletted image with tRNS -> source image has (constant) alpha + ++s->img_n; + } + STBI_FREE(z->expanded); z->expanded = NULL; + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + return 1; + } + + default: + // if critical, fail + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if ((c.type & (1 << 29)) == 0) { + #ifndef STBI_NO_FAILURE_STRINGS + // not threadsafe + static char invalid_chunk[] = "XXXX PNG chunk not known"; + invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); + invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); + invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); + invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); + #endif + return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); + } + stbi__skip(s, c.length); + break; + } + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + } +} + +static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) +{ + void *result=NULL; + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { + if (p->depth <= 8) + ri->bits_per_channel = 8; + else if (p->depth == 16) + ri->bits_per_channel = 16; + else + return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth"); + result = p->out; + p->out = NULL; + if (req_comp && req_comp != p->s->img_out_n) { + if (ri->bits_per_channel == 8) + result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + else + result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + p->s->img_out_n = req_comp; + if (result == NULL) return result; + } + *x = p->s->img_x; + *y = p->s->img_y; + if (n) *n = p->s->img_n; + } + STBI_FREE(p->out); p->out = NULL; + STBI_FREE(p->expanded); p->expanded = NULL; + STBI_FREE(p->idata); p->idata = NULL; + + return result; +} + +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi__png p; + p.s = s; + return stbi__do_png(&p, x,y,comp,req_comp, ri); +} + +static int stbi__png_test(stbi__context *s) +{ + int r; + r = stbi__check_png_header(s); + stbi__rewind(s); + return r; +} + +static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) +{ + if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { + stbi__rewind( p->s ); + return 0; + } + if (x) *x = p->s->img_x; + if (y) *y = p->s->img_y; + if (comp) *comp = p->s->img_n; + return 1; +} + +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__png p; + p.s = s; + return stbi__png_info_raw(&p, x, y, comp); +} + +static int stbi__png_is16(stbi__context *s) +{ + stbi__png p; + p.s = s; + if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) + return 0; + if (p.depth != 16) { + stbi__rewind(p.s); + return 0; + } + return 1; +} +#endif + +// Microsoft/Windows BMP image + +#ifndef STBI_NO_BMP +static int stbi__bmp_test_raw(stbi__context *s) +{ + int r; + int sz; + if (stbi__get8(s) != 'B') return 0; + if (stbi__get8(s) != 'M') return 0; + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + stbi__get32le(s); // discard data offset + sz = stbi__get32le(s); + r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); + return r; +} + +static int stbi__bmp_test(stbi__context *s) +{ + int r = stbi__bmp_test_raw(s); + stbi__rewind(s); + return r; +} + + +// returns 0..31 for the highest set bit +static int stbi__high_bit(unsigned int z) +{ + int n=0; + if (z == 0) return -1; + if (z >= 0x10000) { n += 16; z >>= 16; } + if (z >= 0x00100) { n += 8; z >>= 8; } + if (z >= 0x00010) { n += 4; z >>= 4; } + if (z >= 0x00004) { n += 2; z >>= 2; } + if (z >= 0x00002) { n += 1;/* >>= 1;*/ } + return n; +} + +static int stbi__bitcount(unsigned int a) +{ + a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 + a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 + a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits + a = (a + (a >> 8)); // max 16 per 8 bits + a = (a + (a >> 16)); // max 32 per 8 bits + return a & 0xff; +} + +// extract an arbitrarily-aligned N-bit value (N=bits) +// from v, and then make it 8-bits long and fractionally +// extend it to full full range. +static int stbi__shiftsigned(unsigned int v, int shift, int bits) +{ + static unsigned int mul_table[9] = { + 0, + 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, + 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, + }; + static unsigned int shift_table[9] = { + 0, 0,0,1,0,2,4,6,0, + }; + if (shift < 0) + v <<= -shift; + else + v >>= shift; + STBI_ASSERT(v < 256); + v >>= (8-bits); + STBI_ASSERT(bits >= 0 && bits <= 8); + return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits]; +} + +typedef struct +{ + int bpp, offset, hsz; + unsigned int mr,mg,mb,ma, all_a; + int extra_read; +} stbi__bmp_data; + +static int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress) +{ + // BI_BITFIELDS specifies masks explicitly, don't override + if (compress == 3) + return 1; + + if (compress == 0) { + if (info->bpp == 16) { + info->mr = 31u << 10; + info->mg = 31u << 5; + info->mb = 31u << 0; + } else if (info->bpp == 32) { + info->mr = 0xffu << 16; + info->mg = 0xffu << 8; + info->mb = 0xffu << 0; + info->ma = 0xffu << 24; + info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 + } else { + // otherwise, use defaults, which is all-0 + info->mr = info->mg = info->mb = info->ma = 0; + } + return 1; + } + return 0; // error +} + +static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) +{ + int hsz; + if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + info->offset = stbi__get32le(s); + info->hsz = hsz = stbi__get32le(s); + info->mr = info->mg = info->mb = info->ma = 0; + info->extra_read = 14; + + if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP"); + + if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); + if (hsz == 12) { + s->img_x = stbi__get16le(s); + s->img_y = stbi__get16le(s); + } else { + s->img_x = stbi__get32le(s); + s->img_y = stbi__get32le(s); + } + if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); + info->bpp = stbi__get16le(s); + if (hsz != 12) { + int compress = stbi__get32le(s); + if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); + if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes + if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel + stbi__get32le(s); // discard sizeof + stbi__get32le(s); // discard hres + stbi__get32le(s); // discard vres + stbi__get32le(s); // discard colorsused + stbi__get32le(s); // discard max important + if (hsz == 40 || hsz == 56) { + if (hsz == 56) { + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + } + if (info->bpp == 16 || info->bpp == 32) { + if (compress == 0) { + stbi__bmp_set_mask_defaults(info, compress); + } else if (compress == 3) { + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->extra_read += 12; + // not documented, but generated by photoshop and handled by mspaint + if (info->mr == info->mg && info->mg == info->mb) { + // ?!?!? + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else { + // V4/V5 header + int i; + if (hsz != 108 && hsz != 124) + return stbi__errpuc("bad BMP", "bad BMP"); + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->ma = stbi__get32le(s); + if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs + stbi__bmp_set_mask_defaults(info, compress); + stbi__get32le(s); // discard color space + for (i=0; i < 12; ++i) + stbi__get32le(s); // discard color space parameters + if (hsz == 124) { + stbi__get32le(s); // discard rendering intent + stbi__get32le(s); // discard offset of profile data + stbi__get32le(s); // discard size of profile data + stbi__get32le(s); // discard reserved + } + } + } + return (void *) 1; +} + + +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + unsigned int mr=0,mg=0,mb=0,ma=0, all_a; + stbi_uc pal[256][4]; + int psize=0,i,j,width; + int flip_vertically, pad, target; + stbi__bmp_data info; + STBI_NOTUSED(ri); + + info.all_a = 255; + if (stbi__bmp_parse_header(s, &info) == NULL) + return NULL; // error code already set + + flip_vertically = ((int) s->img_y) > 0; + s->img_y = abs((int) s->img_y); + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + mr = info.mr; + mg = info.mg; + mb = info.mb; + ma = info.ma; + all_a = info.all_a; + + if (info.hsz == 12) { + if (info.bpp < 24) + psize = (info.offset - info.extra_read - 24) / 3; + } else { + if (info.bpp < 16) + psize = (info.offset - info.extra_read - info.hsz) >> 2; + } + if (psize == 0) { + // accept some number of extra bytes after the header, but if the offset points either to before + // the header ends or implies a large amount of extra data, reject the file as malformed + int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original); + int header_limit = 1024; // max we actually read is below 256 bytes currently. + int extra_data_limit = 256*4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size. + if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) { + return stbi__errpuc("bad header", "Corrupt BMP"); + } + // we established that bytes_read_so_far is positive and sensible. + // the first half of this test rejects offsets that are either too small positives, or + // negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn + // ensures the number computed in the second half of the test can't overflow. + if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit) { + return stbi__errpuc("bad offset", "Corrupt BMP"); + } else { + stbi__skip(s, info.offset - bytes_read_so_far); + } + } + + if (info.bpp == 24 && ma == 0xff000000) + s->img_n = 3; + else + s->img_n = ma ? 4 : 3; + if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 + target = req_comp; + else + target = s->img_n; // if they want monochrome, we'll post-convert + + // sanity-check size + if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "Corrupt BMP"); + + out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (info.bpp < 16) { + int z=0; + if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } + for (i=0; i < psize; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + if (info.hsz != 12) stbi__get8(s); + pal[i][3] = 255; + } + stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); + if (info.bpp == 1) width = (s->img_x + 7) >> 3; + else if (info.bpp == 4) width = (s->img_x + 1) >> 1; + else if (info.bpp == 8) width = s->img_x; + else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } + pad = (-width)&3; + if (info.bpp == 1) { + for (j=0; j < (int) s->img_y; ++j) { + int bit_offset = 7, v = stbi__get8(s); + for (i=0; i < (int) s->img_x; ++i) { + int color = (v>>bit_offset)&0x1; + out[z++] = pal[color][0]; + out[z++] = pal[color][1]; + out[z++] = pal[color][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + if((--bit_offset) < 0) { + bit_offset = 7; + v = stbi__get8(s); + } + } + stbi__skip(s, pad); + } + } else { + for (j=0; j < (int) s->img_y; ++j) { + for (i=0; i < (int) s->img_x; i += 2) { + int v=stbi__get8(s),v2=0; + if (info.bpp == 4) { + v2 = v & 15; + v >>= 4; + } + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + v = (info.bpp == 8) ? stbi__get8(s) : v2; + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + } + stbi__skip(s, pad); + } + } + } else { + int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; + int z = 0; + int easy=0; + stbi__skip(s, info.offset - info.extra_read - info.hsz); + if (info.bpp == 24) width = 3 * s->img_x; + else if (info.bpp == 16) width = 2*s->img_x; + else /* bpp = 32 and pad = 0 */ width=0; + pad = (-width) & 3; + if (info.bpp == 24) { + easy = 1; + } else if (info.bpp == 32) { + if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) + easy = 2; + } + if (!easy) { + if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + // right shift amt to put high bit in position #7 + rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); + gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); + bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); + ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); + if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + } + for (j=0; j < (int) s->img_y; ++j) { + if (easy) { + for (i=0; i < (int) s->img_x; ++i) { + unsigned char a; + out[z+2] = stbi__get8(s); + out[z+1] = stbi__get8(s); + out[z+0] = stbi__get8(s); + z += 3; + a = (easy == 2 ? stbi__get8(s) : 255); + all_a |= a; + if (target == 4) out[z++] = a; + } + } else { + int bpp = info.bpp; + for (i=0; i < (int) s->img_x; ++i) { + stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); + unsigned int a; + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); + a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); + all_a |= a; + if (target == 4) out[z++] = STBI__BYTECAST(a); + } + } + stbi__skip(s, pad); + } + } + + // if alpha channel is all 0s, replace with all 255s + if (target == 4 && all_a == 0) + for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) + out[i] = 255; + + if (flip_vertically) { + stbi_uc t; + for (j=0; j < (int) s->img_y>>1; ++j) { + stbi_uc *p1 = out + j *s->img_x*target; + stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; + for (i=0; i < (int) s->img_x*target; ++i) { + t = p1[i]; p1[i] = p2[i]; p2[i] = t; + } + } + } + + if (req_comp && req_comp != target) { + out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + return out; +} +#endif + +// Targa Truevision - TGA +// by Jonathan Dummer +#ifndef STBI_NO_TGA +// returns STBI_rgb or whatever, 0 on error +static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) +{ + // only RGB or RGBA (incl. 16bit) or grey allowed + if (is_rgb16) *is_rgb16 = 0; + switch(bits_per_pixel) { + case 8: return STBI_grey; + case 16: if(is_grey) return STBI_grey_alpha; + // fallthrough + case 15: if(is_rgb16) *is_rgb16 = 1; + return STBI_rgb; + case 24: // fallthrough + case 32: return bits_per_pixel/8; + default: return 0; + } +} + +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) +{ + int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; + int sz, tga_colormap_type; + stbi__get8(s); // discard Offset + tga_colormap_type = stbi__get8(s); // colormap type + if( tga_colormap_type > 1 ) { + stbi__rewind(s); + return 0; // only RGB or indexed allowed + } + tga_image_type = stbi__get8(s); // image type + if ( tga_colormap_type == 1 ) { // colormapped (paletted) image + if (tga_image_type != 1 && tga_image_type != 9) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip image x and y origin + tga_colormap_bpp = sz; + } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE + if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { + stbi__rewind(s); + return 0; // only RGB or grey allowed, +/- RLE + } + stbi__skip(s,9); // skip colormap specification and image x/y origin + tga_colormap_bpp = 0; + } + tga_w = stbi__get16le(s); + if( tga_w < 1 ) { + stbi__rewind(s); + return 0; // test width + } + tga_h = stbi__get16le(s); + if( tga_h < 1 ) { + stbi__rewind(s); + return 0; // test height + } + tga_bits_per_pixel = stbi__get8(s); // bits per pixel + stbi__get8(s); // ignore alpha bits + if (tga_colormap_bpp != 0) { + if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { + // when using a colormap, tga_bits_per_pixel is the size of the indexes + // I don't think anything but 8 or 16bit indexes makes sense + stbi__rewind(s); + return 0; + } + tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); + } else { + tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); + } + if(!tga_comp) { + stbi__rewind(s); + return 0; + } + if (x) *x = tga_w; + if (y) *y = tga_h; + if (comp) *comp = tga_comp; + return 1; // seems to have passed everything +} + +static int stbi__tga_test(stbi__context *s) +{ + int res = 0; + int sz, tga_color_type; + stbi__get8(s); // discard Offset + tga_color_type = stbi__get8(s); // color type + if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed + sz = stbi__get8(s); // image type + if ( tga_color_type == 1 ) { // colormapped (paletted) image + if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + stbi__skip(s,4); // skip image x and y origin + } else { // "normal" image w/o colormap + if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE + stbi__skip(s,9); // skip colormap specification and image x/y origin + } + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height + sz = stbi__get8(s); // bits per pixel + if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + + res = 1; // if we got this far, everything's good and we can return 1 instead of 0 + +errorEnd: + stbi__rewind(s); + return res; +} + +// read 16bit value and convert to 24bit RGB +static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) +{ + stbi__uint16 px = (stbi__uint16)stbi__get16le(s); + stbi__uint16 fiveBitMask = 31; + // we have 3 channels with 5bits each + int r = (px >> 10) & fiveBitMask; + int g = (px >> 5) & fiveBitMask; + int b = px & fiveBitMask; + // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later + out[0] = (stbi_uc)((r * 255)/31); + out[1] = (stbi_uc)((g * 255)/31); + out[2] = (stbi_uc)((b * 255)/31); + + // some people claim that the most significant bit might be used for alpha + // (possibly if an alpha-bit is set in the "image descriptor byte") + // but that only made 16bit test images completely translucent.. + // so let's treat all 15 and 16bit TGAs as RGB with no alpha. +} + +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + // read in the TGA header stuff + int tga_offset = stbi__get8(s); + int tga_indexed = stbi__get8(s); + int tga_image_type = stbi__get8(s); + int tga_is_RLE = 0; + int tga_palette_start = stbi__get16le(s); + int tga_palette_len = stbi__get16le(s); + int tga_palette_bits = stbi__get8(s); + int tga_x_origin = stbi__get16le(s); + int tga_y_origin = stbi__get16le(s); + int tga_width = stbi__get16le(s); + int tga_height = stbi__get16le(s); + int tga_bits_per_pixel = stbi__get8(s); + int tga_comp, tga_rgb16=0; + int tga_inverted = stbi__get8(s); + // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) + // image data + unsigned char *tga_data; + unsigned char *tga_palette = NULL; + int i, j; + unsigned char raw_data[4] = {0}; + int RLE_count = 0; + int RLE_repeating = 0; + int read_next_pixel = 1; + STBI_NOTUSED(ri); + STBI_NOTUSED(tga_x_origin); // @TODO + STBI_NOTUSED(tga_y_origin); // @TODO + + if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + // do a tiny bit of precessing + if ( tga_image_type >= 8 ) + { + tga_image_type -= 8; + tga_is_RLE = 1; + } + tga_inverted = 1 - ((tga_inverted >> 5) & 1); + + // If I'm paletted, then I'll use the number of bits from the palette + if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); + else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); + + if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency + return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); + + // tga info + *x = tga_width; + *y = tga_height; + if (comp) *comp = tga_comp; + + if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) + return stbi__errpuc("too large", "Corrupt TGA"); + + tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); + if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); + + // skip to the data's starting position (offset usually = 0) + stbi__skip(s, tga_offset ); + + if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { + for (i=0; i < tga_height; ++i) { + int row = tga_inverted ? tga_height -i - 1 : i; + stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; + stbi__getn(s, tga_row, tga_width * tga_comp); + } + } else { + // do I need to load a palette? + if ( tga_indexed) + { + if (tga_palette_len == 0) { /* you have to have at least one entry! */ + STBI_FREE(tga_data); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + + // any data to skip? (offset usually = 0) + stbi__skip(s, tga_palette_start ); + // load the palette + tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); + if (!tga_palette) { + STBI_FREE(tga_data); + return stbi__errpuc("outofmem", "Out of memory"); + } + if (tga_rgb16) { + stbi_uc *pal_entry = tga_palette; + STBI_ASSERT(tga_comp == STBI_rgb); + for (i=0; i < tga_palette_len; ++i) { + stbi__tga_read_rgb16(s, pal_entry); + pal_entry += tga_comp; + } + } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { + STBI_FREE(tga_data); + STBI_FREE(tga_palette); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + } + // load the data + for (i=0; i < tga_width * tga_height; ++i) + { + // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? + if ( tga_is_RLE ) + { + if ( RLE_count == 0 ) + { + // yep, get the next byte as a RLE command + int RLE_cmd = stbi__get8(s); + RLE_count = 1 + (RLE_cmd & 127); + RLE_repeating = RLE_cmd >> 7; + read_next_pixel = 1; + } else if ( !RLE_repeating ) + { + read_next_pixel = 1; + } + } else + { + read_next_pixel = 1; + } + // OK, if I need to read a pixel, do it now + if ( read_next_pixel ) + { + // load however much data we did have + if ( tga_indexed ) + { + // read in index, then perform the lookup + int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); + if ( pal_idx >= tga_palette_len ) { + // invalid index + pal_idx = 0; + } + pal_idx *= tga_comp; + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = tga_palette[pal_idx+j]; + } + } else if(tga_rgb16) { + STBI_ASSERT(tga_comp == STBI_rgb); + stbi__tga_read_rgb16(s, raw_data); + } else { + // read in the data raw + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = stbi__get8(s); + } + } + // clear the reading flag for the next pixel + read_next_pixel = 0; + } // end of reading a pixel + + // copy data + for (j = 0; j < tga_comp; ++j) + tga_data[i*tga_comp+j] = raw_data[j]; + + // in case we're in RLE mode, keep counting down + --RLE_count; + } + // do I need to invert the image? + if ( tga_inverted ) + { + for (j = 0; j*2 < tga_height; ++j) + { + int index1 = j * tga_width * tga_comp; + int index2 = (tga_height - 1 - j) * tga_width * tga_comp; + for (i = tga_width * tga_comp; i > 0; --i) + { + unsigned char temp = tga_data[index1]; + tga_data[index1] = tga_data[index2]; + tga_data[index2] = temp; + ++index1; + ++index2; + } + } + } + // clear my palette, if I had one + if ( tga_palette != NULL ) + { + STBI_FREE( tga_palette ); + } + } + + // swap RGB - if the source data was RGB16, it already is in the right order + if (tga_comp >= 3 && !tga_rgb16) + { + unsigned char* tga_pixel = tga_data; + for (i=0; i < tga_width * tga_height; ++i) + { + unsigned char temp = tga_pixel[0]; + tga_pixel[0] = tga_pixel[2]; + tga_pixel[2] = temp; + tga_pixel += tga_comp; + } + } + + // convert to target component count + if (req_comp && req_comp != tga_comp) + tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); + + // the things I do to get rid of an error message, and yet keep + // Microsoft's C compilers happy... [8^( + tga_palette_start = tga_palette_len = tga_palette_bits = + tga_x_origin = tga_y_origin = 0; + STBI_NOTUSED(tga_palette_start); + // OK, done + return tga_data; +} +#endif + +// ************************************************************************************************* +// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s) +{ + int r = (stbi__get32be(s) == 0x38425053); + stbi__rewind(s); + return r; +} + +static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) +{ + int count, nleft, len; + + count = 0; + while ((nleft = pixelCount - count) > 0) { + len = stbi__get8(s); + if (len == 128) { + // No-op. + } else if (len < 128) { + // Copy next len+1 bytes literally. + len++; + if (len > nleft) return 0; // corrupt data + count += len; + while (len) { + *p = stbi__get8(s); + p += 4; + len--; + } + } else if (len > 128) { + stbi_uc val; + // Next -len+1 bytes in the dest are replicated from next source byte. + // (Interpret len as a negative 8-bit int.) + len = 257 - len; + if (len > nleft) return 0; // corrupt data + val = stbi__get8(s); + count += len; + while (len) { + *p = val; + p += 4; + len--; + } + } + } + + return 1; +} + +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + int pixelCount; + int channelCount, compression; + int channel, i; + int bitdepth; + int w,h; + stbi_uc *out; + STBI_NOTUSED(ri); + + // Check identifier + if (stbi__get32be(s) != 0x38425053) // "8BPS" + return stbi__errpuc("not PSD", "Corrupt PSD image"); + + // Check file type version. + if (stbi__get16be(s) != 1) + return stbi__errpuc("wrong version", "Unsupported version of PSD image"); + + // Skip 6 reserved bytes. + stbi__skip(s, 6 ); + + // Read the number of channels (R, G, B, A, etc). + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) + return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); + + // Read the rows and columns of the image. + h = stbi__get32be(s); + w = stbi__get32be(s); + + if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + // Make sure the depth is 8 bits. + bitdepth = stbi__get16be(s); + if (bitdepth != 8 && bitdepth != 16) + return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); + + // Make sure the color mode is RGB. + // Valid options are: + // 0: Bitmap + // 1: Grayscale + // 2: Indexed color + // 3: RGB color + // 4: CMYK color + // 7: Multichannel + // 8: Duotone + // 9: Lab color + if (stbi__get16be(s) != 3) + return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); + + // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) + stbi__skip(s,stbi__get32be(s) ); + + // Skip the image resources. (resolution, pen tool paths, etc) + stbi__skip(s, stbi__get32be(s) ); + + // Skip the reserved data. + stbi__skip(s, stbi__get32be(s) ); + + // Find out if the data is compressed. + // Known values: + // 0: no compression + // 1: RLE compressed + compression = stbi__get16be(s); + if (compression > 1) + return stbi__errpuc("bad compression", "PSD has an unknown compression format"); + + // Check size + if (!stbi__mad3sizes_valid(4, w, h, 0)) + return stbi__errpuc("too large", "Corrupt PSD"); + + // Create the destination image. + + if (!compression && bitdepth == 16 && bpc == 16) { + out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0); + ri->bits_per_channel = 16; + } else + out = (stbi_uc *) stbi__malloc(4 * w*h); + + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + pixelCount = w*h; + + // Initialize the data to zero. + //memset( out, 0, pixelCount * 4 ); + + // Finally, the image data. + if (compression) { + // RLE as used by .PSD and .TIFF + // Loop until you get the number of unpacked bytes you are expecting: + // Read the next source byte into n. + // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. + // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. + // Else if n is 128, noop. + // Endloop + + // The RLE-compressed data is preceded by a 2-byte data count for each row in the data, + // which we're going to just skip. + stbi__skip(s, h * channelCount * 2 ); + + // Read the RLE data by channel. + for (channel = 0; channel < 4; channel++) { + stbi_uc *p; + + p = out+channel; + if (channel >= channelCount) { + // Fill this channel with default data. + for (i = 0; i < pixelCount; i++, p += 4) + *p = (channel == 3 ? 255 : 0); + } else { + // Read the RLE data. + if (!stbi__psd_decode_rle(s, p, pixelCount)) { + STBI_FREE(out); + return stbi__errpuc("corrupt", "bad RLE data"); + } + } + } + + } else { + // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) + // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. + + // Read the data by channel. + for (channel = 0; channel < 4; channel++) { + if (channel >= channelCount) { + // Fill this channel with default data. + if (bitdepth == 16 && bpc == 16) { + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + stbi__uint16 val = channel == 3 ? 65535 : 0; + for (i = 0; i < pixelCount; i++, q += 4) + *q = val; + } else { + stbi_uc *p = out+channel; + stbi_uc val = channel == 3 ? 255 : 0; + for (i = 0; i < pixelCount; i++, p += 4) + *p = val; + } + } else { + if (ri->bits_per_channel == 16) { // output bpc + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + for (i = 0; i < pixelCount; i++, q += 4) + *q = (stbi__uint16) stbi__get16be(s); + } else { + stbi_uc *p = out+channel; + if (bitdepth == 16) { // input bpc + for (i = 0; i < pixelCount; i++, p += 4) + *p = (stbi_uc) (stbi__get16be(s) >> 8); + } else { + for (i = 0; i < pixelCount; i++, p += 4) + *p = stbi__get8(s); + } + } + } + } + } + + // remove weird white matte from PSD + if (channelCount >= 4) { + if (ri->bits_per_channel == 16) { + for (i=0; i < w*h; ++i) { + stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; + if (pixel[3] != 0 && pixel[3] != 65535) { + float a = pixel[3] / 65535.0f; + float ra = 1.0f / a; + float inv_a = 65535.0f * (1 - ra); + pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); + pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); + pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); + } + } + } else { + for (i=0; i < w*h; ++i) { + unsigned char *pixel = out + 4*i; + if (pixel[3] != 0 && pixel[3] != 255) { + float a = pixel[3] / 255.0f; + float ra = 1.0f / a; + float inv_a = 255.0f * (1 - ra); + pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); + pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); + pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); + } + } + } + } + + // convert to desired output format + if (req_comp && req_comp != 4) { + if (ri->bits_per_channel == 16) + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); + else + out = stbi__convert_format(out, 4, req_comp, w, h); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + if (comp) *comp = 4; + *y = h; + *x = w; + + return out; +} +#endif + +// ************************************************************************************************* +// Softimage PIC loader +// by Tom Seddon +// +// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format +// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ + +#ifndef STBI_NO_PIC +static int stbi__pic_is4(stbi__context *s,const char *str) +{ + int i; + for (i=0; i<4; ++i) + if (stbi__get8(s) != (stbi_uc)str[i]) + return 0; + + return 1; +} + +static int stbi__pic_test_core(stbi__context *s) +{ + int i; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) + return 0; + + for(i=0;i<84;++i) + stbi__get8(s); + + if (!stbi__pic_is4(s,"PICT")) + return 0; + + return 1; +} + +typedef struct +{ + stbi_uc size,type,channel; +} stbi__pic_packet; + +static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) +{ + int mask=0x80, i; + + for (i=0; i<4; ++i, mask>>=1) { + if (channel & mask) { + if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); + dest[i]=stbi__get8(s); + } + } + + return dest; +} + +static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) +{ + int mask=0x80,i; + + for (i=0;i<4; ++i, mask>>=1) + if (channel&mask) + dest[i]=src[i]; +} + +static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) +{ + int act_comp=0,num_packets=0,y,chained; + stbi__pic_packet packets[10]; + + // this will (should...) cater for even some bizarre stuff like having data + // for the same channel in multiple packets. + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return stbi__errpuc("bad format","too many packets"); + + packet = &packets[num_packets++]; + + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + + act_comp |= packet->channel; + + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); + if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? + + for(y=0; ytype) { + default: + return stbi__errpuc("bad format","packet has bad compression type"); + + case 0: {//uncompressed + int x; + + for(x=0;xchannel,dest)) + return 0; + break; + } + + case 1://Pure RLE + { + int left=width, i; + + while (left>0) { + stbi_uc count,value[4]; + + count=stbi__get8(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); + + if (count > left) + count = (stbi_uc) left; + + if (!stbi__readval(s,packet->channel,value)) return 0; + + for(i=0; ichannel,dest,value); + left -= count; + } + } + break; + + case 2: {//Mixed RLE + int left=width; + while (left>0) { + int count = stbi__get8(s), i; + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); + + if (count >= 128) { // Repeated + stbi_uc value[4]; + + if (count==128) + count = stbi__get16be(s); + else + count -= 127; + if (count > left) + return stbi__errpuc("bad file","scanline overrun"); + + if (!stbi__readval(s,packet->channel,value)) + return 0; + + for(i=0;ichannel,dest,value); + } else { // Raw + ++count; + if (count>left) return stbi__errpuc("bad file","scanline overrun"); + + for(i=0;ichannel,dest)) + return 0; + } + left-=count; + } + break; + } + } + } + } + + return result; +} + +static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri) +{ + stbi_uc *result; + int i, x,y, internal_comp; + STBI_NOTUSED(ri); + + if (!comp) comp = &internal_comp; + + for (i=0; i<92; ++i) + stbi__get8(s); + + x = stbi__get16be(s); + y = stbi__get16be(s); + + if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); + if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); + + stbi__get32be(s); //skip `ratio' + stbi__get16be(s); //skip `fields' + stbi__get16be(s); //skip `pad' + + // intermediate buffer is RGBA + result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0); + if (!result) return stbi__errpuc("outofmem", "Out of memory"); + memset(result, 0xff, x*y*4); + + if (!stbi__pic_load_core(s,x,y,comp, result)) { + STBI_FREE(result); + result=0; + } + *px = x; + *py = y; + if (req_comp == 0) req_comp = *comp; + result=stbi__convert_format(result,4,req_comp,x,y); + + return result; +} + +static int stbi__pic_test(stbi__context *s) +{ + int r = stbi__pic_test_core(s); + stbi__rewind(s); + return r; +} +#endif + +// ************************************************************************************************* +// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb + +#ifndef STBI_NO_GIF +typedef struct +{ + stbi__int16 prefix; + stbi_uc first; + stbi_uc suffix; +} stbi__gif_lzw; + +typedef struct +{ + int w,h; + stbi_uc *out; // output buffer (always 4 components) + stbi_uc *background; // The current "background" as far as a gif is concerned + stbi_uc *history; + int flags, bgindex, ratio, transparent, eflags; + stbi_uc pal[256][4]; + stbi_uc lpal[256][4]; + stbi__gif_lzw codes[8192]; + stbi_uc *color_table; + int parse, step; + int lflags; + int start_x, start_y; + int max_x, max_y; + int cur_x, cur_y; + int line_size; + int delay; +} stbi__gif; + +static int stbi__gif_test_raw(stbi__context *s) +{ + int sz; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; + sz = stbi__get8(s); + if (sz != '9' && sz != '7') return 0; + if (stbi__get8(s) != 'a') return 0; + return 1; +} + +static int stbi__gif_test(stbi__context *s) +{ + int r = stbi__gif_test_raw(s); + stbi__rewind(s); + return r; +} + +static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) +{ + int i; + for (i=0; i < num_entries; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + pal[i][3] = transp == i ? 0 : 255; + } +} + +static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) +{ + stbi_uc version; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') + return stbi__err("not GIF", "Corrupt GIF"); + + version = stbi__get8(s); + if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); + if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); + + stbi__g_failure_reason = ""; + g->w = stbi__get16le(s); + g->h = stbi__get16le(s); + g->flags = stbi__get8(s); + g->bgindex = stbi__get8(s); + g->ratio = stbi__get8(s); + g->transparent = -1; + + if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + + if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments + + if (is_info) return 1; + + if (g->flags & 0x80) + stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); + + return 1; +} + +static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); + if (!g) return stbi__err("outofmem", "Out of memory"); + if (!stbi__gif_header(s, g, comp, 1)) { + STBI_FREE(g); + stbi__rewind( s ); + return 0; + } + if (x) *x = g->w; + if (y) *y = g->h; + STBI_FREE(g); + return 1; +} + +static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) +{ + stbi_uc *p, *c; + int idx; + + // recurse to decode the prefixes, since the linked-list is backwards, + // and working backwards through an interleaved image would be nasty + if (g->codes[code].prefix >= 0) + stbi__out_gif_code(g, g->codes[code].prefix); + + if (g->cur_y >= g->max_y) return; + + idx = g->cur_x + g->cur_y; + p = &g->out[idx]; + g->history[idx / 4] = 1; + + c = &g->color_table[g->codes[code].suffix * 4]; + if (c[3] > 128) { // don't render transparent pixels; + p[0] = c[2]; + p[1] = c[1]; + p[2] = c[0]; + p[3] = c[3]; + } + g->cur_x += 4; + + if (g->cur_x >= g->max_x) { + g->cur_x = g->start_x; + g->cur_y += g->step; + + while (g->cur_y >= g->max_y && g->parse > 0) { + g->step = (1 << g->parse) * g->line_size; + g->cur_y = g->start_y + (g->step >> 1); + --g->parse; + } + } +} + +static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) +{ + stbi_uc lzw_cs; + stbi__int32 len, init_code; + stbi__uint32 first; + stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; + stbi__gif_lzw *p; + + lzw_cs = stbi__get8(s); + if (lzw_cs > 12) return NULL; + clear = 1 << lzw_cs; + first = 1; + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + bits = 0; + valid_bits = 0; + for (init_code = 0; init_code < clear; init_code++) { + g->codes[init_code].prefix = -1; + g->codes[init_code].first = (stbi_uc) init_code; + g->codes[init_code].suffix = (stbi_uc) init_code; + } + + // support no starting clear code + avail = clear+2; + oldcode = -1; + + len = 0; + for(;;) { + if (valid_bits < codesize) { + if (len == 0) { + len = stbi__get8(s); // start new block + if (len == 0) + return g->out; + } + --len; + bits |= (stbi__int32) stbi__get8(s) << valid_bits; + valid_bits += 8; + } else { + stbi__int32 code = bits & codemask; + bits >>= codesize; + valid_bits -= codesize; + // @OPTIMIZE: is there some way we can accelerate the non-clear path? + if (code == clear) { // clear code + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + avail = clear + 2; + oldcode = -1; + first = 0; + } else if (code == clear + 1) { // end of stream code + stbi__skip(s, len); + while ((len = stbi__get8(s)) > 0) + stbi__skip(s,len); + return g->out; + } else if (code <= avail) { + if (first) { + return stbi__errpuc("no clear code", "Corrupt GIF"); + } + + if (oldcode >= 0) { + p = &g->codes[avail++]; + if (avail > 8192) { + return stbi__errpuc("too many codes", "Corrupt GIF"); + } + + p->prefix = (stbi__int16) oldcode; + p->first = g->codes[oldcode].first; + p->suffix = (code == avail) ? p->first : g->codes[code].first; + } else if (code == avail) + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + + stbi__out_gif_code(g, (stbi__uint16) code); + + if ((avail & codemask) == 0 && avail <= 0x0FFF) { + codesize++; + codemask = (1 << codesize) - 1; + } + + oldcode = code; + } else { + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + } + } + } +} + +// this function is designed to support animated gifs, although stb_image doesn't support it +// two back is the image from two frames ago, used for a very specific disposal format +static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) +{ + int dispose; + int first_frame; + int pi; + int pcount; + STBI_NOTUSED(req_comp); + + // on first frame, any non-written pixels get the background colour (non-transparent) + first_frame = 0; + if (g->out == 0) { + if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header + if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) + return stbi__errpuc("too large", "GIF image is too large"); + pcount = g->w * g->h; + g->out = (stbi_uc *) stbi__malloc(4 * pcount); + g->background = (stbi_uc *) stbi__malloc(4 * pcount); + g->history = (stbi_uc *) stbi__malloc(pcount); + if (!g->out || !g->background || !g->history) + return stbi__errpuc("outofmem", "Out of memory"); + + // image is treated as "transparent" at the start - ie, nothing overwrites the current background; + // background colour is only used for pixels that are not rendered first frame, after that "background" + // color refers to the color that was there the previous frame. + memset(g->out, 0x00, 4 * pcount); + memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) + memset(g->history, 0x00, pcount); // pixels that were affected previous frame + first_frame = 1; + } else { + // second frame - how do we dispose of the previous one? + dispose = (g->eflags & 0x1C) >> 2; + pcount = g->w * g->h; + + if ((dispose == 3) && (two_back == 0)) { + dispose = 2; // if I don't have an image to revert back to, default to the old background + } + + if (dispose == 3) { // use previous graphic + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 ); + } + } + } else if (dispose == 2) { + // restore what was changed last frame to background before that frame; + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 ); + } + } + } else { + // This is a non-disposal case eithe way, so just + // leave the pixels as is, and they will become the new background + // 1: do not dispose + // 0: not specified. + } + + // background is what out is after the undoing of the previou frame; + memcpy( g->background, g->out, 4 * g->w * g->h ); + } + + // clear my history; + memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame + + for (;;) { + int tag = stbi__get8(s); + switch (tag) { + case 0x2C: /* Image Descriptor */ + { + stbi__int32 x, y, w, h; + stbi_uc *o; + + x = stbi__get16le(s); + y = stbi__get16le(s); + w = stbi__get16le(s); + h = stbi__get16le(s); + if (((x + w) > (g->w)) || ((y + h) > (g->h))) + return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); + + g->line_size = g->w * 4; + g->start_x = x * 4; + g->start_y = y * g->line_size; + g->max_x = g->start_x + w * 4; + g->max_y = g->start_y + h * g->line_size; + g->cur_x = g->start_x; + g->cur_y = g->start_y; + + // if the width of the specified rectangle is 0, that means + // we may not see *any* pixels or the image is malformed; + // to make sure this is caught, move the current y down to + // max_y (which is what out_gif_code checks). + if (w == 0) + g->cur_y = g->max_y; + + g->lflags = stbi__get8(s); + + if (g->lflags & 0x40) { + g->step = 8 * g->line_size; // first interlaced spacing + g->parse = 3; + } else { + g->step = g->line_size; + g->parse = 0; + } + + if (g->lflags & 0x80) { + stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); + g->color_table = (stbi_uc *) g->lpal; + } else if (g->flags & 0x80) { + g->color_table = (stbi_uc *) g->pal; + } else + return stbi__errpuc("missing color table", "Corrupt GIF"); + + o = stbi__process_gif_raster(s, g); + if (!o) return NULL; + + // if this was the first frame, + pcount = g->w * g->h; + if (first_frame && (g->bgindex > 0)) { + // if first frame, any pixel not drawn to gets the background color + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi] == 0) { + g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; + memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 ); + } + } + } + + return o; + } + + case 0x21: // Comment Extension. + { + int len; + int ext = stbi__get8(s); + if (ext == 0xF9) { // Graphic Control Extension. + len = stbi__get8(s); + if (len == 4) { + g->eflags = stbi__get8(s); + g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. + + // unset old transparent + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 255; + } + if (g->eflags & 0x01) { + g->transparent = stbi__get8(s); + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 0; + } + } else { + // don't need transparent + stbi__skip(s, 1); + g->transparent = -1; + } + } else { + stbi__skip(s, len); + break; + } + } + while ((len = stbi__get8(s)) != 0) { + stbi__skip(s, len); + } + break; + } + + case 0x3B: // gif stream termination code + return (stbi_uc *) s; // using '1' causes warning on some compilers + + default: + return stbi__errpuc("unknown code", "Corrupt GIF"); + } + } +} + +static void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays) +{ + STBI_FREE(g->out); + STBI_FREE(g->history); + STBI_FREE(g->background); + + if (out) STBI_FREE(out); + if (delays && *delays) STBI_FREE(*delays); + return stbi__errpuc("outofmem", "Out of memory"); +} + +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + if (stbi__gif_test(s)) { + int layers = 0; + stbi_uc *u = 0; + stbi_uc *out = 0; + stbi_uc *two_back = 0; + stbi__gif g; + int stride; + int out_size = 0; + int delays_size = 0; + + STBI_NOTUSED(out_size); + STBI_NOTUSED(delays_size); + + memset(&g, 0, sizeof(g)); + if (delays) { + *delays = 0; + } + + do { + u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + + if (u) { + *x = g.w; + *y = g.h; + ++layers; + stride = g.w * g.h * 4; + + if (out) { + void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride ); + if (!tmp) + return stbi__load_gif_main_outofmem(&g, out, delays); + else { + out = (stbi_uc*) tmp; + out_size = layers * stride; + } + + if (delays) { + int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers ); + if (!new_delays) + return stbi__load_gif_main_outofmem(&g, out, delays); + *delays = new_delays; + delays_size = layers * sizeof(int); + } + } else { + out = (stbi_uc*)stbi__malloc( layers * stride ); + if (!out) + return stbi__load_gif_main_outofmem(&g, out, delays); + out_size = layers * stride; + if (delays) { + *delays = (int*) stbi__malloc( layers * sizeof(int) ); + if (!*delays) + return stbi__load_gif_main_outofmem(&g, out, delays); + delays_size = layers * sizeof(int); + } + } + memcpy( out + ((layers - 1) * stride), u, stride ); + if (layers >= 2) { + two_back = out - 2 * stride; + } + + if (delays) { + (*delays)[layers - 1U] = g.delay; + } + } + } while (u != 0); + + // free temp buffer; + STBI_FREE(g.out); + STBI_FREE(g.history); + STBI_FREE(g.background); + + // do the final conversion after loading everything; + if (req_comp && req_comp != 4) + out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); + + *z = layers; + return out; + } else { + return stbi__errpuc("not GIF", "Image was not as a gif type."); + } +} + +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *u = 0; + stbi__gif g; + memset(&g, 0, sizeof(g)); + STBI_NOTUSED(ri); + + u = stbi__gif_load_next(s, &g, comp, req_comp, 0); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + if (u) { + *x = g.w; + *y = g.h; + + // moved conversion to after successful load so that the same + // can be done for multiple frames. + if (req_comp && req_comp != 4) + u = stbi__convert_format(u, 4, req_comp, g.w, g.h); + } else if (g.out) { + // if there was an error and we allocated an image buffer, free it! + STBI_FREE(g.out); + } + + // free buffers needed for multiple frame loading; + STBI_FREE(g.history); + STBI_FREE(g.background); + + return u; +} + +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) +{ + return stbi__gif_info_raw(s,x,y,comp); +} +#endif + +// ************************************************************************************************* +// Radiance RGBE HDR loader +// originally by Nicolas Schulz +#ifndef STBI_NO_HDR +static int stbi__hdr_test_core(stbi__context *s, const char *signature) +{ + int i; + for (i=0; signature[i]; ++i) + if (stbi__get8(s) != signature[i]) + return 0; + stbi__rewind(s); + return 1; +} + +static int stbi__hdr_test(stbi__context* s) +{ + int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); + stbi__rewind(s); + if(!r) { + r = stbi__hdr_test_core(s, "#?RGBE\n"); + stbi__rewind(s); + } + return r; +} + +#define STBI__HDR_BUFLEN 1024 +static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) +{ + int len=0; + char c = '\0'; + + c = (char) stbi__get8(z); + + while (!stbi__at_eof(z) && c != '\n') { + buffer[len++] = c; + if (len == STBI__HDR_BUFLEN-1) { + // flush to end of line + while (!stbi__at_eof(z) && stbi__get8(z) != '\n') + ; + break; + } + c = (char) stbi__get8(z); + } + + buffer[len] = 0; + return buffer; +} + +static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) +{ + if ( input[3] != 0 ) { + float f1; + // Exponent + f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); + if (req_comp <= 2) + output[0] = (input[0] + input[1] + input[2]) * f1 / 3; + else { + output[0] = input[0] * f1; + output[1] = input[1] * f1; + output[2] = input[2] * f1; + } + if (req_comp == 2) output[1] = 1; + if (req_comp == 4) output[3] = 1; + } else { + switch (req_comp) { + case 4: output[3] = 1; /* fallthrough */ + case 3: output[0] = output[1] = output[2] = 0; + break; + case 2: output[1] = 1; /* fallthrough */ + case 1: output[0] = 0; + break; + } + } +} + +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int width, height; + stbi_uc *scanline; + float *hdr_data; + int len; + unsigned char count, value; + int i, j, k, c1,c2, z; + const char *headerToken; + STBI_NOTUSED(ri); + + // Check identifier + headerToken = stbi__hdr_gettoken(s,buffer); + if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) + return stbi__errpf("not HDR", "Corrupt HDR image"); + + // Parse header + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); + + // Parse width and height + // can't use sscanf() if we're not using stdio! + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + height = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + width = (int) strtol(token, NULL, 10); + + if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + + *x = width; + *y = height; + + if (comp) *comp = 3; + if (req_comp == 0) req_comp = 3; + + if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) + return stbi__errpf("too large", "HDR image is too large"); + + // Read data + hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); + if (!hdr_data) + return stbi__errpf("outofmem", "Out of memory"); + + // Load image data + // image data is stored as some number of sca + if ( width < 8 || width >= 32768) { + // Read flat data + for (j=0; j < height; ++j) { + for (i=0; i < width; ++i) { + stbi_uc rgbe[4]; + main_decode_loop: + stbi__getn(s, rgbe, 4); + stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); + } + } + } else { + // Read RLE-encoded data + scanline = NULL; + + for (j = 0; j < height; ++j) { + c1 = stbi__get8(s); + c2 = stbi__get8(s); + len = stbi__get8(s); + if (c1 != 2 || c2 != 2 || (len & 0x80)) { + // not run-length encoded, so we have to actually use THIS data as a decoded + // pixel (note this can't be a valid pixel--one of RGB must be >= 128) + stbi_uc rgbe[4]; + rgbe[0] = (stbi_uc) c1; + rgbe[1] = (stbi_uc) c2; + rgbe[2] = (stbi_uc) len; + rgbe[3] = (stbi_uc) stbi__get8(s); + stbi__hdr_convert(hdr_data, rgbe, req_comp); + i = 1; + j = 0; + STBI_FREE(scanline); + goto main_decode_loop; // yes, this makes no sense + } + len <<= 8; + len |= stbi__get8(s); + if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } + if (scanline == NULL) { + scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); + if (!scanline) { + STBI_FREE(hdr_data); + return stbi__errpf("outofmem", "Out of memory"); + } + } + + for (k = 0; k < 4; ++k) { + int nleft; + i = 0; + while ((nleft = width - i) > 0) { + count = stbi__get8(s); + if (count > 128) { + // Run + value = stbi__get8(s); + count -= 128; + if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = value; + } else { + // Dump + if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = stbi__get8(s); + } + } + } + for (i=0; i < width; ++i) + stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); + } + if (scanline) + STBI_FREE(scanline); + } + + return hdr_data; +} + +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int dummy; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (stbi__hdr_test(s) == 0) { + stbi__rewind( s ); + return 0; + } + + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) { + stbi__rewind( s ); + return 0; + } + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *y = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *x = (int) strtol(token, NULL, 10); + *comp = 3; + return 1; +} +#endif // STBI_NO_HDR + +#ifndef STBI_NO_BMP +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) +{ + void *p; + stbi__bmp_data info; + + info.all_a = 255; + p = stbi__bmp_parse_header(s, &info); + if (p == NULL) { + stbi__rewind( s ); + return 0; + } + if (x) *x = s->img_x; + if (y) *y = s->img_y; + if (comp) { + if (info.bpp == 24 && info.ma == 0xff000000) + *comp = 3; + else + *comp = info.ma ? 4 : 3; + } + return 1; +} +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) +{ + int channelCount, dummy, depth; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + *y = stbi__get32be(s); + *x = stbi__get32be(s); + depth = stbi__get16be(s); + if (depth != 8 && depth != 16) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 3) { + stbi__rewind( s ); + return 0; + } + *comp = 4; + return 1; +} + +static int stbi__psd_is16(stbi__context *s) +{ + int channelCount, depth; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + STBI_NOTUSED(stbi__get32be(s)); + STBI_NOTUSED(stbi__get32be(s)); + depth = stbi__get16be(s); + if (depth != 16) { + stbi__rewind( s ); + return 0; + } + return 1; +} +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) +{ + int act_comp=0,num_packets=0,chained,dummy; + stbi__pic_packet packets[10]; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { + stbi__rewind(s); + return 0; + } + + stbi__skip(s, 88); + + *x = stbi__get16be(s); + *y = stbi__get16be(s); + if (stbi__at_eof(s)) { + stbi__rewind( s); + return 0; + } + if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { + stbi__rewind( s ); + return 0; + } + + stbi__skip(s, 8); + + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return 0; + + packet = &packets[num_packets++]; + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + act_comp |= packet->channel; + + if (stbi__at_eof(s)) { + stbi__rewind( s ); + return 0; + } + if (packet->size != 8) { + stbi__rewind( s ); + return 0; + } + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); + + return 1; +} +#endif + +// ************************************************************************************************* +// Portable Gray Map and Portable Pixel Map loader +// by Ken Miller +// +// PGM: http://netpbm.sourceforge.net/doc/pgm.html +// PPM: http://netpbm.sourceforge.net/doc/ppm.html +// +// Known limitations: +// Does not support comments in the header section +// Does not support ASCII image data (formats P2 and P3) + +#ifndef STBI_NO_PNM + +static int stbi__pnm_test(stbi__context *s) +{ + char p, t; + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind( s ); + return 0; + } + return 1; +} + +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + STBI_NOTUSED(ri); + + ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n); + if (ri->bits_per_channel == 0) + return 0; + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + + if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0)) + return stbi__errpuc("too large", "PNM too large"); + + out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) { + STBI_FREE(out); + return stbi__errpuc("bad PNM", "PNM file truncated"); + } + + if (req_comp && req_comp != s->img_n) { + if (ri->bits_per_channel == 16) { + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y); + } else { + out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); + } + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + return out; +} + +static int stbi__pnm_isspace(char c) +{ + return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; +} + +static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) +{ + for (;;) { + while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) + *c = (char) stbi__get8(s); + + if (stbi__at_eof(s) || *c != '#') + break; + + while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) + *c = (char) stbi__get8(s); + } +} + +static int stbi__pnm_isdigit(char c) +{ + return c >= '0' && c <= '9'; +} + +static int stbi__pnm_getinteger(stbi__context *s, char *c) +{ + int value = 0; + + while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { + value = value*10 + (*c - '0'); + *c = (char) stbi__get8(s); + if((value > 214748364) || (value == 214748364 && *c > '7')) + return stbi__err("integer parse overflow", "Parsing an integer in the PPM header overflowed a 32-bit int"); + } + + return value; +} + +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) +{ + int maxv, dummy; + char c, p, t; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + stbi__rewind(s); + + // Get identifier + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind(s); + return 0; + } + + *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm + + c = (char) stbi__get8(s); + stbi__pnm_skip_whitespace(s, &c); + + *x = stbi__pnm_getinteger(s, &c); // read width + if(*x == 0) + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); + stbi__pnm_skip_whitespace(s, &c); + + *y = stbi__pnm_getinteger(s, &c); // read height + if (*y == 0) + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); + stbi__pnm_skip_whitespace(s, &c); + + maxv = stbi__pnm_getinteger(s, &c); // read max value + if (maxv > 65535) + return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images"); + else if (maxv > 255) + return 16; + else + return 8; +} + +static int stbi__pnm_is16(stbi__context *s) +{ + if (stbi__pnm_info(s, NULL, NULL, NULL) == 16) + return 1; + return 0; +} +#endif + +static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) +{ + #ifndef STBI_NO_JPEG + if (stbi__jpeg_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNG + if (stbi__png_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_GIF + if (stbi__gif_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_BMP + if (stbi__bmp_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PIC + if (stbi__pic_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNM + if (stbi__pnm_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_info(s, x, y, comp)) return 1; + #endif + + // test tga last because it's a crappy test! + #ifndef STBI_NO_TGA + if (stbi__tga_info(s, x, y, comp)) + return 1; + #endif + return stbi__err("unknown image type", "Image not of any known type, or corrupt"); +} + +static int stbi__is_16_main(stbi__context *s) +{ + #ifndef STBI_NO_PNG + if (stbi__png_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PNM + if (stbi__pnm_is16(s)) return 1; + #endif + return 0; +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_info_from_file(f, x, y, comp); + fclose(f); + return result; +} + +STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__info_main(&s,x,y,comp); + fseek(f,pos,SEEK_SET); + return r; +} + +STBIDEF int stbi_is_16_bit(char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_is_16_bit_from_file(f); + fclose(f); + return result; +} + +STBIDEF int stbi_is_16_bit_from_file(FILE *f) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__is_16_main(&s); + fseek(f,pos,SEEK_SET); + return r; +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__is_16_main(&s); +} + +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__is_16_main(&s); +} + +#endif // STB_IMAGE_IMPLEMENTATION + +/* + revision history: + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug + 1-bit BMP + *_is_16_bit api + avoid warnings + 2.16 (2017-07-23) all functions have 16-bit variants; + STBI_NO_STDIO works again; + compilation fixes; + fix rounding in unpremultiply; + optimize vertical flip; + disable raw_len validation; + documentation fixes + 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; + warning fixes; disable run-time SSE detection on gcc; + uniform handling of optional "return" values; + thread-safe initialization of zlib tables + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) allocate large structures on the stack + remove white matting for transparent PSD + fix reported channel count for PNG & BMP + re-enable SSE2 in non-gcc 64-bit + support RGB-formatted JPEG + read 16-bit PNGs (only as 8-bit) + 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED + 2.09 (2016-01-16) allow comments in PNM files + 16-bit-per-pixel TGA (not bit-per-component) + info() for TGA could break due to .hdr handling + info() for BMP to shares code instead of sloppy parse + can use STBI_REALLOC_SIZED if allocator doesn't support realloc + code cleanup + 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA + 2.07 (2015-09-13) fix compiler warnings + partial animated GIF support + limited 16-bpc PSD support + #ifdef unused functions + bug with < 92 byte PIC,PNM,HDR,TGA + 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value + 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning + 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit + 2.03 (2015-04-12) extra corruption checking (mmozeiko) + stbi_set_flip_vertically_on_load (nguillemot) + fix NEON support; fix mingw support + 2.02 (2015-01-19) fix incorrect assert, fix warning + 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 + 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG + 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) + progressive JPEG (stb) + PGM/PPM support (Ken Miller) + STBI_MALLOC,STBI_REALLOC,STBI_FREE + GIF bugfix -- seemingly never worked + STBI_NO_*, STBI_ONLY_* + 1.48 (2014-12-14) fix incorrectly-named assert() + 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) + optimize PNG (ryg) + fix bug in interlaced PNG with user-specified channel count (stb) + 1.46 (2014-08-26) + fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG + 1.45 (2014-08-16) + fix MSVC-ARM internal compiler error by wrapping malloc + 1.44 (2014-08-07) + various warning fixes from Ronny Chevalier + 1.43 (2014-07-15) + fix MSVC-only compiler problem in code changed in 1.42 + 1.42 (2014-07-09) + don't define _CRT_SECURE_NO_WARNINGS (affects user code) + fixes to stbi__cleanup_jpeg path + added STBI_ASSERT to avoid requiring assert.h + 1.41 (2014-06-25) + fix search&replace from 1.36 that messed up comments/error messages + 1.40 (2014-06-22) + fix gcc struct-initialization warning + 1.39 (2014-06-15) + fix to TGA optimization when req_comp != number of components in TGA; + fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) + add support for BMP version 5 (more ignored fields) + 1.38 (2014-06-06) + suppress MSVC warnings on integer casts truncating values + fix accidental rename of 'skip' field of I/O + 1.37 (2014-06-04) + remove duplicate typedef + 1.36 (2014-06-03) + convert to header file single-file library + if de-iphone isn't set, load iphone images color-swapped instead of returning NULL + 1.35 (2014-05-27) + various warnings + fix broken STBI_SIMD path + fix bug where stbi_load_from_file no longer left file pointer in correct place + fix broken non-easy path for 32-bit BMP (possibly never used) + TGA optimization by Arseny Kapoulkine + 1.34 (unknown) + use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case + 1.33 (2011-07-14) + make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements + 1.32 (2011-07-13) + support for "info" function for all supported filetypes (SpartanJ) + 1.31 (2011-06-20) + a few more leak fixes, bug in PNG handling (SpartanJ) + 1.30 (2011-06-11) + added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) + removed deprecated format-specific test/load functions + removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway + error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) + fix inefficiency in decoding 32-bit BMP (David Woo) + 1.29 (2010-08-16) + various warning fixes from Aurelien Pocheville + 1.28 (2010-08-01) + fix bug in GIF palette transparency (SpartanJ) + 1.27 (2010-08-01) + cast-to-stbi_uc to fix warnings + 1.26 (2010-07-24) + fix bug in file buffering for PNG reported by SpartanJ + 1.25 (2010-07-17) + refix trans_data warning (Won Chun) + 1.24 (2010-07-12) + perf improvements reading from files on platforms with lock-heavy fgetc() + minor perf improvements for jpeg + deprecated type-specific functions so we'll get feedback if they're needed + attempt to fix trans_data warning (Won Chun) + 1.23 fixed bug in iPhone support + 1.22 (2010-07-10) + removed image *writing* support + stbi_info support from Jetro Lauha + GIF support from Jean-Marc Lienher + iPhone PNG-extensions from James Brown + warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) + 1.21 fix use of 'stbi_uc' in header (reported by jon blow) + 1.20 added support for Softimage PIC, by Tom Seddon + 1.19 bug in interlaced PNG corruption check (found by ryg) + 1.18 (2008-08-02) + fix a threading bug (local mutable static) + 1.17 support interlaced PNG + 1.16 major bugfix - stbi__convert_format converted one too many pixels + 1.15 initialize some fields for thread safety + 1.14 fix threadsafe conversion bug + header-file-only version (#define STBI_HEADER_FILE_ONLY before including) + 1.13 threadsafe + 1.12 const qualifiers in the API + 1.11 Support installable IDCT, colorspace conversion routines + 1.10 Fixes for 64-bit (don't use "unsigned long") + optimized upsampling by Fabian "ryg" Giesen + 1.09 Fix format-conversion for PSD code (bad global variables!) + 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz + 1.07 attempt to fix C++ warning/errors again + 1.06 attempt to fix C++ warning/errors again + 1.05 fix TGA loading to return correct *comp and use good luminance calc + 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free + 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR + 1.02 support for (subset of) HDR files, float interface for preferred access to them + 1.01 fix bug: possible bug in handling right-side up bmps... not sure + fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all + 1.00 interface to zlib that skips zlib header + 0.99 correct handling of alpha in palette + 0.98 TGA loader by lonesock; dynamically add loaders (untested) + 0.97 jpeg errors on too large a file; also catch another malloc failure + 0.96 fix detection of invalid v value - particleman@mollyrocket forum + 0.95 during header scan, seek to markers in case of padding + 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same + 0.93 handle jpegtran output; verbose errors + 0.92 read 4,8,16,24,32-bit BMP files of several formats + 0.91 output 24-bit Windows 3.0 BMP files + 0.90 fix a few more warnings; bump version number to approach 1.0 + 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd + 0.60 fix compiling as c++ + 0.59 fix warnings: merge Dave Moore's -Wall fixes + 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian + 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available + 0.56 fix bug: zlib uncompressed mode len vs. nlen + 0.55 fix bug: restart_interval not initialized to 0 + 0.54 allow NULL for 'int *comp' + 0.53 fix bug in png 3->4; speedup png decoding + 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments + 0.51 obey req_comp requests, 1-component jpegs return as 1-component, + on 'test' only check type, not whether we support this variant + 0.50 (2006-11-19) + first released version +*/ + + +/* +------------------------------------------------------------------------------ +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. +------------------------------------------------------------------------------ +*/ diff --git a/include/box3d/base.h b/include/box3d/base.h new file mode 100644 index 0000000..4f16490 --- /dev/null +++ b/include/box3d/base.h @@ -0,0 +1,169 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +// clang-format off +// +// Shared library macros +#if defined(_WIN32) && defined(box3d_EXPORTS) + // build the Windows DLL + #define BOX3D_EXPORT __declspec(dllexport) +#elif defined(_WIN32) && defined(BOX3D_DLL) + // using the Windows DLL + #define BOX3D_EXPORT __declspec(dllimport) +#elif defined(box3d_EXPORTS) + // building or using the shared library + #define BOX3D_EXPORT __attribute__((visibility("default"))) +#else + // static library + #define BOX3D_EXPORT +#endif + +// C++ macros +#ifdef __cplusplus + #define B3_API extern "C" BOX3D_EXPORT + #define B3_INLINE inline + +#if defined( _MSC_VER ) + #define B3_FORCE_INLINE __forceinline +#elif defined( __GNUC__ ) || defined( __clang__ ) + #define B3_FORCE_INLINE inline __attribute__((always_inline)) +#else + #define B3_FORCE_INLINE inline +#endif + + #define B3_LITERAL(T) T + #define B3_ZERO_INIT {} +#else + #define B3_API BOX3D_EXPORT + #define B3_INLINE static inline + +#if defined( _MSC_VER ) + #define B3_FORCE_INLINE static __forceinline +#elif defined( __GNUC__ ) || defined( __clang__ ) + #define B3_FORCE_INLINE static inline __attribute__((always_inline)) +#else + #define B3_FORCE_INLINE static inline +#endif + +/// Used for C literals like (b3Vec3){1.0f, 2.0f, 3.0f} where C++ requires b3Vec3{1.0f, 2.0f, 3.0f} + #define B3_LITERAL(T) (T) + #define B3_ZERO_INIT {0} +#endif +// clang-format on + +#if defined( BOX3D_VALIDATE ) && !defined( NDEBUG ) +#define B3_ENABLE_VALIDATION 1 +#else +#define B3_ENABLE_VALIDATION 0 +#endif + +/** + * @defgroup base Base + * Base functionality + * @{ + */ + +/// This is used to indicate null for interfaces that work with indices instead of pointers +#define B3_NULL_INDEX -1 + +/// 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* b3AllocFcn( int32_t size, int32_t alignment ); + +/// Prototype for user free function. +/// @param mem the memory previously allocated through `b3AllocFcn` +typedef void b3FreeFcn( void* mem ); + +/// Prototype for the user assert callback. Return 0 to skip the debugger break. +typedef int b3AssertFcn( const char* condition, const char* fileName, int lineNumber ); + +/// Prototype for user log callback. Used to log warnings. +typedef void b3LogFcn( const char* message ); + +/// This allows the user to override the allocation functions. These should be +/// set during application startup. +B3_API void b3SetAllocator( b3AllocFcn* allocFcn, b3FreeFcn* freeFcn ); + +/// Total bytes allocated by Box3D +B3_API int32_t b3GetByteCount( void ); + +/// Override the default assert callback. +/// @param assertFcn a non-null assert callback +B3_API void b3SetAssertFcn( b3AssertFcn* assertFcn ); + +// see https://github.com/scottt/debugbreak +#if defined( _MSC_VER ) +#define B3_BREAKPOINT __debugbreak() +#elif defined( __GNUC__ ) || defined( __clang__ ) +#define B3_BREAKPOINT __builtin_trap() +#else +// Unknown compiler +#include +#define B3_BREAKPOINT assert( 0 ) +#endif + +#if !defined( NDEBUG ) || defined( B3_ENABLE_ASSERT ) +B3_API int b3InternalAssert( const char* condition, const char* fileName, int lineNumber ); +#define B3_ASSERT( condition ) \ + ( (void)( ( !!( condition ) ) || ( b3InternalAssert( #condition, __FILE__, (int)( __LINE__ ) ), 0 ) ) ) +#else +#define B3_ASSERT( ... ) ( (void)0 ) +#endif + +#if B3_ENABLE_VALIDATION +// Floating point tolerance checks should use this instead of the regular assertion +#define B3_VALIDATE( condition ) B3_ASSERT( condition ) +#else +#define B3_VALIDATE( ... ) ( (void)0 ) +#endif + +/// Override the default logging callback. +B3_API void b3SetLogFcn( b3LogFcn* logFcn ); + +/// Version numbering scheme. +/// See https://semver.org/ +typedef struct b3Version +{ + /// Significant changes + int major; + + /// Incremental changes + int minor; + + /// Bug fixes + int revision; +} b3Version; + +/// Get the current version of Box2D +B3_API b3Version b3GetVersion( void ); + +/**@}*/ + +//! @cond + +/// Get the absolute number of system ticks. The value is platform specific. +B3_API uint64_t b3GetTicks( void ); + +/// Get the milliseconds passed from an initial tick value. +B3_API float b3GetMilliseconds( uint64_t ticks ); + +/// Get the milliseconds passed from an initial tick value. +B3_API float b3GetMillisecondsAndReset( uint64_t* ticks ); + +/// Yield to be used in a busy loop. +B3_API void b3Yield( void ); + +// Simple djb2 hash function for determinism testing +#define B3_HASH_INIT 5381 +B3_API uint32_t b3Hash( uint32_t hash, const uint8_t* data, int count ); + +// Dump file support functions +B3_API void b3WriteBinaryFile( void* data, int size, const char* fileName ); +B3_API void* b3ReadBinaryFile( const char* prefix, const char* fileName, int* memSize ); + +//! @endcond diff --git a/include/box3d/box3d.h b/include/box3d/box3d.h new file mode 100644 index 0000000..8f369f3 --- /dev/null +++ b/include/box3d/box3d.h @@ -0,0 +1,1492 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "base.h" +#include "collision.h" +#include "id.h" +#include "math_functions.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. +B3_API b3WorldId b3CreateWorld( const b3WorldDef* def ); + +/// Destroy a world +B3_API void b3DestroyWorld( b3WorldId worldId ); + +/// Get the current number of worlds +B3_API int b3GetWorldCount( void ); + +/// Get the maximum number of simultaneous worlds that have been created +B3_API int b3GetMaxWorldCount( void ); + +/// World id validation. Provides validation for up to 64K allocations. +B3_API bool b3World_IsValid( b3WorldId 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. +B3_API void b3World_Step( b3WorldId worldId, float timeStep, int subStepCount ); + +/// Call this to draw shapes and other debug draw data +B3_API void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits ); + +/// Get the body events for the current time step. The event data is transient. Do not store a reference to this data. +B3_API b3BodyEvents b3World_GetBodyEvents( b3WorldId worldId ); + +/// Get sensor events for the current time step. The event data is transient. Do not store a reference to this data. +B3_API b3SensorEvents b3World_GetSensorEvents( b3WorldId worldId ); + +/// Get contact events for this current time step. The event data is transient. Do not store a reference to this data. +B3_API b3ContactEvents b3World_GetContactEvents( b3WorldId worldId ); + +/// Get the joint events for the current time step. The event data is transient. Do not store a reference to this data. +B3_API b3JointEvents b3World_GetJointEvents( b3WorldId worldId ); + +/// Overlap test for all shapes that *potentially* overlap the provided AABB +B3_API b3TreeStats b3World_OverlapAABB( b3WorldId worldId, b3AABB aabb, b3QueryFilter filter, b3OverlapResultFcn* fcn, + void* context ); + +/// Overlap test for all shapes that overlap the provided shape proxy. +B3_API b3TreeStats b3World_OverlapShape( b3WorldId worldId, const b3ShapeProxy* proxy, b3QueryFilter filter, + b3OverlapResultFcn* 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 +B3_API b3TreeStats b3World_CastRay( b3WorldId worldId, b3Vec3 origin, b3Vec3 translation, b3QueryFilter filter, + b3CastResultFcn* 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 b3World_CastRay() and does not allow for custom filtering. +B3_API b3RayResult b3World_CastRayClosest( b3WorldId worldId, b3Vec3 origin, b3Vec3 translation, b3QueryFilter filter ); + +/// Cast a shape through the world. Similar to a cast ray except that a shape is cast instead of a point. +/// @see b3World_CastRay +B3_API b3TreeStats b3World_CastShape( b3WorldId worldId, const b3ShapeProxy* proxy, b3Vec3 translation, b3QueryFilter filter, + b3CastResultFcn* 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. This is not a good source of information about what the mover is touching. Instead use the planes returned by +/// b3World_CollideMover. +/// @param worldId World to cast the mover against +/// @param mover Capsule mover in world space +/// @param translation Desired mover translation +/// @param filter Contains bit flags to filter unwanted shapes from the results +/// @param fcn Optional callback for custom shape filtering +/// @param context A user context that is passed along to the callback function +/// @return the translation fraction +B3_API float b3World_CastMover( b3WorldId worldId, const b3Capsule* mover, b3Vec3 translation, b3QueryFilter filter, + b3MoverFilterFcn* fcn, void* context ); + +/// Collide a capsule mover with the world, gathering collision planes that can be fed to b3SolvePlanes. Useful for +/// kinematic character movement. +B3_API void b3World_CollideMover( b3WorldId worldId, const b3Capsule* mover, b3QueryFilter filter, b3PlaneResultFcn* 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 b3WorldDef +B3_API void b3World_EnableSleeping( b3WorldId worldId, bool flag ); + +/// Is body sleeping enabled? +B3_API bool b3World_IsSleepingEnabled( b3WorldId 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 b3WorldDef +B3_API void b3World_EnableContinuous( b3WorldId worldId, bool flag ); + +/// Is continuous collision enabled? +B3_API bool b3World_IsContinuousEnabled( b3WorldId 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 b3WorldDef +B3_API void b3World_SetRestitutionThreshold( b3WorldId worldId, float value ); + +/// Get the the restitution speed threshold. Usually in meters per second. +B3_API float b3World_GetRestitutionThreshold( b3WorldId worldId ); + +/// Adjust the hit event threshold. This controls the collision speed needed to generate a b3ContactHitEvent. +/// Usually in meters per second. +/// @see b3WorldDef::hitEventThreshold +B3_API void b3World_SetHitEventThreshold( b3WorldId worldId, float value ); + +/// Get the the hit event speed threshold. Usually in meters per second. +B3_API float b3World_GetHitEventThreshold( b3WorldId worldId ); + +/// Register the custom filter callback. This is optional. +B3_API void b3World_SetCustomFilterCallback( b3WorldId worldId, b3CustomFilterFcn* fcn, void* context ); + +/// Register the pre-solve callback. This is optional. +B3_API void b3World_SetPreSolveCallback( b3WorldId worldId, b3PreSolveFcn* 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 b3WorldDef +B3_API void b3World_SetGravity( b3WorldId worldId, b3Vec3 gravity ); + +/// Get the gravity vector +B3_API b3Vec3 b3World_GetGravity( b3WorldId worldId ); + +/// Apply a radial explosion +/// @param worldId The world id +/// @param explosionDef The explosion definition +B3_API void b3World_Explode( b3WorldId worldId, const b3ExplosionDef* 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 contactSpeed The maximum contact constraint push out speed (meters per second) +/// @note Advanced feature +B3_API void b3World_SetContactTuning( b3WorldId worldId, float hertz, float dampingRatio, float contactSpeed ); + +/// Set the contact point recycling distance. Setting this to zero disables contact point recycling. +/// Usually in meters. +B3_API void b3World_SetContactRecycleDistance( b3WorldId worldId, float recycleDistance ); + +/// Get the contact point recycling distance. Usually in meters. +B3_API float b3World_GetContactRecycleDistance( b3WorldId worldId ); + +/// Set the maximum linear speed. Usually in m/s. +B3_API void b3World_SetMaximumLinearSpeed( b3WorldId worldId, float maximumLinearSpeed ); + +/// Get the maximum linear speed. Usually in m/s. +B3_API float b3World_GetMaximumLinearSpeed( b3WorldId worldId ); + +/// Enable/disable constraint warm starting. Advanced feature for testing. Disabling +/// sleeping greatly reduces stability and provides no performance gain. +B3_API void b3World_EnableWarmStarting( b3WorldId worldId, bool flag ); + +/// Is constraint warm starting enabled? +B3_API bool b3World_IsWarmStartingEnabled( b3WorldId worldId ); + +/// Get the number of awake bodies +B3_API int b3World_GetAwakeBodyCount( b3WorldId worldId ); + +/// Get the current world performance profile +B3_API b3Profile b3World_GetProfile( b3WorldId worldId ); + +/// Get world counters and sizes +B3_API b3Counters b3World_GetCounters( b3WorldId worldId ); + +/// Get max capacity. This can be used with b3WorldDef to avoid run-time allocations and copies +B3_API b3Capacity b3World_GetMaxCapacity( b3WorldId worldId ); + +/// Set the user data pointer. +B3_API void b3World_SetUserData( b3WorldId worldId, void* userData ); + +/// Get the user data pointer. +B3_API void* b3World_GetUserData( b3WorldId worldId ); + +/// Set the friction callback. Passing NULL resets to default. +B3_API void b3World_SetFrictionCallback( b3WorldId worldId, b3FrictionCallback* callback ); + +/// Set the restitution callback. Passing NULL resets to default. +B3_API void b3World_SetRestitutionCallback( b3WorldId worldId, b3RestitutionCallback* callback ); + +/// Set the worker count. Must be between in the range [1, B3_MAX_WORKERS] +B3_API void b3World_SetWorkerCount( b3WorldId worldId, int count ); + +/// Get the worker count. +B3_API int b3World_GetWorkerCount( b3WorldId worldId ); + +/// Dump memory stats to box3d_memory.txt +B3_API void b3World_DumpMemoryStats( b3WorldId worldId ); + +/// Dump shape bounds to box3d_bounds.txt +B3_API void b3World_DumpShapeBounds( b3WorldId worldId, b3BodyType type ); + +/// This is for internal testing +B3_API void b3World_RebuildStaticTree( b3WorldId worldId ); + +/// This is for internal testing +B3_API void b3World_EnableSpeculative( b3WorldId worldId, bool flag ); + +/// Dump world to a text file. Saves only awake bodies and associated static bodies. +/// Meshes are saved to binary b3m files. +B3_API void b3World_DumpAwake( b3WorldId worldId ); + +/// Dump world to a text file. Meshes are saved to binary b3m files. +B3_API void b3World_Dump( b3WorldId worldId ); + +/** @} */ + +/** + * @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} +/// b3BodyDef bodyDef = b3DefaultBodyDef(); +/// b3BodyId myBodyId = b3CreateBody(myWorldId, &bodyDef); +/// @endcode +/// @warning This function is locked during callbacks. +B3_API b3BodyId b3CreateBody( b3WorldId worldId, const b3BodyDef* 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. +B3_API void b3DestroyBody( b3BodyId 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. +B3_API bool b3Body_IsValid( b3BodyId id ); + +/// Get the body type: static, kinematic, or dynamic +B3_API b3BodyType b3Body_GetType( b3BodyId bodyId ); + +/// Change the body type. This is an expensive operation. This automatically updates the mass +/// properties regardless of the automatic mass setting. +B3_API void b3Body_SetType( b3BodyId bodyId, b3BodyType type ); + +/// Set the body name. Up to 31 characters excluding 0 termination. +B3_API void b3Body_SetName( b3BodyId bodyId, const char* name ); + +/// Get the body name. +B3_API const char* b3Body_GetName( b3BodyId bodyId ); + +/// Set the user data for a body +B3_API void b3Body_SetUserData( b3BodyId bodyId, void* userData ); + +/// Get the user data stored in a body +B3_API void* b3Body_GetUserData( b3BodyId bodyId ); + +/// Get the world position of a body. This is the location of the body origin. +B3_API b3Vec3 b3Body_GetPosition( b3BodyId bodyId ); + +/// Get the world rotation of a body as a cosine/sine pair (complex number) +B3_API b3Quat b3Body_GetRotation( b3BodyId bodyId ); + +/// Get the world transform of a body. +B3_API b3Transform b3Body_GetTransform( b3BodyId 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 b3BodyDef::position and b3BodyDef::rotation +B3_API void b3Body_SetTransform( b3BodyId bodyId, b3Vec3 position, b3Quat rotation ); + +/// Get a local point on a body given a world point +B3_API b3Vec3 b3Body_GetLocalPoint( b3BodyId bodyId, b3Vec3 worldPoint ); + +/// Get a world point on a body given a local point +B3_API b3Vec3 b3Body_GetWorldPoint( b3BodyId bodyId, b3Vec3 localPoint ); + +/// Get a local vector on a body given a world vector +B3_API b3Vec3 b3Body_GetLocalVector( b3BodyId bodyId, b3Vec3 worldVector ); + +/// Get a world vector on a body given a local vector +B3_API b3Vec3 b3Body_GetWorldVector( b3BodyId bodyId, b3Vec3 localVector ); + +/// Get the linear velocity of a body's center of mass. Usually in meters per second. +B3_API b3Vec3 b3Body_GetLinearVelocity( b3BodyId bodyId ); + +/// Get the angular velocity of a body in radians per second +B3_API b3Vec3 b3Body_GetAngularVelocity( b3BodyId bodyId ); + +/// Set the linear velocity of a body. Usually in meters per second. +B3_API void b3Body_SetLinearVelocity( b3BodyId bodyId, b3Vec3 linearVelocity ); + +/// Set the angular velocity of a body in radians per second +B3_API void b3Body_SetAngularVelocity( b3BodyId bodyId, b3Vec3 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. +/// This will optionally wake the body if asleep, but only if the movement is significant. +B3_API void b3Body_SetTargetTransform( b3BodyId bodyId, b3Transform target, float timeStep, bool wake ); + +/// Get the linear velocity of a local point attached to a body. Usually in meters per second. +B3_API b3Vec3 b3Body_GetLocalPointVelocity( b3BodyId bodyId, b3Vec3 localPoint ); + +/// Get the linear velocity of a world point attached to a body. Usually in meters per second. +B3_API b3Vec3 b3Body_GetWorldPointVelocity( b3BodyId bodyId, b3Vec3 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 +B3_API void b3Body_ApplyForce( b3BodyId bodyId, b3Vec3 force, b3Vec3 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 +B3_API void b3Body_ApplyForceToCenter( b3BodyId bodyId, b3Vec3 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 the world torque vector, usually in N*m. +/// @param wake also wake up the body +B3_API void b3Body_ApplyTorque( b3BodyId bodyId, b3Vec3 torque, bool wake ); + +/// 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. +B3_API void b3Body_ApplyLinearImpulse( b3BodyId bodyId, b3Vec3 impulse, b3Vec3 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. +B3_API void b3Body_ApplyLinearImpulseToCenter( b3BodyId bodyId, b3Vec3 impulse, bool wake ); + +/// Apply an angular impulse in world space. The impulse is ignored if the body is not awake. +/// This optionally wakes the body. +/// @param bodyId The body id +/// @param impulse the world angular impulse vector, 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. +B3_API void b3Body_ApplyAngularImpulse( b3BodyId bodyId, b3Vec3 impulse, bool wake ); + +/// Get the mass of the body, usually in kilograms +B3_API float b3Body_GetMass( b3BodyId bodyId ); + +/// Get the rotational inertia of the body in local space, usually in kg*m^2 +B3_API b3Matrix3 b3Body_GetLocalRotationalInertia( b3BodyId bodyId ); + +/// Get the inverse mass of the body, usually in 1/kilograms +B3_API float b3Body_GetInverseMass( b3BodyId bodyId ); + +/// Get the inverse rotational inertia of the body in world space, usually in 1/kg*m^2 +B3_API b3Matrix3 b3Body_GetWorldInverseRotationalInertia( b3BodyId bodyId ); + +/// Get the center of mass position of the body in local space +B3_API b3Vec3 b3Body_GetLocalCenterOfMass( b3BodyId bodyId ); + +/// Get the center of mass position of the body in world space +B3_API b3Vec3 b3Body_GetWorldCenterOfMass( b3BodyId 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. +B3_API void b3Body_SetMassData( b3BodyId bodyId, b3MassData massData ); + +/// Get the mass data for a body +B3_API b3MassData b3Body_GetMassData( b3BodyId bodyId ); + +/// This update 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. +B3_API void b3Body_ApplyMassFromShapes( b3BodyId bodyId ); + +/// Adjust the linear damping. Normally this is set in b3BodyDef before creation. +B3_API void b3Body_SetLinearDamping( b3BodyId bodyId, float linearDamping ); + +/// Get the current linear damping. +B3_API float b3Body_GetLinearDamping( b3BodyId bodyId ); + +/// Adjust the angular damping. Normally this is set in b3BodyDef before creation. +B3_API void b3Body_SetAngularDamping( b3BodyId bodyId, float angularDamping ); + +/// Get the current angular damping. +B3_API float b3Body_GetAngularDamping( b3BodyId bodyId ); + +/// Adjust the gravity scale. Normally this is set in b3BodyDef before creation. +/// @see b3BodyDef::gravityScale +B3_API void b3Body_SetGravityScale( b3BodyId bodyId, float gravityScale ); + +/// Get the current gravity scale +B3_API float b3Body_GetGravityScale( b3BodyId bodyId ); + +/// @return true if this body is awake +B3_API bool b3Body_IsAwake( b3BodyId 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. +B3_API void b3Body_SetAwake( b3BodyId bodyId, bool awake ); + +/// Enable or disable sleeping for this body. If sleeping is disabled the body will wake. +B3_API void b3Body_EnableSleep( b3BodyId bodyId, bool enableSleep ); + +/// Returns true if sleeping is enabled for this body +B3_API bool b3Body_IsSleepEnabled( b3BodyId bodyId ); + +/// Set the sleep threshold, usually in meters per second +B3_API void b3Body_SetSleepThreshold( b3BodyId bodyId, float sleepThreshold ); + +/// Get the sleep threshold, usually in meters per second. +B3_API float b3Body_GetSleepThreshold( b3BodyId bodyId ); + +/// Returns true if this body is enabled +B3_API bool b3Body_IsEnabled( b3BodyId bodyId ); + +/// Disable a body by removing it completely from the simulation. This is expensive. +B3_API void b3Body_Disable( b3BodyId bodyId ); + +/// Enable a body by adding it to the simulation. This is expensive. +B3_API void b3Body_Enable( b3BodyId bodyId ); + +/// Set the motion locks on this body. +B3_API void b3Body_SetMotionLocks( b3BodyId bodyId, b3MotionLocks locks ); + +/// Get the motion locks for this body. +B3_API b3MotionLocks b3Body_GetMotionLocks( b3BodyId bodyId ); + +/// Set this body to be a bullet. A bullet does continuous collision detection +/// against dynamic bodies (but not other bullets). +B3_API void b3Body_SetBullet( b3BodyId bodyId, bool flag ); + +/// Is this body a bullet? +B3_API bool b3Body_IsBullet( b3BodyId bodyId ); + +/// Enable/disable hit events on all shapes +/// @see b3ShapeDef::enableHitEvents +B3_API void b3Body_EnableHitEvents( b3BodyId bodyId, bool enableHitEvents ); + +/// Get the world that owns this body +B3_API b3WorldId b3Body_GetWorld( b3BodyId bodyId ); + +/// Get the number of shapes on this body +B3_API int b3Body_GetShapeCount( b3BodyId 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 +B3_API int b3Body_GetShapes( b3BodyId bodyId, b3ShapeId* shapeArray, int capacity ); + +/// Get the number of joints on this body +B3_API int b3Body_GetJointCount( b3BodyId 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 +B3_API int b3Body_GetJoints( b3BodyId bodyId, b3JointId* jointArray, int capacity ); + +/// Get the maximum capacity required for retrieving all the touching contacts on a body +B3_API int b3Body_GetContactCapacity( b3BodyId bodyId ); + +/// Get the touching contact data for a body +B3_API int b3Body_GetContactData( b3BodyId bodyId, b3ContactData* 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. +B3_API b3AABB b3Body_ComputeAABB( b3BodyId bodyId ); + +/// Get the closest point on a body to a world target. +B3_API float b3Body_GetClosestPoint( b3BodyId bodyId, b3Vec3* result, b3Vec3 target ); + +/// Cast a ray at a specific body using a specified body transform. +B3_API b3BodyCastResult b3Body_CastRay( b3BodyId bodyId, const b3BodyRayCastInput* input, b3Transform bodyTransform ); + +/// Cast a shape at a specific body using a specified body transform. +B3_API b3BodyCastResult b3Body_CastShape( b3BodyId bodyId, const b3BodyShapeCastInput* input, b3Transform bodyTransform ); + +/// Overlap a shape with a specific body using a specified body transform. +B3_API bool b3Body_OverlapShape( b3BodyId bodyId, const b3ShapeProxy* proxy, b3QueryFilter filter, b3Transform bodyTransform ); + +/// Collide a character mover with a specific body using a specified body transform. +B3_API int b3Body_CollideMover( b3BodyId bodyId, b3BodyPlaneResult* bodyPlanes, int planeCapacity, const b3Capsule* mover, + b3QueryFilter filter, b3Transform bodyTransform ); + +/** @} */ + +/** + * @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 +B3_API b3ShapeId b3CreateSphereShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Sphere* sphere ); + +/// 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 +B3_API b3ShapeId b3CreateCapsuleShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Capsule* capsule ); + +/// Create a convex hull shape and attach it to a body. The hull is cloned. +/// 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 +B3_API b3ShapeId b3CreateHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Hull* hull ); + +/// Create a convex hull shape and attach it to a body. The hull is cloned then transformed with scale applied first. +/// 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 +B3_API b3ShapeId b3CreateTransformedHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Hull* hull, b3Transform transform, + b3Vec3 scale ); + +/// Create a mesh hull shape and attach it to a body. The shape definition is fully cloned but the mesh is not. +/// Contacts are not created until the next time step. +/// Mesh collision only creates contacts on static bodies. +/// @warning this holds reference to the input mesh data which must remain valid for the lifetime of this shape +/// @return the shape id for accessing the shape +B3_API b3ShapeId b3CreateMeshShape( b3BodyId bodyId, const b3ShapeDef* def, const b3MeshData* mesh, b3Vec3 scale ); + +/// Create a height-field shape and attach it to a body. The shape definition is fully cloned but the height field is not. +/// Contacts are not created until the next time step. +/// Height field is only allowed on static bodies. +/// @warning this holds reference to the input height field which must remain valid for the lifetime of this shape +/// @return the shape id for accessing the shape +B3_API b3ShapeId b3CreateHeightFieldShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HeightField* heightField ); + +/// Compound shapes are only allowed on static bodies. +B3_API b3ShapeId b3CreateCompoundShape( b3BodyId bodyId, b3ShapeDef* def, const b3Compound* compound ); + +/// 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 b3Body_ApplyMassFromShapes +B3_API void b3DestroyShape( b3ShapeId shapeId, bool updateBodyMass ); + +/// Shape identifier validation. Provides validation for up to 64K allocations. +B3_API bool b3Shape_IsValid( b3ShapeId id ); + +/// Get the type of a shape +B3_API b3ShapeType b3Shape_GetType( b3ShapeId shapeId ); + +/// Get the id of the body that a shape is attached to +B3_API b3BodyId b3Shape_GetBody( b3ShapeId shapeId ); + +/// Get the world that owns this shape +B3_API b3WorldId b3Shape_GetWorld( b3ShapeId shapeId ); + +/// Returns true If the shape is a sensor +B3_API bool b3Shape_IsSensor( b3ShapeId shapeId ); + +/// Set the shape name. Up to 31 characters excluding 0 termination. +B3_API void b3Shape_SetName( b3ShapeId shapeId, const char* name ); + +/// Get the shape name. +B3_API const char* b3Shape_GetName( b3ShapeId shapeId ); + +/// Set the user data for a shape +B3_API void b3Shape_SetUserData( b3ShapeId shapeId, void* userData ); + +/// Get the user data for a shape. This is useful when you get a shape id +/// from an event or query. +B3_API void* b3Shape_GetUserData( b3ShapeId 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 b3ShapeDef::density, b3Body_ApplyMassFromShapes +B3_API void b3Shape_SetDensity( b3ShapeId shapeId, float density, bool updateBodyMass ); + +/// Get the density of a shape, usually in kg/m^2 +B3_API float b3Shape_GetDensity( b3ShapeId shapeId ); + +/// Set the friction on a shape +B3_API void b3Shape_SetFriction( b3ShapeId shapeId, float friction ); + +/// Get the friction of a shape +B3_API float b3Shape_GetFriction( b3ShapeId shapeId ); + +/// Set the shape restitution (bounciness) +B3_API void b3Shape_SetRestitution( b3ShapeId shapeId, float restitution ); + +/// Get the shape restitution +B3_API float b3Shape_GetRestitution( b3ShapeId shapeId ); + +/// Set the shape base surface material. Does not change per triangle materials. +B3_API void b3Shape_SetSurfaceMaterial( b3ShapeId shapeId, b3SurfaceMaterial surfaceMaterial ); + +/// Get the base shape surface material. +B3_API b3SurfaceMaterial b3Shape_GetSurfaceMaterial( b3ShapeId shapeId ); + +/// Get the number of mesh surface materials. +B3_API int b3Shape_GetMeshMaterialCount( b3ShapeId shapeId ); + +/// Set a surface material for a mesh shape. +B3_API void b3Shape_SetMeshMaterial( b3ShapeId shapeId, b3SurfaceMaterial surfaceMaterial, int index ); + +/// Get a surface material for a mesh shape +B3_API b3SurfaceMaterial b3Shape_GetMeshSurfaceMaterial( b3ShapeId shapeId, int index ); + +/// Get the shape filter +B3_API b3Filter b3Shape_GetFilter( b3ShapeId shapeId ); + +/// Set the current filter. This is almost as expensive as recreating the shape. +/// @see b3ShapeDef::filter +/// @param shapeId the shape +/// @param filter the new filter +/// @param invokeContacts if true then the shape will have all contacts recomputed the next time step (expensive) +B3_API void b3Shape_SetFilter( b3ShapeId shapeId, b3Filter filter, bool invokeContacts ); + +/// Enable sensor events for this shape. Only applies to kinematic and dynamic bodies. Ignored for sensors. +/// @see b3ShapeDef::isSensor +B3_API void b3Shape_EnableSensorEvents( b3ShapeId shapeId, bool flag ); + +/// Returns true if sensor events are enabled +B3_API bool b3Shape_AreSensorEventsEnabled( b3ShapeId shapeId ); + +/// Enable contact events for this shape. Only applies to kinematic and dynamic bodies. Ignored for sensors. +/// @see b3ShapeDef::enableContactEvents +B3_API void b3Shape_EnableContactEvents( b3ShapeId shapeId, bool flag ); + +/// Returns true if contact events are enabled +B3_API bool b3Shape_AreContactEventsEnabled( b3ShapeId 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 b3PreSolveFcn +B3_API void b3Shape_EnablePreSolveEvents( b3ShapeId shapeId, bool flag ); + +/// Returns true if pre-solve events are enabled +B3_API bool b3Shape_ArePreSolveEventsEnabled( b3ShapeId shapeId ); + +/// Enable contact hit events for this shape. Ignored for sensors. +/// @see b3WorldDef.hitEventThreshold +B3_API void b3Shape_EnableHitEvents( b3ShapeId shapeId, bool flag ); + +/// Returns true if hit events are enabled +B3_API bool b3Shape_AreHitEventsEnabled( b3ShapeId shapeId ); + +/// Ray cast a shape directly +B3_API b3CastOutput b3Shape_RayCast( b3ShapeId shapeId, const b3RayCastInput* input ); + +/// Get a copy of the shape's sphere. Asserts the type is correct. +B3_API b3Sphere b3Shape_GetSphere( b3ShapeId shapeId ); + +/// Get a copy of the shape's capsule. Asserts the type is correct. +B3_API b3Capsule b3Shape_GetCapsule( b3ShapeId shapeId ); + +/// Get the shape's convex hull. Asserts the type is correct. +B3_API const b3Hull* b3Shape_GetHull( b3ShapeId shapeId ); + +/// Get the shape's mesh. Asserts the type is correct. +B3_API b3Mesh b3Shape_GetMesh( b3ShapeId shapeId ); + +/// Get the shape's height field. Asserts the type is correct. +B3_API const b3HeightField* b3Shape_GetHeightField( b3ShapeId shapeId ); + +/// Allows you to change a shape to be a sphere or update the current sphere. +/// This does not modify the mass properties. +/// @see b3Body_ApplyMassFromShapes +B3_API void b3Shape_SetSphere( b3ShapeId shapeId, const b3Sphere* sphere ); + +/// Allows you to change a shape to be a capsule or update the current capsule. +/// This does not modify the mass properties. +/// @see b3Body_ApplyMassFromShapes +B3_API void b3Shape_SetCapsule( b3ShapeId shapeId, const b3Capsule* capsule ); + +/// Allows you to change a shape to be a hull or update the current hull. +/// This does not modify the mass properties. +/// @see b3Body_ApplyMassFromShapes +B3_API void b3Shape_SetHull( b3ShapeId shapeId, const b3Hull* hull ); + +/// Allows you to change a shape to be a mesh or update the current mesh. +/// This does not modify the mass properties. +/// @see b3Body_ApplyMassFromShapes +B3_API void b3Shape_SetMesh( b3ShapeId shapeId, const b3MeshData* meshData, b3Vec3 scale ); + +/// Get the maximum capacity required for retrieving all the touching contacts on a shape +B3_API int b3Shape_GetContactCapacity( b3ShapeId shapeId ); + +/// Get the touching contact data for a shape. The provided shapeId will be either shapeIdA or shapeIdB on the contact data. +/// @note Box3D 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 +B3_API int b3Shape_GetContactData( b3ShapeId shapeId, b3ContactData* 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 b3Shape_GetSensorOverlaps +B3_API int b3Shape_GetSensorCapacity( b3ShapeId 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 b3Shape_IsValid to confirm each overlap +B3_API int b3Shape_GetSensorData( b3ShapeId shapeId, b3ShapeId* visitorIds, int capacity ); + +/// Get the current world AABB +B3_API b3AABB b3Shape_GetAABB( b3ShapeId shapeId ); + +/// Compute the mass data for a shape +B3_API b3MassData b3Shape_ComputeMassData( b3ShapeId shapeId ); + +/// Get the closest point on a shape to a target point. Target and result are in world space. +B3_API b3Vec3 b3Shape_GetClosestPoint( b3ShapeId shapeId, b3Vec3 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 maxSpeed the maximum relative speed. Speed cap is necessary for stability. Typically 10m/s or less. +/// @param wake should this wake the body +B3_API void b3Shape_ApplyWind( b3ShapeId shapeId, b3Vec3 wind, float drag, float lift, float maxSpeed, bool wake ); + +/** @} */ + +/** + * @defgroup joint Joint + * @brief Joints allow you to connect rigid bodies together while allowing various forms of relative motions. + * @{ + */ + +/// Destroy a joint +B3_API void b3DestroyJoint( b3JointId jointId, bool wakeAttached ); + +/// Joint identifier validation. Provides validation for up to 64K allocations. +B3_API bool b3Joint_IsValid( b3JointId id ); + +/// Get the joint type +B3_API b3JointType b3Joint_GetType( b3JointId jointId ); + +/// Get body A id on a joint +B3_API b3BodyId b3Joint_GetBodyA( b3JointId jointId ); + +/// Get body B id on a joint +B3_API b3BodyId b3Joint_GetBodyB( b3JointId jointId ); + +/// Get the world that owns this joint +B3_API b3WorldId b3Joint_GetWorld( b3JointId jointId ); + +/// Set the local frame on bodyA +B3_API void b3Joint_SetLocalFrameA( b3JointId jointId, b3Transform localFrame ); + +/// Get the local frame on bodyA +B3_API b3Transform b3Joint_GetLocalFrameA( b3JointId jointId ); + +/// Set the local frame on bodyB +B3_API void b3Joint_SetLocalFrameB( b3JointId jointId, b3Transform localFrame ); + +/// Get the local frame on bodyB +B3_API b3Transform b3Joint_GetLocalFrameB( b3JointId jointId ); + +/// Toggle collision between connected bodies +B3_API void b3Joint_SetCollideConnected( b3JointId jointId, bool shouldCollide ); + +/// Is collision allowed between connected bodies? +B3_API bool b3Joint_GetCollideConnected( b3JointId jointId ); + +/// Set the user data on a joint +B3_API void b3Joint_SetUserData( b3JointId jointId, void* userData ); + +/// Get the user data on a joint +B3_API void* b3Joint_GetUserData( b3JointId jointId ); + +/// Wake the bodies connect to this joint +B3_API void b3Joint_WakeBodies( b3JointId jointId ); + +/// Get the current constraint force for this joint +B3_API b3Vec3 b3Joint_GetConstraintForce( b3JointId jointId ); + +/// Get the current constraint torque for this joint +B3_API b3Vec3 b3Joint_GetConstraintTorque( b3JointId jointId ); + +/// Get the current linear separation error for this joint. Does not consider admissible movement. Usually in meters. +B3_API float b3Joint_GetLinearSeparation( b3JointId jointId ); + +/// Get the current angular separation error for this joint. Does not consider admissible movement. Usually in meters. +B3_API float b3Joint_GetAngularSeparation( b3JointId 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) +B3_API void b3Joint_SetConstraintTuning( b3JointId jointId, float hertz, float dampingRatio ); + +/// Get the joint constraint tuning. Advanced feature. +B3_API void b3Joint_GetConstraintTuning( b3JointId jointId, float* hertz, float* dampingRatio ); + +/// Set the force threshold for joint events (Newtons) +B3_API void b3Joint_SetForceThreshold( b3JointId jointId, float threshold ); + +/// Get the force threshold for joint events (Newtons) +B3_API float b3Joint_GetForceThreshold( b3JointId jointId ); + +/// Set the torque threshold for joint events (N-m) +B3_API void b3Joint_SetTorqueThreshold( b3JointId jointId, float threshold ); + +/// Get the torque threshold for joint events (N-m) +B3_API float b3Joint_GetTorqueThreshold( b3JointId jointId ); + +/** + * @defgroup cone_joint Parallel Joint + * @brief Functions for the parallel joint. + * @{ + */ + +/// Create a parallel joint +/// @see b3ParallelJointDef for details +B3_API b3JointId b3CreateParallelJoint( b3WorldId worldId, const b3ParallelJointDef* def ); + +/// Set the spring stiffness in Hertz +B3_API void b3ParallelJoint_SetSpringHertz( b3JointId jointId, float hertz ); + +/// Set the spring damping ratio, non-dimensional +B3_API void b3ParallelJoint_SetSpringDampingRatio( b3JointId jointId, float dampingRatio ); + +/// Get the spring Hertz +B3_API float b3ParallelJoint_GetSpringHertz( b3JointId jointId ); + +/// Get the spring damping ratio +B3_API float b3ParallelJoint_GetSpringDampingRatio( b3JointId jointId ); + +/// Set the maximum spring torque, usually in newtons-meters +B3_API void b3ParallelJoint_SetMaxTorque( b3JointId jointId, float force ); + +/// Get the maximum spring torque, usually in newtons-meters +B3_API float b3ParallelJoint_GetMaxTorque( b3JointId jointId ); +/** @} */ + +/** + * @defgroup distance_joint Distance Joint + * @brief Functions for the distance joint. + * @{ + */ + +/// Create a distance joint +/// @see b3DistanceJointDef for details +B3_API b3JointId b3CreateDistanceJoint( b3WorldId worldId, const b3DistanceJointDef* def ); + +/// Set the rest length of a distance joint +/// @param jointId The id for a distance joint +/// @param length The new distance joint length +B3_API void b3DistanceJoint_SetLength( b3JointId jointId, float length ); + +/// Get the rest length of a distance joint +B3_API float b3DistanceJoint_GetLength( b3JointId jointId ); + +/// Enable/disable the distance joint spring. When disabled the distance joint is rigid. +B3_API void b3DistanceJoint_EnableSpring( b3JointId jointId, bool enableSpring ); + +/// Is the distance joint spring enabled? +B3_API bool b3DistanceJoint_IsSpringEnabled( b3JointId jointId ); + +/// Set the force range for the spring. +B3_API void b3DistanceJoint_SetSpringForceRange( b3JointId jointId, float lowerForce, float upperForce ); + +/// Get the force range for the spring. +B3_API void b3DistanceJoint_GetSpringForceRange( b3JointId jointId, float* lowerForce, float* upperForce ); + +/// Set the spring stiffness in Hertz +B3_API void b3DistanceJoint_SetSpringHertz( b3JointId jointId, float hertz ); + +/// Set the spring damping ratio, non-dimensional +B3_API void b3DistanceJoint_SetSpringDampingRatio( b3JointId jointId, float dampingRatio ); + +/// Get the spring Hertz +B3_API float b3DistanceJoint_GetSpringHertz( b3JointId jointId ); + +/// Get the spring damping ratio +B3_API float b3DistanceJoint_GetSpringDampingRatio( b3JointId 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. +B3_API void b3DistanceJoint_EnableLimit( b3JointId jointId, bool enableLimit ); + +/// Is the distance joint limit enabled? +B3_API bool b3DistanceJoint_IsLimitEnabled( b3JointId jointId ); + +/// Set the minimum and maximum length parameters of a distance joint +B3_API void b3DistanceJoint_SetLengthRange( b3JointId jointId, float minLength, float maxLength ); + +/// Get the distance joint minimum length +B3_API float b3DistanceJoint_GetMinLength( b3JointId jointId ); + +/// Get the distance joint maximum length +B3_API float b3DistanceJoint_GetMaxLength( b3JointId jointId ); + +/// Get the current length of a distance joint +B3_API float b3DistanceJoint_GetCurrentLength( b3JointId jointId ); + +/// Enable/disable the distance joint motor +B3_API void b3DistanceJoint_EnableMotor( b3JointId jointId, bool enableMotor ); + +/// Is the distance joint motor enabled? +B3_API bool b3DistanceJoint_IsMotorEnabled( b3JointId jointId ); + +/// Set the distance joint motor speed, usually in meters per second +B3_API void b3DistanceJoint_SetMotorSpeed( b3JointId jointId, float motorSpeed ); + +/// Get the distance joint motor speed, usually in meters per second +B3_API float b3DistanceJoint_GetMotorSpeed( b3JointId jointId ); + +/// Set the distance joint maximum motor force, usually in newtons +B3_API void b3DistanceJoint_SetMaxMotorForce( b3JointId jointId, float force ); + +/// Get the distance joint maximum motor force, usually in newtons +B3_API float b3DistanceJoint_GetMaxMotorForce( b3JointId jointId ); + +/// Get the distance joint current motor force, usually in newtons +B3_API float b3DistanceJoint_GetMotorForce( b3JointId 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 b3MotorJointDef for details +B3_API b3JointId b3CreateMotorJoint( b3WorldId worldId, const b3MotorJointDef* def ); + +/// Set the desired relative linear velocity in meters per second +B3_API void b3MotorJoint_SetLinearVelocity( b3JointId jointId, b3Vec3 velocity ); + +/// Get the desired relative linear velocity in meters per second +B3_API b3Vec3 b3MotorJoint_GetLinearVelocity( b3JointId jointId ); + +/// Set the desired relative angular velocity in radians per second +B3_API void b3MotorJoint_SetAngularVelocity( b3JointId jointId, b3Vec3 velocity ); + +/// Get the desired relative angular velocity in radians per second +B3_API b3Vec3 b3MotorJoint_GetAngularVelocity( b3JointId jointId ); + +/// Set the motor joint maximum force, usually in newtons +B3_API void b3MotorJoint_SetMaxVelocityForce( b3JointId jointId, float maxForce ); + +/// Get the motor joint maximum force, usually in newtons +B3_API float b3MotorJoint_GetMaxVelocityForce( b3JointId jointId ); + +/// Set the motor joint maximum torque, usually in newton-meters +B3_API void b3MotorJoint_SetMaxVelocityTorque( b3JointId jointId, float maxTorque ); + +/// Get the motor joint maximum torque, usually in newton-meters +B3_API float b3MotorJoint_GetMaxVelocityTorque( b3JointId jointId ); + +/// Set the spring linear hertz stiffness +B3_API void b3MotorJoint_SetLinearHertz( b3JointId jointId, float hertz ); + +/// Get the spring linear hertz stiffness +B3_API float b3MotorJoint_GetLinearHertz( b3JointId jointId ); + +/// Set the spring linear damping ratio. Use 1.0 for critical damping. +B3_API void b3MotorJoint_SetLinearDampingRatio( b3JointId jointId, float damping ); + +/// Get the spring linear damping ratio. +B3_API float b3MotorJoint_GetLinearDampingRatio( b3JointId jointId ); + +/// Set the spring angular hertz stiffness +B3_API void b3MotorJoint_SetAngularHertz( b3JointId jointId, float hertz ); + +/// Get the spring angular hertz stiffness +B3_API float b3MotorJoint_GetAngularHertz( b3JointId jointId ); + +/// Set the spring angular damping ratio. Use 1.0 for critical damping. +B3_API void b3MotorJoint_SetAngularDampingRatio( b3JointId jointId, float damping ); + +/// Get the spring angular damping ratio. +B3_API float b3MotorJoint_GetAngularDampingRatio( b3JointId jointId ); + +/// Set the maximum spring force in newtons. +B3_API void b3MotorJoint_SetMaxSpringForce( b3JointId jointId, float maxForce ); + +/// Get the maximum spring force in newtons. +B3_API float b3MotorJoint_GetMaxSpringForce( b3JointId jointId ); + +/// Set the maximum spring torque in newtons * meters +B3_API void b3MotorJoint_SetMaxSpringTorque( b3JointId jointId, float maxTorque ); + +/// Get the maximum spring torque in newtons * meters +B3_API float b3MotorJoint_GetMaxSpringTorque( b3JointId jointId ); + +/**@}*/ + +/**@}*/ +/** + * @defgroup null_joint Null Joint + * @brief Functions for the null joint. + * + * The null 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 b3FilterJointDef for details +B3_API b3JointId b3CreateFilterJoint( b3WorldId worldId, const b3FilterJointDef* 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 b3PrismaticJointDef for details +B3_API b3JointId b3CreatePrismaticJoint( b3WorldId worldId, const b3PrismaticJointDef* def ); + +/// Enable/disable the joint spring. +B3_API void b3PrismaticJoint_EnableSpring( b3JointId jointId, bool enableSpring ); + +/// Is the prismatic joint spring enabled or not? +B3_API bool b3PrismaticJoint_IsSpringEnabled( b3JointId 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. +B3_API void b3PrismaticJoint_SetSpringHertz( b3JointId jointId, float hertz ); + +/// Get the prismatic joint stiffness in Hertz +B3_API float b3PrismaticJoint_GetSpringHertz( b3JointId jointId ); + +/// Set the prismatic joint damping ratio (non-dimensional) +B3_API void b3PrismaticJoint_SetSpringDampingRatio( b3JointId jointId, float dampingRatio ); + +/// Get the prismatic spring damping ratio (non-dimensional) +B3_API float b3PrismaticJoint_GetSpringDampingRatio( b3JointId jointId ); + +/// Set the prismatic joint target translation. Usually in meters. +B3_API void b3PrismaticJoint_SetTargetTranslation( b3JointId jointId, float targetTranslation ); + +/// Get the prismatic joint target translation. Usually in meters. +B3_API float b3PrismaticJoint_GetTargetTranslation( b3JointId jointId ); + +/// Enable/disable a prismatic joint limit +B3_API void b3PrismaticJoint_EnableLimit( b3JointId jointId, bool enableLimit ); + +/// Is the prismatic joint limit enabled? +B3_API bool b3PrismaticJoint_IsLimitEnabled( b3JointId jointId ); + +/// Get the prismatic joint lower limit +B3_API float b3PrismaticJoint_GetLowerLimit( b3JointId jointId ); + +/// Get the prismatic joint upper limit +B3_API float b3PrismaticJoint_GetUpperLimit( b3JointId jointId ); + +/// Set the prismatic joint limits +B3_API void b3PrismaticJoint_SetLimits( b3JointId jointId, float lower, float upper ); + +/// Enable/disable a prismatic joint motor +B3_API void b3PrismaticJoint_EnableMotor( b3JointId jointId, bool enableMotor ); + +/// Is the prismatic joint motor enabled? +B3_API bool b3PrismaticJoint_IsMotorEnabled( b3JointId jointId ); + +/// Set the prismatic joint motor speed, usually in meters per second +B3_API void b3PrismaticJoint_SetMotorSpeed( b3JointId jointId, float motorSpeed ); + +/// Get the prismatic joint motor speed, usually in meters per second +B3_API float b3PrismaticJoint_GetMotorSpeed( b3JointId jointId ); + +/// Set the prismatic joint maximum motor force, usually in newtons +B3_API void b3PrismaticJoint_SetMaxMotorForce( b3JointId jointId, float force ); + +/// Get the prismatic joint maximum motor force, usually in newtons +B3_API float b3PrismaticJoint_GetMaxMotorForce( b3JointId jointId ); + +/// Get the prismatic joint current motor force, usually in newtons +B3_API float b3PrismaticJoint_GetMotorForce( b3JointId jointId ); + +/// Get the current joint translation, usually in meters. +B3_API float b3PrismaticJoint_GetTranslation( b3JointId jointId ); + +/// Get the current joint translation speed, usually in meters per second. +B3_API float b3PrismaticJoint_GetSpeed( b3JointId 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 b3RevoluteJointDef for details +B3_API b3JointId b3CreateRevoluteJoint( b3WorldId worldId, const b3RevoluteJointDef* def ); + +/// Enable/disable the revolute joint spring +B3_API void b3RevoluteJoint_EnableSpring( b3JointId jointId, bool enableSpring ); + +/// It the revolute angular spring enabled? +B3_API bool b3RevoluteJoint_IsSpringEnabled( b3JointId jointId ); + +/// Set the revolute joint spring stiffness in Hertz +B3_API void b3RevoluteJoint_SetSpringHertz( b3JointId jointId, float hertz ); + +/// Get the revolute joint spring stiffness in Hertz +B3_API float b3RevoluteJoint_GetSpringHertz( b3JointId jointId ); + +/// Set the revolute joint spring damping ratio, non-dimensional +B3_API void b3RevoluteJoint_SetSpringDampingRatio( b3JointId jointId, float dampingRatio ); + +/// Get the revolute joint spring damping ratio, non-dimensional +B3_API float b3RevoluteJoint_GetSpringDampingRatio( b3JointId jointId ); + +/// Set the revolute joint target angle in radians +B3_API void b3RevoluteJoint_SetTargetAngle( b3JointId jointId, float targetRadians ); + +/// Get the revolute joint target angle in radians +B3_API float b3RevoluteJoint_GetTargetAngle( b3JointId jointId ); + +/// Get the revolute joint current angle in radians relative to the reference angle +/// @see b3RevoluteJointDef::referenceAngle +B3_API float b3RevoluteJoint_GetAngle( b3JointId jointId ); + +/// Enable/disable the revolute joint limit +B3_API void b3RevoluteJoint_EnableLimit( b3JointId jointId, bool enableLimit ); + +/// Is the revolute joint limit enabled? +B3_API bool b3RevoluteJoint_IsLimitEnabled( b3JointId jointId ); + +/// Get the revolute joint lower limit in radians +B3_API float b3RevoluteJoint_GetLowerLimit( b3JointId jointId ); + +/// Get the revolute joint upper limit in radians +B3_API float b3RevoluteJoint_GetUpperLimit( b3JointId jointId ); + +/// Set the revolute joint limits in radians +B3_API void b3RevoluteJoint_SetLimits( b3JointId jointId, float lowerLimitRadians, float upperLimitRadians ); + +/// Enable/disable a revolute joint motor +B3_API void b3RevoluteJoint_EnableMotor( b3JointId jointId, bool enableMotor ); + +/// Is the revolute joint motor enabled? +B3_API bool b3RevoluteJoint_IsMotorEnabled( b3JointId jointId ); + +/// Set the revolute joint motor speed in radians per second +B3_API void b3RevoluteJoint_SetMotorSpeed( b3JointId jointId, float motorSpeed ); + +/// Get the revolute joint motor speed in radians per second +B3_API float b3RevoluteJoint_GetMotorSpeed( b3JointId jointId ); + +/// Get the revolute joint current motor torque, usually in newton-meters +B3_API float b3RevoluteJoint_GetMotorTorque( b3JointId jointId ); + +/// Set the revolute joint maximum motor torque, usually in newton-meters +B3_API void b3RevoluteJoint_SetMaxMotorTorque( b3JointId jointId, float torque ); + +/// Get the revolute joint maximum motor torque, usually in newton-meters +B3_API float b3RevoluteJoint_GetMaxMotorTorque( b3JointId jointId ); + +/**@}*/ + +/** + * @defgroup spherical_joint Spherical Joint + * @brief A spherical joint allows for relative rotation in the 3D space with no relative translation. + * + * Also called a *ball-in-socket* or *point-to-point* joint. + * @{ + */ + +/// Create a revolute joint +/// @see b3RevoluteJointDef for details +B3_API b3JointId b3CreateSphericalJoint( b3WorldId worldId, const b3SphericalJointDef* def ); + +/// Enable/disable the spherical joint cone limit +B3_API void b3SphericalJoint_EnableConeLimit( b3JointId jointId, bool enableLimit ); + +/// Is the spherical joint cone limit enabled? +B3_API bool b3SphericalJoint_IsConeLimitEnabled( b3JointId jointId ); + +/// Get the spherical joint cone limit in radians +B3_API float b3SphericalJoint_GetConeLimit( b3JointId jointId ); + +/// Set the spherical joint limits in radians +B3_API void b3SphericalJoint_SetConeLimit( b3JointId jointId, float angleRadians ); + +/// Get the spherical joint current cone angle in radians. +B3_API float b3SphericalJoint_GetConeAngle( b3JointId jointId ); + +/// Enable/disable the spherical joint limit +B3_API void b3SphericalJoint_EnableTwistLimit( b3JointId jointId, bool enableLimit ); + +/// Is the spherical joint limit enabled? +B3_API bool b3SphericalJoint_IsTwistLimitEnabled( b3JointId jointId ); + +/// Get the spherical joint lower limit in radians +B3_API float b3SphericalJoint_GetLowerTwistLimit( b3JointId jointId ); + +/// Get the spherical joint upper limit in radians +B3_API float b3SphericalJoint_GetUpperTwistLimit( b3JointId jointId ); + +/// Set the spherical joint limits in radians +B3_API void b3SphericalJoint_SetTwistLimits( b3JointId jointId, float lowerLimitRadians, float upperLimitRadians ); + +/// Get the spherical joint current twist angle in radians. +B3_API float b3SphericalJoint_GetTwistAngle( b3JointId jointId ); + +/// Enable/disable the spherical joint spring +B3_API void b3SphericalJoint_EnableSpring( b3JointId jointId, bool enableSpring ); + +/// It the spherical angular spring enabled? +B3_API bool b3SphericalJoint_IsSpringEnabled( b3JointId jointId ); + +/// Set the spherical joint spring stiffness in Hertz +B3_API void b3SphericalJoint_SetSpringHertz( b3JointId jointId, float hertz ); + +/// Get the spherical joint spring stiffness in Hertz +B3_API float b3SphericalJoint_GetSpringHertz( b3JointId jointId ); + +/// Set the spherical joint spring damping ratio, non-dimensional +B3_API void b3SphericalJoint_SetSpringDampingRatio( b3JointId jointId, float dampingRatio ); + +/// Get the spherical joint spring damping ratio, non-dimensional +B3_API float b3SphericalJoint_GetSpringDampingRatio( b3JointId jointId ); + +/// Set the spherical joint spring target rotation +B3_API void b3SphericalJoint_SetTargetRotation( b3JointId jointId, b3Quat targetRotation ); + +/// Get the spherical joint spring target rotation +B3_API b3Quat b3SphericalJoint_GetTargetRotation( b3JointId jointId ); + +/// Enable/disable a spherical joint motor +B3_API void b3SphericalJoint_EnableMotor( b3JointId jointId, bool enableMotor ); + +/// Is the spherical joint motor enabled? +B3_API bool b3SphericalJoint_IsMotorEnabled( b3JointId jointId ); + +/// Set the spherical joint motor velocity in radians per second +B3_API void b3SphericalJoint_SetMotorVelocity( b3JointId jointId, b3Vec3 motorVelocity ); + +/// Get the spherical joint motor velocity in radians per second +B3_API b3Vec3 b3SphericalJoint_GetMotorVelocity( b3JointId jointId ); + +/// Get the spherical joint current motor torque, usually in newton-meters +B3_API b3Vec3 b3SphericalJoint_GetMotorTorque( b3JointId jointId ); + +/// Set the spherical joint maximum motor torque, usually in newton-meters +B3_API void b3SphericalJoint_SetMaxMotorTorque( b3JointId jointId, float torque ); + +/// Get the spherical joint maximum motor torque, usually in newton-meters +B3_API float b3SphericalJoint_GetMaxMotorTorque( b3JointId 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 b3WeldJointDef for details +B3_API b3JointId b3CreateWeldJoint( b3WorldId worldId, const b3WeldJointDef* def ); + +/// Set the weld joint linear stiffness in Hertz. 0 is rigid. +B3_API void b3WeldJoint_SetLinearHertz( b3JointId jointId, float hertz ); + +/// Get the weld joint linear stiffness in Hertz +B3_API float b3WeldJoint_GetLinearHertz( b3JointId jointId ); + +/// Set the weld joint linear damping ratio (non-dimensional) +B3_API void b3WeldJoint_SetLinearDampingRatio( b3JointId jointId, float dampingRatio ); + +/// Get the weld joint linear damping ratio (non-dimensional) +B3_API float b3WeldJoint_GetLinearDampingRatio( b3JointId jointId ); + +/// Set the weld joint angular stiffness in Hertz. 0 is rigid. +B3_API void b3WeldJoint_SetAngularHertz( b3JointId jointId, float hertz ); + +/// Get the weld joint angular stiffness in Hertz +B3_API float b3WeldJoint_GetAngularHertz( b3JointId jointId ); + +/// Set weld joint angular damping ratio, non-dimensional +B3_API void b3WeldJoint_SetAngularDampingRatio( b3JointId jointId, float dampingRatio ); + +/// Get the weld joint angular damping ratio, non-dimensional +B3_API float b3WeldJoint_GetAngularDampingRatio( b3JointId 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 b3WheelJointDef for details +B3_API b3JointId b3CreateWheelJoint( b3WorldId worldId, const b3WheelJointDef* def ); + +/// Enable/disable the wheel joint spring +B3_API void b3WheelJoint_EnableSuspension( b3JointId jointId, bool flag ); + +/// Is the wheel joint spring enabled? +B3_API bool b3WheelJoint_IsSuspensionEnabled( b3JointId jointId ); + +/// Set the wheel joint stiffness in Hertz +B3_API void b3WheelJoint_SetSuspensionHertz( b3JointId jointId, float hertz ); + +/// Get the wheel joint stiffness in Hertz +B3_API float b3WheelJoint_GetSuspensionHertz( b3JointId jointId ); + +/// Set the wheel joint damping ratio, non-dimensional +B3_API void b3WheelJoint_SetSuspensionDampingRatio( b3JointId jointId, float dampingRatio ); + +/// Get the wheel joint damping ratio, non-dimensional +B3_API float b3WheelJoint_GetSuspensionDampingRatio( b3JointId jointId ); + +/// Enable/disable the wheel joint limit +B3_API void b3WheelJoint_EnableSuspensionLimit( b3JointId jointId, bool flag ); + +/// Is the wheel joint limit enabled? +B3_API bool b3WheelJoint_IsSuspensionLimitEnabled( b3JointId jointId ); + +/// Get the wheel joint lower limit +B3_API float b3WheelJoint_GetLowerSuspensionLimit( b3JointId jointId ); + +/// Get the wheel joint upper limit +B3_API float b3WheelJoint_GetUpperSuspensionLimit( b3JointId jointId ); + +/// Set the wheel joint limits +B3_API void b3WheelJoint_SetSuspensionLimits( b3JointId jointId, float lower, float upper ); + +/// Enable/disable the wheel joint motor +B3_API void b3WheelJoint_EnableSpinMotor( b3JointId jointId, bool flag ); + +/// Is the wheel joint motor enabled? +B3_API bool b3WheelJoint_IsSpinMotorEnabled( b3JointId jointId ); + +/// Set the wheel joint motor speed in radians per second +B3_API void b3WheelJoint_SetSpinMotorSpeed( b3JointId jointId, float speed ); + +/// Get the wheel joint motor speed in radians per second +B3_API float b3WheelJoint_GetSpinMotorSpeed( b3JointId jointId ); + +/// Set the wheel joint maximum motor torque, usually in newton-meters +B3_API void b3WheelJoint_SetMaxSpinTorque( b3JointId jointId, float torque ); + +/// Get the wheel joint maximum motor torque, usually in newton-meters +B3_API float b3WheelJoint_GetMaxSpinTorque( b3JointId jointId ); + +/// Get the wheel joint current motor torque, usually in newton-meters +B3_API float b3WheelJoint_GetSpinTorque( b3JointId jointId ); + +/// Enable/disable wheel steering. Steering allows the wheel to rotate about the suspension axis. +B3_API void b3WheelJoint_EnableSteering( b3JointId jointId, bool flag ); + +/// Can the wheel steer? +B3_API bool b3WheelJoint_IsSteeringEnabled( b3JointId jointId ); + +/// Set the wheel joint steering stiffness in Hertz +B3_API void b3WheelJoint_SetSteeringHertz( b3JointId jointId, float hertz ); + +/// Get the wheel joint steering stiffness in Hertz +B3_API float b3WheelJoint_GetSteeringHertz( b3JointId jointId ); + +/// Set the wheel joint steering damping ratio, non-dimensional +B3_API void b3WheelJoint_SetSteeringDampingRatio( b3JointId jointId, float dampingRatio ); + +/// Get the wheel joint steering damping ratio, non-dimensional +B3_API float b3WheelJoint_GetSteeringDampingRatio( b3JointId jointId ); + +/// Set the wheel joint maximum steering torque in N*m. +B3_API void b3WheelJoint_SetMaxSteeringTorque( b3JointId jointId, float torque ); + +/// Get the wheel joint maximum steering torque in N*m. +B3_API float b3WheelJoint_GetMaxSteeringTorque( b3JointId jointId ); + +/// Enable/disable the wheel joint steering limit +B3_API void b3WheelJoint_EnableSteeringLimit( b3JointId jointId, bool flag ); + +/// Is the wheel joint steering limit enabled? +B3_API bool b3WheelJoint_IsSteeringLimitEnabled( b3JointId jointId ); + +/// Get the wheel joint lower steering limit in radians +B3_API float b3WheelJoint_GetLowerSteeringLimit( b3JointId jointId ); + +/// Get the wheel joint upper steering limit in radians +B3_API float b3WheelJoint_GetUpperSteeringLimit( b3JointId jointId ); + +/// Set the wheel joint steering limits in radians +B3_API void b3WheelJoint_SetSteeringLimits( b3JointId jointId, float lowerRadians, float upperRadians ); + +/// Set the wheel joint target steering angle in radians +B3_API void b3WheelJoint_SetTargetSteeringAngle( b3JointId jointId, float radians ); + +/// Get the wheel joint target steering angle in radians +B3_API float b3WheelJoint_GetTargetSteeringAngle( b3JointId jointId ); + +/// Get the current spin speed in radians per second +B3_API float b3WheelJoint_GetSpinSpeed( b3JointId jointId ); + +/// Get the current spin torque in N*m +B3_API float b3WheelJoint_GetSpinTorque( b3JointId jointId ); + +/// Get the current steering angle in radians +B3_API float b3WheelJoint_GetSteeringAngle( b3JointId jointId ); + +/// Get the current steering torque in N*m +B3_API float b3WheelJoint_GetSteeringTorque( b3JointId jointId ); + +/**@}*/ + +/**@}*/ + +/** + * @defgroup contact Contact + * Access to contacts + * @{ + */ + +/// Contact identifier validation. Provides validation for up to 2^32 allocations. +B3_API bool b3Contact_IsValid( b3ContactId id ); + +/// Get the manifolds for a contact. The manifold may have no points if the contact is not touching. +B3_API b3ContactData b3Contact_GetData( b3ContactId contactId ); + +/**@}*/ diff --git a/include/box3d/collision.h b/include/box3d/collision.h new file mode 100644 index 0000000..98dec64 --- /dev/null +++ b/include/box3d/collision.h @@ -0,0 +1,1543 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "base.h" +#include "math_functions.h" + +#include +#include + +/// Material properties supported per triangle on meshes and height fields +/// @ingroup shape +typedef struct b3SurfaceMaterial +{ + /// 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]. This is only used for spheres and capsules. + float rollingResistance; + + /// The tangent velocity for conveyor belts. This is local to the shape and will be projected + /// onto the contact surface. + b3Vec3 tangentVelocity; + + /// 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. Ignored if 0. + /// @see b3HexColor + uint32_t customColor; +} b3SurfaceMaterial; + +/// Use this to initialize your surface material +/// @ingroup shape +B3_API b3SurfaceMaterial b3DefaultSurfaceMaterial( void ); + +/** + * @defgroup geometry Geometry + * @brief Geometry types and algorithms + * + * Definitions of spheres, capsules, hulls, meshes, and height fields. + * Functions should take the shape as the first argument to assist editor auto-complete. + * @{ + */ + +#define B3_MAX_SHAPE_CAST_POINTS 64 + +/// Low level ray cast input data +typedef struct b3RayCastInput +{ + /// Start point of the ray cast + b3Vec3 origin; + + /// Translation of the ray cast + b3Vec3 translation; + + /// The maximum fraction of the translation to consider, typically 1 + float maxFraction; +} b3RayCastInput; + +/// A shape proxy is used by the GJK algorithm. It can represent a convex shape. +typedef struct b3ShapeProxy +{ + /// The point cloud + const b3Vec3* points; + + /// The number of points. Do not exceed B3_MAX_SHAPE_CAST_POINTS. + int count; + + /// The external radius of the point cloud + float radius; +} b3ShapeProxy; + +/// Low level shape cast input in generic form. This allows casting an arbitrary point +/// cloud wrap with a radius. For example, a sphere 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 b3ShapeCastInput +{ + /// A generic query shape + b3ShapeProxy proxy; + + /// The translation of the shape cast + b3Vec3 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; +} b3ShapeCastInput; + +/// Low level ray cast or shape-cast output data +typedef struct b3CastOutput +{ + /// The surface normal at the hit point + b3Vec3 normal; + + /// The surface hit point + b3Vec3 point; + + /// The fraction of the input translation at collision + float fraction; + + /// The number of iterations used + int iterations; + + /// The index of the mesh or height field triangle hit + int triangleIndex; + + /// The index of the compound child shape + int childIndex; + + /// The material index. May be -1 for null. + int materialIndex; + + /// Did the cast hit? + bool hit; +} b3CastOutput; + +/** + * @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. + * @{ + */ + +typedef enum b3TreeNodeFlags +{ + b3_allocatedNode = 0x0001, + b3_enlargedNode = 0x0002, + b3_leafNode = 0x0004, +} b3TreeNodeFlags; + +typedef struct b3TreeNodeChildren +{ + int child1; + int child2; +} b3TreeNodeChildren; + +/// A node in the dynamic tree. This is private data placed here for performance reasons. +/// todo test padding to 64 bytes to avoid straddling cache lines +typedef struct b3TreeNode +{ + /// The node bounding box + b3AABB aabb; // 24 + + /// Category bits for collision filtering + uint64_t categoryBits; // 8 + + union + { + /// Children (internal node) + b3TreeNodeChildren children; + + /// User data (leaf node) + uint64_t userData; + }; // 8 + + union + { + /// The node parent index (allocated node) + int parent; + + /// The node freelist next index (free node) + int next; + }; // 4 + + /// Height of the node. Leaves have a height of 0. + uint16_t height; // 2 + uint16_t flags; // 2 +} b3TreeNode; + +#define B3_DYNAMIC_TREE_VERSION 0x8E867C390754064Bull + +/// The dynamic tree structure. This should be considered private data. +/// It is placed here for performance reasons. +typedef struct b3DynamicTree +{ + uint64_t version; + + /// The tree nodes + b3TreeNode* nodes; + + /// The root index + int root; + + /// The number of nodes + int nodeCount; + + /// The allocated node space + int nodeCapacity; + + /// Number of proxies created + int proxyCount; + + /// Node free list + int freeList; + + /// Leaf indices for rebuild + int* leafIndices; + + /// Leaf bounding boxes for rebuild + b3AABB* leafBoxes; + + /// Leaf bounding box centers for rebuild + b3Vec3* leafCenters; + + /// Bins for sorting during rebuild + int* binIndices; + + /// Allocated space for rebuilding + int rebuildCapacity; +} b3DynamicTree; + +/// These are performance results returned by dynamic tree queries. +typedef struct b3TreeStats +{ + /// Number of internal nodes visited during the query + int nodeVisits; + + /// Number of leaf nodes visited during the query + int leafVisits; +} b3TreeStats; + +/// Constructing the tree initializes the node pool. +B3_API b3DynamicTree b3DynamicTree_Create( int proxyCapacity ); + +/// Destroy the tree, freeing the node pool. +B3_API void b3DynamicTree_Destroy( b3DynamicTree* tree ); + +/// Create a proxy. Provide an AABB and a userData value. +B3_API int b3DynamicTree_CreateProxy( b3DynamicTree* tree, b3AABB aabb, uint64_t categoryBits, uint64_t userData ); + +/// Destroy a proxy. This asserts if the id is invalid. +B3_API void b3DynamicTree_DestroyProxy( b3DynamicTree* tree, int proxyId ); + +/// Move a proxy to a new AABB by removing and reinserting into the tree. +B3_API void b3DynamicTree_MoveProxy( b3DynamicTree* tree, int proxyId, b3AABB aabb ); + +/// Enlarge a proxy and enlarge ancestors as necessary. +B3_API void b3DynamicTree_EnlargeProxy( b3DynamicTree* tree, int proxyId, b3AABB aabb ); + +/// Modify the category bits on a proxy. This is an expensive operation. +B3_API void b3DynamicTree_SetCategoryBits( b3DynamicTree* tree, int proxyId, uint64_t categoryBits ); + +/// Get the category bits on a proxy. +B3_API uint64_t b3DynamicTree_GetCategoryBits( b3DynamicTree* tree, int proxyId ); + +/// This function receives proxies found in the AABB query. +/// @return true if the query should continue +typedef bool b3TreeQueryCallbackFcn( 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 +B3_API b3TreeStats b3DynamicTree_Query( const b3DynamicTree* tree, b3AABB aabb, uint64_t maskBits, bool requireAllBits, + b3TreeQueryCallbackFcn* callback, void* context ); + +/// This function receives the minimum distance squared so far and proxy to check in the closest query. +/// @return minimum distance squared to user objects in the proxy +typedef float b3TreeQueryClosestCallbackFcn( float distanceSqrMin, int proxyId, uint64_t userData, void* context ); + +/// Query an AABB for the closest object. The callback class is called for each proxy that might be closest to the supplied point. +/// @param tree the dynamic tree to query +/// @param point the query point +/// @param maskBits nodes are skipped if the bit-wise AND with the node category bits is zero +/// @param requireAllBits nodes are skipped if the bit-wise AND with the node category bits does not equal the maskBits +/// @param callback a user provided instance of b3TreeQueryClosestCallbackFcn +/// @param context a user context object that is provide to the callback +/// @param minDistanceSqr the initial and final minimum squared distance. Provide a small initial to restrict the search and +/// improve performance. If the value is large this query has performance that scales linearly with the number of proxies and +/// would be slower than a brute force search. +/// @return performance data +B3_API b3TreeStats b3DynamicTree_QueryClosest( const b3DynamicTree* tree, b3Vec3 point, uint64_t maskBits, bool requireAllBits, + b3TreeQueryClosestCallbackFcn* callback, void* context, float* minDistanceSqr ); + +/// 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 b3TreeRayCastCallbackFcn( const b3RayCastInput* 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 bit mask test: `bool accept = (maskBits & node->categoryBits) != 0;` +/// @param requireAllBits modifies bit mask test: `bool accept = (maskBits & node->categoryBits) == maskBits;` +/// @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 +B3_API b3TreeStats b3DynamicTree_RayCast( const b3DynamicTree* tree, const b3RayCastInput* input, uint64_t maskBits, + bool requireAllBits, b3TreeRayCastCallbackFcn* 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 b3TreeShapeCastCallbackFcn( const b3ShapeCastInput* 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 bit mask test: `bool accept = (maskBits & node->categoryBits) != 0;` +/// @param requireAllBits modifies bit mask test: `bool accept = (maskBits & node->categoryBits) == maskBits;` +/// @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 +B3_API b3TreeStats b3DynamicTree_ShapeCast( const b3DynamicTree* tree, const b3ShapeCastInput* input, uint64_t maskBits, + bool requireAllBits, b3TreeShapeCastCallbackFcn* callback, void* context ); + +/// Validate this tree. For testing. +B3_API void b3DynamicTree_Validate( const b3DynamicTree* tree ); + +/// Get the height of the binary tree. +B3_API int b3DynamicTree_GetHeight( const b3DynamicTree* tree ); + +/// Get the ratio of the sum of the node areas to the root area. +B3_API float b3DynamicTree_GetAreaRatio( const b3DynamicTree* tree ); + +/// Get the bounding box that contains the entire tree +B3_API b3AABB b3DynamicTree_GetRootBounds( const b3DynamicTree* tree ); + +/// Get the number of proxies created +B3_API int b3DynamicTree_GetProxyCount( const b3DynamicTree* tree ); + +/// Rebuild the tree while retaining subtrees that haven't changed. Returns the number of boxes sorted. +B3_API int b3DynamicTree_Rebuild( b3DynamicTree* tree, bool fullBuild ); + +/// Get the number of bytes used by this tree +B3_API int b3DynamicTree_GetByteCount( const b3DynamicTree* tree ); + +/// Validate this tree. For testing. +B3_API void b3DynamicTree_Validate( const b3DynamicTree* tree ); + +/// Validate this tree has no enlarged AABBs. For testing. +B3_API void b3DynamicTree_ValidateNoEnlarged( const b3DynamicTree* tree ); + +/// Save this tree to a file for debugging +B3_API void b3DynamicTree_Save( const b3DynamicTree* tree, const char* fileName ); + +/// Load a file for debugging +B3_API b3DynamicTree b3DynamicTree_Load( const char* fileName, float scale ); + +/// Get proxy user data +B3_INLINE uint64_t b3DynamicTree_GetUserData( const b3DynamicTree* tree, int proxyId ) +{ + return tree->nodes[proxyId].userData; +} + +/// Get the AABB of a proxy +B3_INLINE b3AABB b3DynamicTree_GetAABB( const b3DynamicTree* tree, int proxyId ) +{ + return tree->nodes[proxyId].aabb; +} + +/**@}*/ + +/// This holds the mass data computed for a shape. +typedef struct b3MassData +{ + float mass; + b3Vec3 center; + + // todo_erin this should be central inertia + b3Matrix3 inertia; +} b3MassData; + +/// A solid sphere +typedef struct b3Sphere +{ + /// The local center + b3Vec3 center; + + /// The radius + float radius; +} b3Sphere; + +/// A solid capsule can be viewed as two hemispheres connected +/// by a rectangle. +typedef struct b3Capsule +{ + /// Local center of the first hemisphere + b3Vec3 center1; + + /// Local center of the second hemisphere + b3Vec3 center2; + + /// The radius of the hemispheres + float radius; +} b3Capsule; + +typedef struct b3HullVertex +{ + // A half-edge that has this vertex as the origin + // Can be used along with edge twins and winding order + // to traverse all the edges connected to this vertex. + uint8_t edge; +} b3HullVertex; + +/// Half-edge for hull data structure +typedef struct b3HullHalfEdge +{ + // Next edge index CCW + uint8_t next; + + // Twin edge index + uint8_t twin; + + // index of origin vertex and point + uint8_t origin; + + // Face to the left of this edge + uint8_t face; +} b3HullHalfEdge; + +typedef struct b3HullFace +{ + // An arbitrary half-edge on this face + uint8_t edge; +} b3HullFace; + +#define B3_HULL_VERSION 0x8F5034CF987D4FD9ull + +/// A convex hull. +/// @note This data structure has data hanging off the end and cannot be directly copied. +typedef struct b3Hull +{ + // Version must be first and match B3_HULL_VERSION + uint64_t version; + int byteCount; + + // Hash of this hull (this field is zero when the hash is computed) + uint32_t hash; + + // Bulk properties + b3AABB aabb; + float surfaceArea; + float volume; + float innerRadius; + b3Vec3 center; + b3Matrix3 centralInertia; + + // Geometry + int vertexCount; + int vertexOffset; + int pointOffset; + + // This is the half-edge count (double the edge count) + int edgeCount; + int edgeOffset; + + int faceCount; + int faceOffset; + int planeOffset; + +} b3Hull; + +B3_INLINE const b3HullVertex* b3GetHullVertices( const b3Hull* hull ) +{ + if ( hull->vertexOffset == 0 ) + { + return NULL; + } + + return (const b3HullVertex*)( (intptr_t)hull + hull->vertexOffset ); +} + +B3_INLINE const b3Vec3* b3GetHullPoints( const b3Hull* hull ) +{ + if ( hull->pointOffset == 0 ) + { + return NULL; + } + + return (const b3Vec3*)( (intptr_t)hull + hull->pointOffset ); +} + +B3_INLINE const b3HullHalfEdge* b3GetHullEdges( const b3Hull* hull ) +{ + if ( hull->edgeOffset == 0 ) + { + return NULL; + } + + return (const b3HullHalfEdge*)( (intptr_t)hull + hull->edgeOffset ); +} + +B3_INLINE const b3HullFace* b3GetHullFaces( const b3Hull* hull ) +{ + if ( hull->faceOffset == 0 ) + { + return NULL; + } + + return (const b3HullFace*)( (intptr_t)hull + hull->faceOffset ); +} + +B3_INLINE const b3Plane* b3GetHullPlanes( const b3Hull* hull ) +{ + if ( hull->planeOffset == 0 ) + { + return NULL; + } + + return (const b3Plane*)( (intptr_t)hull + hull->planeOffset ); +} + +B3_API b3Hull* b3CreateCylinder( float height, float radius, float yOffset, int sides ); +B3_API b3Hull* b3CreateCone( float height, float radius1, float radius2, int slices ); +B3_API b3Hull* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount ); +B3_API b3Hull* b3CloneHull( const b3Hull* hull ); +B3_API b3Hull* b3CloneAndTransformHull( const b3Hull* original, b3Transform transform, b3Vec3 scale ); +B3_API void b3DestroyHull( b3Hull* hull ); + +/// Efficient box hull +typedef struct b3BoxHull +{ + b3Hull base; + b3HullVertex boxVertices[8]; + b3Vec3 boxPoints[8]; + b3HullHalfEdge boxEdges[24]; + b3HullFace boxFaces[6]; + b3Plane boxPlanes[6]; +} b3BoxHull; + +/// This makes a box hull cube. Do not call b3DestroyHull on this. +B3_API b3BoxHull b3MakeCubeHull( float halfWidth ); + +/// This makes a box hull. Do not call b3DestroyHull on this. +B3_API b3BoxHull b3MakeBoxHull( float hx, float hy, float hz ); + +B3_API b3BoxHull b3MakeOffsetBoxHull( float hx, float hy, float hz, b3Vec3 offset ); + +/// This makes an transformed box hull. Do not call b3DestroyHull on this. +/// @param hx, hy, hz positive half widths +/// @param transform local transform of box +B3_API b3BoxHull b3MakeTransformedBoxHull( float hx, float hy, float hz, b3Transform transform ); + +/// This makes an transformed box hull with post scaling. This is useful for boxes that are scaled in +/// a level editor. Such scaling can have reflection and sheer. In the case of sheer the result +/// may be approximate. If you need to support sheer consider using b3CreateHull. +/// Do not call b3DestroyHull on this. +/// @param halfWidths positive half widths +/// @param transform local transform of box +/// @param postScale scale applied after the transform, may be negative +B3_API b3BoxHull b3MakeScaledBoxHull( b3Vec3 halfWidths, b3Transform transform, b3Vec3 postScale ); + +/// This takes a box with a transform and post scale and converts it into a box with the post scale +/// resolved with new half-widths and transform. This accepts non-uniform and negative scale. +/// This is approximate if there is shear. +/// @param halfWidths [in/out] the box half widths +/// @param transform [in/out] the box transform with rotation and translation +/// @param postScale the post scale being applied to the box after the transform +/// @param minHalfWidth the minimum half width after scale is applied +B3_API void b3ScaleBox( b3Vec3* halfWidths, b3Transform* transform, b3Vec3 postScale, float minHalfWidth ); + +// 64-bit guid that is changed every time the format of the mesh changes +#define B3_MESH_VERSION 0x4A1E7B2C8D5F3091ull + +typedef enum b3MeshEdgeFlags +{ + b3_concaveEdge1 = 0x01, + b3_concaveEdge2 = 0x02, + b3_concaveEdge3 = 0x04, + + b3_inverseConcaveEdge1 = 0x10, + b3_inverseConcaveEdge2 = 0x20, + b3_inverseConcaveEdge3 = 0x40, + + b3_allConcaveEdges = b3_concaveEdge1 | b3_concaveEdge2 | b3_concaveEdge3, + + b3_flatEdge1 = b3_concaveEdge1 | b3_inverseConcaveEdge1, + b3_flatEdge2 = b3_concaveEdge2 | b3_inverseConcaveEdge2, + b3_flatEdge3 = b3_concaveEdge3 | b3_inverseConcaveEdge3, + + b3_allFlatEdges = b3_flatEdge1 | b3_flatEdge2 | b3_flatEdge3, + +} b3MeshEdgeFlags; + +typedef struct b3MeshTriangle +{ + int32_t index1; + int32_t index2; + int32_t index3; +} b3MeshTriangle; + +typedef struct b3MeshNode +{ + b3Vec3 lowerBound; + union + { + // Internal node + struct + { + uint32_t axis : 2; + uint32_t childOffset : 30; + } asNode; + + // Leaf node + struct + { + uint32_t type : 2; + uint32_t triangleCount : 30; + } asLeaf; + } data; + + b3Vec3 upperBound; + uint32_t triangleOffset; +} b3MeshNode; + +/// This is a sorted triangle collision tree. +/// @note This struct has data hanging off the end and cannot be directly copied. +typedef struct b3MeshData +{ + // Version must be first + uint64_t version; + int byteCount; + + // Hash of this mesh (this field is zero when the hash is computed) + uint32_t hash; + + b3AABB bounds; + + /// Combined surface area of all triangles. Single-sided. + float surfaceArea; + + int treeHeight; + int degenerateCount; + + // Offset of the node array in bytes from the struct address + int nodeOffset; + int nodeCount; + + // Offset of the vertex array in bytes from the struct address + int vertexOffset; + int vertexCount; + + // Offset of the triangle array in bytes from the struct address + int triangleOffset; + int triangleCount; + + // Offset of the material array in bytes from the struct address + int materialOffset; + int materialCount; + + // Offset of the triangle flag array in bytes from the struct address + int flagsOffset; +} b3MeshData; + +/// This small struct allows a mesh data to be re-used with different scale. +typedef struct b3Mesh +{ + const b3MeshData* data; + + /// This scale may be non-uniform and have negative components. However, + /// no component may be zero or very small in magnitude. + b3Vec3 scale; + +} b3Mesh; + +// todo these don't need to be inline +B3_INLINE const b3MeshNode* b3GetMeshNodes( const b3MeshData* mesh ) +{ + if ( mesh->nodeOffset == 0 ) + { + return NULL; + } + + return (const b3MeshNode*)( (intptr_t)mesh + mesh->nodeOffset ); +} + +B3_INLINE const b3Vec3* b3GetMeshVertices( const b3MeshData* mesh ) +{ + if ( mesh->vertexOffset == 0 ) + { + return NULL; + } + + return (const b3Vec3*)( (intptr_t)mesh + mesh->vertexOffset ); +} + +B3_INLINE const b3MeshTriangle* b3GetMeshTriangles( const b3MeshData* mesh ) +{ + if ( mesh->triangleOffset == 0 ) + { + return NULL; + } + + return (const b3MeshTriangle*)( (intptr_t)mesh + mesh->triangleOffset ); +} + +// @note count is equal to the triangle count +B3_INLINE const uint8_t* b3GetMeshMaterialIndices( const b3MeshData* mesh ) +{ + if ( mesh->materialOffset == 0 ) + { + return NULL; + } + + return (const uint8_t*)( (intptr_t)mesh + mesh->materialOffset ); +} + +// @note count is equal to the triangle count +B3_INLINE const uint8_t* b3GetMeshFlags( const b3MeshData* mesh ) +{ + if ( mesh->flagsOffset == 0 ) + { + return NULL; + } + + return (const uint8_t*)( (intptr_t)mesh + mesh->flagsOffset ); +} + +/// This is used to create a re-usable collision mesh +typedef struct b3MeshDef +{ + /// Triangle vertices + b3Vec3* vertices; + + /// Triangle vertex indices. 3 for each triangle. + int32_t* indices; + + /// Triangle material index. 1 per triangle. Indexes into b3ShapeDef::materials. + /// This allows different run-time material data to be associated with different + /// instances of this mesh. + uint8_t* materialIndices; + + /// Tolerance for vertex welding in length units. + float weldTolerance; + + int vertexCount; + int triangleCount; + + /// Optionally weld nearby vertices. + bool weldVertices; + + /// Use the median split instead of SAH to speed up mesh creation. Good + /// for meshes that are structured like a grid. + bool useMedianSplit; + + /// Compute triangle adjacency information using shared edges + bool identifyEdges; + +} b3MeshDef; + +/// Creates a grid mesh along the x and z axes. +/// @param xCount the number of rows in the x direction +/// @param zCount the number of rows in the z direction +/// @param cellWidth the width of each cell +/// @param materialCount the number of materials to generate +/// @param identifyEdges compute adjacency information +B3_API b3MeshData* b3CreateGridMesh( int xCount, int zCount, float cellWidth, int materialCount, bool identifyEdges ); + +B3_API b3MeshData* b3CreateWaveMesh( int xCount, int zCount, float cellWidth, float amplitude, float rowFrequency, + float columnFrequency ); +B3_API b3MeshData* b3CreateTorusMesh( int radialResolution, int tubularResolution, float radius, float thickness ); +B3_API b3MeshData* b3CreateBoxMesh( b3Vec3 center, b3Vec3 extent, bool identifyEdges ); +B3_API b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices, int degenerateCapacity ); +B3_API void b3DestroyMesh( b3MeshData* mesh ); +B3_API int b3GetHeight( const b3MeshData* mesh ); + +/// Data used to create a height field +typedef struct b3HeightFieldDef +{ + // Grid point heights + // count = countX * countZ + float* heights; + + // Grid cell material + // A value of 0xFF is reserved for holes + // count = (countX - 1) * (countZ - 1) + uint8_t* materialIndices; + + b3Vec3 scale; + int countX; + int countZ; + + // Global minimum and maximum heights used for quantization. This is important + // if you want height fields to be placed next to each other and line up exactly. + // In that case, both height fields should use the same minimum and maximum heights. + // All height values are clamped to this range. + // These values are in unscaled space. + float globalMinimumHeight; + float globalMaximumHeight; + + bool clockwiseWinding; +} b3HeightFieldDef; + +// This material index is used to designate holes in a height field. +#define B3_HEIGHT_FIELD_HOLE 0xFF + +// 64-bit guid that is changed every time the format of the height field changes +#define B3_HEIGHT_FIELD_VERSION 0xB6E83F1D947A28C5ull + +// A height field with compressed storage. +typedef struct b3HeightField +{ + // Version must be first + uint64_t version; + + // todo_erin use offset storage + uint16_t* compressedHeights; + uint8_t* materialIndices; + uint8_t* flags; + + // Hash of this height field (this field is zero when the hash is computed). + // Pointer values above are skipped; the bulk arrays they reference and the + // scalar block below are folded in at construction time. + uint32_t hash; + + b3AABB aabb; + float minHeight; + float maxHeight; + float heightScale; + b3Vec3 scale; + int columnCount; + int rowCount; + bool clockwise; +} b3HeightField; + +// Create a height field +B3_API b3HeightField* b3CreateHeightField( const b3HeightFieldDef* data ); +B3_API b3HeightField* b3CreateGrid( int rowCount, int columnCount, b3Vec3 scale, bool makeHoles ); +B3_API b3HeightField* b3CreateWave( int rowCount, int columnCount, b3Vec3 scale, float rowFrequency, float columnFrequency, + bool makeHoles ); +B3_API void b3DestroyHeightField( b3HeightField* heightField ); + +// Save input height data to a file +B3_API void b3DumpHeightData( const b3HeightFieldDef* data, const char* fileName ); + +// Create a height field by loading a previously saved height data +B3_API b3HeightField* b3LoadHeightField( const char* fileName ); + +typedef struct b3CompoundCapsuleDef +{ + b3Capsule capsule; + b3SurfaceMaterial material; +} b3CompoundCapsuleDef; + +typedef struct b3CompoundHullDef +{ + const b3Hull* hull; + b3Transform transform; + b3SurfaceMaterial material; +} b3CompoundHullDef; + +typedef struct b3CompoundMeshDef +{ + const b3MeshData* meshData; + b3Transform transform; + b3Vec3 scale; + + // This array must line up with the material indices on the triangles. + const b3SurfaceMaterial* materials; + int materialCount; + +} b3CompoundMeshDef; + +typedef struct b3CompoundSphereDef +{ + b3Sphere sphere; + b3SurfaceMaterial material; +} b3CompoundSphereDef; + +/// Definition to creating a compound shape. No data in this structure +/// is referenced in the compound. +typedef struct b3CompoundDef +{ + b3CompoundCapsuleDef* capsules; + int capsuleCount; + + /// Hulls instances. + b3CompoundHullDef* hulls; + int hullCount; + + /// Mesh instances + b3CompoundMeshDef* meshes; + int meshCount; + + /// Spheres are fully cloned + b3CompoundSphereDef* spheres; + int sphereCount; +} b3CompoundDef; + +#define B3_COMPOUND_VERSION ( 0x902AC5D34D9BD452ull ^ B3_DYNAMIC_TREE_VERSION ^ B3_MESH_VERSION ^ B3_HULL_VERSION ) + +/// Meshes used in compounds have limited space for materials. If you have +/// a mesh with many materials, you can use it outside of the the compound. +#define B3_MAX_COMPOUND_MESH_MATERIALS 4 + +typedef struct b3Compound +{ + uint64_t version; + int byteCount; + + // immutable tree + // The tree node pointer must be fixed up using the node offset + // todo use a custom tree like b3MeshData to save space and improve performance + int nodeOffset; + b3DynamicTree tree; + + int materialOffset; + int materialCount; + + int capsuleOffset; + int capsuleCount; + + int hullOffset; + int hullCount; + int sharedHullCount; + + int meshOffset; + int meshCount; + int sharedMeshCount; + + int sphereOffset; + int sphereCount; +} b3Compound; + +typedef struct b3CompoundCapsule +{ + b3Capsule capsule; + int materialIndex; +} b3CompoundCapsule; + +typedef struct b3CompoundHull +{ + const b3Hull* hull; + b3Transform transform; + int materialIndex; +} b3CompoundHull; + +typedef struct b3CompoundMesh +{ + const b3MeshData* meshData; + b3Transform transform; + b3Vec3 scale; + + // This is used to access the surface material from b3GetCompoundMaterials + // materialIndex = materialIndices[triangle->materialIndex] + int materialIndices[B3_MAX_COMPOUND_MESH_MATERIALS]; +} b3CompoundMesh; + +typedef struct b3CompoundSphere +{ + b3Sphere sphere; + int materialIndex; +} b3CompoundSphere; + +B3_API b3CompoundCapsule b3GetCompoundCapsule( const b3Compound* compound, int index ); +B3_API b3CompoundHull b3GetCompoundHull( const b3Compound* compound, int index ); +B3_API b3CompoundMesh b3GetCompoundMesh( const b3Compound* compound, int index ); +B3_API b3CompoundSphere b3GetCompoundSphere( const b3Compound* compound, int index ); +B3_API const b3SurfaceMaterial* b3GetCompoundMaterials( const b3Compound* compound ); + +// All input data in the definition is cloned into the resulting compound +B3_API b3Compound* b3CreateCompound( const b3CompoundDef* def ); +B3_API void b3DestroyCompound( b3Compound* compound ); + +/// If bytes is null then this returns the number of required bytes. This clones all the +/// data into the bytes buffer. This is expected to run offline or asynchronously. +/// This mutates the compound to nullify pointers, leaving the compound in an unusable state. +B3_API uint8_t* b3ConvertCompoundToBytes( b3Compound* compound ); + +/// Convert bytes to compound. This does not clone. The bytes must remain in scope while the +/// compound is used. This is done to improve run-time performance and allow for instancing. +/// The bytes are mutated to fixup pointers. +B3_API b3Compound* b3ConvertBytesToCompound( uint8_t* bytes, int byteCount ); + +/// Compute mass properties of a sphere +B3_API b3MassData b3ComputeSphereMass( const b3Sphere* shape, float density ); + +/// Compute mass properties of a capsule +B3_API b3MassData b3ComputeCapsuleMass( const b3Capsule* shape, float density ); + +/// Compute mass properties of a hull +B3_API b3MassData b3ComputeHullMass( const b3Hull* shape, float density ); + +/// Compute the bounding box of a transformed sphere +B3_API b3AABB b3ComputeSphereAABB( const b3Sphere* shape, b3Transform transform ); + +/// Compute the bounding box of a transformed capsule +B3_API b3AABB b3ComputeCapsuleAABB( const b3Capsule* shape, b3Transform transform ); + +/// Compute the bounding box of a transformed hull +B3_API b3AABB b3ComputeHullAABB( const b3Hull* shape, b3Transform transform ); + +/// Compute the bounding box of a transformed mesh. Scale may be non-uniform and have negative components. +B3_API b3AABB b3ComputeMeshAABB( const b3MeshData* shape, b3Transform transform, b3Vec3 scale ); + +/// Compute the bounding box of a transformed height-field +B3_API b3AABB b3ComputeHeightFieldAABB( const b3HeightField* shape, b3Transform transform ); + +/// Compute the bounding box of a compound +B3_API b3AABB b3ComputeCompoundAABB( const b3Compound* shape, b3Transform transform ); + +/// Use this to ensure your ray cast input is valid and avoid internal assertions. +B3_API bool b3IsValidRay( const b3RayCastInput* input ); + +/// Overlap shape versus capsule +B3_API bool b3OverlapCapsule( const b3Capsule* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy ); + +/// Overlap shape versus compound +B3_API bool b3OverlapCompound( const b3Compound* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy ); + +/// Overlap shape versus height field +B3_API bool b3OverlapHeightField( const b3HeightField* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy ); + +/// Overlap shape versus hull +B3_API bool b3OverlapHull( const b3Hull* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy ); + +/// Overlap shape versus mesh +B3_API bool b3OverlapMesh( const b3Mesh* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy ); + +/// Overlap shape versus sphere +B3_API bool b3OverlapSphere( const b3Sphere* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy ); + +/// Ray cast versus sphere in local space. Initial overlap is treated as a miss. +B3_API b3CastOutput b3RayCastSphere( const b3Sphere* shape, const b3RayCastInput* input ); + +/// Ray cast versus hollow sphere in local space. +B3_API b3CastOutput b3RayCastHollowSphere( const b3Sphere* shape, const b3RayCastInput* input ); + +/// Ray cast versus capsule in local space. Initial overlap is treated as a miss. +B3_API b3CastOutput b3RayCastCapsule( const b3Capsule* shape, const b3RayCastInput* input ); + +/// Ray cast versus compound in local space. Initial overlap is treated as a miss. +B3_API b3CastOutput b3RayCastCompound( const b3Compound* shape, const b3RayCastInput* input ); + +/// Ray cast versus hull shape in local space. Initial overlap is treated as a miss. +B3_API b3CastOutput b3RayCastHull( const b3Hull* shape, const b3RayCastInput* input ); + +/// Ray cast versus mesh in local space. +B3_API b3CastOutput b3RayCastMesh( const b3Mesh* shape, const b3RayCastInput* input ); + +/// Ray cast versus height field in local space. +B3_API b3CastOutput b3RayCastHeightField( const b3HeightField* shape, const b3RayCastInput* input ); + +/// Shape cast versus a sphere. Initial overlap is treated as a miss. +B3_API b3CastOutput b3ShapeCastSphere( const b3Sphere* shape, const b3ShapeCastInput* input ); + +/// Shape cast versus a capsule. Initial overlap is treated as a miss. +B3_API b3CastOutput b3ShapeCastCapsule( const b3Capsule* shape, const b3ShapeCastInput* input ); + +/// Shape cast versus compound. Initial overlap is treated as a miss. +B3_API b3CastOutput b3ShapeCastCompound( const b3Compound* shape, const b3ShapeCastInput* input ); + +/// Shape cast versus a hull. Initial overlap is treated as a miss. +B3_API b3CastOutput b3ShapeCastHull( const b3Hull* shape, const b3ShapeCastInput* input ); + +/// Shape cast versus a mesh. Initial overlap is treated as a miss. +B3_API b3CastOutput b3ShapeCastMesh( const b3Mesh* shape, const b3ShapeCastInput* input ); + +/// Shape cast versus a height field. Initial overlap is treated as a miss. +B3_API b3CastOutput b3ShapeCastHeightField( const b3HeightField* shape, const b3ShapeCastInput* input ); + +/// Query callback. +typedef bool b3MeshQueryFcn( b3Vec3 a, b3Vec3 b, b3Vec3 c, int triangleIndex, void* context ); + +/// Query a mesh for triangles overlapping a bounding box in local space. May have false positives. Useful for debug draw. +/// @param mesh the mesh to query, includes scale +/// @param bounds the bounding box in local space +/// @param fcn a user function to collect triangles +/// @param context the context sent to the user function. +B3_API void b3QueryMesh( const b3Mesh* mesh, const b3AABB bounds, b3MeshQueryFcn* fcn, void* context ); + +/// Query a height field for triangles overlapping a bounding box in local space. May have false positives. Useful for debug draw. +/// @param heightField the height field to query +/// @param bounds the bounding box in local space +/// @param fcn a user function to collect triangles +/// @param context the context sent to the user function. +B3_API void b3QueryHeightField( const b3HeightField* heightField, b3AABB bounds, b3MeshQueryFcn* fcn, void* context ); + +/** + * @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 b3SegmentDistanceResult +{ + /// The closest point on the first segment + b3Vec3 closest1; + + /// The closest point on the second segment + b3Vec3 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; +} b3SegmentDistanceResult; + +/// Compute the distance between two line segments, clamping at the end points if needed. +B3_API b3SegmentDistanceResult b3SegmentDistance( b3Vec3 p1, b3Vec3 q1, b3Vec3 p2, b3Vec3 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 b3SimplexCache +{ + /// Value use to compare length, area, volume of two simplexes. + float metric; + + // todo use an index of 0xFF as a sentinel and remove the count + /// The number of stored simplex points + uint16_t count; + + /// The cached simplex indices on shape A + uint8_t indexA[4]; + + /// The cached simplex indices on shape B + uint8_t indexB[4]; + +} b3SimplexCache; + +static const b3SimplexCache b3_emptyDistanceCache = B3_ZERO_INIT; + +/// Input for b3ShapeDistance +typedef struct b3DistanceInput +{ + /// The proxy for shape A + b3ShapeProxy proxyA; + + /// The proxy for shape B + b3ShapeProxy proxyB; + + /// The world transform for shape A + b3Transform transformA; + + /// The world transform for shape B + b3Transform transformB; + + /// Should the proxy radius be considered? + bool useRadii; +} b3DistanceInput; + +/// Output for b3ShapeDistance +typedef struct b3DistanceOutput +{ + b3Vec3 pointA; ///< Closest point on shapeA + b3Vec3 pointB; ///< Closest point on shapeB + b3Vec3 normal; ///< Normal vector pointing from A to B + 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 +} b3DistanceOutput; + +/// Simplex vertex for debugging the GJK algorithm +typedef struct b3SimplexVertex +{ + b3Vec3 wA; ///< support point in proxyA + b3Vec3 wB; ///< support point in proxyB + b3Vec3 w; ///< wB - wA + float a; ///< barycentric coordinates + int indexA; ///< wA index + int indexB; ///< wB index +} b3SimplexVertex; + +/// Simplex from the GJK algorithm +typedef struct b3Simplex +{ + b3SimplexVertex vertices[4]; ///< vertices + int count; ///< number of valid vertices +} b3Simplex; + +/// Compute the closest points between two shapes represented as point clouds. +/// b3SimplexCache cache is input/output. On the first call set b3SimplexCache.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. +/// todo make cache optional (can be null) +B3_API b3DistanceOutput b3ShapeDistance( const b3DistanceInput* input, b3SimplexCache* cache, b3Simplex* simplexes, + int simplexCapacity ); + +/// Input parameters for b3ShapeCast +typedef struct b3ShapeCastPairInput +{ + b3ShapeProxy proxyA; ///< The proxy for shape A + b3ShapeProxy proxyB; ///< The proxy for shape B + b3Transform transformA; ///< The world transform for shape A + b3Transform transformB; ///< The world transform for shape B + b3Vec3 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 +} b3ShapeCastPairInput; + +/// Perform a linear shape cast of shape B moving and shape A fixed. Determines the hit point, normal, and translation fraction. +B3_API b3CastOutput b3ShapeCast( const b3ShapeCastPairInput* input ); + +/// 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 b3Sweep +{ + b3Vec3 localCenter; ///< Local center of mass position + b3Vec3 c1; ///< Starting center of mass world position + b3Vec3 c2; ///< Ending center of mass world position + b3Quat q1; ///< Starting world rotation + b3Quat q2; ///< Ending world rotation +} b3Sweep; + +/// Evaluate the transform sweep at a specific time. +B3_API b3Transform b3GetSweepTransform( const b3Sweep* sweep, float time ); + +/// Time of impact input +typedef struct b3TOIInput +{ + b3ShapeProxy proxyA; ///< The proxy for shape A + b3ShapeProxy proxyB; ///< The proxy for shape B + b3Sweep sweepA; ///< The movement of shape A + b3Sweep sweepB; ///< The movement of shape B + float maxFraction; ///< Defines the sweep interval [0, tMax] +} b3TOIInput; + +/// Describes the TOI output +typedef enum b3TOIState +{ + b3_toiStateUnknown, + b3_toiStateFailed, + b3_toiStateOverlapped, + b3_toiStateHit, + b3_toiStateSeparated +} b3TOIState; + +/// Time of impact output +typedef struct b3TOIOutput +{ + /// The type of result + b3TOIState state; + + /// The hit point + b3Vec3 point; + + /// The hit normal + b3Vec3 normal; + + /// The sweep time of the collision + float fraction; + + /// The final distance + float distance; + + /// Number of outer iterations + int distanceIterations; + + /// Total number of push back iterations + int pushBackIterations; + + /// Total number of root iterations + int rootIterations; + + bool usedFallback; +} b3TOIOutput; + +/// 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. +B3_API b3TOIOutput b3TimeOfImpact( const b3TOIInput* input ); + +/**@}*/ + +/// 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. +/// Box3D uses speculative collision so some contact points may be separated. +/// You may use the maxNormalImpulse to determine if there was an interaction during +/// the time step. +typedef struct b3ManifoldPoint +{ + /// Location of the contact point relative to the bodyA center of mass in world space. + b3Vec3 anchorA; + + /// Location of the contact point relative to the bodyB center of mass in world space. + b3Vec3 anchorB; + + /// The separation of the contact point, negative if penetrating + float separation; + + /// Cached separation used for contact recycling + float baseSeparation; + + /// The impulse along the manifold normal vector. Since Box3D uses sub-stepping, this is + /// result from the final sub-step. + float normalImpulse; + + /// The total normal impulse applied during sub-stepping. This is important + /// to identify speculative contact points that had an interaction in the time step. + 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; + + /// Local point for matching + /// Uniquely identifies a contact point between two shapes + uint32_t featureId; + + /// Triangle index if one of the shapes is a mesh or height field + int triangleIndex; + + /// Did this contact point exist the previous step? + bool persisted; +} b3ManifoldPoint; + +/// The maximum number of contact points between two touching shapes. +#define B3_MAX_MANIFOLD_POINTS 4 + +/// A contact manifold describes the contact points between colliding shapes. +/// @note Box3D uses speculative collision so some contact points may be separated. +typedef struct b3Manifold +{ + /// The manifold points. There may be 1 to 4 valid points. + b3ManifoldPoint points[B3_MAX_MANIFOLD_POINTS]; + + /// The unit normal vector in world space, points from shape A to bodyB + b3Vec3 normal; + + // Central friction angular impulse (applied about the normal) + float twistImpulse; + + // Central friction linear impulse + b3Vec3 frictionImpulse; + + // Rolling resistance angular impulse + b3Vec3 rollingImpulse; + + /// The number of contacts points, will be 0, 1, or 2 + int pointCount; + +} b3Manifold; + +// todo adopt this for SAT +typedef enum +{ + b3_invalidAxis = 0, + b3_backsideAxis, + b3_faceAxisA, + b3_faceAxisB, + b3_edgePairAxis, + b3_closestPointsAxis, + + // These are for testing + b3_manualFaceAxisA, + b3_manualFaceAxisB, + b3_manualEdgePairAxis, +} b3SeparatingFeature; + +typedef enum +{ + b3_featureNone = 0, + b3_featureTriangleFace, + b3_featureHullFace, + // v1-v2 + b3_featureEdge1, + // v2-v3 + b3_featureEdge2, + // v3-v1 + b3_featureEdge3, + b3_featureVertex1, + b3_featureVertex2, + b3_featureVertex3 +} b3TriangleFeature; + +typedef struct +{ + float separation; + // b3SeparatingFeature + uint8_t type; + uint8_t indexA; + uint8_t indexB; + uint8_t hit; +} b3SATCache; + +/// Contact points are always the result of two edges intersecting. +/// It can be two edges of the same shape, which is just a shape vertex. +/// Or a contact point can be the result of two edges crossing from different shapes. +/// This is designed to support hull versus hull, but it is adapted to work +/// with all shape types. The feature pair is used to identify contact points +/// for temporal coherence and warm starting. +typedef struct b3FeaturePair +{ + // Incoming type (either edge on shape A or shape B) + uint8_t owner1; + // Incoming edge index (into associated shape array) + uint8_t index1; + // Outgoing type (either edge on shape A or shape B) + uint8_t owner2; + // Outgoing edge index (into associated shape array) + uint8_t index2; +} b3FeaturePair; + +/// A local manifold point and normal in frame A +typedef struct b3LocalManifoldPoint +{ + b3Vec3 point; + b3Vec3 normal; + float separation; + b3FeaturePair pair; + int triangleIndex; +} b3LocalManifoldPoint; + +/// A local manifold with no dynamic information. Used by b3Collide functions. +typedef struct b3LocalManifold +{ + b3Vec3 normal; + b3Plane trianglePlane; + b3LocalManifoldPoint* points; + int pointCount; + int triangleIndex; + int i1, i2, i3; + float squaredDistance; + b3TriangleFeature feature; + int triangleFlags; +} b3LocalManifold; + +B3_API void b3CollideSpheres( b3LocalManifold* manifold, int capacity, const b3Sphere* sphereA, const b3Sphere* sphereB, + b3Transform transformBtoA ); + +B3_API void b3CollideCapsuleAndSphere( b3LocalManifold* manifold, int capacity, const b3Capsule* capsuleA, const b3Sphere* sphereB, + b3Transform transformBtoA ); + +B3_API void b3CollideHullAndSphere( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Sphere* sphereB, + b3Transform transformBtoA, b3SimplexCache* cache ); + +B3_API void b3CollideCapsules( b3LocalManifold* manifold, int capacity, const b3Capsule* capsuleA, const b3Capsule* capsuleB, + b3Transform transformBtoA ); + +B3_API void b3CollideHullAndCapsule( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Capsule* capsuleB, + b3Transform transformBtoA, b3SimplexCache* cache ); + +B3_API void b3CollideHulls( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Hull* hullB, + b3Transform transformBtoA, b3SATCache* cache ); + +B3_API void b3CollideCapsuleAndTriangle( b3LocalManifold* manifold, int capacity, const b3Capsule* capsuleA, + const b3Vec3* triangleB, b3SimplexCache* cache ); + +// b3MeshEdgeFlags +B3_API void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Vec3* triangleB, + int triangleFlags, b3SATCache* cache ); + +B3_API void b3CollideSphereAndTriangle( b3LocalManifold* manifold, int capacity, const b3Sphere* sphereA, const b3Vec3* triangleB ); + +B3_API bool b3IntersectRayAndAABB( b3Vec3 lowerBound, b3Vec3 upperBound, b3Vec3 p1, b3Vec3 p2, float* minFraction, + float* maxFraction ); + +/**@}*/ + +/** + * @defgroup character + * Experimental character movement solver + * @{ + */ + +typedef struct b3PlaneResult +{ + b3Plane plane; + b3Vec3 point; +} b3PlaneResult; + +typedef struct b3CollisionPlane +{ + b3Plane plane; + float pushLimit; + float push; + bool clipVelocity; +} b3CollisionPlane; + +typedef struct b3PlaneSolverResult +{ + b3Vec3 delta; + int iterationCount; +} b3PlaneSolverResult; + +B3_API b3PlaneSolverResult b3SolvePlanes( b3Vec3 targetDelta, b3CollisionPlane* planes, int count ); +B3_API b3Vec3 b3ClipVector( b3Vec3 vector, const b3CollisionPlane* planes, int count ); + +/**@}*/ + +typedef struct b3ClosestApproachResult +{ + b3Vec3 point1; + float lambda1; + b3Vec3 point2; + float lambda2; +} b3ClosestApproachResult; + +/// Compute the closest point on the segment a-b to the target q +B3_API b3Vec3 b3ClosestPointOnSegment( b3Vec3 a, b3Vec3 b, b3Vec3 q ); + +/// Compute the closest points on two infinite lines +B3_API b3ClosestApproachResult b3ClosestApproachLines( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3 d2 ); + +/// Compute the closest points on two line segments +B3_API b3ClosestApproachResult b3ClosestApproachSegments( b3Vec3 p1, b3Vec3 q1, b3Vec3 p2, b3Vec3 q2 ); + +typedef struct b3Point2D +{ + b3Vec2 p; + float separation; + int16_t originalIndex; + bool persisted; +} b3Point2D; + +B3_API int b3Hull2D( b3Point2D* pts, int count, b3Point2D* hull ); +B3_API int b3SimplifyHull2D( b3Point2D* hull, int count, int target ); +B3_API int b3CullPoints( b3Point2D* points, int count, int target ); diff --git a/include/box3d/constants.h b/include/box3d/constants.h new file mode 100644 index 0000000..847fff4 --- /dev/null +++ b/include/box3d/constants.h @@ -0,0 +1,82 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "base.h" + +/// 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. +/// @warning This must be modified before any calls to Box2D +B3_API void b3SetLengthUnitsPerMeter( float lengthUnits ); + +/// Get the current length units per meter. +B3_API float b3GetLengthUnitsPerMeter( void ); + +// 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 B3_HUGE ( 100000.0f * b3GetLengthUnitsPerMeter() ) + +/// Maximum parallel workers. Used for some fixed size arrays. +#define B3_MAX_WORKERS 32 + +/// Maximum number of tasks queued per world step. b2EnqueueTaskCallback will never be called +/// more than this per world step. This is related to B3_MAX_WORKERS. With 32 workers, +/// the maximum observed task count is 130. This allows an external task system to use a fixed +/// size array for Box3D task, which may help with creating stable user task pointers. +#define B3_MAX_TASKS 256 + +// 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 B3_GRAPH_COLOR_COUNT 24 + +// Number of contact point buckets for counting the number of contact points per +// shape contact pair. This is just for reporting and doesn't affect simulation. +#define B3_CONTACT_MANIFOLD_COUNT_BUCKETS 8 + +// A small length used as a collision and constraint tolerance. Usually it is +// chosen to be numerically significant, but visually insignificant. In meters. +// @warning modifying this can have a significant impact on stability +#define B3_LINEAR_SLOP ( 0.005f * b3GetLengthUnitsPerMeter() ) + +#define B3_MIN_CAPSULE_LENGTH ( B3_LINEAR_SLOP ) + +// The distance between shapes where they are considered overlapped. This is needed +// because GJK may return small positive values for overlapped shapes in degenerate +// configurations. +#define B3_OVERLAP_SLOP ( 0.1f * B3_LINEAR_SLOP ) + +// Maximum number of simultaneous worlds that can be allocated +#ifndef B3_MAX_WORLDS +#define B3_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 * b3_pi or greater will break continuous collision. +#define B3_MAX_ROTATION ( 0.25f * B3_PI ) + +// @warning modifying this can have a significant impact on performance and stability +#define B3_SPECULATIVE_DISTANCE ( 4.0f * B3_LINEAR_SLOP ) + +/// The default contact recycling distance. +#define B3_CONTACT_RECYCLE_DISTANCE ( 10.0f * B3_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. +// @warning modifying this can have a significant impact on performance +#define B3_AABB_MARGIN ( 0.05f * b3GetLengthUnitsPerMeter() ) + +// The time that a body must be still before it will go to sleep. In seconds. +#define B3_TIME_TO_SLEEP 0.5f + +// Body and shape name lengths +#define B3_NAME_LENGTH 64 + +// These generous limits allow for easy hashing. See b3ShapePairKey. +#define B3_SHAPE_POWER 22 +#define B3_CHILD_POWER ( 64 - 2 * B3_SHAPE_POWER ) +#define B3_MAX_SHAPES ( 1 << B3_SHAPE_POWER ) +#define B3_MAX_CHILD_SHAPES ( 1 << B3_CHILD_POWER ) diff --git a/include/box3d/id.h b/include/box3d/id.h new file mode 100644 index 0000000..7d59c94 --- /dev/null +++ b/include/box3d/id.h @@ -0,0 +1,172 @@ +// 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} + * b3WorldId worldId = {}; + * @endcode + * + * Or in C: + * + * @code{.c} + * b3WorldId 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 b3WorldId +{ + uint16_t index1; + uint16_t generation; +} b3WorldId; + +/// Body id references a body instance. This should be treated as an opaque handle. +typedef struct b3BodyId +{ + int32_t index1; + uint16_t world0; + uint16_t generation; +} b3BodyId; + +/// Shape id references a shape instance. This should be treated as an opaque handle. +typedef struct b3ShapeId +{ + int32_t index1; + uint16_t world0; + uint16_t generation; +} b3ShapeId; + +/// Joint id references a joint instance. This should be treated as an opaque handle. +typedef struct b3JointId +{ + int32_t index1; + uint16_t world0; + uint16_t generation; +} b3JointId; + +/// Contact id references a contact instance. This should be treated as an opaque handled. +typedef struct b3ContactId +{ + int32_t index1; + uint16_t world0; + int16_t padding; + uint32_t generation; +} b3ContactId; + +#ifdef __cplusplus + #define B3_NULL_ID {} + #define B3_ID_INLINE inline +#else + #define B3_NULL_ID { 0 } + #define B3_ID_INLINE static inline +#endif + +/// Use these to make your identifiers null. +/// You may also use zero initialization to get null. +static const b3WorldId b3_nullWorldId = B3_NULL_ID; +static const b3BodyId b3_nullBodyId = B3_NULL_ID; +static const b3ShapeId b3_nullShapeId = B3_NULL_ID; +static const b3JointId b3_nullJointId = B3_NULL_ID; +static const b3ContactId b3_nullContactId = B3_NULL_ID; + +/// Macro to determine if any id is null. +#define B3_IS_NULL( id ) ( id.index1 == 0 ) + +/// Macro to determine if any id is non-null. +#define B3_IS_NON_NULL( id ) ( id.index1 != 0 ) + +/// Compare two ids for equality. Doesn't work for b3WorldId. Don't mix types. +#define B3_ID_EQUALS( id1, id2 ) ( id1.index1 == id2.index1 && id1.world0 == id2.world0 && id1.generation == id2.generation ) + +/// Store a world id into a uint32_t. +B3_ID_INLINE uint32_t b3StoreWorldId( b3WorldId id ) +{ + return ( (uint32_t)id.index1 << 16 ) | (uint32_t)id.generation; +} + +/// Load a uint32_t into a world id. +B3_ID_INLINE b3WorldId b3LoadWorldId( uint32_t x ) +{ + b3WorldId id = { (uint16_t)( x >> 16 ), (uint16_t)( x ) }; + return id; +} + +/// Store a body id into a uint64_t. +B3_ID_INLINE uint64_t b3StoreBodyId( b3BodyId id ) +{ + return ( (uint64_t)id.index1 << 32 ) | ( (uint64_t)id.world0 ) << 16 | (uint64_t)id.generation; +} + +/// Load a uint64_t into a body id. +B3_ID_INLINE b3BodyId b3LoadBodyId( uint64_t x ) +{ + b3BodyId id = { (int32_t)( x >> 32 ), (uint16_t)( x >> 16 ), (uint16_t)( x ) }; + return id; +} + +/// Store a shape id into a uint64_t. +B3_ID_INLINE uint64_t b3StoreShapeId( b3ShapeId id ) +{ + return ( (uint64_t)id.index1 << 32 ) | ( (uint64_t)id.world0 ) << 16 | (uint64_t)id.generation; +} + +/// Load a uint64_t into a shape id. +B3_ID_INLINE b3ShapeId b3LoadShapeId( uint64_t x ) +{ + b3ShapeId id = { (int32_t)( x >> 32 ), (uint16_t)( x >> 16 ), (uint16_t)( x ) }; + return id; +} + +/// Store a joint id into a uint64_t. +B3_ID_INLINE uint64_t b3StoreJointId( b3JointId id ) +{ + return ( (uint64_t)id.index1 << 32 ) | ( (uint64_t)id.world0 ) << 16 | (uint64_t)id.generation; +} + +/// Load a uint64_t into a joint id. +B3_ID_INLINE b3JointId b3LoadJointId( uint64_t x ) +{ + b3JointId id = { (int32_t)( x >> 32 ), (uint16_t)( x >> 16 ), (uint16_t)( x ) }; + return id; +} + +/// Store a contact id into 16 bytes +B3_ID_INLINE void b3StoreContactId( b3ContactId 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. +B3_ID_INLINE b3ContactId b3LoadContactId( uint32_t values[3] ) +{ + b3ContactId id; + id.index1 = (int32_t)values[0]; + id.world0 = (uint16_t)values[1]; + id.padding = 0; + id.generation = (uint32_t)values[2]; + return id; +} + +/**@}*/ diff --git a/include/box3d/math_functions.h b/include/box3d/math_functions.h new file mode 100644 index 0000000..13a1092 --- /dev/null +++ b/include/box3d/math_functions.h @@ -0,0 +1,1106 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "base.h" + +#include + +// for sqrtf and remainderf +#include +#include + +/** + * @defgroup math Math + * @brief Vector math types and functions + * @{ + */ + +typedef struct b3Vec2 +{ + float x; + float y; +} b3Vec2; + +typedef struct b3Vec3 +{ + float x; + float y; + float z; +} b3Vec3; + +/// Cosine and sine pair +/// This uses a custom implementation designed for cross-platform determinism +typedef struct b3CosSin +{ + /// cosine and sine + float cosine; + float sine; +} b3CosSin; + +typedef struct b3Quat +{ + b3Vec3 v; + float s; +} b3Quat; + +typedef struct b3Transform +{ + b3Vec3 p; + b3Quat q; +} b3Transform; + +typedef struct b3Matrix3 +{ + b3Vec3 cx, cy, cz; +} b3Matrix3; + +typedef struct b3AABB +{ + b3Vec3 lowerBound; + b3Vec3 upperBound; +} b3AABB; + +/// separation = dot(normal, point) - offset +typedef struct b3Plane +{ + b3Vec3 normal; + float offset; +} b3Plane; + +/**@}*/ + +/** + * @addtogroup math + * @{ + */ + +#define B3_PI 3.141592654f +#define B3_DEG_TO_RAD 0.01745329251f +#define B3_RAD_TO_DEG 57.2957795131f + +/// Minimum scale used for scaling collision meshes, etc. +#define B3_MIN_SCALE 0.01f + +static const b3Vec3 b3Vec3_zero = { 0.0f, 0.0f, 0.0f }; +static const b3Vec3 b3Vec3_one = { 1.0f, 1.0f, 1.0f }; +static const b3Vec3 b3Vec3_axisX = { 1.0f, 0.0f, 0.0f }; +static const b3Vec3 b3Vec3_axisY = { 0.0f, 1.0f, 0.0f }; +static const b3Vec3 b3Vec3_axisZ = { 0.0f, 0.0f, 1.0f }; + +static const b3Quat b3Quat_identity = { { 0.0f, 0.0f, 0.0f }, 1.0f }; +static const b3Transform b3Transform_identity = { { 0.0f, 0.0f, 0.0f }, { { 0.0f, 0.0f, 0.0f }, 1.0f } }; + +static const b3Matrix3 b3Mat3_zero = { + { 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.0f }, +}; + +static const b3Matrix3 b3Mat3_identity = { + { 1.0f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f }, + { 0.0f, 0.0f, 1.0f }, +}; + +/// @return the minimum of two integers +B3_INLINE int b3MinInt( int a, int b ) +{ + return a < b ? a : b; +} + +/// @return the maximum of two integers +B3_INLINE int b3MaxInt( int a, int b ) +{ + return a > b ? a : b; +} + +/// @return an integer clamped between a lower and upper bound +B3_INLINE int b3ClampInt( int a, int lower, int upper ) +{ + return a < lower ? lower : ( upper < a ? upper : a ); +} + +/// Is this float valid (finite and not NaN) +B3_API bool b3IsValidFloat( float a ); + +/// @return the absolute value of a float +B3_INLINE float b3AbsFloat( float a ) +{ + return a < 0 ? -a : a; +} + +/// @return the minimum of two floats +B3_INLINE float b3MinFloat( float a, float b ) +{ + return a < b ? a : b; +} + +/// @return the maximum of two floats +B3_INLINE float b3MaxFloat( float a, float b ) +{ + return a > b ? a : b; +} + +/// @return a float clamped between a lower and upper bound +B3_INLINE float b3ClampFloat( float a, float lower, float upper ) +{ + return a < lower ? lower : ( upper < a ? upper : a ); +} + +/// Interpolate a scalar +B3_INLINE float b3LerpFloat( float a, float b, float alpha ) +{ + return ( 1.0f - alpha ) * a + alpha * b; +} + +/// 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 +B3_API float b3Atan2( float y, float x ); + +/// Compute the cosine and sine of an angle in radians. Implemented +/// for cross-platform determinism. +B3_API b3CosSin b3ComputeCosSin( float radians ); + +B3_INLINE float b3Sin( float radians ) +{ + b3CosSin cs = b3ComputeCosSin( radians ); + return cs.sine; +} + +B3_INLINE float b3Cos( float radians ) +{ + b3CosSin cs = b3ComputeCosSin( radians ); + return cs.cosine; +} + +/// Convert any angle into the range [-pi, pi] +B3_INLINE float b3UnwindAngle( float radians ) +{ + // Assuming this is deterministic + return remainderf( radians, 2.0f * B3_PI ); +} + +/// Vector addition +B3_INLINE b3Vec3 b3Add( b3Vec3 a, b3Vec3 b ) +{ + return B3_LITERAL( b3Vec3 ){ a.x + b.x, a.y + b.y, a.z + b.z }; +} + +/// Vector subtraction +B3_INLINE b3Vec3 b3Sub( b3Vec3 a, b3Vec3 b ) +{ + return B3_LITERAL( b3Vec3 ){ a.x - b.x, a.y - b.y, a.z - b.z }; +} + +/// Vector component-wise multiplication +B3_INLINE b3Vec3 b3Mul( b3Vec3 a, b3Vec3 b ) +{ + return B3_LITERAL( b3Vec3 ){ a.x * b.x, a.y * b.y, a.z * b.z }; +} + +/// Vector negation +B3_INLINE b3Vec3 b3Neg( b3Vec3 a ) +{ + return B3_LITERAL( b3Vec3 ){ -a.x, -a.y, -a.z }; +} + +/// Vector dot product +B3_INLINE float b3Dot( b3Vec3 a, b3Vec3 b ) +{ + return a.x * b.x + a.y * b.y + a.z * b.z; +} + +/// Vector length +B3_INLINE float b3Length( b3Vec3 v ) +{ + return sqrtf( b3Dot( v, v ) ); +} + +/// Vector length squared +B3_INLINE float b3LengthSquared( b3Vec3 a ) +{ + return a.x * a.x + a.y * a.y + a.z * a.z; +} + +B3_INLINE float b3Distance( b3Vec3 v1, b3Vec3 v2 ) +{ + b3Vec3 dv = { v2.x - v1.x, v2.y - v1.y, v2.z - v1.z }; + return b3Length( dv ); +} + +B3_INLINE float b3DistanceSquared( b3Vec3 v1, b3Vec3 v2 ) +{ + b3Vec3 dv = { v2.x - v1.x, v2.y - v1.y, v2.z - v1.z }; + return dv.x * dv.x + dv.y * dv.y + dv.z * dv.z; +} + +B3_INLINE b3Vec3 b3Normalize( b3Vec3 a ) +{ + float lengthSquared = a.x * a.x + a.y * a.y + a.z * a.z; + + if ( lengthSquared > 1000.0f * FLT_MIN ) + { + float s = 1.0f / sqrtf( lengthSquared ); + b3Vec3 u = { s * a.x, s * a.y, s * a.z }; + return u; + } + + return B3_LITERAL( b3Vec3 ){ 0.0f, 0.0f, 0.0f }; +} + +B3_INLINE b3Vec3 b3GetLengthAndNormalize( float* length, b3Vec3 v ) +{ + *length = b3Length( v ); + if ( *length < FLT_EPSILON ) + { + return b3Vec3_zero; + } + + float invLength = 1.0f / *length; + b3Vec3 n = { invLength * v.x, invLength * v.y, invLength * v.z }; + return n; +} + +B3_INLINE b3Vec3 b3Perp( b3Vec3 v ) +{ + // Suppose vector a has all equal components and is a unit vector: a = (s, s, s) + // Then 3*s*s = 1, s = sqrt(1/3) = 0.57735. This means that at least one component + // of a unit vector must be greater or equal to 0.57735. + b3Vec3 p; + if ( v.x < -0.5f || 0.5f < v.x ) + { + p = B3_LITERAL( b3Vec3 ){ v.y, -v.x, 0.0f }; + } + else + { + p = B3_LITERAL( b3Vec3 ){ 0.0f, v.z, -v.y }; + } + + return b3Normalize( p ); +} + +B3_INLINE bool b3IsNormalized( b3Vec3 a ) +{ + float aa = b3Dot( a, a ); + return b3AbsFloat( 1.0f - aa ) < 100.0f * FLT_EPSILON; +} + +/// a + s * b +B3_INLINE b3Vec3 b3MulAdd( b3Vec3 a, float s, b3Vec3 b ) +{ + return B3_LITERAL( b3Vec3 ){ a.x + s * b.x, a.y + s * b.y, a.z + s * b.z }; +} + +/// a - s * b +B3_INLINE b3Vec3 b3MulSub( b3Vec3 a, float s, b3Vec3 b ) +{ + return B3_LITERAL( b3Vec3 ){ a.x - s * b.x, a.y - s * b.y, a.z - s * b.z }; +} + +/// a + s * b +B3_INLINE b3Vec3 b3MulSV( float s, b3Vec3 a ) +{ + return B3_LITERAL( b3Vec3 ){ s * a.x, s * a.y, s * a.z }; +} + +B3_INLINE b3Vec3 b3Cross( b3Vec3 a, b3Vec3 b ) +{ + b3Vec3 c; + c.x = a.y * b.z - a.z * b.y; + c.y = a.z * b.x - a.x * b.z; + c.z = a.x * b.y - a.y * b.x; + return c; +} + +B3_INLINE b3Vec3 b3Lerp( b3Vec3 a, b3Vec3 b, float alpha ) +{ + B3_ASSERT( 0.0f <= alpha && alpha <= 1.0f ); + + b3Vec3 c = { + ( 1.0f - alpha ) * a.x + alpha * b.x, + ( 1.0f - alpha ) * a.y + alpha * b.y, + ( 1.0f - alpha ) * a.z + alpha * b.z, + }; + return c; +} + +B3_INLINE b3Vec3 b3Blend2( float s, b3Vec3 a, float t, b3Vec3 b ) +{ + b3Vec3 d = { + s * a.x + t * b.x, + s * a.y + t * b.y, + s * a.z + t * b.z, + }; + return d; +} + +B3_INLINE b3Vec3 b3Blend3( float s, b3Vec3 a, float t, b3Vec3 b, float u, b3Vec3 c ) +{ + b3Vec3 d = { + s * a.x + t * b.x + u * c.x, + s * a.y + t * b.y + u * c.y, + s * a.z + t * b.z + u * c.z, + }; + return d; +} + +B3_INLINE b3Vec3 b3Abs( b3Vec3 a ) +{ + return B3_LITERAL( b3Vec3 ){ + b3AbsFloat( a.x ), + b3AbsFloat( a.y ), + b3AbsFloat( a.z ), + }; +} + +// -1 or 1 (1 if zero) +B3_INLINE b3Vec3 b3Sign( b3Vec3 a ) +{ + return B3_LITERAL( b3Vec3 ){ + a.x >= 0.0f ? 1.0f : -1.0f, + a.y >= 0.0f ? 1.0f : -1.0f, + a.z >= 0.0f ? 1.0f : -1.0f, + }; +} + +B3_INLINE b3Vec3 b3Min( b3Vec3 a, b3Vec3 b ) +{ + return B3_LITERAL( b3Vec3 ){ + b3MinFloat( a.x, b.x ), + b3MinFloat( a.y, b.y ), + b3MinFloat( a.z, b.z ), + }; +} + +B3_INLINE b3Vec3 b3Max( b3Vec3 a, b3Vec3 b ) +{ + return B3_LITERAL( b3Vec3 ){ + b3MaxFloat( a.x, b.x ), + b3MaxFloat( a.y, b.y ), + b3MaxFloat( a.z, b.z ), + }; +} + +B3_INLINE b3Vec3 b3Clamp( b3Vec3 a, b3Vec3 lower, b3Vec3 upper ) +{ + b3Vec3 b; + b.x = b3ClampFloat( a.x, lower.x, upper.x ); + b.y = b3ClampFloat( a.y, lower.y, upper.y ); + b.z = b3ClampFloat( a.z, lower.z, upper.z ); + return b; +} + +// Create a safe scaling value for scaling collision. This allows +// negative scale, but keeps scale sufficiently far from zero. +B3_INLINE b3Vec3 b3SafeScale( b3Vec3 a ) +{ + b3Vec3 absScale = b3Abs( a ); + b3Vec3 minScale = { B3_MIN_SCALE, B3_MIN_SCALE, B3_MIN_SCALE }; + b3Vec3 safeScale = b3Mul( b3Sign( a ), b3Max( absScale, minScale ) ); + return safeScale; +} + +B3_INLINE bool b3IsNormalizedQuat( b3Quat q ) +{ + float qq = q.v.x * q.v.x + q.v.y * q.v.y + q.v.z * q.v.z + q.s * q.s; + return 1.0f - 20.0f * FLT_EPSILON < qq && qq < 1.0f + 20.0f * FLT_EPSILON; +} + +/// Rotate a vector +B3_INLINE b3Vec3 b3RotateVector( b3Quat q, b3Vec3 v ) +{ + // v + 2 * cross(q.v, cross(q.v, v) + q.s * v) + // B3_ASSERT( b3IsNormalizedQuat( q ) ); + b3Vec3 t1 = b3Cross( q.v, v ); + b3Vec3 t2 = b3MulAdd( t1, q.s, v ); + b3Vec3 t3 = b3Cross( q.v, t2 ); + return b3MulAdd( v, 2.0f, t3 ); +} + +/// Inverse rotate a vector +B3_INLINE b3Vec3 b3InvRotateVector( b3Quat q, b3Vec3 v ) +{ + // v + 2 * cross(q.v, cross(q.v, v) - q.s * v) + // B3_ASSERT( b3IsNormalizedQuat( q ) ); + b3Vec3 t1 = b3Cross( q.v, v ); + b3Vec3 t2 = b3MulSub( t1, q.s, v ); + b3Vec3 t3 = b3Cross( q.v, t2 ); + return b3MulAdd( v, 2.0f, t3 ); +} + +B3_INLINE float b3DotQuat( b3Quat a, b3Quat b ) +{ + return a.v.x * b.v.x + a.v.y * b.v.y + a.v.z * b.v.z + a.s * b.s; +} + +B3_INLINE b3Quat b3MulQuat( b3Quat q1, b3Quat q2 ) +{ + b3Vec3 t1 = b3Cross( q1.v, q2.v ); + b3Vec3 t2 = b3MulAdd( t1, q1.s, q2.v ); + b3Vec3 t3 = b3MulAdd( t2, q2.s, q1.v ); + b3Quat q = { t3, q1.s * q2.s - b3Dot( q1.v, q2.v ) }; + return q; +} + +// inv(q1) * q2 +B3_INLINE b3Quat b3InvMulQuat( b3Quat q1, b3Quat q2 ) +{ + b3Vec3 t1 = b3Cross( q2.v, q1.v ); + b3Vec3 t2 = b3MulAdd( t1, q1.s, q2.v ); + b3Vec3 t3 = b3MulSub( t2, q2.s, q1.v ); + b3Quat q = { t3, q1.s * q2.s + b3Dot( q1.v, q2.v ) }; + return q; +} + +B3_INLINE b3Quat b3Conjugate( b3Quat q ) +{ + return B3_LITERAL( b3Quat ){ { -q.v.x, -q.v.y, -q.v.z }, q.s }; +} + +B3_INLINE b3Quat b3NegateQuat( b3Quat q ) +{ + return B3_LITERAL( b3Quat ){ { -q.v.x, -q.v.y, -q.v.z }, -q.s }; +} + +B3_INLINE b3Quat b3NormalizeQuat( b3Quat q ) +{ + float lengthSq = b3DotQuat( q, q ); + if ( lengthSq > 1000.0f * FLT_MIN ) + { + float s = 1.0f / sqrtf( lengthSq ); + b3Quat qn = { { s * q.v.x, s * q.v.y, s * q.v.z }, s * q.s }; + return qn; + } + + return b3Quat_identity; +} + +B3_INLINE b3Quat b3MakeQuatFromAxisAngle( b3Vec3 axis, float radians ) +{ + B3_ASSERT( b3IsNormalized( axis ) ); + b3CosSin cs = b3ComputeCosSin( 0.5f * radians ); + b3Quat q = { { cs.sine * axis.x, cs.sine * axis.y, cs.sine * axis.z }, cs.cosine }; + return q; +} + +B3_INLINE b3Vec3 b3GetAxisAngle( float* radians, b3Quat q ) +{ + float length = sqrtf( q.v.x * q.v.x + q.v.y * q.v.y + q.v.z * q.v.z ); + *radians = 2.0f * b3Atan2( length, q.s ); + if ( length > 0.0f ) + { + float invLength = 1.0f / length; + b3Vec3 axis = { invLength * q.v.x, invLength * q.v.y, invLength * q.v.z }; + return axis; + } + + return b3Vec3_zero; +} + +/// Get the angle for a quaternion in radians +B3_INLINE float b3GetQuatAngle( b3Quat q ) +{ + float length = sqrtf( q.v.x * q.v.x + q.v.y * q.v.y + q.v.z * q.v.z ); + return 2.0f * b3Atan2( length, q.s ); +} + +// Twist angle around the z-axis, used for twist limit and revolute angle limit +B3_INLINE float b3GetTwistAngle( b3Quat q ) +{ + // Account for polarity to keep the twist angle in range. + // This is simpler than asking the user to check polarity or unwinding. + float twist = q.s < 0.0f ? b3Atan2( -q.v.z, -q.s ) : b3Atan2( q.v.z, q.s ); + twist *= 2.0f; + B3_ASSERT( -B3_PI <= twist && twist <= B3_PI ); + return twist; +} + +// Swing angle used for cone limit +B3_INLINE float b3GetSwingAngle( b3Quat q ) +{ + // Polarity should not matter because all terms are squared. + float x = sqrtf( q.v.z * q.v.z + q.s * q.s ); + float y = sqrtf( q.v.x * q.v.x + q.v.y * q.v.y ); + float swing = 2.0f * b3Atan2( y, x ); + B3_ASSERT( 0.0f <= swing && swing <= B3_PI ); + return swing; +} + +/// Extract a quaternion from a rotation matrix +B3_API b3Quat b3MakeQuatFromMatrix( const b3Matrix3* m ); + +/// Find a quaternion that rotations one vector to another +B3_API b3Quat b3ComputeQuatBetweenUnitVectors( b3Vec3 v1, b3Vec3 v2 ); + +/// Linearly interpolate and normalize between two quaternions +B3_INLINE b3Quat b3NLerp( b3Quat q1, b3Quat q2, float alpha ) +{ + B3_ASSERT( 0.0f <= alpha && alpha <= 1.0f ); + if ( b3DotQuat( q1, q2 ) < 0.0f ) + { + q1 = B3_LITERAL( b3Quat ){ { -q1.v.x, -q1.v.y, -q1.v.z }, -q1.s }; + } + + b3Quat q; + q.v = b3Lerp( q1.v, q2.v, alpha ); + q.s = ( 1.0f - alpha ) * q1.s + alpha * q2.s; + + return b3NormalizeQuat( q ); +} + +/// 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. This is useful if frame B is a child of frame A. +B3_INLINE b3Transform b3MulTransforms( b3Transform a, b3Transform b ) +{ + b3Transform out; + out.p = b3Add( b3RotateVector( a.q, b.p ), a.p ); + out.q = b3MulQuat( a.q, b.q ); + return out; +} + +/// Creates a transform that converts a local point in frame B to a local point in frame A. +/// This is useful for transforming points between the local spaces of two frames that are +/// in world space. +B3_FORCE_INLINE b3Transform b3InvMulTransforms( b3Transform a, b3Transform b ) +{ + b3Transform out; + out.p = b3InvRotateVector( a.q, b3Sub( b.p, a.p ) ); + out.q = b3InvMulQuat( a.q, b.q ); + return out; +} + +B3_INLINE b3Transform b3InvertTransform( b3Transform t ) +{ + b3Transform out; + out.p = b3InvRotateVector( t.q, b3Neg( t.p ) ); + out.q = b3Conjugate( t.q ); + return out; +} + +B3_INLINE b3Transform b3NormalizeTransform( b3Transform t ) +{ + b3Transform out; + out.p = t.p; + out.q = b3NormalizeQuat( t.q ); + return out; +} + +B3_INLINE b3Vec3 b3TransformPoint( b3Transform t, b3Vec3 v ) +{ + b3Vec3 rv = b3RotateVector( t.q, v ); + return b3Add( rv, t.p ); +} + +B3_INLINE b3Vec3 b3InvTransformPoint( b3Transform t, b3Vec3 v ) +{ + return b3InvRotateVector( t.q, b3Sub( v, t.p ) ); +} + +B3_INLINE b3Matrix3 b3MakeDiagonalMatrix( float a, float b, float c ) +{ + return B3_LITERAL( b3Matrix3 ){ { a, 0.0f, 0.0f }, { 0.0f, b, 0.0f }, { 0.0f, 0.0f, c } }; +} + +B3_INLINE float b3Det( b3Matrix3 m ) +{ + return b3Dot( m.cx, b3Cross( m.cy, m.cz ) ); +} + +B3_INLINE b3Vec3 b3MulMV( b3Matrix3 m, b3Vec3 a ) +{ + b3Vec3 b = { + m.cx.x * a.x + m.cy.x * a.y + m.cz.x * a.z, + m.cx.y * a.x + m.cy.y * a.y + m.cz.y * a.z, + m.cx.z * a.x + m.cy.z * a.y + m.cz.z * a.z, + }; + return b; +} + +B3_INLINE b3Matrix3 b3NegateMat3( b3Matrix3 a ) +{ + return B3_LITERAL( b3Matrix3 ){ + { -a.cx.x, -a.cx.y, -a.cx.z }, + { -a.cy.x, -a.cy.y, -a.cy.z }, + { -a.cz.x, -a.cz.y, -a.cz.z }, + }; +} + +B3_INLINE b3Matrix3 b3AddMM( b3Matrix3 a, b3Matrix3 b ) +{ + return B3_LITERAL( b3Matrix3 ){ + { a.cx.x + b.cx.x, a.cx.y + b.cx.y, a.cx.z + b.cx.z }, + { a.cy.x + b.cy.x, a.cy.y + b.cy.y, a.cy.z + b.cy.z }, + { a.cz.x + b.cz.x, a.cz.y + b.cz.y, a.cz.z + b.cz.z }, + }; +} + +B3_INLINE b3Matrix3 b3SubMM( b3Matrix3 a, b3Matrix3 b ) +{ + return B3_LITERAL( b3Matrix3 ){ + { a.cx.x - b.cx.x, a.cx.y - b.cx.y, a.cx.z - b.cx.z }, + { a.cy.x - b.cy.x, a.cy.y - b.cy.y, a.cy.z - b.cy.z }, + { a.cz.x - b.cz.x, a.cz.y - b.cz.y, a.cz.z - b.cz.z }, + }; +} + +B3_INLINE b3Matrix3 b3MulSM( float s, b3Matrix3 a ) +{ + return B3_LITERAL( b3Matrix3 ){ + { s * a.cx.x, s * a.cx.y, s * a.cx.z }, + { s * a.cy.x, s * a.cy.y, s * a.cy.z }, + { s * a.cz.x, s * a.cz.y, s * a.cz.z }, + }; +} + +B3_INLINE b3Matrix3 b3MulMM( b3Matrix3 a, b3Matrix3 b ) +{ + b3Matrix3 out; + out.cx = b3MulMV( a, b.cx ); + out.cy = b3MulMV( a, b.cy ); + out.cz = b3MulMV( a, b.cz ); + return out; +} + +B3_INLINE b3Matrix3 b3Transpose( b3Matrix3 m ) +{ + b3Matrix3 out; + out.cx = B3_LITERAL( b3Vec3 ){ m.cx.x, m.cy.x, m.cz.x }; + out.cy = B3_LITERAL( b3Vec3 ){ m.cx.y, m.cy.y, m.cz.y }; + out.cz = B3_LITERAL( b3Vec3 ){ m.cx.z, m.cy.z, m.cz.z }; + + return out; +} + +B3_INLINE b3Matrix3 b3InvertMatrix( b3Matrix3 m ) +{ + float det = b3Det( m ); + if ( b3AbsFloat( det ) > 1000.0f * FLT_MIN ) + { + float invDet = 1.0f / det; + b3Matrix3 out; + out.cx = b3MulSV( invDet, b3Cross( m.cy, m.cz ) ); + out.cy = b3MulSV( invDet, b3Cross( m.cz, m.cx ) ); + out.cz = b3MulSV( invDet, b3Cross( m.cx, m.cy ) ); + + return b3Transpose( out ); + } + + return b3Mat3_zero; +} + +B3_INLINE b3Vec3 b3Solve3( b3Matrix3 m, b3Vec3 x ) +{ + float det = b3Det( m ); + if ( b3AbsFloat( det ) > 1000.0f * FLT_MIN ) + { + float invDet = 1.0f / det; + b3Matrix3 a; + a.cx = b3Cross( m.cy, m.cz ); + a.cy = b3Cross( m.cz, m.cx ); + a.cz = b3Cross( m.cx, m.cy ); + + b3Vec3 b = { + invDet * b3Dot( a.cx, x ), + invDet * b3Dot( a.cy, x ), + invDet * b3Dot( a.cz, x ), + }; + + return b; + } + + return b3Vec3_zero; +} + +B3_INLINE b3Matrix3 b3InvertT( b3Matrix3 m ) +{ + float det = b3Det( m ); + if ( b3AbsFloat( det ) > 1000.0f * FLT_MIN ) + { + float invDet = 1.0f / det; + b3Matrix3 out; + out.cx = b3MulSV( invDet, b3Cross( m.cy, m.cz ) ); + out.cy = b3MulSV( invDet, b3Cross( m.cz, m.cx ) ); + out.cz = b3MulSV( invDet, b3Cross( m.cx, m.cy ) ); + return out; + } + + return b3Mat3_zero; +} + +B3_INLINE b3Matrix3 b3InvertSymmetric( b3Matrix3 m ) +{ + float det = b3Det( m ); + if ( b3AbsFloat( det ) > 1000.0f * FLT_MIN ) + { + float invDet = 1.0f / det; + b3Matrix3 out; + out.cx = b3MulSV( invDet, b3Cross( m.cy, m.cz ) ); + out.cy = b3MulSV( invDet, b3Cross( m.cz, m.cx ) ); + out.cz = b3MulSV( invDet, b3Cross( m.cx, m.cy ) ); + return out; + } + + return b3Mat3_zero; +} + +B3_INLINE b3Matrix3 b3Skew( b3Vec3 v ) +{ + b3Matrix3 out; + out.cx = B3_LITERAL( b3Vec3 ){ 0, v.z, -v.y }; + out.cy = B3_LITERAL( b3Vec3 ){ -v.z, 0, v.x }; + out.cz = B3_LITERAL( b3Vec3 ){ v.y, -v.x, 0 }; + + return out; +} + +B3_INLINE b3Matrix3 b3AbsMatrix3( b3Matrix3 m ) +{ + b3Matrix3 out; + out.cx = b3Abs( m.cx ); + out.cy = b3Abs( m.cy ); + out.cz = b3Abs( m.cz ); + + return out; +} + +B3_INLINE float b3Trace( b3Matrix3 m ) +{ + return m.cx.x + m.cy.y + m.cz.z; +} + +B3_INLINE b3Matrix3 b3ScaleMatrix( float s, b3Matrix3 m ) +{ + return B3_LITERAL( b3Matrix3 ){ + b3MulSV( s, m.cx ), + b3MulSV( s, m.cy ), + b3MulSV( s, m.cz ), + }; +} + +// This force inline improves the performance of b3ShapeDistance +B3_FORCE_INLINE b3Matrix3 b3MakeMatrixFromQuat( b3Quat q ) +{ + float xx = q.v.x * q.v.x; + float yy = q.v.y * q.v.y; + float zz = q.v.z * q.v.z; + float xy = q.v.x * q.v.y; + float xz = q.v.x * q.v.z; + float xw = q.v.x * q.s; + float yz = q.v.y * q.v.z; + float yw = q.v.y * q.s; + float zw = q.v.z * q.s; + + return B3_LITERAL( b3Matrix3 ){ + { 1.0f - 2.0f * ( yy + zz ), 2.0f * ( xy + zw ), 2.0f * ( xz - yw ) }, + { 2.0f * ( xy - zw ), 1.0f - 2.0f * ( xx + zz ), 2.0f * ( yz + xw ) }, + { 2.0f * ( xz + yw ), 2.0f * ( yz - xw ), 1.0f - 2.0f * ( xx + yy ) }, + }; +} + +// https://en.wikipedia.org/wiki/Parallel_axis_theorem +B3_API b3Matrix3 b3Steiner( float mass, b3Vec3 origin ); + +B3_INLINE b3Plane b3MakePlaneFromNormalAndPoint( b3Vec3 normal, b3Vec3 point ) +{ + return B3_LITERAL( b3Plane ){ normal, b3Dot( normal, point ) }; +} + +B3_INLINE b3Plane b3MakePlaneFromPoints( b3Vec3 point1, b3Vec3 point2, b3Vec3 point3 ) +{ + b3Plane plane; + plane.normal = b3Cross( b3Sub( point2, point1 ), b3Sub( point3, point1 ) ); + plane.normal = b3Normalize( plane.normal ); + plane.offset = b3Dot( plane.normal, point1 ); + return plane; +} + +B3_INLINE b3Plane b3NegatePlane( b3Plane plane ) +{ + return B3_LITERAL( b3Plane ){ { -plane.normal.x, -plane.normal.y, -plane.normal.z }, -plane.offset }; +} + +// normal2 = q * normal1 +// offset2 = dot(normal2, p) + offset1 +B3_INLINE b3Plane b3TransformPlane( b3Transform transform, b3Plane plane ) +{ + b3Vec3 normal = b3RotateVector( transform.q, plane.normal ); + return B3_LITERAL( b3Plane ){ normal, plane.offset + b3Dot( normal, transform.p ) }; +} + +// offset1 = offset2 - dot(normal2, p) +// normal1 = qc * normal2 +B3_INLINE b3Plane b3InvTransformPlane( b3Transform transform, b3Plane plane ) +{ + float offset = plane.offset - b3Dot( plane.normal, transform.p ); + b3Vec3 normal = b3InvRotateVector( transform.q, plane.normal ); + return B3_LITERAL( b3Plane ){ normal, offset }; +} + +/// Signed separation of a point from a plane +B3_INLINE float b3PlaneSeparation( b3Plane plane, b3Vec3 point ) +{ + return b3Dot( plane.normal, point ) - plane.offset; +} + +B3_INLINE b3Plane b3ScalePlane( float scale, b3Plane plane ) +{ + return B3_LITERAL( b3Plane ){ plane.normal, scale * plane.offset }; +} + +B3_INLINE b3AABB b3MakeAABB( const b3Vec3* points, int count, float radius ) +{ + B3_ASSERT( count > 0 ); + b3AABB a = { points[0], points[0] }; + for ( int i = 1; i < count; ++i ) + { + a.lowerBound = b3Min( a.lowerBound, points[i] ); + a.upperBound = b3Max( a.upperBound, points[i] ); + } + + b3Vec3 r = { radius, radius, radius }; + a.lowerBound = b3Sub( a.lowerBound, r ); + a.upperBound = b3Add( a.upperBound, r ); + + return a; +} + +B3_INLINE b3AABB b3AABB_AddPoint( b3AABB a, b3Vec3 point ) +{ + return B3_LITERAL( b3AABB ){ b3Min( a.lowerBound, point ), b3Max( a.upperBound, point ) }; +} + +B3_INLINE bool b3AABB_ContainsPoint( b3AABB a, b3Vec3 point ) +{ + if ( a.lowerBound.x > point.x || point.x > a.upperBound.x ) + return false; + if ( a.lowerBound.y > point.y || point.y > a.upperBound.y ) + return false; + if ( a.lowerBound.z > point.z || point.z > a.upperBound.z ) + return false; + + return true; +} + +B3_INLINE bool b3AABB_Contains( b3AABB a, b3AABB b ) +{ + if ( a.lowerBound.x > b.lowerBound.x || b.upperBound.x > a.upperBound.x ) + return false; + if ( a.lowerBound.y > b.lowerBound.y || b.upperBound.y > a.upperBound.y ) + return false; + if ( a.lowerBound.z > b.lowerBound.z || b.upperBound.z > a.upperBound.z ) + return false; + + return true; +} + +B3_INLINE float b3AABB_Area( b3AABB bounds ) +{ + b3Vec3 delta = b3Sub( bounds.upperBound, bounds.lowerBound ); + return 2.0f * ( delta.x * delta.y + delta.y * delta.z + delta.z * delta.x ); +} + +B3_INLINE b3Vec3 b3AABB_Center( b3AABB bounds ) +{ + return b3MulSV( 0.5f, b3Add( bounds.upperBound, bounds.lowerBound ) ); +} + +B3_INLINE b3Vec3 b3AABB_Extents( b3AABB bounds ) +{ + return b3MulSV( 0.5f, b3Sub( bounds.upperBound, bounds.lowerBound ) ); +} + +B3_INLINE b3AABB b3AABB_Union( b3AABB bounds1, b3AABB bounds2 ) +{ + b3AABB out; + out.lowerBound = b3Min( bounds1.lowerBound, bounds2.lowerBound ); + out.upperBound = b3Max( bounds1.upperBound, bounds2.upperBound ); + return out; +} + +B3_INLINE b3AABB b3AABB_Inflate( b3AABB bounds, float extension ) +{ + b3Vec3 radius = { extension, extension, extension }; + + b3AABB out; + out.lowerBound = b3Sub( bounds.lowerBound, radius ); + out.upperBound = b3Add( bounds.upperBound, radius ); + return out; +} + +B3_INLINE bool b3AABB_Overlaps( b3AABB a, b3AABB b ) +{ + // No intersection if separated along one axis + if ( a.upperBound.x < b.lowerBound.x || a.lowerBound.x > b.upperBound.x ) + return false; + if ( a.upperBound.y < b.lowerBound.y || a.lowerBound.y > b.upperBound.y ) + return false; + if ( a.upperBound.z < b.lowerBound.z || a.lowerBound.z > b.upperBound.z ) + return false; + + // Overlapping on all axis means bounds are intersecting + return true; +} + +B3_INLINE b3AABB b3AABB_Transform( b3Transform transform, b3AABB a ) +{ + b3Vec3 center = b3TransformPoint( transform, b3AABB_Center( a ) ); + b3Matrix3 m = b3MakeMatrixFromQuat( transform.q ); + b3Vec3 extent = b3MulMV( b3AbsMatrix3( m ), b3AABB_Extents( a ) ); + b3AABB out = { b3Sub( center, extent ), b3Add( center, extent ) }; + return out; +} + +B3_INLINE b3Vec3 b3ClosestPointToAABB( b3Vec3 point, b3AABB a ) +{ + return b3Clamp( point, a.lowerBound, a.upperBound ); +} + +/// Is this a valid number? Not NaN or infinity. +B3_API bool b3IsValidFloat( float a ); + +/// Is this a valid vector? Not NaN or infinity. +B3_API bool b3IsValidVec3( b3Vec3 a ); + +/// Is this a valid quaternion? Not NaN or infinity. Is normalized. +B3_API bool b3IsValidQuat( b3Quat q ); + +/// Is this a valid transform? Not NaN or infinity. Is normalized. +B3_API bool b3IsValidTransform( b3Transform a ); + +/// Is this a valid matrix? Not NaN or infinity. +B3_API bool b3IsValidMatrix3( b3Matrix3 a ); + +/// Is this a valid bounding box? Not Nan or infinity. Upper bound greater than or equal to lower bound. +B3_API bool b3IsValidAABB( b3AABB a ); + +/// Is this AABB valid and not huge or very far from the origin? +B3_API bool b3IsSaneAABB( b3AABB a ); + +/// Is this a valid plane? Normal is a unit vector. Not Nan or infinity. +B3_API bool b3IsValidPlane( b3Plane a ); + +/**@}*/ + +/** + * @defgroup math_cpp C++ Math + * @brief Math operator overloads for C++ + * Some of the simpler ones are expanded to improve debug performance. + * See math_functions.h for details. + * @{ + */ + +#ifdef __cplusplus + +B3_FORCE_INLINE b3Vec3& operator+=( b3Vec3& a, b3Vec3 b ) +{ + a.x += b.x; + a.y += b.y; + a.z += b.z; + return a; +} + +B3_FORCE_INLINE b3Vec3& operator-=( b3Vec3& a, b3Vec3 b ) +{ + a.x -= b.x; + a.y -= b.y; + a.z -= b.z; + return a; +} + +B3_FORCE_INLINE b3Vec3& operator*=( b3Vec3& a, float s ) +{ + a.x *= s; + a.y *= s; + a.z *= s; + return a; +} + +B3_FORCE_INLINE b3Vec3 operator-( b3Vec3 a ) +{ + return { -a.x, -a.y, -a.z }; +} + +B3_FORCE_INLINE b3Vec3 operator*( float s, b3Vec3 a ) +{ + return { s * a.x, s * a.y, s * a.z }; +} + +B3_FORCE_INLINE b3Vec3 operator*( b3Vec3 a, float s ) +{ + return { s * a.x, s * a.y, s * a.z }; +} + +B3_FORCE_INLINE b3Vec3 operator*( b3Vec3 a, b3Vec3 b ) +{ + return { a.x * b.x, a.y * b.y, a.z * b.z }; +} + +B3_FORCE_INLINE b3Vec3 operator+( b3Vec3 a, b3Vec3 b ) +{ + return { a.x + b.x, a.y + b.y, a.z + b.z }; +} + +B3_FORCE_INLINE b3Vec3 operator-( b3Vec3 a, b3Vec3 b ) +{ + return { a.x - b.x, a.y - b.y, a.z - b.z }; +} + +B3_INLINE b3Vec3 operator*( b3Matrix3 m, b3Vec3 v ) +{ + return b3MulMV( m, v ); +} + +B3_INLINE b3Matrix3& operator+=( b3Matrix3& a, b3Matrix3 b ) +{ + a = b3AddMM( a, b ); + return a; +} + +B3_INLINE b3Matrix3 operator*( b3Matrix3 a, b3Matrix3 b ) +{ + return b3MulMM( a, b ); +} + +B3_INLINE b3Matrix3 operator+( b3Matrix3 a, b3Matrix3 b ) +{ + return b3AddMM( a, b ); +} + +B3_INLINE b3Matrix3 operator-( b3Matrix3 a, b3Matrix3 b ) +{ + return b3SubMM( a, b ); +} + +B3_INLINE b3Matrix3 operator*( float s, b3Matrix3 a ) +{ + return b3MulSM( s, a ); +} + +B3_INLINE b3Quat operator+( b3Quat q1, b3Quat q2 ) +{ + return { q1.v + q2.v, q1.s + q2.s }; +} + +B3_INLINE b3Quat operator-( b3Quat q1, b3Quat q2 ) +{ + return { q1.v - q2.v, q1.s - q2.s }; +} + +B3_INLINE b3Quat operator*( float f, b3Quat q ) +{ + return { f * q.v, f * q.s }; +} + +B3_INLINE b3Quat operator*( b3Quat q, float f ) +{ + return { q.v * f, q.s * f }; +} + +#endif + +/**@}*/ diff --git a/include/box3d/types.h b/include/box3d/types.h new file mode 100644 index 0000000..58bc7fb --- /dev/null +++ b/include/box3d/types.h @@ -0,0 +1,1523 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "base.h" +#include "collision.h" +#include "constants.h" +#include "id.h" +#include "math_functions.h" + +#include + +#define B3_DEFAULT_CATEGORY_BITS 1 +#define B3_DEFAULT_MASK_BITS UINT64_MAX + +/// Task interface +/// This is the prototype for a Box3D task. Your task system is expected to run this callback on a worker thread, +/// exactly once per enqueue, passing back the same taskContext pointer supplied to b3EnqueueTaskCallback. +/// @ingroup world +typedef void b3TaskCallback( void* taskContext ); + +/// These functions can be provided to Box3D to invoke a task system. +/// Returns a pointer to the user's task object. May be nullptr. A nullptr indicates to Box3D that the work was executed +/// serially within the callback and there is no need to call b3FinishTaskCallback. Otherwise the returned +/// value must be non-null will be passed to b3FinishTaskCallback as the userTask. +/// @param task the Box3D task to be called by the scheduler +/// @param taskContext the Box3D context object that the scheduler must pass to the task +/// @param userContext the scheduler context object that is opaque to Box3D +/// @param taskName the Box3D task name that the scheduler can use for diagnostics +/// @ingroup world +typedef void* b3EnqueueTaskCallback( b3TaskCallback* task, void* taskContext, void* userContext, const char* taskName ); + +/// Finishes a user task object that wraps a Box3D task. +/// @ingroup world +typedef void b3FinishTaskCallback( void* userTask, void* userContext ); + +// The user needs to be able to create debug draw shapes for multi-pass rendering to work efficiently. +// These user shapes are created and destroyed via callback so they can be bound to shape lifetime and scaling updates. +typedef struct b3DebugShape b3DebugShape; +typedef void* b3CreateDebugShapeCallback( const b3DebugShape* debugShape, void* userContext ); +typedef void b3DestroyDebugShapeCallback( void* userShape, 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 Box3D state or user application state. +typedef float b3FrictionCallback( 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 Box3D state or user application state. +typedef float b3RestitutionCallback( float restitutionA, uint64_t userMaterialIdA, float restitutionB, uint64_t userMaterialIdB ); + +/// Result from b3World_RayCastClosest +/// @ingroup world +typedef struct b3RayResult +{ + b3ShapeId shapeId; + b3Vec3 point; + b3Vec3 normal; + uint64_t userMaterialId; + float fraction; + int triangleIndex; + int childIndex; + int nodeVisits; + int leafVisits; + bool hit; +} b3RayResult; + +/// Optional world capacities that can be use to avoid run-time allocations +typedef struct b3Capacity +{ + int staticShapeCount; + int dynamicShapeCount; + int staticBodyCount; + int dynamicBodyCount; + int contactCount; +} b3Capacity; + +/// World definition used to create a simulation world. Must be initialized using b3DefaultWorldDef. +typedef struct b3WorldDef +{ + /// Gravity vector. Box3D has no up-vector defined. + b3Vec3 gravity; + + /// Restitution speed threshold, usually in m/s. Collisions above this + /// speed have restitution applied (will bounce). + float restitutionThreshold; + + /// Hit event speed threshold, usually in m/s. Collisions above this + /// speed can generate hit events if the shape also enables hit events. + 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). + b3FrictionCallback* frictionCallback; + + /// Optional mixing callback for restitution. The default uses max(restitutionA, restitutionB). + b3RestitutionCallback* restitutionCallback; + + /// Can bodies go to sleep to improve performance + bool enableSleep; + + /// Enable continuous collision + bool enableContinuous; + + /// Number of workers to use with the provided task system. Box3D performs best when using only + /// performance cores and accessing a single L2 cache. Efficiency cores and hyper-threading provide + /// little benefit and may even harm performance. + /// @note Box3D does not create threads. This is the number of threads your applications has created + /// that you are allocating to b3World_Step. + /// @warning Do not modify the default value unless you are also providing a task system and providing + /// task callbacks (enqueueTask and finishTask). + uint32_t workerCount; + + /// function to spawn task + b3EnqueueTaskCallback* enqueueTask; + + /// function to finish a task + b3FinishTaskCallback* finishTask; + + /// User context that is provided to enqueueTask and finishTask + void* userTaskContext; + + /// User data associated with a world + void* userData; + + /// Used to create debug draw shapes. This is called when a shape is + /// first drawn using b3DebugDraw. + b3CreateDebugShapeCallback* createDebugShape; + + /// Used to destroy debug draw shapes. This is called when a shape is modified or destroyed. + b3DestroyDebugShapeCallback* destroyDebugShape; + + /// This is passed to the debug shape callbacks to provide a user context. + void* userDebugShapeContext; + + /// Optional initial capacities + b3Capacity capacity; + + /// Used internally to detect a valid definition. DO NOT SET. + int internalValue; +} b3WorldDef; + +/// Use this to initialize your world definition +/// @ingroup world +B3_API b3WorldDef b3DefaultWorldDef( 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 b3BodyType +{ + /// zero mass, zero velocity, may be manually moved + b3_staticBody = 0, + + /// zero mass, velocity set by user, moved by solver + b3_kinematicBody = 1, + + /// positive mass, velocity determined by forces, moved by solver + b3_dynamicBody = 2, + + /// number of body types + b3_bodyTypeCount, +} b3BodyType; + +/// Motion locks to restrict the body movement +typedef struct b3MotionLocks +{ + /// Prevent translation along the x-axis + bool linearX; + + /// Prevent translation along the y-axis + bool linearY; + + /// Prevent translation along the z-axis + bool linearZ; + + /// Prevent rotation around the x-axis + bool angularX; + + /// Prevent rotation around the y-axis + bool angularY; + + /// Prevent rotation around the z-axis + bool angularZ; +} b3MotionLocks; + +/// 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 b3DefaultBodyDef(). +/// @ingroup body +typedef struct b3BodyDef +{ + /// The body type: static, kinematic, or dynamic. + b3BodyType 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. + b3Vec3 position; + + /// The initial world rotation of the body. + b3Quat rotation; + + /// The initial linear velocity of the body's origin. Usually in meters per second. + b3Vec3 linearVelocity; + + /// The initial angular velocity of the body. Radians per second. + b3Vec3 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 + b3MotionLocks 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 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. + 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; + + /// Enable continuous collision. This is true by default and should only be disabled for application reasons, such + /// as wheels on a vehicle. + /// todo not hooked up yet + bool enableContinuousCollision; + + /// Used internally to detect a valid definition. DO NOT SET. + int internalValue; +} b3BodyDef; + +/// Use this to initialize your body definition +/// @ingroup body +B3_API b3BodyDef b3DefaultBodyDef( void ); + +/// This is used to filter collision on shapes. It affects shape-vs-shape collision +/// and shape-versus-query collision (such as b3World_CastRay). +/// @ingroup shape +typedef struct b3Filter +{ + /// 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; +} b3Filter; + +/// Use this to initialize your filter +/// @ingroup shape +B3_API b3Filter b3DefaultFilter( 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 b3QueryFilter +{ + /// 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; +} b3QueryFilter; + +/// Use this to initialize your query filter +/// @ingroup shape +B3_API b3QueryFilter b3DefaultQueryFilter( void ); + +/// Shape type +/// @ingroup shape +typedef enum b3ShapeType +{ + /// A capsule is an extruded sphere + b3_capsuleShape, + + /// A compound shape composed of up to 64K spheres, capsules, hulls, and meshes + b3_compoundShape, + + /// A height field useful for terrain + b3_heightShape, + + /// A convex hull + b3_hullShape, + + /// A triangle soup + b3_meshShape, + + /// A sphere with an offset + b3_sphereShape, + + /// The number of shape types + b3_shapeTypeCount +} b3ShapeType; + +/// Used to create a shape +typedef struct b3ShapeDef +{ + /// Optional body name for debugging. Up to 31 characters (excluding null termination) + const char* name; + + /// Use this to store application specific shape data. + void* userData; + + /// Surface material used on mesh shapes per triangle. Ignored for convex shapes. Ignored for compound shapes. + b3SurfaceMaterial* materials; + + /// Surface material count. + int materialCount; + + /// The base surface material. Ignored for compound shapes. + b3SurfaceMaterial baseMaterial; + + /// The density, usually in kg/m^2. + float density; + + /// Explosion scale for b3World_Explode. non-dimensional + float explosionScale; + + /// Contact filtering data. + b3Filter 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. + bool updateBodyMass; + + /// Used internally to detect a valid definition. DO NOT SET. + int internalValue; + +} b3ShapeDef; + +/// Use this to initialize your shape definition +/// @ingroup shape +B3_API b3ShapeDef b3DefaultShapeDef( void ); + +//! @cond +/// Profiling data. Times are in milliseconds. +typedef struct b3Profile +{ + float step; + float pairs; + float collide; + float solve; + float solverSetup; + float constraints; + 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; +} b3Profile; + +/// Counters that give details of the simulation size. +typedef struct b3Counters +{ + int bodyCount; + int shapeCount; + int contactCount; + int jointCount; + int islandCount; + int stackUsed; + int staticTreeHeight; + int treeHeight; + int satCallCount; + int satCacheHitCount; + int byteCount; + int taskCount; + int colorCounts[24]; + int manifoldCounts[B3_CONTACT_MANIFOLD_COUNT_BUCKETS]; + + // Number of contacts touched by the collide pass (graph contacts + awake-set non-touching). + int awakeContactCount; + + // Number of contacts recycled in the most recent step. + int recycledContactCount; +} b3Counters; +//! @endcond + +/// Joint type enumeration +/// +/// This is useful because all joint types use b3JointId and sometimes you +/// want to get the type of a joint. +/// @ingroup joint +typedef enum b3JointType +{ + b3_parallelJoint, + b3_distanceJoint, + b3_filterJoint, + b3_motorJoint, + b3_prismaticJoint, + b3_revoluteJoint, + b3_sphericalJoint, + b3_weldJoint, + b3_wheelJoint, +} b3JointType; + +/// 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 b3JointDef +{ + /// User data pointer + void* userData; + + /// The first attached body + b3BodyId bodyIdA; + + /// The second attached body + b3BodyId bodyIdB; + + /// The first local joint frame + b3Transform localFrameA; + + /// The second local joint frame + b3Transform 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; + + /// Used internally to detect a valid definition. DO NOT SET. + int internalValue; +} b3JointDef; + +/// 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 b3DistanceJointDef +{ + /// Base joint definition + b3JointDef 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. Clamped to a stable minimum value. + float minLength; + + /// Maximum length. 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; +} b3DistanceJointDef; + +/// Use this to initialize your joint definition +/// @ingroup distance_joint +B3_API b3DistanceJointDef b3DefaultDistanceJointDef( void ); + +/// A motor joint is used to control the relative position and velocity between two bodies. +/// @ingroup motor_joint +typedef struct b3MotorJointDef +{ + /// Base joint definition + b3JointDef base; + + /// The desired linear velocity + b3Vec3 linearVelocity; + + /// The maximum motor force in newtons + float maxVelocityForce; + + /// The desired angular velocity + b3Vec3 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; +} b3MotorJointDef; + +/// Use this to initialize your joint definition +/// @ingroup motor_joint +B3_API b3MotorJointDef b3DefaultMotorJointDef( void ); + +/// A filter joint is used to disable collision between two specific bodies. +/// +/// @ingroup filter_joint +typedef struct b3FilterJointDef +{ + /// Base joint definition + b3JointDef base; +} b3FilterJointDef; + +/// Use this to initialize your joint definition +/// @ingroup filter_joint +B3_API b3FilterJointDef b3DefaultFilterJointDef( void ); + +/// Parallel joint definition +/// Constrains the angle between axis z in body A and axis z in body B +/// using a spring. +/// Useful to keep a body upright. +/// @ingroup cone_joint +typedef struct b3ParallelJointDef +{ + /// Base joint definition + b3JointDef base; + + float hertz; + float dampingRatio; + float maxTorque; + +} b3ParallelJointDef; + +/// Use this to initialize your joint definition +/// @ingroup parallel_joint +B3_API b3ParallelJointDef b3DefaultParallelJointDef( 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 b3PrismaticJointDef +{ + /// Base joint definition + b3JointDef 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; +} b3PrismaticJointDef; + +/// Use this to initialize your joint definition +/// @ingroupd prismatic_joint +B3_API b3PrismaticJointDef b3DefaultPrismaticJointDef( void ); + +/// Revolute joint definition +/// A point on body B is fixed to a point on body A. Allows relative rotation about the z-axis. +/// @ingroup revolute_joint +typedef struct b3RevoluteJointDef +{ + /// Base joint definition + b3JointDef base; + + /// The bodyB angle minus bodyA angle in the reference state (radians). + /// This defines the zero angle for the joint limit. + 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 + float lowerAngle; + + /// The upper angle for the joint limit in 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; +} b3RevoluteJointDef; + +/// Use this to initialize your joint definition. +/// @ingroup revolute_joint +B3_API b3RevoluteJointDef b3DefaultRevoluteJointDef( void ); + +/// Spherical joint definition +/// A point on body B is fixed to a point on body A. Allows rotation about the shared point. +/// @ingroup spherical_joint +typedef struct b3SphericalJointDef +{ + /// Base joint definition + b3JointDef base; + + /// Enable a rotational spring that attempts to align the two joint frames. + bool enableSpring; + + /// The spring stiffness Hertz, cycles per second. This may be clamped internally + /// according to the time step to maintain stability. Non-negative number. + float hertz; + + /// The spring damping ratio, non-dimensional. Non-negative number. + float dampingRatio; + + /// Target spring rotation, joint frame B relative to joint frame A. + b3Quat targetRotation; + + /// A flag to enable the cone limit. The cone is centered on the frameA z-axis. + bool enableConeLimit; + + /// The angle for the cone limit in radians. Valid range is [0, pi] + float coneAngle; + + /// A flag to enable the twist limit. The twist is centered on the frameB z-axis. + bool enableTwistLimit; + + /// The angle for the lower twist limit in radians. Valid range is [-pi, pi]. + float lowerTwistAngle; + + /// The angle for the upper twist limit in radians. Valid range is [-pi, pi]. + float upperTwistAngle; + + /// A flag to enable the joint motor + bool enableMotor; + + /// The maximum motor torque, typically in newton-meters. Non-negative number. + float maxMotorTorque; + + /// The desired motor angular velocity in radians per second. + b3Vec3 motorVelocity; +} b3SphericalJointDef; + +/// Use this to initialize your joint definition. +/// @ingroup spherical_joint +B3_API b3SphericalJointDef b3DefaultSphericalJointDef( void ); + +/// Weld joint definition +/// Connects two bodies together rigidly. This constraint provides springs to mimic +/// soft-body simulation. +/// @note The approximate solver in Box3D cannot hold many bodies together rigidly +/// @ingroup weld_joint +typedef struct b3WeldJointDef +{ + /// Base joint definition + b3JointDef 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; +} b3WeldJointDef; + +/// Use this to initialize your joint definition +/// @ingroup weld_joint +B3_API b3WeldJointDef b3DefaultWeldJointDef( void ); + +/// Wheel joint definition +/// Body A is the chassis and body B is the wheel. +/// The wheel rotates around the local z-axis in frame B. +/// The wheel translations along the local x-axis in frame A. +/// The wheel can optionally steer along the x-axis in frame A. +/// @ingroup wheel_joint +typedef struct b3WheelJointDef +{ + /// Base joint definition + b3JointDef base; + + /// Enable a linear spring along the local axis + bool enableSuspensionSpring; + + /// Spring stiffness in Hertz + float suspensionHertz; + + /// Spring damping ratio, non-dimensional + float suspensionDampingRatio; + + /// Enable/disable the joint linear limit + bool enableSuspensionLimit; + + /// The lower suspension translation limit + float lowerSuspensionLimit; + + /// The upper translation limit + float upperSuspensionLimit; + + /// Enable/disable the joint rotational motor + bool enableSpinMotor; + + /// The maximum motor torque, typically in newton-meters + float maxSpinTorque; + + /// The desired motor speed in radians per second + float spinSpeed; + + /// Enable steering, otherwise the steering is fixed forward + bool enableSteering; + + /// Steering stiffness in Hertz + float steeringHertz; + + /// Spring damping ratio, non-dimensional + float steeringDampingRatio; + + /// The target steering angle in radians + float targetSteeringAngle; + + /// The maximum steering torque in N*m + float maxSteeringTorque; + + /// Enable/disable the steering angular limit + bool enableSteeringLimit; + + /// The lower steering angle in radians + float lowerSteeringLimit; + + /// The upper steering angle in radians + float upperSteeringLimit; +} b3WheelJointDef; + +/// Use this to initialize your joint definition +/// @ingroup wheel_joint +B3_API b3WheelJointDef b3DefaultWheelJointDef( void ); + +/// The explosion definition is used to configure options for explosions. Explosions +/// consider shape geometry when computing the impulse. +/// @ingroup world +typedef struct b3ExplosionDef +{ + /// Mask bits to filter shapes + uint64_t maskBits; + + /// The center of the explosion in world space + b3Vec3 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 area. This applies an impulse according to the shape area that + /// is facing the explosion. Explosions only apply to spheres, capsules, and hulls. This + /// may be negative for implosions. + float impulsePerArea; +} b3ExplosionDef; + +/// Use this to initialize your explosion definition +/// @ingroup world +B3_API b3ExplosionDef b3DefaultExplosionDef( 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 Box3D 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 b3SensorBeginTouchEvent +{ + /// The id of the sensor shape + b3ShapeId sensorShapeId; + + /// The id of the shape that began touching the sensor shape + b3ShapeId visitorShapeId; +} b3SensorBeginTouchEvent; + +/// 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 b3Shape_IsValid. +typedef struct b3SensorEndTouchEvent +{ + /// The id of the sensor shape + /// @warning this shape may have been destroyed + /// @see b2Shape_IsValid + b3ShapeId sensorShapeId; + + /// The id of the shape that stopped touching the sensor shape + /// @warning this shape may have been destroyed + /// @see b2Shape_IsValid + b3ShapeId visitorShapeId; +} b3SensorEndTouchEvent; + +/// 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 b3SensorEvents +{ + /// Array of sensor begin touch events + b3SensorBeginTouchEvent* beginEvents; + + /// Array of sensor end touch events + b3SensorEndTouchEvent* endEvents; + + /// The number of begin touch events + int beginCount; + + /// The number of end touch events + int endCount; +} b3SensorEvents; + +/// A begin-touch event is generated when two shapes begin touching. +typedef struct b3ContactBeginTouchEvent +{ + /// Id of the first shape + b3ShapeId shapeIdA; + + /// Id of the second shape + b3ShapeId shapeIdB; + + /// The transient contact id. This contact maybe destroyed automatically when the world is modified or simulated. + /// Used b3Contact_IsValid before using this id. + b3ContactId contactId; +} b3ContactBeginTouchEvent; + +/// 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 b3ContactEndTouchEvent +{ + /// Id of the first shape + /// @warning this shape may have been destroyed + /// @see b3Shape_IsValid + b3ShapeId shapeIdA; + + /// Id of the first shape + /// @warning this shape may have been destroyed + /// @see b3Shape_IsValid + b3ShapeId shapeIdB; + + /// Id of the contact. + /// @warning this contact may have been destroyed + /// @see b3Contact_IsValid + b3ContactId contactId; +} b3ContactEndTouchEvent; + +/// 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 b3ContactHitEvent +{ + /// Id of the first shape + b3ShapeId shapeIdA; + + /// Id of the second shape + b3ShapeId shapeIdB; + + /// Id of the contact. + /// @warning this contact may have been destroyed + /// @see b3Contact_IsValid + b3ContactId 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. + b3Vec3 point; + + /// Normal vector pointing from shape A to shape B + b3Vec3 normal; + + /// The speed the shapes are approaching. Always positive. Typically in meters per second. + float approachSpeed; + + /// User material on shape A + uint64_t userMaterialIdA; + + /// User material on shape B + uint64_t userMaterialIdB; + +} b3ContactHitEvent; + +/// Contact events are buffered in the 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 b3ContactEvents +{ + /// Array of begin touch events + b3ContactBeginTouchEvent* beginEvents; + + /// Array of end touch events + b3ContactEndTouchEvent* endEvents; + + /// Array of hit events + b3ContactHitEvent* hitEvents; + + /// Number of begin touch events + int beginCount; + + /// Number of end touch events + int endCount; + + /// Number of hit events + int hitCount; +} b3ContactEvents; + +/// 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 b3Body_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 b3BodyMoveEvent +{ + void* userData; + b3Transform transform; + b3BodyId bodyId; + bool fellAsleep; +} b3BodyMoveEvent; + +/// Body events are buffered in the world and are available +/// as event arrays after the time step is complete. +/// Note: this date becomes invalid if bodies are destroyed +typedef struct b3BodyEvents +{ + /// Array of move events + b3BodyMoveEvent* moveEvents; + + /// Number of move events + int moveCount; +} b3BodyEvents; + +/// 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 b3JointEvent +{ + /// The joint id + b3JointId jointId; + + /// The user data from the joint for convenience + void* userData; +} b3JointEvent; + +/// 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 b3JointEvents +{ + /// Array of events + b3JointEvent* jointEvents; + + /// Number of events + int count; +} b3JointEvents; + +/// The contact data for two shapes. By convention the manifold normal points +/// from shape A to shape B. +/// @see b3Shape_GetContactData() and b3Body_GetContactData() +typedef struct b3ContactData +{ + b3ContactId contactId; + b3ShapeId shapeIdA; + b3ShapeId shapeIdB; + const struct b3Manifold* manifolds; + int manifoldCount; +} b3ContactData; + +/**@}*/ + +/// 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. @see b3ShapeDef. +/// Notes: +/// - this function must be thread-safe +/// - this is only called if one of the two shapes has enabled custom filtering +/// - this is called only for awake dynamic bodies +/// Return false if you want to disable the collision +/// @warning Do not attempt to modify the world inside this callback +/// @ingroup world +typedef bool b3CustomFilterFcn( b3ShapeId shapeIdA, b3ShapeId shapeIdB, void* context ); + +/// Prototype for a pre-solve callback. +/// This is called after a contact is updated. This allows you to inspect a +/// collision before it goes to the solver. +/// Notes: +/// - this function must be thread-safe +/// - this is only called if the shape has enabled pre-solve events +/// - this may be called for awake dynamic bodies and sensors +/// - this is not called for sensors +/// Return false if you want to disable the contact this step +/// This has limited information because it is used during CCD which does not have the +/// full contact manifold. +/// @warning Do not attempt to modify the world inside this callback +/// @ingroup world +typedef bool b3PreSolveFcn( b3ShapeId shapeIdA, b3ShapeId shapeIdB, b3Vec3 point, b3Vec3 normal, void* context ); + +/// Prototype callback for overlap queries. +/// Called for each shape found in the query. +/// @see b3World_QueryAABB +/// @return false to terminate the query. +/// @ingroup world +typedef bool b3OverlapResultFcn( b3ShapeId shapeId, void* context ); + +/// Prototype callback for ray 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 +/// @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 +/// @param fraction the fraction along the ray at the point of intersection +/// @param userMaterialId the shape or triangle surface type +/// @param triangleIndex the triangle index for mesh or height field shapes or -1 for other shape types +/// @param childIndex the child shape index for compound shapes +/// @param context the user context +/// @return -1 to filter, 0 to terminate, fraction to clip the ray for closest hit, 1 to continue +/// @see b3World_CastRay +/// @ingroup world +typedef float b3CastResultFcn( b3ShapeId shapeId, b3Vec3 point, b3Vec3 normal, float fraction, uint64_t userMaterialId, + int triangleIndex, int childIndex, void* context ); + +// Used to collect collision planes for character movers. +// Return true to continue gathering planes. +typedef bool b3PlaneResultFcn( b3ShapeId shapeId, const b3PlaneResult* plane, int planeCount, void* context ); + +// Used to filter shapes for shape casting character movers. +// Return true to accept the collision +typedef bool b3MoverFilterFcn( b3ShapeId shapeId, void* context ); + +/// Body ray cast for ray casting a specific body with a specified transform. +typedef struct b3BodyRayCastInput +{ + b3Vec3 origin; + b3Vec3 translation; + b3QueryFilter filter; + float maxFraction; +} b3BodyRayCastInput; + +/// Body shape cast for shape casting a specific body with a specified transform. +typedef struct b3BodyShapeCastInput +{ + b3ShapeProxy proxy; + b3Vec3 translation; + b3QueryFilter filter; + float maxFraction; + bool canEncroach; +} b3BodyShapeCastInput; + +/// Body cast result for ray and shape casts. +typedef struct b3BodyCastResult +{ + b3ShapeId shapeId; + b3Vec3 point; + b3Vec3 normal; + float fraction; + int triangleIndex; + uint64_t userMaterialId; + int iterations; + bool hit; +} b3BodyCastResult; + +/// Body plane result for movers. +typedef struct b3BodyPlaneResult +{ + b3ShapeId shapeId; + b3PlaneResult result; +} b3BodyPlaneResult; + +/// 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 b3HexColor +{ + b3_colorAliceBlue = 0xF0F8FF, + b3_colorAntiqueWhite = 0xFAEBD7, + b3_colorAqua = 0x00FFFF, + b3_colorAquamarine = 0x7FFFD4, + b3_colorAzure = 0xF0FFFF, + b3_colorBeige = 0xF5F5DC, + b3_colorBisque = 0xFFE4C4, + b3_colorBlack = 0x000000, + b3_colorBlanchedAlmond = 0xFFEBCD, + b3_colorBlue = 0x0000FF, + b3_colorBlueViolet = 0x8A2BE2, + b3_colorBrown = 0xA52A2A, + b3_colorBurlywood = 0xDEB887, + b3_colorCadetBlue = 0x5F9EA0, + b3_colorChartreuse = 0x7FFF00, + b3_colorChocolate = 0xD2691E, + b3_colorCoral = 0xFF7F50, + b3_colorCornflowerBlue = 0x6495ED, + b3_colorCornsilk = 0xFFF8DC, + b3_colorCrimson = 0xDC143C, + b3_colorCyan = 0x00FFFF, + b3_colorDarkBlue = 0x00008B, + b3_colorDarkCyan = 0x008B8B, + b3_colorDarkGoldenRod = 0xB8860B, + b3_colorDarkGray = 0xA9A9A9, + b3_colorDarkGreen = 0x006400, + b3_colorDarkKhaki = 0xBDB76B, + b3_colorDarkMagenta = 0x8B008B, + b3_colorDarkOliveGreen = 0x556B2F, + b3_colorDarkOrange = 0xFF8C00, + b3_colorDarkOrchid = 0x9932CC, + b3_colorDarkRed = 0x8B0000, + b3_colorDarkSalmon = 0xE9967A, + b3_colorDarkSeaGreen = 0x8FBC8F, + b3_colorDarkSlateBlue = 0x483D8B, + b3_colorDarkSlateGray = 0x2F4F4F, + b3_colorDarkTurquoise = 0x00CED1, + b3_colorDarkViolet = 0x9400D3, + b3_colorDeepPink = 0xFF1493, + b3_colorDeepSkyBlue = 0x00BFFF, + b3_colorDimGray = 0x696969, + b3_colorDodgerBlue = 0x1E90FF, + b3_colorFireBrick = 0xB22222, + b3_colorFloralWhite = 0xFFFAF0, + b3_colorForestGreen = 0x228B22, + b3_colorFuchsia = 0xFF00FF, + b3_colorGainsboro = 0xDCDCDC, + b3_colorGhostWhite = 0xF8F8FF, + b3_colorGold = 0xFFD700, + b3_colorGoldenRod = 0xDAA520, + b3_colorGray = 0x808080, + b3_colorGreen = 0x008000, + b3_colorGreenYellow = 0xADFF2F, + b3_colorHoneyDew = 0xF0FFF0, + b3_colorHotPink = 0xFF69B4, + b3_colorIndianRed = 0xCD5C5C, + b3_colorIndigo = 0x4B0082, + b3_colorIvory = 0xFFFFF0, + b3_colorKhaki = 0xF0E68C, + b3_colorLavender = 0xE6E6FA, + b3_colorLavenderBlush = 0xFFF0F5, + b3_colorLawnGreen = 0x7CFC00, + b3_colorLemonChiffon = 0xFFFACD, + b3_colorLightBlue = 0xADD8E6, + b3_colorLightCoral = 0xF08080, + b3_colorLightCyan = 0xE0FFFF, + b3_colorLightGoldenRodYellow = 0xFAFAD2, + b3_colorLightGray = 0xD3D3D3, + b3_colorLightGreen = 0x90EE90, + b3_colorLightPink = 0xFFB6C1, + b3_colorLightSalmon = 0xFFA07A, + b3_colorLightSeaGreen = 0x20B2AA, + b3_colorLightSkyBlue = 0x87CEFA, + b3_colorLightSlateGray = 0x778899, + b3_colorLightSteelBlue = 0xB0C4DE, + b3_colorLightYellow = 0xFFFFE0, + b3_colorLime = 0x00FF00, + b3_colorLimeGreen = 0x32CD32, + b3_colorLinen = 0xFAF0E6, + b3_colorMagenta = 0xFF00FF, + b3_colorMaroon = 0x800000, + b3_colorMediumAquaMarine = 0x66CDAA, + b3_colorMediumBlue = 0x0000CD, + b3_colorMediumOrchid = 0xBA55D3, + b3_colorMediumPurple = 0x9370DB, + b3_colorMediumSeaGreen = 0x3CB371, + b3_colorMediumSlateBlue = 0x7B68EE, + b3_colorMediumSpringGreen = 0x00FA9A, + b3_colorMediumTurquoise = 0x48D1CC, + b3_colorMediumVioletRed = 0xC71585, + b3_colorMidnightBlue = 0x191970, + b3_colorMintCream = 0xF5FFFA, + b3_colorMistyRose = 0xFFE4E1, + b3_colorMoccasin = 0xFFE4B5, + b3_colorNavajoWhite = 0xFFDEAD, + b3_colorNavy = 0x000080, + b3_colorOldLace = 0xFDF5E6, + b3_colorOlive = 0x808000, + b3_colorOliveDrab = 0x6B8E23, + b3_colorOrange = 0xFFA500, + b3_colorOrangeRed = 0xFF4500, + b3_colorOrchid = 0xDA70D6, + b3_colorPaleGoldenRod = 0xEEE8AA, + b3_colorPaleGreen = 0x98FB98, + b3_colorPaleTurquoise = 0xAFEEEE, + b3_colorPaleVioletRed = 0xDB7093, + b3_colorPapayaWhip = 0xFFEFD5, + b3_colorPeachPuff = 0xFFDAB9, + b3_colorPeru = 0xCD853F, + b3_colorPink = 0xFFC0CB, + b3_colorPlum = 0xDDA0DD, + b3_colorPowderBlue = 0xB0E0E6, + b3_colorPurple = 0x800080, + b3_colorRebeccaPurple = 0x663399, + b3_colorRed = 0xFF0000, + b3_colorRosyBrown = 0xBC8F8F, + b3_colorRoyalBlue = 0x4169E1, + b3_colorSaddleBrown = 0x8B4513, + b3_colorSalmon = 0xFA8072, + b3_colorSandyBrown = 0xF4A460, + b3_colorSeaGreen = 0x2E8B57, + b3_colorSeaShell = 0xFFF5EE, + b3_colorSienna = 0xA0522D, + b3_colorSilver = 0xC0C0C0, + b3_colorSkyBlue = 0x87CEEB, + b3_colorSlateBlue = 0x6A5ACD, + b3_colorSlateGray = 0x708090, + b3_colorSnow = 0xFFFAFA, + b3_colorSpringGreen = 0x00FF7F, + b3_colorSteelBlue = 0x4682B4, + b3_colorTan = 0xD2B48C, + b3_colorTeal = 0x008080, + b3_colorThistle = 0xD8BFD8, + b3_colorTomato = 0xFF6347, + b3_colorTurquoise = 0x40E0D0, + b3_colorViolet = 0xEE82EE, + b3_colorWheat = 0xF5DEB3, + b3_colorWhite = 0xFFFFFF, + b3_colorWhiteSmoke = 0xF5F5F5, + b3_colorYellow = 0xFFFF00, + b3_colorYellowGreen = 0x9ACD32, + + b3_colorBox2DRed = 0xDC3132, + b3_colorBox2DBlue = 0x30AEBF, + b3_colorBox2DGreen = 0x8CC924, + b3_colorBox2DYellow = 0xFFEE8C +} b3HexColor; + +/// Get the visualization color assigned to a constraint graph color slot. The last index +/// (B3_GRAPH_COLOR_COUNT - 1) is the overflow color. +B3_API b3HexColor b3GetGraphColor( int index ); + +// This is sent to the user for debug shape creation. The user should know the type in case they have +// custom sphere or capsule rendering. +typedef struct b3DebugShape +{ + b3ShapeId shapeId; + b3ShapeType type; + union + { + const b3Capsule* capsule; + const b3Compound* compound; + const b3HeightField* heightField; + const b3Hull* hull; + const b3Mesh* mesh; + const b3Sphere* sphere; + }; +} b3DebugShape; + +typedef struct b3DebugDraw +{ + // Draws a shape and returns true if drawing should continue + bool ( *DrawShapeFcn )( void* userShape, b3Transform transform, b3HexColor color, void* context ); + + /// Draw a line segment. + void ( *DrawSegmentFcn )( b3Vec3 p1, b3Vec3 p2, b3HexColor color, void* context ); + + /// Draw a transform. Choose your own length scale. + void ( *DrawTransformFcn )( b3Transform transform, void* context ); + + /// Draw a point. + void ( *DrawPointFcn )( b3Vec3 p, float size, b3HexColor color, void* context ); + + /// Draw a bounding box. + void ( *DrawBoundsFcn )( b3AABB aabb, b3HexColor color, void* context ); + + /// Draw a bounding box. + void ( *DrawBoxFcn )( b3Vec3 extents, b3Transform transform, b3HexColor color, void* context ); + + /// Draw a string in world space + void ( *DrawStringFcn )( b3Vec3 p, const char* s, b3HexColor color, void* context ); + + /// World bounds to use for debug draw + b3AABB 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 drawContacts; + + /// Draw contact anchor A or B + int drawAnchorA; + + /// Option to visualize the graph coloring used for contacts and joints + bool drawGraphColors; + + /// Option to draw contact features + 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; +} b3DebugDraw; + +B3_API b3DebugDraw b3DefaultDebugDraw( void ); + +/**@}*/ diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt new file mode 100644 index 0000000..05f97d2 --- /dev/null +++ b/samples/CMakeLists.txt @@ -0,0 +1,149 @@ +# Samples app + +option(BUILD_SHARED_LIBS "Build using shared libraries" OFF) +# set(FETCHCONTENT_QUIET FALSE) + +# 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 master + 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.92.5.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}/imstb_truetype.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) +# 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 +) + +# implot for drawing real time plots +FetchContent_Declare( + implot + GIT_REPOSITORY https://github.com/epezent/implot.git + GIT_TAG v0.17 + GIT_SHALLOW TRUE + GIT_PROGRESS TRUE +) +FetchContent_MakeAvailable(implot) + +add_library(implot STATIC + ${implot_SOURCE_DIR}/implot.cpp + ${implot_SOURCE_DIR}/implot_items.cpp + ${implot_SOURCE_DIR}/implot_demo.cpp + ${implot_SOURCE_DIR}/implot.h + ${implot_SOURCE_DIR}/implot_internal.h +) +target_link_libraries(implot PUBLIC imgui) +target_include_directories(implot PUBLIC ${implot_SOURCE_DIR}) + +set (BOX3D_SAMPLE_FILES + camera.cpp + camera.h + earcut.h + font.cpp + font.h + geo_buffer.cpp + geo_buffer.h + jsmn.h + main.cpp + mesh_loader.cpp + mesh_loader.h + renderer.cpp + renderer.h + sample.cpp + sample.h + scene.cpp + scene.h + shader.cpp + shader.h + ssao_buffer.cpp + ssao_buffer.h + stb_image_write.h + stb_truetype.h + tiny_obj_loader.h + utility.h + + sample_benchmark.cpp + sample_bodies.cpp + sample_character.cpp + sample_collision.cpp + sample_compound.cpp + sample_continuous.cpp + sample_determinism.cpp + sample_events.cpp + sample_geometry.cpp + sample_issues.cpp + sample_joint.cpp + sample_manifold.cpp + sample_mesh.cpp + sample_ragdoll.cpp + sample_robustness.cpp + sample_shapes.cpp + sample_stacking.cpp + sample_tree.cpp +) + +add_executable(samples ${BOX3D_SAMPLE_FILES}) +target_include_directories(samples PRIVATE ${CMAKE_SOURCE_DIR}/data) +target_include_directories(samples PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) +target_link_libraries(samples PRIVATE box3d shared glfw imgui implot glad) + +set_target_properties(samples PROPERTIES + CMAKE_COMPILE_WARNING_AS_ERROR ON + CXX_STANDARD 20 + CXX_STANDARD_REQUIRED YES + CXX_EXTENSIONS NO +) + +source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${BOX3D_SAMPLE_FILES}) + +message(STATUS "runtime = ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}") +message(STATUS "binary = ${CMAKE_CURRENT_BINARY_DIR}") diff --git a/samples/camera.cpp b/samples/camera.cpp new file mode 100644 index 0000000..b0f4f19 --- /dev/null +++ b/samples/camera.cpp @@ -0,0 +1,330 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "camera.h" + +#include +// prevent clang format sorting glad.h with glfw3.h +#include + +// ImGui +#include +#include + +Matrix4 MakeOrthographicMatrix( float left, float right, float bottom, float top, float near, float far) +{ + Matrix4 m; + m.cx = Vector4{ 2.0f / (right - left), 0.0f, 0.0f, 0.0f }; + m.cy = Vector4{ 0.0f, 2.0f / (top - bottom), 0.0f, 0.0f }; + m.cz = Vector4{ 0.0f, 0.0f, -2.0f / (far - near), 0.0f }; + m.cw.x = -(right + left) / (right - left); + m.cw.y = -(top + bottom) / (top - bottom); + m.cw.z = -(far + near) / (far - near); + m.cw.w = 1.0f; + return m; +} + +Camera::Camera() +{ + m_yaw = 0.0f; + m_pitch = 0.0f; + m_radius = 1.0f; + m_speed = 20.0f; + m_pivot = b3Vec3_zero; + m_nearPlane = 0.02f; + m_farPlane = 100000.0f; + m_fovY = 50.0f; + m_tanY = tanf( 0.5f * B3_DEG_TO_RAD * m_fovY ); + m_thirdPerson = false; + + m_bufferWidth = 1920; + m_bufferHeight = 1080; + + Resize(1920, 1080); + UpdateTransform(); +} + +void Camera::Resize( int width, int height ) +{ + m_width = b3MaxInt(width, 1 ); + m_height = b3MaxInt(height, 1 ); + m_ratio = float( m_width ) / float( m_height ); + + m_nearHeight = 2.0f * m_nearPlane * m_tanY; + m_nearWidth = m_ratio * m_nearHeight; + + m_farHeight = m_farPlane * ( m_nearHeight / m_nearPlane ); + m_farWidth = m_farPlane * ( m_nearWidth / m_nearPlane ); +} + +b3Vec3 Camera::GetRight() const +{ + return m_right; +} + +b3Vec3 Camera::GetUp() const +{ + return m_up; +} + +b3Vec3 Camera::GetForward() const +{ + return m_forward; +} + +b3Vec3 Camera::GetPosition() const +{ + return m_position; +} + +void Camera::Frame( b3AABB bounds) +{ + b3Vec3 center = b3AABB_Center(bounds); + b3Vec3 extent = b3AABB_Extents(bounds); + + float height = 2.0f * b3MaxFloat(extent.x, b3MaxFloat(extent.y, extent.z ) ); + float radius = 0.5f * height / tanf( 0.5f * B3_DEG_TO_RAD * m_fovY ); + + m_pivot = center; + m_radius = 1.25f * radius; +} + +void Camera::SetView( float yaw, float pitch, float radius, b3Vec3 pivot) +{ + m_yaw = yaw; + m_pitch = pitch; + m_radius = radius; + m_pivot = pivot; + UpdateTransform(); +} + +Matrix4 Camera::GetWorldMatrix() const +{ + Matrix4 m; + m.cx = { m_right.x, m_right.y, m_right.z, 0.0f }; + m.cy = { m_up.x, m_up.y, m_up.z, 0.0f }; + m.cz = { m_forward.x, m_forward.y, m_forward.z, 0.0f }; + m.cw = { m_position.x, m_position.y, m_position.z, 1.0f }; + return m; +} + +static Matrix4 InvertOrtho( const Matrix4& m) +{ + // [ R | t ] + // M = [ --+-- ] + // [ 0 | 1 ] + // + // y = M * x -> y = R * x + t -> x = R^-1 * (y - t) -> x = R^-1 * y - R^-1 * t + // + // [ R | t ]-1 [ R^-1 | -R^-1 * t ] + // M^-1 = [ --+-- ] = [ -----+---------- ] + // [ 0 | 1 ] [ 0 | 1 ] + b3Matrix3 r; + r.cx = {m.cx.x, m.cx.y, m.cx.z }; + r.cy = {m.cy.x, m.cy.y, m.cy.z }; + r.cz = {m.cz.x, m.cz.y, m.cz.z }; + b3Matrix3 invR = b3InvertMatrix(r); + + b3Vec3 t{m.cw.x, m.cw.y, m.cw.z }; + b3Vec3 invRXT = invR * t; + + Matrix4 out; + out.cx = {invR.cx.x, invR.cx.y, invR.cx.z, 0.0f }; + out.cy = {invR.cy.x, invR.cy.y, invR.cy.z, 0.0f }; + out.cz = {invR.cz.x, invR.cz.y, invR.cz.z, 0.0f }; + out.cw = { -invRXT.x, -invRXT.y, -invRXT.z, 1.0f }; + + return out; +} + +Matrix4 Camera::GetViewMatrix() const +{ + Matrix4 v = GetWorldMatrix(); + v = InvertOrtho(v); + return v; +} + +// http://www.songho.ca/opengl/gl_projectionmatrix.html +// https://unspecified.wordpress.com/2012/06/21/calculating-the-gluperspective-matrix-and-other-opengl-matrix-maths/ +// https://software.intel.com/en-us/articles/alternatives-to-using-z-bias-to-fix-z-fighting-issues +static Matrix4 Perspective( float fieldOfViewY, float aspectRatio, float nearPlane, float farPlane) +{ + float cot = 1.0f / tanf( 0.5f * fieldOfViewY); + float depth = farPlane - nearPlane; + + Matrix4 out; + out.cx = {cot / aspectRatio, 0.0f, 0.0f, 0.0f }; + out.cy = { 0.0f, cot, 0.0f, 0.0f }; + out.cz = { 0.0f, 0.0f, -(nearPlane + farPlane) / depth, -1.0f }; + out.cw = { 0.0f, 0.0f, -2.0f * nearPlane * farPlane / depth, 0.0f }; + return out; +} + +Matrix4 Camera::GetProjectionMatrix() const +{ + return Perspective( B3_DEG_TO_RAD * m_fovY, m_ratio, m_nearPlane, m_farPlane ); +} + +PickRay Camera::BuildPickRay( float x, float y) const +{ + // Use similar triangles to build pick ray + + // Scale, flip, shift into frustum coordinates + float xRatio = x / m_width - 0.5f; + float yRatio = 0.5f - y / m_height; + + // Near plane coordinates using ratio + float xNear = xRatio * m_nearWidth; + float yNear = yRatio * m_nearHeight; + + // Far plane coordinates using ratio + float xFar = xRatio * m_farWidth; + float yFar = yRatio * m_farHeight; + + // Coordinates of near and far plane points in camera space + Vector4 nearPoint{xNear, yNear, -m_nearPlane, 1.0f }; + Vector4 farPoint{xFar, yFar, -m_farPlane, 1.0f }; + + // Convert to world space + Matrix4 m = GetWorldMatrix(); + nearPoint = MulMV(m, nearPoint); + farPoint = MulMV(m, farPoint); + + PickRay ray; + ray.origin = {nearPoint.x, nearPoint.y, nearPoint.z }; + ray.translation = b3Vec3{farPoint.x, farPoint.y, farPoint.z } - ray.origin; + return ray; +} + +bool Camera::WorldToScreen( float& xScreen, float& yScreen, b3Vec3 worldPoint) const +{ + Matrix4 view = GetViewMatrix(); + Vector4 cameraPoint = MulMV(view, Vector4{ worldPoint.x, worldPoint.y, worldPoint.z, 1.0f }); + + float x = cameraPoint.x; + float y = cameraPoint.y; + float z = cameraPoint.z; + + // Frustum comes out the back of the camera + if (z > -m_nearPlane || z < -m_farPlane ) + { + return false; + } + + // Find the frustum size at depth Z + float heightAtZ = -2.0f * z * m_tanY; + float widthAtZ = m_ratio * heightAtZ; + + // Compute ratios of the point within the frustum rectangle at Z + float xRatio = x / widthAtZ; + float yRatio = y / heightAtZ; + + // Shift, flip, and scale + xScreen = (xRatio + 0.5f ) * m_width; + yScreen = ( 0.5f - yRatio) * m_height; + + return true; +} + +void Camera::Update( GLFWwindow* window, float elapsedTime) +{ + ImGuiIO& io = ImGui::GetIO(); + + if ( m_thirdPerson ) + { + const float sensitivity = 1.0f; + m_radius -= sensitivity * io.MouseWheel; + m_radius = b3MaxFloat( 0.25f, m_radius ); + return; + } + + if (io.KeyAlt ) + { + // Orbit + if ( ImGui::IsMouseDragging( ImGuiMouseButton_Left ) ) + { + const float sensitivity = 0.2f; + m_yaw -= sensitivity * io.MouseDelta.x; + m_pitch += sensitivity * io.MouseDelta.y; + m_pitch = b3ClampFloat( m_pitch, -85.0f, 85.0f ); + } + + if ( ImGui::IsMouseDragging( ImGuiMouseButton_Middle ) ) + { + const float sensitivity = 0.01f; + m_pivot -= sensitivity * io.MouseDelta.x * m_right; + m_pivot += sensitivity * io.MouseDelta.y * m_up; + } + + if ( ImGui::IsMouseDragging( ImGuiMouseButton_Right ) ) + { + const float sensitivity = 0.02f; + m_radius -= sensitivity * io.MouseDelta.y; + m_radius = b3MaxFloat( 0.001f, m_radius ); + } + + const float sensitivity = 1.0f; + m_radius -= sensitivity * io.MouseWheel; + m_radius = b3MaxFloat( 0.001f, m_radius ); + + UpdateTransform(); + } + else if ( ImGui::IsMouseDown( ImGuiMouseButton_Right ) ) + { + m_speed += io.MouseWheel; + m_speed = b3ClampFloat( m_speed, 0.001f * 60.0f, 500.0f * 60.0f ); + + if ( ImGui::IsMouseDragging( ImGuiMouseButton_Right ) ) + { + const float sensitivity = 0.2f; + m_yaw -= sensitivity * io.MouseDelta.x; + m_pitch += sensitivity * io.MouseDelta.y; + m_pitch = b3ClampFloat( m_pitch, -85.0f, 85.0f ); + + float sinYaw = sinf( B3_DEG_TO_RAD * m_yaw ), cosYaw = cosf( B3_DEG_TO_RAD * m_yaw ); + float sinPitch = sinf( B3_DEG_TO_RAD * m_pitch ), cosPitch = cosf( B3_DEG_TO_RAD * m_pitch ); + + m_forward = {sinYaw * cosPitch, sinPitch, cosYaw * cosPitch}; + m_up = { 0.0f, 1.0f, 0.0f }; + m_up = b3Normalize( m_up - b3Dot( m_forward, m_up ) * m_forward ); + m_right = b3Normalize( b3Cross( m_up, m_forward ) ); + } + + // Smoother with GLFW + if ( glfwGetKey(window, GLFW_KEY_W ) ) + { + m_position -= m_speed * elapsedTime * m_forward; + } + + if ( glfwGetKey(window, GLFW_KEY_S ) ) + { + m_position += m_speed * elapsedTime * m_forward; + } + + if ( glfwGetKey(window, GLFW_KEY_A ) ) + { + m_position -= m_speed * elapsedTime * m_right; + } + + if ( glfwGetKey(window, GLFW_KEY_D ) ) + { + m_position += m_speed * elapsedTime * m_right; + } + + m_pivot = m_position - m_radius * m_forward; + } +} + +void Camera::UpdateTransform() +{ + m_yaw = B3_RAD_TO_DEG * b3UnwindAngle( B3_DEG_TO_RAD * m_yaw ); + float sinYaw = sinf( B3_DEG_TO_RAD * m_yaw ), cosYaw = cosf( B3_DEG_TO_RAD * m_yaw ); + float sinPitch = sinf( B3_DEG_TO_RAD * m_pitch ), cosPitch = cosf( B3_DEG_TO_RAD * m_pitch ); + + m_forward = {sinYaw * cosPitch, sinPitch, cosYaw * cosPitch}; + m_up = { 0.0f, 1.0f, 0.0f }; + m_up = b3Normalize( m_up - b3Dot( m_forward, m_up ) * m_forward ); + m_right = b3Normalize( b3Cross( m_up, m_forward ) ); + + m_position = m_pivot + m_radius * m_forward; +} diff --git a/samples/camera.h b/samples/camera.h new file mode 100644 index 0000000..21a3d5b --- /dev/null +++ b/samples/camera.h @@ -0,0 +1,85 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "utility.h" + +#include "box3d/types.h" + +struct GLFWwindow; + +struct PickRay +{ + b3Vec3 origin; + b3Vec3 translation; +}; + +struct Camera +{ + Camera(); + + // Window + void Resize( int width, int height ); + + // View + b3Vec3 GetRight() const; + b3Vec3 GetUp() const; + b3Vec3 GetForward() const; + b3Vec3 GetPosition() const; + + void Frame( b3AABB bounds); + void SetView( float yaw, float pitch, float radius, b3Vec3 pivot = b3Vec3_zero ); + + Matrix4 GetWorldMatrix() const; + Matrix4 GetViewMatrix() const; + + // Projection + Matrix4 GetProjectionMatrix() const; + PickRay BuildPickRay( float x, float y) const; + bool WorldToScreen( float& xScreen, float& yScreen, b3Vec3 worldPoint) const; + + // Control + void Update( GLFWwindow* window, float elapsedTime); + + void UpdateTransform(); + + // Window + int m_width; + int m_height; + + // Frame buffer + int m_bufferWidth; + int m_bufferHeight; + + // View yaw in degrees + float m_yaw; + + // View pitch in degrees + float m_pitch; + + float m_radius; + b3Vec3 m_pivot; + float m_speed; + + // Projection + float m_fovY; + float m_tanY; + float m_ratio; + float m_nearPlane; + float m_farPlane; + + float m_nearWidth; + float m_nearHeight; + + float m_farWidth; + float m_farHeight; + + // World coordinates + b3Vec3 m_right; + b3Vec3 m_up; + b3Vec3 m_forward; + b3Vec3 m_position; + + bool m_thirdPerson; +}; diff --git a/samples/earcut.h b/samples/earcut.h new file mode 100644 index 0000000..01bd7e9 --- /dev/null +++ b/samples/earcut.h @@ -0,0 +1,820 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace mapbox { + +namespace util { + +template struct nth { + inline static typename std::tuple_element::type + get(const T& t) { return std::get(t); }; +}; + +} + +namespace detail { + +template +class Earcut { +public: + std::vector indices; + std::size_t vertices = 0; + + template + void operator()(const Polygon& points); + +private: + struct Node { + Node(N index, double x_, double y_) : i(index), x(x_), y(y_) {} + Node(const Node&) = delete; + Node& operator=(const Node&) = delete; + Node(Node&&) = delete; + Node& operator=(Node&&) = delete; + + const N i; + const double x; + const double y; + + // previous and next vertice nodes in a polygon ring + Node* prev = nullptr; + Node* next = nullptr; + + // z-order curve value + int32_t z = 0; + + // previous and next nodes in z-order + Node* prevZ = nullptr; + Node* nextZ = nullptr; + + // indicates whether this is a steiner point + bool steiner = false; + }; + + template Node* linkedList(const Ring& points, const bool clockwise); + Node* filterPoints(Node* start, Node* end = nullptr); + void earcutLinked(Node* ear, int pass = 0); + bool isEar(Node* ear); + bool isEarHashed(Node* ear); + Node* cureLocalIntersections(Node* start); + void splitEarcut(Node* start); + template Node* eliminateHoles(const Polygon& points, Node* outerNode); + Node* eliminateHole(Node* hole, Node* outerNode); + Node* findHoleBridge(Node* hole, Node* outerNode); + bool sectorContainsSector(const Node* m, const Node* p); + void indexCurve(Node* start); + Node* sortLinked(Node* list); + int32_t zOrder(const double x_, const double y_); + Node* getLeftmost(Node* start); + bool pointInTriangle(double ax, double ay, double bx, double by, double cx, double cy, double px, double py) const; + bool isValidDiagonal(Node* a, Node* b); + double area(const Node* p, const Node* q, const Node* r) const; + bool equals(const Node* p1, const Node* p2); + bool intersects(const Node* p1, const Node* q1, const Node* p2, const Node* q2); + bool onSegment(const Node* p, const Node* q, const Node* r); + int sign(double val); + bool intersectsPolygon(const Node* a, const Node* b); + bool locallyInside(const Node* a, const Node* b); + bool middleInside(const Node* a, const Node* b); + Node* splitPolygon(Node* a, Node* b); + template Node* insertNode(std::size_t i, const Point& p, Node* last); + void removeNode(Node* p); + + bool hashing; + double minX, maxX; + double minY, maxY; + double inv_size = 0; + + template > + class ObjectPool { + public: + ObjectPool() { } + ObjectPool(std::size_t blockSize_) { + reset(blockSize_); + } + ~ObjectPool() { + clear(); + } + template + T* construct(Args&&... args) { + if (currentIndex >= blockSize) { + currentBlock = alloc_traits::allocate(alloc, blockSize); + allocations.emplace_back(currentBlock); + currentIndex = 0; + } + T* object = ¤tBlock[currentIndex++]; + alloc_traits::construct(alloc, object, std::forward(args)...); + return object; + } + void reset(std::size_t newBlockSize) { + for (auto allocation : allocations) { + alloc_traits::deallocate(alloc, allocation, blockSize); + } + allocations.clear(); + blockSize = std::max(1, newBlockSize); + currentBlock = nullptr; + currentIndex = blockSize; + } + void clear() { reset(blockSize); } + private: + T* currentBlock = nullptr; + std::size_t currentIndex = 1; + std::size_t blockSize = 1; + std::vector allocations; + Alloc alloc; + typedef typename std::allocator_traits alloc_traits; + }; + ObjectPool nodes; +}; + +template template +void Earcut::operator()(const Polygon& points) { + // reset + indices.clear(); + vertices = 0; + + if (points.empty()) return; + + double x; + double y; + int threshold = 80; + std::size_t len = 0; + + for (size_t i = 0; threshold >= 0 && i < points.size(); i++) { + threshold -= static_cast(points[i].size()); + len += points[i].size(); + } + + //estimate size of nodes and indices + nodes.reset(len * 3 / 2); + indices.reserve(len + points[0].size()); + + Node* outerNode = linkedList(points[0], true); + if (!outerNode || outerNode->prev == outerNode->next) return; + + if (points.size() > 1) outerNode = eliminateHoles(points, outerNode); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + hashing = threshold < 0; + if (hashing) { + Node* p = outerNode->next; + minX = maxX = outerNode->x; + minY = maxY = outerNode->y; + do { + x = p->x; + y = p->y; + minX = std::min(minX, x); + minY = std::min(minY, y); + maxX = std::max(maxX, x); + maxY = std::max(maxY, y); + p = p->next; + } while (p != outerNode); + + // minX, minY and size are later used to transform coords into integers for z-order calculation + inv_size = std::max(maxX - minX, maxY - minY); + inv_size = inv_size != .0 ? (1. / inv_size) : .0; + } + + earcutLinked(outerNode); + + nodes.clear(); +} + +// create a circular doubly linked list from polygon points in the specified winding order +template template +typename Earcut::Node* +Earcut::linkedList(const Ring& points, const bool clockwise) { + using Point = typename Ring::value_type; + double sum = 0; + const std::size_t len = points.size(); + std::size_t i, j; + Node* last = nullptr; + + // calculate original winding order of a polygon ring + for (i = 0, j = len > 0 ? len - 1 : 0; i < len; j = i++) { + const auto& p1 = points[i]; + const auto& p2 = points[j]; + const double p20 = util::nth<0, Point>::get(p2); + const double p10 = util::nth<0, Point>::get(p1); + const double p11 = util::nth<1, Point>::get(p1); + const double p21 = util::nth<1, Point>::get(p2); + sum += (p20 - p10) * (p11 + p21); + } + + // link points into circular doubly-linked list in the specified winding order + if (clockwise == (sum > 0)) { + for (i = 0; i < len; i++) last = insertNode(vertices + i, points[i], last); + } else { + for (i = len; i-- > 0;) last = insertNode(vertices + i, points[i], last); + } + + if (last && equals(last, last->next)) { + removeNode(last); + last = last->next; + } + + vertices += len; + + return last; +} + +// eliminate colinear or duplicate points +template +typename Earcut::Node* +Earcut::filterPoints(Node* start, Node* end) { + if (!end) end = start; + + Node* p = start; + bool again; + do { + again = false; + + if (!p->steiner && (equals(p, p->next) || area(p->prev, p, p->next) == 0)) { + removeNode(p); + p = end = p->prev; + + if (p == p->next) break; + again = true; + + } else { + p = p->next; + } + } while (again || p != end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +template +void Earcut::earcutLinked(Node* ear, int pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && hashing) indexCurve(ear); + + Node* stop = ear; + Node* prev; + Node* next; + + int iterations = 0; + + // iterate through ears, slicing them one by one + while (ear->prev != ear->next) { + iterations++; + prev = ear->prev; + next = ear->next; + + if (hashing ? isEarHashed(ear) : isEar(ear)) { + // cut off the triangle + indices.emplace_back(prev->i); + indices.emplace_back(ear->i); + indices.emplace_back(next->i); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next->next; + stop = next->next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear == stop) { + // try filtering points and slicing again + if (!pass) earcutLinked(filterPoints(ear), 1); + + // if this didn't work, try curing all small self-intersections locally + else if (pass == 1) { + ear = cureLocalIntersections(filterPoints(ear)); + earcutLinked(ear, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass == 2) splitEarcut(ear); + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +template +bool Earcut::isEar(Node* ear) { + const Node* a = ear->prev; + const Node* b = ear; + const Node* c = ear->next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + Node* p = ear->next->next; + + while (p != ear->prev) { + if (pointInTriangle(a->x, a->y, b->x, b->y, c->x, c->y, p->x, p->y) && + area(p->prev, p, p->next) >= 0) return false; + p = p->next; + } + + return true; +} + +template +bool Earcut::isEarHashed(Node* ear) { + const Node* a = ear->prev; + const Node* b = ear; + const Node* c = ear->next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + const double minTX = std::min(a->x, std::min(b->x, c->x)); + const double minTY = std::min(a->y, std::min(b->y, c->y)); + const double maxTX = std::max(a->x, std::max(b->x, c->x)); + const double maxTY = std::max(a->y, std::max(b->y, c->y)); + + // z-order range for the current triangle bbox; + const int32_t minZ = zOrder(minTX, minTY); + const int32_t maxZ = zOrder(maxTX, maxTY); + + // first look for points inside the triangle in increasing z-order + Node* p = ear->nextZ; + + while (p && p->z <= maxZ) { + if (p != ear->prev && p != ear->next && + pointInTriangle(a->x, a->y, b->x, b->y, c->x, c->y, p->x, p->y) && + area(p->prev, p, p->next) >= 0) return false; + p = p->nextZ; + } + + // then look for points in decreasing z-order + p = ear->prevZ; + + while (p && p->z >= minZ) { + if (p != ear->prev && p != ear->next && + pointInTriangle(a->x, a->y, b->x, b->y, c->x, c->y, p->x, p->y) && + area(p->prev, p, p->next) >= 0) return false; + p = p->prevZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +template +typename Earcut::Node* +Earcut::cureLocalIntersections(Node* start) { + Node* p = start; + do { + Node* a = p->prev; + Node* b = p->next->next; + + // a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2]) + if (!equals(a, b) && intersects(a, p, p->next, b) && locallyInside(a, b) && locallyInside(b, a)) { + indices.emplace_back(a->i); + indices.emplace_back(p->i); + indices.emplace_back(b->i); + + // remove two nodes involved + removeNode(p); + removeNode(p->next); + + p = start = b; + } + p = p->next; + } while (p != start); + + return filterPoints(p); +} + +// try splitting polygon into two and triangulate them independently +template +void Earcut::splitEarcut(Node* start) { + // look for a valid diagonal that divides the polygon into two + Node* a = start; + do { + Node* b = a->next->next; + while (b != a->prev) { + if (a->i != b->i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + Node* c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a->next); + c = filterPoints(c, c->next); + + // run earcut on each half + earcutLinked(a); + earcutLinked(c); + return; + } + b = b->next; + } + a = a->next; + } while (a != start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +template template +typename Earcut::Node* +Earcut::eliminateHoles(const Polygon& points, Node* outerNode) { + const size_t len = points.size(); + + std::vector queue; + for (size_t i = 1; i < len; i++) { + Node* list = linkedList(points[i], false); + if (list) { + if (list == list->next) list->steiner = true; + queue.push_back(getLeftmost(list)); + } + } + std::sort(queue.begin(), queue.end(), [](const Node* a, const Node* b) { + return a->x < b->x; + }); + + // process holes from left to right + for (size_t i = 0; i < queue.size(); i++) { + outerNode = eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode->next); + } + + return outerNode; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +template +typename Earcut::Node* +Earcut::eliminateHole(Node* hole, Node* outerNode) { + Node* bridge = findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } + + Node* bridgeReverse = splitPolygon(bridge, hole); + + // filter collinear points around the cuts + Node* filteredBridge = filterPoints(bridge, bridge->next); + filterPoints(bridgeReverse, bridgeReverse->next); + + // Check if input node was removed by the filtering + return outerNode == bridge ? filteredBridge : outerNode; +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +template +typename Earcut::Node* +Earcut::findHoleBridge(Node* hole, Node* outerNode) { + Node* p = outerNode; + double hx = hole->x; + double hy = hole->y; + double qx = -std::numeric_limits::infinity(); + Node* m = nullptr; + + // find a segment intersected by a ray from the hole's leftmost Vertex to the left; + // segment's endpoint with lesser x will be potential connection Vertex + do { + if (hy <= p->y && hy >= p->next->y && p->next->y != p->y) { + double x = p->x + (hy - p->y) * (p->next->x - p->x) / (p->next->y - p->y); + if (x <= hx && x > qx) { + qx = x; + if (x == hx) { + if (hy == p->y) return p; + if (hy == p->next->y) return p->next; + } + m = p->x < p->next->x ? p : p->next; + } + } + p = p->next; + } while (p != outerNode); + + if (!m) return 0; + + if (hx == qx) return m; // hole touches outer segment; pick leftmost endpoint + + // look for points inside the triangle of hole Vertex, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the Vertex of the minimum angle with the ray as connection Vertex + + const Node* stop = m; + double tanMin = std::numeric_limits::infinity(); + double tanCur = 0; + + p = m; + double mx = m->x; + double my = m->y; + + do { + if (hx >= p->x && p->x >= mx && hx != p->x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p->x, p->y)) { + + tanCur = std::abs(hy - p->y) / (hx - p->x); // tangential + + if (locallyInside(p, hole) && + (tanCur < tanMin || (tanCur == tanMin && (p->x > m->x || sectorContainsSector(m, p))))) { + m = p; + tanMin = tanCur; + } + } + + p = p->next; + } while (p != stop); + + return m; +} + +// whether sector in vertex m contains sector in vertex p in the same coordinates +template +bool Earcut::sectorContainsSector(const Node* m, const Node* p) { + return area(m->prev, m, p->prev) < 0 && area(p->next, m, m->next) < 0; +} + +// interlink polygon nodes in z-order +template +void Earcut::indexCurve(Node* start) { + assert(start); + Node* p = start; + + do { + p->z = p->z ? p->z : zOrder(p->x, p->y); + p->prevZ = p->prev; + p->nextZ = p->next; + p = p->next; + } while (p != start); + + p->prevZ->nextZ = nullptr; + p->prevZ = nullptr; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +template +typename Earcut::Node* +Earcut::sortLinked(Node* list) { + assert(list); + Node* p; + Node* q; + Node* e; + Node* tail; + int i, numMerges, pSize, qSize; + int inSize = 1; + + for (;;) { + p = list; + list = nullptr; + tail = nullptr; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q->nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize == 0) { + e = q; + q = q->nextZ; + qSize--; + } else if (qSize == 0 || !q) { + e = p; + p = p->nextZ; + pSize--; + } else if (p->z <= q->z) { + e = p; + p = p->nextZ; + pSize--; + } else { + e = q; + q = q->nextZ; + qSize--; + } + + if (tail) tail->nextZ = e; + else list = e; + + e->prevZ = tail; + tail = e; + } + + p = q; + } + + tail->nextZ = nullptr; + + if (numMerges <= 1) return list; + + inSize *= 2; + } +} + +// z-order of a Vertex given coords and size of the data bounding box +template +int32_t Earcut::zOrder(const double x_, const double y_) { + // coords are transformed into non-negative 15-bit integer range + int32_t x = static_cast(32767.0 * (x_ - minX) * inv_size); + int32_t y = static_cast(32767.0 * (y_ - minY) * inv_size); + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +template +typename Earcut::Node* +Earcut::getLeftmost(Node* start) { + Node* p = start; + Node* leftmost = start; + do { + if (p->x < leftmost->x || (p->x == leftmost->x && p->y < leftmost->y)) + leftmost = p; + p = p->next; + } while (p != start); + + return leftmost; +} + +// check if a point lies within a convex triangle +template +bool Earcut::pointInTriangle(double ax, double ay, double bx, double by, double cx, double cy, double px, double py) const { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +template +bool Earcut::isValidDiagonal(Node* a, Node* b) { + return a->next->i != b->i && a->prev->i != b->i && !intersectsPolygon(a, b) && // dones't intersect other edges + ((locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible + (area(a->prev, a, b->prev) != 0.0 || area(a, b->prev, b) != 0.0)) || // does not create opposite-facing sectors + (equals(a, b) && area(a->prev, a, a->next) > 0 && area(b->prev, b, b->next) > 0)); // special zero-length case +} + +// signed area of a triangle +template +double Earcut::area(const Node* p, const Node* q, const Node* r) const { + return (q->y - p->y) * (r->x - q->x) - (q->x - p->x) * (r->y - q->y); +} + +// check if two points are equal +template +bool Earcut::equals(const Node* p1, const Node* p2) { + return p1->x == p2->x && p1->y == p2->y; +} + +// check if two segments intersect +template +bool Earcut::intersects(const Node* p1, const Node* q1, const Node* p2, const Node* q2) { + int o1 = sign(area(p1, q1, p2)); + int o2 = sign(area(p1, q1, q2)); + int o3 = sign(area(p2, q2, p1)); + int o4 = sign(area(p2, q2, q1)); + + if (o1 != o2 && o3 != o4) return true; // general case + + if (o1 == 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 + if (o2 == 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 + if (o3 == 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 + if (o4 == 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 + + return false; +} + +// for collinear points p, q, r, check if point q lies on segment pr +template +bool Earcut::onSegment(const Node* p, const Node* q, const Node* r) { + return q->x <= std::max(p->x, r->x) && + q->x >= std::min(p->x, r->x) && + q->y <= std::max(p->y, r->y) && + q->y >= std::min(p->y, r->y); +} + +template +int Earcut::sign(double val) { + return (0.0 < val) - (val < 0.0); +} + +// check if a polygon diagonal intersects any polygon segments +template +bool Earcut::intersectsPolygon(const Node* a, const Node* b) { + const Node* p = a; + do { + if (p->i != a->i && p->next->i != a->i && p->i != b->i && p->next->i != b->i && + intersects(p, p->next, a, b)) return true; + p = p->next; + } while (p != a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +template +bool Earcut::locallyInside(const Node* a, const Node* b) { + return area(a->prev, a, a->next) < 0 ? + area(a, b, a->next) >= 0 && area(a, a->prev, b) >= 0 : + area(a, b, a->prev) < 0 || area(a, a->next, b) < 0; +} + +// check if the middle Vertex of a polygon diagonal is inside the polygon +template +bool Earcut::middleInside(const Node* a, const Node* b) { + const Node* p = a; + bool inside = false; + double px = (a->x + b->x) / 2; + double py = (a->y + b->y) / 2; + do { + if (((p->y > py) != (p->next->y > py)) && p->next->y != p->y && + (px < (p->next->x - p->x) * (py - p->y) / (p->next->y - p->y) + p->x)) + inside = !inside; + p = p->next; + } while (p != a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits +// polygon into two; if one belongs to the outer ring and another to a hole, it merges it into a +// single ring +template +typename Earcut::Node* +Earcut::splitPolygon(Node* a, Node* b) { + Node* a2 = nodes.construct(a->i, a->x, a->y); + Node* b2 = nodes.construct(b->i, b->x, b->y); + Node* an = a->next; + Node* bp = b->prev; + + a->next = b; + b->prev = a; + + a2->next = an; + an->prev = a2; + + b2->next = a2; + a2->prev = b2; + + bp->next = b2; + b2->prev = bp; + + return b2; +} + +// create a node and util::optionally link it with previous one (in a circular doubly linked list) +template template +typename Earcut::Node* +Earcut::insertNode(std::size_t i, const Point& pt, Node* last) { + Node* p = nodes.construct(static_cast(i), util::nth<0, Point>::get(pt), util::nth<1, Point>::get(pt)); + + if (!last) { + p->prev = p; + p->next = p; + + } else { + assert(last); + p->next = last->next; + p->prev = last; + last->next->prev = p; + last->next = p; + } + return p; +} + +template +void Earcut::removeNode(Node* p) { + p->next->prev = p->prev; + p->prev->next = p->next; + + if (p->prevZ) p->prevZ->nextZ = p->nextZ; + if (p->nextZ) p->nextZ->prevZ = p->prevZ; +} +} + +template +std::vector earcut(const Polygon& poly) { + mapbox::detail::Earcut earcut; + earcut(poly); + return std::move(earcut.indices); +} +} diff --git a/samples/font.cpp b/samples/font.cpp new file mode 100644 index 0000000..f60d82c --- /dev/null +++ b/samples/font.cpp @@ -0,0 +1,276 @@ +// 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 "font.h" + +#include "camera.h" +#include "shader.h" +#include "utility.h" + +#define STBTT_STATIC +#define STB_TRUETYPE_IMPLEMENTATION +#include "stb_truetype.h" + +//#define STB_IMAGE_WRITE_IMPLEMENTATION +//#include "stb_image_write.h" + +#include "glad/glad.h" + +#include +#include + +static const char* vertexShaderSrc = R"( +#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; +} +)"; + +static const char* fragmentShaderSrc = R"( +#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); +} +)"; + +Font::Font( const Camera* camera, float fontSize ) +{ + m_camera = camera; + m_fontSize = fontSize; + m_characters = (stbtt_bakedchar*)malloc( m_characterCount * sizeof( stbtt_bakedchar ) ); + m_textureId = 0; + m_vaoId = 0; + m_vboId = 0; + m_programId = 0; +} + +Font::~Font() +{ + if ( m_programId != 0 ) + { + DestroyShader( m_programId ); + } + + glDeleteBuffers( 1, &m_vboId ); + glDeleteVertexArrays( 1, &m_vaoId ); + + if ( m_textureId != 0 ) + { + glDeleteTextures( 1, &m_textureId ); + } + + free( m_characters ); +} + +void Font::AddText( float x, float y, b3HexColor color, const char* text ) +{ + if (text == nullptr) + { + return; + } + + b3Vec3 position = { x, y, 0.0f }; + RGBA8 c = MakeRGBA8( color ); + int pw = m_atlasWidth; + int ph = m_atlasHeight; + + int i = 0; + while ( text[i] != 0 ) + { + int index = (int)text[i] - m_firstCharacter; + + if ( 0 <= index && index < m_characterCount ) + { + // 1=opengl + stbtt_aligned_quad q; + stbtt_GetBakedQuad( m_characters, pw, ph, index, &position.x, &position.y, &q, 1 ); + + Vertex v1 = { { q.x0, q.y0 }, { q.s0, q.t0 }, c }; + Vertex v2 = { { q.x1, q.y0 }, { q.s1, q.t0 }, c }; + Vertex v3 = { { q.x1, q.y1 }, { q.s1, q.t1 }, c }; + Vertex v4 = { { q.x0, q.y1 }, { q.s0, q.t1 }, c }; + + m_vertices.push_back( v1 ); + m_vertices.push_back( v3 ); + m_vertices.push_back( v2 ); + m_vertices.push_back( v1 ); + m_vertices.push_back( v4 ); + m_vertices.push_back( v3 ); + } + + i += 1; + } +} + +void Font::Flush() +{ + Matrix4 projectionMatrix = MakeOrthographicMatrix( 0.0f, m_camera->m_width, m_camera->m_height, 0.0f, -1.0f, 1.0f ); + + glUseProgram( m_programId ); + + glEnable( GL_BLEND ); + glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + glDisable( GL_DEPTH_TEST ); + + int slot = 0; + glActiveTexture( GL_TEXTURE0 + slot ); + glBindTexture( GL_TEXTURE_2D, m_textureId ); + + glBindVertexArray( m_vaoId ); + glBindBuffer( GL_ARRAY_BUFFER, m_vboId ); + + int textureUniform = glGetUniformLocation( m_programId, "FontAtlas" ); + glUniform1i( textureUniform, slot ); + + int matrixUniform = glGetUniformLocation( m_programId, "ProjectionMatrix" ); + glUniformMatrix4fv( matrixUniform, 1, GL_FALSE, &projectionMatrix.cx.x ); + + int totalVertexCount = int( m_vertices.size() ); + int drawCallCount = ( totalVertexCount / m_vboCapacity ) + 1; + + for ( int i = 0; i < drawCallCount; i++ ) + { + const Vertex* data = m_vertices.data() + i * m_vboCapacity; + + int vertexCount; + if ( i == drawCallCount - 1 ) + { + vertexCount = totalVertexCount % m_vboCapacity; + } + else + { + vertexCount = m_vboCapacity; + } + + // todo macOS optimization? + // glBufferData( GL_ARRAY_BUFFER, m_vboCapacity * sizeof( Vertex ), nullptr, GL_DYNAMIC_DRAW ); + glBufferSubData( GL_ARRAY_BUFFER, 0, vertexCount * sizeof( Vertex ), data ); + glDrawArrays( GL_TRIANGLES, 0, vertexCount ); + } + + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + glBindTexture( GL_TEXTURE_2D, 0 ); + + glDisable( GL_BLEND ); + glEnable( GL_DEPTH_TEST ); + + CheckOpenGL(); + + m_vertices.clear(); +} + +bool Font::Initialize( const char* path ) +{ + // Create atlas + FILE* file = fopen( path, "rb" ); + if ( file == nullptr ) + { + assert( false ); + return false; + } + + int fileBufferCapacity = 1 << 20; + unsigned char* fileBuffer = (unsigned char*)malloc( fileBufferCapacity * sizeof( unsigned char ) ); + fread( fileBuffer, 1, fileBufferCapacity, file ); + + int pw = m_atlasWidth; + int ph = m_atlasHeight; + unsigned char* tempBitmap = (unsigned char*)malloc( pw * ph * sizeof( unsigned char ) ); + stbtt_BakeFontBitmap( fileBuffer, 0, m_fontSize, tempBitmap, pw, ph, m_firstCharacter, m_characterCount, m_characters ); + + glGenTextures( 1, &m_textureId ); + glBindTexture( GL_TEXTURE_2D, m_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 ); + + // stbi_write_png( "build/fontAtlas.png", pw, ph, 1, tempBitmap, pw ); + + fclose( file ); + free( fileBuffer ); + free( tempBitmap ); + fileBuffer = nullptr; + tempBitmap = nullptr; + + m_programId = CreateProgramFromStrings( vertexShaderSrc, fragmentShaderSrc ); + if ( m_programId == 0 ) + { + return false; + } + + // Setting up the VAO and VBO + glGenBuffers( 1, &m_vboId ); + glBindBuffer( GL_ARRAY_BUFFER, m_vboId ); + glBufferData( GL_ARRAY_BUFFER, m_vboCapacity * sizeof( Vertex ), nullptr, GL_DYNAMIC_DRAW ); + + glGenVertexArrays( 1, &m_vaoId ); + glBindVertexArray( m_vaoId ); + + // position attribute + glVertexAttribPointer( 0, 2, GL_FLOAT, GL_FALSE, sizeof( Vertex ), (void*)offsetof( Vertex, position ) ); + glEnableVertexAttribArray( 0 ); + + // uv attribute + glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, sizeof( Vertex ), (void*)offsetof( Vertex, uv ) ); + glEnableVertexAttribArray( 1 ); + + // color attribute will be expanded to floats using normalization + glVertexAttribPointer( 2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( Vertex ), (void*)offsetof( Vertex, color ) ); + glEnableVertexAttribArray( 2 ); + + glBindVertexArray( 0 ); + + CheckOpenGL(); + + return true; +} + +// For testing +// Matrix4 MakeProjectionMatrix( float width, float height ) +//{ +// Matrix4 m; +// m.cx = { 2.0f / width, 0.0f, 0.0f, 0.0f }; +// m.cy = { 0.0f, 2.0f / height, 0.0f, 0.0f }; +// m.cz = { 0.0f, 0.0f, -1.0f, 0.0f }; +// m.cw = { -1.0f, -1.0f, 0.0f, 1.0f }; +// return m; +//} + +Font* Font::Create( const Camera* camera, const char* path, int fontSize ) +{ + Font* font = new Font( camera, fontSize ); + if ( font->Initialize( path ) == false ) + { + delete font; + font = nullptr; + } + + return font; +} diff --git a/samples/font.h b/samples/font.h new file mode 100644 index 0000000..dd37ab9 --- /dev/null +++ b/samples/font.h @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "box3d/types.h" +#include "utility.h" +#include "stb_truetype.h" + +#include + +struct Camera; + +struct Vertex +{ + b3Vec2 position; + b3Vec2 uv; + RGBA8 color; +}; + +class Font +{ +public: + static Font* Create( const Camera* camera, const char* path, int fontSize ); + ~Font(); + + void AddText( float x, float y, b3HexColor color, const char* text); + + void Flush( ); + +private: + Font( const Camera* camera, float fontSize ); + bool Initialize( const char* path ); + + static constexpr int m_firstCharacter = 32; + static constexpr int m_characterCount = 96; + static constexpr int m_atlasWidth = 512; + static constexpr int m_atlasHeight = 512; + + // The number of vertices the vbo can hold + static constexpr int m_vboCapacity = 6 * 10000; + + const Camera* m_camera; + float m_fontSize; + stbtt_bakedchar* m_characters; + std::vector m_vertices; + unsigned int m_textureId; + uint32_t m_vaoId; + uint32_t m_vboId; + uint32_t m_programId; +}; diff --git a/samples/geo_buffer.cpp b/samples/geo_buffer.cpp new file mode 100644 index 0000000..1e23dc2 --- /dev/null +++ b/samples/geo_buffer.cpp @@ -0,0 +1,150 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "geo_buffer.h" + +#include +#include +#include +#include + +struct GeoBuffer +{ + int32_t width, height; + uint32_t frameBufferId; + uint32_t positionId; + uint32_t normalId; + uint32_t albedoId; + uint32_t depthTextureId; +}; + +GeoBuffer* CreateGeoBuffer(int32_t width, int32_t height) +{ + GeoBuffer* buffer = new GeoBuffer; + + buffer->width = width; + buffer->height = height; + + glGenFramebuffers(1, &buffer->frameBufferId); + glBindFramebuffer(GL_FRAMEBUFFER, buffer->frameBufferId); + + // position color buffer + glGenTextures(1, &buffer->positionId); + glBindTexture(GL_TEXTURE_2D, buffer->positionId); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, nullptr); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, buffer->positionId, 0); + + // normal color buffer + glGenTextures(1, &buffer->normalId); + glBindTexture(GL_TEXTURE_2D, buffer->normalId); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, nullptr); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, buffer->normalId, 0); + + // color + specular color buffer + glGenTextures(1, &buffer->albedoId); + glBindTexture(GL_TEXTURE_2D, buffer->albedoId); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, buffer->albedoId, 0); + + // tell OpenGL which color attachments we'll use (of this framebuffer) for rendering + const unsigned int attachments[3] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2}; + glDrawBuffers(3, attachments); + + // create and attach depth buffer as a texture + // Using a texture instead of a renderbuffer avoids a slow blit path on Apple Silicon + glGenTextures(1, &buffer->depthTextureId); + glBindTexture(GL_TEXTURE_2D, buffer->depthTextureId); + glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, buffer->depthTextureId, 0); + + // finally check if framebuffer is complete + if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) + { + fprintf(stderr, "Failed to initialize glad\n"); + free(buffer); + return nullptr; + } + + glBindFramebuffer(GL_FRAMEBUFFER, 0); + return buffer; +} + +void BindGeoBuffer(GeoBuffer* buffer) +{ + glBindFramebuffer(GL_FRAMEBUFFER, buffer->frameBufferId); + + // Clear each attachment to zero independently of the global glClearColor, so the + // deferred lighting pass can identify sky pixels by gPosition.xyz == 0. + static const GLfloat zero[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + glClearBufferfv(GL_COLOR, 0, zero); + glClearBufferfv(GL_COLOR, 1, zero); + glClearBufferfv(GL_COLOR, 2, zero); + glClear(GL_DEPTH_BUFFER_BIT); +} + +#if 0 +void tbBindGeoPositionNormal(GeoBuffer* buffer) +{ + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, buffer->positionId); + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, buffer->normalId); +} +#endif + +void BindGeoTextures(GeoBuffer* buffer) +{ + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, buffer->positionId); + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, buffer->normalId); + glActiveTexture(GL_TEXTURE2); + glBindTexture(GL_TEXTURE_2D, buffer->albedoId); +} + +void BindGeoPosition(GeoBuffer* buffer, int textureUnit) +{ + glActiveTexture(GL_TEXTURE0 + textureUnit); + glBindTexture(GL_TEXTURE_2D, buffer->positionId); +} + +void BindGeoDepthTexture(GeoBuffer* buffer, int textureUnit) +{ + glActiveTexture(GL_TEXTURE0 + textureUnit); + glBindTexture(GL_TEXTURE_2D, buffer->depthTextureId); +} + +#if 0 +void tbResize(GeoBuffer* buffer, int32_t width, int32_t height) +{ + glBindTexture(GL_TEXTURE_2D, buffer->positionId); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, nullptr); + + glBindTexture(GL_TEXTURE_2D, buffer->normalId); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, nullptr); + + glBindTexture(GL_TEXTURE_2D, buffer->albedoId); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); +} +#endif + +void DestroyGeoBuffer(GeoBuffer* buffer) +{ + glDeleteFramebuffers(1, &buffer->frameBufferId); + glDeleteTextures(1, &buffer->positionId); + glDeleteTextures(1, &buffer->normalId); + glDeleteTextures(1, &buffer->albedoId); + glDeleteTextures(1, &buffer->depthTextureId); + + delete buffer; +} diff --git a/samples/geo_buffer.h b/samples/geo_buffer.h new file mode 100644 index 0000000..4bee59a --- /dev/null +++ b/samples/geo_buffer.h @@ -0,0 +1,17 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +struct GeoBuffer; + +GeoBuffer* CreateGeoBuffer(int32_t width, int32_t height); +void DestroyGeoBuffer(GeoBuffer* buffer); + +void BindGeoBuffer(GeoBuffer* buffer); +//void tbBindGeoPositionNormal(GeoBuffer* buffer); +void BindGeoTextures(GeoBuffer* buffer); +void BindGeoPosition(GeoBuffer* buffer, int textureUnit); +void BindGeoDepthTexture(GeoBuffer* buffer, int textureUnit); diff --git a/samples/imconfig.h b/samples/imconfig.h new file mode 100644 index 0000000..5841c82 --- /dev/null +++ b/samples/imconfig.h @@ -0,0 +1,156 @@ +//----------------------------------------------------------------------------- +// DEAR IMGUI COMPILE-TIME OPTIONS +// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure. +// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions. +//----------------------------------------------------------------------------- +// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your +// modifications to it) B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own +// file without touching this template. +//----------------------------------------------------------------------------- +// You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the +// imgui*.cpp files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on +// data structures. Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure +// layouts. Call IMGUI_CHECKVERSION() from your .cpp file to verify that the data structures your files are using are matching the +// ones imgui.cpp is using. +//----------------------------------------------------------------------------- + +#pragma once + +//---- Define assertion handler. Defaults to calling assert(). +// If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single +// statement. +// #define IM_ASSERT(_EXPR) MyAssert(_EXPR) +// #define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts + +//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows +// Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee +// backward nor forward ABI compatibility. +// - Windows DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + +// SetAllocatorFunctions() +// for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more +// details. +// #define IMGUI_API __declspec(dllexport) // MSVC Windows: DLL export +// #define IMGUI_API __declspec(dllimport) // MSVC Windows: DLL import +// #define IMGUI_API __attribute__((visibility("default"))) // GCC/Clang: override visibility when set is hidden + +//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to clean your code of +//obsolete function/names. #define IMGUI_DISABLE_OBSOLETE_FUNCTIONS #define IMGUI_DISABLE_OBSOLETE_KEYIO // 1.87+ disable legacy +// io.KeyMap[]+io.KeysDown[] in favor io.AddKeyEvent(). This is automatically done by IMGUI_DISABLE_OBSOLETE_FUNCTIONS. + +//---- Disable all of Dear ImGui or don't implement standard windows/tools. +// It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in +// day to day work. Please read comments in imgui_demo.cpp. +// #define IMGUI_DISABLE // Disable everything: all headers and source files will be empty. +// #define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be +// empty. #define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: +// ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty. + +//---- Don't implement some functions to reduce linkage requirements. +// #define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and +// link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a) #define +// IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME handler +// (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW) #define +// IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default +// IME handler (won't require imm32.lib/.a) #define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and +// link with any Win32 function (clipboard, IME). #define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement +// default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default). +// #define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS // Don't implement default platform_io.Platform_OpenInShellFn() +// handler (Win32: ShellExecute(), require shell32.lib/.a, Mac/Linux: use system("")). #define +// IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them +// yourself (e.g. if you don't want to link with vsnprintf) #define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't +// implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. #define +// IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and +// ImFileHandle at all (replace them with dummies) #define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement +// ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link +// with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. #define IMGUI_DISABLE_DEFAULT_ALLOCATORS // +// Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call +// ImGui::SetAllocatorFunctions(). #define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even +// if available + +//---- Enable Test Engine / Automation features. +// #define IMGUI_ENABLE_TEST_ENGINE // Enable imgui_test_engine hooks. Generally set automatically by +// include "imgui_te_config.h", see Test Engine for details. + +//---- Include imgui_user.h at the end of imgui.h as a convenience +// May be convenient for some users to only explicitly include vanilla imgui.h and have extra stuff included. +// #define IMGUI_INCLUDE_IMGUI_USER_H +// #define IMGUI_USER_H_FILENAME "my_folder/my_imgui_user.h" + +//---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another) +// #define IMGUI_USE_BGRA_PACKED_COLOR + +//---- Use 32-bit for ImWchar (default is 16-bit) to support Unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, +//dingbats, symbols, shapes, ancient languages, etc...) #define IMGUI_USE_WCHAR32 + +//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version +// By default the embedded implementations are declared static and not available outside of Dear ImGui sources files. +// #define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" +// #define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" +// #define IMGUI_STB_SPRINTF_FILENAME "my_folder/stb_sprintf.h" // only used if IMGUI_USE_STB_SPRINTF is defined. +// #define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION +// #define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION +// #define IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION // only disabled if IMGUI_USE_STB_SPRINTF is defined. + +//---- Use stb_sprintf.h for a faster implementation of vsnprintf instead of the one from libc (unless +//IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined) +// Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats +// provided by stb_sprintf.h. +// #define IMGUI_USE_STB_SPRINTF + +//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui) +// Requires FreeType headers to be available in the include path. Requires program to be compiled with +// 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided). On Windows you may use vcpkg +// with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'. +#define IMGUI_ENABLE_FREETYPE + +//---- Use FreeType+lunasvg library to render OpenType SVG fonts (SVGinOT) +// Requires lunasvg headers to be available in the include path + program to be linked with the lunasvg library (not provided). +// Only works in combination with IMGUI_ENABLE_FREETYPE. +// (implementation is based on Freetype's rsvg-port.c which is licensed under CeCILL-C Free Software License Agreement) +// #define IMGUI_ENABLE_FREETYPE_LUNASVG + +//---- Use stb_truetype to build and rasterize the font atlas (default) +// The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend. +// #define IMGUI_ENABLE_STB_TRUETYPE + +//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4. +// This will be inlined as part of ImVec2 and ImVec4 class declarations. +/* +#define IM_VEC2_CLASS_EXTRA \ + constexpr ImVec2(const MyVec2& f) : x(f.x), y(f.y) {} \ + operator MyVec2() const { return MyVec2(x,y); } + +#define IM_VEC4_CLASS_EXTRA \ + constexpr ImVec4(const MyVec4& f) : x(f.x), y(f.y), z(f.z), w(f.w) {} \ + operator MyVec4() const { return MyVec4(x,y,z,w); } +*/ +//---- ...Or use Dear ImGui's own very basic math operators. +// #define IMGUI_DEFINE_MATH_OPERATORS + +//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices. +// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices). +// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer. +// Read about ImGuiBackendFlags_RendererHasVtxOffset for details. +// #define ImDrawIdx unsigned int + +//---- Override ImDrawCallback signature (will need to modify renderer backends accordingly) +// struct ImDrawList; +// struct ImDrawCmd; +// typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data); +// #define ImDrawCallback MyImDrawCallback + +//---- Debug Tools: Macro to break in Debugger (we provide a default implementation of this in the codebase) +// (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.) +// #define IM_DEBUG_BREAK IM_ASSERT(0) +// #define IM_DEBUG_BREAK __debugbreak() + +//---- Debug Tools: Enable slower asserts +// #define IMGUI_DEBUG_PARANOID + +//---- Tip: You can add extra functions within the ImGui:: namespace from anywhere (e.g. your own sources/header files) +/* +namespace ImGui +{ + void MyFunction(const char* name, MyMatrix44* mtx); +} +*/ diff --git a/samples/jsmn.h b/samples/jsmn.h new file mode 100644 index 0000000..8ac14c1 --- /dev/null +++ b/samples/jsmn.h @@ -0,0 +1,471 @@ +/* + * 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 */ diff --git a/samples/main.cpp b/samples/main.cpp new file mode 100644 index 0000000..f8fa767 --- /dev/null +++ b/samples/main.cpp @@ -0,0 +1,356 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +// CRT's memory leak detection +#if defined( _WIN64 ) +#ifndef _CRTDBG_MAP_ALLOC +#define _CRTDBG_MAP_ALLOC +#endif +#include +#endif + +// clang-format off +#include "glad/glad.h" +#include "GLFW/glfw3.h" +// clang-format on + +#include "font.h" +#include "imgui.h" +#include "imgui_impl_glfw.h" +#include "imgui_impl_opengl3.h" +#include "implot.h" +#include "renderer.h" +#include "sample.h" +#include "shader.h" + +#include + +#ifdef TRACY_ENABLE +#include +#endif + +// imgui notes +// high-dpi support: https://github.com/ocornut/imgui/issues/5081 +// linear blending: +// http://arkanis.de/weblog/2023-08-14-simple-good-quality-subpixel-text-rendering-in-opengl-with-stb-truetype-and-dual-source-blending + +inline bool IsPowerOfTwo( int32_t x ) +{ + return ( x != 0 ) && ( ( x & ( x - 1 ) ) == 0 ); +} + +void* AllocFcn( int32_t 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 ) + void* ptr = _aligned_malloc( sizeAligned, alignment ); +#else + void* ptr = aligned_alloc( alignment, sizeAligned ); +#endif + assert( ptr != nullptr ); + return ptr; +} + +void FreeFcn( void* mem ) +{ +#if defined( _MSC_VER ) + _aligned_free( mem ); +#else + free( mem ); +#endif +} + +static int AssertHandler( const char* cond, const char* file, int line ) +{ + printf( "Box3D Assert: %s, %s, line %d\n", cond, file, line ); + return 1; +} + +#define WINDOW_TITLE "Box3D v0.1.0" + +static int s_windowWidth = 1920; +static int s_windowHeight = 1080; +static int s_bufferWidth = s_windowWidth; +static int s_bufferHeight = s_windowHeight; + +Font* s_font = nullptr; +SampleManager s_manager; + +static void WindowSizeCallback( GLFWwindow* window, int width, int height ) +{ + s_windowWidth = width; + s_windowHeight = height; + glfwGetFramebufferSize( window, &s_bufferWidth, &s_bufferHeight ); + s_manager.Resize( s_windowWidth, s_windowHeight, s_bufferWidth, s_bufferHeight ); +} + +static void ErrorCallback( int error, const char* description ) +{ + // Report GLFW error + printf( "GLFW Error %d: %s", error, description ); +} + +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; + } + + s_manager.Keyboard( key, action, mods ); +} + +void CharCallback( GLFWwindow* window, unsigned int character ) +{ + ImGui_ImplGlfw_CharCallback( window, character ); +} + +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 ); + + b3Vec2 ps = { float( xd ), float( yd ) }; + + // Use the mouse to move things around. + if ( button == GLFW_MOUSE_BUTTON_1 ) + { + if ( action == GLFW_PRESS ) + { + s_manager.m_sample->MouseDown( ps, button, modifiers ); + } + + if ( action == GLFW_RELEASE ) + { + s_manager.m_sample->MouseUp( ps, button ); + } + } +} + +static void MouseMotionCallback( GLFWwindow* window, double x, double y ) +{ + b3Vec2 ps = { float( x ), float( y ) }; + + ImGui_ImplGlfw_CursorPosCallback( window, ps.x, ps.y ); + + s_manager.m_sample->MouseMove( ps ); +} + +static void ScrollCallback( GLFWwindow* window, double deltaX, double deltaY ) +{ + ImGui_ImplGlfw_ScrollCallback( window, deltaX, deltaY ); +} + +static void Startup( GLFWwindow* window ) +{ + // Initialize font + s_font = Font::Create( &s_manager.m_context.camera, "data/fonts/Roboto-Medium.ttf", 18.0f ); + + if ( s_font == nullptr ) + { + exit( EXIT_FAILURE ); + } + + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImPlot::CreateContext(); + + // Setup Platform/Renderer bindings + ImGui_ImplGlfw_InitForOpenGL( window, false ); + ImGui_ImplOpenGL3_Init(); + + ImGuiIO& io = ImGui::GetIO(); + io.Fonts->AddFontFromFileTTF( "data/fonts/Roboto-Medium.ttf", 16.0f ); + + // Initialize test manager + s_manager.Startup( window, s_windowWidth, s_windowHeight, s_bufferWidth, s_bufferHeight ); +} + +static void Render( GLFWwindow* window, float elapsedTime ) +{ + // Start the Dear ImGui frame + ImGui_ImplOpenGL3_NewFrame(); + ImGui_ImplGlfw_NewFrame(); + + ImGui::NewFrame(); + + glViewport( 0, 0, s_bufferWidth, s_bufferHeight ); + + glClearColor( 0.3f, 0.3f, 0.3f, 1.0f ); + glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); + + s_manager.Render( window, elapsedTime ); + + int y = s_windowHeight - 10; + + int triangleIndex = s_manager.m_sample->m_triangleIndex; + uint64_t materialId = s_manager.m_sample->m_userMaterialId; + + const Camera* camera = &s_manager.m_context.camera; + static char buffer[128]; + snprintf( buffer, 128, "%.1f ms - step %d - camera (%g, %g, %g, %g) - tri %d - mat %d", 1000.0f * elapsedTime, s_manager.m_sample->m_stepCount, + camera->m_yaw, camera->m_pitch, camera->m_radius, camera->m_speed, triangleIndex, (int)materialId ); + DrawText( 10, y, b3_colorLightGray, buffer ); + + if ( s_font != nullptr ) + { + s_font->Flush(); + } + + //ImGui::ShowDemoWindow(); + //ImPlot::ShowDemoWindow(); + + ImGui::Render(); + ImGui_ImplOpenGL3_RenderDrawData( ImGui::GetDrawData() ); + + // Platform functions may have changed the current OpenGL context + glfwMakeContextCurrent( window ); + glfwSwapBuffers( window ); +} + +static void Shutdown( GLFWwindow* window ) +{ + // Shutdown test manager + s_manager.Shutdown( window ); + + ImGui_ImplOpenGL3_Shutdown(); + ImGui_ImplGlfw_Shutdown(); + ImPlot::DestroyContext(); + ImGui::DestroyContext(); + + delete s_font; + s_font = nullptr; +} + +int main() +{ +#if defined( _WIN64 ) + // Enable run-time memory check for debug builds + // 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. + // https://learn.microsoft.com/en-us/troubleshoot/developer/visualstudio/cpp/libraries/use-rtbreakalloc-debug-memory-allocation + //_CrtSetBreakAlloc(1392); + _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE ); + _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT ); + //_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); +#endif + +#ifdef TRACY_ENABLE + tracy::StartupProfiler(); +#endif + + b3SetAllocator( AllocFcn, FreeFcn ); + b3SetAssertFcn( AssertHandler ); + + // Initialize GLFW + glfwSetErrorCallback( ErrorCallback ); + if ( !glfwInit() ) + { + fprintf( stderr, "Failed to initialize GLFW\n" ); + return -1; + } + + // Create OpenGL window + glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 4 ); + glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 1 ); + glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE ); + + // MSAA + glfwWindowHint( GLFW_SAMPLES, 4 ); + + GLFWwindow* window = glfwCreateWindow( s_windowWidth, s_windowHeight, WINDOW_TITLE, nullptr, nullptr ); + if ( window == nullptr ) + { + glfwTerminate(); + return -1; + } + + glfwGetWindowSize( window, &s_windowWidth, &s_windowHeight ); + glfwGetFramebufferSize( window, &s_bufferWidth, &s_bufferHeight ); + + // Set window callbacks + glfwSetKeyCallback( window, KeyCallback ); + glfwSetCharCallback( window, CharCallback ); + glfwSetCursorPosCallback( window, MouseMotionCallback ); + glfwSetMouseButtonCallback( window, MouseButtonCallback ); + glfwSetScrollCallback( window, ScrollCallback ); + glfwSetWindowSizeCallback( window, WindowSizeCallback ); + + // Make OpenGL context current + glfwMakeContextCurrent( window ); + + // This enables v-sync + // glfwSwapInterval( 1 ); + + // Setup GLAD bindings + 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 ); + } + + Startup( window ); + + glEnable( GL_DEPTH_TEST ); + + float frameTime = 0.0f; + while ( !glfwWindowShouldClose( window ) ) + { + glfwPollEvents(); + + if (s_manager.m_context.minimized) + { + continue; + } + + double time1 = glfwGetTime(); + + s_manager.Step(); + Render( window, frameTime ); + + // Limit frame rate to 60Hz + double time2 = glfwGetTime(); + double targetTime = time1 + 1.0 / 60.0; + while ( time2 < targetTime ) + { + b3Yield(); + time2 = glfwGetTime(); + } + + frameTime = float( time2 - time1 ); + } + + Shutdown( window ); + + glfwDestroyWindow( window ); + glfwTerminate(); + +#ifdef TRACY_ENABLE + tracy::ShutdownProfiler(); +#endif + +#if defined( _WIN64 ) + _CrtDumpMemoryLeaks(); +#endif + + return 0; +} diff --git a/samples/mesh_loader.cpp b/samples/mesh_loader.cpp new file mode 100644 index 0000000..d31d307 --- /dev/null +++ b/samples/mesh_loader.cpp @@ -0,0 +1,172 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "mesh_loader.h" + +#include "box3d/collision.h" +#include "box3d/math_functions.h" + +#define TINYOBJLOADER_IMPLEMENTATION +#define TINYOBJLOADER_USE_MAPBOX_EARCUT +#include "tiny_obj_loader.h" + +#include + +// Load a wavefront obj file using tiny obj loader and earcut for triangulation. +void LoadTempMesh( const char* path, TempMesh* tempMesh, float scale, bool zUp ) +{ + std::string inputFile = path; + tinyobj::ObjReaderConfig readerConfig; + readerConfig.triangulate = true; + readerConfig.mtl_search_path = "./"; // Path to material files + + tinyobj::ObjReader reader; + + if ( !reader.ParseFromFile( inputFile, readerConfig ) ) + { + if ( !reader.Error().empty() ) + { + std::cerr << "TinyObjReader: " << reader.Error(); + } + exit( 1 ); + } + + if ( !reader.Warning().empty() ) + { + std::cout << "TinyObjReader: " << reader.Warning(); + } + + const tinyobj::attrib_t& attrib = reader.GetAttrib(); + const std::vector& shapes = reader.GetShapes(); + // const std::vector& objMaterials = reader.GetMaterials(); + + tempMesh->vertices.clear(); + tempMesh->indices.clear(); + tempMesh->materialIndices.clear(); + + int vertexCount = int( attrib.vertices.size() / 3 ); + for ( int i = 0; i < vertexCount; i++ ) + { + float x = scale * attrib.vertices[3 * i + 0]; + float y = scale * attrib.vertices[3 * i + 1]; + float z = scale * attrib.vertices[3 * i + 2]; + b3Vec3 vertex = zUp ? b3Vec3{ y, z, x } : b3Vec3{ x, y, z }; + tempMesh->vertices.push_back( vertex ); + } + + // Loop over shapes + int shapeCount = (int)shapes.size(); + int materialIndex = 0; + for ( int shapeIndex = 0; shapeIndex < shapeCount; ++shapeIndex ) + { + int faceCount = (int)shapes[shapeIndex].mesh.num_face_vertices.size(); + int baseIndex = 0; + for ( int faceIndex = 0; faceIndex < faceCount; ++faceIndex ) + { + int faceVertexCount = (int)shapes[shapeIndex].mesh.num_face_vertices[faceIndex]; + + // todo only triangles for now + if ( faceVertexCount != 3 ) + { + baseIndex += faceVertexCount; + continue; + } + + for ( int vertexIndex = 0; vertexIndex < faceVertexCount; ++vertexIndex ) + { + tinyobj::index_t idx = shapes[shapeIndex].mesh.indices[baseIndex + vertexIndex]; + tempMesh->indices.push_back( idx.vertex_index ); + } + + tempMesh->materialIndices.push_back( materialIndex ); + materialIndex = ( materialIndex + 1 ) % 3; + + baseIndex += faceVertexCount; + } + } +} + +b3MeshData* CreateMeshData( const char* path, float scale, bool zUp, bool useMedianSplit, bool identifyConvexEdges, bool weldVertices ) +{ + std::string inputFile = path; + tinyobj::ObjReaderConfig readerConfig; + readerConfig.triangulate = true; + readerConfig.mtl_search_path = "./"; // Path to material files + + tinyobj::ObjReader reader; + + if ( !reader.ParseFromFile( inputFile, readerConfig ) ) + { + if ( !reader.Error().empty() ) + { + std::cerr << "TinyObjReader: " << reader.Error(); + } + exit( 1 ); + } + + if ( !reader.Warning().empty() ) + { + std::cout << "TinyObjReader: " << reader.Warning(); + } + + const tinyobj::attrib_t& attrib = reader.GetAttrib(); + const std::vector& shapes = reader.GetShapes(); + // const std::vector& objMaterials = reader.GetMaterials(); + + TempMesh mesh; + + int vertexCount = int( attrib.vertices.size() / 3 ); + for ( int i = 0; i < vertexCount; i++ ) + { + float x = scale * attrib.vertices[3 * i + 0]; + float y = scale * attrib.vertices[3 * i + 1]; + float z = scale * attrib.vertices[3 * i + 2]; + b3Vec3 vertex = zUp ? b3Vec3{ y, z, x } : b3Vec3{ x, y, z }; + mesh.vertices.push_back( vertex ); + } + + // Loop over shapes + int shapeCount = (int)shapes.size(); + int materialIndex = 0; + for ( int shapeIndex = 0; shapeIndex < shapeCount; ++shapeIndex ) + { + int faceCount = (int)shapes[shapeIndex].mesh.num_face_vertices.size(); + int baseIndex = 0; + for ( int faceIndex = 0; faceIndex < faceCount; ++faceIndex ) + { + int faceVertexCount = (int)shapes[shapeIndex].mesh.num_face_vertices[faceIndex]; + + // todo only triangles for now + if ( faceVertexCount != 3 ) + { + baseIndex += faceVertexCount; + continue; + } + + for ( int vertexIndex = 0; vertexIndex < faceVertexCount; ++vertexIndex ) + { + tinyobj::index_t idx = shapes[shapeIndex].mesh.indices[baseIndex + vertexIndex]; + mesh.indices.push_back( idx.vertex_index ); + } + + mesh.materialIndices.push_back( materialIndex ); + materialIndex = ( materialIndex + 1 ) % 3; + + baseIndex += faceVertexCount; + } + } + + b3MeshDef def = {}; + def.vertices = mesh.vertices.data(); + def.vertexCount = (int)mesh.vertices.size(); + def.indices = mesh.indices.data(); + def.triangleCount = (int)mesh.indices.size() / 3; + def.materialIndices = mesh.materialIndices.data(); + def.useMedianSplit = useMedianSplit; + def.identifyEdges = identifyConvexEdges; + def.weldVertices = weldVertices; + def.weldTolerance = 0.002f; + + b3MeshData* meshData = b3CreateMesh( &def, nullptr, 0 ); + return meshData; +} diff --git a/samples/mesh_loader.h b/samples/mesh_loader.h new file mode 100644 index 0000000..d91dad6 --- /dev/null +++ b/samples/mesh_loader.h @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "box3d/math_functions.h" + +#include + +struct b3MeshData; +b3MeshData* CreateMeshData( const char* path, float scale, bool zUp, bool useMedianSplit, bool identifyConvexEdges, + bool weldVertices ); + +struct TempMesh +{ + std::vector vertices; + std::vector indices; + std::vector materialIndices; +}; + +void LoadTempMesh( const char* path, TempMesh* tempMesh, float scale, bool zUp ); diff --git a/samples/renderer.cpp b/samples/renderer.cpp new file mode 100644 index 0000000..5373313 --- /dev/null +++ b/samples/renderer.cpp @@ -0,0 +1,783 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "renderer.h" + +#include "camera.h" +#include "font.h" +#include "sample.h" +#include "scene.h" +#include "shader.h" + +#include "box3d/collision.h" +#include "box3d/math_functions.h" + +// clang-format off +#include +#include +// clang-format on + +#include "box3d/box3d.h" + +#include +#include +#include +#include +#include + +struct PointData +{ + b3Vec3 position; + float size; + RGBA8 rgba; +}; + +struct PointDraw +{ + enum + { + e_batchSize = 2048 + }; + + std::vector Points; + + uint32_t programId; + + uint32_t vaoId; + uint32_t vboId; + + int ProjectionUniform; + int ViewUniform; + int SizeUniform; +}; + +PointDraw* CreateDebugPoints() +{ + const char* vs = R"( + #version 330 core + uniform mat4 projection; + uniform mat4 view; + layout(location = 0) in vec3 point; + layout(location = 1) in vec4 color; + layout(location = 2) in float size; + out vec4 f_color; + void main(void) + { + gl_Position = projection * view * vec4(point, 1.0f); + f_color = color; + gl_PointSize = size; + } + )"; + + const char* fs = R"( + #version 330 core + in vec4 f_color; + out vec4 color; + void main(void) + { + color = f_color; + } + )"; + + PointDraw* draw = new PointDraw; + + draw->programId = CreateProgramFromStrings( vs, fs ); + draw->ProjectionUniform = GetUniformLocation( draw->programId, "projection" ); + draw->ViewUniform = GetUniformLocation( draw->programId, "view" ); + + constexpr int vertexAttribute = 0; + constexpr int sizeAttribute = 1; + constexpr int colorAttribute = 2; + + // Generate + glGenVertexArrays( 1, &draw->vaoId ); + glGenBuffers( 1, &draw->vboId ); + + glBindVertexArray( draw->vaoId ); + glEnableVertexAttribArray( vertexAttribute ); + glEnableVertexAttribArray( sizeAttribute ); + glEnableVertexAttribArray( colorAttribute ); + + // Vertex buffer + glBindBuffer( GL_ARRAY_BUFFER, draw->vboId ); + + glBufferData( GL_ARRAY_BUFFER, PointDraw::e_batchSize * sizeof( PointData ), nullptr, GL_DYNAMIC_DRAW ); + + glVertexAttribPointer( vertexAttribute, 3, GL_FLOAT, GL_FALSE, sizeof( PointData ), (void*)offsetof( PointData, position ) ); + glVertexAttribPointer( colorAttribute, 4, GL_FLOAT, GL_FALSE, sizeof( PointData ), (void*)offsetof( PointData, size ) ); + // save bandwidth by expanding color to floats in the shader + glVertexAttribPointer( sizeAttribute, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( PointData ), (void*)offsetof( PointData, rgba ) ); + + CheckOpenGL(); + + // Cleanup + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + + return draw; +} + +void DestroyDebugPoints( PointDraw* draw ) +{ + if ( draw->vaoId ) + { + glDeleteVertexArrays( 1, &draw->vaoId ); + glDeleteBuffers( 1, &draw->vboId ); + draw->vaoId = 0; + } + + DestroyShader( draw->programId ); + draw->programId = 0; + + delete draw; +} + +void AddPoint( PointDraw* draw, b3Vec3 point, float size, b3HexColor color ) +{ + draw->Points.push_back( { point, size, MakeRGBA8( color ) } ); +} + +void FlushPoints( PointDraw* draw, Camera* camera ) +{ + if ( draw->Points.size() == 0 ) + { + return; + } + + glDepthFunc( GL_LEQUAL ); + + glUseProgram( draw->programId ); + + Matrix4 projection = camera->GetProjectionMatrix(); + Matrix4 view = camera->GetViewMatrix(); + + SetUniformMatrix4( draw->ProjectionUniform, projection ); + SetUniformMatrix4( draw->ViewUniform, view ); + + glBindVertexArray( draw->vaoId ); + + int totalCount = (int)draw->Points.size(); + PointData* points = draw->Points.data(); + + while ( totalCount > 0 ) + { + int count = b3MinInt( totalCount, PointDraw::e_batchSize ); + + glBindBuffer( GL_ARRAY_BUFFER, draw->vboId ); + // todo macOS optimization? + // glBufferData( GL_ARRAY_BUFFER, PointDraw::e_batchSize * sizeof( PointData ), nullptr, GL_DYNAMIC_DRAW ); + glBufferSubData( GL_ARRAY_BUFFER, 0, count * sizeof( PointData ), points ); + + glEnable( GL_PROGRAM_POINT_SIZE ); + glDrawArrays( GL_POINTS, 0, count ); + glDisable( GL_PROGRAM_POINT_SIZE ); + + points += count; + totalCount -= count; + } + + CheckOpenGL(); + + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + glUseProgram( 0 ); + + draw->Points.clear(); +} + +struct LinePoint +{ + b3Vec3 position; + RGBA8 rgba; +}; + +struct LineDraw +{ + enum + { + e_batchSize = 2048 + }; + + std::vector points; + + uint32_t programId; + + uint32_t VaoId; + uint32_t VboId; + + int ProjectionUniform; + int ViewUniform; +}; + +LineDraw* CreateDebugLines() +{ + const char* vs = R"( + #version 330 core + uniform mat4 projection; + uniform mat4 view; + layout(location = 0) in vec3 point; + layout(location = 1) in vec4 color; + out vec4 f_color; + void main(void) + { + gl_Position = projection * view * vec4(point, 1.0f); + f_color = color; + } + )"; + + const char* fs = R"( + #version 330 core + in vec4 f_color; + out vec4 color; + void main(void) + { + color = f_color; + } + )"; + + LineDraw* draw = new LineDraw; + + draw->programId = CreateProgramFromStrings( vs, fs ); + draw->ProjectionUniform = GetUniformLocation( draw->programId, "projection" ); + draw->ViewUniform = GetUniformLocation( draw->programId, "view" ); + + constexpr int vertexAttribute = 0; + constexpr int colorAttribute = 1; + + // Generate + glGenVertexArrays( 1, &draw->VaoId ); + glGenBuffers( 1, &draw->VboId ); + + glBindVertexArray( draw->VaoId ); + glEnableVertexAttribArray( vertexAttribute ); + glEnableVertexAttribArray( colorAttribute ); + + // Vertex buffer + glBindBuffer( GL_ARRAY_BUFFER, draw->VboId ); + glBufferData( GL_ARRAY_BUFFER, LineDraw::e_batchSize * sizeof( LinePoint ), nullptr, GL_DYNAMIC_DRAW ); + + glVertexAttribPointer( vertexAttribute, 3, GL_FLOAT, GL_FALSE, sizeof( LinePoint ), + (void*)offsetof( LinePoint, position ) ); + // save bandwidth by expanding color to floats in the shader + glVertexAttribPointer( colorAttribute, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( LinePoint ), + (void*)offsetof( LinePoint, rgba ) ); + + CheckOpenGL(); + + // Cleanup + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + + return draw; +} + +void DestroyDebugLines( LineDraw* draw ) +{ + if ( draw->VaoId ) + { + glDeleteVertexArrays( 1, &draw->VaoId ); + glDeleteBuffers( 1, &draw->VboId ); + draw->VaoId = 0; + } + + DestroyShader( draw->programId ); + draw->programId = 0; + + delete draw; +} + +void AddLine( LineDraw* draw, b3Vec3 point1, b3Vec3 point2, b3HexColor color ) +{ + draw->points.push_back( { point1, MakeRGBA8( color ) } ); + draw->points.push_back( { point2, MakeRGBA8( color ) } ); +} + +void FlushLines( LineDraw* draw, Camera* camera ) +{ + if ( draw->points.size() == 0 ) + { + return; + } + + // WARNING: very slow + //glEnable( GL_LINE_SMOOTH ); + + glEnable( GL_BLEND ); + glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + + glUseProgram( draw->programId ); + + Matrix4 projection = camera->GetProjectionMatrix(); + Matrix4 view = camera->GetViewMatrix(); + + SetUniformMatrix4( draw->ProjectionUniform, projection ); + SetUniformMatrix4( draw->ViewUniform, view ); + + glBindVertexArray( draw->VaoId ); + glBindBuffer( GL_ARRAY_BUFFER, draw->VboId ); + + int count = (int)draw->points.size(); + LinePoint* points = draw->points.data(); + + while ( count > 0 ) + { + int batchCount = b3MinInt( count, LineDraw::e_batchSize ); + + // todo buffer orphaning for macOS? + // glBufferData( GL_ARRAY_BUFFER, LineDraw::e_batchSize * sizeof( LinePoint ), nullptr, GL_DYNAMIC_DRAW ); + glBufferSubData( GL_ARRAY_BUFFER, 0, batchCount * sizeof( LinePoint ), points ); + glDrawArrays( GL_LINES, 0, batchCount ); + + points += batchCount; + count -= batchCount; + } + + CheckOpenGL(); + + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + glUseProgram( 0 ); + glDisable( GL_BLEND ); + + draw->points.clear(); +} + +static DebugShape* CreateDebugSphere( const b3Sphere* sphere ) +{ + DebugShape* s = new DebugShape; + s->type = DebugShapeType::sphere; + s->sphere.center = sphere->center; + s->sphere.radius = sphere->radius; + return s; +} + +static DebugShape* CreateDebugCapsule( const b3Capsule* capsule, Arena arena ) +{ + DebugShape* s = new DebugShape; + s->type = DebugShapeType::capsule; + s->capsule.center1 = capsule->center1; + s->capsule.center2 = capsule->center2; + s->capsule.radius = capsule->radius; + return s; +} + +static DebugShape* CreateDebugCompound(Scene* scene, const b3Compound* compound, Arena arena ) +{ + DebugShape* s = new DebugShape; + memset( s, 0, sizeof( DebugShape ) ); + s->type = DebugShapeType::compound; + + // Capsules + s->compound.capsuleCount = compound->capsuleCount; + DebugCapsule* debugCapsules = new DebugCapsule[s->compound.capsuleCount]; + for (int i = 0; i < s->compound.capsuleCount; ++i) + { + b3CompoundCapsule element = b3GetCompoundCapsule( compound, i ); + + debugCapsules[i].center1 = element.capsule.center1; + debugCapsules[i].center2 = element.capsule.center2; + debugCapsules[i].radius = element.capsule.radius; + } + s->compound.capsules = debugCapsules; + + // Hulls + s->compound.hullCount = compound->hullCount; + DebugHull* debugHulls = new DebugHull[s->compound.hullCount]; + for (int i = 0; i < s->compound.hullCount; ++i) + { + b3CompoundHull hull = b3GetCompoundHull( compound, i ); + + uint32_t id = CreateInstanceHull( scene, hull.hull, arena ); + debugHulls[i].transform = hull.transform; + debugHulls[i].id = id; + } + s->compound.hulls = debugHulls; + + // Meshes + s->compound.meshCount = compound->meshCount; + DebugMesh* debugMeshes = new DebugMesh[s->compound.meshCount]; + for ( int i = 0; i < s->compound.meshCount; ++i ) + { + b3CompoundMesh mesh = b3GetCompoundMesh( compound, i ); + + uint32_t id = CreateInstanceMesh( scene, mesh.meshData, arena ); + debugMeshes[i].transform = mesh.transform; + debugMeshes[i].scale = mesh.scale; + debugMeshes[i].id = id; + } + s->compound.meshes = debugMeshes; + + // Spheres + s->compound.sphereCount = compound->sphereCount; + DebugSphere* debugSpheres = new DebugSphere[s->compound.sphereCount]; + for (int i = 0; i < s->compound.sphereCount; ++i) + { + b3CompoundSphere sphere = b3GetCompoundSphere( compound, i ); + debugSpheres[i].center = sphere.sphere.center; + debugSpheres[i].radius = sphere.sphere.radius; + } + s->compound.spheres = debugSpheres; + + return s; +} + +static void DestroyDebugCompound( DebugCompound* compound ) +{ + delete[] compound->capsules; + delete[] compound->hulls; + delete[] compound->meshes; + delete[] compound->spheres; +} + +static DebugShape* CreateDebugHull( Scene* scene, const b3Hull* hull, Arena arena ) +{ + uint32_t id = CreateInstanceHull( scene, hull, arena ); + + DebugShape* s = new DebugShape; + s->type = DebugShapeType::hull; + s->hull.id = id; + s->hull.transform = b3Transform_identity; + return s; +} + +static DebugShape* CreateDebugMesh( Scene* scene, const b3Mesh* mesh, Arena arena ) +{ + uint32_t id = CreateInstanceMesh( scene, mesh->data, arena ); + + DebugShape* s = new DebugShape; + s->type = DebugShapeType::mesh; + s->mesh.id = id; + s->mesh.transform = b3Transform_identity; + s->mesh.scale = mesh->scale; + return s; +} + +static DebugShape* CreateDebugHeightField( Scene* scene, const b3HeightField* heightField, Arena arena ) +{ + uint32_t id = CreateInstanceHeightField( scene, heightField, arena ); + + DebugShape* s = new DebugShape; + s->type = DebugShapeType::heightField; + s->heightField.id = id; + return s; +} + +void* CreateDebugShape( const b3DebugShape* debugShape, void* context ) +{ + SampleContext* sampleContext = static_cast( context ); + DebugShape* s = nullptr; + switch ( debugShape->type ) + { + case b3_capsuleShape: + s = CreateDebugCapsule( debugShape->capsule, sampleContext->arena ); + break; + + case b3_compoundShape: + s = CreateDebugCompound( sampleContext->scene, debugShape->compound, sampleContext->arena ); + break; + + case b3_hullShape: + s = CreateDebugHull( sampleContext->scene, debugShape->hull, sampleContext->arena ); + break; + + case b3_meshShape: + s = CreateDebugMesh( sampleContext->scene, debugShape->mesh, sampleContext->arena ); + break; + + case b3_heightShape: + s = CreateDebugHeightField( sampleContext->scene, debugShape->heightField, sampleContext->arena ); + break; + + case b3_sphereShape: + s = CreateDebugSphere( debugShape->sphere ); + break; + + default: + break; + } + + if (s != nullptr) + { + b3BodyId bodyId = b3Shape_GetBody( debugShape->shapeId ); + s->bodyType = b3Body_GetType( bodyId ); + } + else + { + s->bodyType = b3_staticBody; + } + + return s; +} + +void DestroyDebugShape( void* userShape, void* context ) +{ + DebugShape* s = static_cast( userShape ); + switch ( s->type ) + { + case DebugShapeType::compound: + DestroyDebugCompound( &s->compound ); + break; + + default: + break; + } + + delete s; +} + +extern Font* s_font; +void DrawText( int x, int y, b3HexColor color, const char* text ) +{ + s_font->AddText( x, y, color, text ); +} + +void DrawFormat( int x, int y, b3HexColor color, const char* format, ... ) +{ + va_list args; + va_start( args, format ); + char text[512]; + vsnprintf( text, sizeof( text ), format, args ); + DrawText( x, y, color, text ); + va_end( args ); +} + +void DrawWorldString( Camera* camera, b3Vec3 point, b3HexColor color, const char* format, ... ) +{ + float x, y; + bool valid = camera->WorldToScreen( x, y, point ); + if ( valid ) + { + va_list args; + va_start( args, format ); + char text[512]; + vsnprintf( text, sizeof( text ), format, args ); + DrawText( (int)x, (int)y, color, text ); + va_end( args ); + } +} + +static void DrawDisc( Scene* scene, b3Vec3 center, b3Vec3 normal, float radius, b3HexColor color ) +{ + b3Vec3 tangent1 = b3Perp( normal ); + b3Vec3 tangent2 = b3Cross( normal, tangent1 ); + + int n = 9; + float delta = B3_PI / (float)n; + b3CosSin cs = b3ComputeCosSin( delta ); + float x1 = radius, y1 = 0.0f; + b3Vec3 vertex1 = center + x1 * tangent1 + y1 * tangent2; + + for ( int i = 0; i < 2 * n; ++i ) + { + float x2 = cs.cosine * x1 - cs.sine * y1; + float y2 = cs.sine * x1 + cs.cosine * y1; + b3Vec3 vertex2 = center + x2 * tangent1 + y2 * tangent2; + + DrawLine( scene, vertex1, vertex2, color ); + + x1 = x2; + y1 = y2; + vertex1 = vertex2; + } +} + +static void DrawArc( Scene* scene, b3Vec3 center, b3Vec3 normal, float radius, b3Vec3 start, float maxAngle, b3HexColor color ) +{ + b3Vec3 tangent1 = b3Normalize( start ); + b3Vec3 tangent2 = b3Cross( normal, tangent1 ); + + for ( float angle = 0.0f; angle < maxAngle; angle += 5.0f ) + { + float alpha1 = B3_DEG_TO_RAD * ( angle + 0.0f ); + b3Vec3 vertex1 = center + b3Cos( alpha1 ) * radius * tangent1 + b3Sin( alpha1 ) * radius * tangent2; + float alpha2 = B3_DEG_TO_RAD * ( angle + 5.0f ); + b3Vec3 vertex2 = center + b3Cos( alpha2 ) * radius * tangent1 + b3Sin( alpha2 ) * radius * tangent2; + + DrawLine( scene, vertex1, vertex2, color ); + } +} + +void DrawGrid( Scene* scene, int size ) +{ + float grid = float( size ); + + for ( int x = -size; x <= size; ++x ) + { + if ( x == 0 ) + { + DrawLine( scene, { 0.0f, 0.0f, -grid }, { 0.0f, 0.0f, 0.0f }, b3_colorLightGray ); + DrawLine( scene, { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, grid }, b3_colorBlue ); + } + else if ( ( x % 10 ) == 0 ) + { + DrawLine( scene, { float( x ), 0.0f, -grid }, { float( x ), 0.0f, grid }, b3_colorDarkGray ); + } + else + { + DrawLine( scene, { float( x ), 0.0f, -grid }, { float( x ), 0.0f, grid }, b3_colorGray ); + } + } + + for ( int z = -size; z <= size; ++z ) + { + if ( z == 0 ) + { + DrawLine( scene, { -grid, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, b3_colorLightGray ); + DrawLine( scene, { 0.0f, 0.0f, 0.0f }, { grid, 0.0f, 0.0f }, b3_colorRed ); + } + else if ( ( z % 10 ) == 0 ) + { + DrawLine( scene, { -grid, 0.0f, float( z ) }, { grid, 0.0f, float( z ) }, b3_colorDarkGray ); + } + else + { + DrawLine( scene, { -grid, 0.0f, float( z ) }, { grid, 0.0f, float( z ) }, b3_colorGray ); + } + } +} + +void DrawCross( Scene* scene, b3Vec3 center, float radius, b3HexColor color ) +{ + DrawLine( scene, center - b3Vec3{ radius, 0.0, 0.0f }, center + b3Vec3{ radius, 0.0f, 0.0f }, color ); + DrawLine( scene, center - b3Vec3{ 0.0f, radius, 0.0f }, center + b3Vec3{ 0.0f, radius, 0.0f }, color ); + DrawLine( scene, center - b3Vec3{ 0.0f, 0.0f, radius }, center + b3Vec3{ 0.0f, 0.0f, radius }, color ); +} + +void DrawSphere( Scene* scene, const b3Transform& transform, const b3Sphere& sphere, b3HexColor color ) +{ + b3Vec3 center = b3TransformPoint( transform, sphere.center ); + float radius = sphere.radius; + + b3Vec3 axisX = b3RotateVector( transform.q, { 1.0f, 0.0f, 0.0f } ); + b3Vec3 axisY = b3RotateVector( transform.q, { 0.0f, 1.0f, 0.0f } ); + b3Vec3 axisZ = b3RotateVector( transform.q, { 0.0f, 0.0f, 1.0f } ); + + DrawDisc( scene, center, axisX, radius, color ); + DrawDisc( scene, center, axisY, radius, color ); + DrawDisc( scene, center, axisZ, radius, color ); +} + +void DrawCapsule( Scene* scene, const b3Transform& transform, const b3Capsule& capsule, b3HexColor color ) +{ + b3Vec3 center1 = b3TransformPoint( transform, capsule.center1 ); + b3Vec3 center2 = b3TransformPoint( transform, capsule.center2 ); + float radius = capsule.radius; + + b3Vec3 normal = b3Normalize( center2 - center1 ); + b3Vec3 tangent1 = b3Perp( normal ); + b3Vec3 tangent2 = b3Cross( normal, tangent1 ); + + DrawLine( scene, center1 + radius * tangent1, center2 + radius * tangent1, color ); + DrawLine( scene, center1 + radius * tangent2, center2 + radius * tangent2, color ); + DrawLine( scene, center1 - radius * tangent1, center2 - radius * tangent1, color ); + DrawLine( scene, center1 - radius * tangent2, center2 - radius * tangent2, color ); + + DrawArc( scene, center1, -tangent1, radius, tangent2, 180.0f, color ); + DrawArc( scene, center1, tangent2, radius, tangent1, 180.0f, color ); + DrawArc( scene, center2, tangent1, radius, tangent2, 180.0f, color ); + DrawArc( scene, center2, -tangent2, radius, tangent1, 180.0f, color ); + + DrawDisc( scene, center1, normal, radius, color ); + DrawDisc( scene, center2, normal, radius, color ); +} + +void DrawHull( Scene* scene, const b3Transform& transform, const b3Hull* hull, b3HexColor color, bool drawNormals ) +{ + const b3HullHalfEdge* edges = b3GetHullEdges( hull ); + const b3Vec3* points = b3GetHullPoints( hull ); + + for ( int edgeIndex = 0; edgeIndex < hull->edgeCount; edgeIndex += 2 ) + { + const b3HullHalfEdge* edge = edges + edgeIndex + 0; + const b3HullHalfEdge* twin = edges + edgeIndex + 1; + + b3Vec3 vertex1 = b3TransformPoint( transform, points[edge->origin] ); + b3Vec3 vertex2 = b3TransformPoint( transform, points[twin->origin] ); + + DrawLine( scene, vertex1, vertex2, color ); + } + + if (drawNormals) + { + const b3HullFace* faces = b3GetHullFaces( hull ); + const b3Plane* planes = b3GetHullPlanes( hull ); + int faceCount = hull->faceCount; + + for (int i = 0; i < faceCount; ++i) + { + uint8_t startEdgeIndex = faces[i].edge; + uint8_t edgeIndex = startEdgeIndex; + + int count = 0; + b3Vec3 p1 = b3Vec3_zero; + do + { + const b3HullHalfEdge* edge = edges + edgeIndex; + p1 += points[edge->origin]; + count += 1; + edgeIndex = edge->next; + } + while ( edgeIndex != startEdgeIndex ); + + assert( count > 0 ); + p1 = b3MulSV( 1.0f / count, p1 ); + b3Vec3 p2 = p1 + 0.2f * planes[i].normal; + + p1 = b3TransformPoint( transform, p1 ); + p2 = b3TransformPoint( transform, p2 ); + + DrawLine( scene, p1, p2, b3_colorWhite ); + DrawPoint( scene, p1, 6.0f, b3_colorLime ); + } + } +} + +void DrawEllipsoid( Scene* scene, const b3Transform& transform, b3Vec3 radius, b3HexColor color ) +{ + b3Vec3 ex = { 1.0f, 0.0, 0.0f }; + b3Vec3 ey = { 0.0f, 1.0, 0.0f }; + b3Vec3 ez = { 0.0f, 0.0, 1.0f }; + + for ( float angle = 0.0f; angle < 360.0f; angle += 5.0f ) + { + float alpha1 = B3_DEG_TO_RAD * ( angle + 0.0f ); + float alpha2 = B3_DEG_TO_RAD * ( angle + 5.0f ); + + // XY - Plane + { + b3Vec3 vertex1 = radius * ( b3Cos( alpha1 ) * ex + b3Sin( alpha1 ) * ey ); + b3Vec3 vertex2 = radius * ( b3Cos( alpha2 ) * ex + b3Sin( alpha2 ) * ey ); + vertex1 = b3TransformPoint( transform, vertex1 ); + vertex2 = b3TransformPoint( transform, vertex2 ); + DrawLine( scene, vertex1, vertex2, color ); + } + // XZ - Plane + { + b3Vec3 vertex1 = radius * ( b3Cos( alpha1 ) * ex + b3Sin( alpha1 ) * ez ); + b3Vec3 vertex2 = radius * ( b3Cos( alpha2 ) * ex + b3Sin( alpha2 ) * ez ); + vertex1 = b3TransformPoint( transform, vertex1 ); + vertex2 = b3TransformPoint( transform, vertex2 ); + DrawLine( scene, vertex1, vertex2, color ); + } + // YZ - Plane + { + b3Vec3 vertex1 = radius * ( b3Cos( alpha1 ) * ex + b3Sin( alpha1 ) * ez ); + b3Vec3 vertex2 = radius * ( b3Cos( alpha2 ) * ey + b3Sin( alpha2 ) * ez ); + vertex1 = b3TransformPoint( transform, vertex1 ); + vertex2 = b3TransformPoint( transform, vertex2 ); + DrawLine( scene, vertex1, vertex2, color ); + } + } +} + +void DrawTransform( Scene* scene, const b3Transform& transform, float length ) +{ + b3Vec3 p = transform.p; + b3Vec3 ax = b3RotateVector( transform.q, { 1.0f, 0.0f, 0.0f } ); + b3Vec3 ay = b3RotateVector( transform.q, { 0.0f, 1.0f, 0.0f } ); + b3Vec3 az = b3RotateVector( transform.q, { 0.0f, 0.0f, 1.0f } ); + + DrawLine( scene, p, p + length * ax, b3_colorRed ); + DrawLine( scene, p, p + length * ay, b3_colorGreen ); + DrawLine( scene, p, p + length * az, b3_colorBlue ); +} diff --git a/samples/renderer.h b/samples/renderer.h new file mode 100644 index 0000000..0185677 --- /dev/null +++ b/samples/renderer.h @@ -0,0 +1,44 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "utility.h" + +struct b3Capsule; +struct b3DebugShape; +struct b3Hull; +struct b3MeshData; +struct b3Sphere; + +struct Camera; +struct LineDraw; +struct PointDraw; +struct Scene; + +void* CreateDebugShape( const b3DebugShape* debugShape, void* context ); +void DestroyDebugShape( void* userShape, void* userContext ); + +void DrawText( int x, int y, b3HexColor color, const char* text ); +void DrawFormat( int x, int y, b3HexColor color, const char* format, ... ); +void DrawWorldString( Camera* camera, b3Vec3 point, b3HexColor color, const char* format, ... ); + +void DrawGrid( Scene* scene, int size ); +void DrawCross( Scene* scene, b3Vec3 center, float radius, b3HexColor color ); +void DrawSphere( Scene* scene, const b3Transform& transform, const b3Sphere& sphere, b3HexColor color ); +void DrawCapsule( Scene* scene, const b3Transform& transform, const b3Capsule& capsule, b3HexColor color ); +void DrawHull( Scene* scene, const b3Transform& transform, const b3Hull* hull, b3HexColor color, bool drawNormals ); +void DrawEllipsoid( Scene* scene, const b3Transform& transform, b3Vec3 radius, b3HexColor color ); +void DrawTransform( Scene* scene, const b3Transform& transform, float length ); + +// Debug points +PointDraw* CreateDebugPoints(); +void DestroyDebugPoints( PointDraw* draw ); +void AddPoint( PointDraw* draw, b3Vec3 point, float size, b3HexColor color ); +void FlushPoints( PointDraw* draw, Camera* camera ); + +// Debug lines +LineDraw* CreateDebugLines(); +void DestroyDebugLines( LineDraw* draw ); +void AddLine( LineDraw* draw, b3Vec3 point1, b3Vec3 point2, b3HexColor color ); +void FlushLines( LineDraw* draw, Camera* camera ); diff --git a/samples/sample.cpp b/samples/sample.cpp new file mode 100644 index 0000000..d07b691 --- /dev/null +++ b/samples/sample.cpp @@ -0,0 +1,1757 @@ +// 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 "sample.h" + +#include "camera.h" +#include "imgui.h" +#include "implot.h" +#include "jsmn.h" +#include "renderer.h" +#include "scene.h" +#include "shader.h" +#include "utils.h" + +// clang-format off +#include "glad/glad.h" +#include "GLFW/glfw3.h" +// clang-format on + +#include "human.h" + +#include "box3d/box3d.h" + +#include +#include + +// Load a file. You must free the character array. +static char* ReadFile( int& size, const char* filename ) +{ + FILE* file = fopen( filename, "rb" ); + if ( file == nullptr ) + { + return nullptr; + } + + fseek( file, 0, SEEK_END ); + size = static_cast( ftell( file ) ); + fseek( file, 0, SEEK_SET ); + + if ( size == 0 ) + { + fclose( file ); + return nullptr; + } + + char* data = (char*)malloc( size + 1 ); + fread( data, size, 1, file ); + fclose( file ); + data[size] = 0; + + return data; +} + +static const char* settingsFileName = "settings.ini"; + +void Arena::Create( int byteCount ) +{ + data = (char*)malloc( byteCount ); + capacity = byteCount; + index = 0; +} + +void Arena::Destroy() +{ + free( data ); + data = nullptr; + capacity = 0; + index = 0; +} + +void* Arena::Allocate( int byteCount ) +{ + if ( index + byteCount > capacity ) + { + assert( false ); + return nullptr; + } + + void* mem = data + index; + index += byteCount; + return mem; +} + +void Arena::Clear() +{ + index = 0; +} + +static bool DrawShapeCallback( void* userShape, b3Transform transform, b3HexColor color, void* context ) +{ + DebugShape* shape = (DebugShape*)userShape; + SampleContext* sampleContext = (SampleContext*)context; + float alpha = sampleContext->transparentDynamic && shape->bodyType != b3_staticBody ? 0.6f : 1.0f; + DrawDebugShape( sampleContext->scene, shape, transform, color, alpha ); + return true; +} + +static void DrawPointCallback( b3Vec3 point, float size, b3HexColor color, void* context ) +{ + SampleContext* sampleContext = (SampleContext*)context; + DrawPoint( sampleContext->scene, point, size, color ); +} + +static void DrawLineCallback( b3Vec3 vertex1, b3Vec3 vertex2, b3HexColor color, void* context ) +{ + SampleContext* sampleContext = (SampleContext*)context; + DrawLine( sampleContext->scene, vertex1, vertex2, color ); +} + +static void DrawBoundsCallback( b3AABB bounds, b3HexColor color, void* context ) +{ + SampleContext* sampleContext = (SampleContext*)context; + float extension = 0.0f; + DrawBounds( sampleContext->scene, bounds, extension, color ); +} + +static void DrawBoxCallback( b3Vec3 extents, b3Transform transform, b3HexColor color, void* context ) +{ + SampleContext* sampleContext = (SampleContext*)context; + DrawBox( sampleContext->scene, extents, transform, color ); +} + +static void DrawTransformCallback( b3Transform transform, void* context ) +{ + SampleContext* sampleContext = (SampleContext*)context; + DrawTransform( sampleContext->scene, transform, 0.25f ); +} + +static void DrawSceneTextCallback( b3Vec3 position, const char* text, b3HexColor color, void* context ) +{ + SampleContext* sampleContext = (SampleContext*)context; + DrawWorldString( &sampleContext->camera, position, color, text ); +} + +void SampleContext::Save() +{ + FILE* file = fopen( settingsFileName, "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, " \"drawContacts\": %s,\n", debugDraw.drawContacts ? "true" : "false" ); + fprintf( file, " \"drawImpulses\": %s,\n", debugDraw.drawContactForces ? "true" : "false" ); + fprintf( file, " \"drawBounds\": %s,\n", debugDraw.drawBounds ? "true" : "false" ); + fprintf( file, " \"drawCounters\": %s,\n", drawCounters ? "true" : "false" ); + fprintf( file, " \"drawProfile\": %s,\n", drawProfile ? "true" : "false" ); + fprintf( file, " \"transparent\": %s,\n", transparent ? "true" : "false" ); + fprintf( file, " \"enableSleep\": %s\n", enableSleep ? "true" : "false" ); + fprintf( file, " \"enableContinuous\": %s,\n", enableContinuous ? "true" : "false" ); + fprintf( file, "}\n" ); + fclose( file ); +} + +#define MAX_TOKENS 32 + +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 SampleContext::Load() +{ + debugDraw = b3DefaultDebugDraw(); + debugDraw.DrawShapeFcn = DrawShapeCallback; + debugDraw.DrawSegmentFcn = DrawLineCallback; + debugDraw.DrawPointFcn = DrawPointCallback; + debugDraw.DrawBoundsFcn = DrawBoundsCallback; + debugDraw.DrawBoxFcn = DrawBoxCallback; + debugDraw.DrawTransformFcn = DrawTransformCallback; + debugDraw.DrawStringFcn = DrawSceneTextCallback; + debugDraw.context = this; + + recycleDistance = B3_CONTACT_RECYCLE_DISTANCE; + + int size = 0; + char* data = ReadFile( size, settingsFileName ); + if ( data == nullptr ) + { + return; + } + + jsmn_parser parser; + jsmntok_t tokens[MAX_TOKENS]; + + jsmn_init( &parser ); + + 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 ); + + if ( sampleIndex < 0 ) + { + sampleIndex = 0; + } + else if ( sampleIndex >= SampleManager::sEntryCount ) + { + sampleIndex = SampleManager::sEntryCount - 1; + } + } + 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; + } + } + } + + free( data ); +} + +Sample::Sample( SampleContext* context ) +{ + m_context = context; + m_window = context->window; + m_scene = m_context->scene; + m_camera = &m_context->camera; + + m_worldId = b3_nullWorldId; + + m_mouseBodyId = {}; + m_mouseJointId = {}; + m_mouseFraction = 0.0f; + m_mouseForceScale = 100.0f; + + m_textLine = 0; + m_textIncrement = 22; + m_stepCount = 0; + m_userMaterialId = 0; + + memset( m_profiles, 0, sizeof( m_profiles ) ); + m_currentProfileIndex = 0; + m_profileReadIndex = 0; + m_profileWriteIndex = 0; + + m_stepWhilePaused = true; + m_didStep = false; + + m_haveMouseLast = false; + m_mouseLast = { 0.0f, 0.0f }; + m_mouseDelta = { 0.0f, 0.0f }; + m_launchSpeedScale = 5.0f; + + g_randomSeed = RAND_SEED; + + b3Capacity capacity = {}; + CreateWorld( &capacity ); +} + +Sample::~Sample() +{ + b3DestroyWorld( m_worldId ); + + DestroySharedMeshes( m_context->scene ); +} + +void Sample::CreateWorld( b3Capacity* capacity ) +{ + if ( B3_IS_NON_NULL( m_worldId ) ) + { + b3DestroyWorld( m_worldId ); + } + + m_mouseBodyId = {}; + m_mouseJointId = {}; + m_mousePoint = {}; + + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.workerCount = m_context->workerCount; + worldDef.userTaskContext = this; + worldDef.enableSleep = m_context->enableSleep; + worldDef.createDebugShape = CreateDebugShape; + worldDef.destroyDebugShape = DestroyDebugShape; + worldDef.userDebugShapeContext = m_context; + worldDef.capacity = *capacity; + m_worldId = b3CreateWorld( &worldDef ); + + b3World_SetContactRecycleDistance( m_worldId, m_context->recycleDistance ); +} + +void Sample::Step() +{ + m_didStep = false; + + float timeStep = 0.0f; + if ( m_context->pause == false || m_context->singleStep > 0 ) + { + timeStep = m_context->hertz > 0.0f ? 1.0f / m_context->hertz : 0.0f; + m_context->singleStep = b3MaxInt( 0, m_context->singleStep - 1 ); + } + + if ( B3_IS_NON_NULL( m_mouseJointId ) && b3Joint_IsValid( m_mouseJointId ) == false ) + { + // The world or attached body was destroyed. + m_mouseJointId = {}; + + if ( B3_IS_NON_NULL( m_mouseBodyId ) ) + { + b3DestroyBody( m_mouseBodyId ); + m_mouseBodyId = {}; + } + } + + if ( B3_IS_NON_NULL( m_mouseBodyId ) && timeStep > 0.0f ) + { + b3Body_SetTargetTransform( m_mouseBodyId, { m_mousePoint, b3Quat_identity }, timeStep, true ); + } + + b3World_EnableSleeping( m_worldId, m_context->enableSleep ); + b3World_EnableWarmStarting( m_worldId, m_context->enableWarmStarting ); + b3World_EnableContinuous( m_worldId, m_context->enableContinuous ); + + if ( timeStep > 0.0f || m_stepWhilePaused ) + { + b3World_Step( m_worldId, timeStep, m_context->subStepCount ); + } + + // if (glfwGetKey( m_window, 'F' )) + //{ + // b3World_DumpShapeBounds( m_worldId, b3_staticBody ); + // } + + if ( timeStep > 0.0f ) + { + m_stepCount += 1; + m_didStep = true; + + if ( m_profileWriteIndex - m_profileReadIndex == m_profileCapacity ) + { + m_profileReadIndex += 1; + } + + m_currentProfileIndex = m_profileWriteIndex & ( m_profileCapacity - 1 ); + m_profiles[m_currentProfileIndex] = b3World_GetProfile( m_worldId ); + + m_profileWriteIndex += 1; + } + + m_triangleIndex = -1; + m_userMaterialId = 0; + + { + double screenX, screenY; + glfwGetCursorPos( m_window, &screenX, &screenY ); + PickRay pickRay = m_camera->BuildPickRay( (float)screenX, (float)screenY ); + + b3RayResult result = b3World_CastRayClosest( m_worldId, pickRay.origin, pickRay.translation, b3DefaultQueryFilter() ); + + if ( result.hit ) + { + b3ShapeType type = b3Shape_GetType( result.shapeId ); + if ( type == b3_meshShape ) + { + m_triangleIndex = result.triangleIndex; + } + + m_userMaterialId = result.userMaterialId; + } + } +} + +void Sample::Render() +{ + // Draw world + b3Vec3 position = m_context->camera.GetPosition(); + b3Vec3 r = { 1000.0f, 1000.0f, 1000.0f }; + b3AABB bounds = { position - r, position + r }; + m_context->debugDraw.drawingBounds = bounds; + + b3World_Draw( m_worldId, &m_context->debugDraw, B3_DEFAULT_MASK_BITS ); + + DrawTextLine( "camera radius = %g", m_camera->m_radius ); +} + +void Sample::ResetProfile() +{ + m_stepCount = 0; +} + +void Sample::UpdateUI() +{ + float fontSize = ImGui::GetFontSize(); + + if ( m_context->drawProfile ) + { + ImGui::SetNextWindowPos( { fontSize, 8.0f * fontSize }, ImGuiCond_FirstUseEver ); + ImGui::Begin( "Profile (ms)", nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize ); + + const int count = static_cast( m_profileWriteIndex - m_profileReadIndex ); + + // Unroll ring buffer into per-field histories. + constexpr int kRowCount = 22; + float histories[kRowCount][m_profileCapacity]; + float totals[kRowCount] = {}; + for ( int i = 0; i < count; ++i ) + { + int idx = static_cast( ( m_profileReadIndex + i ) & ( m_profileCapacity - 1 ) ); + const b3Profile& p = m_profiles[idx]; + histories[0][i] = p.step; + histories[1][i] = p.pairs; + histories[2][i] = p.collide; + histories[3][i] = p.solve; + histories[4][i] = p.solverSetup; + histories[5][i] = p.constraints; + histories[6][i] = p.prepareConstraints; + histories[7][i] = p.integrateVelocities; + histories[8][i] = p.warmStart; + histories[9][i] = p.solveImpulses; + histories[10][i] = p.integratePositions; + histories[11][i] = p.relaxImpulses; + histories[12][i] = p.applyRestitution; + histories[13][i] = p.storeImpulses; + histories[14][i] = p.splitIslands; + histories[15][i] = p.transforms; + histories[16][i] = p.jointEvents; + histories[17][i] = p.hitEvents; + histories[18][i] = p.refit; + histories[19][i] = p.sleepIslands; + histories[20][i] = p.bullets; + histories[21][i] = p.sensors; + + totals[0] += p.step; + totals[1] += p.pairs; + totals[2] += p.collide; + totals[3] += p.solve; + totals[4] += p.solverSetup; + totals[5] += p.constraints; + totals[6] += p.prepareConstraints; + totals[7] += p.integrateVelocities; + totals[8] += p.warmStart; + totals[9] += p.solveImpulses; + totals[10] += p.integratePositions; + totals[11] += p.relaxImpulses; + totals[12] += p.applyRestitution; + totals[13] += p.storeImpulses; + totals[14] += p.splitIslands; + totals[15] += p.transforms; + totals[16] += p.jointEvents; + totals[17] += p.hitEvents; + totals[18] += p.refit; + totals[19] += p.sleepIslands; + totals[20] += p.bullets; + totals[21] += p.sensors; + } + + const b3Profile& cur = m_profiles[m_currentProfileIndex]; + const float now[kRowCount] = { + cur.step, + cur.pairs, + cur.collide, + cur.solve, + cur.solverSetup, + cur.constraints, + cur.prepareConstraints, + cur.integrateVelocities, + cur.warmStart, + cur.solveImpulses, + cur.integratePositions, + cur.relaxImpulses, + cur.applyRestitution, + cur.storeImpulses, + cur.splitIslands, + cur.transforms, + cur.jointEvents, + cur.hitEvents, + cur.refit, + cur.sleepIslands, + cur.bullets, + cur.sensors, + }; + + // Rolling average + float avg[kRowCount] = {}; + if ( count > 0 ) + { + float scale = 1.0f / count; + for ( int i = 0; i < kRowCount; ++i ) + { + avg[i] = scale * totals[i]; + } + } + + // Match Frame Time chart's first three colors so rows read with the line plot. + const ImU32 colorStep = IM_COL32( 102, 153, 255, 255 ); + const ImU32 colorCollide = IM_COL32( 255, 140, 51, 255 ); + const ImU32 colorSolve = IM_COL32( 102, 204, 102, 255 ); + const ImU32 colorDefault = IM_COL32( 220, 220, 220, 255 ); + + struct RowDef + { + const char* name; + int indent; + ImU32 color; + }; + const RowDef rows[kRowCount] = { + { "step", 0, colorStep }, { "pairs", 0, colorDefault }, { "collide", 0, colorCollide }, + { "solve", 0, colorSolve }, { "setup", 1, colorDefault }, { "constraints", 1, colorDefault }, + { "prepare", 2, colorDefault }, { "velocities", 2, colorDefault }, { "warm start", 2, colorDefault }, + { "bias", 2, colorDefault }, { "positions", 2, colorDefault }, { "relax", 2, colorDefault }, + { "restitution", 2, colorDefault }, { "store", 2, colorDefault }, { "split islands", 2, colorDefault }, + { "transforms", 1, colorDefault }, { "joint events", 1, colorDefault }, { "hit events", 1, colorDefault }, + { "refit BVH", 1, colorDefault }, { "sleep", 1, colorDefault }, { "bullets", 1, colorDefault }, + { "sensors", 0, colorDefault }, + }; + + // Derive parent/child links from the indent levels so we can collapse subtrees. + int parents[kRowCount]; + bool hasChildren[kRowCount] = {}; + { + int stack[8]; + int stackSize = 0; + for ( int i = 0; i < kRowCount; ++i ) + { + while ( stackSize > 0 && rows[stack[stackSize - 1]].indent >= rows[i].indent ) + { + --stackSize; + } + parents[i] = stackSize > 0 ? stack[stackSize - 1] : -1; + stack[stackSize++] = i; + if ( parents[i] >= 0 ) + { + hasChildren[parents[i]] = true; + } + } + } + + static bool s_rowOpen[kRowCount]; + static bool s_showPlots = false; + + // Bars are drawn relative to the step row so the proportions are visually consistent. + const float stepNow = b3MaxFloat( cur.step, 0.001f ); + + if ( ImGui::Button( "Reset" ) ) + { + ResetProfile(); + } + ImGui::SameLine(); + ImGui::Checkbox( "Show plots", &s_showPlots ); + + const ImGuiTableFlags tableFlags = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit; + + const int colCount = s_showPlots ? 6 : 5; + if ( ImGui::BeginTable( "profile", colCount, tableFlags ) ) + { + ImGui::TableSetupColumn( "section", ImGuiTableColumnFlags_WidthFixed, 8.0f * fontSize ); + ImGui::TableSetupColumn( "now", ImGuiTableColumnFlags_WidthFixed, 3.0f * fontSize ); + ImGui::TableSetupColumn( "avg", ImGuiTableColumnFlags_WidthFixed, 3.0f * fontSize ); + ImGui::TableSetupColumn( "max", ImGuiTableColumnFlags_WidthFixed, 3.0f * fontSize ); + ImGui::TableSetupColumn( "% step", ImGuiTableColumnFlags_WidthFixed, 8.0f * fontSize ); + if ( s_showPlots ) + { + ImGui::TableSetupColumn( "history", ImGuiTableColumnFlags_WidthFixed, 16.0f * fontSize ); + } + ImGui::TableHeadersRow(); + + const float rowHeight = 1.5f * fontSize; + + for ( int r = 0; r < kRowCount; ++r ) + { + bool visible = true; + for ( int p = parents[r]; p >= 0; p = parents[p] ) + { + if ( !s_rowOpen[p] ) + { + visible = false; + break; + } + } + if ( !visible ) + { + continue; + } + + const RowDef& d = rows[r]; + const float* hist = histories[r]; + + float rollingMax = 0.0f; + for ( int i = 0; i < count; ++i ) + { + rollingMax = b3MaxFloat( rollingMax, hist[i] ); + } + + ImGui::TableNextRow(); + + ImGui::TableNextColumn(); + if ( d.indent > 0 ) + { + ImGui::Indent( d.indent * fontSize ); + } + if ( hasChildren[r] ) + { + ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | + ImGuiTreeNodeFlags_NoTreePushOnOpen; + ImGui::PushStyleColor( ImGuiCol_Text, d.color ); + s_rowOpen[r] = ImGui::TreeNodeEx( d.name, flags ); + ImGui::PopStyleColor(); + } + else + { + float leafIndent = ImGui::GetTreeNodeToLabelSpacing(); + ImGui::Indent( leafIndent ); + ImGui::PushStyleColor( ImGuiCol_Text, d.color ); + ImGui::TextUnformatted( d.name ); + ImGui::PopStyleColor(); + ImGui::Unindent( leafIndent ); + } + if ( d.indent > 0 ) + { + ImGui::Unindent( d.indent * fontSize ); + } + + ImGui::TableNextColumn(); + ImGui::Text( "%6.2f", now[r] ); + ImGui::TableNextColumn(); + ImGui::Text( "%6.2f", avg[r] ); + ImGui::TableNextColumn(); + ImGui::Text( "%6.2f", rollingMax ); + + ImGui::TableNextColumn(); + float frac = b3ClampFloat( now[r] / stepNow, 0.0f, 1.0f ); + ImGui::PushStyleColor( ImGuiCol_PlotHistogram, d.color ); + ImGui::ProgressBar( frac, ImVec2( -FLT_MIN, 0.0f ), "" ); + ImGui::PopStyleColor(); + + if ( s_showPlots ) + { + ImGui::TableNextColumn(); + if ( count > 1 ) + { + char id[16]; + snprintf( id, sizeof( id ), "##h%d", r ); + ImGui::PushStyleColor( ImGuiCol_PlotLines, d.color ); + ImGui::PlotLines( id, hist, count, 0, nullptr, 0.0f, rollingMax * 1.05f + 0.001f, + ImVec2( -FLT_MIN, rowHeight ) ); + ImGui::PopStyleColor(); + } + } + } + ImGui::EndTable(); + } + + ImGui::End(); + } + + if ( m_context->drawCounters ) + { + b3Counters s = b3World_GetCounters( m_worldId ); + constexpr int colorCount = sizeof( s.colorCounts ) / sizeof( s.colorCounts[0] ); + const int overflowIndex = colorCount - 1; + constexpr int manifoldBucketCount = sizeof( s.manifoldCounts ) / sizeof( s.manifoldCounts[0] ); + + // Bars are scaled to the largest non-overflow color so the distribution shape reads clearly; + // overflow gets its own bar against the same scale, with a red tint to flag coupling problems. + int totalCount = 0; + int maxCount = 1; + for ( int i = 0; i < colorCount; ++i ) + { + totalCount += s.colorCounts[i]; + if ( i != overflowIndex && s.colorCounts[i] > maxCount ) + { + maxCount = s.colorCounts[i]; + } + } + + int totalManifolds = 0; + int maxManifolds = 1; + for ( int i = 0; i < manifoldBucketCount; ++i ) + { + totalManifolds += s.manifoldCounts[i]; + if ( s.manifoldCounts[i] > maxManifolds ) + { + maxManifolds = s.manifoldCounts[i]; + } + } + + ImGui::SetNextWindowPos( { fontSize, 8.0f * fontSize }, ImGuiCond_FirstUseEver ); + ImGui::Begin( "Counters", nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize ); + + ImGui::Text( "bodies/shapes/contacts/joints = %d/%d/%d/%d", s.bodyCount, s.shapeCount, s.contactCount, s.jointCount ); + { + float frac = s.awakeContactCount > 0 + ? b3ClampFloat( (float)s.recycledContactCount / (float)s.awakeContactCount, 0.0f, 1.0f ) + : 0.0f; + + char overlay[32]; + snprintf( overlay, sizeof( overlay ), "%d / %d", s.recycledContactCount, s.awakeContactCount ); + + ImGui::TextUnformatted( "recycled contacts" ); + ImGui::SameLine(); + ImGui::ProgressBar( frac, ImVec2( -FLT_MIN, 0.0f ), overlay ); + } + ImGui::Text( "islands/tasks = %d/%d", s.islandCount, s.taskCount ); + ImGui::Text( "tree height static/movable = %d/%d", s.staticTreeHeight, s.treeHeight ); + ImGui::Text( "sat call/hit = %d/%d", s.satCallCount, s.satCacheHitCount ); + ImGui::Text( "stack allocator size = %d K", s.stackUsed / 1024 ); + ImGui::Text( "total allocation = %d K", s.byteCount / 1024 ); + + ImGui::Separator(); + b3Capacity c = b3World_GetMaxCapacity( m_worldId ); + ImGui::Text( "max capacities" ); + ImGui::BulletText( "static shapes/bodies = %d/%d", c.staticShapeCount, c.staticBodyCount ); + ImGui::BulletText( "dynamic shapes/bodies = %d/%d", c.dynamicShapeCount, c.dynamicBodyCount ); + ImGui::BulletText( "contacts = %d", c.contactCount ); + + ImGui::Separator(); + ImGui::Text( "%d constraints across %d colors", totalCount, colorCount ); + + const ImGuiTableFlags tableFlags = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit; + if ( ImGui::BeginTable( "graphColors", 3, tableFlags ) ) + { + ImGui::TableSetupColumn( "color", ImGuiTableColumnFlags_WidthFixed, 3.5f * fontSize ); + ImGui::TableSetupColumn( "count", ImGuiTableColumnFlags_WidthFixed, 5.0f * fontSize ); + ImGui::TableSetupColumn( "share", ImGuiTableColumnFlags_WidthFixed, 16.0f * fontSize ); + ImGui::TableHeadersRow(); + + const float invMax = 1.0f / static_cast( maxCount ); + + for ( int i = 0; i < colorCount; ++i ) + { + int count = s.colorCounts[i]; + bool isOverflow = ( i == overflowIndex ); + + // Skip empty slots, but always show overflow — a non-zero overflow row is the signal we care about. + if ( count == 0 && !isOverflow ) + { + continue; + } + + uint32_t hex = static_cast( b3GetGraphColor( i ) ); + ImU32 swatch = IM_COL32( ( hex >> 16 ) & 0xFF, ( hex >> 8 ) & 0xFF, hex & 0xFF, 255 ); + ImU32 barColor = isOverflow ? IM_COL32( 220, 60, 60, 255 ) : swatch; + + ImGui::TableNextRow(); + + ImGui::TableNextColumn(); + if ( isOverflow ) + { + ImGui::PushStyleColor( ImGuiCol_Text, IM_COL32( 220, 60, 60, 255 ) ); + ImGui::TextUnformatted( "over" ); + ImGui::PopStyleColor(); + } + else + { + ImGui::PushStyleColor( ImGuiCol_Text, swatch ); + ImGui::Text( "%d", i ); + ImGui::PopStyleColor(); + } + + ImGui::TableNextColumn(); + ImGui::Text( "%d", count ); + + ImGui::TableNextColumn(); + float frac = b3ClampFloat( count * invMax, 0.0f, 1.0f ); + ImGui::PushStyleColor( ImGuiCol_PlotHistogram, barColor ); + ImGui::ProgressBar( frac, ImVec2( -FLT_MIN, 0.0f ), "" ); + ImGui::PopStyleColor(); + } + ImGui::EndTable(); + } + + ImGui::Separator(); + ImGui::Text( "%d manifolds across %d buckets", totalManifolds, manifoldBucketCount ); + if ( ImGui::BeginTable( "manifolds", 3, tableFlags ) ) + { + ImGui::TableSetupColumn( "points", ImGuiTableColumnFlags_WidthFixed, 3.5f * fontSize ); + ImGui::TableSetupColumn( "count", ImGuiTableColumnFlags_WidthFixed, 5.0f * fontSize ); + ImGui::TableSetupColumn( "share", ImGuiTableColumnFlags_WidthFixed, 16.0f * fontSize ); + ImGui::TableHeadersRow(); + + const float invMax = 1.0f / static_cast( maxManifolds ); + + for ( int i = 0; i < manifoldBucketCount; ++i ) + { + int count = s.manifoldCounts[i]; + if ( count == 0 ) + { + continue; + } + + ImGui::TableNextRow(); + + ImGui::TableNextColumn(); + ImGui::Text( "%d", i + 1 ); + + ImGui::TableNextColumn(); + ImGui::Text( "%d", count ); + + ImGui::TableNextColumn(); + float frac = b3ClampFloat( count * invMax, 0.0f, 1.0f ); + ImGui::ProgressBar( frac, ImVec2( -FLT_MIN, 0.0f ), "" ); + } + ImGui::EndTable(); + } + + ImGui::End(); + } + + if ( m_context->frameTime ) + { + float frameTimeHeight = 400.0f; + float frameTimeWidth = 800.0f; + + ImGui::SetNextWindowPos( { 30.0f, 30.0f }, ImGuiCond_FirstUseEver ); + ImGui::SetNextWindowSize( { frameTimeWidth, frameTimeHeight }, ImGuiCond_FirstUseEver ); + + ImGui::Begin( "Frame Time", nullptr, ImGuiWindowFlags_NoCollapse ); + + ImGui::PushItemWidth( ImGui::GetWindowWidth() - 20.0f ); + + float maxValue = 0.0f; + float times[m_profileCapacity]; + float stepTimes[m_profileCapacity]; + float collideTimes[m_profileCapacity]; + float solveTimes[m_profileCapacity]; + int count = m_profileWriteIndex - m_profileReadIndex; + for ( int i = 0; i < count; ++i ) + { + int index = ( m_profileReadIndex + i ) & ( m_profileCapacity - 1 ); + times[i] = i / 60.0f; + stepTimes[i] = m_profiles[index].step; + collideTimes[i] = m_profiles[index].collide; + solveTimes[i] = m_profiles[index].solve; + maxValue = b3MaxFloat( stepTimes[i], maxValue ); + } + + // This is the pixel size, not the range. + ImVec2 plotSize = { -1, 22.0f * ImGui::GetTextLineHeight() }; + if ( ImPlot::BeginPlot( "Profile", plotSize, ImPlotFlags_NoTitle ) ) + { + ImPlot::SetupAxes( "t", "ms" ); + ImPlot::SetupAxes( "t", "ms", 0, ImPlotAxisFlags_AutoFit | ImPlotAxisFlags_RangeFit ); + ImPlot::SetupAxesLimits( 0, m_profileCapacity / 60.0, 0.0, maxValue ); + ImPlot::PlotLine( "step", times, stepTimes, count ); + ImPlot::PlotLine( "collide", times, collideTimes, count ); + ImPlot::PlotLine( "solve", times, solveTimes, count ); + ImPlot::EndPlot(); + } + + ImGui::PopItemWidth(); + ImGui::End(); + } +} + +void Sample::MouseDown( b3Vec2 p, int button, int modifiers ) +{ + if ( modifiers == 0 ) + { + PickRay pickRay = m_camera->BuildPickRay( p.x, p.y ); + + b3RayResult result = b3World_CastRayClosest( m_worldId, pickRay.origin, pickRay.translation, b3DefaultQueryFilter() ); + + if ( result.hit ) + { + m_mousePoint = result.point; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_kinematicBody; + bodyDef.position = m_mousePoint; + bodyDef.enableSleep = false; + m_mouseBodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3BodyId bodyId = b3Shape_GetBody( result.shapeId ); + + b3MotorJointDef jointDef = b3DefaultMotorJointDef(); + jointDef.base.bodyIdA = m_mouseBodyId; + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameB.p = b3Body_GetLocalPoint( bodyId, result.point ); + jointDef.linearHertz = 7.5f; + jointDef.linearDampingRatio = 1.0f; + + b3MassData massData = b3Body_GetMassData( bodyId ); + float g = b3Length( b3World_GetGravity( m_worldId ) ); + float mg = massData.mass * g; + jointDef.maxSpringForce = m_mouseForceScale * mg; + + if ( massData.mass > 0.0f ) + { + // This acts like angular friction + float trace = massData.inertia.cx.x + massData.inertia.cy.y + massData.inertia.cz.z; + float lever = sqrtf( trace / ( 3.0f * massData.mass ) ); + jointDef.maxVelocityTorque = 0.5f * lever * mg; + } + + m_mouseJointId = b3CreateMotorJoint( m_worldId, &jointDef ); + + b3Body_SetAwake( bodyId, true ); + + m_mouseFraction = result.fraction; + } + } + else if ( modifiers & GLFW_MOD_SHIFT ) + { + PickRay pickRay = m_camera->BuildPickRay( p.x, p.y ); + b3Vec3 direction = b3Normalize( pickRay.translation ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + if ( modifiers & GLFW_MOD_CONTROL ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = pickRay.origin + 2.0f * direction; + bodyDef.linearVelocity = ( 10.0f * m_launchSpeedScale ) * direction; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3Hull* hull = b3CreateCylinder( 2.0f, 0.15f, 0.0f, 6 ); + b3CreateHullShape( bodyId, &shapeDef, hull ); + b3DestroyHull( hull ); + } + else if ( modifiers & GLFW_MOD_ALT ) + { + b3Vec3 position = pickRay.origin + 2.0f * direction; + Human human = {}; + CreateHuman( &human, m_worldId, position, 1.0f, 1.0f, 1.0f, 0, nullptr, true ); + Human_SetVelocity( &human, ( 5.0f * m_launchSpeedScale ) * direction ); + } + else + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = pickRay.origin + 2.0f * direction; + bodyDef.linearVelocity = ( 20.0f * m_launchSpeedScale ) * direction; + bodyDef.isBullet = true; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3Sphere sphere = { b3Vec3_zero, 0.25f }; + shapeDef.density *= 4.0f; + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + } + } +} + +void Sample::MouseUp( b3Vec2 p, int button ) +{ + if ( b3Joint_IsValid( m_mouseJointId ) ) + { + b3DestroyJoint( m_mouseJointId, true ); + } + + if ( b3Body_IsValid( m_mouseBodyId ) ) + { + b3DestroyBody( m_mouseBodyId ); + } + + m_mouseJointId = b3_nullJointId; + m_mouseBodyId = b3_nullBodyId; + m_mouseFraction = 0.0f; +} + +void Sample::MouseMove( b3Vec2 p ) +{ + if ( m_camera->m_thirdPerson ) + { + if ( m_haveMouseLast == false ) + { + m_mouseLast = p; + m_haveMouseLast = true; + } + else + { + m_mouseDelta = { p.x - m_mouseLast.x, p.y - m_mouseLast.y }; + // printf( "mdx = %g, mdy = %g\n", m_mouseDelta.x, m_mouseDelta.y ); + m_mouseLast = p; + } + + const float sensitivity = 0.1f; + m_camera->m_yaw -= 2.0f * sensitivity * m_mouseDelta.x; + m_camera->m_pitch += sensitivity * m_mouseDelta.y; + m_camera->m_pitch = b3ClampFloat( m_camera->m_pitch, -85.0f, 85.0f ); + } + + PickRay pickRay = m_camera->BuildPickRay( p.x, p.y ); + if ( B3_IS_NON_NULL( m_mouseJointId ) ) + { + m_mousePoint = pickRay.origin + m_mouseFraction * pickRay.translation; + // b3Transform localFrameA = { target, b3Quat_identity }; + // b3Joint_SetLocalFrameA( m_mouseJointId, localFrameA ); + } +} + +void Sample::DrawTextLine( const char* text, ... ) +{ + va_list args; + va_start( args, text ); + char buffer[512]; + vsnprintf( buffer, sizeof( buffer ), text, args ); + DrawText( 5, m_textLine, b3_colorWhite, buffer ); + va_end( args ); + m_textLine += m_textIncrement; +} + +SampleEntry SampleManager::sEntries[MAX_SAMPLES]; +int SampleManager::sEntryCount = 0; + +int SampleManager::Register( const char* category, const char* name, SampleCreateFcn* fcn ) +{ + int index = sEntryCount; + if ( index < MAX_SAMPLES ) + { + sEntries[index] = { category, name, fcn }; + sEntryCount += 1; + return index; + } + + return -1; +} + +static int CompareSamples( const void* a, const void* b ) +{ + SampleEntry* entryA = (SampleEntry*)a; + SampleEntry* entryB = (SampleEntry*)b; + + int result = strcmp( entryA->Category, entryB->Category ); + if ( result == 0 ) + { + result = strcmp( entryA->Name, entryB->Name ); + } + + return result; +} + +void SampleManager::Startup( GLFWwindow* window, int width, int height, int bufferWidth, int bufferHeight ) +{ + m_context.Load(); + + m_context.workerCount = b3MinInt( 8, GetNumberOfCores() / 2 ); + + // todo_erin testing + // m_context.settings.workerCount = 1; + + m_context.arena.Create( 100 * 1024 * 1024 ); + m_context.window = window; + m_context.camera.Resize( width, height ); + + assert( bufferWidth > 0 && bufferHeight > 0 ); + m_context.camera.m_bufferWidth = bufferWidth; + m_context.camera.m_bufferHeight = bufferHeight; + m_context.scene = CreateScene( &m_context.camera, m_context.arena ); + + if ( m_context.scene == nullptr ) + { + fprintf( stderr, "Failed to create scene\n" ); + glfwTerminate(); + } + + qsort( sEntries, sEntryCount, sizeof( SampleEntry ), CompareSamples ); + + m_sample = sEntries[m_context.sampleIndex].CreateFcn( &m_context ); +} + +void SampleManager::Step() +{ + const SampleEntry* entry = sEntries + m_context.sampleIndex; + DrawFormat( 5, m_sample->m_textIncrement, b3_colorCyan, "%s : %s", entry->Category, entry->Name ); + m_sample->m_textLine = 2 * m_sample->m_textIncrement; + + if ( m_context.pause ) + { + m_sample->DrawTextLine( "****PAUSED****" ); + } + + m_sample->Step(); +} + +void SampleManager::Resize( int width, int height, int bufferWidth, int bufferHeight ) +{ + m_context.minimized = false; + if ( width == 0 || height == 0 || bufferWidth == 0 || bufferHeight == 0 ) + { + m_context.minimized = true; + return; + } + + m_context.camera.Resize( width, height ); + m_context.camera.m_bufferWidth = bufferWidth; + m_context.camera.m_bufferHeight = bufferHeight; + ResizeScene( m_context.scene, &m_context.camera ); +} + +void SampleManager::Render( GLFWwindow* window, float elapsedTime ) +{ + RenderScene( window, elapsedTime ); + UpdateUI( window ); +} + +void SampleManager::Shutdown( GLFWwindow* window ) +{ + // Must destroy sample first because it will destroy debug shapes. + delete m_sample; + m_sample = nullptr; + + m_context.Save(); + + DestroyScene( m_context.scene ); + m_context.scene = nullptr; + + m_context.arena.Destroy(); +} + +void SampleManager::Keyboard( int key, int action, int modifiers ) +{ + if ( action == GLFW_PRESS ) + { + switch ( key ) + { + case GLFW_KEY_ESCAPE: + glfwSetWindowShouldClose( m_context.window, GL_TRUE ); + break; + + case GLFW_KEY_TAB: + m_showMenu = !m_showMenu; + break; + + case GLFW_KEY_O: + if ( modifiers & GLFW_MOD_SHIFT ) + { + m_context.singleStep += 5; + } + else + { + m_context.singleStep += 1; + } + break; + + case GLFW_KEY_P: + m_context.pause = !m_context.pause; + break; + + case GLFW_KEY_R: + m_context.restart = true; + CreateSample(); + break; + + case GLFW_KEY_LEFT_BRACKET: + m_context.sampleIndex = b3MaxInt( 0, m_context.sampleIndex - 1 ); + m_context.restart = false; + CreateSample(); + break; + + case GLFW_KEY_RIGHT_BRACKET: + m_context.sampleIndex = b3MinInt( sEntryCount - 1, m_context.sampleIndex + 1 ); + m_context.restart = false; + CreateSample(); + break; + + default: + m_sample->Keyboard( key, action, modifiers ); + break; + } + } +} + +void SampleManager::CreateSample() +{ + B3_ASSERT( m_sample ); + + if (m_context.restart == false) + { + EnableGrid( m_context.scene, false ); + } + + delete m_sample; + m_sample = sEntries[m_context.sampleIndex].CreateFcn( &m_context ); +} + +void SampleManager::RenderScene( GLFWwindow* window, float elapsedTime ) +{ + // Update camera + m_context.camera.Update( window, elapsedTime ); + + m_sample->Render(); + // CheckOpenGL(); + + // Actually render + DrawScene( m_context.scene, &m_context.camera ); + // CheckOpenGL(); +} + +void SampleManager::UpdateUI( GLFWwindow* window ) +{ + if ( m_showMenu == false ) + { + return; + } + + int maxWorkers = B3_MAX_WORKERS; + + int savedTestIndex = m_context.sampleIndex; + float menuWidth = 220.0f; + b3WorldId worldId = m_sample->m_worldId; + + ImGui::SetNextWindowPos( { m_context.camera.m_width - menuWidth - 10.0f, 10.0f } ); + ImGui::SetNextWindowSize( { menuWidth, m_context.camera.m_height - 20.0f } ); + + ImGui::Begin( "Tools", &m_showMenu, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse ); + + if ( ImGui::BeginTabBar( "ControlTabs", ImGuiTabBarFlags_None ) ) + { + if ( ImGui::BeginTabItem( "Controls" ) ) + { + ImGui::SliderInt( "Sub-steps", &m_context.subStepCount, 1, 50 ); + ImGui::SliderFloat( "Hertz", &m_context.hertz, 5.0f, 2000.0f, "%.0f hz" ); + + if ( ImGui::SliderInt( "Workers", &m_context.workerCount, 1, maxWorkers ) ) + { + m_context.workerCount = b3ClampInt( m_context.workerCount, 1, maxWorkers ); + m_context.restart = true; + CreateSample(); + } + + ImGui::Separator(); + + ImGui::Checkbox( "Sleep", &m_context.enableSleep ); + ImGui::Checkbox( "Warm Starting", &m_context.enableWarmStarting ); + ImGui::Checkbox( "Continuous", &m_context.enableContinuous ); + + ImGui::PushItemWidth( 100.0f ); + float recyclingCentimeters = 100.0f * m_context.recycleDistance; + if ( ImGui::SliderFloat( "Recycle", &recyclingCentimeters, 0.0f, 10.0f, "%.1f cm" ) ) + { + m_context.recycleDistance = 0.01f * recyclingCentimeters; + b3World_SetContactRecycleDistance( worldId, m_context.recycleDistance ); + } + ImGui::PopItemWidth(); + + ImGui::Separator(); + + ImGui::Checkbox( "Shapes", &m_context.debugDraw.drawShapes ); + ImGui::Checkbox( "Transparent", &m_context.transparentDynamic ); + ImGui::Checkbox( "Joints", &m_context.debugDraw.drawJoints ); + ImGui::Checkbox( "Joint Extras", &m_context.debugDraw.drawJointExtras ); + ImGui::Checkbox( "Bounds", &m_context.debugDraw.drawBounds ); + + ImGui::Separator(); + + ImGui::Checkbox( "Contact Points", &m_context.debugDraw.drawContacts ); + ImGui::RadioButton( "Anchor A", &m_context.debugDraw.drawAnchorA, 1 ); + ImGui::SameLine(); + ImGui::RadioButton( "Anchor B", &m_context.debugDraw.drawAnchorA, 0 ); + ImGui::Checkbox( "Contact Normals", &m_context.debugDraw.drawContactNormals ); + ImGui::Checkbox( "Contact Forces", &m_context.debugDraw.drawContactForces ); + ImGui::Checkbox( "Contact Features", &m_context.debugDraw.drawContactFeatures ); + ImGui::Checkbox( "Friction Forces", &m_context.debugDraw.drawFrictionForces ); + + ImGui::Separator(); + + ImGui::Checkbox( "Mass", &m_context.debugDraw.drawMass ); + ImGui::Checkbox( "Body Names", &m_context.debugDraw.drawBodyNames ); + ImGui::Checkbox( "Graph Colors", &m_context.debugDraw.drawGraphColors ); + ImGui::Checkbox( "Draw Islands", &m_context.debugDraw.drawIslands ); + ImGui::Checkbox( "Counters", &m_context.drawCounters ); + ImGui::Checkbox( "Profile", &m_context.drawProfile ); + ImGui::Checkbox( "Frame Time", &m_context.frameTime ); + + ImGui::PushItemWidth( 80.0f ); + ImGui::InputFloat( "Joint Scale", &m_context.debugDraw.jointScale ); + ImGui::InputFloat( "Force Scale", &m_context.debugDraw.forceScale ); + ImGui::PopItemWidth(); + + ImGui::Separator(); + + bool useSSAO = IsSSAOEnabled( m_context.scene ); + if ( ImGui::Checkbox( "SSAO", &useSSAO ) ) + { + EnableSSAO( m_context.scene, useSSAO ); + } + + bool useShadows = AreShadowsEnabled( m_context.scene ); + if ( ImGui::Checkbox( "Shadows", &useShadows ) ) + { + EnableShadows( m_context.scene, useShadows ); + } + + SceneAOSettings* ao = GetAOSettings( m_context.scene ); + ImGui::SliderFloat( "AO Radius", &ao->radius, 0.0f, 5.0f ); + ImGui::SliderFloat( "AO Bias", &ao->bias, 0.0f, 0.5f ); + ImGui::SliderFloat( "AO Min", &ao->minScale, 0.0f, 1.0f ); + ImGui::SliderFloat( "AO Power", &ao->power, 0.5f, 8.0f ); + ImGui::SliderFloat( "AO Direct", &ao->direct, 0.0f, 1.0f ); + ImGui::Checkbox( "AO Only", &ao->aoOnly ); + + ImGui::Separator(); + + if ( ImGui::Button( "Pause", ImVec2( -1, 0 ) ) ) + { + m_context.pause = !m_context.pause; + } + + if ( ImGui::Button( "Restart", ImVec2( -1, 0 ) ) ) + { + m_context.restart = true; + CreateSample(); + } + + if ( ImGui::Button( "Dump", ImVec2( -1, 0 ) ) ) + { + b3World_Dump( m_sample->m_worldId ); + } + + if ( ImGui::Button( "Dump Awake", ImVec2( -1, 0 ) ) ) + { + b3World_DumpAwake( m_sample->m_worldId ); + } + + if ( ImGui::Button( "Quit", ImVec2( -1, 0 ) ) ) + { + glfwSetWindowShouldClose( 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( "Tests" ) ) + { + const char* category = sEntries[0].Category; + int i = 0; + while ( i < sEntryCount ) + { + bool categorySelected = strcmp( category, sEntries[m_context.sampleIndex].Category ) == 0; + ImGuiTreeNodeFlags nodeSelectionFlags = categorySelected ? ImGuiTreeNodeFlags_Selected : 0; + bool nodeOpen = ImGui::TreeNodeEx( category, nodeFlags | nodeSelectionFlags ); + + if ( nodeOpen ) + { + while ( i < sEntryCount && strcmp( category, sEntries[i].Category ) == 0 ) + { + ImGuiTreeNodeFlags selectionFlags = 0; + if ( m_context.sampleIndex == i ) + { + selectionFlags = ImGuiTreeNodeFlags_Selected; + } + ImGui::TreeNodeEx( (void*)(intptr_t)i, leafNodeFlags | selectionFlags, "%s", sEntries[i].Name ); + if ( ImGui::IsItemClicked() ) + { + m_context.sampleIndex = i; + } + ++i; + } + ImGui::TreePop(); + } + else + { + while ( i < sEntryCount && strcmp( category, sEntries[i].Category ) == 0 ) + { + ++i; + } + } + + if ( i < sEntryCount ) + { + category = sEntries[i].Category; + } + } + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } + + ImGui::End(); + + m_sample->UpdateUI(); + + // todo wrong place for this + if ( m_context.sampleIndex != savedTestIndex ) + { + m_context.restart = false; + CreateSample(); + } +} + +void Sample::ToggleThirdPerson() +{ + if ( m_camera->m_thirdPerson ) + { + glfwSetInputMode( m_window, GLFW_CURSOR, GLFW_CURSOR_NORMAL ); + m_camera->m_thirdPerson = false; + } + else + { + glfwSetInputMode( m_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED ); + m_camera->m_thirdPerson = true; + } +} + +float CastClosestCallback( b3ShapeId shapeId, b3Vec3 point, b3Vec3 normal, float fraction, uint64_t materialId, int triangleIndex, + int childIndex, void* context ) +{ + CastClosestContext* rayContext = (CastClosestContext*)context; + rayContext->shapeId = shapeId; + rayContext->point = point; + rayContext->normal = normal; + rayContext->fraction = fraction; + rayContext->materialId = materialId; + rayContext->childIndex = childIndex; + rayContext->triangleIndex = triangleIndex; + rayContext->hit = true; + return fraction; +} + +static bool MoverFilterCallback( b3ShapeId shapeId, void* context ) +{ + CharacterMover* self = (CharacterMover*)context; + for ( int i = 0; i < self->m_ignoreCount; ++i ) + { + if ( B3_ID_EQUALS( shapeId, self->m_ignoreShapeIds[i] ) ) + { + return false; + } + } + + return true; +} + +void CharacterMover::Initialize( Sample* sample, b3Vec3 position ) +{ + m_sample = sample; + m_transform.p = position; + m_transform.q = b3Quat_identity; + m_velocity = { 0.0f, 0.0f, 0.0f }; + m_capsule = { { 0.0f, -0.5f, 0.0f }, { 0.0f, 0.5f, 0.0f }, 0.3f }; + + m_planeCount = 0; + m_totalIterations = 0; + m_pogoVelocity = 0.0f; + m_onGround = false; + m_sprint = false; + + m_ignoreShapeIds = nullptr; + m_ignoreCount = 0; +} + +static bool PlaneResultFcn( b3ShapeId shapeId, const b3PlaneResult* planeResults, int planeCount, void* context ) +{ + if ( MoverFilterCallback( shapeId, context ) == false ) + { + // ignore these planes but continue looking for more + return true; + } + + CharacterMover* self = static_cast( context ); + float maxPush = FLT_MAX; + bool clipVelocity = true; + MoverShapeUserData* userData = static_cast( (void*)b3Shape_GetUserData( shapeId ) ); + if ( userData != nullptr ) + { + maxPush = userData->maxPush; + clipVelocity = userData->clipVelocity; + } + + for ( int i = 0; i < planeCount && self->m_planeCount < CharacterMover::m_planeCapacity; ++i ) + { + assert( b3IsValidPlane( planeResults[i].plane ) ); + self->m_planes[self->m_planeCount] = { + .plane = planeResults[i].plane, + .pushLimit = maxPush, + .push = 0.0f, + .clipVelocity = clipVelocity, + }; + self->m_planeExtras[self->m_planeCount] = { + .point = planeResults[i].point, + .shapeId = shapeId, + }; + self->m_planeCount += 1; + } + + return true; +} + +void CharacterMover::SolveMove( float timeStep, b3Vec3 forward, b3Vec3 right, b3Vec2 throttle, bool clipVelocity ) +{ + // Friction + float speed = b3Length( m_velocity ); + if ( speed < m_minSpeed ) + { + m_velocity.x = 0.0f; + m_velocity.y = 0.0f; + } + else + { + // 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 = b3MaxFloat( 0.0f, speed - drop ); + m_velocity *= newSpeed / speed; + } + + float maxSpeed = m_sprint ? 1.5f * m_maxSpeed : m_maxSpeed; + + b3Vec3 desiredVelocity = maxSpeed * throttle.x * forward + maxSpeed * throttle.y * right; + float desiredSpeed; + b3Vec3 desiredDirection = b3GetLengthAndNormalize( &desiredSpeed, desiredVelocity ); + + if ( desiredSpeed > maxSpeed ) + { + desiredVelocity *= maxSpeed / desiredSpeed; + desiredSpeed = maxSpeed; + } + + if ( m_onGround ) + { + m_velocity.y = 0.0f; + } + + // Accelerate + float currentSpeed = b3Dot( m_velocity, desiredDirection ); + float addSpeed = desiredSpeed - currentSpeed; + if ( addSpeed > 0.0f ) + { + float accelSpeed = m_accelerate * maxSpeed * timeStep; + if ( accelSpeed > addSpeed ) + { + accelSpeed = addSpeed; + } + + m_velocity += accelSpeed * desiredDirection; + } + + m_velocity.y -= m_gravity * timeStep; + + b3WorldId worldId = m_sample->m_worldId; + Scene* scene = m_sample->m_scene; + + float pogoRestLength = 3.0f * m_capsule.radius; + float rayLength = pogoRestLength + m_capsule.radius; + b3Vec3 rayOrigin = b3TransformPoint( m_transform, m_capsule.center1 ); + b3Vec3 rayTranslation = -rayLength * b3Vec3_axisY; + b3QueryFilter skipTeamFilter = { 1, ~2u }; + b3RayResult rayResult = b3World_CastRayClosest( worldId, rayOrigin, rayTranslation, skipTeamFilter ); + + if ( rayResult.hit == false ) + { + m_onGround = false; + m_pogoVelocity = 0.0f; + + DrawLine( scene, rayOrigin, rayOrigin + rayTranslation, b3_colorGray ); + } + else + { + m_onGround = true; + float pogoCurrentLength = rayResult.fraction * rayLength; + + float zeta = 0.7f; + float hertz = 4.0f; + float omega = 2.0f * B3_PI * hertz; + float omegaH = omega * timeStep; + + m_pogoVelocity = ( m_pogoVelocity - omega * omegaH * ( pogoCurrentLength - pogoRestLength ) ) / + ( 1.0f + 2.0f * zeta * omegaH + omegaH * omegaH ); + DrawLine( scene, rayOrigin, rayResult.point, b3_colorGreen ); + } + + b3Vec3 startPosition = m_transform.p; + b3Vec3 target = m_transform.p + timeStep * m_velocity + timeStep * m_pogoVelocity * b3Vec3_axisY; + + // Want the mover to collide with allies + b3QueryFilter moverFilter = { .categoryBits = 1, .maskBits = ~0u }; + + // The cast should ignore allies + b3QueryFilter castFilter = { .categoryBits = 1, .maskBits = ~2u }; + + m_totalIterations = 0; + float tolerance = 0.01f; + + for ( int iteration = 0; iteration < 5; ++iteration ) + { + m_planeCount = 0; + + b3Capsule mover; + mover.center1 = b3TransformPoint( m_transform, m_capsule.center1 ); + mover.center2 = b3TransformPoint( m_transform, m_capsule.center2 ); + mover.radius = m_capsule.radius; + + b3World_CollideMover( worldId, &mover, moverFilter, PlaneResultFcn, this ); + + b3Vec3 targetDelta = target - m_transform.p; + b3PlaneSolverResult result = b3SolvePlanes( targetDelta, m_planes, m_planeCount ); + + m_totalIterations += result.iterationCount; + + b3Vec3 delta = result.delta; + + float fraction = b3World_CastMover( worldId, &mover, delta, castFilter, MoverFilterCallback, this ); + + delta *= fraction; + m_transform.p += delta; + + if ( b3LengthSquared( delta ) < tolerance * tolerance ) + { + break; + } + } + + for ( int i = 0; i < m_planeCount; ++i ) + { + b3BodyId bodyId = b3Shape_GetBody( m_planeExtras[i].shapeId ); + b3BodyType bodyType = b3Body_GetType( bodyId ); + if ( bodyType != b3_dynamicBody ) + { + continue; + } + + b3Vec3 point = m_planeExtras[i].point; + b3Vec3 normal = b3Neg( m_planes[i].plane.normal ); + + float invMassA = 0.0f; + float invMassB = b3Body_GetInverseMass( bodyId ); + b3Matrix3 invIB = b3Body_GetWorldInverseRotationalInertia( bodyId ); + + b3Vec3 pB = b3Body_GetWorldCenterOfMass( bodyId ); + b3Vec3 rB = point - pB; + + b3Vec3 rnB = b3Cross( rB, normal ); + float kNormal = invMassA + invMassB + b3Dot( rnB, b3MulMV( invIB, rnB ) ); + float normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; + + b3Vec3 vB = b3Body_GetLinearVelocity( bodyId ); + b3Vec3 omegaB = b3Body_GetAngularVelocity( bodyId ); + b3Vec3 vrB = b3Add( vB, b3Cross( omegaB, rB ) ); + float vn = b3Dot( b3Sub( vrB, m_velocity ), normal ); + float impulse = b3MaxFloat( -normalMass * vn, 0.0f ); + + b3Vec3 P = b3MulSV( impulse, normal ); + m_velocity = b3MulSub( m_velocity, invMassA, P ); + + b3Body_ApplyLinearImpulse( bodyId, P, point, true ); + } + + if ( clipVelocity ) + { + // Using the velocity clipper can avoid picking up velocity from depenetration. + // This allows the mover to avoid velocity from soft collision depenetration. + m_velocity = b3ClipVector( m_velocity, m_planes, m_planeCount ); + } + else if ( timeStep > 0.0f ) + { + // Using the position delta is more holistic and intuitive in some cases. + m_velocity = ( 1.0f / timeStep ) * ( m_transform.p - startPosition ); + } +} + +void CharacterMover::Step( b3ShapeId* ignoreShapes, int ignoreCount, bool clipVelocity ) +{ + m_ignoreShapeIds = ignoreShapes; + m_ignoreCount = ignoreCount; + + b3Vec2 throttle = { 0.0f, 0.0f }; + b3Vec3 forward = -m_sample->m_camera->GetForward(); + b3Vec3 right = m_sample->m_camera->GetRight(); + forward.y = 0.0f; + + if ( m_sample->m_camera->m_thirdPerson ) + { + if ( glfwGetKey( m_sample->m_window, GLFW_KEY_W ) ) + { + throttle.x += 1.0f; + } + + if ( glfwGetKey( m_sample->m_window, GLFW_KEY_S ) ) + { + throttle.x -= 1.0f; + } + + if ( glfwGetKey( m_sample->m_window, GLFW_KEY_A ) ) + { + throttle.y -= 1.0f; + } + + if ( glfwGetKey( m_sample->m_window, GLFW_KEY_D ) ) + { + throttle.y += 1.0f; + } + + if ( glfwGetKey( m_sample->m_window, GLFW_KEY_SPACE ) && m_onGround == true ) + { + m_velocity.y = m_jumpSpeed; + m_onGround = false; + } + + if ( m_onGround == true ) + { + m_sprint = glfwGetKey( m_sample->m_window, GLFW_KEY_LEFT_SHIFT ) != 0; + } + else + { + m_sprint = false; + } + } + + float hertz = m_sample->m_context->hertz; + float timeStep = hertz > 0.0f ? 1.0f / hertz : 0.0f; + + // throttle = { 0.0f, 0.0f, -1.0f }; + + SolveMove( timeStep, forward, right, throttle, clipVelocity ); + + Scene* scene = m_sample->m_scene; + + int count = m_planeCount; + for ( int i = 0; i < count; ++i ) + { + b3Plane plane = m_planes[i].plane; + b3Vec3 p1 = m_transform.p + ( plane.offset - m_capsule.radius ) * plane.normal; + b3Vec3 p2 = p1 + 0.1f * plane.normal; + DrawPoint( scene, p1, 5.0f, b3_colorYellow ); + DrawLine( scene, p1, p2, b3_colorYellow ); + } + + DrawCapsule( scene, m_transform, m_capsule, b3_colorBlue ); + DrawLine( scene, m_transform.p, m_transform.p + m_velocity, b3_colorPurple ); + + b3Vec3 p = m_transform.p; + // m_sample->DrawTextLine( "position %.2f %.2f %.2f", p.x, p.y, p.z ); + // m_sample->DrawTextLine( "forward %.2f %.2f %.2f", forward.x, forward.y, forward.z ); + // m_sample->DrawTextLine( "right %.2f %.2f %.2f", right.x, right.y, right.z ); + // m_sample->DrawTextLine( "velocity %.2f %.2f %.2f", m_velocity.x, m_velocity.y, m_velocity.z ); + // m_sample->DrawTextLine( "iterations %d", m_totalIterations ); + + if ( m_sample->m_camera->m_thirdPerson ) + { + m_sample->m_camera->m_pivot = p; + m_sample->m_camera->UpdateTransform(); + } + + m_ignoreShapeIds = nullptr; + m_ignoreCount = 0; +} diff --git a/samples/sample.h b/samples/sample.h new file mode 100644 index 0000000..e490bb8 --- /dev/null +++ b/samples/sample.h @@ -0,0 +1,215 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "camera.h" + +class Font; +struct MouseEvent; +struct MouseMoveEvent; +struct MouseWheelEvent; +struct Scene; +struct GLFWwindow; + +struct SampleContext +{ + void Save(); + void Load(); + + GLFWwindow* window = nullptr; + Camera camera; + Arena arena; + Scene* scene = nullptr; + bool minimized = false; + class Sample* sample = nullptr; + b3Capacity capacity; + b3DebugDraw debugDraw; + + int windowWidth = 1920; + int windowHeight = 1080; + + // Used to shift the origin and test round-off problems + b3Vec3 origin = b3Vec3_zero; + + float hertz = 60.0f; + float recycleDistance = 0.05f; + int subStepCount = 4; + int workerCount = 1; + bool transparentDynamic = false; + bool drawCounters = false; + bool drawProfile = false; + bool frameTime = false; + bool transparent = false; + bool enableWarmStarting = true; + bool enableContinuous = true; + bool enableSleep = true; + bool pause = false; + int singleStep = 0; + bool restart = false; + + int sampleIndex = 0; +}; + +class Sample +{ +public: + explicit Sample( SampleContext* context ); + virtual ~Sample(); + + void CreateWorld( b3Capacity* capacity ); + + // Update and render are split to support pausing the simulation + virtual void Step(); + + virtual void Render(); + + virtual void UpdateUI(); + + virtual void Keyboard( int key, int action, int modifiers ) + { + } + + virtual void MouseDown( b3Vec2 p, int button, int modifiers ); + virtual void MouseUp( b3Vec2 p, int button ); + virtual void MouseMove( b3Vec2 p ); + + void ToggleThirdPerson(); + void DrawTextLine( const char* text, ... ); + void ResetProfile(); + +#if defined( NDEBUG ) + static constexpr bool m_isDebug = false; +#else + static constexpr bool m_isDebug = true; +#endif + + static constexpr int m_maxTasks = 64; + static constexpr int m_maxThreads = 64; + static constexpr int m_profileCapacity = 512; + + SampleContext* m_context; + GLFWwindow* m_window; + Scene* m_scene; + Camera* m_camera; + + b3WorldId m_worldId; + b3Vec3 m_mousePoint; + b3BodyId m_mouseBodyId; + b3JointId m_mouseJointId; + float m_mouseFraction; + float m_mouseForceScale; + float m_launchSpeedScale; + int m_stepCount; + int m_textLine; + int m_textIncrement; + int m_triangleIndex; + uint64_t m_userMaterialId; + + b3Profile m_profiles[m_profileCapacity]; + int m_currentProfileIndex; + int m_profileReadIndex; + int m_profileWriteIndex; + + b3Vec2 m_mouseLast; + b3Vec2 m_mouseDelta; + bool m_didStep; + bool m_stepWhilePaused; + bool m_haveMouseLast; +}; + +#define MAX_SAMPLES 256 + +typedef Sample* SampleCreateFcn( SampleContext* context ); + +struct SampleEntry +{ + const char* Category; + const char* Name; + SampleCreateFcn* CreateFcn; +}; + +class SampleManager +{ +public: + static int Register( const char* category, const char* name, SampleCreateFcn* fcn ); + + void Startup( GLFWwindow* window, int width, int height, int bufferWidth, int bufferHeight ); + void Step(); + void Resize( int width, int height, int bufferWidth, int bufferHeight ); + void Render( GLFWwindow* window, float elapsedTime ); + void Shutdown( GLFWwindow* window ); + + void Keyboard( int key, int action, int modifiers ); + + void CreateSample(); + + void RenderScene( GLFWwindow* window, float elapsedTime ); + void UpdateUI( GLFWwindow* window ); + + static SampleEntry sEntries[MAX_SAMPLES]; + static int sEntryCount; + + SampleContext m_context; + Sample* m_sample = nullptr; + bool m_showMenu = true; +}; + +struct CastClosestContext +{ + b3ShapeId shapeId; + b3Vec3 point; + b3Vec3 normal; + float fraction; + uint64_t materialId; + int childIndex; + int triangleIndex; + bool hit; +}; + +float CastClosestCallback( b3ShapeId shapeId, b3Vec3 point, b3Vec3 normal, float fraction, uint64_t materialId, + int triangleIndex, int childIndex, void* context ); + +struct MoverShapeUserData +{ + float maxPush; + bool clipVelocity; +}; + +struct PlaneExtra +{ + b3Vec3 point; + b3ShapeId shapeId; +}; + +struct CharacterMover +{ + static constexpr int m_planeCapacity = 8; + static constexpr float m_jumpSpeed = 5.0f; + static constexpr float m_maxSpeed = 6.0f; + static constexpr float m_minSpeed = 0.01f; + static constexpr float m_stopSpeed = 1.0f; + static constexpr float m_accelerate = 30.0f; + static constexpr float m_friction = 4.0f; + static constexpr float m_gravity = 15.0f; + + void Initialize( Sample* sample, b3Vec3 position ); + void SolveMove( float timeStep, b3Vec3 forward, b3Vec3 right, b3Vec2 throttle, bool clipVelocity ); + void Step( b3ShapeId* ignoreShapes, int ignoreCount, bool clipVelocity ); + + Sample* m_sample; + b3Transform m_transform; + b3Vec3 m_velocity; + b3Capsule m_capsule; + b3CollisionPlane m_planes[m_planeCapacity] = {}; + PlaneExtra m_planeExtras[m_planeCapacity] = {}; + int m_planeCount; + int m_totalIterations; + float m_pogoVelocity; + bool m_onGround; + bool m_sprint; + + // Transient + b3ShapeId* m_ignoreShapeIds; + int m_ignoreCount; +}; diff --git a/samples/sample_benchmark.cpp b/samples/sample_benchmark.cpp new file mode 100644 index 0000000..37d9ff4 --- /dev/null +++ b/samples/sample_benchmark.cpp @@ -0,0 +1,1468 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "benchmarks.h" +#include "camera.h" +#include "imgui.h" +#include "utils.h" +#include "renderer.h" +#include "sample.h" +#include "scene.h" + +#include "box3d/box3d.h" + +#include + +inline bool operator<( b3BodyId a, b3BodyId b ) +{ + uint64_t ua = b3StoreBodyId( a ); + uint64_t ub = b3StoreBodyId( b ); + return ua < ub; +} + +class BenchmarkLargePyramid : public Sample +{ +public: + explicit BenchmarkLargePyramid( SampleContext* context ) + : Sample( context ) + { + if (context->restart == false) + { + m_camera->SetView( 0.0f, 5.0f, 80.0f, { 0.0f, 18.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + CreateLargePyramid( m_worldId ); + } + + static Sample* Create( SampleContext* context ) + { + return new BenchmarkLargePyramid( context ); + } +}; + +static int sampleLargePyramid = SampleManager::Register( "Benchmark", "Large Pyramid", BenchmarkLargePyramid::Create ); + +class BenchmarkWidePyramid : public Sample +{ +public: + explicit BenchmarkWidePyramid( SampleContext* context ) + : Sample( context ) + { + if (context->restart == false) + { + m_camera->SetView( 0.0f, 5.0f, 80.0f, { 0.0f, 18.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + CreateWidePyramid( m_worldId ); + } + + static Sample* Create( SampleContext* context ) + { + return new BenchmarkWidePyramid( context ); + } +}; + +static int sampleWidePyramid = SampleManager::Register( "Benchmark", "Wide Pyramid", BenchmarkWidePyramid::Create ); + +class BenchmarkManyPyramids : public Sample +{ +public: + explicit BenchmarkManyPyramids( SampleContext* context ) + : Sample( context ) + { + if (context->restart == false) + { + m_camera->SetView( 0.0f, 5.0f, 80.0f, { 0.0f, 18.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + CreateManyPyramids( m_worldId ); + + // float frictionTorque = 5.0f; + // float hertz = 1.0f; + // float dampingRatio = 0.7f; + // bool colorize = true; + + // Human human = {}; + // b3Vec3 position = m_isDebug ? b3Vec3{ 0.0f, 20.0f, 0.0f } : b3Vec3{ 5.0f, 20.0f, 53.0f }; + // CreateHuman( &human, m_worldId, position, frictionTorque, hertz, dampingRatio, 0, nullptr, colorize ); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 4.0f ); + } + + static Sample* Create( SampleContext* context ) + { + return new BenchmarkManyPyramids( context ); + } +}; + +static int sampleManyPyramids = SampleManager::Register( "Benchmark", "Many Pyramids", BenchmarkManyPyramids::Create ); + +class BenchmarkRain : public Sample +{ +public: + explicit BenchmarkRain( SampleContext* context ) + : Sample( context ) + { + if (context->restart == false) + { + m_camera->SetView( 45.0f, 30.0f, 40.0f, b3Vec3_zero ); + context->debugDraw.drawJoints = false; + } + + b3Capacity capacity = {}; + GetRainCapacity( &capacity ); + CreateWorld( &capacity ); + + CreateRain( m_worldId ); + } + + ~BenchmarkRain() override + { + DestroyRain(); + } + + void Step() override + { + StepRain( m_worldId, m_stepCount ); + + // This is for testing adjustable worker count + // if (m_stepCount == 200) + //{ + // m_scheduler->Initialize( 3 ); + // b3World_SetWorkerCount( m_worldId, 3 ); + //} + + Sample::Step(); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 2.0f ); + } + + static Sample* Create( SampleContext* context ) + { + return new BenchmarkRain( context ); + } +}; + +static int sampleRain = SampleManager::Register( "Benchmark", "Rain", BenchmarkRain::Create ); + +#if 0 +class BenchmarkLargeWorld : public Sample +{ +public: + explicit BenchmarkLargeWorld( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 40.0f, b3Vec3_zero ); + } + + CreateRain( m_worldId ); + } + + ~BenchmarkLargeWorld() override + { + DestroyRain(); + } + + void Step() override + { + StepRain( m_worldId, m_stepCount ); + + // This is for testing adjustable worker count + // if (m_stepCount == 200) + //{ + // m_scheduler->Initialize( 3 ); + // b3World_SetWorkerCount( m_worldId, 3 ); + //} + + Sample::Step(); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 2.0f ); + } + + static Sample* Create( SampleContext* context ) + { + return new BenchmarkLargeWorld( context ); + } +}; + +static int sampleLargeWorld = SampleManager::Register( "Benchmark", "Large World", BenchmarkLargeWorld::Create ); +#endif + +class BenchmarkJointGrid : public Sample +{ +public: + explicit BenchmarkJointGrid( SampleContext* context ) + : Sample( context ) + { + if (context->restart == false) + { + m_camera->SetView( -25.0f, 25.0f, 94.0f, { 30.0f, -30.0f, 30.0f } ); + } + + CreateJointGrid( m_worldId ); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 4.0f ); + + // transform.p.y = 0.0f; + // transform.p.z = -5.0f; + + // for (int i = 0; i < 100; ++i) + //{ + // transform.p.x = -50.0f; + // for (int j = 0; j < 100; ++j) + // { + // AddSphere( m_scene, transform, 0.5f, b3_colorYellowGreen ); + // transform.p.x += 1.0f; + // } + + // transform.p.y -= 1.0f; + //} + } + + static Sample* Create( SampleContext* context ) + { + return new BenchmarkJointGrid( context ); + } +}; + +static int sampleJointGrid = SampleManager::Register( "Benchmark", "Joint Grid", BenchmarkJointGrid::Create ); + +class FallingBoxes : public Sample +{ +public: + explicit FallingBoxes( SampleContext* context ) + : Sample( context ) + { + if (context->restart == false) + { + m_camera->SetView( 45.0f, 45.0f, 250.0f, b3Vec3_zero ); + EnableGrid( m_scene, true ); + } + + { + b3BoxHull groundBox = b3MakeBoxHull( 250.0f, 1.0f, 250.0f ); + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + } + + { + constexpr int n = m_isDebug ? 4 : 50; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull box = b3MakeBoxHull( 1.0f, 1.0f, 1.0f ); + + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < 8; ++j) + { + for (int k = 0; k < 8; ++k) + { + bodyDef.position = { -16.0f + 4.0f * j, 4.0f * i + 5.0f, -16.0f + 4.0f * k }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + } + } + } + } + + static Sample* Create( SampleContext* context ) + { + return new FallingBoxes( context ); + } +}; + +static int sampleFallingBoxes = SampleManager::Register( "Benchmark", "Falling Boxes", FallingBoxes::Create ); + +class CandyCups : public Sample +{ +public: + explicit CandyCups( SampleContext* context ) + : Sample( context ) + { + if (context->restart == false) + { + m_camera->SetView( 45.0f, 35.0f, 40.0f, b3Vec3_zero ); + EnableGrid( m_scene, true ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull groundBox = b3MakeBoxHull( 250.0f, 1.0f, 250.0f ); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + } + + { + constexpr int n = m_isDebug ? 4 : 16; + constexpr int m = m_isDebug ? 4 : 16; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + m_convex = CreateConvex( 0.6f, 0.0f, 0.95f, 1.0f, context->arena ); + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < m; ++j) + { + for (int k = 0; k < m; ++k) + { + bodyDef.position = { -10.0f + 2.5f * j, 1.0f * i, -10.0f + 2.5f * k }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, m_convex ); + } + } + } + } + } + + ~CandyCups() override + { + b3DestroyHull( m_convex ); + } + + b3Hull* CreateConvex( float radius1, float height1, float radius2, float height2, Arena arena ) const + { + const int sideCount = 8; + const float deltaAlpha = 2.0f * B3_PI / sideCount; + + int vertexCount = 2 * sideCount; + b3Vec3* vertexBase = static_cast( arena.Allocate( vertexCount * sizeof( b3Vec3 ) ) ); + + float alpha = 0.0f; + for (int sideIndex = 0; sideIndex < sideCount; ++sideIndex) + { + b3CosSin cs = b3ComputeCosSin( alpha ); + + float x1 = radius1 * cs.cosine; + float z1 = radius1 * cs.sine; + float x2 = radius2 * cs.cosine; + float z2 = radius2 * cs.sine; + + vertexBase[2 * sideIndex + 0] = { x1, height1, z1 }; + vertexBase[2 * sideIndex + 1] = { x2, height2, z2 }; + alpha += deltaAlpha; + } + + return b3CreateHull( vertexBase, vertexCount, vertexCount ); + } + + static Sample* Create( SampleContext* context ) + { + return new CandyCups( context ); + } + + b3Hull* m_convex; +}; + +static int sampleSmallConvexes = SampleManager::Register( "Benchmark", "Candy Cups", CandyCups::Create ); + +class BenchmarkExplosion : public Sample +{ +public: + explicit BenchmarkExplosion( SampleContext* context ) + : Sample( context ) + { + if (m_context->restart == false) + { + m_camera->SetView( 0.0f, 40.0f, 10.0f, { 0.0f, 0.0f, 0.0f } ); + } + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.name = "grid"; + m_gridMesh = b3CreateGridMesh( 40, 40, 1.0f, 0, true ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateMeshShape( groundId, &shapeDef, m_gridMesh, b3Vec3_one ); + + { + b3Transform transform; + transform.p = { 0.0f, 5.0f, -20.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 20.0f, 5.0f, 0.1f, transform ); + shapeDef.name = "wall1"; + b3CreateHullShape( groundId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform; + transform.p = { 0.0f, 5.0f, 20.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 20.0f, 5.0f, 0.1f, transform ); + shapeDef.name = "wall2"; + b3CreateHullShape( groundId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform; + transform.p = { -20.0f, 5.0f, 0.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, 5.0f, 20.0f, transform ); + shapeDef.name = "wall3"; + b3CreateHullShape( groundId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform; + transform.p = { 20.0f, 5.0f, 0.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, 5.0f, 20.0f, transform ); + shapeDef.name = "wall4"; + b3CreateHullShape( groundId, &shapeDef, &wallBox.base ); + } + + // Using 15 sides rather than 16 to avoid manifold degeneracies + m_cylinder = b3CreateCylinder( 0.5f, 0.2f, 0.0f, 15 ); + + constexpr int n = m_isDebug ? 3 : 16; + + bodyDef.type = b3_dynamicBody; + shapeDef.explosionScale = 2.0f; + + for (int i = -n; i <= n; ++i) + { + for (int k = -n; k <= n; ++k) + { + bodyDef.position = { 1.0f * i, 0.0f, 1.0f * k }; + + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, m_cylinder ); + } + } + + m_impulse = 1000.0f; + + m_stepWhilePaused = false; + } + + ~BenchmarkExplosion() override + { + b3DestroyHull( m_cylinder ); + b3DestroyMesh( m_gridMesh ); + } + + void Explode() + { + b3ExplosionDef def = b3DefaultExplosionDef(); + def.radius = 16.0f; + def.position = { 0.0f, -4.0f, 0.0f }; + def.impulsePerArea = m_impulse; + + b3World_Explode( m_worldId, &def ); + } + + void UpdateUI() override + { + Sample::UpdateUI(); + + float fontSize = ImGui::GetFontSize(); + float height = 10.0f * fontSize; + ImGui::SetNextWindowPos( { 1.0f * fontSize, m_camera->m_height - height - 3.0f * fontSize }, ImGuiCond_Once ); + ImGui::SetNextWindowSize( { 20.0f * fontSize, height } ); + + ImGui::Begin( "Explosion", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + + ImGui::SliderFloat( "impulse", &m_impulse, 0.0f, 2000.0f, "%.0f" ); + + if (ImGui::Button( "explode" )) + { + Explode(); + } + + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 4.0f ); + } + + static Sample* Create( SampleContext* context ) + { + return new BenchmarkExplosion( context ); + } + + b3MeshData* m_gridMesh; + b3Hull* m_cylinder; + float m_impulse; +}; + +static int sampleExplosion = SampleManager::Register( "Benchmark", "Explosion", BenchmarkExplosion::Create ); + +class BenchmarkHeightField : public Sample +{ +public: + struct Context + { + b3Vec3 point; + b3Vec3 normal; + float fraction; + bool hit; + }; + + static float CastCallback( b3ShapeId shapeId, b3Vec3 point, b3Vec3 normal, float fraction, uint64_t userMaterialId, + int triangleIndex, int childIndex, void* context ) + { + (void)shapeId; + (void)userMaterialId; + (void)triangleIndex; + (void)childIndex; + + Context* rayContext = (Context*)context; + rayContext->point = point; + rayContext->normal = normal; + rayContext->fraction = fraction; + rayContext->hit = true; + return fraction; + } + + explicit BenchmarkHeightField( SampleContext* context ) + : Sample( context ) + { + if (context->restart == false) + { + m_camera->SetView( 45.0f, 30.0f, 20.0f ); + } + + m_columnCount = 50; + m_rowCount = 50; + m_radius = 0.1f; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { -0.5f * m_columnCount, 0.0f, -0.5f * m_rowCount }; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + + m_heightField = b3CreateWave( 50, 50, b3Vec3_one, 0.02f, 0.04f, true ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHeightFieldShape( body, &shapeDef, m_heightField ); + } + + ~BenchmarkHeightField() override + { + b3DestroyHeightField( m_heightField ); + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 4.0f * fontSize; + ImGui::SetNextWindowPos( { 1.0f * fontSize, m_camera->m_height - height - 3.0f * fontSize }, ImGuiCond_Once ); + ImGui::SetNextWindowSize( { 20.0f * fontSize, height } ); + + ImGui::Begin( "Height Field", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + ImGui::SliderFloat( "radius", &m_radius, 0.0f, 1.0f, "%.1f" ); + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + + DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisX, b3_colorRed ); + DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisY, b3_colorGreen ); + DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisZ, b3_colorBlue ); + + int hitCount = 0; + int iterationCount = 0; + int innerIterationCount = 0; + + float delta = m_isDebug ? 2.0f * 0.95f : 0.4f; + + float spanX = 0.94f * 0.5f * m_columnCount; + float spanZ = 0.96f * 0.5f * m_rowCount; + + uint64_t startTick = b3GetTicks(); + + b3Vec3 rayTranslation = { 80000.0f, -80000.0f, 8.0f }; + // b3Vec3 rayTranslation = { 0.0f, -16.0f, 0.0f }; + + b3Sphere sphere = { b3Vec3_zero, m_radius }; + int castCount = 0; + + for (float x = -spanX; x <= spanX; x += delta) + { + for (float z = -spanZ; z <= spanZ; z += delta) + { + b3Vec3 rayOrigin = { x, 2.0f, z }; + + b3RayResult result = {}; + if (m_radius == 0.0f) + { + result = b3World_CastRayClosest( m_worldId, rayOrigin, rayTranslation, b3DefaultQueryFilter() ); + } + else + { + Context context = {}; + b3ShapeProxy proxy = { &rayOrigin, 1, m_radius }; + b3World_CastShape( m_worldId, &proxy, rayTranslation, b3DefaultQueryFilter(), CastCallback, &context ); + + if (context.hit) + { + result.point = context.point; + result.normal = context.normal; + result.fraction = context.fraction; + result.hit = true; + } + } + + castCount += 1; + + if (result.hit) + { + hitCount += 1; + if (m_isDebug) + { + b3Vec3 point = result.point; + DrawLine( m_scene, point, point + 0.5f * result.normal, b3_colorGreen ); + DrawPoint( m_scene, point, 10.0f, b3_colorGreen ); + + if (m_radius > 0.0f) + { + b3Transform transform = b3Transform_identity; + transform.p = rayOrigin + result.fraction * rayTranslation; + DrawSphere( m_scene, transform, sphere, b3_colorPurple ); + } + + b3Vec3 rayEnd = rayOrigin + result.fraction * rayTranslation; + DrawLine( m_scene, rayOrigin, rayEnd, b3_colorYellow ); + DrawPoint( m_scene, rayOrigin, 2.0f, b3_colorRed ); + DrawPoint( m_scene, rayEnd, 2.0f, b3_colorRed ); + } + } + else if (m_isDebug) + { + b3Vec3 rayEnd = rayOrigin + rayTranslation; + DrawLine( m_scene, rayOrigin, rayEnd, b3_colorYellow ); + DrawPoint( m_scene, rayOrigin, 2.0f, b3_colorRed ); + DrawPoint( m_scene, rayEnd, 2.0f, b3_colorRed ); + } + } + } + + float milliseconds = b3GetMilliseconds( startTick ); + uint64_t tickCount = b3GetTicks() - startTick; + float aveIterations = float( iterationCount ) / float( castCount ); + float aveInner = float( innerIterationCount ) / float( castCount ); + + float aveCastTime = 1000.0f * milliseconds / float( castCount ); + + DrawTextLine( "count = %d, hit count = %d, iterations = %d, inner = %d, ticks = %ld", castCount, hitCount, iterationCount, + innerIterationCount, tickCount ); + + DrawTextLine( "ave iterations = %.1f, ave inner = %.1f, ave cast us %.3f", aveIterations, aveInner, aveCastTime ); + } + + static Sample* Create( SampleContext* context ) + { + return new BenchmarkHeightField( context ); + } + + b3HeightField* m_heightField; + int m_columnCount; + int m_rowCount; + float m_radius; +}; + +static int sampleHeightFieldBenchmark = SampleManager::Register( "Benchmark", "Height Field", BenchmarkHeightField::Create ); + +class BenchmarkCompoundCapsules : public Sample +{ +public: + explicit BenchmarkCompoundCapsules( SampleContext* context ) + : Sample( context ) + { + if (context->restart == false) + { + float distance = 220.0f; + float height = 20.0f; + m_camera->SetView( 25.0f, 10.0f, distance, { 0.0f, height, 0.0f } ); + } + + CreateCompoundCapsules( m_worldId ); + } + + ~BenchmarkCompoundCapsules() override + { + DestroyCompoundCapsules(); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 4.0f ); + } + + static Sample* Create( SampleContext* context ) + { + return new BenchmarkCompoundCapsules( context ); + } +}; + +static int sampleCompoundCapsules = + SampleManager::Register( "Benchmark", "Compounds Capsules", BenchmarkCompoundCapsules::Create ); + +class BenchmarkCompoundHulls : public Sample +{ +public: + explicit BenchmarkCompoundHulls( SampleContext* context ) + : Sample( context ) + { + if (context->restart == false) + { + float distance = 220.0f; + float height = 20.0f; + m_camera->SetView( 25.0f, 10.0f, distance, { 0.0f, height, 0.0f } ); + } + + CreateCompoundHulls( m_worldId ); + } + + ~BenchmarkCompoundHulls() override + { + DestroyCompoundHulls(); + } + + static Sample* Create( SampleContext* context ) + { + return new BenchmarkCompoundHulls( context ); + } +}; + +static int sampleCompoundHulls = SampleManager::Register( "Benchmark", "Compounds Hulls", BenchmarkCompoundHulls::Create ); + +class WeldedHulls : public Sample +{ +public: + explicit WeldedHulls( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + float distance = 220.0f; + float height = 20.0f; + m_camera->SetView( 25.0f, 10.0f, distance, { 0.0f, height, 0.0f } ); + } + + CreateWeldedHulls( m_worldId ); + } + + ~WeldedHulls() override + { + DestroyWeldedHulls(); + } + + static Sample* Create( SampleContext* context ) + { + return new WeldedHulls( context ); + } +}; + +static int sampleWeldedHulls = SampleManager::Register( "Benchmark", "Welded Hulls", WeldedHulls::Create ); + +struct ShapeUserData +{ + int row; + bool active; +}; + +class BenchmarkSensor : public Sample +{ +public: + explicit BenchmarkSensor( SampleContext* context ) + : Sample( context ) + { + if (m_context->restart == false) + { + m_camera->SetView( 5.0f, 18.0f, 180.0f, { 0.0f, 5.0f, 0.0f } ); + } + + b3World_SetCustomFilterCallback( m_worldId, FilterFcn, this ); + + m_activeSensor.row = 0; + m_activeSensor.active = true; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + { + float gridSize = 3.0f; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + 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) + { + b3Vec3 extents = { 0.5f * gridSize, 0.5f * gridSize, 0.5f * gridSize }; + b3Transform transform = { { x, y, 0.0f }, b3Quat_identity }; + b3BoxHull box = b3MakeTransformedBoxHull( extents.x, extents.y, extents.z, transform ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + x += gridSize; + } + } + + g_randomSeed = 42; + + float shift = 5.0f; + float xCenter = 0.5f * shift * m_columnCount; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.isSensor = true; + shapeDef.enableSensorEvents = true; + + float yStart = 10.0f; + + for (int j = 0; j < m_rowCount; ++j) + { + m_passiveSensors[j].row = j; + m_passiveSensors[j].active = false; + shapeDef.userData = m_passiveSensors + j; + + float y = j * shift + yStart; + for (int i = 0; i < m_columnCount; ++i) + { + float x = i * shift - xCenter; + b3Vec3 extents = { 0.5f, 0.5f, 0.5f }; + b3Transform transform = { { x, y, 0.0f }, b3Quat_identity }; + b3BoxHull box = b3MakeTransformedBoxHull( extents.x, extents.y, extents.z, transform ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + } + + m_maxBeginCount = 0; + m_maxEndCount = 0; + m_lastStepCount = 0; + m_filterRow = m_rowCount >> 1; + } + + void CreateRow( float y ) + { + float shift = 5.0f; + float xCenter = 0.5f * shift * m_columnCount; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.gravityScale = 0.0f; + bodyDef.linearVelocity = { 0.0f, -5.0f }; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.enableSensorEvents = true; + + b3Sphere sphere = { { 0.0f, 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, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + } + } + + void Step() override + { + Sample::Step(); + + if (m_stepCount == m_lastStepCount) + { + return; + } + + std::set zombies; + + b3SensorEvents events = b3World_GetSensorEvents( m_worldId ); + for (int i = 0; i < events.beginCount; ++i) + { + b3SensorBeginTouchEvent* event = events.beginEvents + i; + + // shapes on begin touch are always valid + + ShapeUserData* userData = static_cast( b3Shape_GetUserData( event->sensorShapeId ) ); + if (userData->active) + { + zombies.emplace( b3Shape_GetBody( event->visitorShapeId ) ); + } + else + { + // Check custom filter correctness + assert( userData->row != m_filterRow ); + + // Modify color while overlapped with a sensor + b3SurfaceMaterial surfaceMaterial = b3Shape_GetSurfaceMaterial( event->visitorShapeId ); + surfaceMaterial.customColor = b3_colorLime; + b3Shape_SetSurfaceMaterial( event->visitorShapeId, surfaceMaterial ); + } + } + + for (int i = 0; i < events.endCount; ++i) + { + b3SensorEndTouchEvent* event = events.endEvents + i; + + if (b3Shape_IsValid( event->visitorShapeId ) == false) + { + continue; + } + + // Restore color to default + b3SurfaceMaterial surfaceMaterial = b3Shape_GetSurfaceMaterial( event->visitorShapeId ); + surfaceMaterial.customColor = 0; + b3Shape_SetSurfaceMaterial( event->visitorShapeId, surfaceMaterial ); + } + + for (b3BodyId bodyId : zombies) + { + b3DestroyBody( bodyId ); + } + + int delay = 0x1F; + + if (( m_stepCount & delay ) == 0) + { + CreateRow( 10.0f + m_rowCount * 5.0f ); + } + + m_lastStepCount = m_stepCount; + + m_maxBeginCount = b3MaxInt( events.beginCount, m_maxBeginCount ); + m_maxEndCount = b3MaxInt( events.endCount, m_maxEndCount ); + DrawTextLine( "max begin touch events = %d", m_maxBeginCount ); + DrawTextLine( "max end touch events = %d", m_maxEndCount ); + } + + bool Filter( b3ShapeId idA, b3ShapeId idB ) + { + ShapeUserData* userData = nullptr; + if (b3Shape_IsSensor( idA )) + { + userData = (ShapeUserData*)b3Shape_GetUserData( idA ); + } + else if (b3Shape_IsSensor( idB )) + { + userData = (ShapeUserData*)b3Shape_GetUserData( idB ); + } + + if (userData != nullptr) + { + return userData->active == true || userData->row != m_filterRow; + } + + return true; + } + + static bool FilterFcn( b3ShapeId idA, b3ShapeId 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 = SampleManager::Register( "Benchmark", "Sensor", BenchmarkSensor::Create ); + +class BenchmarkWasher : public Sample +{ +public: + explicit BenchmarkWasher( SampleContext* context ) + : Sample( context ) + { + if (m_context->restart == false) + { + m_camera->SetView( 0.0f, 20.0f, 60.0, { 0.0f, 15.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + b3Capacity capacity = {}; + GetWasherCapacity( &capacity ); + CreateWorld( &capacity ); + + CreateWasher( m_worldId ); + } + + static Sample* Create( SampleContext* context ) + { + return new BenchmarkWasher( context ); + } +}; + +static int benchmarkWasher = SampleManager::Register( "Benchmark", "Washer", BenchmarkWasher::Create ); + +class BenchmarkHull : public Sample +{ +public: + explicit BenchmarkHull( SampleContext* context ) + : Sample( context ) + { + if (m_context->restart == false) + { + m_camera->SetView( 0.0f, 15.0f, 5.0f, b3Vec3_zero ); + } + + g_randomSeed = 42; + + m_count = 64; + for (int i = 0; i < m_count; ++i) + { + m_points[i] = RandomVec3( { -1.0f, -1.0f, -1.0f }, { 1.0f, 1.0f, 1.0f } ); + } + + m_hull = b3CreateHull( m_points, m_count, m_count ); + m_scale = { -1.0f, 1.0f, 1.0f }; + m_transformedHull = b3CloneAndTransformHull( m_hull, b3Transform_identity, m_scale ); + } + + ~BenchmarkHull() override + { + b3DestroyHull( m_hull ); + b3DestroyHull( m_transformedHull ); + } + + void Render() override + { + b3Transform transform1 = { { -2.0f, 0.0f, 0.0f }, b3Quat_identity }; + b3Transform transform2 = { { 2.0f, 0.0f, 0.0f }, b3Quat_identity }; + + DrawHull( m_scene, transform1, m_hull, b3_colorGreen, true ); + DrawHull( m_scene, transform2, m_transformedHull, b3_colorYellow, true ); + + Sample::Render(); + } + + void Step() override + { + uint64_t startTick = b3GetTicks(); + float area = 0.0f; + int trials = m_isDebug ? 200 : 2000; + + for (int i = 0; i < trials; ++i) + { + b3Hull* hull = b3CreateHull( m_points, m_count, m_count ); + area += hull->surfaceArea; + b3DestroyHull( hull ); + } + + float createTime = b3GetMillisecondsAndReset( &startTick ); + + float scaledArea = 0.0f; + for (int i = 0; i < trials; ++i) + { + b3Hull* hull = b3CloneAndTransformHull( m_hull, b3Transform_identity, m_scale ); + scaledArea += hull->surfaceArea; + b3DestroyHull( hull ); + } + + float cloneTime = b3GetMilliseconds( startTick ); + + DrawTextLine( "trials = %d", trials ); + DrawTextLine( "createTime (us) = %.2f, area = %.2f", 1000.0f * createTime / trials, area / trials ); + DrawTextLine( "cloneTime (us) = %.2f, area = %.2f", 1000.0f * cloneTime / trials, scaledArea / trials ); + DrawTextLine( "createTime / cloneTime = %.2f", createTime / cloneTime ); + Sample::Step(); + } + + static Sample* Create( SampleContext* sampleContext ) + { + return new BenchmarkHull( sampleContext ); + } + + static constexpr int m_capacity = 64; + b3Hull* m_hull; + b3Hull* m_transformedHull; + b3Vec3 m_scale; + b3Vec3 m_points[m_capacity]; + int m_count; +}; + +static int sampleBenchmarkHull = SampleManager::Register( "Benchmark", "Hull", BenchmarkHull::Create ); + +class BenchmarkChains : public Sample +{ +public: + explicit BenchmarkChains( SampleContext* context ) + : Sample( context ) + { + if (context->restart == false) + { + m_camera->SetView( 0.0f, 15.0f, 50.0f, { 0.0f, 5.0f, 0.0f } ); + EnableGrid( context->scene, false ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + m_meshData = b3CreateWaveMesh( 80, 80, 1.0f, 0.5f, 0.05f, 0.01f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateMeshShape( groundId, &shapeDef, m_meshData, b3Vec3_one ); + + float linkRadius = 0.125f; + float linkExtent = 0.25f; + b3Capsule capsule = { { 0.0f, -linkExtent, 0.0f }, { 0.0f, linkExtent, 0.0f }, linkRadius }; + + bodyDef.enableSleep = false; + + int linkCount = 4; + + b3SphericalJointDef jointDef = b3DefaultSphericalJointDef(); + jointDef.base.localFrameA = { { 0.0f, -linkExtent, 0.0f }, b3Quat_identity }; + jointDef.base.localFrameB = { { 0.0f, linkExtent, 0.0f }, b3Quat_identity }; + jointDef.enableSpring = true; + jointDef.hertz = 1.0f; + jointDef.dampingRatio = 0.7f; + jointDef.enableMotor = true; + jointDef.maxMotorTorque = 1.0f; + + int shapeIndex = 0; + + float x = -1.0f * m_gridCount; + for (int rowIndex = 0; rowIndex < m_gridCount; ++rowIndex) + { + float z = -1.0f * m_gridCount; + for (int columnIndex = 0; columnIndex < m_gridCount; ++columnIndex) + { + for (int i = 0; i < linkCount; ++i) + { + bodyDef.position = { x, ( 1.0f - 2.0f * i ) * linkExtent + 3.0f, z }; + + bodyDef.type = i == 0 ? b3_staticBody : b3_dynamicBody; + + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeId shapeId = b3CreateCapsuleShape( bodyId, &shapeDef, &capsule ); + if (i == linkCount - 1) + { + m_shapeIds[shapeIndex] = shapeId; + shapeIndex += 1; + } + + if (i > 0) + { + jointDef.base.bodyIdB = bodyId; + b3CreateSphericalJoint( m_worldId, &jointDef ); + } + + jointDef.base.bodyIdA = bodyId; + } + + z += 2.0f; + } + + x += 2.0f; + } + + m_noise = {}; + } + + ~BenchmarkChains() override + { + b3DestroyMesh( m_meshData ); + } + + void Step() override + { + b3Vec3 baseWind = { 20.0f, 0.0f, 0.0f }; + float speed; + b3Vec3 direction = b3GetLengthAndNormalize( &speed, baseWind ); + b3Vec3 wind = b3MulSV( speed, b3Add( direction, m_noise ) ); + + for (int i = 0; i < m_gridCount * m_gridCount; ++i) + { + b3Shape_ApplyWind( m_shapeIds[i], wind, 1.0f, 1.0f, 20.0f, false ); + } + + b3Vec3 rand = RandomVec3( { -0.3f, -0.3f, -0.3f }, { 0.3f, 0.3f, 0.3f } ); + m_noise = b3Lerp( m_noise, rand, 0.05f ); + + Sample::Step(); + } + + static Sample* Create( SampleContext* context ) + { + return new BenchmarkChains( context ); + } + + static constexpr int m_gridCount = m_isDebug ? 10 : 25; + b3ShapeId m_shapeIds[m_gridCount * m_gridCount]; + b3MeshData* m_meshData; + b3Vec3 m_noise; +}; + +static int sampleBenchmarkChains = SampleManager::Register( "Benchmark", "Chains", BenchmarkChains::Create ); + +class BenchmarkDestruction : public Sample +{ +public: + explicit BenchmarkDestruction( SampleContext* context ) + : Sample( context ) + { + if (m_context->restart == false) + { + if (m_small) + { + m_camera->SetView( 0.0f, 40.0f, 10.0f, { 0.0f, 0.0f, 0.0f } ); + } + else + { + m_camera->SetView( 0.0f, 40.0f, 30.0f, { 0.0f, 0.0f, 0.0f } ); + } + EnableGrid( m_context->scene, false ); + } + + int bodyCapacity = m_gridCount * m_gridCount * m_gridCount; + + b3Capacity capacity = {}; + capacity.dynamicShapeCount = bodyCapacity; + capacity.dynamicBodyCount = bodyCapacity; + capacity.contactCount = m_small ? 10000 : 50000; + CreateWorld( &capacity ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.name = "grid"; + m_gridMesh = b3CreateGridMesh( 40, 40, 1.0f, 0, true ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateMeshShape( groundId, &shapeDef, m_gridMesh, b3Vec3_one ); + + { + b3Transform transform; + transform.p = { 0.0f, 5.0f, -20.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 20.0f, 5.0f, 0.1f, transform ); + shapeDef.name = "wall1"; + b3CreateHullShape( groundId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform; + transform.p = { 0.0f, 5.0f, 20.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 20.0f, 5.0f, 0.1f, transform ); + shapeDef.name = "wall2"; + b3CreateHullShape( groundId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform; + transform.p = { -20.0f, 5.0f, 0.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, 5.0f, 20.0f, transform ); + shapeDef.name = "wall3"; + b3CreateHullShape( groundId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform; + transform.p = { 20.0f, 5.0f, 0.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, 5.0f, 20.0f, transform ); + shapeDef.name = "wall4"; + b3CreateHullShape( groundId, &shapeDef, &wallBox.base ); + } + + m_bodyIds = (b3BodyId*)malloc( bodyCapacity * sizeof( b3BodyId ) ); + memset( m_bodyIds, 0, bodyCapacity * sizeof( b3BodyId ) ); + m_bodyCount = 0; + + m_explosionDef = b3DefaultExplosionDef(); + m_explosionDef.radius = m_extent; + m_explosionDef.falloff = 0.5f * m_extent; + m_explosionDef.position = { 0.0f, 2.0f * m_extent, 0.0f }; + m_explosionDef.impulsePerArea = m_small ? 200.0f : 1000.0f; + + m_spawnMilliseconds = 0.0f; + m_destroyMilliseconds = 0.0f; + + Spawn(); + } + + ~BenchmarkDestruction() override + { + b3DestroyMesh( m_gridMesh ); + free( m_bodyIds ); + } + + void DestroyBodies() + { + uint64_t ticks = b3GetTicks(); + + for (int i = 0; i < m_bodyCount; ++i) + { + b3DestroyBody( m_bodyIds[i] ); + } + + m_destroyMilliseconds = b3GetMilliseconds( ticks ); + } + + void Spawn() + { + uint64_t ticks = b3GetTicks(); + + float a = m_extent / m_gridCount; + b3BoxHull box = b3MakeBoxHull( 0.8f * a, 0.8f * a, 0.8f * a ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + int randomRange = m_small ? 3 : 2; + m_bodyCount = 0; + for (int i = 0; i < m_gridCount; ++i) + { + for (int j = 0; j < m_gridCount; ++j) + { + for (int k = 0; k < m_gridCount; ++k) + { + if (RandomIntRange( 1, randomRange ) == 1) + { + continue; + } + + bodyDef.position = { ( 2.0f * i - m_gridCount + 1.0f ) * a, ( 2.0f * j + 1.0f ) * a, + ( 2.0f * k - m_gridCount + 1.0f ) * a }; + + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + m_bodyIds[m_bodyCount] = bodyId; + m_bodyCount += 1; + } + } + } + + b3World_Explode( m_worldId, &m_explosionDef ); + + m_spawnMilliseconds = b3GetMilliseconds( ticks ); + } + + void Render() override + { + Sample::Render(); + + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 4.0f ); + + DrawTextLine( "spawn = %.2f ms", m_spawnMilliseconds ); + DrawTextLine( "destroy = %.2f ms", m_destroyMilliseconds ); + + float r = m_explosionDef.radius; + DrawSphere( m_scene, b3Transform_identity, { m_explosionDef.position, r }, b3_colorAqua ); + + float rf = r + m_explosionDef.falloff; + DrawSphere( m_scene, b3Transform_identity, { m_explosionDef.position, rf }, b3_colorCornsilk ); + } + + void Step() override + { + Sample::Step(); + + int spawnStep = m_small ? 80 : 140; + if (m_stepCount % spawnStep == 0) + { + DestroyBodies(); + Spawn(); + } + } + + static Sample* Create( SampleContext* context ) + { + return new BenchmarkDestruction( context ); + } + + static constexpr bool m_small = m_isDebug; + static constexpr int m_gridCount = m_small ? 6 : 20; + static constexpr float m_extent = m_small ? 0.75f : 2.5f; + + b3BodyId* m_bodyIds; + int m_bodyCount; + b3ExplosionDef m_explosionDef; + b3MeshData* m_gridMesh; + float m_spawnMilliseconds; + float m_destroyMilliseconds; +}; + +static int sampleDestruction = SampleManager::Register( "Benchmark", "Destruction", BenchmarkDestruction::Create ); + +class BenchmarkJunkyard : public Sample +{ +public: + explicit BenchmarkJunkyard( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 100.0f, b3Vec3_zero ); + context->debugDraw.drawJoints = false; + EnableGrid( m_scene, true ); + } + + CreateJunkyard( m_worldId ); + } + + void Step() override + { + StepJunkyard( m_worldId, m_stepCount ); + Sample::Step(); + } + + static Sample* Create( SampleContext* context ) + { + return new BenchmarkJunkyard( context ); + } +}; + +static int sampleJunkyard = SampleManager::Register( "Benchmark", "Junkyard", BenchmarkJunkyard::Create ); diff --git a/samples/sample_bodies.cpp b/samples/sample_bodies.cpp new file mode 100644 index 0000000..40d7ada --- /dev/null +++ b/samples/sample_bodies.cpp @@ -0,0 +1,965 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "GLFW/glfw3.h" +#include "camera.h" +#include "imgui.h" +#include "renderer.h" +#include "sample.h" +#include "scene.h" + +#include "box3d/box3d.h" + +class BodyType : public Sample +{ +public: + explicit BodyType( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 30.0f, 30.0f, { 0.0f, 1.5f, 0.0f } ); + } + + m_type = b3_dynamicBody; + m_isEnabled = true; + + b3BodyId groundId = b3_nullBodyId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position.y = -1.0f; + bodyDef.name = "ground"; + groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull box = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + + // Define attachment + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { -2.0f, 3.0f, 0.0f }; + bodyDef.name = "attach1"; + m_attachmentId = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull box = b3MakeBoxHull( 0.5f, 2.0f, 0.5f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 1.0f; + b3CreateHullShape( m_attachmentId, &shapeDef, &box.base ); + } + + // Define second attachment + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = m_type; + bodyDef.isEnabled = m_isEnabled; + bodyDef.position = { 3.0f, 3.0f }; + bodyDef.name = "attach2"; + m_secondAttachmentId = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull box = b3MakeBoxHull( 0.5f, 2.0f, 0.5f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 1.0f; + b3CreateHullShape( m_secondAttachmentId, &shapeDef, &box.base ); + } + + // Define platform + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = m_type; + bodyDef.isEnabled = m_isEnabled; + bodyDef.position = { -4.0f, 5.0f }; + bodyDef.name = "platform"; + m_platformId = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull box = b3MakeTransformedBoxHull( + 0.5f, 4.0f, 0.5f, { { 4.0f, 0.0f, 0.0f }, b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.5f * B3_PI ) } ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 2.0f; + b3CreateHullShape( m_platformId, &shapeDef, &box.base ); + + b3RevoluteJointDef revoluteDef = b3DefaultRevoluteJointDef(); + b3Vec3 pivot = { -2.0f, 5.0f, 0.0f }; + revoluteDef.base.bodyIdA = m_attachmentId; + revoluteDef.base.bodyIdB = m_platformId; + revoluteDef.base.localFrameA.p = b3Body_GetLocalPoint( m_attachmentId, pivot ); + revoluteDef.base.localFrameB.p = b3Body_GetLocalPoint( m_platformId, pivot ); + revoluteDef.maxMotorTorque = 50.0f; + revoluteDef.enableMotor = true; + b3CreateRevoluteJoint( m_worldId, &revoluteDef ); + + pivot = { 3.0f, 5.0f }; + revoluteDef.base.bodyIdA = m_secondAttachmentId; + revoluteDef.base.bodyIdB = m_platformId; + revoluteDef.base.localFrameA.p = b3Body_GetLocalPoint( m_secondAttachmentId, pivot ); + revoluteDef.base.localFrameB.p = b3Body_GetLocalPoint( m_platformId, pivot ); + revoluteDef.maxMotorTorque = 50.0f; + revoluteDef.enableMotor = true; + b3CreateRevoluteJoint( m_worldId, &revoluteDef ); + + b3PrismaticJointDef prismaticDef = b3DefaultPrismaticJointDef(); + b3Vec3 anchor = { 0.0f, 5.0f, 0.0f }; + prismaticDef.base.bodyIdA = groundId; + prismaticDef.base.bodyIdB = m_platformId; + prismaticDef.base.localFrameA.p = b3Body_GetLocalPoint( groundId, anchor ); + prismaticDef.base.localFrameB.p = b3Body_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; + + b3CreatePrismaticJoint( m_worldId, &prismaticDef ); + + m_speed = 3.0f; + } + + // Create a payload + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { -3.0f, 8.0f }; + bodyDef.name = "crate1"; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull box = b3MakeBoxHull( 0.75f, 0.75f, 0.75f ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 2.0f; + + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + + // Create a second payload + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = m_type; + bodyDef.isEnabled = m_isEnabled; + bodyDef.position = { 2.0f, 8.0f }; + bodyDef.name = "crate2"; + m_secondPayloadId = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull box = b3MakeBoxHull( 0.75f, 0.75f, 0.75f ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 2.0f; + + b3CreateHullShape( m_secondPayloadId, &shapeDef, &box.base ); + } + + // Create a separate body on the ground + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = m_type; + bodyDef.isEnabled = m_isEnabled; + bodyDef.position = { 8.0f, 0.2f }; + bodyDef.name = "debris"; + m_touchingBodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3Capsule capsule = { { 0.0f, 0.0f }, { 1.0f, 0.0f }, 0.25f }; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 2.0f; + + b3CreateCapsuleShape( m_touchingBodyId, &shapeDef, &capsule ); + } + + // Create a separate floating body + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = m_type; + bodyDef.isEnabled = m_isEnabled; + bodyDef.position = { -8.0f, 12.0f }; + bodyDef.gravityScale = 0.0f; + bodyDef.name = "floater"; + m_floatingBodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3Sphere sphere = { { 0.0f, 0.5f, 0.0f }, 0.25f }; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 2.0f; + + b3CreateSphereShape( m_floatingBodyId, &shapeDef, &sphere ); + } + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 11.0f * fontSize; + ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->m_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 == b3_staticBody ) ) + { + m_type = b3_staticBody; + b3Body_SetType( m_platformId, b3_staticBody ); + b3Body_SetType( m_secondAttachmentId, b3_staticBody ); + b3Body_SetType( m_secondPayloadId, b3_staticBody ); + b3Body_SetType( m_touchingBodyId, b3_staticBody ); + b3Body_SetType( m_floatingBodyId, b3_staticBody ); + } + + if ( ImGui::RadioButton( "Kinematic", m_type == b3_kinematicBody ) ) + { + m_type = b3_kinematicBody; + b3Body_SetType( m_platformId, b3_kinematicBody ); + b3Body_SetLinearVelocity( m_platformId, { -m_speed, 0.0f } ); + b3Body_SetAngularVelocity( m_platformId, b3Vec3_zero ); + + b3Body_SetType( m_secondAttachmentId, b3_kinematicBody ); + b3Body_SetLinearVelocity( m_secondAttachmentId, b3Vec3_zero ); + b3Body_SetAngularVelocity( m_secondAttachmentId, b3Vec3_zero ); + + b3Body_SetType( m_secondPayloadId, b3_kinematicBody ); + b3Body_SetType( m_touchingBodyId, b3_kinematicBody ); + b3Body_SetType( m_floatingBodyId, b3_kinematicBody ); + } + + if ( ImGui::RadioButton( "Dynamic", m_type == b3_dynamicBody ) ) + { + m_type = b3_dynamicBody; + b3Body_SetType( m_platformId, b3_dynamicBody ); + b3Body_SetType( m_secondAttachmentId, b3_dynamicBody ); + b3Body_SetType( m_secondPayloadId, b3_dynamicBody ); + b3Body_SetType( m_touchingBodyId, b3_dynamicBody ); + b3Body_SetType( m_floatingBodyId, b3_dynamicBody ); + } + + if ( ImGui::Checkbox( "Enable", &m_isEnabled ) ) + { + if ( m_isEnabled ) + { + b3Body_Enable( m_attachmentId ); + b3Body_Enable( m_secondPayloadId ); + b3Body_Enable( m_floatingBodyId ); + } + else + { + b3Body_Disable( m_attachmentId ); + b3Body_Disable( m_secondPayloadId ); + b3Body_Disable( m_floatingBodyId ); + } + } + + ImGui::End(); + } + + void Step() override + { + // Drive the kinematic body. + if ( m_type == b3_kinematicBody ) + { + b3Vec3 p = b3Body_GetPosition( m_platformId ); + b3Vec3 v = b3Body_GetLinearVelocity( m_platformId ); + + if ( ( p.x < -14.0f && v.x < 0.0f ) || ( p.x > 6.0f && v.x > 0.0f ) ) + { + v.x = -v.x; + b3Body_SetLinearVelocity( m_platformId, v ); + } + } + + Sample::Step(); + } + + static Sample* Create( SampleContext* context ) + { + return new BodyType( context ); + } + + b3BodyId m_attachmentId; + b3BodyId m_secondAttachmentId; + b3BodyId m_platformId; + b3BodyId m_secondPayloadId; + b3BodyId m_touchingBodyId; + b3BodyId m_floatingBodyId; + b3BodyType m_type; + float m_speed; + bool m_isEnabled; +}; + +static int sampleBodyType = SampleManager::Register( "Bodies", "Body Type", BodyType::Create ); + +class SpinningBooks : public Sample +{ +public: + explicit SpinningBooks( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 30.0f, 10.0f, { 0.0f, 1.0f, 0.0f } ); + } + + b3BoxHull box = b3MakeBoxHull( 0.35f, 0.08f, 0.5f ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.gravityScale = 0.0f; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + bodyDef.position = { -2.0f, 2.0f, 0.0f }; + bodyDef.angularVelocity = { 5.0f, 0.01f, 0.01f }; + + b3BodyId body1 = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( body1, &shapeDef, &box.base ); + + bodyDef.position = { 0.0f, 2.0f, 0.0f }; + bodyDef.angularVelocity = { 0.01f, 5.0f, 0.01f }; + + b3BodyId body2 = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( body2, &shapeDef, &box.base ); + + bodyDef.position = { 2.0f, 2.0f, 0.0f }; + bodyDef.angularVelocity = { 0.01f, 0.01f, -5.0f }; + + b3BodyId body3 = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( body3, &shapeDef, &box.base ); + } + + void Render() override + { + DrawGrid( m_scene, 10 ); + Sample::Render(); + } + + static Sample* Create( SampleContext* context ) + { + return new SpinningBooks( context ); + } +}; + +static int sampleBook = SampleManager::Register( "Bodies", "Spinning Book", SpinningBooks::Create ); + +// Dzhanibekov effect +class GyroscopicTorque : public Sample +{ +public: + explicit GyroscopicTorque( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 20.0f, 4.0f, { 0.0f, 2.0f, 0.0f } ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 2.0f, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisX, -0.5f * B3_PI ); + bodyDef.angularVelocity = { 0.01f, 0.01f, 10.0f }; + bodyDef.gravityScale = 0.0f; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3Hull* cylinder = b3CreateCylinder( 0.6f, 0.15f, 0.0f, 32 ); + b3BoxHull box = b3MakeBoxHull( 1.0f, 0.05f, 0.1f ); + b3CreateHullShape( bodyId, &shapeDef, cylinder ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + b3DestroyHull( cylinder ); + } + + void Render() override + { + Sample::Render(); + DrawGrid( m_scene, 10 ); + } + + static Sample* Create( SampleContext* sampleContext ) + { + return new GyroscopicTorque( sampleContext ); + } +}; + +static int sampleGyroscopicTorque = SampleManager::Register( "Bodies", "Gyroscopic Torque", GyroscopicTorque::Create ); + +class Weeble : public Sample +{ +public: + static Sample* Create( SampleContext* context ) + { + return new Weeble( context ); + } + + explicit Weeble( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 45.0f, 25.0f, 25.0f, b3Vec3_zero ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull box = b3MakeBoxHull( 32.0f, 1.0f, 32.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundBody, &shapeDef, &box.base ); + + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 3.0f, 0.0f }; + m_weebleId = b3CreateBody( m_worldId, &bodyDef ); + + b3Capsule capsule = { { 0.0f, -1.0f }, { 0.0f, 1.0f }, 1.0f }; + shapeDef.baseMaterial.rollingResistance = 0.1f; + b3CreateCapsuleShape( m_weebleId, &shapeDef, &capsule ); + + float mass = b3Body_GetMass( m_weebleId ); + b3Matrix3 inertiaTensor = b3Body_GetLocalRotationalInertia( m_weebleId ); + + b3Vec3 offset = { 0.0f, -1.5f, 0.0f }; + + // See: https://en.wikipedia.org/wiki/Parallel_axis_theorem + inertiaTensor += b3Steiner( mass, offset ); + + b3MassData massData = { + .mass = mass, + .center = offset, + .inertia = inertiaTensor, + }; + + b3Body_SetMassData( m_weebleId, massData ); + + m_explosionPosition = { 0.0f, -0.1f, 0.0f }; + m_explosionRadius = 8.0f; + m_explosionMagnitude = 10000.0f; + } + + void UpdateUI() override + { + float height = 120.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); + + ImGui::Begin( "Weeble", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + if ( ImGui::Button( "Teleport" ) ) + { + b3Body_SetTransform( m_weebleId, { 0.0f, 5.0f, 0.0f }, b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.95f * B3_PI ) ); + b3Body_SetAwake( m_weebleId, true ); + } + + if ( ImGui::Button( "Explode" ) ) + { + b3ExplosionDef def = b3DefaultExplosionDef(); + def.position = m_explosionPosition; + def.radius = m_explosionRadius; + def.falloff = 0.1f; + def.impulsePerArea = m_explosionMagnitude; + b3World_Explode( m_worldId, &def ); + } + ImGui::PushItemWidth( 100.0f ); + + ImGui::SliderFloat( "Magnitude", &m_explosionMagnitude, -100000.0f, 100000.0f, "%.0f" ); + + ImGui::PopItemWidth(); + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 4.0f ); + } + + void Step() override + { + Sample::Step(); + + b3Sphere sphere = { b3Vec3_zero, m_explosionRadius }; + DrawSphere( m_scene, { m_explosionPosition, b3Quat_identity }, sphere, b3_colorAzure ); + + // This shows how to get the velocity of a point on a body + b3Vec3 localPoint = { 0.0f, 2.0f, 0.0f }; + b3Vec3 worldPoint = b3Body_GetWorldPoint( m_weebleId, localPoint ); + + b3Vec3 v1 = b3Body_GetLocalPointVelocity( m_weebleId, localPoint ); + b3Vec3 v2 = b3Body_GetWorldPointVelocity( m_weebleId, worldPoint ); + + b3Vec3 offset = { 0.05f, 0.0f }; + DrawLine( m_scene, worldPoint, worldPoint + v1, b3_colorRed ); + DrawLine( m_scene, worldPoint + offset, worldPoint + v2 + offset, b3_colorGreen ); + } + + b3BodyId m_weebleId; + b3Vec3 m_explosionPosition; + float m_explosionRadius; + float m_explosionMagnitude; +}; + +static int sampleWeeble = SampleManager::Register( "Bodies", "Weeble", Weeble::Create ); + +class DisableBody : public Sample +{ +public: + enum + { + e_count = 4 + }; + + explicit DisableBody( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 45.0f, 25.0f, 10.0f, b3Vec3_zero ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + + b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull box = b3MakeBoxHull( 25.0f, 1.0f, 25.0f ); + b3CreateHullShape( groundBody, &shapeDef, &box.base ); + + float linkRadius = 0.1f; + float linkLength = 5.0f * linkRadius; + b3Capsule capsule = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, linkLength }, linkRadius }; + + b3BodyId parentId = {}; + for ( int link = 0; link < e_count; ++link ) + { + bodyDef.position = { 0.0f, 0.8f * float( e_count ) * linkLength, link * linkLength }; + bodyDef.type = B3_IS_NULL( parentId ) ? b3_kinematicBody : b3_dynamicBody; + b3BodyId childId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateCapsuleShape( childId, &shapeDef, &capsule ); + m_bodyIds[link] = childId; + + if ( B3_IS_NON_NULL( parentId ) ) + { + b3WeldJointDef jointDef = b3DefaultWeldJointDef(); + jointDef.base.bodyIdA = parentId; + jointDef.base.bodyIdB = childId; + jointDef.base.localFrameA.p = { 0.0f, 0.0f, linkLength }; + jointDef.angularHertz = 10.0f; + jointDef.angularDampingRatio = 1.0f; + b3CreateWeldJoint( m_worldId, &jointDef ); + } + + parentId = childId; + } + + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 3.0f, 3.0f, 0.0f }; + m_ballId = b3CreateBody( m_worldId, &bodyDef ); + + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f }; + b3CreateSphereShape( m_ballId, &shapeDef, &sphere ); + } + + void UpdateUI() override + { + float height = 100.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); + + ImGui::Begin( "Distance", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + + { + bool enabled = b3Body_IsEnabled( m_bodyIds[2] ); + if ( ImGui::Checkbox( "Enable Link", &enabled ) ) + { + if ( enabled ) + { + b3Body_Enable( m_bodyIds[2] ); + } + else + { + b3Body_Disable( m_bodyIds[2] ); + } + } + } + + { + bool enabled = b3Body_IsEnabled( m_ballId ); + if ( ImGui::Checkbox( "Enable Ball", &enabled ) ) + { + if ( enabled ) + { + b3Body_Enable( m_ballId ); + } + else + { + b3Body_Disable( m_ballId ); + } + } + } + + ImGui::End(); + } + + void Step() override + { + b3Body_ApplyLinearImpulseToCenter( m_bodyIds[2], { 0.0f, 0.1f, 0.0f }, true ); + + Sample::Step(); + } + + static Sample* Create( SampleContext* context ) + { + return new DisableBody( context ); + } + + b3BodyId m_bodyIds[e_count]; + b3BodyId m_ballId; +}; + +static int sampleDisable = SampleManager::Register( "Bodies", "Disable", DisableBody::Create ); + +class BodyCast : public Sample +{ +public: + explicit BodyCast( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 120.0f, 30.0f, 20.0f, { 0.0f, 1.5f, 0.0f } ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_kinematicBody; + bodyDef.position = { 5.0f, 5.0f, 0.0f }; + bodyDef.angularVelocity = { 0.1f, -0.1f, 0.1f }; + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + m_cylinder = b3CreateCylinder( 2.0f, 0.5f, 0.0f, 16 ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( m_bodyId, &shapeDef, m_cylinder ); + + m_transform.p = { -10.0f, 2.0f, 0.0f }; + m_transform.q = b3MakeQuatFromAxisAngle( b3Normalize( { 1.0f, -2.0f, 3.0f } ), 0.75f * B3_PI ); + + m_baseTranslation = b3Vec3_zero; + m_baseX = 0; + m_baseY = 0; + m_origin = b3Vec3_zero; + m_tracking = false; + } + + ~BodyCast() override + { + b3DestroyHull( m_cylinder ); + } + + void MouseDown( b3Vec2 p, int button, int modifiers ) override + { + if ( button == 0 && modifiers == GLFW_MOD_ALT ) + { + PickRay pickRay = m_camera->BuildPickRay( p.x, p.y ); + m_origin = pickRay.origin + 10.0f * b3Normalize( pickRay.translation ); + m_baseTranslation = m_transform.p; + m_tracking = true; + } + else + { + m_tracking = false; + } + } + + void MouseMove( b3Vec2 p ) override + { + if ( m_tracking ) + { + PickRay pickRay = m_camera->BuildPickRay( p.x, p.y ); + b3Vec3 origin = pickRay.origin + 10.0f * b3Normalize( pickRay.translation ); + m_transform.p = m_baseTranslation + origin - m_origin; + } + } + + void Render() override + { + Sample::Render(); + + DrawGrid( m_scene, 10 ); + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 4.0f ); + + DrawHull( m_scene, m_transform, m_cylinder, b3_colorBlue, false ); + } + + void Step() override + { + // Cast ray + { + b3BodyRayCastInput input = {}; + input.origin = { -9.75f, 3.0f, -4.0f }; + input.translation = { 0.0f, 0.0f, 8.0f }; + input.filter = b3DefaultQueryFilter(); + input.maxFraction = 1.0f; + b3BodyCastResult result = b3Body_CastRay( m_bodyId, &input, m_transform ); + + DrawLine( m_scene, input.origin, input.origin + input.maxFraction * input.translation, b3_colorCyan ); + + if ( result.hit ) + { + DrawLine( m_scene, result.point, result.point + 0.2f * result.normal, b3_colorYellow ); + DrawPoint( m_scene, result.point, 10.0f, b3_colorYellow ); + } + + DrawPoint( m_scene, input.origin, 10.0f, b3_colorGreen ); + DrawPoint( m_scene, input.origin + input.translation, 10.0f, b3_colorRed ); + } + + // Cast sphere + { + b3Sphere sphere = { { -14.5f, 2.5f, 0.5f }, 0.2f }; + + b3BodyShapeCastInput input = {}; + input.proxy = { &sphere.center, 1, sphere.radius }; + input.translation = { 8.0f, 0.0f, 0.0f }; + input.filter = b3DefaultQueryFilter(); + input.maxFraction = 1.0f; + input.canEncroach = true; + b3BodyCastResult result = b3Body_CastShape( m_bodyId, &input, m_transform ); + + if ( result.hit ) + { + b3Transform transform = { result.fraction * input.translation, b3Quat_identity }; + DrawSphere( m_scene, transform, sphere, b3_colorGreen ); + DrawLine( m_scene, result.point, result.point + 0.2f * result.normal, b3_colorYellow ); + } + else + { + b3Transform transform = { input.maxFraction * input.translation, b3Quat_identity }; + DrawSphere( m_scene, transform, sphere, b3_colorWhite ); + } + + DrawLine( m_scene, sphere.center, sphere.center + input.maxFraction * input.translation, b3_colorWhite ); + DrawPoint( m_scene, sphere.center, 10.0f, b3_colorGreen ); + DrawPoint( m_scene, sphere.center + input.maxFraction * input.translation, 10.0f, b3_colorRed ); + } + + // Overlap capsule + { + b3Capsule capsule = { { -10.5f, 2.0f, 0.5f }, { -9.5f, 1.0f, 0.5f }, 0.5f }; + b3ShapeProxy proxy = { &capsule.center1, 2, capsule.radius }; + bool overlaps = b3Body_OverlapShape( m_bodyId, &proxy, b3DefaultQueryFilter(), m_transform ); + + if ( overlaps ) + { + DrawCapsule( m_scene, b3Transform_identity, capsule, b3_colorGreen ); + } + else + { + DrawCapsule( m_scene, b3Transform_identity, capsule, b3_colorGray ); + } + } + + // Collide capsule + { + b3Capsule capsule = { { -10.25f, 2.0f, -0.75f }, { -10.25f, 3.0f, -0.75f }, 0.3f }; + b3BodyPlaneResult bodyPlanes[4]; + int count = b3Body_CollideMover( m_bodyId, bodyPlanes, 4, &capsule, b3DefaultQueryFilter(), m_transform ); + DrawCapsule( m_scene, b3Transform_identity, capsule, b3_colorPurple ); + + for ( int i = 0; i < count; ++i ) + { + b3PlaneResult result = bodyPlanes[i].result; + DrawPlane( m_scene, result.plane.normal, result.point, b3_colorOrange ); + } + } + } + + static Sample* Create( SampleContext* context ) + { + return new BodyCast( context ); + } + + b3Hull* m_cylinder; + b3BodyId m_bodyId; + b3Transform m_transform; + + b3Vec3 m_baseTranslation; + b3Vec3 m_origin; + int m_baseX; + int m_baseY; + bool m_tracking; +}; + +static int sampleBodyCast = SampleManager::Register( "Bodies", "Cast", BodyCast::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_camera->SetView( 0.0f, 30.0f, 10.0f, { 0.0f, 1.5f, 0.0f } ); + } + + m_amplitude = 2.0f; + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_kinematicBody; + bodyDef.position.x = 2.0f * m_amplitude; + bodyDef.position.y = m_amplitude; + + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull box = b3MakeBoxHull( 0.1f, 1.0f, 0.2f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( m_bodyId, &shapeDef, &box.base ); + } + + m_time = 0.0f; + } + + void Render() override + { + Sample::Render(); + DrawGrid( m_scene, 10 ); + DrawTransform( m_scene, b3Transform_identity, 4.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 == 0 ) + { + timeStep = 0.0f; + } + + float delay = 2.0f; + + if ( timeStep > 0.0f && m_time > delay ) + { + float t = m_time - delay; + + b3Vec3 point; + point.x = 2.0f * m_amplitude * cosf( t ); + point.y = m_amplitude * ( sinf( 2.0f * t ) + 1.0f ); + point.z = 0.0f; + b3Quat rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 2.0f * t ); + + b3Vec3 axis = b3RotateVector( rotation, { 0.0f, 1.0f, 0.0f } ); + DrawLine( m_scene, point - 0.5f * axis, point + 0.5f * axis, b3_colorPlum ); + DrawPoint( m_scene, point, 10.0f, b3_colorPlum ); + + b3Body_SetTargetTransform( m_bodyId, { point, rotation }, timeStep, true ); + } + + Sample::Step(); + + m_time += timeStep; + } + + static Sample* Create( SampleContext* context ) + { + return new Kinematic( context ); + } + + b3BodyId m_bodyId; + float m_amplitude; + float m_time; +}; + +static int sampleKinematic = SampleManager::Register( "Bodies", "Kinematic", Kinematic::Create ); + +class LockMixing : public Sample +{ +public: + explicit LockMixing( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 40.0f, b3Vec3_zero ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull hull = b3MakeBoxHull( 15.0f, 1.0f, 15.0f ); + b3CreateHullShape( groundId, &shapeDef, &hull.base ); + } + + b3BoxHull cube = b3MakeBoxHull( 1.0f, 1.0f, 1.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.name = "free"; + bodyDef.position = { 0.0f, 2.0f, 0.0f }; + + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &cube.base ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.name = "angular xz"; + bodyDef.position = { 2.0f, 2.0f, 0.0f }; + bodyDef.motionLocks.angularX = true; + //bodyDef.motionLocks.angularY = true; + bodyDef.motionLocks.angularZ = true; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &cube.base ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.name = "linear xyz"; + bodyDef.position = { -2.0f, 2.0f, 0.0f }; + bodyDef.motionLocks.linearX = true; + bodyDef.motionLocks.linearY = true; + bodyDef.motionLocks.linearZ = true; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &cube.base ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.name = "full"; + bodyDef.position = { 0.0f, 1.0f, 2.0f }; + bodyDef.motionLocks.linearX = true; + bodyDef.motionLocks.linearY = true; + bodyDef.motionLocks.linearZ = true; + bodyDef.motionLocks.angularX = true; + bodyDef.motionLocks.angularY = true; + bodyDef.motionLocks.angularZ = true; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &cube.base ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "static"; + bodyDef.position = { 0.0f, 1.0f, -3.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &cube.base ); + } + } + + static Sample* Create( SampleContext* context ) + { + return new LockMixing( context ); + } +}; + +static int sampleLockMixing = SampleManager::Register( "Bodies", "Lock Mixing", LockMixing::Create ); diff --git a/samples/sample_character.cpp b/samples/sample_character.cpp new file mode 100644 index 0000000..d05b07f --- /dev/null +++ b/samples/sample_character.cpp @@ -0,0 +1,438 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "camera.h" +#include "mesh_loader.h" +#include "renderer.h" +#include "sample.h" +#include "scene.h" + +#include "box3d/box3d.h" + +#include +// prevent clang format sorting glad.h with glfw3.h +#include +#include + +class CapsulePlane : public Sample +{ +public: + static Sample* Create( SampleContext* context ) + { + return new CapsulePlane( context ); + } + + explicit CapsulePlane( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 120.0f, 30.0f, 20.0f, { 0.0f, 1.5f, 0.0f } ); + } + + m_transform = { { 0.0f, 1.0f, 0.4f }, b3Quat_identity }; + m_capsule = { { 0.0f, -0.5f, 0.0f }, { 0.0f, 0.5f, 0.0f }, 0.25f }; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, 1.0f, 1.0f }; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3CreateHullShape( body, &shapeDef, &box.base ); + + m_baseTranslation = b3Vec3_zero; + m_baseX = 0; + m_baseY = 0; + m_origin = b3Vec3_zero; + m_tracking = false; + m_planeCount = 0; + } + + void Solve() + { + b3PlaneSolverResult result = b3SolvePlanes( b3Vec3_zero, m_planes, m_planeCount ); + m_transform.p += result.delta; + } + + void Render() override + { + Sample::Render(); + + DrawGrid( m_scene, 10 ); + DrawLine( m_scene, b3Vec3_zero, 2.0f * b3Vec3_axisX, b3_colorRed ); + DrawLine( m_scene, b3Vec3_zero, 2.0f * b3Vec3_axisY, b3_colorGreen ); + DrawLine( m_scene, b3Vec3_zero, 2.0f * b3Vec3_axisZ, b3_colorBlue ); + } + + void UpdateUI() override + { + ImGui::SetNextWindowPos( ImVec2( 10.0f, 600.0f ) ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, 80.0f ) ); + ImGui::Begin( "Capsule Plane", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + + if ( ImGui::Button( "Solve" ) ) + { + Solve(); + } + + ImGui::End(); + } + + static bool PlaneResultFcn( b3ShapeId shape, const b3PlaneResult* results, int planeCount, void* context ) + { + CapsulePlane* self = static_cast( context ); + for ( int i = 0; i < planeCount && self->m_planeCount < 3; ++i ) + { + self->m_planes[self->m_planeCount] = { results[i].plane, FLT_MAX, 0.0f, true }; + self->m_planeCount += 1; + } + return true; + } + + void MouseDown( b3Vec2 p, int button, int modifiers ) override + { + if ( button == 0 && ( modifiers & GLFW_MOD_ALT ) == 0 ) + { + PickRay pickRay = m_camera->BuildPickRay( p.x, p.y ); + m_origin = pickRay.origin + 10.0f * b3Normalize( pickRay.translation ); + m_baseTranslation = m_transform.p; + m_tracking = true; + } + } + + void MouseUp( b3Vec2 p, int button ) override + { + m_tracking = false; + } + + void MouseMove( b3Vec2 p ) override + { + if ( m_tracking ) + { + PickRay pickRay = m_camera->BuildPickRay( p.x, p.y ); + b3Vec3 origin = pickRay.origin + 10.0f * b3Normalize( pickRay.translation ); + m_transform.p = m_baseTranslation + origin - m_origin; + } + } + + void Step() override + { + m_planeCount = 0; + + DrawCapsule( m_scene, m_transform, m_capsule, b3_colorGreen ); + b3QueryFilter filter = b3DefaultQueryFilter(); + + b3Capsule capsule = { m_capsule.center1 + m_transform.p, m_capsule.center2 + m_transform.p, m_capsule.radius }; + b3World_CollideMover( m_worldId, &capsule, filter, PlaneResultFcn, this ); + + for ( int i = 0; i < m_planeCount; ++i ) + { + b3Plane plane = m_planes[i].plane; + b3Vec3 p1 = m_transform.p + ( plane.offset - m_capsule.radius ) * plane.normal; + b3Vec3 p2 = p1 + 0.1f * plane.normal; + DrawPoint( m_scene, p1, 5.0f, b3_colorYellow ); + DrawLine( m_scene, p1, p2, b3_colorYellow ); + } + } + + static constexpr int m_planeCapacity = 3; + + b3Transform m_transform; + b3Capsule m_capsule; + b3CollisionPlane m_planes[m_planeCapacity] = {}; + int m_planeCount; + + b3Vec3 m_baseTranslation; + b3Vec3 m_origin; + int m_baseX; + int m_baseY; + bool m_tracking; +}; + +static int sampleCapsulePlane = SampleManager::Register( "Character", "CapsulePlane", CapsulePlane::Create ); + +class BasicMover : public Sample +{ +public: + explicit BasicMover( SampleContext* context ) + : Sample( context ) + { + b3Vec3 moverPosition = { 7.5f, 0.75f, 9.0f }; + + if ( m_context->restart == false ) + { + m_camera->SetView( 120.0f, 30.0f, 5.0f, moverPosition ); + } + + m_mover.Initialize( this, moverPosition ); + + { + m_levelMesh = CreateMeshData( "data/meshes/test_map01.obj", 1.0f, false, false, true, true ); + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3SurfaceMaterial materials[3]; + materials[0] = { 0.6f, 0.0f, 0 }; + materials[1] = { 0.6f, 1.0f, 1 }; + materials[2] = { 0.1f, 0.0f, 2 }; + shapeDef.materials = materials; + shapeDef.materialCount = 3; + + b3CreateMeshShape( body, &shapeDef, m_levelMesh, b3Vec3_one ); + + // b3Transform transform = { { 0.0f, 1.0f, 14.0f }, b3MakeQuatFromAxisAngle( b3Vec3_axisY, 0.75f * B3_PI ) }; + // b3BoxHull box = b3MakeTransformedBoxHull( 5.0f, 1.0f, 0.5f, transform ); + // b3CreateHullShape( body, &shapeDef, &box.base ); + + { + b3Transform transform = { { 4.0f, 1.0f, 14.0f }, b3Quat_identity }; + b3BoxHull box = b3MakeTransformedBoxHull( 1.0f, 1.0f, 1.0f, transform ); + b3CreateHullShape( body, &shapeDef, &box.base ); + } + { + b3Transform transform = { { 4.0f, 1.0f, 13.95f }, b3Quat_identity }; + b3BoxHull box = b3MakeTransformedBoxHull( 1.0f, 1.0f, 1.0f, transform ); + b3CreateHullShape( body, &shapeDef, &box.base ); + } + { + b3Transform transform = { { 5.8f, 1.0f, 13.7f }, b3MakeQuatFromAxisAngle( b3Vec3_axisY, 0.1f * B3_PI ) }; + b3BoxHull box = b3MakeTransformedBoxHull( 1.0f, 1.0f, 1.0f, transform ); + b3CreateHullShape( body, &shapeDef, &box.base ); + } + } + + { + m_stairs = CreateMeshData( "data/meshes/stairs.obj", 1.0f, false, false, true, true ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { -10.0f, 0.0f, 0.0f }; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3CreateMeshShape( body, &shapeDef, m_stairs, { 0.75f, 0.75f, -1.5f } ); + } + + { + m_torus = b3CreateTorusMesh( 10, 12, 2.0f, 1.0f ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { -10.0f, 1.0f, -8.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisY, 0.5f * B3_PI ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3CreateMeshShape( body, &shapeDef, m_torus, { -0.75f, 1.5f, 0.5f } ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 20.0f, 0.0f, 0.0f }; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + + m_heightField = b3CreateWave( 50.0f, 50.0f, b3Vec3_one, 0.02f, 0.04f, true ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3SurfaceMaterial materials[3]; + materials[0] = { 0.6f, 0.0f, 0 }; + materials[1] = { 0.6f, 1.0f, 1 }; + materials[2] = { 0.1f, 0.0f, 2 }; + shapeDef.materials = materials; + shapeDef.materialCount = 3; + + b3CreateHeightFieldShape( body, &shapeDef, m_heightField ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, 1.4f, 6.0f }; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + m_enemyShape.maxPush = 1.0f; + m_enemyShape.clipVelocity = true; + + b3Capsule capsule = { + { 0.0f, -0.5f, 0.0f }, + { 0.0f, 0.5f, 0.0f }, + 0.3f, + }; + + //shapeDef.filter = { 2u, ~0u, 0 }; + shapeDef.userData = &m_enemyShape; + shapeDef.baseMaterial.customColor = b3_colorMediumVioletRed; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3CreateCapsuleShape( body, &shapeDef, &capsule ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, 1.4f, 5.0f }; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + m_friendlyShape.maxPush = 0.01f; + m_friendlyShape.clipVelocity = false; + + b3Capsule capsule = { + { 0.0f, -0.5f, 0.0f }, + { 0.0f, 0.5f, 0.0f }, + 0.3f, + }; + + shapeDef.filter = { 2u, ~0u, 0 }; + shapeDef.userData = &m_friendlyShape; + shapeDef.baseMaterial.customColor = b3_colorLimeGreen; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3CreateCapsuleShape( body, &shapeDef, &capsule ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 7.0f, 5.0f, 0.0f }; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3Sphere sphere = { b3Vec3_zero, 0.5f }; + b3CreateSphereShape( body, &shapeDef, &sphere ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 7.0f, 2.0f, -3.0f }; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.customColor = b3_colorFloralWhite; + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.25f, 0.5f ); + m_ignoreShapeId = b3CreateHullShape( body, &shapeDef, &box.base ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + bodyDef.type = b3_dynamicBody; + bodyDef.position = { -2.0f, 1.6f, 0.0f }; + bodyDef.gravityScale = 2.0f; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 1000.0f; + + b3BoxHull box = b3MakeBoxHull( 0.75f, 1.5f, 0.1f ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + b3Quat axisQuat = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisZ, b3Vec3_axisY ); + b3Vec3 offset = { -0.75f, 0.0f, 0.0f }; + + b3RevoluteJointDef jointDef = b3DefaultRevoluteJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameA.p = b3Add( bodyDef.position, offset ); + jointDef.base.localFrameA.q = axisQuat; + jointDef.base.localFrameB.p = offset; + jointDef.base.localFrameB.q = axisQuat; + + jointDef.enableLimit = true; + jointDef.lowerAngle = B3_DEG_TO_RAD * -90.0f; + jointDef.upperAngle = B3_DEG_TO_RAD * 90.0f; + jointDef.enableSpring = true; + jointDef.hertz = 1.0f; + jointDef.dampingRatio = 0.5f; + jointDef.enableMotor = false; + jointDef.maxMotorTorque = 100.0f; + jointDef.base.drawScale = 2.0f; + + b3CreateRevoluteJoint( m_worldId, &jointDef ); + } + + //{ + // b3BodyDef BodyDef = b3DefaultBodyDef(); + // BodyDef.type = b3_dynamicBody; + // BodyDef.position = { 25.0f, 5.0f, 10.0f }; + // b3BodyId Body = b3CreateBody(m_worldId, &bodyDef ); + + // b3ShapeDef ShapeDef = b3DefaultShapeDef(); + // b3Sphere Sphere = { b3Vec3_zero, 0.5f }; + // Body->AddSphere( &ShapeDef, Sphere ); + //} + + m_camera->m_thirdPerson = true; + m_clipVelocity = true; + glfwSetInputMode( m_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED ); + + //m_haveMouseLast = false; + //m_mouseLast = { 0.0f, 0.0f }; + //m_mouseDelta = { 0.0f, 0.0f }; + } + + ~BasicMover() override + { + m_camera->m_thirdPerson = false; + glfwSetInputMode( m_window, GLFW_CURSOR, GLFW_CURSOR_NORMAL ); + b3DestroyMesh( m_levelMesh ); + b3DestroyMesh( m_stairs ); + b3DestroyMesh( m_torus ); + b3DestroyHeightField( m_heightField ); + } + + void Render() override + { + Sample::Render(); + DrawTransform( m_scene, { { 0.0f, 0.0f, 0.02f }, b3Quat_identity }, 2.0f ); + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 9.0f * fontSize; + ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->m_height - height - 2.0f * fontSize ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 19.0f * fontSize, height ) ); + + ImGui::Begin( "Mover", nullptr, ImGuiWindowFlags_NoResize ); + + bool thirdPerson = m_camera->m_thirdPerson; + if ( ImGui::Checkbox( "Third Person (Key: T)", &thirdPerson ) ) + { + ToggleThirdPerson(); + } + + ImGui::Checkbox( "Clip Velocity", &m_clipVelocity ); + + ImGui::End(); + } + + void Keyboard( int key, int action, int mods ) override + { + if ( key == GLFW_KEY_T && action == GLFW_PRESS ) + { + ToggleThirdPerson(); + } + } + + void Step() override + { + m_mover.Step(&m_ignoreShapeId, 1, m_clipVelocity); + DrawTextLine( "third person (T) = %d", m_camera->m_thirdPerson ); + DrawTextLine( "deltaX = %g, deltaY = %g", m_mouseDelta.x, m_mouseDelta.y ); + + Sample::Step(); + } + + static Sample* Create( SampleContext* context ) + { + return new BasicMover( context ); + } + + CharacterMover m_mover; + MoverShapeUserData m_enemyShape; + MoverShapeUserData m_friendlyShape; + b3MeshData* m_levelMesh; + b3MeshData* m_stairs; + b3MeshData* m_torus; + b3HeightField* m_heightField; + b3ShapeId m_ignoreShapeId; + bool m_clipVelocity; +}; + +static int sampleMover = SampleManager::Register( "Character", "Mover", BasicMover::Create ); diff --git a/samples/sample_collision.cpp b/samples/sample_collision.cpp new file mode 100644 index 0000000..3622e4f --- /dev/null +++ b/samples/sample_collision.cpp @@ -0,0 +1,2821 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "GLFW/glfw3.h" +#include "camera.h" +#include "utils.h" +#include "renderer.h" +#include "sample.h" +#include "scene.h" + +#include "box3d/box3d.h" + +#include + +class RayCurtain : public Sample +{ +public: + static Sample* Create( SampleContext* context ) + { + return new RayCurtain( context ); + } + + explicit RayCurtain( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 20.0f ); + } + + b3BoxHull box = b3MakeBoxHull( 0.6f, 0.6f, 0.6f ); + + m_mesh = b3CreateTorusMesh( 10, 12, 0.65f, 0.35f ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_kinematicBody; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + bodyDef.position = { -6.0f, 3.0f, 0.0f }; + bodyDef.angularVelocity = { 0.8f, 0.4f, 0.8f }; + b3BodyId sphereBody = b3CreateBody( m_worldId, &bodyDef ); + b3Sphere sphere = { b3Vec3_zero, 0.9f }; + b3CreateSphereShape( sphereBody, &shapeDef, &sphere ); + + bodyDef.position = { -2.0f, 3.0f, 0.0f }; + bodyDef.angularVelocity = { 0.8f, 0.4f, 0.8f }; + b3BodyId capsuleBody = b3CreateBody( m_worldId, &bodyDef ); + b3Capsule capsule = { { -0.5f, 0.0f, 0.0f }, { 0.5f, 0.0f, 0.0f }, 0.8f }; + b3CreateCapsuleShape( capsuleBody, &shapeDef, &capsule ); + + bodyDef.position = { 2.0f, 3.0f, 0.0f }; + bodyDef.angularVelocity = { 0.8f, 0.4f, 0.8f }; + b3BodyId hullBody = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( hullBody, &shapeDef, &box.base ); + + bodyDef.position = { 6.0f, 3.0f, 0.0f }; + bodyDef.angularVelocity = { 0.8f, 0.4f, 0.8f }; + b3BodyId meshBody = b3CreateBody( m_worldId, &bodyDef ); + b3CreateMeshShape( meshBody, &shapeDef, m_mesh, b3Vec3_one ); + + m_absSpeed = 0.015f; + m_offset = 2.0f; + m_speed = -m_absSpeed; + } + + ~RayCurtain() override + { + b3DestroyMesh( m_mesh ); + } + + void Render() override + { + Sample::Render(); + + DrawGrid( m_scene, 10 ); + DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisX, b3_colorRed ); + DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisY, b3_colorGreen ); + DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisZ, b3_colorBlue ); + + for ( float x = -8.0f; x <= 8.0f; x += 0.1f ) + { + b3Vec3 rayOrigin = { x, 8.0f, m_offset }; + b3Vec3 rayTranslation = b3Vec3{ x, 0.0f, m_offset } - rayOrigin; + + b3RayResult result = b3World_CastRayClosest( m_worldId, rayOrigin, rayTranslation, b3DefaultQueryFilter() ); + if ( result.hit ) + { + b3Vec3 point = result.point; + + DrawLine( m_scene, point, point + 0.5f * result.normal, b3_colorGreen ); + } + + DrawPoint( m_scene, rayOrigin, 4.0f, b3_colorGreen ); + DrawPoint( m_scene, rayOrigin + rayTranslation, 4.0f, b3_colorRed ); + DrawLine( m_scene, rayOrigin, rayOrigin + rayTranslation, b3_colorYellow ); + } + + if ( m_offset > 2.0f ) + { + m_speed = -m_absSpeed; + } + else if ( m_offset < -2.0f ) + { + m_speed = m_absSpeed; + } + + if ( m_context->pause == false ) + { + m_offset += m_speed; + } + } + + float m_offset; + float m_absSpeed; + float m_speed; + b3MeshData* m_mesh; +}; + +static int sampleRayCurtain = SampleManager::Register( "Collision", "Ray Curtain", RayCurtain::Create ); + +// Context for ray cast callbacks. Do what you want with this. +struct CastContext +{ + b3Vec3 points[3]; + b3Vec3 normals[3]; + float fractions[3]; + uint64_t materialIds[3]; + int triangleIndices[3]; + int childIndices[3]; + int count; + bool initialOverlap; +}; + +// This callback finds the closest hit. This is the most common callback used in games. +static float RayCastClosestCallback( b3ShapeId shapeId, b3Vec3 point, b3Vec3 normal, float fraction, uint64_t materialId, + int triangleIndex, int childIndex, void* context ) +{ + CastContext* rayContext = (CastContext*)context; + + // Check for initial overlap + if ( rayContext->initialOverlap == false && 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; + } + + // Ignore a specific shape. Also ignore initial overlap. + intptr_t ignoreFlag = intptr_t( b3Shape_GetUserData( shapeId ) ); + if ( ignoreFlag == 1 ) + { + // 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->materialIds[0] = materialId; + rayContext->triangleIndices[0] = triangleIndex; + rayContext->childIndices[0] = childIndex; + 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( b3ShapeId shapeId, b3Vec3 point, b3Vec3 normal, float fraction, uint64_t materialId, + int triangleIndex, int childIndex, void* context ) +{ + CastContext* rayContext = (CastContext*)context; + + // Check for initial overlap + if ( rayContext->initialOverlap == false && 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; + } + + intptr_t ignoreFlag = intptr_t( b3Shape_GetUserData( shapeId ) ); + if ( ignoreFlag == 1 ) + { + // 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->materialIds[0] = materialId; + rayContext->triangleIndices[0] = triangleIndex; + rayContext->childIndices[0] = childIndex; + 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( b3ShapeId shapeId, b3Vec3 point, b3Vec3 normal, float fraction, uint64_t materialId, + int triangleIndex, int childIndex, void* context ) +{ + CastContext* rayContext = (CastContext*)context; + + // Check for initial overlap + if ( rayContext->initialOverlap == false && 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; + } + + intptr_t ignoreFlag = intptr_t( b3Shape_GetUserData( shapeId ) ); + if ( ignoreFlag == 1 ) + { + // 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->materialIds[count] = materialId; + rayContext->triangleIndices[count] = triangleIndex; + rayContext->childIndices[count] = childIndex; + 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( b3ShapeId shapeId, b3Vec3 point, b3Vec3 normal, float fraction, uint64_t materialId, + int triangleIndex, int childIndex, void* context ) +{ + CastContext* rayContext = (CastContext*)context; + + // Check for initial overlap + if ( rayContext->initialOverlap == false && 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; + } + + intptr_t ignoreFlag = intptr_t( b3Shape_GetUserData( shapeId ) ); + if ( ignoreFlag == 1 ) + { + // 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->materialIds[j] = rayContext->materialIds[j - 1]; + rayContext->triangleIndices[j] = rayContext->triangleIndices[j - 1]; + rayContext->childIndices[j] = rayContext->childIndices[j - 1]; + } + + rayContext->points[index] = point; + rayContext->normals[index] = normal; + rayContext->fractions[index] = fraction; + rayContext->materialIds[index] = materialId; + rayContext->triangleIndices[index] = triangleIndex; + rayContext->childIndices[index] = childIndex; + 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; +} + +class CastWorld : public Sample +{ +public: + enum + { + e_any = 0, + e_closest = 1, + e_multiple = 2, + e_sorted = 3 + }; + + enum + { + e_rayCast = 0, + e_sphereCast = 1, + e_capsuleCast = 2, + e_boxCast = 3 + }; + + enum + { + e_maxCount = 64 + }; + + static Sample* Create( SampleContext* context ) + { + return new CastWorld( context ); + } + + explicit CastWorld( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 20.0f ); + } + + m_sphere = { b3Vec3_zero, 0.9f }; + m_capsule = { { -0.5f, 0.0f, 0.0f }, { 0.5f, 0.0f, 0.0f }, 0.8f }; + m_box = b3MakeBoxHull( 0.6f, 0.6f, 0.6f ); + m_mesh = b3CreateTorusMesh( 10, 12, 0.65f, 0.35f ); + + m_heightField = b3CreateWave( 10, 10, 0.5f * b3Vec3_one, 0.03f, 0.09f, false ); + + m_bodyIndex = 0; + + for ( int i = 0; i < e_maxCount; ++i ) + { + m_bodies[i] = {}; + } + + m_mode = e_closest; + + m_castType = e_rayCast; + m_castRadius = 0.5f; + + m_origin = { -20.0f, 10.0f, 0.0f }; + m_translation = { 20.0f, 10.0f, 0.0f }; + + m_castContext = {}; + m_initialOverlap = false; + } + + ~CastWorld() override + { + b3DestroyMesh( m_mesh ); + b3DestroyHeightField( m_heightField ); + } + + void CreateShapes( b3ShapeType shapeType, int count ) + { + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.gravityScale = 0.0f; + + for ( int i = 0; i < count; ++i ) + { + if ( B3_IS_NULL( m_bodies[m_bodyIndex] ) == false ) + { + b3DestroyBody( m_bodies[m_bodyIndex] ); + m_bodies[m_bodyIndex] = b3_nullBodyId; + } + + if ( m_bodyIndex % 3 == 0 ) + { + bodyDef.type = b3_kinematicBody; + } + else if ( m_bodyIndex % 2 == 0 ) + { + bodyDef.type = b3_dynamicBody; + } + else + { + bodyDef.type = b3_staticBody; + } + + // Heightfield must be a static body + if (shapeType == b3_heightShape) + { + bodyDef.type = b3_staticBody; + } + + bodyDef.position = RandomVec3Uniform( -20.0f, 20.0f ); + + b3Vec3 axis = RandomVec3Uniform( -1.0f, 1.0f ); + axis = b3Normalize( axis ); + float angle = RandomFloatRange( -B3_PI, B3_PI ); + bodyDef.rotation = b3MakeQuatFromAxisAngle( axis, angle ); + + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + int flag = ( m_bodyIndex & m_ignoreBase ) == m_ignoreBase ? 1 : 0; + shapeDef.userData = (void*)(intptr_t)flag; + + switch ( shapeType ) + { + case b3_sphereShape: + shapeDef.baseMaterial.userMaterialId = 11; + b3CreateSphereShape( bodyId, &shapeDef, &m_sphere ); + break; + + case b3_capsuleShape: + shapeDef.baseMaterial.userMaterialId = 22; + b3CreateCapsuleShape( bodyId, &shapeDef, &m_capsule ); + break; + + case b3_hullShape: + shapeDef.baseMaterial.userMaterialId = 33; + b3CreateHullShape( bodyId, &shapeDef, &m_box.base ); + break; + + case b3_meshShape: + shapeDef.baseMaterial.userMaterialId = 44; + b3CreateMeshShape( bodyId, &shapeDef, m_mesh, { 4.0f, 3.0f, -2.0f } ); + break; + + case b3_heightShape: + { + shapeDef.baseMaterial.userMaterialId = 55; + b3SurfaceMaterial materials[3] = { + { + .userMaterialId = 111, + }, + { + .userMaterialId = 222, + }, + { + .userMaterialId = 333, + }, + }; + shapeDef.materials = materials; + shapeDef.materialCount = 3; + + b3CreateHeightFieldShape( bodyId, &shapeDef, m_heightField ); + } + break; + + default: + assert( false ); + break; + } + + m_bodies[m_bodyIndex] = bodyId; + + m_bodyIndex = ( m_bodyIndex + 1 ) % e_maxCount; + } + } + + void DestroyBody() + { + for ( int i = 0; i < e_maxCount; ++i ) + { + if ( B3_IS_NULL( m_bodies[i] ) == false ) + { + b3DestroyBody( m_bodies[i] ); + m_bodies[i] = b3_nullBodyId; + return; + } + } + } + + void MouseDown( b3Vec2 p, int button, int modifiers ) override + { + if ( button == 0 && modifiers == GLFW_MOD_CONTROL ) + { + PickRay pickRay = m_camera->BuildPickRay( p.x, p.y ); + m_origin = pickRay.origin; + m_translation = 100.0f * b3Normalize( pickRay.translation ); + } + } + + void UpdateUI() override + { + float height = 360.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 210.0f, height ) ); + + ImGui::Begin( "Options", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + + const char* castTypes[] = { "Ray", "Sphere", "Capsule", "Box" }; + if ( ImGui::Combo( "Cast Type", &m_castType, castTypes, IM_ARRAYSIZE( castTypes ) ) ) + { + } + + if ( m_castType != e_rayCast && m_castType != e_boxCast ) + { + ImGui::SliderFloat( "Radius", &m_castRadius, 0.1f, 2.0f, "%.1f" ); + } + + const char* modes[] = { "Any", "Closest", "Multiple", "Sorted" }; + if ( ImGui::Combo( "Mode", &m_mode, modes, IM_ARRAYSIZE( modes ) ) ) + { + } + + ImGui::Checkbox( "Initial Overlap", &m_initialOverlap ); + + if ( ImGui::Button( "Spheres" ) ) + { + CreateShapes( b3_sphereShape, 10 ); + } + + if ( ImGui::Button( "Capsules" ) ) + { + CreateShapes( b3_capsuleShape, 10 ); + } + + if ( ImGui::Button( "Hulls" ) ) + { + CreateShapes( b3_hullShape, 10 ); + } + + if ( ImGui::Button( "Meshes" ) ) + { + CreateShapes( b3_meshShape, 1 ); + } + + if ( ImGui::Button( "Height Field" ) ) + { + CreateShapes( b3_heightShape, 1 ); + } + + if ( ImGui::Button( "Destroy Shape" ) ) + { + DestroyBody(); + } + + ImGui::End(); + + for ( int i = 0; i < m_maxCount; ++i ) + { + if ( ( i & m_ignoreBase ) == m_ignoreBase && B3_IS_NULL( m_bodies[i] ) == false ) + { + b3AABB bounds = b3Body_ComputeAABB( m_bodies[i] ); + DrawBounds( m_scene, bounds, 0.0f, b3_colorYellow ); + } + } + } + + void Render() override + { + DrawTextLine( "Ctrl + left mouse to cast through cursor" ); + DrawTextLine( "Shapes drawn in yellow boxes are ignored by the ray" ); + + 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 multiple shapes - unsorted" ); + break; + + case e_sorted: + DrawTextLine( "Cast mode: sorted - gather multiple shapes sorted by closeness" ); + break; + + default: + assert( false ); + break; + } + + for ( int i = 0; i < m_castContext.count; ++i ) + { + DrawTextLine( "material = %d, triangle = %d", m_castContext.materialIds[i], m_castContext.triangleIndices[i] ); + } + + DrawGrid( m_scene, 10 ); + DrawTransform( m_scene, b3Transform_identity, 1.0f ); + + Sample::Render(); + } + + void Step() override + { + Sample::Step(); + + b3HexColor color1 = b3_colorOrange; + b3HexColor color2 = b3_colorAqua; + b3HexColor green = b3_colorGreen; + b3HexColor gray = b3_colorGray; + + b3CastResultFcn* functions[] = { RayCastAnyCallback, RayCastClosestCallback, RayCastMultipleCallback, + RayCastSortedCallback }; + b3CastResultFcn* modeFcn = functions[m_mode]; + + m_castContext = {}; + m_castContext.initialOverlap = m_initialOverlap; + + // Must initialize fractions for sorting + m_castContext.fractions[0] = FLT_MAX; + m_castContext.fractions[1] = FLT_MAX; + m_castContext.fractions[2] = FLT_MAX; + + b3Sphere sphere = { m_origin, m_castRadius }; + b3Capsule capsule = { m_origin, m_origin + b3Vec3{ 0.0f, 1.0f, 0.0f }, m_castRadius }; + b3BoxHull box = {}; + + b3Vec3 pointBuffer[2]; + + b3ShapeProxy proxy = {}; + + switch ( m_castType ) + { + case e_rayCast: + proxy.count = 0; + break; + + case e_sphereCast: + proxy.count = 1; + proxy.radius = m_castRadius; + proxy.points = &sphere.center; + break; + + case e_capsuleCast: + proxy.count = 2; + proxy.radius = m_castRadius; + pointBuffer[0] = capsule.center1; + pointBuffer[1] = capsule.center2; + proxy.points = pointBuffer; + break; + + case e_boxCast: + { + b3Vec3 extent = { m_castRadius, 0.5f * m_castRadius, 0.25f * m_castRadius }; + box = b3MakeTransformedBoxHull( extent.x, extent.y, extent.z, { m_origin, b3Quat_identity } ); + proxy.points = box.boxPoints; + proxy.count = box.base.vertexCount; + } + break; + + default: + assert( false ); + break; + } + + if ( m_castType == e_rayCast ) + { + b3World_CastRay( m_worldId, m_origin, m_translation, b3DefaultQueryFilter(), modeFcn, &m_castContext ); + } + else + { + b3World_CastShape( m_worldId, &proxy, m_translation, b3DefaultQueryFilter(), modeFcn, &m_castContext ); + } + + if ( m_castContext.count > 0 ) + { + assert( m_castContext.count <= 3 ); + b3HexColor colors[3] = { b3_colorRed, b3_colorGreen, b3_colorBlue }; + DrawLine( m_scene, m_origin, m_origin + m_translation, color2 ); + + for ( int i = 0; i < m_castContext.count; ++i ) + { + b3Vec3 point = m_castContext.points[i]; + b3Vec3 normal = m_castContext.normals[i]; + DrawPoint( m_scene, point, 10.0f, colors[i] ); + b3Vec3 head = point + 0.5f * normal; + + b3Transform transform = { m_castContext.fractions[i] * m_translation, b3Quat_identity }; + + if ( m_castType == e_rayCast ) + { + DrawLine( m_scene, point, head, colors[i] ); + } + else if ( m_castType == e_sphereCast ) + { + DrawLine( m_scene, point, head, color1 ); + DrawSphere( m_scene, transform, sphere, colors[i] ); + } + else if ( m_castType == e_capsuleCast ) + { + DrawLine( m_scene, point, head, color1 ); + DrawCapsule( m_scene, transform, capsule, colors[i] ); + } + else if ( m_castType == e_boxCast ) + { + DrawLine( m_scene, point, head, color1 ); + DrawHull( m_scene, transform, &box.base, colors[i], false ); + } + } + } + else + { + DrawLine( m_scene, m_origin, m_origin + m_translation, color2 ); + + b3Transform transform = { m_translation, b3Quat_identity }; + + if ( m_castType == e_sphereCast ) + { + DrawSphere( m_scene, transform, sphere, gray ); + } + else if ( m_castType == e_capsuleCast ) + { + DrawCapsule( m_scene, transform, capsule, gray ); + } + else if ( m_castType == e_boxCast ) + { + DrawHull( m_scene, transform, &box.base, gray, false ); + } + } + + DrawPoint( m_scene, m_origin, 2.0f, green ); + } + + static constexpr int m_maxCount = 64; + static constexpr int m_ignoreBase = 0x3; + + b3Capsule m_capsule; + b3Sphere m_sphere; + b3BoxHull m_box; + b3MeshData* m_mesh; + b3HeightField* m_heightField; + + b3BodyId m_bodies[m_maxCount]; + int m_bodyIndex; + int m_mode; + int m_castType; + float m_castRadius; + bool m_initialOverlap; + + b3Vec3 m_origin; + b3Vec3 m_translation; + + CastContext m_castContext; +}; + +static int sampleCastWorld = SampleManager::Register( "Collision", "Cast World", CastWorld::Create ); + +class MeshScale : public Sample +{ +public: + static Sample* Create( SampleContext* context ) + { + return new MeshScale( context ); + } + + explicit MeshScale( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 20.0f ); + } + + m_mesh = b3CreateBoxMesh( { 0.0f, 0.0f, 0.0f }, { 0.5f, 0.5f, 0.5f }, true ); + m_scale = { 1.0f, 1.0f, 1.0f }; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + m_meshBodyId = b3CreateBody( m_worldId, &bodyDef ); + m_meshShapeId = b3CreateMeshShape( m_meshBodyId, &shapeDef, m_mesh, m_scale ); + m_start = { -2.0f, 0.0f, 0.0f }; + m_sphereCast = true; + } + + ~MeshScale() override + { + b3DestroyMesh( m_mesh ); + } + + void UpdateUI() override + { + float height = 200.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); + + ImGui::Begin( "Mesh Scale", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + + b3Vec3 scale = m_scale; + bool changed = false; + changed = changed || ImGui::SliderFloat( "Scale X", &scale.x, -2.0f, 2.0f, "%.1f" ); + changed = changed || ImGui::SliderFloat( "Scale Y", &scale.y, -2.0f, 2.0f, "%.1f" ); + changed = changed || ImGui::SliderFloat( "Scale Z", &scale.z, -2.0f, 2.0f, "%.1f" ); + + if ( changed ) + { + m_scale = scale; + b3Shape_SetMesh( m_meshShapeId, m_mesh, m_scale ); + } + + ImGui::SliderFloat( "Start Y", &m_start.y, -2.0f, 2.0f, "%.1f" ); + ImGui::SliderFloat( "Start Z", &m_start.z, -2.0f, 2.0f, "%.1f" ); + + ImGui::Checkbox( "sphere Cast", &m_sphereCast ); + + ImGui::End(); + } + + void Step() override + { + b3Vec3 rayOrigin = m_start; + b3Vec3 rayTranslation = { 4.0f, 0.0f, 0.0f }; + + DrawPoint( m_scene, rayOrigin, 8.0f, b3_colorGreen ); + DrawPoint( m_scene, rayOrigin + rayTranslation, 8.0f, b3_colorRed ); + DrawLine( m_scene, rayOrigin, rayOrigin + rayTranslation, b3_colorWhite ); + + if ( m_sphereCast ) + { + b3Sphere sphere = { rayOrigin, 0.25f }; + + CastContext context = {}; + b3ShapeProxy proxy = { &sphere.center, 1, sphere.radius }; + b3World_CastShape( m_worldId, &proxy, rayTranslation, b3DefaultQueryFilter(), RayCastClosestCallback, &context ); + + if ( context.count > 0 ) + { + b3Transform transform = { context.fractions[0] * rayTranslation, b3Quat_identity }; + DrawSphere( m_scene, transform, sphere, b3_colorYellow ); + + b3Vec3 point = context.points[0]; + DrawLine( m_scene, point, point + 0.5f * context.normals[0], b3_colorGreen ); + DrawPoint( m_scene, point, 5.0f, b3_colorYellow ); + } + else + { + b3Transform transform = { rayTranslation, b3Quat_identity }; + DrawSphere( m_scene, transform, sphere, b3_colorGray ); + } + } + else + { + b3RayResult result = b3World_CastRayClosest( m_worldId, rayOrigin, rayTranslation, b3DefaultQueryFilter() ); + if ( result.hit ) + { + b3Vec3 point = result.point; + DrawLine( m_scene, point, point + 0.5f * result.normal, b3_colorGreen ); + DrawPoint( m_scene, point, 5.0f, b3_colorYellow ); + } + } + } + + b3Vec3 m_scale; + b3MeshData* m_mesh; + b3BodyId m_meshBodyId; + b3ShapeId m_meshShapeId; + b3Vec3 m_start; + bool m_sphereCast; +}; + +static int sampleMeshScale = SampleManager::Register( "Collision", "Mesh Scale", MeshScale::Create ); + +class ShapeCast : public Sample +{ +public: + explicit ShapeCast( SampleContext* context ) + : Sample( context ) + { + m_camera->SetView( 120.0f, 30.0f, 20.0f, { 0.0f, 1.5f, 0.0f } ); + + b3BoxHull box = b3MakeBoxHull( 0.6f, 0.6f, 0.6f ); + m_mesh = b3CreateTorusMesh( 10, 12, 0.65f, 0.35f ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + for ( int index = 0; index < 3; ++index ) + { + bodyDef.position = { -6.0f, 3.0f + 2.0f * index, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisX, 0.5f * B3_PI ); + b3BodyId sphereBody = b3CreateBody( m_worldId, &bodyDef ); + b3Sphere sphere = { b3Vec3_zero, 0.9f }; + b3CreateSphereShape( sphereBody, &shapeDef, &sphere ); + + bodyDef.position = { -2.0f, 3.0f + 2.0f * index, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.25f * B3_PI ); + b3BodyId capsuleBody = b3CreateBody( m_worldId, &bodyDef ); + b3Capsule capsule = { { -0.5f, 0.0f, 0.0f }, { 0.5f, 0.0f, 0.0f }, 0.7f }; + b3CreateCapsuleShape( capsuleBody, &shapeDef, &capsule ); + + bodyDef.position = { 2.0f, 3.0f + 2.0f * index, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.25f * B3_PI ); + b3BodyId hullBody = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( hullBody, &shapeDef, &box.base ); + + bodyDef.position = { 6.0f, 3.0f + 2.0f * index, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisX, 0.5f * B3_PI ); + b3BodyId meshBody = b3CreateBody( m_worldId, &bodyDef ); + b3CreateMeshShape( meshBody, &shapeDef, m_mesh, b3Vec3_one ); + + // todo add height field + } + + m_baseX = 0; + m_baseY = 0; + m_castOffset = {}; + m_trackingX = false; + m_trackingY = false; + m_initialOverlap = false; + } + + ~ShapeCast() override + { + b3DestroyMesh( m_mesh ); + } + + void CastSpheres() const + { + for ( int castIndex = 0; castIndex < 4; ++castIndex ) + { + // World space sweep + b3Sphere sphere = { b3Vec3_zero, 0.3f }; + b3Vec3 offset = b3Vec3{ -6.0f + 4.0f * castIndex, 3.0f, -5.0f } + m_castOffset; + sphere.center += offset; + b3Vec3 translation = 10.0f * b3Vec3_axisZ; + b3ShapeProxy proxy = { &sphere.center, 1, sphere.radius }; + + CastContext context = {}; + context.initialOverlap = m_initialOverlap; + + b3World_CastShape( m_worldId, &proxy, translation, b3DefaultQueryFilter(), RayCastClosestCallback, &context ); + + DrawSphere( m_scene, b3Transform_identity, sphere, b3_colorGreen ); + + if ( context.count > 0 ) + { + b3Vec3 point = context.points[0]; + b3Vec3 normal = context.normals[0]; + float fraction = context.fractions[0]; + + // final position with overlap resolution + DrawSphere( m_scene, { fraction * translation, b3Quat_identity }, sphere, b3_colorRed ); + + DrawPoint( m_scene, point, 2.0f, b3_colorRed ); + DrawLine( m_scene, point, point + 0.2f * normal, b3_colorYellow ); + } + else + { + DrawSphere( m_scene, { translation, b3Quat_identity }, sphere, b3_colorGray ); + } + } + } + + void CastCapsules() const + { + for ( int castIndex = 0; castIndex < 4; ++castIndex ) + { + b3Capsule capsule = { { -0.2f, -0.2f, -0.2f }, { 0.2f, 0.2f, 0.2f }, 0.2f }; + b3Vec3 offset = b3Vec3{ -6.0f + 4.0f * castIndex, 5.0f, -5.0f } + m_castOffset; + capsule.center1 += offset; + capsule.center2 += offset; + b3Vec3 translation = 10.0f * b3Vec3_axisZ; + b3ShapeProxy proxy = { &capsule.center1, 2, capsule.radius }; + + CastContext context = {}; + context.initialOverlap = m_initialOverlap; + + b3World_CastShape( m_worldId, &proxy, translation, b3DefaultQueryFilter(), RayCastClosestCallback, &context ); + + DrawCapsule( m_scene, b3Transform_identity, capsule, b3_colorGreen ); + + if ( context.count > 0 ) + { + b3Vec3 point = context.points[0]; + b3Vec3 normal = context.normals[0]; + float fraction = context.fractions[0]; + + DrawCapsule( m_scene, { fraction * translation, b3Quat_identity }, capsule, b3_colorRed ); + + DrawPoint( m_scene, point, 2.0f, b3_colorRed ); + DrawLine( m_scene, point, point + 0.2f * normal, b3_colorYellow ); + } + else + { + DrawCapsule( m_scene, { translation, b3Quat_identity }, capsule, b3_colorGray ); + } + } + } + + void CastHulls() const + { + for ( int castIndex = 0; castIndex < 4; ++castIndex ) + { + b3Vec3 offset = b3Vec3{ -6.0f + 4.0f * castIndex, 7.0f, -5.0f } + m_castOffset; + b3Quat qx = b3MakeQuatFromAxisAngle( b3Vec3_axisX, 0.25f * B3_PI ); + b3Quat qy = b3MakeQuatFromAxisAngle( b3Vec3_axisY, 0.25f * B3_PI ); + b3Quat qz = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.25f * B3_PI ); + + b3Quat q = b3MulQuat( qx, b3MulQuat( qy, qz ) ); + + b3Transform transform = { offset, q }; + + b3BoxHull box = b3MakeTransformedBoxHull( 0.3f, 0.3f, 0.3f, transform ); + + b3Vec3 translation = 10.0f * b3Vec3_axisZ; + b3ShapeProxy proxy = { box.boxPoints, box.base.vertexCount, 0.0f }; + + CastContext context = {}; + context.initialOverlap = m_initialOverlap; + + b3World_CastShape( m_worldId, &proxy, translation, b3DefaultQueryFilter(), RayCastClosestCallback, &context ); + + DrawHull( m_scene, b3Transform_identity, &box.base, b3_colorGreen, false ); + + if ( context.count > 0 ) + { + b3Vec3 point = context.points[0]; + b3Vec3 normal = context.normals[0]; + float fraction = context.fractions[0]; + + // final position with overlap resolution + DrawHull( m_scene, { fraction * translation, b3Quat_identity }, &box.base, b3_colorRed, false ); + + DrawPoint( m_scene, point, 2.0f, b3_colorRed ); + DrawLine( m_scene, point, point + 0.2f * normal, b3_colorYellow ); + } + else + { + DrawHull( m_scene, { translation, b3Quat_identity }, &box.base, b3_colorGray, false ); + } + } + } + + void UpdateUI() override + { + float height = 80.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 210.0f, height ) ); + ImGui::Begin( "Shape Cast", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + ImGui::Checkbox( "Initial Overlap", &m_initialOverlap ); + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + + DrawTextLine( "Shift + LMB and drag to shift start position" ); + + DrawGrid( m_scene, 10 ); + DrawTransform( m_scene, b3Transform_identity, 1.0f ); + } + + void MouseDown( b3Vec2 p, int button, int modifiers ) override + { + if ( button == 0 ) + { + if ( modifiers == GLFW_MOD_SHIFT ) + { + m_trackingX = true; + m_baseX = p.x; + } + else if ( modifiers == GLFW_MOD_CONTROL ) + { + m_trackingY = true; + m_baseY = p.y; + } + } + } + + void MouseUp( b3Vec2 p, int button ) override + { + if ( button == 0 ) + { + m_trackingX = false; + m_trackingY = false; + } + } + + void MouseMove( b3Vec2 p ) override + { + if ( m_trackingX ) + { + m_castOffset.z = 0.05f * ( m_baseX - p.x ); + } + + if ( m_trackingY ) + { + m_castOffset.y = 0.05f * ( m_baseY - p.y ); + } + } + + void Step() override + { + CastSpheres(); + CastCapsules(); + CastHulls(); + } + + static Sample* Create( SampleContext* context ) + { + return new ShapeCast( context ); + } + + b3MeshData* m_mesh; + int m_baseX; + int m_baseY; + b3Vec3 m_castOffset; + bool m_trackingX; + bool m_trackingY; + bool m_initialOverlap; +}; + +static int sampleShapeCast = SampleManager::Register( "Collision", "Shape Cast", ShapeCast::Create ); + +// Tests shape overlap versus world +class OverlapWorld : public Sample +{ +public: + enum + { + BODY_COUNT = 12 + }; + + static Sample* Create( SampleContext* context ) + { + return new OverlapWorld( context ); + } + + explicit OverlapWorld( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + + m_camera->SetView( 120.0f, 30.0f, 20.0f, { 0.0f, 1.5f, 0.0f } ); + } + + b3World_SetGravity( m_worldId, b3Vec3_zero ); + + m_box = b3MakeBoxHull( 0.6f, 0.6f, 0.6f ); + m_mesh = b3CreateTorusMesh( 10, 12, 0.65f, 0.35f ); + + m_heightField = b3CreateWave( 10, 10, 0.2f * b3Vec3_one, 0.03f, 0.09f, false ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + for ( int index = 0; index < 3; ++index ) + { + b3BodyType type = b3BodyType( index ); + + bodyDef.type = type; + bodyDef.position = { -6.0f, 3.0f + 2.0f * index, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisX, 0.5f * B3_PI ); + b3BodyId sphereBody = b3CreateBody( m_worldId, &bodyDef ); + b3Sphere sphere = { b3Vec3_zero, 0.8f }; + b3CreateSphereShape( sphereBody, &shapeDef, &sphere ); + + bodyDef.type = type; + bodyDef.position = { -3.0f, 3.0f + 2.0f * index, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.25f * B3_PI ); + b3BodyId capsuleBody = b3CreateBody( m_worldId, &bodyDef ); + b3Capsule capsule = { { -0.5f, 0.0f, 0.0f }, { 0.5f, 0.0f, 0.0f }, 0.5f }; + b3CreateCapsuleShape( capsuleBody, &shapeDef, &capsule ); + + bodyDef.type = type; + bodyDef.position = { 0.0f, 3.0f + 2.0f * index, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.25f * B3_PI ); + b3BodyId hullBody = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( hullBody, &shapeDef, &m_box.base ); + + bodyDef.type = type; + bodyDef.position = { 3.0f, 3.0f + 2.0f * index, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisX, 0.5f * B3_PI ); + b3BodyId meshBody = b3CreateBody( m_worldId, &bodyDef ); + b3CreateMeshShape( meshBody, &shapeDef, m_mesh, { -0.5f, 1.5f, -1.0f } ); + + // Height fields only on static bodies + bodyDef.type = b3_staticBody; + bodyDef.position = { 5.0f, 2.0f + 2.0f * index, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisX, -0.5f * B3_PI ); + b3BodyId heightBody = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHeightFieldShape( heightBody, &shapeDef, m_heightField ); + } + + m_baseX = 0; + m_castOffset = 0.0f; + m_tracking = false; + } + + ~OverlapWorld() override + { + b3DestroyHeightField( m_heightField ); + b3DestroyMesh( m_mesh ); + } + + static bool OverlapResultFcn( b3ShapeId shapeId, void* context ) + { + b3HexColor* color = static_cast( context ); + *color = b3_colorRed; + + // terminate the query + return false; + } + + void OverlapSpheres() const + { + for ( int i = 0; i < 5; ++i ) + { + b3Sphere sphere = { { -6.0f + 3.0f * i, 3.0f, -5.0f + m_castOffset }, 0.3f }; + b3ShapeProxy proxy = { &sphere.center, 1, sphere.radius }; + b3HexColor color = b3_colorGreen; + b3World_OverlapShape( m_worldId, &proxy, b3DefaultQueryFilter(), OverlapResultFcn, &color ); + DrawSphere( m_scene, b3Transform_identity, sphere, color ); + } + } + + void OverlapCapsules() const + { + + for ( int i = 0; i < 5; ++i ) + { + b3Vec3 offset = { -6.0f + 3.0f * i, 5.0f, -5.0f + m_castOffset }; + b3Capsule capsule = { { -0.2f, -0.2f, -0.2f }, { 0.2f, 0.2f, 0.2f }, 0.2f }; + capsule.center1 += offset; + capsule.center2 += offset; + b3ShapeProxy proxy = { &capsule.center1, 2, capsule.radius }; + b3HexColor color = b3_colorGreen; + b3World_OverlapShape( m_worldId, &proxy, b3DefaultQueryFilter(), OverlapResultFcn, &color ); + DrawCapsule( m_scene, b3Transform_identity, capsule, color ); + } + } + + void OverlapHulls() const + { + for ( int i = 0; i < 5; ++i ) + { + b3Transform transform{ { -6.0f + 3.0f * i, 7.0f, -5.0f + m_castOffset }, b3Quat_identity }; + b3BoxHull box = b3MakeTransformedBoxHull( 0.3f, 0.3f, 0.3f, transform ); + b3ShapeProxy proxy = { box.boxPoints, box.base.vertexCount, 0.0f }; + b3HexColor color = b3_colorGreen; + b3World_OverlapShape( m_worldId, &proxy, b3DefaultQueryFilter(), OverlapResultFcn, &color ); + DrawHull( m_scene, b3Transform_identity, &box.base, color, false ); + } + } + + void Render() override + { + Sample::Render(); + + DrawTextLine( "Shift + LMB and drag to move shapes" ); + + DrawGrid( m_scene, 10 ); + DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisX, b3_colorRed ); + DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisY, b3_colorGreen ); + DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisZ, b3_colorBlue ); + } + + void MouseDown( b3Vec2 p, int button, int modifiers ) override + { + if ( button == 0 ) + { + if ( modifiers == GLFW_MOD_SHIFT ) + { + m_tracking = true; + m_baseX = p.x; + } + } + } + + void MouseUp( b3Vec2 p, int button ) override + { + if ( button == 0 ) + { + m_tracking = false; + } + } + + void MouseMove( b3Vec2 p ) override + { + if ( m_tracking ) + { + m_castOffset = 0.05f * ( m_baseX - p.x ); + } + } + + void Step() override + { + OverlapSpheres(); + OverlapCapsules(); + OverlapHulls(); + } + + b3BoxHull m_box; + b3MeshData* m_mesh; + b3HeightField* m_heightField; + int m_baseX; + float m_castOffset; + bool m_tracking; +}; + +static int sampleOverlapWorld = SampleManager::Register( "Collision", "Overlap World", OverlapWorld::Create ); + +class InitialOverlap : public Sample +{ +public: + explicit InitialOverlap( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( -140.0f, 10.0f, 10.0f, { 0.0f, 0.0f, 0.0f } ); + } + + int indices[] = { 0, 1, 2, 2, 3, 0 }; + + b3Vec3 vertices[] = { { -0.5f, 0.5f, 0.5f }, { -0.5f, 0.5f, -0.5f }, { -0.5f, -0.5f, -0.5f }, { -0.5f, -0.5f, 0.5f } }; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, 0.0f, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 10.0f * B3_DEG_TO_RAD ); + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + // m_mesh = b3CreateBoxMesh( { 0.0f, 0.0f, 0.0f }, { 0.5f, 0.5f, 0.5f } ); + b3MeshDef def = {}; + def.triangleCount = 2; + def.indices = indices; + def.vertexCount = 4; + def.vertices = vertices; + def.materialIndices = nullptr; + def.useMedianSplit = false; + + m_mesh = b3CreateMesh( &def, nullptr, 0 ); + b3CreateMeshShape( body, &shapeDef, m_mesh, 4.0f * b3Vec3_one ); + + m_initialOverlap = true; + } + + ~InitialOverlap() override + { + b3DestroyMesh( m_mesh ); + } + + void Render() override + { + Sample::Render(); + + DrawTransform( m_scene, b3Transform_identity, 1.0f ); + } + + void UpdateUI() override + { + float height = 80.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); + ImGui::Begin( "Initial Overlap", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + ImGui::Checkbox( "initial overlap", &m_initialOverlap ); + ImGui::End(); + } + + void Step() override + { + Sample::Step(); + + b3Vec3 offset = { -2.1f, -0.8f, 0.95f }; + + CastContext context = {}; + context.initialOverlap = m_initialOverlap; + + b3Capsule capsule = { + .center1 = offset, + .center2 = offset + b3Vec3{ 0.0f, 1.0f, 0.0f }, + .radius = 0.25f, + }; + + // zero length cast + b3Vec3 translation = { 0.0f, 0.0f, 0.0f }; + + b3ShapeProxy proxy = { &capsule.center1, 2, capsule.radius }; + + DrawCapsule( m_scene, b3Transform_identity, capsule, b3_colorGreen ); + + b3World_CastShape( m_worldId, &proxy, translation, b3DefaultQueryFilter(), RayCastClosestCallback, &context ); + + float fraction = context.count > 0 ? context.fractions[0] : 1.0f; + b3Transform shapeEnd = { fraction * translation, b3Quat_identity }; + DrawCapsule( m_scene, shapeEnd, capsule, context.count > 0 ? b3_colorRed : b3_colorGreen ); + + if ( context.count > 0 ) + { + b3Vec3 p = context.points[0]; + b3Vec3 n = context.normals[0]; + DrawLine( m_scene, p, p + 0.5f * n, b3_colorAliceBlue ); + DrawPoint( m_scene, p, 8.0f, b3_colorAliceBlue ); + } + } + + static Sample* Create( SampleContext* context ) + { + return new InitialOverlap( context ); + } + + b3MeshData* m_mesh; + bool m_initialOverlap; +}; + +static int sampleInitialOverlap = SampleManager::Register( "Collision", "Initial Overlap", InitialOverlap::Create ); + +// pointA[0] = {0.000000000, 0.000000000, 0.000000000} +// pointA[1] = {0.000000000, -6400.000000000, 0.000000000} +// pointA[2] = {6400.000000000, 0.000000000, 22.609375000} +// pointB[i] = {43616.210937500, -100213.000000000, 132631.812500000} +// pointB[i] = {342231.968750000, 359711.687500000, 132631.812500000} +// radiusB = 40.0f +// xfA = {{0.000000000, 0.000000000, 0.000000000}, {{0.000000000, 0.000000000, 0.000000000}, 1.000000000} +// xfB = {{-115200.000000000, -19200.000000000, -202755.000000000}, {{0.000000000, 0.000000000, 0.000000000}, 1.000000000} +// t = {0.008614914, 0.000000000, 72267.117187500} +// maxFraction = 0.970617533, canEncroach = 0 +class ShapeCastDebug : public Sample +{ +public: + explicit ShapeCastDebug( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 120.0f, 30.0f, 20.0f, { 0.0f, 1.5f, 0.0f } ); + } + + // this triggers an assert with scale of 1 and b3_lengthUnitsPerMeter of 100 + float scale = 0.01f; + m_triangle[0] = scale * b3Vec3{ 0.000000000, 0.000000000, 0.000000000 }; + m_triangle[1] = scale * b3Vec3{ 0.000000000, -6400.000000000, 0.000000000 }; + m_triangle[2] = scale * b3Vec3{ 6400.000000000, 0.000000000, 22.609375000 }; + + b3Vec3 origin = m_triangle[0]; + m_triangle[0] = b3Vec3_zero; + m_triangle[1] -= origin; + m_triangle[2] -= origin; + + m_points[0] = scale * b3Vec3{ 200.305283, 200.460999, 9.53760529 }; + m_points[1] = scale * b3Vec3{ -200.305283, 200.460999, 9.53760529 }; + m_points[2] = scale * b3Vec3{ -200.305283, -200.460999, 9.53760529 }; + m_points[3] = scale * b3Vec3{ 200.305283, -200.460999, 9.53760529 }; + m_points[4] = scale * b3Vec3{ 200.305283, 200.460999, -9.53760529 }; + m_points[5] = scale * b3Vec3{ -200.305283, 200.460999, -9.53760529 }; + m_points[6] = scale * b3Vec3{ -200.305283, -200.460999, -9.53760529 }; + m_points[7] = scale * b3Vec3{ 200.305283, -200.460999, -9.53760529 }; + + m_capsule.center1 = scale * b3Vec3{ 43616.210937500, -100213.000000000, 132631.812500000 }; + m_capsule.center2 = scale * b3Vec3{ 342231.968750000, 359711.687500000, 132631.812500000 }; + m_capsule.radius = scale * 1.0f; + + float length = b3Distance( m_capsule.center1, m_capsule.center2 ); + (void)length; + + m_transform = { scale * b3Vec3{ -115200.000000000, -19200.000000000, -202755.000000000 } - origin, + { { 0.00000000, 0.00000000, 0.0f }, 1.0f } }; + + m_translation = scale * b3Vec3{ 0.008614914, 0.000000000, 72267.117187500 }; + + m_box = b3CreateHull( m_points, 8, 8 ); + } + + ~ShapeCastDebug() override + { + b3DestroyHull( m_box ); + } + + void Render() override + { + Sample::Render(); + + DrawGrid( m_scene, 10 ); + DrawTransform( m_scene, b3Transform_identity, 1.0f ); + + b3ShapeCastPairInput input; + input.proxyA = { m_triangle, 3, 0.0f }; + // input.proxyB = { m_points, 8, 0.0f }; + input.proxyB = { &m_capsule.center1, 2, m_capsule.radius }; + input.transformA = b3Transform_identity; + input.transformB = m_transform; + input.translationB = m_translation; + input.maxFraction = 0.970617533; + input.canEncroach = false; + + b3CastOutput output = b3ShapeCast( &input ); + + DrawFace( m_scene, m_triangle[0], m_triangle[1], m_triangle[2], b3_colorCyan ); + // DrawHull( m_scene, m_transform, m_box, b3_colorGreen, false ); + DrawCapsule( m_scene, m_transform, m_capsule, b3_colorGreen ); + + if ( output.hit ) + { + // final position with overlap resolution + b3Vec3 shapeEnd = m_transform.p + output.fraction * m_translation; + // DrawHull( m_scene, { shapeEnd, m_transform.q }, m_box, b3_colorRed, false ); + DrawCapsule( m_scene, { shapeEnd, m_transform.q }, m_capsule, b3_colorRed ); + } + + b3Vec3 shapeEnd = m_transform.p + m_translation; + // DrawHull( m_scene, { shapeEnd, m_transform.q }, m_box, b3_colorGray, false ); + DrawCapsule( m_scene, { shapeEnd, m_transform.q }, m_capsule, b3_colorGray ); + } + + static Sample* Create( SampleContext* context ) + { + return new ShapeCastDebug( context ); + } + + b3Transform m_transform; + b3Vec3 m_translation; + b3Capsule m_capsule; + b3Hull* m_box; + b3Vec3 m_points[8]; + b3Vec3 m_triangle[3]; +}; + +static int sampleShapeCastDebug = SampleManager::Register( "Collision", "Shape Cast Debug", ShapeCastDebug::Create ); + +class DistanceDebug : public Sample +{ +public: + explicit DistanceDebug( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 120.0f, 30.0f, 20.0f, { 0.0f, 1.5f, 0.0f } ); + } + + // this triggers an assert with scale of 1 and b3_lengthUnitsPerMeter of 100 + float scale = 0.01f; + m_triangle[0] = scale * b3Vec3{ 1400.00000, 1600.00000, 70.1534424 }; + m_triangle[1] = scale * b3Vec3{ 1400.00000, 1500.00000, 66.1250000 }; + m_triangle[2] = scale * b3Vec3{ 1500.00000, 1600.00000, 72.3507080 }; + + // shifting to the origin give more accuracy + b3Vec3 origin = m_triangle[0]; + m_triangle[0] = b3Vec3_zero; + m_triangle[1] -= origin; + m_triangle[2] -= origin; + + m_points[0] = scale * b3Vec3{ 200.305283, 200.460999, 9.53760529 }; + m_points[1] = scale * b3Vec3{ -200.305283, 200.460999, 9.53760529 }; + m_points[2] = scale * b3Vec3{ -200.305283, -200.460999, 9.53760529 }; + m_points[3] = scale * b3Vec3{ 200.305283, -200.460999, 9.53760529 }; + m_points[4] = scale * b3Vec3{ 200.305283, 200.460999, -9.53760529 }; + m_points[5] = scale * b3Vec3{ -200.305283, 200.460999, -9.53760529 }; + m_points[6] = scale * b3Vec3{ -200.305283, -200.460999, -9.53760529 }; + m_points[7] = scale * b3Vec3{ 200.305283, -200.460999, -9.53760529 }; + + m_boxA = b3MakeBoxHull( 40.0f, 1.0f, 40.0f ); + m_boxB = b3MakeTransformedBoxHull( 0.5f, 10.0f, 0.5f, { { 0.0f, 10.0f, 0.0f }, b3Quat_identity } ); + + // m_transformA = { + // .p = { 0.0f, -1.0f, 0.0f }, + // .q = b3Quat_identity, + // }; + + m_transformB = { + .p = { -1.64657831e-06, 1.00989532471, 0.0f }, + .q = { { 0.00000000, 0.00000000, 0.00494779600 }, 0.999987781 }, + }; + + m_box = b3CreateHull( m_points, 8, 8 ); + + m_simplexCount = 0; + m_simplexIndex = 0; + + memset( m_simplexes, 0, sizeof( m_simplexes ) ); + } + + ~DistanceDebug() override + { + b3DestroyHull( m_box ); + } + + void Render() override + { + Sample::Render(); + + DrawGrid( m_scene, 10 ); + DrawTransform( m_scene, b3Transform_identity, 1.0f ); + } + + void UpdateUI() override + { + float height = 80.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); + + ImGui::Begin( "Distance Debug", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + + ImGui::SliderInt( "simplex index", &m_simplexIndex, 0, m_simplexCount - 1 ); + + ImGui::End(); + } + + static void BuildWitnessPoints( const b3Simplex* simplex, b3Vec3& vertexA, b3Vec3& vertexB ) + { + const b3SimplexVertex* vs = simplex->vertices; + int count = simplex->count; + B3_ASSERT( 1 <= count && count <= 4 ); + + switch ( count ) + { + case 1: + vertexA = vs[0].wA; + vertexB = vs[0].wB; + break; + + case 2: + vertexA = vs[0].a * vs[0].wA + vs[1].a * vs[1].wA; + vertexB = vs[0].a * vs[0].wB + vs[1].a * vs[1].wB; + break; + + case 3: + vertexA = vs[0].a * vs[0].wA + vs[1].a * vs[1].wA + vs[2].a * vs[2].wA; + vertexB = vs[0].a * vs[0].wB + vs[1].a * vs[1].wB + vs[2].a * vs[2].wB; + break; + + case 4: + // Force identical points and *zero* distance + vertexA = vertexB = vs[0].a * vs[0].wA + vs[1].a * vs[1].wA + vs[2].a * vs[2].wA + vs[3].a * vs[3].wA; + break; + + default: + B3_ASSERT( !"Should never get here!" ); + break; + } + } + + static b3Vec3 GetClosestPoint( const b3Simplex* simplex ) + { + int count = simplex->count; + B3_ASSERT( 1 <= count && count <= 4 ); + + const b3SimplexVertex* vs = simplex->vertices; + + switch ( count ) + { + case 1: + return simplex->vertices[0].w; + + case 2: + return vs[0].a * vs[0].w + vs[1].a * vs[1].w; + + case 3: + return vs[0].a * vs[0].w + vs[1].a * vs[1].w + vs[2].a * vs[2].w; + + case 4: + return vs[0].a * vs[0].w + vs[1].a * vs[1].w + vs[2].a * vs[2].w + vs[3].a * vs[3].w; + + default: + B3_ASSERT( !"Should never get here!" ); + break; + } + + return b3Vec3_zero; + } + + void Step() override + { + b3DistanceInput input; + input.proxyA = { m_boxA.boxPoints, 8, 0.0f }; + input.proxyB = { m_boxB.boxPoints, 8, 0.0f }; + input.transformA = b3Transform_identity; + input.transformB = m_transformB; + input.useRadii = false; + + b3SimplexCache cache = {}; + b3DistanceOutput output = b3ShapeDistance( &input, &cache, m_simplexes, 32 ); + m_simplexCount = output.simplexCount; + + // DrawFace( m_scene, m_triangle[0], m_triangle[1], m_triangle[2], b3_colorCyan ); + // DrawHull( m_scene, m_transformB, m_box, b3_colorGreen, false ); + + DrawHull( m_scene, b3Transform_identity, &m_boxA.base, b3_colorGreen, false ); + DrawHull( m_scene, m_transformB, &m_boxB.base, b3_colorCyan, false ); + + for ( int i = 0; i < m_boxB.base.vertexCount; ++i ) + { + b3Vec3 p = b3TransformPoint( m_transformB, m_boxB.boxPoints[i] ); + DrawWorldString( m_camera, p, b3_colorAliceBlue, " %d", i ); + } + + DrawPoint( m_scene, output.pointA, 5.0f, b3_colorWhite ); + DrawPoint( m_scene, output.pointB, 5.0f, b3_colorWhite ); + DrawLine( m_scene, output.pointA, output.pointA + 1.0f * output.normal, b3_colorWhite ); + + b3Vec3 n = output.normal; + DrawTextLine( "distance = %g, normal = %g, %g, %g", output.distance, n.x, n.y, n.z ); + + B3_ASSERT( output.distance > 0.0f && b3IsNormalized( output.normal ) ); + + if ( m_simplexCount > 0 ) + { + b3Simplex* simplex = m_simplexes + m_simplexIndex; + + b3Vec3 v1, v2; + BuildWitnessPoints( simplex, v1, v2 ); + + DrawPoint( m_scene, v1, 10.0f, b3_colorGreen ); + DrawPoint( m_scene, v2, 10.0f, b3_colorGreen ); + + for ( int i = 0; i < simplex->count; ++i ) + { + v1 = simplex->vertices[i].wA; + v2 = simplex->vertices[i].wB; + DrawPoint( m_scene, v1, 5.0f, b3_colorRed ); + DrawPoint( m_scene, v2, 5.0f, b3_colorRed ); + } + + b3Vec3 p = GetClosestPoint( simplex ); + float distance = b3Length( p ); + + DrawTextLine( "current distance = %.5f", distance ); + } + + for ( int i = 0; i < m_simplexCount; ++i ) + { + b3Simplex* simplex = m_simplexes + i; + + if ( simplex->count == 1 ) + { + b3SimplexVertex* v1 = simplex->vertices + 0; + DrawTextLine( "v1s : %d, v2s : %d", v1->indexA, v1->indexB ); + } + else if ( simplex->count == 2 ) + { + b3SimplexVertex* v1 = simplex->vertices + 0; + b3SimplexVertex* v2 = simplex->vertices + 1; + DrawTextLine( "v1s : %d/%d, v2s : %d/%d", v1->indexA, v2->indexA, v1->indexB, v2->indexB ); + } + else if ( simplex->count == 3 ) + { + b3SimplexVertex* v1 = simplex->vertices + 0; + b3SimplexVertex* v2 = simplex->vertices + 1; + b3SimplexVertex* v3 = simplex->vertices + 2; + DrawTextLine( "v1s : %d/%d/%d, v2s : %d/%d/%d", v1->indexA, v2->indexA, v3->indexA, v1->indexB, v2->indexB, + v3->indexB ); + } + else if ( simplex->count == 3 ) + { + b3SimplexVertex* v1 = simplex->vertices + 0; + b3SimplexVertex* v2 = simplex->vertices + 1; + b3SimplexVertex* v3 = simplex->vertices + 2; + b3SimplexVertex* v4 = simplex->vertices + 3; + DrawTextLine( "v1s : %d/%d/%d/%d, v2s : %d/%d/%d/%d", v1->indexA, v2->indexA, v3->indexA, v4->indexA, v1->indexB, + v2->indexB, v3->indexB, v4->indexB ); + } + } + } + + static Sample* Create( SampleContext* context ) + { + return new DistanceDebug( context ); + } + + b3Transform m_transformB; + b3Hull* m_box; + b3BoxHull m_boxA; + b3BoxHull m_boxB; + b3Vec3 m_points[8]; + b3Vec3 m_triangle[3]; + b3Simplex m_simplexes[32]; + int m_simplexIndex; + int m_simplexCount; +}; + +static int sampleDistanceDebug = SampleManager::Register( "Collision", "Distance Debug", DistanceDebug::Create ); + +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_camera->SetView( -90.0f, 0.0f, 10.0f, { 0.0f, 0.0f, 0.0f } ); + } + + m_point = b3Vec3_zero; + m_segment[0] = { -0.5f, 0.0f }; + m_segment[1] = { 0.5f, 0.0f }; + + m_triangle[0] = { -0.5f, 0.0f }; + m_triangle[1] = { 0.5f, 0.0f }; + m_triangle[2] = { 0.0f, 1.0f }; + m_box = b3MakeBoxHull( 0.25f, 0.5f, 1.0f ); + + m_triangle[0] = { 0.0f, 0.0f, -4.0f }; + m_triangle[1] = { 0.0f, 0.0f, -8.0f }; + m_triangle[2] = { -4.0f, 0.0f, -8.0f }; + m_box = b3MakeBoxHull( 0.02f, 0.2f, 0.04f ); + + m_transform = { { 0.0f, 0.0f, 0.0f }, b3Quat_identity }; + m_transform = { + .p = { 0.00000000, 0.796873450, -4.50000000 }, + .q = { { -0.964603841, -0.0856034234, 0.248849452 }, 0.0168983955 }, + }; + + m_cache = {}; + m_simplexCount = 0; + m_simplexIndex = 0; + m_dragStart = { 0.0f, 0.0f }; + m_basePosition = { 0.0f, 0.0f, 0.0f }; + m_baseQuat = { .v = { .z = 1.0f } }; + + m_dragging = false; + m_rotating = false; + m_showIndices = false; + m_useCache = false; + m_drawSimplex = false; + + m_typeA = e_triangle; + 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 ); + } + + b3ShapeProxy MakeProxy( ShapeType type, float radius ) + { + b3ShapeProxy proxy = {}; + proxy.radius = radius; + + switch ( type ) + { + case e_point: + proxy.points = &m_point; + proxy.count = 1; + break; + + case e_segment: + proxy.points = m_segment; + proxy.count = 2; + break; + + case e_triangle: + proxy.points = m_triangle; + proxy.count = 3; + break; + + case e_box: + proxy.points = b3GetHullPoints( &m_box.base ); + proxy.count = m_box.base.vertexCount; + break; + + default: + assert( false ); + } + + return proxy; + } + + void DrawShape( ShapeType type, b3Transform transform, float radius, b3HexColor color ) + { + switch ( type ) + { + case e_point: + { + if ( radius > 0.0f ) + { + b3Sphere sphere = { + .center = m_point, + .radius = radius, + }; + DrawSphere( m_scene, transform, sphere, color ); + } + else + { + b3Vec3 p = b3TransformPoint( transform, m_point ); + DrawPoint( m_scene, p, 5.0f, color ); + } + } + break; + + case e_segment: + { + if ( radius > 0.0f ) + { + b3Capsule capsule = { + .center1 = m_segment[0], + .center2 = m_segment[1], + .radius = radius, + }; + + DrawCapsule( m_scene, transform, capsule, color ); + } + else + { + b3Vec3 p1 = b3TransformPoint( transform, m_segment[0] ); + b3Vec3 p2 = b3TransformPoint( transform, m_segment[1] ); + DrawLine( m_scene, p1, p2, color ); + } + } + break; + + case e_triangle: + { + b3Vec3 p1 = b3TransformPoint( transform, m_triangle[0] ); + b3Vec3 p2 = b3TransformPoint( transform, m_triangle[1] ); + b3Vec3 p3 = b3TransformPoint( transform, m_triangle[2] ); + DrawLine( m_scene, p1, p2, color ); + DrawLine( m_scene, p2, p3, color ); + DrawLine( m_scene, p3, p1, color ); + } + break; + + case e_box: + DrawHull( m_scene, transform, &m_box.base, color, false ); + break; + + default: + assert( false ); + } + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 16.0f * fontSize; + ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->m_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 ( ( m_typeA == e_point || m_typeA == e_segment ) && 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 ( ( m_typeB == e_point || m_typeB == e_segment ) && ImGui::SliderFloat( "radius B", &m_radiusB, 0.0f, 0.5f, "%.2f" ) ) + { + m_proxyB.radius = m_radiusB; + } + + 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 = b3ClampInt( m_simplexIndex, 0, m_simplexCount - 1 ); + } + + ImGui::End(); + } + + void MouseDown( b3Vec2 ps, int button, int mods ) override + { + if ( button == GLFW_MOUSE_BUTTON_1 ) + { + if ( mods == 0 && m_rotating == false ) + { + m_dragging = true; + PickRay ray = m_camera->BuildPickRay( ps.x, ps.y ); + b3Vec3 d = b3Normalize( ray.translation ); + + // Intersect with plane going through origin + // p = c + alpha * f + // dot(p, f) = 0 + // dot(c, f) + alpha = 0 + // p = c - dot(c, f) * f + m_dragStart = b3MulSub( ray.origin, b3Dot( ray.origin, d ), d ); + m_basePosition = m_transform.p; + } + else if ( mods == GLFW_MOD_SHIFT && m_dragging == false ) + { + m_rotating = true; + m_rotateStart = ps.x; + m_baseQuat = m_transform.q; + } + } + } + + void MouseUp( b3Vec2, int button ) override + { + if ( button == GLFW_MOUSE_BUTTON_1 ) + { + m_dragging = false; + m_rotating = false; + } + } + + void MouseMove( b3Vec2 ps ) override + { + if ( m_dragging ) + { + PickRay ray = m_camera->BuildPickRay( ps.x, ps.y ); + b3Vec3 d = b3Normalize( ray.translation ); + b3Vec3 p = b3MulSub( ray.origin, b3Dot( ray.origin, d ), d ); + m_transform.p = m_basePosition + ( p - m_dragStart ); + } + else if ( m_rotating && m_camera->m_width > 0.0f ) + { + float dx = ( ps.x - m_rotateStart ) / m_camera->m_width; + float angle = b3ClampFloat( 2.0f * dx, -B3_PI, B3_PI ); + b3Vec3 axis = m_camera->GetForward(); + b3Quat deltaQuat = b3MakeQuatFromAxisAngle( axis, angle ); + m_transform.q = b3MulQuat( deltaQuat, m_baseQuat ); + } + } + + static b3Vec3 Weight2( float a1, b3Vec3 w1, float a2, b3Vec3 w2 ) + { + return { a1 * w1.x + a2 * w2.x, a1 * w1.y + a2 * w2.y }; + } + + static b3Vec3 Weight3( float a1, b3Vec3 w1, float a2, b3Vec3 w2, float a3, b3Vec3 w3 ) + { + return { a1 * w1.x + a2 * w2.x + a3 * w3.x, a1 * w1.y + a2 * w2.y + a3 * w3.y }; + } + + static void ComputeWitnessPoints( b3Vec3* a, b3Vec3* b, const b3Simplex* s ) + { + const b3SimplexVertex* vs = s->vertices; + int count = s->count; + B3_ASSERT( 1 <= count && count <= 4 ); + + switch ( count ) + { + case 1: + *a = vs[0].wA; + *b = vs[0].wB; + break; + + case 2: + *a = vs[0].a * vs[0].wA + vs[1].a * vs[1].wA; + *b = vs[0].a * vs[0].wB + vs[1].a * vs[1].wB; + break; + + case 3: + *a = vs[0].a * vs[0].wA + vs[1].a * vs[1].wA + vs[2].a * vs[2].wA; + *b = vs[0].a * vs[0].wB + vs[1].a * vs[1].wB + vs[2].a * vs[2].wB; + break; + + case 4: + // Force identical points and *zero* distance + *a = *b = vs[0].a * vs[0].wA + vs[1].a * vs[1].wA + vs[2].a * vs[2].wA + vs[3].a * vs[3].wA; + break; + + default: + B3_ASSERT( !"Should never get here!" ); + break; + } + } + + void Render() override + { + DrawTransform( m_scene, b3Transform_identity, 0.5f ); + Sample::Render(); + } + + void Step() override + { + b3DistanceInput input; + input.proxyA = m_proxyA; + input.proxyB = m_proxyB; + input.transformA = b3Transform_identity; + input.transformB = m_transform; + input.useRadii = m_radiusA > 0.0f || m_radiusB > 0.0f; + + if ( m_useCache == false ) + { + m_cache.count = 0; + } + + b3DistanceOutput output = b3ShapeDistance( &input, &m_cache, m_simplexes, m_simplexCapacity ); + + if ( output.distance > 0.0f ) + { + assert( b3IsNormalized( output.normal ) ); + b3Vec3 d = b3Sub( output.pointB, output.pointA ); + float length = b3Length( d ); + assert( b3AbsFloat( length - output.distance ) < 10.0f * FLT_EPSILON ); + b3Vec3 n = b3Normalize( d ); + assert( b3AbsFloat( n.x - output.normal.x ) < 100.0f * FLT_EPSILON ); + assert( b3AbsFloat( n.y - output.normal.y ) < 100.0f * FLT_EPSILON ); + assert( b3AbsFloat( n.z - output.normal.z ) < 100.0f * FLT_EPSILON ); + } + + m_simplexCount = output.simplexCount; + + DrawShape( m_typeA, b3Transform_identity, m_radiusA, b3_colorCyan ); + DrawShape( m_typeB, m_transform, m_radiusB, b3_colorBisque ); + + if ( m_drawSimplex ) + { + b3Simplex* simplex = m_simplexes + m_simplexIndex; + b3SimplexVertex* vertices = simplex->vertices; + + if ( m_simplexIndex > 0 ) + { + // The first recorded simplex does not have valid barycentric coordinates + b3Vec3 pointA, pointB; + ComputeWitnessPoints( &pointA, &pointB, simplex ); + + DrawLine( m_scene, pointA, pointB, b3_colorWhite ); + DrawPoint( m_scene, pointA, 10.0f, b3_colorLightGreen ); + DrawPoint( m_scene, pointB, 10.0f, b3_colorLightBlue ); + } + + b3HexColor colors[3] = { b3_colorRed, b3_colorGreen, b3_colorBlue }; + + for ( int i = 0; i < simplex->count; ++i ) + { + b3SimplexVertex* vertex = vertices + i; + DrawPoint( m_scene, vertex->wA, 10.0f, colors[i] ); + DrawPoint( m_scene, vertex->wB, 10.0f, colors[i] ); + } + } + else + { + DrawLine( m_scene, output.pointA, output.pointB, b3_colorDimGray ); + DrawPoint( m_scene, output.pointA, 10.0f, b3_colorLightGreen ); + DrawPoint( m_scene, output.pointB, 10.0f, b3_colorLightBlue ); + DrawLine( m_scene, output.pointA, output.pointA + 0.5f * output.normal, b3_colorYellow ); + } + + if ( m_showIndices ) + { + for ( int i = 0; i < m_proxyA.count; ++i ) + { + b3Vec3 p = m_proxyA.points[i]; + DrawWorldString( m_camera, p, b3_colorWhite, " %d", i ); + } + + for ( int i = 0; i < m_proxyB.count; ++i ) + { + b3Vec3 p = b3TransformPoint( m_transform, m_proxyB.points[i] ); + DrawWorldString( m_camera, p, b3_colorWhite, " %d", i ); + } + } + + DrawTextLine( "mouse button 1: drag" ); + DrawTextLine( "mouse button 1 + shift: rotate" ); + DrawTextLine( "distance = %.4f, 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; + + b3BoxHull m_box; + b3Vec3 m_triangle[3]; + b3Vec3 m_point; + b3Vec3 m_segment[2]; + + ShapeType m_typeA; + ShapeType m_typeB; + float m_radiusA; + float m_radiusB; + b3ShapeProxy m_proxyA; + b3ShapeProxy m_proxyB; + + b3SimplexCache m_cache; + b3Simplex m_simplexes[m_simplexCapacity]; + int m_simplexCount; + int m_simplexIndex; + + b3Transform m_transform; + + b3Vec3 m_basePosition; + b3Vec3 m_dragStart; + + b3Quat m_baseQuat; + float m_rotateStart; + + bool m_dragging; + bool m_rotating; + bool m_showIndices; + bool m_useCache; + bool m_drawSimplex; +}; + +static int sampleShapeDistance = SampleManager::Register( "Collision", "Shape Distance", ShapeDistance::Create ); + +class TimeOfImpact : public Sample +{ +public: + enum ShapeType + { + e_box, + e_capsule, + e_triangle, + }; + + explicit TimeOfImpact( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( -90.0f, 0.0f, 10.0f, { 0.0f, 0.0f, 0.0f } ); + } + + m_box = b3MakeBoxHull( 0.02f, 0.2f, 0.04f ); + m_capsule = { { 0.0f, -0.2f, 0.0f }, { 0.0f, 0.2f, 0.0f }, 0.02f }; + m_triangle[0] = { -4.0f, 0.0f, -4.0f }; + m_triangle[1] = { -4.0f, 0.0f, -8.0f }; + m_triangle[2] = { -8.0f, 0.0f, -8.0f }; + + m_typeA = e_triangle; + m_typeB = e_capsule; + + m_proxyA = MakeProxy( m_typeA ); + m_proxyB = MakeProxy( m_typeB ); + + m_sweepA = {}; + m_sweepA.q1.s = 1.0f; + m_sweepA.q2.s = 1.0f; + + m_sweepB = {}; + m_sweepB.c1 = { -4.06512070, 0.101333618, -7.87591267 }; + m_sweepB.c2 = { -4.15895557, 0.0356027633, -7.69682646 }; + m_sweepB.q1 = { { -0.860495985, -0.272824734, 0.0724888667 }, 0.424097389 }; + m_sweepB.q2 = { { -0.604184389, -0.424355596, 0.0457959622 }, 0.672894001 }; + } + + b3ShapeProxy MakeProxy( ShapeType type ) + { + b3ShapeProxy proxy = {}; + + switch ( type ) + { + case e_capsule: + proxy.points = &m_capsule.center1; + proxy.radius = m_capsule.radius; + proxy.count = 2; + break; + + case e_triangle: + proxy.points = m_triangle; + proxy.count = 3; + break; + + case e_box: + proxy.points = b3GetHullPoints( &m_box.base ); + proxy.count = m_box.base.vertexCount; + break; + + default: + assert( false ); + } + + return proxy; + } + + void DrawShape( ShapeType type, b3Transform transform, b3HexColor color ) + { + switch ( type ) + { + case e_capsule: + { + DrawCapsule( m_scene, transform, m_capsule, color ); + b3Vec3 center = b3Lerp( m_capsule.center1, m_capsule.center2, 0.5f ); + center = b3TransformPoint( transform, center ); + b3Transform xf = { + .p = center, + .q = transform.q, + }; + DrawTransform( m_scene, xf, 0.025f ); + } + break; + + case e_triangle: + { + b3Vec3 p1 = b3TransformPoint( transform, m_triangle[0] ); + b3Vec3 p2 = b3TransformPoint( transform, m_triangle[1] ); + b3Vec3 p3 = b3TransformPoint( transform, m_triangle[2] ); + DrawLine( m_scene, p1, p2, color ); + DrawLine( m_scene, p2, p3, color ); + DrawLine( m_scene, p3, p1, color ); + DrawWorldString( m_camera, p1, b3_colorWhite, "0" ); + DrawWorldString( m_camera, p2, b3_colorWhite, "1" ); + DrawWorldString( m_camera, p3, b3_colorWhite, "2" ); + } + break; + + case e_box: + DrawHull( m_scene, transform, &m_box.base, color, false ); + break; + + default: + assert( false ); + } + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 16.0f * fontSize; + ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->m_height - height - 2.0f * fontSize ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 19.0f * fontSize, height ) ); + + ImGui::Begin( "Time of Impact", 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 ); + } + + shapeType = int( m_typeB ); + if ( ImGui::Combo( "shape B", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) ) + { + m_typeB = ShapeType( shapeType ); + m_proxyB = MakeProxy( m_typeB ); + } + + ImGui::Separator(); + + ImGui::End(); + } + + void Render() override + { + DrawTransform( m_scene, b3Transform_identity, 0.5f ); + Sample::Render(); + } + + void Step() override + { + b3TOIInput input = {}; + input.proxyA = m_proxyA; + input.proxyB = m_proxyB; + input.sweepA = m_sweepA; + input.sweepB = m_sweepB; + input.maxFraction = 1.0f; + + b3TOIOutput output = b3TimeOfImpact( &input ); + + DrawShape( m_typeA, b3Transform_identity, b3_colorCyan ); + + b3Transform transform1 = b3GetSweepTransform( &m_sweepB, 0.0f ); + b3Transform transform2 = b3GetSweepTransform( &m_sweepB, 1.0f ); + + // qr = inv(q1) * q2 + b3Quat qr = b3InvMulQuat( transform1.q, transform2.q ); + float angle; + (void)b3GetAxisAngle( &angle, qr ); + DrawTextLine( "angle = %g", 180.0f * angle / B3_PI ); + + DrawShape( m_typeB, transform1, b3_colorLightGreen ); + DrawShape( m_typeB, transform2, b3_colorLightCoral ); + + if ( output.fraction < 1.0f ) + { + b3Transform transformHit = b3GetSweepTransform( &m_sweepB, output.fraction ); + DrawShape( m_typeB, transformHit, b3_colorLightCyan ); + } + + if ( output.state == b3_toiStateHit || output.state == b3_toiStateFailed ) + { + DrawLine( m_scene, output.point, output.point + 0.5f * output.normal, b3_colorDimGray ); + DrawPoint( m_scene, output.point, 10.0f, b3_colorLightGreen ); + } + + switch ( output.state ) + { + case b3_toiStateUnknown: + DrawTextLine( "unknown" ); + break; + + case b3_toiStateFailed: + DrawTextLine( "failed" ); + break; + + case b3_toiStateOverlapped: + DrawTextLine( "overlapped" ); + break; + + case b3_toiStateHit: + DrawTextLine( "hit %g", output.fraction ); + break; + + case b3_toiStateSeparated: + DrawTextLine( "separated" ); + break; + + default: + assert( false ); + break; + } + + DrawTextLine( "iterations / push / root = %d / %d / %d", output.distanceIterations, output.pushBackIterations, + output.rootIterations ); + } + + static Sample* Create( SampleContext* context ) + { + return new TimeOfImpact( context ); + } + + b3BoxHull m_box; + b3Vec3 m_triangle[3]; + b3Capsule m_capsule; + + ShapeType m_typeA; + ShapeType m_typeB; + b3ShapeProxy m_proxyA; + b3ShapeProxy m_proxyB; + b3Sweep m_sweepA; + b3Sweep m_sweepB; +}; + +static int sampleTimeOfImpact = SampleManager::Register( "Collision", "Time of Impact", TimeOfImpact::Create ); + +class CapsuleCastRay : public Sample +{ +public: + static Sample* Create( SampleContext* context ) + { + return new CapsuleCastRay( context ); + } + + explicit CapsuleCastRay( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 120.0f, 30.0f, 20.0f, { 0.0f, 1.5f, 0.0f } ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_kinematicBody; + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + m_scale = 1.0f; + + // b3Capsule Capsule = { + // { 1.88094640f, 1.13457823f, 30.2966614f }, { -1.37514091f, -2.26233172f, 848.671997f }, 51.7184296f + // }; + + b3Capsule capsule = { + .center1 = { 0.0f, 0.0f, 0.0f }, + .center2 = { 0.0f, 1.0f, 0.0f }, + .radius = 0.5f, + }; + + m_offset = capsule.center1; + + b3CreateCapsuleShape( m_bodyId, &shapeDef, &capsule ); + } + + void Render() override + { + Sample::Render(); + + DrawGrid( m_scene, 10 ); + DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisX, b3_colorRed ); + DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisY, b3_colorGreen ); + DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisZ, b3_colorBlue ); + + b3BodyRayCastInput input; + input.origin = { -1.0f, 0.5f, 0.0f }; + input.translation = { 2.0f, 0.0f, 0.0f }; + input.filter = b3DefaultQueryFilter(); + input.maxFraction = 1.0f; + + b3BodyCastResult result = b3Body_CastRay( m_bodyId, &input, b3Transform_identity ); + + DrawLine( m_scene, input.origin, input.origin + input.translation, b3_colorGray ); + DrawPoint( m_scene, input.origin, 4.0f, b3_colorGreen ); + DrawPoint( m_scene, input.origin + input.translation, 4.0f, b3_colorRed ); + + if ( result.hit ) + { + DrawPoint( m_scene, result.point, 4.0f, b3_colorOrange ); + } + } + + b3BodyId m_bodyId; + b3Vec3 m_offset; + float m_scale; +}; + +static int sampleCapsuleCastRay = SampleManager::Register( "Collision", "Capsule Cast Ray", CapsuleCastRay::Create ); + +class Hull2D : public Sample +{ +public: + enum SourceMode + { + e_random = 0, + e_preset = 1, + }; + + static Sample* Create( SampleContext* context ) + { + return new Hull2D( context ); + } + + explicit Hull2D( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 0.0f, 20.0f, { 0.0f, 0.0f, 0.0f } ); + } + + m_sourceMode = e_preset; + m_inputCount = 0; + m_hullCount = 0; + m_simplifiedCount = 0; + m_targetCount = 6; + m_randomCount = 20; + m_simpleCull = true; + m_drawLabels = true; + + Generate(); + } + + void Generate() + { + if ( m_sourceMode == e_random ) + { + m_inputCount = m_randomCount; + for ( int i = 0; i < m_inputCount; ++i ) + { + m_inputPoints[i].p = { RandomFloatRange( -5.0f, 5.0f ), RandomFloatRange( -5.0f, 5.0f ) }; + m_inputPoints[i].separation = 0.0f; + m_inputPoints[i].originalIndex = (int16_t)i; + m_inputPoints[i].persisted = false; + } + } + else + { +#if 0 + b3Vec2 points[m_pointCapacity]; + int n = b3MinInt(15, m_pointCapacity); + float delta = 2.0f * B3_PI / (float)n; + // This makes a difference when comparing areas + //b3CosSin cs = b3ComputeCosSin( delta ); + b3CosSin cs = { + cosf( delta ), + sinf( delta ), + }; + ; + float x1 = 0.5f, y1 = 0.0f; + + for ( int i = 0; i < n; ++i ) + { + points[i] = {x1, y1}; + float x2 = cs.cosine * x1 - cs.sine * y1; + float y2 = cs.sine * x1 + cs.cosine * y1; + x1 = x2; + y1 = y2; + } + m_drawScale = 1.0f; +#else + b3Vec2 points[] = { + { 0.00000000, 0.00000000 }, { -0.00305632968, 5.54900616e-05 }, { -0.00305632968, 0.0246563386 }, + { -0.00305632968, 0.0246562902 }, { -0.00305632968, 0.0800221488 }, + }; + int n = sizeof( points ) / sizeof( b3Vec2 ); + m_drawScale = 50.0f; +#endif + + m_targetCount = b3MinInt( 6, n ); + m_inputCount = n; + + for ( int i = 0; i < m_inputCount; ++i ) + { + m_inputPoints[i].p = { points[i].x, points[i].y }; + m_inputPoints[i].separation = 0.0f; + m_inputPoints[i].originalIndex = (int16_t)i; + m_inputPoints[i].persisted = false; + } + } + } + + void ComputeHull() + { + // Copy input for hull computation because b3Hull2D may modify the array + + if ( m_simpleCull ) + { + for ( int i = 0; i < m_inputCount; ++i ) + { + m_hullPoints[i] = m_inputPoints[i]; + } + + m_hullCount = b3CullPoints( m_hullPoints, m_inputCount, m_targetCount ); + } + else + { + // Copy input for hull computation because b3Hull2D may modify the array + b3Point2D points[m_pointCapacity]; + for ( int i = 0; i < m_inputCount; ++i ) + { + points[i] = m_inputPoints[i]; + } + + m_hullCount = b3Hull2D( points, m_inputCount, m_hullPoints ); + + // Copy hull for simplification + for ( int i = 0; i < m_hullCount; ++i ) + { + m_simplifiedPoints[i] = m_hullPoints[i]; + } + + int target = m_targetCount < 3 ? 3 : m_targetCount; + m_simplifiedCount = b3SimplifyHull2D( m_simplifiedPoints, m_hullCount, target ); + } + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 16.0f * fontSize; + ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->m_height - height - 2.0f * fontSize ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 19.0f * fontSize, height ) ); + + ImGui::Begin( "Hull 2D", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + + const char* modes[] = { "Random", "Preset" }; + if ( ImGui::Combo( "Source", (int*)&m_sourceMode, modes, IM_ARRAYSIZE( modes ) ) ) + { + Generate(); + } + + if ( m_sourceMode == e_random ) + { + if ( ImGui::SliderInt( "Point Count", &m_randomCount, 4, m_pointCapacity ) ) + { + Generate(); + } + + if ( ImGui::Button( "Regenerate" ) ) + { + Generate(); + } + } + + ImGui::Checkbox( "Simple Cull", &m_simpleCull ); + ImGui::SliderInt( "Target Count", &m_targetCount, 1, m_inputCount ); + + ImGui::Checkbox( "Draw Labels", &m_drawLabels ); + + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + + DrawTextLine( "Hull 2D: input=%d, hull=%d, simplified=%d", m_inputCount, m_hullCount, m_simplifiedCount ); + + DrawTransform( m_scene, b3Transform_identity, 0.4f ); + + bool onHull[m_pointCapacity] = {}; + for ( int i = 0; i < m_hullCount; ++i ) + { + onHull[m_hullPoints[i].originalIndex] = true; + } + + float s = m_drawScale; + + // Draw input points (small gray) + for ( int i = 0; i < m_inputCount; ++i ) + { + if ( onHull[i] ) + { + continue; + } + + b3Vec3 p = { s * m_inputPoints[i].p.x, s * m_inputPoints[i].p.y, 0.0f }; + DrawPoint( m_scene, p, 4.0f, b3_colorGray ); + + if ( m_drawLabels ) + { + DrawWorldString( m_camera, p, b3_colorGray, " %d", i ); + } + } + + // Draw convex hull edges and vertices (cyan) + for ( int i = 0; i < m_hullCount; ++i ) + { + int next = ( i + 1 ) % m_hullCount; + b3Vec3 p1 = { s * m_hullPoints[i].p.x, s * m_hullPoints[i].p.y, 0.0f }; + b3Vec3 p2 = { s * m_hullPoints[next].p.x, s * m_hullPoints[next].p.y, 0.0f }; + DrawLine( m_scene, p1, p2, b3_colorCyan ); + DrawPoint( m_scene, p1, 6.0f, b3_colorCyan ); + + if ( m_drawLabels ) + { + DrawWorldString( m_camera, p1, b3_colorCyan, " %d : %d", m_hullPoints[i].originalIndex, i ); + } + } + + if ( m_simpleCull == false ) + { + // Draw simplified hull edges and vertices (yellow, slightly offset in z so visible) + for ( int i = 0; i < m_simplifiedCount; ++i ) + { + int next = ( i + 1 ) % m_simplifiedCount; + b3Vec3 p1 = { s * m_simplifiedPoints[i].p.x, s * m_simplifiedPoints[i].p.y, 0.01f }; + b3Vec3 p2 = { s * m_simplifiedPoints[next].p.x, s * m_simplifiedPoints[next].p.y, 0.01f }; + DrawLine( m_scene, p1, p2, b3_colorYellow ); + DrawPoint( m_scene, p1, 10.0f, b3_colorYellow ); + } + } + } + + void Step() override + { + ComputeHull(); + } + + static constexpr int m_pointCapacity = 128; + SourceMode m_sourceMode; + b3Point2D m_inputPoints[m_pointCapacity]; + b3Point2D m_hullPoints[2 * m_pointCapacity]; + b3Point2D m_simplifiedPoints[2 * m_pointCapacity]; + float m_drawScale; + int m_inputCount; + int m_hullCount; + int m_simplifiedCount; + int m_targetCount; + int m_randomCount; + bool m_simpleCull; + bool m_drawLabels; +}; + +static int sampleHull2D = SampleManager::Register( "Collision", "Hull 2D", Hull2D::Create ); diff --git a/samples/sample_compound.cpp b/samples/sample_compound.cpp new file mode 100644 index 0000000..67a263c --- /dev/null +++ b/samples/sample_compound.cpp @@ -0,0 +1,800 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "camera.h" +#include "human.h" +#include "mesh_loader.h" +#include "renderer.h" +#include "sample.h" +#include "scene.h" +#include "utils.h" + +#include "box3d/box3d.h" + +#include + +class SimpleCompound : public Sample +{ +public: + explicit SimpleCompound( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 45.0f, b3Vec3_zero ); + } + + { + float a = 4.0f; + b3Vec3 extents = { a, 0.125f * a, a }; + b3SurfaceMaterial material = b3DefaultSurfaceMaterial(); + b3BoxHull box = b3MakeBoxHull( extents.x, extents.y, extents.z ); + + b3Transform hullTransform; + hullTransform.p = { 1.0f, -0.125f * a, 0.0f }; + hullTransform.q = b3MakeQuatFromAxisAngle( b3Normalize({ 1.0f, 0.0f, 1.0f }), 0.0f * B3_PI ); + + b3CompoundHullDef hullDef = { + .hull = &box.base, + .transform = hullTransform, + .material = material, + }; + + b3CompoundDef def = {}; + def.hulls = &hullDef; + def.hullCount = 1; + + m_compound = b3CreateCompound( &def ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 2.0f, -1.0f, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( { 0.0f, 1.0f, 0.0f }, 0.25f * B3_PI ); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + (void)b3CreateCompoundShape( groundId, &shapeDef, m_compound ); + } + + b3World_SetContactRecycleDistance( m_worldId, 0.0f ); + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 2.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3Sphere sphere = { b3Vec3_zero, 0.25f }; + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + } + + //{ + // b3BodyDef bodyDef = b3DefaultBodyDef(); + // bodyDef.type = b3_dynamicBody; + // bodyDef.position = { 0.0f, 10.0f, 2.0f }; + // b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + // b3ShapeDef shapeDef = b3DefaultShapeDef(); + // b3BoxHull box = b3MakeBoxHull( 0.2f, 0.3f, 0.4f ); + // b3CreateHullShape( bodyId, &shapeDef, &box.base ); + //} + + m_launchSpeedScale = 1.0f; + } + + ~SimpleCompound() override + { + b3DestroyCompound( m_compound ); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 1.0f ); + + int height = b3DynamicTree_GetHeight( &m_compound->tree ); + DrawTextLine( "compound tree height = %d", height ); + } + + static Sample* Create( SampleContext* context ) + { + return new SimpleCompound( context ); + } + + b3Compound* m_compound; +}; + +static int sampleSimple = SampleManager::Register( "Compound", "Simple", SimpleCompound::Create ); + +class CompoundSpheres : public Sample +{ +public: + explicit CompoundSpheres( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 45.0f, b3Vec3_zero ); + } + + float h = 10.0f; + b3Vec3 lower = { -h, -h, -h }; + b3Vec3 upper = { h, h, h }; + b3CompoundSphereDef spheres[m_count]; + for ( int i = 0; i < m_count; ++i ) + { + spheres[i].sphere.center = RandomVec3( lower, upper ); + spheres[i].sphere.radius = RandomFloatRange( 0.01f * h, 0.05f * h ); + spheres[i].material = b3DefaultSurfaceMaterial(); + } + + b3CompoundDef def = {}; + def.spheres = spheres; + def.sphereCount = m_count; + + m_compound = b3CreateCompound( &def ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + (void)b3CreateCompoundShape( groundId, &shapeDef, m_compound ); + } + + ~CompoundSpheres() override + { + b3DestroyCompound( m_compound ); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 1.0f ); + + int height = b3DynamicTree_GetHeight( &m_compound->tree ); + DrawTextLine( "compound tree height = %d", height ); + } + + static Sample* Create( SampleContext* context ) + { + return new CompoundSpheres( context ); + } + + static constexpr int m_count = 20; + b3Compound* m_compound; +}; + +static int sampleCompoundSpheres = SampleManager::Register( "Compound", "Spheres", CompoundSpheres::Create ); + +class CompoundHulls : public Sample +{ +public: + explicit CompoundHulls( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 45.0f, b3Vec3_zero ); + } + + float h = 10.0f; + b3Vec3 lower = { -h, -h, -h }; + b3Vec3 upper = { h, h, h }; + b3SurfaceMaterial material = b3DefaultSurfaceMaterial(); + b3BoxHull boxHulls[m_count]; + b3CompoundHullDef hulls[m_count]; + for ( int i = 0; i < m_count; ++i ) + { + b3Vec3 extents = { + .x = RandomFloatRange( 0.01f * h, 0.05f * h ), + .y = RandomFloatRange( 0.01f * h, 0.05f * h ), + .z = RandomFloatRange( 0.01f * h, 0.05f * h ), + }; + + b3Transform transform; + transform.p = RandomVec3( lower, upper ); + transform.q = RandomQuat(); + + boxHulls[i] = b3MakeBoxHull( extents.x, extents.y, extents.z ); + hulls[i].hull = &boxHulls[i].base; + hulls[i].transform = transform; + hulls[i].material = material; + } + + b3CompoundDef def = {}; + def.hulls = hulls; + def.hullCount = m_count; + + m_compound = b3CreateCompound( &def ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + (void)b3CreateCompoundShape( groundId, &shapeDef, m_compound ); + } + + ~CompoundHulls() override + { + b3DestroyCompound( m_compound ); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 1.0f ); + + int height = b3DynamicTree_GetHeight( &m_compound->tree ); + DrawTextLine( "compound tree height = %d", height ); + } + + static Sample* Create( SampleContext* context ) + { + return new CompoundHulls( context ); + } + + static constexpr int m_count = 20; + b3Compound* m_compound; +}; + +static int sampleCompoundHulls = SampleManager::Register( "Compound", "Hulls", CompoundHulls::Create ); + +class TileFloor : public Sample +{ +public: + explicit TileFloor( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 45.0f, b3Vec3_zero ); + } + + { + constexpr int gridCount = 50; + constexpr int boxCount = gridCount * gridCount; + + float a = 4.0f; + b3Vec3 extents = { a, 0.5f * a, a }; + b3SurfaceMaterial material = b3DefaultSurfaceMaterial(); + b3BoxHull box = b3MakeBoxHull( extents.x, extents.y, extents.z ); + + // Must allocate to avoid stack overflow + b3CompoundHullDef* hulls = new b3CompoundHullDef[boxCount]; + b3Transform transform = b3Transform_identity; + + int index = 0; + for ( int i = 0; i < gridCount; ++i ) + { + transform.p.x = ( 2.0f * i - gridCount ) * a; + + for ( int j = 0; j < gridCount; ++j ) + { + transform.p.z = ( 2.0f * j - gridCount ) * a; + transform.p.y = RandomFloatRange( -0.5f, 0.25f ) * a; + + assert( index < boxCount ); + + hulls[index].hull = &box.base; + hulls[index].transform = transform; + hulls[index].material = material; + + index += 1; + } + } + + b3CompoundDef def = {}; + def.hulls = hulls; + def.hullCount = boxCount; + + m_compound = b3CreateCompound( &def ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { -2.0f, 1.0f, -3.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Normalize( { 1.0f, -1.0f, 0.5f } ), 0.0f ); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + (void)b3CreateCompoundShape( groundId, &shapeDef, m_compound ); + + delete[] hulls; + hulls = nullptr; + } + + //b3World_SetContactRecycleDistance( m_worldId, 0.0f ); + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 3.0f, 12.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3Sphere sphere = { b3Vec3_zero, 0.25f }; + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + } + +#if 0 + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 10.0f, 2.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull box = b3MakeBoxHull( 0.2f, 0.3f, 0.4f ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } +#endif + } + + ~TileFloor() override + { + b3DestroyCompound( m_compound ); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 1.0f ); + + DrawTextLine( "compound hull count = %d, mesh count = %d", m_compound->hullCount, m_compound->meshCount ); + DrawTextLine( "compound byte count = %d", m_compound->byteCount ); + + int treeBytes = b3DynamicTree_GetByteCount( &m_compound->tree ); + int height = b3DynamicTree_GetHeight( &m_compound->tree ); + DrawTextLine( "compound tree byte count = %d, height = %d", treeBytes, height ); + } + + static Sample* Create( SampleContext* context ) + { + return new TileFloor( context ); + } + + b3Compound* m_compound; +}; + +static int sampleTileFloor = SampleManager::Register( "Compound", "Tile Floor", TileFloor::Create ); + +class MeshTile : public Sample +{ +public: + explicit MeshTile( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 45.0f, b3Vec3_zero ); + } + + { + constexpr int gridCount = 2; + constexpr int boxCount = gridCount * gridCount; + + float a = 4.0f; + b3Vec3 extents = { a, 0.5f * a, a }; + b3SurfaceMaterial material = b3DefaultSurfaceMaterial(); + + b3MeshData* box = b3CreateBoxMesh( { 0.0f, 0.0f, 0.0f }, extents, true ); + b3CompoundMeshDef* meshes = new b3CompoundMeshDef[boxCount]; + b3Transform transform = b3Transform_identity; + transform.p.y = -0.5f * a; + + int index = 0; + for ( int i = 0; i < gridCount; ++i ) + { + transform.p.x = ( 2.0f * i - gridCount ) * a; + + for ( int j = 0; j < gridCount; ++j ) + { + transform.p.z = ( 2.0f * j - gridCount ) * a; + + transform.p.y = RandomFloatRange( -0.5f, 0.25f ) * a; + + assert( index < boxCount ); + + meshes[index].meshData = box; + meshes[index].transform = transform; + meshes[index].scale = { 1.0f, 1.0f, 1.0f }; + meshes[index].materials = &material; + meshes[index].materialCount = 1; + + index += 1; + } + } + + b3CompoundDef def = {}; + def.meshes = meshes; + def.meshCount = boxCount; + + m_compound = b3CreateCompound( &def ); + delete[] meshes; + b3DestroyMesh( box ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + (void)b3CreateCompoundShape( groundId, &shapeDef, m_compound ); + } + +#if 0 + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 3.0f, 12.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3Sphere sphere = { b3Vec3_zero, 0.25f }; + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + } +#endif + //{ + // b3BodyDef bodyDef = b3DefaultBodyDef(); + // bodyDef.type = b3_dynamicBody; + // bodyDef.position = { 0.0f, 10.0f, 2.0f }; + // b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + // b3ShapeDef shapeDef = b3DefaultShapeDef(); + // b3BoxHull box = b3MakeBoxHull( 0.2f, 0.3f, 0.4f ); + // b3CreateHullShape( bodyId, &shapeDef, &box.base ); + //} + } + + ~MeshTile() override + { + b3DestroyCompound( m_compound ); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 1.0f ); + + DrawTextLine( "compound instance count = %d, byte count = %d", m_compound->meshCount, m_compound->byteCount ); + + int treeBytes = b3DynamicTree_GetByteCount( &m_compound->tree ); + int height = b3DynamicTree_GetHeight( &m_compound->tree ); + DrawTextLine( "compound tree byte count = %d, height = %d", treeBytes, height ); + } + + static Sample* Create( SampleContext* context ) + { + return new MeshTile( context ); + } + + b3Compound* m_compound; +}; + +static int sampleCompoundMesh = SampleManager::Register( "Compound", "Mesh Tile", MeshTile::Create ); + +static bool OverlapResultFcn( b3ShapeId shapeId, void* context ) +{ + (void)shapeId; + bool* overlap = (bool*)context; + *overlap = true; + return false; +} + +class Village : public Sample +{ +public: + explicit Village( SampleContext* context ) + : Sample( context ) + { + constexpr int gridCount = m_isDebug ? 8 : 200; + constexpr float a = 4.0f; + m_worldWidth = 2.0f * gridCount * a; + + b3Vec3 position = { 0.0f, 10.0f, 0.0f }; + if ( m_context->restart == false ) + { + m_camera->SetView( 45.0f, 10.0f, 5.0f, position ); + } + + m_launchSpeedScale = 1.0f; + m_mover.Initialize( this, position ); + + { + constexpr int capsuleCapacity = gridCount * gridCount / 8 + 1; + constexpr int hullCount = gridCount * gridCount; + constexpr int sphereCapacity = gridCount * gridCount / 8 + 1; + + b3Vec3 extents = { a, 0.5f * a, a }; + b3SurfaceMaterial material = b3DefaultSurfaceMaterial(); + b3BoxHull box = b3MakeBoxHull( extents.x, extents.y, extents.z ); + + // Must allocate to avoid stack overflow + b3CompoundCapsuleDef* capsules = new b3CompoundCapsuleDef[capsuleCapacity]; + b3CompoundHullDef* hulls = new b3CompoundHullDef[hullCount]; + b3CompoundSphereDef* spheres = new b3CompoundSphereDef[sphereCapacity]; + + b3Transform transform = b3Transform_identity; + + int capsuleIndex = 0; + int hullIndex = 0; + int sphereIndex = 0; + + for ( int i = 0; i < gridCount; ++i ) + { + transform.p.x = ( 2.0f * i - gridCount ) * a; + + for ( int j = 0; j < gridCount; ++j ) + { + transform.p.z = ( 2.0f * j - gridCount ) * a; + transform.p.y = RandomFloatRange( -0.25f, 0.125f ) * a; + + assert( hullIndex < hullCount ); + + if ( ( i & 1 ) && ( j & 1 ) ) + { + b3Vec3 p1 = transform.p + RandomVec3( { -a, a, -a }, { a, 2.0f * a, a } ); + b3Vec3 p2 = transform.p + RandomVec3( { -a, a, -a }, { a, 2.0f * a, a } ); + float radius = RandomFloatRange( 0.1f, 0.5f ); + + if ( capsuleIndex < sphereIndex ) + { + assert( capsuleIndex < capsuleCapacity ); + capsules[capsuleIndex].capsule = { p1, p2, radius }; + capsules[capsuleIndex].material = material; + capsuleIndex += 1; + } + else + { + assert( sphereIndex < capsuleCapacity ); + spheres[sphereIndex].sphere = { p1, radius }; + spheres[sphereIndex].material = material; + sphereIndex += 1; + } + } + + hulls[hullIndex].hull = &box.base; + hulls[hullIndex].transform = transform; + hulls[hullIndex].material = material; + + hullIndex += 1; + } + } + + assert( capsuleIndex <= capsuleCapacity ); + assert( hullIndex == hullCount ); + assert( sphereIndex <= sphereCapacity ); + + constexpr int meshGridCount = gridCount / 4; + constexpr int meshCount = meshGridCount * meshGridCount; + constexpr float b = 4.0f * a; + constexpr int materialCapacity = 5; + + b3SurfaceMaterial meshMaterials[materialCapacity]; + b3MeshData* buildingMesh = CreateMeshData( "data/meshes/building.obj", 1.0f, false, false, true, true ); + + int materialCount = buildingMesh->materialCount; + assert( materialCount <= materialCapacity ); + + for ( int i = 0; i < materialCount; ++i ) + { + meshMaterials[i] = b3DefaultSurfaceMaterial(); + if ( i == 0 ) + { + meshMaterials[i].friction = 0.0f; + } + else if ( i == 1 ) + { + meshMaterials[i].restitution = 0.5f; + } + meshMaterials[i].userMaterialId = i + 42; + } + + b3CompoundMeshDef* meshes = new b3CompoundMeshDef[meshCount]; + transform = b3Transform_identity; + + int meshIndex = 0; + for ( int i = 0; i < meshGridCount; ++i ) + { + transform.p.x = ( 2.0f * i - meshGridCount ) * b + 0.5f * b; + + for ( int j = 0; j < meshGridCount; ++j ) + { + transform.p.y = 0.5f * a; + transform.p.z = ( 2.0f * j - meshGridCount ) * b + 0.5f * b; + transform.q = b3MakeQuatFromAxisAngle( { 0.0f, 1.0f, 0.0 }, RandomFloatRange( -B3_PI, B3_PI ) ); + + assert( meshIndex < meshCount ); + + meshes[meshIndex].meshData = buildingMesh; + meshes[meshIndex].transform = transform; + meshes[meshIndex].scale = RandomVec3( { 0.5f, 0.5f, 0.5f }, { 2.0f, 2.0f, 2.0f } ); + + if ( meshIndex & 1 ) + { + meshes[meshIndex].scale.x = -meshes[meshIndex].scale.x; + } + + if ( meshIndex & 3 ) + { + meshes[meshIndex].scale.z = -meshes[meshIndex].scale.z; + } + + meshes[meshIndex].materials = meshMaterials; + meshes[meshIndex].materialCount = materialCount; + + meshIndex += 1; + } + } + + assert( meshIndex == meshCount ); + + b3CompoundDef def = {}; + def.capsules = capsules; + def.capsuleCount = capsuleIndex; + def.hullCount = hullCount; + def.hulls = hulls; + def.hullCount = hullCount; + def.meshes = meshes; + def.meshCount = meshCount; + def.spheres = spheres; + def.sphereCount = sphereIndex; + + m_compound = b3CreateCompound( &def ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { -1.0f, -0.5f, 2.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( {0.0f, 1.0f, 0.0f}, -1.15f * B3_PI ); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + (void)b3CreateCompoundShape( groundId, &shapeDef, m_compound ); + + delete[] capsules; + capsules = nullptr; + + delete[] hulls; + hulls = nullptr; + + delete[] meshes; + meshes = nullptr; + + delete[] spheres; + spheres = nullptr; + + b3DestroyMesh( buildingMesh ); + } + + m_rayOrigin = { -0.45f * m_worldWidth, 20.0f, -0.45f * m_worldWidth }; + } + + ~Village() override + { + b3DestroyCompound( m_compound ); + } + + void Keyboard( int key, int action, int mods ) override + { + if ( key == 'T' && action == 1 ) + { + ToggleThirdPerson(); + } + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 4.0f ); + + DrawTextLine( "surface type = %d", m_userMaterialId ); + DrawTextLine( "compound capsules/hulls/meshes/sphere = %d / %d / %d / %d", m_compound->capsuleCount, + m_compound->hullCount, m_compound->meshCount, m_compound->sphereCount ); + DrawTextLine( "compound byte count = %d", m_compound->byteCount ); + + int treeBytes = b3DynamicTree_GetByteCount( &m_compound->tree ); + int height = b3DynamicTree_GetHeight( &m_compound->tree ); + DrawTextLine( "compound tree byte count = %d, height = %d", treeBytes, height ); + } + + void Step() override + { + m_mover.Step( nullptr, 0, true ); + DrawTextLine( "third person (T) = %d", m_camera->m_thirdPerson ); + + b3Vec3 translation = { 10.0f, -40.0f, -5.0f }; + b3QueryFilter filter = b3DefaultQueryFilter(); + + { + CastClosestContext context = {}; + (void)b3World_CastRay( m_worldId, m_rayOrigin, translation, filter, CastClosestCallback, &context ); + + DrawLine( m_scene, m_rayOrigin, m_rayOrigin + translation, b3_colorAliceBlue ); + if ( context.hit ) + { + b3Vec3 p1 = context.point; + b3Vec3 p2 = b3MulAdd( p1, 0.5f, context.normal ); + DrawLine( m_scene, p1, p2, b3_colorYellow ); + DrawPoint( m_scene, p1, 8.0f, b3_colorLightCoral ); + DrawTextLine( "ray hit triangle/child/material = %d / %d / %d", context.triangleIndex, context.childIndex, + context.materialId ); + } + else + { + DrawTextLine( "ray miss" ); + } + } + + { + CastClosestContext context = {}; + b3Vec3 origin = b3Sub( m_rayOrigin, { 1.0f, 0.0f, 1.0f } ); + b3ShapeProxy proxy = { &origin, 1, 0.25f }; + b3World_CastShape( m_worldId, &proxy, translation, filter, CastClosestCallback, &context ); + + DrawLine( m_scene, origin, origin + translation, b3_colorAliceBlue ); + if ( context.hit ) + { + b3Vec3 position = b3MulAdd( origin, context.fraction, translation ); + b3Vec3 p1 = context.point; + b3Vec3 p2 = b3MulAdd( p1, 0.5f, context.normal ); + DrawLine( m_scene, p1, p2, b3_colorYellow ); + DrawPoint( m_scene, p1, 8.0f, b3_colorLightCoral ); + b3Sphere sphere = { position, 0.25f }; + DrawSphere( m_scene, b3Transform_identity, sphere, b3_colorOrchid ); + DrawTextLine( "shape hit triangle/child/material = %d / %d / %d", context.triangleIndex, context.childIndex, + context.materialId ); + } + else + { + DrawTextLine( "shape miss" ); + } + } + + { + bool overlap = false; + b3Vec3 origin = { m_rayOrigin.x - 1.0f, 2.0f, m_rayOrigin.z - 1.0f }; + b3ShapeProxy proxy = { &origin, 1, 0.3f }; + b3World_OverlapShape( m_worldId, &proxy, filter, OverlapResultFcn, &overlap ); + + b3HexColor color = overlap ? b3_colorDarkMagenta : b3_colorDarkSeaGreen; + b3Sphere sphere = { origin, 0.3f }; + DrawSphere( m_scene, b3Transform_identity, sphere, color ); + } + + if ( m_rayOrigin.x > 0.45f * m_worldWidth ) + { + m_rayOrigin.x = -0.45f * m_worldWidth; + m_rayOrigin.z += 8.0f; + } + + if ( m_rayOrigin.z > 0.45f * m_worldWidth ) + { + m_rayOrigin.z = -0.45f * m_worldWidth; + } + + float timeStep = 0.0f; + if ( m_context->pause == false || m_context->singleStep > 0 ) + { + timeStep = m_context->hertz > 0.0f ? 1.0f / m_context->hertz : 0.0f; + } + + m_rayOrigin.x += 2.0f * timeStep; + + Sample::Step(); + } + + static Sample* Create( SampleContext* context ) + { + return new Village( context ); + } + + b3Compound* m_compound; + CharacterMover m_mover; + float m_worldWidth; + b3Vec3 m_rayOrigin; +}; + +static int sampleVillage = SampleManager::Register( "Compound", "Village", Village::Create ); diff --git a/samples/sample_continuous.cpp b/samples/sample_continuous.cpp new file mode 100644 index 0000000..81a11e2 --- /dev/null +++ b/samples/sample_continuous.cpp @@ -0,0 +1,1040 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "GLFW/glfw3.h" +#include "camera.h" +#include "imgui.h" +#include "renderer.h" +#include "sample.h" +#include "scene.h" +#include "stability.h" +#include "utils.h" + +#include "box3d/box3d.h" + +#include +#include + +class ThinWall : public Sample +{ +public: + explicit ThinWall( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 30.0f, b3Vec3_zero ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 50.0f ); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + + bodyDef.position = { 0.0f, 10.0f, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisX, 90.0f * B3_DEG_TO_RAD ); + b3BodyId wallId = b3CreateBody( m_worldId, &bodyDef ); + b3BoxHull wallBox = b3MakeBoxHull( 10.0f, 0.1f, 10.0f ); + b3CreateHullShape( wallId, &shapeDef, &wallBox.base ); + + bodyDef.type = b3_dynamicBody; + bodyDef.rotation = b3Quat_identity; + shapeDef.baseMaterial.rollingResistance = 0.1f; + + bodyDef.position = { -5.0, 10.0f, 20.0f }; + bodyDef.linearVelocity = { 0.0f, 0.0, -180.0f }; + bodyDef.angularVelocity = { 20.0f, 0.0f, 0.0f }; + b3BodyId sphereBodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3Sphere sphere = { b3Vec3_zero, 0.1f }; + b3CreateSphereShape( sphereBodyId, &shapeDef, &sphere ); + + bodyDef.position = { 0.0, 10.0f, 20.0f }; + bodyDef.linearVelocity = { 0.0f, 0.0, -180.0f }; + bodyDef.angularVelocity = { 20.0f, -5.0f, 0.0f }; + b3BodyId capsuleBodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3Capsule capsule = { { -0.3f, 0.0f, 0.0f }, { 0.3f, 0.0f, 0.0f }, 0.1f }; + b3CreateCapsuleShape( capsuleBodyId, &shapeDef, &capsule ); + + bodyDef.position = { 5.0, 10.0f, 20.0f }; + bodyDef.linearVelocity = { 0.0f, 0.0, -180.0f }; + bodyDef.angularVelocity = { 20.0f, 5.0f, 0.0f }; + b3BodyId boxBodyId = b3CreateBody( m_worldId, &bodyDef ); + b3BoxHull box = b3MakeBoxHull( 0.4f, 0.1f, 0.1f ); + b3CreateHullShape( boxBodyId, &shapeDef, &box.base ); + } + + static Sample* Create( SampleContext* context ) + { + return new ThinWall( context ); + } +}; + +static int sampleThinWall = SampleManager::Register( "Continuous", "Thin Wall", ThinWall::Create ); + +class BounceHouse : public Sample +{ +public: + explicit BounceHouse( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 45.0f, 50.0f, b3Vec3_zero ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundBodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull groundBox = b3MakeBoxHull( 10.0f, 1.0f, 10.0f ); + b3CreateHullShape( groundBodyId, &shapeDef, &groundBox.base ); + + { + b3Transform transform = { { 10.0f, 5.0f, 0.0f }, b3Quat_identity }; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, 5.0f, 10.0f, transform ); + b3CreateHullShape( groundBodyId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform = { { -10.0f, 5.0f, 0.0f }, b3Quat_identity }; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, 5.0f, 10.0f, transform ); + b3CreateHullShape( groundBodyId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform = { { 0.0f, 5.0f, -10.0f }, b3Quat_identity }; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 10.0f, 5.0f, 0.1f, transform ); + b3CreateHullShape( groundBodyId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform = { { 0.0f, 5.0f, 10.0f }, b3Quat_identity }; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 10.0f, 5.0f, 0.1f, transform ); + b3CreateHullShape( groundBodyId, &shapeDef, &wallBox.base ); + } + + bodyDef.type = b3_dynamicBody; + bodyDef.gravityScale = 0.0f; + bodyDef.position = { -8.0, 4.0f, 0.0f }; + bodyDef.linearVelocity = { 120.0f, 0.0, 120.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3Sphere sphere = { b3Vec3_zero, 0.5f }; + shapeDef.baseMaterial.friction = 0.0f; + shapeDef.baseMaterial.restitution = 1.0f; + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + + // This mesh tries to collide with the hulls. Not a good setup. + m_dummyMesh = b3CreateBoxMesh( b3Vec3_zero, { 0.8f, 0.4f, 0.4f }, true ); + // b3CreateMeshShape( bodyId, &shapeDef, m_dummyMesh, b3Vec3_one ); + } + + ~BounceHouse() override + { + b3DestroyMesh( m_dummyMesh ); + } + + static Sample* Create( SampleContext* context ) + { + return new BounceHouse( context ); + } + + b3MeshData* m_dummyMesh; +}; + +static int sampleBounceHouse = SampleManager::Register( "Continuous", "Bounce House", BounceHouse::Create ); + +class SpinningStick : public Sample +{ +public: + explicit SpinningStick( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 25.0f, 50.0f, { 0.0f, 2.0f, 0.0f } ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + bodyDef.position = { 0.0f, -0.1f, 0.0f }; + b3BodyId groundBodyId = b3CreateBody( m_worldId, &bodyDef ); + b3BoxHull groundBox = b3MakeBoxHull( 10.0f, 0.1f, 10.0f ); + b3CreateHullShape( groundBodyId, &shapeDef, &groundBox.base ); + + bodyDef.position = { 0.0f, 0.5f, 0.0f }; + b3BodyId wallBodyId = b3CreateBody( m_worldId, &bodyDef ); + b3BoxHull wallBox = b3MakeBoxHull( 0.125f, 0.5f, 10.0f ); + b3CreateHullShape( wallBodyId, &shapeDef, &wallBox.base ); + + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 20.0f, 0.5f }; + bodyDef.linearVelocity = { 0.0f, -100.0f, 0.0f }; + b3Vec3 range = { 50.0f, 50.0f, 50.0f }; + b3Vec3 omega = RandomVec3( -range, range ); + bodyDef.angularVelocity = omega; + printf( "%f, %f, %f\n", omega.x, omega.y, omega.z ); + b3BodyId stickBodyId = b3CreateBody( m_worldId, &bodyDef ); + b3BoxHull stickBox = b3MakeBoxHull( 2.0f, 0.1f, 0.1f ); + shapeDef.baseMaterial.rollingResistance = 0.1f; + b3CreateHullShape( stickBodyId, &shapeDef, &stickBox.base ); + } + + static Sample* Create( SampleContext* context ) + { + return new SpinningStick( context ); + } +}; + +static int sampleSpinningStick = SampleManager::Register( "Continuous", "Spinning Stick", SpinningStick::Create ); + +// This tests bullets and chain reactions +class BulletVersusStack : public Sample +{ +public: + static Sample* Create( SampleContext* context ) + { + return new BulletVersusStack( context ); + } + + explicit BulletVersusStack( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( -7.5f, 20.0f, 30.0f, { 0.0f, 2.0f, 0.0f } ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundBodyId = b3CreateBody( m_worldId, &bodyDef ); + b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 50.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundBodyId, &shapeDef, &groundBox.base ); + + b3Transform transform = { { 1.0f, 5.0f, 0.0f }, b3Quat_identity }; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, 5.0f, 10.0f, transform ); + b3CreateHullShape( groundBodyId, &shapeDef, &wallBox.base ); + } + + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + for ( int row = 0; row < 10; ++row ) + { + bodyDef.position = { 0.0f, 0.5f + 1.1f * row, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + + m_bulletId = b3_nullBodyId; + } + + void Render() override + { + Sample::Render(); + DrawTransform( m_scene, { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }, 1.0f ); + } + + void Launch() + { + if ( B3_IS_NON_NULL( m_bulletId ) ) + { + b3DestroyBody( m_bulletId ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.isBullet = true; + bodyDef.position = { -20.5f, 5.5f, 0.0f }; + bodyDef.linearVelocity = { 500.0f, 0.0f, 0.0f }; + m_bulletId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density *= 10.0f; + b3Sphere sphere = { b3Vec3_zero, 0.25f }; + b3CreateSphereShape( m_bulletId, &shapeDef, &sphere ); + } + + void Keyboard( int key, int action, int mods ) override + { + if ( key == 'L' ) + { + Launch(); + } + } + + void UpdateUI() override + { + float height = 80.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 150.0f, height ) ); + + ImGui::Begin( "Bullet vs Stack", nullptr, ImGuiWindowFlags_NoResize ); + + ImGui::PushItemWidth( 200.0f ); + + if ( ImGui::Button( "Launch" ) ) + { + Launch(); + } + + ImGui::PopItemWidth(); + + ImGui::End(); + } + + b3BodyId m_bulletId; +}; + +static int sampleContinuous6 = SampleManager::Register( "Continuous", "Bullet vs Stack", BulletVersusStack::Create ); + +class NeedleMesh : public Sample +{ +public: + explicit NeedleMesh( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 25.0f, 4.0f, { 0.0f, 1.2f, 0.0f } ); + } + + int slices = 8; + m_needle1 = CreateNeedle( 0.99f, 0.1f, { 0.2f, 0.0f, 0.2f }, slices ); + m_needle2 = CreateNeedle( 1.01f, 0.1f, { 0.2f, 0.0f, -0.2f }, slices ); + m_needle3 = CreateNeedle( 0.98f, 0.1f, { -0.2f, 0.0f, -0.2f }, slices ); + m_needle4 = CreateNeedle( 1.02f, 0.1f, { -0.2f, 0.0f, 0.2f }, slices ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundBodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateMeshShape( groundBodyId, &shapeDef, m_needle1, b3Vec3_one ); + b3CreateMeshShape( groundBodyId, &shapeDef, m_needle2, b3Vec3_one ); + b3CreateMeshShape( groundBodyId, &shapeDef, m_needle3, b3Vec3_one ); + b3CreateMeshShape( groundBodyId, &shapeDef, m_needle4, b3Vec3_one ); + + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 5.0f, 0.0f }; + bodyDef.linearVelocity = { 0.0f, -10.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull box = b3MakeBoxHull( 0.3f, 0.01f, 0.3f ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + + ~NeedleMesh() override + { + b3DestroyMesh( m_needle4 ); + b3DestroyMesh( m_needle3 ); + b3DestroyMesh( m_needle2 ); + b3DestroyMesh( m_needle1 ); + } + + void Render() override + { + DrawGrid( m_scene, 10 ); + Sample::Render(); + } + + b3MeshData* CreateNeedle( float height, float radius, b3Vec3 center, int slices ) const + { + // Vertices + int vertexCount = slices + 1; + b3Vec3* vertices = (b3Vec3*)malloc( vertexCount * sizeof( b3Vec3 ) ); + B3_ASSERT( vertices ); + + float alpha = 0.0f; + float deltaAlpha = 2.0f * B3_PI / slices; + + vertices[0] = b3Vec3{ 0.0f, height, 0.0f } + center; + for ( int index = 1; index < vertexCount; ++index ) + { + b3CosSin cs = b3ComputeCosSin( alpha ); + vertices[index] = b3Vec3{ radius * cs.cosine, 0.0f, radius * cs.sine } + center; + alpha += deltaAlpha; + } + + // Indices + int triangleCount = slices; + int* indexBase = (int*)malloc( 3 * triangleCount * sizeof( int ) ); + B3_ASSERT( indexBase ); + + int index1 = vertexCount - 1; + for ( int index = 0; index < triangleCount; ++index ) + { + int index2 = index + 1; + indexBase[3 * index + 0] = 0; + indexBase[3 * index + 1] = index2; + indexBase[3 * index + 2] = index1; + index1 = index2; + } + + b3MeshDef def = {}; + def.vertexCount = vertexCount; + def.vertices = vertices; + def.triangleCount = triangleCount; + def.indices = indexBase; + def.useMedianSplit = true; + + b3MeshData* data = b3CreateMesh( &def, nullptr, 0 ); + + free( vertices ); + free( indexBase ); + + return data; + } + + static Sample* Create( SampleContext* context ) + { + return new NeedleMesh( context ); + } + + b3MeshData* m_needle1; + b3MeshData* m_needle2; + b3MeshData* m_needle3; + b3MeshData* m_needle4; + b3Hull* mConvex; +}; + +static int sampleNeedleMesh = SampleManager::Register( "Continuous", "Needle Mesh", NeedleMesh::Create ); + +struct IndexPair +{ + int index1; + int index2; +}; + +static inline IndexPair ConvertToPair( void* userData ) +{ + static_assert( sizeof( intptr_t ) >= 8 && sizeof( int ) == 4 ); + intptr_t value = (intptr_t)userData; + int index1 = (int)value; + int index2 = (int)( value >> 32 ); + return { index1, index2 }; +} + +static inline void* ConvertToUserData( IndexPair pair ) +{ + intptr_t value = (intptr_t)pair.index2 << 32 | (intptr_t)pair.index1; + return (void*)value; +} + +class MeshDrop : public Sample +{ +public: + enum ShapeType + { + e_box, + e_capsule, + e_cylinder, + e_sphere, + }; + + explicit MeshDrop( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 30.0f, 20.0f, b3Vec3_zero ); + m_context->debugDraw.forceScale = 0.1f; + } + + m_groundId = b3_nullBodyId; + m_groundMesh = nullptr; + m_groundAmplitude = 0.5f; + CreateGround(); + + m_bodies = new b3BodyId[m_bodyCount]; + memset( m_bodies, 0, m_bodyCount * sizeof( b3BodyId ) ); + + m_cylinder = b3CreateCylinder( 0.4f, 0.05f, 0.0f, 6 ); + m_shapeType = e_box; + m_runCount = 0; + m_failure = false; + m_autoGenerate = false; + + m_stepWhilePaused = true; + + Generate(); + } + + ~MeshDrop() override + { + delete[] m_bodies; + b3DestroyHull( m_cylinder ); + b3DestroyMesh( m_groundMesh ); + } + + void CreateGround() + { + if ( B3_IS_NON_NULL( m_groundId ) ) + { + b3DestroyBody( m_groundId ); + m_groundId = b3_nullBodyId; + } + + if ( m_groundMesh != nullptr ) + { + b3DestroyMesh( m_groundMesh ); + m_groundMesh = nullptr; + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + m_groundId = b3CreateBody( m_worldId, &bodyDef ); + + int gridCount = 40; + float cellWidth = 1.0f; + float rowHz = 0.1f; + float columnHz = 0.2f; + + m_groundMesh = b3CreateWaveMesh( gridCount, gridCount, cellWidth, m_groundAmplitude, rowHz, columnHz ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.filter.categoryBits = 1; + b3CreateMeshShape( m_groundId, &shapeDef, m_groundMesh, b3Vec3_one ); + + float extent = 0.5f * gridCount * cellWidth; + float halfHeight = 1.0f; + + { + b3Transform transform; + transform.p = { 0.0f, halfHeight, -extent }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( extent, halfHeight, 0.1f, transform ); + shapeDef.name = "wall1"; + b3CreateHullShape( m_groundId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform; + transform.p = { 0.0f, halfHeight, extent }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( extent, halfHeight, 0.1f, transform ); + shapeDef.name = "wall2"; + b3CreateHullShape( m_groundId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform; + transform.p = { -extent, halfHeight, 0.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, halfHeight, extent, transform ); + shapeDef.name = "wall3"; + b3CreateHullShape( m_groundId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform; + transform.p = { extent, halfHeight, 0.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, halfHeight, extent, transform ); + shapeDef.name = "wall4"; + b3CreateHullShape( m_groundId, &shapeDef, &wallBox.base ); + } + } + + void Generate() + { + for ( int i = 0; i < m_bodyCount; ++i ) + { + if ( B3_IS_NULL( m_bodies[i] ) ) + { + continue; + } + + b3DestroyBody( m_bodies[i] ); + m_bodies[i] = b3_nullBodyId; + } + + // The soft contact solver cannot always resolve this small shape at 4 sub-steps. + // Also this small shape has trouble moving advancing in the time of impact code + // because the size is very close to the tolerances used. + // b3BoxHull box = b3MakeBoxHull( 0.01f, 0.1f, 0.02f ); + b3BoxHull box = b3MakeBoxHull( 0.02f, 0.2f, 0.04f ); + b3Capsule capsule = { { 0.0f, -0.2f, 0.0f }, { 0.0f, 0.2f, 0.0f }, 0.05f }; + b3Sphere sphere = { b3Vec3_zero, 0.05f }; + + int bodyIndex = 0; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.rollingResistance = 0.1f; + + // Don't allow shapes to collide with each other. This + // makes isolating failures easier. + shapeDef.filter.categoryBits = 2; + shapeDef.filter.maskBits = 1; + + g_randomSeed = (uint32_t)b3GetTicks(); + + bool simulateAll = true; + // g_randomSeed = 3963634789; + + m_runCount += 1; + m_stepCount = 0; + printf( "run %d seed %u\n", m_runCount, g_randomSeed ); + + for ( int i = 0; i < m_gridCount; ++i ) + { + for ( int j = 0; j < m_gridCount; ++j ) + { + b3Vec3 linearVelocity = RandomVec3Uniform( -1.0f, 1.0f ); + b3Vec3 angularVelocity = RandomVec3Uniform( -5.0f, 5.0f ); + + if ( simulateAll || ( i == 5 && j == 4 ) ) + { + bodyDef.position = { 0.5f * ( i - 0.5f * m_gridCount ), 5.0f, 0.5f * ( j - 0.5f * m_gridCount ) }; + bodyDef.linearVelocity = linearVelocity; + bodyDef.angularVelocity = angularVelocity; + // bodyDef.angularDamping = 0.1f; + bodyDef.userData = ConvertToUserData( { i, j } ); + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + if ( m_shapeType == e_box ) + { + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + else if ( m_shapeType == e_capsule ) + { + b3CreateCapsuleShape( bodyId, &shapeDef, &capsule ); + } + else if ( m_shapeType == e_cylinder ) + { + b3CreateHullShape( bodyId, &shapeDef, m_cylinder ); + } + else + { + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + } + + m_bodies[bodyIndex] = bodyId; + } + else + { + m_bodies[bodyIndex] = b3_nullBodyId; + } + bodyIndex += 1; + } + } + + assert( bodyIndex == m_bodyCount ); + } + + void UpdateUI() override + { + Sample::UpdateUI(); + + float fontSize = ImGui::GetFontSize(); + float height = 9.0f * fontSize; + ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->m_height - height - 2.0f * fontSize ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 19.0f * fontSize, height ) ); + + ImGui::Begin( "Mesh Drop", nullptr, ImGuiWindowFlags_NoResize ); + + const char* shapeTypes[] = { "box", "capsule", "cylinder", "sphere" }; + int shapeType = (int)m_shapeType; + if ( ImGui::Combo( "Type", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) ) + { + m_stepCount = 0; + m_shapeType = ShapeType( shapeType ); + Generate(); + } + + if ( ImGui::SliderFloat( "Amplitude", &m_groundAmplitude, 0.0f, 1.0f ) ) + { + CreateGround(); + Generate(); + } + + if ( ImGui::Button( "Generate" ) ) + { + Generate(); + } + + if ( ImGui::Button( "Auto Generate" ) ) + { + m_autoGenerate = !m_autoGenerate; + m_stepCount = 0; + } + + ImGui::End(); + } + + void Step() override + { + Sample::Step(); + + { + double screenX, screenY; + glfwGetCursorPos( m_window, &screenX, &screenY ); + PickRay pickRay = m_camera->BuildPickRay( (float)screenX, (float)screenY ); + + b3RayResult result = b3World_CastRayClosest( m_worldId, pickRay.origin, pickRay.translation, b3DefaultQueryFilter() ); + + if ( result.hit ) + { + b3BodyId bodyId = b3Shape_GetBody( result.shapeId ); + void* userData = b3Body_GetUserData( bodyId ); + IndexPair pair = ConvertToPair( userData ); + DrawTextLine( "indices: (%d, %d)\n", pair.index1, pair.index2 ); + } + } + + for ( int i = 0; i < m_bodyCount && m_failure == false; i += 1 ) + { + b3BodyId bodyId = m_bodies[i]; + if ( B3_IS_NULL( bodyId ) ) + { + continue; + } + + b3Vec3 massCenter = b3Body_GetWorldCenterOfMass( bodyId ); + if ( massCenter.y < -2.0f ) + { + IndexPair pair = ConvertToPair( b3Body_GetUserData( bodyId ) ); + printf( "index1: %d - index2: %d\n", pair.index1, pair.index2 ); + printf( "(%6.2f, %6.2f, %6.2f)\n", massCenter.x, massCenter.y, massCenter.z ); + m_context->pause = true; + m_failure = true; + m_autoGenerate = false; + } + + // This is for debugging the fallback inner sphere + // b3Sphere sphere = {massCenter, 0.015f}; + // DrawSphere( m_scene, b3Transform_identity, sphere, b3_colorLightGray ); + } + + if ( m_autoGenerate ) + { + b3BodyEvents bodyEvents = b3World_GetBodyEvents( m_worldId ); + if ( bodyEvents.moveCount == 0 ) + { + Generate(); + } + + float timeStep = 0.0f; + if ( m_context->pause == false || m_context->singleStep > 0 ) + { + timeStep = m_context->hertz > 0.0f ? 1.0f / m_context->hertz : 0.0f; + m_context->singleStep = b3MaxInt( 0, m_context->singleStep - 1 ); + } + + // Many steps + if ( timeStep > 0.0f ) + { + int n = 20; + for ( int i = 0; i < n; ++i ) + { + b3World_Step( m_worldId, timeStep, m_context->subStepCount ); + } + + m_stepCount += n; + } + + if ( m_stepCount > 1000 ) + { + m_context->pause = true; + m_failure = true; + m_autoGenerate = false; + } + } + } + + static Sample* Create( SampleContext* context ) + { + return new MeshDrop( context ); + } + + static constexpr int m_gridCount = 32; + // static constexpr int m_gridCount = 3; + static constexpr int m_bodyCount = m_gridCount * m_gridCount; + + b3MeshData* m_groundMesh; + float m_groundAmplitude; + b3BodyId m_groundId; + b3Hull* m_cylinder; + b3BodyId* m_bodies; + ShapeType m_shapeType; + int m_runCount; + bool m_failure; + bool m_autoGenerate; +}; + +static int sampleMeshDrop = SampleManager::Register( "Continuous", "Mesh Drop", MeshDrop::Create ); + +class MeshDropUnitTest : public Sample +{ +public: + explicit MeshDropUnitTest( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 30.0f, 20.0f, b3Vec3_zero ); + m_context->debugDraw.forceScale = 0.1f; + } + + m_data = CreateMeshDrop( m_worldId ); + m_failed = false; + } + + ~MeshDropUnitTest() override + { + DestroyMeshDrop( &m_data ); + } + + void Step() override + { + Sample::Step(); + + if ( m_failed == false ) + { + if ( m_stepCount >= 300 ) + { + b3BodyEvents bodyEvents = b3World_GetBodyEvents( m_worldId ); + if ( bodyEvents.moveCount > 0 ) + { + m_failed = true; + } + } + } + + if ( m_failed == true ) + { + DrawTextLine( "failed!" ); + } + } + + static Sample* Create( SampleContext* context ) + { + return new MeshDropUnitTest( context ); + } + + MeshDropData m_data; + bool m_failed; +}; + +static int sampleMeshDropUnitTest = SampleManager::Register( "Continuous", "Mesh Drop Unit Test", MeshDropUnitTest::Create ); + +// This sample shows that clustering based on the manifold normal can lead to clipping and/or tunneling. +class HumpMesh : public Sample +{ +public: + explicit HumpMesh( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 25.0f, 4.0f, { 0.0f, 1.2f, 0.0f } ); + } + + m_hump = CreateHump( 8.0f ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundBodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateMeshShape( groundBodyId, &shapeDef, m_hump, b3Vec3_one ); + + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 5.0f, 0.0f }; + bodyDef.linearVelocity = { 0.0f, -50.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.05f, 1.0f ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + + ~HumpMesh() override + { + b3DestroyMesh( m_hump ); + } + + void Render() override + { + DrawGrid( m_scene, 10 ); + Sample::Render(); + } + + b3MeshData* CreateHump( float cellWidth ) const + { + // Vertices + b3Vec3 vertices[6]; + + int index = 0; + float x = -0.5f * cellWidth; + for ( int ix = 0; ix <= 1; ++ix ) + { + float z = -cellWidth; + for ( int iz = 0; iz <= 2; ++iz ) + { + vertices[index] = { x, 0.0f, z }; + if ( iz == 1 ) + { + vertices[index].y = 0.05f * cellWidth; + } + z += cellWidth; + index += 1; + } + x += cellWidth; + } + B3_ASSERT( index == 6 ); + + int triangleCount = 4; + int indices[3 * 4]; + + index = 0; + for ( int ix = 0; ix < 1; ++ix ) + { + for ( int iz = 0; iz < 2; ++iz ) + { + int index1 = iz + 3 * ix; + int index2 = index1 + 1; + int index3 = index2 + 3; + int index4 = index3 - 1; + + B3_ASSERT( index1 < 6 ); + B3_ASSERT( index2 < 6 ); + B3_ASSERT( index3 < 6 ); + B3_ASSERT( index4 < 6 ); + + indices[index + 0] = index1; + indices[index + 1] = index2; + indices[index + 2] = index3; + + indices[index + 3] = index3; + indices[index + 4] = index4; + indices[index + 5] = index1; + + index += 6; + } + } + B3_ASSERT( index == 3 * triangleCount ); + + b3MeshDef def = {}; + def.vertexCount = 6; + def.vertices = vertices; + def.triangleCount = 4; + def.indices = indices; + def.useMedianSplit = true; + def.identifyEdges = true; + + b3MeshData* meshData = b3CreateMesh( &def, nullptr, 0 ); + return meshData; + } + + static Sample* Create( SampleContext* context ) + { + return new HumpMesh( context ); + } + + b3MeshData* m_hump; +}; + +static int sampleHumpMesh = SampleManager::Register( "Continuous", "Hump Mesh", HumpMesh::Create ); + +class IsFast : public Sample +{ +public: + explicit IsFast( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 15.0f, 50.0f, { 0.0f, 15.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_staticBody; + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull groundBox = b3MakeBoxHull( 40.0f, 1.0f, 40.0f ); + b3CreateHullShape( groundBody, &shapeDef, &groundBox.base ); + } + + b3BoxHull box = b3MakeBoxHull( 0.5f, 10.0f, 0.5f ); + b3Capsule capsule = {{0.0f, -9.5f, 0.0f}, {0.0f, 9.5f, 0.0f}, 0.5f}; + + bool useCapsule = false; + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { -12.0f, 20.0f, 0.0f }; + bodyDef.gravityScale = 0.0f; + bodyDef.angularVelocity = { 0.0f, 0.0f, 4.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + if (useCapsule) + { + b3CreateCapsuleShape( bodyId, &shapeDef, &capsule ); + } + else + { + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 20.0f, 0.0f }; + bodyDef.gravityScale = 0.0f; + bodyDef.angularVelocity = { 0.0f, 4.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + if ( useCapsule ) + { + b3CreateCapsuleShape( bodyId, &shapeDef, &capsule ); + } + else + { + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 12.0f, 20.0f, 0.0f }; + bodyDef.gravityScale = 0.0f; + bodyDef.angularVelocity = { 4.0f, 0.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + if ( useCapsule ) + { + b3CreateCapsuleShape( bodyId, &shapeDef, &capsule ); + } + else + { + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + } + } + + static Sample* Create( SampleContext* context ) + { + return new IsFast( context ); + } +}; + +static int sampleIsFast = SampleManager::Register( "Continuous", "Is Fast", IsFast::Create ); diff --git a/samples/sample_determinism.cpp b/samples/sample_determinism.cpp new file mode 100644 index 0000000..8e8a273 --- /dev/null +++ b/samples/sample_determinism.cpp @@ -0,0 +1,59 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "camera.h" +#include "determinism.h" +#include "sample.h" +#include "scene.h" + +#include + +class FallingRagdolls : public Sample +{ +public: + explicit FallingRagdolls( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 40.0f, b3Vec3_zero ); + } + + m_data = CreateFallingRagdolls( m_worldId ); + m_done = false; + } + + ~FallingRagdolls() override + { + DestroyFallingRagdolls( &m_data ); + } + + void Step( ) override + { + Sample::Step( ); + + if ( m_done == false ) + { + m_done = UpdateFallingRagdolls( m_worldId, &m_data ); + if (m_done) + { + printf( "sleep step = %d, hash = 0x%08X\n", m_data.sleepStep, m_data.hash ); + } + } + else + { + DrawTextLine( "sleep step = %d, hash = 0x%08X", m_data.sleepStep, m_data.hash ); + + } + } + + static Sample* Create( SampleContext* context ) + { + return new FallingRagdolls( context ); + } + + FallingRagdollData m_data; + bool m_done; +}; + +static int sampleFallingRagdolls = SampleManager::Register( "Determinism", "Falling Ragdolls", FallingRagdolls::Create ); diff --git a/samples/sample_events.cpp b/samples/sample_events.cpp new file mode 100644 index 0000000..2222a6e --- /dev/null +++ b/samples/sample_events.cpp @@ -0,0 +1,918 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "GLFW/glfw3.h" +#include "camera.h" +#include "imgui.h" +#include "renderer.h" +#include "sample.h" +#include "scene.h" +#include "utils.h" + +#include "box3d/box3d.h" + +#include + +class SensorVisit : public Sample +{ +public: + static Sample* Create( SampleContext* context ) + { + return new SensorVisit( context ); + } + + explicit SensorVisit( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 30.0f, 20.0f, { 0.0f, 5.0f, 0.0f } ); + } + + // Visitor + b3BoxHull dynamicBox = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 12.5f, 0.0f }; + b3BodyId dynamicBody = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.enableSensorEvents = true; + b3CreateHullShape( dynamicBody, &shapeDef, &dynamicBox.base ); + + // Sensor + b3BoxHull sensorBox = b3MakeBoxHull( 2.0f, 2.0f, 2.0f ); + + bodyDef.type = b3_kinematicBody; + bodyDef.position = { 0.0f, 2.0f, 0.0f }; + b3BodyId sensorBody = b3CreateBody( m_worldId, &bodyDef ); + shapeDef.isSensor = true; + shapeDef.enableSensorEvents = true; + m_sensorShapeId = b3CreateHullShape( sensorBody, &shapeDef, &sensorBox.base ); + } + + void Render() override + { + DrawGrid( m_scene, 10 ); + Sample::Render(); + } + + void Step() override + { + Sample::Step(); + + b3SensorEvents events = b3World_GetSensorEvents( m_worldId ); + + for ( int i = 0; i < events.beginCount; ++i ) + { + b3SensorBeginTouchEvent* event = events.beginEvents + i; + if ( B3_ID_EQUALS( event->sensorShapeId, m_sensorShapeId ) ) + { + b3BodyId bodyId = b3Shape_GetBody( event->visitorShapeId ); + b3DestroyBody( bodyId ); + break; + } + } + } + + b3ShapeId m_sensorShapeId; +}; + +static int sampleSensorVisit = SampleManager::Register( "Events", "Sensor Visit", SensorVisit::Create ); + +class HitEvent : public Sample +{ +public: + enum + { + e_maxEvents = 32, + }; + + static Sample* Create( SampleContext* context ) + { + return new HitEvent( context ); + } + + explicit HitEvent( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 30.0f, 100.0f, { 0.0f, 5.0f, 0.0f } ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + constexpr int materialCount = 6; + m_gridMesh = b3CreateGridMesh( 20, 20, 8.0f, materialCount, true ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + b3SurfaceMaterial materials[materialCount]; + for ( int i = 0; i < materialCount; ++i ) + { + materials[i] = b3DefaultSurfaceMaterial(); + materials[i].userMaterialId = i + 1; + } + + shapeDef.materials = materials; + shapeDef.materialCount = materialCount; + + b3CreateMeshShape( groundId, &shapeDef, m_gridMesh, b3Vec3_one ); + // b3BoxHull groundBox = b3MakeTransformedBoxHull( 80.0f, 1.0f, 80.0f, { { 0.0f, -1.0f, 0.0f }, b3Quat_identity } ); + // b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + } + + b3WeldJointDef jointDef = b3DefaultWeldJointDef(); + jointDef.angularHertz = 10.0f; + jointDef.angularDampingRatio = 2.0f; + + float r = 0.75f; + float y = r; + float l = 1.5f; + float offset = 0.05f; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.enableHitEvents = true; + shapeDef.baseMaterial.rollingResistance = 0.2f; + shapeDef.baseMaterial.userMaterialId = 42; + shapeDef.updateBodyMass = false; + + b3Vec3 origin = { 0.0f, 0.0f, 0.0f }; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = origin; + + b3BodyId prevBodyId = {}; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + int shapeCount = 22; + float velocityScale = 0.5f; + int shapesPerBody = 3; + + for ( int i = 0; i < shapeCount; ++i ) + { + b3Capsule capsule = { { offset, y, 0.0f }, { 0.0f, y + l, -offset }, r }; + b3CreateCapsuleShape( bodyId, &shapeDef, &capsule ); + + if ( ( i + 1 ) % shapesPerBody == 0 || i == shapeCount - 1 ) + { + b3Body_ApplyMassFromShapes( bodyId ); + + b3Vec3 center = b3Body_GetWorldCenterOfMass( bodyId ); + b3Vec3 omega = { 0.0f, 0.0f, -1.0f * velocityScale }; + b3Vec3 v = b3Cross( omega, center - origin ); + b3Body_SetAngularVelocity( bodyId, omega ); + b3Body_SetLinearVelocity( bodyId, v ); + + if ( i < shapeCount - 1 ) + { + prevBodyId = bodyId; + + if ( i < shapeCount - 1 ) + { + bodyId = b3CreateBody( m_worldId, &bodyDef ); + + if ( B3_IS_NON_NULL( prevBodyId ) ) + { + jointDef.base.bodyIdA = prevBodyId; + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameA.p = { 0.0f, y + l + r, 0.0f }; + jointDef.base.localFrameB.p = { 0.0f, y + l + r, 0.0f }; + + b3CreateWeldJoint( m_worldId, &jointDef ); + } + + velocityScale *= 0.75f; + } + } + } + + y += l + 2.0f * r; + r = 0.95f * r; + offset = -offset; + } + + m_eventCount = 0; + } + + ~HitEvent() override + { + b3DestroyMesh( m_gridMesh ); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 4.0f ); + + for ( int i = 0; i < m_eventCount; ++i ) + { + // void DrawLine(Scene * Scene, b3Vector3 Vertex1, b3Vector3 Vertex2, b3Color Color); + // void DrawPoint(Scene * Scene, b3Vector3 Point, b3Color Color, float Size); + + b3Vec3 p1 = m_events[i].point; + DrawPoint( m_scene, m_events[i].point, 10.0f, b3_colorYellow ); + + b3Vec3 p2 = p1 - m_events[i].approachSpeed * m_events[i].normal; + DrawLine( m_scene, p1, p2, b3_colorYellow ); + + DrawWorldString( m_camera, p1, b3_colorWhite, "%.1f, %d", m_events[i].approachSpeed, m_events[i].userMaterialIdA ); + } + + DrawTextLine( "event count = %d", m_eventCount ); + } + + void Step() override + { + Sample::Step(); + + b3ContactEvents events = b3World_GetContactEvents( m_worldId ); + for ( int i = 0; i < events.hitCount && m_eventCount < e_maxEvents; ++i ) + { + m_events[m_eventCount] = events.hitEvents[i]; + m_eventCount += 1; + } + } + + static constexpr int m_maxEvents = 32; + b3MeshData* m_gridMesh; + b3ContactHitEvent m_events[m_maxEvents] = {}; + int m_eventCount; +}; + +static int sampleHitEvent = SampleManager::Register( "Events", "Hit", HitEvent::Create ); + +class MoveEvent : public Sample +{ +public: + explicit MoveEvent( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 30.0f, 40.0f, { 0.0f, 5.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + bodyDef.type = b3_staticBody; + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull groundBox = b3MakeBoxHull( 40.0f, 1.0f, 40.0f ); + b3CreateHullShape( groundBody, &shapeDef, &groundBox.base ); + + b3Vec3 pivot = { 0.0f, 1.0f, 0.0f }; + bodyDef.type = b3_dynamicBody; + bodyDef.position = pivot; + bodyDef.name = "big box"; + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + m_localPivot = b3Body_GetLocalPoint( m_bodyId, pivot ); + + shapeDef.enableHitEvents = true; + b3BoxHull dynamicBox = b3MakeTransformedBoxHull( 0.5f, 10.0f, 0.5f, { { 0.0f, 10.0f, 0.0f }, b3Quat_identity } ); + b3CreateHullShape( m_bodyId, &shapeDef, &dynamicBox.base ); + + b3Vec3 center = b3Body_GetWorldCenterOfMass( m_bodyId ); + + b3Vec3 r = pivot - center; + float rr = b3LengthSquared( r ); + if ( rr > 0.0f ) + { + b3Vec3 v = { -10.0f, 0.0f, 0.0f }; + b3Vec3 omega = ( 1.0f / rr ) * b3Cross( v, r ); + b3Body_SetAngularVelocity( m_bodyId, omega ); + b3Body_SetLinearVelocity( m_bodyId, v ); + } + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 4.0f ); + + b3Vec3 vp = b3Body_GetLocalPointVelocity( m_bodyId, m_localPivot ); + b3Vec3 v = b3Body_GetLinearVelocity( m_bodyId ); + b3Vec3 omega = b3Body_GetAngularVelocity( m_bodyId ); + + DrawTextLine( "vp = [%.2f, %.2f, %.2f], v = [%.2f, %.2f, %.2f], w = [%.2f, %.2f, %.2f]", vp.x, vp.y, vp.z, v.x, v.y, v.z, + omega.x, omega.y, omega.z ); + } + + void Step() override + { + Sample::Step(); + + b3BodyEvents moveEvents = b3World_GetBodyEvents( m_worldId ); + for ( int i = 0; i < moveEvents.moveCount; ++i ) + { + b3BodyId body = moveEvents.moveEvents[i].bodyId; + if ( moveEvents.moveEvents[i].fellAsleep ) + { + DrawTextLine( "%s fell asleep", b3Body_GetName( body ) ); + } + else + { + DrawTextLine( "%s moved", b3Body_GetName( body ) ); + } + } + } + + static Sample* Create( SampleContext* context ) + { + return new MoveEvent( context ); + } + + b3BodyId m_bodyId; + b3Vec3 m_localPivot; +}; + +static int sampleMoveEvent = SampleManager::Register( "Events", "Move", MoveEvent::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_camera->SetView( 0.0f, 30.0f, 40.0f, { 0.0f, 5.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + groundId = b3CreateBody( m_worldId, &bodyDef ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull box = b3MakeTransformedBoxHull( 20.0f, 1.0f, 20.0f, { { 0.0f, -1.0f, 0.0f }, b3Quat_identity } ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + + for ( int i = 0; i < e_count; ++i ) + { + m_jointIds[i] = b3_nullJointId; + } + + b3Vec3 position = { -12.5f, 10.0, 0.0f }; + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.enableSleep = false; + + b3BoxHull box = b3MakeBoxHull( 1.0f, 1.0f, 0.5f ); + + int index = 0; + + float forceThreshold = 3000.0f; + float torqueThreshold = 10000.0f; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 1.0f; + + // distance joint + { + assert( index < e_count ); + + bodyDef.position = position; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + float length = 2.0f; + b3Vec3 pivot1 = { position.x, position.y + 1.0f + length, 0.0f }; + b3Vec3 pivot2 = { position.x, position.y + 1.0f, 0.0f }; + b3DistanceJointDef jointDef = b3DefaultDistanceJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameA.p = b3Body_GetLocalPoint( jointDef.base.bodyIdA, pivot1 ); + jointDef.base.localFrameB.p = b3Body_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] = b3CreateDistanceJoint( m_worldId, &jointDef ); + } + + position.x += 5.0f; + ++index; + + // motor joint +#if 0 + { + assert( index < e_count ); + + bodyDef.position = position; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + b3MotorJointDef jointDef = b3DefaultMotorJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameA.p = position; + jointDef.maxForce = 1000.0f; + jointDef.maxTorque = 20.0f; + jointDef.base.forceThreshold = forceThreshold; + jointDef.base.torqueThreshold = torqueThreshold; + jointDef.base.collideConnected = true; + jointDef.base.userData = (void*)(intptr_t)index; + m_jointIds[index] = b3CreateMotorJoint( m_worldId, &jointDef ); + } +#else + m_jointIds[index] = {}; +#endif + + position.x += 5.0f; + ++index; + + // prismatic joint + { + assert( index < e_count ); + + bodyDef.position = position; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + b3Vec3 pivot = { position.x - 1.0f, position.y, 0.0f }; + b3PrismaticJointDef jointDef = b3DefaultPrismaticJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameA.p = b3Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); + jointDef.base.localFrameB.p = b3Body_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] = b3CreatePrismaticJoint( m_worldId, &jointDef ); + } + + position.x += 5.0f; + ++index; + + // revolute joint + { + assert( index < e_count ); + + bodyDef.position = position; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + b3Vec3 pivot = { position.x - 1.0f, position.y, 0.0f }; + b3RevoluteJointDef jointDef = b3DefaultRevoluteJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameA.p = b3Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); + jointDef.base.localFrameB.p = b3Body_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] = b3CreateRevoluteJoint( m_worldId, &jointDef ); + } + + position.x += 5.0f; + ++index; + + // weld joint + { + assert( index < e_count ); + + bodyDef.position = position; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + b3Vec3 pivot = { position.x - 1.0f, position.y, 0.0f }; + b3WeldJointDef jointDef = b3DefaultWeldJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameA.p = b3Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); + jointDef.base.localFrameB.p = b3Body_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] = b3CreateWeldJoint( m_worldId, &jointDef ); + } + + position.x += 5.0f; + ++index; + + // wheel joint +#if 0 + { + assert( index < e_count ); + + bodyDef.position = position; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + b3Vec3 pivot = { position.x - 1.0f, position.y, 0.0f }; + b3WheelJointDef jointDef = b3DefaultWheelJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameA.p = b3Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); + jointDef.base.localFrameB.p = b3Body_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] = b3CreateWheelJoint( m_worldId, &jointDef ); + } +#else + m_jointIds[index] = {}; +#endif + + position.x += 5.0f; + ++index; + } + + void Step() override + { + Sample::Step(); + + // Process joint events + b3JointEvents events = b3World_GetJointEvents( m_worldId ); + for ( int i = 0; i < events.count; ++i ) + { + // Destroy the joint if it is still valid + const b3JointEvent* event = events.jointEvents + i; + + if ( b3Joint_IsValid( event->jointId ) ) + { + int index = (int)(intptr_t)event->userData; + assert( 0 <= index && index < e_count ); + b3DestroyJoint( event->jointId, true ); + m_jointIds[index] = b3_nullJointId; + } + } + } + + static Sample* Create( SampleContext* context ) + { + return new JointEvent( context ); + } + + b3JointId m_jointIds[e_count]; +}; + +static int sampleJointEvent = SampleManager::Register( "Events", "Joint", JointEvent::Create ); + +class PersistentContact : public Sample +{ +public: + explicit PersistentContact( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 30.0f, 40.0f, { 0.0f, 5.0f, 0.0f } ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + m_meshData = b3CreateGridMesh( 20, 20, 2.0f, 2, true ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateMeshShape( groundId, &shapeDef, m_meshData, b3Vec3_one ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { -18.0f, 1.0f, 0.5f }; + bodyDef.linearVelocity = { 4.0f, 0.0f, 0.0f }; + + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 20.0f; + shapeDef.enableContactEvents = true; + shapeDef.baseMaterial.rollingResistance = 0.01f; + b3Sphere sphere = { b3Vec3_zero, 0.5f }; + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + } + + m_contactId = b3_nullContactId; + } + + ~PersistentContact() override + { + b3DestroyMesh( m_meshData ); + } + + void Step() override + { + Sample::Step(); + + b3ContactEvents events = b3World_GetContactEvents( m_worldId ); + for ( int i = 0; i < events.beginCount && i < 1; ++i ) + { + m_contactId = events.beginEvents[i].contactId; + } + + for ( int i = 0; i < events.endCount; ++i ) + { + if ( B3_ID_EQUALS( m_contactId, events.endEvents[i].contactId ) ) + { + m_contactId = b3_nullContactId; + break; + } + } + + if ( B3_IS_NON_NULL( m_contactId ) && b3Contact_IsValid( m_contactId ) ) + { + b3ContactData data = b3Contact_GetData( m_contactId ); + b3Vec3 centerOfMass = b3Body_GetWorldCenterOfMass( b3Shape_GetBody( data.shapeIdA ) ); + + for ( int i = 0; i < data.manifoldCount; ++i ) + { + const b3Manifold* manifold = data.manifolds + i; + b3Vec3 normal = manifold->normal; + for ( int j = 0; j < manifold->pointCount; ++j ) + { + const b3ManifoldPoint* manifoldPoint = manifold->points + i; + b3Vec3 p1 = manifoldPoint->anchorA + centerOfMass; + b3Vec3 p2 = p1 + manifoldPoint->totalNormalImpulse * normal; + DrawLine( m_scene, p1, p2, b3_colorCrimson ); + DrawPoint( m_scene, p1, 6.0f, b3_colorCrimson ); + DrawWorldString( m_camera, p1, b3_colorGray, "%.2f", manifoldPoint->totalNormalImpulse ); + } + } + } + else + { + m_contactId = b3_nullContactId; + } + } + + static Sample* Create( SampleContext* context ) + { + return new PersistentContact( context ); + } + + b3ContactId m_contactId; + b3MeshData* m_meshData; +}; + +static int samplePersistentContact = SampleManager::Register( "Events", "Persistent Contact", PersistentContact::Create ); + +class SensorHits : public Sample +{ +public: + explicit SensorHits( SampleContext* context ) + : Sample( context ) + , m_transforms{} + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 30.0f, 40.0f, { 0.0f, 5.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "ground"; + + groundId = b3CreateBody( m_worldId, &bodyDef ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + b3BoxHull groundBox = b3MakeOffsetBoxHull( 10.0f, 1.0f, 10.0f, {0.0f, -1.0f, 0.0f} ); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + + b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, 5.0f, 5.0f, { { 10.0f, 5.0f, 0.0f }, b3Quat_identity } ); + b3CreateHullShape( groundId, &shapeDef, &wallBox.base ); + } + + m_gridMesh = b3CreateGridMesh( 2, 2, 5.0f, 0, true ); + + // Static sensor + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "static sensor"; + bodyDef.position = { -4.0f, 6.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.5f * B3_PI ); + + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.isSensor = true; + shapeDef.enableSensorEvents = true; + + m_staticSensorId = b3CreateMeshShape( bodyId, &shapeDef, m_gridMesh, b3Vec3_one ); + } + + // Kinematic sensor + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "kinematic sensor"; + bodyDef.type = b3_kinematicBody; + bodyDef.position = { 0.0f, 6.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.5f * B3_PI ); + bodyDef.linearVelocity = { 0.5f, 0.0f }; + + m_kinematicBodyId = b3CreateBody( m_worldId, &bodyDef ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.isSensor = true; + shapeDef.enableSensorEvents = true; + + m_kinematicSensorId = b3CreateMeshShape( m_kinematicBodyId, &shapeDef, m_gridMesh, b3Vec3_one ); + } + + // Dynamic sensor + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "dynamic sensor"; + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 4.0f, 1.0f }; + + m_dynamicBodyId = b3CreateBody( m_worldId, &bodyDef ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.isSensor = true; + shapeDef.enableSensorEvents = true; + + b3Capsule capsule = { { 0.0f, 1.0f }, { 0.0f, 9.0f }, 0.1f }; + m_dynamicSensorId = b3CreateCapsuleShape( m_dynamicBodyId, &shapeDef, &capsule ); + + b3Vec3 pivot = bodyDef.position + b3Vec3{ 0.0f, 6.0f, 0.0f }; + b3PrismaticJointDef jointDef = b3DefaultPrismaticJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = m_dynamicBodyId; + jointDef.base.localFrameA.p = b3Body_GetLocalPoint( groundId, pivot ); + jointDef.base.localFrameB.p = b3Body_GetLocalPoint( m_dynamicBodyId, pivot ); + jointDef.enableMotor = true; + jointDef.maxMotorForce = 1000.0f; + jointDef.motorSpeed = 0.5f; + + m_jointId = b3CreatePrismaticJoint( m_worldId, &jointDef ); + } + + m_beginCount = 0; + m_endCount = 0; + m_bodyId = {}; + m_shapeId = {}; + m_transformCount = 0; + m_isBullet = true; + + Launch(); + } + + ~SensorHits() override + { + b3DestroyMesh( m_gridMesh ); + } + + void Launch() + { + if ( B3_IS_NON_NULL( m_bodyId ) ) + { + b3DestroyBody( m_bodyId ); + } + + m_transformCount = 0; + m_beginCount = 0; + m_endCount = 0; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_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 = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.enableSensorEvents = true; + shapeDef.baseMaterial.friction = 0.8f; + shapeDef.baseMaterial.rollingResistance = 0.01f; + b3Sphere sphere = { { 0.0f, 0.0f }, 0.25f }; + m_shapeId = b3CreateSphereShape( m_bodyId, &shapeDef, &sphere ); + } + + void UpdateUI() override + { + float height = 120.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_context->camera.m_height - height - 50.0f ), 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( b3ShapeId sensorShapeId ) + { + constexpr int capacity = 5; + b3ShapeId visitorIds[capacity]; + int count = b3Shape_GetSensorData( sensorShapeId, visitorIds, capacity ); + + for ( int i = 0; i < count && m_transformCount < m_transformCapacity; ++i ) + { + b3BodyId sensorBodyId = b3Shape_GetBody( sensorShapeId ); + m_transforms[m_transformCount] = b3Body_GetTransform( sensorBodyId ); + m_transforms[m_transformCount].p = b3Body_GetWorldCenterOfMass( sensorBodyId ); + m_transformCount += 1; + } + } + + void Step() override + { + b3Vec3 p = b3Body_GetPosition( m_kinematicBodyId ); + if ( p.x > 1.0f ) + { + b3Body_SetLinearVelocity( m_kinematicBodyId, { -0.5f, 0.0f } ); + } + else if ( p.x < -1.0f ) + { + b3Body_SetLinearVelocity( m_kinematicBodyId, { 0.5f, 0.0f } ); + } + + float x = b3PrismaticJoint_GetTranslation( m_jointId ); + if ( x > 1.0f ) + { + b3PrismaticJoint_SetMotorSpeed( m_jointId, -0.5f ); + } + else if ( x < -1.0f ) + { + b3PrismaticJoint_SetMotorSpeed( m_jointId, 0.5f ); + } + + Sample::Step(); + + for ( int i = 0; i < m_transformCount; ++i ) + { + DrawTransform( m_scene, m_transforms[i], 0.1f ); + } + + b3SensorEvents sensorEvents = b3World_GetSensorEvents( m_worldId ); + m_beginCount += sensorEvents.beginCount; + m_endCount += sensorEvents.endCount; + + for ( int i = 0; i < sensorEvents.beginCount; ++i ) + { + const b3SensorBeginTouchEvent* event = sensorEvents.beginEvents + i; + 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 ); + } + + b3MeshData* m_gridMesh; + + b3ShapeId m_staticSensorId; + b3ShapeId m_kinematicSensorId; + b3ShapeId m_dynamicSensorId; + + b3BodyId m_kinematicBodyId; + b3BodyId m_dynamicBodyId; + b3JointId m_jointId; + + b3BodyId m_bodyId; + b3ShapeId m_shapeId; + + static constexpr int m_transformCapacity = 20; + int m_transformCount; + b3Transform m_transforms[m_transformCapacity]; + + bool m_isBullet; + int m_beginCount; + int m_endCount; +}; + +static int sampleSensorHits = SampleManager::Register( "Events", "Sensor Hits", SensorHits::Create ); diff --git a/samples/sample_geometry.cpp b/samples/sample_geometry.cpp new file mode 100644 index 0000000..eda7496 --- /dev/null +++ b/samples/sample_geometry.cpp @@ -0,0 +1,651 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "camera.h" +#include "renderer.h" +#include "sample.h" +#include "scene.h" +#include "utils.h" + +#include + +class BoxHull : public Sample +{ +public: + explicit BoxHull( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 15.0f, 5.0f, b3Vec3_zero ); + } + + m_hull = nullptr; + + m_halfWidths = { 1.0f, 0.5f, 0.25f }; + m_postScale = { 1.0f, 1.0f, 1.0f }; + m_rotation = { 0.0f, 0.0f, 0.0f }; + m_transform = b3Transform_identity; + + UpdateRotation(); + CreateHulls( m_halfWidths, m_transform, m_postScale ); + } + + ~BoxHull() override + { + b3DestroyHull( m_hull ); + } + + void UpdateRotation() + { + b3Quat qx = b3MakeQuatFromAxisAngle( b3Vec3_axisX, B3_DEG_TO_RAD * m_rotation.x ); + b3Quat qy = b3MakeQuatFromAxisAngle( b3Vec3_axisY, B3_DEG_TO_RAD * m_rotation.y ); + b3Quat qz = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, B3_DEG_TO_RAD * m_rotation.z ); + + m_transform.q = b3MulQuat( qz, b3MulQuat( qy, qx ) ); + } + + void CreateHulls( b3Vec3 h, b3Transform transform, b3Vec3 postScale ) + { + if ( m_hull != nullptr ) + { + b3DestroyHull( m_hull ); + m_hull = nullptr; + } + + b3Vec3 scale = b3SafeScale( postScale ); + b3Vec3 points[8]; + + points[0] = scale * b3TransformPoint( transform, { h.x, h.y, h.z } ); + points[1] = scale * b3TransformPoint( transform, { h.x, h.y, -h.z } ); + points[2] = scale * b3TransformPoint( transform, { h.x, -h.y, h.z } ); + points[3] = scale * b3TransformPoint( transform, { h.x, -h.y, -h.z } ); + points[4] = scale * b3TransformPoint( transform, { -h.x, h.y, h.z } ); + points[5] = scale * b3TransformPoint( transform, { -h.x, h.y, -h.z } ); + points[6] = scale * b3TransformPoint( transform, { -h.x, -h.y, h.z } ); + points[7] = scale * b3TransformPoint( transform, { -h.x, -h.y, -h.z } ); + + m_hull = b3CreateHull( points, 8, 8 ); + m_box = b3MakeScaledBoxHull( h, transform, postScale ); + } + + void UpdateUI() override + { + float height = 180.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 350.0f, height ) ); + ImGui::Begin( "Box Hull", nullptr, 0 ); + + ImGui::PushItemWidth( 320.0f ); + + if ( ImGui::SliderFloat3( "h", &m_halfWidths.x, 0.1f, 2.0f, "%.1f" ) ) + { + CreateHulls( m_halfWidths, m_transform, m_postScale ); + } + + if ( ImGui::SliderFloat3( "c", &m_transform.p.x, -2.0f, 2.0f, "%.1f" ) ) + { + CreateHulls( m_halfWidths, m_transform, m_postScale ); + } + + if ( ImGui::SliderFloat3( "r", &m_rotation.x, -180.0f, 180.0f, "%.0f" ) ) + { + UpdateRotation(); + CreateHulls( m_halfWidths, m_transform, m_postScale ); + } + + if ( ImGui::SliderFloat3( "s", &m_postScale.x, -2.0f, 2.0f, "%.1f" ) ) + { + CreateHulls( m_halfWidths, m_transform, m_postScale ); + } + + ImGui::PopItemWidth(); + + if ( ImGui::Button( "refresh" ) ) + { + CreateHulls( m_halfWidths, m_transform, m_postScale ); + } + + ImGui::End(); + } + + void Render() override + { + DrawHull( m_scene, b3Transform_identity, m_hull, b3_colorYellow, true ); + DrawHull( m_scene, b3Transform_identity, &m_box.base, b3_colorCyan, true ); + + DrawTransform( m_scene, b3Transform_identity, 1.0f ); + + Sample::Render(); + } + + static Sample* Create( SampleContext* sampleContext ) + { + return new BoxHull( sampleContext ); + } + + b3Vec3 m_halfWidths; + b3Vec3 m_rotation; + b3Transform m_transform; + b3Vec3 m_postScale; + b3BoxHull m_box; + b3Hull* m_hull; +}; + +static int sampleBoxHull = SampleManager::Register( "Geometry", "Box Hull", BoxHull::Create ); + +class Hull : public Sample +{ +public: + explicit Hull( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 15.0f, 5.0f, b3Vec3_zero ); + } + + m_hull = nullptr; + + // this fails because it generates too many edges + b3Vec3 points[] = { + { -3.9866004, 75.4595108, 28.3783073 }, { -13.1079493, 73.080368, 28.296587 }, + { -18.6611958, 72.0040894, 16.9292431 }, { 4.82537603, 79.2908554, 22.2369995 }, + { -12.7315464, 79.2187576, 2.94275379 }, { -21.806488, 78.7758865, 0.985544085 }, + { -27.7619209, 73.3481522, 11.9647141 }, { -22.3994541, 72.2203826, 21.4116211 }, + { -25.3797474, 76.7417755, 27.9124985 }, { -22.7552319, 77.0559006, 29.4733639 }, + { -6.81736374, 78.3484726, 36.8649979 }, { 3.62397718, 85.5270843, 29.2077713 }, + { 7.90363788, 84.121231, 18.2612896 }, { -12.3809223, 84.5280533, -0.43230924 }, + { 5.83599472, 95.2908325, 4.4423275 }, { -22.5541401, 89.9094467, -4.87791252 }, + { -43.9060402, 78.5287094, 1.32877088 }, { -42.6015129, 76.7829742, 7.67437983 }, + { -25.735527, 78.1218796, 27.908411 }, { -23.5183544, 77.6326675, 29.1178799 }, + { 2.0977366, 100.430191, 34.3929482 }, { 1.09743047, 103.952553, 35.5656395 }, + { 8.50175952, 96.0529861, 8.73674774 }, { 2.52570295, 103.303696, 32.2314339 }, + { -20.099781, 89.4923248, -4.15468454 }, { 2.8092947, 123.516098, -1.12693477 }, + { -43.9318161, 79.1106186, 1.39006138 }, { -23.358511, 90.9599686, -4.25683546 }, + { 2.10804915, 123.603645, -1.38435471 }, { -44.1329117, 78.7192383, 1.54941654 }, + { -42.4365158, 77.725357, 8.14835929 }, { -43.204792, 77.5811691, 7.14319515 }, + { -44.17416, 78.7810363, 2.50146222 }, { -32.8975143, 99.1221771, 7.55588436 }, + { -0.624746263, 110.070351, 32.7381058 }, { 0.00431228895, 109.14341, 33.6411133 }, + { -0.58865279, 122.980537, 16.6554794 }, { 2.18539238, 124.324593, -0.620266676 }, + { -1.02177501, 123.881721, 16.8230057 }, { 1.9842999, 124.571777, -0.321986318 }, + { 1.86570692, 124.365791, -0.599836588 }, { -43.591507, 78.1373291, 6.1135149 }, + { -43.8235397, 79.2239074, 3.48619604 }, { -43.591507, 78.50811, 5.54555655 }, + { 1.21086729, 124.49453, 1.07543683 }, { -1.86223853, 124.195847, 15.6257992 }, + { -1.46520972, 124.355492, 16.9864483 }, { 1.654302, 124.612976, 0.621887207 }, + }; + + static_assert( sizeof( points ) / sizeof( points[0] ) < m_capacity, "bad" ); + + m_count = sizeof( points ) / sizeof( points[0] ); + for ( int i = 0; i < m_count; ++i ) + { + m_points[i] = 0.01f * points[i]; + } + + // This shift shouldn't be necessary but I'm doing it so the hull + // appears on the screen. + // for ( int i = 0; i < m_count; ++i ) + //{ + // m_points[i] -= m_points[0]; + // m_points[i] *= 0.01f; + //} + + m_hull = b3CreateHull( m_points, m_count, 16 ); + + (void)m_hull; + } + + ~Hull() override + { + if ( m_hull != nullptr ) + { + b3DestroyHull( m_hull ); + } + } + + void Render() override + { + if ( m_hull != nullptr ) + { + DrawHull( m_scene, b3Transform_identity, m_hull, b3_colorYellow, true ); + } + + DrawTransform( m_scene, b3Transform_identity, 1.0f ); + + Sample::Render(); + } + + static Sample* Create( SampleContext* sampleContext ) + { + return new Hull( sampleContext ); + } + + static constexpr int m_capacity = 64; + b3Hull* m_hull; + b3Vec3 m_points[m_capacity]; + int m_count; +}; + +static int sampleHull = SampleManager::Register( "Geometry", "Hull", Hull::Create ); + +class HullReduction : public Sample +{ +public: + enum Type + { + e_box, + e_sphere, + }; + + explicit HullReduction( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 15.0f, 5.0f, b3Vec3_zero ); + } + + m_hull = nullptr; + + m_type = e_sphere; + m_count = 16; + GeneratePoints(); + GenerateHull(); + } + + void GeneratePoints() + { + g_randomSeed = 42; + + if ( m_type == e_box ) + { + b3Vec3 lower = { -2.0f, -2.0f, -2.0f }; + b3Vec3 upper = { 2.0f, 2.0f, 2.0f }; + b3AABB box = { { -1.0f, -1.0f, -1.0f }, { 1.0f, 1.0f, 1.0f } }; + float a = 0.001f; + b3AABB noise = { { -a, -a, -a }, { a, a, a } }; + + for ( int i = 0; i < m_capacity; ++i ) + { + b3Vec3 p = RandomVec3( lower, upper ); + p = b3Clamp( p, box.lowerBound, box.upperBound ); + b3Vec3 f = RandomVec3( noise.lowerBound, noise.upperBound ); + m_points[i] = b3Add(p, f); + } + } + else + { + for ( int i = 0; i < m_capacity; ++i ) + { + m_points[i] = RandomUnitVector(); + } + } + } + + void GenerateHull() + { + if ( m_hull != nullptr ) + { + b3DestroyHull( m_hull ); + } + + m_hull = b3CreateHull( m_points, m_capacity, m_count ); + } + + ~HullReduction() override + { + if ( m_hull != nullptr ) + { + b3DestroyHull( m_hull ); + } + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 12.0f * fontSize; + ImGui::SetNextWindowPos( { 1.0f * fontSize, m_camera->m_height - height - 3.0f * fontSize }, ImGuiCond_Once ); + ImGui::SetNextWindowSize( { 16.0f * fontSize, height } ); + + ImGui::Begin( "Hull Reduction", nullptr, ImGuiWindowFlags_NoResize ); + + if ( ImGui::RadioButton( "Box", m_type == e_box ) ) + { + m_type = e_box; + GeneratePoints(); + GenerateHull(); + } + + if ( ImGui::RadioButton( "Sphere", m_type == e_sphere ) ) + { + m_type = e_sphere; + GeneratePoints(); + GenerateHull(); + } + + if ( ImGui::SliderInt( "count", &m_count, 4, m_capacity ) ) + { + GenerateHull(); + } + + ImGui::End(); + } + + void Render() override + { + if ( m_hull != nullptr ) + { + DrawHull( m_scene, b3Transform_identity, m_hull, b3_colorYellow, true ); + + DrawTextLine( "v/f/e = %d/%d/%d", m_hull->vertexCount, m_hull->faceCount, m_hull->edgeCount / 2 ); + } + + DrawTransform( m_scene, b3Transform_identity, 1.0f ); + + Sample::Render(); + } + + static Sample* Create( SampleContext* sampleContext ) + { + return new HullReduction( sampleContext ); + } + + static constexpr int m_capacity = 128; + Type m_type; + b3Hull* m_hull; + b3Vec3 m_points[m_capacity]; + int m_count; +}; + +static int sampleHullReduction = SampleManager::Register( "Geometry", "Hull Reduction", HullReduction::Create ); + +class HullScale : public Sample +{ +public: + explicit HullScale( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 15.0f, 5.0f, b3Vec3_zero ); + } + + m_original = b3CreateCylinder( 1.0f, 0.5f, 0.0f, 9 ); + m_box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + // m_original = &m_box.base; + m_scale = { 1.0f, 1.0f, 1.0f }; + m_angles = b3Vec3_zero; + m_offset = b3Vec3_zero; + m_hull = b3CloneAndTransformHull( m_original, b3Transform_identity, m_scale ); + } + + ~HullScale() override + { + if ( m_original != &m_box.base ) + { + b3DestroyHull( m_original ); + } + + b3DestroyHull( m_hull ); + } + + void UpdateHull() + { + b3DestroyHull( m_hull ); + + b3Quat qx = b3MakeQuatFromAxisAngle( b3Vec3_axisX, m_angles.x * B3_PI / 180.0f ); + b3Quat qy = b3MakeQuatFromAxisAngle( b3Vec3_axisY, m_angles.y * B3_PI / 180.0f ); + b3Quat qz = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, m_angles.z * B3_PI / 180.0f ); + b3Quat q = b3MulQuat( qz, b3MulQuat( qy, qx ) ); + + m_hull = b3CloneAndTransformHull( m_original, { m_offset, q }, m_scale ); + } + + void Render() override + { + b3Transform transform1 = { { -2.0f, 0.0f, 0.0f }, b3Quat_identity }; + b3Transform transform2 = { { 2.0f, 0.0f, 0.0f }, b3Quat_identity }; + + DrawHull( m_scene, transform1, m_original, b3_colorGreen, true ); + DrawHull( m_scene, transform2, m_hull, b3_colorYellow, true ); + DrawTransform( m_scene, b3Transform_identity, 1.0f ); + + DrawTextLine( "hull 1: area = %g, volume = %g, radius = %g", m_original->surfaceArea, m_original->volume, + m_original->innerRadius ); + DrawTextLine( "hull 2: area = %g, volume = %g, radius = %g", m_hull->surfaceArea, m_hull->volume, m_hull->innerRadius ); + + Sample::Render(); + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 18.0f * fontSize; + ImGui::SetNextWindowPos( { 1.0f * fontSize, m_camera->m_height - height - 3.0f * fontSize }, ImGuiCond_Once ); + ImGui::SetNextWindowSize( { 18.0f * fontSize, height } ); + + ImGui::Begin( "Hull Scale", nullptr, ImGuiWindowFlags_NoResize ); + + if ( ImGui::SliderFloat( "sx", &m_scale.x, -2.0f, 2.0f, "%.1f" ) ) + { + UpdateHull(); + } + + if ( ImGui::SliderFloat( "sy", &m_scale.y, -2.0f, 2.0f, "%.1f" ) ) + { + UpdateHull(); + } + + if ( ImGui::SliderFloat( "sz", &m_scale.z, -2.0f, 2.0f, "%.1f" ) ) + { + UpdateHull(); + } + + if ( ImGui::SliderFloat( "rx", &m_angles.x, -180.0f, 180.0f, "%.0f" ) ) + { + UpdateHull(); + } + + if ( ImGui::SliderFloat( "ry", &m_angles.y, -180.0f, 180.0f, "%.0f" ) ) + { + UpdateHull(); + } + + if ( ImGui::SliderFloat( "rz", &m_angles.z, -180.0f, 180.0f, "%.0f" ) ) + { + UpdateHull(); + } + + if ( ImGui::SliderFloat( "px", &m_offset.x, -1.0f, 1.0f, "%.1f" ) ) + { + UpdateHull(); + } + + if ( ImGui::SliderFloat( "py", &m_offset.y, -1.0f, 1.0f, "%.1f" ) ) + { + UpdateHull(); + } + + if ( ImGui::SliderFloat( "pz", &m_offset.z, -1.0f, 1.0f, "%.1f" ) ) + { + UpdateHull(); + } + + ImGui::End(); + } + + static Sample* Create( SampleContext* sampleContext ) + { + return new HullScale( sampleContext ); + } + + b3BoxHull m_box; + b3Hull* m_original; + b3Hull* m_hull; + b3Vec3 m_angles; + b3Vec3 m_scale; + b3Vec3 m_offset; +}; + +static int sampleHullScale = SampleManager::Register( "Geometry", "Hull Scale", HullScale::Create ); + +class CapsuleMass : public Sample +{ +public: + explicit CapsuleMass( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 15.0f, 5.0f, b3Vec3_zero ); + } + + m_radius = 1.0f; + m_length = 2.0f; + m_sides = 6; + m_capsule = { { -0.5f * m_length, 0.0f, 0.0f }, { 0.5f * m_length, 0.0f, 0.0f }, m_radius }; + m_box = b3MakeBoxHull( m_radius + 0.5f * m_length, m_radius, m_radius ); + + m_hull = nullptr; + CreateCapsuleHull( m_sides ); + } + + ~CapsuleMass() override + { + if ( m_hull != nullptr ) + { + b3DestroyHull( m_hull ); + } + } + + void CreateCapsuleHull( int sides ) + { + if ( m_hull != nullptr ) + { + b3DestroyHull( m_hull ); + m_hull = nullptr; + } + + constexpr int N = m_maxSides; + constexpr int M = 2 * N * N; + b3Vec3 points[M]; + + if ( sides > N ) + { + return; + } + + int count = 2 * sides * sides; + float d = B3_PI / ( sides - 1.0f ); + float angle1 = -0.5f * B3_PI; + int index = 0; + for ( int i = 0; i < sides; ++i ) + { + float s1 = sinf( angle1 ); + float c1 = cosf( angle1 ); + float angle2 = -0.5f * B3_PI; + for ( int j = 0; j < sides; ++j ) + { + points[index].x = 1.0f + m_radius * c1; + points[index].y = m_radius * s1 * cosf( angle2 ); + points[index].z = m_radius * s1 * sinf( angle2 ); + angle2 += d; + index += 1; + } + + angle1 += d; + } + + angle1 = 0.5f * B3_PI; + for ( int i = 0; i < sides; ++i ) + { + float s1 = sinf( angle1 ); + float c1 = cosf( angle1 ); + float angle2 = -0.5f * B3_PI; + for ( int j = 0; j < sides; ++j ) + { + points[index].x = -1.0f + m_radius * c1; + points[index].y = m_radius * s1 * cosf( angle2 ); + points[index].z = m_radius * s1 * sinf( angle2 ); + angle2 += d; + index += 1; + } + + angle1 += d; + } + + assert( index == count ); + + m_hull = b3CreateHull( points, count, count ); + } + + void Render() override + { + DrawCapsule( m_scene, b3Transform_identity, m_capsule, b3_colorAqua ); + DrawHull( m_scene, b3Transform_identity, &m_box.base, b3_colorBlueViolet, true ); + + if ( m_hull != nullptr ) + { + DrawHull( m_scene, b3Transform_identity, m_hull, b3_colorYellow, true ); + } + + DrawTransform( m_scene, b3Transform_identity, 1.0f ); + + if ( m_hull != nullptr ) + { + b3MassData lowerMassData = b3ComputeHullMass( m_hull, 1.0f ); + b3MassData massData = b3ComputeCapsuleMass( &m_capsule, 1.0f ); + b3MassData upperMassData = b3ComputeHullMass( &m_box.base, 1.0f ); + + DrawTextLine( "mass hull: %g", lowerMassData.mass ); + DrawTextLine( "mass capsule: %g", massData.mass ); + DrawTextLine( "mass box: %g", upperMassData.mass ); + m_textLine += m_textIncrement; + DrawTextLine( "Ixx hull: %g", lowerMassData.inertia.cx.x ); + DrawTextLine( "Ixx capsule: %g", massData.inertia.cx.x ); + DrawTextLine( "Ixx box: %g", upperMassData.inertia.cx.x ); + m_textLine += m_textIncrement; + DrawTextLine( "Iyy hull: %g", lowerMassData.inertia.cy.y ); + DrawTextLine( "Iyy capsule: %g", massData.inertia.cy.y ); + DrawTextLine( "Iyy box: %g", upperMassData.inertia.cy.y ); + m_textLine += m_textIncrement; + DrawTextLine( "Izz hull: %g", lowerMassData.inertia.cz.z ); + DrawTextLine( "Izz capsule: %g", massData.inertia.cz.z ); + DrawTextLine( "Izz box: %g", upperMassData.inertia.cz.z ); + } + + Sample::Render(); + } + + void UpdateUI() override + { + float height = 180.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 350.0f, height ) ); + ImGui::Begin( "Mass Data", nullptr, 0 ); + + if ( ImGui::SliderInt( "sides", &m_sides, 3, m_maxSides ) ) + { + CreateCapsuleHull( m_sides ); + } + + ImGui::End(); + } + + static Sample* Create( SampleContext* sampleContext ) + { + return new CapsuleMass( sampleContext ); + } + + // Limited by edge count + static constexpr int m_maxSides = 6; + b3Capsule m_capsule; + b3BoxHull m_box; + b3Hull* m_hull; + float m_radius; + float m_length; + int m_sides; +}; + +static int sampleCapsuleMass = SampleManager::Register( "Geometry", "Capsule Mass", CapsuleMass::Create ); diff --git a/samples/sample_issues.cpp b/samples/sample_issues.cpp new file mode 100644 index 0000000..3324205 --- /dev/null +++ b/samples/sample_issues.cpp @@ -0,0 +1,401 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "camera.h" +#include "imgui.h" +#include "renderer.h" +#include "sample.h" +#include "scene.h" + +#include "box3d/box3d.h" + +#include + +class DumpLoader : public Sample +{ +public: + explicit DumpLoader( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 15.0f, { 0.0f, 2.0f, 0.0f } ); + //m_camera->SetView( 45.0f, 30.0f, 300.0f, { 3910.62109f, 9862.50293f, 875.395081f } ); + } + + b3SetLengthUnitsPerMeter( 1.0f ); + + const char* dumpPrefix = "data/dumps/single_box/"; + + #include "dumps/single_box/box3d_dump.inl" + } + + ~DumpLoader() override + { + for (b3MeshData* md : m_meshes) + { + b3DestroyMesh( md ); + } + + b3SetLengthUnitsPerMeter( 1.0f ); + } + + static Sample* Create( SampleContext* context ) + { + return new DumpLoader( context ); + } + + std::vector m_meshes; +}; + +static int sampleDumpLoader = SampleManager::Register( "Issues", "Dump Loader", DumpLoader::Create ); + +class Crash : public Sample +{ +public: + explicit Crash( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 15.0f, { 0.0f, 2.0f, 0.0f } ); + } + + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + m_gridMesh = b3CreateGridMesh( 20, 20, 2, 0, true ); + b3CreateMeshShape( groundId, &shapeDef, m_gridMesh, b3Vec3_one ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 2.0f, 4.0f, 0.0f }; + m_bodyId1 = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3CreateHullShape( m_bodyId1, &shapeDef, &box.base ); + + bodyDef.position = { -2.0f, 4.0f, 0.0f }; + m_bodyId2 = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( m_bodyId2, &shapeDef, &box.base ); + } + + ~Crash() override + { + b3DestroyMesh( m_gridMesh ); + } + + void UpdateUI() override + { + float height = 320.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 300.0f, height ) ); + + ImGui::Begin( "Crash", nullptr, ImGuiWindowFlags_NoResize ); + + if ( ImGui::Button( "Add Joint" ) ) + { + b3WeldJointDef jointDef = b3DefaultWeldJointDef(); + jointDef.base.bodyIdA = m_bodyId1; + jointDef.base.bodyIdB = m_bodyId2; + b3CreateWeldJoint( m_worldId, &jointDef ); + } + + ImGui::End(); + } + + static Sample* Create( SampleContext* context ) + { + return new Crash( context ); + } + + b3BodyId m_bodyId1; + b3BodyId m_bodyId2; + b3MeshData* m_gridMesh; +}; + +static int sampleCrash = SampleManager::Register( "Issues", "Crash", Crash::Create ); + +class MultiplePrismatic : public Sample +{ +public: + explicit MultiplePrismatic( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 0.0f, 65.0f, { 0.0f, 0.0f, 0.0f } ); + } + + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + groundId = b3CreateBody( m_worldId, &bodyDef ); + } + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3PrismaticJointDef jointDef = b3DefaultPrismaticJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.localFrameA.p = { 0.0f, 0.0f, 0.0f }; + jointDef.base.localFrameB.p = { 0.0f, -0.6f, 0.0f }; + jointDef.base.drawScale = 2.0f; + jointDef.base.constraintHertz = 240.0f; + jointDef.lowerTranslation = -6.0f; + jointDef.upperTranslation = 6.0f; + jointDef.enableLimit = true; + + for ( int i = 0; i < 6; ++i ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, 0.6f + 1.2f * i, 0.0f }; + bodyDef.type = b3_dynamicBody; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + jointDef.base.bodyIdB = bodyId; + b3CreatePrismaticJoint( m_worldId, &jointDef ); + + jointDef.base.bodyIdA = bodyId; + jointDef.base.localFrameA.p = { 0.0f, 0.6f, 0.0f }; + } + + // huge mouse force + m_mouseForceScale = 1000000.0f; + } + + static Sample* Create( SampleContext* context ) + { + return new MultiplePrismatic( context ); + } +}; + +static int sampleMultiplePrismatic = SampleManager::Register( "Issues", "Multiple Prismatic", MultiplePrismatic::Create ); + +class HullCrash : public Sample +{ +public: + explicit HullCrash( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 15.0f, 5.0f, b3Vec3_zero ); + } + + + m_hull = nullptr; + +#if 0 + // bad hull SM_Waterfall_MED_Wide_01 + b3Vec3 points[] = { + { 0.100183107, -498.925385, -1275.39966 }, { 0.100183107, -498.925415, 0.125000000 }, + { 0.100183107, 486.343750, 0.125000000 }, { 0.100183107, 486.343719, -1275.39966 }, + { -395.117462, 486.343781, -1462.43750 }, { -395.117462, 486.343750, -96.7426758 }, + { -395.117462, -498.925415, -96.7424469 }, { -395.117462, -498.925446, -1462.52612 }, + { -186.979691, 486.294891, -1462.47949 }, { -298.250000, 486.294891, 0.125000000 }, + { -395.121216, 486.294891, -1462.52612 }, { -186.984360, -498.913361, -1462.48413 }, + { -298.250000, -498.913361, 0.125000000 }, + }; + +#elif 1 + b3Vec3 points[] = { + { 100.000000, -142.292389, 130.826111 }, { 99.5354385, -71.3011093, 130.826111 }, + { 99.5930862, -80.1112213, -100.000000 }, { 100.000000, -142.292389, -100.000000 }, + { 99.5930862, -80.1112213, 130.826111 }, + }; +#else + b3Vec3 points[] = { + { -11.3861933, -24.2451687, -12.0037909 }, { -11.3889809, -24.2466526, -11.9013014 }, + { -11.3804407, -24.3151531, -12.0046492 }, { -11.3832273, -24.3166409, -11.9021587 }, + { -14.4396200, -24.3636723, -12.1324549 }, { -14.4432650, -24.3655701, -12.0299988 }, + { -14.4356947, -24.4337788, -12.1336164 }, { -14.4393377, -24.4356804, -12.0311594 }, + }; +#endif + + static_assert( sizeof( points ) / sizeof( points[0] ) < m_capacity, "bad" ); + + m_count = sizeof( points ) / sizeof( points[0] ); + for ( int i = 0; i < m_count; ++i ) + { + m_points[i] = 0.01f * points[i]; + } + + // This shift shouldn't be necessary but I'm doing it so the hull + // appears on the screen. + // for ( int i = 0; i < m_count; ++i ) + //{ + // m_points[i] -= m_points[0]; + // m_points[i] *= 0.01f; + //} + + m_hull = b3CreateHull( m_points, m_count, m_count ); + + (void)m_hull; + } + + ~HullCrash() override + { + if ( m_hull != nullptr ) + { + b3DestroyHull( m_hull ); + } + } + + void Render() override + { + if ( m_hull != nullptr ) + { + DrawHull( m_scene, b3Transform_identity, m_hull, b3_colorYellow, true ); + } + else + { + for (int i = 0; i < m_count; ++i) + { + DrawPoint( m_scene, m_points[i], 5.0f, b3_colorWhite ); + } + } + + DrawTransform( m_scene, b3Transform_identity, 1.0f ); + + Sample::Render(); + } + + static Sample* Create( SampleContext* sampleContext ) + { + return new HullCrash( sampleContext ); + } + + static constexpr int m_capacity = 64; + b3Hull* m_hull; + b3Vec3 m_points[m_capacity]; + int m_count; +}; + +static int sampleHullCrash = SampleManager::Register( "Issues", "Hull Crash", HullCrash::Create ); + +class ConvexJitter : public Sample +{ +public: + explicit ConvexJitter( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 15.0f, 10.0f, { 0.0f, 2.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + +#if 1 + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull box = b3MakeBoxHull( 10.0f, 1.0f, 10.0f ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } +#endif + + float s = 0.01f; + + { + b3Vec3 b = { -459.292877f, 217.398331f, 1.00115335f }; + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { s * b.x, s * b.z + 2.0f, s * b.y }; + bodyDef.rotation = { { 0.0f, -0.707106769f, 0.0f }, 0.707106769f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + constexpr int count = 16; + b3Vec3 points[count]; + points[0] = { -44.8770714, -91.6598053, -1.92012548 }; + points[1] = { -92.5001831, 51.0151291, 15.8006573 }; + points[2] = { -91.0282211, -9.44371605, 15.6148796 }; + points[3] = { 90.2375641, 77.3870087, 15.9356089 }; + points[4] = { -85.5353241, 91.3750992, -1.36629653 }; + points[5] = { 88.9092178, -87.2975464, -1.86754704 }; + points[6] = { 83.7932816, -89.8572235, 15.4168339 }; + points[7] = { 87.0243988, 88.9776535, -1.32423306 }; + points[8] = { -91.6564941, -85.4949493, 15.3782759 }; + points[9] = { -90.2922516, -87.2074127, -1.92012548 }; + points[10] = { -87.2944870, 89.9510498, 15.9215889 }; + points[11] = { 79.2338104, 89.9690781, 15.9724140 }; + points[12] = { -91.6744461, 81.0823212, -1.39959598 }; + points[13] = { 90.3452759, -76.4459610, 15.4588966 }; + points[14] = { -87.4021912, -89.2263107, 15.3677588 }; + points[15] = { 76.3258057, 92.0059967, 1.82873762 }; + + for ( int i = 0; i < count; ++i ) + { + b3Vec3 p = points[i]; + points[i] = { s * p.x, s * p.z, s * p.y }; + } + + b3Hull* hull = b3CreateHull( points, count, count ); + + b3CreateHullShape( bodyId, &shapeDef, hull ); + b3DestroyHull( hull ); + } + + { + b3Vec3 b = { -402.321838f, 157.310364f, 16.8169250f }; + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { s * b.x, s * b.z + 2.0f, s * b.y }; + bodyDef.rotation = { { 0.0f, -0.00152086187f, 0.0f }, 0.999998868f }; + bodyDef.type = b3_dynamicBody; + + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.rollingResistance = 0.1f; + + constexpr int count = 18; + b3Vec3 points[count]; + points[0] = { 29.5000000, 17.1488495, 0.175081104 }; + points[1] = { 29.5000000, -17.2990532, 0.125000000 }; + points[2] = { 29.4840164, -17.3057766, 24.0200863 }; + points[3] = { 29.4840164, 17.1648350, 24.1781254 }; + points[4] = { -29.1345520, 17.5529804, 0.125000000 }; + points[5] = { -29.1345520, 17.5529804, 23.7899799 }; + points[6] = { -29.1441040, 16.9679585, 24.3750000 }; + points[7] = { -29.1345520, -17.2990532, 24.3750000 }; + points[8] = { -29.1345520, -17.2990532, 0.175081253 }; + points[9] = { 29.0720215, 17.5529785, 0.125000000 }; + points[10] = { 29.0859070, 17.5629406, 23.8120594 }; + points[11] = { 29.1401348, -17.2990532, 24.3750000 }; + points[12] = { 29.1123581, 16.9722290, 24.4027710 }; + points[13] = { 29.3944912, 17.2543602, 24.1206398 }; + points[14] = { -29.1345520, -17.2990532, 24.0759430 }; + points[15] = { -29.1345520, -16.9722252, 24.4027710 }; + points[16] = { 29.1123619, -16.9722271, 24.4027729 }; + points[17] = { 29.5000000, 17.3429642, 24.0000000 }; + + for ( int i = 0; i < count; ++i ) + { + b3Vec3 p = points[i]; + points[i] = { s * p.x, s * p.z, s * p.y }; + } + + b3Hull* hull = b3CreateHull( points, count, count ); + + b3CreateHullShape( bodyId, &shapeDef, hull ); + b3DestroyHull( hull ); + } + } + + static Sample* Create( SampleContext* context ) + { + return new ConvexJitter( context ); + } +}; + +static int sampleConvexJitter = SampleManager::Register( "Issues", "Convex Jitter", ConvexJitter::Create ); diff --git a/samples/sample_joint.cpp b/samples/sample_joint.cpp new file mode 100644 index 0000000..e0b87c6 --- /dev/null +++ b/samples/sample_joint.cpp @@ -0,0 +1,2784 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "GLFW/glfw3.h" +#include "camera.h" +#include "imgui.h" +#include "renderer.h" +#include "sample.h" +#include "scene.h" + +#include "box3d/box3d.h" + +// Test the distance joint and all options +class DistanceJoint : public Sample +{ +public: + enum + { + e_maxCount = 10 + }; + + explicit DistanceJoint( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 0.0f, 40.0f, { 0.0f, 10.0f, 0.0f } ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + m_groundId = b3CreateBody( 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] = b3_nullBodyId; + m_jointIds[i] = b3_nullJointId; + } + + CreateScene( 1 ); + } + + void CreateScene( int newCount ) + { + for ( int i = 0; i < m_count; ++i ) + { + b3DestroyJoint( m_jointIds[i], false ); + m_jointIds[i] = b3_nullJointId; + } + + for ( int i = 0; i < m_count; ++i ) + { + b3DestroyBody( m_bodyIds[i] ); + m_bodyIds[i] = b3_nullBodyId; + } + + m_count = newCount; + + float radius = 0.25f; + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, radius }; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 20.0f; + + float yOffset = 20.0f; + + b3DistanceJointDef jointDef = b3DefaultDistanceJointDef(); + 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; + + b3BodyId prevBodyId = m_groundId; + for ( int i = 0; i < m_count; ++i ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.angularDamping = 1.0f; + bodyDef.position = { m_length * ( i + 1.0f ), yOffset }; + m_bodyIds[i] = b3CreateBody( m_worldId, &bodyDef ); + b3CreateSphereShape( m_bodyIds[i], &shapeDef, &sphere ); + + b3Vec3 pivotA = { m_length * i, yOffset, 0.0f }; + b3Vec3 pivotB = { m_length * ( i + 1.0f ), yOffset, 0.0f }; + jointDef.base.bodyIdA = prevBodyId; + jointDef.base.bodyIdB = m_bodyIds[i]; + jointDef.base.localFrameA.p = b3Body_GetLocalPoint( prevBodyId, pivotA ); + jointDef.base.localFrameB.p = b3Body_GetLocalPoint( m_bodyIds[i], pivotB ); + m_jointIds[i] = b3CreateDistanceJoint( m_worldId, &jointDef ); + + prevBodyId = m_bodyIds[i]; + } + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 20.0f * fontSize; + ImGui::SetNextWindowPos( { 0.5f * fontSize, m_camera->m_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 ) + { + b3DistanceJoint_SetLength( m_jointIds[i], m_length ); + b3Joint_WakeBodies( m_jointIds[i] ); + } + } + + if ( ImGui::Checkbox( "Spring", &m_enableSpring ) ) + { + for ( int i = 0; i < m_count; ++i ) + { + b3DistanceJoint_EnableSpring( m_jointIds[i], m_enableSpring ); + b3Joint_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 ) + { + b3DistanceJoint_SetSpringForceRange( m_jointIds[i], -m_tensionForce, m_compressionForce ); + b3Joint_WakeBodies( m_jointIds[i] ); + } + } + + if ( ImGui::SliderFloat( "Compression", &m_compressionForce, 0.0f, 200.0f ) ) + { + for ( int i = 0; i < m_count; ++i ) + { + b3DistanceJoint_SetSpringForceRange( m_jointIds[i], -m_tensionForce, m_compressionForce ); + b3Joint_WakeBodies( m_jointIds[i] ); + } + } + + if ( ImGui::SliderFloat( "Hertz", &m_hertz, 0.0f, 15.0f, "%3.1f" ) ) + { + for ( int i = 0; i < m_count; ++i ) + { + b3DistanceJoint_SetSpringHertz( m_jointIds[i], m_hertz ); + b3Joint_WakeBodies( m_jointIds[i] ); + } + } + + if ( ImGui::SliderFloat( "Damping", &m_dampingRatio, 0.0f, 4.0f, "%3.1f" ) ) + { + for ( int i = 0; i < m_count; ++i ) + { + b3DistanceJoint_SetSpringDampingRatio( m_jointIds[i], m_dampingRatio ); + b3Joint_WakeBodies( m_jointIds[i] ); + } + } + } + + if ( ImGui::Checkbox( "Limit", &m_enableLimit ) ) + { + for ( int i = 0; i < m_count; ++i ) + { + b3DistanceJoint_EnableLimit( m_jointIds[i], m_enableLimit ); + b3Joint_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 ) + { + b3DistanceJoint_SetLengthRange( m_jointIds[i], m_minLength, m_maxLength ); + b3Joint_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 ) + { + b3DistanceJoint_SetLengthRange( m_jointIds[i], m_minLength, m_maxLength ); + b3Joint_WakeBodies( m_jointIds[i] ); + } + } + } + + int count = m_count; + if ( ImGui::SliderInt( "Count", &count, 1, e_maxCount ) ) + { + CreateScene( count ); + } + + ImGui::PopItemWidth(); + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + + DrawGrid( m_scene, 20 ); + } + + static Sample* Create( SampleContext* context ) + { + return new DistanceJoint( context ); + } + + b3BodyId m_groundId; + b3BodyId m_bodyIds[e_maxCount]; + b3JointId 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 = SampleManager::Register( "Joints", "Distance Joint", DistanceJoint::Create ); + +class FilterJoint : public Sample +{ +public: + explicit FilterJoint( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 15.0f, { 0.0f, 2.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 2.0f, 4.0f, 0.0f }; + b3BodyId bodyId1 = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3CreateHullShape( bodyId1, &shapeDef, &box.base ); + + bodyDef.position = { -2.0f, 4.0f, 0.0f }; + b3BodyId bodyId2 = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId2, &shapeDef, &box.base ); + + b3FilterJointDef jointDef = b3DefaultFilterJointDef(); + jointDef.base.bodyIdA = bodyId1; + jointDef.base.bodyIdB = bodyId2; + b3CreateFilterJoint( m_worldId, &jointDef ); + } + + void Render() override + { + Sample::Render(); + + b3Transform transform = b3Transform_identity; + transform.p.y += 0.05f; + DrawTransform( m_scene, transform, 2.0f ); + } + + static Sample* Create( SampleContext* context ) + { + return new FilterJoint( context ); + } +}; + +static int sampleFilterJoint = SampleManager::Register( "Joints", "Filter", FilterJoint::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 ( context->restart == false ) + { + m_camera->SetView( 0.0f, 0.0f, 40.0f, { 0.0f, 10.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position.y = -1.0f; + groundId = b3CreateBody( m_worldId, &bodyDef ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull box = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + + m_transform = { .p = { 0.0f, 10.0f, 0.0f }, .q = b3Quat_identity }; + + // Define a target body + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_kinematicBody; + bodyDef.position = m_transform.p; + m_targetId = b3CreateBody( m_worldId, &bodyDef ); + } + + // Define motorized body + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = m_transform.p; + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull box = b3MakeBoxHull( 1.0f, 0.25f, 0.25f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( m_bodyId, &shapeDef, &box.base ); + + m_maxForce = 400000.0f; + m_maxTorque = 500000.0f; + + b3MotorJointDef jointDef = b3DefaultMotorJointDef(); + 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 = b3CreateMotorJoint( m_worldId, &jointDef ); + } + + // Define spring body + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { -2.0f, 2.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + b3MotorJointDef jointDef = b3DefaultMotorJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameA.p = b3Add( bodyDef.position, { 0.25f, 1.25f, 0.0f } ); + jointDef.base.localFrameB.p = { 0.25f, 0.25f }; + jointDef.base.collideConnected = true; + jointDef.linearHertz = 7.5f; + jointDef.linearDampingRatio = 0.7f; + jointDef.angularHertz = 7.5f; + jointDef.angularDampingRatio = 0.7f; + jointDef.maxSpringForce = 200000.0f; + jointDef.maxSpringTorque = 10000.0f; + + b3CreateMotorJoint( m_worldId, &jointDef ); + } + + m_speed = 0.0f; + m_time = 0.0f; + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 180.0f; + ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->m_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, 1000000.0f, "%.0f" ) ) + { + b3MotorJoint_SetMaxSpringForce( m_jointId, m_maxForce ); + } + + if ( ImGui::SliderFloat( "Max Torque", &m_maxTorque, 0.0f, 1000000.0f, "%.0f" ) ) + { + b3MotorJoint_SetMaxSpringTorque( m_jointId, m_maxTorque ); + } + + if ( ImGui::Button( "Apply Impulse" ) ) + { + b3Body_ApplyLinearImpulseToCenter( m_bodyId, { 100000.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 == 0 ) + { + timeStep = 0.0f; + } + } + + if ( timeStep > 0.0f ) + { + m_time += m_speed * timeStep; + + b3Vec3 linearOffset; + linearOffset.x = 6.0f * sinf( 2.0f * m_time ); + linearOffset.y = 10.0f + 4.0f * sinf( 1.0f * m_time ); + linearOffset.z = 0.0f; + + float angularOffset = 2.0f * m_time; + m_transform = { linearOffset, b3MakeQuatFromAxisAngle( b3Vec3_axisZ, angularOffset ) }; + + b3Body_SetTargetTransform( m_targetId, m_transform, timeStep, true ); + } + + DrawTransform( m_scene, m_transform, 1.0f ); + + Sample::Step(); + + b3Vec3 force = b3Joint_GetConstraintForce( m_jointId ); + b3Vec3 torque = b3Joint_GetConstraintTorque( m_jointId ); + + DrawTextLine( "force = %3.f, torque = %3.f", b3Length( force ), b3Length( torque ) ); + } + + static Sample* Create( SampleContext* context ) + { + return new MotorJoint( context ); + } + + b3BodyId m_targetId; + b3BodyId m_bodyId; + b3JointId m_jointId; + b3Transform m_transform; + float m_time; + float m_speed; + float m_maxForce; + float m_maxTorque; +}; + +static int sampleMotorJoint = SampleManager::Register( "Joints", "Motor Joint", MotorJoint::Create ); + +class TopDownFriction : public Sample +{ +public: + explicit TopDownFriction( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 0.0f, 25.0f, { 0.0f, 10.0f, 0.0f } ); + } + + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + groundId = b3CreateBody( m_worldId, &bodyDef ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull box = b3MakeTransformedBoxHull( 10.0f, 0.5f, 50.0f, { b3Vec3_zero, b3Quat_identity } ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + + box = b3MakeTransformedBoxHull( 0.5f, 10.0f, 50.0f, { { -10.0f, 10.0f, 0.0f }, b3Quat_identity } ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + + box = b3MakeTransformedBoxHull( 0.5f, 10.0f, 50.0f, { { 10.0f, 10.0f, 0.0f }, b3Quat_identity } ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + + box = b3MakeTransformedBoxHull( 10.0f, 0.5f, 50.0f, { { 00.0f, 20.0f, 0.0f }, b3Quat_identity } ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + + b3MotorJointDef jointDef = b3DefaultMotorJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.collideConnected = true; + jointDef.maxVelocityForce = 1000.0f; + jointDef.maxVelocityTorque = 1000.0f; + + b3Capsule capsule = { { -0.25f, 0.0f }, { 0.25f, 0.0f }, 0.25f }; + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.35f }; + b3BoxHull cube = b3MakeBoxHull( 0.35f, 0.35f, 0.35f ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.gravityScale = 0.0f; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.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 }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + int remainder = ( n * i + j ) % 4; + if ( remainder == 0 ) + { + b3CreateCapsuleShape( bodyId, &shapeDef, &capsule ); + } + else if ( remainder == 1 ) + { + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + } + else + { + b3CreateHullShape( bodyId, &shapeDef, &cube.base ); + } + + jointDef.base.bodyIdB = bodyId; + b3CreateMotorJoint( m_worldId, &jointDef ); + + x += 1.0f; + } + + x = -5.0f; + y -= 1.0f; + } + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 180.0f; + ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->m_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" ) ) + { + b3Sphere sphere = { { 0.0f, 10.0f, 0.0 }, 10.0f }; + b3ExplosionDef def = b3DefaultExplosionDef(); + def.position = sphere.center; + def.radius = sphere.radius; + def.falloff = 5.0f; + def.impulsePerArea = 10000.0f; + b3World_Explode( m_worldId, &def ); + + DrawSphere( m_scene, b3Transform_identity, sphere, b3_colorWhite ); + } + + ImGui::End(); + } + + static Sample* Create( SampleContext* context ) + { + return new TopDownFriction( context ); + } +}; + +static int sampleTopDownFriction = SampleManager::Register( "Joints", "Top Down Friction", TopDownFriction::Create ); + +class PrismaticJoint : public Sample +{ +public: + explicit PrismaticJoint( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 15.0f, { 0.0f, 2.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + m_targetTranslation = 0.0f; + m_motorSpeed = 0.0f; + m_motorForce = 20.0f; + m_hertz = 2.0f; + m_dampingRatio = 0.7f; + m_lowerTranslation = -1.0f; + m_upperTranslation = 1.0f; + m_enableSpring = true; + m_enableMotor = false; + m_enableLimit = false; + + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 4.0f, 0.0f }; + bodyDef.gravityScale = 0.0f; + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + b3BoxHull box = b3MakeBoxHull( 0.5f, 1.5f, 0.25f ); + b3CreateHullShape( m_bodyId, &shapeDef, &box.base ); + + b3PrismaticJointDef jointDef = b3DefaultPrismaticJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = m_bodyId; + jointDef.base.localFrameA.p = { 0.0f, 6.5f, 0.0f }; + jointDef.base.localFrameB.p = { 0.0f, 1.5f, 0.0f }; + jointDef.base.constraintHertz = 120.0f; + jointDef.enableLimit = m_enableLimit; + jointDef.lowerTranslation = m_lowerTranslation; + jointDef.upperTranslation = m_upperTranslation; + jointDef.enableSpring = m_enableSpring; + jointDef.hertz = m_hertz; + jointDef.dampingRatio = m_dampingRatio; + jointDef.targetTranslation = m_targetTranslation; + jointDef.enableMotor = m_enableMotor; + jointDef.maxMotorForce = m_motorForce; + jointDef.motorSpeed = m_motorSpeed; + + m_jointId = b3CreatePrismaticJoint( m_worldId, &jointDef ); + } + + void UpdateUI() override + { + float height = 320.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 300.0f, height ) ); + + ImGui::Begin( "Prismatic Joint", nullptr, ImGuiWindowFlags_NoResize ); + + if ( ImGui::Checkbox( "Limit", &m_enableLimit ) ) + { + b3PrismaticJoint_EnableLimit( m_jointId, m_enableLimit ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( m_enableLimit ) + { + if ( ImGui::SliderFloat( "Lower Translation", &m_lowerTranslation, -10.0f, 10.0f, "%.1f" ) ) + { + m_lowerTranslation = b3MinFloat( m_lowerTranslation, m_upperTranslation ); + b3PrismaticJoint_SetLimits( m_jointId, m_lowerTranslation, m_upperTranslation ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Upper Translation", &m_upperTranslation, -10.0f, 10.0f, "%.1f" ) ) + { + m_upperTranslation = b3MaxFloat( m_upperTranslation, m_lowerTranslation ); + b3PrismaticJoint_SetLimits( m_jointId, m_lowerTranslation, m_upperTranslation ); + b3Joint_WakeBodies( m_jointId ); + } + } + + if ( ImGui::Checkbox( "Motor", &m_enableMotor ) ) + { + b3PrismaticJoint_EnableMotor( m_jointId, m_enableMotor ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( m_enableMotor ) + { + if ( ImGui::SliderFloat( "Max Force", &m_motorForce, 0.0f, 100000.0f, "%.0f" ) ) + { + b3PrismaticJoint_SetMaxMotorForce( m_jointId, m_motorForce ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Speed", &m_motorSpeed, -10.0f, 10.0f, "%.0f" ) ) + { + b3PrismaticJoint_SetMotorSpeed( m_jointId, m_motorSpeed ); + b3Joint_WakeBodies( m_jointId ); + } + } + + if ( ImGui::Checkbox( "Spring", &m_enableSpring ) ) + { + b3PrismaticJoint_EnableSpring( m_jointId, m_enableSpring ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( m_enableSpring ) + { + if ( ImGui::SliderFloat( "Hertz", &m_hertz, 0.0f, 10.0f, "%.1f" ) ) + { + b3PrismaticJoint_SetSpringHertz( m_jointId, m_hertz ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Damping", &m_dampingRatio, 0.0f, 2.0f, "%.1f" ) ) + { + b3PrismaticJoint_SetSpringDampingRatio( m_jointId, m_dampingRatio ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Translation", &m_targetTranslation, -20.0f, 20.0f, "%.1f" ) ) + { + b3PrismaticJoint_SetTargetTranslation( m_jointId, m_targetTranslation ); + b3Joint_WakeBodies( m_jointId ); + } + } + + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + } + + static Sample* Create( SampleContext* context ) + { + return new PrismaticJoint( context ); + } + + b3BodyId m_bodyId; + b3JointId m_jointId; + float m_targetTranslation; + float m_motorSpeed; + float m_motorForce; + float m_hertz; + float m_dampingRatio; + float m_lowerTranslation; + float m_upperTranslation; + bool m_enableSpring; + bool m_enableMotor; + bool m_enableLimit; +}; + +static int samplePrismaticJoint = SampleManager::Register( "Joints", "Prismatic", PrismaticJoint::Create ); + +class SphericalJoint : public Sample +{ +public: + explicit SphericalJoint( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 15.0f, { 0.0f, 2.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 4.0f, 1.5f }; + bodyDef.gravityScale = 0.0f; + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.25f, 1.5f ); + b3CreateHullShape( m_bodyId, &shapeDef, &box.base ); + + b3SphericalJointDef jointDef = b3DefaultSphericalJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = m_bodyId; + jointDef.base.drawScale = 2.0f; + jointDef.base.localFrameA.p = { 0.0f, 5.5f, 0.0f }; + jointDef.base.localFrameB.p = { 0.0f, 0.0f, -1.5f }; + jointDef.enableConeLimit = m_enableConeLimit; + jointDef.coneAngle = B3_DEG_TO_RAD * m_coneAngleDegrees; + jointDef.enableTwistLimit = m_enableTwistLimit; + jointDef.lowerTwistAngle = B3_DEG_TO_RAD * m_lowerTwistDegrees; + jointDef.upperTwistAngle = B3_DEG_TO_RAD * m_upperTwistDegrees; + jointDef.enableSpring = m_enableSpring; + jointDef.hertz = m_hertz; + jointDef.dampingRatio = m_dampingRatio; + jointDef.enableMotor = m_enableMotor; + jointDef.maxMotorTorque = m_motorTorque; + jointDef.motorVelocity = m_motorVelocity; + + m_jointId = b3CreateSphericalJoint( m_worldId, &jointDef ); + } + + void UpdateUI() override + { + float height = 360.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 300.0f, height ) ); + + ImGui::Begin( "Spherical Joint", nullptr, ImGuiWindowFlags_NoResize ); + + if ( ImGui::Checkbox( "Cone Limit", &m_enableConeLimit ) ) + { + b3SphericalJoint_EnableConeLimit( m_jointId, m_enableConeLimit ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( m_enableConeLimit ) + { + if ( ImGui::SliderFloat( "Cone Angle", &m_coneAngleDegrees, 0.0f, 90.0f, "%.0f" ) ) + { + b3SphericalJoint_SetConeLimit( m_jointId, B3_DEG_TO_RAD * m_coneAngleDegrees ); + b3Joint_WakeBodies( m_jointId ); + } + } + + if ( ImGui::Checkbox( "Twist Limit", &m_enableTwistLimit ) ) + { + b3SphericalJoint_EnableTwistLimit( m_jointId, m_enableTwistLimit ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( m_enableTwistLimit ) + { + if ( ImGui::SliderFloat( "Lower Twist", &m_lowerTwistDegrees, -180.0f, 180.0f, "%.0f" ) ) + { + m_lowerTwistDegrees = b3MinFloat( m_lowerTwistDegrees, m_upperTwistDegrees ); + b3SphericalJoint_SetTwistLimits( m_jointId, B3_DEG_TO_RAD * m_lowerTwistDegrees, + B3_DEG_TO_RAD * m_upperTwistDegrees ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Upper Twist", &m_upperTwistDegrees, -180.0f, 180.0f, "%.0f" ) ) + { + m_upperTwistDegrees = b3MaxFloat( m_upperTwistDegrees, m_lowerTwistDegrees ); + b3SphericalJoint_SetTwistLimits( m_jointId, B3_DEG_TO_RAD * m_lowerTwistDegrees, + B3_DEG_TO_RAD * m_upperTwistDegrees ); + b3Joint_WakeBodies( m_jointId ); + } + } + + if ( ImGui::Checkbox( "Motor", &m_enableMotor ) ) + { + b3SphericalJoint_EnableMotor( m_jointId, m_enableMotor ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( m_enableMotor ) + { + if ( ImGui::SliderFloat( "Max Torque", &m_motorTorque, 0.0f, 50.0f, "%.0f" ) ) + { + b3SphericalJoint_SetMaxMotorTorque( m_jointId, m_motorTorque ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat3( "Velocity", &m_motorVelocity.x, -10.0f, 10.0f, "%.0f" ) ) + { + b3SphericalJoint_SetMotorVelocity( m_jointId, m_motorVelocity ); + b3Joint_WakeBodies( m_jointId ); + } + } + + if ( ImGui::Checkbox( "Spring", &m_enableSpring ) ) + { + b3SphericalJoint_EnableSpring( m_jointId, m_enableSpring ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( m_enableSpring ) + { + if ( ImGui::SliderFloat( "Hertz", &m_hertz, 0.0f, 10.0f, "%.1f" ) ) + { + b3SphericalJoint_SetSpringHertz( m_jointId, m_hertz ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Damping", &m_dampingRatio, 0.0f, 2.0f, "%.1f" ) ) + { + b3SphericalJoint_SetSpringDampingRatio( m_jointId, m_dampingRatio ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat3( "Rotation", &m_targetRotation.x, -180.0f, 180.0f, "%.0f" ) ) + { + b3Quat qx = b3MakeQuatFromAxisAngle( b3Vec3_axisX, B3_DEG_TO_RAD * m_targetRotation.x ); + b3Quat qy = b3MakeQuatFromAxisAngle( b3Vec3_axisY, B3_DEG_TO_RAD * m_targetRotation.y ); + b3Quat qz = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, B3_DEG_TO_RAD * m_targetRotation.z ); + b3Quat q = b3MulQuat( qz, b3MulQuat( qy, qx ) ); + b3SphericalJoint_SetTargetRotation( m_jointId, q ); + b3Joint_WakeBodies( m_jointId ); + } + } + + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + + b3Transform transform = b3Transform_identity; + transform.p.y += 0.05f; + DrawTransform( m_scene, transform, 2.0f ); + + transform = b3Body_GetTransform( m_bodyId ); + DrawTransform( m_scene, transform, 2.0f ); + } + + static Sample* Create( SampleContext* context ) + { + return new SphericalJoint( context ); + } + + b3BodyId m_bodyId; + b3JointId m_jointId; + b3Vec3 m_targetRotation = b3Vec3_zero; + b3Vec3 m_motorVelocity = b3Vec3_zero; + float m_motorTorque = 20.0f; + float m_hertz = 2.0f; + float m_dampingRatio = 0.7f; + float m_coneAngleDegrees = 30.0f; + float m_lowerTwistDegrees = -35.0f; + float m_upperTwistDegrees = 35.0f; + bool m_enableSpring = true; + bool m_enableMotor = false; + bool m_enableTwistLimit = false; + bool m_enableConeLimit = false; +}; + +static int sampleSphericalJoint = SampleManager::Register( "Joints", "Spherical", SphericalJoint::Create ); + +class ParallelJoint : public Sample +{ +public: + explicit ParallelJoint( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 15.0f, { 0.0f, 2.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + m_hertz = 10.0f; + m_dampingRatio = 0.7f; + m_maxTorque = 5000.0f; + + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + } + + { + b3Transform transform; + transform.p = { 0.0f, 5.0f, -20.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 20.0f, 5.0f, 0.1f, transform ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform; + transform.p = { 0.0f, 5.0f, 20.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 20.0f, 5.0f, 0.1f, transform ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform; + transform.p = { -20.0f, 5.0f, 0.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, 5.0f, 20.0f, transform ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform; + transform.p = { 20.0f, 5.0f, 0.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, 5.0f, 20.0f, transform ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &shapeDef, &wallBox.base ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 4.0f, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisX, 0.25f * B3_PI ); + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + b3BoxHull box = b3MakeBoxHull( 0.5f, 1.5f, 0.25f ); + b3CreateHullShape( m_bodyId, &shapeDef, &box.base ); + + b3ParallelJointDef jointDef = b3DefaultParallelJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = m_bodyId; + jointDef.base.localFrameA.q = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisZ, b3Vec3_axisY ); + jointDef.base.localFrameB.q = b3InvMulQuat( bodyDef.rotation, jointDef.base.localFrameA.q ); + + jointDef.base.drawScale = 2.0f; + jointDef.base.collideConnected = true; + jointDef.hertz = m_hertz; + jointDef.dampingRatio = m_dampingRatio; + + m_jointId = b3CreateParallelJoint( m_worldId, &jointDef ); + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 20.0f * fontSize; + ImGui::SetNextWindowPos( { 1.0f * fontSize, m_camera->m_height - height - 3.0f * fontSize }, ImGuiCond_Once ); + ImGui::SetNextWindowSize( { 20.0f * fontSize, height } ); + + ImGui::Begin( "Parallel Joint", nullptr, ImGuiWindowFlags_NoResize ); + + if ( ImGui::SliderFloat( "Hertz", &m_hertz, 0.0f, 5.0f, "%.1f" ) ) + { + b3ParallelJoint_SetSpringHertz( m_jointId, m_hertz ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Damping", &m_dampingRatio, 0.0f, 2.0f, "%.1f" ) ) + { + b3ParallelJoint_SetSpringDampingRatio( m_jointId, m_dampingRatio ); + b3Joint_WakeBodies( m_jointId ); + } + + ImGui::End(); + } + + static Sample* Create( SampleContext* context ) + { + return new ParallelJoint( context ); + } + + b3BodyId m_bodyId; + b3JointId m_jointId; + float m_maxTorque; + float m_hertz; + float m_dampingRatio; +}; + +static int sampleParallelJoint = SampleManager::Register( "Joints", "Parallel Spring", ParallelJoint::Create ); + +class RevoluteJoint : public Sample +{ +public: + explicit RevoluteJoint( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 15.0f, { 0.0f, 2.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + m_targetAngle = 0.0f; + m_motorSpeed = 0.0f; + m_motorTorque = 5000.0f; + m_hertz = 2.0f; + m_dampingRatio = 0.7f; + m_lowerDegrees = -35.0f; + m_upperDegrees = 35.0f; + m_enableSpring = false; + m_enableMotor = false; + m_enableLimit = false; + + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 4.0f, 0.0f }; + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + b3BoxHull box = b3MakeBoxHull( 0.5f, 1.5f, 0.25f ); + b3CreateHullShape( m_bodyId, &shapeDef, &box.base ); + + b3RevoluteJointDef jointDef = b3DefaultRevoluteJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = m_bodyId; + jointDef.base.localFrameA.p = { 0.0f, 6.5f, 0.0f }; + jointDef.base.localFrameB.p = { 0.0f, 1.5f, 0.0f }; + jointDef.base.drawScale = 2.0f; + jointDef.enableLimit = m_enableLimit; + jointDef.lowerAngle = B3_DEG_TO_RAD * m_lowerDegrees; + jointDef.upperAngle = B3_DEG_TO_RAD * m_upperDegrees; + jointDef.enableSpring = m_enableSpring; + jointDef.hertz = m_hertz; + jointDef.dampingRatio = m_dampingRatio; + jointDef.enableMotor = m_enableMotor; + jointDef.maxMotorTorque = m_motorTorque; + jointDef.motorSpeed = m_motorSpeed; + + m_jointId = b3CreateRevoluteJoint( m_worldId, &jointDef ); + } + + void UpdateUI() override + { + float height = 320.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 300.0f, height ) ); + + ImGui::Begin( "Revolute Joint", nullptr, ImGuiWindowFlags_NoResize ); + + if ( ImGui::Checkbox( "Limit", &m_enableLimit ) ) + { + b3RevoluteJoint_EnableLimit( m_jointId, m_enableLimit ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( m_enableLimit ) + { + if ( ImGui::SliderFloat( "Lower Angle", &m_lowerDegrees, -180.0f, 180.0f, "%.0f" ) ) + { + m_lowerDegrees = b3MinFloat( m_lowerDegrees, m_upperDegrees ); + b3RevoluteJoint_SetLimits( m_jointId, B3_DEG_TO_RAD * m_lowerDegrees, B3_DEG_TO_RAD * m_upperDegrees ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Upper Angle", &m_upperDegrees, -180.0f, 180.0f, "%.0f" ) ) + { + m_upperDegrees = b3MaxFloat( m_upperDegrees, m_lowerDegrees ); + b3RevoluteJoint_SetLimits( m_jointId, B3_DEG_TO_RAD * m_lowerDegrees, B3_DEG_TO_RAD * m_upperDegrees ); + b3Joint_WakeBodies( m_jointId ); + } + } + + if ( ImGui::Checkbox( "Motor", &m_enableMotor ) ) + { + b3RevoluteJoint_EnableMotor( m_jointId, m_enableMotor ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( m_enableMotor ) + { + if ( ImGui::SliderFloat( "Max Torque", &m_motorTorque, 0.0f, 50000.0f, "%.0f" ) ) + { + b3RevoluteJoint_SetMaxMotorTorque( m_jointId, m_motorTorque ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Speed", &m_motorSpeed, -10.0f, 10.0f, "%.0f" ) ) + { + b3RevoluteJoint_SetMotorSpeed( m_jointId, m_motorSpeed ); + b3Joint_WakeBodies( m_jointId ); + } + } + + if ( ImGui::Checkbox( "Spring", &m_enableSpring ) ) + { + b3RevoluteJoint_EnableSpring( m_jointId, m_enableSpring ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( m_enableSpring ) + { + if ( ImGui::SliderFloat( "Hertz", &m_hertz, 0.0f, 10.0f, "%.1f" ) ) + { + b3RevoluteJoint_SetSpringHertz( m_jointId, m_hertz ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Damping", &m_dampingRatio, 0.0f, 2.0f, "%.1f" ) ) + { + b3RevoluteJoint_SetSpringDampingRatio( m_jointId, m_dampingRatio ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Rotation", &m_targetAngle, -180.0f, 180.0f, "%.0f" ) ) + { + b3RevoluteJoint_SetTargetAngle( m_jointId, B3_DEG_TO_RAD * m_targetAngle ); + b3Joint_WakeBodies( m_jointId ); + } + } + + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + + b3MassData massData = b3Body_GetMassData( m_bodyId ); + b3Vec3 angularVelocity = b3Body_GetAngularVelocity( m_bodyId ); + b3Vec3 linearVelocity = b3Body_GetLinearVelocity( m_bodyId ); + float kineticEnergy = 0.5f * b3Dot( angularVelocity, b3MulMV( massData.inertia, angularVelocity ) ); + kineticEnergy += 0.5f * massData.mass * b3Dot( linearVelocity, linearVelocity ); + b3Vec3 center = b3Body_GetWorldCenterOfMass( m_bodyId ); + b3Vec3 gravity = b3World_GetGravity( m_worldId ); + float potentialEnergy = -massData.mass * center.y * gravity.y; + DrawTextLine( "kinetic energy = %g", kineticEnergy ); + DrawTextLine( "potential energy = %g", potentialEnergy ); + DrawTextLine( "total energy = %g", kineticEnergy + potentialEnergy ); + } + + static Sample* Create( SampleContext* context ) + { + return new RevoluteJoint( context ); + } + + b3BodyId m_bodyId; + b3JointId m_jointId; + float m_targetAngle; + float m_motorSpeed; + float m_motorTorque; + float m_hertz; + float m_dampingRatio; + float m_lowerDegrees; + float m_upperDegrees; + bool m_enableSpring; + bool m_enableMotor; + bool m_enableLimit; +}; + +static int sampleRevoluteJoint = SampleManager::Register( "Joints", "Revolute", RevoluteJoint::Create ); + +class WeldJoint : public Sample +{ +public: + explicit WeldJoint( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 15.0f, { 0.0f, 2.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 4.0f, 0.0f }; + bodyDef.gravityScale = 0.0f; + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + b3BoxHull box = b3MakeBoxHull( 0.5f, 1.5f, 0.25f ); + b3CreateHullShape( m_bodyId, &shapeDef, &box.base ); + + b3WeldJointDef jointDef = b3DefaultWeldJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = m_bodyId; + jointDef.base.localFrameA.p = { 0.0f, 6.5f, 0.0f }; + jointDef.base.localFrameB.p = { 0.0f, 1.5f, 0.0f }; + jointDef.base.constraintHertz = 240.0f; + jointDef.linearHertz = m_linearHertz; + jointDef.linearDampingRatio = m_linearDampingRatio; + jointDef.angularHertz = m_angularHertz; + jointDef.angularDampingRatio = m_angularDampingRatio; + jointDef.base.drawScale = 2.0f; + + m_jointId = b3CreateWeldJoint( m_worldId, &jointDef ); + } + + void UpdateUI() override + { + float height = 150.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 350.0f, height ) ); + + ImGui::Begin( "Weld Joint", nullptr, ImGuiWindowFlags_NoResize ); + + ImGui::PushItemWidth( 200.0f ); + + if ( ImGui::SliderFloat( "Linear Hertz", &m_linearHertz, 0.0f, 10.0f, "%.1f" ) ) + { + b3WeldJoint_SetLinearHertz( m_jointId, m_linearHertz ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Linear Damping", &m_linearDampingRatio, 0.0f, 2.0f, "%.1f" ) ) + { + b3WeldJoint_SetLinearDampingRatio( m_jointId, m_linearDampingRatio ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Angular Hertz", &m_angularHertz, 0.0f, 10.0f, "%.1f" ) ) + { + b3WeldJoint_SetAngularHertz( m_jointId, m_angularHertz ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Angular Damping", &m_angularDampingRatio, 0.0f, 2.0f, "%.1f" ) ) + { + b3WeldJoint_SetAngularDampingRatio( m_jointId, m_angularDampingRatio ); + b3Joint_WakeBodies( m_jointId ); + } + + ImGui::PopItemWidth(); + + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + } + + static Sample* Create( SampleContext* context ) + { + return new WeldJoint( context ); + } + + b3BodyId m_bodyId; + b3JointId m_jointId; + float m_linearHertz = 0.0f; + float m_linearDampingRatio = 0.0f; + float m_angularHertz = 2.0f; + float m_angularDampingRatio = 0.7f; +}; + +static int sampleWeldJoint = SampleManager::Register( "Joints", "Weld", WeldJoint::Create ); + +class WheelJoint : public Sample +{ +public: + explicit WheelJoint( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 25.0f, 20.0f, 7.0f, { 0.0f, 2.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + m_spinSpeed = 0.0f; + m_maxSpinTorque = 20.0f; + m_suspensionHertz = 2.0f; + m_suspensionDampingRatio = 0.7f; + m_lowerTranslation = -1.0f; + m_upperTranslation = 1.0f; + m_enableSuspension = false; + m_enableSpinMotor = false; + m_enableSuspensionLimit = false; + + m_enableSteering = false; + m_steeringHertz = 1.0f; + m_steeringDampingRatio = 0.7f; + m_enableSteeringLimit = false; + m_lowerSteeringDegrees = -45.0f; + m_upperSteeringDegrees = 45.0f; + m_maxSteeringTorque = 20.0f; + m_targetSteeringDegrees = 0.0f; + + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 2.0f, 0.0f }; + bodyDef.rotation = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisY, b3Vec3_axisZ ); + // bodyDef.gravityScale = 0.0f; + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + b3Hull* hull = b3CreateCylinder( 0.25f, 0.4f, 0.0f, 12 ); + // b3BoxHull box = b3MakeBoxHull( 0.5f, 1.5f, 0.25f ); + b3CreateHullShape( m_bodyId, &shapeDef, hull ); + b3DestroyHull( hull ); + + b3WheelJointDef jointDef = b3DefaultWheelJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = m_bodyId; + jointDef.base.localFrameA.p = { 0.0f, 3.0f, 0.0f }; + jointDef.base.localFrameA.q = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisX, b3Vec3_axisY ); + jointDef.base.localFrameB.p = { 0.0f, 0.0f, 0.0f }; + jointDef.base.localFrameB.q = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisZ, b3Vec3_axisY ); + jointDef.base.collideConnected = true; + jointDef.enableSuspensionLimit = m_enableSuspensionLimit; + jointDef.lowerSuspensionLimit = m_lowerTranslation; + jointDef.upperSuspensionLimit = m_upperTranslation; + jointDef.enableSuspensionSpring = m_enableSuspension; + jointDef.suspensionHertz = m_suspensionHertz; + jointDef.suspensionDampingRatio = m_suspensionDampingRatio; + jointDef.enableSpinMotor = m_enableSpinMotor; + jointDef.maxSpinTorque = m_maxSpinTorque; + jointDef.spinSpeed = m_spinSpeed; + jointDef.enableSteering = m_enableSteering; + jointDef.steeringHertz = m_steeringHertz; + jointDef.steeringDampingRatio = m_steeringDampingRatio; + jointDef.targetSteeringAngle = B3_PI / 180.0f * m_targetSteeringDegrees; + jointDef.maxSteeringTorque = m_maxSteeringTorque; + jointDef.enableSteeringLimit = m_enableSteeringLimit; + jointDef.lowerSteeringLimit = B3_PI / 180.0f * m_lowerSteeringDegrees; + jointDef.upperSteeringLimit = B3_PI / 180.0f * m_upperSteeringDegrees; + + m_jointId = b3CreateWheelJoint( m_worldId, &jointDef ); + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 30.0f * fontSize; + ImGui::SetNextWindowPos( { 1.0f * fontSize, m_camera->m_height - height - 3.0f * fontSize }, ImGuiCond_Once ); + ImGui::SetNextWindowSize( { 25.0f * fontSize, height } ); + + ImGui::Begin( "Wheel Joint", nullptr, ImGuiWindowFlags_NoResize ); + + if ( ImGui::Checkbox( "Suspension Limit", &m_enableSuspensionLimit ) ) + { + b3WheelJoint_EnableSuspensionLimit( m_jointId, m_enableSuspensionLimit ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( m_enableSuspensionLimit ) + { + if ( ImGui::SliderFloat( "Lower Translation", &m_lowerTranslation, -10.0f, 10.0f, "%.1f" ) ) + { + m_lowerTranslation = b3MinFloat( m_lowerTranslation, m_upperTranslation ); + b3WheelJoint_SetSuspensionLimits( m_jointId, m_lowerTranslation, m_upperTranslation ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Upper Translation", &m_upperTranslation, -10.0f, 10.0f, "%.1f" ) ) + { + m_upperTranslation = b3MaxFloat( m_upperTranslation, m_lowerTranslation ); + b3WheelJoint_SetSuspensionLimits( m_jointId, m_lowerTranslation, m_upperTranslation ); + b3Joint_WakeBodies( m_jointId ); + } + } + + if ( ImGui::Checkbox( "Motor", &m_enableSpinMotor ) ) + { + b3WheelJoint_EnableSpinMotor( m_jointId, m_enableSpinMotor ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( m_enableSpinMotor ) + { + if ( ImGui::SliderFloat( "Max Torque", &m_maxSpinTorque, 0.0f, 100.0f, "%.0f" ) ) + { + b3WheelJoint_SetMaxSpinTorque( m_jointId, m_maxSpinTorque ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Speed", &m_spinSpeed, -10.0f, 10.0f, "%.0f" ) ) + { + b3WheelJoint_SetSpinMotorSpeed( m_jointId, m_spinSpeed ); + b3Joint_WakeBodies( m_jointId ); + } + } + + if ( ImGui::Checkbox( "Suspension", &m_enableSuspension ) ) + { + b3WheelJoint_EnableSuspension( m_jointId, m_enableSuspension ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( m_enableSuspension ) + { + if ( ImGui::SliderFloat( "Suspension Hertz", &m_suspensionHertz, 0.0f, 10.0f, "%.1f" ) ) + { + b3WheelJoint_SetSuspensionHertz( m_jointId, m_suspensionHertz ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Suspension Damping", &m_suspensionDampingRatio, 0.0f, 2.0f, "%.1f" ) ) + { + b3WheelJoint_SetSuspensionDampingRatio( m_jointId, m_suspensionDampingRatio ); + b3Joint_WakeBodies( m_jointId ); + } + } + + if ( ImGui::Checkbox( "Steering", &m_enableSteering ) ) + { + b3WheelJoint_EnableSteering( m_jointId, m_enableSteering ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( m_enableSteering ) + { + if ( ImGui::SliderFloat( "Steering Hertz", &m_steeringHertz, 0.0f, 10.0f, "%.1f" ) ) + { + b3WheelJoint_SetSteeringHertz( m_jointId, m_steeringHertz ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Steering Damping", &m_steeringDampingRatio, 0.0f, 2.0f, "%.1f" ) ) + { + b3WheelJoint_SetSuspensionDampingRatio( m_jointId, m_suspensionDampingRatio ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Steering Degrees", &m_targetSteeringDegrees, -90.0f, 90.0f, "%.0f" ) ) + { + b3WheelJoint_SetTargetSteeringAngle( m_jointId, m_targetSteeringDegrees * B3_PI / 180.0f ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::Checkbox( "Steering Limit", &m_enableSteeringLimit ) ) + { + b3WheelJoint_EnableSteeringLimit( m_jointId, m_enableSteeringLimit ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( m_enableSteeringLimit ) + { + if ( ImGui::SliderFloat( "Lower Degrees", &m_lowerSteeringDegrees, -90.0f, 0.0f, "%.0f" ) ) + { + b3WheelJoint_SetSteeringLimits( m_jointId, B3_PI / 180.0f * m_lowerSteeringDegrees, + B3_PI / 180.0f * m_upperSteeringDegrees ); + b3Joint_WakeBodies( m_jointId ); + } + + if ( ImGui::SliderFloat( "Upper Degrees", &m_upperSteeringDegrees, 0.0f, 90.0f, "%.0f" ) ) + { + b3WheelJoint_SetSteeringLimits( m_jointId, B3_PI / 180.0f * m_lowerSteeringDegrees, + B3_PI / 180.0f * m_upperSteeringDegrees ); + b3Joint_WakeBodies( m_jointId ); + } + } + } + + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + + float angle = b3WheelJoint_GetSteeringAngle( m_jointId ); + DrawTextLine( "steering degrees = %.1f", 180.0f / B3_PI * angle ); + + b3Transform transform = b3Transform_identity; + transform.p.y += 0.05f; + DrawTransform( m_scene, transform, 2.0f ); + } + + static Sample* Create( SampleContext* context ) + { + return new WheelJoint( context ); + } + + b3BodyId m_bodyId; + b3JointId m_jointId; + float m_spinSpeed; + float m_maxSpinTorque; + float m_suspensionHertz; + float m_suspensionDampingRatio; + float m_lowerTranslation; + float m_upperTranslation; + bool m_enableSuspension; + bool m_enableSpinMotor; + bool m_enableSuspensionLimit; + bool m_enableSteering; + float m_steeringHertz; + float m_steeringDampingRatio; + bool m_enableSteeringLimit; + float m_lowerSteeringDegrees; + float m_upperSteeringDegrees; + float m_maxSteeringTorque; + float m_targetSteeringDegrees; +}; + +static int sampleWheelJoint = SampleManager::Register( "Joints", "Wheel", WheelJoint::Create ); + +class BallAndChain : public Sample +{ +public: + explicit BallAndChain( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 180.0f, 15.0f, 50.0f, { 0.0f, -20.0f, 0.0f } ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef ); + + float linkRadius = 0.125f; + float linkExtent = 0.5f; + b3Capsule capsule = { { -linkExtent, 0.0f, 0.0f }, { linkExtent, 0.0f, 0.0f }, linkRadius }; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + int linkCount = 32; + + bodyDef.type = b3_dynamicBody; + b3BodyId parent = groundBody; + b3SphericalJointDef jointDef = b3DefaultSphericalJointDef(); + jointDef.base.localFrameA = b3Transform_identity; + jointDef.base.localFrameB = { { -linkExtent, 0.0f, 0.0f }, b3Quat_identity }; + jointDef.enableMotor = true; + jointDef.maxMotorTorque = 10.0f; + + for ( int i = 0; i < linkCount; ++i ) + { + bodyDef.position = { ( 1.0f + 2.0f * i ) * linkExtent, 0.0f, 0.0f }; + b3BodyId childId = b3CreateBody( m_worldId, &bodyDef ); + + b3CreateCapsuleShape( childId, &shapeDef, &capsule ); + + jointDef.base.bodyIdA = parent; + jointDef.base.bodyIdB = childId; + b3CreateSphericalJoint( m_worldId, &jointDef ); + + jointDef.base.localFrameA = { { linkExtent, 0.0f, 0.0f }, b3Quat_identity }; + parent = childId; + } + + float sphereRadius = 2.0f; + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, sphereRadius }; + + bodyDef.position = { ( 1.0f + 2.0f * linkCount ) * linkExtent + sphereRadius - linkExtent, 0.0f, 0.0f }; + + b3BodyId childId = b3CreateBody( m_worldId, &bodyDef ); + + b3CreateSphereShape( childId, &shapeDef, &sphere ); + jointDef.base.bodyIdA = parent; + jointDef.base.bodyIdB = childId; + jointDef.base.localFrameB = { { -sphereRadius, 0.0f, 0.0f }, b3Quat_identity }; + b3CreateSphericalJoint( m_worldId, &jointDef ); + } + + static Sample* Create( SampleContext* context ) + { + return new BallAndChain( context ); + } +}; + +static int sampleBallAndChain = SampleManager::Register( "Joints", "Ball and Chain", BallAndChain::Create ); + +class Door : public Sample +{ +public: + explicit Door( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 15.0f, { 0.0f, 2.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + m_groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3CreateHullShape( m_groundId, &shapeDef, &groundBox.base ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 1.5f, 0.0f }; + bodyDef.gravityScale = 2.0f; + m_doorId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 1000.0f; + + b3BoxHull box = b3MakeBoxHull( 0.75f, 1.5f, 0.1f ); + b3CreateHullShape( m_doorId, &shapeDef, &box.base ); + } + + //{ + // b3BoxHull cube = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + // b3BodyDef bodyDef = b3DefaultBodyDef(); + // bodyDef.name = "cube"; + // bodyDef.type = b3_dynamicBody; + // bodyDef.position = { 0.0f, 2.0f, 0.0f }; + // bodyDef.gravityScale = 2.0f; + // b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + // b3ShapeDef shapeDef = b3DefaultShapeDef(); + // b3CreateHullShape( bodyId, &shapeDef, &cube.base ); + //} + + m_magnitude = 50000.0f; + m_twoJoints = true; + m_constraintHertz = 120.0f; + m_constraintDampingRatio = 0.0f; + + CreateJoints(); + } + + void CreateJoints() + { + if ( b3Joint_IsValid( m_jointId1 ) ) + { + b3DestroyJoint( m_jointId1, false ); + m_jointId1 = b3_nullJointId; + } + + if ( b3Joint_IsValid( m_jointId2 ) ) + { + b3DestroyJoint( m_jointId2, false ); + m_jointId2 = b3_nullJointId; + } + + b3Quat axisQuat = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisZ, b3Vec3_axisY ); + + { + b3RevoluteJointDef jointDef = b3DefaultRevoluteJointDef(); + jointDef.base.bodyIdA = m_groundId; + jointDef.base.bodyIdB = m_doorId; + jointDef.base.localFrameA.p = { -0.75f, 1.0f, 0.0f }; + jointDef.base.localFrameA.q = axisQuat; + jointDef.base.localFrameB.p = { -0.75f, -1.5f, 0.0f }; + jointDef.base.localFrameB.q = axisQuat; + jointDef.base.constraintHertz = m_constraintHertz; + jointDef.base.constraintDampingRatio = m_constraintDampingRatio; + jointDef.enableLimit = true; + jointDef.lowerAngle = B3_DEG_TO_RAD * -90.0f; + jointDef.upperAngle = B3_DEG_TO_RAD * 90.0f; + jointDef.enableSpring = true; + jointDef.hertz = 1.0f; + jointDef.dampingRatio = 0.5f; + jointDef.enableMotor = false; + jointDef.maxMotorTorque = 100.0f; + jointDef.motorSpeed = 0.0f; + jointDef.base.drawScale = 2.0f; + + m_jointId1 = b3CreateRevoluteJoint( m_worldId, &jointDef ); + } + + if ( m_twoJoints ) + { + b3RevoluteJointDef jointDef = b3DefaultRevoluteJointDef(); + jointDef.base.bodyIdA = m_groundId; + jointDef.base.bodyIdB = m_doorId; + jointDef.base.localFrameA.p = { -0.75f, 4.0f, 0.0f }; + jointDef.base.localFrameA.q = axisQuat; + jointDef.base.localFrameB.p = { -0.75f, 1.5f, 0.0f }; + jointDef.base.localFrameB.q = axisQuat; + jointDef.base.constraintHertz = m_constraintHertz; + jointDef.base.constraintDampingRatio = m_constraintDampingRatio; + jointDef.enableLimit = true; + jointDef.lowerAngle = B3_DEG_TO_RAD * -90.0f; + jointDef.upperAngle = B3_DEG_TO_RAD * 90.0f; + jointDef.enableSpring = true; + jointDef.hertz = 1.0f; + jointDef.dampingRatio = 0.5f; + jointDef.enableMotor = false; + jointDef.maxMotorTorque = 100.0f; + jointDef.motorSpeed = 0.0f; + jointDef.base.drawScale = 2.0f; + + m_jointId2 = b3CreateRevoluteJoint( m_worldId, &jointDef ); + } + } + + void MouseDown( b3Vec2 p, int button, int modifiers ) override + { + if ( button == 0 && modifiers == 2 ) + { + PickRay pickRay = m_camera->BuildPickRay( p.x, p.y ); + + b3RayResult result = b3World_CastRayClosest( m_worldId, pickRay.origin, pickRay.translation, b3DefaultQueryFilter() ); + + if ( result.hit ) + { + b3BodyId bodyId = b3Shape_GetBody( result.shapeId ); + + b3Vec3 impulse = m_magnitude * b3Normalize( pickRay.translation ); + b3Body_ApplyLinearImpulse( bodyId, impulse, result.point, true ); + } + } + else + { + Sample::MouseDown( p, button, modifiers ); + } + } + + void UpdateUI() override + { + float height = 220.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 350.0f, height ) ); + + ImGui::Begin( "Door", nullptr, ImGuiWindowFlags_NoResize ); + + ImGui::PushItemWidth( 200.0f ); + + if ( ImGui::Button( "impulse" ) ) + { + b3Vec3 p = b3Body_GetWorldPoint( m_doorId, { 0.75f, 0.0f, 0.0f } ); + b3Body_ApplyLinearImpulse( m_doorId, { 0.0f, 0.0f, -m_magnitude }, p, true ); + m_translationError1 = 0.0f; + m_translationError2 = 0.0f; + } + + ImGui::SliderFloat( "magnitude", &m_magnitude, 1000.0f, 100000.0f, "%.0f" ); + + if ( ImGui::Checkbox( "limit", &m_enableLimit ) ) + { + b3RevoluteJoint_EnableLimit( m_jointId1, m_enableLimit ); + + if ( b3Joint_IsValid( m_jointId2 ) ) + { + b3RevoluteJoint_EnableLimit( m_jointId2, m_enableLimit ); + } + } + + if ( ImGui::Checkbox( "two joints", &m_twoJoints ) ) + { + CreateJoints(); + } + + if ( ImGui::SliderFloat( "hertz", &m_constraintHertz, 15.0f, 240.0f, "%.0f" ) ) + { + b3Joint_SetConstraintTuning( m_jointId1, m_constraintHertz, m_constraintDampingRatio ); + + if ( B3_IS_NON_NULL( m_jointId2 ) ) + { + b3Joint_SetConstraintTuning( m_jointId2, m_constraintHertz, m_constraintDampingRatio ); + } + } + + if ( ImGui::SliderFloat( "damping", &m_constraintDampingRatio, 0.0f, 10.0f, "%.1f" ) ) + { + b3Joint_SetConstraintTuning( m_jointId1, m_constraintHertz, m_constraintDampingRatio ); + + if ( B3_IS_NON_NULL( m_jointId2 ) ) + { + b3Joint_SetConstraintTuning( m_jointId2, m_constraintHertz, m_constraintDampingRatio ); + } + } + + ImGui::PopItemWidth(); + + ImGui::End(); + } + + void Step() override + { + Sample::Step(); + + b3Vec3 p = b3Body_GetWorldPoint( m_doorId, { 0.75f, 0.0f, 0.0f } ); + DrawPoint( m_scene, p, 10.0f, b3_colorDarkKhaki ); + + DrawTransform( m_scene, b3Transform_identity, 1.0f ); + + float translationError1 = b3Joint_GetLinearSeparation( m_jointId1 ); + m_translationError1 = b3MaxFloat( m_translationError1, translationError1 ); + DrawTextLine( "translation error 1 = %g", m_translationError1 ); + + if ( B3_IS_NON_NULL( m_jointId2 ) ) + { + float translationError2 = b3Joint_GetLinearSeparation( m_jointId2 ); + m_translationError2 = b3MaxFloat( m_translationError2, translationError2 ); + DrawTextLine( "translation error 2 = %g", m_translationError2 ); + } + } + + static Sample* Create( SampleContext* context ) + { + return new Door( context ); + } + + b3BodyId m_groundId; + b3BodyId m_doorId; + b3JointId m_jointId1; + b3JointId m_jointId2; + float m_magnitude; + float m_translationError1; + float m_translationError2; + float m_constraintHertz; + float m_constraintDampingRatio; + bool m_enableLimit; + bool m_twoJoints; +}; + +static int sampleDoor = SampleManager::Register( "Joints", "Door", Door::Create ); + +// A suspension bridge +class Bridge : public Sample +{ +public: + explicit Bridge( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 20.0f, 35.0, { 0.0f, 10.0f, 0.0f } ); + } + + b3BodyId groundId = b3_nullBodyId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + groundId = b3CreateBody( m_worldId, &bodyDef ); + } + + { + float a = 0.125f; + + b3BoxHull box = b3MakeBoxHull( a, 0.125f, 0.5f ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 20.0f; + + b3SphericalJointDef jointDef = b3DefaultSphericalJointDef(); + // b3RevoluteJointDef jointDef = b3DefaultRevoluteJointDef(); + jointDef.base.constraintHertz = 1000.0f; + jointDef.enableSpring = true; + jointDef.hertz = 2.0f; + jointDef.dampingRatio = 1.0f; + + m_gravityScale = 1.0f; + + float xbase = -160.0f * a; + + b3BodyId prevBodyId = groundId; + for ( int i = 0; i < m_count; ++i ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { xbase + a * ( 1.0f + 2.0f * i ), 20.0f }; + bodyDef.linearDamping = 0.1f; + bodyDef.angularDamping = 0.1f; + m_bodyIds[i] = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( m_bodyIds[i], &shapeDef, &box.base ); + + { + b3Vec3 pivot = { xbase + 2.0f * a * i, 20.0f, -0.5f }; + jointDef.base.bodyIdA = prevBodyId; + jointDef.base.bodyIdB = m_bodyIds[i]; + jointDef.base.localFrameA.p = b3Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); + jointDef.base.localFrameB.p = b3Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); + b3CreateSphericalJoint( m_worldId, &jointDef ); + // b3CreateRevoluteJoint( m_worldId, &jointDef ); + } + + { + b3Vec3 pivot = { xbase + 2.0f * a * i, 20.0f, 0.5f }; + jointDef.base.bodyIdA = prevBodyId; + jointDef.base.bodyIdB = m_bodyIds[i]; + jointDef.base.localFrameA.p = b3Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); + jointDef.base.localFrameB.p = b3Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); + b3CreateSphericalJoint( m_worldId, &jointDef ); + // b3CreateRevoluteJoint( m_worldId, &jointDef ); + } + + prevBodyId = m_bodyIds[i]; + } + + { + b3Vec3 pivot = { xbase + 2.0f * a * m_count, 20.0f, -0.5f }; + jointDef.base.bodyIdA = prevBodyId; + jointDef.base.bodyIdB = groundId; + jointDef.base.localFrameA.p = b3Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); + jointDef.base.localFrameB.p = b3Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); + b3CreateSphericalJoint( m_worldId, &jointDef ); + // b3CreateRevoluteJoint( m_worldId, &jointDef ); + } + + { + b3Vec3 pivot = { xbase + 2.0f * a * m_count, 20.0f, 0.5f }; + jointDef.base.bodyIdA = prevBodyId; + jointDef.base.bodyIdB = groundId; + jointDef.base.localFrameA.p = b3Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); + jointDef.base.localFrameB.p = b3Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); + b3CreateSphericalJoint( m_worldId, &jointDef ); + // b3CreateRevoluteJoint( m_worldId, &jointDef ); + } + } + } + + void UpdateUI() override + { + float height = 80.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_context->camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); + + ImGui::Begin( "Bridge", nullptr, ImGuiWindowFlags_NoResize ); + + // Slider takes half the window + ImGui::PushItemWidth( ImGui::GetWindowWidth() * 0.5f ); + + if ( ImGui::SliderFloat( "Gravity scale", &m_gravityScale, -1.0f, 1.0f, "%.1f" ) ) + { + for ( int i = 0; i < m_count; ++i ) + { + b3Body_SetGravityScale( m_bodyIds[i], m_gravityScale ); + } + } + + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + + DrawGrid( m_scene, 20 ); + } + + static Sample* Create( SampleContext* context ) + { + return new Bridge( context ); + } + + static constexpr int m_count = 150; + b3BodyId m_bodyIds[m_count]; + float m_gravityScale; +}; + +static int sampleBridgeIndex = SampleManager::Register( "Joints", "Bridge", Bridge::Create ); + +// This test ensures joints work correctly with bodies that have motion locks +class MotionLocks : public Sample +{ +public: + explicit MotionLocks( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 30.0f, 40.0f, { 0.0f, 5.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + groundId = b3CreateBody( m_worldId, &bodyDef ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull box = b3MakeTransformedBoxHull( 20.0f, 1.0f, 20.0f, { { 0.0f, -1.0f, 0.0f }, b3Quat_identity } ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + + m_motionLocks = {}; + + for ( int i = 0; i < m_capacity; ++i ) + { + m_bodyIds[i] = b3_nullBodyId; + } + + b3Vec3 position = { -12.5f, 10.0, 0.0f }; + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.enableSleep = false; + + b3BoxHull box = b3MakeBoxHull( 1.0f, 1.0f, 0.5f ); + + m_count = 0; + + float forceThreshold = 20000.0f; + float torqueThreshold = 10000.0f; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 1.0f; + + // distance joint + { + assert( m_count < m_capacity ); + + bodyDef.position = position; + m_bodyIds[m_count] = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( m_bodyIds[m_count], &shapeDef, &box.base ); + + float length = 2.0f; + b3Vec3 pivot1 = { position.x, position.y + 1.0f + length, 0.0f }; + b3Vec3 pivot2 = { position.x, position.y + 1.0f, 0.0f }; + b3DistanceJointDef jointDef = b3DefaultDistanceJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = m_bodyIds[m_count]; + jointDef.base.localFrameA.p = b3Body_GetLocalPoint( jointDef.base.bodyIdA, pivot1 ); + jointDef.base.localFrameB.p = b3Body_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)m_count; + b3CreateDistanceJoint( m_worldId, &jointDef ); + } + + position.x += 5.0f; + ++m_count; + + // motor joint +#if 0 + { + assert( m_bodyCount < e_count ); + + bodyDef.position = position; + m_bodyIds[m_bodyCount] = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( m_bodyIds[m_bodyCount], &shapeDef, &box.base ); + + b3MotorJointDef jointDef = b3DefaultMotorJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = m_bodyIds[m_bodyCount]; + jointDef.base.localFrameA.p = position; + jointDef.maxForce = 1000.0f; + jointDef.maxTorque = 20.0f; + jointDef.base.forceThreshold = forceThreshold; + jointDef.base.torqueThreshold = torqueThreshold; + jointDef.base.collideConnected = true; + jointDef.base.userData = (void*)(intptr_t)m_bodyCount; + b3CreateMotorJoint( m_worldId, &jointDef ); + } + + position.x += 5.0f; + ++m_count; +#endif + + // prismatic joint + { + assert( m_count < m_capacity ); + + bodyDef.position = position; + m_bodyIds[m_count] = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( m_bodyIds[m_count], &shapeDef, &box.base ); + + b3Vec3 pivot = { position.x - 1.0f, position.y, 0.0f }; + b3PrismaticJointDef jointDef = b3DefaultPrismaticJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = m_bodyIds[m_count]; + jointDef.base.localFrameA.p = b3Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); + jointDef.base.localFrameB.p = b3Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); + jointDef.base.forceThreshold = forceThreshold; + jointDef.base.torqueThreshold = torqueThreshold; + jointDef.base.collideConnected = true; + jointDef.base.userData = (void*)(intptr_t)m_count; + b3CreatePrismaticJoint( m_worldId, &jointDef ); + } + + position.x += 5.0f; + ++m_count; + + // revolute joint + { + assert( m_count < m_capacity ); + + bodyDef.position = position; + m_bodyIds[m_count] = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( m_bodyIds[m_count], &shapeDef, &box.base ); + + b3Vec3 pivot = { position.x - 1.0f, position.y, 0.0f }; + b3RevoluteJointDef jointDef = b3DefaultRevoluteJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = m_bodyIds[m_count]; + jointDef.base.localFrameA.p = b3Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); + jointDef.base.localFrameB.p = b3Body_GetLocalPoint( jointDef.base.bodyIdB, pivot ); + jointDef.base.forceThreshold = forceThreshold; + jointDef.base.torqueThreshold = torqueThreshold; + jointDef.base.collideConnected = true; + jointDef.base.userData = (void*)(intptr_t)m_count; + b3CreateRevoluteJoint( m_worldId, &jointDef ); + } + + position.x += 5.0f; + ++m_count; + + // weld joint + { + assert( m_count < m_capacity ); + + bodyDef.position = position; + m_bodyIds[m_count] = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( m_bodyIds[m_count], &shapeDef, &box.base ); + + b3Vec3 pivot = { position.x - 1.0f, position.y, 0.0f }; + b3WeldJointDef jointDef = b3DefaultWeldJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = m_bodyIds[m_count]; + jointDef.base.localFrameA.p = b3Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); + jointDef.base.localFrameB.p = b3Body_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)m_count; + b3CreateWeldJoint( m_worldId, &jointDef ); + } + + position.x += 5.0f; + ++m_count; + + // wheel joint +#if 0 + { + assert( index < e_count ); + + bodyDef.position = position; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + b3Vec3 pivot = { position.x - 1.0f, position.y, 0.0f }; + b3WheelJointDef jointDef = b3DefaultWheelJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameA.p = b3Body_GetLocalPoint( jointDef.base.bodyIdA, pivot ); + jointDef.base.localFrameB.p = b3Body_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; + b3CreateWheelJoint( m_worldId, &jointDef ); + } + + position.x += 5.0f; + ++m_count; +#endif + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 13.0f * fontSize; + ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->m_height - height - 2.0f * fontSize ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 10.0f * fontSize, height ) ); + + ImGui::Begin( "Motion Locks", nullptr, ImGuiWindowFlags_NoResize ); + + if ( ImGui::Checkbox( "Lock Linear X", &m_motionLocks.linearX ) ) + { + for ( int i = 0; i < m_count; ++i ) + { + b3Body_SetMotionLocks( m_bodyIds[i], m_motionLocks ); + b3Body_SetAwake( m_bodyIds[i], true ); + } + } + + if ( ImGui::Checkbox( "Lock Linear Y", &m_motionLocks.linearY ) ) + { + for ( int i = 0; i < m_count; ++i ) + { + b3Body_SetMotionLocks( m_bodyIds[i], m_motionLocks ); + b3Body_SetAwake( m_bodyIds[i], true ); + } + } + + if ( ImGui::Checkbox( "Lock Linear Z", &m_motionLocks.linearZ ) ) + { + for ( int i = 0; i < m_count; ++i ) + { + b3Body_SetMotionLocks( m_bodyIds[i], m_motionLocks ); + b3Body_SetAwake( m_bodyIds[i], true ); + } + } + + if ( ImGui::Checkbox( "Lock Angular X", &m_motionLocks.angularX ) ) + { + for ( int i = 0; i < m_count; ++i ) + { + b3Body_SetMotionLocks( m_bodyIds[i], m_motionLocks ); + b3Body_SetAwake( m_bodyIds[i], true ); + } + } + + if ( ImGui::Checkbox( "Lock Angular Y", &m_motionLocks.angularY ) ) + { + for ( int i = 0; i < m_count; ++i ) + { + b3Body_SetMotionLocks( m_bodyIds[i], m_motionLocks ); + b3Body_SetAwake( m_bodyIds[i], true ); + } + } + + if ( ImGui::Checkbox( "Lock Angular Z", &m_motionLocks.angularZ ) ) + { + for ( int i = 0; i < m_count; ++i ) + { + b3Body_SetMotionLocks( m_bodyIds[i], m_motionLocks ); + b3Body_SetAwake( m_bodyIds[i], true ); + } + } + + ImGui::End(); + + if ( glfwGetKey( m_context->window, GLFW_KEY_L ) == GLFW_PRESS ) + { + b3Body_ApplyLinearImpulseToCenter( m_bodyIds[0], { 100.0f, 0.0f }, true ); + } + } + + void Render() override + { + Sample::Render(); + + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 1.0f ); + } + + static Sample* Create( SampleContext* context ) + { + return new MotionLocks( context ); + } + + static constexpr int m_capacity = 6; + b3BodyId m_bodyIds[m_capacity]; + int m_count; + b3MotionLocks m_motionLocks; +}; + +static int sampleMotionLocks = SampleManager::Register( "Joints", "Motion Locks", MotionLocks::Create ); + +class Driving : public Sample +{ +public: + explicit Driving( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 25.0f, 20.0f, 7.0f, { 0.0f, 2.0f, 0.0f } ); + } + + m_spinSpeed = 30.0f; + m_maxSpinTorque = 5.0f; + m_suspensionHertz = 4.0f; + m_suspensionDampingRatio = 0.7f; + m_lowerTranslation = -0.2f; + m_upperTranslation = 0.2f; + m_steeringHertz = 10.0f; + m_steeringDampingRatio = 0.7f; + m_lowerSteeringDegrees = -45.0f; + m_upperSteeringDegrees = 45.0f; + m_maxSteeringTorque = 5.0f; + m_targetSteeringDegrees = 0.0f; + + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + // bodyDef.position = { 0.0f, -1.0f, 0.0f }; + bodyDef.position = { -20.0f, 0.0f, -20.0f }; + groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + // b3BoxHull groundBox = b3MakeBoxHull( 200.0f, 1.0f, 200.0f ); + // b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + + m_heightField = b3CreateWave( 50.0f, 50.0f, { 4.0f, 2.0f, 4.0f }, 0.02f, 0.04f, false ); + // b3ShapeDef shapeDef = b3DefaultShapeDef(); + // b3SurfaceMaterial materials[3] = b3DefaultSurfaceMaterial(); + // materials[0] = { .friction = 0.6f, .restitution = 0.0f, 0 }; + // materials[1] = { .friction = 0.6f, .restitution = 1.0f, 1 }; + // materials[2] = { .friction = 0.6f, .restitution = 0.0f, 2 }; + // shapeDef.materials = materials; + // shapeDef.materialCount = 3; + + b3CreateHeightFieldShape( groundId, &shapeDef, m_heightField ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + { + bodyDef.position = { 0.0f, 2.5f, 0.0f }; + bodyDef.type = b3_dynamicBody; + m_chassisId = b3CreateBody( m_worldId, &bodyDef ); + + shapeDef.density = 0.5f; + b3BoxHull box = b3MakeBoxHull( 2.0f, 0.5f, 1.0f ); + b3CreateHullShape( m_chassisId, &shapeDef, &box.base ); + } + + // Keep vehicle upright + { + b3ParallelJointDef parallelJointDef = b3DefaultParallelJointDef(); + parallelJointDef.base.bodyIdA = groundId; + parallelJointDef.base.bodyIdB = m_chassisId; + parallelJointDef.base.localFrameA.q = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisZ, b3Vec3_axisY ); + parallelJointDef.base.localFrameB.q = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisZ, b3Vec3_axisY ); + parallelJointDef.base.drawScale = 2.0f; + parallelJointDef.base.collideConnected = true; + parallelJointDef.hertz = 0.5f; + parallelJointDef.dampingRatio = 1.0f; + b3CreateParallelJoint( m_worldId, ¶llelJointDef ); + } + + shapeDef.density = 2.0f; + shapeDef.baseMaterial.friction = 3.0f; + + bodyDef.type = b3_dynamicBody; + bodyDef.allowFastRotation = true; + bodyDef.enableContinuousCollision = false; + bodyDef.rotation = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisY, b3Vec3_axisZ ); + + // b3Hull* hull = b3CreateCylinder( 0.25f, 0.4f, 0.0f, 16 ); + + b3WheelJointDef jointDef = b3DefaultWheelJointDef(); + jointDef.base.bodyIdA = m_chassisId; + jointDef.base.localFrameA.q = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisX, b3Vec3_axisY ); + jointDef.base.localFrameB.q = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisZ, b3Vec3_axisY ); + jointDef.enableSuspensionLimit = true; + jointDef.lowerSuspensionLimit = m_lowerTranslation; + jointDef.upperSuspensionLimit = m_upperTranslation; + jointDef.enableSuspensionSpring = true; + jointDef.suspensionHertz = m_suspensionHertz; + jointDef.suspensionDampingRatio = m_suspensionDampingRatio; + jointDef.enableSpinMotor = true; + jointDef.maxSpinTorque = m_maxSpinTorque; + jointDef.enableSteering = true; + jointDef.steeringHertz = m_steeringHertz; + jointDef.steeringDampingRatio = m_steeringDampingRatio; + jointDef.targetSteeringAngle = 0.0f; + jointDef.maxSteeringTorque = m_maxSteeringTorque; + jointDef.enableSteeringLimit = true; + jointDef.lowerSteeringLimit = B3_PI / 180.0f * m_lowerSteeringDegrees; + jointDef.upperSteeringLimit = B3_PI / 180.0f * m_upperSteeringDegrees; + + b3Sphere sphere = { b3Vec3_zero, 0.4f }; + + { + bodyDef.position = { 1.5f, 2.0f, 0.8f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + // b3CreateHullShape( bodyId, &shapeDef, hull ); + + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameA.p = { 1.5f, -0.5f, 0.8f }; + jointDef.enableSteering = true; + jointDef.enableSpinMotor = false; + m_frontLeftId = b3CreateWheelJoint( m_worldId, &jointDef ); + } + + { + bodyDef.position = { 1.5f, 2.0f, -0.8f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + // b3CreateHullShape( bodyId, &shapeDef, hull ); + + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameA.p = { 1.5f, -0.5f, -0.8f }; + jointDef.enableSteering = true; + jointDef.enableSpinMotor = false; + m_frontRightId = b3CreateWheelJoint( m_worldId, &jointDef ); + } + + { + bodyDef.position = { -1.5f, 2.0f, 0.8f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + // b3CreateHullShape( bodyId, &shapeDef, hull ); + + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameA.p = { -1.5f, -0.5f, 0.8f }; + jointDef.enableSteering = false; + jointDef.enableSpinMotor = true; + m_rearLeftId = b3CreateWheelJoint( m_worldId, &jointDef ); + } + + { + bodyDef.position = { -1.5f, 2.0f, -0.8f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + // b3CreateHullShape( bodyId, &shapeDef, hull ); + + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameA.p = { -1.5f, -0.5f, -0.8f }; + jointDef.enableSteering = false; + jointDef.enableSpinMotor = true; + m_rearRightId = b3CreateWheelJoint( m_worldId, &jointDef ); + } + + // b3DestroyHull( hull ); + + m_camera->m_thirdPerson = true; + glfwSetInputMode( m_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED ); + + m_haveMouseLast = false; + m_mouseLast = { 0.0f, 0.0f }; + m_mouseDelta = { 0.0f, 0.0f }; + } + + ~Driving() override + { + m_camera->m_thirdPerson = false; + glfwSetInputMode( m_window, GLFW_CURSOR, GLFW_CURSOR_NORMAL ); + b3DestroyHeightField( m_heightField ); + } + +#if 0 + void MouseMove( b3Vec2 p ) override + { + if ( m_camera->m_thirdPerson ) + { + if ( m_haveMouseLast == false ) + { + m_mouseLast = p; + m_haveMouseLast = true; + } + else + { + m_mouseDelta = { p.x - m_mouseLast.x, p.y - m_mouseLast.y }; + m_mouseLast = p; + } + + const float sensitivity = 0.05f; + m_camera->m_yaw -= 2.0f * sensitivity * m_mouseDelta.x; + m_camera->m_pitch += sensitivity * m_mouseDelta.y; + m_camera->m_pitch = b3ClampFloat( m_camera->m_pitch, -85.0f, 85.0f ); + } + + Sample::MouseMove( p ); + } +#endif + + void Keyboard( int key, int action, int mods ) override + { + if ( key == GLFW_KEY_T && action == GLFW_PRESS ) + { + ToggleThirdPerson(); + } + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 22.0f * fontSize; + ImGui::SetNextWindowPos( { 1.0f * fontSize, m_camera->m_height - height - 3.0f * fontSize }, ImGuiCond_Once ); + ImGui::SetNextWindowSize( { 25.0f * fontSize, height } ); + + ImGui::Begin( "Driving", nullptr, ImGuiWindowFlags_NoResize ); + + if ( ImGui::SliderFloat( "Lower Translation", &m_lowerTranslation, -10.0f, 10.0f, "%.1f" ) ) + { + m_lowerTranslation = b3MinFloat( m_lowerTranslation, m_upperTranslation ); + b3WheelJoint_SetSuspensionLimits( m_frontLeftId, m_lowerTranslation, m_upperTranslation ); + b3WheelJoint_SetSuspensionLimits( m_frontRightId, m_lowerTranslation, m_upperTranslation ); + b3WheelJoint_SetSuspensionLimits( m_rearLeftId, m_lowerTranslation, m_upperTranslation ); + b3WheelJoint_SetSuspensionLimits( m_rearRightId, m_lowerTranslation, m_upperTranslation ); + } + + if ( ImGui::SliderFloat( "Upper Translation", &m_upperTranslation, -10.0f, 10.0f, "%.1f" ) ) + { + m_upperTranslation = b3MaxFloat( m_upperTranslation, m_lowerTranslation ); + b3WheelJoint_SetSuspensionLimits( m_frontLeftId, m_lowerTranslation, m_upperTranslation ); + b3WheelJoint_SetSuspensionLimits( m_frontRightId, m_lowerTranslation, m_upperTranslation ); + b3WheelJoint_SetSuspensionLimits( m_rearLeftId, m_lowerTranslation, m_upperTranslation ); + b3WheelJoint_SetSuspensionLimits( m_rearRightId, m_lowerTranslation, m_upperTranslation ); + } + + ImGui::SliderFloat( "Max Torque", &m_maxSpinTorque, 0.0f, 100.0f, "%.0f" ); + ImGui::SliderFloat( "Speed", &m_spinSpeed, 0.0f, 100.0f, "%.0f" ); + + if ( ImGui::SliderFloat( "Suspension Hertz", &m_suspensionHertz, 0.0f, 10.0f, "%.1f" ) ) + { + b3WheelJoint_SetSuspensionHertz( m_frontLeftId, m_suspensionHertz ); + b3WheelJoint_SetSuspensionHertz( m_frontRightId, m_suspensionHertz ); + b3WheelJoint_SetSuspensionHertz( m_rearLeftId, m_suspensionHertz ); + b3WheelJoint_SetSuspensionHertz( m_rearRightId, m_suspensionHertz ); + } + + if ( ImGui::SliderFloat( "Suspension Damping", &m_suspensionDampingRatio, 0.0f, 2.0f, "%.1f" ) ) + { + b3WheelJoint_SetSuspensionDampingRatio( m_frontLeftId, m_suspensionDampingRatio ); + b3WheelJoint_SetSuspensionDampingRatio( m_frontRightId, m_suspensionDampingRatio ); + b3WheelJoint_SetSuspensionDampingRatio( m_rearLeftId, m_suspensionDampingRatio ); + b3WheelJoint_SetSuspensionDampingRatio( m_rearRightId, m_suspensionDampingRatio ); + } + + if ( ImGui::SliderFloat( "Steering Hertz", &m_steeringHertz, 0.0f, 10.0f, "%.1f" ) ) + { + b3WheelJoint_SetSteeringHertz( m_frontLeftId, m_steeringHertz ); + b3WheelJoint_SetSteeringHertz( m_frontRightId, m_steeringHertz ); + } + + if ( ImGui::SliderFloat( "Steering Damping", &m_steeringDampingRatio, 0.0f, 2.0f, "%.1f" ) ) + { + b3WheelJoint_SetSteeringDampingRatio( m_frontLeftId, m_steeringDampingRatio ); + b3WheelJoint_SetSteeringDampingRatio( m_frontRightId, m_steeringDampingRatio ); + } + + if ( ImGui::SliderFloat( "Steering Torque", &m_maxSteeringTorque, 0.0f, 20.0f, "%.1f" ) ) + { + b3WheelJoint_SetMaxSteeringTorque( m_frontLeftId, m_maxSteeringTorque ); + b3WheelJoint_SetMaxSteeringTorque( m_frontRightId, m_maxSteeringTorque ); + } + + if ( ImGui::SliderFloat( "Lower Degrees", &m_lowerSteeringDegrees, -90.0f, 0.0f, "%.0f" ) ) + { + b3WheelJoint_SetSteeringLimits( m_frontLeftId, B3_PI / 180.0f * m_lowerSteeringDegrees, + B3_PI / 180.0f * m_upperSteeringDegrees ); + b3WheelJoint_SetSteeringLimits( m_frontRightId, B3_PI / 180.0f * m_lowerSteeringDegrees, + B3_PI / 180.0f * m_upperSteeringDegrees ); + } + + if ( ImGui::SliderFloat( "Upper Degrees", &m_upperSteeringDegrees, 0.0f, 90.0f, "%.0f" ) ) + { + b3WheelJoint_SetSteeringLimits( m_frontLeftId, B3_PI / 180.0f * m_lowerSteeringDegrees, + B3_PI / 180.0f * m_upperSteeringDegrees ); + b3WheelJoint_SetSteeringLimits( m_frontRightId, B3_PI / 180.0f * m_lowerSteeringDegrees, + B3_PI / 180.0f * m_upperSteeringDegrees ); + } + + bool thirdPerson = m_camera->m_thirdPerson; + if ( ImGui::Checkbox( "Third Person (Key: T)", &thirdPerson ) ) + { + ToggleThirdPerson(); + } + + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + + b3Vec3 velocity = b3Body_GetLinearVelocity( m_chassisId ); + b3Quat quat = b3Body_GetRotation( m_chassisId ); + b3Vec3 forward = b3RotateVector( quat, { -1.0f, 0.0f, 0.0f } ); + float speed = b3Dot( velocity, forward ); + DrawTextLine( "speed = %.1f", speed ); + + float leftSpeed = b3WheelJoint_GetSpinSpeed( m_rearLeftId ); + float rightSpeed = b3WheelJoint_GetSpinSpeed( m_rearRightId ); + DrawTextLine( "spin speed = %.1f/%.1f", leftSpeed, rightSpeed ); + + float leftSpinTorque = b3WheelJoint_GetSpinTorque( m_rearLeftId ); + float rightSpinTorque = b3WheelJoint_GetSpinTorque( m_rearRightId ); + DrawTextLine( "spin torque = %.1f/%.1f", leftSpinTorque, rightSpinTorque ); + + float angleLeft = b3WheelJoint_GetSteeringAngle( m_frontLeftId ); + float angleRight = b3WheelJoint_GetSteeringAngle( m_frontRightId ); + DrawTextLine( "steering degrees = %.1f/%.1f", 180.0f / B3_PI * angleLeft, 180.0f / B3_PI * angleRight ); + + float leftSteerTorque = b3WheelJoint_GetSteeringTorque( m_frontLeftId ); + float rightSteerTorque = b3WheelJoint_GetSteeringTorque( m_frontRightId ); + DrawTextLine( "steering torque = %.1f/%.1f", leftSteerTorque, rightSteerTorque ); + + b3Transform transform = b3Transform_identity; + transform.p.y += 0.05f; + DrawTransform( m_scene, transform, 2.0f ); + } + + void Step() override + { + b3Vec2 throttle = { 0.0f, 0.0f }; + + if ( m_camera->m_thirdPerson ) + { + if ( glfwGetKey( m_window, GLFW_KEY_W ) ) + { + throttle.x += 1.0f; + b3Body_SetAwake( m_chassisId, true ); + } + + if ( glfwGetKey( m_window, GLFW_KEY_S ) ) + { + throttle.x -= 1.0f; + b3Body_SetAwake( m_chassisId, true ); + } + + if ( glfwGetKey( m_window, GLFW_KEY_A ) ) + { + throttle.y += 1.0f; + b3Body_SetAwake( m_chassisId, true ); + } + + if ( glfwGetKey( m_window, GLFW_KEY_D ) ) + { + throttle.y -= 1.0f; + b3Body_SetAwake( m_chassisId, true ); + } + } + + float maxSteeringAngle = 0.25f * B3_PI; + b3WheelJoint_SetTargetSteeringAngle( m_frontLeftId, maxSteeringAngle * throttle.y ); + b3WheelJoint_SetTargetSteeringAngle( m_frontRightId, maxSteeringAngle * throttle.y ); + + b3WheelJoint_SetSpinMotorSpeed( m_rearLeftId, -m_spinSpeed * throttle.x ); + b3WheelJoint_SetSpinMotorSpeed( m_rearRightId, -m_spinSpeed * throttle.x ); + + if ( m_camera->m_thirdPerson ) + { + b3Transform transform = b3Body_GetTransform( m_chassisId ); + m_camera->m_pivot = transform.p; + m_camera->UpdateTransform(); + } + + Sample::Step(); + } + + static Sample* Create( SampleContext* context ) + { + return new Driving( context ); + } + + b3HeightField* m_heightField; + b3BodyId m_chassisId; + b3JointId m_frontLeftId; + b3JointId m_frontRightId; + b3JointId m_rearLeftId; + b3JointId m_rearRightId; + + float m_spinSpeed; + float m_maxSpinTorque; + float m_suspensionHertz; + float m_suspensionDampingRatio; + float m_lowerTranslation; + float m_upperTranslation; + float m_steeringHertz; + float m_steeringDampingRatio; + float m_lowerSteeringDegrees; + float m_upperSteeringDegrees; + float m_maxSteeringTorque; + float m_targetSteeringDegrees; + + b3Vec2 m_mouseLast; + b3Vec2 m_mouseDelta; + bool m_haveMouseLast; +}; + +static int sampleDriving = SampleManager::Register( "Joints", "Driving", Driving::Create ); diff --git a/samples/sample_manifold.cpp b/samples/sample_manifold.cpp new file mode 100644 index 0000000..94b934f --- /dev/null +++ b/samples/sample_manifold.cpp @@ -0,0 +1,940 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "GLFW/glfw3.h" +#include "camera.h" +#include "renderer.h" +#include "sample.h" +#include "scene.h" + +#include "box3d/constants.h" + +#include + +class Manifold : public Sample +{ +public: + explicit Manifold( SampleContext* sampleContext ) + : Sample( sampleContext ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 35.0f, 30.0f, 50.0f, { 0.0f, 5.0f, 0.0f } ); + } + + memset( m_points, 0, sizeof( m_points ) ); + m_manifold = {}; + m_manifold.points = m_points; + + { + m_transformA.p = { 3.5f, 0.5f, 0.0f }; + m_transformA.q = b3MakeQuatFromAxisAngle( { 0.0f, 1.0f, 0.0f }, 0.5f * B3_PI ); + } + + { + m_transformB.p = { 0.0f, 1.5f, 3.5f }; + m_transformB.q = b3Quat_identity; + } + + m_simplexCache = {}; + m_satCache = {}; + m_manualFeature = 0; + m_baseTranslation = b3Vec3_zero; + m_baseQuaternion = b3Quat_identity; + m_baseX = 0; + m_baseY = 0; + m_origin = b3Vec3_zero; + m_useCache = false; + m_tracking = false; + m_rotating = false; + } + + void Render() override + { + DrawTextLine( "origin: %g %g %g", m_origin.x, m_origin.y, m_origin.z ); + DrawTextLine( "count = %d", m_manifold.pointCount ); + + DrawTransform( m_scene, b3Transform_identity, 1.0f ); + + if ( m_manifold.pointCount == 0 ) + { + return; + } + + float length = 0.5f * b3GetLengthUnitsPerMeter(); + b3Vec3 normal = b3RotateVector( m_transformA.q, m_manifold.normal ); + + for ( int pointIndex = 0; pointIndex < m_manifold.pointCount; ++pointIndex ) + { + const b3LocalManifoldPoint& manifoldPoint = m_manifold.points[pointIndex]; + + b3Vec3 point = b3TransformPoint( m_transformA, manifoldPoint.point ); + + DrawLine( m_scene, point, point + length * normal, b3_colorWhite ); + + if ( manifoldPoint.separation > 0.0f ) + { + DrawPoint( m_scene, point, 10.0f, b3_colorWhite ); + } + else + { + DrawPoint( m_scene, point, 10.0f, b3_colorYellow ); + } + + DrawWorldString( m_camera, point, b3_colorWhite, " %.3f", manifoldPoint.separation ); + + b3Vec3 perp = b3Perp( normal ); + b3FeaturePair pair = manifoldPoint.pair; + DrawWorldString( m_camera, point + 0.025f * normal + 0.05f * perp, b3_colorPapayaWhip, " %X:%X %X:%X", pair.owner1, + pair.index1, pair.owner2, pair.index2 ); + } + + Sample::Render(); + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 12.0f * fontSize; + ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->m_height - height - 2.0f * fontSize ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 10.0f * fontSize, height ) ); + ImGui::Begin( "Manifold", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + ImGui::Checkbox( "Use cache", &m_useCache ); + if ( m_useCache ) + { + ImGui::RadioButton( "auto", &m_manualFeature, 0 ); + ImGui::RadioButton( "faceA", &m_manualFeature, 1 ); + ImGui::RadioButton( "faceB", &m_manualFeature, 2 ); + ImGui::RadioButton( "edgePair", &m_manualFeature, 3 ); + } + + ImGui::End(); + } + + void MouseDown( b3Vec2 p, int button, int modifiers ) override + { + if ( button == 0 && ( modifiers & GLFW_MOD_ALT ) == 0 ) + { + if ( modifiers & GLFW_MOD_SHIFT ) + { + m_baseX = p.x; + m_baseY = p.y; + m_baseQuaternion = m_transformB.q; + m_rotating = true; + } + else + { + PickRay pickRay = m_camera->BuildPickRay( p.x, p.y ); + m_origin = pickRay.origin + 10.0f * b3Normalize( pickRay.translation ); + m_baseTranslation = m_transformB.p; + m_tracking = true; + } + } + } + + void MouseUp( b3Vec2 p, int button ) override + { + m_tracking = false; + m_rotating = false; + } + + void MouseMove( b3Vec2 p ) override + { + if ( m_tracking ) + { + PickRay pickRay = m_camera->BuildPickRay( p.x, p.y ); + b3Vec3 origin = pickRay.origin + 10.0f * b3Normalize( pickRay.translation ); + m_transformB.p = m_baseTranslation + origin - m_origin; + } + + if ( m_rotating ) + { + int x = p.x; + int y = p.y; + + b3Quat qx = b3MakeQuatFromAxisAngle( b3Vec3_axisY, 0.01f * ( x - m_baseX ) ); + b3Quat qz = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.01f * ( y - m_baseY ) ); + m_transformB.q = b3NormalizeQuat( b3MulQuat( m_baseQuaternion, b3MulQuat( qx, qz ) ) ); + } + } + + static constexpr int m_pointCapacity = 64; + b3LocalManifold m_manifold; + b3LocalManifoldPoint m_points[m_pointCapacity]; + b3Transform m_transformA; + b3Transform m_transformB; + b3Vec3 m_baseTranslation; + b3Quat m_baseQuaternion; + b3Vec3 m_origin; + b3SimplexCache m_simplexCache; + b3SATCache m_satCache; + int m_manualFeature; + int m_baseX; + int m_baseY; + bool m_useCache; + bool m_tracking; + bool m_rotating; +}; + +class TriangleManifold : public Sample +{ +public: + explicit TriangleManifold( SampleContext* sampleContext ) + : Sample( sampleContext ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 35.0f, 30.0f, 50.0f, { 0.0f, 5.0f, 0.0f } ); + } + + m_manifold = {}; + memset( m_points, 0, sizeof( m_points ) ); + m_manifold.points = m_points; + + { + m_transformA.p = { 3.5f, 0.5f, 0.0f }; + m_transformA.q = b3MakeQuatFromAxisAngle( { 0.0f, 1.0f, 0.0f }, 0.5f * B3_PI ); + } + + { + m_transformB.p = { 0.0f, 1.5f, 3.5f }; + m_transformB.q = b3Quat_identity; + } + + m_simplexCache = {}; + m_satCache = {}; + m_baseTranslation = b3Vec3_zero; + m_baseQuaternion = b3Quat_identity; + m_baseX = 0; + m_baseY = 0; + m_origin = b3Vec3_zero; + m_useCache = false; + m_tracking = false; + m_rotating = false; + + m_manualFeature = 0; + } + + void Render() override + { + DrawTextLine( "origin: %g %g %g", m_origin.x, m_origin.y, m_origin.z ); + DrawTextLine( "count = %d", m_manifold.pointCount ); + DrawTextLine( "feature = %d", m_manifold.feature ); + DrawTextLine( "cache hit = %d", m_satCache.hit ); + + DrawTransform( m_scene, b3Transform_identity, 1.0f ); + + if ( m_manifold.pointCount > 0 ) + { + float length = 0.5f * b3GetLengthUnitsPerMeter(); + + for ( int pointIndex = 0; pointIndex < m_manifold.pointCount; ++pointIndex ) + { + const b3LocalManifoldPoint& manifoldPoint = m_manifold.points[pointIndex]; + + b3Vec3 point = manifoldPoint.point; + + DrawLine( m_scene, point, point + length * m_manifold.normal, b3_colorWhite ); + + if ( manifoldPoint.separation > 0.0f ) + { + DrawPoint( m_scene, point, 10.0f, b3_colorWhite ); + } + else + { + DrawPoint( m_scene, point, 10.0f, b3_colorYellow ); + } + + DrawWorldString( m_camera, point, b3_colorWhite, " %.2f", 100.0f * manifoldPoint.separation ); + + b3FeaturePair pair = manifoldPoint.pair; + DrawWorldString( m_camera, point + 0.025f * m_manifold.normal, b3_colorPapayaWhip, " %X:%X %X:%X", pair.owner1, + pair.index1, pair.owner2, pair.index2 ); + } + } + + b3Vec3 p1 = b3TransformPoint( m_transformA, m_triangle[0] ); + b3Vec3 p2 = b3TransformPoint( m_transformA, m_triangle[1] ); + b3Vec3 p3 = b3TransformPoint( m_transformA, m_triangle[2] ); + DrawFace( m_scene, p1, p2, p3, b3_colorCyan ); + + DrawWorldString( m_camera, p1, b3_colorWhite, "0" ); + DrawWorldString( m_camera, p2, b3_colorWhite, "1" ); + DrawWorldString( m_camera, p3, b3_colorWhite, "2" ); + + b3Vec3 center = 1.0f / 3.0f * ( p1 + p2 + p3 ); + b3Vec3 normal = b3Normalize( b3Cross( p2 - p1, p3 - p1 ) ); + DrawArrow( m_scene, center, center + 0.5f * normal, 0.05f, b3_colorMediumPurple ); + + Sample::Render(); + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 12.0f * fontSize; + ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->m_height - height - 2.0f * fontSize ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 10.0f * fontSize, height ) ); + + ImGui::Begin( "Triangle Manifold", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + ImGui::Checkbox( "Use cache", &m_useCache ); + if ( m_useCache ) + { + ImGui::RadioButton( "auto", &m_manualFeature, 0 ); + ImGui::RadioButton( "faceA", &m_manualFeature, 1 ); + ImGui::RadioButton( "faceB", &m_manualFeature, 2 ); + ImGui::RadioButton( "edgePair", &m_manualFeature, 3 ); + } + + ImGui::End(); + } + + void MouseDown( b3Vec2 p, int button, int modifiers ) override + { + if ( button == 0 && ( modifiers & GLFW_MOD_ALT ) == 0 ) + { + if ( modifiers & GLFW_MOD_SHIFT ) + { + m_baseX = p.x; + m_baseY = p.y; + m_baseQuaternion = m_transformB.q; + m_rotating = true; + } + else + { + PickRay pickRay = m_camera->BuildPickRay( p.x, p.y ); + m_origin = pickRay.origin + 10.0f * b3Normalize( pickRay.translation ); + m_baseTranslation = m_transformB.p; + m_tracking = true; + } + } + } + + void MouseUp( b3Vec2 p, int button ) override + { + m_tracking = false; + m_rotating = false; + } + + void MouseMove( b3Vec2 p ) override + { + if ( m_tracking ) + { + PickRay pickRay = m_camera->BuildPickRay( p.x, p.y ); + b3Vec3 origin = pickRay.origin + 10.0f * b3Normalize( pickRay.translation ); + m_transformB.p = m_baseTranslation + origin - m_origin; + } + + if ( m_rotating ) + { + int x = p.x; + int y = p.y; + + b3Quat qx = b3MakeQuatFromAxisAngle( b3Vec3_axisY, 0.01f * ( x - m_baseX ) ); + b3Quat qz = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.01f * ( y - m_baseY ) ); + m_transformB.q = b3NormalizeQuat( b3MulQuat( m_baseQuaternion, b3MulQuat( qx, qz ) ) ); + } + } + + static constexpr int m_pointCapacity = 8; + b3LocalManifold m_manifold; + b3LocalManifoldPoint m_points[m_pointCapacity]; + b3Transform m_transformA; + b3Transform m_transformB; + b3Vec3 m_triangle[3] = {}; + b3Vec3 m_baseTranslation; + b3Quat m_baseQuaternion; + b3Vec3 m_origin; + b3SimplexCache m_simplexCache; + b3SATCache m_satCache; + int m_manualFeature; + int m_baseX; + int m_baseY; + bool m_useCache; + bool m_tracking; + bool m_rotating; +}; + +class SphereAndSphere : public Manifold +{ +public: + explicit SphereAndSphere( SampleContext* sampleContext ) + : Manifold( sampleContext ) + { + m_sphere = { { 0.5f, 0.0f, -0.25f }, 2.0f }; + } + + void Render() override + { + DrawSphere( m_scene, m_transformA, m_sphere, b3_colorGreen ); + DrawSphere( m_scene, m_transformB, m_sphere, b3_colorCyan ); + + Manifold::Render(); + } + + void Step() override + { + b3Transform transformBtoA = b3InvMulTransforms( m_transformA, m_transformB ); + b3CollideSpheres( &m_manifold, m_pointCapacity, &m_sphere, &m_sphere, transformBtoA ); + } + + static Sample* Create( SampleContext* sampleContext ) + { + return new SphereAndSphere( sampleContext ); + } + + b3Sphere m_sphere; +}; + +static int sampleCollideSpheres = SampleManager::Register( "Manifold", "Sphere vs Sphere", SphereAndSphere::Create ); + +class CapsuleAndSphere : public Manifold +{ +public: + static Sample* Create( SampleContext* sampleContext ) + { + return new CapsuleAndSphere( sampleContext ); + } + + explicit CapsuleAndSphere( SampleContext* sampleContext ) + : Manifold( sampleContext ) + { + m_capsule = { { -2.0f, 0.0f, 0.0f }, { 2.0f, 0.0f, 0.0f }, 1.0f }; + m_sphere = { { 0.0f, 0.0f, 0.0f }, 2.0f }; + + m_transformA = { { 0.0f, 0.0f, 0.0f }, b3Quat_identity }; + m_transformB = { { -4.0f, 0.0f, 0.0f }, b3Quat_identity }; + } + + void Render() override + { + DrawCapsule( m_scene, m_transformA, m_capsule, b3_colorCyan ); + DrawSphere( m_scene, m_transformB, m_sphere, b3_colorGreen ); + + Manifold::Render(); + } + + void Step() override + { + b3Transform transformBtoA = b3InvMulTransforms( m_transformA, m_transformB ); + b3CollideCapsuleAndSphere( &m_manifold, m_pointCapacity, &m_capsule, &m_sphere, transformBtoA ); + } + + b3Sphere m_sphere; + b3Capsule m_capsule; +}; + +static int sampleSphereAndCapsule = SampleManager::Register( "Manifold", "Capsule vs Sphere", CapsuleAndSphere::Create ); + +class HullAndSphere : public Manifold +{ +public: + explicit HullAndSphere( SampleContext* sampleContext ) + : Manifold( sampleContext ) + { + m_sphere = { { 0.0f, 0.0f, 0.0f }, 1.0f }; + m_hull = b3MakeBoxHull( 2.0f, 0.5f, 0.5f ); + + m_transformA = { { 0.0f, 0.0f, 0.0f }, b3Quat_identity }; + m_transformB = { { 1.5f, 0.0f, 0.0f }, b3Quat_identity }; + } + + void Render() override + { + DrawHull( m_scene, m_transformA, &m_hull.base, b3_colorCyan, false ); + DrawSphere( m_scene, m_transformB, m_sphere, b3_colorGreen ); + + Manifold::Render(); + } + + void Step() override + { + if ( m_useCache == false ) + { + m_simplexCache = {}; + } + + b3Transform transformBtoA = b3InvMulTransforms( m_transformA, m_transformB ); + b3CollideHullAndSphere( &m_manifold, m_pointCapacity, &m_hull.base, &m_sphere, transformBtoA, &m_simplexCache ); + } + + static Sample* Create( SampleContext* sampleContext ) + { + return new HullAndSphere( sampleContext ); + } + + b3Sphere m_sphere; + b3BoxHull m_hull; +}; + +static int sampleSphereAndHull = SampleManager::Register( "Manifold", "Hull vs Sphere", HullAndSphere::Create ); + +class TriangleAndSphere : public TriangleManifold +{ +public: + static Sample* Create( SampleContext* sampleContext ) + { + return new TriangleAndSphere( sampleContext ); + } + + explicit TriangleAndSphere( SampleContext* sampleContext ) + : TriangleManifold( sampleContext ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 30.0f, 10.0f, b3Vec3_zero ); + } + + m_sphere = { { 0.0f, 0.0f, 0.0f }, 1.0f }; + m_triangle[0] = { 0.0f, 0.0f, 0.0f }; + m_triangle[1] = { 4.0f, 0.0f, 4.0f }; + m_triangle[2] = { 4.0f, 0.0f, 0.0f }; + + // b3Quat qA = b3MakeQuatFromAxisAngle( { 0.0f, 1.0f, 0.0f }, 2.0f ); + // m_transformA = { { 1.0f, 1.0f, 0.0f }, qA }; + + m_transformA = b3Transform_identity; + m_transformB = { { 2.0f, 0.5f, 1.0f }, b3Quat_identity }; + } + + void Render() override + { + DrawSphere( m_scene, m_transformB, m_sphere, b3_colorGreen ); + + TriangleManifold::Render(); + } + + void Step() override + { + // Convert triangle to frame B + b3Transform xf = b3InvMulTransforms( m_transformB, m_transformA ); + b3Vec3 localTriangle[3] = { + b3TransformPoint( xf, m_triangle[0] ), + b3TransformPoint( xf, m_triangle[1] ), + b3TransformPoint( xf, m_triangle[2] ), + }; + + b3CollideSphereAndTriangle( &m_manifold, m_pointCapacity, &m_sphere, localTriangle ); + + // Convert manifold from frame B to world space + m_manifold.normal = b3RotateVector( m_transformB.q, m_manifold.normal ); + for ( int i = 0; i < m_manifold.pointCount; ++i ) + { + m_manifold.points[i].point = b3TransformPoint( m_transformB, m_manifold.points[i].point ); + } + } + + b3Sphere m_sphere; +}; + +static int sampleSphereAndTriangle = SampleManager::Register( "Manifold", "Triangle vs Sphere", TriangleAndSphere::Create ); + +class CapsuleAndCapsule : public Manifold +{ +public: + explicit CapsuleAndCapsule( SampleContext* sampleContext ) + : Manifold( sampleContext ) + { + m_capsule = { { -2.0f, 0.0f, 0.0f }, { 2.0f, 0.0f, 0.0f }, 1.0f }; + + m_transformA = { { 1.0f, 1.0f, 0.0f }, b3Quat_identity }; + m_transformB = { { -4.0f, 1.0f, 0.0f }, b3Quat_identity }; + } + + void Render() override + { + DrawCapsule( m_scene, m_transformA, m_capsule, b3_colorGreen ); + DrawCapsule( m_scene, m_transformB, m_capsule, b3_colorCyan ); + + Manifold::Render(); + } + + void Step() override + { + b3Transform transformBtoA = b3InvMulTransforms( m_transformA, m_transformB ); + b3CollideCapsules( &m_manifold, m_pointCapacity, &m_capsule, &m_capsule, transformBtoA ); + } + + static Sample* Create( SampleContext* sampleContext ) + { + return new CapsuleAndCapsule( sampleContext ); + } + + b3Capsule m_capsule; +}; + +static int sampleCapsuleAndCapsule = SampleManager::Register( "Manifold", "Capsule vs Capsule", CapsuleAndCapsule::Create ); + +class CapsuleAndHull : public Manifold +{ +public: + explicit CapsuleAndHull( SampleContext* sampleContext ) + : Manifold( sampleContext ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 30.0f, 5.0f, b3Vec3_zero ); + } + + m_capsule = { { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, 0.5f }; + m_hull = b3MakeBoxHull( 1.0f, 0.5f, 0.5f ); + + m_transformA = { { 0.0f, 0.0f, 0.0f }, b3Quat_identity }; + m_transformB = { { 0.0f, 1.0f, 0.0f }, b3Quat_identity }; + + /* + p [ 1.58523774, 0.729615569, 0.451690674 ] b3Vec3 + q [ [ -0.00256555085, -0.0201825816, 0.126076236 ], 0.991811991 ] b3Quat + */ + // m_capsule = { + // { 0.0799999982, -0.0151330000, -0.0918010026 }, { -0.0799999982, -0.0151330000, -0.0918010026 }, 0.100000001 }; + // m_hull = b3CreateBox( { 0.5f, 1.0f, 1.5f } ); + + m_transformB = { { 1.58523774, 0.729615569, 0.451690674 }, + { { -0.00256555085, -0.0201825816, 0.126076236 }, 0.991811991 } }; + } + + void Render() override + { + DrawHull( m_scene, m_transformA, &m_hull.base, b3_colorCyan, false ); + DrawCapsule( m_scene, m_transformB, m_capsule, b3_colorGreen ); + + Manifold::Render(); + } + + void Step() override + { + if ( m_useCache == false ) + { + m_simplexCache = {}; + } + + b3Transform transformBtoA = b3InvMulTransforms( m_transformA, m_transformB ); + b3CollideHullAndCapsule( &m_manifold, m_pointCapacity, &m_hull.base, &m_capsule, transformBtoA, &m_simplexCache ); + } + + static Sample* Create( SampleContext* sampleContext ) + { + return new CapsuleAndHull( sampleContext ); + } + + b3BoxHull m_hull; + b3Capsule m_capsule; +}; + +static int sampleCapsuleAndHull = SampleManager::Register( "Manifold", "Capsule vs Hull", CapsuleAndHull::Create ); + +class TriangleAndCapsule : public TriangleManifold +{ +public: + static Sample* Create( SampleContext* sampleContext ) + { + return new TriangleAndCapsule( sampleContext ); + } + + explicit TriangleAndCapsule( SampleContext* sampleContext ) + : TriangleManifold( sampleContext ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 30.0f, 10.0f, b3Vec3_zero ); + } + + m_capsule = { { 0.0f, -0.2f, 0.0f }, { 0.0f, 0.2f, 0.0f }, 0.05f }; + m_triangle[0] = { -4.0f, 0.0f, -4.0f }; + m_triangle[1] = { -4.0f, 0.0f, 0.0f }; + m_triangle[2] = { 0.0f, 0.0f, 0.0f }; + + m_transformA = b3Transform_identity; + m_transformB = { { 0.0f, 0.5f, 0.0f }, b3Quat_identity }; + m_transformB.q = b3MakeQuatFromAxisAngle( { 0.0f, 0.0f, 1.0f }, 0.5f * B3_PI ); + + m_transformB = { { -0.500000000, 0.123778239, -0.500000000 }, + { { -0.157559350, 0.294042289, 0.821513653 }, -0.462417006 } }; + } + + void Render() override + { + DrawCapsule( m_scene, m_transformB, m_capsule, b3_colorGreen ); + DrawTransform( m_scene, m_transformB, 0.1f ); + + TriangleManifold::Render(); + } + + void Step() override + { + if ( m_useCache == false ) + { + m_simplexCache = {}; + } + + // Put triangle into capsule coordinates + b3Transform xf = b3InvMulTransforms( m_transformB, m_transformA ); + b3Vec3 localTriangle[3] = { + b3TransformPoint( xf, m_triangle[0] ), + b3TransformPoint( xf, m_triangle[1] ), + b3TransformPoint( xf, m_triangle[2] ), + }; + + b3CollideCapsuleAndTriangle( &m_manifold, m_pointCapacity, &m_capsule, localTriangle, &m_simplexCache ); + + // Convert manifold from frame B to world space + m_manifold.normal = b3RotateVector( m_transformB.q, m_manifold.normal ); + for ( int i = 0; i < m_manifold.pointCount; ++i ) + { + m_manifold.points[i].point = b3TransformPoint( m_transformB, m_manifold.points[i].point ); + } + } + + b3Capsule m_capsule; +}; + +static int sampleCapsuleAndTriangle = SampleManager::Register( "Manifold", "Triangle vs Capsule", TriangleAndCapsule::Create ); + +class HullAndHull : public Manifold +{ +public: + explicit HullAndHull( SampleContext* context ) + : Manifold( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 15.0f, 4.0f, b3Vec3_zero ); + } + + // m_boxA = b3MakeTransformedBoxHull( 0.5f, 0.5f, 0.5f, { { 0.0f, -0.5f, 0.0f }, b3Quat_identity } ); + + b3Transform transform = { { 1.0f, 0.5f, 0.0f }, b3Quat_identity }; + m_boxA = b3MakeTransformedBoxHull( 0.5f, 1.0f, 1.0f, transform ); + + // m_hull = CreateConvex( 0.6f, 0.0f, 0.95f, 1.0f, context->arena ); + m_hullA = &m_boxA.base; + + m_boxB = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + // m_hull = CreateConvex( 0.6f, 0.0f, 0.95f, 1.0f, context->arena ); + m_hullB = &m_boxB.base; + + /* +- xfA {p=[ -10.0000000, 0.00000000, -10.0000000 ] q=[ [ 0.00000000, 0.00000000, 0.00000000 ], 1.00000000 ] } b3Transform ++ p [ -10.0000000, 0.00000000, -10.0000000 ] b3Vec3 ++ q [ [ 0.00000000, 0.00000000, 0.00000000 ], 1.00000000 ] b3Quat +- xfB {p=[ -10.0000000, 1.00000000, -10.0000000 ] q=[ [ 0.00000000, 0.00000000, 0.00000000 ], 1.00000000 ] } b3Transform ++ p [ -10.0000000, 1.00000000, -10.0000000 ] b3Vec3 ++ q [ [ 0.00000000, 0.00000000, 0.00000000 ], 1.00000000 ] b3Quat + + */ + m_transformA = { { 0.0f, 0.0f, 0.0f }, b3Quat_identity }; + m_transformB = { { 0.0f, 0.0f, 0.0f }, b3Quat_identity }; + + /* + p [ 0.691772044, 0.951781273, 0.0741987228 ] b3Vec3 + q [ [ -0.00162522844, -0.0456664972, 0.0355294086 ], 0.998323441 ] b3Quat + */ + // m_transformB = { { 0.691772044, 0.951781273, 0.0741987228 }, + // { { -0.00162522844, -0.0456664972, 0.0355294086 }, 0.998323441 } }; + + m_satCache = {}; + } + + ~HullAndHull() override + { + if ( m_hullA != &m_boxA.base ) + { + b3DestroyHull( m_hullA ); + } + + if ( m_hullB != &m_boxB.base ) + { + b3DestroyHull( m_hullB ); + } + } + + b3Hull* CreateConvex( float radius1, float height1, float radius2, float height2, Arena arena ) const + { + const int sideCount = 32; + const float deltaAlpha = 2.0f * B3_PI / sideCount; + + int vertexCount = 2 * sideCount; + b3Vec3* vertexBase = static_cast( arena.Allocate( vertexCount * sizeof( b3Vec3 ) ) ); + + float alpha = 0.0f; + for ( int sideIndex = 0; sideIndex < sideCount; ++sideIndex ) + { + b3CosSin cs = b3ComputeCosSin( alpha ); + + float x1 = radius1 * cs.cosine; + float z1 = radius1 * cs.sine; + float x2 = radius2 * cs.cosine; + float z2 = radius2 * cs.sine; + + vertexBase[2 * sideIndex + 0] = { x1, height1, z1 }; + vertexBase[2 * sideIndex + 1] = { x2, height2, z2 }; + alpha += deltaAlpha; + } + + return b3CreateHull( vertexBase, vertexCount, vertexCount ); + } + + void Render() override + { + DrawHull( m_scene, m_transformA, m_hullA, b3_colorGreen, false ); + DrawHull( m_scene, m_transformB, m_hullB, b3_colorCyan, false ); + + Manifold::Render(); + } + + void Step() override + { + if ( m_useCache == true ) + { + if ( m_manualFeature == 1 ) + { + m_satCache.type = b3_manualFaceAxisA; + } + else if ( m_manualFeature == 2 ) + { + m_satCache.type = b3_manualFaceAxisB; + } + else if ( m_manualFeature == 3 ) + { + m_satCache.type = b3_manualEdgePairAxis; + } + } + else + { + m_satCache = {}; + } + + b3Transform transformBtoA = b3InvMulTransforms( m_transformA, m_transformB ); + b3CollideHulls( &m_manifold, m_pointCapacity, m_hullA, m_hullB, transformBtoA, &m_satCache ); + + DrawTextLine( "SAT type: %d", m_satCache.type ); + } + + static Sample* Create( SampleContext* sampleContext ) + { + return new HullAndHull( sampleContext ); + } + + b3BoxHull m_boxA; + b3BoxHull m_boxB; + b3Hull* m_hullA; + b3Hull* m_hullB; +}; + +static int sampleCollideHulls = SampleManager::Register( "Manifold", "Hull vs Hull", HullAndHull::Create ); + +class TriangleAndHull : public TriangleManifold +{ +public: + static Sample* Create( SampleContext* sampleContext ) + { + return new TriangleAndHull( sampleContext ); + } + + explicit TriangleAndHull( SampleContext* sampleContext ) + : TriangleManifold( sampleContext ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 30.0f, 3.0f, b3Vec3_zero ); + } + + m_triangle[0] = { 1.00000000, 0, 1.00000000 }; + m_triangle[1] = { 1.00000000, 0, 0.00000000 }; + m_triangle[2] = { 0.00000000, 0, 0.00000000 }; + + m_boxHull = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + + m_transformA = b3Transform_identity; + m_transformB = b3Transform_identity; + m_transformB.p = { 0.0f, 0.45f, 0.1f }; + + // b3MeshEdgeFlags + m_flags = 0; + + /* + * separation -0.0415397286 float + type 2 '\x2' unsigned char + indexA 0 '\0' unsigned char + indexB 1 '\x1' unsigned char + hit 1 '\x1' unsigned char + + */ + + m_satCache = { + .separation = -0.0107582733f, + .type = 1, + .indexA = 0, + .indexB = 4, + }; + + m_satCache = {}; + m_useCache = false; + m_cylinder = b3CreateCylinder( 0.4f, 0.05f, 0.0f, 6 ); + m_hull = &m_boxHull.base; + } + + ~TriangleAndHull() override + { + b3DestroyHull( m_cylinder ); + } + + void Render() override + { + DrawHull( m_scene, m_transformB, m_hull, b3_colorGreen, false ); + + b3Transform xf; + xf.p = b3TransformPoint( m_transformB, m_hull->center ); + xf.q = m_transformB.q; + DrawTransform( m_scene, xf, 0.1f ); + + TriangleManifold::Render(); + } + + void Step() override + { + if ( m_useCache == true ) + { + if ( m_manualFeature == 1 ) + { + m_satCache.type = b3_manualFaceAxisA; + } + else if ( m_manualFeature == 2 ) + { + m_satCache.type = b3_manualFaceAxisB; + } + else if ( m_manualFeature == 3 ) + { + m_satCache.type = b3_manualEdgePairAxis; + } + } + else + { + m_satCache = {}; + } + + b3Transform xf = b3InvMulTransforms( m_transformB, m_transformA ); + b3Vec3 localTriangle[3] = { + b3TransformPoint( xf, m_triangle[0] ), + b3TransformPoint( xf, m_triangle[1] ), + b3TransformPoint( xf, m_triangle[2] ), + }; + + b3CollideHullAndTriangle( &m_manifold, m_pointCapacity, m_hull, localTriangle, m_flags, &m_satCache ); + + // Convert manifold from frame B to world space + m_manifold.normal = b3RotateVector( m_transformB.q, m_manifold.normal ); + for ( int i = 0; i < m_manifold.pointCount; ++i ) + { + m_manifold.points[i].point = b3TransformPoint( m_transformB, m_manifold.points[i].point ); + } + } + + int m_flags; + b3BoxHull m_boxHull; + b3Hull* m_cylinder; + b3Hull* m_hull; +}; + +static int sampleHullAndTriangle = SampleManager::Register( "Manifold", "Triangle vs Hull", TriangleAndHull::Create ); diff --git a/samples/sample_mesh.cpp b/samples/sample_mesh.cpp new file mode 100644 index 0000000..6568a24 --- /dev/null +++ b/samples/sample_mesh.cpp @@ -0,0 +1,1523 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "camera.h" +#include "human.h" +#include "mesh_loader.h" +#include "renderer.h" +#include "sample.h" +#include "scene.h" + +#include "box3d/box3d.h" + +#include +#include +#include + +enum class ShapeType +{ + sphere, + capsule, + box, + cylinder +}; + +class GridMesh : public Sample +{ +public: + explicit GridMesh( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 6.0f, b3Vec3_zero ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + m_gridMesh = b3CreateGridMesh( 20, 20, 1.0f, 0, true ); + + m_scale = b3Vec3_one; + m_scale = {2.0f, 2.0f, 2.0f}; + //m_scale = { -1.2f, 2.0f, 4.0f }; + //m_scale = { 8.0f, 8.0f, 8.0f }; + //m_scale = { 0.5f, 0.5f, 0.5f }; + //m_scale = { 0.25f, 0.25f, 0.25f }; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + m_gridShapeId = b3CreateMeshShape( groundId, &shapeDef, m_gridMesh, m_scale ); + + m_shapeType = ShapeType::cylinder; + m_bodyId = b3_nullBodyId; + m_cylinderHull = b3CreateCylinder( 1.0f, 0.25f, 0.0f, 15 ); + //m_cylinderHull = b3CreateCylinder( 0.5f, 0.2f, 0.0f, 15 ); + + Spawn(); + + m_context->debugDraw.forceScale = 0.01f; + } + + ~GridMesh() override + { + b3DestroyHull( m_cylinderHull ); + b3DestroyMesh( m_gridMesh ); + } + + void Spawn() + { + if ( B3_IS_NON_NULL( m_bodyId ) ) + { + b3DestroyBody( m_bodyId ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + //bodyDef.position = { 0.5f, 2.0f, -0.5f }; + bodyDef.position = { 0.1f, 1.0f, -0.1f }; + // bodyDef.linearVelocity = { 2.0f, 0.0f, 0.0f }; + // bodyDef.position = { 0.208701894, 0.0791450217, -0.298710823 }; + // bodyDef.rotation = { { 0.0808477178, -0.00305216131, 0.000387475739 }, 0.996721804 }; + // bodyDef.linearVelocity = { 7.28029263e-05, 0.000761006493, 0.0104003791 }; + // bodyDef.angularVelocity = { 0.116714634, -0.00774557842, -0.000242586044 }; + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + switch ( m_shapeType ) + { + case ShapeType::sphere: + { + shapeDef.baseMaterial.rollingResistance = 0.05f; + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f }; + b3CreateSphereShape( m_bodyId, &shapeDef, &sphere ); + } + break; + + case ShapeType::capsule: + { + shapeDef.baseMaterial.rollingResistance = 0.05f; + b3Capsule capsule = { { 0.0f, 0.0f, 1.276f }, { 0.0f, 0.0f, 0.476f }, 0.15f }; + b3CreateCapsuleShape( m_bodyId, &shapeDef, &capsule ); + } + break; + + case ShapeType::box: + { + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + //shapeDef.baseMaterial.friction = 0.01f; + b3CreateHullShape( m_bodyId, &shapeDef, &box.base ); + } + break; + + case ShapeType::cylinder: + { + shapeDef.baseMaterial.rollingResistance = 0.01f; + //shapeDef.baseMaterial.friction = 0.1f; + b3CreateHullShape( m_bodyId, &shapeDef, m_cylinderHull ); + } + break; + + default: + assert( false ); + } + } + + void UpdateUI() override + { + float height = 220.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 280.0f, height ) ); + ImGui::Begin( "Mesh Grid", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + + if ( ImGui::RadioButton( "Sphere", m_shapeType == ShapeType::sphere ) ) + { + m_shapeType = ShapeType::sphere; + Spawn(); + } + + if ( ImGui::RadioButton( "Capsule", m_shapeType == ShapeType::capsule ) ) + { + m_shapeType = ShapeType::capsule; + Spawn(); + } + + if ( ImGui::RadioButton( "Box", m_shapeType == ShapeType::box ) ) + { + m_shapeType = ShapeType::box; + Spawn(); + } + + if ( ImGui::RadioButton( "Cylinder", m_shapeType == ShapeType::cylinder ) ) + { + m_shapeType = ShapeType::cylinder; + Spawn(); + } + + b3Vec3 scale = m_scale; + bool changed = false; + changed = changed || ImGui::SliderFloat( "Scale X", &scale.x, -2.0f, 2.0f, "%.1f" ); + changed = changed || ImGui::SliderFloat( "Scale Z", &scale.z, -2.0f, 2.0f, "%.1f" ); + + if ( changed ) + { + m_scale = scale; + b3Shape_SetMesh( m_gridShapeId, m_gridMesh, m_scale ); + } + + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + + DrawTextLine( "triangle count = %d, bytes = %d", m_gridMesh->triangleCount, m_gridMesh->byteCount ); + b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 1.0f ); + } + + void Step() override + { + if ( m_stepCount == 83 ) + { + // m_context->settings.pause = true; + } + + if ( m_stepCount < 100 ) + { + // b3Vec3 p = b3Body_GetPosition( m_bodyId ); + // printf( "%d : %g %g %g\n", m_stepCount, p.x, p.y, p.z ); + // b3Vec3 v = b3Body_GetLinearVelocity( m_bodyId ); + // printf( "%d : %g %g %g\n", m_stepCount, v.x, v.y, v.z ); + } + + Sample::Step(); + } + + static Sample* Create( SampleContext* context ) + { + return new GridMesh( context ); + } + + b3Hull* m_cylinderHull; + ShapeType m_shapeType; + b3BodyId m_bodyId; + b3MeshData* m_gridMesh; + b3ShapeId m_gridShapeId; + b3Vec3 m_scale; +}; + +static int sampleGridMesh = SampleManager::Register( "Mesh", "Grid", GridMesh::Create ); + +class BigBoxMesh : public Sample +{ +public: + explicit BigBoxMesh( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 6.0f, b3Vec3_zero ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + m_boxMesh = b3CreateBoxMesh( b3Vec3_zero, { 50.0f, 1.0f, 50.0f }, true ); + m_scale = b3Vec3_one; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.friction = 0.5f; + //shapeDef.baseMaterial.restitution = 0.5f; + //shapeDef.baseMaterial.rollingResistance = 0.5f; + m_gridShapeId = b3CreateMeshShape( groundId, &shapeDef, m_boxMesh, m_scale ); + + m_shapeType = ShapeType::cylinder; + m_bodyId = b3_nullBodyId; + m_cylinderHull = b3CreateCylinder( 0.5f, 0.2f, 0.0f, 15 ); + + m_stepWhilePaused = false; + + Spawn(); + } + + ~BigBoxMesh() override + { + b3DestroyHull( m_cylinderHull ); + b3DestroyMesh( m_boxMesh ); + } + + void Spawn() + { + if ( B3_IS_NON_NULL( m_bodyId ) ) + { + b3DestroyBody( m_bodyId ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 2.0f, 0.0f }; + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.rollingResistance = 0.05f; + + switch ( m_shapeType ) + { + case ShapeType::sphere: + { + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f }; + b3CreateSphereShape( m_bodyId, &shapeDef, &sphere ); + } + break; + + case ShapeType::capsule: + { + b3SurfaceMaterial material = b3DefaultSurfaceMaterial(); + //material.friction = 0.0f; + //material.restitution = 1.0f; + material.rollingResistance = 0.1f; + shapeDef.materials = &material; + shapeDef.materialCount = 1; + b3Capsule capsule = { { 0.0f, 0.0f, 1.276f }, { 0.0f, 0.0f, 0.476f }, 0.15f }; + b3CreateCapsuleShape( m_bodyId, &shapeDef, &capsule ); + } + break; + + case ShapeType::box: + { + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + //shapeDef.baseMaterial.friction = 0.01f; + b3CreateHullShape( m_bodyId, &shapeDef, &box.base ); + } + break; + + case ShapeType::cylinder: + { + b3CreateHullShape( m_bodyId, &shapeDef, m_cylinderHull ); + } + break; + + default: + assert( false ); + } + } + + void UpdateUI() override + { + float height = 220.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 280.0f, height ) ); + ImGui::Begin( "Mesh Grid", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + + if ( ImGui::RadioButton( "Sphere", m_shapeType == ShapeType::sphere ) ) + { + m_shapeType = ShapeType::sphere; + Spawn(); + } + + if ( ImGui::RadioButton( "Capsule", m_shapeType == ShapeType::capsule ) ) + { + m_shapeType = ShapeType::capsule; + Spawn(); + } + + if ( ImGui::RadioButton( "Box", m_shapeType == ShapeType::box ) ) + { + m_shapeType = ShapeType::box; + Spawn(); + } + + if ( ImGui::RadioButton( "Cylinder", m_shapeType == ShapeType::cylinder ) ) + { + m_shapeType = ShapeType::cylinder; + Spawn(); + } + + b3Vec3 scale = m_scale; + bool changed = false; + changed = changed || ImGui::SliderFloat( "Scale X", &scale.x, -2.0f, 2.0f, "%.1f" ); + changed = changed || ImGui::SliderFloat( "Scale Z", &scale.z, -2.0f, 2.0f, "%.1f" ); + + if ( changed ) + { + m_scale = scale; + b3Shape_SetMesh( m_gridShapeId, m_boxMesh, m_scale ); + } + + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 1.0f ); + } + + void Step() override + { + if ( m_stepCount == 83 ) + { + // m_context->settings.pause = true; + } + + if ( m_stepCount < 100 ) + { + // b3Vec3 p = b3Body_GetPosition( m_bodyId ); + // printf( "%d : %g %g %g\n", m_stepCount, p.x, p.y, p.z ); + // b3Vec3 v = b3Body_GetLinearVelocity( m_bodyId ); + // printf( "%d : %g %g %g\n", m_stepCount, v.x, v.y, v.z ); + } + + Sample::Step(); + } + + static Sample* Create( SampleContext* context ) + { + return new BigBoxMesh( context ); + } + + b3Hull* m_cylinderHull; + ShapeType m_shapeType; + b3BodyId m_bodyId; + b3MeshData* m_boxMesh; + b3ShapeId m_gridShapeId; + b3Vec3 m_scale; +}; + +static int sampleBigBoxMesh = SampleManager::Register( "Mesh", "Big Box", BigBoxMesh::Create ); + +class BoxMesh : public Sample +{ +public: + explicit BoxMesh( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 6.0f, b3Vec3_zero ); + EnableGrid( m_scene, true ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisY, 0.25f * B3_PI ); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull box = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + + m_boxMesh = b3CreateBoxMesh( { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 1.0f }, true ); + // m_scale = { -0.6f, 1.0f, 2.0f }; + m_scale = b3Vec3_one; + m_boxShapeId = b3CreateMeshShape( groundId, &shapeDef, m_boxMesh, m_scale ); + + m_cylinderHull = b3CreateCylinder( 1.0f, 0.75f, 0.0f, 8 ); + + m_shapeType = ShapeType::box; + m_bodyId = b3_nullBodyId; + + Spawn(); + } + + ~BoxMesh() override + { + b3DestroyMesh( m_boxMesh ); + b3DestroyHull( m_cylinderHull ); + } + + void Spawn() + { + if ( B3_IS_NON_NULL( m_bodyId ) ) + { + b3DestroyBody( m_bodyId ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 1.5f, 0.0f }; + //bodyDef.position = { -0.2f, 1.5f, -1.25f }; + + if ( m_shapeType == ShapeType::cylinder ) + { + bodyDef.position.y -= 0.5f; + } + + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + switch ( m_shapeType ) + { + case ShapeType::sphere: + { + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f }; + b3CreateSphereShape( m_bodyId, &shapeDef, &sphere ); + } + break; + + case ShapeType::capsule: + { + b3Capsule capsule = { { -0.5f, 0.0f, 0.0f }, { 0.5f, 0.0f, 0.0f }, 0.1f }; + b3CreateCapsuleShape( m_bodyId, &shapeDef, &capsule ); + } + break; + + case ShapeType::box: + { + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + // b3BoxHull box = b3MakeBoxHull( 0.1f, 1.0f, 0.1f ); + b3CreateHullShape( m_bodyId, &shapeDef, &box.base ); + } + break; + + case ShapeType::cylinder: + { + b3CreateHullShape( m_bodyId, &shapeDef, m_cylinderHull ); + } + break; + + default: + assert( false ); + } + } + + void UpdateUI() override + { + float height = 220.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 280.0f, height ) ); + ImGui::Begin( "Box Mesh", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + + if ( ImGui::RadioButton( "Sphere", m_shapeType == ShapeType::sphere ) ) + { + m_shapeType = ShapeType::sphere; + Spawn(); + } + + if ( ImGui::RadioButton( "Capsule", m_shapeType == ShapeType::capsule ) ) + { + m_shapeType = ShapeType::capsule; + Spawn(); + } + + if ( ImGui::RadioButton( "Box", m_shapeType == ShapeType::box ) ) + { + m_shapeType = ShapeType::box; + Spawn(); + } + + if ( ImGui::RadioButton( "Cylinder", m_shapeType == ShapeType::cylinder ) ) + { + m_shapeType = ShapeType::cylinder; + Spawn(); + } + + b3Vec3 scale = m_scale; + bool changed = false; + changed = changed || ImGui::SliderFloat( "Scale X", &scale.x, -2.0f, 2.0f, "%.1f" ); + changed = changed || ImGui::SliderFloat( "Scale Z", &scale.z, -2.0f, 2.0f, "%.1f" ); + + if ( changed ) + { + m_scale = scale; + b3Shape_SetMesh( m_boxShapeId, m_boxMesh, m_scale ); + } + + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 2.0f ); + } + + void Step() override + { + if ( m_stepCount == 83 ) + { + // m_context->settings.pause = true; + } + + if ( m_stepCount < 100 ) + { + // b3Vec3 p = b3Body_GetPosition( m_bodyId ); + // printf( "%d : %g %g %g\n", m_stepCount, p.x, p.y, p.z ); + // b3Vec3 v = b3Body_GetLinearVelocity( m_bodyId ); + // printf( "%d : %g %g %g\n", m_stepCount, v.x, v.y, v.z ); + } + + Sample::Step(); + } + + static Sample* Create( SampleContext* context ) + { + return new BoxMesh( context ); + } + + ShapeType m_shapeType; + b3BodyId m_bodyId; + b3MeshData* m_boxMesh; + b3Hull* m_cylinderHull; + b3ShapeId m_boxShapeId; + b3Vec3 m_scale; +}; + +static int sampleBoxMesh = SampleManager::Register( "Mesh", "Box", BoxMesh::Create ); + +class MeshReflection : public Sample +{ +public: + enum + { + e_humanCount = 20 + }; + + explicit MeshReflection( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 40.0f, b3Vec3_zero ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + { + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + m_gridMesh = b3CreateGridMesh( 20, 20, 2.0f, 2, true ); + b3CreateMeshShape( body, &shapeDef, m_gridMesh, b3Vec3_one ); + } + + { + m_buildingMesh = CreateMeshData( "data/meshes/building.obj", 1.0f, false, false, true, true ); + + b3ShapeDef meshShapeDef = b3DefaultShapeDef(); + b3SurfaceMaterial materials[3] = { + { + .friction = 0.6f, + }, + { + .friction = 0.0f, + .restitution = 0.95f, + .userMaterialId = 1, + }, + { + .friction = 0.2f, + .restitution = 0.2f, + .userMaterialId = 2, + }, + }; + meshShapeDef.materials = materials; + meshShapeDef.materialCount = 3; + + bodyDef.position = { -10.0f, 0.0f, 0.0f }; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3CreateMeshShape( body, &meshShapeDef, m_buildingMesh, b3Vec3_one ); + + m_scale = { -1.0f, 1.0f, 1.0f }; + bodyDef.position = { 10.0f, 0.0f, 0.0f }; + m_meshBodyId = b3CreateBody( m_worldId, &bodyDef ); + m_meshShapeId = b3CreateMeshShape( m_meshBodyId, &meshShapeDef, m_buildingMesh, m_scale ); + } + + bodyDef.type = b3_dynamicBody; + { + bodyDef.position = { 6.0f, 15.0f, 0.0f }; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3Sphere sphere = { b3Vec3_zero, 0.5f }; + shapeDef.baseMaterial.rollingResistance = 0.2f; + shapeDef.baseMaterial.userMaterialId = 42; + b3CreateSphereShape( body, &shapeDef, &sphere ); + } + + { + bodyDef.position = { 9.0f, 15.0f, 0.0f }; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3Capsule capsule = { { -0.5f, 0.5f, 0.0f }, { 0.5f, 0.0f, 0.0f }, 0.25f }; + shapeDef.baseMaterial.rollingResistance = 0.2f; + shapeDef.baseMaterial.userMaterialId = 11; + b3CreateCapsuleShape( body, &shapeDef, &capsule ); + } + + { + bodyDef.position = { 12.0f, 15.0f, 0.0f }; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3BoxHull hull = b3MakeBoxHull( 0.25f, 0.5f, 0.75f ); + shapeDef.baseMaterial.userMaterialId = 555; + b3CreateHullShape( body, &shapeDef, &hull.base ); + } + + float frictionTorque = 5.0f; + float hertz = 1.0f; + float dampingRatio = 0.7f; + bool colorize = false; + for ( int humanIndex = 0; humanIndex < e_humanCount; humanIndex += 1 ) + { + m_humans[humanIndex] = {}; + + int groupIndex = humanIndex; + b3Vec3 position = { -14.0f + 1.5f * humanIndex, 8.0f, 0.0f }; + CreateHuman( &m_humans[humanIndex], m_worldId, position, frictionTorque, hertz, dampingRatio, groupIndex, nullptr, + colorize ); + } + } + + ~MeshReflection() override + { + b3DestroyMesh( m_gridMesh ); + b3DestroyMesh( m_buildingMesh ); + + for ( int i = 0; i < e_humanCount; ++i ) + { + DestroyHuman( m_humans + i ); + } + } + + void UpdateUI() override + { + ImGui::SetNextWindowPos( ImVec2( 10.0f, 600.0f ) ); + ImGui::SetNextWindowSize( ImVec2( 200.0f, 150.0f ) ); + ImGui::Begin( "Mesh Reflection", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + + bool changed = false; + b3Vec3 scale = m_scale; + if ( ImGui::RadioButton( "Neg X", scale.x < 0.0f ) ) + { + scale.x = -1.0f; + changed = true; + } + + ImGui::SameLine(); + + if ( ImGui::RadioButton( "Pos X", scale.x > 0.0f ) ) + { + scale.x = 1.0f; + changed = true; + } + + if ( ImGui::RadioButton( "Neg Y", scale.y < 0.0f ) ) + { + scale.y = -1.0f; + changed = true; + } + + ImGui::SameLine(); + + if ( ImGui::RadioButton( "Pos Y", scale.y > 0.0f ) ) + { + scale.y = 1.0f; + changed = true; + } + + if ( ImGui::RadioButton( "Neg Z", scale.z < 0.0f ) ) + { + scale.z = -1.0f; + changed = true; + } + + ImGui::SameLine(); + + if ( ImGui::RadioButton( "Pos Z", scale.z > 0.0f ) ) + { + scale.z = 1.0f; + changed = true; + } + + if ( changed ) + { + m_scale = scale; + + b3Shape_SetMesh( m_meshShapeId, m_buildingMesh, m_scale ); + } + + ImGui::End(); + } + + void Render() override + { + DrawTextLine( "scale = (%.2g, %.2g, %.2g)", m_scale.x, m_scale.y, m_scale.z ); + DrawTextLine( "surface type = %d", m_userMaterialId ); + + Sample::Render(); + } + + static Sample* Create( SampleContext* context ) + { + return new MeshReflection( context ); + } + + b3Vec3 m_scale; + b3MeshData* m_gridMesh; + b3MeshData* m_buildingMesh; + b3BodyId m_meshBodyId; + b3ShapeId m_meshShapeId; + Human m_humans[e_humanCount]; +}; + +static int sampleMeshReflection = SampleManager::Register( "Mesh", "Reflection", MeshReflection::Create ); + +struct CastContext +{ + b3Vec3 point; + b3Vec3 normal; + float fraction; + bool hit; +}; + +class HeightField : public Sample +{ +public: + static Sample* Create( SampleContext* context ) + { + return new HeightField( context ); + } + + explicit HeightField( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 40.0f, b3Vec3_zero ); + } + +#if defined(NDEBUG) + m_rowCount = 400; + m_columnCount = 400; +#else + m_rowCount = 100; + m_columnCount = 100; +#endif + + m_groundId = {}; + m_bodyId1 = {}; + m_bodyId2 = {}; + m_amplitude = 0.75f; + m_holes = false; + + // m_rayOrigin = { 1.4f, 2.0f, 1.5f }; + // m_rayTranslation = { -3.0f, -4.0f, 3.0f }; + // m_rayOrigin = { 30.0f, 2.0f, 0.0f }; + // m_rayTranslation = { -60.0f, -4.0f, 0.0f }; + + m_rayOrigin = { 0.0f, 2.0f, 15.0f }; + m_rayTranslation = { 0.0f, -4.0f, 0.0f }; + m_radius = 0.571f; + + m_heightField = nullptr; + + CreateScene(); + } + + ~HeightField() override + { + b3DestroyHeightField( m_heightField ); + } + + void CreateScene() + { + if ( B3_IS_NULL( m_groundId ) == false ) + { + b3DestroyBody( m_groundId ); + m_groundId = {}; + } + + if ( B3_IS_NULL( m_bodyId1 ) == false ) + { + b3DestroyBody( m_bodyId1 ); + m_bodyId1 = {}; + } + + if ( B3_IS_NULL( m_bodyId2 ) == false ) + { + b3DestroyBody( m_bodyId2 ); + m_bodyId2 = {}; + } + + if ( m_heightField != nullptr ) + { + b3DestroyHeightField( m_heightField ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + m_scale = { 2.0f, 2.0f * m_amplitude, 2.0f }; + + if ( m_amplitude == 0.0f ) + { + m_heightField = b3CreateGrid( m_rowCount, m_columnCount, m_scale, m_holes ); + } + else + { + m_heightField = b3CreateWave( m_rowCount, m_columnCount, m_scale, 0.1f, 0.03333f, m_holes ); + } + + bodyDef.position = { -0.5f * m_heightField->scale.x * ( m_columnCount - 1 ), 0.0f, + -0.5f * m_heightField->scale.z * ( m_rowCount - 1 ) }; + // bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisY, 0.25f * B3_PI ); + m_groundId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHeightFieldShape( m_groundId, &shapeDef, m_heightField ); + +#if 0 + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 4.0f, 1.0f }; + m_bodyId1 = b3CreateBody( m_worldId, &bodyDef ); + b3Sphere sphere = { b3Vec3_zero, 0.5f }; + b3CreateSphereShape( m_bodyId1, &shapeDef, &sphere ); + + bodyDef.position = { 0.0f, 0.5f, -0.5f }; + bodyDef.linearVelocity = { 5.0f, 0.0f, 0.0f }; + m_bodyId2 = b3CreateBody( m_worldId, &bodyDef ); + b3BoxHull box = b3MakeBoxHull( 0.3f, 0.3f, 0.3f ); + shapeDef.baseMaterial.friction = 0.05f; + b3CreateHullShape( m_bodyId2, &shapeDef, &box.base ); +#endif + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 18.0f * fontSize; + ImGui::SetNextWindowPos( { 1.0f * fontSize, m_camera->m_height - height - 3.0f * fontSize }, ImGuiCond_Once ); + ImGui::SetNextWindowSize( { 20.0f * fontSize, height } ); + + ImGui::Begin( "Height Field", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + + ImGui::PushItemWidth( 200.0f ); + + if ( ImGui::SliderInt( "columns", &m_columnCount, 1, 500 ) ) + { + CreateScene(); + } + + if ( ImGui::SliderInt( "rows", &m_rowCount, 1, 500 ) ) + { + CreateScene(); + } + + if ( ImGui::SliderFloat( "amplitude", &m_amplitude, 0.0f, 2.0f ) ) + { + CreateScene(); + } + + if ( ImGui::Checkbox( "holes", &m_holes ) ) + { + CreateScene(); + } + + ImGui::SliderFloat( "ray x", &m_rayOrigin.x, -2.0f * m_radius - 1.0f * m_scale.x * ( m_columnCount - 1 ), + 2.0f * m_radius + 1.0f * m_scale.x * ( m_columnCount - 1 ) ); + ImGui::SliderFloat( "ray z", &m_rayOrigin.z, -2.0f * m_radius - 1.0f * m_scale.z * ( m_rowCount - 1 ), + 2.0f * m_radius + 1.0f * m_scale.z * ( m_rowCount - 1 ) ); + ImGui::SliderFloat( "delta x", &m_rayTranslation.x, -2.0f * m_scale.x * ( m_columnCount - 1 ), + 2.0f * m_scale.x * ( m_columnCount - 1 ) ); + ImGui::SliderFloat( "delta z", &m_rayTranslation.z, -2.0f * m_scale.z * ( m_rowCount - 1 ), + 2.0f * m_scale.z * ( m_rowCount - 1 ) ); + ImGui::SliderFloat( "radius", &m_radius, 0.0f, 1.0f ); + + ImGui::PopItemWidth(); + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 0.5f ); + } + + // This callback finds the closest hit. + static float CastCallback( b3ShapeId shapeId, b3Vec3 point, b3Vec3 normal, float fraction, uint64_t surfaceType, + int triangleIndex, int childIndex, void* context ) + { + (void)shapeId; + (void)surfaceType; + (void)triangleIndex; + (void)childIndex; + + CastContext* castContext = (CastContext*)context; + + castContext->point = point; + castContext->normal = normal; + castContext->fraction = fraction; + castContext->hit = true; + + // 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; + } + + void Step() override + { + Sample::Step(); + + if ( m_radius == 0.0f ) + { + // m_rayOrigin = { 0.0f, -FLT_EPSILON, 0.0f }; + // m_rayTranslation = { -1000.0f, 0.0f, 0.0 }; + + b3RayResult result = b3World_CastRayClosest( m_worldId, m_rayOrigin, m_rayTranslation, b3DefaultQueryFilter() ); + + DrawPoint( m_scene, m_rayOrigin, 6.0f, b3_colorGreenYellow ); + DrawPoint( m_scene, m_rayOrigin + m_rayTranslation, 6.0f, b3_colorRed ); + DrawLine( m_scene, m_rayOrigin, m_rayOrigin + m_rayTranslation, b3_colorGray ); + + if ( result.hit ) + { + b3Vec3 point = result.point; + DrawLine( m_scene, point, point + 0.5f * result.normal, b3_colorGray ); + DrawPoint( m_scene, point, 10.0f, b3_colorOrange ); + } + } + else + { + b3ShapeProxy proxy = { + .points = &m_rayOrigin, + .count = 1, + .radius = m_radius, + }; + + CastContext result = {}; + result.fraction = 1.0f; + + b3World_CastShape( m_worldId, &proxy, m_rayTranslation, b3DefaultQueryFilter(), CastCallback, &result ); + + DrawPoint( m_scene, m_rayOrigin, 2.0f, b3_colorGreen ); + DrawPoint( m_scene, m_rayOrigin + m_rayTranslation, 2.0f, b3_colorRed ); + DrawLine( m_scene, m_rayOrigin, m_rayOrigin + m_rayTranslation, b3_colorYellow ); + + b3Sphere sphere = { b3Vec3_zero, m_radius }; + DrawSphere( m_scene, { m_rayOrigin + result.fraction * m_rayTranslation, b3Quat_identity }, sphere, b3_colorOrange ); + + if ( result.hit ) + { + b3Vec3 point = result.point; + DrawLine( m_scene, point, point + 0.5f * result.normal, b3_colorGreen ); + DrawPoint( m_scene, point, 6.0f, b3_colorPurple ); + } + } + } + + b3BodyId m_groundId; + b3BodyId m_bodyId1; + b3BodyId m_bodyId2; + float m_amplitude; + b3Vec3 m_scale; + b3Vec3 m_rayOrigin; + b3Vec3 m_rayTranslation; + b3HeightField* m_heightField; + float m_radius; + int m_rowCount; + int m_columnCount; + bool m_holes; +}; + +static int sampleHeightField = SampleManager::Register( "Mesh", "Height Field", HeightField::Create ); + +static float ComputeInternalSurfaceArea( const b3MeshData* data ) +{ + const b3MeshNode* nodes = b3GetMeshNodes( data ); + int nodeCount = data->nodeCount; + float area = 0.0f; + for ( int i = 1; i < nodeCount; ++i ) + { + const b3MeshNode* node = nodes + i; + if ( node->data.asLeaf.type == 3 ) + { + continue; + } + + b3AABB box = { + node->lowerBound, + node->upperBound, + }; + + area += b3AABB_Area( box ); + } + + return area; +} + +class MeshViewer : public Sample +{ +public: + explicit MeshViewer( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 50.0f, b3Vec3_zero ); + } + + m_meshIndex = 0; + m_mesh = nullptr; + m_bodyId = b3_nullBodyId; + m_medianSplit = true; + m_concaveEdges = true; + m_weldVertices = true; + m_weldToleranceMillimeters = 1.5f; + m_area = 0.0f; + m_drawLevel = -1; + m_height = 0; + m_buildTime = 0.0f; + m_launchSpeedScale = 1.0f; + + LoadMesh(); + } + + ~MeshViewer() override + { + b3DestroyMesh( m_mesh ); + } + + void LoadMesh() + { + if ( B3_IS_NON_NULL( m_bodyId ) ) + { + b3DestroyBody( m_bodyId ); + m_bodyId = b3_nullBodyId; + } + + if ( m_mesh != nullptr ) + { + b3DestroyMesh( m_mesh ); + m_mesh = nullptr; + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + float scale = 0.01f; + + const char* filesNames[m_meshCount] = { + "voxel_mesh_01.obj", "voxel_mesh_02.obj", "voxel_mesh_03.obj", "voxel_mesh_04.obj", + }; + + char buffer[64] = {}; + snprintf( buffer, 64, "data/meshes/%s", filesNames[m_meshIndex] ); + + LoadTempMesh( buffer, &m_tempMesh, scale, true ); + + b3MeshDef def = {}; + def.vertices = m_tempMesh.vertices.data(); + def.vertexCount = (int)m_tempMesh.vertices.size(); + def.indices = m_tempMesh.indices.data(); + def.triangleCount = (int)m_tempMesh.indices.size() / 3; + def.materialIndices = m_tempMesh.materialIndices.data(); + def.useMedianSplit = m_medianSplit; + def.identifyEdges = m_concaveEdges; + def.weldVertices = m_weldVertices; + def.weldTolerance = 0.001f * m_weldToleranceMillimeters; + + uint64_t startTicks = b3GetTicks(); + m_mesh = b3CreateMesh( &def, m_degenerateTriangles, m_degenerateCapacity ); + m_buildTime = b3GetMilliseconds( startTicks ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateMeshShape( m_bodyId, &shapeDef, m_mesh, b3Vec3_one ); + + m_area = ComputeInternalSurfaceArea( m_mesh ); + m_height = b3GetHeight( m_mesh ); + m_drawLevel = b3ClampInt( m_drawLevel, -1, m_height ); + } + + void DrawNodes() + { + if ( m_drawLevel < 0 || m_mesh == nullptr ) + { + return; + } + + int count = m_mesh->nodeCount; + if ( count == 0 ) + { + return; + } + + constexpr int colorCount = 20; + b3HexColor colors[colorCount] = { + b3_colorAliceBlue, b3_colorAntiqueWhite, b3_colorAqua, b3_colorAquamarine, b3_colorAzure, + b3_colorBeige, b3_colorBisque, b3_colorBlanchedAlmond, b3_colorBlue, b3_colorBlueViolet, + b3_colorBrown, b3_colorBurlywood, b3_colorCadetBlue, b3_colorChartreuse, b3_colorChocolate, + b3_colorCoral, b3_colorCornflowerBlue, b3_colorCornsilk, b3_colorCrimson, b3_colorCyan, + }; + + const b3MeshNode* nodes = b3GetMeshNodes( m_mesh ); + const b3MeshNode* root = nodes + 0; + + // Queue to store nodes along with their levels + std::queue> q; + + // Start with the root at level 0 + q.push( { root, 0 } ); + + while ( !q.empty() ) + { + std::pair pair = q.front(); + q.pop(); + + const b3MeshNode* node = pair.first; + int level = pair.second; + + // If the current level matches the target level, add the node's data to the result + if ( level == m_drawLevel ) + { + b3AABB box = { + node->lowerBound, + node->upperBound, + }; + DrawBounds( m_scene, box, 0.0f, colors[level % colorCount] ); + + int axis = node->data.asNode.axis; + b3Vec3 center = b3AABB_Center( box ); + if ( axis == 0 ) + { + DrawArrow( m_scene, center, center + 0.1f * b3Vec3_axisX, 0.02f, b3_colorRed ); + } + else if ( axis == 1 ) + { + DrawArrow( m_scene, center, center + 0.1f * b3Vec3_axisY, 0.02f, b3_colorGreen ); + } + else if ( axis == 2 ) + { + DrawArrow( m_scene, center, center + 0.1f * b3Vec3_axisZ, 0.02f, b3_colorBlue ); + } + else + { + DrawSphere( m_scene, b3Transform_identity, { center, 0.03f }, b3_colorOrange ); + } + } + + // If the current level exceeds the target level, stop processing + if ( level > m_drawLevel ) + { + break; + } + + bool isLeaf = node->data.asNode.axis == 3; + if ( isLeaf == false ) + { + // Enqueue the left and right children with their respective levels + // I'm using some internal knowledge of how the node data is organized. + q.push( { node + 1, level + 1 } ); + q.push( { node + node->data.asNode.childOffset, level + 1 } ); + } + } + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 14.0f * fontSize; + ImGui::SetNextWindowPos( { 1.0f * fontSize, m_camera->m_height - height - 3.0f * fontSize }, ImGuiCond_Once ); + ImGui::SetNextWindowSize( { 20.0f * fontSize, height } ); + + ImGui::Begin( "Mesh Viewer", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + + if ( ImGui::SliderInt( "index", &m_meshIndex, 0, m_meshCount - 1 ) ) + { + LoadMesh(); + } + + if ( ImGui::RadioButton( "median split", m_medianSplit ) ) + { + m_medianSplit = true; + LoadMesh(); + } + + if ( ImGui::RadioButton( "sah binning", m_medianSplit == false ) ) + { + m_medianSplit = false; + LoadMesh(); + } + + if ( ImGui::Checkbox( "concave edges", &m_concaveEdges ) ) + { + LoadMesh(); + } + + if ( ImGui::Checkbox( "weld vertices", &m_weldVertices ) ) + { + LoadMesh(); + } + + if ( ImGui::SliderFloat( "tolerance", &m_weldToleranceMillimeters, 0.0f, 10.0f, "%.1f" ) ) + { + LoadMesh(); + } + + ImGui::SliderInt( "draw level", &m_drawLevel, -1, m_height ); + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + DrawTransform( m_scene, b3Transform_identity, 1.0f ); + + DrawTextLine( "triangle count = %d", m_mesh->triangleCount ); + DrawTextLine( "vertex count = %d", m_mesh->vertexCount ); + DrawTextLine( "degenerate count = %d", m_mesh->degenerateCount ); + DrawTextLine( "node area = %g", m_area ); + DrawTextLine( "height = %d", m_height ); + DrawTextLine( "build time (ms) = %g", m_buildTime ); + + DrawNodes(); + + b3Vec3 offset = { 0.01f, 0.01f, 0.01f }; + for ( int i = 0; i < m_mesh->degenerateCount; ++i ) + { + int triangleIndex = m_degenerateTriangles[i]; + int i1 = m_tempMesh.indices[3 * triangleIndex + 0]; + int i2 = m_tempMesh.indices[3 * triangleIndex + 1]; + int i3 = m_tempMesh.indices[3 * triangleIndex + 2]; + b3Vec3 v1 = m_tempMesh.vertices[i1]; + b3Vec3 v2 = m_tempMesh.vertices[i2]; + b3Vec3 v3 = m_tempMesh.vertices[i3]; + + float area = b3Length( b3Cross( v2 - v1, v3 - v1 ) ); + (void)area; + + b3Vec3 p = ( 1.0f / 3.0f ) * ( v1 + v2 + v3 ); + DrawPoint( m_scene, p, 10.0f, b3_colorCyan ); + + DrawWorldString( m_camera, p + offset, b3_colorOrange, "%d", triangleIndex ); + + { + DrawPoint( m_scene, v1, 10.0f, b3_colorRed ); + DrawPoint( m_scene, v2, 10.0f, b3_colorGreen ); + DrawPoint( m_scene, v3, 10.0f, b3_colorBlue ); + + DrawWorldString( m_camera, v1 + offset, b3_colorRed, "%d", i1 ); + DrawWorldString( m_camera, v2 + offset, b3_colorGreen, "%d", i2 ); + DrawWorldString( m_camera, v3 + offset, b3_colorBlue, "%d", i3 ); + } + } + } + + static Sample* Create( SampleContext* context ) + { + return new MeshViewer( context ); + } + + static constexpr int m_meshCount = 4; + static constexpr int m_degenerateCapacity = 64; + TempMesh m_tempMesh; + b3MeshData* m_mesh; + b3BodyId m_bodyId; + float m_area; + float m_weldToleranceMillimeters; + float m_buildTime; + int m_meshIndex; + int m_degenerateTriangles[m_degenerateCapacity]; + int m_drawLevel; + int m_height; + bool m_medianSplit; + bool m_concaveEdges; + bool m_weldVertices; +}; + +static int sampleMeshViewer = SampleManager::Register( "Mesh", "Viewer", MeshViewer::Create ); + +// Results 9/29/25 +// base median split: 0.222 ms per mesh +// weld: 0.526 +// weld + edge: 0.755 +class MeshCreationBenchmark : public Sample +{ +public: + explicit MeshCreationBenchmark( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 40.0f, b3Vec3_zero ); + } + + LoadTempMesh( "data/meshes/voxel_mesh_01.obj", m_tempMeshes + 0, 0.01f, true ); + LoadTempMesh( "data/meshes/voxel_mesh_02.obj", m_tempMeshes + 1, 0.01f, true ); + LoadTempMesh( "data/meshes/voxel_mesh_03.obj", m_tempMeshes + 2, 0.01f, true ); + LoadTempMesh( "data/meshes/voxel_mesh_04.obj", m_tempMeshes + 3, 0.01f, true ); + + m_time = FLT_MAX; + } + + void Step() override + { + bool computeArea = false; + int iterations = m_isDebug ? 1 : 10; + int meshCount = m_meshCount; + int triangleCount = 0; + float area = 0.0f; + + for ( int i = 0; i < iterations; ++i ) + { + uint64_t startTicks = b3GetTicks(); + + for ( int j = 0; j < meshCount; ++j ) + { + TempMesh& mesh = m_tempMeshes[j]; + b3MeshDef def = {}; + def.vertices = mesh.vertices.data(); + def.vertexCount = (int)mesh.vertices.size(); + def.indices = mesh.indices.data(); + def.triangleCount = (int)mesh.indices.size() / 3; + def.materialIndices = mesh.materialIndices.data(); + def.useMedianSplit = true; + def.identifyEdges = false; + def.weldVertices = true; + def.weldTolerance = 0.0015f; + + b3MeshData* meshData = b3CreateMesh( &def, nullptr, 0 ); + triangleCount += i == 0 ? meshData->triangleCount : 0; + + if ( computeArea && i == 0 ) + { + area += ComputeInternalSurfaceArea( meshData ); + } + + b3DestroyMesh( meshData ); + } + + float ms = b3GetMilliseconds( startTicks ); + m_time = b3MinFloat( m_time, ms ); + } + + DrawTextLine( "triangle count = %d, area = %g", triangleCount, area ); + DrawTextLine( "total time = %.4f ms", m_time ); + DrawTextLine( "time per mesh = %.4f ms", m_time / meshCount ); + } + + static Sample* Create( SampleContext* context ) + { + return new MeshCreationBenchmark( context ); + } + + static constexpr int m_meshCount = 4; + TempMesh m_tempMeshes[m_meshCount]; + float m_time; +}; + +static int sampleMeshCreationBenchmark = SampleManager::Register( "Mesh", "Creation Benchmark", MeshCreationBenchmark::Create ); + +class VoxelMesh : public Sample +{ +public: + explicit VoxelMesh( SampleContext* context ) + : Sample( context ) + { + b3Vec3 origin = { 5000.0f, 3500.0f, -7000.0f }; + + if ( context->restart == false ) + { + m_camera->SetView( -115.0f, 5.0f, 5.0f, b3Vec3{ 0.0f, 10.0f, 0.0f } + origin ); + } + + m_launchSpeedScale = 1.0f; + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "ground"; + bodyDef.position = origin; + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + float scale = 0.01f; + TempMesh tempMesh; + const char* fileName = "data/meshes/collision_mesh_01.obj"; + LoadTempMesh( fileName, &tempMesh, scale, true ); + + b3MeshDef def = {}; + def.vertices = tempMesh.vertices.data(); + def.vertexCount = (int)tempMesh.vertices.size(); + def.indices = tempMesh.indices.data(); + def.triangleCount = (int)tempMesh.indices.size() / 3; + def.materialIndices = tempMesh.materialIndices.data(); + def.useMedianSplit = true; + + // this has a big impact on stability because the faces are nearly coplanar + def.identifyEdges = true; + + def.weldVertices = true; + def.weldTolerance = 0.002f; + + m_meshData = b3CreateMesh( &def, nullptr, 0 ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateMeshShape( groundId, &shapeDef, m_meshData, b3Vec3_one ); + } + + { + b3Vec3 points[16]; + points[0] = { -3.13548756, 3.81141949, 237.289047 }; + points[1] = { -16.2333279, -23.4977913, 235.486603 }; + points[2] = { -13.8834839, 6.20244455, 23.7760544 }; + points[3] = { 14.0794125, 4.63170528, 24.9530792 }; + points[4] = { 3.98322797, -16.4192238, 236.704071 }; + points[5] = { -23.3520412, -3.26714420, 236.071594 }; + points[6] = { 13.4517860, -6.94963741, 24.4085312 }; + points[7] = { -5.24953651, 13.9316301, 24.5058060 }; + points[8] = { -4.65071201, -24.1484108, 235.974121 }; + points[9] = { -14.5111103, -5.37889385, 23.2315063 }; + points[10] = { 6.33307076, 13.2810068, 24.9935150 }; + points[11] = { 4.81784487, -14.6788225, 23.6787796 }; + points[12] = { -14.7180958, 4.46204281, 236.801331 }; + points[13] = { -23.9796677, -14.8484812, 235.527039 }; + points[14] = { 4.61085415, -4.83788204, 237.248611 }; + points[15] = { -6.76476669, -14.0281992, 23.1910706 }; + + for ( int i = 0; i < 16; ++i ) + { + b3Vec3 p = points[i]; + points[i] = b3MulSV( 0.01f, b3Vec3{ p.y, p.z, p.x } ); + } + + b3Hull* hull = b3CreateHull( points, 16, 16 ); + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "cylinder"; + bodyDef.type = b3_dynamicBody; + bodyDef.position = b3Vec3{ 5020.27734, 3506.22559, -6986.48584 }; + bodyDef.rotation = { { 0.664546967, 0.669287264, 0.135021493 }, 0.303646326 }; + + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.rollingResistance = 0.1f; + b3CreateHullShape( bodyId, &shapeDef, hull ); + b3DestroyHull( hull ); + } + + // float jointFrictionTorque = 5.0f; + // float jointHertz = 1.0f; + // float jointDampingRatio = 0.7f; + + m_human = {}; + // CreateHuman( &m_human, m_worldId, b3Vec3{ 15.0f, 10.0f, 15.0f } + origin, jointFrictionTorque, jointHertz, + // jointDampingRatio, 1, nullptr, false ); + } + + ~VoxelMesh() override + { + b3DestroyMesh( m_meshData ); + } + + void Step() override + { + Sample::Step(); + } + + static Sample* Create( SampleContext* context ) + { + return new VoxelMesh( context ); + } + + b3MeshData* m_meshData; + Human m_human; +}; + +static int sampleVoxelMesh = SampleManager::Register( "Mesh", "Voxel", VoxelMesh::Create ); diff --git a/samples/sample_ragdoll.cpp b/samples/sample_ragdoll.cpp new file mode 100644 index 0000000..86b31d2 --- /dev/null +++ b/samples/sample_ragdoll.cpp @@ -0,0 +1,484 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "camera.h" +#include "human.h" +#include "imgui.h" +#include "sample.h" +#include "scene.h" + +#include "box3d/box3d.h" + +class RagdollOnBox : public Sample +{ +public: + explicit RagdollOnBox( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 6.0f, b3Vec3_zero ); + EnableGrid( m_scene, true ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull box = b3MakeBoxHull( 10.0f, 1.0f, 10.0f ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + + m_jointFrictionTorque = 5.0f; + m_jointHertz = 1.0f; + m_jointDampingRatio = 0.7f; + + m_human = {}; + + Spawn(); + } + + void Spawn() + { + CreateHuman( &m_human, m_worldId, { 0.0f, 2.0f, 0.0f }, m_jointFrictionTorque, m_jointHertz, m_jointDampingRatio, 1, + nullptr, false ); + // Human_ApplyRandomAngularImpulse( &m_human, 10.0f ); + } + + void UpdateUI() override + { + float height = 140.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 350.0f, height ) ); + + ImGui::Begin( "Ragdoll on Box", nullptr, ImGuiWindowFlags_NoResize ); + ImGui::PushItemWidth( 200.0f ); + + if ( ImGui::SliderFloat( "Joint Friction", &m_jointFrictionTorque, 0.0f, 20.0f, "%3.0f" ) ) + { + Human_SetJointFrictionTorque( &m_human, m_jointFrictionTorque ); + } + + if ( ImGui::SliderFloat( "Hertz", &m_jointHertz, 0.0f, 20.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 RagdollOnBox( context ); + } + + Human m_human; + float m_jointFrictionTorque; + float m_jointHertz; + float m_jointDampingRatio; +}; + +static int sampleRagdollOnBox = SampleManager::Register( "Ragdoll", "Box", RagdollOnBox::Create ); + +class RagdollOnMesh : public Sample +{ +public: + explicit RagdollOnMesh( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 6.0f, b3Vec3_zero ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + m_groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + m_groundMesh = b3CreateGridMesh( 20, 20, 2.0f, 2, true ); + b3CreateMeshShape( m_groundId, &shapeDef, m_groundMesh, b3Vec3_one ); + } + + { + b3Transform transform; + transform.p = { 0.0f, 5.0f, -20.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 20.0f, 5.0f, 0.1f, transform ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( m_groundId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform; + transform.p = { 0.0f, 5.0f, 20.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 20.0f, 5.0f, 0.1f, transform ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( m_groundId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform; + transform.p = { -20.0f, 5.0f, 0.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, 5.0f, 20.0f, transform ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( m_groundId, &shapeDef, &wallBox.base ); + } + + { + b3Transform transform; + transform.p = { 20.0f, 5.0f, 0.0f }; + transform.q = b3Quat_identity; + b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, 5.0f, 20.0f, transform ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( m_groundId, &shapeDef, &wallBox.base ); + } + + m_jointFrictionTorque = 5.0f; + m_jointHertz = 2.0f; + m_jointDampingRatio = 0.7f; + + m_human = {}; + + Spawn(); + } + + ~RagdollOnMesh() override + { + b3DestroyMesh( m_groundMesh ); + } + + void Spawn() + { + CreateHuman( &m_human, m_worldId, { 0.0f, 1.0f, 0.0f }, m_jointFrictionTorque, m_jointHertz, m_jointDampingRatio, 1, + nullptr, false ); + // Human_AlignSpring( &m_human, m_worldId, m_groundId, 25.0f, 1.0f ); + // Human_ApplyRandomAngularImpulse( &m_human, 10.0f ); + // b3Body_SetType( m_human.bones[bone_thigh_l].bodyId, b3_kinematicBody ); + // b3Body_SetType( m_human.bones[bone_thigh_r].bodyId, b3_kinematicBody ); + // b3Body_SetType( m_human.bones[bone_pelvis].bodyId, b3_kinematicBody ); + // Human_CreateMotorAnchors( &m_human, m_worldId ); + Human_CreateParallelAnchors( &m_human, m_worldId ); + } + + void UpdateUI() override + { + float height = 140.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 350.0f, height ) ); + + ImGui::Begin( "Ragdoll", nullptr, ImGuiWindowFlags_NoResize ); + ImGui::PushItemWidth( 200.0f ); + + if ( ImGui::SliderFloat( "Joint Friction", &m_jointFrictionTorque, 0.0f, 20.0f, "%3.0f" ) ) + { + Human_SetJointFrictionTorque( &m_human, m_jointFrictionTorque ); + } + + if ( ImGui::SliderFloat( "Hertz", &m_jointHertz, 0.0f, 20.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 RagdollOnMesh( context ); + } + + b3MeshData* m_groundMesh; + b3BodyId m_groundId; + Human m_human; + float m_jointFrictionTorque; + float m_jointHertz; + float m_jointDampingRatio; +}; + +static int sampleRagdollMesh = SampleManager::Register( "Ragdoll", "Mesh", RagdollOnMesh::Create ); + +class RagdollPile : public Sample +{ +public: + enum + { +#ifdef NDEBUG + e_count = 20 +#else + e_count = 8 +#endif + }; + + explicit RagdollPile( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 180.0f, 30.0f, 20.0f, b3Vec3_zero ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + m_groundMesh = b3CreateGridMesh( 20, 20, 1.0f, 1, true ); + b3CreateMeshShape( groundId, &shapeDef, m_groundMesh, b3Vec3_one ); + + for ( int i = 0; i < e_count; ++i ) + { + b3Vec3 position = { 0.1f * i, 2.0f + 0.5f * i, -0.1f * i }; + float torque = 10.0f; + float hertz = 0.5f; + float damping = 0.7f; + int groupIndex = i; + void* userData = nullptr; + bool colorize = false; + CreateHuman( m_humans + i, m_worldId, position, torque, hertz, damping, groupIndex, userData, colorize ); + } + } + + ~RagdollPile() override + { + b3DestroyMesh( m_groundMesh ); + } + + static Sample* Create( SampleContext* context ) + { + return new RagdollPile( context ); + } + + b3MeshData* m_groundMesh; + Human m_humans[e_count] = {}; +}; + +static int sampleRagdollPile = SampleManager::Register( "Ragdoll", "Pile", RagdollPile::Create ); + +class RagdollIncline : public Sample +{ +public: + explicit RagdollIncline( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( -20.0f, 30.0f, 25.0f, b3Vec3_zero ); + } + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + m_groundMesh = b3CreateGridMesh( 4, 4, 2.0f, 1, true ); + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { -10.0f, 2.0f, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, -0.2f * B3_PI ); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateMeshShape( groundId, &shapeDef, m_groundMesh, b3Vec3_one ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, 0.0f, 0.0f }; + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + b3Vec3 scale = { 4.0f, 4.0f, 4.0f }; + b3CreateMeshShape( groundId, &shapeDef, m_groundMesh, scale ); + } + + m_human = {}; + b3Vec3 position = { -12.0f, 6.0f, 0.0f }; + float torque = 10.0f; + float hertz = 2.0f; + float damping = 0.7f; + int groupIndex = 1; + void* userData = nullptr; + bool colorize = false; + CreateHuman( &m_human, m_worldId, position, torque, hertz, damping, groupIndex, userData, colorize ); + m_time = 0.0f; + m_motorized = true; + } + + ~RagdollIncline() override + { + b3DestroyMesh( m_groundMesh ); + } + + void Step() override + { + if ( m_time > 2.0f && m_motorized == true ) + { + Human_SetJointFrictionTorque( &m_human, 0.5f ); + Human_SetJointSpringHertz( &m_human, 0.5f ); + m_motorized = false; + } + + m_time += m_context->hertz > 0.0f ? 1.0f / m_context->hertz : 0.0f; + + Sample::Step(); + } + + static Sample* Create( SampleContext* context ) + { + return new RagdollIncline( context ); + } + + b3MeshData* m_groundMesh; + Human m_human; + float m_time; + bool m_motorized; +}; + +static int sampleRagdollIncline = SampleManager::Register( "Ragdoll", "Incline", RagdollIncline::Create ); + +#if 0 +class RagdollPose : public Sample +{ +public: + static Sample* Create( SampleContext* context ) + { + return new RagdollPose( context ); + } + + explicit RagdollPose( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 6.0f, b3Vec3_zero ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, 0.0f, 0.0f }; + // bodyDef.rotation = b3Rotation(B3_VEC3_AXIS_Y, 0.25f * B3_PI); + b3BodyId groundId = m_worldId->CreateBody( &bodyDef ); + m_ground = b3CreateGrid( 4, 2.0f, 0.0f ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + groundId->AddMesh( &shapeDef, m_ground ); + + b3Hull* Hull = b3CreateOffsetBox( { { -3.0f, 0.5f, 0.0f }, b3Quat_identity }, { 0.25f, 0.5f, 3.0f } ); + groundId->AddHull( &shapeDef, Hull ); + b3DestroyHull( Hull ); + + m_motorized = false; + m_motorHertz = 1.0f; + m_human.Spawn( m_worldId, { 0.0f, 0.1f, 0.0f }, m_motorHertz, m_motorized ); + + m_poseControl = true; + m_poseHertz = 2.0f; + m_human.EnablePoseControl( m_worldId, m_poseHertz, m_poseControl ); + + m_time = 0.0f; + + { + b3Hull* Cylinder = b3CreateCylinder( 0.5f, 0.5f, 0.0f, 16 ); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 3.0f, 0.5f, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( B3_VEC3_AXIS_Z, 0.5f * B3_PI ); + b3BodyId Body = m_worldId->CreateBody( &bodyDef ); + Body->AddHull( &shapeDef, Cylinder ); + b3DestroyHull( Cylinder ); + } + + m_angle = 0.0f; + m_angularVelocity = 0.0f; + } + + ~RagdollPose() override + { + b3DestroyMesh( m_ground ); + } + + void OnRenderUI( GLFWwindow* ) override + { + ImGui::SetNextWindowPos( ImVec2( 10.0f, 600.0f ) ); + ImGui::SetNextWindowSize( ImVec2( 260.0f, 160.0f ) ); + ImGui::Begin( "Pose", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + + if ( ImGui::Checkbox( "motors", &m_motorized ) ) + { + m_human.EnableMotors( m_motorized ); + m_human.AdjustMotors( m_motorHertz ); + } + + if ( ImGui::SliderFloat( "motor hertz", &m_motorHertz, 0.01f, 20.0f, "%.2f" ) ) + { + m_human.AdjustMotors( m_motorHertz ); + } + + if ( ImGui::Checkbox( "pose", &m_poseControl ) ) + { + m_human.EnablePoseControl( m_worldId, m_poseHertz, m_poseControl ); + } + + if ( ImGui::SliderFloat( "pose hertz", &m_poseHertz, 0.01f, 8.0f, "%.2f" ) ) + { + m_human.AdjustPoseControl( m_poseHertz ); + } + + ImGui::SliderFloat( "omega", &m_angularVelocity, 0.0f, 8.0f, "%.1f" ); + + ImGui::End(); + } + + void OnUpdate() override + { + float timeStep = 1.0f / m_context->Settings.Frequency; + m_time += timeStep; + + if ( m_poseControl ) + { + b3Transform transform = m_human.m_rootBody->GetTransform(); + transform.p.x = 4.0f * sinf( 0.5f * m_time ); + transform.p.y = 0.5f * ( cosf( 1.0f * m_time + B3_PI ) + 1.0f ); + m_angle += m_angularVelocity * timeStep; + transform.q = b3MakeQuatFromAxisAngle( B3_VEC3_AXIS_Y, m_angle ); + m_human.DriveBase( transform, timeStep ); + } + + // transform = mHuman.m_bones[0].poseJoint->GetRelativeTransform(); + // transform.Translation.Y = 0.5f * ( cosf( 1.0f * mTime + B3_PI ) + 1.0f ); + // mHuman.m_bones[0].poseJoint->SetRelativeTransform( transform ); + + Sample::OnUpdate(); + } + + b3MeshData* m_ground; + Human m_human; + float m_time; + float m_motorHertz; + float m_poseHertz; + float m_angle; + float m_angularVelocity; + bool m_motorized; + bool m_poseControl; +}; + +static int sampleRagodllPose = SampleManager::Register( "Ragdoll", "Pose", RagdollPose::Create ); +#endif diff --git a/samples/sample_robustness.cpp b/samples/sample_robustness.cpp new file mode 100644 index 0000000..f32befb --- /dev/null +++ b/samples/sample_robustness.cpp @@ -0,0 +1,404 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "camera.h" +#include "sample.h" +#include "scene.h" + +#include "box3d/box3d.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_camera->SetView( 45.0f, 20.0f, 50.0f, b3Vec3_zero ); + EnableGrid( m_scene, true ); + } + + float extent = 1.0f; + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull box = b3MakeTransformedBoxHull( 50.0f, 1.0f, 50.0f, { { 0.0f, -1.0f, 0.0f }, b3Quat_identity } ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + b3BoxHull box = b3MakeBoxHull( extent, extent, extent ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + 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, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + shapeDef.density = count == 1 ? ( j + 1.0f ) * 100.0f : 1.0f; + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + + --count; + y += 2.0f * extent; + } + } + } + } + + static Sample* Create( SampleContext* context ) + { + return new HighMassRatio1( context ); + } +}; + +static int sampleHighMassRatio1 = SampleManager::Register( "Robustness", "HighMassRatio1", HighMassRatio1::Create ); + +class OverlapRecovery : public Sample +{ +public: + explicit OverlapRecovery( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 45.0f, 20.0f, 50.0f, b3Vec3_zero ); + EnableGrid( m_scene, true ); + } + + 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; + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull box = b3MakeTransformedBoxHull( 20.0f, 1.0f, 20.0f, { { 0.0f, -1.0f, 0.0f }, b3Quat_identity } ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + + CreateScene(); + } + + ~OverlapRecovery() override + { + free( m_bodyIds ); + } + + void CreateScene() + { + for ( int i = 0; i < m_bodyCount; ++i ) + { + b3DestroyBody( m_bodyIds[i] ); + } + + b3World_SetContactTuning( m_worldId, m_hertz, m_dampingRatio, m_speed ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + + b3BoxHull box = b3MakeBoxHull( m_extent, m_extent, m_extent ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 1.0f; + + m_bodyCount = m_baseCount * ( m_baseCount + 1 ) / 2; + m_bodyIds = (b3BodyId*)realloc( m_bodyIds, m_bodyCount * sizeof( b3BodyId ) ); + + 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 }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + m_bodyIds[bodyIndex++] = bodyId; + + x += 2.0f * fraction * m_extent; + } + + y += 2.0f * fraction * m_extent; + } + + assert( bodyIndex == m_bodyCount ); + } + + void UpdateUI() override + { + float height = 220.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_context->camera.m_height - height - 50.0f ), 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 ); + } + + b3BodyId* 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 = SampleManager::Register( "Robustness", "Overlap Recovery", OverlapRecovery::Create ); + +class Cart : public Sample +{ +public: + explicit Cart( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 15.0f, { 0.0f, 2.0f, 0.0f } ); + //context->settings.subStepCount = 12; + EnableGrid( m_scene, true ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + } + + b3World_SetGravity( m_worldId, { 0, -22, 0 } ); + + m_contactHertz = 240.0f; + m_contactDampingRatio = 10.0f; + m_contactSpeed = 0.5f; + b3World_SetContactTuning( m_worldId, m_contactHertz, m_contactDampingRatio, m_contactSpeed ); + + m_constraintHertz = 240.0f; + m_constraintDampingRatio = 0.0f; + + m_chassisId = {}; + m_wheelId1 = {}; + m_wheelId2 = {}; + m_wheelId3 = {}; + m_wheelId4 = {}; + m_jointId1 = {}; + m_jointId2 = {}; + m_jointId3 = {}; + m_jointId4 = {}; + + CreateScene(); + } + + void CreateScene() + { + if ( B3_IS_NON_NULL( m_chassisId ) ) + { + b3DestroyBody( m_chassisId ); + } + + if ( B3_IS_NON_NULL( m_wheelId1 ) ) + { + b3DestroyBody( m_wheelId1 ); + } + + if ( B3_IS_NON_NULL( m_wheelId2 ) ) + { + b3DestroyBody( m_wheelId2 ); + } + + if ( B3_IS_NON_NULL( m_wheelId3 ) ) + { + b3DestroyBody( m_wheelId3 ); + } + + if ( B3_IS_NON_NULL( m_wheelId4 ) ) + { + b3DestroyBody( m_wheelId4 ); + } + + float yBase = 1.0f; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, yBase, 0.0f }; + m_chassisId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 1000.0f; + + b3BoxHull box = b3MakeTransformedBoxHull( 1.0f, 0.25f, 0.5f, { { 0.0f, 0.25f, 0.0f }, b3Quat_identity } ); + b3CreateHullShape( m_chassisId, &shapeDef, &box.base ); + + shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.rollingResistance = 0.02f; + shapeDef.density = 200.0f; + + b3Sphere sphere = { b3Vec3_zero, 0.1f }; + bodyDef.position = { -0.9f, yBase - 0.15f, 0.4f }; + m_wheelId1 = b3CreateBody( m_worldId, &bodyDef ); + b3CreateSphereShape( m_wheelId1, &shapeDef, &sphere ); + + bodyDef.position = { 0.9f, yBase - 0.15f, 0.4f }; + m_wheelId2 = b3CreateBody( m_worldId, &bodyDef ); + b3CreateSphereShape( m_wheelId2, &shapeDef, &sphere ); + + bodyDef.position = { 0.9f, yBase - 0.15f, -0.4f }; + m_wheelId3 = b3CreateBody( m_worldId, &bodyDef ); + b3CreateSphereShape( m_wheelId3, &shapeDef, &sphere ); + + bodyDef.position = { -0.9f, yBase - 0.15f, -0.4f }; + m_wheelId4 = b3CreateBody( m_worldId, &bodyDef ); + b3CreateSphereShape( m_wheelId4, &shapeDef, &sphere ); + + b3SphericalJointDef jointDef = b3DefaultSphericalJointDef(); + jointDef.base.constraintHertz = m_constraintHertz; + jointDef.base.constraintDampingRatio = m_constraintDampingRatio; + jointDef.base.drawScale = 0.5f; + + jointDef.base.bodyIdA = m_chassisId; + jointDef.base.bodyIdB = m_wheelId1; + jointDef.base.localFrameA.p = { -0.9f, -0.15f, 0.4f }; + jointDef.base.localFrameB.p = { 0.0f, 0.0f, 0.0f }; + m_jointId1 = b3CreateSphericalJoint( m_worldId, &jointDef ); + + jointDef.base.bodyIdA = m_chassisId; + jointDef.base.bodyIdB = m_wheelId2; + jointDef.base.localFrameA.p = { 0.9f, -0.15f, 0.4f }; + jointDef.base.localFrameB.p = { 0.0f, 0.0f, 0.0f }; + m_jointId2 = b3CreateSphericalJoint( m_worldId, &jointDef ); + + jointDef.base.bodyIdA = m_chassisId; + jointDef.base.bodyIdB = m_wheelId3; + jointDef.base.localFrameA.p = { 0.9f, -0.15f, -0.4f }; + jointDef.base.localFrameB.p = { 0.0f, 0.0f, 0.0f }; + m_jointId3 = b3CreateSphericalJoint( m_worldId, &jointDef ); + + jointDef.base.bodyIdA = m_chassisId; + jointDef.base.bodyIdB = m_wheelId4; + jointDef.base.localFrameA.p = { -0.9f, -0.15f, -0.4f }; + jointDef.base.localFrameB.p = { 0.0f, 0.0f, 0.0f }; + m_jointId4 = b3CreateSphericalJoint( m_worldId, &jointDef ); + } + + void UpdateUI() override + { + float height = 240.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_context->camera.m_height - height - 50.0f ), 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 ) + { + b3World_SetContactTuning( m_worldId, m_contactHertz, m_contactDampingRatio, m_contactSpeed ); + CreateScene(); + } + + ImGui::Separator(); + + changed = false; + ImGui::Text( "Joint" ); + changed = changed || ImGui::SliderFloat( "Hertz##joint", &m_constraintHertz, 0.0f, 240.0f, "%.f" ); + changed = changed || ImGui::SliderFloat( "Damping Ratio##joint", &m_constraintDampingRatio, 0.0f, 20.0f, "%.f" ); + + ImGui::Separator(); + + changed = changed || ImGui::Button( "Reset Scene" ); + + if ( changed ) + { + b3Joint_SetConstraintTuning( m_jointId1, m_constraintHertz, m_constraintDampingRatio ); + b3Joint_SetConstraintTuning( m_jointId2, m_constraintHertz, m_constraintDampingRatio ); + b3Joint_SetConstraintTuning( m_jointId3, m_constraintHertz, m_constraintDampingRatio ); + b3Joint_SetConstraintTuning( m_jointId4, m_constraintHertz, m_constraintDampingRatio ); + CreateScene(); + } + + ImGui::PopItemWidth(); + ImGui::End(); + } + + static Sample* Create( SampleContext* context ) + { + return new Cart( context ); + } + + b3BodyId m_chassisId; + b3BodyId m_wheelId1; + b3BodyId m_wheelId2; + b3BodyId m_wheelId3; + b3BodyId m_wheelId4; + b3JointId m_jointId1; + b3JointId m_jointId2; + b3JointId m_jointId3; + b3JointId m_jointId4; + + float m_contactHertz; + float m_contactDampingRatio; + float m_contactSpeed; + float m_constraintHertz; + float m_constraintDampingRatio; +}; + +static int sampleCart = SampleManager::Register( "Robustness", "Cart", Cart::Create ); diff --git a/samples/sample_shapes.cpp b/samples/sample_shapes.cpp new file mode 100644 index 0000000..3ec2f61 --- /dev/null +++ b/samples/sample_shapes.cpp @@ -0,0 +1,1145 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "camera.h" +#include "human.h" +#include "imgui.h" +#include "mesh_loader.h" +#include "utils.h" +#include "renderer.h" +#include "sample.h" +#include "scene.h" + +#include "box3d/box3d.h" + +class InclinedPlane : public Sample +{ +public: + explicit InclinedPlane( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( -55.0f, 30.0f, 60.0f, { 0.0f, 7.5f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.friction = 1.0f; + b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 50.0f ); + b3CreateHullShape( groundBody, &shapeDef, &groundBox.base ); + + bodyDef.position = { 0.0f, 7.5f, -5.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( { 1.0f, 0.0f, 0.0f }, 40.0f * B3_DEG_TO_RAD ); + b3BodyId planeBody = b3CreateBody( m_worldId, &bodyDef ); + b3BoxHull planeBox = b3MakeBoxHull( 16.0f, 0.5f, 10.0f ); + shapeDef.baseMaterial.friction = 1.0f; + b3CreateHullShape( planeBody, &shapeDef, &planeBox.base ); + + b3BoxHull box = b3MakeBoxHull( 1.0f, 1.0f, 1.0f ); + bodyDef.type = b3_dynamicBody; + for ( int index = 0; index < m_boxCount; ++index ) + { + bodyDef.position = { -10.0f + 5.0f * index, 15.75f, -10.6f }; + b3BodyId boxBody = b3CreateBody( m_worldId, &bodyDef ); + shapeDef.baseMaterial.friction = ( index + 1 ) * ( index + 1 ) * 0.04f; + b3CreateHullShape( boxBody, &shapeDef, &box.base ); + } + } + + static Sample* Create( SampleContext* context ) + { + return new InclinedPlane( context ); + } + + static constexpr int m_boxCount = 5; +}; + +static int sampleInclinedPlane = SampleManager::Register( "Shapes", "Inclined Plane", InclinedPlane::Create ); + +class RollingResistance : public Sample +{ +public: + explicit RollingResistance( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( -140.0f, 17.0f, 60.0f, { 0.0f, 7.5f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull mGround = b3MakeBoxHull( 50.0f, 1.0f, 50.0f ); + b3CreateHullShape( groundBody, &shapeDef, &mGround.base ); + + bodyDef.position = { 0.0f, 2.0f, -20.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( { 1.0f, 0.0f, 0.0f }, 10.0f * B3_DEG_TO_RAD ); + b3BodyId planeBody = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull mPlane = b3MakeBoxHull( 32.0f, 0.5f, 15.0f ); + b3CreateHullShape( planeBody, &shapeDef, &mPlane.base ); + + b3Sphere sphere = { b3Vec3_zero, 1.0f }; + bodyDef.type = b3_dynamicBody; + for ( int index = 0; index < m_count; ++index ) + { + bodyDef.position = { -25.0f + 5.0f * index, 8.0f, -24.0f }; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + + shapeDef.baseMaterial.rollingResistance = 0.05f * index; + b3CreateSphereShape( body, &shapeDef, &sphere ); + } + + b3Capsule capsule = { { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, 0.5f }; + bodyDef.type = b3_dynamicBody; + for ( int index = 0; index < m_count; ++index ) + { + bodyDef.position = { 2.0f + 5.0f * index, 8.0f, -24.0f }; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + + shapeDef.baseMaterial.rollingResistance = 0.05f * index; + b3CreateCapsuleShape( body, &shapeDef, &capsule ); + } + } + + static constexpr int m_count = 5; + + static Sample* Create( SampleContext* context ) + { + return new RollingResistance( context ); + } +}; + +static int sampleRollingResistance = SampleManager::Register( "Shapes", "Rolling Resistance", RollingResistance::Create ); + +class HighResistance : public Sample +{ +public: + explicit HighResistance( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 5.0f, 40.0f, { 0.0f, 7.5f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull mGround = b3MakeBoxHull( 50.0f, 1.0f, 50.0f ); + b3CreateHullShape( groundBody, &shapeDef, &mGround.base ); + + b3Capsule capsule = { { 0.0f, -1.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 0.5f }; + bodyDef.type = b3_dynamicBody; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, B3_DEG_TO_RAD * 30.0f ); + for ( int index = 0; index < m_count; ++index ) + { + bodyDef.position = { -22.0f + 5.0f * index, 1.5f, 0.0f }; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + + shapeDef.baseMaterial.rollingResistance = 0.2f * index; + b3CreateCapsuleShape( body, &shapeDef, &capsule ); + } + } + + static Sample* Create( SampleContext* context ) + { + return new HighResistance( context ); + } + + static constexpr int m_count = 10; +}; + +static int sampleHighResistance = SampleManager::Register( "Shapes", "High Resistance", HighResistance::Create ); + +class IsotropicFriction : public Sample +{ +public: + explicit IsotropicFriction( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 30.0f, 150.0f, b3Vec3_zero ); + EnableGrid( m_scene, true ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull mGround = b3MakeBoxHull( 75.0f, 1.0f, 75.0f ); + shapeDef.baseMaterial.friction = 1.0f; + b3CreateHullShape( groundBody, &shapeDef, &mGround.base ); + + b3BoxHull box = b3MakeBoxHull( 1.0f, 1.0f, 1.0f ); + bodyDef.type = b3_dynamicBody; + shapeDef.baseMaterial.friction = 0.6f; + for ( int index = 0; index < m_boxCount; ++index ) + { + float alpha = B3_PI / 16.0f * index; + b3CosSin cs = b3ComputeCosSin( alpha ); + b3Vec3 position = { 15.0f * cs.cosine, 1.0f, 15.0f * cs.sine }; + b3Quat orientation = b3MakeQuatFromAxisAngle( { 0.0f, 1.0f, 0.0f }, -alpha ); + b3Vec3 velocity = { 25.0f * cs.cosine, 0.0f, 25.0f * cs.sine }; + + bodyDef.position = position; + bodyDef.rotation = orientation; + bodyDef.linearVelocity = velocity; + b3BodyId boxBody = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( boxBody, &shapeDef, &box.base ); + } + } + + static Sample* Create( SampleContext* context ) + { + return new IsotropicFriction( context ); + } + + static constexpr int m_boxCount = 32; +}; + +static int sampleIsotropicFriction = SampleManager::Register( "Shapes", "Isotropic Friction", IsotropicFriction::Create ); + +// todo what is the point of this? +class SlideTwist : public Sample +{ +public: + explicit SlideTwist( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( -30.0f, 17.0f, 22.0f, { 0.0f, 5.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + b3Quat orientation = b3MakeQuatFromAxisAngle( b3Vec3_axisX, 20.0f * B3_DEG_TO_RAD ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.friction = 1.0f; + b3BoxHull mGround = b3MakeBoxHull( 50.0f, 1.0f, 50.0f ); + b3CreateHullShape( groundBody, &shapeDef, &mGround.base ); + + bodyDef.position = { 0.0f, 4.0f, 0.0f }; + bodyDef.rotation = orientation; + b3BodyId planeBody = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull mPlane = b3MakeBoxHull( 10.0f, 0.5f, 10.0f ); + shapeDef.baseMaterial.friction = 0.6f; + b3CreateHullShape( planeBody, &shapeDef, &mPlane.base ); + + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 5.0f, 0.0f }; + bodyDef.rotation = orientation; + bodyDef.angularVelocity = 25.0f * b3RotateVector( orientation, b3Vec3_axisY ); + b3BodyId boxBody = b3CreateBody( m_worldId, &bodyDef ); + b3BoxHull mBox = b3MakeBoxHull( 1.0f, 0.5f, 1.0f ); + shapeDef.baseMaterial.friction = 0.3f; + b3CreateHullShape( boxBody, &shapeDef, &mBox.base ); + } + + static Sample* Create( SampleContext* context ) + { + return new SlideTwist( context ); + } +}; + +static int sampleSlideTwist = SampleManager::Register( "Shapes", "Slide Twist", SlideTwist::Create ); + +class Restitution : public Sample +{ +public: + enum ShapeType + { + e_sphereShape = 0, + e_boxShape + }; + + explicit Restitution( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 25.0f, 85.0f, { 0.0f, 20.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef ); + b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 20.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundBody, &shapeDef, &groundBox.base ); + + m_shapeType = e_sphereShape; + + CreateBodies(); + } + + void CreateBodies() + { + for ( int i = 0; i < m_count; ++i ) + { + if ( B3_IS_NON_NULL( m_bodyIds[i] ) ) + { + b3DestroyBody( m_bodyIds[i] ); + m_bodyIds[i] = b3_nullBodyId; + } + } + + b3Sphere sphere = { b3Vec3_zero, 0.5f }; + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_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, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + m_bodyIds[i] = bodyId; + + if ( m_shapeType == e_sphereShape ) + { + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + } + else + { + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + + shapeDef.baseMaterial.restitution += dr; + x += dx; + } + } + + void UpdateUI() override + { + float height = 100.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); + + ImGui::Begin( "Restitution", nullptr, ImGuiWindowFlags_NoResize ); + + if ( ImGui::RadioButton( "Sphere", m_shapeType == e_sphereShape ) ) + { + m_shapeType = e_sphereShape; + CreateBodies(); + } + + if ( ImGui::RadioButton( "Box", m_shapeType == e_boxShape ) ) + { + m_shapeType = e_boxShape; + CreateBodies(); + } + + ImGui::End(); + } + + static Sample* Create( SampleContext* context ) + { + return new Restitution( context ); + } + + static constexpr int m_count = 40; + + b3BodyId m_bodyIds[m_count] = {}; + ShapeType m_shapeType; +}; + +static int sampleRestitution = SampleManager::Register( "Shapes", "Restitution", Restitution::Create ); + +// This shows an optimization when creating many static shapes you can skip having them invoke collision, assuming +// dynamic bodies are added after the static bodies. +class StaticInvoke : public Sample +{ +public: + explicit StaticInvoke( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 25.0f, 10.0f, { 0.0f, 1.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef ); + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundBody, &shapeDef, &groundBox.base ); + + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.25f, 1.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + shapeDef.baseMaterial.rollingResistance = 0.2f; + b3Sphere sphere = { b3Vec3_zero, 0.5f }; + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + + m_invoke = false; + m_bodyId = {}; + } + + void CreateStatic() + { + if ( B3_IS_NON_NULL( m_bodyId ) ) + { + b3DestroyBody( m_bodyId ); + m_bodyId = b3_nullBodyId; + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, 0.5f, 0.0f }; + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3Sphere sphere = { b3Vec3_zero, 0.5f }; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.invokeContactCreation = m_invoke; + + b3CreateSphereShape( m_bodyId, &shapeDef, &sphere ); + } + + void UpdateUI() override + { + float height = 150.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); + + ImGui::Begin( "Restitution", nullptr, ImGuiWindowFlags_NoResize ); + + if ( ImGui::RadioButton( "Invoke", m_invoke == true ) ) + { + m_invoke = true; + } + + if ( ImGui::RadioButton( "Passive", m_invoke == false ) ) + { + m_invoke = false; + } + + if ( B3_IS_NULL( m_bodyId ) ) + { + if ( ImGui::Button( "Create" ) ) + { + CreateStatic(); + } + } + else + { + if ( ImGui::Button( "Destroy" ) ) + { + b3DestroyBody( m_bodyId ); + m_bodyId = {}; + } + } + + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 4.0f ); + } + + void Step() override + { + Sample::Step(); + + if ( m_stepCount == 20 ) + { + CreateStatic(); + } + } + + static Sample* Create( SampleContext* context ) + { + return new StaticInvoke( context ); + } + + b3BodyId m_bodyId; + bool m_invoke; +}; + +static int sampleStaticInvoke = SampleManager::Register( "Shapes", "Static Invoke", StaticInvoke::Create ); + +class ConveyorBelt : public Sample +{ +public: + explicit ConveyorBelt( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 25.0f, 40.0f, { 0.0f, 1.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + // Ground + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + } + + // Platform + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { -5.0f, 5.0f, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisY, 0.2f ); + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull box = b3MakeBoxHull( 10.0f, 0.25f, 2.0f ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.friction = 0.8f; + shapeDef.baseMaterial.tangentVelocity = { 2.0f, 0.0f, 0.0f }; + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + + // Boxes + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull cube = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + for ( int i = 0; i < 5; ++i ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { -10.0f + 2.0f * i, 7.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3CreateHullShape( bodyId, &shapeDef, &cube.base ); + } + } + + void Render() override + { + Sample::Render(); + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 4.0f ); + } + + static Sample* Create( SampleContext* context ) + { + return new ConveyorBelt( context ); + } +}; + +static int sampleConveyorBelt = SampleManager::Register( "Shapes", "Conveyor Belt", ConveyorBelt::Create ); + +class ConveyorMesh : public Sample +{ +public: + explicit ConveyorMesh( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 65.0f, 25.0f, 28.0f, { 0.0f, 1.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + // Ground + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + } + + // Mesh + { + m_meshData = CreateMeshData( "data/meshes/conveyor.obj", 1.0f, false, true, true, true ); + + int triangleCount = m_meshData->triangleCount; + + uint8_t* materialIndices = (uint8_t*)( (intptr_t)m_meshData + m_meshData->materialOffset ); + + memset( materialIndices, 0, triangleCount * sizeof( uint8_t ) ); + m_velocities[0] = { 0.0f, 0.0f, 0.0f }; + + // +x -z + materialIndices[0] = 1; + materialIndices[4] = 1; + m_velocities[1] = { 0.7f, 0.0f, -0.2f }; + + // +x +z + materialIndices[9] = 2; + materialIndices[12] = 2; + m_velocities[2] = { 0.6f, 0.0f, 0.4f }; + + // +z + materialIndices[21] = 3; + materialIndices[38] = 3; + m_velocities[3] = { 0.0f, 0.0f, 1.3f }; + + // -x +z + materialIndices[43] = 4; + materialIndices[46] = 4; + m_velocities[4] = { -0.6f, 0.0f, 0.4f }; + + // -x -z + materialIndices[30] = 5; + materialIndices[33] = 5; + m_velocities[5] = { -0.75f, 0.0f, -0.4f }; + + // -z + materialIndices[18] = 6; + materialIndices[24] = 6; + m_velocities[6] = { 0.0f, 0.0f, -1.3f }; + + b3SurfaceMaterial materials[7]; + for ( int i = 0; i < 7; ++i ) + { + materials[i] = b3DefaultSurfaceMaterial(); + materials[i].friction = 0.8f; + materials[i].tangentVelocity = 2.0f * m_velocities[i]; + } + + m_meshTransform.p = { 0.0f, 0.5f, 6.0f }; + m_meshTransform.q = b3MakeQuatFromAxisAngle( b3Vec3_axisY, 0.5f * B3_PI ); + // m_meshTransform.q = b3Quat_identity; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = m_meshTransform.p; + bodyDef.rotation = m_meshTransform.q; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.materials = materials; + shapeDef.materialCount = 7; + b3CreateMeshShape( bodyId, &shapeDef, m_meshData, b3Vec3_one ); + } + + // High number of sides to stress the collision code + // Normally the number of sides should be 16 or less. + m_cylinderHull = b3CreateCylinder( 0.3f, 0.15f, 0.0f, 32 ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + // Cylinders + for ( int i = 0; i < 20; ++i ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { -8.5f + 0.9f * i, 1.5f, -5.5f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3CreateHullShape( bodyId, &shapeDef, m_cylinderHull ); + } + +#if 0 + // Boxes + b3BoxHull cube = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + for ( int i = 0; i < 5; ++i ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { -8.5f + 3.0f * i, 2.0f, -7.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3CreateHullShape( bodyId, &shapeDef, &cube.base ); + } + b3Sphere sphere = { b3Vec3_zero, 0.25f }; + shapeDef.baseMaterial.rollingResistance = 0.1f; + for ( int i = 0; i < 10; ++i ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = { -8.5f + 2.0f * i, 2.0f, -6.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + } +#endif + +#if 0 + for ( int i = 0; i < 10; ++i ) + { + Human human = {}; + CreateHuman( &human, m_worldId, { -8.0f + 2.0f * i, 3.0f, -5.5f }, 10.0f, 1.0f, 1.0f, 0, nullptr, true ); + } +#endif + } + + ~ConveyorMesh() override + { + b3DestroyMesh( m_meshData ); + b3DestroyHull( m_cylinderHull ); + } + + void Render() override + { + Sample::Render(); + + int triangleCount = m_meshData->triangleCount; + const b3MeshTriangle* triangles = b3GetMeshTriangles( m_meshData ); + const b3Vec3* vertices = b3GetMeshVertices( m_meshData ); + const uint8_t* materialIndices = b3GetMeshMaterialIndices( m_meshData ); + + for ( int i = 0; i < triangleCount; ++i ) + { + const b3MeshTriangle* t = triangles + i; + b3Vec3 v1 = vertices[t->index1]; + b3Vec3 v2 = vertices[t->index2]; + b3Vec3 v3 = vertices[t->index3]; + + b3Vec3 n = b3Cross( v2 - v1, v3 - v1 ); + n = b3Normalize( n ); + + if ( n.y < 0.9f ) + { + continue; + } + + b3Vec3 p = 1.0f / 3.0f * ( v1 + v2 + v3 ); + p = b3TransformPoint( m_meshTransform, p ); + + DrawWorldString( m_camera, p, b3_colorAqua, "%d", i ); + + int materialIndex = materialIndices[i]; + + b3Vec3 v = b3RotateVector( m_meshTransform.q, m_velocities[materialIndex] ); + DrawLine( m_scene, p, p + v, b3_colorBlueViolet ); + } + + DrawTransform( m_scene, b3Transform_identity, 0.5f ); + } + + static Sample* Create( SampleContext* context ) + { + return new ConveyorMesh( context ); + } + + b3Transform m_meshTransform; + b3MeshData* m_meshData; + b3Hull* m_cylinderHull; + b3Vec3 m_velocities[7]; +}; + +static int sampleConveyorMesh = SampleManager::Register( "Shapes", "Conveyor Mesh", ConveyorMesh::Create ); + +class Wind : public Sample +{ +public: + enum ShapeType + { + e_sphereShape = 0, + e_capsuleShape, + e_boxShape + }; + + explicit Wind( SampleContext* context ) + : Sample( context ) + , m_bodyIds{} + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 0.0f, 5.0f, { 0.0f, 1.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + m_groundId = b3CreateBody( m_worldId, &bodyDef ); + } + + m_shapeType = e_sphereShape; + m_wind = { 6.0f, 0.0f }; + m_drag = 1.0f; + m_lift = 0.75f; + m_count = 10; + m_noise = { 0.0f, 0.0f }; + + // Need this to be false for debug draw to work + m_stepWhilePaused = false; + + CreateScene(); + } + + void CreateScene() + { + for ( int i = 0; i < m_maxCount; ++i ) + { + if ( B3_IS_NON_NULL( m_bodyIds[i] ) ) + { + b3DestroyBody( m_bodyIds[i] ); + m_bodyIds[i] = b3_nullBodyId; + } + } + + float radius = 0.1f; + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, radius }; + b3Capsule capsule = { { 0.0f, -radius }, { 0.0f, radius }, 0.25f * radius }; + b3BoxHull box = b3MakeBoxHull( 0.25f * radius, 1.25f * radius, 0.5f * radius ); + + b3SphericalJointDef jointDef = b3DefaultSphericalJointDef(); + jointDef.base.bodyIdA = m_groundId; + jointDef.base.localFrameA.p = { 0.0f, 2.0f + radius }; + jointDef.base.drawScale = 0.1f; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 20.0f; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_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] = b3CreateBody( m_worldId, &bodyDef ); + + if ( m_shapeType == e_sphereShape ) + { + b3CreateSphereShape( m_bodyIds[i], &shapeDef, &sphere ); + } + else if ( m_shapeType == e_capsuleShape ) + { + b3CreateCapsuleShape( m_bodyIds[i], &shapeDef, &capsule ); + } + else + { + b3CreateHullShape( m_bodyIds[i], &shapeDef, &box.base ); + } + + jointDef.base.bodyIdB = m_bodyIds[i]; + jointDef.base.localFrameB.p = { 0.0f, radius }; + b3CreateSphericalJoint( m_worldId, &jointDef ); + + jointDef.base.bodyIdA = m_bodyIds[i]; + jointDef.base.localFrameA.p = { 0.0f, -radius }; + } + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 15.0f * fontSize; + ImGui::SetNextWindowPos( { 0.5f * fontSize, m_camera->m_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, -50.0f, 50.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 Render() override + { + Sample::Render(); + + DrawGrid( m_scene, 20 ); + } + + void Step() override + { + bool shouldStep = m_context->pause == false || m_context->singleStep > 0; + Sample::Step(); + + if ( shouldStep == true ) + { + float speed; + b3Vec3 direction = b3GetLengthAndNormalize( &speed, m_wind ); + b3Vec3 wind = b3MulSV( speed, b3Add( direction, m_noise ) ); + + for ( int i = 0; i < m_count; ++i ) + { + b3ShapeId shapeIds[1]; + int count = b3Body_GetShapes( m_bodyIds[i], shapeIds, 1 ); + for ( int j = 0; j < count; ++j ) + { + b3Shape_ApplyWind( shapeIds[j], wind, m_drag, m_lift, 10.0f, true ); + } + } + + b3Vec3 rand = RandomVec3( { -0.3f, -0.3f, -0.3f }, { 0.3f, 0.3f, 0.3f } ); + m_noise = b3Lerp( m_noise, rand, 0.05f ); + + DrawLine( m_scene, b3Vec3_zero, b3MulSV( 0.2f, wind ), b3_colorFuchsia ); + } + } + + static Sample* Create( SampleContext* context ) + { + return new Wind( context ); + } + + static constexpr int m_maxCount = 60; + + ShapeType m_shapeType; + b3Vec3 m_wind; + float m_drag; + float m_lift; + b3Vec3 m_noise; + b3BodyId m_groundId; + b3BodyId m_bodyIds[m_maxCount]; + int m_count; +}; + +static int sampleWind = SampleManager::Register( "Shapes", "Wind", Wind::Create ); + +class WindDrop : public Sample +{ +public: + explicit WindDrop( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, -10.0f, 20.0f, { 0.0f, 5.0f, 0.0f } ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "ground"; + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull hull = b3MakeBoxHull( 15.0f, 1.0f, 15.0f ); + b3CreateHullShape( groundId, &shapeDef, &hull.base ); + } + + m_drag = 1.0f; + m_lift = 4.0f; + + // Need this to be false for debug draw to work + m_stepWhilePaused = false; + + float radius = 0.1f; + // b3BoxHull box = b3MakeBoxHull( 0.25f * radius, 1.25f * radius, 0.25f * radius ); + b3BoxHull box = b3MakeBoxHull( 4.0f * radius, 0.1f * radius, 4.0f * radius ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 2.0f; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.linearVelocity = { 0.0f, 0.0f, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisX, 0.25f ); + bodyDef.gravityScale = 0.5f; + + bodyDef.position = { 0.0f, 10.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + m_shapeId = b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + + void Render() override + { + Sample::Render(); + + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 1.0f ); + } + + void Step() override + { + bool shouldStep = m_context->pause == false || m_context->singleStep > 0; + Sample::Step(); + + if ( shouldStep == true ) + { + b3Shape_ApplyWind( m_shapeId, b3Vec3_zero, m_drag, m_lift, 10.0f, true ); + } + } + + static Sample* Create( SampleContext* context ) + { + return new WindDrop( context ); + } + + float m_drag; + float m_lift; + b3ShapeId m_shapeId; +}; + +static int sampleWindDrop = SampleManager::Register( "Shapes", "Wind Drop", WindDrop::Create ); + +class WindFlap : public Sample +{ +public: + explicit WindFlap( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, -10.0f, 20.0f, { 0.0f, 5.0f, 0.0f } ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "ground"; + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull hull = b3MakeBoxHull( 50.0f, 1.0f, 50.0f ); + b3CreateHullShape( groundId, &shapeDef, &hull.base ); + } + + m_drag = 1.0f; + m_lift = 2.0f; + + // Need this to be false for debug draw to work + m_stepWhilePaused = false; + + float a = 0.4f; + // b3BoxHull box = b3MakeBoxHull( 0.25f * radius, 1.25f * radius, 0.25f * radius ); + b3Capsule capsule = { { 0.0f, 0.0f, -a }, { 0.0f, 0.0f, a }, 0.25f * a }; + //b3BoxHull box = b3MakeBoxHull( 2.0f * a, 0.01f, a ); + b3Transform wingTransform1 = {b3Vec3_zero, b3MakeQuatFromAxisAngle(b3Vec3_axisX, 0.1f)}; + b3BoxHull box1 = b3MakeTransformedBoxHull( 2.0f * a, 0.01f, a, wingTransform1 ); + b3Transform wingTransform2 = {b3Vec3_zero, b3MakeQuatFromAxisAngle(b3Vec3_axisX, 0.1f)}; + b3BoxHull box2 = b3MakeTransformedBoxHull( 2.0f * a, 0.01f, a, wingTransform2 ); + + float y = 20.0f; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + //bodyDef.gravityScale = 0.5f; + + shapeDef.density = 5.0f; + bodyDef.position = { -2.0f * a, y, 0.0f }; + b3BodyId wingBodyId1 = b3CreateBody( m_worldId, &bodyDef ); + m_shapeId1 = b3CreateHullShape( wingBodyId1, &shapeDef, &box1.base ); + + bodyDef.position = { 2.0f * a, y, 0.0f }; + b3BodyId wingBodyId2 = b3CreateBody( m_worldId, &bodyDef ); + m_shapeId2 = b3CreateHullShape( wingBodyId2, &shapeDef, &box2.base ); + + bodyDef.position = { 0.0f, y, 0.0f }; + //bodyDef.type = b3_staticBody; + b3BodyId torsoBodyId = b3CreateBody( m_worldId, &bodyDef ); + + shapeDef.density = 10.0f; + m_torsoShapeId = b3CreateCapsuleShape( torsoBodyId, &shapeDef, &capsule ); + + b3RevoluteJointDef jointDef = b3DefaultRevoluteJointDef(); + jointDef.base.drawScale = 0.1f; + jointDef.base.bodyIdA = torsoBodyId; + jointDef.base.localFrameA.p = { 0.0f, 0.0f, 0.0f }; + jointDef.base.bodyIdB = wingBodyId1; + jointDef.base.localFrameB.p = { 2.0f * a, 0.0f, 0.0f }; + jointDef.enableSpring = true; + jointDef.hertz = 6.0f; + jointDef.dampingRatio = 0.5f; + jointDef.enableLimit = true; + jointDef.lowerAngle = -30.0f * B3_PI / 180.0f; + jointDef.upperAngle = 30.0f * B3_PI / 180.0f; + m_jointId1 = b3CreateRevoluteJoint( m_worldId, &jointDef ); + + jointDef.base.bodyIdB = wingBodyId2; + jointDef.base.localFrameB.p = { -2.0f * a, 0.0f, 0.0f }; + m_jointId2 = b3CreateRevoluteJoint( m_worldId, &jointDef ); + + b3FilterJointDef filterDef = b3DefaultFilterJointDef(); + filterDef.base.bodyIdA = wingBodyId1; + filterDef.base.bodyIdB = wingBodyId2; + b3CreateFilterJoint( m_worldId, &filterDef ); + + m_time = 0.0f; + } + + void Render() override + { + Sample::Render(); + + b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }; + DrawTransform( m_scene, transform, 1.0f ); + } + + void Step() override + { + bool shouldStep = m_context->pause == false || m_context->singleStep > 0; + Sample::Step(); + + if ( shouldStep == true ) + { + float maxSpeed = 10.0f; + bool wake = false; + b3Shape_ApplyWind( m_shapeId1, b3Vec3_zero, m_drag, m_lift, maxSpeed, wake ); + b3Shape_ApplyWind( m_shapeId2, b3Vec3_zero, m_drag, m_lift, maxSpeed, wake ); + //b3Shape_ApplyWind( m_torsoShapeId, b3Vec3_zero, m_drag, m_lift, maxSpeed, wake ); + + float angle = b3Sin( 10.0f * m_time ); + b3RevoluteJoint_SetTargetAngle(m_jointId1, angle); + b3RevoluteJoint_SetTargetAngle(m_jointId2, -angle); + + m_time += m_context->hertz > 0.0f ? 1.0f / m_context->hertz : 0.0f; + } + } + + static Sample* Create( SampleContext* context ) + { + return new WindFlap( context ); + } + + float m_time; + float m_drag; + float m_lift; + b3ShapeId m_shapeId1; + b3ShapeId m_shapeId2; + b3ShapeId m_torsoShapeId; + b3JointId m_jointId1; + b3JointId m_jointId2; +}; + +static int sampleWindFlap = SampleManager::Register( "Shapes", "Wind Flap", WindFlap::Create ); diff --git a/samples/sample_stacking.cpp b/samples/sample_stacking.cpp new file mode 100644 index 0000000..c58de83 --- /dev/null +++ b/samples/sample_stacking.cpp @@ -0,0 +1,955 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "camera.h" +#include "human.h" +#include "imgui.h" +#include "mesh_loader.h" +#include "sample.h" +#include "scene.h" + +#include "box3d/box3d.h" + +class CardHouseThick : public Sample +{ +public: + explicit CardHouseThick( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 25.0f, 10.0f, { 0.0f, 2.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + const float alpha = 25.0f * B3_DEG_TO_RAD; + const float width = 0.38f; + const float height = 0.98f; + const float depth = 0.08f; + + float offsetX = 0.5f * height * b3Sin( alpha ) + 0.045f; + float offsetY = 0.5f * height * b3Cos( alpha ) + 0.035f; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + b3BoxHull mGround = b3MakeOffsetBoxHull( 10.0f, 1.0f, 10.0f, {0.0f, -1.0f, 0.0f} ); + b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( groundBody, &shapeDef, &mGround.base ); + + b3BoxHull box = b3MakeBoxHull( 0.5f * depth, 0.5f * height, 0.5f * width ); + AddVerticalRow( 4, -6.0f * offsetX, offsetX, offsetY, alpha, box ); + AddHorizontalRow( 3, -4.0f * offsetX, 4.0f * offsetX, 2.0f * offsetY + 0.04f, box ); + AddVerticalRow( 3, -4.0f * offsetX, offsetX, 3.0f * offsetY + 0.08f, alpha, box ); + AddHorizontalRow( 2, -2.0f * offsetX, 4.0f * offsetX, 4.0f * offsetY + 0.12f, box ); + AddVerticalRow( 2, -2.0f * offsetX, offsetX, 5.0f * offsetY + 0.16f, alpha, box ); + AddHorizontalRow( 1, -0.0f * offsetX, 4.0f * offsetX, 6.0f * offsetY + 0.20f, box ); + AddVerticalRow( 1, -0.0f * offsetX, offsetX, 7.0f * offsetY + 0.24f, alpha, box ); + } + + void AddVerticalRow( int n, float startX, float offsetX, float startY, float alpha, const b3BoxHull& box ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.friction = 0.8f; + + for ( int index = 0; index < n; ++index ) + { + bodyDef.position = { startX - offsetX, startY, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, -alpha ); + b3BodyId body1 = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( body1, &shapeDef, &box.base ); + + bodyDef.position = { startX + offsetX, startY, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, alpha ); + b3BodyId body2 = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( body2, &shapeDef, &box.base ); + + startX += 4.0f * offsetX; + } + } + + void AddHorizontalRow( int n, float startX, float offsetX, float startY, const b3BoxHull& box ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.friction = 0.8f; + + for ( int index = 0; index < n; ++index ) + { + bodyDef.position = { startX + index * offsetX, startY, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.5f * B3_PI ); + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( body, &shapeDef, &box.base ); + } + } + + static Sample* Create( SampleContext* context ) + { + return new CardHouseThick( context ); + } +}; + +static int sampleCardHouseThick = SampleManager::Register( "Stacking", "Card House Thick", CardHouseThick::Create ); + +// From PEEL +class CardHouse : public Sample +{ +public: + explicit CardHouse( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + b3Vec3 pivot = { 0.75, 1.0, 0.4f }; + m_camera->SetView( 0.0f, 15.0f, 3.0f, pivot ); + EnableGrid( m_scene, true ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -2.0f }; + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.friction = 0.7f; + + b3BoxHull groundBox = b3MakeBoxHull( 40.0f, 2.0f, 40.0f ); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + + float cardHeight = 0.2f; + float cardThickness = 0.001f; + float cardDepth = 0.1f; + + float angle0 = 25.0f * B3_PI / 180.0f; + float angle1 = -25.0f * B3_PI / 180.0f; + float angle2 = 0.5f * B3_PI; + + // todo box hull is limiting the minimum thickness, breaking this test + b3BoxHull cardBox = b3MakeBoxHull( cardThickness, cardHeight, cardDepth ); + bodyDef.type = b3_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, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, angle2 ); + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &cardBox.base ); + } + + bodyDef.position = { z, y, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, angle1 ); + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &cardBox.base ); + + z += 0.175f; + + bodyDef.position = { z, y, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, angle0 ); + bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &cardBox.base ); + + 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 = SampleManager::Register( "Stacking", "Card House", CardHouse::Create ); + +class SphereStack : public Sample +{ +public: + explicit SphereStack( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 15.0f, 50.0f, {0.0f, 10.0f, 0.0f} ); + EnableGrid( m_scene, true ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "ground"; + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull hull = b3MakeBoxHull( 15.0f, 1.0f, 15.0f ); + b3CreateHullShape( groundId, &shapeDef, &hull.base ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + + float r = 0.5f; + b3Sphere sphere = { b3Vec3_zero, r }; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.rollingResistance = 0.1f; + + float y = 1.5f * r; + + for ( int i = 0; i < 30; ++i ) + { + bodyDef.name = "sphere"; + //bodyDef.position.x = 0.1f * i; + bodyDef.position.y = y; + bodyDef.angularVelocity = { 0.0f, 0.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + if ( i == 0 ) + { + m_bodyId = bodyId; + } + + // shapeDef.density = 1.0f + 4.0f * i; + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + + y += 3.0f * r; + } + } + + void Step() override + { + // b3Vec3 p = b3Body_GetPosition( m_bodyId ); + // printf( "%g %g %g\n", p.x, p.y, p.z ); + + Sample::Step(); + } + + static Sample* Create( SampleContext* context ) + { + return new SphereStack( context ); + } + + b3BodyId m_bodyId; +}; + +static int sampleSphereStack = SampleManager::Register( "Stacking", "Sphere Stack", SphereStack::Create ); + +class SingleBox : public Sample +{ +public: + explicit SingleBox( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 25.0f, 10.0f, b3Vec3_zero ); + EnableGrid( m_scene, true ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "ground"; + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull hull = b3MakeBoxHull( 15.0f, 1.0f, 15.0f ); + b3CreateHullShape( groundId, &shapeDef, &hull.base ); + } + +#if 1 + { + b3BoxHull cube = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "cube"; + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 0.5f, 0.0f }; + //bodyDef.linearVelocity = { 4.0f, 0.0f, 0.0f }; + bodyDef.angularVelocity = { 0.0f, 10.0f, 0.0f }; + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( m_bodyId, &shapeDef, &cube.base ); + } +#else + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "capsule"; + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 2.0f, 0.0f }; + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3Capsule capsule = { { -0.25f, 0.0f }, { 0.25f, 0.0f }, 0.1f }; + b3CreateCapsuleShape( m_bodyId, &shapeDef, &capsule ); + } +#endif + } + + void Step() override + { + Sample::Step(); + + b3Vec3 position = b3Body_GetPosition( m_bodyId ); + DrawTextLine( "(x, y, z) = (%.2g, %.2g, %.2g)", position.x, position.y, position.z ); + } + + static Sample* Create( SampleContext* context ) + { + return new SingleBox( context ); + } + + b3BodyId m_bodyId; +}; + +static int sampleSingleBox = SampleManager::Register( "Stacking", "Single Box", SingleBox::Create ); + +class Cylinder : public Sample +{ +public: + explicit Cylinder( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 15.0f, 10.0f, b3Vec3_zero ); + EnableGrid( m_scene, true ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "ground"; + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull hull = b3MakeBoxHull( 10.0f, 1.0f, 10.0f ); + b3CreateHullShape( groundId, &shapeDef, &hull.base ); + } + + { + m_hull = b3CreateCylinder( 1.0f, 0.25f, 0.0f, 12 ); + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "cylinder"; + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 2.0f, 0.0f }; + bodyDef.linearVelocity = { 0.0f, 0.0f, 0.0f }; + // bodyDef.angularVelocity = { 0.0f, 5.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.rollingResistance = 0.05f; + b3CreateHullShape( bodyId, &shapeDef, m_hull ); + } + + m_context->debugDraw.forceScale = 0.01f; + } + + ~Cylinder() override + { + b3DestroyHull( m_hull ); + } + + void Step() override + { + Sample::Step(); + } + + static Sample* Create( SampleContext* context ) + { + return new Cylinder( context ); + } + + b3Hull* m_hull; +}; + +static int sampleCylinder = SampleManager::Register( "Stacking", "Cylinder", Cylinder::Create ); + +class CylinderStack : public Sample +{ +public: + explicit CylinderStack( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 15.0f, 15.0f, {0.0f, 5.0f, 0.0f} ); + EnableGrid( m_scene, true ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "ground"; + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull hull = b3MakeBoxHull( 10.0f, 1.0f, 10.0f ); + b3CreateHullShape( groundId, &shapeDef, &hull.base ); + } + + m_hull = b3CreateCylinder( 1.0f, 0.5f, 0.0f, 15 ); + + b3Vec3 scales[4] = { + b3Vec3_one, + { -0.75f, 1.0f, 1.0f }, + { 1.2f, 1.0f, -0.9f }, + { 0.9f, 0.9f, 0.9f }, + }; + + for ( int i = 0; i < 10; ++i ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "cylinder"; + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 0.0f + 1.1f * i, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + //shapeDef.baseMaterial.rollingResistance = 0.1f; + b3CreateTransformedHullShape( bodyId, &shapeDef, m_hull, b3Transform_identity, scales[i % 4] ); + } + + m_context->debugDraw.forceScale = 0.001f; + } + + ~CylinderStack() override + { + b3DestroyHull( m_hull ); + } + + void Step() override + { + Sample::Step(); + } + + static Sample* Create( SampleContext* context ) + { + return new CylinderStack( context ); + } + + b3Hull* m_hull; +}; + +static int sampleCylinderStack = SampleManager::Register( "Stacking", "Cylinder Stack", CylinderStack::Create ); + +class BoxStack : public Sample +{ +public: + explicit BoxStack( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 15.0f, 50.0f, {0.0f, 20.0f, 0.0f} ); + EnableGrid( m_scene, true ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "ground"; + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull hull = b3MakeBoxHull( 40.0f, 1.0f, 40.0f ); + b3CreateHullShape( groundId, &shapeDef, &hull.base ); + } + + float a = 0.5f; + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.name = "cube"; + bodyDef.type = b3_dynamicBody; + + b3BoxHull cube = b3MakeBoxHull( a, a, a ); + // b3Quat q = b3MakeQuatFromAxisAngle( { 1.0f, 0.0f, 0.0f }, 0.5f * B3_PI ); + + for ( int i = 0; i < 40; ++i ) + { + bodyDef.position = { 0.0f, 1.5f * a + 2.5f * a * i, 0.0f }; + // bodyDef.rotation = b3MulQuat( q, bodyDef.rotation ); + + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.rollingResistance = 0.1f; + + b3CreateHullShape( bodyId, &shapeDef, &cube.base ); + } + + //{ + // b3BoxHull wide = b3MakeBoxHull( 2.0f, 0.6f, 0.6f ); + // b3BodyDef bodyDef = b3DefaultBodyDef(); + // bodyDef.name = "wide"; + // bodyDef.type = b3_dynamicBody; + // bodyDef.position = { 0.0f, 0.6f + 1.0f * m_count, 0.0f }; + // b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + // b3ShapeDef shapeDef = b3DefaultShapeDef(); + // b3CreateHullShape( bodyId, &shapeDef, &wide.base ); + //} + } + + static Sample* Create( SampleContext* context ) + { + return new BoxStack( context ); + } +}; + +static int sampleBoxStack = SampleManager::Register( "Stacking", "Box Stack", BoxStack::Create ); + +class JengaStack : public Sample +{ +public: + explicit JengaStack( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 35.0f, 15.0f, 30.0f, { 0.0f, 10.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + m_shapeType = b3_hullShape; + CreateStack(); + } + + void CreateStack() + { + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 50.0f ); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + } + + { + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.rollingResistance = m_shapeType == b3_capsuleShape ? 0.1f : 0.01f; + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + + b3BoxHull box = b3MakeBoxHull( 2.5f, 0.25f, 0.25f ); + b3Capsule capsule = { { -2.5f, 0.0f, 0.0f }, { 2.5f, 0.0f, 0.0f }, 0.25f }; + + for ( int i = 0; i < m_size; ++i ) + { + float alpha = ( i & 1 ) == 1 ? 0.0f : 0.5f * B3_PI; + + float x = ( i & 1 ) == 0 ? 1.75f : 0.0f; + float z = ( i & 1 ) == 0 ? 0.0f : 1.75f; + + bodyDef.position = { x, 0.5f * i + 0.25f, z }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisY, alpha ); + b3BodyId boxBody1 = b3CreateBody( m_worldId, &bodyDef ); + + bodyDef.position = { -x, 0.5f * i + 0.25f, -z }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisY, alpha ); + b3BodyId boxBody2 = b3CreateBody( m_worldId, &bodyDef ); + + if ( m_shapeType == b3_capsuleShape ) + { + b3CreateCapsuleShape( boxBody1, &shapeDef, &capsule ); + b3CreateCapsuleShape( boxBody2, &shapeDef, &capsule ); + } + else + { + b3CreateHullShape( boxBody1, &shapeDef, &box.base ); + b3CreateHullShape( boxBody2, &shapeDef, &box.base ); + } + } + } + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + float height = 6.0f * fontSize; + ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->m_height - height - 2.0f * fontSize ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 8.0f * fontSize, height ) ); + + ImGui::Begin( "Jenga Stack", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + + b3Capacity capacity = {}; + + if ( ImGui::RadioButton( "Capsule", m_shapeType == b3_capsuleShape ) ) + { + m_shapeType = b3_capsuleShape; + CreateWorld( &capacity ); + CreateStack(); + } + + if ( ImGui::RadioButton( "Hull", m_shapeType == b3_hullShape ) ) + { + m_shapeType = b3_hullShape; + CreateWorld( &capacity ); + CreateStack(); + } + + ImGui::End(); + + Sample::UpdateUI(); + } + + static Sample* Create( SampleContext* context ) + { + return new JengaStack( context ); + } + + static constexpr int m_size = 40; + b3ShapeType m_shapeType; +}; + +static int sampleJengaStack = SampleManager::Register( "Stacking", "Jenga Stack", JengaStack::Create ); + +class Dominoes : public Sample +{ +public: + explicit Dominoes( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 15.0f, 50.0f, b3Vec3_zero ); + EnableGrid( m_scene, true ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + b3BoxHull groundBox = b3MakeBoxHull( 80.0f, 1.0f, 80.0f ); + b3CreateHullShape( groundBody, &shapeDef, &groundBox.base ); + + constexpr int n = m_isDebug ? 2 : 30; + + b3BoxHull box = b3MakeBoxHull( 0.2f, 0.8f, 0.05f ); + for ( int ring = 0; ring < n; ++ring ) + { + float radius = 7.0f + 1.1f * ring; + CreateRing( radius, box ); + } + } + + void CreateRing( float radius, b3BoxHull& box ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + for ( float alpha = 0; alpha <= 360.0f; alpha += 2.0f ) + // for (float Alpha = 0; Alpha <= 4.0f; Alpha += 4.0f) + { + b3CosSin cs = b3ComputeCosSin( B3_DEG_TO_RAD * alpha ); + b3Vec3 position = { radius * cs.cosine, 0.8f, radius * cs.sine }; + b3Vec3 normal = { cs.cosine, 0.0f, cs.sine }; + position -= alpha / 630.0f * normal; + + b3Quat orientation = b3MakeQuatFromAxisAngle( b3Vec3_axisY, -B3_DEG_TO_RAD * alpha ); + + bodyDef.position = position; + bodyDef.rotation = orientation; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( body, &shapeDef, &box.base ); + + if ( alpha == 0.0f ) + { + b3Body_ApplyLinearImpulse( body, { 0.0f, 0.0f, 25.0f }, position + b3Vec3{ 0.0f, 0.8f, 0.0f }, true ); + } + } + } + + static Sample* Create( SampleContext* context ) + { + return new Dominoes( context ); + } +}; + +static int sampleDominoes = SampleManager::Register( "Stacking", "Dominoes", Dominoes::Create ); + +// This wedge shape can have an incorrect manifold if not handled correctly +class Wedge : public Sample +{ +public: + static Sample* Create( SampleContext* context ) + { + return new Wedge( context ); + } + + explicit Wedge( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 77.0f, 10.0f, 5.0f ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3BoxHull groundBox = b3MakeBoxHull( 25.0f, 1.0f, 25.0f ); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + + b3Vec3 vertices[] = { + { -1.0, 1.0f, -0.1f }, { 1.0, 1.0f, -0.1f }, { -1.0, 1.0f, 0.1f }, + { 1.0, 1.0f, 0.1f }, { -0.5, 0.5f, 0.0f }, { 0.5, 0.5f, 0.0f }, + }; + + m_wedgeHull = b3CreateHull( vertices, 6, 6 ); + + bodyDef.type = b3_dynamicBody; + bodyDef.position = { 0.0f, 1.0f, 0.0f }; + b3BodyId wedgeBody = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( wedgeBody, &shapeDef, m_wedgeHull ); + } + + ~Wedge() override + { + b3DestroyHull( m_wedgeHull ); + } + + b3Hull* m_wedgeHull; +}; + +static int sampleWedge = SampleManager::Register( "Stacking", "Wedge", Wedge::Create ); + +// jitter +/* + *+ position [ -459.292877, 217.398331, 1.00115335 ] b3Vec3 ++ rotation [ [ -0.00000000, 0.00000000, -0.707106769 ], 0.707106769 ] b3Quat + +points[0] = { -44.8770714, -91.6598053, -1.92012548 }; +points[1] = { -92.5001831, 51.0151291, 15.8006573 }; +points[2] = { -91.0282211, -9.44371605, 15.6148796 }; +points[3] = { 90.2375641, 77.3870087, 15.9356089 }; +points[4] = { -85.5353241, 91.3750992, -1.36629653 }; +points[5] = { 88.9092178, -87.2975464, -1.86754704 }; +points[6] = { 83.7932816, -89.8572235, 15.4168339 }; +points[7] = { 87.0243988, 88.9776535, -1.32423306 }; +points[8] = { -91.6564941, -85.4949493, 15.3782759 }; +points[9] = { -90.2922516, -87.2074127, -1.92012548 }; +points[10] = { -87.2944870, 89.9510498, 15.9215889 }; +points[11] = { 79.2338104, 89.9690781, 15.9724140 }; +points[12] = { -91.6744461, 81.0823212, -1.39959598 }; +points[13] = { 90.3452759, -76.4459610, 15.4588966 }; +points[14] = { -87.4021912, -89.2263107, 15.3677588 }; +points[15] = { 76.3258057, 92.0059967, 1.82873762 }; +*/ + +/* + * + *+ position [ -402.321838, 157.310364, 16.8169250 ] b3Vec3 ++ rotation [ [ -0.00000000, 0.00000000, -0.00152086187 ], 0.999998868 ] b3Quat + + * +points[0] = { 29.5000000, 17.1488495, 0.175081104 }; +points[1] = { 29.5000000, -17.2990532, 0.125000000 }; +points[2] = { 29.4840164, -17.3057766, 24.0200863 }; +points[3] = { 29.4840164, 17.1648350, 24.1781254 }; +points[4] = { -29.1345520, 17.5529804, 0.125000000 }; +points[5] = { -29.1345520, 17.5529804, 23.7899799 }; +points[6] = { -29.1441040, 16.9679585, 24.3750000 }; +points[7] = { -29.1345520, -17.2990532, 24.3750000 }; +points[8] = { -29.1345520, -17.2990532, 0.175081253 }; +points[9] = { 29.0720215, 17.5529785, 0.125000000 }; +points[10] = { 29.0859070, 17.5629406, 23.8120594 }; +points[11] = { 29.1401348, -17.2990532, 24.3750000 }; +points[12] = { 29.1123581, 16.9722290, 24.4027710 }; +points[13] = { 29.3944912, 17.2543602, 24.1206398 }; +points[14] = { -29.1345520, -17.2990532, 24.0759430 }; +points[15] = { -29.1345520, -16.9722252, 24.4027710 }; +points[16] = { 29.1123619, -16.9722271, 24.4027729 }; +points[17] = { 29.5000000, 17.3429642, 24.0000000 }; +*/ + +class Arch : public Sample +{ +public: + explicit Arch( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 15.0f, 30.0f, { 0.0f, 5.0f, 0.0f } ); + EnableGrid( m_scene, true ); + } + + b3Vec3 ps1[9] = { { 16.0f, 0.0f, 0.0f }, + { 14.93803712795643f, 5.133601056842984f, 0.0f }, + { 13.79871746027416f, 10.24928069555078f, 0.0f }, + { 12.56252963284711f, 15.34107019122473f, 0.0f }, + { 11.20040987372525f, 20.39856541571217f, 0.0f }, + { 9.66521217819836f, 25.40369899225096f, 0.0f }, + { 7.87179930638133f, 30.3179337000085f, 0.0f }, + { 5.635199558196225f, 35.03820717801641f, 0.0f }, + { 2.405937953536585f, 39.09554102558315f, 0.0f } }; + + b3Vec3 ps2[9] = { { 24.0f, 0.0f, 0.0f }, + { 22.33619528222415f, 6.02299846205841f, 0.0f }, + { 20.54936888969905f, 12.00964361211476f, 0.0f }, + { 18.60854610798073f, 17.9470321677465f, 0.0f }, + { 16.46769273811807f, 23.81367936585418f, 0.0f }, + { 14.05325025774858f, 29.57079353071012f, 0.0f }, + { 11.23551045834022f, 35.13775818285372f, 0.0f }, + { 7.752568160730571f, 40.30450679009583f, 0.0f }, + { 3.016931552701656f, 44.28891593799322f, 0.0f } }; + + float scale = 0.25f; + for ( int i = 0; i < 9; ++i ) + { + ps1[i].x *= scale; + ps1[i].y *= scale; + ps2[i].x *= scale; + ps2[i].y *= scale; + } + + const float halfDepth = 0.5f; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 50.0f ); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + + for ( int i = 0; i < 8; ++i ) + { + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3Vec3 ps[8] = { + { ps1[i].x, ps1[i].y, -halfDepth }, { ps2[i].x, ps2[i].y, -halfDepth }, + { ps2[i + 1].x, ps2[i + 1].y, -halfDepth }, { ps1[i + 1].x, ps1[i + 1].y, -halfDepth }, + { ps1[i].x, ps1[i].y, halfDepth }, { ps2[i].x, ps2[i].y, halfDepth }, + { ps2[i + 1].x, ps2[i + 1].y, halfDepth }, { ps1[i + 1].x, ps1[i + 1].y, halfDepth }, + }; + b3Hull* hull = b3CreateHull( ps, 8, 8 ); + b3CreateHullShape( bodyId, &shapeDef, hull ); + b3DestroyHull( hull ); + } + + for ( int i = 0; i < 8; ++i ) + { + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3Vec3 ps[8] = { + { -ps2[i].x, ps2[i].y, -halfDepth }, { -ps1[i].x, ps1[i].y, -halfDepth }, + { -ps1[i + 1].x, ps1[i + 1].y, -halfDepth }, { -ps2[i + 1].x, ps2[i + 1].y, -halfDepth }, + { -ps2[i].x, ps2[i].y, halfDepth }, { -ps1[i].x, ps1[i].y, halfDepth }, + { -ps1[i + 1].x, ps1[i + 1].y, halfDepth }, { -ps2[i + 1].x, ps2[i + 1].y, halfDepth }, + }; + b3Hull* hull = b3CreateHull( ps, 8, 8 ); + b3CreateHullShape( bodyId, &shapeDef, hull ); + b3DestroyHull( hull ); + } + + { + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3Vec3 ps[8] = { + { ps1[8].x, ps1[8].y, -halfDepth }, { ps2[8].x, ps2[8].y, -halfDepth }, + { -ps2[8].x, ps2[8].y, -halfDepth }, { -ps1[8].x, ps1[8].y, -halfDepth }, + { ps1[8].x, ps1[8].y, halfDepth }, { ps2[8].x, ps2[8].y, halfDepth }, + { -ps2[8].x, ps2[8].y, halfDepth }, { -ps1[8].x, ps1[8].y, halfDepth }, + }; + b3Hull* hull = b3CreateHull( ps, 8, 8 ); + b3CreateHullShape( bodyId, &shapeDef, hull ); + b3DestroyHull( hull ); + } + + for ( int i = 0; i < 4; ++i ) + { + b3BoxHull box = b3MakeBoxHull( 2.0f, 0.5f, halfDepth ); + bodyDef.position = { 0.0f, 0.5f + ps2[8].y + 1.0f * i, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + } + + static Sample* Create( SampleContext* context ) + { + return new Arch( context ); + } +}; + +static int sampleArch = SampleManager::Register( "Stacking", "Arch", Arch::Create ); + +class Pyramid2D : public Sample +{ +public: + explicit Pyramid2D( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 30.0f, 50.0f, { 0.0f, 5.0f, 0.0f } ); + } + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, -1.0f, 0.0f }; + b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 50.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + // shapeDef.filter = { 1, ~0u, 0 }; + + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + } + + float a = 1.0f; + b3BoxHull box = b3MakeBoxHull( a, a, a ); + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.motionLocks.linearZ = true; + bodyDef.motionLocks.angularX = true; + bodyDef.motionLocks.angularY = true; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + for ( int row = 0; row < m_size; ++row ) + { + for ( int column = 0; column < m_size - row; ++column ) + { + bodyDef.position = { ( -20.0f + 2.0f * column + row ) * a, ( 1.5f + 2.5f * row ) * a, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + } + } + + static Sample* Create( SampleContext* context ) + { + return new Pyramid2D( context ); + } + + static constexpr int m_size = 12; +}; + +static int samplePyramid2D = SampleManager::Register( "Stacking", "Pyramid2D", Pyramid2D::Create ); + diff --git a/samples/sample_tree.cpp b/samples/sample_tree.cpp new file mode 100644 index 0000000..ac03af4 --- /dev/null +++ b/samples/sample_tree.cpp @@ -0,0 +1,848 @@ +// 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 "camera.h" +#include "imgui.h" +#include "utils.h" +#include "renderer.h" +#include "sample.h" +#include "scene.h" + +#include +#include +#include +#include + +constexpr int colorCount = 12; +b3HexColor colors[colorCount] = { + b3_colorRoyalBlue, b3_colorPink, b3_colorLightGreen, b3_colorOrange, b3_colorYellow, b3_colorViolet, + b3_colorAqua, b3_colorCoral, b3_colorLightGray, b3_colorMoccasin, b3_colorLavender, b3_colorMediumOrchid, +}; + +struct FileConfig +{ + float scale; + bool zUp; +}; + +struct Proxy +{ + b3AABB aabb; + int proxyId; + int queryTimeStamp; + int rayTimeStamp; +}; + +struct Ray +{ + b3Vec3 origin, translation; +}; + +#ifdef _WIN32 + +#include + +// Warning: this code has not been validated +void ClosestPointAVX2( const float* aabbMinX, const float* aabbMinY, const float* aabbMinZ, const float* aabbMaxX, + const float* aabbMaxY, const float* aabbMaxZ, int proxyCount, b3Vec3 point, b3Vec3* outClosestPoint, + float* outMinDistSq ) +{ + const __m256 px = _mm256_set1_ps( point.x ); + const __m256 py = _mm256_set1_ps( point.y ); + const __m256 pz = _mm256_set1_ps( point.z ); + + __m256 bestDistSq = _mm256_set1_ps( FLT_MAX ); + __m256i bestIndex = _mm256_set1_epi32( -1 ); + + int j = 0; + for ( ; j + 8 <= proxyCount; j += 8 ) + { + // Load AABB bounds for 8 proxies + __m256 minX = _mm256_loadu_ps( aabbMinX + j ); + __m256 minY = _mm256_loadu_ps( aabbMinY + j ); + __m256 minZ = _mm256_loadu_ps( aabbMinZ + j ); + __m256 maxX = _mm256_loadu_ps( aabbMaxX + j ); + __m256 maxY = _mm256_loadu_ps( aabbMaxY + j ); + __m256 maxZ = _mm256_loadu_ps( aabbMaxZ + j ); + + // Closest point on AABB to point: clamp each coordinate + __m256 cx = _mm256_min_ps( _mm256_max_ps( px, minX ), maxX ); + __m256 cy = _mm256_min_ps( _mm256_max_ps( py, minY ), maxY ); + __m256 cz = _mm256_min_ps( _mm256_max_ps( pz, minZ ), maxZ ); + + // d = point - closest + __m256 dx = _mm256_sub_ps( px, cx ); + __m256 dy = _mm256_sub_ps( py, cy ); + __m256 dz = _mm256_sub_ps( pz, cz ); + + __m256 dx2 = _mm256_mul_ps( dx, dx ); + __m256 dy2 = _mm256_mul_ps( dy, dy ); + __m256 dz2 = _mm256_mul_ps( dz, dz ); + __m256 distSq = _mm256_add_ps( _mm256_add_ps( dx2, dy2 ), dz2 ); + + // Compare to current best + __m256 mask = _mm256_cmp_ps( distSq, bestDistSq, _CMP_LT_OQ ); + bestDistSq = _mm256_blendv_ps( bestDistSq, distSq, mask ); + + __m256i indices = _mm256_set_epi32( j + 7, j + 6, j + 5, j + 4, j + 3, j + 2, j + 1, j + 0 ); + + // Tracks the 8 best indices + bestIndex = + _mm256_castps_si256( _mm256_blendv_ps( _mm256_castsi256_ps( bestIndex ), _mm256_castsi256_ps( indices ), mask ) ); + } + + // Now find the best index among the best 8. + alignas( 32 ) float distBuf[8]; + alignas( 32 ) int indexBuf[8]; + + _mm256_store_ps( distBuf, bestDistSq ); + _mm256_store_si256( (__m256i*)indexBuf, bestIndex ); + + float minDist = distBuf[0]; + int minIdx = indexBuf[0]; + for ( int k = 1; k < 8; ++k ) + { + if ( distBuf[k] < minDist ) + { + minDist = distBuf[k]; + minIdx = indexBuf[k]; + } + } + + // Remainder + for ( ; j < proxyCount; ++j ) + { + float cx = b3MinFloat( b3MaxFloat( point.x, aabbMinX[j] ), aabbMaxX[j] ); + float cy = b3MinFloat( b3MaxFloat( point.y, aabbMinY[j] ), aabbMaxY[j] ); + float cz = b3MinFloat( b3MaxFloat( point.z, aabbMinZ[j] ), aabbMaxZ[j] ); + + float dx = point.x - cx; + float dy = point.y - cy; + float dz = point.z - cz; + float d2 = dx * dx + dy * dy + dz * dz; + + if ( d2 < minDist ) + { + minDist = d2; + minIdx = j; + } + } + + b3Vec3 cp; + cp.x = b3MinFloat( b3MaxFloat( point.x, aabbMinX[minIdx] ), aabbMaxX[minIdx] ); + cp.y = b3MinFloat( b3MaxFloat( point.y, aabbMinY[minIdx] ), aabbMaxY[minIdx] ); + cp.z = b3MinFloat( b3MaxFloat( point.z, aabbMinZ[minIdx] ), aabbMaxZ[minIdx] ); + + *outClosestPoint = cp; + *outMinDistSq = minDist; +} +#endif + +class TreeBenchmark : public Sample +{ +public: + explicit TreeBenchmark( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 45.0f, 45.0f, 250.0f, b3Vec3_zero ); + } + + m_fileNames[0] = { "bounds01" }; + m_fileNames[1] = { "bounds02" }; + m_fileNames[2] = { "bounds03" }; + m_config[0] = { 1.0f, false }; + m_config[1] = { 1.0f, false }; + m_config[2] = { 0.01f, false }; + m_fileIndex = 0; + + m_closestPoint = b3Vec3_zero; + m_timeStamp = 1; + m_doOverlap = false; + m_doClosest = false; + m_doRay = false; + m_testIndex = 0; + m_rayTime = 0.0f; + m_overlapTime = 0.0f; + m_closestTime = 0.0f; + m_haveClosest = false; + m_buildTime = 0.0f; + m_areaRatio = 0.0f; + m_drawDistance = 1.0f; + m_loadScale = 1.0f; + m_height = 0; + m_tree = {}; + + m_aabbMinX = nullptr; + m_aabbMinY = nullptr; + m_aabbMinZ = nullptr; + m_aabbMaxX = nullptr; + m_aabbMaxY = nullptr; + m_aabbMaxZ = nullptr; + + CreateTree(); + } + + ~TreeBenchmark() override + { + b3DynamicTree_Destroy( &m_tree ); + +#ifdef _WIN32 + _aligned_free( m_aabbMinX ); + _aligned_free( m_aabbMinY ); + _aligned_free( m_aabbMinZ ); + _aligned_free( m_aabbMaxX ); + _aligned_free( m_aabbMaxY ); + _aligned_free( m_aabbMaxZ ); +#endif + } + + // Breath-first search to compute node depth values start with 0 at the root. + int ComputeDepths() + { + m_depths.resize( m_tree.nodeCapacity, 0 ); + + int* queue = (int*)malloc( m_tree.nodeCount * sizeof( int ) ); + int front = 0; + int back = 0; + + b3TreeNode* nodes = m_tree.nodes; + queue[0] = m_tree.root; + back += 1; + int depth = 0; + + while ( back > front ) + { + int index = queue[front]; + front += 1; + + b3TreeNode* node = nodes + index; + if ( node->parent == B3_NULL_INDEX ) + { + m_depths[index] = 0; + } + else + { + m_depths[index] = m_depths[node->parent] + 1; + depth = b3MaxInt( depth, m_depths[index] ); + } + + if ( ( node->flags & b3_leafNode ) == 0 ) + { + B3_ASSERT( back < m_tree.nodeCount - 1 ); + queue[back++] = node->children.child1; + queue[back++] = node->children.child2; + } + } + + free( queue ); + + return depth; + } + + void CreateTree() + { + if ( m_tree.nodeCapacity > 0 ) + { + b3DynamicTree_Destroy( &m_tree ); + m_tree = {}; + } + + m_proxies.clear(); + +#ifdef _WIN32 + _aligned_free( m_aabbMinX ); + _aligned_free( m_aabbMinY ); + _aligned_free( m_aabbMinZ ); + _aligned_free( m_aabbMaxX ); + _aligned_free( m_aabbMaxY ); + _aligned_free( m_aabbMaxZ ); +#endif + + m_tree = b3DynamicTree_Create( 512 ); + + char filePath[64] = {}; + snprintf( filePath, 64, "data/trees/%s.txt", m_fileNames[m_fileIndex] ); + float scale = m_config[m_fileIndex].scale; + bool zUp = m_config[m_fileIndex].zUp; + + FILE* file = fopen( filePath, "r" ); + if ( file == nullptr ) + { + return; + } + + constexpr int bufferSize = 512; + char buffer[bufferSize]; + + int maxArea = 0.0f; + int maxAreaIndex = -1; + uint64_t key = 0; + + while ( fgets( buffer, sizeof( buffer ), file ) ) + { + char* trim = buffer; + while ( *trim == ' ' || *trim == '\t' ) + { + ++trim; + } + + if ( *trim == '\0' || *trim == '\n' || *trim == '#' ) + { + continue; + } + + Proxy rec = {}; + float b1, b2, b3, b4, b5, b6; + int parsed = sscanf( buffer, "%f %f %f %f %f %f", &b1, &b2, &b3, &b4, &b5, &b6 ); + + if ( parsed != 6 ) + { + fprintf( stderr, "Skipping malformed line: %s", buffer ); + continue; + } + + if ( zUp ) + { + rec.aabb.lowerBound.x = scale * b1; + rec.aabb.lowerBound.y = scale * b3; + rec.aabb.lowerBound.z = scale * b2; + rec.aabb.upperBound.x = scale * b4; + rec.aabb.upperBound.y = scale * b6; + rec.aabb.upperBound.z = scale * b5; + } + else + { + rec.aabb.lowerBound.x = scale * b1; + rec.aabb.lowerBound.y = scale * b2; + rec.aabb.lowerBound.z = scale * b3; + rec.aabb.upperBound.x = scale * b4; + rec.aabb.upperBound.y = scale * b5; + rec.aabb.upperBound.z = scale * b6; + } + + float area = b3AABB_Area( rec.aabb ); + if ( area > maxArea ) + { + maxArea = area; + maxAreaIndex = (int)m_proxies.size(); + } + + m_proxies[key] = rec; + key += 1; + + // if ( m_proxies.size() == 320 ) + //{ + // break; + // } + } + +#ifdef _WIN32 + int proxyCount = m_proxies.size(); + m_aabbMinX = (float*)_aligned_malloc( proxyCount * sizeof( float ), 32 ); + m_aabbMinY = (float*)_aligned_malloc( proxyCount * sizeof( float ), 32 ); + m_aabbMinZ = (float*)_aligned_malloc( proxyCount * sizeof( float ), 32 ); + m_aabbMaxX = (float*)_aligned_malloc( proxyCount * sizeof( float ), 32 ); + m_aabbMaxY = (float*)_aligned_malloc( proxyCount * sizeof( float ), 32 ); + m_aabbMaxZ = (float*)_aligned_malloc( proxyCount * sizeof( float ), 32 ); + + for ( int i = 0; i < proxyCount; ++i ) + { + b3Vec3 lb = m_proxies[i].aabb.lowerBound; + b3Vec3 ub = m_proxies[i].aabb.upperBound; + + m_aabbMinX[i] = lb.x; + m_aabbMinY[i] = lb.y; + m_aabbMinZ[i] = lb.z; + m_aabbMaxX[i] = ub.x; + m_aabbMaxY[i] = ub.y; + m_aabbMaxZ[i] = ub.z; + } +#endif + + printf( "max index = %d\n", maxAreaIndex ); + + // constexpr int n = m_isDebug ? 1000 : INT_MAX; + + uint64_t ticks = b3GetTicks(); + int count = (int)m_proxies.size(); + for ( int i = 0; i < count; ++i ) + { + // Arbitrary category bits to ensure correctness + m_proxies[i].proxyId = b3DynamicTree_CreateProxy( &m_tree, m_proxies[i].aabb, 1, i ); + m_proxies[i].queryTimeStamp = 0; + m_proxies[i].rayTimeStamp = 0; + } + + m_buildTime = b3GetMilliseconds( ticks ); + b3DynamicTree_Validate( &m_tree ); + m_areaRatio = b3DynamicTree_GetAreaRatio( &m_tree ); + + m_height = ComputeDepths(); + m_drawLevel = -1; + + Generate(); + } + + void LoadTree() + { + if ( m_tree.nodeCapacity > 0 ) + { + b3DynamicTree_Destroy( &m_tree ); + m_tree = {}; + } + + m_proxies.clear(); + +#ifdef _WIN32 + _aligned_free( m_aabbMinX ); + _aligned_free( m_aabbMinY ); + _aligned_free( m_aabbMinZ ); + _aligned_free( m_aabbMaxX ); + _aligned_free( m_aabbMaxY ); + _aligned_free( m_aabbMaxZ ); +#endif + + { + //bool zUp = true; + m_tree = b3DynamicTree_Load( m_saveFileName, m_loadScale ); + } + + constexpr int bufferSize = 512; + char buffer[bufferSize]; + + int maxArea = 0.0f; + int maxAreaIndex = -1; + + for ( int i = 0; i < m_tree.nodeCapacity; ++i ) + { + b3TreeNode* node = m_tree.nodes + i; + + if ( ( node->flags & b3_leafNode ) == 0 ) + { + continue; + } + + assert( node->flags & b3_allocatedNode ); + + Proxy proxy = {}; + proxy.aabb = node->aabb; + + float area = b3AABB_Area( proxy.aabb ); + if ( area > maxArea ) + { + maxArea = area; + maxAreaIndex = (int)m_proxies.size(); + } + + proxy.proxyId = i; + m_proxies[node->userData] = proxy; + } + +#ifdef _WIN32 + int proxyCount = m_proxies.size(); + m_aabbMinX = (float*)_aligned_malloc( proxyCount * sizeof( float ), 32 ); + m_aabbMinY = (float*)_aligned_malloc( proxyCount * sizeof( float ), 32 ); + m_aabbMinZ = (float*)_aligned_malloc( proxyCount * sizeof( float ), 32 ); + m_aabbMaxX = (float*)_aligned_malloc( proxyCount * sizeof( float ), 32 ); + m_aabbMaxY = (float*)_aligned_malloc( proxyCount * sizeof( float ), 32 ); + m_aabbMaxZ = (float*)_aligned_malloc( proxyCount * sizeof( float ), 32 ); + + for ( int i = 0; i < proxyCount; ++i ) + { + b3Vec3 lb = m_proxies[i].aabb.lowerBound; + b3Vec3 ub = m_proxies[i].aabb.upperBound; + + m_aabbMinX[i] = lb.x; + m_aabbMinY[i] = lb.y; + m_aabbMinZ[i] = lb.z; + m_aabbMaxX[i] = ub.x; + m_aabbMaxY[i] = ub.y; + m_aabbMaxZ[i] = ub.z; + } +#endif + + printf( "max index = %d\n", maxAreaIndex ); + + // constexpr int n = m_isDebug ? 1000 : INT_MAX; + + m_buildTime = 0.0f; + b3DynamicTree_Validate( &m_tree ); + m_areaRatio = b3DynamicTree_GetAreaRatio( &m_tree ); + + m_height = ComputeDepths(); + m_drawLevel = -1; + + Generate(); + } + + static float RayCallback( const b3RayCastInput* input, int proxyId, uint64_t userData, void* context ) + { + TreeBenchmark* sample = static_cast( context ); + Proxy& proxy = sample->m_proxies[userData]; + proxy.rayTimeStamp = sample->m_timeStamp; + return 1.0f; + } + + static bool QueryCallback( int proxyId, uint64_t userData, void* context ) + { + TreeBenchmark* sample = static_cast( context ); + Proxy& proxy = sample->m_proxies[userData]; + proxy.queryTimeStamp = sample->m_timeStamp; + return true; + } + + static float ClosetPointCallback( float minDistanceSquared, int proxyId, uint64_t userData, void* context ) + { + (void)proxyId; + + TreeBenchmark* sample = static_cast( context ); + int testIndex = sample->m_testIndex; + Proxy& proxy = sample->m_proxies[userData]; + proxy.queryTimeStamp = sample->m_timeStamp; + b3Vec3 queryPoint = sample->m_closestPointQueries[testIndex].center; + b3Vec3 closestPoint = b3ClosestPointToAABB( queryPoint, proxy.aabb ); + float distanceSquared = b3DistanceSquared( queryPoint, closestPoint ); + if ( distanceSquared < minDistanceSquared ) + { + sample->m_closestPoint = closestPoint; + sample->m_haveClosest = true; + } + + return distanceSquared; + } + + void Generate() + { + srand( 42 ); + + b3AABB bounds = m_tree.nodes[m_tree.root].aabb; + b3Vec3 extents = b3AABB_Extents( bounds ); + float radius = ( extents.x + extents.y + extents.z ) / 3.0f; + + for ( int i = 0; i < m_testCount; ++i ) + { + m_rays[i].origin = RandomVec3( bounds.lowerBound, bounds.upperBound ); + + b3Vec3 end = RandomVec3( bounds.lowerBound, bounds.upperBound ); + m_rays[i].translation = end - m_rays[i].origin; + + float s = RandomFloatRange( 0.01f, 0.2f ); + b3Vec3 c = RandomVec3( bounds.lowerBound, bounds.upperBound ); + b3Vec3 p1 = c - s * extents; + b3Vec3 p2 = c + s * extents; + + m_overlapQueries[i].lowerBound = b3Min( p1, p2 ); + m_overlapQueries[i].upperBound = b3Max( p1, p2 ); + + m_closestPointQueries[i] = { + .center = c, + .radius = s * radius, + }; + } + } + + void Profile() + { + uint64_t ticks = b3GetTicks(); + for ( int i = 0; i < m_testCount; ++i ) + { + Ray ray = m_rays[i]; + b3RayCastInput input = { ray.origin, ray.translation, 1.0f }; + + b3DynamicTree_RayCast( &m_tree, &input, B3_DEFAULT_MASK_BITS, false, RayCallback, this ); + } + m_rayTime = b3GetMillisecondsAndReset( &ticks ); + + for ( int i = 0; i < m_testCount; ++i ) + { + b3DynamicTree_Query( &m_tree, m_overlapQueries[i], B3_DEFAULT_MASK_BITS, false, QueryCallback, this ); + } + m_overlapTime = b3GetMilliseconds( ticks ); + +#if 0 && defined( _WIN32 ) + // brute force avx2 + int proxyCount = (int)m_proxies.size(); + for ( int i = 0; i < m_testCount; ++i ) + { + b3Vec3 point = m_closestPointQueries[i].center; + float minDistSq; + b3Vec3 closest; + + ClosestPointAVX2( m_aabbMinX, m_aabbMinY, m_aabbMinZ, m_aabbMaxX, m_aabbMaxY, m_aabbMaxZ, proxyCount, point, &closest, + &minDistSq ); + + m_closestPoint = closest; + m_haveClosest = true; + } +#elif 0 + // Brute force + int proxyCount = (int)m_proxies.size(); + for ( int i = 0; i < m_testCount; ++i ) + { + b3Vec3 point = m_closestPointQueries[i].center; + float minDistanceSquared = FLT_MAX; + m_haveClosest = false; + for ( int j = 0; j < proxyCount; ++j ) + { + b3Vec3 closestPoint = b3ClosestPointToAABB( point, m_proxies[j].aabb ); + float d = b3DistanceSquared( point, closestPoint ); + if ( d < minDistanceSquared ) + { + m_closestPoint = closestPoint; + m_haveClosest = true; + minDistanceSquared = d; + } + } + } +#else + for ( int i = 0; i < m_testCount; ++i ) + { + b3Vec3 point = m_closestPointQueries[i].center; + float radius = m_closestPointQueries[i].radius; + float distanceSquared = radius * radius; + m_closestPoint = point; + m_haveClosest = false; + b3DynamicTree_QueryClosest( &m_tree, point, B3_DEFAULT_MASK_BITS, false, ClosetPointCallback, this, + &distanceSquared ); + } +#endif + m_closestTime = b3GetMilliseconds( ticks ); + } + + void UpdateUI() override + { + DrawTextLine( "leaves = %d, height = %d, area = %g", m_tree.proxyCount, m_height, m_areaRatio ); + DrawTextLine( "build time = %g ms", m_buildTime ); + DrawTextLine( "total: ray = %g ms, overlap = %g ms, closest = %g ms", m_rayTime, m_overlapTime, m_closestTime ); + + float s = 1000.0f / m_testCount; + DrawTextLine( "ave: ray = %g us, overlap = %g us, closest = %g us", s * m_rayTime, s * m_overlapTime, s * m_closestTime ); + + float fontSize = ImGui::GetFontSize(); + float height = 23.0f * fontSize; + ImGui::SetNextWindowPos( { 0.5f * fontSize, m_camera->m_height - height - 2.0f * fontSize }, ImGuiCond_Once ); + ImGui::SetNextWindowSize( { 18.0f * fontSize, height } ); + + ImGui::Begin( "Tree", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + + if ( ImGui::Combo( "File", &m_fileIndex, m_fileNames, m_fileCount ) ) + { + CreateTree(); + } + + if ( ImGui::Button( "Top Down" ) ) + { + uint64_t ticks = b3GetTicks(); + b3DynamicTree_Rebuild( &m_tree, true ); + m_buildTime = b3GetMilliseconds( ticks ); + m_areaRatio = b3DynamicTree_GetAreaRatio( &m_tree ); + m_height = ComputeDepths(); + } + + ImGui::Separator(); + + ImGui::Checkbox( "Ray Cast", &m_doRay ); + ImGui::Checkbox( "Overlap", &m_doOverlap ); + ImGui::Checkbox( "Closet Point", &m_doClosest ); + + if ( ImGui::Button( "Profile" ) ) + { + Profile(); + } + + ImGui::SliderInt( "Test", &m_testIndex, 0, m_testCount - 1 ); + ImGui::SliderInt( "Level", &m_drawLevel, -1, m_height ); + ImGui::SliderFloat( "Kilometers", &m_drawDistance, 0.5f, 20.0f, "%.1f" ); + + if ( ImGui::Button( "Save" ) ) + { + b3DynamicTree_Save( &m_tree, m_saveFileName ); + } + + if ( ImGui::Button( "Load" ) ) + { + LoadTree(); + } + + ImGui::SliderFloat( "Load Scale", &m_loadScale, 0.01f, 1.0f ); + + ImGui::End(); + } + + void Render() override + { + Sample::Render(); + + DrawTransform( m_scene, b3Transform_identity, 2.0f ); + + b3Vec3 cp = m_camera->GetPosition(); + b3TreeNode* nodes = m_tree.nodes; + float distSquared = m_drawDistance * m_drawDistance * 1000.0f * 1000.0f; + + if ( m_drawLevel >= 0 ) + { + constexpr int colorCount = 20; + b3HexColor colors[colorCount] = { + b3_colorAliceBlue, b3_colorAntiqueWhite, b3_colorAqua, b3_colorAquamarine, b3_colorAzure, + b3_colorBeige, b3_colorBisque, b3_colorBlanchedAlmond, b3_colorBlue, b3_colorBlueViolet, + b3_colorBrown, b3_colorBurlywood, b3_colorCadetBlue, b3_colorChartreuse, b3_colorChocolate, + b3_colorCoral, b3_colorCornflowerBlue, b3_colorCornsilk, b3_colorCrimson, b3_colorCyan, + }; + + int capacity = m_tree.nodeCapacity; + for ( int i = 0; i < capacity; ++i ) + { + b3TreeNode* node = nodes + i; + if ( m_depths[i] != m_drawLevel || ( node->flags & b3_allocatedNode ) == 0 ) + { + // skip internal nodes + continue; + } + + b3Vec3 c = b3AABB_Center( node->aabb ); + if ( m_drawLevel < 10 || b3DistanceSquared( c, cp ) < distSquared ) + { + DrawBounds( m_scene, node->aabb, 0.0f, colors[m_drawLevel % colorCount] ); + } + } + } + else + { + uint16_t requiredFlags = b3_allocatedNode | b3_leafNode; + for ( int i = 0; i < m_tree.nodeCapacity; ++i ) + { + b3TreeNode* node = nodes + i; + + if ( node->flags != requiredFlags ) + { + continue; + } + + b3Vec3 c = b3AABB_Center( node->aabb ); + if ( b3DistanceSquared( c, cp ) > distSquared ) + { + continue; + } + + Proxy& proxy = m_proxies[node->userData]; + if ( proxy.queryTimeStamp == m_timeStamp || proxy.rayTimeStamp == m_timeStamp ) + { + DrawBounds( m_scene, node->aabb, 0.0f, b3_colorLightGray ); + } + else + { + // float extension = 0.01f * node->height; + float extension = 0.0f; + DrawBounds( m_scene, node->aabb, extension, b3_colorLightBlue ); + } + } + } + + if ( m_doRay ) + { + Ray ray = m_rays[m_testIndex]; + DrawLine( m_scene, ray.origin, ray.origin + ray.translation, b3_colorRed ); + } + + if ( m_doOverlap ) + { + DrawBounds( m_scene, m_overlapQueries[m_testIndex], 0.0f, b3_colorRed ); + } + + if ( m_doClosest ) + { + DrawSphere( m_scene, b3Transform_identity, m_closestPointQueries[m_testIndex], b3_colorCyan ); + if ( m_haveClosest ) + { + DrawPoint( m_scene, m_closestPoint, 15.0f, b3_colorOrange ); + } + } + } + + void Step() override + { + Sample::Step(); + ++m_timeStamp; + + if ( m_doRay ) + { + Ray ray = m_rays[m_testIndex]; + b3RayCastInput input = { ray.origin, ray.translation, 1.0f }; + + b3DynamicTree_RayCast( &m_tree, &input, B3_DEFAULT_MASK_BITS, false, RayCallback, this ); + } + + if ( m_doOverlap ) + { + b3DynamicTree_Query( &m_tree, m_overlapQueries[m_testIndex], B3_DEFAULT_MASK_BITS, false, QueryCallback, this ); + } + + if ( m_doClosest ) + { + b3Vec3 point = m_closestPointQueries[m_testIndex].center; + float radius = m_closestPointQueries[m_testIndex].radius; + float distanceSquared = radius * radius; + m_closestPoint = point; + m_haveClosest = false; + b3DynamicTree_QueryClosest( &m_tree, point, B3_DEFAULT_MASK_BITS, false, ClosetPointCallback, this, + &distanceSquared ); + } + + // constexpr int n = m_isDebug ? 0 : 100; + // for ( int i = 0; i < n; ++i ) + //{ + // Profile(); + // } + } + + static Sample* Create( SampleContext* context ) + { + return new TreeBenchmark( context ); + } + + static constexpr int m_fileCount = 3; + static constexpr int m_testCount = 1024; + static constexpr const char* m_saveFileName = "tree.dt"; + + const char* m_fileNames[m_fileCount]; + FileConfig m_config[m_fileCount]; + int m_fileIndex; + + float* m_aabbMinX; + float* m_aabbMinY; + float* m_aabbMinZ; + float* m_aabbMaxX; + float* m_aabbMaxY; + float* m_aabbMaxZ; + + std::unordered_map m_proxies; + std::vector m_depths; + b3DynamicTree m_tree; + Ray m_rays[m_testCount]; + b3AABB m_overlapQueries[m_testCount]; + b3Sphere m_closestPointQueries[m_testCount]; + b3Vec3 m_closestPoint; + float m_areaRatio; + float m_rayTime; + float m_overlapTime; + float m_closestTime; + float m_buildTime; + float m_drawDistance; + float m_loadScale; + int m_testIndex; + int m_timeStamp; + int m_drawLevel; + int m_height; + bool m_haveClosest; + bool m_doOverlap; + bool m_doClosest; + bool m_doRay; +}; + +static int sampleTree = SampleManager::Register( "Tree", "Benchmark", TreeBenchmark::Create ); diff --git a/samples/scene.cpp b/samples/scene.cpp new file mode 100644 index 0000000..76f0dd1 --- /dev/null +++ b/samples/scene.cpp @@ -0,0 +1,2320 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "scene.h" + +#include "../src/core.h" +#include "camera.h" +#include "geo_buffer.h" +#include "renderer.h" +#include "shader.h" +#include "ssao_buffer.h" +#include "utility.h" + +#include "box3d/math_functions.h" + +#include +#include +#include +#include +#include +#include +#include + +static const int shadowWidth = 4096; +static const int shadowHeight = 4096; +static constexpr int s_batchSize = 256; + +// The number of sides of the base circle. For spheres and capsules. +static constexpr int s_sideCount = 16; + +// The number of quad rings going from the middle to the sphere end point +// for example, a value of 2 has 2 rings plus the end cone. For spheres and capsules. +static constexpr int s_ringCount = 8; + +struct Cube +{ + b3Transform transform; + RGBAf color; + bool invert; + bool shadowCaster; +}; + +struct DebugCube +{ + b3Transform transform; + RGBAf color; +}; + +struct Edge +{ + int index1; + int index2; + int flags; +}; + +struct EdgeData +{ + b3Vec3 position; + int flags; +}; + +struct InstanceShape +{ + int triangleCount; + uint32_t triangleArrayId; + + // Static and dynamic buffers + uint32_t triangleBufferIds[2]; + + int edgeCount; + uint32_t edgeArrayId; + + // Static and dynamic buffers + uint32_t edgeBufferIds[2]; +}; + +struct InstanceData +{ + RGBA8 rgba8; + Matrix4 matrix; +}; + +struct Scene +{ + Scene() = default; + + Arena arena; + + std::vector debugCubes; + std::vector sphereInstances; + std::vector openHemisphereInstances; + std::vector openCylinderInstances; + + // Instances organized by hash + std::unordered_map> hullInstances; + std::unordered_map> meshInstances; + std::unordered_map> heightFieldInstances; + + std::vector transparentSphereInstances; + std::vector transparentOpenHemisphereInstances; + std::vector transparentOpenCylinderInstances; + std::unordered_map> transparentHullInstances; + + uint32_t shadowShader = 0; + uint32_t meshShader = 0; + uint32_t meshShadowShader = 0; + uint32_t meshEdgeShader = 0; + uint32_t geometryShader = 0; + uint32_t ssaoShader = 0; + uint32_t ssaoBlurShader = 0; + uint32_t deferredShader = 0; + uint32_t meshForwardShader = 0; + uint32_t forwardShader = 0; + uint32_t depthCopyShader = 0; + + uint32_t depthMapFBO = 0; + uint32_t depthMap = 0; + + PointDraw* pointDraw = nullptr; + LineDraw* lineDraw = nullptr; + GeoBuffer* geoBuffer = nullptr; + SsaoBuffer* ssaoBuffer = nullptr; + + InstanceShape sphere; + + // Building blocks for capsules + InstanceShape openHemisphere; + InstanceShape openCylinder; + + std::unordered_map sharedHulls; + std::unordered_map sharedMeshes; + std::unordered_map sharedHeightFields; + + SceneAOSettings ao = {}; + + b3Vec3 lightPosition{ -16.0f, 40.0f, 10.0f }; + + bool useSSAO = false; + bool useShadow = false; + bool useGrid = false; +}; + +// Renders a 1x1 XY quad in NDC +static uint32_t quadVAO = 0; +static uint32_t quadVBO = 0; +static void DrawQuad() +{ + if ( quadVAO == 0 ) + { + float quadVertices[] = { + // positions texture Coords + // (x, y, z, u, v) + -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, + 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, + }; + + glGenVertexArrays( 1, &quadVAO ); + glGenBuffers( 1, &quadVBO ); + glBindVertexArray( quadVAO ); + glBindBuffer( GL_ARRAY_BUFFER, quadVBO ); + glBufferData( GL_ARRAY_BUFFER, sizeof( quadVertices ), &quadVertices, GL_STATIC_DRAW ); + glEnableVertexAttribArray( 0 ); + glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof( float ), (void*)0 ); + glEnableVertexAttribArray( 1 ); + glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof( float ), (void*)( 3 * sizeof( float ) ) ); + } + + glBindVertexArray( quadVAO ); + glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); + glBindVertexArray( 0 ); +} + +static uint32_t cubeArrayId = 0; +static uint32_t cubeBufferId = 0; +void DrawCube( Scene* scene, b3Transform transform, b3HexColor color, const Matrix4& view, const Matrix4& projection ) +{ + // initialize (if necessary) + if ( cubeArrayId == 0 ) + { + // position / normal / uv + + float vertices[] = { + // back face + -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, // bottom-left + 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, // top-right + 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, // bottom-right + 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, // top-right + -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, // bottom-left + -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, // top-left + // front face + -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // bottom-left + 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // bottom-right + 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top-right + 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top-right + -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top-left + -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // bottom-left + // left face + -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, // top-right + -1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, // top-left + -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, // bottom-left + -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, // bottom-left + -1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, // bottom-right + -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, // top-right + // right face + 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // top-left + 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, // bottom-right + 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, // top-right + 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, // bottom-right + 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // top-left + 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // bottom-left + // bottom face + -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, // top-right + 1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, // top-left + 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, // bottom-left + 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, // bottom-left + -1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, // bottom-right + -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, // top-right + // top face + -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, // top-left + 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom-right + 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, // top-right + 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom-right + -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, // top-left + -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f // bottom-left + }; + + glGenVertexArrays( 1, &cubeArrayId ); + glGenBuffers( 1, &cubeBufferId ); + + // fill buffer + glBindBuffer( GL_ARRAY_BUFFER, cubeBufferId ); + glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW ); + + // link vertex attributes + glBindVertexArray( cubeArrayId ); + + // position + glEnableVertexAttribArray( 0 ); + glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof( float ), (void*)0 ); + + // normal + glEnableVertexAttribArray( 1 ); + glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof( float ), (void*)( 3 * sizeof( float ) ) ); + + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + } + + glUseProgram( scene->forwardShader ); + SetUniformMatrix4( scene->forwardShader, "projection", projection ); + SetUniformMatrix4( scene->forwardShader, "view", view ); + + Matrix4 m = MakeMatrix4( transform, 0.25f ); + SetUniformMatrix4( scene->forwardShader, "model", m ); + + RGBAf c = MakeRGBAf( color ); + SetUniformVec3( scene->forwardShader, "color", { c.r, c.g, c.b } ); + + glBindVertexArray( cubeArrayId ); + glDrawArrays( GL_TRIANGLES, 0, 36 ); + glBindVertexArray( 0 ); +} + +struct VertexData +{ + b3Vec3 position; + b3Vec3 normal; + int material; +}; + +// Creates a shape that can be instanced +InstanceShape CreateInstanceShape( const b3Vec3* vertexPositions, const b3Vec3* vertexNormals, const int* triangleIndices, + int triangleCount, const Edge* edges, int edgeCount, const int* materials, Arena arena ) +{ + InstanceShape shape = {}; + + // Vertex buffer + { + int vertexCount = 3 * triangleCount; + VertexData* vertexData = (VertexData*)arena.Allocate( vertexCount * sizeof( VertexData ) ); + + int index = 0; + for ( int triangleIndex = 0; triangleIndex < triangleCount; ++triangleIndex ) + { + int vertexIndex1 = triangleIndices[3 * triangleIndex + 0]; + int vertexIndex2 = triangleIndices[3 * triangleIndex + 1]; + int vertexIndex3 = triangleIndices[3 * triangleIndex + 2]; + + b3Vec3 vertexPosition1 = vertexPositions[vertexIndex1]; + b3Vec3 vertexPosition2 = vertexPositions[vertexIndex2]; + b3Vec3 vertexPosition3 = vertexPositions[vertexIndex3]; + + vertexData[index + 0].position = vertexPosition1; + vertexData[index + 1].position = vertexPosition2; + vertexData[index + 2].position = vertexPosition3; + + b3Vec3 vertexNormal1, vertexNormal2, vertexNormal3; + if ( vertexNormals ) + { + vertexNormal1 = vertexNormals[vertexIndex1]; + vertexNormal2 = vertexNormals[vertexIndex2]; + vertexNormal3 = vertexNormals[vertexIndex3]; + } + else + { + b3Vec3 edge1 = vertexPosition2 - vertexPosition1; + b3Vec3 edge2 = vertexPosition3 - vertexPosition1; + b3Vec3 normal = b3Cross( edge1, edge2 ); + normal = b3Normalize( normal ); + + vertexNormal1 = normal; + vertexNormal2 = normal; + vertexNormal3 = normal; + } + + vertexData[index + 0].normal = vertexNormal1; + vertexData[index + 1].normal = vertexNormal2; + vertexData[index + 2].normal = vertexNormal3; + + if ( materials != nullptr ) + { + vertexData[index + 0].material = materials[triangleIndex]; + vertexData[index + 1].material = materials[triangleIndex]; + vertexData[index + 2].material = materials[triangleIndex]; + } + else + { + vertexData[index + 0].material = -1; + vertexData[index + 1].material = -1; + vertexData[index + 2].material = -1; + } + + index += 3; + } + + assert( index == vertexCount ); + + // Fill vertex buffers + shape.triangleCount = triangleCount; + + glGenVertexArrays( 1, &shape.triangleArrayId ); + glGenBuffers( 2, shape.triangleBufferIds ); + + // Copy static vertex data + glBindVertexArray( shape.triangleArrayId ); + glBindBuffer( GL_ARRAY_BUFFER, shape.triangleBufferIds[0] ); + glBufferData( GL_ARRAY_BUFFER, vertexCount * sizeof( VertexData ), vertexData, GL_STATIC_DRAW ); + + // positions + uint32_t positionAttribute = 0; + glEnableVertexAttribArray( positionAttribute ); + glVertexAttribPointer( positionAttribute, 3, GL_FLOAT, GL_FALSE, sizeof( VertexData ), + (void*)offsetof( VertexData, position ) ); + + // normals + uint32_t normalAttribute = 1; + glEnableVertexAttribArray( normalAttribute ); + glVertexAttribPointer( normalAttribute, 3, GL_FLOAT, GL_FALSE, sizeof( VertexData ), + (void*)offsetof( VertexData, normal ) ); + + // materials + uint32_t materialAttribute = 2; + glEnableVertexAttribArray( materialAttribute ); + glVertexAttribIPointer( materialAttribute, 1, GL_INT, sizeof( VertexData ), (void*)offsetof( VertexData, material ) ); + + // Instance data setup + glBindBuffer( GL_ARRAY_BUFFER, shape.triangleBufferIds[1] ); + glBufferData( GL_ARRAY_BUFFER, s_batchSize * sizeof( InstanceData ), nullptr, GL_DYNAMIC_DRAW ); + + uint32_t colorInstance = 3; + glEnableVertexAttribArray( colorInstance ); + // Save bandwidth by expanding color to floats in the shader + glVertexAttribPointer( colorInstance, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( InstanceData ), + (void*)offsetof( InstanceData, rgba8 ) ); + + // This makes the color an instance + glVertexAttribDivisor( colorInstance, 1 ); + + // Matrix has to use 4 attributes each 16 bytes + uint32_t matrixAttribute = 4; + glEnableVertexAttribArray( matrixAttribute + 0 ); + glEnableVertexAttribArray( matrixAttribute + 1 ); + glEnableVertexAttribArray( matrixAttribute + 2 ); + glEnableVertexAttribArray( matrixAttribute + 3 ); + + glVertexAttribPointer( matrixAttribute + 0, 4, GL_FLOAT, GL_FALSE, sizeof( InstanceData ), + (void*)offsetof( InstanceData, matrix.cx ) ); + glVertexAttribPointer( matrixAttribute + 1, 4, GL_FLOAT, GL_FALSE, sizeof( InstanceData ), + (void*)offsetof( InstanceData, matrix.cy ) ); + glVertexAttribPointer( matrixAttribute + 2, 4, GL_FLOAT, GL_FALSE, sizeof( InstanceData ), + (void*)offsetof( InstanceData, matrix.cz ) ); + glVertexAttribPointer( matrixAttribute + 3, 4, GL_FLOAT, GL_FALSE, sizeof( InstanceData ), + (void*)offsetof( InstanceData, matrix.cw ) ); + + // This makes the matrix an instance + glVertexAttribDivisor( matrixAttribute + 0, 1 ); + glVertexAttribDivisor( matrixAttribute + 1, 1 ); + glVertexAttribDivisor( matrixAttribute + 2, 1 ); + glVertexAttribDivisor( matrixAttribute + 3, 1 ); + + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + } + + CheckOpenGL(); + + // Edges are optional + if ( edgeCount > 0 ) + { + // Create edge buffer + EdgeData* edgeBuffer = (EdgeData*)arena.Allocate( 2 * edgeCount * sizeof( EdgeData ) ); + for ( int edgeIndex = 0; edgeIndex < edgeCount; ++edgeIndex ) + { + int vertexIndex1 = edges[edgeIndex].index1; + int vertexIndex2 = edges[edgeIndex].index2; + int flags = edges[edgeIndex].flags; + + const b3Vec3* vb = vertexPositions; + b3Vec3 vertexPosition1 = vb[vertexIndex1]; + b3Vec3 vertexPosition2 = vb[vertexIndex2]; + + edgeBuffer[2 * edgeIndex + 0].position = vertexPosition1; + edgeBuffer[2 * edgeIndex + 0].flags = flags; + edgeBuffer[2 * edgeIndex + 1].position = vertexPosition2; + edgeBuffer[2 * edgeIndex + 1].flags = flags; + } + + shape.edgeCount = edgeCount; + + glGenVertexArrays( 1, &shape.edgeArrayId ); + glGenBuffers( 2, shape.edgeBufferIds ); + + // Copy static vertex data + glBindVertexArray( shape.edgeArrayId ); + glBindBuffer( GL_ARRAY_BUFFER, shape.edgeBufferIds[0] ); + glBufferData( GL_ARRAY_BUFFER, 2 * edgeCount * sizeof( EdgeData ), edgeBuffer, GL_STATIC_DRAW ); + + uint32_t positionIndex = 0; + glEnableVertexAttribArray( positionIndex ); + glVertexAttribPointer( positionIndex, 3, GL_FLOAT, GL_FALSE, sizeof( EdgeData ), (void*)offsetof( EdgeData, position ) ); + + uint32_t flagsIndex = 1; + glEnableVertexAttribArray( flagsIndex ); + glVertexAttribIPointer( flagsIndex, 1, GL_INT, sizeof( EdgeData ), (void*)offsetof( EdgeData, flags ) ); + + // Instance data setup + glBindBuffer( GL_ARRAY_BUFFER, shape.edgeBufferIds[1] ); + glBufferData( GL_ARRAY_BUFFER, s_batchSize * sizeof( InstanceData ), nullptr, GL_DYNAMIC_DRAW ); + + uint32_t colorInstance = 2; + glEnableVertexAttribArray( colorInstance ); + // Save bandwidth by expanding color to floats in the shader + glVertexAttribPointer( colorInstance, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( InstanceData ), + (void*)offsetof( InstanceData, rgba8 ) ); + + // This makes the color an instance + glVertexAttribDivisor( colorInstance, 1 ); + + // Matrix has to use 4 attributes each 16 bytes + uint32_t matrixAttribute = 3; + glEnableVertexAttribArray( matrixAttribute + 0 ); + glEnableVertexAttribArray( matrixAttribute + 1 ); + glEnableVertexAttribArray( matrixAttribute + 2 ); + glEnableVertexAttribArray( matrixAttribute + 3 ); + + glVertexAttribPointer( matrixAttribute + 0, 4, GL_FLOAT, GL_FALSE, sizeof( InstanceData ), + (void*)offsetof( InstanceData, matrix.cx ) ); + glVertexAttribPointer( matrixAttribute + 1, 4, GL_FLOAT, GL_FALSE, sizeof( InstanceData ), + (void*)offsetof( InstanceData, matrix.cy ) ); + glVertexAttribPointer( matrixAttribute + 2, 4, GL_FLOAT, GL_FALSE, sizeof( InstanceData ), + (void*)offsetof( InstanceData, matrix.cz ) ); + glVertexAttribPointer( matrixAttribute + 3, 4, GL_FLOAT, GL_FALSE, sizeof( InstanceData ), + (void*)offsetof( InstanceData, matrix.cw ) ); + + // This makes the matrix an instance + glVertexAttribDivisor( matrixAttribute + 0, 1 ); + glVertexAttribDivisor( matrixAttribute + 1, 1 ); + glVertexAttribDivisor( matrixAttribute + 2, 1 ); + glVertexAttribDivisor( matrixAttribute + 3, 1 ); + + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + } + + CheckOpenGL(); + + return shape; +} + +void DestroySharedShape( InstanceShape shape ) +{ + glDeleteBuffers( 2, shape.triangleBufferIds ); + glDeleteVertexArrays( 1, &shape.triangleArrayId ); + + if ( shape.edgeCount > 0 ) + { + glDeleteBuffers( 2, shape.edgeBufferIds ); + glDeleteVertexArrays( 1, &shape.edgeArrayId ); + } +} + +static InstanceShape CreateSphere( Arena arena ) +{ + float radius = 1.0f; + + int vertexCount = s_sideCount * s_ringCount + 2; + b3Vec3* vertices = (b3Vec3*)arena.Allocate( vertexCount * sizeof( b3Vec3 ) ); + b3Vec3* normals = (b3Vec3*)arena.Allocate( vertexCount * sizeof( b3Vec3 ) ); + + int triangleCount = s_sideCount * 2 * s_ringCount; + int* indices = (int*)arena.Allocate( 3 * triangleCount * sizeof( int ) ); + + // poles + vertices[s_sideCount * s_ringCount + 0] = b3Vec3{ -radius, 0.0f, 0.0f }; + normals[s_sideCount * s_ringCount + 0] = { -1.0f, 0.0f, 0.0f }; + vertices[s_sideCount * s_ringCount + 1] = b3Vec3{ radius, 0.0f, 0.0f }; + normals[s_sideCount * s_ringCount + 1] = { 1.0f, 0.0f, 0.0f }; + + int j = 0; + + for ( int i = 0; i < s_sideCount; ++i ) + { + float theta = ( -2 * B3_PI * i ) / s_sideCount; + float s0 = b3Sin( theta ); + float c0 = b3Cos( theta ); + + int i1 = ( i + 1 ) % s_sideCount; + + // Sides + for ( int k = 0; k <= s_ringCount; ++k ) + { + float phi = ( k + 1 ) * B3_PI / ( s_ringCount + 1 ) - 0.5f * B3_PI; + float x0 = b3Sin( phi ); + float y0 = b3Cos( phi ); + + b3Vec3 normal = { x0, c0 * y0, s0 * y0 }; + vertices[s_ringCount * i + k] = radius * normal; + normals[s_ringCount * i + k] = normal; + + if ( k + 1 < s_ringCount ) + { + indices[j++] = s_ringCount * i1 + k; + indices[j++] = s_ringCount * i + k; + indices[j++] = s_ringCount * i1 + k + 1; + + indices[j++] = s_ringCount * i1 + k + 1; + indices[j++] = s_ringCount * i + k; + indices[j++] = s_ringCount * i + k + 1; + } + else + { + // Needed the vertices, but not the indices + break; + } + + B3_ASSERT( s_ringCount * i + k + 1 < vertexCount ); + } + + // Caps + indices[j++] = s_ringCount * s_sideCount; + indices[j++] = s_ringCount * i; + indices[j++] = s_ringCount * i1; + + indices[j++] = s_ringCount * s_sideCount + 1; + indices[j++] = s_ringCount * i1 + s_ringCount - 1; + indices[j++] = s_ringCount * i + s_ringCount - 1; + } + + B3_ASSERT( j == 3 * triangleCount ); + + // todo add line discs for transparent view + + return CreateInstanceShape( vertices, normals, indices, triangleCount, nullptr, 0, nullptr, arena ); +} + +// Open hemisphere along x-axis. Radius is 1. +static InstanceShape CreateOpenHemisphere( Arena arena ) +{ + float radius = 1.0f; + + const int sideVertexCount = s_ringCount + 1; + + // Vertex count including pole + int vertexCount = s_sideCount * sideVertexCount + 1; + b3Vec3* vertices = (b3Vec3*)arena.Allocate( vertexCount * sizeof( b3Vec3 ) ); + b3Vec3* normals = (b3Vec3*)arena.Allocate( vertexCount * sizeof( b3Vec3 ) ); + + // Hemisphere quad rings and a cone at the pole + int triangleCount = 2 * s_sideCount * s_ringCount + s_sideCount; + int* indices = (int*)arena.Allocate( 3 * triangleCount * sizeof( int ) ); + + // Pole at the end of the array + vertices[s_sideCount * sideVertexCount] = b3Vec3{ radius, 0.0f, 0.0f }; + normals[s_sideCount * sideVertexCount] = b3Vec3{ 1.0f, 0.0f, 0.0f }; + + int j = 0; + + // loop sides + for ( int i = 0; i < s_sideCount; ++i ) + { + int i1 = ( i + 1 ) % s_sideCount; + + float theta = ( -2.0f * B3_PI * i ) / s_sideCount; + b3CosSin csTheta = b3ComputeCosSin( theta ); + float c0 = csTheta.cosine; + float s0 = csTheta.sine; + + // loop rings + for ( int k = 0;; ++k ) + { + int k1 = k + 1; + + float phi = ( 0.5f * k * B3_PI ) / ( s_ringCount + 1 ); + b3CosSin csPhi = b3ComputeCosSin( phi ); + float y0 = csPhi.cosine; + float x0 = csPhi.sine; + + b3Vec3 normal = { x0, c0 * y0, s0 * y0 }; + b3Vec3 vertex = radius * normal; + vertices[sideVertexCount * i + k] = vertex; + normals[sideVertexCount * i + k] = normal; + + if ( k < s_ringCount ) + { + // ring quad + indices[j++] = sideVertexCount * i1 + k; + indices[j++] = sideVertexCount * i + k; + indices[j++] = sideVertexCount * i1 + k1; + + indices[j++] = sideVertexCount * i1 + k1; + indices[j++] = sideVertexCount * i + k; + indices[j++] = sideVertexCount * i + k1; + } + else + { + // cone + indices[j++] = s_sideCount * sideVertexCount; + indices[j++] = sideVertexCount * i1 + k; + indices[j++] = sideVertexCount * i + k; + break; + } + } + } + + B3_ASSERT( j == 3 * triangleCount ); + + return CreateInstanceShape( vertices, normals, indices, triangleCount, nullptr, 0, nullptr, arena ); +} + +static InstanceShape CreateOpenCylinder( Arena arena ) +{ + float radius = 1.0f; + float height = 1.0f; + + int vertexCount = 2 * s_sideCount; + b3Vec3* vertices = (b3Vec3*)arena.Allocate( vertexCount * sizeof( b3Vec3 ) ); + b3Vec3* normals = (b3Vec3*)arena.Allocate( vertexCount * sizeof( b3Vec3 ) ); + + int triangleCount = 2 * s_sideCount; + int* indices = (int*)arena.Allocate( 3 * triangleCount * sizeof( int ) ); + + int j = 0; + + // loop sides + for ( int i = 0; i < s_sideCount; ++i ) + { + int i1 = ( i + 1 ) % s_sideCount; + + float theta = ( -2.0f * B3_PI * i ) / s_sideCount; + b3CosSin csTheta = b3ComputeCosSin( theta ); + float c0 = csTheta.cosine; + float s0 = csTheta.sine; + + b3Vec3 normal = { 0.0f, c0, s0 }; + b3Vec3 vertex1 = radius * normal - b3Vec3{ 0.5f * height, 0.0f, 0.0f }; + vertices[2 * i + 0] = vertex1; + normals[2 * i + 0] = normal; + + b3Vec3 vertex2 = radius * normal + b3Vec3{ 0.5f * height, 0.0f, 0.0f }; + vertices[2 * i + 1] = vertex2; + normals[2 * i + 1] = normal; + + // side quad + indices[j++] = 2 * i1; + indices[j++] = 2 * i; + indices[j++] = 2 * i1 + 1; + + indices[j++] = 2 * i1 + 1; + indices[j++] = 2 * i; + indices[j++] = 2 * i + 1; + } + + B3_ASSERT( j == 3 * triangleCount ); + + return CreateInstanceShape( vertices, normals, indices, triangleCount, nullptr, 0, nullptr, arena ); +} + +Scene* CreateScene( const Camera* camera, Arena arena ) +{ + Scene* scene = new Scene; + + scene->ao.radius = 1.0f; + scene->ao.bias = 0.25f; + scene->ao.minScale = 0.0f; + scene->ao.power = 2.0f; + scene->ao.direct = 0.5f; + scene->ao.aoOnly = false; + scene->useSSAO = true; + scene->useShadow = true; + scene->useGrid = false; + + scene->pointDraw = CreateDebugPoints(); + scene->lineDraw = CreateDebugLines(); + + scene->shadowShader = CreateProgramFromFiles( "shaders/shadow_map.vs", "shaders/empty.fs" ); + scene->meshShader = CreateProgramFromFiles( "shaders/mesh.vs", "shaders/mesh.fs" ); + scene->meshShadowShader = CreateProgramFromFiles( "shaders/mesh_shadow.vs", "shaders/empty.fs" ); + scene->meshEdgeShader = CreateProgramFromFiles( "shaders/mesh_edge.vs", "shaders/forward.fs" ); + scene->geometryShader = CreateProgramFromFiles( "shaders/geometry_vs.glsl", "shaders/geometry_fs.glsl" ); + scene->ssaoShader = CreateProgramFromFiles( "shaders/quad_vs.glsl", "shaders/ssao_fs.glsl" ); + scene->ssaoBlurShader = CreateProgramFromFiles( "shaders/quad_vs.glsl", "shaders/ssao_blur_fs.glsl" ); + scene->deferredShader = CreateProgramFromFiles( "shaders/quad_vs.glsl", "shaders/deferred_lighting_fs.glsl" ); + scene->meshForwardShader = CreateProgramFromFiles( "shaders/mesh_forward.vs", "shaders/mesh_forward.fs" ); + scene->forwardShader = CreateProgramFromFiles( "shaders/forward.vs", "shaders/forward.fs" ); + scene->depthCopyShader = CreateProgramFromFiles( "shaders/quad_vs.glsl", "shaders/depth_copy_fs.glsl" ); + + scene->sphere = CreateSphere( arena ); + scene->openHemisphere = CreateOpenHemisphere( arena ); + scene->openCylinder = CreateOpenCylinder( arena ); + + if ( scene->shadowShader == 0 || scene->meshShader == 0 || scene->meshEdgeShader == 0 || scene->meshEdgeShader == 0 || + scene->geometryShader == 0 || scene->ssaoShader == 0 || scene->ssaoBlurShader == 0 || scene->deferredShader == 0 || + scene->forwardShader == 0 || scene->depthCopyShader == 0 ) + { + fprintf( stderr, "Failed to create shaders\n" ); + return nullptr; + } + + // configure depth map FBO for shadow map + glGenFramebuffers( 1, &scene->depthMapFBO ); + + // create depth texture + glGenTextures( 1, &scene->depthMap ); + glBindTexture( GL_TEXTURE_2D, scene->depthMap ); + glTexImage2D( GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, shadowWidth, shadowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr ); + // Linear filtering combined with comparison mode gives free hardware 2x2 PCF + // inside each tap when sampled via sampler2DShadow. + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL ); + float borderColor[] = { 1.0f, 1.0f, 1.0f, 1.0f }; + glTexParameterfv( GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor ); + + // attach depth texture as FBO's depth buffer + glBindFramebuffer( GL_FRAMEBUFFER, scene->depthMapFBO ); + glFramebufferTexture2D( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, scene->depthMap, 0 ); + glDrawBuffer( GL_NONE ); + glReadBuffer( GL_NONE ); + glBindFramebuffer( GL_FRAMEBUFFER, 0 ); + + scene->geoBuffer = CreateGeoBuffer( camera->m_bufferWidth, camera->m_bufferHeight ); + scene->ssaoBuffer = CreateSsaoBuffer( camera->m_bufferWidth, camera->m_bufferHeight ); + + glUseProgram( scene->ssaoShader ); + SetUniformInt( scene->ssaoShader, "gPosition", 0 ); + SetUniformInt( scene->ssaoShader, "gNormal", 1 ); + SetUniformInt( scene->ssaoShader, "texNoise", 2 ); + + glUseProgram( scene->ssaoBlurShader ); + SetUniformInt( scene->ssaoBlurShader, "ssaoInput", 0 ); + SetUniformInt( scene->ssaoBlurShader, "gPosition", 1 ); + + glUseProgram( scene->deferredShader ); + SetUniformInt( scene->deferredShader, "gPosition", 0 ); + SetUniformInt( scene->deferredShader, "gNormal", 1 ); + SetUniformInt( scene->deferredShader, "gAlbedoSpec", 2 ); + SetUniformInt( scene->deferredShader, "ssao", 3 ); + SetUniformInt( scene->deferredShader, "shadowMap", 4 ); + + glUseProgram( scene->depthCopyShader ); + SetUniformInt( scene->depthCopyShader, "depthTexture", 0 ); + + return scene; +} + +void DestroySharedMeshes( Scene* scene ) +{ + for ( std::unordered_map::iterator shared = scene->sharedHeightFields.begin(); + shared != scene->sharedHeightFields.end(); ++shared ) + { + DestroySharedShape( shared->second ); + } + + for ( std::unordered_map::iterator shared = scene->sharedHulls.begin(); + shared != scene->sharedHulls.end(); ++shared ) + { + DestroySharedShape( shared->second ); + } + + for ( std::unordered_map::iterator shared = scene->sharedMeshes.begin(); + shared != scene->sharedMeshes.end(); ++shared ) + { + DestroySharedShape( shared->second ); + } + + scene->sharedHeightFields.clear(); + scene->sharedHulls.clear(); + scene->sharedMeshes.clear(); + scene->heightFieldInstances.clear(); + scene->hullInstances.clear(); + scene->meshInstances.clear(); + scene->transparentHullInstances.clear(); +} + +void DestroyScene( Scene* scene ) +{ + DestroyDebugPoints( scene->pointDraw ); + DestroyDebugLines( scene->lineDraw ); + DestroyGeoBuffer( scene->geoBuffer ); + DestroySsaoBuffer( scene->ssaoBuffer ); + + DestroySharedShape( scene->sphere ); + DestroySharedShape( scene->openHemisphere ); + DestroySharedShape( scene->openCylinder ); + + DestroySharedMeshes( scene ); + + DestroyShader( scene->shadowShader ); + DestroyShader( scene->meshShader ); + DestroyShader( scene->meshShadowShader ); + DestroyShader( scene->meshEdgeShader ); + DestroyShader( scene->geometryShader ); + DestroyShader( scene->ssaoShader ); + DestroyShader( scene->ssaoBlurShader ); + DestroyShader( scene->deferredShader ); + DestroyShader( scene->meshForwardShader ); + DestroyShader( scene->forwardShader ); + DestroyShader( scene->depthCopyShader ); + + delete scene; +} + +uint32_t CreateInstanceHull( Scene* scene, const b3Hull* hull, Arena arena ) +{ + uint32_t hash = hull->hash; + + std::unordered_map::iterator result = scene->sharedHulls.find( hash ); + if ( result != scene->sharedHulls.end() ) + { + // Already created + return hash; + } + + int vertexCount = hull->vertexCount; + b3Vec3* vertices = (b3Vec3*)arena.Allocate( hull->vertexCount * sizeof( b3Vec3 ) ); + + const b3Vec3* hullPoints = b3GetHullPoints( hull ); + memcpy( vertices, hullPoints, vertexCount * sizeof( b3Vec3 ) ); + + int triangleCount = 0; + int faceCount = hull->faceCount; + const b3HullFace* hullFaces = b3GetHullFaces( hull ); + const b3HullHalfEdge* hullEdges = b3GetHullEdges( hull ); + + // Count triangles + for ( int i = 0; i < faceCount; ++i ) + { + const b3HullFace* face = hullFaces + i; + + const b3HullHalfEdge* edge1 = hullEdges + face->edge; + const b3HullHalfEdge* edge2 = hullEdges + edge1->next; + const b3HullHalfEdge* edge3 = hullEdges + edge2->next; + B3_ASSERT( edge1 != edge3 ); + + do + { + triangleCount += 1; + edge3 = hullEdges + edge3->next; + } + while ( edge1 != edge3 ); + } + + int* indices = (int*)arena.Allocate( 3 * triangleCount * sizeof( int ) ); + int triangleIndex = 0; + + for ( int i = 0; i < faceCount; ++i ) + { + const b3HullFace* face = hullFaces + i; + + const b3HullHalfEdge* edge1 = hullEdges + face->edge; + const b3HullHalfEdge* edge2 = hullEdges + edge1->next; + const b3HullHalfEdge* edge3 = hullEdges + edge2->next; + B3_ASSERT( edge1 != edge3 ); + + do + { + B3_ASSERT( triangleIndex < triangleCount ); + indices[3 * triangleIndex + 0] = edge1->origin; + indices[3 * triangleIndex + 1] = edge2->origin; + indices[3 * triangleIndex + 2] = edge3->origin; + triangleIndex += 1; + + edge2 = edge3; + edge3 = hullEdges + edge3->next; + } + while ( edge1 != edge3 ); + } + + B3_ASSERT( triangleIndex == triangleCount ); + + int edgeCount = hull->edgeCount / 2; + Edge* edges = (Edge*)arena.Allocate( edgeCount * sizeof( Edge ) ); + + for ( int i = 0; i < edgeCount; ++i ) + { + const b3HullHalfEdge* edge = hullEdges + 2 * i + 0; + const b3HullHalfEdge* twin = hullEdges + 2 * i + 1; + + edges[i].index1 = edge->origin; + edges[i].index2 = twin->origin; + edges[i].flags = 0; + } + + InstanceShape shape = CreateInstanceShape( vertices, nullptr, indices, triangleCount, edges, edgeCount, nullptr, arena ); + scene->sharedHulls[hash] = shape; + + // reserve a slot + scene->hullInstances[hash] = {}; + scene->transparentHullInstances[hash] = {}; + + return hash; +} + +static inline bool EdgeLess( Edge e1, Edge e2 ) +{ + if ( e1.index1 == e2.index1 ) + { + return e1.index2 < e2.index2; + } + + return e1.index1 < e2.index1; +} + +static bool EdgeEquals( Edge e1, Edge e2 ) +{ + return e1.index1 == e2.index1 && e1.index2 == e2.index2; +} + +uint32_t CreateInstanceMesh( Scene* scene, const b3MeshData* meshData, Arena arena ) +{ + uint32_t hash = meshData->hash; + + std::unordered_map::iterator result = scene->sharedMeshes.find( hash ); + if ( result != scene->sharedMeshes.end() ) + { + // Already created + return hash; + } + + int vertexCount = meshData->vertexCount; + const b3Vec3* meshVertices = b3GetMeshVertices( meshData ); + + int triangleCount = meshData->triangleCount; + std::vector indices; + indices.resize( 3 * triangleCount ); + + int edgeCount = 3 * triangleCount; + std::vector edges; + edges.resize( edgeCount ); + + std::vector materials; + materials.resize( triangleCount ); + + const b3MeshTriangle* meshTriangles = b3GetMeshTriangles( meshData ); + const uint8_t* materialIndices = b3GetMeshMaterialIndices( meshData ); + const uint8_t* meshFlags = b3GetMeshFlags( meshData ); + + for ( int i = 0; i < triangleCount; ++i ) + { + b3MeshTriangle triangle = meshTriangles[i]; + + int i1 = triangle.index1; + int i2 = triangle.index2; + int i3 = triangle.index3; + + assert( i1 < vertexCount && i2 < vertexCount && i3 < vertexCount ); + + indices[3 * i + 0] = i1; + indices[3 * i + 1] = i2; + indices[3 * i + 2] = i3; + + uint8_t triangleFlags = meshFlags[i]; + + int flag1 = ( triangleFlags & b3_concaveEdge1 ) != 0 ? 0 : 1; + int flag2 = ( triangleFlags & b3_concaveEdge2 ) != 0 ? 0 : 1; + int flag3 = ( triangleFlags & b3_concaveEdge3 ) != 0 ? 0 : 1; + + edges[3 * i + 0] = { i1, i2, flag1 }; + edges[3 * i + 1] = { i2, i3, flag2 }; + edges[3 * i + 2] = { i3, i1, flag3 }; + + if ( materialIndices != nullptr ) + { + materials[i] = materialIndices[i]; + } + else + { + materials[i] = 0; + } + } + + // Remove duplicate edges + std::sort( edges.data(), edges.data() + edges.size(), EdgeLess ); + auto last = std::ranges::unique( edges, EdgeEquals ).begin(); + edges.erase( last, edges.end() ); + edgeCount = (int)edges.size(); + + InstanceShape shape = CreateInstanceShape( meshVertices, nullptr, indices.data(), triangleCount, edges.data(), edgeCount, + materials.data(), arena ); + scene->sharedMeshes[hash] = shape; + + // reserve a slot + scene->meshInstances[hash] = {}; + + return hash; +} + +uint32_t CreateInstanceHeightField( Scene* scene, const b3HeightField* heightField, Arena arena ) +{ + uint32_t hash = heightField->hash; + + std::unordered_map::iterator result = scene->sharedHeightFields.find( hash ); + if ( result != scene->sharedHeightFields.end() ) + { + // Already created + return hash; + } + + int rowCount = heightField->rowCount; + int columnCount = heightField->columnCount; + uint16_t* compressedHeights = heightField->compressedHeights; + uint8_t* materialIndices = heightField->materialIndices; + uint8_t* flags = heightField->flags; + float minHeight = heightField->minHeight; + float heightScale = heightField->heightScale; + b3Vec3 scale = heightField->scale; + + int vertexCount = rowCount * columnCount; + int cellCount = ( rowCount - 1 ) * ( columnCount - 1 ); + + std::vector vertices; + vertices.resize( vertexCount ); + + int vertexIndex = 0; + for ( int row = 0; row < rowCount; ++row ) + { + for ( int column = 0; column < columnCount; ++column ) + { + int heightIndex = row * columnCount + column; + + float x = float( column ); + float y = minHeight + heightScale * compressedHeights[heightIndex]; + float z = float( row ); + + vertices[vertexIndex] = scale * b3Vec3{ x, y, z }; + vertexIndex += 1; + } + } + assert( vertexIndex == vertexCount ); + + int triangleCount = 2 * ( rowCount - 1 ) * ( columnCount - 1 ); + + std::vector materials; + materials.resize( triangleCount ); + + // int cellCount = triangleCount >> 1; + int materialIndex = 0; + for ( int i = 0; i < cellCount; ++i ) + { + uint8_t index = materialIndices[i]; + if ( index != B3_HEIGHT_FIELD_HOLE ) + { + materials[materialIndex + 0] = index; + materials[materialIndex + 1] = index; + materialIndex += 2; + } + } + + int indexCount = 3 * triangleCount; + std::vector indices; + indices.resize( indexCount ); + + // Edge along each column, row, and diagonal + int edgeCount = columnCount * ( rowCount - 1 ) + rowCount * ( columnCount - 1 ) + ( rowCount - 1 ) * ( columnCount - 1 ); + std::vector edges; + edges.resize( edgeCount ); + + int index = 0; + int edgeIndex = 0; + for ( int row = 0; row < rowCount - 1; ++row ) + { + for ( int column = 0; column < columnCount - 1; ++column ) + { + int cellIndex = row * ( columnCount - 1 ) + column; + int triangleIndex = 2 * cellIndex; + assert( triangleIndex < triangleCount ); + + assert( cellIndex < cellCount ); + if ( materialIndices[cellIndex] == B3_HEIGHT_FIELD_HOLE ) + { + continue; + } + + int index11 = row * columnCount + column; + int index12 = index11 + 1; + int index21 = ( row + 1 ) * columnCount + column; + int index22 = index21 + 1; + + indices[index + 0] = index11; + indices[index + 1] = index21; + indices[index + 2] = index12; + + indices[index + 3] = index22; + indices[index + 4] = index12; + indices[index + 5] = index21; + + index += 6; + + int flag = ( flags[triangleIndex] & b3_concaveEdge2 ) != 0 ? 0 : 1; + edges[edgeIndex] = { index12, index21, flag }; + edgeIndex += 1; + } + } + assert( index <= indexCount ); + indexCount = index; + + // Edge rows + for ( int row = 0; row < rowCount; ++row ) + { + for ( int column = 0; column < columnCount - 1; ++column ) + { + int index1 = row * columnCount + column; + int index2 = index1 + 1; + + int flag; + if ( row < rowCount - 1 ) + { + int cellIndex = row * ( columnCount - 1 ) + column; + int triangleIndex = 2 * cellIndex; + + assert( triangleIndex < triangleCount ); + flag = ( flags[triangleIndex] & b3_concaveEdge3 ) != 0 ? 0 : 1; + } + else + { + int cellIndex = ( row - 1 ) * ( columnCount - 1 ) + column; + int triangleIndex = 2 * cellIndex + 1; + assert( triangleIndex < triangleCount ); + flag = ( flags[triangleIndex] & b3_concaveEdge3 ) != 0 ? 0 : 1; + } + + edges[edgeIndex + 0] = { index1, index2, flag }; + edgeIndex += 1; + } + } + + // Edge columns + for ( int column = 0; column < columnCount; ++column ) + { + for ( int row = 0; row < rowCount - 1; ++row ) + { + int index1 = row * columnCount + column; + int index2 = ( row + 1 ) * columnCount + column; + + int flag; + if ( column < columnCount - 1 ) + { + int cellIndex = row * ( columnCount - 1 ) + column; + int triangleIndex = 2 * cellIndex; + assert( triangleIndex < triangleCount ); + flag = ( flags[triangleIndex] & b3_concaveEdge1 ) != 0 ? 0 : 1; + } + else + { + int cellIndex = row * ( columnCount - 1 ) + column - 1; + int triangleIndex = 2 * cellIndex + 1; + assert( triangleIndex < triangleCount ); + flag = ( flags[triangleIndex] & b3_concaveEdge1 ) != 0 ? 0 : 1; + } + + edges[edgeIndex + 0] = { index1, index2, flag }; + edgeIndex += 1; + } + } + assert( edgeIndex <= edgeCount ); + edgeCount = edgeIndex; + + triangleCount = indexCount / 3; + + assert( materialIndex == triangleCount ); + + InstanceShape shape = CreateInstanceShape( vertices.data(), nullptr, indices.data(), triangleCount, edges.data(), edgeCount, + materials.data(), arena ); + scene->sharedHeightFields[hash] = shape; + + // reserve a slot + scene->heightFieldInstances[hash] = {}; + + return hash; +} + +void ResizeScene( Scene* scene, const Camera* camera ) +{ + DestroyGeoBuffer( scene->geoBuffer ); + scene->geoBuffer = CreateGeoBuffer( camera->m_bufferWidth, camera->m_bufferHeight ); + + DestroySsaoBuffer( scene->ssaoBuffer ); + scene->ssaoBuffer = CreateSsaoBuffer( camera->m_bufferWidth, camera->m_bufferHeight ); + + CheckOpenGL(); +} + +#if 0 +UniqueMesh CreateUniqueMesh( const b3Vec3* vertexPositions, const b3Vec3* vertexNormals, int triangleCount, + const int* triangleIndices, const Edge* edges, int edgeCount, const int* materials, Arena arena ) +{ + UniqueMesh shape = {}; + + // Vertex buffers + { + // Create vertex buffers + int vertexCount = 3 * triangleCount; + VertexData* vertexData = (VertexData*)arena.Allocate( vertexCount * sizeof( VertexData ) ); + + int index = 0; + for ( int triangleIndex = 0; triangleIndex < triangleCount; ++triangleIndex ) + { + int vertexIndex1 = triangleIndices[3 * triangleIndex + 0]; + int vertexIndex2 = triangleIndices[3 * triangleIndex + 1]; + int vertexIndex3 = triangleIndices[3 * triangleIndex + 2]; + + b3Vec3 vertexPosition1 = vertexPositions[vertexIndex1]; + b3Vec3 vertexPosition2 = vertexPositions[vertexIndex2]; + b3Vec3 vertexPosition3 = vertexPositions[vertexIndex3]; + + vertexData[index + 0].position = vertexPosition1; + vertexData[index + 1].position = vertexPosition2; + vertexData[index + 2].position = vertexPosition3; + + b3Vec3 vertexNormal1, vertexNormal2, vertexNormal3; + if ( vertexNormals ) + { + vertexNormal1 = vertexNormals[vertexIndex1]; + vertexNormal2 = vertexNormals[vertexIndex2]; + vertexNormal3 = vertexNormals[vertexIndex3]; + } + else + { + b3Vec3 edge1 = vertexPosition2 - vertexPosition1; + b3Vec3 edge2 = vertexPosition3 - vertexPosition1; + b3Vec3 normal = b3Cross( edge1, edge2 ); + normal = b3Normalize( normal ); + + vertexNormal1 = normal; + vertexNormal2 = normal; + vertexNormal3 = normal; + } + + vertexData[index + 0].normal = vertexNormal1; + vertexData[index + 1].normal = vertexNormal2; + vertexData[index + 2].normal = vertexNormal3; + + if ( materials != nullptr ) + { + vertexData[index + 0].material = materials[triangleIndex]; + vertexData[index + 1].material = materials[triangleIndex]; + vertexData[index + 2].material = materials[triangleIndex]; + } + else + { + vertexData[index + 0].material = -1; + vertexData[index + 1].material = -1; + vertexData[index + 2].material = -1; + } + + index += 3; + } + + assert( index == vertexCount ); + + // Fill vertex buffers + shape.triangleCount = triangleCount; + + glGenVertexArrays( 1, &shape.vertexArrayId ); + glGenBuffers( 1, &shape.vertexBufferId ); + + // Copy static vertex data + glBindVertexArray( shape.vertexArrayId ); + glBindBuffer( GL_ARRAY_BUFFER, shape.vertexBufferId ); + glBufferData( GL_ARRAY_BUFFER, vertexCount * sizeof( VertexData ), vertexData, GL_STATIC_DRAW ); + + // positions + uint32_t positionAttribute = 0; + glEnableVertexAttribArray( positionAttribute ); + glVertexAttribPointer( positionAttribute, 3, GL_FLOAT, GL_FALSE, sizeof( VertexData ), + (void*)offsetof( VertexData, position ) ); + + // normals + uint32_t normalAttribute = 1; + glEnableVertexAttribArray( normalAttribute ); + glVertexAttribPointer( normalAttribute, 3, GL_FLOAT, GL_FALSE, sizeof( VertexData ), + (void*)offsetof( VertexData, normal ) ); + + // materials + uint32_t materialAttribute = 2; + glEnableVertexAttribArray( materialAttribute ); + glVertexAttribIPointer( materialAttribute, 1, GL_INT, sizeof( VertexData ), (void*)offsetof( VertexData, material ) ); + + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + + shape.shadowCaster = true; + } + + // Edge buffer + { + // Create edge buffer + EdgeData* edgeBuffer = (EdgeData*)arena.Allocate( 2 * edgeCount * sizeof( EdgeData ) ); + + for ( int edgeIndex = 0; edgeIndex < edgeCount; ++edgeIndex ) + { + int vertexIndex1 = edges[edgeIndex].index1; + int vertexIndex2 = edges[edgeIndex].index2; + int flags = edges[edgeIndex].flags; + + const b3Vec3* vb = vertexPositions; + b3Vec3 vertexPosition1 = vb[vertexIndex1]; + b3Vec3 vertexPosition2 = vb[vertexIndex2]; + + edgeBuffer[2 * edgeIndex + 0].position = vertexPosition1; + edgeBuffer[2 * edgeIndex + 0].flags = flags; + edgeBuffer[2 * edgeIndex + 1].position = vertexPosition2; + edgeBuffer[2 * edgeIndex + 1].flags = flags; + } + + // Fill edge buffer + shape.edgeCount = edgeCount; + + glGenVertexArrays( 1, &shape.edgeArrayId ); + glGenBuffers( 1, &shape.edgeBufferId ); + + glBindVertexArray( shape.edgeArrayId ); + glBindBuffer( GL_ARRAY_BUFFER, shape.edgeBufferId ); + glBufferData( GL_ARRAY_BUFFER, 2 * edgeCount * sizeof( EdgeData ), edgeBuffer, GL_STATIC_DRAW ); + + uint32_t positionIndex = 0; + glEnableVertexAttribArray( positionIndex ); + glVertexAttribPointer( positionIndex, 3, GL_FLOAT, GL_FALSE, sizeof( EdgeData ), (void*)offsetof( EdgeData, position ) ); + + uint32_t flagsIndex = 1; + glEnableVertexAttribArray( flagsIndex ); + glVertexAttribIPointer( flagsIndex, 1, GL_INT, sizeof( EdgeData ), (void*)offsetof( EdgeData, flags ) ); + + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + } + + CheckOpenGL(); + + return shape; +} + +void DestroyUniqueMesh( UniqueMesh* shape ) +{ + if ( shape->vertexBufferId != 0 ) + { + glDeleteBuffers( 1, &shape->vertexBufferId ); + } + + if ( shape->vertexArrayId != 0 ) + { + glDeleteVertexArrays( 1, &shape->vertexArrayId ); + } + + if ( shape->edgeBufferId != 0 ) + { + glDeleteBuffers( 1, &shape->edgeBufferId ); + } + + if ( shape->edgeArrayId != 0 ) + { + glDeleteVertexArrays( 1, &shape->edgeArrayId ); + } +} +#endif + +void DrawDebugCapsule( Scene* scene, DebugCapsule* capsule, b3Transform transform, b3HexColor color, float alpha ) +{ + float radius = capsule->radius; + b3Vec3 c1 = capsule->center1; + b3Vec3 c2 = capsule->center2; + b3Vec3 origin = 0.5f * ( c1 + c2 ); + b3Vec3 d = c2 - c1; + float length = b3Length( d ); + + assert( length > 0.005f ); + + RGBA8 rgba8 = MakeRGBA8( color, alpha ); + b3Vec3 axis = b3Normalize( d ); + + // Capsule mesh is along x-axis. Build from two open hemispheres and an open cylinder. + + // Left cap + b3Quat qc1 = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisX, -axis ); + + b3Transform xfCap1 = { + .p = b3TransformPoint( transform, c1 ), + .q = b3MulQuat( transform.q, qc1 ), + }; + + Matrix4 matrixCap1 = MakeMatrix4( xfCap1, radius ); + + // Right cap + b3Quat qc2 = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisX, axis ); + + b3Transform xfCap2 = { + .p = b3TransformPoint( transform, c2 ), + .q = b3MulQuat( transform.q, qc2 ), + }; + + Matrix4 matrixCap2 = MakeMatrix4( xfCap2, radius ); + + // Middle + b3Transform xfMiddle = { + .p = b3TransformPoint( transform, origin ), + .q = b3MulQuat( transform.q, qc2 ), + }; + + Matrix4 matrixMiddle = MakeMatrix4( xfMiddle, { length, radius, radius } ); + + if ( alpha < 1.0f ) + { + scene->transparentOpenHemisphereInstances.push_back( { + .rgba8 = rgba8, + .matrix = matrixCap1, + } ); + + scene->transparentOpenHemisphereInstances.push_back( { + .rgba8 = rgba8, + .matrix = matrixCap2, + } ); + + scene->transparentOpenCylinderInstances.push_back( { + .rgba8 = rgba8, + .matrix = matrixMiddle, + } ); + } + else + { + scene->openHemisphereInstances.push_back( { + .rgba8 = rgba8, + .matrix = matrixCap1, + } ); + + scene->openHemisphereInstances.push_back( { + .rgba8 = rgba8, + .matrix = matrixCap2, + } ); + + scene->openCylinderInstances.push_back( { + .rgba8 = rgba8, + .matrix = matrixMiddle, + } ); + } +} + +void DrawDebugHull( Scene* scene, DebugHull* hull, b3Transform transform, b3HexColor color, float alpha ) +{ + b3Transform worldTransform = b3MulTransforms( transform, hull->transform ); + Matrix4 matrix = MakeMatrix4( worldTransform, 1.0f ); + InstanceData instanceData = { + .rgba8 = MakeRGBA8( color, alpha ), + .matrix = matrix, + }; + + uint32_t id = hull->id; + if ( alpha < 1.0f ) + { + assert( scene->transparentHullInstances.contains( id ) ); + scene->transparentHullInstances[id].push_back( instanceData ); + } + else + { + assert( scene->hullInstances.contains( id ) ); + scene->hullInstances[id].push_back( instanceData ); + } +} + +void DrawDebugMesh( Scene* scene, DebugMesh* mesh, b3Transform transform, b3HexColor color, float alpha ) +{ + b3Transform worldTransform = b3MulTransforms( transform, mesh->transform ); + Matrix4 matrix = MakeMatrix4( worldTransform, mesh->scale ); + InstanceData instanceData = { + .rgba8 = MakeRGBA8( color, alpha ), + .matrix = matrix, + }; + + uint32_t id = mesh->id; + assert( scene->meshInstances.contains( id ) ); + scene->meshInstances[id].push_back( instanceData ); +} + +void DrawDebugSphere( Scene* scene, DebugSphere* sphere, b3Transform transform, b3HexColor color, float alpha ) +{ + b3Vec3 center = sphere->center; + b3Transform xf = { + .p = b3TransformPoint( transform, center ), + .q = transform.q, + }; + Matrix4 matrix = MakeMatrix4( xf, sphere->radius ); + InstanceData instanceData = { + .rgba8 = MakeRGBA8( color, alpha ), + .matrix = matrix, + }; + + if ( alpha < 1.0f ) + { + scene->transparentSphereInstances.push_back( instanceData ); + } + else + { + scene->sphereInstances.push_back( instanceData ); + } +} + +void DrawDebugShape( Scene* scene, DebugShape* debugShape, b3Transform transform, b3HexColor color, float alpha ) +{ + switch ( debugShape->type ) + { + case DebugShapeType::capsule: + DrawDebugCapsule( scene, &debugShape->capsule, transform, color, alpha ); + break; + + case DebugShapeType::compound: + { + DebugCompound* compound = &debugShape->compound; + for ( int i = 0; i < compound->capsuleCount; ++i ) + { + DrawDebugCapsule( scene, compound->capsules + i, transform, color, alpha ); + } + + for ( int i = 0; i < compound->hullCount; ++i ) + { + DrawDebugHull( scene, compound->hulls + i, transform, color, alpha ); + } + + for ( int i = 0; i < compound->meshCount; ++i ) + { + DrawDebugMesh( scene, compound->meshes + i, transform, color, alpha ); + } + + for ( int i = 0; i < compound->sphereCount; ++i ) + { + DrawDebugSphere( scene, compound->spheres + i, transform, color, alpha ); + } + } + break; + + case DebugShapeType::hull: + DrawDebugHull( scene, &debugShape->hull, transform, color, alpha ); + break; + + case DebugShapeType::heightField: + { + Matrix4 matrix = MakeMatrix4( transform, 1.0f ); + InstanceData instanceData = { + .rgba8 = MakeRGBA8( color, alpha ), + .matrix = matrix, + }; + + uint32_t id = debugShape->heightField.id; + assert( scene->heightFieldInstances.contains( id ) ); + scene->heightFieldInstances[id].push_back( instanceData ); + } + break; + + case DebugShapeType::mesh: + { + b3Transform xf = b3MulTransforms( transform, debugShape->hull.transform ); + Matrix4 matrix = MakeMatrix4( xf, debugShape->mesh.scale ); + InstanceData instanceData = { + .rgba8 = MakeRGBA8( color, alpha ), + .matrix = matrix, + }; + + uint32_t id = debugShape->mesh.id; + assert( scene->meshInstances.contains( id ) ); + scene->meshInstances[id].push_back( instanceData ); + } + break; + + case DebugShapeType::sphere: + DrawDebugSphere( scene, &debugShape->sphere, transform, color, alpha ); + break; + + default: + assert( false ); + break; + } +} + +static void DrawMeshInstances( InstanceShape shape, const InstanceData* instances, int count, bool cull ) +{ + if ( count == 0 ) + { + return; + } + + if ( cull == false ) + { + glDisable( GL_CULL_FACE ); + } + + glBindVertexArray( shape.triangleArrayId ); + glBindBuffer( GL_ARRAY_BUFFER, shape.triangleBufferIds[1] ); + + int base = 0; + while ( count > 0 ) + { + int batchCount = b3MinInt( count, s_batchSize ); + + glBufferData( GL_ARRAY_BUFFER, s_batchSize * sizeof( InstanceData ), nullptr, GL_DYNAMIC_DRAW ); + glBufferSubData( GL_ARRAY_BUFFER, 0, batchCount * sizeof( InstanceData ), &instances[base] ); + glDrawArraysInstanced( GL_TRIANGLES, 0, 3 * shape.triangleCount, batchCount ); + + // CheckOpenGL(); + + count -= s_batchSize; + base += s_batchSize; + } + + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + + if ( cull == false ) + { + glEnable( GL_CULL_FACE ); + } +} + +static void DrawEdgeInstances( InstanceShape shape, const InstanceData* instances, int count ) +{ + if ( count == 0 ) + { + return; + } + + glBindVertexArray( shape.edgeArrayId ); + glBindBuffer( GL_ARRAY_BUFFER, shape.edgeBufferIds[1] ); + + int base = 0; + while ( count > 0 ) + { + int batchCount = b3MinInt( count, s_batchSize ); + + glBufferData( GL_ARRAY_BUFFER, s_batchSize * sizeof( InstanceData ), nullptr, GL_DYNAMIC_DRAW ); + glBufferSubData( GL_ARRAY_BUFFER, 0, batchCount * sizeof( InstanceData ), &instances[base] ); + glDrawArraysInstanced( GL_LINES, 0, 2 * shape.edgeCount, batchCount ); + + // CheckOpenGL(); + + count -= s_batchSize; + base += s_batchSize; + } + + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); +} + +static void DrawMeshes( Scene* scene, const Matrix4& view, const Matrix4& projection, bool forShadow ) +{ + if ( forShadow == true ) + { + // Receiver-plane depth bias in the deferred shader handles per-pixel bias + // precisely, so the shadow pass needs no polygon offset. Adding one back + // reintroduces "Peter Panning" — a visible gap between objects and their + // contact shadows. + glDisable( GL_POLYGON_OFFSET_FILL ); + + glUseProgram( scene->meshShadowShader ); + SetUniformMatrix4( scene->meshShadowShader, "lightSpaceMatrix", view ); + } + else + { + glEnable( GL_POLYGON_OFFSET_FILL ); + glPolygonOffset( 2.0f, 2.0f ); + + glUseProgram( scene->meshShader ); + SetUniformMatrix4( scene->meshShader, "view", view ); + SetUniformMatrix4( scene->meshShader, "projection", projection ); + } + + DrawMeshInstances( scene->sphere, scene->sphereInstances.data(), (int)scene->sphereInstances.size(), true ); + DrawMeshInstances( scene->openHemisphere, scene->openHemisphereInstances.data(), (int)scene->openHemisphereInstances.size(), + true ); + DrawMeshInstances( scene->openCylinder, scene->openCylinderInstances.data(), (int)scene->openCylinderInstances.size(), true ); + + for ( std::unordered_map>::iterator instances = scene->heightFieldInstances.begin(); + instances != scene->heightFieldInstances.end(); ++instances ) + { + uint32_t id = instances->first; + InstanceShape shape = scene->sharedHeightFields.at( id ); + DrawMeshInstances( shape, instances->second.data(), (int)instances->second.size(), true ); + } + + for ( std::unordered_map>::iterator instances = scene->hullInstances.begin(); + instances != scene->hullInstances.end(); ++instances ) + { + uint32_t id = instances->first; + InstanceShape shape = scene->sharedHulls.at( id ); + DrawMeshInstances( shape, instances->second.data(), (int)instances->second.size(), true ); + } + + for ( std::unordered_map>::iterator instances = scene->meshInstances.begin(); + instances != scene->meshInstances.end(); ++instances ) + { + uint32_t id = instances->first; + InstanceShape shape = scene->sharedMeshes.at( id ); + DrawMeshInstances( shape, instances->second.data(), (int)instances->second.size(), false ); + } + + glDisable( GL_POLYGON_OFFSET_FILL ); +} + +static void DrawTransparentShapes( Scene* scene, const Matrix4& view, const Matrix4& projection, b3Vec3 sunDirWorld, + b3Vec3 cameraPos ) +{ + glUseProgram( scene->meshForwardShader ); + SetUniformVec3( scene->meshForwardShader, "sunDirWorld", sunDirWorld ); + SetUniformVec3( scene->meshForwardShader, "cameraPos", cameraPos ); + + SetUniformMatrix4( scene->meshForwardShader, "view", view ); + SetUniformMatrix4( scene->meshForwardShader, "projection", projection ); + + glEnable( GL_POLYGON_OFFSET_FILL ); + glPolygonOffset( 2.0, 2.0 ); + + glCullFace( GL_BACK ); + glEnable( GL_CULL_FACE ); + glEnable( GL_BLEND ); + glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + glDepthMask( GL_FALSE ); + + DrawMeshInstances( scene->sphere, scene->transparentSphereInstances.data(), (int)scene->transparentSphereInstances.size(), + true ); + DrawMeshInstances( scene->openHemisphere, scene->transparentOpenHemisphereInstances.data(), + (int)scene->transparentOpenHemisphereInstances.size(), true ); + DrawMeshInstances( scene->openCylinder, scene->transparentOpenCylinderInstances.data(), + (int)scene->transparentOpenCylinderInstances.size(), true ); + + for ( std::unordered_map>::iterator hulls = scene->transparentHullInstances.begin(); + hulls != scene->transparentHullInstances.end(); ++hulls ) + { + uint32_t id = hulls->first; + InstanceShape shape = scene->sharedHulls.at( id ); + DrawMeshInstances( shape, hulls->second.data(), (int)hulls->second.size(), true ); + } + + glDisable( GL_POLYGON_OFFSET_FILL ); + glDisable( GL_BLEND ); + glDepthMask( GL_TRUE ); +} + +#if 0 +static void DrawObjects( Scene* scene, uint32_t shader, bool isShadow ) +{ + CheckOpenGL(); + + // glFrontFace( GL_CCW ); + // glDepthFunc( GL_LESS ); + // glCullFace( GL_BACK ); + glEnable( GL_POLYGON_OFFSET_FILL ); + glPolygonOffset( 2.0, 2.0 ); + + for ( int i = 0; i < scene->uniqueShapes.size(); ++i ) + { + UniqueShape& shape = scene->uniqueShapes[i]; + if ( isShadow && shape.mesh->shadowCaster == false ) + { + continue; + } + + if ( shape.color.a < 1.0f ) + { + continue; + } + + SetUniformMatrix4( shader, "model", shape.matrix ); + SetUniformColor( shader, "objectColor", shape.color ); + SetUniformBool( shader, "invertedNormals", false ); + CheckOpenGL(); + + glBindVertexArray( shape.mesh->vertexArrayId ); + glDrawArrays( GL_TRIANGLES, 0, 3 * shape.mesh->triangleCount ); + glBindVertexArray( 0 ); + + CheckOpenGL(); + } + + glDisable( GL_POLYGON_OFFSET_FILL ); +} +#endif + +static void DrawLines( Scene* scene, const Matrix4& view, const Matrix4& projection ) +{ + // WARNING: very slow + // glEnable( GL_LINE_SMOOTH ); + + glEnable( GL_BLEND ); + glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + + glUseProgram( scene->meshEdgeShader ); + SetUniformMatrix4( scene->meshEdgeShader, "view", view ); + SetUniformMatrix4( scene->meshEdgeShader, "projection", projection ); + + for ( std::unordered_map>::iterator instances = scene->heightFieldInstances.begin(); + instances != scene->heightFieldInstances.end(); ++instances ) + { + uint32_t id = instances->first; + InstanceShape shape = scene->sharedHeightFields.at( id ); + DrawEdgeInstances( shape, instances->second.data(), (int)instances->second.size() ); + } + + for ( std::unordered_map>::iterator instances = scene->hullInstances.begin(); + instances != scene->hullInstances.end(); ++instances ) + { + uint32_t id = instances->first; + InstanceShape shape = scene->sharedHulls.at( id ); + DrawEdgeInstances( shape, instances->second.data(), (int)instances->second.size() ); + } + + for ( std::unordered_map>::iterator instances = scene->meshInstances.begin(); + instances != scene->meshInstances.end(); ++instances ) + { + uint32_t id = instances->first; + InstanceShape shape = scene->sharedMeshes.at( id ); + DrawEdgeInstances( shape, instances->second.data(), (int)instances->second.size() ); + } + + glDisable( GL_BLEND ); +} + +static Matrix4 LookAt( b3Vec3 eye, b3Vec3 center, b3Vec3 up ) +{ + // Build view transform + b3Vec3 axisZ = b3Normalize( center - eye ); + b3Vec3 axisX = b3Normalize( b3Cross( axisZ, up ) ); + b3Vec3 axisY = b3Cross( axisX, axisZ ); + + // Negate + axisZ = -axisZ; + + Matrix4 out; + out.cx = { axisX.x, axisY.x, axisZ.x, 0.0f }; + out.cy = { axisX.y, axisY.y, axisZ.y, 0.0f }; + out.cz = { axisX.z, axisY.z, axisZ.z, 0.0f }; + out.cw = { -b3Dot( axisX, eye ), -b3Dot( axisY, eye ), -b3Dot( axisZ, eye ), 1.0f }; + + return out; +} + +void DrawScene( Scene* scene, Camera* camera ) +{ + // float temp1[2] = {}; + // glGetFloatv( GL_ALIASED_LINE_WIDTH_RANGE, temp1 ); + + // float temp2[2] = {}; + // glGetFloatv( GL_SMOOTH_LINE_WIDTH_RANGE, temp2 ); + + // CheckOpenGL(); + // glDisable( GL_LINE_SMOOTH ); + + // GLboolean test = glIsEnabled( GL_LINE_SMOOTH ); + // B3_UNUSED( test ); + + // todo wirefame + // glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); + + glDepthFunc( GL_LESS ); + + // Get camera matrices + Matrix4 projection = camera->GetProjectionMatrix(); + Matrix4 view = camera->GetViewMatrix(); + Matrix4 cameraMatrix = camera->GetWorldMatrix(); + + // 1. render shadow map — fit the ortho frustum to the camera's view frustum + // each frame so all shadow-map texels go to what the camera can actually see. + Matrix4 lightView = LookAt( scene->lightPosition, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } ); + + // Scale the shadow region with camera radius so large scenes still get + // covered. Trades off texel density at long camera distances — true large + // scenes want cascaded shadow maps, but a single fitted cascade plus an edge + // fade in the shader keeps the cutoff invisible at this scale. + // + // In third-person the radius is the orbit distance to the pivot, so + // 1.5 * radius is a tight cover of the actual scene of interest and a small + // floor (8) gives great texel density at close orbits. In first-person the + // radius is a stale value — the camera moves m_position directly while + // m_radius keeps whatever it was last set to. Fall back to a wider fixed + // floor there so the shadow frustum still covers the scene the camera can + // see, at the cost of some texel density. + float minShadowDistance = camera->m_thirdPerson ? 8.0f : 60.0f; + const float shadowDistance = b3ClampFloat( 1.5f * camera->m_radius, minShadowDistance, 500.0f ); + float shadowNear = camera->m_nearPlane; + float shadowFar = b3MinFloat( shadowDistance, camera->m_farPlane ); + + b3Vec3 lookDir = -camera->m_forward; // m_forward is the camera-z axis (away from view) + b3Vec3 nearC = camera->m_position + shadowNear * lookDir; + b3Vec3 farC = camera->m_position + shadowFar * lookDir; + float nearH = shadowNear * camera->m_tanY; + float nearW = camera->m_ratio * nearH; + float farH = shadowFar * camera->m_tanY; + float farW = camera->m_ratio * farH; + + b3Vec3 frustumCorners[8] = { + nearC + ( -nearW ) * camera->m_right + ( -nearH ) * camera->m_up, + nearC + (nearW)*camera->m_right + ( -nearH ) * camera->m_up, + nearC + (nearW)*camera->m_right + (nearH)*camera->m_up, + nearC + ( -nearW ) * camera->m_right + (nearH)*camera->m_up, + farC + ( -farW ) * camera->m_right + ( -farH ) * camera->m_up, + farC + (farW)*camera->m_right + ( -farH ) * camera->m_up, + farC + (farW)*camera->m_right + (farH)*camera->m_up, + farC + ( -farW ) * camera->m_right + (farH)*camera->m_up, + }; + + Vector4 c0 = MulMV( lightView, { frustumCorners[0].x, frustumCorners[0].y, frustumCorners[0].z, 1.0f } ); + float minX = c0.x, maxX = c0.x; + float minY = c0.y, maxY = c0.y; + float minZ = c0.z, maxZ = c0.z; + for ( int i = 1; i < 8; ++i ) + { + Vector4 c = MulMV( lightView, { frustumCorners[i].x, frustumCorners[i].y, frustumCorners[i].z, 1.0f } ); + minX = b3MinFloat( minX, c.x ); + maxX = b3MaxFloat( maxX, c.x ); + minY = b3MinFloat( minY, c.y ); + maxY = b3MaxFloat( maxY, c.y ); + minZ = b3MinFloat( minZ, c.z ); + maxZ = b3MaxFloat( maxZ, c.z ); + } + + // Texel-snap the fitted ortho origin so the shadow texel grid stays + // world-locked frame-to-frame. Without this, sub-texel drift as the camera + // moves creates a wandering pattern on lit surfaces that reads as banding. + // Span is held constant within a frame, so each shadow texel maps to exactly + // (texelX, texelY) world-space units perpendicular to the light direction. + float texelX = ( maxX - minX ) / float( shadowWidth ); + float texelY = ( maxY - minY ) / float( shadowHeight ); + minX = floorf( minX / texelX ) * texelX; + minY = floorf( minY / texelY ) * texelY; + maxX = minX + texelX * float( shadowWidth ); + maxY = minY + texelY * float( shadowHeight ); + + // Pull the near plane back so off-camera geometry between the light and the + // view frustum still casts shadows into the visible region. + const float zPad = 50.0f; + float lightNearPlane = -maxZ - zPad; + float lightFarPlane = -minZ; + + Matrix4 lightProjection = MakeOrthographicMatrix( minX, maxX, minY, maxY, lightNearPlane, lightFarPlane ); + Matrix4 lightSpaceMatrix = MulMM( lightProjection, lightView ); + + // World-space size of one shadow texel (light view is rigid, so light-space + // distances equal world-space distances). The deferred shader uses this for + // normal-offset bias; max() keeps the offset conservative when texels are + // non-square. + float worldTexelSize = b3MaxFloat( texelX, texelY ); + + // render scene from light's point of view + glUseProgram( scene->shadowShader ); + SetUniformMatrix4( scene->shadowShader, "lightSpaceMatrix", lightSpaceMatrix ); + CheckOpenGL(); + + glViewport( 0, 0, shadowWidth, shadowHeight ); + glBindFramebuffer( GL_FRAMEBUFFER, scene->depthMapFBO ); + glClear( GL_DEPTH_BUFFER_BIT ); + glActiveTexture( GL_TEXTURE0 ); + + // Back-face cull during the shadow pass: combined with slope-scaled polygon + // offset (applied in DrawMeshes) this eliminates self-shadow acne on solid + // hulls without the gap that front-face culling introduces. + glCullFace( GL_BACK ); + glEnable( GL_CULL_FACE ); + + CheckOpenGL(); + + // DrawObjects( scene, scene->shadowShader, true ); + DrawMeshes( scene, lightSpaceMatrix, Matrix4{}, true ); + + glBindFramebuffer( GL_FRAMEBUFFER, 0 ); + + // reset viewport + glViewport( 0, 0, camera->m_bufferWidth, camera->m_bufferHeight ); + glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); + + // 2. geometry pass: render scene's geometry/color data into geoBuffer + BindGeoBuffer( scene->geoBuffer ); + glUseProgram( scene->geometryShader ); + SetUniformMatrix4( scene->geometryShader, "view", view ); + SetUniformMatrix4( scene->geometryShader, "projection", projection ); + + glCullFace( GL_BACK ); + glEnable( GL_CULL_FACE ); + + // DrawObjects( scene, scene->geometryShader, false ); + DrawMeshes( scene, view, projection, false ); + + glBindFramebuffer( GL_FRAMEBUFFER, 0 ); + + // 3. generate SSAO texture (full resolution — sharp silhouettes) + BindSsaoBuffer( scene->ssaoBuffer ); + glUseProgram( scene->ssaoShader ); + SetUniformMatrix4( scene->ssaoShader, "projection", projection ); + SetUniformFloat( scene->ssaoShader, "radius", scene->ao.radius ); + SetUniformFloat( scene->ssaoShader, "bias", scene->ao.bias ); + SetUniformFloat( scene->ssaoShader, "minScale", scene->ao.minScale ); + { + int loc = glGetUniformLocation( scene->ssaoShader, "noiseScale" ); + glUniform2f( loc, float( camera->m_bufferWidth ) / 4.0f, float( camera->m_bufferHeight ) / 4.0f ); + } + SetSsaoSamples( scene->ssaoBuffer, scene->ssaoShader ); + BindGeoTextures( scene->geoBuffer ); + BindSsaoTextures( scene->ssaoBuffer ); + DrawQuad(); + glBindFramebuffer( GL_FRAMEBUFFER, 0 ); + + CheckOpenGL(); + + // 4. bilateral blur of SSAO — depth-weighted so the blur doesn't leak across silhouettes. + BindSsaoBlurBuffer( scene->ssaoBuffer ); + glUseProgram( scene->ssaoBlurShader ); + BindSsaoColorTexture( scene->ssaoBuffer ); + BindGeoPosition( scene->geoBuffer, 1 ); + DrawQuad(); + glBindFramebuffer( GL_FRAMEBUFFER, 0 ); + + CheckOpenGL(); + + // 5. lighting pass: calculate lighting by iterating over a screen filled quad pixel-by-pixel using the geoBuffer's content. + glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); + glUseProgram( scene->deferredShader ); + BindGeoTextures( scene->geoBuffer ); + BindSsaoBlurTexture( scene->ssaoBuffer ); + + glActiveTexture( GL_TEXTURE4 ); + glBindTexture( GL_TEXTURE_2D, scene->depthMap ); + + SetUniformBool( scene->deferredShader, "useSSAO", scene->useSSAO ); + SetUniformBool( scene->deferredShader, "useShadow", scene->useShadow ); + SetUniformBool( scene->deferredShader, "useGrid", scene->useGrid ); + SetUniformFloat( scene->deferredShader, "aoPower", scene->ao.power ); + SetUniformFloat( scene->deferredShader, "aoDirect", scene->ao.direct ); + SetUniformBool( scene->deferredShader, "aoOnly", scene->ao.aoOnly ); + + // Sun direction in world space (from scene toward sun) — shared with the shadow projection, + // which already uses scene->lightPosition as the light source. + b3Vec3 sunDirWorld = b3Normalize( scene->lightPosition ); + SetUniformVec3( scene->deferredShader, "sunDirWorld", sunDirWorld ); + + // View-ray reconstruction parameters for the sky/fog path. + SetUniformFloat( scene->deferredShader, "tanHalfFovY", camera->m_tanY ); + SetUniformFloat( scene->deferredShader, "aspectRatio", camera->m_ratio ); + + SetUniformMatrix4( scene->deferredShader, "lightSpaceMatrix", lightSpaceMatrix ); + SetUniformMatrix4( scene->deferredShader, "cameraMatrix", cameraMatrix ); + SetUniformFloat( scene->deferredShader, "worldTexelSize", worldTexelSize ); + SetUniformFloat( scene->deferredShader, "lightZRange", lightFarPlane - lightNearPlane ); + + // finally render quad + DrawQuad(); + + CheckOpenGL(); + + // 5.5. Copy geometry depth to the default framebuffer using a depth-only draw pass. + // This avoids glBlitFramebuffer which is very slow on Apple Silicon. + glUseProgram( scene->depthCopyShader ); + BindGeoDepthTexture( scene->geoBuffer, 0 ); + glColorMask( GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE ); + glDepthFunc( GL_ALWAYS ); + glDepthMask( GL_TRUE ); + DrawQuad(); + glColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE ); + glDepthFunc( GL_LESS ); + + CheckOpenGL(); + + // 6. forward render lights on top of scene + // glUseProgram( scene->forwardShader ); + // SetUniformMatrix4( scene->forwardShader, "projection", projection ); + // SetUniformMatrix4( scene->forwardShader, "view", view ); + + // b3Transform transform; + // transform.p = scene->lightPosition; + // transform.q = b3Quat_identity; + // Matrix4 m = MakeMatrix4( transform, 0.25f ); + // SetUniformMatrix4( scene->forwardShader, "model", m ); + // SetUniformVec3( scene->forwardShader, "color", { 1.0f, 1.0f, 1.0f } ); + // DrawCube( scene, transform, b3_colorWhite, view, projection ); + + // Draw mesh edges + DrawLines( scene, view, projection ); + + // Draw transparent hulls + DrawTransparentShapes( scene, view, projection, b3Normalize( scene->lightPosition ), camera->GetPosition() ); + + // 7. Debug draw lines and points + FlushLines( scene->lineDraw, camera ); + FlushPoints( scene->pointDraw, camera ); + + // 8. Clear instances + // scene->uniqueShapes.clear(); + scene->sphereInstances.clear(); + scene->openHemisphereInstances.clear(); + scene->openCylinderInstances.clear(); + + // Clear instances + for ( std::unordered_map>::iterator instance = scene->heightFieldInstances.begin(); + instance != scene->heightFieldInstances.end(); ++instance ) + { + instance->second.clear(); + } + + for ( std::unordered_map>::iterator instance = scene->hullInstances.begin(); + instance != scene->hullInstances.end(); ++instance ) + { + instance->second.clear(); + } + + for ( std::unordered_map>::iterator instance = scene->meshInstances.begin(); + instance != scene->meshInstances.end(); ++instance ) + { + instance->second.clear(); + } + + scene->transparentSphereInstances.clear(); + scene->transparentOpenHemisphereInstances.clear(); + scene->transparentOpenCylinderInstances.clear(); + + for ( std::unordered_map>::iterator hulls = scene->transparentHullInstances.begin(); + hulls != scene->transparentHullInstances.end(); ++hulls ) + { + hulls->second.clear(); + } +} + +void DrawDebugCube( Scene* scene, b3Transform transform, RGBAf color ) +{ + int index = (int)scene->debugCubes.size(); + scene->debugCubes[index] = { transform, color }; +} + +void EnableShadows( Scene* scene, bool useShadows ) +{ + scene->useShadow = useShadows; +} + +bool AreShadowsEnabled( Scene* scene ) +{ + return scene->useShadow; +} + +void EnableSSAO( Scene* scene, bool enable ) +{ + scene->useSSAO = enable; +} + +bool IsSSAOEnabled( Scene* scene ) +{ + return scene->useSSAO; +} + +void EnableGrid( Scene* scene, bool enable ) +{ + scene->useGrid = enable; +} + +bool IsGridEnabled( Scene* scene ) +{ + return scene->useGrid; +} + +SceneAOSettings* GetAOSettings( Scene* scene ) +{ + return &scene->ao; +} + +void DrawPoint( Scene* scene, b3Vec3 point, float size, b3HexColor color ) +{ + AddPoint( scene->pointDraw, point, size, color ); +} + +void DrawLine( Scene* scene, b3Vec3 point1, b3Vec3 point2, b3HexColor color ) +{ + AddLine( scene->lineDraw, point1, point2, color ); +} + +void DrawPlane( Scene* scene, b3Vec3 normal, b3Vec3 point, b3HexColor color ) +{ + b3Vec3 perp1 = b3Perp( normal ); + b3Vec3 perp2 = b3Cross( perp1, normal ); + b3Vec3 p = point; + float a = 1.0f; + b3Vec3 p1 = p + a * perp1 + a * perp2; + b3Vec3 p2 = p - a * perp1 + a * perp2; + b3Vec3 p3 = p - a * perp1 - a * perp2; + b3Vec3 p4 = p + a * perp1 - a * perp2; + + AddLine( scene->lineDraw, p1, p2, color ); + AddLine( scene->lineDraw, p2, p3, color ); + AddLine( scene->lineDraw, p3, p4, color ); + AddLine( scene->lineDraw, p4, p1, color ); + AddLine( scene->lineDraw, p, p + 0.5f * normal, color ); + AddPoint( scene->pointDraw, p, 10.0f, color ); +} + +void DrawArrow( Scene* scene, b3Vec3 point1, b3Vec3 point2, float size, b3HexColor color ) +{ + AddLine( scene->lineDraw, point1, point2, color ); + b3Vec3 axis = b3Normalize( point2 - point1 ); + b3Vec3 perp = b3Perp( axis ); + AddLine( scene->lineDraw, point2, point2 - size * axis + size * perp, color ); + AddLine( scene->lineDraw, point2, point2 - size * axis - size * perp, color ); +} + +void DrawBounds( Scene* scene, b3AABB bounds, float extension, b3HexColor color ) +{ + LineDraw* draw = scene->lineDraw; + + b3Vec3 extents = b3AABB_Extents( bounds ); + b3Vec3 center = b3AABB_Center( bounds ); + float hx = extents.x + extension; + float hy = extents.y + extension; + float hz = extents.z + extension; + + b3Vec3 p1 = b3Vec3{ -hx, -hy, hz } + center; + b3Vec3 p2 = b3Vec3{ -hx, hy, hz } + center; + b3Vec3 p3 = b3Vec3{ -hx, hy, -hz } + center; + b3Vec3 p4 = b3Vec3{ -hx, -hy, -hz } + center; + + b3Vec3 p5 = b3Vec3{ hx, -hy, hz } + center; + b3Vec3 p6 = b3Vec3{ hx, hy, hz } + center; + b3Vec3 p7 = b3Vec3{ hx, hy, -hz } + center; + b3Vec3 p8 = b3Vec3{ hx, -hy, -hz } + center; + + // negative x loop + AddLine( draw, p1, p2, color ); + AddLine( draw, p2, p3, color ); + AddLine( draw, p3, p4, color ); + AddLine( draw, p4, p1, color ); + + // positive x loop + AddLine( draw, p5, p6, color ); + AddLine( draw, p6, p7, color ); + AddLine( draw, p7, p8, color ); + AddLine( draw, p8, p5, color ); + + // connect loops + AddLine( draw, p1, p5, color ); + AddLine( draw, p2, p6, color ); + AddLine( draw, p3, p7, color ); + AddLine( draw, p4, p8, color ); +} + +void DrawBox( Scene* scene, b3Vec3 extents, b3Transform transform, b3HexColor color ) +{ + LineDraw* draw = scene->lineDraw; + + float hx = extents.x; + float hy = extents.y; + float hz = extents.z; + + b3Vec3 p1 = b3TransformPoint( transform, { -hx, -hy, hz } ); + b3Vec3 p2 = b3TransformPoint( transform, { -hx, hy, hz } ); + b3Vec3 p3 = b3TransformPoint( transform, { -hx, hy, -hz } ); + b3Vec3 p4 = b3TransformPoint( transform, { -hx, -hy, -hz } ); + + b3Vec3 p5 = b3TransformPoint( transform, { hx, -hy, hz } ); + b3Vec3 p6 = b3TransformPoint( transform, { hx, hy, hz } ); + b3Vec3 p7 = b3TransformPoint( transform, { hx, hy, -hz } ); + b3Vec3 p8 = b3TransformPoint( transform, { hx, -hy, -hz } ); + + // negative x loop + AddLine( draw, p1, p2, color ); + AddLine( draw, p2, p3, color ); + AddLine( draw, p3, p4, color ); + AddLine( draw, p4, p1, color ); + + // positive x loop + AddLine( draw, p5, p6, color ); + AddLine( draw, p6, p7, color ); + AddLine( draw, p7, p8, color ); + AddLine( draw, p8, p5, color ); + + // connect loops + AddLine( draw, p1, p5, color ); + AddLine( draw, p2, p6, color ); + AddLine( draw, p3, p7, color ); + AddLine( draw, p4, p8, color ); +} + +void DrawFace( Scene* scene, b3Vec3 vertex1, b3Vec3 vertex2, b3Vec3 vertex3, b3HexColor color ) +{ + LineDraw* draw = scene->lineDraw; + + AddLine( draw, vertex1, vertex2, color ); + AddLine( draw, vertex2, vertex3, color ); + AddLine( draw, vertex3, vertex1, color ); +} diff --git a/samples/scene.h b/samples/scene.h new file mode 100644 index 0000000..837bade --- /dev/null +++ b/samples/scene.h @@ -0,0 +1,147 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "utility.h" + +#include "box3d/math_functions.h" + +struct Camera; +struct b3DebugShape; +struct Scene; +struct UniqueMesh; + +enum struct DebugShapeType +{ + capsule, + compound, + hull, + heightField, + mesh, + sphere, +}; + +struct DebugSphere +{ + b3Vec3 center; + float radius; +}; + +struct DebugCapsule +{ + b3Vec3 center1, center2; + float radius; +}; + +struct DebugHeightField +{ + uint32_t id; +}; + +struct DebugHull +{ + b3Transform transform; + uint32_t id; +}; + +struct DebugMesh +{ + b3Transform transform; + b3Vec3 scale; + uint32_t id; +}; + +struct DebugCompound +{ + DebugCapsule* capsules; + int capsuleCount; + + DebugHull* hulls; + int hullCount; + + DebugMesh* meshes; + int meshCount; + + DebugSphere* spheres; + int sphereCount; +}; + +struct DebugShape +{ + DebugShapeType type; + b3BodyType bodyType; + union + { + DebugCapsule capsule; + DebugCompound compound; + DebugHeightField heightField; + DebugHull hull; + DebugMesh mesh; + DebugSphere sphere; + }; +}; + +Scene* CreateScene( const Camera* camera, Arena arena ); +void DestroyScene( Scene* scene ); + +// Register a hull and get an id to render it later +uint32_t CreateInstanceHull( Scene* scene, const b3Hull* hull, Arena arena ); + +// Register a mesh and get an id to render it later +uint32_t CreateInstanceMesh( Scene* scene, const b3MeshData* meshData, Arena arena ); + +// Register a height field and get an id to render it later +uint32_t CreateInstanceHeightField( Scene* scene, const b3HeightField* heightField, Arena arena ); + +// This should be called when a sample is destroyed to avoid leaking instances +void DestroySharedMeshes( Scene* scene ); + +void ResizeScene( Scene* scene, const Camera* camera ); + +// UniqueMesh CreateUniqueMesh( const b3Vec3* vertexPositions, const b3Vec3* vertexNormals, int triangleCount, +// const int* triangleIndices, const Edge* edges, int edgeCount, const int* materials, +// Arena arena ); +// void DestroyUniqueMesh( UniqueMesh* shape ); + +void DrawDebugShape( Scene* scene, DebugShape* debugShape, b3Transform transform, b3HexColor color, float alpha ); + +void DrawScene( Scene* scene, Camera* camera ); + +void DrawCube( Scene* scene, b3Transform transform, b3HexColor color, const Matrix4& view, const Matrix4& projection ); + +void DrawDebugCube( Scene* scene, b3Transform transform, b3HexColor color ); + +struct SceneAOSettings +{ + float radius; + float bias; + float minScale; + float power; + float direct; + bool aoOnly; +}; + +// Mutable view of the scene's SSAO parameters. Pointer is valid for the lifetime of the scene. +SceneAOSettings* GetAOSettings( Scene* scene ); + +void EnableShadows( Scene* scene, bool useShadows ); +bool AreShadowsEnabled( Scene* scene ); + +void EnableSSAO( Scene* scene, bool enable ); +bool IsSSAOEnabled( Scene* scene ); + +// World-space ground grid drawn on near-horizontal upward faces. Useful on +// flat-box ground; should be disabled for samples whose ground is a mesh +// (the mesh's triangle wireframe already provides the grid signal). +void EnableGrid( Scene* scene, bool enable ); +bool IsGridEnabled( Scene* scene ); + +void DrawPoint( Scene* scene, b3Vec3 point, float size, b3HexColor color ); +void DrawLine( Scene* scene, b3Vec3 point1, b3Vec3 point2, b3HexColor color ); +void DrawPlane( Scene* scene, b3Vec3 normal, b3Vec3 point, b3HexColor color ); +void DrawArrow( Scene* scene, b3Vec3 point1, b3Vec3 point2, float size, b3HexColor color ); + +void DrawBounds( Scene* scene, b3AABB bounds, float extension, b3HexColor color ); +void DrawBox( Scene* scene, b3Vec3 extents, b3Transform transform, b3HexColor color ); +void DrawFace( Scene* scene, b3Vec3 vertex1, b3Vec3 vertex2, b3Vec3 vertex3, b3HexColor color ); diff --git a/samples/shader.cpp b/samples/shader.cpp new file mode 100644 index 0000000..c904fd1 --- /dev/null +++ b/samples/shader.cpp @@ -0,0 +1,465 @@ +// 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 "shader.h" + +#include +#include +#include +#include +#include +#include + +#include + +void CheckOpenGL() +{ + GLenum errCode = glGetError(); + if ( errCode != GL_NO_ERROR ) + { + fprintf( stderr, "OpenGL error = %d\n", errCode ); + assert( false ); + } +} + +void DumpGLInfo( bool dumpExtensions ) +{ + const GLubyte* renderer = glGetString( GL_RENDERER ); + const GLubyte* vendor = glGetString( GL_VENDOR ); + const GLubyte* version = glGetString( GL_VERSION ); + const GLubyte* glslVersion = 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" ); + + if ( dumpExtensions ) + { + int nExtensions; + glGetIntegerv( GL_NUM_EXTENSIONS, &nExtensions ); + for ( int i = 0; i < nExtensions; i++ ) + { + printf( "%s\n", glGetStringi( GL_EXTENSIONS, i ) ); + } + } +} + +static void PrintLog( uint32_t object ) +{ + int length = 0; + if ( glIsShader( object ) ) + { + glGetShaderiv( object, GL_INFO_LOG_LENGTH, &length ); + } + else if ( glIsProgram( object ) ) + { + glGetProgramiv( object, GL_INFO_LOG_LENGTH, &length ); + } + else + { + fprintf( stderr, "printlog: Not a shader or a program\n" ); + return; + } + + char* log = static_cast( malloc( length * sizeof( char ) ) ); + + if ( glIsShader( object ) ) + { + glGetShaderInfoLog( object, length, nullptr, log ); + } + else if ( glIsProgram( object ) ) + { + glGetProgramInfoLog( object, length, nullptr, log ); + } + + fprintf( stderr, "%s", log ); + free( log ); +} + +static uint32_t CreateShaderFromString( const char* source, GLenum type ) +{ + uint32_t shader = glCreateShader( type ); + const char* sources[] = { source }; + + glShaderSource( shader, 1, sources, nullptr ); + 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 ); + PrintLog( shader ); + } + + return shader; +} + +static bool ReadFile( const char* filename, std::string& out ) +{ + FILE* file = fopen( filename, "rb" ); + if ( file == nullptr ) + { + return false; + } + + fseek( file, 0, SEEK_END ); + long size = ftell( file ); + fseek( file, 0, SEEK_SET ); + + out.resize( (size_t)size ); + if ( size > 0 ) + { + fread( &out[0], 1, (size_t)size, file ); + } + fclose( file ); + return true; +} + +static std::string DirectoryOf( const char* path ) +{ + const char* lastSep = nullptr; + for ( const char* p = path; *p; ++p ) + { + if ( *p == '/' || *p == '\\' ) + { + lastSep = p; + } + } + return lastSep ? std::string( path, lastSep + 1 ) : std::string(); +} + +// Substitutes lines of the form `#include "name"` with the contents of that +// file (resolved relative to `baseDir`). Recursive but not cyclic-safe — keep +// the include graph a DAG. Emits `#line` directives so compile errors keep +// readable line numbers in both the parent and the included file. +static bool ResolveIncludes( const std::string& source, const std::string& baseDir, std::string& out ) +{ + out.reserve( out.size() + source.size() * 2 ); + + int lineNo = 1; + size_t i = 0; + while ( i < source.size() ) + { + size_t lineStart = i; + size_t lineEnd = source.find( '\n', i ); + if ( lineEnd == std::string::npos ) + { + lineEnd = source.size(); + } + + size_t t = lineStart; + while ( t < lineEnd && ( source[t] == ' ' || source[t] == '\t' ) ) + { + t++; + } + + bool isInclude = false; + std::string includeName; + if ( lineEnd >= t + 9 && source.compare( t, 8, "#include" ) == 0 && + ( source[t + 8] == ' ' || source[t + 8] == '\t' ) ) + { + size_t q1 = source.find( '"', t + 8 ); + size_t q2 = ( q1 != std::string::npos && q1 < lineEnd ) ? source.find( '"', q1 + 1 ) : std::string::npos; + if ( q1 != std::string::npos && q2 != std::string::npos && q2 < lineEnd ) + { + isInclude = true; + includeName = source.substr( q1 + 1, q2 - q1 - 1 ); + } + } + + if ( isInclude ) + { + std::string includePath = baseDir + includeName; + std::string includedRaw; + if ( !ReadFile( includePath.c_str(), includedRaw ) ) + { + fprintf( stderr, "Cannot open include '%s'\n", includePath.c_str() ); + return false; + } + + char hdr[64]; + snprintf( hdr, sizeof( hdr ), "#line 1\n" ); + out += hdr; + + if ( !ResolveIncludes( includedRaw, DirectoryOf( includePath.c_str() ), out ) ) + { + return false; + } + + if ( !out.empty() && out.back() != '\n' ) + { + out += '\n'; + } + + snprintf( hdr, sizeof( hdr ), "#line %d\n", lineNo + 1 ); + out += hdr; + } + else + { + out.append( source, lineStart, lineEnd - lineStart ); + out += '\n'; + } + + i = ( lineEnd < source.size() ) ? lineEnd + 1 : lineEnd; + lineNo++; + } + return true; +} + +static uint32_t CreateShaderFromFile( const char* filename, GLenum type ) +{ + std::string raw; + if ( !ReadFile( filename, raw ) ) + { + fprintf( stderr, "Error opening %s\n", filename ); + return 0; + } + + std::string source; + if ( !ResolveIncludes( raw, DirectoryOf( filename ), source ) ) + { + fprintf( stderr, "Error resolving includes in %s\n", filename ); + return 0; + } + + uint32_t shader = glCreateShader( type ); + const char* sources[] = { source.c_str() }; + + glShaderSource( shader, 1, sources, nullptr ); + glCompileShader( shader ); + + int success = GL_FALSE; + glGetShaderiv( shader, GL_COMPILE_STATUS, &success ); + + if ( success == GL_FALSE ) + { + fprintf( stderr, "Error compiling shader of type %d in %s!\n", type, filename ); + PrintLog( shader ); + } + + return shader; +} + +uint32_t CreateProgramFromFiles( const char* vertexPath, const char* fragmentPath ) +{ + uint32_t vertex = CreateShaderFromFile( vertexPath, GL_VERTEX_SHADER ); + if ( vertex == 0 ) + { + return 0; + } + + uint32_t fragment = CreateShaderFromFile( fragmentPath, GL_FRAGMENT_SHADER ); + if ( fragment == 0 ) + { + return 0; + } + + uint32_t program = glCreateProgram(); + glAttachShader( program, vertex ); + glAttachShader( program, fragment ); + + glLinkProgram( program ); + + int success = GL_FALSE; + glGetProgramiv( program, GL_LINK_STATUS, &success ); + if ( success == GL_FALSE ) + { + fprintf( stderr, "glLinkProgram:" ); + PrintLog( program ); + return 0; + } + + glDeleteShader( vertex ); + glDeleteShader( fragment ); + + return program; +} + +uint32_t CreateProgramFromStrings( const char* vs, const char* fs ) +{ + uint32_t vertex = CreateShaderFromString( vs, GL_VERTEX_SHADER ); + if ( vertex == 0 ) + { + return 0; + } + + uint32_t fragment = CreateShaderFromString( fs, GL_FRAGMENT_SHADER ); + if ( fragment == 0 ) + { + return 0; + } + + uint32_t programId = glCreateProgram(); + glAttachShader( programId, vertex ); + glAttachShader( programId, fragment ); + + glLinkProgram( programId ); + + int success = GL_FALSE; + glGetProgramiv( programId, GL_LINK_STATUS, &success ); + if ( success == GL_FALSE ) + { + fprintf( stderr, "glLinkProgram:" ); + PrintLog( programId ); + return 0; + } + + glDeleteShader( vertex ); + glDeleteShader( fragment ); + + return programId; +} + +void DestroyShader( uint32_t programId ) +{ + glDeleteProgram( programId ); +} + +int GetUniformLocation( uint32_t programId, const char* name ) +{ + return glGetUniformLocation( programId, name ); +} + +void SetUniformBool( int location, bool value ) +{ + glUniform1i( location, (int)value ); +} + +void SetUniformInt( int location, int value ) +{ + glUniform1i( location, value ); +} + +void SetUniformFloat( int location, float value ) +{ + glUniform1f( location, value ); +} + +void SetUniformVec3( int location, b3Vec3 value ) +{ + glUniform3fv( location, 1, &value.x ); +} + +void SetUniformVec3( int location, float x, float y, float z ) +{ + glUniform3f( location, x, y, z ); +} + +void SetUniformVec4( int location, Vector4 value ) +{ + glUniform4fv( location, 1, &value.x ); +} + +void SetUniformColor( int location, RGBAf value ) +{ + glUniform4fv( location, 1, &value.r ); +} + +void SetUniformVec4( int location, float x, float y, float z, float w ) +{ + glUniform4f( location, x, y, z, w ); +} + +void SetUniformMatrix4( int location, const Matrix4& mat ) +{ + glUniformMatrix4fv( location, 1, GL_FALSE, &mat.cx.x ); +} + +void SetUniformBool( uint32_t programId, const char* name, bool value ) +{ + int location = glGetUniformLocation( programId, name ); + if ( location != -1 ) + { + glUniform1i( location, (int)value ); + } + else + { + location += 0; + } +} + +void SetUniformInt( uint32_t programId, const char* name, int value ) +{ + int location = glGetUniformLocation( programId, name ); + if ( location != -1 ) + { + glUniform1i( location, value ); + } +} + +void SetUniformFloat( uint32_t programId, const char* name, float value ) +{ + int location = glGetUniformLocation( programId, name ); + if ( location != -1 ) + { + glUniform1f( location, value ); + } +} + +void SetUniformVec3( uint32_t programId, const char* name, b3Vec3 value ) +{ + int location = glGetUniformLocation( programId, name ); + if ( location != -1 ) + { + glUniform3fv( location, 1, &value.x ); + } +} + +void SetUniformVec3( uint32_t programId, const char* name, float x, float y, float z ) +{ + int location = glGetUniformLocation( programId, name ); + if ( location != -1 ) + { + glUniform3f( location, x, y, z ); + } +} + +void SetUniformVec4( uint32_t programId, const char* name, Vector4 value ) +{ + int location = glGetUniformLocation( programId, name ); + if ( location != -1 ) + { + glUniform4fv( location, 1, &value.x ); + } +} + +void SetUniformVec4( uint32_t programId, const char* name, float x, float y, float z, float w ) +{ + int location = glGetUniformLocation( programId, name ); + if ( location != -1 ) + { + glUniform4f( location, x, y, z, w ); + } +} + +void SetUniformColor( uint32_t programId, const char* name, RGBAf value ) +{ + int location = glGetUniformLocation( programId, name ); + if ( location != -1 ) + { + glUniform4fv( location, 1, &value.r ); + } +} + +void SetUniformMatrix4( uint32_t programId, const char* name, const Matrix4& mat ) +{ + int location = glGetUniformLocation( programId, name ); + if ( location != -1 ) + { + glUniformMatrix4fv( location, 1, GL_FALSE, &mat.cx.x ); + } +} diff --git a/samples/shader.h b/samples/shader.h new file mode 100644 index 0000000..c180333 --- /dev/null +++ b/samples/shader.h @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "utility.h" + +#include "box3d/types.h" + +uint32_t CreateProgramFromFiles( const char* vertexPath, const char* fragmentPath ); +uint32_t CreateProgramFromStrings( const char* vs, const char* fs ); + +void DestroyShader( uint32_t programId ); + +// todo these are low value wrappers +int GetUniformLocation( uint32_t programId, const char* name ); + +void SetUniformBool( int location, bool value ); +void SetUniformInt( int location, int value ); +void SetUniformFloat( int location, float value ); +void SetUniformVec3( int location, b3Vec3 value ); +void SetUniformVec3( int location, float x, float y, float z ); +void SetUniformVec4( int location, Vector4 value ); +void SetUniformVec4( int location, float x, float y, float z, float w ); +void SetUniformColor( int location, RGBAf value ); +void SetUniformMatrix4( int location, const Matrix4& mat ); + +void SetUniformBool( uint32_t programId, const char* name, bool value ); +void SetUniformInt( uint32_t programId, const char* name, int value ); +void SetUniformFloat( uint32_t programId, const char* name, float value ); +void SetUniformVec3( uint32_t programId, const char* name, b3Vec3 value ); +void SetUniformVec3( uint32_t programId, const char* name, float x, float y, float z ); +void SetUniformVec4( uint32_t programId, const char* name, Vector4 value ); +void SetUniformVec4( uint32_t programId, const char* name, float x, float y, float z, float w ); +void SetUniformColor( uint32_t programId, const char* name, RGBAf value ); +void SetUniformMatrix4( uint32_t programId, const char* name, const Matrix4& mat ); + +void CheckOpenGL(); +void DumpGLInfo( bool dumpExtensions ); diff --git a/samples/ssao_buffer.cpp b/samples/ssao_buffer.cpp new file mode 100644 index 0000000..1ff1516 --- /dev/null +++ b/samples/ssao_buffer.cpp @@ -0,0 +1,163 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "ssao_buffer.h" + +#include "box3d/math_functions.h" +#include "shader.h" + +#include +#include +#include +#include +#include + +#include "geo_buffer.h" + +struct SsaoBuffer +{ + int32_t width, height; + uint32_t frameBufferId; + uint32_t blurFrameBufferId; + uint32_t colorBufferId; + uint32_t blurColorBufferId; + + b3Vec3 ssaoKernel[32]; + uint32_t noiseTexture; +}; + +SsaoBuffer* CreateSsaoBuffer(int32_t width, int32_t height) +{ + SsaoBuffer* buffer = (SsaoBuffer*)malloc(sizeof(SsaoBuffer)); + buffer->width = width; + buffer->height = height; + + // frame buffer + glGenFramebuffers(1, &buffer->frameBufferId); + glBindFramebuffer(GL_FRAMEBUFFER, buffer->frameBufferId); + + // color buffer + glGenTextures(1, &buffer->colorBufferId); + glBindTexture(GL_TEXTURE_2D, buffer->colorBufferId); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, width, height, 0, GL_RED, GL_FLOAT, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, buffer->colorBufferId, 0); + + if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) + { + fprintf(stderr, "SSAO Framebuffer not complete!\n"); + free(buffer); + return nullptr; + } + + // blur frame buffer + glGenFramebuffers(1, &buffer->blurFrameBufferId); + glBindFramebuffer(GL_FRAMEBUFFER, buffer->blurFrameBufferId); + + // blur color buffer + glGenTextures(1, &buffer->blurColorBufferId); + glBindTexture(GL_TEXTURE_2D, buffer->blurColorBufferId); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, width, height, 0, GL_RED, GL_FLOAT, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, buffer->blurColorBufferId, 0); + if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) + { + fprintf(stderr, "SSAO Blur Framebuffer not complete!\n"); + free(buffer); + return nullptr; + } + + // unbind frame buffer + glBindFramebuffer(GL_FRAMEBUFFER, 0); + + // generate sample kernel + std::uniform_real_distribution randomFloats(0.0f, 1.0f); // generates random floats between 0.0 and 1.0 + std::default_random_engine generator; + + for (uint32_t i = 0; i < 32; ++i) + { + b3Vec3 sample{randomFloats(generator) * 2.0f - 1.0f, randomFloats(generator) * 2.0f - 1.0f, randomFloats(generator)}; + sample = b3Normalize(sample); + sample = randomFloats(generator) * sample; + float scale = float(i) / 32.0f; + + // scale samples s.t. they're more aligned to center of kernel + scale = b3LerpFloat(0.1f, 1.0f, scale * scale); + sample = scale * sample; + buffer->ssaoKernel[i] = sample; + } + + // random sample kernel tangent vectors stuffed into a texture + b3Vec3 ssaoNoise[16]; + for (b3Vec3& noise : ssaoNoise) + { + // rotate around z-axis (in tangent space) + noise = {randomFloats(generator) * 2.0f - 1.0f, randomFloats(generator) * 2.0f - 1.0f, 0.0f}; + } + + glGenTextures(1, &buffer->noiseTexture); + glBindTexture(GL_TEXTURE_2D, buffer->noiseTexture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, 4, 4, 0, GL_RGB, GL_FLOAT, &ssaoNoise[0]); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + + return buffer; +} + +void BindSsaoBuffer(SsaoBuffer* buffer) +{ + glBindFramebuffer(GL_FRAMEBUFFER, buffer->frameBufferId); + glClear(GL_COLOR_BUFFER_BIT); +} + +void SetSsaoSamples(SsaoBuffer* buffer, uint32_t ssaoShader) +{ + // Send kernel + rotation + for (uint32_t i = 0; i < 32; ++i) + { + char sampleName[32]; + snprintf(sampleName, 32, "samples[%d]", i); + SetUniformVec3(ssaoShader, sampleName, buffer->ssaoKernel[i]); + } +} + +void BindSsaoTextures(SsaoBuffer* buffer) +{ + glActiveTexture(GL_TEXTURE2); + glBindTexture(GL_TEXTURE_2D, buffer->noiseTexture); +} + +void BindSsaoBlurBuffer(SsaoBuffer* buffer) +{ + glBindFramebuffer(GL_FRAMEBUFFER, buffer->blurFrameBufferId); + glClear(GL_COLOR_BUFFER_BIT); +} + +void BindSsaoColorTexture(SsaoBuffer* buffer) +{ + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, buffer->colorBufferId); +} + +void BindSsaoBlurTexture(SsaoBuffer* buffer) +{ + glActiveTexture(GL_TEXTURE3); + glBindTexture(GL_TEXTURE_2D, buffer->blurColorBufferId); +} + +void DestroySsaoBuffer(SsaoBuffer* buffer) +{ + glDeleteFramebuffers(1, &buffer->frameBufferId); + glDeleteFramebuffers(1, &buffer->blurFrameBufferId); + + glDeleteTextures(1, &buffer->colorBufferId); + glDeleteTextures(1, &buffer->blurColorBufferId); + + glDeleteTextures(1, &buffer->noiseTexture); + + free(buffer); +} diff --git a/samples/ssao_buffer.h b/samples/ssao_buffer.h new file mode 100644 index 0000000..e9c1d11 --- /dev/null +++ b/samples/ssao_buffer.h @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +struct SsaoBuffer; +struct GeoBuffer; + +SsaoBuffer* CreateSsaoBuffer(int32_t width, int32_t height); + +void BindSsaoBuffer(SsaoBuffer* buffer); +void SetSsaoSamples(SsaoBuffer* buffer, uint32_t ssaoShader); +void BindSsaoTextures(SsaoBuffer* buffer); + +void BindSsaoBlurBuffer(SsaoBuffer* buffer); +void BindSsaoColorTexture(SsaoBuffer* buffer); +void BindSsaoBlurTexture(SsaoBuffer* buffer); + +void DestroySsaoBuffer(SsaoBuffer* buffer); diff --git a/samples/stb_image_write.h b/samples/stb_image_write.h new file mode 100644 index 0000000..151eaca --- /dev/null +++ b/samples/stb_image_write.h @@ -0,0 +1,1724 @@ +/* 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. +------------------------------------------------------------------------------ +*/ diff --git a/samples/stb_truetype.h b/samples/stb_truetype.h new file mode 100644 index 0000000..90a5c2e --- /dev/null +++ b/samples/stb_truetype.h @@ -0,0 +1,5079 @@ +// 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. +------------------------------------------------------------------------------ +*/ diff --git a/samples/tiny_obj_loader.h b/samples/tiny_obj_loader.h new file mode 100644 index 0000000..942b149 --- /dev/null +++ b/samples/tiny_obj_loader.h @@ -0,0 +1,3499 @@ +/* +The MIT License (MIT) + +Copyright (c) 2012-Present, Syoyo Fujita and many contributors. + +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. +*/ + +// +// version 2.0.0 : Add new object oriented API. 1.x API is still provided. +// * Add python binding. +// * Support line primitive. +// * Support points primitive. +// * Support multiple search path for .mtl(v1 API). +// * Support vertex skinning weight `vw`(as an tinyobj +// extension). Note that this differs vertex weight([w] +// component in `v` line) +// * Support escaped whitespece in mtllib +// * Add robust triangulation using Mapbox +// earcut(TINYOBJLOADER_USE_MAPBOX_EARCUT). +// version 1.4.0 : Modifed ParseTextureNameAndOption API +// version 1.3.1 : Make ParseTextureNameAndOption API public +// version 1.3.0 : Separate warning and error message(breaking API of LoadObj) +// version 1.2.3 : Added color space extension('-colorspace') to tex opts. +// version 1.2.2 : Parse multiple group names. +// version 1.2.1 : Added initial support for line('l') primitive(PR #178) +// version 1.2.0 : Hardened implementation(#175) +// version 1.1.1 : Support smoothing groups(#162) +// version 1.1.0 : Support parsing vertex color(#144) +// version 1.0.8 : Fix parsing `g` tag just after `usemtl`(#138) +// version 1.0.7 : Support multiple tex options(#126) +// version 1.0.6 : Add TINYOBJLOADER_USE_DOUBLE option(#124) +// version 1.0.5 : Ignore `Tr` when `d` exists in MTL(#43) +// version 1.0.4 : Support multiple filenames for 'mtllib'(#112) +// version 1.0.3 : Support parsing texture options(#85) +// version 1.0.2 : Improve parsing speed by about a factor of 2 for large +// files(#105) +// version 1.0.1 : Fixes a shape is lost if obj ends with a 'usemtl'(#104) +// version 1.0.0 : Change data structure. Change license from BSD to MIT. +// + +// +// Use this in *one* .cc +// #define TINYOBJLOADER_IMPLEMENTATION +// #include "tiny_obj_loader.h" +// + +#ifndef TINY_OBJ_LOADER_H_ +#define TINY_OBJ_LOADER_H_ + +#include +#include +#include + +namespace tinyobj { + +// TODO(syoyo): Better C++11 detection for older compiler +#if __cplusplus > 199711L +#define TINYOBJ_OVERRIDE override +#else +#define TINYOBJ_OVERRIDE +#endif + +#ifdef __clang__ +#pragma clang diagnostic push +#if __has_warning("-Wzero-as-null-pointer-constant") +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" +#endif + +#pragma clang diagnostic ignored "-Wpadded" + +#endif + +// https://en.wikipedia.org/wiki/Wavefront_.obj_file says ... +// +// -blendu on | off # set horizontal texture blending +// (default on) +// -blendv on | off # set vertical texture blending +// (default on) +// -boost real_value # boost mip-map sharpness +// -mm base_value gain_value # modify texture map values (default +// 0 1) +// # base_value = brightness, +// gain_value = contrast +// -o u [v [w]] # Origin offset (default +// 0 0 0) +// -s u [v [w]] # Scale (default +// 1 1 1) +// -t u [v [w]] # Turbulence (default +// 0 0 0) +// -texres resolution # texture resolution to create +// -clamp on | off # only render texels in the clamped +// 0-1 range (default off) +// # When unclamped, textures are +// repeated across a surface, +// # when clamped, only texels which +// fall within the 0-1 +// # range are rendered. +// -bm mult_value # bump multiplier (for bump maps +// only) +// +// -imfchan r | g | b | m | l | z # specifies which channel of the file +// is used to +// # create a scalar or bump texture. +// r:red, g:green, +// # b:blue, m:matte, l:luminance, +// z:z-depth.. +// # (the default for bump is 'l' and +// for decal is 'm') +// bump -imfchan r bumpmap.tga # says to use the red channel of +// bumpmap.tga as the bumpmap +// +// For reflection maps... +// +// -type sphere # specifies a sphere for a "refl" +// reflection map +// -type cube_top | cube_bottom | # when using a cube map, the texture +// file for each +// cube_front | cube_back | # side of the cube is specified +// separately +// cube_left | cube_right +// +// TinyObjLoader extension. +// +// -colorspace SPACE # Color space of the texture. e.g. +// 'sRGB` or 'linear' +// + +#ifdef TINYOBJLOADER_USE_DOUBLE +//#pragma message "using double" +typedef double real_t; +#else +//#pragma message "using float" +typedef float real_t; +#endif + +typedef enum { + TEXTURE_TYPE_NONE, // default + TEXTURE_TYPE_SPHERE, + TEXTURE_TYPE_CUBE_TOP, + TEXTURE_TYPE_CUBE_BOTTOM, + TEXTURE_TYPE_CUBE_FRONT, + TEXTURE_TYPE_CUBE_BACK, + TEXTURE_TYPE_CUBE_LEFT, + TEXTURE_TYPE_CUBE_RIGHT +} texture_type_t; + +struct texture_option_t { + texture_type_t type; // -type (default TEXTURE_TYPE_NONE) + real_t sharpness; // -boost (default 1.0?) + real_t brightness; // base_value in -mm option (default 0) + real_t contrast; // gain_value in -mm option (default 1) + real_t origin_offset[3]; // -o u [v [w]] (default 0 0 0) + real_t scale[3]; // -s u [v [w]] (default 1 1 1) + real_t turbulence[3]; // -t u [v [w]] (default 0 0 0) + int texture_resolution; // -texres resolution (No default value in the spec. + // We'll use -1) + bool clamp; // -clamp (default false) + char imfchan; // -imfchan (the default for bump is 'l' and for decal is 'm') + bool blendu; // -blendu (default on) + bool blendv; // -blendv (default on) + real_t bump_multiplier; // -bm (for bump maps only, default 1.0) + + // extension + std::string colorspace; // Explicitly specify color space of stored texel + // value. Usually `sRGB` or `linear` (default empty). +}; + +struct material_t { + std::string name; + + real_t ambient[3]; + real_t diffuse[3]; + real_t specular[3]; + real_t transmittance[3]; + real_t emission[3]; + real_t shininess; + real_t ior; // index of refraction + real_t dissolve; // 1 == opaque; 0 == fully transparent + // illumination model (see http://www.fileformat.info/format/material/) + int illum; + + int dummy; // Suppress padding warning. + + std::string ambient_texname; // map_Ka. For ambient or ambient occlusion. + std::string diffuse_texname; // map_Kd + std::string specular_texname; // map_Ks + std::string specular_highlight_texname; // map_Ns + std::string bump_texname; // map_bump, map_Bump, bump + std::string displacement_texname; // disp + std::string alpha_texname; // map_d + std::string reflection_texname; // refl + + texture_option_t ambient_texopt; + texture_option_t diffuse_texopt; + texture_option_t specular_texopt; + texture_option_t specular_highlight_texopt; + texture_option_t bump_texopt; + texture_option_t displacement_texopt; + texture_option_t alpha_texopt; + texture_option_t reflection_texopt; + + // PBR extension + // http://exocortex.com/blog/extending_wavefront_mtl_to_support_pbr + real_t roughness; // [0, 1] default 0 + real_t metallic; // [0, 1] default 0 + real_t sheen; // [0, 1] default 0 + real_t clearcoat_thickness; // [0, 1] default 0 + real_t clearcoat_roughness; // [0, 1] default 0 + real_t anisotropy; // aniso. [0, 1] default 0 + real_t anisotropy_rotation; // anisor. [0, 1] default 0 + real_t pad0; + std::string roughness_texname; // map_Pr + std::string metallic_texname; // map_Pm + std::string sheen_texname; // map_Ps + std::string emissive_texname; // map_Ke + std::string normal_texname; // norm. For normal mapping. + + texture_option_t roughness_texopt; + texture_option_t metallic_texopt; + texture_option_t sheen_texopt; + texture_option_t emissive_texopt; + texture_option_t normal_texopt; + + int pad2; + + std::map unknown_parameter; + +#ifdef TINY_OBJ_LOADER_PYTHON_BINDING + // For pybind11 + std::array GetDiffuse() { + std::array values; + values[0] = double(diffuse[0]); + values[1] = double(diffuse[1]); + values[2] = double(diffuse[2]); + + return values; + } + + std::array GetSpecular() { + std::array values; + values[0] = double(specular[0]); + values[1] = double(specular[1]); + values[2] = double(specular[2]); + + return values; + } + + std::array GetTransmittance() { + std::array values; + values[0] = double(transmittance[0]); + values[1] = double(transmittance[1]); + values[2] = double(transmittance[2]); + + return values; + } + + std::array GetEmission() { + std::array values; + values[0] = double(emission[0]); + values[1] = double(emission[1]); + values[2] = double(emission[2]); + + return values; + } + + std::array GetAmbient() { + std::array values; + values[0] = double(ambient[0]); + values[1] = double(ambient[1]); + values[2] = double(ambient[2]); + + return values; + } + + void SetDiffuse(std::array &a) { + diffuse[0] = real_t(a[0]); + diffuse[1] = real_t(a[1]); + diffuse[2] = real_t(a[2]); + } + + void SetAmbient(std::array &a) { + ambient[0] = real_t(a[0]); + ambient[1] = real_t(a[1]); + ambient[2] = real_t(a[2]); + } + + void SetSpecular(std::array &a) { + specular[0] = real_t(a[0]); + specular[1] = real_t(a[1]); + specular[2] = real_t(a[2]); + } + + void SetTransmittance(std::array &a) { + transmittance[0] = real_t(a[0]); + transmittance[1] = real_t(a[1]); + transmittance[2] = real_t(a[2]); + } + + std::string GetCustomParameter(const std::string &key) { + std::map::const_iterator it = + unknown_parameter.find(key); + + if (it != unknown_parameter.end()) { + return it->second; + } + return std::string(); + } + +#endif +}; + +struct tag_t { + std::string name; + + std::vector intValues; + std::vector floatValues; + std::vector stringValues; +}; + +struct joint_and_weight_t { + int joint_id; + real_t weight; +}; + +struct skin_weight_t { + int vertex_id; // Corresponding vertex index in `attrib_t::vertices`. + // Compared to `index_t`, this index must be positive and + // start with 0(does not allow relative indexing) + std::vector weightValues; +}; + +// Index struct to support different indices for vtx/normal/texcoord. +// -1 means not used. +struct index_t { + int vertex_index; + int normal_index; + int texcoord_index; +}; + +struct mesh_t { + std::vector indices; + std::vector + num_face_vertices; // The number of vertices per + // face. 3 = triangle, 4 = quad, ... + std::vector material_ids; // per-face material ID + std::vector smoothing_group_ids; // per-face smoothing group + // ID(0 = off. positive value + // = group id) + std::vector tags; // SubD tag +}; + +// struct path_t { +// std::vector indices; // pairs of indices for lines +//}; + +struct lines_t { + // Linear flattened indices. + std::vector indices; // indices for vertices(poly lines) + std::vector num_line_vertices; // The number of vertices per line. +}; + +struct points_t { + std::vector indices; // indices for points +}; + +struct shape_t { + std::string name; + mesh_t mesh; + lines_t lines; + points_t points; +}; + +// Vertex attributes +struct attrib_t { + std::vector vertices; // 'v'(xyz) + + // For backward compatibility, we store vertex weight in separate array. + std::vector vertex_weights; // 'v'(w) + std::vector normals; // 'vn' + std::vector texcoords; // 'vt'(uv) + + // For backward compatibility, we store texture coordinate 'w' in separate + // array. + std::vector texcoord_ws; // 'vt'(w) + std::vector colors; // extension: vertex colors + + // + // TinyObj extension. + // + + // NOTE(syoyo): array index is based on the appearance order. + // To get a corresponding skin weight for a specific vertex id `vid`, + // Need to reconstruct a look up table: `skin_weight_t::vertex_id` == `vid` + // (e.g. using std::map, std::unordered_map) + std::vector skin_weights; + + attrib_t() {} + + // + // For pybind11 + // + const std::vector &GetVertices() const { return vertices; } + + const std::vector &GetVertexWeights() const { return vertex_weights; } +}; + +struct callback_t { + // W is optional and set to 1 if there is no `w` item in `v` line + void (*vertex_cb)(void *user_data, real_t x, real_t y, real_t z, real_t w); + void (*vertex_color_cb)(void *user_data, real_t x, real_t y, real_t z, + real_t r, real_t g, real_t b, bool has_color); + void (*normal_cb)(void *user_data, real_t x, real_t y, real_t z); + + // y and z are optional and set to 0 if there is no `y` and/or `z` item(s) in + // `vt` line. + void (*texcoord_cb)(void *user_data, real_t x, real_t y, real_t z); + + // called per 'f' line. num_indices is the number of face indices(e.g. 3 for + // triangle, 4 for quad) + // 0 will be passed for undefined index in index_t members. + void (*index_cb)(void *user_data, index_t *indices, int num_indices); + // `name` material name, `material_id` = the array index of material_t[]. -1 + // if + // a material not found in .mtl + void (*usemtl_cb)(void *user_data, const char *name, int material_id); + // `materials` = parsed material data. + void (*mtllib_cb)(void *user_data, const material_t *materials, + int num_materials); + // There may be multiple group names + void (*group_cb)(void *user_data, const char **names, int num_names); + void (*object_cb)(void *user_data, const char *name); + + callback_t() + : vertex_cb(NULL), + vertex_color_cb(NULL), + normal_cb(NULL), + texcoord_cb(NULL), + index_cb(NULL), + usemtl_cb(NULL), + mtllib_cb(NULL), + group_cb(NULL), + object_cb(NULL) {} +}; + +class MaterialReader { + public: + MaterialReader() {} + virtual ~MaterialReader(); + + virtual bool operator()(const std::string &matId, + std::vector *materials, + std::map *matMap, std::string *warn, + std::string *err) = 0; +}; + +/// +/// Read .mtl from a file. +/// +class MaterialFileReader : public MaterialReader { + public: + // Path could contain separator(';' in Windows, ':' in Posix) + explicit MaterialFileReader(const std::string &mtl_basedir) + : m_mtlBaseDir(mtl_basedir) {} + virtual ~MaterialFileReader() TINYOBJ_OVERRIDE {} + virtual bool operator()(const std::string &matId, + std::vector *materials, + std::map *matMap, std::string *warn, + std::string *err) TINYOBJ_OVERRIDE; + + private: + std::string m_mtlBaseDir; +}; + +/// +/// Read .mtl from a stream. +/// +class MaterialStreamReader : public MaterialReader { + public: + explicit MaterialStreamReader(std::istream &inStream) + : m_inStream(inStream) {} + virtual ~MaterialStreamReader() TINYOBJ_OVERRIDE {} + virtual bool operator()(const std::string &matId, + std::vector *materials, + std::map *matMap, std::string *warn, + std::string *err) TINYOBJ_OVERRIDE; + + private: + std::istream &m_inStream; +}; + +// v2 API +struct ObjReaderConfig { + bool triangulate; // triangulate polygon? + + // Currently not used. + // "simple" or empty: Create triangle fan + // "earcut": Use the algorithm based on Ear clipping + std::string triangulation_method; + + /// Parse vertex color. + /// If vertex color is not present, its filled with default value. + /// false = no vertex color + /// This will increase memory of parsed .obj + bool vertex_color; + + /// + /// Search path to .mtl file. + /// Default = "" = search from the same directory of .obj file. + /// Valid only when loading .obj from a file. + /// + std::string mtl_search_path; + + ObjReaderConfig() + : triangulate(true), triangulation_method("simple"), vertex_color(true) {} +}; + +/// +/// Wavefront .obj reader class(v2 API) +/// +class ObjReader { + public: + ObjReader() : valid_(false) {} + + /// + /// Load .obj and .mtl from a file. + /// + /// @param[in] filename wavefront .obj filename + /// @param[in] config Reader configuration + /// + bool ParseFromFile(const std::string &filename, + const ObjReaderConfig &config = ObjReaderConfig()); + + /// + /// Parse .obj from a text string. + /// Need to supply .mtl text string by `mtl_text`. + /// This function ignores `mtllib` line in .obj text. + /// + /// @param[in] obj_text wavefront .obj filename + /// @param[in] mtl_text wavefront .mtl filename + /// @param[in] config Reader configuration + /// + bool ParseFromString(const std::string &obj_text, const std::string &mtl_text, + const ObjReaderConfig &config = ObjReaderConfig()); + + /// + /// .obj was loaded or parsed correctly. + /// + bool Valid() const { return valid_; } + + const attrib_t &GetAttrib() const { return attrib_; } + + const std::vector &GetShapes() const { return shapes_; } + + const std::vector &GetMaterials() const { return materials_; } + + /// + /// Warning message(may be filled after `Load` or `Parse`) + /// + const std::string &Warning() const { return warning_; } + + /// + /// Error message(filled when `Load` or `Parse` failed) + /// + const std::string &Error() const { return error_; } + + private: + bool valid_; + + attrib_t attrib_; + std::vector shapes_; + std::vector materials_; + + std::string warning_; + std::string error_; +}; + +/// ==>>========= Legacy v1 API ============================================= + +/// Loads .obj from a file. +/// 'attrib', 'shapes' and 'materials' will be filled with parsed shape data +/// 'shapes' will be filled with parsed shape data +/// Returns true when loading .obj become success. +/// Returns warning message into `warn`, and error message into `err` +/// 'mtl_basedir' is optional, and used for base directory for .mtl file. +/// In default(`NULL'), .mtl file is searched from an application's working +/// directory. +/// 'triangulate' is optional, and used whether triangulate polygon face in .obj +/// or not. +/// Option 'default_vcols_fallback' specifies whether vertex colors should +/// always be defined, even if no colors are given (fallback to white). +bool LoadObj(attrib_t *attrib, std::vector *shapes, + std::vector *materials, std::string *warn, + std::string *err, const char *filename, + const char *mtl_basedir = NULL, bool triangulate = true, + bool default_vcols_fallback = true); + +/// Loads .obj from a file with custom user callback. +/// .mtl is loaded as usual and parsed material_t data will be passed to +/// `callback.mtllib_cb`. +/// Returns true when loading .obj/.mtl become success. +/// Returns warning message into `warn`, and error message into `err` +/// See `examples/callback_api/` for how to use this function. +bool LoadObjWithCallback(std::istream &inStream, const callback_t &callback, + void *user_data = NULL, + MaterialReader *readMatFn = NULL, + std::string *warn = NULL, std::string *err = NULL); + +/// Loads object from a std::istream, uses `readMatFn` to retrieve +/// std::istream for materials. +/// Returns true when loading .obj become success. +/// Returns warning and error message into `err` +bool LoadObj(attrib_t *attrib, std::vector *shapes, + std::vector *materials, std::string *warn, + std::string *err, std::istream *inStream, + MaterialReader *readMatFn = NULL, bool triangulate = true, + bool default_vcols_fallback = true); + +/// Loads materials into std::map +void LoadMtl(std::map *material_map, + std::vector *materials, std::istream *inStream, + std::string *warning, std::string *err); + +/// +/// Parse texture name and texture option for custom texture parameter through +/// material::unknown_parameter +/// +/// @param[out] texname Parsed texture name +/// @param[out] texopt Parsed texopt +/// @param[in] linebuf Input string +/// +bool ParseTextureNameAndOption(std::string *texname, texture_option_t *texopt, + const char *linebuf); + +/// =<<========== Legacy v1 API ============================================= + +} // namespace tinyobj + +#endif // TINY_OBJ_LOADER_H_ + +#ifdef TINYOBJLOADER_IMPLEMENTATION +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef TINYOBJLOADER_USE_MAPBOX_EARCUT + +#ifdef TINYOBJLOADER_DONOT_INCLUDE_MAPBOX_EARCUT +// Assume earcut.hpp is included outside of tiny_obj_loader.h +#else + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Weverything" +#endif + +#include + +#include "earcut.h" + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#endif + +#endif // TINYOBJLOADER_USE_MAPBOX_EARCUT + +namespace tinyobj { + +MaterialReader::~MaterialReader() {} + +struct vertex_index_t { + int v_idx, vt_idx, vn_idx; + vertex_index_t() : v_idx(-1), vt_idx(-1), vn_idx(-1) {} + explicit vertex_index_t(int idx) : v_idx(idx), vt_idx(idx), vn_idx(idx) {} + vertex_index_t(int vidx, int vtidx, int vnidx) + : v_idx(vidx), vt_idx(vtidx), vn_idx(vnidx) {} +}; + +// Internal data structure for face representation +// index + smoothing group. +struct face_t { + unsigned int + smoothing_group_id; // smoothing group id. 0 = smoothing groupd is off. + int pad_; + std::vector vertex_indices; // face vertex indices. + + face_t() : smoothing_group_id(0), pad_(0) {} +}; + +// Internal data structure for line representation +struct __line_t { + // l v1/vt1 v2/vt2 ... + // In the specification, line primitrive does not have normal index, but + // TinyObjLoader allow it + std::vector vertex_indices; +}; + +// Internal data structure for points representation +struct __points_t { + // p v1 v2 ... + // In the specification, point primitrive does not have normal index and + // texture coord index, but TinyObjLoader allow it. + std::vector vertex_indices; +}; + +struct tag_sizes { + tag_sizes() : num_ints(0), num_reals(0), num_strings(0) {} + int num_ints; + int num_reals; + int num_strings; +}; + +struct obj_shape { + std::vector v; + std::vector vn; + std::vector vt; +}; + +// +// Manages group of primitives(face, line, points, ...) +struct PrimGroup { + std::vector faceGroup; + std::vector<__line_t> lineGroup; + std::vector<__points_t> pointsGroup; + + void clear() { + faceGroup.clear(); + lineGroup.clear(); + pointsGroup.clear(); + } + + bool IsEmpty() const { + return faceGroup.empty() && lineGroup.empty() && pointsGroup.empty(); + } + + // TODO(syoyo): bspline, surface, ... +}; + +// See +// http://stackoverflow.com/questions/6089231/getting-std-ifstream-to-handle-lf-cr-and-crlf +static std::istream &safeGetline(std::istream &is, std::string &t) { + t.clear(); + + // The characters in the stream are read one-by-one using a std::streambuf. + // That is faster than reading them one-by-one using the std::istream. + // Code that uses streambuf this way must be guarded by a sentry object. + // The sentry object performs various tasks, + // such as thread synchronization and updating the stream state. + + std::istream::sentry se(is, true); + std::streambuf *sb = is.rdbuf(); + + if (se) { + for (;;) { + int c = sb->sbumpc(); + switch (c) { + case '\n': + return is; + case '\r': + if (sb->sgetc() == '\n') sb->sbumpc(); + return is; + case EOF: + // Also handle the case when the last line has no line ending + if (t.empty()) is.setstate(std::ios::eofbit); + return is; + default: + t += static_cast(c); + } + } + } + + return is; +} + +#define IS_SPACE(x) (((x) == ' ') || ((x) == '\t')) +#define IS_DIGIT(x) \ + (static_cast((x) - '0') < static_cast(10)) +#define IS_NEW_LINE(x) (((x) == '\r') || ((x) == '\n') || ((x) == '\0')) + +template +static inline std::string toString(const T &t) { + std::stringstream ss; + ss << t; + return ss.str(); +} + +struct warning_context { + std::string *warn; + size_t line_number; +}; + +// Make index zero-base, and also support relative index. +static inline bool fixIndex(int idx, int n, int *ret, bool allow_zero, + const warning_context &context) { + if (!ret) { + return false; + } + + if (idx > 0) { + (*ret) = idx - 1; + return true; + } + + if (idx == 0) { + // zero is not allowed according to the spec. + if (context.warn) { + (*context.warn) += + "A zero value index found (will have a value of -1 for normal and " + "tex indices. Line " + + toString(context.line_number) + ").\n"; + } + + (*ret) = idx - 1; + return allow_zero; + } + + if (idx < 0) { + (*ret) = n + idx; // negative value = relative + if ((*ret) < 0) { + return false; // invalid relative index + } + return true; + } + + return false; // never reach here. +} + +static inline std::string parseString(const char **token) { + std::string s; + (*token) += strspn((*token), " \t"); + size_t e = strcspn((*token), " \t\r"); + s = std::string((*token), &(*token)[e]); + (*token) += e; + return s; +} + +static inline int parseInt(const char **token) { + (*token) += strspn((*token), " \t"); + int i = atoi((*token)); + (*token) += strcspn((*token), " \t\r"); + return i; +} + +// Tries to parse a floating point number located at s. +// +// s_end should be a location in the string where reading should absolutely +// stop. For example at the end of the string, to prevent buffer overflows. +// +// Parses the following EBNF grammar: +// sign = "+" | "-" ; +// END = ? anything not in digit ? +// digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ; +// integer = [sign] , digit , {digit} ; +// decimal = integer , ["." , integer] ; +// float = ( decimal , END ) | ( decimal , ("E" | "e") , integer , END ) ; +// +// Valid strings are for example: +// -0 +3.1417e+2 -0.0E-3 1.0324 -1.41 11e2 +// +// If the parsing is a success, result is set to the parsed value and true +// is returned. +// +// The function is greedy and will parse until any of the following happens: +// - a non-conforming character is encountered. +// - s_end is reached. +// +// The following situations triggers a failure: +// - s >= s_end. +// - parse failure. +// +static bool tryParseDouble(const char *s, const char *s_end, double *result) { + if (s >= s_end) { + return false; + } + + double mantissa = 0.0; + // This exponent is base 2 rather than 10. + // However the exponent we parse is supposed to be one of ten, + // thus we must take care to convert the exponent/and or the + // mantissa to a * 2^E, where a is the mantissa and E is the + // exponent. + // To get the final double we will use ldexp, it requires the + // exponent to be in base 2. + int exponent = 0; + + // NOTE: THESE MUST BE DECLARED HERE SINCE WE ARE NOT ALLOWED + // TO JUMP OVER DEFINITIONS. + char sign = '+'; + char exp_sign = '+'; + char const *curr = s; + + // How many characters were read in a loop. + int read = 0; + // Tells whether a loop terminated due to reaching s_end. + bool end_not_reached = false; + bool leading_decimal_dots = false; + + /* + BEGIN PARSING. + */ + + // Find out what sign we've got. + if (*curr == '+' || *curr == '-') { + sign = *curr; + curr++; + if ((curr != s_end) && (*curr == '.')) { + // accept. Somethig like `.7e+2`, `-.5234` + leading_decimal_dots = true; + } + } else if (IS_DIGIT(*curr)) { /* Pass through. */ + } else if (*curr == '.') { + // accept. Somethig like `.7e+2`, `-.5234` + leading_decimal_dots = true; + } else { + goto fail; + } + + // Read the integer part. + end_not_reached = (curr != s_end); + if (!leading_decimal_dots) { + while (end_not_reached && IS_DIGIT(*curr)) { + mantissa *= 10; + mantissa += static_cast(*curr - 0x30); + curr++; + read++; + end_not_reached = (curr != s_end); + } + + // We must make sure we actually got something. + if (read == 0) goto fail; + } + + // We allow numbers of form "#", "###" etc. + if (!end_not_reached) goto assemble; + + // Read the decimal part. + if (*curr == '.') { + curr++; + read = 1; + end_not_reached = (curr != s_end); + while (end_not_reached && IS_DIGIT(*curr)) { + static const double pow_lut[] = { + 1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001, + }; + const int lut_entries = sizeof pow_lut / sizeof pow_lut[0]; + + // NOTE: Don't use powf here, it will absolutely murder precision. + mantissa += static_cast(*curr - 0x30) * + (read < lut_entries ? pow_lut[read] : std::pow(10.0, -read)); + read++; + curr++; + end_not_reached = (curr != s_end); + } + } else if (*curr == 'e' || *curr == 'E') { + } else { + goto assemble; + } + + if (!end_not_reached) goto assemble; + + // Read the exponent part. + if (*curr == 'e' || *curr == 'E') { + curr++; + // Figure out if a sign is present and if it is. + end_not_reached = (curr != s_end); + if (end_not_reached && (*curr == '+' || *curr == '-')) { + exp_sign = *curr; + curr++; + } else if (IS_DIGIT(*curr)) { /* Pass through. */ + } else { + // Empty E is not allowed. + goto fail; + } + + read = 0; + end_not_reached = (curr != s_end); + while (end_not_reached && IS_DIGIT(*curr)) { + // To avoid annoying MSVC's min/max macro definiton, + // Use hardcoded int max value + if (exponent > + (2147483647 / 10)) { // 2147483647 = std::numeric_limits::max() + // Integer overflow + goto fail; + } + exponent *= 10; + exponent += static_cast(*curr - 0x30); + curr++; + read++; + end_not_reached = (curr != s_end); + } + exponent *= (exp_sign == '+' ? 1 : -1); + if (read == 0) goto fail; + } + +assemble: + *result = (sign == '+' ? 1 : -1) * + (exponent ? std::ldexp(mantissa * std::pow(5.0, exponent), exponent) + : mantissa); + return true; +fail: + return false; +} + +static inline real_t parseReal(const char **token, double default_value = 0.0) { + (*token) += strspn((*token), " \t"); + const char *end = (*token) + strcspn((*token), " \t\r"); + double val = default_value; + tryParseDouble((*token), end, &val); + real_t f = static_cast(val); + (*token) = end; + return f; +} + +static inline bool parseReal(const char **token, real_t *out) { + (*token) += strspn((*token), " \t"); + const char *end = (*token) + strcspn((*token), " \t\r"); + double val; + bool ret = tryParseDouble((*token), end, &val); + if (ret) { + real_t f = static_cast(val); + (*out) = f; + } + (*token) = end; + return ret; +} + +static inline void parseReal2(real_t *x, real_t *y, const char **token, + const double default_x = 0.0, + const double default_y = 0.0) { + (*x) = parseReal(token, default_x); + (*y) = parseReal(token, default_y); +} + +static inline void parseReal3(real_t *x, real_t *y, real_t *z, + const char **token, const double default_x = 0.0, + const double default_y = 0.0, + const double default_z = 0.0) { + (*x) = parseReal(token, default_x); + (*y) = parseReal(token, default_y); + (*z) = parseReal(token, default_z); +} + +#if 0 // not used +static inline void parseV(real_t *x, real_t *y, real_t *z, real_t *w, + const char **token, const double default_x = 0.0, + const double default_y = 0.0, + const double default_z = 0.0, + const double default_w = 1.0) { + (*x) = parseReal(token, default_x); + (*y) = parseReal(token, default_y); + (*z) = parseReal(token, default_z); + (*w) = parseReal(token, default_w); +} +#endif + +// Extension: parse vertex with colors(6 items) +// Return 3: xyz, 4: xyzw, 6: xyzrgb +// `r`: red(case 6) or [w](case 4) +static inline int parseVertexWithColor(real_t *x, real_t *y, real_t *z, + real_t *r, real_t *g, real_t *b, + const char **token, + const double default_x = 0.0, + const double default_y = 0.0, + const double default_z = 0.0) { + // TODO: Check error + (*x) = parseReal(token, default_x); + (*y) = parseReal(token, default_y); + (*z) = parseReal(token, default_z); + + // - 4 components(x, y, z, w) ot 6 components + bool has_r = parseReal(token, r); + + if (!has_r) { + (*r) = (*g) = (*b) = 1.0; + return 3; + } + + bool has_g = parseReal(token, g); + + if (!has_g) { + (*g) = (*b) = 1.0; + return 4; + } + + bool has_b = parseReal(token, b); + + if (!has_b) { + (*r) = (*g) = (*b) = 1.0; + return 3; // treated as xyz + } + + return 6; +} + +static inline bool parseOnOff(const char **token, bool default_value = true) { + (*token) += strspn((*token), " \t"); + const char *end = (*token) + strcspn((*token), " \t\r"); + + bool ret = default_value; + if ((0 == strncmp((*token), "on", 2))) { + ret = true; + } else if ((0 == strncmp((*token), "off", 3))) { + ret = false; + } + + (*token) = end; + return ret; +} + +static inline texture_type_t parseTextureType( + const char **token, texture_type_t default_value = TEXTURE_TYPE_NONE) { + (*token) += strspn((*token), " \t"); + const char *end = (*token) + strcspn((*token), " \t\r"); + texture_type_t ty = default_value; + + if ((0 == strncmp((*token), "cube_top", strlen("cube_top")))) { + ty = TEXTURE_TYPE_CUBE_TOP; + } else if ((0 == strncmp((*token), "cube_bottom", strlen("cube_bottom")))) { + ty = TEXTURE_TYPE_CUBE_BOTTOM; + } else if ((0 == strncmp((*token), "cube_left", strlen("cube_left")))) { + ty = TEXTURE_TYPE_CUBE_LEFT; + } else if ((0 == strncmp((*token), "cube_right", strlen("cube_right")))) { + ty = TEXTURE_TYPE_CUBE_RIGHT; + } else if ((0 == strncmp((*token), "cube_front", strlen("cube_front")))) { + ty = TEXTURE_TYPE_CUBE_FRONT; + } else if ((0 == strncmp((*token), "cube_back", strlen("cube_back")))) { + ty = TEXTURE_TYPE_CUBE_BACK; + } else if ((0 == strncmp((*token), "sphere", strlen("sphere")))) { + ty = TEXTURE_TYPE_SPHERE; + } + + (*token) = end; + return ty; +} + +static tag_sizes parseTagTriple(const char **token) { + tag_sizes ts; + + (*token) += strspn((*token), " \t"); + ts.num_ints = atoi((*token)); + (*token) += strcspn((*token), "/ \t\r"); + if ((*token)[0] != '/') { + return ts; + } + + (*token)++; // Skip '/' + + (*token) += strspn((*token), " \t"); + ts.num_reals = atoi((*token)); + (*token) += strcspn((*token), "/ \t\r"); + if ((*token)[0] != '/') { + return ts; + } + (*token)++; // Skip '/' + + ts.num_strings = parseInt(token); + + return ts; +} + +// Parse triples with index offsets: i, i/j/k, i//k, i/j +static bool parseTriple(const char **token, int vsize, int vnsize, int vtsize, + vertex_index_t *ret, const warning_context &context) { + if (!ret) { + return false; + } + + vertex_index_t vi(-1); + + if (!fixIndex(atoi((*token)), vsize, &vi.v_idx, false, context)) { + return false; + } + + (*token) += strcspn((*token), "/ \t\r"); + if ((*token)[0] != '/') { + (*ret) = vi; + return true; + } + (*token)++; + + // i//k + if ((*token)[0] == '/') { + (*token)++; + if (!fixIndex(atoi((*token)), vnsize, &vi.vn_idx, true, context)) { + return false; + } + (*token) += strcspn((*token), "/ \t\r"); + (*ret) = vi; + return true; + } + + // i/j/k or i/j + if (!fixIndex(atoi((*token)), vtsize, &vi.vt_idx, true, context)) { + return false; + } + + (*token) += strcspn((*token), "/ \t\r"); + if ((*token)[0] != '/') { + (*ret) = vi; + return true; + } + + // i/j/k + (*token)++; // skip '/' + if (!fixIndex(atoi((*token)), vnsize, &vi.vn_idx, true, context)) { + return false; + } + (*token) += strcspn((*token), "/ \t\r"); + + (*ret) = vi; + + return true; +} + +// Parse raw triples: i, i/j/k, i//k, i/j +static vertex_index_t parseRawTriple(const char **token) { + vertex_index_t vi(static_cast(0)); // 0 is an invalid index in OBJ + + vi.v_idx = atoi((*token)); + (*token) += strcspn((*token), "/ \t\r"); + if ((*token)[0] != '/') { + return vi; + } + (*token)++; + + // i//k + if ((*token)[0] == '/') { + (*token)++; + vi.vn_idx = atoi((*token)); + (*token) += strcspn((*token), "/ \t\r"); + return vi; + } + + // i/j/k or i/j + vi.vt_idx = atoi((*token)); + (*token) += strcspn((*token), "/ \t\r"); + if ((*token)[0] != '/') { + return vi; + } + + // i/j/k + (*token)++; // skip '/' + vi.vn_idx = atoi((*token)); + (*token) += strcspn((*token), "/ \t\r"); + return vi; +} + +bool ParseTextureNameAndOption(std::string *texname, texture_option_t *texopt, + const char *linebuf) { + // @todo { write more robust lexer and parser. } + bool found_texname = false; + std::string texture_name; + + const char *token = linebuf; // Assume line ends with NULL + + while (!IS_NEW_LINE((*token))) { + token += strspn(token, " \t"); // skip space + if ((0 == strncmp(token, "-blendu", 7)) && IS_SPACE((token[7]))) { + token += 8; + texopt->blendu = parseOnOff(&token, /* default */ true); + } else if ((0 == strncmp(token, "-blendv", 7)) && IS_SPACE((token[7]))) { + token += 8; + texopt->blendv = parseOnOff(&token, /* default */ true); + } else if ((0 == strncmp(token, "-clamp", 6)) && IS_SPACE((token[6]))) { + token += 7; + texopt->clamp = parseOnOff(&token, /* default */ true); + } else if ((0 == strncmp(token, "-boost", 6)) && IS_SPACE((token[6]))) { + token += 7; + texopt->sharpness = parseReal(&token, 1.0); + } else if ((0 == strncmp(token, "-bm", 3)) && IS_SPACE((token[3]))) { + token += 4; + texopt->bump_multiplier = parseReal(&token, 1.0); + } else if ((0 == strncmp(token, "-o", 2)) && IS_SPACE((token[2]))) { + token += 3; + parseReal3(&(texopt->origin_offset[0]), &(texopt->origin_offset[1]), + &(texopt->origin_offset[2]), &token); + } else if ((0 == strncmp(token, "-s", 2)) && IS_SPACE((token[2]))) { + token += 3; + parseReal3(&(texopt->scale[0]), &(texopt->scale[1]), &(texopt->scale[2]), + &token, 1.0, 1.0, 1.0); + } else if ((0 == strncmp(token, "-t", 2)) && IS_SPACE((token[2]))) { + token += 3; + parseReal3(&(texopt->turbulence[0]), &(texopt->turbulence[1]), + &(texopt->turbulence[2]), &token); + } else if ((0 == strncmp(token, "-type", 5)) && IS_SPACE((token[5]))) { + token += 5; + texopt->type = parseTextureType((&token), TEXTURE_TYPE_NONE); + } else if ((0 == strncmp(token, "-texres", 7)) && IS_SPACE((token[7]))) { + token += 7; + // TODO(syoyo): Check if arg is int type. + texopt->texture_resolution = parseInt(&token); + } else if ((0 == strncmp(token, "-imfchan", 8)) && IS_SPACE((token[8]))) { + token += 9; + token += strspn(token, " \t"); + const char *end = token + strcspn(token, " \t\r"); + if ((end - token) == 1) { // Assume one char for -imfchan + texopt->imfchan = (*token); + } + token = end; + } else if ((0 == strncmp(token, "-mm", 3)) && IS_SPACE((token[3]))) { + token += 4; + parseReal2(&(texopt->brightness), &(texopt->contrast), &token, 0.0, 1.0); + } else if ((0 == strncmp(token, "-colorspace", 11)) && + IS_SPACE((token[11]))) { + token += 12; + texopt->colorspace = parseString(&token); + } else { +// Assume texture filename +#if 0 + size_t len = strcspn(token, " \t\r"); // untile next space + texture_name = std::string(token, token + len); + token += len; + + token += strspn(token, " \t"); // skip space +#else + // Read filename until line end to parse filename containing whitespace + // TODO(syoyo): Support parsing texture option flag after the filename. + texture_name = std::string(token); + token += texture_name.length(); +#endif + + found_texname = true; + } + } + + if (found_texname) { + (*texname) = texture_name; + return true; + } else { + return false; + } +} + +static void InitTexOpt(texture_option_t *texopt, const bool is_bump) { + if (is_bump) { + texopt->imfchan = 'l'; + } else { + texopt->imfchan = 'm'; + } + texopt->bump_multiplier = static_cast(1.0); + texopt->clamp = false; + texopt->blendu = true; + texopt->blendv = true; + texopt->sharpness = static_cast(1.0); + texopt->brightness = static_cast(0.0); + texopt->contrast = static_cast(1.0); + texopt->origin_offset[0] = static_cast(0.0); + texopt->origin_offset[1] = static_cast(0.0); + texopt->origin_offset[2] = static_cast(0.0); + texopt->scale[0] = static_cast(1.0); + texopt->scale[1] = static_cast(1.0); + texopt->scale[2] = static_cast(1.0); + texopt->turbulence[0] = static_cast(0.0); + texopt->turbulence[1] = static_cast(0.0); + texopt->turbulence[2] = static_cast(0.0); + texopt->texture_resolution = -1; + texopt->type = TEXTURE_TYPE_NONE; +} + +static void InitMaterial(material_t *material) { + InitTexOpt(&material->ambient_texopt, /* is_bump */ false); + InitTexOpt(&material->diffuse_texopt, /* is_bump */ false); + InitTexOpt(&material->specular_texopt, /* is_bump */ false); + InitTexOpt(&material->specular_highlight_texopt, /* is_bump */ false); + InitTexOpt(&material->bump_texopt, /* is_bump */ true); + InitTexOpt(&material->displacement_texopt, /* is_bump */ false); + InitTexOpt(&material->alpha_texopt, /* is_bump */ false); + InitTexOpt(&material->reflection_texopt, /* is_bump */ false); + InitTexOpt(&material->roughness_texopt, /* is_bump */ false); + InitTexOpt(&material->metallic_texopt, /* is_bump */ false); + InitTexOpt(&material->sheen_texopt, /* is_bump */ false); + InitTexOpt(&material->emissive_texopt, /* is_bump */ false); + InitTexOpt(&material->normal_texopt, + /* is_bump */ false); // @fixme { is_bump will be true? } + material->name = ""; + material->ambient_texname = ""; + material->diffuse_texname = ""; + material->specular_texname = ""; + material->specular_highlight_texname = ""; + material->bump_texname = ""; + material->displacement_texname = ""; + material->reflection_texname = ""; + material->alpha_texname = ""; + for (int i = 0; i < 3; i++) { + material->ambient[i] = static_cast(0.0); + material->diffuse[i] = static_cast(0.0); + material->specular[i] = static_cast(0.0); + material->transmittance[i] = static_cast(0.0); + material->emission[i] = static_cast(0.0); + } + material->illum = 0; + material->dissolve = static_cast(1.0); + material->shininess = static_cast(1.0); + material->ior = static_cast(1.0); + + material->roughness = static_cast(0.0); + material->metallic = static_cast(0.0); + material->sheen = static_cast(0.0); + material->clearcoat_thickness = static_cast(0.0); + material->clearcoat_roughness = static_cast(0.0); + material->anisotropy_rotation = static_cast(0.0); + material->anisotropy = static_cast(0.0); + material->roughness_texname = ""; + material->metallic_texname = ""; + material->sheen_texname = ""; + material->emissive_texname = ""; + material->normal_texname = ""; + + material->unknown_parameter.clear(); +} + +// code from https://wrf.ecse.rpi.edu//Research/Short_Notes/pnpoly.html +template +static int pnpoly(int nvert, T *vertx, T *verty, T testx, T testy) { + int i, j, c = 0; + for (i = 0, j = nvert - 1; i < nvert; j = i++) { + if (((verty[i] > testy) != (verty[j] > testy)) && + (testx < + (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + + vertx[i])) + c = !c; + } + return c; +} + +struct TinyObjPoint { + real_t x, y, z; + TinyObjPoint() : x(0), y(0), z(0) {} + TinyObjPoint(real_t x_, real_t y_, real_t z_) : x(x_), y(y_), z(z_) {} +}; + +inline TinyObjPoint cross(const TinyObjPoint &v1, const TinyObjPoint &v2) { + return TinyObjPoint(v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, + v1.x * v2.y - v1.y * v2.x); +} + +inline real_t dot(const TinyObjPoint &v1, const TinyObjPoint &v2) { + return (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z); +} + +inline real_t GetLength(TinyObjPoint &e) { + return std::sqrt(e.x * e.x + e.y * e.y + e.z * e.z); +} + +inline TinyObjPoint Normalize(TinyObjPoint e) { + real_t inv_length = real_t(1) / GetLength(e); + return TinyObjPoint(e.x * inv_length, e.y * inv_length, e.z * inv_length); +} + +inline TinyObjPoint WorldToLocal(const TinyObjPoint &a, const TinyObjPoint &u, + const TinyObjPoint &v, const TinyObjPoint &w) { + return TinyObjPoint(dot(a, u), dot(a, v), dot(a, w)); +} + +// TODO(syoyo): refactor function. +static bool exportGroupsToShape(shape_t *shape, const PrimGroup &prim_group, + const std::vector &tags, + const int material_id, const std::string &name, + bool triangulate, const std::vector &v, + std::string *warn) { + if (prim_group.IsEmpty()) { + return false; + } + + shape->name = name; + + // polygon + if (!prim_group.faceGroup.empty()) { + // Flatten vertices and indices + for (size_t i = 0; i < prim_group.faceGroup.size(); i++) { + const face_t &face = prim_group.faceGroup[i]; + + size_t npolys = face.vertex_indices.size(); + + if (npolys < 3) { + // Face must have 3+ vertices. + if (warn) { + (*warn) += "Degenerated face found\n."; + } + continue; + } + + if (triangulate && npolys != 3) { + if (npolys == 4) { + vertex_index_t i0 = face.vertex_indices[0]; + vertex_index_t i1 = face.vertex_indices[1]; + vertex_index_t i2 = face.vertex_indices[2]; + vertex_index_t i3 = face.vertex_indices[3]; + + size_t vi0 = size_t(i0.v_idx); + size_t vi1 = size_t(i1.v_idx); + size_t vi2 = size_t(i2.v_idx); + size_t vi3 = size_t(i3.v_idx); + + if (((3 * vi0 + 2) >= v.size()) || ((3 * vi1 + 2) >= v.size()) || + ((3 * vi2 + 2) >= v.size()) || ((3 * vi3 + 2) >= v.size())) { + // Invalid triangle. + // FIXME(syoyo): Is it ok to simply skip this invalid triangle? + if (warn) { + (*warn) += "Face with invalid vertex index found.\n"; + } + continue; + } + + real_t v0x = v[vi0 * 3 + 0]; + real_t v0y = v[vi0 * 3 + 1]; + real_t v0z = v[vi0 * 3 + 2]; + real_t v1x = v[vi1 * 3 + 0]; + real_t v1y = v[vi1 * 3 + 1]; + real_t v1z = v[vi1 * 3 + 2]; + real_t v2x = v[vi2 * 3 + 0]; + real_t v2y = v[vi2 * 3 + 1]; + real_t v2z = v[vi2 * 3 + 2]; + real_t v3x = v[vi3 * 3 + 0]; + real_t v3y = v[vi3 * 3 + 1]; + real_t v3z = v[vi3 * 3 + 2]; + + // There are two candidates to split the quad into two triangles. + // + // Choose the shortest edge. + // TODO: Is it better to determine the edge to split by calculating + // the area of each triangle? + // + // +---+ + // |\ | + // | \ | + // | \| + // +---+ + // + // +---+ + // | /| + // | / | + // |/ | + // +---+ + + real_t e02x = v2x - v0x; + real_t e02y = v2y - v0y; + real_t e02z = v2z - v0z; + real_t e13x = v3x - v1x; + real_t e13y = v3y - v1y; + real_t e13z = v3z - v1z; + + real_t sqr02 = e02x * e02x + e02y * e02y + e02z * e02z; + real_t sqr13 = e13x * e13x + e13y * e13y + e13z * e13z; + + index_t idx0, idx1, idx2, idx3; + + idx0.vertex_index = i0.v_idx; + idx0.normal_index = i0.vn_idx; + idx0.texcoord_index = i0.vt_idx; + idx1.vertex_index = i1.v_idx; + idx1.normal_index = i1.vn_idx; + idx1.texcoord_index = i1.vt_idx; + idx2.vertex_index = i2.v_idx; + idx2.normal_index = i2.vn_idx; + idx2.texcoord_index = i2.vt_idx; + idx3.vertex_index = i3.v_idx; + idx3.normal_index = i3.vn_idx; + idx3.texcoord_index = i3.vt_idx; + + if (sqr02 < sqr13) { + // [0, 1, 2], [0, 2, 3] + shape->mesh.indices.push_back(idx0); + shape->mesh.indices.push_back(idx1); + shape->mesh.indices.push_back(idx2); + + shape->mesh.indices.push_back(idx0); + shape->mesh.indices.push_back(idx2); + shape->mesh.indices.push_back(idx3); + } else { + // [0, 1, 3], [1, 2, 3] + shape->mesh.indices.push_back(idx0); + shape->mesh.indices.push_back(idx1); + shape->mesh.indices.push_back(idx3); + + shape->mesh.indices.push_back(idx1); + shape->mesh.indices.push_back(idx2); + shape->mesh.indices.push_back(idx3); + } + + // Two triangle faces + shape->mesh.num_face_vertices.push_back(3); + shape->mesh.num_face_vertices.push_back(3); + + shape->mesh.material_ids.push_back(material_id); + shape->mesh.material_ids.push_back(material_id); + + shape->mesh.smoothing_group_ids.push_back(face.smoothing_group_id); + shape->mesh.smoothing_group_ids.push_back(face.smoothing_group_id); + + } else { +#ifdef TINYOBJLOADER_USE_MAPBOX_EARCUT + vertex_index_t i0 = face.vertex_indices[0]; + vertex_index_t i0_2 = i0; + + // TMW change: Find the normal axis of the polygon using Newell's + // method + TinyObjPoint n; + for (size_t k = 0; k < npolys; ++k) { + i0 = face.vertex_indices[k % npolys]; + size_t vi0 = size_t(i0.v_idx); + + size_t j = (k + 1) % npolys; + i0_2 = face.vertex_indices[j]; + size_t vi0_2 = size_t(i0_2.v_idx); + + real_t v0x = v[vi0 * 3 + 0]; + real_t v0y = v[vi0 * 3 + 1]; + real_t v0z = v[vi0 * 3 + 2]; + + real_t v0x_2 = v[vi0_2 * 3 + 0]; + real_t v0y_2 = v[vi0_2 * 3 + 1]; + real_t v0z_2 = v[vi0_2 * 3 + 2]; + + const TinyObjPoint point1(v0x, v0y, v0z); + const TinyObjPoint point2(v0x_2, v0y_2, v0z_2); + + TinyObjPoint a(point1.x - point2.x, point1.y - point2.y, + point1.z - point2.z); + TinyObjPoint b(point1.x + point2.x, point1.y + point2.y, + point1.z + point2.z); + + n.x += (a.y * b.z); + n.y += (a.z * b.x); + n.z += (a.x * b.y); + } + real_t length_n = GetLength(n); + // Check if zero length normal + if (length_n <= 0) { + continue; + } + // Negative is to flip the normal to the correct direction + real_t inv_length = -real_t(1.0) / length_n; + n.x *= inv_length; + n.y *= inv_length; + n.z *= inv_length; + + TinyObjPoint axis_w, axis_v, axis_u; + axis_w = n; + TinyObjPoint a; + if (std::fabs(axis_w.x) > real_t(0.9999999)) { + a = TinyObjPoint(0, 1, 0); + } else { + a = TinyObjPoint(1, 0, 0); + } + axis_v = Normalize(cross(axis_w, a)); + axis_u = cross(axis_w, axis_v); + using Point = std::array; + + // first polyline define the main polygon. + // following polylines define holes(not used in tinyobj). + std::vector > polygon; + + std::vector polyline; + + // TMW change: Find best normal and project v0x and v0y to those + // coordinates, instead of picking a plane aligned with an axis (which + // can flip polygons). + + // Fill polygon data(facevarying vertices). + for (size_t k = 0; k < npolys; k++) { + i0 = face.vertex_indices[k]; + size_t vi0 = size_t(i0.v_idx); + + assert(((3 * vi0 + 2) < v.size())); + + real_t v0x = v[vi0 * 3 + 0]; + real_t v0y = v[vi0 * 3 + 1]; + real_t v0z = v[vi0 * 3 + 2]; + + TinyObjPoint polypoint(v0x, v0y, v0z); + TinyObjPoint loc = WorldToLocal(polypoint, axis_u, axis_v, axis_w); + + polyline.push_back({loc.x, loc.y}); + } + + polygon.push_back(polyline); + std::vector indices = mapbox::earcut(polygon); + // => result = 3 * faces, clockwise + + assert(indices.size() % 3 == 0); + + // Reconstruct vertex_index_t + for (size_t k = 0; k < indices.size() / 3; k++) { + { + index_t idx0, idx1, idx2; + idx0.vertex_index = face.vertex_indices[indices[3 * k + 0]].v_idx; + idx0.normal_index = + face.vertex_indices[indices[3 * k + 0]].vn_idx; + idx0.texcoord_index = + face.vertex_indices[indices[3 * k + 0]].vt_idx; + idx1.vertex_index = face.vertex_indices[indices[3 * k + 1]].v_idx; + idx1.normal_index = + face.vertex_indices[indices[3 * k + 1]].vn_idx; + idx1.texcoord_index = + face.vertex_indices[indices[3 * k + 1]].vt_idx; + idx2.vertex_index = face.vertex_indices[indices[3 * k + 2]].v_idx; + idx2.normal_index = + face.vertex_indices[indices[3 * k + 2]].vn_idx; + idx2.texcoord_index = + face.vertex_indices[indices[3 * k + 2]].vt_idx; + + shape->mesh.indices.push_back(idx0); + shape->mesh.indices.push_back(idx1); + shape->mesh.indices.push_back(idx2); + + shape->mesh.num_face_vertices.push_back(3); + shape->mesh.material_ids.push_back(material_id); + shape->mesh.smoothing_group_ids.push_back( + face.smoothing_group_id); + } + } + +#else // Built-in ear clipping triangulation + vertex_index_t i0 = face.vertex_indices[0]; + vertex_index_t i1(-1); + vertex_index_t i2 = face.vertex_indices[1]; + + // find the two axes to work in + size_t axes[2] = {1, 2}; + for (size_t k = 0; k < npolys; ++k) { + i0 = face.vertex_indices[(k + 0) % npolys]; + i1 = face.vertex_indices[(k + 1) % npolys]; + i2 = face.vertex_indices[(k + 2) % npolys]; + size_t vi0 = size_t(i0.v_idx); + size_t vi1 = size_t(i1.v_idx); + size_t vi2 = size_t(i2.v_idx); + + if (((3 * vi0 + 2) >= v.size()) || ((3 * vi1 + 2) >= v.size()) || + ((3 * vi2 + 2) >= v.size())) { + // Invalid triangle. + // FIXME(syoyo): Is it ok to simply skip this invalid triangle? + continue; + } + real_t v0x = v[vi0 * 3 + 0]; + real_t v0y = v[vi0 * 3 + 1]; + real_t v0z = v[vi0 * 3 + 2]; + real_t v1x = v[vi1 * 3 + 0]; + real_t v1y = v[vi1 * 3 + 1]; + real_t v1z = v[vi1 * 3 + 2]; + real_t v2x = v[vi2 * 3 + 0]; + real_t v2y = v[vi2 * 3 + 1]; + real_t v2z = v[vi2 * 3 + 2]; + real_t e0x = v1x - v0x; + real_t e0y = v1y - v0y; + real_t e0z = v1z - v0z; + real_t e1x = v2x - v1x; + real_t e1y = v2y - v1y; + real_t e1z = v2z - v1z; + real_t cx = std::fabs(e0y * e1z - e0z * e1y); + real_t cy = std::fabs(e0z * e1x - e0x * e1z); + real_t cz = std::fabs(e0x * e1y - e0y * e1x); + const real_t epsilon = std::numeric_limits::epsilon(); + // std::cout << "cx " << cx << ", cy " << cy << ", cz " << cz << + // "\n"; + if (cx > epsilon || cy > epsilon || cz > epsilon) { + // std::cout << "corner\n"; + // found a corner + if (cx > cy && cx > cz) { + // std::cout << "pattern0\n"; + } else { + // std::cout << "axes[0] = 0\n"; + axes[0] = 0; + if (cz > cx && cz > cy) { + // std::cout << "axes[1] = 1\n"; + axes[1] = 1; + } + } + break; + } + } + + face_t remainingFace = face; // copy + size_t guess_vert = 0; + vertex_index_t ind[3]; + real_t vx[3]; + real_t vy[3]; + + // How many iterations can we do without decreasing the remaining + // vertices. + size_t remainingIterations = face.vertex_indices.size(); + size_t previousRemainingVertices = + remainingFace.vertex_indices.size(); + + while (remainingFace.vertex_indices.size() > 3 && + remainingIterations > 0) { + // std::cout << "remainingIterations " << remainingIterations << + // "\n"; + + npolys = remainingFace.vertex_indices.size(); + if (guess_vert >= npolys) { + guess_vert -= npolys; + } + + if (previousRemainingVertices != npolys) { + // The number of remaining vertices decreased. Reset counters. + previousRemainingVertices = npolys; + remainingIterations = npolys; + } else { + // We didn't consume a vertex on previous iteration, reduce the + // available iterations. + remainingIterations--; + } + + for (size_t k = 0; k < 3; k++) { + ind[k] = remainingFace.vertex_indices[(guess_vert + k) % npolys]; + size_t vi = size_t(ind[k].v_idx); + if (((vi * 3 + axes[0]) >= v.size()) || + ((vi * 3 + axes[1]) >= v.size())) { + // ??? + vx[k] = static_cast(0.0); + vy[k] = static_cast(0.0); + } else { + vx[k] = v[vi * 3 + axes[0]]; + vy[k] = v[vi * 3 + axes[1]]; + } + } + + // + // area is calculated per face + // + real_t e0x = vx[1] - vx[0]; + real_t e0y = vy[1] - vy[0]; + real_t e1x = vx[2] - vx[1]; + real_t e1y = vy[2] - vy[1]; + real_t cross = e0x * e1y - e0y * e1x; + // std::cout << "axes = " << axes[0] << ", " << axes[1] << "\n"; + // std::cout << "e0x, e0y, e1x, e1y " << e0x << ", " << e0y << ", " + // << e1x << ", " << e1y << "\n"; + + real_t area = + (vx[0] * vy[1] - vy[0] * vx[1]) * static_cast(0.5); + // std::cout << "cross " << cross << ", area " << area << "\n"; + // if an internal angle + if (cross * area < static_cast(0.0)) { + // std::cout << "internal \n"; + guess_vert += 1; + // std::cout << "guess vert : " << guess_vert << "\n"; + continue; + } + + // check all other verts in case they are inside this triangle + bool overlap = false; + for (size_t otherVert = 3; otherVert < npolys; ++otherVert) { + size_t idx = (guess_vert + otherVert) % npolys; + + if (idx >= remainingFace.vertex_indices.size()) { + // std::cout << "???0\n"; + // ??? + continue; + } + + size_t ovi = size_t(remainingFace.vertex_indices[idx].v_idx); + + if (((ovi * 3 + axes[0]) >= v.size()) || + ((ovi * 3 + axes[1]) >= v.size())) { + // std::cout << "???1\n"; + // ??? + continue; + } + real_t tx = v[ovi * 3 + axes[0]]; + real_t ty = v[ovi * 3 + axes[1]]; + if (pnpoly(3, vx, vy, tx, ty)) { + // std::cout << "overlap\n"; + overlap = true; + break; + } + } + + if (overlap) { + // std::cout << "overlap2\n"; + guess_vert += 1; + continue; + } + + // this triangle is an ear + { + index_t idx0, idx1, idx2; + idx0.vertex_index = ind[0].v_idx; + idx0.normal_index = ind[0].vn_idx; + idx0.texcoord_index = ind[0].vt_idx; + idx1.vertex_index = ind[1].v_idx; + idx1.normal_index = ind[1].vn_idx; + idx1.texcoord_index = ind[1].vt_idx; + idx2.vertex_index = ind[2].v_idx; + idx2.normal_index = ind[2].vn_idx; + idx2.texcoord_index = ind[2].vt_idx; + + shape->mesh.indices.push_back(idx0); + shape->mesh.indices.push_back(idx1); + shape->mesh.indices.push_back(idx2); + + shape->mesh.num_face_vertices.push_back(3); + shape->mesh.material_ids.push_back(material_id); + shape->mesh.smoothing_group_ids.push_back( + face.smoothing_group_id); + } + + // remove v1 from the list + size_t removed_vert_index = (guess_vert + 1) % npolys; + while (removed_vert_index + 1 < npolys) { + remainingFace.vertex_indices[removed_vert_index] = + remainingFace.vertex_indices[removed_vert_index + 1]; + removed_vert_index += 1; + } + remainingFace.vertex_indices.pop_back(); + } + + // std::cout << "remainingFace.vi.size = " << + // remainingFace.vertex_indices.size() << "\n"; + if (remainingFace.vertex_indices.size() == 3) { + i0 = remainingFace.vertex_indices[0]; + i1 = remainingFace.vertex_indices[1]; + i2 = remainingFace.vertex_indices[2]; + { + index_t idx0, idx1, idx2; + idx0.vertex_index = i0.v_idx; + idx0.normal_index = i0.vn_idx; + idx0.texcoord_index = i0.vt_idx; + idx1.vertex_index = i1.v_idx; + idx1.normal_index = i1.vn_idx; + idx1.texcoord_index = i1.vt_idx; + idx2.vertex_index = i2.v_idx; + idx2.normal_index = i2.vn_idx; + idx2.texcoord_index = i2.vt_idx; + + shape->mesh.indices.push_back(idx0); + shape->mesh.indices.push_back(idx1); + shape->mesh.indices.push_back(idx2); + + shape->mesh.num_face_vertices.push_back(3); + shape->mesh.material_ids.push_back(material_id); + shape->mesh.smoothing_group_ids.push_back( + face.smoothing_group_id); + } + } +#endif + } // npolys + } else { + for (size_t k = 0; k < npolys; k++) { + index_t idx; + idx.vertex_index = face.vertex_indices[k].v_idx; + idx.normal_index = face.vertex_indices[k].vn_idx; + idx.texcoord_index = face.vertex_indices[k].vt_idx; + shape->mesh.indices.push_back(idx); + } + + shape->mesh.num_face_vertices.push_back( + static_cast(npolys)); + shape->mesh.material_ids.push_back(material_id); // per face + shape->mesh.smoothing_group_ids.push_back( + face.smoothing_group_id); // per face + } + } + + shape->mesh.tags = tags; + } + + // line + if (!prim_group.lineGroup.empty()) { + // Flatten indices + for (size_t i = 0; i < prim_group.lineGroup.size(); i++) { + for (size_t j = 0; j < prim_group.lineGroup[i].vertex_indices.size(); + j++) { + const vertex_index_t &vi = prim_group.lineGroup[i].vertex_indices[j]; + + index_t idx; + idx.vertex_index = vi.v_idx; + idx.normal_index = vi.vn_idx; + idx.texcoord_index = vi.vt_idx; + + shape->lines.indices.push_back(idx); + } + + shape->lines.num_line_vertices.push_back( + int(prim_group.lineGroup[i].vertex_indices.size())); + } + } + + // points + if (!prim_group.pointsGroup.empty()) { + // Flatten & convert indices + for (size_t i = 0; i < prim_group.pointsGroup.size(); i++) { + for (size_t j = 0; j < prim_group.pointsGroup[i].vertex_indices.size(); + j++) { + const vertex_index_t &vi = prim_group.pointsGroup[i].vertex_indices[j]; + + index_t idx; + idx.vertex_index = vi.v_idx; + idx.normal_index = vi.vn_idx; + idx.texcoord_index = vi.vt_idx; + + shape->points.indices.push_back(idx); + } + } + } + + return true; +} + +// Split a string with specified delimiter character and escape character. +// https://rosettacode.org/wiki/Tokenize_a_string_with_escaping#C.2B.2B +static void SplitString(const std::string &s, char delim, char escape, + std::vector &elems) { + std::string token; + + bool escaping = false; + for (size_t i = 0; i < s.size(); ++i) { + char ch = s[i]; + if (escaping) { + escaping = false; + } else if (ch == escape) { + escaping = true; + continue; + } else if (ch == delim) { + if (!token.empty()) { + elems.push_back(token); + } + token.clear(); + continue; + } + token += ch; + } + + elems.push_back(token); +} + +static std::string JoinPath(const std::string &dir, + const std::string &filename) { + if (dir.empty()) { + return filename; + } else { + // check '/' + char lastChar = *dir.rbegin(); + if (lastChar != '/') { + return dir + std::string("/") + filename; + } else { + return dir + filename; + } + } +} + +void LoadMtl(std::map *material_map, + std::vector *materials, std::istream *inStream, + std::string *warning, std::string *err) { + (void)err; + + // Create a default material anyway. + material_t material; + InitMaterial(&material); + + // Issue 43. `d` wins against `Tr` since `Tr` is not in the MTL specification. + bool has_d = false; + bool has_tr = false; + + // has_kd is used to set a default diffuse value when map_Kd is present + // and Kd is not. + bool has_kd = false; + + std::stringstream warn_ss; + + size_t line_no = 0; + std::string linebuf; + while (inStream->peek() != -1) { + safeGetline(*inStream, linebuf); + line_no++; + + // Trim trailing whitespace. + if (linebuf.size() > 0) { + linebuf = linebuf.substr(0, linebuf.find_last_not_of(" \t") + 1); + } + + // Trim newline '\r\n' or '\n' + if (linebuf.size() > 0) { + if (linebuf[linebuf.size() - 1] == '\n') + linebuf.erase(linebuf.size() - 1); + } + if (linebuf.size() > 0) { + if (linebuf[linebuf.size() - 1] == '\r') + linebuf.erase(linebuf.size() - 1); + } + + // Skip if empty line. + if (linebuf.empty()) { + continue; + } + + // Skip leading space. + const char *token = linebuf.c_str(); + token += strspn(token, " \t"); + + assert(token); + if (token[0] == '\0') continue; // empty line + + if (token[0] == '#') continue; // comment line + + // new mtl + if ((0 == strncmp(token, "newmtl", 6)) && IS_SPACE((token[6]))) { + // flush previous material. + if (!material.name.empty()) { + material_map->insert(std::pair( + material.name, static_cast(materials->size()))); + materials->push_back(material); + } + + // initial temporary material + InitMaterial(&material); + + has_d = false; + has_tr = false; + + // set new mtl name + token += 7; + { + std::string namebuf = parseString(&token); + // TODO: empty name check? + if (namebuf.empty()) { + if (warning) { + (*warning) += "empty material name in `newmtl`\n"; + } + } + material.name = namebuf; + } + continue; + } + + // ambient + if (token[0] == 'K' && token[1] == 'a' && IS_SPACE((token[2]))) { + token += 2; + real_t r, g, b; + parseReal3(&r, &g, &b, &token); + material.ambient[0] = r; + material.ambient[1] = g; + material.ambient[2] = b; + continue; + } + + // diffuse + if (token[0] == 'K' && token[1] == 'd' && IS_SPACE((token[2]))) { + token += 2; + real_t r, g, b; + parseReal3(&r, &g, &b, &token); + material.diffuse[0] = r; + material.diffuse[1] = g; + material.diffuse[2] = b; + has_kd = true; + continue; + } + + // specular + if (token[0] == 'K' && token[1] == 's' && IS_SPACE((token[2]))) { + token += 2; + real_t r, g, b; + parseReal3(&r, &g, &b, &token); + material.specular[0] = r; + material.specular[1] = g; + material.specular[2] = b; + continue; + } + + // transmittance + if ((token[0] == 'K' && token[1] == 't' && IS_SPACE((token[2]))) || + (token[0] == 'T' && token[1] == 'f' && IS_SPACE((token[2])))) { + token += 2; + real_t r, g, b; + parseReal3(&r, &g, &b, &token); + material.transmittance[0] = r; + material.transmittance[1] = g; + material.transmittance[2] = b; + continue; + } + + // ior(index of refraction) + if (token[0] == 'N' && token[1] == 'i' && IS_SPACE((token[2]))) { + token += 2; + material.ior = parseReal(&token); + continue; + } + + // emission + if (token[0] == 'K' && token[1] == 'e' && IS_SPACE(token[2])) { + token += 2; + real_t r, g, b; + parseReal3(&r, &g, &b, &token); + material.emission[0] = r; + material.emission[1] = g; + material.emission[2] = b; + continue; + } + + // shininess + if (token[0] == 'N' && token[1] == 's' && IS_SPACE(token[2])) { + token += 2; + material.shininess = parseReal(&token); + continue; + } + + // illum model + if (0 == strncmp(token, "illum", 5) && IS_SPACE(token[5])) { + token += 6; + material.illum = parseInt(&token); + continue; + } + + // dissolve + if ((token[0] == 'd' && IS_SPACE(token[1]))) { + token += 1; + material.dissolve = parseReal(&token); + + if (has_tr) { + warn_ss << "Both `d` and `Tr` parameters defined for \"" + << material.name + << "\". Use the value of `d` for dissolve (line " << line_no + << " in .mtl.)\n"; + } + has_d = true; + continue; + } + if (token[0] == 'T' && token[1] == 'r' && IS_SPACE(token[2])) { + token += 2; + if (has_d) { + // `d` wins. Ignore `Tr` value. + warn_ss << "Both `d` and `Tr` parameters defined for \"" + << material.name + << "\". Use the value of `d` for dissolve (line " << line_no + << " in .mtl.)\n"; + } else { + // We invert value of Tr(assume Tr is in range [0, 1]) + // NOTE: Interpretation of Tr is application(exporter) dependent. For + // some application(e.g. 3ds max obj exporter), Tr = d(Issue 43) + material.dissolve = static_cast(1.0) - parseReal(&token); + } + has_tr = true; + continue; + } + + // PBR: roughness + if (token[0] == 'P' && token[1] == 'r' && IS_SPACE(token[2])) { + token += 2; + material.roughness = parseReal(&token); + continue; + } + + // PBR: metallic + if (token[0] == 'P' && token[1] == 'm' && IS_SPACE(token[2])) { + token += 2; + material.metallic = parseReal(&token); + continue; + } + + // PBR: sheen + if (token[0] == 'P' && token[1] == 's' && IS_SPACE(token[2])) { + token += 2; + material.sheen = parseReal(&token); + continue; + } + + // PBR: clearcoat thickness + if (token[0] == 'P' && token[1] == 'c' && IS_SPACE(token[2])) { + token += 2; + material.clearcoat_thickness = parseReal(&token); + continue; + } + + // PBR: clearcoat roughness + if ((0 == strncmp(token, "Pcr", 3)) && IS_SPACE(token[3])) { + token += 4; + material.clearcoat_roughness = parseReal(&token); + continue; + } + + // PBR: anisotropy + if ((0 == strncmp(token, "aniso", 5)) && IS_SPACE(token[5])) { + token += 6; + material.anisotropy = parseReal(&token); + continue; + } + + // PBR: anisotropy rotation + if ((0 == strncmp(token, "anisor", 6)) && IS_SPACE(token[6])) { + token += 7; + material.anisotropy_rotation = parseReal(&token); + continue; + } + + // ambient or ambient occlusion texture + if ((0 == strncmp(token, "map_Ka", 6)) && IS_SPACE(token[6])) { + token += 7; + ParseTextureNameAndOption(&(material.ambient_texname), + &(material.ambient_texopt), token); + continue; + } + + // diffuse texture + if ((0 == strncmp(token, "map_Kd", 6)) && IS_SPACE(token[6])) { + token += 7; + ParseTextureNameAndOption(&(material.diffuse_texname), + &(material.diffuse_texopt), token); + + // Set a decent diffuse default value if a diffuse texture is specified + // without a matching Kd value. + if (!has_kd) { + material.diffuse[0] = static_cast(0.6); + material.diffuse[1] = static_cast(0.6); + material.diffuse[2] = static_cast(0.6); + } + + continue; + } + + // specular texture + if ((0 == strncmp(token, "map_Ks", 6)) && IS_SPACE(token[6])) { + token += 7; + ParseTextureNameAndOption(&(material.specular_texname), + &(material.specular_texopt), token); + continue; + } + + // specular highlight texture + if ((0 == strncmp(token, "map_Ns", 6)) && IS_SPACE(token[6])) { + token += 7; + ParseTextureNameAndOption(&(material.specular_highlight_texname), + &(material.specular_highlight_texopt), token); + continue; + } + + // bump texture + if (((0 == strncmp(token, "map_bump", 8)) || + (0 == strncmp(token, "map_Bump", 8))) && + IS_SPACE(token[8])) { + token += 9; + ParseTextureNameAndOption(&(material.bump_texname), + &(material.bump_texopt), token); + continue; + } + + // bump texture + if ((0 == strncmp(token, "bump", 4)) && IS_SPACE(token[4])) { + token += 5; + ParseTextureNameAndOption(&(material.bump_texname), + &(material.bump_texopt), token); + continue; + } + + // alpha texture + if ((0 == strncmp(token, "map_d", 5)) && IS_SPACE(token[5])) { + token += 6; + material.alpha_texname = token; + ParseTextureNameAndOption(&(material.alpha_texname), + &(material.alpha_texopt), token); + continue; + } + + // displacement texture + if (((0 == strncmp(token, "map_disp", 8)) || + (0 == strncmp(token, "map_Disp", 8))) && + IS_SPACE(token[8])) { + token += 9; + ParseTextureNameAndOption(&(material.displacement_texname), + &(material.displacement_texopt), token); + continue; + } + + // displacement texture + if ((0 == strncmp(token, "disp", 4)) && IS_SPACE(token[4])) { + token += 5; + ParseTextureNameAndOption(&(material.displacement_texname), + &(material.displacement_texopt), token); + continue; + } + + // reflection map + if ((0 == strncmp(token, "refl", 4)) && IS_SPACE(token[4])) { + token += 5; + ParseTextureNameAndOption(&(material.reflection_texname), + &(material.reflection_texopt), token); + continue; + } + + // PBR: roughness texture + if ((0 == strncmp(token, "map_Pr", 6)) && IS_SPACE(token[6])) { + token += 7; + ParseTextureNameAndOption(&(material.roughness_texname), + &(material.roughness_texopt), token); + continue; + } + + // PBR: metallic texture + if ((0 == strncmp(token, "map_Pm", 6)) && IS_SPACE(token[6])) { + token += 7; + ParseTextureNameAndOption(&(material.metallic_texname), + &(material.metallic_texopt), token); + continue; + } + + // PBR: sheen texture + if ((0 == strncmp(token, "map_Ps", 6)) && IS_SPACE(token[6])) { + token += 7; + ParseTextureNameAndOption(&(material.sheen_texname), + &(material.sheen_texopt), token); + continue; + } + + // PBR: emissive texture + if ((0 == strncmp(token, "map_Ke", 6)) && IS_SPACE(token[6])) { + token += 7; + ParseTextureNameAndOption(&(material.emissive_texname), + &(material.emissive_texopt), token); + continue; + } + + // PBR: normal map texture + if ((0 == strncmp(token, "norm", 4)) && IS_SPACE(token[4])) { + token += 5; + ParseTextureNameAndOption(&(material.normal_texname), + &(material.normal_texopt), token); + continue; + } + + // unknown parameter + const char *_space = strchr(token, ' '); + if (!_space) { + _space = strchr(token, '\t'); + } + if (_space) { + std::ptrdiff_t len = _space - token; + std::string key(token, static_cast(len)); + std::string value = _space + 1; + material.unknown_parameter.insert( + std::pair(key, value)); + } + } + // flush last material. + material_map->insert(std::pair( + material.name, static_cast(materials->size()))); + materials->push_back(material); + + if (warning) { + (*warning) = warn_ss.str(); + } +} + +bool MaterialFileReader::operator()(const std::string &matId, + std::vector *materials, + std::map *matMap, + std::string *warn, std::string *err) { + if (!m_mtlBaseDir.empty()) { +#ifdef _WIN32 + char sep = ';'; +#else + char sep = ':'; +#endif + + // https://stackoverflow.com/questions/5167625/splitting-a-c-stdstring-using-tokens-e-g + std::vector paths; + std::istringstream f(m_mtlBaseDir); + + std::string s; + while (getline(f, s, sep)) { + paths.push_back(s); + } + + for (size_t i = 0; i < paths.size(); i++) { + std::string filepath = JoinPath(paths[i], matId); + + std::ifstream matIStream(filepath.c_str()); + if (matIStream) { + LoadMtl(matMap, materials, &matIStream, warn, err); + + return true; + } + } + + std::stringstream ss; + ss << "Material file [ " << matId + << " ] not found in a path : " << m_mtlBaseDir << "\n"; + if (warn) { + (*warn) += ss.str(); + } + return false; + + } else { + std::string filepath = matId; + std::ifstream matIStream(filepath.c_str()); + if (matIStream) { + LoadMtl(matMap, materials, &matIStream, warn, err); + + return true; + } + + std::stringstream ss; + ss << "Material file [ " << filepath + << " ] not found in a path : " << m_mtlBaseDir << "\n"; + if (warn) { + (*warn) += ss.str(); + } + + return false; + } +} + +bool MaterialStreamReader::operator()(const std::string &matId, + std::vector *materials, + std::map *matMap, + std::string *warn, std::string *err) { + (void)err; + (void)matId; + if (!m_inStream) { + std::stringstream ss; + ss << "Material stream in error state. \n"; + if (warn) { + (*warn) += ss.str(); + } + return false; + } + + LoadMtl(matMap, materials, &m_inStream, warn, err); + + return true; +} + +bool LoadObj(attrib_t *attrib, std::vector *shapes, + std::vector *materials, std::string *warn, + std::string *err, const char *filename, const char *mtl_basedir, + bool triangulate, bool default_vcols_fallback) { + attrib->vertices.clear(); + attrib->normals.clear(); + attrib->texcoords.clear(); + attrib->colors.clear(); + shapes->clear(); + + std::stringstream errss; + + std::ifstream ifs(filename); + if (!ifs) { + errss << "Cannot open file [" << filename << "]\n"; + if (err) { + (*err) = errss.str(); + } + return false; + } + + std::string baseDir = mtl_basedir ? mtl_basedir : ""; + if (!baseDir.empty()) { +#ifndef _WIN32 + const char dirsep = '/'; +#else + const char dirsep = '\\'; +#endif + if (baseDir[baseDir.length() - 1] != dirsep) baseDir += dirsep; + } + MaterialFileReader matFileReader(baseDir); + + return LoadObj(attrib, shapes, materials, warn, err, &ifs, &matFileReader, + triangulate, default_vcols_fallback); +} + +bool LoadObj(attrib_t *attrib, std::vector *shapes, + std::vector *materials, std::string *warn, + std::string *err, std::istream *inStream, + MaterialReader *readMatFn /*= NULL*/, bool triangulate, + bool default_vcols_fallback) { + std::stringstream errss; + + std::vector v; + std::vector vertex_weights; // optional [w] component in `v` + std::vector vn; + std::vector vt; + std::vector vc; + std::vector vw; // tinyobj extension: vertex skin weights + std::vector tags; + PrimGroup prim_group; + std::string name; + + // material + std::set material_filenames; + std::map material_map; + int material = -1; + + // smoothing group id + unsigned int current_smoothing_id = + 0; // Initial value. 0 means no smoothing. + + int greatest_v_idx = -1; + int greatest_vn_idx = -1; + int greatest_vt_idx = -1; + + shape_t shape; + + bool found_all_colors = true; // check if all 'v' line has color info + + size_t line_num = 0; + std::string linebuf; + while (inStream->peek() != -1) { + safeGetline(*inStream, linebuf); + + line_num++; + + // Trim newline '\r\n' or '\n' + if (linebuf.size() > 0) { + if (linebuf[linebuf.size() - 1] == '\n') + linebuf.erase(linebuf.size() - 1); + } + if (linebuf.size() > 0) { + if (linebuf[linebuf.size() - 1] == '\r') + linebuf.erase(linebuf.size() - 1); + } + + // Skip if empty line. + if (linebuf.empty()) { + continue; + } + + // Skip leading space. + const char *token = linebuf.c_str(); + token += strspn(token, " \t"); + + assert(token); + if (token[0] == '\0') continue; // empty line + + if (token[0] == '#') continue; // comment line + + // vertex + if (token[0] == 'v' && IS_SPACE((token[1]))) { + token += 2; + real_t x, y, z; + real_t r, g, b; + + int num_components = parseVertexWithColor(&x, &y, &z, &r, &g, &b, &token); + found_all_colors &= (num_components == 6); + + v.push_back(x); + v.push_back(y); + v.push_back(z); + + vertex_weights.push_back( + r); // r = w, and initialized to 1.0 when `w` component is not found. + + if ((num_components == 6) || default_vcols_fallback) { + vc.push_back(r); + vc.push_back(g); + vc.push_back(b); + } + + continue; + } + + // normal + if (token[0] == 'v' && token[1] == 'n' && IS_SPACE((token[2]))) { + token += 3; + real_t x, y, z; + parseReal3(&x, &y, &z, &token); + vn.push_back(x); + vn.push_back(y); + vn.push_back(z); + continue; + } + + // texcoord + if (token[0] == 'v' && token[1] == 't' && IS_SPACE((token[2]))) { + token += 3; + real_t x, y; + parseReal2(&x, &y, &token); + vt.push_back(x); + vt.push_back(y); + continue; + } + + // skin weight. tinyobj extension + if (token[0] == 'v' && token[1] == 'w' && IS_SPACE((token[2]))) { + token += 3; + + // vw ... + // example: + // vw 0 0 0.25 1 0.25 2 0.5 + + // TODO(syoyo): Add syntax check + int vid = 0; + vid = parseInt(&token); + + skin_weight_t sw; + + sw.vertex_id = vid; + + while (!IS_NEW_LINE(token[0])) { + real_t j, w; + // joint_id should not be negative, weight may be negative + // TODO(syoyo): # of elements check + parseReal2(&j, &w, &token, -1.0); + + if (j < static_cast(0)) { + if (err) { + std::stringstream ss; + ss << "Failed parse `vw' line. joint_id is negative. " + "line " + << line_num << ".)\n"; + (*err) += ss.str(); + } + return false; + } + + joint_and_weight_t jw; + + jw.joint_id = int(j); + jw.weight = w; + + sw.weightValues.push_back(jw); + + size_t n = strspn(token, " \t\r"); + token += n; + } + + vw.push_back(sw); + } + + warning_context context; + context.warn = warn; + context.line_number = line_num; + + // line + if (token[0] == 'l' && IS_SPACE((token[1]))) { + token += 2; + + __line_t line; + + while (!IS_NEW_LINE(token[0])) { + vertex_index_t vi; + if (!parseTriple(&token, static_cast(v.size() / 3), + static_cast(vn.size() / 3), + static_cast(vt.size() / 2), &vi, context)) { + if (err) { + (*err) += + "Failed to parse `l' line (e.g. a zero value for vertex index. " + "Line " + + toString(line_num) + ").\n"; + } + return false; + } + + line.vertex_indices.push_back(vi); + + size_t n = strspn(token, " \t\r"); + token += n; + } + + prim_group.lineGroup.push_back(line); + + continue; + } + + // points + if (token[0] == 'p' && IS_SPACE((token[1]))) { + token += 2; + + __points_t pts; + + while (!IS_NEW_LINE(token[0])) { + vertex_index_t vi; + if (!parseTriple(&token, static_cast(v.size() / 3), + static_cast(vn.size() / 3), + static_cast(vt.size() / 2), &vi, context)) { + if (err) { + (*err) += + "Failed to parse `p' line (e.g. a zero value for vertex index. " + "Line " + + toString(line_num) + ").\n"; + } + return false; + } + + pts.vertex_indices.push_back(vi); + + size_t n = strspn(token, " \t\r"); + token += n; + } + + prim_group.pointsGroup.push_back(pts); + + continue; + } + + // face + if (token[0] == 'f' && IS_SPACE((token[1]))) { + token += 2; + token += strspn(token, " \t"); + + face_t face; + + face.smoothing_group_id = current_smoothing_id; + face.vertex_indices.reserve(3); + + while (!IS_NEW_LINE(token[0])) { + vertex_index_t vi; + if (!parseTriple(&token, static_cast(v.size() / 3), + static_cast(vn.size() / 3), + static_cast(vt.size() / 2), &vi, context)) { + if (err) { + (*err) += + "Failed to parse `f' line (e.g. a zero value for vertex index " + "or invalid relative vertex index). Line " + + toString(line_num) + ").\n"; + } + return false; + } + + greatest_v_idx = greatest_v_idx > vi.v_idx ? greatest_v_idx : vi.v_idx; + greatest_vn_idx = + greatest_vn_idx > vi.vn_idx ? greatest_vn_idx : vi.vn_idx; + greatest_vt_idx = + greatest_vt_idx > vi.vt_idx ? greatest_vt_idx : vi.vt_idx; + + face.vertex_indices.push_back(vi); + size_t n = strspn(token, " \t\r"); + token += n; + } + + // replace with emplace_back + std::move on C++11 + prim_group.faceGroup.push_back(face); + + continue; + } + + // use mtl + if ((0 == strncmp(token, "usemtl", 6))) { + token += 6; + std::string namebuf = parseString(&token); + + int newMaterialId = -1; + std::map::const_iterator it = + material_map.find(namebuf); + if (it != material_map.end()) { + newMaterialId = it->second; + } else { + // { error!! material not found } + if (warn) { + (*warn) += "material [ '" + namebuf + "' ] not found in .mtl\n"; + } + } + + if (newMaterialId != material) { + // Create per-face material. Thus we don't add `shape` to `shapes` at + // this time. + // just clear `faceGroup` after `exportGroupsToShape()` call. + exportGroupsToShape(&shape, prim_group, tags, material, name, + triangulate, v, warn); + prim_group.faceGroup.clear(); + material = newMaterialId; + } + + continue; + } + + // load mtl + if ((0 == strncmp(token, "mtllib", 6)) && IS_SPACE((token[6]))) { + if (readMatFn) { + token += 7; + + std::vector filenames; + SplitString(std::string(token), ' ', '\\', filenames); + + if (filenames.empty()) { + if (warn) { + std::stringstream ss; + ss << "Looks like empty filename for mtllib. Use default " + "material (line " + << line_num << ".)\n"; + + (*warn) += ss.str(); + } + } else { + bool found = false; + for (size_t s = 0; s < filenames.size(); s++) { + if (material_filenames.count(filenames[s]) > 0) { + found = true; + continue; + } + + std::string warn_mtl; + std::string err_mtl; + bool ok = (*readMatFn)(filenames[s].c_str(), materials, + &material_map, &warn_mtl, &err_mtl); + if (warn && (!warn_mtl.empty())) { + (*warn) += warn_mtl; + } + + if (err && (!err_mtl.empty())) { + (*err) += err_mtl; + } + + if (ok) { + found = true; + material_filenames.insert(filenames[s]); + break; + } + } + + if (!found) { + if (warn) { + (*warn) += + "Failed to load material file(s). Use default " + "material.\n"; + } + } + } + } + + continue; + } + + // group name + if (token[0] == 'g' && IS_SPACE((token[1]))) { + // flush previous face group. + bool ret = exportGroupsToShape(&shape, prim_group, tags, material, name, + triangulate, v, warn); + (void)ret; // return value not used. + + if (shape.mesh.indices.size() > 0) { + shapes->push_back(shape); + } + + shape = shape_t(); + + // material = -1; + prim_group.clear(); + + std::vector names; + + while (!IS_NEW_LINE(token[0])) { + std::string str = parseString(&token); + names.push_back(str); + token += strspn(token, " \t\r"); // skip tag + } + + // names[0] must be 'g' + + if (names.size() < 2) { + // 'g' with empty names + if (warn) { + std::stringstream ss; + ss << "Empty group name. line: " << line_num << "\n"; + (*warn) += ss.str(); + name = ""; + } + } else { + std::stringstream ss; + ss << names[1]; + + // tinyobjloader does not support multiple groups for a primitive. + // Currently we concatinate multiple group names with a space to get + // single group name. + + for (size_t i = 2; i < names.size(); i++) { + ss << " " << names[i]; + } + + name = ss.str(); + } + + continue; + } + + // object name + if (token[0] == 'o' && IS_SPACE((token[1]))) { + // flush previous face group. + bool ret = exportGroupsToShape(&shape, prim_group, tags, material, name, + triangulate, v, warn); + (void)ret; // return value not used. + + if (shape.mesh.indices.size() > 0 || shape.lines.indices.size() > 0 || + shape.points.indices.size() > 0) { + shapes->push_back(shape); + } + + // material = -1; + prim_group.clear(); + shape = shape_t(); + + // @todo { multiple object name? } + token += 2; + std::stringstream ss; + ss << token; + name = ss.str(); + + continue; + } + + if (token[0] == 't' && IS_SPACE(token[1])) { + const int max_tag_nums = 8192; // FIXME(syoyo): Parameterize. + tag_t tag; + + token += 2; + + tag.name = parseString(&token); + + tag_sizes ts = parseTagTriple(&token); + + if (ts.num_ints < 0) { + ts.num_ints = 0; + } + if (ts.num_ints > max_tag_nums) { + ts.num_ints = max_tag_nums; + } + + if (ts.num_reals < 0) { + ts.num_reals = 0; + } + if (ts.num_reals > max_tag_nums) { + ts.num_reals = max_tag_nums; + } + + if (ts.num_strings < 0) { + ts.num_strings = 0; + } + if (ts.num_strings > max_tag_nums) { + ts.num_strings = max_tag_nums; + } + + tag.intValues.resize(static_cast(ts.num_ints)); + + for (size_t i = 0; i < static_cast(ts.num_ints); ++i) { + tag.intValues[i] = parseInt(&token); + } + + tag.floatValues.resize(static_cast(ts.num_reals)); + for (size_t i = 0; i < static_cast(ts.num_reals); ++i) { + tag.floatValues[i] = parseReal(&token); + } + + tag.stringValues.resize(static_cast(ts.num_strings)); + for (size_t i = 0; i < static_cast(ts.num_strings); ++i) { + tag.stringValues[i] = parseString(&token); + } + + tags.push_back(tag); + + continue; + } + + if (token[0] == 's' && IS_SPACE(token[1])) { + // smoothing group id + token += 2; + + // skip space. + token += strspn(token, " \t"); // skip space + + if (token[0] == '\0') { + continue; + } + + if (token[0] == '\r' || token[1] == '\n') { + continue; + } + + if (strlen(token) >= 3 && token[0] == 'o' && token[1] == 'f' && + token[2] == 'f') { + current_smoothing_id = 0; + } else { + // assume number + int smGroupId = parseInt(&token); + if (smGroupId < 0) { + // parse error. force set to 0. + // FIXME(syoyo): Report warning. + current_smoothing_id = 0; + } else { + current_smoothing_id = static_cast(smGroupId); + } + } + + continue; + } // smoothing group id + + // Ignore unknown command. + } + + // not all vertices have colors, no default colors desired? -> clear colors + if (!found_all_colors && !default_vcols_fallback) { + vc.clear(); + } + + if (greatest_v_idx >= static_cast(v.size() / 3)) { + if (warn) { + std::stringstream ss; + ss << "Vertex indices out of bounds (line " << line_num << ".)\n\n"; + (*warn) += ss.str(); + } + } + if (greatest_vn_idx >= static_cast(vn.size() / 3)) { + if (warn) { + std::stringstream ss; + ss << "Vertex normal indices out of bounds (line " << line_num + << ".)\n\n"; + (*warn) += ss.str(); + } + } + if (greatest_vt_idx >= static_cast(vt.size() / 2)) { + if (warn) { + std::stringstream ss; + ss << "Vertex texcoord indices out of bounds (line " << line_num + << ".)\n\n"; + (*warn) += ss.str(); + } + } + + bool ret = exportGroupsToShape(&shape, prim_group, tags, material, name, + triangulate, v, warn); + // exportGroupsToShape return false when `usemtl` is called in the last + // line. + // we also add `shape` to `shapes` when `shape.mesh` has already some + // faces(indices) + if (ret || shape.mesh.indices + .size()) { // FIXME(syoyo): Support other prims(e.g. lines) + shapes->push_back(shape); + } + prim_group.clear(); // for safety + + if (err) { + (*err) += errss.str(); + } + + attrib->vertices.swap(v); + attrib->vertex_weights.swap(vertex_weights); + attrib->normals.swap(vn); + attrib->texcoords.swap(vt); + attrib->texcoord_ws.swap(vt); + attrib->colors.swap(vc); + attrib->skin_weights.swap(vw); + + return true; +} + +bool LoadObjWithCallback(std::istream &inStream, const callback_t &callback, + void *user_data /*= NULL*/, + MaterialReader *readMatFn /*= NULL*/, + std::string *warn, /* = NULL*/ + std::string *err /*= NULL*/) { + std::stringstream errss; + + // material + std::set material_filenames; + std::map material_map; + int material_id = -1; // -1 = invalid + + std::vector indices; + std::vector materials; + std::vector names; + names.reserve(2); + std::vector names_out; + + std::string linebuf; + while (inStream.peek() != -1) { + safeGetline(inStream, linebuf); + + // Trim newline '\r\n' or '\n' + if (linebuf.size() > 0) { + if (linebuf[linebuf.size() - 1] == '\n') + linebuf.erase(linebuf.size() - 1); + } + if (linebuf.size() > 0) { + if (linebuf[linebuf.size() - 1] == '\r') + linebuf.erase(linebuf.size() - 1); + } + + // Skip if empty line. + if (linebuf.empty()) { + continue; + } + + // Skip leading space. + const char *token = linebuf.c_str(); + token += strspn(token, " \t"); + + assert(token); + if (token[0] == '\0') continue; // empty line + + if (token[0] == '#') continue; // comment line + + // vertex + if (token[0] == 'v' && IS_SPACE((token[1]))) { + token += 2; + real_t x, y, z; + real_t r, g, b; + + int num_components = parseVertexWithColor(&x, &y, &z, &r, &g, &b, &token); + if (callback.vertex_cb) { + callback.vertex_cb(user_data, x, y, z, r); // r=w is optional + } + if (callback.vertex_color_cb) { + bool found_color = (num_components == 6); + callback.vertex_color_cb(user_data, x, y, z, r, g, b, found_color); + } + continue; + } + + // normal + if (token[0] == 'v' && token[1] == 'n' && IS_SPACE((token[2]))) { + token += 3; + real_t x, y, z; + parseReal3(&x, &y, &z, &token); + if (callback.normal_cb) { + callback.normal_cb(user_data, x, y, z); + } + continue; + } + + // texcoord + if (token[0] == 'v' && token[1] == 't' && IS_SPACE((token[2]))) { + token += 3; + real_t x, y, z; // y and z are optional. default = 0.0 + parseReal3(&x, &y, &z, &token); + if (callback.texcoord_cb) { + callback.texcoord_cb(user_data, x, y, z); + } + continue; + } + + // face + if (token[0] == 'f' && IS_SPACE((token[1]))) { + token += 2; + token += strspn(token, " \t"); + + indices.clear(); + while (!IS_NEW_LINE(token[0])) { + vertex_index_t vi = parseRawTriple(&token); + + index_t idx; + idx.vertex_index = vi.v_idx; + idx.normal_index = vi.vn_idx; + idx.texcoord_index = vi.vt_idx; + + indices.push_back(idx); + size_t n = strspn(token, " \t\r"); + token += n; + } + + if (callback.index_cb && indices.size() > 0) { + callback.index_cb(user_data, &indices.at(0), + static_cast(indices.size())); + } + + continue; + } + + // use mtl + if ((0 == strncmp(token, "usemtl", 6)) && IS_SPACE((token[6]))) { + token += 7; + std::stringstream ss; + ss << token; + std::string namebuf = ss.str(); + + int newMaterialId = -1; + std::map::const_iterator it = + material_map.find(namebuf); + if (it != material_map.end()) { + newMaterialId = it->second; + } else { + // { warn!! material not found } + if (warn && (!callback.usemtl_cb)) { + (*warn) += "material [ " + namebuf + " ] not found in .mtl\n"; + } + } + + if (newMaterialId != material_id) { + material_id = newMaterialId; + } + + if (callback.usemtl_cb) { + callback.usemtl_cb(user_data, namebuf.c_str(), material_id); + } + + continue; + } + + // load mtl + if ((0 == strncmp(token, "mtllib", 6)) && IS_SPACE((token[6]))) { + if (readMatFn) { + token += 7; + + std::vector filenames; + SplitString(std::string(token), ' ', '\\', filenames); + + if (filenames.empty()) { + if (warn) { + (*warn) += + "Looks like empty filename for mtllib. Use default " + "material. \n"; + } + } else { + bool found = false; + for (size_t s = 0; s < filenames.size(); s++) { + if (material_filenames.count(filenames[s]) > 0) { + found = true; + continue; + } + + std::string warn_mtl; + std::string err_mtl; + bool ok = (*readMatFn)(filenames[s].c_str(), &materials, + &material_map, &warn_mtl, &err_mtl); + + if (warn && (!warn_mtl.empty())) { + (*warn) += warn_mtl; // This should be warn message. + } + + if (err && (!err_mtl.empty())) { + (*err) += err_mtl; + } + + if (ok) { + found = true; + material_filenames.insert(filenames[s]); + break; + } + } + + if (!found) { + if (warn) { + (*warn) += + "Failed to load material file(s). Use default " + "material.\n"; + } + } else { + if (callback.mtllib_cb) { + callback.mtllib_cb(user_data, &materials.at(0), + static_cast(materials.size())); + } + } + } + } + + continue; + } + + // group name + if (token[0] == 'g' && IS_SPACE((token[1]))) { + names.clear(); + + while (!IS_NEW_LINE(token[0])) { + std::string str = parseString(&token); + names.push_back(str); + token += strspn(token, " \t\r"); // skip tag + } + + assert(names.size() > 0); + + if (callback.group_cb) { + if (names.size() > 1) { + // create const char* array. + names_out.resize(names.size() - 1); + for (size_t j = 0; j < names_out.size(); j++) { + names_out[j] = names[j + 1].c_str(); + } + callback.group_cb(user_data, &names_out.at(0), + static_cast(names_out.size())); + + } else { + callback.group_cb(user_data, NULL, 0); + } + } + + continue; + } + + // object name + if (token[0] == 'o' && IS_SPACE((token[1]))) { + // @todo { multiple object name? } + token += 2; + + std::stringstream ss; + ss << token; + std::string object_name = ss.str(); + + if (callback.object_cb) { + callback.object_cb(user_data, object_name.c_str()); + } + + continue; + } + +#if 0 // @todo + if (token[0] == 't' && IS_SPACE(token[1])) { + tag_t tag; + + token += 2; + std::stringstream ss; + ss << token; + tag.name = ss.str(); + + token += tag.name.size() + 1; + + tag_sizes ts = parseTagTriple(&token); + + tag.intValues.resize(static_cast(ts.num_ints)); + + for (size_t i = 0; i < static_cast(ts.num_ints); ++i) { + tag.intValues[i] = atoi(token); + token += strcspn(token, "/ \t\r") + 1; + } + + tag.floatValues.resize(static_cast(ts.num_reals)); + for (size_t i = 0; i < static_cast(ts.num_reals); ++i) { + tag.floatValues[i] = parseReal(&token); + token += strcspn(token, "/ \t\r") + 1; + } + + tag.stringValues.resize(static_cast(ts.num_strings)); + for (size_t i = 0; i < static_cast(ts.num_strings); ++i) { + std::stringstream ss; + ss << token; + tag.stringValues[i] = ss.str(); + token += tag.stringValues[i].size() + 1; + } + + tags.push_back(tag); + } +#endif + + // Ignore unknown command. + } + + if (err) { + (*err) += errss.str(); + } + + return true; +} + +bool ObjReader::ParseFromFile(const std::string &filename, + const ObjReaderConfig &config) { + std::string mtl_search_path; + + if (config.mtl_search_path.empty()) { + // + // split at last '/'(for unixish system) or '\\'(for windows) to get + // the base directory of .obj file + // + size_t pos = filename.find_last_of("/\\"); + if (pos != std::string::npos) { + mtl_search_path = filename.substr(0, pos); + } + } else { + mtl_search_path = config.mtl_search_path; + } + + valid_ = LoadObj(&attrib_, &shapes_, &materials_, &warning_, &error_, + filename.c_str(), mtl_search_path.c_str(), + config.triangulate, config.vertex_color); + + return valid_; +} + +bool ObjReader::ParseFromString(const std::string &obj_text, + const std::string &mtl_text, + const ObjReaderConfig &config) { + std::stringbuf obj_buf(obj_text); + std::stringbuf mtl_buf(mtl_text); + + std::istream obj_ifs(&obj_buf); + std::istream mtl_ifs(&mtl_buf); + + MaterialStreamReader mtl_ss(mtl_ifs); + + valid_ = LoadObj(&attrib_, &shapes_, &materials_, &warning_, &error_, + &obj_ifs, &mtl_ss, config.triangulate, config.vertex_color); + + return valid_; +} + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif +} // namespace tinyobj + +#endif diff --git a/samples/utility.h b/samples/utility.h new file mode 100644 index 0000000..4b92bb4 --- /dev/null +++ b/samples/utility.h @@ -0,0 +1,118 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "box3d/types.h" + +struct Vector4 +{ + float x, y, z, w; +}; + +struct Matrix4 +{ + Vector4 cx, cy, cz, cw; +}; + +inline Matrix4 MakeMatrix4( const b3Transform& transform, b3Vec3 scale ) +{ + b3Matrix3 m3 = b3MakeMatrixFromQuat( transform.q ); + Matrix4 m = {}; + m.cx = { scale.x * m3.cx.x, scale.x * m3.cx.y, scale.x * m3.cx.z, 0.0f }; + m.cy = { scale.y * m3.cy.x, scale.y * m3.cy.y, scale.y * m3.cy.z, 0.0f }; + m.cz = { scale.z * m3.cz.x, scale.z * m3.cz.y, scale.z * m3.cz.z, 0.0f }; + m.cw = { transform.p.x, transform.p.y, transform.p.z, 1.0f }; + return m; +} + +inline Matrix4 MakeMatrix4( const b3Transform& transform, float scale ) +{ + b3Matrix3 m3 = b3MakeMatrixFromQuat( transform.q ); + Matrix4 m = {}; + m.cx = { scale * m3.cx.x, scale * m3.cx.y, scale * m3.cx.z, 0.0f }; + m.cy = { scale * m3.cy.x, scale * m3.cy.y, scale * m3.cy.z, 0.0f }; + m.cz = { scale * m3.cz.x, scale * m3.cz.y, scale * m3.cz.z, 0.0f }; + m.cw = { transform.p.x, transform.p.y, transform.p.z, 1.0f }; + return m; +} + +inline Vector4 MulMV( const Matrix4& m, Vector4 a ) +{ + Vector4 b; + b.x = m.cx.x * a.x + m.cy.x * a.y + m.cz.x * a.z + m.cw.x * a.w; + b.y = m.cx.y * a.x + m.cy.y * a.y + m.cz.y * a.z + m.cw.y * a.w; + b.z = m.cx.z * a.x + m.cy.z * a.y + m.cz.z * a.z + m.cw.z * a.w; + b.w = m.cx.w * a.x + m.cy.w * a.y + m.cz.w * a.z + m.cw.w * a.w; + return b; +} + +inline Matrix4 MulMM( const Matrix4& a, const Matrix4& b ) +{ + Matrix4 c; + c.cx = MulMV( a, b.cx ); + c.cy = MulMV( a, b.cy ); + c.cz = MulMV( a, b.cz ); + c.cw = MulMV( a, b.cw ); + return c; +} + +struct RGBA8 +{ + uint8_t r, g, b, a; +}; + +inline RGBA8 MakeRGBA8( b3HexColor h, float alpha ) +{ + RGBA8 color; + color.r = ( h >> 16 ) & 0xFF; + color.g = ( h >> 8 ) & 0xFF; + color.b = h & 0xFF; + color.a = uint8_t( 255.0f * alpha + 0.5f ); + return color; +} + +inline RGBA8 MakeRGBA8( b3HexColor h ) +{ + RGBA8 color; + color.r = ( h >> 16 ) & 0xFF; + color.g = ( h >> 8 ) & 0xFF; + color.b = h & 0xFF; + color.a = 0xFF; + return color; +} + +struct RGBAf +{ + float r, g, b, a; +}; + +inline RGBAf MakeRGBAf( b3HexColor h, float alpha ) +{ + RGBAf color; + color.r = ( ( h >> 16 ) & 0xFF ) / 255.0f; + color.g = ( ( h >> 8 ) & 0xFF ) / 255.0f; + color.b = ( h & 0xFF ) / 255.0f; + color.a = alpha; + return color; +} + +inline RGBAf MakeRGBAf( b3HexColor h ) +{ + return MakeRGBAf( h, 1.0f ); +} + +Matrix4 MakeOrthographicMatrix( float left, float right, float bottom, float top, float near, float far ); + +struct Arena +{ + void Create( int byteCount ); + void Destroy(); + + void* Allocate( int byteCount ); + void Clear(); + + char* data; + int capacity; + int index; +}; diff --git a/shaders/common.glsl b/shaders/common.glsl new file mode 100644 index 0000000..4479268 --- /dev/null +++ b/shaders/common.glsl @@ -0,0 +1,80 @@ +// Shared constants and helpers used across deferred and forward fragment shaders. +// Included via the loader's `#include "common.glsl"` directive (no `#version` +// here; the including shader provides it). +// +// All color constants are authored in sRGB (display) space and converted to +// linear at use. Intensities are linear-space scalars. + +vec3 SrgbToLinear(vec3 c) { return pow(c, vec3(2.2)); } +vec3 LinearToSrgb(vec3 c) { return pow(c, vec3(1.0 / 2.2)); } + +vec3 ACESFilm(vec3 x) +{ + float a = 2.51, b = 0.03, c = 2.43, d = 0.59, e = 0.14; + return clamp((x * (a * x + b)) / (x * (c * x + d) + e), 0.0, 1.0); +} + +const vec3 SUN_COLOR_SRGB = vec3(1.00, 0.97, 0.92); +const float SUN_INTENSITY = 0.5; +const vec3 SKY_AMBIENT_SRGB = vec3(0.55, 0.60, 0.68); +const vec3 GROUND_AMBIENT_SRGB = vec3(0.22, 0.20, 0.17); +const float AMBIENT_INTENSITY = 0.4; +const float SPEC_POWER = 32.0; +const float SPEC_SCALE = 0.20; + +const vec3 SKY_ZENITH_SRGB = vec3(0.28, 0.48, 0.78); +const vec3 SKY_HORIZON_SRGB = vec3(0.55, 0.65, 0.78); +const vec3 SKY_GROUND_SRGB = vec3(0.28, 0.25, 0.22); +const vec3 SUN_DISK_SRGB = vec3(1.00, 0.97, 0.85); +const float SUN_DISK_BRIGHT = 8.0; +const vec3 SUN_HALO_SRGB = vec3(1.00, 0.92, 0.78); +const float SUN_HALO_BRIGHT = 0.35; + +const float FOG_DENSITY = 0.002; + +vec3 SkyColor(vec3 rayDir, vec3 sunDir) +{ + float t = clamp(rayDir.y, -1.0, 1.0); + vec3 skySrgb = (t >= 0.0) + ? mix(SKY_HORIZON_SRGB, SKY_ZENITH_SRGB, pow(t, 1.2)) + : mix(SKY_HORIZON_SRGB, SKY_GROUND_SRGB, pow(-t, 0.50)); + vec3 sky = SrgbToLinear(skySrgb); + + float sunCos = max(dot(rayDir, sunDir), 0.0); + sky += SrgbToLinear(SUN_DISK_SRGB) * SUN_DISK_BRIGHT * pow(sunCos, 800.0); + sky += SrgbToLinear(SUN_HALO_SRGB) * SUN_HALO_BRIGHT * pow(sunCos, 8.0); + return sky; +} + +// Hemispheric ambient term for a +Y-up world. N is world-space normal. +vec3 HemisphericAmbient(vec3 N) +{ + float hemi = 0.5 + 0.5 * N.y; + return AMBIENT_INTENSITY * mix(SrgbToLinear(GROUND_AMBIENT_SRGB), + SrgbToLinear(SKY_AMBIENT_SRGB), hemi); +} + +// TPDF (triangular) dither for 8-bit sRGB output. Two independent IGN samples +// give noise in [-1, +1] LSB; converting smooth gradients (sky, fog) from +// hard contour bands into high-frequency texture the eye averages out. Apply +// AFTER LinearToSrgb so quantization happens in display space. +vec3 DitherSrgb(vec3 c, vec2 fragCoord) +{ + const vec2 magic = vec2(0.06711056, 0.00583715); + const float k = 52.9829189; + float r1 = fract(k * fract(dot(fragCoord, magic))); + float r2 = fract(k * fract(dot(fragCoord + 7.0, magic))); + float t = r1 + r2 - 1.0; + return c + vec3(t) * (1.0 / 255.0); +} + +// Anti-aliased 1-pixel-wide world-space grid. uv is the tiled coordinate +// (e.g. worldXZ divided by the desired cell size). Returns ~1.0 on a line, +// ~0.0 in the cell interior; fwidth filtering keeps the line crisp at any +// distance and prevents the grid from aliasing on far receivers. +float WorldGrid(vec2 uv) +{ + vec2 grid = abs(fract(uv - 0.5) - 0.5); + vec2 line = grid / fwidth(uv); + return 1.0 - smoothstep(0.0, 1.5, min(line.x, line.y)); +} diff --git a/shaders/deferred_lighting_fs.glsl b/shaders/deferred_lighting_fs.glsl new file mode 100644 index 0000000..f01ebf1 --- /dev/null +++ b/shaders/deferred_lighting_fs.glsl @@ -0,0 +1,253 @@ +#version 330 core + +#include "common.glsl" + +out vec4 outColor; + +in vec2 TexCoords; + +uniform sampler2D gPosition; // view-space position (xyz=0 for sky) +uniform sampler2D gNormal; // view-space normal +uniform sampler2D gAlbedoSpec; // sRGB albedo, a specular strength +uniform sampler2D ssao; +uniform sampler2DShadow shadowMap; + +uniform mat4 lightSpaceMatrix; +uniform mat4 cameraMatrix; // camera-to-world +uniform float worldTexelSize; // world-space span of one shadow-map texel +uniform float lightZRange; // lightFarPlane - lightNearPlane, in world units + +// Sun + sky +uniform vec3 sunDirWorld; // normalized, points from scene toward sun +uniform float tanHalfFovY; +uniform float aspectRatio; + +uniform bool useSSAO; +uniform bool useShadow; +uniform bool useGrid; +uniform float aoPower; +uniform float aoDirect; +uniform bool aoOnly; + +// Vogel disk (phyllotaxis spiral) sampling. Produces naturally well-distributed +// taps for any sample count, and the rotation phase is just an additive angle +// per tap — no rotation matrix needed. +const float GOLDEN_ANGLE = 2.39996323; +const int PCF_TAP_COUNT = 32; +const float PCF_RADIUS_TEXELS = 3.0; + +float ShadowCalculation(vec4 lightSpacePos, vec3 worldNormal, vec3 worldPos) +{ + vec3 projCoords = lightSpacePos.xyz / lightSpacePos.w; + projCoords = projCoords * 0.5 + 0.5; + + // dFdx/dFdy must run before any early return so neighboring fragments in the + // 2x2 quad always reach this point with valid projCoords values. + vec3 ddxCoords = dFdx(projCoords); + vec3 ddyCoords = dFdy(projCoords); + + if (projCoords.z > 1.0 || projCoords.z < 0.0) return 0.0; + + // Soft-fade near the shadow map boundary so geometry just outside the fitted + // frustum doesn't produce a hard cutoff line. Falls off over the outer 6% + // of the xy range and outer 10% of the depth range. + vec2 edge = min(projCoords.xy, 1.0 - projCoords.xy); + float xyFade = smoothstep(0.0, 0.06, min(edge.x, edge.y)); + float zFade = 1.0 - smoothstep(0.90, 1.0, projCoords.z); + float fade = xyFade * zFade; + if (fade <= 0.0) return 0.0; + + // Receiver-plane depth bias: convert the screen-space gradient of projCoords.z + // into a gradient with respect to shadow-map UV via the inverse Jacobian. + // Each PCF tap then gets the depth the receiver surface would *actually* have + // at that tap's offset, so per-texel acne disappears without lifting shadows + // off contact via a large constant bias. + // + // Silhouette guard: at object edges, dFdx/dFdy mix samples from two unrelated + // surfaces, producing a meaningless gradient that would over-bias the test + // and paint a bright fringe along the silhouette. fwidth flags that case and + // we fall back to a constant bias for those fragments. + vec2 dzduv = vec2(0.0); + // True silhouettes (adjacent pixels on different surfaces) have huge zWidth, + // close to 1.0. Continuous surfaces even at grazing angles stay well below. + float zWidth = abs(ddxCoords.z) + abs(ddyCoords.z); + bool onSilhouette = zWidth > 0.3; + if (!onSilhouette) + { + float det = ddxCoords.x * ddyCoords.y - ddxCoords.y * ddyCoords.x; + if (abs(det) > 1e-8) + { + float invDet = 1.0 / det; + dzduv.x = (ddyCoords.y * ddxCoords.z - ddxCoords.y * ddyCoords.z) * invDet; + dzduv.y = (ddxCoords.x * ddyCoords.z - ddyCoords.x * ddxCoords.z) * invDet; + } + // Clamp loose enough to cover legitimate steep slopes (e.g. surfaces + // nearly aligned with the light direction) but still finite. + dzduv = clamp(dzduv, vec2(-2.0), vec2(2.0)); + } + + vec2 texelSize = 1.0 / textureSize(shadowMap, 0); + + // Adapt PCF kernel radius to the screen pixel's footprint in shadow texels. + // At far view distances each screen pixel covers many shadow texels; a + // fixed 3-texel disk fits *inside* a single pixel, so adjacent pixels see + // nearly the same texel set just rotated differently — that resonates with + // the texel grid into the swirly moire visible on distant flat receivers. + // Growing the kernel with the footprint makes the taps actually average + // over the pixel's shadow-texel coverage, and as a bonus distant shadows + // get the gentle softening they should naturally have. Clamped so very + // distant geometry doesn't blow the kernel up to a useless smear. + float footprintTexels = max(length(ddxCoords.xy), length(ddyCoords.xy)) / texelSize.x; + float radiusTexels = clamp(footprintTexels, PCF_RADIUS_TEXELS, 8.0); + vec2 sampleScale = radiusTexels * texelSize; + + // Hardware bilinear PCF samples a 2x2 texel neighborhood against a single + // refZ, but the four stored depths differ by up to dzduv * 0.5 * texelSize. + // Without absorbing that, half the bilinear neighbors pass and half fail, + // producing the residual banding RPDB alone can't kill. Scaling the bias + // with the receiver slope keeps adjacent texels on the same side of the + // comparison. + float slopeBias = (abs(dzduv.x) + abs(dzduv.y)) * texelSize.x; + // World-unit bias floor: the existing constants are in normalized [0,1] + // light-space depth, but the geometric scale that actually causes acne + // (stacked-brick seams, hull-on-hull contacts) is in world units. A + // 1-world-unit caster spans `1.0 / lightZRange` of normalized depth, so + // any bias smaller than that lets self-shadow bands appear at every + // brick interface. Floor it at ~half a world unit so the bias adapts + // automatically to camera distance (which controls lightZRange). + float minBias = 0.5 / max(lightZRange, 1.0); + float bias = max(minBias, onSilhouette ? 0.003 : (slopeBias + 0.0005)); + + // Per-pixel rotation phase. At extreme grazing angles each screen pixel + // covers many shadow texels and rotation makes adjacent pixels sample + // wildly different texel subsets — that resonates with the texel grid into + // visible moire. Fade rotation out as the receiver becomes foreshortened. + // + // Use Interleaved Gradient Noise (Jimenez 2014) for the angle. The basic + // fract(sin(dot(...))*43758.5453) hash has low-frequency structure that + // shows through as concentric/swirl moire when each screen pixel covers + // many shadow texels (distant view of a flat receiver). IGN was designed + // for shader dithering and decorrelates much better at neighboring pixels. + float rotStrength = 1.0 - smoothstep(0.05, 0.20, zWidth); + float ign = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))); + float phi = ign * 6.2831853 * rotStrength; + + // Vogel-disk PCF: each tap is one rotation step further around the golden- + // angle spiral, with radius growing as sqrt(i/N) so density is uniform + // across the disk. sampler2DShadow + GL_LEQUAL returns 1.0 when refZ <= + // storedDepth (lit), with hardware bilinear PCF inside each tap thanks to + // GL_LINEAR filtering on the depth texture. + float lit = 0.0; + float invN = 1.0 / float(PCF_TAP_COUNT); + for (int i = 0; i < PCF_TAP_COUNT; ++i) + { + float r = sqrt((float(i) + 0.5) * invN); + float theta = float(i) * GOLDEN_ANGLE + phi; + vec2 offset = vec2(cos(theta), sin(theta)) * r * sampleScale; + float refZ = projCoords.z + dot(dzduv, offset) - bias; + lit += texture(shadowMap, vec3(projCoords.xy + offset, refZ)); + } + return (1.0 - lit * invN) * fade; +} + +void main() +{ + vec2 ndc = TexCoords * 2.0 - 1.0; + vec3 camRight = cameraMatrix[0].xyz; + vec3 camUp = cameraMatrix[1].xyz; + vec3 camForward = -cameraMatrix[2].xyz; + vec3 viewDirWorld = normalize( + camForward + + ndc.x * tanHalfFovY * aspectRatio * camRight + + ndc.y * tanHalfFovY * camUp + ); + + vec3 viewPos = texture(gPosition, TexCoords).rgb; + vec3 viewNormal = texture(gNormal, TexCoords).rgb; + vec3 albedoSrgb = texture(gAlbedoSpec, TexCoords).rgb; + float specStrength = texture(gAlbedoSpec, TexCoords).a; + float ao = useSSAO ? texture(ssao, TexCoords).r : 1.0; + + if (viewPos.z == 0.0) + { + // AO-only debug still shows sky as sky so the geometry framing reads. + vec3 sky = LinearToSrgb(ACESFilm(SkyColor(viewDirWorld, sunDirWorld))); + outColor = vec4(DitherSrgb(sky, gl_FragCoord.xy), 1.0); + return; + } + + if (aoOnly) + { + // Bypass tonemap so AO of 1.0 reads as pure white. + outColor = vec4(vec3(ao), 1.0); + return; + } + + vec3 baseColor = SrgbToLinear(albedoSrgb); + vec3 worldPos = (cameraMatrix * vec4(viewPos, 1.0)).xyz; + vec3 worldNormal = normalize(mat3(cameraMatrix) * viewNormal); + + // World-space grid on near-horizontal upward faces. Two tiers so distance + // reads at any zoom: minor lines every 1 unit, major every 5. fwidth keeps + // each line ~1 pixel wide regardless of camera distance, which both + // avoids aliasing and produces a natural "fade with distance" since lines + // sub-pixel-merge into the surface tint as they recede. The orientation + // gate lets the same grid apply to stacked-cube tops without leaking onto + // walls or sloped faces. Disabled per-sample on mesh-collision grounds + // where the wireframe overlay already provides the same signal. + if (useGrid && abs(worldPos.y) < 0.5) + { + float groundFactor = smoothstep(0.95, 0.99, worldNormal.y); + if (groundFactor > 0.0) + { + float minor = WorldGrid(worldPos.xz); + float major = WorldGrid(worldPos.xz * 0.2); + float gridDarken = (1.0 - 0.15 * minor) * (1.0 - 0.40 * major); + baseColor *= mix(1.0, gridDarken, groundFactor); + } + } + + float aoFactor = pow(ao, aoPower); + + vec3 ambient = HemisphericAmbient(worldNormal) * aoFactor; + + vec3 sunColor = SrgbToLinear(SUN_COLOR_SRGB) * SUN_INTENSITY; + + float NdotL = max(dot(worldNormal, sunDirWorld), 0.0); + vec3 diffuse = NdotL * sunColor; + + vec3 viewDirToCam = -viewDirWorld; + vec3 halfDir = normalize(sunDirWorld + viewDirToCam); + float spec = pow(max(dot(worldNormal, halfDir), 0.0), SPEC_POWER); + vec3 specular = spec * specStrength * SPEC_SCALE * sunColor; + + float shadow = 0.0; + if (useShadow) + { + // Normal-offset bias: push the receiver point along the world normal + // before projecting to light space. RPDB inside ShadowCalculation + // handles per-tap bias well on flat receivers, but its Jacobian breaks + // down at grazing angles where dzduv saturates the ±2 clamp. Offsetting + // along N concentrates extra bias exactly on faces near-perpendicular + // to the light (NdotL near 0), killing the residual acne RPDB misses. + vec3 biasedWorldPos = worldPos + worldNormal * worldTexelSize * 1.5 * (1.0 - NdotL); + vec4 lightSpacePos = lightSpaceMatrix * vec4(biasedWorldPos, 1.0); + shadow = ShadowCalculation(lightSpacePos, worldNormal, worldPos); + } + + // todo for disabling shadows + // shadow = 0.0f; + + // Physically AO should only modulate indirect light, but direct sun overwhelms ambient on + // sunlit surfaces and the contact darkening disappears. aoDirect dials in a controllable + // amount of AO on the direct term — a fudge, but the only way to get visible contact AO + // on a brightly lit floor without a separate contact-shadow pass. + float directAO = mix(1.0, aoFactor, aoDirect); + vec3 color = baseColor * (ambient + (1.0 - shadow) * (diffuse + specular) * directAO); + + float dist = length(viewPos); + float fog = 1.0 - exp(-FOG_DENSITY * dist); + color = mix(color, SkyColor(viewDirWorld, sunDirWorld), fog); + + outColor = vec4(DitherSrgb(LinearToSrgb(ACESFilm(color)), gl_FragCoord.xy), 1.0); +} diff --git a/shaders/depth_copy_fs.glsl b/shaders/depth_copy_fs.glsl new file mode 100644 index 0000000..3661142 --- /dev/null +++ b/shaders/depth_copy_fs.glsl @@ -0,0 +1,10 @@ +#version 330 core + +in vec2 TexCoords; + +uniform sampler2D depthTexture; + +void main() +{ + gl_FragDepth = texture(depthTexture, TexCoords).r; +} diff --git a/shaders/empty.fs b/shaders/empty.fs new file mode 100644 index 0000000..cd61250 --- /dev/null +++ b/shaders/empty.fs @@ -0,0 +1,5 @@ +#version 330 core + +void main() +{ +} diff --git a/shaders/forward.fs b/shaders/forward.fs new file mode 100644 index 0000000..cea36dc --- /dev/null +++ b/shaders/forward.fs @@ -0,0 +1,10 @@ +#version 330 core + +layout (location = 0) out vec4 fragmentColor; + +in vec3 overrideColor; + +void main() +{ + fragmentColor = vec4(overrideColor, 1.0); +} diff --git a/shaders/forward.vs b/shaders/forward.vs new file mode 100644 index 0000000..d45a38a --- /dev/null +++ b/shaders/forward.vs @@ -0,0 +1,17 @@ +#version 330 core + +layout (location = 0) in vec3 v_position; +layout (location = 1) in int v_flags; + +uniform mat4 projection; +uniform mat4 view; +uniform mat4 model; +uniform vec3 color; + +out vec3 overrideColor; + +void main() +{ + overrideColor = v_flags != 0 ? vec3(0.9, 0.9, 0.9) : color; + gl_Position = projection * view * model * vec4(v_position, 1.0); +} diff --git a/shaders/geometry_fs.glsl b/shaders/geometry_fs.glsl new file mode 100644 index 0000000..0ffb3d9 --- /dev/null +++ b/shaders/geometry_fs.glsl @@ -0,0 +1,20 @@ +#version 330 core + +layout (location = 0) out vec3 gPosition; +layout (location = 1) out vec3 gNormal; +layout (location = 2) out vec4 gAlbedoSpec; + +in vec3 fragmentPosition; +in vec3 normal; +in vec4 color; + +void main() +{ + // store the fragment position vector in the first gbuffer texture + gPosition = fragmentPosition; + + // also store the per-fragment normals into the gbuffer + gNormal = normalize(normal); + + gAlbedoSpec = color; +} \ No newline at end of file diff --git a/shaders/geometry_vs.glsl b/shaders/geometry_vs.glsl new file mode 100644 index 0000000..bc74a2a --- /dev/null +++ b/shaders/geometry_vs.glsl @@ -0,0 +1,46 @@ +#version 330 core + +layout (location = 0) in vec3 aPos; +layout (location = 1) in vec3 aNormal; +layout (location = 2) in int aMaterial; + +out vec3 fragmentPosition; +out vec3 normal; +out vec4 color; + +// for drawing a hollow cube +uniform bool invertedNormals; + +uniform mat4 model; +uniform mat4 view; +uniform mat4 projection; +uniform vec4 objectColor; + +void main() +{ + // Define an array of 10 colors + vec3 colors[10]; + colors[0] = vec3(0.4706, 0.6118, 0.2); + colors[1] = vec3(0.5255, 0.2941, 0.3529); + colors[2] = vec3(0.2, 0.2, 0.4588); + colors[3] = vec3(0.7451, 0.5725, 0.2471); + colors[4] = vec3(0.6784, 0.2627, 0.6784); + colors[5] = vec3(0.2784, 0.6, 0.6); + colors[6] = vec3(0.502, 0.251, 0.0039); + colors[7] = vec3(0.698, 0.5608, 0.8314); + colors[8] = vec3(0.0, 0.2941, 0.0); + colors[9] = vec3(0.5, 0.5, 0.5); + + vec4 viewPos = view * model * vec4(aPos, 1.0); + fragmentPosition = viewPos.xyz; + + mat3 normalMatrix = transpose(inverse(mat3(view * model))); + normal = normalMatrix * (invertedNormals ? -aNormal : aNormal); + + int colorIndex = max(0, aMaterial) % 10; + color = aMaterial >= 0 ? vec4(colors[colorIndex], 1.0) : objectColor; + + // color = vec4(colors[2], 1.0f); + + gl_Position = projection * viewPos; +} \ No newline at end of file diff --git a/shaders/mesh.fs b/shaders/mesh.fs new file mode 100644 index 0000000..0ffb3d9 --- /dev/null +++ b/shaders/mesh.fs @@ -0,0 +1,20 @@ +#version 330 core + +layout (location = 0) out vec3 gPosition; +layout (location = 1) out vec3 gNormal; +layout (location = 2) out vec4 gAlbedoSpec; + +in vec3 fragmentPosition; +in vec3 normal; +in vec4 color; + +void main() +{ + // store the fragment position vector in the first gbuffer texture + gPosition = fragmentPosition; + + // also store the per-fragment normals into the gbuffer + gNormal = normalize(normal); + + gAlbedoSpec = color; +} \ No newline at end of file diff --git a/shaders/mesh.vs b/shaders/mesh.vs new file mode 100644 index 0000000..8c50074 --- /dev/null +++ b/shaders/mesh.vs @@ -0,0 +1,48 @@ +#version 330 core + +// Static +layout (location = 0) in vec3 v_localPosition; +layout (location = 1) in vec3 v_localNormal; +layout (location = 2) in int v_material; + +// Instance +layout (location = 3) in vec4 v_instanceColor; +layout (location = 4) in mat4 v_instanceMatrix; + +out vec3 fragmentPosition; +out vec3 normal; +out vec4 color; + +uniform mat4 view; +uniform mat4 projection; + +void main() +{ + // Define an array of 10 colors + vec3 colors[10]; + colors[0] = vec3(0.4706, 0.6118, 0.2); + colors[1] = vec3(0.5255, 0.2941, 0.3529); + colors[2] = vec3(0.2, 0.2, 0.4588); + colors[3] = vec3(0.7451, 0.5725, 0.2471); + colors[4] = vec3(0.6784, 0.2627, 0.6784); + colors[5] = vec3(0.2784, 0.6, 0.6); + colors[6] = vec3(0.502, 0.251, 0.0039); + colors[7] = vec3(0.698, 0.5608, 0.8314); + colors[8] = vec3(0.0, 0.2941, 0.0); + colors[9] = vec3(0.5, 0.5, 0.5); + + vec4 viewPos = view * v_instanceMatrix * vec4(v_localPosition, 1.0); + fragmentPosition = viewPos.xyz; + + mat3 normalMatrix = transpose(inverse(mat3(view * v_instanceMatrix))); + normal = normalMatrix * v_localNormal; + + int colorIndex = max(0, v_material) % 10; + + // alpha is specular + color = v_material >= 0 ? vec4(colors[colorIndex], 1.0) : v_instanceColor; + + //color = vec4(colors[4], 1.0f); + + gl_Position = projection * viewPos; +} \ No newline at end of file diff --git a/shaders/mesh_edge.vs b/shaders/mesh_edge.vs new file mode 100644 index 0000000..7667f77 --- /dev/null +++ b/shaders/mesh_edge.vs @@ -0,0 +1,20 @@ +#version 330 core + +// Static +layout (location = 0) in vec3 v_localPosition; +layout (location = 1) in int v_flags; + +// Instance +layout (location = 2) in vec4 v_instanceColor; +layout (location = 3) in mat4 v_instanceMatrix; + +out vec3 overrideColor; + +uniform mat4 projection; +uniform mat4 view; + +void main() +{ + overrideColor = v_flags != 0 ? vec3(0.6, 0.6, 0.6) : 0.5 * v_instanceColor.rgb; + gl_Position = projection * view * v_instanceMatrix * vec4(v_localPosition, 1.0); +} diff --git a/shaders/mesh_forward.fs b/shaders/mesh_forward.fs new file mode 100644 index 0000000..96c17f6 --- /dev/null +++ b/shaders/mesh_forward.fs @@ -0,0 +1,34 @@ +#version 330 core + +#include "common.glsl" + +layout (location = 0) out vec4 fragmentColor; + +in vec3 position; // world space +in vec3 normal; // world space +in vec4 color; // sRGB albedo, alpha is opacity + +uniform vec3 sunDirWorld; +uniform vec3 cameraPos; + +void main() +{ + vec3 N = normalize(normal); + vec3 viewRay = normalize(position - cameraPos); + + vec3 baseColor = SrgbToLinear(color.rgb); + + vec3 ambient = HemisphericAmbient(N); + + vec3 sunColor = SrgbToLinear(SUN_COLOR_SRGB) * SUN_INTENSITY; + float NdotL = max(dot(N, sunDirWorld), 0.0); + vec3 diffuse = NdotL * sunColor; + + vec3 lit = baseColor * (ambient + diffuse); + + float dist = length(position - cameraPos); + float fog = 1.0 - exp(-FOG_DENSITY * dist); + lit = mix(lit, SkyColor(viewRay, sunDirWorld), fog); + + fragmentColor = vec4(DitherSrgb(LinearToSrgb(ACESFilm(lit)), gl_FragCoord.xy), color.a); +} diff --git a/shaders/mesh_forward.vs b/shaders/mesh_forward.vs new file mode 100644 index 0000000..19b203d --- /dev/null +++ b/shaders/mesh_forward.vs @@ -0,0 +1,47 @@ +#version 330 core + +layout (location = 0) in vec3 v_localPosition; +layout (location = 1) in vec3 v_localNormal; +layout (location = 2) in int v_material; +layout (location = 3) in vec4 v_instanceColor; +layout (location = 4) in mat4 v_instanceMatrix; + +out vec3 position; +out vec3 normal; +out vec4 color; + +uniform mat4 view; +uniform mat4 projection; + +void main() +{ + // Define an array of 10 colors + vec3 colors[10]; + colors[0] = vec3(0.4706, 0.6118, 0.2); + colors[1] = vec3(0.5255, 0.2941, 0.3529); + colors[2] = vec3(0.2, 0.2, 0.4588); + colors[3] = vec3(0.7451, 0.5725, 0.2471); + colors[4] = vec3(0.6784, 0.2627, 0.6784); + colors[5] = vec3(0.2784, 0.6, 0.6); + colors[6] = vec3(0.502, 0.251, 0.0039); + colors[7] = vec3(0.698, 0.5608, 0.8314); + colors[8] = vec3(0.0, 0.2941, 0.0); + colors[9] = vec3(0.5, 0.5, 0.5); + + // world space position + position = vec3(v_instanceMatrix * vec4(v_localPosition, 1.0)); + + vec4 viewPos = view * vec4(position, 1.0); + + // world space normal, accounting for non-uniform scale + mat3 normalMatrix = transpose(inverse(mat3(v_instanceMatrix))); + normal = normalMatrix * v_localNormal; + + int colorIndex = max(0, v_material) % 10; + color = v_material >= 0 ? vec4(colors[colorIndex], v_instanceColor.a) : v_instanceColor; + + // color = vec4(colors[2], 0.5f); + + gl_Position = projection * viewPos; + +} \ No newline at end of file diff --git a/shaders/mesh_shadow.vs b/shaders/mesh_shadow.vs new file mode 100644 index 0000000..551471f --- /dev/null +++ b/shaders/mesh_shadow.vs @@ -0,0 +1,14 @@ +#version 330 core + +layout (location = 0) in vec3 v_localPosition; +layout (location = 1) in vec3 v_localNormal; +layout (location = 2) in int v_material; +layout (location = 3) in vec4 v_instanceColor; +layout (location = 4) in mat4 v_instanceMatrix; + +uniform mat4 lightSpaceMatrix; + +void main() +{ + gl_Position = lightSpaceMatrix * v_instanceMatrix * vec4(v_localPosition, 1.0); +} diff --git a/shaders/quad_vs.glsl b/shaders/quad_vs.glsl new file mode 100644 index 0000000..9f93e29 --- /dev/null +++ b/shaders/quad_vs.glsl @@ -0,0 +1,11 @@ +#version 330 core +layout (location = 0) in vec3 aPos; +layout (location = 1) in vec2 aTexCoords; + +out vec2 TexCoords; + +void main() +{ + TexCoords = aTexCoords; + gl_Position = vec4(aPos, 1.0); +} \ No newline at end of file diff --git a/shaders/shadow_map.vs b/shaders/shadow_map.vs new file mode 100644 index 0000000..947562f --- /dev/null +++ b/shaders/shadow_map.vs @@ -0,0 +1,10 @@ +#version 330 core +layout (location = 0) in vec3 aPos; + +uniform mat4 lightSpaceMatrix; +uniform mat4 model; + +void main() +{ + gl_Position = lightSpaceMatrix * model * vec4(aPos, 1.0); +} \ No newline at end of file diff --git a/shaders/ssao_blur_fs.glsl b/shaders/ssao_blur_fs.glsl new file mode 100644 index 0000000..24ec446 --- /dev/null +++ b/shaders/ssao_blur_fs.glsl @@ -0,0 +1,47 @@ +#version 330 core +out float FragColor; + +in vec2 TexCoords; + +uniform sampler2D ssaoInput; +uniform sampler2D gPosition; + +// Depth difference (in view-space units) over which a tap's weight halves. +// Tight enough to keep silhouette edges sharp, loose enough not to leave +// per-tap noise behind on smooth surfaces. +const float DEPTH_SIGMA = 0.25; + +void main() +{ + vec2 texelSize = 1.0 / vec2(textureSize(ssaoInput, 0)); + float centerZ = texture(gPosition, TexCoords).z; + + // Sky / no-geometry: pass through. Avoids contaminating real geometry's + // bilateral weights with the zero-init sentinel from the G-buffer. + if (centerZ == 0.0) + { + FragColor = texture(ssaoInput, TexCoords).r; + return; + } + + float invTwoSigmaSq = 1.0 / (2.0 * DEPTH_SIGMA * DEPTH_SIGMA); + + float result = 0.0; + float weightSum = 0.0; + for (int x = -2; x < 2; ++x) + { + for (int y = -2; y < 2; ++y) + { + vec2 sampleUV = TexCoords + vec2(float(x), float(y)) * texelSize; + float tapZ = texture(gPosition, sampleUV).z; + // Drop sky taps so they don't pull the weighted average toward 1.0 + // along silhouettes against the background. + if (tapZ == 0.0) continue; + float dz = centerZ - tapZ; + float w = exp(-dz * dz * invTwoSigmaSq); + result += texture(ssaoInput, sampleUV).r * w; + weightSum += w; + } + } + FragColor = (weightSum > 0.0) ? (result / weightSum) : texture(ssaoInput, TexCoords).r; +} diff --git a/shaders/ssao_fs.glsl b/shaders/ssao_fs.glsl new file mode 100644 index 0000000..3ae4423 --- /dev/null +++ b/shaders/ssao_fs.glsl @@ -0,0 +1,67 @@ +#version 330 core +out float FragColor; + +in vec2 TexCoords; + +uniform sampler2D gPosition; +uniform sampler2D gNormal; +uniform sampler2D texNoise; + +uniform vec3 samples[32]; +uniform float radius = 0.5; +uniform float bias = 0.025; +uniform float minScale = 0.1; + +// parameters (you'd probably want to use them as uniforms to more easily tweak the effect) +int kernelSize = 32; + +// tile noise texture over screen based on screen dimensions divided by noise size +uniform vec2 noiseScale; + +uniform mat4 projection; + +void main() +{ + // get input for SSAO algorithm + vec3 fragPos = texture(gPosition, TexCoords).xyz; + + // early-out for sky/background fragments (no geometry in G-buffer) + if (fragPos.z == 0.0) + { + FragColor = 1.0; + return; + } + + vec3 normal = normalize(texture(gNormal, TexCoords).rgb); + vec3 randomVec = normalize(texture(texNoise, TexCoords * noiseScale).xyz); + + // create TBN change-of-basis matrix: from tangent-space to view-space + vec3 tangent = normalize(randomVec - normal * dot(randomVec, normal)); + vec3 bitangent = cross(normal, tangent); + mat3 TBN = mat3(tangent, bitangent, normal); + + // iterate over the sample kernel and calculate occlusion factor + float occlusion = 0.0; + for(int i = 0; i < kernelSize; ++i) + { + // get sample position + vec3 samplePos = TBN * samples[i]; // from tangent to view-space + samplePos = fragPos + samplePos * radius; + + // project sample position (to sample texture) (to get position on screen/texture) + vec4 offset = vec4(samplePos, 1.0); + offset = projection * offset; // from view to clip-space + offset.xyz /= offset.w; // perspective divide + offset.xyz = offset.xyz * 0.5 + 0.5; // transform to range 0.0 - 1.0 + + // get sample depth + float sampleDepth = texture(gPosition, offset.xy).z; // get depth value of kernel sample + + // range check & accumulate + float rangeCheck = smoothstep(0.0, 1.0, radius / abs(fragPos.z - sampleDepth)); + occlusion += (sampleDepth >= samplePos.z + bias ? 1.0 : 0.0) * rangeCheck; + } + occlusion = max(1.0 - (occlusion / kernelSize), minScale); + + FragColor = occlusion; +} diff --git a/shared/CMakeLists.txt b/shared/CMakeLists.txt new file mode 100644 index 0000000..aba87f1 --- /dev/null +++ b/shared/CMakeLists.txt @@ -0,0 +1,25 @@ +# Shared code for samples, benchmarks, and unit tests + +set(BOX3D_SHARED_FILES + benchmarks.c + benchmarks.h + determinism.c + determinism.h + human.c + human.h + stability.c + stability.h + utils.c + utils.h +) + +add_library(shared ${BOX3D_SHARED_FILES}) + +set_target_properties(shared PROPERTIES + C_STANDARD 17 +) + +target_include_directories(shared PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +target_link_libraries(shared PRIVATE box3d) + +source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} PREFIX "" FILES ${BOX3D_SHARED_FILES}) \ No newline at end of file diff --git a/shared/benchmarks.c b/shared/benchmarks.c new file mode 100644 index 0000000..7fb9587 --- /dev/null +++ b/shared/benchmarks.c @@ -0,0 +1,1005 @@ +// SPDX-FileCopyrightText: 2022 Erin Catto +// SPDX-License-Identifier: MIT + +#include "benchmarks.h" + +#include "human.h" +#include "utils.h" + +#include "box3d/box3d.h" + +#include +#include +#include + +#ifdef NDEBUG +#define BENCHMARK_DEBUG 0 +#else +#define BENCHMARK_DEBUG 1 +#endif + +void CreateJointGrid( b3WorldId worldId ) +{ + b3World_EnableSleeping( worldId, false ); + + int n = BENCHMARK_DEBUG ? 10 : 100; + + // Allocate to avoid huge stack usage + b3BodyId* bodies = malloc( n * n * sizeof( b3BodyId ) ); + int index = 0; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.filter.categoryBits = 2; + shapeDef.filter.maskBits = ~2u; + + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.4f }; + + b3SphericalJointDef jointDef = b3DefaultSphericalJointDef(); + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.enableSleep = false; + + for ( int k = 0; k < n; ++k ) + { + for ( int i = 0; i < n; ++i ) + { + float fk = (float)k; + float fi = (float)i; + + if ( i == 0 ) + { + bodyDef.type = b3_staticBody; + } + else + { + bodyDef.type = b3_dynamicBody; + } + + bodyDef.position = (b3Vec3){ fk, -fi, 0.0f }; + + b3BodyId body = b3CreateBody( worldId, &bodyDef ); + + b3CreateSphereShape( body, &shapeDef, &sphere ); + + if ( i > 0 ) + { + jointDef.base.bodyIdA = bodies[index - 1]; + jointDef.base.bodyIdB = body; + jointDef.base.localFrameA.p = (b3Vec3){ 0.0f, -0.5f, 0.0f }; + jointDef.base.localFrameB.p = (b3Vec3){ 0.0f, 0.5f, 0.0f }; + b3CreateSphericalJoint( worldId, &jointDef ); + } + + if ( k > 0 ) + { + jointDef.base.bodyIdA = bodies[index - n]; + jointDef.base.bodyIdB = body; + jointDef.base.localFrameA.p = (b3Vec3){ 0.5f, 0.0f, 0.0f }; + jointDef.base.localFrameB.p = (b3Vec3){ -0.5f, 0.0f, 0.0f }; + b3CreateSphericalJoint( worldId, &jointDef ); + } + + bodies[index++] = body; + } + } + + free( bodies ); +} + +// The 80 block version falls over after 1000 steps. +void CreateLargePyramid( b3WorldId worldId ) +{ + b3World_EnableSleeping( worldId, false ); + + int baseCount = BENCHMARK_DEBUG ? 20 : 90; + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = (b3Vec3){ 0.0f, -1.0f }; + b3BodyId groundId = b3CreateBody( worldId, &bodyDef ); + + b3BoxHull box = b3MakeBoxHull( 100.0f, 1.0f, 100.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 1.0f; + + float h = 0.5f; + b3BoxHull box = b3MakeBoxHull( h, h, h ); + + float shift = 1.0f * h; + + 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 - h * baseCount; + + bodyDef.position = (b3Vec3){ x, y, 0.0f }; + + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + } +} + +void CreateWidePyramid( b3WorldId worldId ) +{ + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = (b3Vec3){ 0.0f, -1.0f }; + b3BodyId groundId = b3CreateBody( worldId, &bodyDef ); + + b3BoxHull box = b3MakeBoxHull( 100.0f, 1.0f, 100.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + + const float boxSize = 2.0f; + const float boxSeparation = 0.5f; + const float halfBoxSize = 0.5f * boxSize; + const int pyramidHeight = BENCHMARK_DEBUG ? 5 : 15; + + float h = halfBoxSize - 0.025; + b3BoxHull box = b3MakeBoxHull( h, h, h ); + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + for ( int i = 0; i < pyramidHeight; ++i ) + { + for ( int j = i / 2; j < pyramidHeight - ( i + 1 ) / 2; ++j ) + { + for ( int k = i / 2; k < pyramidHeight - ( i + 1 ) / 2; ++k ) + { + float x = -pyramidHeight + boxSize * j + ( i & 1 ? halfBoxSize : 0.0f ); + float y = 1.0f + ( boxSize + boxSeparation ) * i; + float z = -pyramidHeight + boxSize * k + ( i & 1 ? halfBoxSize : 0.0f ); + bodyDef.position = (b3Vec3){ x, y, z }; + + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + } + } +} + +static void CreateSmallPyramid( b3WorldId worldId, int baseCount, float extent, float centerX, float baseZ ) +{ + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.enableSleep = false; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + b3BoxHull box = b3MakeBoxHull( extent, extent, extent ); + + for ( int i = 0; i < baseCount; ++i ) + { + float y = ( 2.0f * i + 1.0f ) * extent; + + for ( int j = i; j < baseCount; ++j ) + { + float x = ( i + 1.0f ) * extent + 2.0f * ( j - i ) * extent + centerX - 0.5f; + bodyDef.position = (b3Vec3){ x, y, baseZ }; + + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + } +} + +void CreateManyPyramids( b3WorldId worldId ) +{ + int baseCount = 10; + float extent = 0.5f; + int rowCount = BENCHMARK_DEBUG ? 3 : 14; + int columnCount = BENCHMARK_DEBUG ? 3 : 14; + float groundExtent = extent * columnCount * ( baseCount + 1.0f ); + + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = (b3Vec3){ 0.0f, -1.0f, 0.0f }; + b3BodyId groundId = b3CreateBody( worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + b3BoxHull box = b3MakeBoxHull( groundExtent, 1.0f, groundExtent ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + + float baseWidth = 2.0f * extent * baseCount; + float baseZ = -groundExtent + 2.0f * extent; + float deltaZ = 2.0f * ( groundExtent - 2.0f * extent ) / ( rowCount - 1.0f ); + + for ( int i = 0; i < rowCount; ++i ) + { + for ( int j = 0; j < columnCount; ++j ) + { + float centerX = -groundExtent + j * ( baseWidth + 2.0f * extent ) + 2.0f * extent; + CreateSmallPyramid( worldId, baseCount, extent, centerX, baseZ ); + } + + baseZ += deltaZ; + } +} + +#define RAIN_GRID_SIZE 15.0f +#define RAIN_LARGE_WORLD 0 +#ifdef NDEBUG +#if RAIN_LARGE_WORLD == 1 +#define RAIN_GRID_COUNT 700 +#define RAIN_GROUP_SIZE 1 +#else +#define RAIN_GRID_COUNT 10 +#define RAIN_GROUP_SIZE 3 +#endif + +#else + +#if RAIN_LARGE_WORLD == 1 +#define RAIN_GRID_COUNT 12 +#define RAIN_GROUP_SIZE 1 +#else +#define RAIN_GRID_COUNT 3 +#define RAIN_GROUP_SIZE 2 +#endif +#endif + +typedef struct Group +{ + Human humans[RAIN_GROUP_SIZE]; +} Group; + +typedef struct RainData +{ + Group* groups; + b3MeshData* gridMesh; + b3MeshData* torusMesh; + int columnCount; + int columnIndex; +} RainData; + +RainData g_rainData; + +void GetRainCapacity( b3Capacity* capacity ) +{ +#if RAIN_LARGE_WORLD == 1 +#ifdef NDEBUG + capacity->staticShapeCount = 1000 * 1024; + capacity->dynamicShapeCount = 2 * 1024; + capacity->staticBodyCount = 500 * 1024; + capacity->dynamicBodyCount = 2 * 1024; +#else + capacity->staticShapeCount = 512; + capacity->dynamicShapeCount = 128; + capacity->staticBodyCount = 256; + capacity->dynamicBodyCount = 128; +#endif +#endif +} + +void CreateRain( b3WorldId worldId ) +{ + memset( &g_rainData, 0, sizeof( g_rainData ) ); + + g_rainData.groups = malloc( RAIN_GRID_COUNT * RAIN_GRID_COUNT * sizeof( Group ) ); + memset( g_rainData.groups, 0, RAIN_GRID_COUNT * RAIN_GRID_COUNT * sizeof( Group ) ); + + int halfMeshGridRows = 4; + float meshGridCellWidth = RAIN_GRID_SIZE / ( 2.0f * halfMeshGridRows ); + g_rainData.gridMesh = b3CreateGridMesh( 2 * halfMeshGridRows, 2 * halfMeshGridRows, meshGridCellWidth, 1, true ); + g_rainData.torusMesh = b3CreateTorusMesh( 16, 16, 0.25f * RAIN_GRID_SIZE, 1.0f ); + + float span = RAIN_GRID_SIZE * RAIN_GRID_COUNT; + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + bodyDef.position.x = -0.5f * span + 0.5f * RAIN_GRID_SIZE; + for ( int i = 0; i < RAIN_GRID_COUNT; ++i ) + { + bodyDef.position.z = -0.5f * span + 0.5f * RAIN_GRID_SIZE; + for ( int j = 0; j < RAIN_GRID_COUNT; ++j ) + { + b3BodyId body = b3CreateBody( worldId, &bodyDef ); + b3CreateMeshShape( body, &shapeDef, g_rainData.gridMesh, b3Vec3_one ); + b3CreateMeshShape( body, &shapeDef, g_rainData.torusMesh, b3Vec3_one ); + + bodyDef.position.z += RAIN_GRID_SIZE; + } + + bodyDef.position.x += RAIN_GRID_SIZE; + } + + // b3World_SetJointTuning( worldId, 60.0f, 1.0f ); +} + +void DestroyRain( void ) +{ + b3DestroyMesh( g_rainData.gridMesh ); + b3DestroyMesh( g_rainData.torusMesh ); + + free( g_rainData.groups ); + g_rainData.groups = NULL; +} + +void CreateGroup( b3WorldId worldId, int rowIndex, int columnIndex ) +{ + assert( rowIndex < RAIN_GRID_COUNT && columnIndex < RAIN_GRID_COUNT ); + + int groupIndex = rowIndex * RAIN_GRID_COUNT + columnIndex; + + float span = RAIN_GRID_COUNT * RAIN_GRID_SIZE; + float groupDistance = 1.0f * span / RAIN_GRID_COUNT; + + b3Vec3 position; + position.x = -0.5f * span + groupDistance * ( columnIndex + 0.5f ); + position.y = 20.0f; + position.z = -0.5f * span + groupDistance * ( rowIndex + 0.5f ); + + float frictionTorque = 5.0f; + float hertz = 1.0f; + float dampingRatio = 0.7f; + bool colorize = false; + + for ( int i = 0; i < RAIN_GROUP_SIZE; ++i ) + { + Human* human = g_rainData.groups[groupIndex].humans + i; + CreateHuman( human, worldId, position, frictionTorque, hertz, dampingRatio, groupIndex, NULL, colorize ); + position.x += 0.75f; + } +} + +void DestroyGroup( int rowIndex, int columnIndex ) +{ + assert( rowIndex < RAIN_GRID_COUNT && columnIndex < RAIN_GRID_COUNT ); + + int groupIndex = rowIndex * RAIN_GRID_COUNT + columnIndex; + + for ( int i = 0; i < RAIN_GROUP_SIZE; ++i ) + { + DestroyHuman( g_rainData.groups[groupIndex].humans + i ); + } +} + +void StepRain( b3WorldId worldId, int stepCount ) +{ + int delay = BENCHMARK_DEBUG ? 0x7F : 0x2F; + int increment = RAIN_LARGE_WORLD ? 100 : 1; + + if ( ( stepCount & delay ) == 0 ) + { + if ( g_rainData.columnCount < RAIN_GRID_COUNT ) + { + for ( int i = 0; i < RAIN_GRID_COUNT; i += increment ) + { + CreateGroup( worldId, i, g_rainData.columnCount ); + } + + g_rainData.columnCount = b3MinInt( g_rainData.columnCount + increment, RAIN_GRID_COUNT ); + } + else + { + for ( int i = 0; i < RAIN_GRID_COUNT; i += increment ) + { + DestroyGroup( i, g_rainData.columnIndex ); + CreateGroup( worldId, i, g_rainData.columnIndex ); + } + + g_rainData.columnIndex = g_rainData.columnIndex + increment; + if ( g_rainData.columnIndex >= RAIN_GRID_COUNT ) + { + g_rainData.columnIndex = 0; + } + } + } +} + +void GetWasherCapacity( b3Capacity* capacity ) +{ + capacity->staticShapeCount = 16; + capacity->dynamicShapeCount = 10000; + capacity->staticBodyCount = 16; + capacity->dynamicBodyCount = 10000; + capacity->contactCount = 60000; +} + +void CreateWasher( b3WorldId worldId ) +{ + bool kinematic = true; + + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position.y = -1.0f; + groundId = b3CreateBody( worldId, &bodyDef ); + + b3BoxHull box = b3MakeBoxHull( 60.0f, 1.0f, 60.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + + { + float motorSpeed = 25.0f; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = (b3Vec3){ 0.0f, 21.0f, 0.0f }; + + if ( kinematic == true ) + { + bodyDef.type = b3_kinematicBody; + bodyDef.angularVelocity = (b3Vec3){ 0.0f, 0.0f, ( B3_PI / 180.0f ) * motorSpeed }; + bodyDef.linearVelocity = (b3Vec3){ 0.001f, -0.002f, 0.0f }; + } + else + { + bodyDef.type = b3_dynamicBody; + } + + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + float r0 = 14.0f; + float r1 = 16.0f; + float r2 = 18.0f; + b3Vec3 nd = { 0.0f, 0.0f, -10.0f }; + b3Vec3 pd = { 0.0f, 0.0f, 10.0f }; + + float angle = B3_PI / 18.0f; + b3Quat q = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, angle ); + b3Quat qo = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.1f * angle ); + b3Vec3 u1 = { 1.0f, 0.0f, 0.0f }; + for ( int i = 0; i < 36; ++i ) + { + b3Vec3 u2; + if ( i == 35 ) + { + u2 = (b3Vec3){ 1.0f, 0.0f, 0.0f }; + } + else + { + u2 = b3RotateVector( q, u1 ); + } + + { + b3Vec3 a1 = b3InvRotateVector( qo, u1 ); + b3Vec3 a2 = b3RotateVector( qo, u2 ); + b3Vec3 p1 = b3MulAdd( nd, r1, a1 ); + b3Vec3 p2 = b3MulAdd( nd, r2, a1 ); + b3Vec3 p3 = b3MulAdd( nd, r1, a2 ); + b3Vec3 p4 = b3MulAdd( nd, r2, a2 ); + b3Vec3 p5 = b3MulAdd( pd, r1, a1 ); + b3Vec3 p6 = b3MulAdd( pd, r2, a1 ); + b3Vec3 p7 = b3MulAdd( pd, r1, a2 ); + b3Vec3 p8 = b3MulAdd( pd, r2, a2 ); + + b3Vec3 points[8] = { p1, p2, p3, p4, p5, p6, p7, p8 }; + b3Hull* hull = b3CreateHull( points, 8, 8 ); + b3CreateHullShape( bodyId, &shapeDef, hull ); + b3DestroyHull( hull ); + } + + if ( i % 9 == 0 ) + { + b3Vec3 p1 = b3MulAdd( nd, r0, u1 ); + b3Vec3 p2 = b3MulAdd( nd, r1, u1 ); + b3Vec3 p3 = b3MulAdd( nd, r0, u2 ); + b3Vec3 p4 = b3MulAdd( nd, r1, u2 ); + b3Vec3 p5 = b3MulAdd( pd, r0, u1 ); + b3Vec3 p6 = b3MulAdd( pd, r1, u1 ); + b3Vec3 p7 = b3MulAdd( pd, r0, u2 ); + b3Vec3 p8 = b3MulAdd( pd, r1, u2 ); + + b3Vec3 points[8] = { p1, p2, p3, p4, p5, p6, p7, p8 }; + b3Hull* hull = b3CreateHull( points, 8, 8 ); + b3CreateHullShape( bodyId, &shapeDef, hull ); + b3DestroyHull( hull ); + } + + u1 = u2; + } + + if ( kinematic == false ) + { + b3RevoluteJointDef jointDef = b3DefaultRevoluteJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameA.p.y = 10.0f; + jointDef.motorSpeed = ( B3_PI / 180.0f ) * motorSpeed; + jointDef.maxMotorTorque = 1e8f; + jointDef.enableMotor = true; + + b3CreateRevoluteJoint( worldId, &jointDef ); + } + } + + int gridCount = BENCHMARK_DEBUG ? 8 : 20; + float a = 0.2f; + + b3BoxHull cube = b3MakeBoxHull( a, a, a ); + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + float x = -2.0f * a * gridCount; + for ( int i = 0; i < gridCount; ++i ) + { + float y = -2.0f * a * gridCount + 21.0f; + for ( int j = 0; j < gridCount; ++j ) + { + float z = -2.0f * a * gridCount; + for ( int k = 0; k < gridCount; ++k ) + { + bodyDef.position = (b3Vec3){ x, y, z }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + + b3CreateHullShape( bodyId, &shapeDef, &cube.base ); + z += 4.0f * a; + } + + y += 4.0f * a; + } + + x += 4.0f * a; + } +} + +struct +{ + b3MeshData* meshData; +} g_compoundCapsulesData; + +void CreateCompoundCapsules( b3WorldId worldId ) +{ + memset( &g_compoundCapsulesData, 0, sizeof( g_compoundCapsulesData ) ); + + // float tilt = 0.15f * B3_PI; + float tilt = 0.0f * B3_PI; + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = (b3Vec3){ 0.0f, -1.0f, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( (b3Vec3){ 1.0f, 0.0f, 0.0 }, tilt ); + b3BodyId groundId = b3CreateBody( worldId, &bodyDef ); + + int xCount = 200; + int zCount = 400; + + float cellWidth = 1.0f; + float amplitude = 0.4f; + float rowHz = 0.05f; + float columnHz = 0.1f; + + g_compoundCapsulesData.meshData = b3CreateWaveMesh( xCount, zCount, cellWidth, amplitude, rowHz, columnHz ); + + // g_compoundCapsulesData.meshData = b3CreateWaveMesh( xCount, zCount, 1.0f, 2.5f, 0.05f, 0.01f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateMeshShape( groundId, &shapeDef, g_compoundCapsulesData.meshData, b3Vec3_one ); + + bodyDef.rotation = b3Quat_identity; + bodyDef.type = b3_dynamicBody; + bodyDef.sleepThreshold = 0.2f; + + int bodyCount = BENCHMARK_DEBUG ? 10 : 90; + + shapeDef.baseMaterial.friction = 0.9f; + shapeDef.baseMaterial.rollingResistance = 0.2f; + shapeDef.updateBodyMass = false; + shapeDef.density = 1.0f; + + float angularVelocity = -0.5f; + float z = BENCHMARK_DEBUG ? -15.0f : -140.0f; + b3CosSin cs = b3ComputeCosSin( tilt ); + float yTilt = cs.sine / cs.cosine; + //b3CosSin stubCS = b3ComputeCosSin( 50.0f * B3_PI / 180.0f ); + for ( int bodyIndex = 0; bodyIndex < bodyCount; ++bodyIndex ) + { + bodyDef.position = (b3Vec3){ 0.0, 0.5f - z * yTilt, z }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + + float y = 1.0f; + float r = 0.75f; + float l = 1.5f; + float offset = 0.05f; + //float stubX = 1.4f; + //float stubZ = 0.0f; + for ( int shapeIndex = 0; shapeIndex < 22; ++shapeIndex ) + { + b3Capsule capsule = { { offset, y, 0.0f }, { 0.0f, y + l, -offset }, r }; + b3CreateCapsuleShape( bodyId, &shapeDef, &capsule ); + +#if 0 + if ( ( shapeIndex & 1 ) == 0 ) + { + b3Capsule stub = { { 0.0f, y + 0.5f * l, 0.0f }, { 1.4f * r, y + 0.5f * l, 0.0f }, 0.2f }; + b3CreateCapsuleShape( bodyId, &shapeDef, &stub ); + } + else + { + } +#elif 0 + b3Capsule stub = { { 0.0f, y + 0.5f * l, 0.0f }, { stubX * r, y + 0.5f * l, stubZ * r }, 0.2f }; + b3CreateCapsuleShape( bodyId, &shapeDef, &stub ); + stubCS = b3ComputeCosSin( B3_PI * RandomFloat() ); + float sx = stubX * stubCS.cosine - stubZ * stubCS.sine; + float sz = stubX * stubCS.sine + stubZ * stubCS.cosine; + stubX = sx; + stubZ = sz; +#endif + y += l + 2.0f * r; + r = 0.95f * r; + offset = -offset; + } + + float velocityScale = 0.5f + ( 0.5f * bodyIndex ) / bodyCount; + b3Body_ApplyMassFromShapes( bodyId ); + b3Vec3 center = b3Body_GetWorldCenterOfMass( bodyId ); + b3Vec3 omega = { 0.0f, 0.0f, velocityScale * angularVelocity }; + b3Vec3 v = b3Cross( omega, b3Sub( center, bodyDef.position ) ); + b3Body_SetAngularVelocity( bodyId, omega ); + b3Body_SetLinearVelocity( bodyId, v ); + + z += 3.0f; + angularVelocity = -angularVelocity; + } +} + +void DestroyCompoundCapsules( void ) +{ + b3DestroyMesh( g_compoundCapsulesData.meshData ); + memset( &g_compoundCapsulesData, 0, sizeof( g_compoundCapsulesData ) ); +} + +struct +{ + b3MeshData* meshData; +} g_compoundHullsData; + +void CreateCompoundHulls( b3WorldId worldId ) +{ + memset( &g_compoundHullsData, 0, sizeof( g_compoundHullsData ) ); + + // float tilt = 0.15f * B3_PI; + float tilt = 0.0f * B3_PI; + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = (b3Vec3){ 0.0f, 0.0f, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( (b3Vec3){ 1.0f, 0.0f, 0.0 }, tilt ); + b3BodyId groundId = b3CreateBody( worldId, &bodyDef ); + + int xCount = 200; + // int zCount = BENCHMARK_DEBUG ? 100 : 400; + int zCount = 400; + + float cellWidth = 1.0f; + float amplitude = 0.4f; + float rowHz = 0.05f; + float columnHz = 0.1f; + + g_compoundHullsData.meshData = b3CreateWaveMesh( xCount, zCount, cellWidth, amplitude, rowHz, columnHz ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateMeshShape( groundId, &shapeDef, g_compoundHullsData.meshData, b3Vec3_one ); + + bodyDef.type = b3_dynamicBody; + bodyDef.sleepThreshold = 0.2f; + bodyDef.rotation = b3Quat_identity; + + int bodyCount = BENCHMARK_DEBUG ? 10 : 90; + + shapeDef.baseMaterial.friction = 0.9f; + shapeDef.baseMaterial.rollingResistance = 0.05f; + shapeDef.updateBodyMass = false; + shapeDef.density = 1.0f; + + int hullCount = 22; + b3Hull* hulls[22] = { 0 }; + + float y = 1.0f; + float r = 0.75f; + float l = 1.5f; + for ( int i = 0; i < hullCount; ++i ) + { + hulls[i] = b3CreateCylinder( l + 2.0f * r, r, y - r, 6 ); + y += l + 2.0f * r; + r = 0.95f * r; + } + + float angularVelocity = -0.5f; + float z = BENCHMARK_DEBUG ? -15.0f : -140.0f; + b3CosSin cs = b3ComputeCosSin( tilt ); + float yTilt = cs.sine / cs.cosine; + for ( int bodyIndex = 0; bodyIndex < bodyCount; ++bodyIndex ) + { + bodyDef.position = (b3Vec3){ 0.0, 1.0f - z * yTilt, z }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + + for ( int shapeIndex = 0; shapeIndex < 22; ++shapeIndex ) + { + // Random rotation provided no benefit to behavior. + // float angle = B3_PI * RandomFloat(); + // b3Transform xf; + // xf.p = b3Vec3_zero; + // xf.q = b3MakeQuatFromAxisAngle( (b3Vec3){ 0.0f, 1.0f, 0.0f }, angle ); + // b3Vec3 scale = {1.0f, 1.0f, 1.0f}; + // b3CreateTransformedHullShape( bodyId, &shapeDef, hulls[shapeIndex], xf, scale ); + b3CreateHullShape( bodyId, &shapeDef, hulls[shapeIndex] ); + } + + float velocityScale = 0.5f + ( 0.5f * bodyIndex ) / bodyCount; + b3Body_ApplyMassFromShapes( bodyId ); + b3Vec3 center = b3Body_GetWorldCenterOfMass( bodyId ); + b3Vec3 omega = { 0.0f, 0.0f, velocityScale * angularVelocity }; + b3Vec3 v = b3Cross( omega, b3Sub( center, bodyDef.position ) ); + b3Body_SetAngularVelocity( bodyId, omega ); + b3Body_SetLinearVelocity( bodyId, v ); + + z += 3.0f; + angularVelocity = -angularVelocity; + } + + for ( int i = 0; i < hullCount; ++i ) + { + b3DestroyHull( hulls[i] ); + } +} + +void DestroyCompoundHulls( void ) +{ + b3DestroyMesh( g_compoundHullsData.meshData ); + memset( &g_compoundHullsData, 0, sizeof( g_compoundHullsData ) ); +} + +struct +{ + b3MeshData* meshData; +} g_weldedHullsData; + +void CreateWeldedHulls( b3WorldId worldId ) +{ + memset( &g_weldedHullsData, 0, sizeof( g_weldedHullsData ) ); + + float tilt = 0.0f * B3_PI; + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = (b3Vec3){ 0.0f, 0.0f, 0.0f }; + bodyDef.rotation = b3MakeQuatFromAxisAngle( (b3Vec3){ 1.0f, 0.0f, 0.0 }, tilt ); + b3BodyId groundId = b3CreateBody( worldId, &bodyDef ); + + int xCount = 200; + // int zCount = BENCHMARK_DEBUG ? 100 : 400; + int zCount = 400; + + float cellWidth = 1.0f; + float amplitude = 0.4f; + float rowHz = 0.05f; + float columnHz = 0.1f; + + g_weldedHullsData.meshData = b3CreateWaveMesh( xCount, zCount, cellWidth, amplitude, rowHz, columnHz ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateMeshShape( groundId, &shapeDef, g_weldedHullsData.meshData, b3Vec3_one ); + + int entityCount = BENCHMARK_DEBUG ? 10 : 90; + + int shapeCount = 22; + b3Hull* hulls[22] = { 0 }; + + float y = 1.0f; + float r = 0.75f; + float l = 1.5f; + for ( int i = 0; i < shapeCount; ++i ) + { + hulls[i] = b3CreateCylinder( l + 2.0f * r, r, y - r, 6 ); + y += l + 2.0f * r; + r = 0.95f * r; + } + + b3WeldJointDef jointDef = b3DefaultWeldJointDef(); + jointDef.angularHertz = 6.0f; + jointDef.angularDampingRatio = 2.0f; + + float angularVelocity = -0.5f; + float z = BENCHMARK_DEBUG ? -15.0f : -140.0f; + b3CosSin cs = b3ComputeCosSin( tilt ); + float yTilt = cs.sine / cs.cosine; + + int shapesPerBody = 5; + + shapeDef.baseMaterial.friction = 0.9f; + shapeDef.baseMaterial.rollingResistance = 0.1f; + shapeDef.updateBodyMass = false; + shapeDef.density = 1.0f; + + bodyDef.type = b3_dynamicBody; + bodyDef.sleepThreshold = 0.2f; + + for ( int entityIndex = 0; entityIndex < entityCount; ++entityIndex ) + { + b3BodyId prevBodyId = b3_nullBodyId; + + y = 1.0f; + r = 0.75f; + b3Vec3 base = (b3Vec3){ 0.0, 1.0f - z * yTilt, z }; + bodyDef.position = base; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + float velocityScale = 0.5f + ( 0.5f * entityIndex ) / entityCount; + + for ( int i = 0; i < shapeCount; ++i ) + { + b3CreateHullShape( bodyId, &shapeDef, hulls[i] ); + + if ( ( i + 1 ) % shapesPerBody == 0 || i == shapeCount - 1 ) + { + b3Body_ApplyMassFromShapes( bodyId ); + + b3Vec3 center = b3Body_GetWorldCenterOfMass( bodyId ); + b3Vec3 omega = { 0.0f, 0.0f, angularVelocity * velocityScale }; + b3Vec3 v = b3Cross( omega, b3Sub( center, base ) ); + b3Body_SetAngularVelocity( bodyId, omega ); + b3Body_SetLinearVelocity( bodyId, v ); + + if ( i < shapeCount - 1 ) + { + prevBodyId = bodyId; + + if ( i < shapeCount - 1 ) + { + bodyId = b3CreateBody( worldId, &bodyDef ); + + if ( B3_IS_NON_NULL( prevBodyId ) ) + { + jointDef.base.bodyIdA = prevBodyId; + jointDef.base.bodyIdB = bodyId; + jointDef.base.localFrameA.p = (b3Vec3){ 0.0f, y + l + r, 0.0f }; + jointDef.base.localFrameB.p = (b3Vec3){ 0.0f, y + l + r, 0.0f }; + + b3CreateWeldJoint( worldId, &jointDef ); + } + + velocityScale *= 0.75f; + } + } + } + + y += l + 2.0f * r; + r = 0.95f * r; + } + + z += 3.0f; + angularVelocity = -angularVelocity; + } + + for ( int i = 0; i < shapeCount; ++i ) + { + b3DestroyHull( hulls[i] ); + } +} + +void DestroyWeldedHulls( void ) +{ + b3DestroyMesh( g_weldedHullsData.meshData ); + memset( &g_weldedHullsData, 0, sizeof( g_weldedHullsData ) ); +} + +struct JunkyardData +{ + b3BodyId pusherId; + float degrees; + float radius; +} g_junkyardData; + +void CreateJunkyard( b3WorldId worldId ) +{ + b3BodyId groundId; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position.y = -1.0f; + groundId = b3CreateBody( worldId, &bodyDef ); + } + + { + b3ShapeDef shapeDef = b3DefaultShapeDef(); + { + b3BoxHull box = b3MakeBoxHull( 120.0f, 1.0f, 120.0f ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + { + b3Vec3 offset = { -50.0f, 8.0f, 0.0f }; + b3BoxHull box = b3MakeOffsetBoxHull( 1.0f, 8.0f, 50.0f, offset ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + { + b3Vec3 offset = { 50.0f, 8.0f, 0.0f }; + b3BoxHull box = b3MakeOffsetBoxHull( 1.0f, 8.0f, 50.0f, offset ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + { + b3Vec3 offset = { 0.0f, 8.0f, -50.0f }; + b3BoxHull box = b3MakeOffsetBoxHull( 50.0f, 8.0f, 1.0f, offset ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + { + b3Vec3 offset = { 0.0f, 8.0f, 50.0f }; + b3BoxHull box = b3MakeOffsetBoxHull( 50.0f, 8.0f, 1.0f, offset ); + b3CreateHullShape( groundId, &shapeDef, &box.base ); + } + } + { + b3Hull* hull; + { + float radius = 1.5f; + int pointCount = 10; + + // Golden ratio + const float phi = ( 1.0f + sqrtf( 5.0f ) ) / 2.0f; + + // Random points on sphere (Fibonacci lattice) + b3Vec3 points[10]; + for ( int i = 0; i < pointCount; ++i ) + { + float Theta = 2.0f * B3_PI * i / phi; // Azimuthal angle + float Z = 1.0f - ( 2.0f * i + 1.0f ) / pointCount; // Z coordinate + float Radius_XY = sqrtf( 1.0f - Z * Z ); // Radius in xy-plane + + points[i].x = radius * Radius_XY * cosf( Theta ); + points[i].y = radius * Radius_XY * sinf( Theta ); + points[i].z = radius * Z; + } + + hull = b3CreateHull( points, pointCount, pointCount ); + } + + int count = BENCHMARK_DEBUG ? 2 : 24; + float height = 24.0f; + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + for ( int Y = 0; Y < count; ++Y ) + { + for ( int X = 0; X <= 20; ++X ) + { + for ( int Z = 0; Z <= 20; ++Z ) + { + bodyDef.position.x = -40.0f + 4.0f * X; + bodyDef.position.y = 4.0f * Y + height + 1.0f; + bodyDef.position.z = -40.0f + 4.0f * Z; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, hull ); + } + } + } + + b3DestroyHull( hull ); + } + + g_junkyardData.radius = 35.0f; + float mHeight = 24.0f; + + b3Hull* hull = b3CreateCylinder( mHeight, 4.0f, 0.0f, 16 ); + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_kinematicBody; + bodyDef.position = (b3Vec3){ g_junkyardData.radius, 0.0f, 0.0f }; + g_junkyardData.pusherId = b3CreateBody( worldId, &bodyDef ); + g_junkyardData.degrees = 0.0f; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( g_junkyardData.pusherId, &shapeDef, hull ); + b3DestroyHull( hull ); +} + +void StepJunkyard( b3WorldId worldId, int stepCount ) +{ + (void)worldId; + (void)stepCount; + + float timeStep = 1.0f / 60.0f; + const float omega = -6.0f; + g_junkyardData.degrees += omega * timeStep; + b3CosSin cs = b3ComputeCosSin( g_junkyardData.degrees * B3_PI / 180.0f ); + float r = g_junkyardData.radius; + b3Vec3 targetPos = { r * cs.cosine, 0.0f, r * cs.sine }; + b3Transform target = { .p = targetPos, .q = b3Quat_identity }; + b3Body_SetTargetTransform( g_junkyardData.pusherId, target, timeStep, false ); +} diff --git a/shared/benchmarks.h b/shared/benchmarks.h new file mode 100644 index 0000000..8f07af5 --- /dev/null +++ b/shared/benchmarks.h @@ -0,0 +1,47 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT +#pragma once + +#include "box3d/id.h" + +#include + +// This allows benchmarks to be tested on the benchmark app and also visualized in the samples app + +typedef struct b3Capacity b3Capacity; + +#ifdef __cplusplus +extern "C" +{ +#endif + +void CreateCompoundCapsules( b3WorldId worldId ); +void DestroyCompoundCapsules( void ); +void CreateCompoundHulls( b3WorldId worldId ); +void DestroyCompoundHulls( void ); +void CreateJointGrid( b3WorldId worldId ); +void CreateJunkyard( b3WorldId worldId ); +void StepJunkyard( b3WorldId worldId, int stepCount ); +void CreateLargePyramid( b3WorldId worldId ); +//void CreateLargeWorld( b3WorldId worldId ); +//void StepLargeWorld( b3WorldId worldId, int stepCount ); +//void DestroyLargeWorld( void ); +void CreateWidePyramid( b3WorldId worldId ); +void CreateManyPyramids( b3WorldId worldId ); +void GetRainCapacity( b3Capacity* capacity ); +void CreateRain( b3WorldId worldId ); +void StepRain( b3WorldId worldId, int stepCount ); +void DestroyRain( void ); +void GetWasherCapacity( b3Capacity* capacity ); +void CreateWasher( b3WorldId worldId ); +void CreateWeldedHulls( b3WorldId worldId ); +void DestroyWeldedHulls( void ); + +// void CreateSpinner( b3WorldId worldId ); +// float StepSpinner( b3WorldId worldId, int stepCount ); +// void CreateSmash( b3WorldId worldId ); +// void CreateTumbler( b3WorldId worldId ); + +#ifdef __cplusplus +} +#endif diff --git a/shared/determinism.c b/shared/determinism.c new file mode 100644 index 0000000..011cac1 --- /dev/null +++ b/shared/determinism.c @@ -0,0 +1,124 @@ +// SPDX-FileCopyrightText: 2022 Erin Catto +// SPDX-License-Identifier: MIT + +#include "determinism.h" + +#include "human.h" + +#include "box3d/box3d.h" + +#include +#include + +#define GRID_SIZE 15.0f + +static void CreateGroup( FallingRagdollData* data, b3WorldId worldId, int rowIndex, int columnIndex ) +{ + assert( rowIndex < RAGDOLL_GRID_COUNT && columnIndex < RAGDOLL_GRID_COUNT ); + + int groupIndex = rowIndex * RAGDOLL_GRID_COUNT + columnIndex; + + float span = RAGDOLL_GRID_COUNT * GRID_SIZE; + float groupDistance = 1.0f * span / RAGDOLL_GRID_COUNT; + + b3Vec3 position; + position.x = -0.5f * span + groupDistance * ( columnIndex + 0.5f ); + position.y = 15.0f; + position.z = -0.5f * span + groupDistance * ( rowIndex + 0.5f ); + + float frictionTorque = 5.0f; + float hertz = 1.0f; + float dampingRatio = 0.7f; + bool colorize = false; + + for ( int i = 0; i < RAGDOLL_GROUP_SIZE; ++i ) + { + Human* human = data->groups[groupIndex].humans + i; + CreateHuman( human, worldId, position, frictionTorque, hertz, dampingRatio, groupIndex, NULL, colorize ); + position.x += 0.75f; + } +} + +FallingRagdollData CreateFallingRagdolls( b3WorldId worldId ) +{ + FallingRagdollData data = { 0 }; + + int halfMeshGridRows = 4; + float meshGridCellWidth = GRID_SIZE / ( 2.0f * halfMeshGridRows ); + data.gridMesh = b3CreateGridMesh( 2 * halfMeshGridRows, 2 * halfMeshGridRows, meshGridCellWidth, 0, true ); + data.torusMesh = b3CreateTorusMesh( 16, 16, 0.25f * GRID_SIZE, 1.0f ); + + float span = GRID_SIZE * RAGDOLL_GRID_COUNT; + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + bodyDef.position.x = -0.5f * span + 0.5f * GRID_SIZE; + for ( int i = 0; i < RAGDOLL_GRID_COUNT; ++i ) + { + bodyDef.position.z = -0.5f * span + 0.5f * GRID_SIZE; + for ( int j = 0; j < RAGDOLL_GRID_COUNT; ++j ) + { + b3BodyId body = b3CreateBody( worldId, &bodyDef ); + b3CreateMeshShape( body, &shapeDef, data.gridMesh, b3Vec3_one ); + b3CreateMeshShape( body, &shapeDef, data.torusMesh, b3Vec3_one ); + + CreateGroup( &data, worldId, i, j ); + + bodyDef.position.z += GRID_SIZE; + } + + bodyDef.position.x += GRID_SIZE; + } + + return data; +} + +bool UpdateFallingRagdolls( b3WorldId worldId, FallingRagdollData* data ) +{ + if ( data->hash == 0 ) + { + b3BodyEvents bodyEvents = b3World_GetBodyEvents( worldId ); + + if ( bodyEvents.moveCount == 0 ) + { + int awakeCount = b3World_GetAwakeBodyCount( worldId ); + assert( awakeCount == 0 ); + + data->hash = B3_HASH_INIT; + for ( int i = 0; i < RAGDOLL_GRID_COUNT; ++i ) + { + for ( int j = 0; j < RAGDOLL_GRID_COUNT; ++j ) + { + for ( int k = 0; k < RAGDOLL_GROUP_SIZE; ++k ) + { + int groupIndex = i * RAGDOLL_GRID_COUNT + j; + + Human* human = data->groups[groupIndex].humans + k; + + for ( int b = 0; b < bone_count; ++b ) + { + b3BodyId bodyId = human->bones[b].bodyId; + b3Transform xf = b3Body_GetTransform( bodyId ); + data->hash = b3Hash( data->hash, (uint8_t*)( &xf ), sizeof( b3Transform ) ); + } + } + } + } + + data->sleepStep = data->stepCount; + } + } + + data->stepCount += 1; + + return data->hash != 0; +} + +void DestroyFallingRagdolls( FallingRagdollData* data ) +{ + b3DestroyMesh( data->gridMesh ); + b3DestroyMesh( data->torusMesh ); + + data->gridMesh = NULL; + data->torusMesh = NULL; +} diff --git a/shared/determinism.h b/shared/determinism.h new file mode 100644 index 0000000..0839fbf --- /dev/null +++ b/shared/determinism.h @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT +#pragma once + +#include "box3d/id.h" + +#include "human.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + +#define RAGDOLL_GROUP_SIZE 2 +#define RAGDOLL_GRID_COUNT 2 + +typedef struct RagdollGroup +{ + Human humans[RAGDOLL_GROUP_SIZE]; +} RagdollGroup; + +typedef struct FallingRagdollData +{ + RagdollGroup groups[RAGDOLL_GRID_COUNT * RAGDOLL_GRID_COUNT]; + b3MeshData* gridMesh; + b3MeshData* torusMesh; + int columnCount; + int columnIndex; + int stepCount; + int sleepStep; + uint32_t hash; +} FallingRagdollData; + +FallingRagdollData CreateFallingRagdolls( b3WorldId worldId ); +bool UpdateFallingRagdolls( b3WorldId worldId, FallingRagdollData* data ); +void DestroyFallingRagdolls( FallingRagdollData* data ); + +#ifdef __cplusplus +} +#endif diff --git a/shared/human.c b/shared/human.c new file mode 100644 index 0000000..ea87668 --- /dev/null +++ b/shared/human.c @@ -0,0 +1,775 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#include "human.h" + +#include "utils.h" + +#include "box3d/box3d.h" + +#include +#include + +void CreateHuman( Human* human, b3WorldId worldId, b3Vec3 position, 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 = b3_nullBodyId; + human->bones[i].anchorId = b3_nullBodyId; + human->bones[i].jointId = b3_nullJointId; + human->bones[i].jointFriction = 1.0f; + human->bones[i].parentIndex = -1; + } + + for ( int i = 0; i < FILTER_JOINT_COUNT; ++i ) + { + human->filterJoints[i] = b3_nullJointId; + } + + human->frictionTorque = frictionTorque; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.userData = userData; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + // shapeDef.friction = 0.2f; + shapeDef.baseMaterial.rollingResistance = 0.2f; + + b3HexColor shirtColor = b3_colorMediumTurquoise; + b3HexColor pantColor = b3_colorDodgerBlue; + b3HexColor skinColors[4] = { b3_colorNavajoWhite, b3_colorLightYellow, b3_colorPeru, b3_colorTan }; + b3HexColor skinColor = skinColors[groupIndex % 4]; + + { + Bone* bone = human->bones + bone_pelvis; + + bone->parentIndex = -1; + + bodyDef.name = "pelvis"; + bone->referenceFrame = ( b3Transform ){ { 0.0f, 0.932087f, -0.051708f }, { { 0.739169f, 0.0f, 0.0f }, 0.673520f } }; + bodyDef.rotation = bone->referenceFrame.q; + bodyDef.position = b3Add( bone->referenceFrame.p, position ); + bone->bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Capsule capsule = { { 0.07f, 0.0f, -0.08f }, { -0.07f, 0.0f, -0.08f }, 0.13f }; + shapeDef.filter.groupIndex = 0; + shapeDef.baseMaterial.customColor = colorize ? pantColor : 0; + + b3CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); + } + + { + Bone* bone = human->bones + bone_spine_01; + bone->parentIndex = bone_pelvis; + + bodyDef.name = "spine_01"; + bone->referenceFrame = ( b3Transform ){ { 0.0f, 1.113505f, -0.03481f }, { { 0.739973f, 0.0f, 0.0f }, 0.672637f } }; + bodyDef.rotation = bone->referenceFrame.q; + bodyDef.position = b3Add( bone->referenceFrame.p, position ); + //bodyDef.type = b3_staticBody; + bone->bodyId = b3CreateBody( worldId, &bodyDef ); + bodyDef.type = b3_dynamicBody; + + b3Capsule capsule = { { 0.06f, -0.0f, -0.052264f }, { -0.06f, 0.0f, -0.052264f }, 0.12f }; + shapeDef.filter.groupIndex = -groupIndex; + shapeDef.baseMaterial.customColor = colorize ? shirtColor : 0; + b3CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); + + bone->jointType = b3_sphericalJoint; + bone->localFrameA = + ( b3Transform ){ { 0.000000, 0.000000, -0.182204 }, { { -0.999999, 0.000000, -0.000000 }, 0.001194 } }; + bone->localFrameB = + ( b3Transform ){ { 0.000000, 0.000000, -0.007736 }, { { -1.000000, 0.000000, -0.000000 }, 0.000000 } }; + bone->swingLimit = 25.0f * B3_DEG_TO_RAD; + bone->twistLimit = ( b3Vec2 ){ -15.0f * B3_DEG_TO_RAD, 15.0f * B3_DEG_TO_RAD }; + } + + { + Bone* bone = human->bones + bone_spine_02; + bone->parentIndex = bone_spine_01; + + // bodyDef.name = "spine_02"; + bone->referenceFrame = ( b3Transform ){ { 0.0f, 1.194336f, -0.027087f }, { { 0.703611f, 0.0f, 0.0f }, 0.710586f } }; + bodyDef.rotation = bone->referenceFrame.q; + bodyDef.position = b3Add( bone->referenceFrame.p, position ); + bone->bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Capsule capsule = { { 0.08f, -0.015133f, -0.091801f }, { -0.08f, -0.015133f, -0.091801f }, 0.10f }; + shapeDef.filter.groupIndex = 0; + shapeDef.baseMaterial.customColor = colorize ? shirtColor : 0; + b3CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); + + bone->jointType = b3_sphericalJoint; + bone->localFrameA = + ( b3Transform ){ { 0.000000, -0.000000, -0.088935 }, { { -0.998619, -0.000000, 0.000000 }, -0.052540 } }; + bone->localFrameB = + ( b3Transform ){ { -0.000000, 0.000000, -0.008199 }, { { -1.000000, 0.000000, -0.000000 }, 0.000000 } }; + bone->swingLimit = 25.0f * B3_DEG_TO_RAD; + bone->twistLimit = ( b3Vec2 ){ -15.0f * B3_DEG_TO_RAD, 15.0f * B3_DEG_TO_RAD }; + } + + { + Bone* bone = human->bones + bone_spine_03; + bone->parentIndex = bone_spine_02; + + bodyDef.name = "spine_03"; + bone->referenceFrame = + ( b3Transform ){ { -0.0f, 1.31043f, -0.028232f }, { { 0.669856f, 0.000001f, -0.000001f }, 0.742491f } }; + bodyDef.rotation = bone->referenceFrame.q; + bodyDef.position = b3Add( bone->referenceFrame.p, position ); + bone->bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Capsule capsule = { { 0.11f, -0.039753f, -0.13f }, { -0.11f, -0.039753f, -0.13f }, 0.145f }; + shapeDef.filter.groupIndex = 0; + shapeDef.baseMaterial.customColor = colorize ? shirtColor : 0; + b3CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); + + bone->jointType = b3_sphericalJoint; + bone->localFrameA = + ( b3Transform ){ { -0.000000, 0.000000, -0.124298 }, { { -0.998921, 0.000001, -0.000001 }, -0.046434 } }; + bone->localFrameB = ( b3Transform ){ { 0.000000, 0.000000, 0.000000 }, { { -1.000000, 0.000000, -0.000001 }, 0.000000 } }; + bone->swingLimit = 15.0f * B3_DEG_TO_RAD; + bone->twistLimit = ( b3Vec2 ){ -10.0f * B3_DEG_TO_RAD, 10.0f * B3_DEG_TO_RAD }; + } + + { + Bone* bone = human->bones + bone_neck; + bone->parentIndex = bone_spine_03; + + bodyDef.name = "neck"; + bone->referenceFrame = ( b3Transform ){ { 0.0f, 1.575582f, -0.055837f }, { { 0.879922f, 0.0f, 0.0f }, 0.475118f } }; + bodyDef.rotation = bone->referenceFrame.q; + bodyDef.position = b3Add( bone->referenceFrame.p, position ); + bone->bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Capsule capsule = { { -0.000001f, -0.0f, -0.02f }, { 0.0f, -0.005f, -0.08f }, 0.07f }; + shapeDef.filter.groupIndex = 0; + shapeDef.baseMaterial.customColor = colorize ? skinColor : 0; + b3CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); + + bone->jointType = b3_sphericalJoint; + bone->localFrameA = + ( b3Transform ){ { 0.000001, -0.000259, -0.266585 }, { { -0.942192, -0.000001, 0.000000 }, 0.335074 } }; + bone->localFrameB = ( b3Transform ){ { 0.000000, 0.000000, 0.000000 }, { { -1.000000, 0.000000, -0.000001 }, 0.000000 } }; + bone->swingLimit = 45.0f * B3_DEG_TO_RAD; + bone->twistLimit = ( b3Vec2 ){ -15.0f * B3_DEG_TO_RAD, 15.0f * B3_DEG_TO_RAD }; + bone->jointFriction = 0.8f; + } + + { + Bone* bone = human->bones + bone_head; + bone->parentIndex = bone_neck; + + bodyDef.name = "head"; + bone->referenceFrame = ( b3Transform ){ { 0.0f, 1.653348f, -0.003241f }, { { 0.750288f, 0.0f, 0.0f }, 0.661111f } }; + bodyDef.rotation = bone->referenceFrame.q; + bodyDef.position = b3Add( bone->referenceFrame.p, position ); + bone->bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Capsule capsule = { { -0.000001f, 0.016892f, -0.05869f }, { 0.0f, -0.003629f, -0.115072f }, 0.0975f }; + shapeDef.filter.groupIndex = 0; + shapeDef.baseMaterial.customColor = colorize ? skinColor : 0; + b3CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); + + bone->jointType = b3_sphericalJoint; + bone->localFrameA = + ( b3Transform ){ { 0.000000, 0.001321, -0.093873 }, { { -0.974301, -0.000000, -0.000000 }, -0.225251 } }; + bone->localFrameB = ( b3Transform ){ { 0.000000, 0.001268, -0.005104 }, { { -1.000000, 0.000000, -0.00000 }, 0.000000 } }; + bone->swingLimit = 15.0f * B3_DEG_TO_RAD; + bone->twistLimit = ( b3Vec2 ){ -15.0f * B3_DEG_TO_RAD, 15.0f * B3_DEG_TO_RAD }; + bone->jointFriction = 0.4f; + } + + { + Bone* bone = human->bones + bone_thigh_l; + bone->parentIndex = bone_pelvis; + + bodyDef.name = "thigh_l"; + bone->referenceFrame = + ( b3Transform ){ { 0.090416f, 0.986104f, -0.035090f }, { { -0.703287f, -0.070715f, 0.053866f }, 0.705327f } }; + bodyDef.rotation = bone->referenceFrame.q; + bodyDef.position = b3Add( bone->referenceFrame.p, position ); + bone->bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Capsule capsule = { { 0.023719f, 0.006008f, -0.039068f }, { -0.064492f, -0.004664f, -0.424718f }, 0.09f }; + shapeDef.filter.groupIndex = -groupIndex; + shapeDef.baseMaterial.customColor = colorize ? pantColor : 0; + b3CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); + + bone->jointType = b3_sphericalJoint; + bone->localFrameA = + ( b3Transform ){ { 0.05f, 0.011537f, -0.055325f }, { { -0.714896, -0.022305, -0.698361 }, -0.026790 } }; + bone->localFrameB = ( b3Transform ){ { 0.0f, 0.0f, 0.0f }, { { -0.002064, 0.758987, 0.017046 }, 0.650880 } }; + bone->swingLimit = 10.0f * B3_DEG_TO_RAD; + bone->twistLimit = ( b3Vec2 ){ -60.0f * B3_DEG_TO_RAD, 40.0f * B3_DEG_TO_RAD }; + } + + { + Bone* bone = human->bones + bone_calf_l; + bone->parentIndex = bone_thigh_l; + + bodyDef.name = "calf_l"; + bone->referenceFrame = + ( b3Transform ){ { 0.101198f, 0.527027f, -0.037374f }, { { -0.653328f, -0.066860f, 0.058582f }, 0.751838f } }; + bodyDef.rotation = bone->referenceFrame.q; + bodyDef.position = b3Add( bone->referenceFrame.p, position ); + bone->bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Capsule capsule = { { 0.001778f, 0.0f, 0.009841f }, { -0.078577f, 0.014707f, -0.41816f }, 0.075f }; + shapeDef.filter.groupIndex = 0; + shapeDef.baseMaterial.customColor = colorize ? pantColor : 0; + b3CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); + + bone->jointType = b3_revoluteJoint; + bone->localFrameA = + ( b3Transform ){ { -0.069989, 0.000253, -0.453844 }, { { -0.000677, 0.760087, 0.105674 }, 0.641171 } }; + bone->localFrameB = ( b3Transform ){ { 0.0f, 0.0f, 0.0f }, { { -0.044589, 0.765540, 0.053368 }, 0.639619 } }; + bone->twistLimit = ( b3Vec2 ){ -5.0f * B3_DEG_TO_RAD, 45.0f * B3_DEG_TO_RAD }; + } + + { + Bone* bone = human->bones + bone_thigh_r; + bone->parentIndex = bone_pelvis; + + bodyDef.name = "thigh_r"; + bone->referenceFrame = + ( b3Transform ){ { -0.090416f, 0.986104f, -0.03509f }, { { -0.703287f, 0.070715f, -0.053865f }, 0.705326f } }; + bodyDef.rotation = bone->referenceFrame.q; + bodyDef.position = b3Add( bone->referenceFrame.p, position ); + bone->bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Capsule capsule = { { -0.023719f, 0.006008f, -0.039068f }, { 0.064492f, -0.004664f, -0.424718f }, 0.09f }; + shapeDef.filter.groupIndex = -groupIndex; + shapeDef.baseMaterial.customColor = colorize ? pantColor : 0; + b3CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); + + bone->jointType = b3_sphericalJoint; + bone->localFrameA = ( b3Transform ){ { -0.05, 0.011537, -0.055326 }, { { -0.039089, -0.714094, 0.043177 }, 0.697623 } }; + bone->localFrameB = ( b3Transform ){ { 0.0f, 0.0f, 0.0f }, { { 0.758805, -0.019886, -0.651012 }, -0.001759 } }; + bone->swingLimit = 10.0f * B3_DEG_TO_RAD; + bone->twistLimit = ( b3Vec2 ){ -30.0f * B3_DEG_TO_RAD, 60.0f * B3_DEG_TO_RAD }; + } + + { + Bone* bone = human->bones + bone_calf_r; + bone->parentIndex = bone_thigh_r; + + bodyDef.name = "calf_r"; + bone->referenceFrame = + ( b3Transform ){ { -0.101198f, 0.527027f, -0.037373f }, { { -0.653327f, 0.06686f, -0.058582f }, 0.751839f } }; + bodyDef.rotation = bone->referenceFrame.q; + bodyDef.position = b3Add( bone->referenceFrame.p, position ); + bone->bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Capsule capsule = { { -0.001820f, 0.0f, 0.010071f }, { 0.077883f, 0.014825f, -0.418047f }, 0.075f }; + shapeDef.filter.groupIndex = 0; + shapeDef.baseMaterial.customColor = colorize ? pantColor : 0; + b3CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); + + bone->jointType = b3_revoluteJoint; + bone->localFrameA = + ( b3Transform ){ { 0.069988, 0.000253, -0.453844 }, { { 0.760086, -0.000675, -0.641171 }, -0.105676 } }; + bone->localFrameB = ( b3Transform ){ { 0.0f, 0.0f, 0.0f }, { { 0.765540, -0.044589, -0.639619 }, -0.053368 } }; + bone->twistLimit = ( b3Vec2 ){ -45.0f * B3_DEG_TO_RAD, 5.0f * B3_DEG_TO_RAD }; + } + + { + Bone* bone = human->bones + bone_upper_arm_l; + bone->parentIndex = bone_spine_03; + + bodyDef.name = "upper_arm_l"; + bone->referenceFrame = + ( b3Transform ){ { 0.20378f, 1.484275f, -0.115897f }, { { 0.143082f, 0.695980f, -0.690130f }, 0.13733f } }; + bodyDef.rotation = bone->referenceFrame.q; + bodyDef.position = b3Add( bone->referenceFrame.p, position ); + bone->bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Capsule capsule = { { 0.0f, 0.0f, 0.0f }, { -0.091118f, 0.037775f, 0.229719f }, 0.075f }; + shapeDef.filter.groupIndex = 0; + shapeDef.baseMaterial.customColor = colorize ? shirtColor : 0; + b3CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); + + bone->jointType = b3_sphericalJoint; + bone->localFrameA = + ( b3Transform ){ { 0.203780, -0.069369, -0.181921 }, { { -0.278486, 0.445600, -0.097014 }, 0.845266 } }; + bone->localFrameB = ( b3Transform ){ { 0.000000, 0.000000, 0.000000 }, { { -0.201396, -0.001586, 0.901850 }, 0.382234 } }; + bone->swingLimit = 60.0f * B3_DEG_TO_RAD; + bone->twistLimit = ( b3Vec2 ){ -5.0f * B3_DEG_TO_RAD, 5.0f * B3_DEG_TO_RAD }; + } + + { + Bone* bone = human->bones + bone_lower_arm_l; + bone->parentIndex = bone_upper_arm_l; + + bodyDef.name = "lower_arm_l"; + bone->referenceFrame = + ( b3Transform ){ { 0.305614f, 1.242908f, -0.117599f }, { { 0.165048f, 0.563437f, -0.802002f }, 0.109959f } }; + bodyDef.rotation = bone->referenceFrame.q; + bodyDef.position = b3Add( bone->referenceFrame.p, position ); + bone->bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Capsule capsule = { { 0.0f, 0.0f, 0.0f }, { -0.142406f, 0.039392f, 0.261092f }, 0.05f }; + shapeDef.filter.groupIndex = 0; + shapeDef.baseMaterial.customColor = colorize ? skinColor : 0; + b3CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); + + bone->jointType = b3_revoluteJoint; + bone->localFrameA = ( b3Transform ){ { -0.095482, 0.039584, 0.240723 }, { { 0.512487, -0.180629, 0.839474 }, 0.003742 } }; + bone->localFrameB = ( b3Transform ){ { 0.0f, 0.0f, 0.0f }, { { 0.503803, -0.029831, 0.858168 }, 0.094017 } }; + bone->twistLimit = ( b3Vec2 ){ -5.0f * B3_DEG_TO_RAD, 60.0f * B3_DEG_TO_RAD }; + } + + { + Bone* bone = human->bones + bone_upper_arm_r; + bone->parentIndex = bone_spine_03; + + bodyDef.name = "upper_arm_r"; + bone->referenceFrame = + ( b3Transform ){ { -0.20378f, 1.484276f, -0.115899f }, { { 0.143083f, -0.695978f, 0.690132f }, 0.137329f } }; + bodyDef.rotation = bone->referenceFrame.q; + bodyDef.position = b3Add( bone->referenceFrame.p, position ); + bone->bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Capsule capsule = { { 0.0f, 0.0f, 0.0f }, { 0.091118f, 0.037775f, 0.229718f }, 0.075f }; + shapeDef.filter.groupIndex = 0; + shapeDef.baseMaterial.customColor = colorize ? shirtColor : 0; + b3CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); + + bone->jointType = b3_sphericalJoint; + bone->localFrameA = + ( b3Transform ){ { -0.203779, -0.069371, -0.181922 }, { { -0.253621, -0.414842, 0.106962 }, 0.867261 } }; + bone->localFrameB = ( b3Transform ){ { 0.000000, 0.000000, 0.000000 }, { { -0.201397, 0.001587, -0.901850 }, 0.382233 } }; + bone->swingLimit = 60.0f * B3_DEG_TO_RAD; + bone->twistLimit = ( b3Vec2 ){ -5.0f * B3_DEG_TO_RAD, 5.0f * B3_DEG_TO_RAD }; + } + + { + Bone* bone = human->bones + bone_lower_arm_r; + bone->parentIndex = bone_upper_arm_r; + + bodyDef.name = "lower_arm_r"; + bone->referenceFrame = + ( b3Transform ){ { -0.305614f, 1.242907f, -0.117599f }, { { 0.165048f, -0.563437f, 0.802002f }, 0.109959f } }; + bodyDef.rotation = bone->referenceFrame.q; + bodyDef.position = b3Add( bone->referenceFrame.p, position ); + bone->bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Capsule capsule = { { 0.0f, 0.0f, 0.0f }, { 0.142406f, 0.039392f, 0.261092f }, 0.05f }; + shapeDef.filter.groupIndex = 0; + shapeDef.baseMaterial.customColor = colorize ? skinColor : 0; + b3CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); + + bone->jointType = b3_revoluteJoint; + bone->localFrameA = + ( b3Transform ){ { 0.095484, 0.039585, 0.240723 }, { { -0.180627, 0.512487, -0.003744 }, -0.839474 } }; + bone->localFrameB = ( b3Transform ){ { 0.0f, 0.0f, 0.0f }, { { -0.029831, 0.503803, -0.094017 }, -0.858169 } }; + bone->twistLimit = ( b3Vec2 ){ -60.0f * B3_DEG_TO_RAD, 5.0f * B3_DEG_TO_RAD }; + } + + // float dampingRatio = 0.9f; + for ( int i = 1; i < bone_count; ++i ) + { + Bone* bone = human->bones + i; + Bone* parent = human->bones + bone->parentIndex; + + b3BodyId bodyIdA = parent->bodyId; + b3BodyId bodyIdB = bone->bodyId; + + b3Transform frameA = b3NormalizeTransform( bone->localFrameA ); + b3Transform frameB = b3NormalizeTransform( bone->localFrameB ); + + if ( bone->jointType == b3_revoluteJoint ) + { + b3RevoluteJointDef jointDef = b3DefaultRevoluteJointDef(); + jointDef.base.bodyIdA = bodyIdA; + jointDef.base.bodyIdB = bodyIdB; + jointDef.base.localFrameA = frameA; + jointDef.base.localFrameB = frameB; + jointDef.enableLimit = true; + jointDef.lowerAngle = bone->twistLimit.x; + jointDef.upperAngle = bone->twistLimit.y; + jointDef.enableSpring = hertz > 0.0f; + jointDef.hertz = hertz; + jointDef.dampingRatio = dampingRatio; + jointDef.enableMotor = true; + jointDef.maxMotorTorque = bone->jointFriction * frictionTorque; + bone->jointId = b3CreateRevoluteJoint( worldId, &jointDef ); + } + else if ( bone->jointType == b3_sphericalJoint ) + { + b3SphericalJointDef jointDef = b3DefaultSphericalJointDef(); + jointDef.base.bodyIdA = bodyIdA; + jointDef.base.bodyIdB = bodyIdB; + jointDef.base.localFrameA = frameA; + jointDef.base.localFrameB = frameB; + jointDef.enableConeLimit = true; + jointDef.coneAngle = bone->swingLimit; + jointDef.enableTwistLimit = true; + jointDef.lowerTwistAngle = bone->twistLimit.x; + jointDef.upperTwistAngle = bone->twistLimit.y; + jointDef.enableSpring = hertz > 0.0f; + jointDef.hertz = hertz; + jointDef.dampingRatio = dampingRatio; + jointDef.enableMotor = true; + jointDef.maxMotorTorque = bone->jointFriction * frictionTorque; + bone->jointId = b3CreateSphericalJoint( worldId, &jointDef ); + } + } + + // Disable some collisions + b3FilterJointDef filterDef = b3DefaultFilterJointDef(); + filterDef.base.bodyIdA = human->bones[bone_thigh_l].bodyId; + filterDef.base.bodyIdB = human->bones[bone_thigh_r].bodyId; + human->filterJoints[0] = b3CreateFilterJoint( worldId, &filterDef ); + human->filterJointCount = 1; + + human->isSpawned = true; +} + +void DestroyHuman( Human* human ) +{ + assert( human->isSpawned == true ); + + for ( int i = 0; i < human->filterJointCount; ++i ) + { + b3DestroyJoint( human->filterJoints[i], false ); + human->filterJoints[i] = b3_nullJointId; + } + + for ( int i = 0; i < bone_count; ++i ) + { + if ( B3_IS_NULL( human->bones[i].jointId ) ) + { + continue; + } + + b3DestroyJoint( human->bones[i].jointId, false ); + human->bones[i].jointId = b3_nullJointId; + } + + for ( int i = 0; i < bone_count; ++i ) + { + if ( B3_IS_NULL( human->bones[i].bodyId ) ) + { + continue; + } + + b3DestroyBody( human->bones[i].bodyId ); + human->bones[i].bodyId = b3_nullBodyId; + } + + human->isSpawned = false; +} + +void Human_SetVelocity( Human* human, b3Vec3 velocity ) +{ + for ( int i = 0; i < bone_count; ++i ) + { + b3BodyId bodyId = human->bones[i].bodyId; + + if ( B3_IS_NULL( bodyId ) ) + { + continue; + } + + b3Body_SetLinearVelocity( bodyId, velocity ); + } +} + +void Human_ApplyRandomAngularImpulse( Human* human, float magnitude ) +{ + assert( human->isSpawned == true ); + b3Vec3 range = { magnitude, magnitude, magnitude }; + b3Vec3 impulse = RandomVec3( b3Neg( range ), range ); + b3Body_ApplyAngularImpulse( human->bones[bone_spine_01].bodyId, impulse, true ); +} + +void Human_SetJointFrictionTorque( Human* human, float torque ) +{ + assert( human->isSpawned == true ); + human->frictionTorque = torque; + + for ( int i = 1; i < bone_count; ++i ) + { + Bone* bone = human->bones + i; + if ( bone->jointType == b3_revoluteJoint ) + { + b3RevoluteJoint_SetMaxMotorTorque( bone->jointId, bone->jointFriction * torque ); + } + else + { + b3SphericalJoint_SetMaxMotorTorque( bone->jointId, bone->jointFriction * torque ); + } + } +} + +void Human_SetJointSpringHertz( Human* human, float hertz ) +{ + assert( human->isSpawned == true ); + for ( int i = 1; i < bone_count; ++i ) + { + Bone* bone = human->bones + i; + if ( bone->jointType == b3_revoluteJoint ) + { + b3RevoluteJoint_SetSpringHertz( bone->jointId, hertz ); + } + else + { + b3SphericalJoint_SetSpringHertz( bone->jointId, hertz ); + } + } +} + +void Human_SetJointDampingRatio( Human* human, float dampingRatio ) +{ + assert( human->isSpawned == true ); + for ( int i = 1; i < bone_count; ++i ) + { + Bone* bone = human->bones + i; + if ( bone->jointType == b3_revoluteJoint ) + { + b3RevoluteJoint_SetSpringDampingRatio( bone->jointId, dampingRatio ); + } + else + { + b3SphericalJoint_SetSpringDampingRatio( bone->jointId, dampingRatio ); + } + } +} + +void Human_AlignSpring(Human* human, b3WorldId worldId, b3BodyId groundId, float hertz, float dampingRatio) +{ + assert( human->isSpawned == true ); + + Bone* bone = human->bones + bone_pelvis; + assert( B3_IS_NULL( bone->jointId ) == true ); + b3Quat q = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisZ, b3Vec3_axisY ); + b3Quat qb = b3Body_GetRotation( bone->bodyId ); + + b3ParallelJointDef jointDef = b3DefaultParallelJointDef(); + jointDef.base.bodyIdA = groundId; + jointDef.base.bodyIdB = bone->bodyId; + jointDef.base.localFrameA.q = q; + jointDef.base.localFrameB.q = b3InvMulQuat( qb, q ); + jointDef.base.drawScale = 2.0f; + jointDef.base.collideConnected = true; + jointDef.hertz = hertz; + jointDef.dampingRatio = dampingRatio; + + bone->jointId = b3CreateParallelJoint( worldId, &jointDef ); +} + +void Human_CreateMotorAnchors( Human* human, b3WorldId worldId ) +{ + b3BodyDef anchorDef = b3DefaultBodyDef(); + anchorDef.type = b3_kinematicBody; + + b3MotorJointDef motorDef = b3DefaultMotorJointDef(); + motorDef.angularHertz = 5.0f; + motorDef.angularDampingRatio = 1.0f; + motorDef.linearHertz = 5.0f; + motorDef.linearDampingRatio = 1.0f; + motorDef.maxSpringForce = FLT_MAX; + motorDef.maxSpringTorque = FLT_MAX; + + for ( int i = 0; i < bone_count; ++i ) + { + Bone* bone = human->bones + i; + + b3Transform bodyTransform = b3Body_GetTransform( bone->bodyId ); + anchorDef.position = bodyTransform.p; + anchorDef.rotation = bodyTransform.q; + bone->anchorId = b3CreateBody(worldId, &anchorDef ); + + motorDef.base.bodyIdA = bone->anchorId; + motorDef.base.bodyIdB = bone->bodyId; + + bone->anchorJointId = b3CreateMotorJoint( worldId, &motorDef ); + } +} + +void Human_CreateParallelAnchors( Human* human, b3WorldId worldId ) +{ + b3BodyDef anchorDef = b3DefaultBodyDef(); + anchorDef.type = b3_kinematicBody; + + b3Quat qFrameWorld = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisZ, b3Vec3_axisY ); + b3ParallelJointDef jointDef = b3DefaultParallelJointDef(); + jointDef.hertz = 8.0f; + jointDef.dampingRatio = 1.0f; + jointDef.maxTorque = 800.0f; + + for ( int i = 0; i < bone_count; ++i ) + { + Bone* bone = human->bones + i; + + b3Transform bodyTransform = b3Body_GetTransform( bone->bodyId ); + anchorDef.position = bodyTransform.p; + anchorDef.rotation = bodyTransform.q; + bone->anchorId = b3CreateBody(worldId, &anchorDef ); + + jointDef.base.bodyIdA = bone->anchorId; + jointDef.base.bodyIdB = bone->bodyId; + + b3Quat frameQuat = b3InvMulQuat( bodyTransform.q, qFrameWorld ); + jointDef.base.localFrameA.q = frameQuat; + jointDef.base.localFrameB.q = frameQuat; + + bone->anchorJointId = b3CreateParallelJoint( worldId, &jointDef ); + } +} + +#if 0 +void Human::EnablePoseControl( b3World* world, float springHertz, bool poseControl ) +{ + if ( poseControl == m_poseControl ) + { + return; + } + + if ( m_poseControl ) + { + for ( int i = 0; i < bone_count; ++i ) + { + Bone* bone = human->bones + i; + + world->RemoveJoint( bone->poseJoint, true ); + bone->poseJoint = nullptr; + } + + world->DestroyBody( m_rootBody, true ); + m_rootBody = nullptr; + } + else + { + b3BodyDef rootDef = b3DefaultBodyDef(); + rootDef.type = b3_kinematicBody; + rootDef.position = m_baseTransform.p; + rootDef.rotation = m_baseTransform.q; + m_rootBody = world->CreateBody( &rootDef ); + + float dampingRatio = 0.9f; + + for ( int i = 0; i < bone_count; ++i ) + { + Bone* bone = human->bones + i; + + b3Body* bodyIdA = m_rootBody; + b3Body* bodyIdB = bone->bodyId; + + bool enableCollision = false; + bool useBlockSolver = false; + + // bone->poseJoint = world->AddRigidJoint( bodyIdA, bodyIdB, bodyIdB->GetPosition(), enableCollision, useBlockSolver ); + bone->poseJoint = world->AddRigidJoint( bodyIdA, bone->referenceFrame, bodyIdB, b3Transform_identity, + b3Transform_identity, enableCollision, useBlockSolver ); + bone->poseJoint->SetAngularFrequency( springHertz ); + bone->poseJoint->SetAngularDampingRatio( dampingRatio ); + bone->poseJoint->SetLinearFrequency( springHertz ); + bone->poseJoint->SetLinearDampingRatio( dampingRatio ); + } + } + + m_poseControl = poseControl; +} + +void Human::AdjustPoseControl( float springHertz ) +{ + if ( m_poseControl == false ) + { + return; + } + + for ( int i = 0; i < bone_count; ++i ) + { + Bone* bone = human->bones + i; + + bone->poseJoint->SetAngularFrequency( springHertz ); + bone->poseJoint->SetLinearFrequency( springHertz ); + } +} + +void Human::DriveBase( const b3Transform& transform, float timeStep ) +{ + m_rootBody->SetVelocityFromKeyframe( transform, timeStep ); + m_baseTransform = transform; +} + +void Human::EnableMotors( bool enableMotors ) +{ + if ( enableMotors == m_motorized ) + { + return; + } + + for ( int i = 1; i < bone_count; ++i ) + { + Bone* bone = human->bones + i; + + if ( bone->joint == nullptr ) + { + continue; + } + + if ( bone->joint->mType == b3_revoluteJoint ) + { + b3RevoluteJoint* joint = static_cast( bone->joint ); + if ( enableMotors ) + { + joint->SetMotorMode( B3_POSITION_MODE ); + } + else + { + joint->SetMotorFriction( bone->jointFriction ); + } + } + else if ( bone->joint->mType == b3_sphericalJoint ) + { + b3SphericalJoint* joint = static_cast( bone->joint ); + if ( enableMotors ) + { + joint->SetMotorMode( B3_POSITION_MODE ); + } + else + { + joint->SetMotorFriction( bone->jointFriction ); + } + } + } + + m_motorized = enableMotors; +} + +void Human::AdjustMotors( float springHertz ) +{ + if ( m_motorized == false ) + { + return; + } + + for ( int i = 1; i < bone_count; ++i ) + { + Bone* bone = human->bones + i; + + if ( bone->joint == nullptr ) + { + continue; + } + + if ( bone->joint->mType == b3_revoluteJoint ) + { + b3RevoluteJoint* joint = static_cast( bone->joint ); + joint->mAngularSpring.Frequency = springHertz; + } + else if ( bone->joint->mType == b3_sphericalJoint ) + { + b3SphericalJoint* joint = static_cast( bone->joint ); + joint->mAngularSpring.Frequency = springHertz; + } + } +} +#endif diff --git a/shared/human.h b/shared/human.h new file mode 100644 index 0000000..9e8e6be --- /dev/null +++ b/shared/human.h @@ -0,0 +1,82 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "box3d/types.h" + +typedef enum BoneId +{ + bone_pelvis, + bone_spine_01, + bone_spine_02, + bone_spine_03, + bone_neck, + bone_head, + bone_thigh_l, + bone_calf_l, + bone_thigh_r, + bone_calf_r, + bone_upper_arm_l, + bone_lower_arm_l, + bone_upper_arm_r, + bone_lower_arm_r, + bone_count, +} BoneId; + +typedef struct Bone +{ + b3BodyId bodyId; + b3JointId jointId; + b3BodyId anchorId; + b3JointId anchorJointId; + b3Transform localFrameA; + b3Transform localFrameB; + b3Transform referenceFrame; + b3JointType jointType; + float swingLimit; + b3Vec2 twistLimit; + float jointFriction; + int parentIndex; +} Bone; + +#define FILTER_JOINT_COUNT 8 + +// This must be zero initialized +typedef struct Human +{ + Bone bones[bone_count]; + b3JointId filterJoints[FILTER_JOINT_COUNT]; + int filterJointCount; + float frictionTorque; + bool isSpawned; +} Human; + +#ifdef __cplusplus +extern "C" +{ +#endif + +void CreateHuman( Human* human, b3WorldId worldId, b3Vec3 position, float frictionTorque, float hertz, float dampingRatio, + int groupIndex, void* userData, bool colorize ); + +// There are no allocations so this does not need to be called when the world is destroyed. +void DestroyHuman( Human* human ); + +void Human_SetVelocity( Human* human, b3Vec3 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_AlignSpring( Human* human, b3WorldId worldId, b3BodyId groundId, float hertz, float dampingRatio ); +void Human_CreateMotorAnchors( Human* human, b3WorldId worldId ); +void Human_CreateParallelAnchors( Human* human, b3WorldId worldId ); + +// void Human_EnablePoseControl( Human* human, float springHertz, bool enablePoseControl ); +// void Human_AdjustPoseControl( Human* human, float springHertz ); +// void Human_DriveBase( Human* human, b3Transform transform, float timeStep ); + +#ifdef __cplusplus +} +#endif diff --git a/shared/stability.c b/shared/stability.c new file mode 100644 index 0000000..a23b4cc --- /dev/null +++ b/shared/stability.c @@ -0,0 +1,74 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#include "stability.h" + +#include "utils.h" + +#include "box3d/box3d.h" + +#include +#include + +#define MESH_DROP_GRID_COUNT 32 + +MeshDropData CreateMeshDrop( b3WorldId worldId ) +{ + MeshDropData data = { 0 }; + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundId = b3CreateBody( worldId, &bodyDef ); + + int gridCount = 40; + float cellWidth = 1.0f; + float rowHz = 0.1f; + float columnHz = 0.2f; + float groundAmplitude = 0.5f; + + data.mesh = b3CreateWaveMesh( gridCount, gridCount, cellWidth, groundAmplitude, rowHz, columnHz ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.filter.categoryBits = 1; + b3CreateMeshShape( groundId, &shapeDef, data.mesh, b3Vec3_one ); + } + + { + b3BoxHull box = b3MakeBoxHull( 0.02f, 0.2f, 0.04f ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.rollingResistance = 0.1f; + + // Don't allow shapes to collide with each other. + shapeDef.filter.categoryBits = 2; + shapeDef.filter.maskBits = 1; + + g_randomSeed = 3963634789; + + int gridCount = MESH_DROP_GRID_COUNT; + + for ( int i = 0; i < gridCount; ++i ) + { + for ( int j = 0; j < gridCount; ++j ) + { + b3Vec3 linearVelocity = RandomVec3Uniform( -1.0f, 1.0f ); + b3Vec3 angularVelocity = RandomVec3Uniform( -5.0f, 5.0f ); + + bodyDef.position = (b3Vec3){ 0.5f * ( i - 0.5f * gridCount ), 5.0f, 0.5f * ( j - 0.5f * gridCount ) }; + bodyDef.linearVelocity = linearVelocity; + bodyDef.angularVelocity = angularVelocity; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + } + } + } + + return data; +} + +void DestroyMeshDrop( MeshDropData* data ) +{ + b3DestroyMesh( data->mesh ); +} diff --git a/shared/stability.h b/shared/stability.h new file mode 100644 index 0000000..a512a61 --- /dev/null +++ b/shared/stability.h @@ -0,0 +1,24 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT +#pragma once + +#include "box3d/id.h" + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + +typedef struct MeshDropData +{ + struct b3MeshData* mesh; +} MeshDropData; + +MeshDropData CreateMeshDrop( b3WorldId worldId ); +void DestroyMeshDrop( MeshDropData* data ); + +#ifdef __cplusplus +} +#endif diff --git a/shared/utils.c b/shared/utils.c new file mode 100644 index 0000000..ac19aff --- /dev/null +++ b/shared/utils.c @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "utils.h" + +#if defined( _WIN64 ) +#include +#elif defined( __APPLE__ ) +#include +#elif defined( __linux__ ) +#include +#elif defined( __EMSCRIPTEN__ ) +#include +#endif + +uint32_t g_randomSeed = RAND_SEED; + +int GetNumberOfCores( void ) +{ +#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 +} diff --git a/shared/utils.h b/shared/utils.h new file mode 100644 index 0000000..80b9ec4 --- /dev/null +++ b/shared/utils.h @@ -0,0 +1,122 @@ +// SPDX-FileCopyrightText: 2023 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "box3d/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; + +int GetNumberOfCores( void ); + +#ifdef __cplusplus +} +#endif + +// Simple random number generator. Using this instead of rand() for cross platform determinism. +B3_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] +B3_INLINE float RandomIntRange( int lo, int hi ) +{ + return lo + RandomInt() % ( hi - lo + 1 ); +} + +// Random number in range [-1,1] +B3_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] +B3_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] +B3_INLINE b3Vec3 RandomVec3( b3Vec3 lo, b3Vec3 hi ) +{ + b3Vec3 v; + v.x = RandomFloatRange( lo.x, hi.x ); + v.y = RandomFloatRange( lo.y, hi.y ); + v.z = RandomFloatRange( lo.z, hi.z ); + return v; +} + +B3_INLINE b3Vec3 RandomVec3Uniform( float lo, float hi ) +{ + b3Vec3 v; + v.x = RandomFloatRange( lo, hi ); + v.y = RandomFloatRange( lo, hi ); + v.z = RandomFloatRange( lo, hi ); + return v; +} + +B3_INLINE b3Vec3 RandomUnitVector() +{ + // Generate uniformly distributed random quaternion using Shoemake's method + // Reference: "Uniform Random Rotations", Ken Shoemake, Graphics Gems III, 1992 + + float u1 = RandomFloatRange( 0.0f, 1.0f ); + float u2 = RandomFloatRange( 0.0f, 2.0f * B3_PI ); + float u3 = RandomFloatRange( 0.0f, 2.0f * B3_PI ); + + float sqrt1MinusU1 = sqrtf( 1.0f - u1 ); + float sqrtU1 = sqrtf( u1 ); + + b3Vec3 v; + v.x = sqrt1MinusU1 * sinf( u2 ); + v.y = sqrt1MinusU1 * cosf( u2 ); + v.z = sqrtU1 * sinf( u3 ); + + return v; +} + +B3_INLINE b3Quat RandomQuat() +{ + // Generate uniformly distributed random quaternion using Shoemake's method + // Reference: "Uniform Random Rotations", Ken Shoemake, Graphics Gems III, 1992 + + float u1 = RandomFloatRange( 0.0f, 1.0f ); + float u2 = RandomFloatRange( 0.0f, 2.0f * B3_PI ); + float u3 = RandomFloatRange( 0.0f, 2.0f * B3_PI ); + + float sqrt1MinusU1 = sqrtf( 1.0f - u1 ); + float sqrtU1 = sqrtf( u1 ); + + b3Quat q; + q.v.x = sqrt1MinusU1 * sinf( u2 ); + q.v.y = sqrt1MinusU1 * cosf( u2 ); + q.v.z = sqrtU1 * sinf( u3 ); + q.s = sqrtU1 * cosf( u3 ); + + return q; +} diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..5ba4eb3 --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,240 @@ +include(GNUInstallDirs) +include(FetchContent) + +set(BOX3D_SOURCE_FILES + aabb.c + aabb.h + algorithm.h + arena_allocator.c + arena_allocator.h + bitset.c + bitset.h + block_allocator.c + block_allocator.h + body.c + body.h + broad_phase.c + broad_phase.h + capsule.c + compound.c + compound.h + constraint_graph.c + constraint_graph.h + contact.c + contact.h + contact_solver.c + contact_solver.h + container.h + convex_manifold.c + core.c + core.h + ctz.h + distance.c + distance_joint.c + dynamic_tree.c + height_field.c + hull.c + id_pool.c + id_pool.h + island.c + island.h + joint.c + joint.h + manifold.c + manifold.h + math_functions.c + math_internal.h + mesh.c + mesh_contact.c + motor_joint.c + mover.c + parallel_for.c + parallel_for.h + parallel_joint.c + physics_world.c + physics_world.h + platform.h + prismatic_joint.c + qsort.h + revolute_joint.c + scheduler.c + scheduler.h + sensor.c + sensor.h + shape.c + shape.h + simd.c + simd.h + solver.c + solver.h + solver_set.c + solver_set.h + sphere.c + spherical_joint.c + table.c + table.h + timer.c + triangle_manifold.c + types.c + verstable.h + weld_joint.c + wheel_joint.c + + box3d.natvis +) + +set(BOX3D_INCLUDE_FILES + ../include/box3d/base.h + ../include/box3d/box3d.h + ../include/box3d/collision.h + ../include/box3d/constants.h + ../include/box3d/id.h + ../include/box3d/math_functions.h + ../include/box3d/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(box3d STATIC ${BOX3D_SOURCE_FILES} ${BOX3D_INCLUDE_FILES}) + +# target_link_libraries(box3d PRIVATE eastl) + +target_include_directories(box3d + PUBLIC + $ + $ + $ + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR} +) + +set(CMAKE_DEBUG_POSTFIX "d") + +# Box3D uses C17 for _Static_assert and anonymous unions +set_target_properties(box3d PROPERTIES + C_STANDARD 17 + C_STANDARD_REQUIRED YES + C_EXTENSIONS YES + VERSION ${PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR} + DEBUG_POSTFIX ${CMAKE_DEBUG_POSTFIX} +) + +if (BOX3D_COMPILE_WARNING_AS_ERROR) + set_target_properties(box3d PROPERTIES COMPILE_WARNING_AS_ERROR ON) +endif() + +if (BOX3D_PROFILE) + target_compile_definitions(box3d PRIVATE BOX3D_PROFILE) + set(TRACY_DELAYED_INIT ON CACHE BOOL "Enable delayed init for Tracy" FORCE) + set(TRACY_MANUAL_LIFETIME ON CACHE BOOL "Enable manual lifetime for Tracy" FORCE) + + FetchContent_Declare( + tracy + GIT_REPOSITORY https://github.com/wolfpld/tracy.git + GIT_TAG v0.13.1 + GIT_SHALLOW TRUE + GIT_PROGRESS TRUE + ) + FetchContent_MakeAvailable(tracy) + + target_link_libraries(box3d PUBLIC TracyClient) +endif() + +if(BOX3D_VALIDATE) + message(STATUS "Box3D validation ON") + target_compile_definitions(box3d PRIVATE BOX3D_VALIDATE) +endif() + +if (BOX3D_DISABLE_SIMD) + message(STATUS "Box3D SIMD disabled") + target_compile_definitions(box3d PRIVATE BOX3D_DISABLE_SIMD) +endif() + +if (MSVC) + message(STATUS "Box3D on MSVC") + if (BUILD_SHARED_LIBS) + # this is needed by DLL users to import Box3D symbols + target_compile_definitions(box3d INTERFACE BOX3D_DLL) + endif() + + # Visual Studio won't load the natvis unless it is in the project + target_sources(box3d PRIVATE box3d.natvis) + + # Enable asserts in release with debug info + target_compile_definitions(box3d PUBLIC "$<$:B3_ENABLE_ASSERT>") + + # Warnings Wall is problematic in mixed C/C++, so using W4 + target_compile_options(box3d PRIVATE /W4) + # target_compile_options(box3d PRIVATE /wd4820 /wd5045 /wd4061 /wd4711 /wd4514 /wd4365 /wd5219 /wd5039) + target_compile_options(box3d PRIVATE /wd4820 /wd5045 /wd4061 /wd4711) + # 4710 - warn about inline functions that are not inlined + target_compile_options(box3d PRIVATE /wd4710 ) + + if (${CMAKE_CXX_COMPILER_ID} STREQUAL "Clang") + target_compile_options(box3d PRIVATE -Wmissing-prototypes) + endif() + +elseif (MINGW) + message(STATUS "Box3D on MinGW") +elseif (APPLE) + message(STATUS "Box3D on Apple") + target_compile_options(box3d PRIVATE -Wmissing-prototypes -Wall -Wextra -pedantic) +elseif (EMSCRIPTEN) + message(STATUS "Box3D on Emscripten") + target_compile_options(box3d PRIVATE -msimd128 -msse2) +elseif (UNIX) + message(STATUS "Box3D using Unix") + target_compile_options(box3d PRIVATE -Wmissing-prototypes -Wall -Wextra -pedantic -Wno-unused-value) + if ("${CMAKE_HOST_SYSTEM_PROCESSOR}" STREQUAL "aarch64") + # raspberry pi + # -mfpu=neon + # target_compile_options(box3d PRIVATE) + else() + endif() +endif() + +source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}" PREFIX "src" FILES ${BOX3D_SOURCE_FILES}) +source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}/../include" PREFIX "include" FILES ${BOX3D_INCLUDE_FILES}) + +add_library(box3d::box3d ALIAS box3d) + +# libm is required on many Unix toolchains for sqrtf, etc. +if(UNIX AND NOT APPLE AND NOT EMSCRIPTEN) + target_link_libraries(box3d PUBLIC m) +endif() + +install( + TARGETS box3d + EXPORT box3dConfig + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +install( + EXPORT box3dConfig + NAMESPACE box3d:: + DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/box3d" +) + +install( + FILES ${BOX3D_API_FILES} + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/box3d +) + +include(CMakePackageConfigHelpers) + +write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/box3dConfigVersion.cmake" + VERSION ${BOX3D_VERSION} + COMPATIBILITY SameMajorVersion +) + +install( + FILES "${CMAKE_CURRENT_BINARY_DIR}/box3dConfigVersion.cmake" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/box3d" +) diff --git a/src/aabb.c b/src/aabb.c new file mode 100644 index 0000000..c1d5342 --- /dev/null +++ b/src/aabb.c @@ -0,0 +1,124 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "aabb.h" + +#include "box3d/math_functions.h" + +#include + +// From Real-time Collision Detection, p179. +b3CastOutput b3RayCastAABB( b3AABB a, b3Vec3 p1, b3Vec3 p2 ) +{ + // Radius not handled + b3CastOutput output = { 0 }; + + float tmin = -FLT_MAX; + float tmax = FLT_MAX; + + b3Vec3 p = p1; + b3Vec3 d = b3Sub( p2, p1 ); + b3Vec3 absD = b3Abs( d ); + + b3Vec3 normal = b3Vec3_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 = b3MinFloat( 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 = b3MinFloat( tmax, t2 ); + + if ( tmin > tmax ) + { + return output; + } + } + + // Does the ray start inside the box? + // Does the ray intersect beyond the max fraction? + if ( tmin < 0.0f || 1.0f < tmin ) + { + return output; + } + + // Intersection. + output.fraction = tmin; + output.normal = normal; + output.point = b3Lerp( p1, p2, tmin ); + output.hit = true; + return output; +} diff --git a/src/aabb.h b/src/aabb.h new file mode 100644 index 0000000..c20dca3 --- /dev/null +++ b/src/aabb.h @@ -0,0 +1,80 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "box3d/types.h" + +// Ray cast an AABB +b3CastOutput b3RayCastAABB( b3AABB a, b3Vec3 p1, b3Vec3 p2 ); + +// Get the surface area (perimeter) +static inline float b3Perimeter( b3AABB a ) +{ + float wx = a.upperBound.x - a.lowerBound.x; + float wy = a.upperBound.y - a.lowerBound.y; + float wz = a.upperBound.z - a.lowerBound.z; + return 2.0f * ( wx * wz + wy * wx + wz * wy ); +} + +/// Enlarge a to contain b +/// @return true if the AABB grew +static inline bool b3EnlargeAABB( b3AABB* a, b3AABB 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 ( b.lowerBound.z < a->lowerBound.z ) + { + a->lowerBound.z = b.lowerBound.z; + 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; + } + + if ( a->upperBound.z < b.upperBound.z ) + { + a->upperBound.z = b.upperBound.z; + changed = true; + } + + return changed; +} + +#if 0 +/// Do a and b overlap +inline bool b3OverlapAABBs( b3AABB a, b3AABB b ) +{ + return !( b.lowerBound.x > a.upperBound.x || b.lowerBound.y > a.upperBound.y || b.lowerBound.z > a.upperBound.z || + a.lowerBound.x > b.upperBound.x || a.lowerBound.y > b.upperBound.y || a.lowerBound.z > b.upperBound.z ); +} +#endif + +static inline b3Vec3 b3FarthestPointOnAABB( b3AABB b, b3Vec3 p ) +{ + return (b3Vec3){ + .x = ( p.x - b.lowerBound.x ) > ( b.upperBound.x - p.x ) ? b.lowerBound.x : b.upperBound.x, + .y = ( p.y - b.lowerBound.y ) > ( b.upperBound.y - p.y ) ? b.lowerBound.y : b.upperBound.y, + .z = ( p.z - b.lowerBound.z ) > ( b.upperBound.z - p.z ) ? b.lowerBound.z : b.upperBound.z, + }; +} diff --git a/src/algorithm.h b/src/algorithm.h new file mode 100644 index 0000000..67d4b46 --- /dev/null +++ b/src/algorithm.h @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#ifdef __cplusplus +#define B3_TYPE_OF( A ) decltype( A ) +#else +#define B3_TYPE_OF( A ) __typeof__( A ) +#endif + +#define B3_SWAP( x, y ) \ + do \ + { \ + B3_TYPE_OF( x ) B3_SWAP_TEMP = x; \ + x = y; \ + y = B3_SWAP_TEMP; \ + } \ + while ( 0 ) diff --git a/src/arena_allocator.c b/src/arena_allocator.c new file mode 100644 index 0000000..b7031f0 --- /dev/null +++ b/src/arena_allocator.c @@ -0,0 +1,127 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "arena_allocator.h" + +#include "core.h" + +#include +#include + +b3Stack b3CreateStack( int capacity ) +{ + B3_ASSERT( capacity >= 0 ); + b3Stack stack = { 0 }; + stack.capacity = capacity; + stack.memory = (char*)b3Alloc( capacity ); + return stack; +} + +void b3DestroyStack( b3Stack* stack ) +{ + b3Free( stack->memory, stack->capacity ); +} + +void* b3StackAlloc( b3Stack* stack, int size, const char* name ) +{ + if ( stack->entryCount == B3_MAX_STACK_ENTRIES ) + { + B3_ASSERT( false ); + return NULL; + } + + // ensure allocation is 32 byte aligned to support 256-bit SIMD + int size32 = ( ( size - 1 ) | 0x1F ) + 1; + + b3StackEntry entry; + entry.size = size32; + entry.name = name; + if ( stack->index + size32 > stack->capacity ) + { + // fall back to the heap (undesirable) + entry.data = (char*)b3Alloc( size32 ); + entry.usedMalloc = true; + + B3_ASSERT( ( (uintptr_t)entry.data & 0x1F ) == 0 ); + } + else + { + entry.data = stack->memory + stack->index; + entry.usedMalloc = false; + stack->index += size32; + + B3_ASSERT( ( (uintptr_t)entry.data & 0x1F ) == 0 ); + } + + stack->allocation += size32; + if ( stack->allocation > stack->maxAllocation ) + { + stack->maxAllocation = stack->allocation; + } + + stack->entries[stack->entryCount] = entry; + stack->entryCount += 1; + return entry.data; +} + +void b3StackFree( b3Stack* stack, void* mem ) +{ + int entryCount = stack->entryCount; + B3_ASSERT( entryCount > 0 ); + b3StackEntry* entry = stack->entries + ( entryCount - 1 ); + B3_ASSERT( mem == entry->data ); + if ( entry->usedMalloc ) + { + b3Free( mem, entry->size ); + } + else + { + stack->index -= entry->size; + } + stack->allocation -= entry->size; + stack->entryCount -= 1; +} + +void b3GrowStack( b3Stack* stack ) +{ + // Stack must not be in use + B3_ASSERT( stack->allocation == 0 ); + + if ( stack->maxAllocation > stack->capacity ) + { + b3Free( stack->memory, stack->capacity ); + stack->capacity = stack->maxAllocation + stack->maxAllocation / 2; + stack->memory = (char*)b3Alloc( stack->capacity ); + } +} + +int b3GetStackCapacity( b3Stack* stack ) +{ + return stack->capacity; +} + +int b3GetStackAllocation( b3Stack* stack ) +{ + return stack->allocation; +} + +int b3GetMaxStackAllocation( b3Stack* stack ) +{ + return stack->maxAllocation; +} + +b3Arena b3CreateArena( int capacity ) +{ + int c = capacity > 8 ? capacity : 8; + return (b3Arena){ + .memory = b3Alloc( c ), + .capacity = c, + .index = 0, + }; +} + +void b3DestroyArena(b3Arena* arena) +{ + b3Free( arena->memory, arena->capacity ); + *arena = (b3Arena){ 0 }; +} diff --git a/src/arena_allocator.h b/src/arena_allocator.h new file mode 100644 index 0000000..f5e59f9 --- /dev/null +++ b/src/arena_allocator.h @@ -0,0 +1,86 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once +#include "box3d/base.h" + +#include +#include + +#define B3_MAX_STACK_ENTRIES 32 + +typedef struct b3StackEntry +{ + char* data; + const char* name; + int size; + bool usedMalloc; +} b3StackEntry; + +// This is a stack-like arena allocator used for fast per step allocations. +// You must nest allocate/free pairs. The code will B3_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 b3Stack +{ + char* memory; + int capacity; + int index; + + int allocation; + int maxAllocation; + + b3StackEntry entries[B3_MAX_STACK_ENTRIES]; + int entryCount; +} b3Stack; + +typedef struct b3Arena +{ + char* memory; + int capacity; + int index; +} b3Arena; + +#ifdef __cplusplus +extern "C" +{ +#endif + +b3Stack b3CreateStack( int capacity ); +void b3DestroyStack( b3Stack* stack ); + +void* b3StackAlloc( b3Stack* stack, int size, const char* name ); +void b3StackFree( b3Stack* stack, void* mem ); + +// Grow the stack based on usage +void b3GrowStack( b3Stack* stack ); + +int b3GetStackCapacity( b3Stack* stack ); +int b3GetStackAllocation( b3Stack* stack ); +int b3GetMaxStackAllocation( b3Stack* stack ); + +b3Arena b3CreateArena( int capacity ); +void b3DestroyArena( b3Arena* arena ); + +static inline void* b3Bump( b3Arena* arena, int size ) +{ + if (size == 0) + { + return NULL; + } + + if ( size + arena->index > arena->capacity ) + { + B3_ASSERT( false ); + return NULL; + } + + void* memory = arena->memory + arena->index; + arena->index += size; + return memory; +} + +#ifdef __cplusplus +} +#endif diff --git a/src/bitset.c b/src/bitset.c new file mode 100644 index 0000000..319725b --- /dev/null +++ b/src/bitset.c @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "bitset.h" + +#include + +b3BitSet b3CreateBitSet( uint32_t bitCapacity ) +{ + b3BitSet bitSet = { 0 }; + bitSet.blockCapacity = ( bitCapacity + sizeof( uint64_t ) * 8 - 1 ) / ( sizeof( uint64_t ) * 8 ); + bitSet.blockCount = 0; + bitSet.bits = (uint64_t*)b3Alloc( bitSet.blockCapacity * sizeof( uint64_t ) ); + memset( bitSet.bits, 0, bitSet.blockCapacity * sizeof( uint64_t ) ); + return bitSet; +} + +void b3DestroyBitSet( b3BitSet* bitSet ) +{ + b3Free( bitSet->bits, bitSet->blockCapacity * sizeof( uint64_t ) ); + bitSet->blockCapacity = 0; + bitSet->blockCount = 0; + bitSet->bits = NULL; +} + +void b3SetBitCountAndClear( b3BitSet* bitSet, uint32_t bitCount ) +{ + uint32_t blockCount = ( bitCount + sizeof( uint64_t ) * 8 - 1 ) / ( sizeof( uint64_t ) * 8 ); + if ( bitSet->blockCapacity < blockCount ) + { + b3DestroyBitSet( bitSet ); + uint32_t newBitCapacity = bitCount + ( bitCount >> 1 ); + *bitSet = b3CreateBitSet( newBitCapacity ); + } + + bitSet->blockCount = blockCount; + memset( bitSet->bits, 0, bitSet->blockCount * sizeof( uint64_t ) ); +} + +void b3GrowBitSet( b3BitSet* bitSet, uint32_t blockCount ) +{ + B3_ASSERT( blockCount > bitSet->blockCount ); + if ( blockCount > bitSet->blockCapacity ) + { + uint32_t oldCapacity = bitSet->blockCapacity; + bitSet->blockCapacity = blockCount + blockCount / 2; + uint64_t* newBits = (uint64_t*)b3Alloc( bitSet->blockCapacity * sizeof( uint64_t ) ); + memset( newBits, 0, bitSet->blockCapacity * sizeof( uint64_t ) ); + B3_ASSERT( bitSet->bits != NULL ); + memcpy( newBits, bitSet->bits, oldCapacity * sizeof( uint64_t ) ); + b3Free( bitSet->bits, oldCapacity * sizeof( uint64_t ) ); + bitSet->bits = newBits; + } + + bitSet->blockCount = blockCount; +} + +void b3InPlaceUnion( b3BitSet* __restrict setA, const b3BitSet* __restrict setB ) +{ + B3_ASSERT( setA->blockCount == setB->blockCount ); + uint32_t blockCount = setA->blockCount; + for ( uint32_t i = 0; i < blockCount; ++i ) + { + setA->bits[i] |= setB->bits[i]; + } +} diff --git a/src/bitset.h b/src/bitset.h new file mode 100644 index 0000000..8eb9bef --- /dev/null +++ b/src/bitset.h @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: 2025 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 b3BitSet +{ + uint64_t* bits; + uint32_t blockCapacity; + uint32_t blockCount; +} b3BitSet; + + +#ifdef __cplusplus +extern "C" +{ +#endif + +b3BitSet b3CreateBitSet( uint32_t bitCapacity ); +void b3DestroyBitSet( b3BitSet* bitSet ); +void b3SetBitCountAndClear( b3BitSet* bitSet, uint32_t bitCount ); +void b3InPlaceUnion( b3BitSet* setA, const b3BitSet* setB ); +void b3GrowBitSet( b3BitSet* bitSet, uint32_t blockCount ); +int b3CountSetBits( b3BitSet* bitSet ); + +#ifdef __cplusplus +} +#endif + +static inline void b3SetBit( b3BitSet* bitSet, uint32_t bitIndex ) +{ + uint32_t blockIndex = bitIndex / 64; + B3_ASSERT( blockIndex < bitSet->blockCount ); + bitSet->bits[blockIndex] |= ( (uint64_t)1 << bitIndex % 64 ); +} + +static inline void b3SetBitGrow( b3BitSet* bitSet, uint32_t bitIndex ) +{ + uint32_t blockIndex = bitIndex / 64; + if ( blockIndex >= bitSet->blockCount ) + { + b3GrowBitSet( bitSet, blockIndex + 1 ); + } + bitSet->bits[blockIndex] |= ( (uint64_t)1 << bitIndex % 64 ); +} + +static inline void b3ClearBit( b3BitSet* 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 b3GetBit( const b3BitSet* 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 b3GetBitSetBytes( b3BitSet* bitSet ) +{ + return bitSet->blockCapacity * sizeof( uint64_t ); +} diff --git a/src/block_allocator.c b/src/block_allocator.c new file mode 100644 index 0000000..b008595 --- /dev/null +++ b/src/block_allocator.c @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#include "block_allocator.h" + +#include "core.h" + +b3BlockAllocator b3CreateBlockAllocator( int elementSize, int initialCount ) +{ + B3_ASSERT( elementSize >= (int)sizeof( void* ) ); + + b3BlockAllocator allocator = { 0 }; + + b3Array_Create( allocator.blocks ); + allocator.elementSize = elementSize; + allocator.freeList = NULL; + allocator.nextIndex = 0; + allocator.allocationCount = 0; + + if ( initialCount > 0 ) + { + int count = ( initialCount + B3_BLOCK_SIZE - 1 ) >> B3_BLOCK_EXPONENT; + b3Array_Resize( allocator.blocks, count ); + + for ( int i = 0; i < allocator.blocks.count; ++i ) + { + allocator.blocks.data[i].memory = b3Alloc( B3_BLOCK_SIZE * elementSize ); + } + } + + return allocator; +} + +void b3DestroyBlockAllocator( b3BlockAllocator* allocator ) +{ + for ( int i = 0; i < allocator->blocks.count; ++i ) + { + b3Free( allocator->blocks.data[i].memory, B3_BLOCK_SIZE * allocator->elementSize ); + } + + b3Array_Destroy( allocator->blocks ); +} + +void* b3AllocateElement( b3BlockAllocator* allocator ) +{ + B3_ASSERT( allocator != NULL ); + + allocator->allocationCount += 1; + + // Pop from free list first + if ( allocator->freeList != NULL ) + { + void* element = allocator->freeList; + allocator->freeList = *(void**)element; + return element; + } + + int startIndex = allocator->nextIndex; + int startOffset = startIndex & ( B3_BLOCK_SIZE - 1 ); + + if ( startOffset + 1 > B3_BLOCK_SIZE ) + { + startIndex = ( startIndex + B3_BLOCK_SIZE ) & ~( B3_BLOCK_SIZE - 1 ); + } + + allocator->nextIndex = startIndex + 1; + + int lastIndex = allocator->nextIndex - 1; + int requiredBlockCount = ( lastIndex >> B3_BLOCK_EXPONENT ) + 1; + + if ( requiredBlockCount > allocator->blocks.count ) + { + int oldCount = allocator->blocks.count; + b3Array_Resize( allocator->blocks, requiredBlockCount ); + + for ( int i = oldCount; i < requiredBlockCount; ++i ) + { + allocator->blocks.data[i].memory = b3Alloc( B3_BLOCK_SIZE * allocator->elementSize ); + } + } + + int blockIndex = startIndex >> B3_BLOCK_EXPONENT; + int blockOffset = startIndex & ( B3_BLOCK_SIZE - 1 ); + + return allocator->blocks.data[blockIndex].memory + blockOffset * allocator->elementSize; +} + +void b3FreeElement( b3BlockAllocator* allocator, void* element ) +{ + B3_ASSERT( allocator != NULL ); + B3_ASSERT( element != NULL ); + B3_ASSERT( allocator->allocationCount > 0 ); + + allocator->allocationCount -= 1; + + // Push onto free list + *(void**)element = allocator->freeList; + allocator->freeList = element; +} diff --git a/src/block_allocator.h b/src/block_allocator.h new file mode 100644 index 0000000..77ee538 --- /dev/null +++ b/src/block_allocator.h @@ -0,0 +1,44 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "container.h" + +#include "box3d/base.h" + +#define B3_BLOCK_EXPONENT 8 +#define B3_BLOCK_SIZE ( 1 << B3_BLOCK_EXPONENT ) + +typedef struct b3Block +{ + char* memory; +} b3Block; + +b3DeclareArray( b3Block ); + +typedef struct b3BlockAllocator +{ + b3ArrayC( b3Block ) blocks; + void* freeList; + int elementSize; + int nextIndex; + int allocationCount; +} b3BlockAllocator; + +#ifdef __cplusplus +extern "C" +{ +#endif + +// Element must be large enough to hold a pointer +b3BlockAllocator b3CreateBlockAllocator( int elementSize, int initialCount ); +void b3DestroyBlockAllocator( b3BlockAllocator* allocator ); + +// Elements are guaranteed contiguous. +void* b3AllocateElement( b3BlockAllocator* allocator ); +void b3FreeElement( b3BlockAllocator* allocator, void* element ); + +#ifdef __cplusplus +} +#endif diff --git a/src/body.c b/src/body.c new file mode 100644 index 0000000..d3e4e37 --- /dev/null +++ b/src/body.c @@ -0,0 +1,2323 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "body.h" + +#include "aabb.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" + +// needed for dll export +#include "box3d/box3d.h" +#include "box3d/id.h" + +#include +#include + +// Get a validated body from a world using an id. +b3Body* b3GetBodyFullId( b3World* world, b3BodyId bodyId ) +{ + B3_ASSERT( b3Body_IsValid( bodyId ) ); + + // id index starts at one so that zero can represent null + // id index starts at one so that zero can represent null + return b3Array_Get( world->bodies, bodyId.index1 - 1 ); +} + +b3Transform b3GetBodyTransformQuick( b3World* world, b3Body* body ) +{ + b3SolverSet* set = b3Array_Get( world->solverSets, body->setIndex ); + b3BodySim* bodySim = b3Array_Get( set->bodySims, body->localIndex ); + return bodySim->transform; +} + +b3Transform b3GetBodyTransform( b3World* world, int bodyId ) +{ + b3Body* body = b3Array_Get( world->bodies, bodyId ); + return b3GetBodyTransformQuick( world, body ); +} + +// Create a b3BodyId from a raw id. +b3BodyId b3MakeBodyId( b3World* world, int bodyId ) +{ + b3Body* body = b3Array_Get( world->bodies, bodyId ); + return (b3BodyId){ bodyId + 1, world->worldId, body->generation }; +} + +b3BodySim* b3GetBodySim( b3World* world, b3Body* body ) +{ + b3SolverSet* set = b3Array_Get( world->solverSets, body->setIndex ); + b3BodySim* bodySim = b3Array_Get( set->bodySims, body->localIndex ); + return bodySim; +} + +b3BodyState* b3GetBodyState( b3World* world, b3Body* body ) +{ + if ( body->setIndex == b3_awakeSet ) + { + b3SolverSet* set = b3Array_Get( world->solverSets, b3_awakeSet ); + return b3Array_Get( set->bodyStates, body->localIndex ); + } + + return NULL; +} + +static void b3CreateIslandForBody( b3World* world, int setIndex, b3Body* body ) +{ + B3_ASSERT( body->islandId == B3_NULL_INDEX ); + B3_ASSERT( setIndex != b3_disabledSet ); + + b3Island* island = b3CreateIsland( world, setIndex ); + b3Array_Push( island->bodies, body->id ); + body->islandId = island->islandId; + body->islandIndex = 0; + + b3ValidateIsland( world, island->islandId ); +} + +static void b3RemoveBodyFromIsland( b3World* world, b3Body* body ) +{ + if ( body->islandId == B3_NULL_INDEX ) + { + B3_ASSERT( body->islandIndex == B3_NULL_INDEX ); + return; + } + + int islandId = body->islandId; + b3Island* island = b3Array_Get( world->islands, islandId ); + { + int localIndex = body->islandIndex; + int movedBodyId = island->bodies.data[island->bodies.count - 1]; + island->bodies.data[localIndex] = movedBodyId; + B3_VALIDATE( world->bodies.data[movedBodyId].islandIndex == island->bodies.count - 1 ); + world->bodies.data[movedBodyId].islandIndex = localIndex; + island->bodies.count -= 1; + } + + if ( island->bodies.count == 0 ) + { + // Destroy empty island + B3_ASSERT( island->contacts.count == 0 ); + B3_ASSERT( island->joints.count == 0 ); + + // Free the island + b3DestroyIsland( world, island->islandId ); + } + else + { + b3ValidateIsland( world, islandId ); + } + + body->islandId = B3_NULL_INDEX; + body->islandIndex = B3_NULL_INDEX; +} + +static void b3DestroyBodyContacts( b3World* world, b3Body* body, bool wakeBodies ) +{ + // Destroy the attached contacts + int edgeKey = body->headContactKey; + while ( edgeKey != B3_NULL_INDEX ) + { + int contactId = edgeKey >> 1; + int edgeIndex = edgeKey & 1; + + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + edgeKey = contact->edges[edgeIndex].nextKey; + b3DestroyContact( world, contact, wakeBodies ); + } + + b3ValidateSolverSets( world ); +} + +b3BodyId b3CreateBody( b3WorldId worldId, const b3BodyDef* def ) +{ + B3_CHECK_DEF( def ); + B3_ASSERT( b3IsValidVec3( def->position ) ); + B3_ASSERT( b3IsValidQuat( def->rotation ) ); + B3_ASSERT( b3IsValidVec3( def->linearVelocity ) ); + B3_ASSERT( b3IsValidVec3( def->angularVelocity ) ); + B3_ASSERT( b3IsValidFloat( def->linearDamping ) && def->linearDamping >= 0.0f ); + B3_ASSERT( b3IsValidFloat( def->angularDamping ) && def->angularDamping >= 0.0f ); + B3_ASSERT( b3IsValidFloat( def->sleepThreshold ) && def->sleepThreshold >= 0.0f ); + B3_ASSERT( b3IsValidFloat( def->gravityScale ) ); + + b3World* world = b3GetUnlockedWorldFromId( worldId ); + + if ( world == NULL ) + { + return b3_nullBodyId; + } + + world->locked = true; + + 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 = b3_disabledSet; + } + else if ( def->type == b3_staticBody ) + { + setId = b3_staticSet; + } + else if ( isAwake == true ) + { + setId = b3_awakeSet; + } + else + { + // new set for a sleeping body in its own island + setId = b3AllocId( &world->solverSetIdPool ); + if ( setId == world->solverSets.count ) + { + // Create a zero initialized solver set. All sub-arrays are also zero initialized. + b3Array_Push( world->solverSets, (b3SolverSet){ 0 } ); + } + else + { + B3_ASSERT( world->solverSets.data[setId].setIndex == B3_NULL_INDEX ); + } + + world->solverSets.data[setId].setIndex = setId; + } + + B3_ASSERT( 0 <= setId && setId < world->solverSets.count ); + + int bodyId = b3AllocId( &world->bodyIdPool ); + + uint32_t lockFlags = 0; + lockFlags |= def->motionLocks.linearX ? b3_lockLinearX : 0; + lockFlags |= def->motionLocks.linearY ? b3_lockLinearY : 0; + lockFlags |= def->motionLocks.linearZ ? b3_lockLinearZ : 0; + lockFlags |= def->motionLocks.angularX ? b3_lockAngularX : 0; + lockFlags |= def->motionLocks.angularY ? b3_lockAngularY : 0; + lockFlags |= def->motionLocks.angularZ ? b3_lockAngularZ : 0; + + b3SolverSet* set = b3Array_Get( world->solverSets, setId ); + b3BodySim* bodySim = b3Array_Emplace( set->bodySims ); + *bodySim = (b3BodySim){ 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->localCenter = b3Vec3_zero; + bodySim->force = b3Vec3_zero; + bodySim->torque = b3Vec3_zero; + bodySim->invMass = 0.0f; + bodySim->invInertiaLocal = b3Mat3_zero; + bodySim->minExtent = B3_HUGE; + bodySim->maxExtent = b3Vec3_zero; + bodySim->linearDamping = def->linearDamping; + bodySim->angularDamping = def->angularDamping; + bodySim->gravityScale = def->gravityScale; + bodySim->bodyId = bodyId; + bodySim->flags = lockFlags; + bodySim->flags |= def->isBullet ? b3_isBullet : 0; + bodySim->flags |= def->allowFastRotation ? b3_allowFastRotation : 0; + bodySim->flags |= def->type == b3_dynamicBody ? b3_dynamicFlag : 0; + + if ( setId == b3_awakeSet ) + { + b3BodyState* bodyState = b3Array_Emplace( set->bodyStates ); + + *bodyState = (b3BodyState){ 0 }; + bodyState->linearVelocity = def->linearVelocity; + bodyState->angularVelocity = def->angularVelocity; + bodyState->deltaRotation = b3Quat_identity; + bodyState->flags = bodySim->flags; + + bodySim->maxAngularVelocity = b3Length( def->angularVelocity ) + 5.0f; + } + + if ( bodyId == world->bodies.count ) + { + b3Array_Push( world->bodies, (b3Body){ 0 } ); + } + else + { + B3_ASSERT( world->bodies.data[bodyId].id == B3_NULL_INDEX ); + } + + b3Body* body = b3Array_Get( world->bodies, bodyId ); + + if ( def->name ) + { + int i = 0; + while ( i < B3_NAME_LENGTH - 1 && def->name[i] != 0 ) + { + body->name[i] = def->name[i]; + i += 1; + } + + while ( i < B3_NAME_LENGTH ) + { + body->name[i] = 0; + i += 1; + } + } + else + { + memset( body->name, 0, B3_NAME_LENGTH * sizeof( char ) ); + } + + body->userData = def->userData; + body->setIndex = setId; + body->localIndex = set->bodySims.count - 1; + body->generation += 1; + body->headShapeId = B3_NULL_INDEX; + body->shapeCount = 0; + body->headChainId = B3_NULL_INDEX; + body->headContactKey = B3_NULL_INDEX; + body->contactCount = 0; + body->headJointKey = B3_NULL_INDEX; + body->jointCount = 0; + body->islandId = B3_NULL_INDEX; + body->islandIndex = B3_NULL_INDEX; + body->bodyMoveIndex = B3_NULL_INDEX; + body->id = bodyId; + body->sleepThreshold = def->sleepThreshold; + body->sleepTime = 0.0f; + body->mass = 0.0f; + body->inertia = b3Mat3_zero; + body->type = def->type; + body->flags = bodySim->flags; + body->enableSleep = def->enableSleep; + + // dynamic and kinematic bodies that are enabled need a island + if ( setId >= b3_awakeSet ) + { + b3CreateIslandForBody( world, setId, body ); + } + + b3ValidateSolverSets( world ); + + b3BodyId id = { bodyId + 1, world->worldId, body->generation }; + + world->locked = false; + + return id; +} + +bool b3IsBodyAwake( b3World* world, b3Body* body ) +{ + B3_UNUSED( world ); + return body->setIndex == b3_awakeSet; +} + +bool b3WakeBody( b3World* world, b3Body* body ) +{ + if ( body->setIndex >= b3_firstSleepingSet ) + { + b3WakeSolverSet( world, body->setIndex ); + b3ValidateSolverSets( world ); + return true; + } + + return false; +} + +bool b3WakeBodyWithLock( b3World* world, b3Body* body ) +{ + B3_ASSERT( world->locked == false ); + world->locked = true; + bool woke = b3WakeBody( world, body ); + world->locked = false; + return woke; +} + +void b3DestroyBody( b3BodyId bodyId ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return; + } + + world->locked = true; + + b3Body* body = b3GetBodyFullId( 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 != B3_NULL_INDEX ) + { + int jointId = edgeKey >> 1; + int edgeIndex = edgeKey & 1; + + b3Joint* joint = b3Array_Get( world->joints, jointId ); + edgeKey = joint->edges[edgeIndex].nextKey; + + // Careful because this modifies the list being traversed + b3DestroyJointInternal( world, joint, wakeBodies ); + } + + // Destroy all contacts attached to this body. + b3DestroyBodyContacts( world, body, wakeBodies ); + + // Destroy the attached shapes and their broad-phase proxies. + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + + if ( shape->sensorIndex != B3_NULL_INDEX ) + { + b3DestroySensor( world, shape ); + } + + b3DestroyShapeProxy( shape, &world->broadPhase ); + + b3DestroyShapeAllocations( world, shape ); + + // Return shape to free list. + b3FreeId( &world->shapeIdPool, shapeId ); + shape->id = B3_NULL_INDEX; + + shapeId = shape->nextShapeId; + } + + b3RemoveBodyFromIsland( world, body ); + + // Remove body sim from solver set that owns it + b3SolverSet* set = b3Array_Get( world->solverSets, body->setIndex ); + int movedIndex = b3Array_RemoveSwap( set->bodySims, body->localIndex ); + if ( movedIndex != B3_NULL_INDEX ) + { + // Fix moved body index + b3BodySim* movedSim = set->bodySims.data + body->localIndex; + int movedId = movedSim->bodyId; + b3Body* movedBody = b3Array_Get( world->bodies, movedId ); + B3_ASSERT( movedBody->localIndex == movedIndex ); + movedBody->localIndex = body->localIndex; + } + + // Remove body state from awake set + if ( body->setIndex == b3_awakeSet ) + { + int result = b3Array_RemoveSwap( set->bodyStates, body->localIndex ); + B3_UNUSED( result ); + B3_ASSERT( result == movedIndex ); + } + else if ( set->setIndex >= b3_firstSleepingSet && set->bodySims.count == 0 ) + { + // Remove solver set if it's now an orphan. + b3DestroySolverSet( world, set->setIndex ); + } + + // Free body and id (preserve body revision) + b3FreeId( &world->bodyIdPool, body->id ); + + body->setIndex = B3_NULL_INDEX; + body->localIndex = B3_NULL_INDEX; + body->id = B3_NULL_INDEX; + + b3ValidateSolverSets( world ); + + world->locked = false; +} + +int b3Body_GetContactCapacity( b3BodyId bodyId ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return 0; + } + + b3Body* body = b3GetBodyFullId( world, bodyId ); + + // Conservative and fast + return body->contactCount; +} + +int b3Body_GetContactData( b3BodyId bodyId, b3ContactData* contactData, int capacity ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return 0; + } + + b3Body* body = b3GetBodyFullId( world, bodyId ); + + int contactKey = body->headContactKey; + int index = 0; + while ( contactKey != B3_NULL_INDEX && index < capacity ) + { + int contactId = contactKey >> 1; + int edgeIndex = contactKey & 1; + + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + + // Is contact touching? + if ( contact->flags & b3_contactTouchingFlag ) + { + b3Shape* shapeA = b3Array_Get( world->shapes, contact->shapeIdA ); + b3Shape* shapeB = b3Array_Get( world->shapes, contact->shapeIdB ); + + contactData[index].contactId = (b3ContactId){ contact->contactId + 1, bodyId.world0, 0, contact->generation }; + contactData[index].shapeIdA = (b3ShapeId){ shapeA->id + 1, bodyId.world0, shapeA->generation }; + contactData[index].shapeIdB = (b3ShapeId){ shapeB->id + 1, bodyId.world0, shapeB->generation }; + contactData[index].manifolds = contact->manifolds; + contactData[index].manifoldCount = contact->manifoldCount; + index += 1; + } + + contactKey = contact->edges[edgeIndex].nextKey; + } + + B3_ASSERT( index <= capacity ); + + return index; +} + +b3AABB b3Body_ComputeAABB( b3BodyId bodyId ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return (b3AABB){ 0 }; + } + + b3Body* body = b3GetBodyFullId( world, bodyId ); + if ( body->headShapeId == B3_NULL_INDEX ) + { + b3Transform transform = b3GetBodyTransform( world, body->id ); + return (b3AABB){ transform.p, transform.p }; + } + + b3Shape* shape = b3Array_Get( world->shapes, body->headShapeId ); + b3AABB aabb = shape->aabb; + while ( shape->nextShapeId != B3_NULL_INDEX ) + { + shape = b3Array_Get( world->shapes, shape->nextShapeId ); + aabb = b3AABB_Union( aabb, shape->aabb ); + } + + return aabb; +} + +float b3Body_GetClosestPoint( b3BodyId bodyId, b3Vec3* result, b3Vec3 target ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + *result = (b3Vec3){ 0 }; + return 0.0f; + } + + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3Transform transform = b3GetBodyTransform( world, body->id ); + + float closestDistance = FLT_MAX; + b3Vec3 closestPoint = transform.p; + + b3DistanceInput input = { 0 }; + input.proxyA = (b3ShapeProxy){ &target, 1, 0.0f }; + input.transformA.q = b3Quat_identity; + input.transformB = transform; + input.useRadii = false; + + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + shapeId = shape->nextShapeId; + + b3ShapeType type = shape->type; + if ( type != b3_sphereShape && type != b3_capsuleShape && type != b3_hullShape ) + { + continue; + } + + input.proxyB = b3MakeShapeProxy( shape ); + + b3SimplexCache cache = { 0 }; + b3DistanceOutput output = b3ShapeDistance( &input, &cache, NULL, 0 ); + if ( output.distance < closestDistance ) + { + closestDistance = output.distance; + closestPoint = output.pointB; + } + } + + *result = closestPoint; + return closestDistance; +} + +b3BodyCastResult b3Body_CastRay( b3BodyId bodyId, const b3BodyRayCastInput* input, b3Transform bodyTransform ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return (b3BodyCastResult){ 0 }; + } + + b3BodyCastResult result = { 0 }; + b3Body* body = b3GetBodyFullId( world, bodyId ); + + b3RayCastInput shapeInput = { 0 }; + shapeInput.origin = input->origin; + shapeInput.translation = input->translation; + shapeInput.maxFraction = input->maxFraction; + + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + shapeId = shape->nextShapeId; + + if ( b3ShouldQueryCollide( &shape->filter, &input->filter ) == false ) + { + continue; + } + + b3CastOutput shapeOutput = b3RayCastShape( shape, bodyTransform, &shapeInput ); + + if ( shapeOutput.hit == false ) + { + continue; + } + + if ( shapeOutput.fraction > shapeInput.maxFraction ) + { + continue; + } + + // Careful with id, shapeId is the next shape. + b3ShapeId id = { shape->id + 1, bodyId.world0, shape->generation }; + + int materialIndex = b3ClampInt( shapeOutput.materialIndex, 0, shape->materialCount - 1 ); + uint64_t userMaterialId = shape->materials[materialIndex].userMaterialId; + + result = (b3BodyCastResult){ + .shapeId = id, + .point = shapeOutput.point, + .normal = shapeOutput.normal, + .fraction = shapeOutput.fraction, + .triangleIndex = shapeOutput.triangleIndex, + .userMaterialId = userMaterialId, + .iterations = shapeOutput.iterations, + .hit = true, + }; + + shapeInput.maxFraction = shapeOutput.fraction; + } + + return result; +} + +b3BodyCastResult b3Body_CastShape( b3BodyId bodyId, const b3BodyShapeCastInput* input, b3Transform bodyTransform ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return (b3BodyCastResult){ 0 }; + } + + b3BodyCastResult result = { 0 }; + b3Body* body = b3GetBodyFullId( world, bodyId ); + + b3ShapeCastInput shapeInput = { 0 }; + shapeInput.proxy = input->proxy; + shapeInput.translation = input->translation; + shapeInput.maxFraction = input->maxFraction; + shapeInput.canEncroach = input->canEncroach; + + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + shapeId = shape->nextShapeId; + + if ( b3ShouldQueryCollide( &shape->filter, &input->filter ) == false ) + { + continue; + } + + b3CastOutput shapeOutput = b3ShapeCastShape( shape, bodyTransform, &shapeInput ); + + if ( shapeOutput.hit == false ) + { + continue; + } + + if ( shapeOutput.fraction > shapeInput.maxFraction ) + { + continue; + } + + // Careful with id, shapeId is the next shape. + b3ShapeId id = { shape->id + 1, bodyId.world0, shape->generation }; + int materialIndex = b3ClampInt( shapeOutput.materialIndex, 0, shape->materialCount - 1 ); + uint64_t userMaterialId = shape->materials[materialIndex].userMaterialId; + + result = (b3BodyCastResult){ + .shapeId = id, + .point = shapeOutput.point, + .normal = shapeOutput.normal, + .fraction = shapeOutput.fraction, + .triangleIndex = shapeOutput.triangleIndex, + .userMaterialId = userMaterialId, + .iterations = shapeOutput.iterations, + .hit = true, + }; + + shapeInput.maxFraction = shapeOutput.fraction; + } + + return result; +} + +bool b3Body_OverlapShape( b3BodyId bodyId, const b3ShapeProxy* proxy, b3QueryFilter filter, b3Transform bodyTransform ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return false; + } + + b3Body* body = b3GetBodyFullId( world, bodyId ); + + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + shapeId = shape->nextShapeId; + + if ( b3ShouldQueryCollide( &shape->filter, &filter ) == false ) + { + continue; + } + + bool overlaps = b3OverlapShape( shape, bodyTransform, proxy ); + if ( overlaps ) + { + return true; + } + } + + return false; +} + +int b3Body_CollideMover( b3BodyId bodyId, b3BodyPlaneResult* bodyPlanes, int planeCapacity, const b3Capsule* mover, + b3QueryFilter filter, b3Transform bodyTransform ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return 0; + } + + if ( planeCapacity == 0 ) + { + return 0; + } + + int resultCount = 0; + b3Body* body = b3GetBodyFullId( world, bodyId ); + + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + shapeId = shape->nextShapeId; + + if ( b3ShouldQueryCollide( &shape->filter, &filter ) == false ) + { + continue; + } + + b3ShapeType type = shape->type; + if ( type != b3_sphereShape && type != b3_capsuleShape && type != b3_hullShape ) + { + continue; + } + + b3PlaneResult plane; + int count = b3CollideMover( &plane, 1, shape, bodyTransform, mover ); + + if ( count > 0 ) + { + b3ShapeId id = { shape->id + 1, world->worldId, shape->generation }; + bodyPlanes[resultCount] = (b3BodyPlaneResult){ .shapeId = id, .result = plane }; + resultCount += 1; + if ( resultCount == planeCapacity ) + { + return resultCount; + } + } + } + + return resultCount; +} + +void b3UpdateBodyMassData( b3World* world, b3Body* body ) +{ + b3BodySim* bodySim = b3GetBodySim( world, body ); + + // Compute mass data from shapes. Each shape has its own density. + body->mass = 0.0f; + body->inertia = b3Mat3_zero; + + bodySim->invMass = 0.0f; + bodySim->invInertiaLocal = b3Mat3_zero; + bodySim->invInertiaWorld = b3Mat3_zero; + bodySim->localCenter = b3Vec3_zero; + bodySim->minExtent = B3_HUGE; + bodySim->maxExtent = b3Vec3_zero; + + if ( body->headShapeId == B3_NULL_INDEX ) + { + return; + } + + // Static and kinematic sims have zero mass. + if ( body->type != b3_dynamicBody ) + { + bodySim->center = bodySim->transform.p; + bodySim->center0 = bodySim->center; + + // Need extents for kinematic bodies for sleeping to work correctly. + if ( body->type == b3_kinematicBody ) + { + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + const b3Shape* s = b3Array_Get( world->shapes, shapeId ); + + b3ShapeExtent extent = b3ComputeShapeExtent( s, b3Vec3_zero ); + bodySim->minExtent = b3MinFloat( bodySim->minExtent, extent.minExtent ); + bodySim->maxExtent = b3Max( bodySim->maxExtent, extent.maxExtent ); + + shapeId = s->nextShapeId; + } + } + + return; + } + + // Accumulate mass over all shapes. + b3Vec3 localCenter = b3Vec3_zero; + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + const b3Shape* s = b3Array_Get( world->shapes, shapeId ); + shapeId = s->nextShapeId; + + if ( s->density == 0.0f ) + { + continue; + } + + b3MassData massData = b3ComputeShapeMass( s ); + body->mass += massData.mass; + localCenter = b3MulAdd( localCenter, massData.mass, massData.center ); + body->inertia = b3AddMM( body->inertia, massData.inertia ); + } + + // Compute center of mass. + if ( body->mass > 0.0f ) + { + bodySim->invMass = 1.0f / body->mass; + localCenter = b3MulSV( bodySim->invMass, localCenter ); + + // Shift inertia to mass center + body->inertia = b3SubMM( body->inertia, b3Steiner( body->mass, localCenter ) ); + + // This call is faster than b3Invert + bodySim->invInertiaLocal = b3InvertT( body->inertia ); + + b3Matrix3 rotationMatrix = b3MakeMatrixFromQuat( bodySim->transform.q ); + bodySim->invInertiaWorld = b3MulMM( b3MulMM( rotationMatrix, bodySim->invInertiaLocal ), b3Transpose( rotationMatrix ) ); + } + + // Move center of mass. + b3Vec3 oldCenter = bodySim->center; + bodySim->localCenter = localCenter; + bodySim->center = b3TransformPoint( bodySim->transform, bodySim->localCenter ); + bodySim->center0 = bodySim->center; + + // Update center of mass velocity + b3BodyState* state = b3GetBodyState( world, body ); + if ( state != NULL ) + { + b3Vec3 deltaLinear = b3Cross( state->angularVelocity, b3Sub( bodySim->center, oldCenter ) ); + state->linearVelocity = b3Add( state->linearVelocity, deltaLinear ); + } + + // Compute body extents relative to center of mass + shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* s = b3Array_Get( world->shapes, shapeId ); + + b3ShapeExtent extent = b3ComputeShapeExtent( s, localCenter ); + bodySim->minExtent = b3MinFloat( bodySim->minExtent, extent.minExtent ); + bodySim->maxExtent = b3Max( bodySim->maxExtent, extent.maxExtent ); + + shapeId = s->nextShapeId; + } +} + +void b3DumpBody( b3World* world, b3Body* body ) +{ + // int32 bodyIndex = m_islandIndex; + + b3BodySim* sim = b3GetBodySim( world, body ); + b3Vec3 p = sim->transform.p; + b3Quat q = sim->transform.q; + + b3Vec3 v = b3Vec3_zero; + b3Vec3 w = b3Vec3_zero; + b3BodyState* state = b3GetBodyState( world, body ); + if ( state != NULL ) + { + v = state->linearVelocity; + w = state->angularVelocity; + } + + // %.9g is sufficient to save and load the same value using text + // FLT_DECIMAL_DIG == 9 + b3Dump( "{\n" ); + b3Dump( " b3BodyDef bd = b3DefaultBodyDef();\n" ); + if ( body->name[0] != 0 ) + { + b3Dump( " bd.name = \"%s\";\n", body->name ); + } + b3Dump( " bd.type = b3BodyType(%d);\n", body->type ); + b3Dump( " bd.position = {%.9g, %.9g, %.9g};\n", p.x, p.y, p.z ); + b3Dump( " bd.rotation = {{%.9g, %.9g, %.9g}, %.9g};\n", q.v.x, q.v.y, q.v.z, q.s ); + b3Dump( " bd.linearVelocity = {%.9g, %.9g, %.9g};\n", v.x, v.y, v.z ); + b3Dump( " bd.angularVelocity = {%.9g, %.9g, %.9g};\n", w.x, w.y, w.z ); + b3Dump( " bd.linearDamping = %.9g;\n", sim->linearDamping ); + b3Dump( " bd.angularDamping = %.9g;\n", sim->angularDamping ); + b3Dump( " bd.enableSleep = bool(%d);\n", body->enableSleep ); + b3Dump( " bd.isAwake = bool(%d);\n", body->setIndex == b3_awakeSet ); + b3Dump( " bd.gravityScale = %.9g;\n", sim->gravityScale ); + b3Dump( " b3BodyId bodyId = b3CreateBody(m_worldId, &bd);\n" ); + b3Dump( " bodies.push_back(bodyId);\n" ); + b3Dump( "\n" ); + + int shapeIndex = body->headShapeId; + while ( shapeIndex != B3_NULL_INDEX ) + { + b3Dump( " {\n" ); + b3DumpShape( world, shapeIndex ); + b3Dump( " }\n" ); + + b3Shape* shape = b3Array_Get( world->shapes, shapeIndex ); + shapeIndex = shape->nextShapeId; + } + b3Dump( "}\n" ); +} + +b3Vec3 b3Body_GetPosition( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3Transform transform = b3GetBodyTransformQuick( world, body ); + return transform.p; +} + +b3Quat b3Body_GetRotation( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3Transform transform = b3GetBodyTransformQuick( world, body ); + return transform.q; +} + +b3Transform b3Body_GetTransform( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + return b3GetBodyTransformQuick( world, body ); +} + +b3Vec3 b3Body_GetLocalPoint( b3BodyId bodyId, b3Vec3 worldPoint ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3Transform transform = b3GetBodyTransformQuick( world, body ); + return b3InvTransformPoint( transform, worldPoint ); +} + +b3Vec3 b3Body_GetWorldPoint( b3BodyId bodyId, b3Vec3 localPoint ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3Transform transform = b3GetBodyTransformQuick( world, body ); + return b3TransformPoint( transform, localPoint ); +} + +b3Vec3 b3Body_GetLocalVector( b3BodyId bodyId, b3Vec3 worldVector ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3Transform transform = b3GetBodyTransformQuick( world, body ); + return b3InvRotateVector( transform.q, worldVector ); +} + +b3Vec3 b3Body_GetWorldVector( b3BodyId bodyId, b3Vec3 localVector ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3Transform transform = b3GetBodyTransformQuick( world, body ); + return b3RotateVector( transform.q, localVector ); +} + +void b3Body_SetTransform( b3BodyId bodyId, b3Vec3 position, b3Quat rotation ) +{ + B3_ASSERT( b3IsValidVec3( position ) ); + B3_ASSERT( b3IsValidQuat( rotation ) ); + B3_ASSERT( b3Body_IsValid( bodyId ) ); + b3World* world = b3GetWorld( bodyId.world0 ); + B3_ASSERT( world->locked == false ); + + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodySim* bodySim = b3GetBodySim( world, body ); + + bodySim->transform.p = position; + bodySim->transform.q = rotation; + bodySim->center = b3TransformPoint( bodySim->transform, bodySim->localCenter ); + + b3Matrix3 rotationMatrix = b3MakeMatrixFromQuat( bodySim->transform.q ); + bodySim->invInertiaWorld = b3MulMM( b3MulMM( rotationMatrix, bodySim->invInertiaLocal ), b3Transpose( rotationMatrix ) ); + + bodySim->rotation0 = bodySim->transform.q; + bodySim->center0 = bodySim->center; + + b3BroadPhase* broadPhase = &world->broadPhase; + + b3Transform transform = bodySim->transform; + const float margin = B3_AABB_MARGIN; + const float speculativeDistance = B3_SPECULATIVE_DISTANCE; + + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + b3AABB aabb = b3ComputeShapeAABB( shape, transform ); + aabb.lowerBound.x -= speculativeDistance; + aabb.lowerBound.y -= speculativeDistance; + aabb.lowerBound.z -= speculativeDistance; + aabb.upperBound.x += speculativeDistance; + aabb.upperBound.y += speculativeDistance; + aabb.upperBound.z += speculativeDistance; + shape->aabb = aabb; + + if ( b3AABB_Contains( shape->fatAABB, aabb ) == false ) + { + b3AABB fatAABB; + fatAABB.lowerBound.x = aabb.lowerBound.x - margin; + fatAABB.lowerBound.y = aabb.lowerBound.y - margin; + fatAABB.lowerBound.z = aabb.lowerBound.z - margin; + fatAABB.upperBound.x = aabb.upperBound.x + margin; + fatAABB.upperBound.y = aabb.upperBound.y + margin; + fatAABB.upperBound.z = aabb.upperBound.z + margin; + shape->fatAABB = fatAABB; + + // The body could be disabled + if ( shape->proxyKey != B3_NULL_INDEX ) + { + b3BroadPhase_MoveProxy( broadPhase, shape->proxyKey, fatAABB ); + } + } + + shapeId = shape->nextShapeId; + } +} + +b3Vec3 b3Body_GetLinearVelocity( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodyState* state = b3GetBodyState( world, body ); + if ( state != NULL ) + { + return state->linearVelocity; + } + return b3Vec3_zero; +} + +b3Vec3 b3Body_GetAngularVelocity( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodyState* state = b3GetBodyState( world, body ); + if ( state != NULL ) + { + return state->angularVelocity; + } + return b3Vec3_zero; +} + +void b3Body_SetLinearVelocity( b3BodyId bodyId, b3Vec3 linearVelocity ) +{ + B3_ASSERT( b3IsValidVec3( linearVelocity ) ); + + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + + if ( body->type == b3_staticBody ) + { + return; + } + + if ( b3LengthSquared( linearVelocity ) > 0.0f ) + { + b3WakeBodyWithLock( world, body ); + } + + b3BodyState* state = b3GetBodyState( world, body ); + if ( state == NULL ) + { + return; + } + + state->linearVelocity = linearVelocity; +} + +void b3Body_SetAngularVelocity( b3BodyId bodyId, b3Vec3 angularVelocity ) +{ + B3_ASSERT( b3IsValidVec3( angularVelocity ) ); + + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + + if ( body->type == b3_staticBody ) + { + return; + } + + // Apply locks to avoid waking + b3Vec3 w; + w.x = ( body->flags & b3_lockAngularX ) ? 0.0f : angularVelocity.x; + w.y = ( body->flags & b3_lockAngularY ) ? 0.0f : angularVelocity.y; + w.z = ( body->flags & b3_lockAngularZ ) ? 0.0f : angularVelocity.z; + + if ( b3LengthSquared( w ) != 0.0f ) + { + b3WakeBodyWithLock( world, body ); + } + + b3BodyState* state = b3GetBodyState( world, body ); + if ( state == NULL ) + { + return; + } + + state->angularVelocity = w; +} + +void b3Body_SetTargetTransform( b3BodyId bodyId, b3Transform target, float timeStep, bool wake ) +{ + B3_ASSERT( b3IsValidTransform( target ) ); + + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + + if ( body->setIndex == b3_disabledSet ) + { + return; + } + + if ( body->type == b3_staticBody || timeStep <= 0.0f ) + { + return; + } + + if ( body->setIndex != b3_awakeSet && wake == false ) + { + return; + } + + b3BodySim* sim = b3GetBodySim( world, body ); + + // Compute linear velocity + b3Vec3 center1 = sim->center; + b3Vec3 center2 = b3TransformPoint( target, sim->localCenter ); + float invTimeStep = 1.0f / timeStep; + b3Vec3 linearVelocity = b3MulSV( invTimeStep, b3Sub( center2, center1 ) ); + + // Compute angular velocity: + // q' = 0.5 * w * q + // <~> ( q2 - q1 ) / dt = 0.5 * w * q1 + // <=> w = 2 * ( q2 - q1 ) * Conjugate( q1 ) / dt + b3Quat q1 = sim->transform.q; + b3Quat q2 = target.q; + + // Use the shortest arc quaternion + if ( b3DotQuat( q1, q2 ) < 0.0f ) + { + q2 = b3NegateQuat( q2 ); + } + + b3Quat dq = { b3Sub( q2.v, q1.v ), q2.s - q1.s }; + b3Quat omega = b3MulQuat( dq, b3Conjugate( q1 ) ); + b3Vec3 angularVelocity = b3MulSV( 2.0f * invTimeStep, omega.v ); + + // Early out if the body is asleep already and the desired movement is small + if ( body->setIndex != b3_awakeSet ) + { + float maxVelocity = b3Length( linearVelocity ) + b3Length( b3Mul( angularVelocity, sim->maxExtent ) ); + + // Return if velocity would be sleepy + if ( maxVelocity < body->sleepThreshold ) + { + return; + } + + // Must wake for state to exist + b3WakeBodyWithLock( world, body ); + } + + B3_ASSERT( body->setIndex == b3_awakeSet ); + + b3BodyState* state = b3GetBodyState( world, body ); + state->linearVelocity = linearVelocity; + state->angularVelocity = angularVelocity; +} + +b3Vec3 b3Body_GetLocalPointVelocity( b3BodyId bodyId, b3Vec3 localPoint ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodyState* state = b3GetBodyState( world, body ); + if ( state == NULL ) + { + return b3Vec3_zero; + } + + b3SolverSet* set = b3Array_Get( world->solverSets, body->setIndex ); + b3BodySim* bodySim = b3Array_Get( set->bodySims, body->localIndex ); + + b3Vec3 r = b3RotateVector( bodySim->transform.q, b3Sub( localPoint, bodySim->localCenter ) ); + b3Vec3 v = b3Add( state->linearVelocity, b3Cross( state->angularVelocity, r ) ); + return v; +} + +b3Vec3 b3Body_GetWorldPointVelocity( b3BodyId bodyId, b3Vec3 worldPoint ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodyState* state = b3GetBodyState( world, body ); + if ( state == NULL ) + { + return b3Vec3_zero; + } + + b3SolverSet* set = b3Array_Get( world->solverSets, body->setIndex ); + b3BodySim* bodySim = b3Array_Get( set->bodySims, body->localIndex ); + + b3Vec3 r = b3Sub( worldPoint, bodySim->center ); + b3Vec3 v = b3Add( state->linearVelocity, b3Cross( state->angularVelocity, r ) ); + return v; +} + +void b3Body_ApplyForce( b3BodyId bodyId, b3Vec3 force, b3Vec3 point, bool wake ) +{ + B3_ASSERT( b3IsValidVec3( force ) ); + + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + + if ( wake && body->setIndex >= b3_firstSleepingSet ) + { + b3WakeBodyWithLock( world, body ); + } + + if ( body->setIndex == b3_awakeSet ) + { + b3BodySim* bodySim = b3GetBodySim( world, body ); + bodySim->force = b3Add( bodySim->force, force ); + bodySim->torque = b3Add( bodySim->torque, b3Cross( b3Sub( point, bodySim->center ), force ) ); + } +} + +void b3Body_ApplyForceToCenter( b3BodyId bodyId, b3Vec3 force, bool wake ) +{ + B3_ASSERT( b3IsValidVec3( force ) ); + + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + + if ( wake && body->setIndex >= b3_firstSleepingSet ) + { + b3WakeBodyWithLock( world, body ); + } + + if ( body->setIndex == b3_awakeSet ) + { + b3BodySim* bodySim = b3GetBodySim( world, body ); + bodySim->force = b3Add( bodySim->force, force ); + } +} + +void b3Body_ApplyTorque( b3BodyId bodyId, b3Vec3 torque, bool wake ) +{ + B3_ASSERT( b3IsValidVec3( torque ) ); + + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + + if ( wake && body->setIndex >= b3_firstSleepingSet ) + { + b3WakeBodyWithLock( world, body ); + } + + if ( body->setIndex == b3_awakeSet ) + { + b3BodySim* bodySim = b3GetBodySim( world, body ); + bodySim->torque = b3Add( bodySim->torque, torque ); + } +} + +void b3Body_ApplyLinearImpulse( b3BodyId bodyId, b3Vec3 impulse, b3Vec3 point, bool wake ) +{ + B3_ASSERT( b3IsValidVec3( impulse ) ); + B3_ASSERT( b3IsValidVec3( point ) ); + + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + + if ( wake && body->setIndex >= b3_firstSleepingSet ) + { + b3WakeBodyWithLock( world, body ); + } + + if ( body->setIndex == b3_awakeSet ) + { + int localIndex = body->localIndex; + b3SolverSet* set = b3Array_Get( world->solverSets, b3_awakeSet ); + b3BodyState* state = b3Array_Get( set->bodyStates, localIndex ); + b3BodySim* bodySim = b3Array_Get( set->bodySims, localIndex ); + + state->linearVelocity = b3MulAdd( state->linearVelocity, bodySim->invMass, impulse ); + + float maxLinearSpeed = world->maxLinearSpeed; + if ( b3LengthSquared( state->linearVelocity ) > maxLinearSpeed * maxLinearSpeed ) + { + state->linearVelocity = b3MulSV( maxLinearSpeed, b3Normalize( state->linearVelocity ) ); + } + + b3Vec3 delta = b3MulMV( bodySim->invInertiaWorld, b3Cross( b3Sub( point, bodySim->center ), impulse ) ); + state->angularVelocity = b3Add( state->angularVelocity, delta ); + } +} + +void b3Body_ApplyLinearImpulseToCenter( b3BodyId bodyId, b3Vec3 impulse, bool wake ) +{ + B3_ASSERT( b3IsValidVec3( impulse ) ); + + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + + if ( wake && body->setIndex >= b3_firstSleepingSet ) + { + b3WakeBodyWithLock( world, body ); + } + + if ( body->setIndex == b3_awakeSet ) + { + int localIndex = body->localIndex; + b3SolverSet* set = b3Array_Get( world->solverSets, b3_awakeSet ); + b3BodyState* state = b3Array_Get( set->bodyStates, localIndex ); + b3BodySim* bodySim = b3Array_Get( set->bodySims, localIndex ); + state->linearVelocity = b3MulAdd( state->linearVelocity, bodySim->invMass, impulse ); + + float maxLinearSpeed = world->maxLinearSpeed; + if ( b3LengthSquared( state->linearVelocity ) > maxLinearSpeed * maxLinearSpeed ) + { + state->linearVelocity = b3MulSV( maxLinearSpeed, b3Normalize( state->linearVelocity ) ); + } + } +} + +void b3Body_ApplyAngularImpulse( b3BodyId bodyId, b3Vec3 impulse, bool wake ) +{ + B3_ASSERT( b3IsValidVec3( impulse ) ); + B3_ASSERT( b3Body_IsValid( bodyId ) ); + + b3World* world = b3GetWorld( bodyId.world0 ); + + int id = bodyId.index1 - 1; + b3Body* body = b3Array_Get( world->bodies, id ); + B3_ASSERT( body->generation == bodyId.generation ); + + if ( wake && body->setIndex >= b3_firstSleepingSet ) + { + // this will not invalidate body pointer + b3WakeBodyWithLock( world, body ); + } + + if ( body->setIndex == b3_awakeSet ) + { + int localIndex = body->localIndex; + b3SolverSet* set = b3Array_Get( world->solverSets, b3_awakeSet ); + b3BodyState* state = b3Array_Get( set->bodyStates, localIndex ); + b3BodySim* bodySim = b3Array_Get( set->bodySims, localIndex ); + + b3Vec3 localImpulse = b3InvRotateVector( bodySim->transform.q, impulse ); + b3Vec3 localAngularVelocityDelta = b3MulMV( bodySim->invInertiaLocal, localImpulse ); + state->angularVelocity = + b3Add( state->angularVelocity, b3RotateVector( bodySim->transform.q, localAngularVelocityDelta ) ); + } +} + +b3BodyType b3Body_GetType( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( 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 b3Body_SetType( b3BodyId bodyId, b3BodyType type ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return; + } + + world->locked = true; + b3Body* body = b3GetBodyFullId( world, bodyId ); + + b3BodyType originalType = body->type; + if ( originalType == type ) + { + world->locked = false; + return; + } + + if ( type != b3_staticBody ) + { + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + if ( shape->type == b3_compoundShape || shape->type == b3_heightShape ) + { + // Setting the body type is not supported for bodies with compound shapes + return; + } + + shapeId = shape->nextShapeId; + } + } + + // Stage 1: skip disabled bodies + if ( body->setIndex == b3_disabledSet ) + { + // Disabled bodies don't change solver sets or islands when they change type. + body->type = type; + + if ( type == b3_dynamicBody ) + { + body->flags |= b3_dynamicFlag; + } + else + { + body->flags &= ~b3_dynamicFlag; + } + + // Body type affects the mass properties + b3UpdateBodyMassData( world, body ); + world->locked = false; + return; + } + + // Stage 2: destroy all contacts but don't wake bodies (because we don't need to) + bool wakeBodies = false; + b3DestroyBodyContacts( 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. + b3WakeBody( world, body ); + + // Stage 4: move joints to temporary storage + b3SolverSet* staticSet = b3Array_Get( world->solverSets, b3_staticSet ); + + int jointKey = body->headJointKey; + while ( jointKey != B3_NULL_INDEX ) + { + int jointId = jointKey >> 1; + int edgeIndex = jointKey & 1; + + b3Joint* joint = b3Array_Get( world->joints, jointId ); + jointKey = joint->edges[edgeIndex].nextKey; + + // Joint may be disabled by other body + if ( joint->setIndex == b3_disabledSet ) + { + continue; + } + + // Wake attached bodies. The b3WakeBody call above does not wake bodies + // attached to a static body. But it is necessary because the body may have + // no joints. + b3Body* bodyA = b3Array_Get( world->bodies, joint->edges[0].bodyId ); + b3Body* bodyB = b3Array_Get( world->bodies, joint->edges[1].bodyId ); + b3WakeBody( world, bodyA ); + b3WakeBody( world, bodyB ); + + // Remove joint from island + b3UnlinkJoint( 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. + b3SolverSet* jointSourceSet = b3Array_Get( world->solverSets, joint->setIndex ); + b3TransferJoint( world, staticSet, jointSourceSet, joint ); + } + + // Stage 5: change the body type and transfer body + body->type = type; + + if ( type == b3_dynamicBody ) + { + body->flags |= b3_dynamicFlag; + } + else + { + body->flags &= ~b3_dynamicFlag; + } + + b3SolverSet* awakeSet = b3Array_Get( world->solverSets, b3_awakeSet ); + b3SolverSet* sourceSet = b3Array_Get( world->solverSets, body->setIndex ); + b3SolverSet* targetSet = type == b3_staticBody ? staticSet : awakeSet; + + // Transfer body + b3TransferBody( world, targetSet, sourceSet, body ); + + // Stage 6: update island participation for the body + if ( originalType == b3_staticBody ) + { + // Create island for body + b3CreateIslandForBody( world, b3_awakeSet, body ); + } + else if ( type == b3_staticBody ) + { + // Remove body from island. + b3RemoveBodyFromIsland( world, body ); + } + + // Stage 7: Transfer joints to the target set + jointKey = body->headJointKey; + while ( jointKey != B3_NULL_INDEX ) + { + int jointId = jointKey >> 1; + int edgeIndex = jointKey & 1; + + b3Joint* joint = b3Array_Get( world->joints, jointId ); + + jointKey = joint->edges[edgeIndex].nextKey; + + // Joint may be disabled by other body + if ( joint->setIndex == b3_disabledSet ) + { + continue; + } + + // All joints were transferred to the static set in an earlier stage + B3_ASSERT( joint->setIndex == b3_staticSet ); + + b3Body* bodyA = b3Array_Get( world->bodies, joint->edges[0].bodyId ); + b3Body* bodyB = b3Array_Get( world->bodies, joint->edges[1].bodyId ); + B3_ASSERT( bodyA->setIndex == b3_staticSet || bodyA->setIndex == b3_awakeSet ); + B3_ASSERT( bodyB->setIndex == b3_staticSet || bodyB->setIndex == b3_awakeSet ); + + if ( bodyA->type == b3_dynamicBody || bodyB->type == b3_dynamicBody ) + { + b3TransferJoint( world, awakeSet, staticSet, joint ); + } + } + + // Recreate shape proxies in broadphase + b3Transform transform = b3GetBodyTransformQuick( world, body ); + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + + // Setting the body type is not supported for bodies with compound shapes + B3_ASSERT( shape->type != b3_compoundShape ); + + shapeId = shape->nextShapeId; + b3DestroyShapeProxy( shape, &world->broadPhase ); + bool forcePairCreation = true; + b3CreateShapeProxy( shape, &world->broadPhase, type, transform, forcePairCreation ); + } + + // Relink all joints + jointKey = body->headJointKey; + while ( jointKey != B3_NULL_INDEX ) + { + int jointId = jointKey >> 1; + int edgeIndex = jointKey & 1; + + b3Joint* joint = b3Array_Get( world->joints, jointId ); + jointKey = joint->edges[edgeIndex].nextKey; + + int otherEdgeIndex = edgeIndex ^ 1; + int otherBodyId = joint->edges[otherEdgeIndex].bodyId; + b3Body* otherBody = b3Array_Get( world->bodies, otherBodyId ); + + if ( otherBody->setIndex == b3_disabledSet ) + { + continue; + } + + if ( body->type != b3_dynamicBody && otherBody->type != b3_dynamicBody ) + { + continue; + } + + b3LinkJoint( world, joint ); + } + + // Body type affects the mass + b3UpdateBodyMassData( world, body ); + + b3BodyState* state = b3GetBodyState( world, body ); + if ( state != NULL ) + { + // Ensure flags are in sync (b2_skipSolverWrite) + state->flags = body->flags; + } + + b3ValidateSolverSets( world ); + b3ValidateIsland( world, body->islandId ); + + world->locked = false; +} + +void b3Body_SetName( b3BodyId bodyId, const char* name ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + + if ( name ) + { + int i = 0; + while ( i < B3_NAME_LENGTH - 1 && name[i] != 0 ) + { + body->name[i] = name[i]; + i += 1; + } + + while ( i < B3_NAME_LENGTH ) + { + body->name[i] = 0; + i += 1; + } + } + else + { + memset( body->name, 0, B3_NAME_LENGTH * sizeof( char ) ); + } +} + +const char* b3Body_GetName( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + return body->name; +} + +void b3Body_SetUserData( b3BodyId bodyId, void* userData ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + body->userData = userData; +} + +void* b3Body_GetUserData( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + return body->userData; +} + +float b3Body_GetMass( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + return body->mass; +} + +b3Matrix3 b3Body_GetLocalRotationalInertia( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + return body->inertia; +} + +float b3Body_GetInverseMass( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodySim* sim = b3GetBodySim( world, body ); + return sim->invMass; +} + +b3Matrix3 b3Body_GetWorldInverseRotationalInertia( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodySim* sim = b3GetBodySim( world, body ); + return sim->invInertiaWorld; +} + +b3Vec3 b3Body_GetLocalCenterOfMass( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodySim* bodySim = b3GetBodySim( world, body ); + return bodySim->localCenter; +} + +b3Vec3 b3Body_GetWorldCenterOfMass( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodySim* bodySim = b3GetBodySim( world, body ); + return bodySim->center; +} + +void b3Body_SetMassData( b3BodyId bodyId, b3MassData massData ) +{ + B3_ASSERT( b3IsValidFloat( massData.mass ) && massData.mass >= 0.0f ); + B3_ASSERT( b3IsValidMatrix3( massData.inertia ) ); + B3_ASSERT( b3IsValidVec3( massData.center ) ); + + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return; + } + + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodySim* bodySim = b3GetBodySim( world, body ); + + body->mass = massData.mass; + body->inertia = massData.inertia; + bodySim->localCenter = massData.center; + + b3Vec3 center = b3TransformPoint( bodySim->transform, massData.center ); + bodySim->center = center; + bodySim->center0 = center; + + bodySim->invMass = body->mass > 0.0f ? 1.0f / body->mass : 0.0f; + bodySim->invInertiaLocal = b3Det( body->inertia ) > 0.0f ? b3InvertT( body->inertia ) : b3Mat3_zero; +} + +b3MassData b3Body_GetMassData( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodySim* bodySim = b3GetBodySim( world, body ); + b3MassData massData = { body->mass, bodySim->localCenter, body->inertia }; + return massData; +} + +void b3Body_ApplyMassFromShapes( b3BodyId bodyId ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return; + } + + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3UpdateBodyMassData( world, body ); +} + +void b3Body_SetLinearDamping( b3BodyId bodyId, float linearDamping ) +{ + B3_ASSERT( b3IsValidFloat( linearDamping ) && linearDamping >= 0.0f ); + + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return; + } + + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodySim* bodySim = b3GetBodySim( world, body ); + bodySim->linearDamping = linearDamping; +} + +float b3Body_GetLinearDamping( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodySim* bodySim = b3GetBodySim( world, body ); + return bodySim->linearDamping; +} + +void b3Body_SetAngularDamping( b3BodyId bodyId, float angularDamping ) +{ + B3_ASSERT( b3IsValidFloat( angularDamping ) && angularDamping >= 0.0f ); + + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return; + } + + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodySim* bodySim = b3GetBodySim( world, body ); + bodySim->angularDamping = angularDamping; +} + +float b3Body_GetAngularDamping( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodySim* bodySim = b3GetBodySim( world, body ); + return bodySim->angularDamping; +} + +void b3Body_SetGravityScale( b3BodyId bodyId, float gravityScale ) +{ + B3_ASSERT( b3Body_IsValid( bodyId ) ); + B3_ASSERT( b3IsValidFloat( gravityScale ) ); + + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return; + } + + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodySim* bodySim = b3GetBodySim( world, body ); + bodySim->gravityScale = gravityScale; +} + +float b3Body_GetGravityScale( b3BodyId bodyId ) +{ + B3_ASSERT( b3Body_IsValid( bodyId ) ); + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodySim* bodySim = b3GetBodySim( world, body ); + return bodySim->gravityScale; +} + +bool b3Body_IsAwake( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + return body->setIndex == b3_awakeSet; +} + +void b3Body_SetAwake( b3BodyId bodyId, bool awake ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return; + } + + world->locked = true; + + b3Body* body = b3GetBodyFullId( world, bodyId ); + + if ( awake && body->setIndex >= b3_firstSleepingSet ) + { + b3WakeBody( world, body ); + } + else if ( awake == false && body->setIndex == b3_awakeSet ) + { + b3Island* island = b3Array_Get( world->islands, body->islandId ); + if ( island->constraintRemoveCount > 0 ) + { + // Must split the island before sleeping. This is expensive. + b3SplitIsland( world, body->islandId ); + } + + b3TrySleepIsland( world, body->islandId ); + } + + world->locked = false; +} + +bool b3Body_IsEnabled( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + return body->setIndex != b3_disabledSet; +} + +bool b3Body_IsSleepEnabled( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + return body->enableSleep; +} + +void b3Body_SetSleepThreshold( b3BodyId bodyId, float sleepThreshold ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + body->sleepThreshold = sleepThreshold; +} + +float b3Body_GetSleepThreshold( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + return body->sleepThreshold; +} + +void b3Body_EnableSleep( b3BodyId bodyId, bool enableSleep ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return; + } + + world->locked = true; + + b3Body* body = b3GetBodyFullId( world, bodyId ); + body->enableSleep = enableSleep; + + if ( enableSleep == false ) + { + b3WakeBody( world, body ); + } + + world->locked = false; +} + +// Disabling a body requires a lot of detailed bookkeeping, but it is a valuable feature. +// The most challenging aspect that joints may connect to bodies that are not disabled. +void b3Body_Disable( b3BodyId bodyId ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return; + } + + world->locked = true; + + b3Body* body = b3GetBodyFullId( world, bodyId ); + if ( body->setIndex == b3_disabledSet ) + { + world->locked = false; + return; + } + + // Destroy contacts and wake bodies touching this body. This avoid floating bodies. + // This is necessary even for static bodies. + bool wakeBodies = true; + b3DestroyBodyContacts( world, body, wakeBodies ); + + // The current solver set of the body + b3SolverSet* set = b3Array_Get( world->solverSets, body->setIndex ); + + // Disabled bodies and connected joints are moved to the disabled set + b3SolverSet* disabledSet = b3Array_Get( world->solverSets, b3_disabledSet ); + + // Unlink joints and transfer them to the disabled set + int jointKey = body->headJointKey; + while ( jointKey != B3_NULL_INDEX ) + { + int jointId = jointKey >> 1; + int edgeIndex = jointKey & 1; + + b3Joint* joint = b3Array_Get( world->joints, jointId ); + jointKey = joint->edges[edgeIndex].nextKey; + + // joint may already be disabled by other body + if ( joint->setIndex == b3_disabledSet ) + { + continue; + } + + B3_ASSERT( joint->setIndex == set->setIndex || set->setIndex == b3_staticSet ); + + // Remove joint from island + b3UnlinkJoint( world, joint ); + + // Transfer joint to disabled set + b3SolverSet* jointSet = b3Array_Get( world->solverSets, joint->setIndex ); + b3TransferJoint( world, disabledSet, jointSet, joint ); + } + + // Remove shapes from broad-phase + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + shapeId = shape->nextShapeId; + b3DestroyShapeProxy( shape, &world->broadPhase ); + } + + // Disabled bodies are not in an island. If the island becomes empty it will be destroyed. + b3RemoveBodyFromIsland( world, body ); + + // Transfer body sim + b3TransferBody( world, disabledSet, set, body ); + + b3ValidateConnectivity( world ); + b3ValidateSolverSets( world ); + + world->locked = false; +} + +void b3Body_Enable( b3BodyId bodyId ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return; + } + + b3Body* body = b3GetBodyFullId( world, bodyId ); + if ( body->setIndex != b3_disabledSet ) + { + return; + } + + b3SolverSet* disabledSet = b3Array_Get( world->solverSets, b3_disabledSet ); + int setId = body->type == b3_staticBody ? b3_staticSet : b3_awakeSet; + b3SolverSet* targetSet = b3Array_Get( world->solverSets, setId ); + + b3TransferBody( world, targetSet, disabledSet, body ); + + b3Transform transform = b3GetBodyTransformQuick( world, body ); + + // Add shapes to broad-phase + b3BodyType proxyType = body->type; + bool forcePairCreation = true; + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + shapeId = shape->nextShapeId; + + b3CreateShapeProxy( shape, &world->broadPhase, proxyType, transform, forcePairCreation ); + } + + if ( setId != b3_staticSet ) + { + b3CreateIslandForBody( 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 != B3_NULL_INDEX ) + { + int jointId = jointKey >> 1; + int edgeIndex = jointKey & 1; + + b3Joint* joint = b3Array_Get( world->joints, jointId ); + B3_ASSERT( joint->setIndex == b3_disabledSet ); + B3_ASSERT( joint->islandId == B3_NULL_INDEX ); + + jointKey = joint->edges[edgeIndex].nextKey; + + b3Body* bodyA = b3Array_Get( world->bodies, joint->edges[0].bodyId ); + b3Body* bodyB = b3Array_Get( world->bodies, joint->edges[1].bodyId ); + + if ( bodyA->setIndex == b3_disabledSet || bodyB->setIndex == b3_disabledSet ) + { + // one body is still disabled + continue; + } + + // Transfer joint first + int jointSetId; + if ( bodyA->setIndex == b3_staticSet && bodyB->setIndex == b3_staticSet ) + { + jointSetId = b3_staticSet; + } + else if ( bodyA->setIndex == b3_staticSet ) + { + jointSetId = bodyB->setIndex; + } + else + { + jointSetId = bodyA->setIndex; + } + + b3SolverSet* jointSet = b3Array_Get( world->solverSets, jointSetId ); + b3TransferJoint( world, jointSet, disabledSet, joint ); + + // Now that the joint is in the correct set, I can link the joint in the island. + if ( jointSetId != b3_staticSet ) + { + b3LinkJoint( world, joint ); + } + } + + b3ValidateSolverSets( world ); +} + +void b3Body_SetMotionLocks( b3BodyId bodyId, b3MotionLocks locks ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return; + } + + uint32_t newFlags = 0; + newFlags |= locks.linearX ? b3_lockLinearX : 0; + newFlags |= locks.linearY ? b3_lockLinearY : 0; + newFlags |= locks.linearZ ? b3_lockLinearZ : 0; + newFlags |= locks.angularX ? b3_lockAngularX : 0; + newFlags |= locks.angularY ? b3_lockAngularY : 0; + newFlags |= locks.angularZ ? b3_lockAngularZ : 0; + + b3Body* body = b3GetBodyFullId( world, bodyId ); + if ( ( body->flags & b3_allLocks ) != newFlags ) + { + body->flags &= ~b3_allLocks; + body->flags |= newFlags; + + b3BodySim* bodySim = b3GetBodySim( world, body ); + bodySim->flags &= ~b3_allLocks; + bodySim->flags |= newFlags; + + b3BodyState* state = b3GetBodyState( world, body ); + + if ( state != NULL ) + { + state->flags = body->flags; + + if ( locks.linearX ) + { + state->linearVelocity.x = 0.0f; + } + + if ( locks.linearY ) + { + state->linearVelocity.y = 0.0f; + } + + if ( locks.linearZ ) + { + state->linearVelocity.z = 0.0f; + } + + if ( locks.angularX ) + { + state->angularVelocity.x = 0.0f; + } + + if ( locks.angularY ) + { + state->angularVelocity.y = 0.0f; + } + + if ( locks.angularZ ) + { + state->angularVelocity.z = 0.0f; + } + } + } +} + +b3MotionLocks b3Body_GetMotionLocks( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + + b3MotionLocks locks; + locks.linearX = ( body->flags & b3_lockLinearX ); + locks.linearY = ( body->flags & b3_lockLinearY ); + locks.linearZ = ( body->flags & b3_lockLinearZ ); + locks.angularX = ( body->flags & b3_lockAngularX ); + locks.angularY = ( body->flags & b3_lockAngularY ); + locks.angularZ = ( body->flags & b3_lockAngularZ ); + return locks; +} + +void b3Body_SetBullet( b3BodyId bodyId, bool flag ) +{ + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return; + } + + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodySim* bodySim = b3GetBodySim( world, body ); + + if ( flag ) + { + bodySim->flags |= b3_isBullet; + } + else + { + bodySim->flags &= ~b3_isBullet; + } +} + +bool b3Body_IsBullet( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodySim* bodySim = b3GetBodySim( world, body ); + return ( bodySim->flags & b3_isBullet ) != 0; +} + +void b3Body_EnableHitEvents( b3BodyId bodyId, bool enableHitEvents ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + shape->enableHitEvents = enableHitEvents; + shapeId = shape->nextShapeId; + } +} + +b3WorldId b3Body_GetWorld( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + return (b3WorldId){ (uint16_t)( bodyId.world0 + 1 ), world->generation }; +} + +int b3Body_GetShapeCount( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + return body->shapeCount; +} + +int b3Body_GetShapes( b3BodyId bodyId, b3ShapeId* shapeArray, int capacity ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + int shapeId = body->headShapeId; + int shapeCount = 0; + while ( shapeId != B3_NULL_INDEX && shapeCount < capacity ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + b3ShapeId id = { shape->id + 1, bodyId.world0, shape->generation }; + shapeArray[shapeCount] = id; + shapeCount += 1; + + shapeId = shape->nextShapeId; + } + + return shapeCount; +} + +int b3Body_GetJointCount( b3BodyId bodyId ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + return body->jointCount; +} + +int b3Body_GetJoints( b3BodyId bodyId, b3JointId* jointArray, int capacity ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + int jointKey = body->headJointKey; + + int jointCount = 0; + while ( jointKey != B3_NULL_INDEX && jointCount < capacity ) + { + int jointId = jointKey >> 1; + int edgeIndex = jointKey & 1; + + b3Joint* joint = b3Array_Get( world->joints, jointId ); + + b3JointId id = { jointId + 1, bodyId.world0, joint->generation }; + jointArray[jointCount] = id; + jointCount += 1; + + jointKey = joint->edges[edgeIndex].nextKey; + } + + return jointCount; +} + +bool b3ShouldBodiesCollide( b3World* world, b3Body* bodyA, b3Body* bodyB ) +{ + if ( bodyA->type != b3_dynamicBody && bodyB->type != b3_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 != B3_NULL_INDEX ) + { + int jointId = jointKey >> 1; + int edgeIndex = jointKey & 1; + int otherEdgeIndex = edgeIndex ^ 1; + + b3Joint* joint = b3Array_Get( world->joints, jointId ); + if ( joint->collideConnected == false && joint->edges[otherEdgeIndex].bodyId == otherBodyId ) + { + return false; + } + + jointKey = joint->edges[edgeIndex].nextKey; + } + + return true; +} diff --git a/src/body.h b/src/body.h new file mode 100644 index 0000000..e094895 --- /dev/null +++ b/src/body.h @@ -0,0 +1,254 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "box3d/constants.h" +#include "box3d/math_functions.h" +#include "box3d/types.h" + +typedef struct b3World b3World; + +enum b3BodyFlags +{ + // This body has fixed translation along the x-axis + b3_lockLinearX = 0x00000001, + + // This body has fixed translation along the y-axis + b3_lockLinearY = 0x00000002, + + // This body has fixed translation along the z-axis + b3_lockLinearZ = 0x00000004, + + // This body has fixed rotation around the x-axis + b3_lockAngularX = 0x00000008, + + // This body has fixed rotation around the y-axis + b3_lockAngularY = 0x00000010, + + // This body has fixed rotation around the z-axis + b3_lockAngularZ = 0x00000020, + + // This flag is used for debug draw + b3_isFast = 0x00000040, + + // This dynamic body does a final CCD pass against all body types, but not other bullets + b3_isBullet = 0x00000080, + + // This body was speed capped in the current time step + b3_isSpeedCapped = 0x00000100, + + // This body had a time of impact event in the current time step + b3_hadTimeOfImpact = 0x00000200, + + // This body has no limit on angular velocity + b3_allowFastRotation = 0x00000400, + + // This body need's to have its AABB increased + b3_enlargeBounds = 0x00000800, + + // 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 b3BodyState flags. + b3_dynamicFlag = 0x00001000, + + // All lock flags + b3_allLocks = b3_lockLinearX | b3_lockLinearY | b3_lockLinearZ | b3_lockAngularX | b3_lockAngularY | b3_lockAngularZ, +}; + +// Body organizational details that are not used in the solver. +typedef struct b3Body +{ + char name[B3_NAME_LENGTH]; + + void* userData; + + // index of solver set stored in b3World + // may be B3_NULL_INDEX + int setIndex; + + // body sim and state index within set + // may be B3_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; + + // Index into the island's bodies array for O(1) swap-removal. + // B3_NULL_INDEX when not in an island. + int islandIndex; + + float sleepThreshold; + float sleepTime; + + float mass; + + // local space inertia + b3Matrix3 inertia; + + // this is used to adjust the fellAsleep flag in the body move array + int bodyMoveIndex; + + int id; + + // b3BodyFlags + uint32_t flags; + + b3BodyType type; + + // This is monotonically advanced when a body is allocated in this slot + // Used to check for invalid b3BodyId + uint16_t generation; + + // todo move into flags + bool enableSleep; +} b3Body; + +// 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. +// +// 56 bytes +// todo_erin measure perf padding to 64 bytes +typedef struct b3BodyState +{ + b3Vec3 linearVelocity; // 12 + b3Vec3 angularVelocity; // 12 + + // Using delta position reduces round-off error far from the origin + b3Vec3 deltaPosition; // 12 + + // 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) + b3Quat deltaRotation; // 16 + + // b3BodyFlags + // Important flags: locking, dynamic + uint32_t flags; // 4 +} b3BodyState; + +// Identity body state, notice the deltaRotation is identity +static const b3BodyState b3_identityBodyState = { + { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { { 0.0f, 0.0f, 0.0f }, 1.0f }, 0, +}; + +// Body simulation data used for integration of position and velocity +// Transform data used for collision and solver preparation. +typedef struct b3BodySim +{ + // transform for body origin + b3Transform transform; + + // center of mass position in world space + b3Vec3 center; + + // previous rotation and COM for TOI + b3Quat rotation0; + b3Vec3 center0; + + // location of center of mass relative to the body origin + b3Vec3 localCenter; + + b3Vec3 force; + b3Vec3 torque; + + float invMass; + + // Rotational inertia about the center of mass. The world space inverse inertia tensor + // must be updated whenever the body rotation is modified. + b3Matrix3 invInertiaLocal; + b3Matrix3 invInertiaWorld; + + float minExtent; + b3Vec3 maxExtent; + float maxAngularVelocity; + float linearDamping; + float angularDamping; + float gravityScale; + + // Index of b3Body + int bodyId; + + // b3BodyFlags + uint32_t flags; +} b3BodySim; + +#ifdef __cplusplus +extern "C" +{ +#endif + +// Get a validated body from a world using an id. +b3Body* b3GetBodyFullId( b3World* world, b3BodyId bodyId ); + +b3Transform b3GetBodyTransformQuick( b3World* world, b3Body* body ); +b3Transform b3GetBodyTransform( b3World* world, int bodyId ); + +// Create a b3BodyId from a raw id. +b3BodyId b3MakeBodyId( b3World* world, int bodyId ); + +bool b3ShouldBodiesCollide( b3World* world, b3Body* bodyA, b3Body* bodyB ); +bool b3IsBodyAwake( b3World* world, b3Body* body ); + +b3BodySim* b3GetBodySim( b3World* world, b3Body* body ); +b3BodyState* b3GetBodyState( b3World* world, b3Body* body ); + +// careful calling this because it can invalidate body, state, joint, and contact pointers +bool b3WakeBody( b3World* world, b3Body* body ); +bool b3WakeBodyWithLock( b3World* world, b3Body* body ); + +void b3UpdateBodyMassData( b3World* world, b3Body* body ); +void b3DumpBody( b3World* world, b3Body* body ); + +#ifdef __cplusplus +} +#endif + +B3_INLINE b3Sweep b3MakeSweep( const b3BodySim* bodySim ) +{ + b3Sweep s; + s.c1 = bodySim->center0; + s.c2 = bodySim->center; + s.q1 = bodySim->rotation0; + s.q2 = bodySim->transform.q; + s.localCenter = bodySim->localCenter; + return s; +} + diff --git a/src/box3d.natvis b/src/box3d.natvis new file mode 100644 index 0000000..a5d1d7e --- /dev/null +++ b/src/box3d.natvis @@ -0,0 +1,138 @@ + + + + + + [ {x}, {y} ] + + + + [ {x}, {y}, {z} ] + + + + [ {v}, {s} ] + + + + index: {index1} + + b3_worlds[ index1 - 1 ] + + + + + + {b3_worlds[world0].bodies.data[index1-1].name,na}, + {b3_worlds[world0].bodies.data[index1-1].type} + + + b3_worlds[ world0 ].bodies.data[index1-1] + + + + + + {b3_worlds[world0].shapes.data[index1-1].type} + + + + + + {point}, sep = {separation} + + + + + + {int(owner1)}:{int(index1)}, {int(owner2)}:{int(index2)} + + + + + count: { pointCount }, triangle: { triangleIndex }, cluster: {clusterIndex} + + normal + feature + triangleFlags + + pointCount + points + + + + + + {{{count} : {radius}}} + + count + radius + + count + points + + + + + + type: {type} + + witnessA + witnessB + sweepA + sweepB + proxyA + proxyB + + + + + {{{count} / {capacity}}} + + count + capacity + + count + data + + + + + + + {{{count} / {capacity}}} + + count + capacity + + count + data + + + + + + {{{count} / {capacity}}} + + count + capacity + + count + data + + + + + + {{{count} / {capacity}}} + + count + capacity + + count + data + + + + + diff --git a/src/broad_phase.c b/src/broad_phase.c new file mode 100644 index 0000000..bd7b855 --- /dev/null +++ b/src/broad_phase.c @@ -0,0 +1,534 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "broad_phase.h" + +#include "aabb.h" +#include "arena_allocator.h" +#include "body.h" +#include "contact.h" +#include "core.h" +#include "parallel_for.h" +#include "physics_world.h" +#include "platform.h" +#include "shape.h" + +#include + +void b3CreateBroadPhase( b3BroadPhase* bp, const b3Capacity* capacity ) +{ + _Static_assert( b3_bodyTypeCount == 3, "must be three body types" ); + + bp->moveSet = b3CreateSet( 2 * capacity->dynamicShapeCount ); + b3Array_Reserve( bp->moveArray, capacity->dynamicShapeCount ); + bp->moveResults = NULL; + bp->movePairs = NULL; + bp->movePairCapacity = 0; + b3AtomicStoreInt( &bp->movePairIndex, 0 ); + bp->pairSet = b3CreateSet( 2 * capacity->contactCount ); + + int staticCapacity = b3MaxInt( 16, capacity->staticShapeCount ); + bp->trees[b3_staticBody] = b3DynamicTree_Create( staticCapacity ); + + int kinematicCapacity = 16; + bp->trees[b3_kinematicBody] = b3DynamicTree_Create( kinematicCapacity ); + + int dynamicCapacity = b3MaxInt( 16, capacity->dynamicShapeCount ); + bp->trees[b3_dynamicBody] = b3DynamicTree_Create( dynamicCapacity ); +} + +void b3DestroyBroadPhase( b3BroadPhase* bp ) +{ + for ( int i = 0; i < b3_bodyTypeCount; ++i ) + { + b3DynamicTree_Destroy( bp->trees + i ); + } + + b3DestroySet( &bp->moveSet ); + b3Array_Destroy( bp->moveArray ); + b3DestroySet( &bp->pairSet ); + + *bp = (b3BroadPhase){ 0 }; + + memset( bp, 0, sizeof( b3BroadPhase ) ); +} + +static void b3UnBufferMove( b3BroadPhase* bp, int proxyKey ) +{ + bool found = b3RemoveKey( &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 ) + { + b3Array_RemoveSwap( bp->moveArray, i ); + break; + } + } + } +} + +int b3BroadPhase_CreateProxy( b3BroadPhase* bp, b3BodyType proxyType, b3AABB aabb, uint64_t categoryBits, int shapeIndex, + bool forcePairCreation ) +{ + B3_ASSERT( 0 <= proxyType && proxyType < b3_bodyTypeCount ); + int proxyId = b3DynamicTree_CreateProxy( bp->trees + proxyType, aabb, categoryBits, shapeIndex ); + int proxyKey = B3_PROXY_KEY( proxyId, proxyType ); + if ( proxyType != b3_staticBody || forcePairCreation ) + { + b3BufferMove( bp, proxyKey ); + } + return proxyKey; +} + +void b3BroadPhase_DestroyProxy( b3BroadPhase* bp, int proxyKey ) +{ + B3_ASSERT( bp->moveArray.count == (int)bp->moveSet.count ); + b3UnBufferMove( bp, proxyKey ); + + b3BodyType proxyType = B3_PROXY_TYPE( proxyKey ); + int proxyId = B3_PROXY_ID( proxyKey ); + + B3_ASSERT( 0 <= proxyType && proxyType <= b3_bodyTypeCount ); + b3DynamicTree_DestroyProxy( bp->trees + proxyType, proxyId ); +} + +void b3BroadPhase_MoveProxy( b3BroadPhase* bp, int proxyKey, b3AABB aabb ) +{ + b3BodyType proxyType = B3_PROXY_TYPE( proxyKey ); + int proxyId = B3_PROXY_ID( proxyKey ); + + b3DynamicTree_MoveProxy( bp->trees + proxyType, proxyId, aabb ); + b3BufferMove( bp, proxyKey ); +} + +void b3BroadPhase_EnlargeProxy( b3BroadPhase* bp, int proxyKey, b3AABB aabb ) +{ + B3_ASSERT( proxyKey != B3_NULL_INDEX ); + int typeIndex = B3_PROXY_TYPE( proxyKey ); + int proxyId = B3_PROXY_ID( proxyKey ); + + B3_ASSERT( typeIndex != b3_staticBody ); + + b3DynamicTree_EnlargeProxy( bp->trees + typeIndex, proxyId, aabb ); + b3BufferMove( bp, proxyKey ); +} + +typedef struct b3MovePair +{ + int shapeIndexA; + int shapeIndexB; + int childIndex; + b3MovePair* next; + bool heap; +} b3MovePair; + +typedef struct b3MoveResult +{ + b3MovePair* pairList; +} b3MoveResult; + +typedef struct b3QueryPairContext +{ + b3World* world; + b3MoveResult* moveResult; + b3AABB aabb; + b3BodyType queryTreeType; + int queryProxyKey; + int queryShapeIndex; + + int compoundProxyId; + int compoundShapeIndex; +} b3QueryPairContext; + +// This is called from b3DynamicTree::Query when we are gathering pairs. +static bool b3PairQueryCallback( int proxyId, uint64_t userData, void* context ) +{ + b3QueryPairContext* queryContext = (b3QueryPairContext*)context; + b3World* world = queryContext->world; + int shapeIndex; + int childIndex = 0; + + if ( queryContext->compoundShapeIndex == B3_NULL_INDEX ) + { + // Outer query: userData is a shape index. + shapeIndex = (int)userData; + + // A proxy cannot form a pair with itself. + if ( shapeIndex == queryContext->queryShapeIndex ) + { + return true; + } + + b3Shape* shape = b3Array_Get( world->shapes, shapeIndex ); + if ( shape->type == b3_compoundShape ) + { + b3Transform compoundTransform = b3GetBodyTransform( world, shape->bodyId ); + b3AABB localAABB = b3AABB_Transform( b3InvertTransform( compoundTransform ), queryContext->aabb ); + + // recurse + queryContext->compoundShapeIndex = shapeIndex; + queryContext->compoundProxyId = proxyId; + + b3DynamicTree_Query( &shape->compound->tree, localAABB, B3_DEFAULT_MASK_BITS, false, b3PairQueryCallback, context ); + queryContext->compoundShapeIndex = B3_NULL_INDEX; + queryContext->compoundProxyId = B3_NULL_INDEX; + return true; + } + } + else + { + // Inner query into a compound shape: userData is the compound child index, not a shape + // index, so do not compare it against queryShapeIndex. + shapeIndex = queryContext->compoundShapeIndex; + proxyId = queryContext->compoundProxyId; + childIndex = (int)userData; + } + + b3BroadPhase* broadPhase = &queryContext->world->broadPhase; + + int proxyKey = B3_PROXY_KEY( proxyId, queryContext->queryTreeType ); + int queryProxyKey = queryContext->queryProxyKey; + + // A proxy cannot form a pair with itself. + B3_ASSERT( proxyKey != queryContext->queryProxyKey ); + + b3BodyType treeType = queryContext->queryTreeType; + b3BodyType queryProxyType = B3_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 + // b3ShapeDef::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 == b3_dynamicBody ) + { + if ( treeType == b3_dynamicBody && proxyKey < queryProxyKey ) + { + bool moved = b3ContainsKey( &broadPhase->moveSet, proxyKey + 1 ); + if ( moved ) + { + // Both proxies are moving. Avoid duplicate pairs. + return true; + } + } + } + else + { + B3_ASSERT( treeType == b3_dynamicBody ); + bool moved = b3ContainsKey( &broadPhase->moveSet, proxyKey + 1 ); + if ( moved ) + { + // Both proxies are moving. Avoid duplicate pairs. + return true; + } + } + + uint64_t pairKey = b3ShapePairKey( shapeIndex, queryContext->queryShapeIndex, childIndex ); + if ( b3ContainsKey( &broadPhase->pairSet, pairKey ) ) + { + // contact exists + return true; + } + + // Order shapes so that B3_SHAPE_PAIR_KEY works correctly + int shapeIdA = shapeIndex; + int shapeIdB = queryContext->queryShapeIndex; + b3Shape* shapeA = b3Array_Get( world->shapes, shapeIdA ); + b3Shape* shapeB = b3Array_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 != B3_NULL_INDEX || shapeB->sensorIndex != B3_NULL_INDEX ) + { + return true; + } + + if ( b3ShouldShapesCollide( shapeA->filter, shapeB->filter ) == false ) + { + return true; + } + + // Does a joint override collision? + b3Body* bodyA = b3Array_Get( world->bodies, bodyIdA ); + b3Body* bodyB = b3Array_Get( world->bodies, bodyIdB ); + if ( b3ShouldBodiesCollide( world, bodyA, bodyB ) == false ) + { + return true; + } + + // Custom user filter + if ( shapeA->enableCustomFiltering || shapeB->enableCustomFiltering ) + { + b3CustomFilterFcn* customFilterFcn = queryContext->world->customFilterFcn; + if ( customFilterFcn != NULL ) + { + b3ShapeId idA = { shapeIdA + 1, world->worldId, shapeA->generation }; + b3ShapeId 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 = b3AtomicFetchAddInt( &broadPhase->movePairIndex, 1 ); + + b3MovePair* pair; + if ( pairIndex < broadPhase->movePairCapacity ) + { + pair = broadPhase->movePairs + pairIndex; + pair->heap = false; + } + else + { + // todo experimenting with ignoring this pair if we ran out of space + return true; + // pair = (b3MovePair*)b3Alloc( sizeof( b3MovePair ) ); + // pair->heap = true; + } + + pair->shapeIndexA = shapeIdA; + pair->shapeIndexB = shapeIdB; + pair->childIndex = childIndex; + pair->next = queryContext->moveResult->pairList; + queryContext->moveResult->pairList = pair; + + // continue the query + return true; +} + +static void b3FindPairsTask( int startIndex, int endIndex, int workerIndex, void* context ) +{ + b3TracyCZoneNC( pair_task, "Pair Task", b3_colorAquamarine, true ); + + B3_UNUSED( workerIndex ); + + b3World* world = (b3World*)context; + b3BroadPhase* bp = &world->broadPhase; + + b3QueryPairContext queryContext = { 0 }; + queryContext.world = world; + queryContext.compoundShapeIndex = B3_NULL_INDEX; + + 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 == B3_NULL_INDEX ) + { + // proxy was destroyed after it moved + continue; + } + + b3BodyType proxyType = B3_PROXY_TYPE( proxyKey ); + + int proxyId = B3_PROXY_ID( proxyKey ); + queryContext.queryProxyKey = proxyKey; + + const b3DynamicTree* 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. + b3AABB fatAABB = b3DynamicTree_GetAABB( baseTree, proxyId ); + queryContext.queryShapeIndex = (int)b3DynamicTree_GetUserData( baseTree, proxyId ); + queryContext.aabb = fatAABB; + + // Compound shape collision invocation is not supported + B3_VALIDATE( world->shapes.data[queryContext.queryShapeIndex].type != b3_compoundShape ); + + // Query trees. Only dynamic proxies collide with kinematic and static proxies. + // Using B3_DEFAULT_MASK_BITS so that b3Filter::groupIndex works. + // consider using bits = groupIndex > 0 ? B3_DEFAULT_MASK_BITS : maskBits + bool requireAllBits = false; + if ( proxyType == b3_dynamicBody ) + { + queryContext.queryTreeType = b3_kinematicBody; + b3DynamicTree_Query( bp->trees + b3_kinematicBody, fatAABB, B3_DEFAULT_MASK_BITS, requireAllBits, b3PairQueryCallback, + &queryContext ); + + queryContext.queryTreeType = b3_staticBody; + b3DynamicTree_Query( bp->trees + b3_staticBody, fatAABB, B3_DEFAULT_MASK_BITS, requireAllBits, b3PairQueryCallback, + &queryContext ); + } + + // All proxies collide with dynamic proxies + // Using B3_DEFAULT_MASK_BITS so that b3Filter::groupIndex works. + queryContext.queryTreeType = b3_dynamicBody; + b3DynamicTree_Query( bp->trees + b3_dynamicBody, fatAABB, B3_DEFAULT_MASK_BITS, requireAllBits, b3PairQueryCallback, + &queryContext ); + } + + b3TracyCZoneEnd( pair_task ); +} + +static void b3UpdateTreesTask( void* context ) +{ + b3TracyCZoneNC( tree_task, "Rebuild Trees", b3_colorFireBrick, true ); + + b3World* world = (b3World*)context; + b3DynamicTree_Rebuild( world->broadPhase.trees + b3_dynamicBody, false ); + b3DynamicTree_Rebuild( world->broadPhase.trees + b3_kinematicBody, false ); + + b3TracyCZoneEnd( tree_task ); +} + +void b3UpdateBroadPhasePairs( b3World* world ) +{ + b3BroadPhase* bp = &world->broadPhase; + + int moveCount = bp->moveArray.count; + B3_ASSERT( moveCount == (int)bp->moveSet.count ); + + if ( moveCount == 0 ) + { + return; + } + + b3TracyCZoneNC( update_pairs, "Pairs", b3_colorMediumSlateBlue, true ); + + b3Stack* alloc = &world->stack; + + // todo these could be in the step context + bp->moveResults = (b3MoveResult*)b3StackAlloc( alloc, moveCount * sizeof( b3MoveResult ), "move results" ); + bp->movePairCapacity = 16 * moveCount; + bp->movePairs = (b3MovePair*)b3StackAlloc( alloc, bp->movePairCapacity * sizeof( b3MovePair ), "move pairs" ); + + b3AtomicStoreInt( &bp->movePairIndex, 0 ); + +#ifndef NDEBUG + extern b3AtomicInt b3_probeCount; + b3AtomicStoreInt( &b3_probeCount, 0 ); +#endif + + int minRange = 64; + b3ParallelFor( world, b3FindPairsTask, moveCount, minRange, world, "pairs" ); + + b3TracyCZoneNC( create_contacts, "Create Contacts", b3_colorCoral, 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 + if ( world->taskCount < B3_MAX_TASKS ) + { + world->userTreeTask = world->enqueueTaskFcn( &b3UpdateTreesTask, world, world->userTaskContext, "rebuild tree" ); + world->taskCount += 1; + world->activeTaskCount += world->userTreeTask == NULL ? 0 : 1; + } + else + { + world->userTreeTask = NULL; + b3UpdateTreesTask( world ); + } + + // Single-threaded work + // - Clear move flags + // - Create contacts in deterministic order + for ( int i = 0; i < moveCount; ++i ) + { + b3MoveResult* result = bp->moveResults + i; + b3MovePair* pair = result->pairList; + while ( pair != NULL ) + { + int shapeIdA = pair->shapeIndexA; + int shapeIdB = pair->shapeIndexB; + int childIndex = pair->childIndex; + + b3Shape* shapeA = b3Array_Get( world->shapes, shapeIdA ); + b3Shape* shapeB = b3Array_Get( world->shapes, shapeIdB ); + + b3CreateContact( world, shapeA, shapeB, childIndex ); + + if ( pair->heap ) + { + b3MovePair* temp = pair; + pair = pair->next; + b3Free( temp, sizeof( b3MovePair ) ); + } + else + { + pair = pair->next; + } + } + } + + // Reset move buffer + b3Array_Clear( bp->moveArray ); + b3ClearSet( &bp->moveSet ); + + b3StackFree( alloc, bp->movePairs ); + bp->movePairs = NULL; + b3StackFree( alloc, bp->moveResults ); + bp->moveResults = NULL; + + b3ValidateSolverSets( world ); + + b3TracyCZoneEnd( create_contacts ); + + b3TracyCZoneEnd( update_pairs ); +} + +bool b3BroadPhase_TestOverlap( const b3BroadPhase* bp, int proxyKeyA, int proxyKeyB ) +{ + int typeIndexA = B3_PROXY_TYPE( proxyKeyA ); + int proxyIdA = B3_PROXY_ID( proxyKeyA ); + int typeIndexB = B3_PROXY_TYPE( proxyKeyB ); + int proxyIdB = B3_PROXY_ID( proxyKeyB ); + + b3AABB aabbA = b3DynamicTree_GetAABB( bp->trees + typeIndexA, proxyIdA ); + b3AABB aabbB = b3DynamicTree_GetAABB( bp->trees + typeIndexB, proxyIdB ); + return b3AABB_Overlaps( aabbA, aabbB ); +} + +int b3BroadPhase_GetShapeIndex( b3BroadPhase* bp, int proxyKey ) +{ + int typeIndex = B3_PROXY_TYPE( proxyKey ); + int proxyId = B3_PROXY_ID( proxyKey ); + + return (int)b3DynamicTree_GetUserData( bp->trees + typeIndex, proxyId ); +} + +void b3ValidateBroadphase( const b3BroadPhase* bp ) +{ + b3DynamicTree_Validate( bp->trees + b3_dynamicBody ); + b3DynamicTree_Validate( bp->trees + b3_kinematicBody ); + + // todo validate every shape AABB is contained in tree AABB +} + +void b3ValidateNoEnlarged( const b3BroadPhase* bp ) +{ +#if B3_ENABLE_VALIDATION == 1 + for ( int j = 0; j < b3_bodyTypeCount; ++j ) + { + const b3DynamicTree* tree = bp->trees + j; + b3DynamicTree_ValidateNoEnlarged( tree ); + } +#else + B3_UNUSED( bp ); +#endif +} diff --git a/src/broad_phase.h b/src/broad_phase.h new file mode 100644 index 0000000..660d91f --- /dev/null +++ b/src/broad_phase.h @@ -0,0 +1,88 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "container.h" +#include "table.h" + +#include "box3d/collision.h" +#include "box3d/types.h" + +typedef struct b3Shape b3Shape; +typedef struct b3MovePair b3MovePair; +typedef struct b3MoveResult b3MoveResult; +typedef struct b3Stack b3Stack; +typedef struct b3World b3World; + +// Store the proxy type in the lower 2 bits of the proxy key. This leaves 30 bits for the id. +#define B3_PROXY_TYPE( KEY ) ( (b3BodyType)( ( KEY ) & 3 ) ) +#define B3_PROXY_ID( KEY ) ( ( KEY ) >> 2 ) +#define B3_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 b3BroadPhase +{ + b3DynamicTree trees[b3_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 + b3HashSet moveSet; + b3ArrayC( int ) 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 + b3MoveResult* moveResults; + b3MovePair* movePairs; + int movePairCapacity; + b3AtomicInt movePairIndex; + + // Tracks shape pairs that have a b3Contact + // todo pairSet can grow quite large on the first time step and remain large + b3HashSet pairSet; +} b3BroadPhase; + +#ifdef __cplusplus +extern "C" +{ +#endif + +void b3CreateBroadPhase( b3BroadPhase* bp, const b3Capacity* capacity ); +void b3DestroyBroadPhase( b3BroadPhase* bp ); + +int b3BroadPhase_CreateProxy( b3BroadPhase* bp, b3BodyType proxyType, b3AABB aabb, uint64_t categoryBits, int shapeIndex, + bool forcePairCreation ); +void b3BroadPhase_DestroyProxy( b3BroadPhase* bp, int proxyKey ); + +void b3BroadPhase_MoveProxy( b3BroadPhase* bp, int proxyKey, b3AABB aabb ); +void b3BroadPhase_EnlargeProxy( b3BroadPhase* bp, int proxyKey, b3AABB aabb ); + +int b3BroadPhase_GetShapeIndex( b3BroadPhase* bp, int proxyKey ); + +void b3UpdateBroadPhasePairs( b3World* world ); +bool b3BroadPhase_TestOverlap( const b3BroadPhase* bp, int proxyKeyA, int proxyKeyB ); + +void b3ValidateBroadphase( const b3BroadPhase* bp ); +void b3ValidateNoEnlarged( const b3BroadPhase* bp ); + +#ifdef __cplusplus +} +#endif + +// This is what triggers new contact pairs to be created +// Warning: this must be called in deterministic order +static inline void b3BufferMove( b3BroadPhase* bp, int queryProxy ) +{ + // Adding 1 because 0 is the sentinel + bool alreadyAdded = b3AddKey( &bp->moveSet, queryProxy + 1 ); + if ( alreadyAdded == false ) + { + b3Array_Push( bp->moveArray, queryProxy ); + } +} diff --git a/src/capsule.c b/src/capsule.c new file mode 100644 index 0000000..ea6c457 --- /dev/null +++ b/src/capsule.c @@ -0,0 +1,290 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "math_internal.h" +#include "shape.h" + +#include "box3d/base.h" +#include "box3d/collision.h" +#include "box3d/constants.h" + +b3MassData b3ComputeCapsuleMass( const b3Capsule* shape, float density ) +{ + b3Vec3 c1 = shape->center1; + b3Vec3 c2 = shape->center2; + float r = shape->radius; + + // Cylinder + float cylinderHeight = b3Distance( c1, c2 ); + float cylinderVolume = B3_PI * r * r * cylinderHeight; + float cylinderMass = cylinderVolume * density; + + // Sphere + float sphereVolume = ( 4.0f / 3.0f ) * B3_PI * r * r * r; + float sphereMass = sphereVolume * density; + + // Local accumulated inertia + b3Matrix3 inertia = b3AddMM( b3CylinderInertia( cylinderMass, r, cylinderHeight ), b3SphereInertia( sphereMass, r ) ); + + float steiner = 0.125f * sphereMass * ( 3.0f * r + 2.0f * cylinderHeight ) * cylinderHeight; + inertia.cx.x += steiner; + inertia.cz.z += steiner; + + // Align capsule axis with chosen up-axis + b3Matrix3 rotation = b3Mat3_identity; + if ( cylinderHeight * cylinderHeight > 1000.0f * FLT_MIN ) + { + b3Vec3 direction = b3Normalize( b3Sub( c2, c1 ) ); + b3Quat q = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisY, direction ); + rotation = b3MakeMatrixFromQuat( q ); + } + + // Parallel Axis Theorem capsule + float mass = sphereMass + cylinderMass; + b3Vec3 center = b3MulSV( 0.5f, b3Add( c1, c2 ) ); + + b3MassData out; + out.mass = mass; + out.center = center; + out.inertia = b3AddMM( b3MulMM( rotation, b3MulMM( inertia, b3Transpose( rotation ) ) ), b3Steiner( mass, center ) ); + + return out; +} + +b3AABB b3ComputeCapsuleAABB( const b3Capsule* shape, b3Transform transform ) +{ + float r = shape->radius; + + b3Vec3 center1 = b3TransformPoint( transform, shape->center1 ); + b3Vec3 center2 = b3TransformPoint( transform, shape->center2 ); + b3Vec3 extent = { r, r, r }; + + b3AABB aabb; + aabb.lowerBound = b3Sub( b3Min( center1, center2 ), extent ); + aabb.upperBound = b3Add( b3Max( center1, center2 ), extent ); + return aabb; +} + +b3AABB b3ComputeSweptCapsuleAABB( const b3Capsule* shape, b3Transform xf1, b3Transform xf2 ) +{ + b3Vec3 r = { shape->radius, shape->radius, shape->radius }; + b3Vec3 a = b3TransformPoint( xf1, shape->center1 ); + b3Vec3 b = b3TransformPoint( xf1, shape->center2 ); + b3Vec3 c = b3TransformPoint( xf2, shape->center1 ); + b3Vec3 d = b3TransformPoint( xf2, shape->center2 ); + + b3AABB aabb = { + .lowerBound = b3Sub( b3Min( b3Min( a, b ), b3Min( c, d ) ), r ), + .upperBound = b3Add( b3Max( b3Max( a, b ), b3Max( c, d ) ), r ), + }; + return aabb; +} + +static b3CastOutput b3CastRayAgainstCap( b3Vec3 p, b3Vec3 q, b3Vec3 c, float r, float maxFraction ) +{ + b3Sphere sphere = { c, r }; + b3RayCastInput input = { + .origin = p, + .translation = b3Sub( q, p ), + .maxFraction = maxFraction, + }; + + b3CastOutput output = b3RayCastSphere( &sphere, &input ); + return output; +} + +static b3CastOutput b3TransformCapsuleResult( b3CastOutput result, b3Quat rotation, b3Vec3 translation ) +{ + b3CastOutput out = result; + out.point = b3Add( b3RotateVector( rotation, result.point ), translation ); + out.normal = b3RotateVector( rotation, result.normal ); + return out; +} + +bool b3OverlapCapsule( const b3Capsule* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy ) +{ + b3DistanceInput input; + input.proxyA = (b3ShapeProxy){ &shape->center1, 2, shape->radius }; + input.proxyB = *proxy; + input.transformA = shapeTransform; + input.transformB = b3Transform_identity; + input.useRadii = true; + + b3SimplexCache cache = { 0 }; + b3DistanceOutput output = b3ShapeDistance( &input, &cache, NULL, 0 ); + return output.distance < B3_OVERLAP_SLOP; +} + +// todo_erin implement precision improvement +// Precision Improvements for Ray / Sphere Intersection - Ray Tracing Gems 2019 +// http://www.codercorner.com/blog/?p=321 +b3CastOutput b3RayCastCapsule( const b3Capsule* shape, const b3RayCastInput* input ) +{ + b3Vec3 c1 = shape->center1; + b3Vec3 c2 = shape->center2; + float r = shape->radius; + + // Initialize result structure + b3CastOutput output = { 0 }; + + // Compute height and handle degenerate capsules + float height = b3Distance( c1, c2 ); + if ( height < 1000.0f * FLT_MIN ) + { + b3Vec3 sphereCenter = b3MulSV( 0.5f, b3Add( shape->center1, shape->center2 ) ); + b3Sphere sphere = { sphereCenter, shape->radius }; + return b3RayCastSphere( &sphere, input ); + } + + // Transform ray and capsule into local space capsule space + b3Quat rotation = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisY, b3MulSV( 1.0f / height, b3Sub( c2, c1 ) ) ); + b3Vec3 offset = c1; + + // Capsule starts at the origin and is along the y-axis + b3Vec3 a = b3Vec3_zero; + b3Vec3 b = { 0.0f, height, 0.0f }; + b3Vec3 ab = b3Sub( b, a ); + + // Ray expressed relative to capsule space (capsule along y-axis) + b3Vec3 p = b3InvRotateVector( rotation, b3Sub( input->origin, offset ) ); + b3Vec3 q = b3Add( p, b3InvRotateVector( rotation, input->translation ) ); + b3Vec3 pq = b3Sub( q, p ); + + // Ray 2D translation length squared + float k1 = pq.x * pq.x + pq.z * pq.z; + + // Ray start point 2D separation squared from circle + float k3 = p.x * p.x + p.z * p.z - r * r; + + // Parallel case (2D ray translation is zero) + if ( k1 < 1000.0f * FLT_MIN ) + { + if ( k3 > 0.0f ) + { + // Parallel and outside + return output; + } + + if ( 0.0f <= p.y && p.y <= height ) + { + // Parallel and inside + output.hit = true; + output.point = input->origin; + return output; + } + + // Below cylinder and casting upwards + if ( p.y < 0.0f && pq.y > 0.0f ) + { + output = b3CastRayAgainstCap( p, q, a, r, input->maxFraction ); + return b3TransformCapsuleResult( output, rotation, offset ); + } + + // Above cylinder and casting downwards + if ( p.y > height && pq.y < 0.0f ) + { + output = b3CastRayAgainstCap( p, q, b, r, input->maxFraction ); + return b3TransformCapsuleResult( output, rotation, offset ); + } + + // Above or below and casting away from cylinder + return output; + } + + // Non-parallel case + float k2 = pq.x * p.x + pq.z * p.z; + + float discriminant = k2 * k2 - k1 * k3; + if ( discriminant < 0.0f ) + { + // No real roots - no intersection + return output; + } + + float t = ( -k2 - sqrtf( discriminant ) ) / k1; + if ( t > input->maxFraction ) + { + // Segment approaching cylinder, but not quite getting there. + return output; + } + + // Don't skip t < 0. This means that we start in the *infinite* cylinder and still might hit a cap + + // This is the point on the ray that hits the infinite cylinder + b3Vec3 c = b3MulAdd( p, t, pq ); + + // This is the cylinder hit point relative to the capsule base + b3Vec3 ac = b3Sub( c, a ); + + // Fraction of the cylinder hit point along the capsule axis + float s = b3Dot( ac, ab ) / ( height * height ); + + if ( s < 0.0f ) + { + // X projects outside A, run test through sphere at A + output = b3CastRayAgainstCap( p, q, a, r, input->maxFraction ); + return b3TransformCapsuleResult( output, rotation, offset ); + } + + if ( s > 1.0f ) + { + // X projects outside B, run test through sphere at B + output = b3CastRayAgainstCap( p, q, b, r, input->maxFraction ); + return b3TransformCapsuleResult( output, rotation, offset ); + } + + if ( t < 0.0f ) + { + // Ray starts inside + output.hit = true; + output.point = input->origin; + return output; + } + + // Ray hits cylinder inside segment AB + output.fraction = t; + output.point = c; + output.normal = b3Normalize( (b3Vec3){ c.x, 0.0f, c.z } ); + output.hit = true; + + return b3TransformCapsuleResult( output, rotation, offset ); +} + +b3CastOutput b3ShapeCastCapsule( const b3Capsule* capsule, const b3ShapeCastInput* input ) +{ + b3ShapeCastPairInput pairInput; + pairInput.proxyA = (b3ShapeProxy){ &capsule->center1, 2, capsule->radius }; + pairInput.proxyB = input->proxy; + pairInput.transformA = b3Transform_identity; + pairInput.transformB = b3Transform_identity; + pairInput.translationB = input->translation; + pairInput.maxFraction = input->maxFraction; + pairInput.canEncroach = input->canEncroach; + + b3CastOutput output = b3ShapeCast( &pairInput ); + return output; +} + +int b3CollideMoverAndCapsule( b3PlaneResult* result, const b3Capsule* shape, const b3Capsule* mover ) +{ + b3DistanceInput distanceInput; + distanceInput.proxyA = (b3ShapeProxy){ &shape->center1, 2, 0.0f }; + distanceInput.proxyB = (b3ShapeProxy){ &mover->center1, 2, mover->radius }; + distanceInput.transformA = b3Transform_identity; + distanceInput.transformB = b3Transform_identity; + distanceInput.useRadii = false; + + float totalRadius = mover->radius + shape->radius; + + b3SimplexCache cache = { 0 }; + b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, &cache, NULL, 0 ); + + if ( distanceOutput.distance <= totalRadius ) + { + b3Plane plane = { distanceOutput.normal, totalRadius - distanceOutput.distance }; + *result = (b3PlaneResult){ plane, distanceOutput.pointA }; + return 1; + } + + return 0; +} diff --git a/src/compound.c b/src/compound.c new file mode 100644 index 0000000..71c3f7f --- /dev/null +++ b/src/compound.c @@ -0,0 +1,1210 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "compound.h" + +#include "math_internal.h" +#include "shape.h" + +#include "box3d/base.h" +#include "box3d/collision.h" +#include "box3d/constants.h" +#include "box3d/types.h" + +#include +#include + +typedef struct b3SharedHull +{ + const b3Hull* hull; + int hullOffset; +} b3SharedHull; + +typedef struct b3SharedMesh +{ + const b3MeshData* meshData; + int meshOffset; +} b3SharedMesh; + +typedef struct b3HullInstance +{ + b3Transform transform; + uint32_t hullOffset; + uint32_t materialIndex; +} b3HullInstance; + +typedef struct b3MeshInstance +{ + b3Transform transform; + b3Vec3 scale; + uint32_t meshOffset; + uint32_t materialIndices[B3_MAX_COMPOUND_MESH_MATERIALS]; +} b3MeshInstance; + +static inline b3TreeNode* b3GetCompoundNodes( b3Compound* compound ) +{ + if ( compound->nodeOffset == 0 ) + { + return NULL; + } + + return (b3TreeNode*)( (intptr_t)compound + compound->nodeOffset ); +} + +const b3SurfaceMaterial* b3GetCompoundMaterials( const b3Compound* compound ) +{ + if ( compound->materialOffset == 0 ) + { + return NULL; + } + + return (b3SurfaceMaterial*)( (intptr_t)compound + compound->materialOffset ); +} + +b3CompoundCapsule b3GetCompoundCapsule( const b3Compound* compound, int index ) +{ + B3_ASSERT( 0 <= index && index < compound->capsuleCount && compound->capsuleOffset > 0 ); + + b3CompoundCapsule result = { 0 }; + if ( compound->capsuleOffset == 0 ) + { + return result; + } + + const b3CompoundCapsule* capsules = (const b3CompoundCapsule*)( (intptr_t)compound + compound->capsuleOffset ); + return capsules[index]; +} + +b3CompoundHull b3GetCompoundHull( const b3Compound* compound, int index ) +{ + B3_ASSERT( 0 <= index && index < compound->hullCount && compound->hullOffset > 0 ); + + b3CompoundHull result = { 0 }; + if ( compound->hullOffset == 0 ) + { + return result; + } + + const b3HullInstance* hullInstances = (const b3HullInstance*)( (intptr_t)compound + compound->hullOffset ); + uint32_t hullOffset = hullInstances[index].hullOffset; + B3_ASSERT( hullOffset >= compound->hullOffset + compound->hullCount * sizeof( b3HullInstance ) ); + result.hull = (const b3Hull*)( (intptr_t)compound + hullOffset ); + result.transform = hullInstances[index].transform; + result.materialIndex = hullInstances[index].materialIndex; + return result; +} + +b3CompoundMesh b3GetCompoundMesh( const b3Compound* compound, int index ) +{ + B3_ASSERT( 0 <= index && index < compound->meshCount && compound->meshOffset > 0 ); + + b3CompoundMesh result = { 0 }; + if ( compound->meshOffset == 0 ) + { + return result; + } + + const b3MeshInstance* meshInstances = (const b3MeshInstance*)( (intptr_t)compound + compound->meshOffset ); + uint32_t meshOffset = meshInstances[index].meshOffset; + B3_ASSERT( meshOffset >= compound->meshOffset + compound->meshCount * sizeof( b3HullInstance ) ); + result.meshData = (const b3MeshData*)( (intptr_t)compound + meshOffset ); + result.transform = meshInstances[index].transform; + result.scale = meshInstances[index].scale; + for ( int i = 0; i < B3_MAX_COMPOUND_MESH_MATERIALS; ++i ) + { + result.materialIndices[i] = meshInstances[index].materialIndices[i]; + } + return result; +} + +b3CompoundSphere b3GetCompoundSphere( const b3Compound* compound, int index ) +{ + B3_ASSERT( 0 <= index && index < compound->sphereCount && compound->sphereOffset > 0 ); + + b3CompoundSphere result = { 0 }; + if ( compound->sphereOffset == 0 ) + { + return result; + } + + const b3CompoundSphere* spheres = (const b3CompoundSphere*)( (intptr_t)compound + compound->sphereOffset ); + return spheres[index]; +} + +b3ChildShape b3GetCompoundChild( const b3Compound* compound, int childIndex ) +{ + // Capsule? + if ( 0 <= childIndex && childIndex < compound->capsuleCount ) + { + b3CompoundCapsule compoundCapsule = b3GetCompoundCapsule( compound, childIndex ); + return (b3ChildShape){ + .capsule = compoundCapsule.capsule, + .transform = b3Transform_identity, + .materialIndices = { compoundCapsule.materialIndex }, + .type = b3_capsuleShape, + }; + } + childIndex -= compound->capsuleCount; + + // Hull? + if ( 0 <= childIndex && childIndex < compound->hullCount ) + { + b3CompoundHull compoundHull = b3GetCompoundHull( compound, childIndex ); + return (b3ChildShape){ + .hull = compoundHull.hull, + .transform = compoundHull.transform, + .materialIndices = { compoundHull.materialIndex }, + .type = b3_hullShape, + }; + } + childIndex -= compound->hullCount; + + // Mesh? + if ( 0 <= childIndex && childIndex < compound->meshCount ) + { + b3CompoundMesh compoundMesh = b3GetCompoundMesh( compound, childIndex ); + const int* m = compoundMesh.materialIndices; + _Static_assert( B3_MAX_COMPOUND_MESH_MATERIALS == 4, "too many materials in compound mesh" ); + + return (b3ChildShape){ + .mesh = + { + .data = compoundMesh.meshData, + .scale = compoundMesh.scale, + }, + .transform = compoundMesh.transform, + .materialIndices = { m[0], m[1], m[2], m[3] }, + .type = b3_meshShape, + }; + } + childIndex -= compound->meshCount; + + B3_ASSERT( 0 <= childIndex && childIndex < compound->sphereCount ); + + // Sphere? + { + b3CompoundSphere compoundSphere = b3GetCompoundSphere( compound, childIndex ); + return (b3ChildShape){ + .sphere = compoundSphere.sphere, + .transform = b3Transform_identity, + .materialIndices = { compoundSphere.materialIndex }, + .type = b3_sphereShape, + }; + } +} + +static inline size_t vt_wyhash( const void* key, size_t len ); + +static inline uint64_t b3HashHull( const b3Hull* hull ) +{ + return vt_wyhash( hull, hull->byteCount ); +} + +static bool b3CompareHulls( const b3Hull* hull1, const b3Hull* hull2 ) +{ + if ( hull1 == hull2 ) + { + return true; + } + + if ( hull1->byteCount != hull2->byteCount ) + { + return false; + } + + int result = memcmp( hull1, hull2, hull1->byteCount ); + return result == 0; +} + +#define NAME b3HullMap +#define KEY_TY const b3Hull* +#define VAL_TY int +#define HASH_FN b3HashHull +#define CMPR_FN b3CompareHulls +#define MALLOC_FN b3Alloc +#define FREE_FN b3Free +#include "verstable.h" + +static inline uint64_t b3HashMesh( const b3MeshData* mesh ) +{ + return vt_wyhash( mesh, mesh->byteCount ); +} + +static bool b3CompareMeshes( const b3MeshData* mesh1, const b3MeshData* mesh2 ) +{ + if ( mesh1 == mesh2 ) + { + return true; + } + + if ( mesh1->byteCount != mesh2->byteCount ) + { + return false; + } + + int result = memcmp( mesh1, mesh2, mesh1->byteCount ); + return result == 0; +} + +#define NAME b3MeshMap +#define KEY_TY const b3MeshData* +#define VAL_TY int +#define HASH_FN b3HashMesh +#define CMPR_FN b3CompareMeshes +#define MALLOC_FN b3Alloc +#define FREE_FN b3Free +#include "verstable.h" + +static inline uint64_t b3HashMaterial( const b3SurfaceMaterial* material ) +{ + return vt_wyhash( material, sizeof( b3SurfaceMaterial ) ); +} + +static bool b3CompareMaterials( const b3SurfaceMaterial* mat1, const b3SurfaceMaterial* mat2 ) +{ + if ( mat1 == mat2 ) + { + return true; + } + + int result = memcmp( mat1, mat2, sizeof( b3SurfaceMaterial ) ); + return result == 0; +} + +#define NAME b3MaterialMap +#define KEY_TY const b3SurfaceMaterial* +#define VAL_TY int +#define HASH_FN b3HashMaterial +#define CMPR_FN b3CompareMaterials +#define MALLOC_FN b3Alloc +#define FREE_FN b3Free +#include "verstable.h" + +b3Compound* b3CreateCompound( const b3CompoundDef* def ) +{ + int convexCount = def->capsuleCount + def->hullCount + def->sphereCount; + int shapeCount = convexCount + def->meshCount; + + if ( shapeCount >= B3_MAX_CHILD_SHAPES ) + { + B3_ASSERT( false ); + return NULL; + } + + b3DynamicTree tree = b3DynamicTree_Create( shapeCount ); + + int childIndex = 0; + + // Instances + int capsuleCount = def->capsuleCount; + b3CompoundCapsule* capsuleInstances = b3AllocZeroed( capsuleCount * sizeof( b3CompoundCapsule ) ); + int hullCount = def->hullCount; + b3HullInstance* hullInstances = b3AllocZeroed( hullCount * sizeof( b3HullInstance ) ); + int meshCount = def->meshCount; + b3MeshInstance* meshInstances = b3AllocZeroed( meshCount * sizeof( b3MeshInstance ) ); + int sphereCount = def->sphereCount; + b3CompoundSphere* sphereInstances = b3AllocZeroed( sphereCount * sizeof( b3CompoundSphere ) ); + + // Determine material capacity + int materialCapacity = convexCount; + for ( int i = 0; i < def->meshCount; ++i ) + { + B3_ASSERT( def->meshes[i].materialCount > 0 ); + materialCapacity += def->meshes[i].materialCount; + } + + // Material map for convex material sharing. Mesh materials are not shared for simplicity. + b3MaterialMap materialMap; + b3MaterialMap_init( &materialMap ); + b3MaterialMap_reserve( &materialMap, materialCapacity ); + b3SurfaceMaterial* materials = b3AllocZeroed( materialCapacity * sizeof( b3SurfaceMaterial ) ); + int materialCount = 0; + + for ( int i = 0; i < def->capsuleCount; ++i ) + { + const b3CompoundCapsuleDef* capsuleDef = def->capsules + i; + capsuleInstances[i].capsule = capsuleDef->capsule; + + // Look for an existing material + b3MaterialMap_itr materialItr = b3MaterialMap_get_or_insert( &materialMap, &capsuleDef->material, materialCount ); + + // Get the shared material index + int materialIndex = materialItr.data->val; + capsuleInstances[i].materialIndex = materialIndex; + + // Is this a new material? + if ( materialIndex == materialCount ) + { + materials[materialIndex] = capsuleDef->material; + materialCount += 1; + } + + b3AABB aabb = b3ComputeCapsuleAABB( &capsuleDef->capsule, b3Transform_identity ); + b3DynamicTree_CreateProxy( &tree, aabb, ~0ull, childIndex ); + childIndex += 1; + } + + // Hulls + b3SharedHull* sharedHulls = b3AllocZeroed( hullCount * sizeof( b3SharedHull ) ); + int sharedHullCount = 0; + + if ( hullCount > 0 ) + { + b3HullMap hullMap; + b3HullMap_init( &hullMap ); + b3HullMap_reserve( &hullMap, hullCount ); + + for ( int i = 0; i < hullCount; ++i ) + { + const b3CompoundHullDef* hullDef = def->hulls + i; + const b3Hull* hull = hullDef->hull; + b3AABB aabb = b3ComputeHullAABB( hull, hullDef->transform ); + b3DynamicTree_CreateProxy( &tree, aabb, ~0ull, childIndex ); + childIndex += 1; + + // Look for an existing material + b3MaterialMap_itr materialItr = b3MaterialMap_get_or_insert( &materialMap, &hullDef->material, materialCount ); + + // Get the shared material index + int materialIndex = materialItr.data->val; + hullInstances[i].materialIndex = materialIndex; + + // Is this a new material? + if ( materialIndex == materialCount ) + { + materials[materialIndex] = hullDef->material; + materialCount += 1; + } + + hullInstances[i].transform = hullDef->transform; + + // Look for an existing matching hull + b3HullMap_itr itr = b3HullMap_get_or_insert( &hullMap, hull, sharedHullCount ); + + // Get the unique index for this hull + int sharedHullIndex = itr.data->val; + + // The offset isn't known yet, so store the index of the shared hull + hullInstances[i].hullOffset = sharedHullIndex; + + // Is this a new hull? + if ( sharedHullIndex == sharedHullCount ) + { + // Create a shared hull. The offset is determined below. + sharedHulls[sharedHullIndex].hull = hull; + sharedHulls[sharedHullIndex].hullOffset = B3_NULL_INDEX; + sharedHullCount += 1; + } + } + + b3HullMap_cleanup( &hullMap ); + } + + // Meshes + b3SharedMesh* sharedMeshes = b3AllocZeroed( meshCount * sizeof( b3SharedMesh ) ); + int sharedMeshCount = 0; + + if ( meshCount > 0 ) + { + b3MeshMap meshMap; + b3MeshMap_init( &meshMap ); + b3MeshMap_reserve( &meshMap, meshCount ); + + for ( int i = 0; i < meshCount; ++i ) + { + const b3CompoundMeshDef* meshDef = def->meshes + i; + + const b3MeshData* meshData = meshDef->meshData; + b3AABB aabb = b3ComputeMeshAABB( meshData, meshDef->transform, meshDef->scale ); + b3DynamicTree_CreateProxy( &tree, aabb, ~0ull, childIndex ); + childIndex += 1; + + // No effort to share mesh materials. It would be easier to do if the number of materials was limited. + B3_ASSERT( meshData->materialCount == meshDef->materialCount ); + + for ( int j = 0; j < meshDef->materialCount; ++j ) + { + // Look for an existing material + b3MaterialMap_itr materialItr = + b3MaterialMap_get_or_insert( &materialMap, &meshDef->materials[j], materialCount ); + + // Get the shared material index + int materialIndex = materialItr.data->val; + meshInstances[i].materialIndices[j] = materialIndex; + + // Is this a new material? + if ( materialIndex == materialCount ) + { + materials[materialIndex] = meshDef->materials[j]; + materialCount += 1; + } + } + + // Look for an existing matching mesh + b3MeshMap_itr itr = b3MeshMap_get_or_insert( &meshMap, meshData, sharedMeshCount ); + + // Get the shared mesh index + int sharedMeshIndex = itr.data->val; + + // Create mesh instance + meshInstances[i].transform = def->meshes[i].transform; + meshInstances[i].scale = def->meshes[i].scale; + + // The offset isn't known yet, so store the index of the shared mesh + meshInstances[i].meshOffset = sharedMeshIndex; + + // Is this a new mesh? + if ( sharedMeshIndex == sharedMeshCount ) + { + // Create a shared mesh. The offset is determined below. + sharedMeshes[sharedMeshIndex].meshData = meshData; + sharedMeshes[sharedMeshIndex].meshOffset = B3_NULL_INDEX; + sharedMeshCount += 1; + } + } + + b3MeshMap_cleanup( &meshMap ); + } + + // Spheres + for ( int i = 0; i < def->sphereCount; ++i ) + { + const b3CompoundSphereDef* sphereDef = def->spheres + i; + sphereInstances[i].sphere = sphereDef->sphere; + + // Look for an existing material + b3MaterialMap_itr materialItr = b3MaterialMap_get_or_insert( &materialMap, &sphereDef->material, materialCount ); + + // Get the shared material index + int materialIndex = materialItr.data->val; + sphereInstances[i].materialIndex = materialIndex; + + // Is this a new material? + if ( materialIndex == materialCount ) + { + materials[materialIndex] = sphereDef->material; + materialCount += 1; + } + + b3AABB aabb = b3ComputeSphereAABB( &sphereDef->sphere, b3Transform_identity ); + b3DynamicTree_CreateProxy( &tree, aabb, ~0ull, childIndex ); + childIndex += 1; + } + + B3_ASSERT( materialCount <= materialCapacity ); + B3_ASSERT( tree.nodeCount > 0 ); + + b3DynamicTree_Rebuild( &tree, true ); + + int byteCount = sizeof( b3Compound ); + + // Tree nodes - todo 64 byte alignment + int nodeOffset = byteCount; + byteCount += tree.nodeCapacity * sizeof( b3TreeNode ); + + int materialOffset = byteCount; + byteCount += materialCount * sizeof( b3SurfaceMaterial ); + + int capsuleOffset = byteCount; + byteCount += def->capsuleCount * sizeof( b3CompoundCapsule ); + + // Hull data layout has another level of indirection to allow for tight data packing + // 1. hull instance array : hull count array of b3HullInstance with individual hull transforms and offsets + // 2. heterogeneous array of shared hull data : each shared hull can have a different byte count, so direct indexing is not + // possible + int hullArrayOffset = byteCount; + + // Array of hull instances + byteCount += hullCount * sizeof( b3HullInstance ); + + // Packed shared hull blobs + for ( int i = 0; i < sharedHullCount; ++i ) + { + sharedHulls[i].hullOffset = byteCount; + byteCount += sharedHulls[i].hull->byteCount; + } + + // Mesh data layout has another level of indirection to allow for tight data packing + // 1. mesh instance array : mesh count array of b3MeshInstance with individual mesh transform, scale, and offset + // 2. heterogeneous array of shared mesh data : each shared mesh can have a different byte count, so direct indexing is not + // possible + int meshArrayOffset = byteCount; + + // Array of mesh instances + byteCount += meshCount * sizeof( b3MeshInstance ); + + // Packed shared mesh blobs + for ( int i = 0; i < sharedMeshCount; ++i ) + { + sharedMeshes[i].meshOffset = byteCount; + byteCount += sharedMeshes[i].meshData->byteCount; + } + + int sphereOffset = byteCount; + byteCount += def->sphereCount * sizeof( b3CompoundSphere ); + + b3Compound* compound = b3Alloc( byteCount ); + memset( compound, 0, byteCount ); + + compound->version = B3_COMPOUND_VERSION; + compound->byteCount = byteCount; + compound->nodeOffset = nodeOffset; + memcpy( &compound->tree, &tree, sizeof( b3DynamicTree ) ); + + // todo clean up this mess + compound->tree.freeList = 0; + compound->tree.leafIndices = NULL; + compound->tree.leafBoxes = NULL; + compound->tree.leafCenters = NULL; + compound->tree.binIndices = NULL; + compound->tree.rebuildCapacity = 0; + + compound->tree.nodes = NULL; + compound->materialOffset = materialOffset; + compound->materialCount = materialCount; + compound->capsuleOffset = capsuleOffset; + compound->capsuleCount = capsuleCount; + compound->hullOffset = hullArrayOffset; + compound->hullCount = hullCount; + compound->meshOffset = meshArrayOffset; + compound->meshCount = meshCount; + compound->sphereOffset = sphereOffset; + compound->sphereCount = sphereCount; + + // Tree nodes + b3TreeNode* nodes = b3GetCompoundNodes( compound ); + memcpy( nodes, tree.nodes, tree.nodeCapacity * sizeof( b3TreeNode ) ); + compound->tree.nodes = nodes; + + // Materials + B3_ASSERT( materialCount > 0 ); + b3SurfaceMaterial* destinationMaterials = (b3SurfaceMaterial*)( (intptr_t)compound + compound->materialOffset ); + if ( materials != NULL ) + { + memcpy( destinationMaterials, materials, materialCount * sizeof( b3SurfaceMaterial ) ); + } + + // Capsules + if ( def->capsuleCount > 0 ) + { + B3_ASSERT( compound->capsuleOffset > 0 ); + b3CompoundCapsule* capsules = (b3CompoundCapsule*)( (intptr_t)compound + compound->capsuleOffset ); + memcpy( capsules, capsuleInstances, capsuleCount * sizeof( b3CompoundCapsule ) ); + } + + // Hulls + for ( int i = 0; i < hullCount; ++i ) + { + // Fix up offsets + int sharedIndex = hullInstances[i].hullOffset; + B3_ASSERT( 0 <= sharedIndex && sharedIndex < sharedHullCount ); + hullInstances[i].hullOffset = sharedHulls[sharedIndex].hullOffset; + } + + b3HullInstance* destinationHullInstances = (b3HullInstance*)( (intptr_t)compound + hullArrayOffset ); + memcpy( destinationHullInstances, hullInstances, hullCount * sizeof( b3HullInstance ) ); + + for ( int i = 0; i < sharedHullCount; ++i ) + { + int offset = sharedHulls[i].hullOffset; + b3Hull* destinationHull = (b3Hull*)( (intptr_t)compound + offset ); + memcpy( destinationHull, sharedHulls[i].hull, sharedHulls[i].hull->byteCount ); + } + + compound->sharedHullCount = sharedHullCount; + + // Meshes + for ( int i = 0; i < meshCount; ++i ) + { + // Fix up offsets + int sharedIndex = meshInstances[i].meshOffset; + B3_ASSERT( 0 <= sharedIndex && sharedIndex < sharedMeshCount ); + meshInstances[i].meshOffset = sharedMeshes[sharedIndex].meshOffset; + } + + b3MeshInstance* destinationMeshInstances = (b3MeshInstance*)( (intptr_t)compound + meshArrayOffset ); + memcpy( destinationMeshInstances, meshInstances, meshCount * sizeof( b3MeshInstance ) ); + + for ( int i = 0; i < sharedMeshCount; ++i ) + { + int offset = sharedMeshes[i].meshOffset; + b3MeshData* destinationMesh = (b3MeshData*)( (intptr_t)compound + offset ); + memcpy( destinationMesh, sharedMeshes[i].meshData, sharedMeshes[i].meshData->byteCount ); + } + + compound->sharedMeshCount = sharedMeshCount; + + // Spheres + if ( def->sphereCount > 0 ) + { + B3_ASSERT( compound->sphereOffset > 0 ); + b3CompoundSphere* spheres = (b3CompoundSphere*)( (intptr_t)compound + compound->sphereOffset ); + memcpy( spheres, sphereInstances, sphereCount * sizeof( b3CompoundSphere ) ); + } + + b3MaterialMap_cleanup( &materialMap ); + b3Free( sharedHulls, hullCount * sizeof( b3SharedHull ) ); + b3Free( sharedMeshes, meshCount * sizeof( b3SharedMesh ) ); + b3Free( capsuleInstances, capsuleCount * sizeof( b3CompoundCapsule ) ); + b3Free( hullInstances, hullCount * sizeof( b3HullInstance ) ); + b3Free( meshInstances, meshCount * sizeof( b3MeshInstance ) ); + b3Free( sphereInstances, sphereCount * sizeof( b3CompoundSphere ) ); + b3Free( materials, materialCapacity * sizeof( b3SurfaceMaterial ) ); + b3DynamicTree_Destroy( &tree ); + + return compound; +} + +void b3DestroyCompound( b3Compound* compound ) +{ + b3Free( compound, compound->byteCount ); +} + +uint8_t* b3ConvertCompoundToBytes( b3Compound* compound ) +{ + // scrub this pointer before serialization + compound->tree.nodes = NULL; + return (uint8_t*)compound; +} + +b3Compound* b3ConvertBytesToCompound( uint8_t* bytes, int byteCount ) +{ + b3Compound* compound = (b3Compound*)bytes; + if ( compound->version != B3_COMPOUND_VERSION ) + { + return NULL; + } + + if ( compound->byteCount < (int)sizeof( b3Compound ) ) + { + return NULL; + } + + if ( byteCount != compound->byteCount ) + { + return NULL; + } + + if ( compound->nodeOffset <= 0 ) + { + return NULL; + } + + // this mutates the input bytes + compound->tree.nodes = (b3TreeNode*)( (intptr_t)compound + compound->nodeOffset ); + return compound; +} + +b3AABB b3ComputeCompoundAABB( const b3Compound* shape, b3Transform transform ) +{ + B3_ASSERT( shape->nodeOffset > 0 ); + + const b3TreeNode* nodes = (const b3TreeNode*)( (intptr_t)shape + shape->nodeOffset ); + int root = shape->tree.root; + b3AABB aabb = nodes[root].aabb; + return b3AABB_Transform( transform, aabb ); +} + +struct b3CompoundOverlapContext +{ + const b3Compound* compound; + // transform of the compound + b3Transform transform; + b3ShapeProxy proxy; + bool overlap; +}; + +static bool b3CompoundOverlapCallback( int proxyId, uint64_t userData, void* context ) +{ + B3_UNUSED( proxyId ); + + int childIndex = (int)userData; + struct b3CompoundOverlapContext* overlapContext = context; + b3ChildShape child = b3GetCompoundChild( overlapContext->compound, childIndex ); + + b3Transform transform = b3MulTransforms( overlapContext->transform, child.transform ); + + bool overlap = false; + switch ( child.type ) + { + case b3_capsuleShape: + overlap = b3OverlapCapsule( &child.capsule, transform, &overlapContext->proxy ); + break; + + case b3_hullShape: + overlap = b3OverlapHull( child.hull, transform, &overlapContext->proxy ); + break; + + case b3_meshShape: + overlap = b3OverlapMesh( &child.mesh, transform, &overlapContext->proxy ); + break; + + case b3_sphereShape: + overlap = b3OverlapSphere( &child.sphere, transform, &overlapContext->proxy ); + break; + + default: + B3_ASSERT( false ); + break; + } + + if ( overlap ) + { + // Done + overlapContext->overlap = true; + return false; + } + + // Continue the query if there is no overlap + return true; +} + +bool b3OverlapCompound( const b3Compound* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy ) +{ + struct b3CompoundOverlapContext context = { + .compound = shape, + .transform = shapeTransform, + .proxy = *proxy, + .overlap = false, + }; + + b3AABB aabb = { proxy->points[0], proxy->points[0] }; + for ( int i = 1; i < proxy->count; ++i ) + { + aabb.lowerBound = b3Min( aabb.lowerBound, proxy->points[i] ); + aabb.upperBound = b3Max( aabb.upperBound, proxy->points[i] ); + } + + b3Vec3 r = { proxy->radius, proxy->radius, proxy->radius }; + aabb.lowerBound = b3Sub( aabb.lowerBound, r ); + aabb.upperBound = b3Add( aabb.upperBound, r ); + + (void)b3DynamicTree_Query( &shape->tree, aabb, ~0ull, false, b3CompoundOverlapCallback, &context ); + + return context.overlap; +} + +struct b3CompoundCastContext +{ + const b3Compound* compound; + b3CastOutput* output; +}; + +static float b3CompoundRayCastCallback( const b3RayCastInput* input, int proxyId, uint64_t userData, void* context ) +{ + B3_UNUSED( proxyId ); + + struct b3CompoundCastContext* castContext = context; + const b3Compound* compound = castContext->compound; + + int childIndex = (int)userData; + + b3ChildShape child = b3GetCompoundChild( compound, childIndex ); + + b3RayCastInput localInput = *input; + localInput.origin = b3InvTransformPoint( child.transform, input->origin ); + localInput.translation = b3InvRotateVector( child.transform.q, input->translation ); + + b3CastOutput output = { 0 }; + + switch ( child.type ) + { + case b3_capsuleShape: + output = b3RayCastCapsule( &child.capsule, &localInput ); + output.materialIndex = child.materialIndices[0]; + break; + + case b3_hullShape: + output = b3RayCastHull( child.hull, &localInput ); + output.materialIndex = child.materialIndices[0]; + break; + + case b3_meshShape: + { + output = b3RayCastMesh( &child.mesh, &localInput ); + B3_ASSERT( 0 <= output.materialIndex ); + int childMaterialIndex = b3MinInt( output.materialIndex, B3_MAX_COMPOUND_MESH_MATERIALS - 1 ); + output.materialIndex = child.materialIndices[childMaterialIndex]; + } + break; + + case b3_sphereShape: + output = b3RayCastSphere( &child.sphere, &localInput ); + output.materialIndex = child.materialIndices[0]; + break; + + default: + B3_ASSERT( false ); + break; + } + + if ( output.hit ) + { + output.point = b3TransformPoint( child.transform, output.point ); + output.normal = b3RotateVector( child.transform.q, output.normal ); + output.childIndex = childIndex; + *castContext->output = output; + return output.fraction; + } + + return input->maxFraction; +} + +b3CastOutput b3RayCastCompound( const b3Compound* shape, const b3RayCastInput* input ) +{ + b3CastOutput result = { 0 }; + + struct b3CompoundCastContext context = { + .compound = shape, + .output = &result, + }; + (void)b3DynamicTree_RayCast( &shape->tree, input, ~0ull, false, b3CompoundRayCastCallback, &context ); + return result; +} + +static float b3CompoundShapeCastCallback( const b3ShapeCastInput* input, int proxyId, uint64_t userData, void* context ) +{ + B3_UNUSED( proxyId ); + + struct b3CompoundCastContext* castContext = context; + const b3Compound* compound = castContext->compound; + + int childIndex = (int)userData; + + b3ChildShape child = b3GetCompoundChild( compound, childIndex ); + + b3ShapeCastInput localInput = *input; + b3Vec3 localPoints[B3_MAX_SHAPE_CAST_POINTS]; + + localInput.proxy.count = b3MinInt( input->proxy.count, B3_MAX_SHAPE_CAST_POINTS ); + + b3Transform invTransform = b3InvertTransform( child.transform ); + b3Matrix3 R = b3MakeMatrixFromQuat( invTransform.q ); + + for ( int i = 0; i < localInput.proxy.count; ++i ) + { + localPoints[i] = b3Add( b3MulMV( R, input->proxy.points[i] ), invTransform.p ); + } + + localInput.proxy.points = localPoints; + localInput.translation = b3MulMV( R, input->translation ); + + b3CastOutput output = { 0 }; + + switch ( child.type ) + { + case b3_capsuleShape: + output = b3ShapeCastCapsule( &child.capsule, &localInput ); + output.materialIndex = child.materialIndices[0]; + break; + + case b3_hullShape: + output = b3ShapeCastHull( child.hull, &localInput ); + output.materialIndex = child.materialIndices[0]; + break; + + case b3_meshShape: + { + output = b3ShapeCastMesh( &child.mesh, &localInput ); + B3_ASSERT( 0 <= output.materialIndex ); + int childMaterialIndex = b3MinInt( output.materialIndex, B3_MAX_COMPOUND_MESH_MATERIALS - 1 ); + output.materialIndex = child.materialIndices[childMaterialIndex]; + } + break; + + case b3_sphereShape: + output = b3ShapeCastSphere( &child.sphere, &localInput ); + output.materialIndex = child.materialIndices[0]; + break; + + default: + B3_ASSERT( false ); + break; + } + + if ( output.hit ) + { + output.point = b3TransformPoint( child.transform, output.point ); + output.normal = b3RotateVector( child.transform.q, output.normal ); + output.childIndex = childIndex; + *castContext->output = output; + return output.fraction; + } + + return input->maxFraction; +} + +b3CastOutput b3ShapeCastCompound( const b3Compound* shape, const b3ShapeCastInput* input ) +{ + b3CastOutput result = { 0 }; + + struct b3CompoundCastContext context = { + .compound = shape, + .output = &result, + }; + (void)b3DynamicTree_ShapeCast( &shape->tree, input, ~0ull, false, b3CompoundShapeCastCallback, &context ); + return result; +} + +struct b3CompoundQueryContext +{ + const b3Compound* compound; + b3CompoundQueryFcn* fcn; + void* userContext; +}; + +static bool TreeQueryCallbackFcn( int proxyId, uint64_t userData, void* treeContext ) +{ + B3_UNUSED( proxyId ); + struct b3CompoundQueryContext* context = treeContext; + return context->fcn( context->compound, (int)userData, context->userContext ); +} + +void b3QueryCompound( const b3Compound* compound, b3AABB aabb, b3CompoundQueryFcn* fcn, void* context ) +{ + struct b3CompoundQueryContext compoundContext = { + .compound = compound, + .fcn = fcn, + .userContext = context, + }; + + b3DynamicTree_Query( &compound->tree, aabb, B3_DEFAULT_MASK_BITS, false, TreeQueryCallbackFcn, &compoundContext ); +} + +#if 0 +struct b3CompoundImpactContext +{ + b3TOIInput toiInput; + b3TOIOutput toiOutput; + b3Transform compoundTransform; + + // Bounds local to compound + b3AABB localSweepBoundsB; + + // Centroid of shape in body B local space + b3Vec3 localCentroidB; + float fallbackRadius; +}; + +static bool b3CompoundTimeOfImpactFcn( const b3Compound* compound, int childIndex, void* context ) +{ + b3CompoundImpactContext* toiContext = (b3CompoundImpactContext*)context; + + b3ChildShape child = b3GetCompoundChild( compound, childIndex ); + + b3TOIOutput output = {0 }; + toiContext->toiInput.sweepA = b3MakeCompoundChildSweep( toiContext->compoundTransform, child.transform ); + + switch ( child.type ) + { + case b3_capsuleShape: + { + toiContext->toiInput.proxyA.points = &child.capsule.center1; + toiContext->toiInput.proxyA.count = 2; + toiContext->toiInput.proxyA.radius = child.capsule.radius; + output = b3TimeOfImpact( &toiContext->toiInput ); + } + break; + + case b3_hullShape: + { + toiContext->toiInput.proxyA.points = b3GetHullPoints( child.hull ); + toiContext->toiInput.proxyA.count = child.hull->vertexCount; + toiContext->toiInput.proxyA.radius = 0.0f; + output = b3TimeOfImpact( &toiContext->toiInput ); + } + break; + + case b3_meshShape: + { + b3MeshImpactContext meshContext = {0}; + meshContext.toiInput = toiContext->toiInput; + meshContext.isSensor = false; + meshContext.localCentroidB = toiContext->localCentroidB; + meshContext.fallbackRadius = toiContext->fallbackRadius; + + b3Transform meshWorldTransform = b3MulTransforms( toiContext->compoundTransform, child.transform ); + + const b3Sweep* sweepB = &toiContext->toiInput.sweepB; + b3Transform xfB1 = { + .p = sweepB->c1 - b3RotateVector( sweepB->q1, sweepB->localCenter ), + .q = sweepB->q1, + }; + + b3Transform xfB2 = { + .p = sweepB->c2 - b3RotateVector( sweepB->q2, sweepB->localCenter ), + .q = sweepB->q2, + }; + + meshContext.meshLocalCentroidB1 = + b3InvTransformPoint( meshWorldTransform, b3TransformPoint( xfB1, meshContext.localCentroidB ) ); + meshContext.meshLocalCentroidB2 = + b3InvTransformPoint( meshWorldTransform, b3TransformPoint( xfB2, meshContext.localCentroidB ) ); + + // Bounds local to mesh + b3AABB localBounds = b3AABB_Transform( b3InvertTransform( child.transform ), toiContext->localSweepBoundsB ); + + b3QueryMesh( &child.mesh, localBounds, b3MeshTimeOfImpactFcn, &meshContext ); + + output = meshContext.toiOutput; + } + break; + + case b3_sphereShape: + { + toiContext->toiInput.proxyA.points = &child.sphere.center; + toiContext->toiInput.proxyA.count = 1; + toiContext->toiInput.proxyA.radius = child.sphere.radius; + output = b3TimeOfImpact( &toiContext->toiInput ); + } + break; + + default: + B3_ASSERT( false ); + break; + } + + if ( 0.0f < output.fraction && output.fraction < toiContext->toiInput.maxFraction ) + { + toiContext->toiOutput = output; + toiContext->toiInput.maxFraction = output.fraction; + } + + // Clear this to be safe + toiContext->toiInput.proxyA = {0}; + + // Continue the query + return true; +} + +b3TOIOutput b3CompoundTimeOfImpact(const b3Compound* compound, b3Transform transform, const b3ShapeProxy* proxy, + const b3Sweep* sweep, float maxFraction) +{ + b3CompoundImpactContext context = {0}; + context.toiInput.proxyB = b3MakeShapeProxy( shapeB ); + context.toiInput.sweepB = *sweepB; + context.toiInput.maxFraction = maxFraction; + + context.compoundTransform = { + .p = sweepA->c1, + .q = sweepA->q1, + }; + + b3Vec3 localCentroidB = b3GetShapeCentroid( shapeB ); + context.localCentroidB = localCentroidB; + + b3ShapeExtent extents = b3ComputeShapeExtent( shapeB, context.localCentroidB ); + context.fallbackRadius = b3MaxFloat( 0.5f * extents.minExtent, B3_SPECULATIVE_DISTANCE ); + + // Swept bounds of shapeB + b3AABB aabb = b3ComputeSweptShapeAABB( shapeB, sweepB, maxFraction ); + + // Bounds local to mesh + b3AABB localBounds = b3AABB_Transform( b3InvertTransform( context.compoundTransform ), bounds ); + context.localSweepBoundsB = localBounds; + + b3DynamicTree_Query( &compound->tree, aabb, B3_DEFAULT_MASK_BITS, false, TreeQueryCallbackFcn, &compoundContext ); + + return context.toiOutput; +} +#endif + +// xf = xfP * xfC +b3Sweep b3MakeCompoundChildSweep( b3Transform compoundTransform, b3Transform childTransform ) +{ + b3Transform xf = b3MulTransforms( compoundTransform, childTransform ); + return (b3Sweep){ + .localCenter = b3Vec3_zero, + .c1 = xf.p, + .c2 = xf.p, + .q1 = xf.q, + .q2 = xf.q, + }; +} + +struct b3CompoundMoverContext +{ + const b3Compound* compound; + b3PlaneResult* planes; + int planeCapacity; + int planeCount; + b3Capsule mover; +}; + +static bool b3CompoundMoverCallback( int proxyId, uint64_t userData, void* context ) +{ + B3_UNUSED( proxyId ); + + int childIndex = (int)userData; + struct b3CompoundMoverContext* moverContext = context; + b3ChildShape child = b3GetCompoundChild( moverContext->compound, childIndex ); + + // Transform mover to child space + b3Capsule localMover; + localMover.center1 = b3InvTransformPoint( child.transform, moverContext->mover.center1 ); + localMover.center2 = b3InvTransformPoint( child.transform, moverContext->mover.center2 ); + localMover.radius = moverContext->mover.radius; + + int capacity = moverContext->planeCapacity - moverContext->planeCount; + B3_ASSERT( capacity > 0 ); + + b3PlaneResult* planes = moverContext->planes + moverContext->planeCount; + int planeCount = 0; + + switch ( child.type ) + { + case b3_capsuleShape: + planeCount = b3CollideMoverAndCapsule( planes, &child.capsule, &localMover ); + break; + + case b3_hullShape: + planeCount = b3CollideMoverAndHull( planes, child.hull, &localMover ); + break; + + case b3_meshShape: + planeCount = b3CollideMoverAndMesh( planes, capacity, &child.mesh, &localMover ); + break; + + case b3_sphereShape: + planeCount = b3CollideMoverAndSphere( planes, &child.sphere, &localMover ); + break; + + default: + B3_ASSERT( false ); + break; + } + + // Transform results back to shape space + for ( int i = 0; i < planeCount; ++i ) + { + planes[i].plane.normal = b3RotateVector( child.transform.q, planes[i].plane.normal ); + planes[i].point = b3TransformPoint( child.transform, planes[i].point ); + } + + moverContext->planeCount += planeCount; + + // Continue query while there is room for more planes + return moverContext->planeCount < moverContext->planeCapacity; +} + +int b3CollideMoverAndCompound( b3PlaneResult* planes, int capacity, const b3Compound* shape, const b3Capsule* mover ) +{ + struct b3CompoundMoverContext context = { + .compound = shape, + .planes = planes, + .planeCapacity = capacity, + .planeCount = 0, + .mover = *mover, + }; + + b3AABB aabb; + aabb.lowerBound = b3Min( mover->center1, mover->center2 ); + aabb.upperBound = b3Max( mover->center1, mover->center2 ); + b3Vec3 r = { mover->radius, mover->radius, mover->radius }; + aabb.lowerBound = b3Sub( aabb.lowerBound, r ); + aabb.upperBound = b3Add( aabb.upperBound, r ); + + (void)b3DynamicTree_Query( &shape->tree, aabb, ~0ull, false, b3CompoundMoverCallback, &context ); + + return context.planeCount; +} diff --git a/src/compound.h b/src/compound.h new file mode 100644 index 0000000..237556c --- /dev/null +++ b/src/compound.h @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "box3d/types.h" + +typedef struct b3ChildShape +{ + union + { + b3Capsule capsule; + const b3Hull* hull; + b3Mesh mesh; + b3Sphere sphere; + }; + + b3Transform transform; + + // Index 0 is used for convex shapes. + // todo limit to 64K? + int materialIndices[B3_MAX_COMPOUND_MESH_MATERIALS]; + b3ShapeType type; +} b3ChildShape; + +typedef bool b3CompoundQueryFcn( const b3Compound* compound, int childIndex, void* context ); + +#ifdef __cplusplus +extern "C" +{ +#endif + +b3ChildShape b3GetCompoundChild( const b3Compound* compound, int childIndex ); +void b3QueryCompound( const b3Compound* compound, b3AABB aabb, b3CompoundQueryFcn* fcn, void* context ); + +b3TOIOutput b3CompoundTimeOfImpact( const b3Compound* compound, b3Transform transform, const b3ShapeProxy* proxy, + const b3Sweep* sweep, float maxFraction ); + +// Transforms a sweep for a compound child shape +b3Sweep b3MakeCompoundChildSweep( b3Transform compoundTransform, b3Transform childTransform ); + +int b3CollideMoverAndCompound( b3PlaneResult* planes, int capacity, const b3Compound* shape, const b3Capsule* mover ); + +#ifdef __cplusplus +} +#endif diff --git a/src/constraint_graph.c b/src/constraint_graph.c new file mode 100644 index 0000000..9f06e9e --- /dev/null +++ b/src/constraint_graph.c @@ -0,0 +1,328 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "constraint_graph.h" + +#include "bitset.h" +#include "body.h" +#include "contact.h" +#include "joint.h" +#include "physics_world.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. + +// This is used for debugging by making all constraints be assigned to overflow. +#define B3_FORCE_OVERFLOW 0 + +static const b3HexColor b3_graphColors[B3_GRAPH_COLOR_COUNT] = { + b3_colorRed, b3_colorOrange, b3_colorYellow, b3_colorLimeGreen, b3_colorSpringGreen, + b3_colorAqua, b3_colorDodgerBlue, b3_colorBlueViolet, b3_colorMagenta, b3_colorDeepPink, + b3_colorCrimson, b3_colorCoral, b3_colorGold, b3_colorGreenYellow, b3_colorMediumSeaGreen, + b3_colorTurquoise, b3_colorDeepSkyBlue, b3_colorCornflowerBlue, b3_colorMediumSlateBlue, b3_colorMediumOrchid, + b3_colorHotPink, b3_colorTomato, b3_colorKhaki, b3_colorSilver, +}; + +b3HexColor b3GetGraphColor( int index ) +{ + B3_ASSERT( 0 <= index && index < B3_GRAPH_COLOR_COUNT ); + return b3_graphColors[index]; +} + +void b3CreateGraph( b3ConstraintGraph* graph, int bodyCapacity ) +{ + _Static_assert( B3_GRAPH_COLOR_COUNT >= 2, "must have at least two constraint graph colors" ); + _Static_assert( B3_OVERFLOW_INDEX == B3_GRAPH_COLOR_COUNT - 1, "bad over flow index" ); + + *graph = (b3ConstraintGraph){ 0 }; + + bodyCapacity = b3MaxInt( bodyCapacity, 8 ); + + // Initialize graph color bit set. + // No bitset for overflow color. + for ( int i = 0; i < B3_OVERFLOW_INDEX; ++i ) + { + b3GraphColor* color = graph->colors + i; + color->bodySet = b3CreateBitSet( bodyCapacity ); + b3SetBitCountAndClear( &color->bodySet, bodyCapacity ); + } +} + +void b3DestroyGraph( b3ConstraintGraph* graph ) +{ + for ( int i = 0; i < B3_GRAPH_COLOR_COUNT; ++i ) + { + b3GraphColor* color = graph->colors + i; + + // The bit set should never be used on the overflow color + B3_ASSERT( i != B3_OVERFLOW_INDEX || color->bodySet.bits == NULL ); + + b3DestroyBitSet( &color->bodySet ); + + b3Array_Destroy( color->convexContacts ); + b3Array_Destroy( color->contacts ); + b3Array_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 b3AddContactToGraph( b3World* world, b3Contact* contact ) +{ + B3_ASSERT( contact->manifoldCount > 0 ); + B3_ASSERT( contact->flags & b3_contactTouchingFlag ); + + b3ConstraintGraph* graph = &world->constraintGraph; + int colorIndex = B3_OVERFLOW_INDEX; + + int bodyIdA = contact->edges[0].bodyId; + int bodyIdB = contact->edges[1].bodyId; + b3Body* bodyA = b3Array_Get( world->bodies, bodyIdA ); + b3Body* bodyB = b3Array_Get( world->bodies, bodyIdB ); + + b3BodyType typeA = bodyA->type; + b3BodyType typeB = bodyB->type; + B3_ASSERT( typeA == b3_dynamicBody || typeB == b3_dynamicBody ); + +#if B3_FORCE_OVERFLOW == 0 + if ( typeA == b3_dynamicBody && typeB == b3_dynamicBody ) + { + // Dynamic constraint colors cannot encroach on colors reserved for static constraints + for ( int i = 0; i < B3_DYNAMIC_COLOR_COUNT; ++i ) + { + b3GraphColor* color = graph->colors + i; + if ( b3GetBit( &color->bodySet, bodyIdA ) || b3GetBit( &color->bodySet, bodyIdB ) ) + { + continue; + } + + b3SetBitGrow( &color->bodySet, bodyIdA ); + b3SetBitGrow( &color->bodySet, bodyIdB ); + colorIndex = i; + break; + } + } + else if ( typeA == b3_dynamicBody ) + { + // Static constraint colors build from the end to get higher priority than dyn-dyn constraints + for ( int i = B3_OVERFLOW_INDEX - 1; i >= 1; --i ) + { + b3GraphColor* color = graph->colors + i; + if ( b3GetBit( &color->bodySet, bodyIdA ) ) + { + continue; + } + + b3SetBitGrow( &color->bodySet, bodyIdA ); + colorIndex = i; + break; + } + } + else if ( typeB == b3_dynamicBody ) + { + // Static constraint colors build from the end to get higher priority than dyn-dyn constraints + for ( int i = B3_OVERFLOW_INDEX - 1; i >= 1; --i ) + { + b3GraphColor* color = graph->colors + i; + if ( b3GetBit( &color->bodySet, bodyIdB ) ) + { + continue; + } + + b3SetBitGrow( &color->bodySet, bodyIdB ); + colorIndex = i; + break; + } + } +#endif + + bool isScalar = ( contact->flags & b3_simMeshContact ) || colorIndex == B3_OVERFLOW_INDEX; + + b3GraphColor* color = graph->colors + colorIndex; + contact->colorIndex = colorIndex; + contact->localIndex = isScalar ? color->contacts.count : color->convexContacts.count; + contact->bodySimIndexA = bodyA->type == b3_staticBody ? B3_NULL_INDEX : bodyA->localIndex; + contact->bodySimIndexB = bodyB->type == b3_staticBody ? B3_NULL_INDEX : bodyB->localIndex; + + if ( isScalar ) + { + B3_ASSERT( contact->manifoldCount < UINT16_MAX ); + b3ContactSpec spec = { + .contactId = contact->contactId, + .manifoldStart = 0, + .manifoldCount = (uint16_t)contact->manifoldCount, + }; + b3Array_Push( color->contacts, spec ); + } + else + { + b3Array_Push( color->convexContacts, contact->contactId ); + } +} + +void b3RemoveContactFromGraph( b3World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex, bool meshContact ) +{ + b3ConstraintGraph* graph = &world->constraintGraph; + + B3_ASSERT( 0 <= colorIndex && colorIndex < B3_GRAPH_COLOR_COUNT ); + b3GraphColor* color = graph->colors + colorIndex; + + if ( colorIndex != B3_OVERFLOW_INDEX ) + { + // This might clear a bit for a static body, but this has no effect + b3ClearBit( &color->bodySet, bodyIdA ); + b3ClearBit( &color->bodySet, bodyIdB ); + } + + if ( meshContact || colorIndex == B3_OVERFLOW_INDEX ) + { + int movedIndex = b3Array_RemoveSwap( color->contacts, localIndex ); + if ( movedIndex != B3_NULL_INDEX ) + { + // Fix index on swapped contact + int movedContactId = color->contacts.data[localIndex].contactId; + b3Contact* movedContact = b3Array_Get( world->contacts, movedContactId ); + B3_ASSERT( movedContact->setIndex == b3_awakeSet ); + B3_ASSERT( movedContact->colorIndex == colorIndex ); + B3_ASSERT( movedContact->localIndex == movedIndex ); + movedContact->localIndex = localIndex; + } + } + else + { + int movedIndex = b3Array_RemoveSwap( color->convexContacts, localIndex ); + if ( movedIndex != B3_NULL_INDEX ) + { + // Fix index on swapped contact + int movedContactId = color->convexContacts.data[localIndex]; + b3Contact* movedContact = b3Array_Get( world->contacts, movedContactId ); + B3_ASSERT( movedContact->setIndex == b3_awakeSet ); + B3_ASSERT( movedContact->colorIndex == colorIndex ); + B3_ASSERT( movedContact->localIndex == movedIndex ); + B3_ASSERT( ( movedContact->flags & b3_simMeshContact ) == 0 ); + movedContact->localIndex = localIndex; + } + } +} + +static int b3AssignJointColor( b3ConstraintGraph* graph, int bodyIdA, int bodyIdB, b3BodyType typeA, b3BodyType typeB ) +{ + B3_ASSERT( typeA == b3_dynamicBody || typeB == b3_dynamicBody ); + B3_UNUSED( graph ); + B3_UNUSED( bodyIdA ); + B3_UNUSED( bodyIdB ); + B3_UNUSED( typeA ); + B3_UNUSED( typeB ); + +#if B3_FORCE_OVERFLOW == 0 + if ( typeA == b3_dynamicBody && typeB == b3_dynamicBody ) + { + // Dynamic constraint colors cannot encroach on colors reserved for static constraints + for ( int i = 0; i < B3_DYNAMIC_COLOR_COUNT; ++i ) + { + b3GraphColor* color = graph->colors + i; + if ( b3GetBit( &color->bodySet, bodyIdA ) || b3GetBit( &color->bodySet, bodyIdB ) ) + { + continue; + } + + b3SetBitGrow( &color->bodySet, bodyIdA ); + b3SetBitGrow( &color->bodySet, bodyIdB ); + return i; + } + } + else if ( typeA == b3_dynamicBody ) + { + // Static constraint colors build from the end to get higher priority than dyn-dyn constraints + for ( int i = B3_OVERFLOW_INDEX - 1; i >= 1; --i ) + { + b3GraphColor* color = graph->colors + i; + if ( b3GetBit( &color->bodySet, bodyIdA ) ) + { + continue; + } + + b3SetBitGrow( &color->bodySet, bodyIdA ); + return i; + } + } + else if ( typeB == b3_dynamicBody ) + { + // Static constraint colors build from the end to get higher priority than dyn-dyn constraints + for ( int i = B3_OVERFLOW_INDEX - 1; i >= 1; --i ) + { + b3GraphColor* color = graph->colors + i; + if ( b3GetBit( &color->bodySet, bodyIdB ) ) + { + continue; + } + + b3SetBitGrow( &color->bodySet, bodyIdB ); + return i; + } + } +#endif + + return B3_OVERFLOW_INDEX; +} + +b3JointSim* b3CreateJointInGraph( b3World* world, b3Joint* joint ) +{ + b3ConstraintGraph* graph = &world->constraintGraph; + + int bodyIdA = joint->edges[0].bodyId; + int bodyIdB = joint->edges[1].bodyId; + b3Body* bodyA = b3Array_Get( world->bodies, bodyIdA ); + b3Body* bodyB = b3Array_Get( world->bodies, bodyIdB ); + + int colorIndex = b3AssignJointColor( graph, bodyIdA, bodyIdB, bodyA->type, bodyB->type ); + + b3JointSim* jointSim = b3Array_Emplace( graph->colors[colorIndex].jointSims ); + memset( jointSim, 0, sizeof( b3JointSim ) ); + + joint->colorIndex = colorIndex; + joint->localIndex = graph->colors[colorIndex].jointSims.count - 1; + return jointSim; +} + +void b3AddJointToGraph( b3World* world, b3JointSim* jointSim, b3Joint* joint ) +{ + b3JointSim* jointDst = b3CreateJointInGraph( world, joint ); + memcpy( jointDst, jointSim, sizeof( b3JointSim ) ); +} + +void b3RemoveJointFromGraph( b3World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex ) +{ + b3ConstraintGraph* graph = &world->constraintGraph; + + B3_ASSERT( 0 <= colorIndex && colorIndex < B3_GRAPH_COLOR_COUNT ); + b3GraphColor* color = graph->colors + colorIndex; + + if ( colorIndex != B3_OVERFLOW_INDEX ) + { + // May clear static bodies, no effect + b3ClearBit( &color->bodySet, bodyIdA ); + b3ClearBit( &color->bodySet, bodyIdB ); + } + + int movedIndex = b3Array_RemoveSwap( color->jointSims, localIndex ); + if ( movedIndex != B3_NULL_INDEX ) + { + // Fix moved joint + b3JointSim* movedJointSim = color->jointSims.data + localIndex; + int movedId = movedJointSim->jointId; + b3Joint* movedJoint = b3Array_Get( world->joints, movedId ); + B3_ASSERT( movedJoint->setIndex == b3_awakeSet ); + B3_ASSERT( movedJoint->colorIndex == colorIndex ); + B3_ASSERT( movedJoint->localIndex == movedIndex ); + movedJoint->localIndex = localIndex; + } +} diff --git a/src/constraint_graph.h b/src/constraint_graph.h new file mode 100644 index 0000000..1776cc0 --- /dev/null +++ b/src/constraint_graph.h @@ -0,0 +1,86 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "bitset.h" +#include "contact.h" +#include "container.h" +#include "solver.h" +#include "solver_set.h" +#include "box3d/constants.h" + +typedef struct b3Body b3Body; +typedef struct b3Contact b3Contact; +typedef struct b3JointSim b3JointSim; +typedef struct b3Joint b3Joint; +typedef struct b3StepContext b3StepContext; +typedef struct b3World b3World; + +// This holds constraints that cannot fit the graph color limit. This happens when a single dynamic body +// is touching many other bodies. +#define B3_OVERFLOW_INDEX ( B3_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 B3_DYNAMIC_COLOR_COUNT ( B3_GRAPH_COLOR_COUNT - 4 ) + +// todo optimize mesh contact constraints +// They can be lumped with convex contacts and I can use the bitset event to re-link if the manifold count increases +// Could also create a group for two wide manifolds and use bitset event +// This could create ping-pong jitter so may need to pin to high water mark or introduce hysteresis somehow +// +// Dirk has the idea to do graph coloring based on manifolds. This suggests mesh contact will have manifolds +// in multiple graph colors. So each manifold with have a color and local index. +// Some concerns about this: +// - manifolds don't have a strong identity, would this affect stability/jitter? +// - this creates a lot of static graph colors and can overflow + +typedef struct b3GraphColor +{ + // 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. + b3BitSet bodySet; + + // cache friendly arrays + b3ArrayC( b3JointSim ) jointSims; + + b3ArrayC( int ) convexContacts; + b3ArrayC( b3ContactSpec ) contacts; + + // These are used for convex contacts + struct b3ContactConstraintWide* wideConstraints; + int wideConstraintCount; + + // These are used for mesh and overflow contacts + struct b3ManifoldConstraint* manifoldConstraints; + int manifoldConstraintCount; + struct b3ContactConstraint* contactConstraints; + int contactConstraintCount; +} b3GraphColor; + +typedef struct b3ConstraintGraph +{ + // including overflow at the end + b3GraphColor colors[B3_GRAPH_COLOR_COUNT]; +} b3ConstraintGraph; + +#ifdef __cplusplus +extern "C" +{ +#endif + +void b3CreateGraph( b3ConstraintGraph* graph, int bodyCapacity ); +void b3DestroyGraph( b3ConstraintGraph* graph ); + +void b3AddContactToGraph( b3World* world, b3Contact* contact ); +void b3RemoveContactFromGraph( b3World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex, bool meshContact ); + +b3JointSim* b3CreateJointInGraph( b3World* world, b3Joint* joint ); +void b3AddJointToGraph( b3World* world, b3JointSim* jointSim, b3Joint* joint ); +void b3RemoveJointFromGraph( b3World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex ); + +#ifdef __cplusplus +} +#endif diff --git a/src/contact.c b/src/contact.c new file mode 100644 index 0000000..ac3929f --- /dev/null +++ b/src/contact.c @@ -0,0 +1,862 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "contact.h" + +#include "algorithm.h" +#include "body.h" +#include "compound.h" +#include "island.h" +#include "manifold.h" +#include "physics_world.h" +#include "shape.h" +#include "solver_set.h" +#include "table.h" + +#include "box3d/box3d.h" + +// Contacts and determinism +// A deterministic simulation requires contacts to exist in the same order in b3Island 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 b3UpdateBroadPhasePairs +// - 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: +// b3ManifoldPoint::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. +// typedef b3Manifold b3ManifoldFcn( const b3Shape* shapeA, b3Transform xfA, const b3Shape* shapeB, b3Transform xfB, +// b3ContactCache* cache ); + +static b3Contact* b3GetContactFullId( b3World* world, b3ContactId contactId ) +{ + int id = contactId.index1 - 1; + b3Contact* contact = b3Array_Get( world->contacts, id ); + B3_ASSERT( contact->contactId == id && contact->generation == contactId.generation ); + return contact; +} + +b3ContactData b3Contact_GetData( b3ContactId contactId ) +{ + b3World* world = b3GetWorld( contactId.world0 ); + b3Contact* contact = b3GetContactFullId( world, contactId ); + + const b3Shape* shapeA = b3Array_Get( world->shapes, contact->shapeIdA ); + const b3Shape* shapeB = b3Array_Get( world->shapes, contact->shapeIdB ); + + b3ContactData data = { 0 }; + data.contactId = contactId; + data.shapeIdA = (b3ShapeId){ + .index1 = shapeA->id + 1, + .world0 = contactId.world0, + .generation = shapeA->generation, + }; + data.shapeIdB = (b3ShapeId){ + .index1 = shapeB->id + 1, + .world0 = contactId.world0, + .generation = shapeB->generation, + }; + + if ( contact->manifoldCount > 0 ) + { + data.manifolds = contact->manifolds; + data.manifoldCount = contact->manifoldCount; + } + else + { + data.manifolds = NULL; + data.manifoldCount = 0; + } + + return data; +} + +struct b3ContactRegister +{ + // b3ManifoldFcn* fcn; + bool supported; + bool primary; +}; + +static struct b3ContactRegister s_registers[b3_shapeTypeCount][b3_shapeTypeCount]; +static bool s_initialized = false; + +static void b3AddType( b3ShapeType type1, b3ShapeType type2 ) +{ + B3_ASSERT( 0 <= type1 && type1 < b3_shapeTypeCount ); + B3_ASSERT( 0 <= type2 && type2 < b3_shapeTypeCount ); + + s_registers[type1][type2].supported = true; + s_registers[type1][type2].primary = true; + + if ( type1 != type2 ) + { + s_registers[type2][type1].supported = true; + s_registers[type2][type1].primary = false; + } +} + +void b3InitializeContactRegisters( void ) +{ + if ( s_initialized == false ) + { + b3AddType( b3_sphereShape, b3_sphereShape ); + b3AddType( b3_capsuleShape, b3_sphereShape ); + b3AddType( b3_capsuleShape, b3_capsuleShape ); + b3AddType( b3_compoundShape, b3_sphereShape ); + b3AddType( b3_compoundShape, b3_capsuleShape ); + b3AddType( b3_compoundShape, b3_hullShape ); + b3AddType( b3_hullShape, b3_sphereShape ); + b3AddType( b3_hullShape, b3_capsuleShape ); + b3AddType( b3_hullShape, b3_hullShape ); + b3AddType( b3_meshShape, b3_sphereShape ); + b3AddType( b3_meshShape, b3_capsuleShape ); + b3AddType( b3_meshShape, b3_hullShape ); + b3AddType( b3_heightShape, b3_sphereShape ); + b3AddType( b3_heightShape, b3_capsuleShape ); + b3AddType( b3_heightShape, b3_hullShape ); + s_initialized = true; + } +} + +void b3CreateContact( b3World* world, b3Shape* shapeA, b3Shape* shapeB, int childIndex ) +{ + b3ShapeType typeA = shapeA->type; + b3ShapeType typeB = shapeB->type; + + B3_ASSERT( 0 <= typeA && typeA < b3_shapeTypeCount ); + B3_ASSERT( 0 <= typeB && typeB < b3_shapeTypeCount ); + + if ( s_registers[typeA][typeB].supported == false ) + { + // For example, no mesh vs mesh collision + return; + } + + if ( s_registers[typeA][typeB].primary == false ) + { + // flip order + b3CreateContact( world, shapeB, shapeA, childIndex ); + return; + } + + b3Body* bodyA = b3Array_Get( world->bodies, shapeA->bodyId ); + b3Body* bodyB = b3Array_Get( world->bodies, shapeB->bodyId ); + + B3_ASSERT( bodyA->setIndex != b3_disabledSet && bodyB->setIndex != b3_disabledSet ); + B3_ASSERT( bodyA->setIndex != b3_staticSet || bodyB->setIndex != b3_staticSet ); + + int setIndex; + if ( bodyA->setIndex == b3_awakeSet || bodyB->setIndex == b3_awakeSet ) + { + setIndex = b3_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 + + // This is possible if a shape moves slightly then falls asleep + setIndex = b3_disabledSet; + } + + b3SolverSet* set = b3Array_Get( world->solverSets, setIndex ); + + // Create contact key and contact + int contactId = b3AllocId( &world->contactIdPool ); + if ( contactId == world->contacts.count ) + { + b3Contact emptyContact = { 0 }; + b3Array_Push( world->contacts, emptyContact ); + } + + int shapeIdA = shapeA->id; + int shapeIdB = shapeB->id; + + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + int generation = contact->generation; + *contact = (b3Contact){ 0 }; + contact->contactId = contactId; + contact->generation = generation + 1; + contact->setIndex = setIndex; + contact->colorIndex = B3_NULL_INDEX; + contact->localIndex = set->contactIndices.count; + contact->islandId = B3_NULL_INDEX; + contact->islandIndex = B3_NULL_INDEX; + contact->shapeIdA = shapeIdA; + contact->shapeIdB = shapeIdB; + contact->childIndex = childIndex; + + if ( shapeA->type == b3_meshShape || shapeA->type == b3_heightShape ) + { + contact->flags |= b3_simMeshContact; + } + else if ( shapeA->type == b3_compoundShape ) + { + b3ChildShape child = b3GetCompoundChild( shapeA->compound, childIndex ); + if ( child.type == b3_meshShape ) + { + contact->flags |= b3_simMeshContact; + } + } + + // todo impose these restrictions to make life easier + B3_ASSERT( shapeB->type == b3_sphereShape || shapeB->type == b3_capsuleShape || shapeB->type == b3_hullShape ); + // B3_ASSERT( bodyB->type != b3_staticBody ); + + // Is either body static? + // Note: it is possible to have a dynamic mesh collide with a static convex shape. Maybe I should disallow this. + if ( bodyA->type == b3_staticBody || bodyB->type == b3_staticBody ) + { + contact->flags |= b3_contactStaticFlag; + } + + B3_ASSERT( shapeA->sensorIndex == B3_NULL_INDEX && shapeB->sensorIndex == B3_NULL_INDEX ); + + if ( shapeA->enableContactEvents || shapeB->enableContactEvents ) + { + contact->flags |= b3_contactEnableContactEvents; + } + + // Connect to body A + { + contact->edges[0].bodyId = shapeA->bodyId; + contact->edges[0].prevKey = B3_NULL_INDEX; + contact->edges[0].nextKey = bodyA->headContactKey; + + int keyA = ( contactId << 1 ) | 0; + int headContactKey = bodyA->headContactKey; + if ( headContactKey != B3_NULL_INDEX ) + { + b3Contact* headContact = b3Array_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 = B3_NULL_INDEX; + contact->edges[1].nextKey = bodyB->headContactKey; + + int keyB = ( contactId << 1 ) | 1; + int headContactKey = bodyB->headContactKey; + if ( bodyB->headContactKey != B3_NULL_INDEX ) + { + b3Contact* headContact = b3Array_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 = b3ShapePairKey( shapeIdA, shapeIdB, childIndex ); + b3AddKey( &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. + b3Array_Push( set->contactIndices, contactId ); + + float radiusA = 0.0f; + if ( typeA == b3_sphereShape ) + { + radiusA = shapeA->sphere.radius; + } + else if ( typeA == b3_capsuleShape ) + { + radiusA = shapeA->capsule.radius; + } + + float radiusB = 0.0f; + if ( typeB == b3_sphereShape ) + { + radiusB = shapeB->sphere.radius; + } + else if ( typeB == b3_capsuleShape ) + { + radiusB = shapeB->capsule.radius; + } + + float maxRadius = b3MaxFloat( radiusA, radiusB ); + + // Assuming the rolling resistance doesn't change + contact->rollingResistance = + b3MaxFloat( shapeA->materials[0].rollingResistance, shapeB->materials[0].rollingResistance ) * maxRadius; + + if ( shapeA->enablePreSolveEvents || shapeB->enablePreSolveEvents ) + { + contact->flags |= b3_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 b3DestroyContact( b3World* world, b3Contact* contact, bool wakeBodies ) +{ + // Remove pair from set + uint64_t pairKey = b3ShapePairKey( contact->shapeIdA, contact->shapeIdB, contact->childIndex ); + b3RemoveKey( &world->broadPhase.pairSet, pairKey ); + + b3FreeManifolds( world, contact->manifolds, contact->manifoldCount ); + contact->manifolds = NULL; + contact->manifoldCount = 0; + + b3ContactEdge* edgeA = contact->edges + 0; + b3ContactEdge* edgeB = contact->edges + 1; + + int bodyIdA = edgeA->bodyId; + int bodyIdB = edgeB->bodyId; + b3Body* bodyA = b3Array_Get( world->bodies, bodyIdA ); + b3Body* bodyB = b3Array_Get( world->bodies, bodyIdB ); + + uint32_t flags = contact->flags; + bool touching = ( flags & b3_contactTouchingFlag ) != 0; + + // End touch event + if ( touching && ( flags & b3_contactEnableContactEvents ) != 0 ) + { + uint16_t worldId = world->worldId; + const b3Shape* shapeA = b3Array_Get( world->shapes, contact->shapeIdA ); + const b3Shape* shapeB = b3Array_Get( world->shapes, contact->shapeIdB ); + b3ShapeId shapeIdA = { shapeA->id + 1, worldId, shapeA->generation }; + b3ShapeId shapeIdB = { shapeB->id + 1, worldId, shapeB->generation }; + + b3ContactId contactId = { + .index1 = contact->contactId + 1, + .world0 = world->worldId, + .padding = 0, + .generation = contact->generation, + }; + + b3ContactEndTouchEvent event = { + .shapeIdA = shapeIdA, + .shapeIdB = shapeIdB, + .contactId = contactId, + }; + + b3Array_Push( world->contactEndEvents[world->endEventArrayIndex], event ); + } + + // Remove from body A + if ( edgeA->prevKey != B3_NULL_INDEX ) + { + b3Contact* prevContact = b3Array_Get( world->contacts, edgeA->prevKey >> 1 ); + b3ContactEdge* prevEdge = prevContact->edges + ( edgeA->prevKey & 1 ); + prevEdge->nextKey = edgeA->nextKey; + } + + if ( edgeA->nextKey != B3_NULL_INDEX ) + { + b3Contact* nextContact = b3Array_Get( world->contacts, edgeA->nextKey >> 1 ); + b3ContactEdge* 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 != B3_NULL_INDEX ) + { + b3Contact* prevContact = b3Array_Get( world->contacts, edgeB->prevKey >> 1 ); + b3ContactEdge* prevEdge = prevContact->edges + ( edgeB->prevKey & 1 ); + prevEdge->nextKey = edgeB->nextKey; + } + + if ( edgeB->nextKey != B3_NULL_INDEX ) + { + b3Contact* nextContact = b3Array_Get( world->contacts, edgeB->nextKey >> 1 ); + b3ContactEdge* 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; + + if ( contact->flags & b3_simMeshContact ) + { + b3Array_Destroy( contact->meshContact.triangleCache ); + } + + // Remove contact from the array that owns it + if ( contact->islandId != B3_NULL_INDEX ) + { + b3UnlinkContact( world, contact ); + } + + if ( contact->colorIndex != B3_NULL_INDEX ) + { + // contact is an active constraint + B3_ASSERT( contact->setIndex == b3_awakeSet ); + bool meshContact = contact->flags & b3_simMeshContact; + b3RemoveContactFromGraph( world, bodyIdA, bodyIdB, contact->colorIndex, contact->localIndex, meshContact ); + } + else + { + // contact is non-touching or is sleeping or is a sensor + B3_ASSERT( contact->setIndex != b3_awakeSet || ( contact->flags & b3_contactTouchingFlag ) == 0 ); + b3SolverSet* set = b3Array_Get( world->solverSets, contact->setIndex ); + + int localIndex = contact->localIndex; + int movedIndex = b3Array_RemoveSwap( set->contactIndices, localIndex ); + if ( movedIndex != B3_NULL_INDEX ) + { + int movedContactIndex = set->contactIndices.data[localIndex]; + b3Contact* movedContact = b3Array_Get( world->contacts, movedContactIndex ); + movedContact->localIndex = localIndex; + } + } + + // Free contact and id (preserve generation) + contact->contactId = B3_NULL_INDEX; + contact->setIndex = B3_NULL_INDEX; + contact->colorIndex = B3_NULL_INDEX; + contact->localIndex = B3_NULL_INDEX; + b3FreeId( &world->contactIdPool, contactId ); + + if ( wakeBodies && touching ) + { + b3WakeBody( world, bodyA ); + b3WakeBody( world, bodyB ); + } +} + +static bool b3ComputeConvexManifold( b3World* world, int workerIndex, b3Contact* contact, const b3Shape* shapeA, b3Transform xfA, + const b3Shape* shapeB, b3Transform xfB, b3Arena arena ) +{ + b3ShapeType typeA = shapeA->type; + b3ShapeType typeB = shapeB->type; + + b3ContactCache* cache = &contact->convexContact.cache; + + int pointCapacity = 32; + b3LocalManifoldPoint* pointBuffer = (b3LocalManifoldPoint*)b3Bump( &arena, pointCapacity * sizeof( b3LocalManifoldPoint ) ); + + b3LocalManifold geomManifold = { 0 }; + geomManifold.points = pointBuffer; + + b3Transform transformBtoA = b3InvMulTransforms( xfA, xfB ); + + if ( typeA == b3_sphereShape ) + { + B3_ASSERT( typeB == b3_sphereShape ); + b3CollideSpheres( &geomManifold, pointCapacity, &shapeA->sphere, &shapeB->sphere, transformBtoA ); + } + else if ( typeA == b3_capsuleShape ) + { + if ( typeB == b3_sphereShape ) + { + b3CollideCapsuleAndSphere( &geomManifold, pointCapacity, &shapeA->capsule, &shapeB->sphere, transformBtoA ); + } + else + { + B3_ASSERT( typeB == b3_capsuleShape ); + b3CollideCapsules( &geomManifold, pointCapacity, &shapeA->capsule, &shapeB->capsule, transformBtoA ); + } + } + else + { + B3_ASSERT( typeA == b3_hullShape ); + + if ( typeB == b3_sphereShape ) + { + b3CollideHullAndSphere( &geomManifold, pointCapacity, shapeA->hull, &shapeB->sphere, transformBtoA, + &cache->simplexCache ); + } + else if ( typeB == b3_capsuleShape ) + { + b3CollideHullAndCapsule( &geomManifold, pointCapacity, shapeA->hull, &shapeB->capsule, transformBtoA, + &cache->simplexCache ); + } + else + { + B3_ASSERT( typeB == b3_hullShape ); + b3CollideHulls( &geomManifold, pointCapacity, shapeA->hull, shapeB->hull, transformBtoA, &cache->satCache ); + world->taskContexts.data[workerIndex].satCallCount += 1; + world->taskContexts.data[workerIndex].satCacheHitCount += cache->satCache.hit; + } + } + + if ( geomManifold.pointCount == 0 ) + { + if ( contact->manifoldCount > 0 ) + { + b3FreeManifolds( world, contact->manifolds, contact->manifoldCount ); + contact->manifolds = NULL; + contact->manifoldCount = 0; + } + + return false; + } + + b3ManifoldPoint oldPoints[B3_MAX_MANIFOLD_POINTS]; + int oldCount = 0; + + if ( contact->manifoldCount == 0 ) + { + contact->manifolds = b3AllocateManifolds( world, 1 ); + contact->manifoldCount = 1; + } + else + { + oldCount = contact->manifolds[0].pointCount; + memcpy( oldPoints, contact->manifolds[0].points, oldCount * sizeof( b3ManifoldPoint ) ); + } + + b3Manifold* manifold = contact->manifolds; + manifold->pointCount = geomManifold.pointCount; + + b3Matrix3 matrixA = b3MakeMatrixFromQuat( xfA.q ); + manifold->normal = b3MulMV( matrixA, geomManifold.normal ); + + // Store point data in contact + for ( int i = 0; i < geomManifold.pointCount; ++i ) + { + const b3LocalManifoldPoint* source = geomManifold.points + i; + b3ManifoldPoint* target = manifold->points + i; + + // Contact points are computed in frame A + target->anchorA = b3MulMV( matrixA, source->point ); + target->anchorB = b3Add( target->anchorA, b3Sub( xfA.p, xfB.p ) ); + target->separation = source->separation; + target->featureId = b3MakeFeatureId( source->pair ); + target->triangleIndex = B3_NULL_INDEX; + target->normalVelocity = 0.0f; + } + + // Copy impulses from old points + for ( int i = 0; i < geomManifold.pointCount; ++i ) + { + b3ManifoldPoint* pt2 = manifold->points + i; + pt2->totalNormalImpulse = 0.0f; + pt2->persisted = false; + + for ( int j = 0; j < oldCount; ++j ) + { + b3ManifoldPoint* pt1 = oldPoints + j; + + if ( pt2->featureId == pt1->featureId ) + { + pt2->normalImpulse = pt1->normalImpulse; + pt2->persisted = true; + + // claimed + pt1->featureId = UINT32_MAX; + + break; + } + } + + if ( pt2->persisted == false ) + { + pt2->normalImpulse = 0.0f; + } + } + + return true; +} + +static bool b3UpdateConvexContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3Transform xfA, + b3Shape* shapeB, b3Transform xfB, bool flip, b3Arena arena ) +{ + // Compute new manifold + bool touching = b3ComputeConvexManifold( world, workerIndex, contact, shapeA, xfA, shapeB, xfB, arena ); + + if ( touching == false ) + { + B3_ASSERT( contact->manifolds == NULL && contact->manifoldCount == 0 ); + return false; + } + + B3_ASSERT( contact->manifoldCount == 1 ); + + if ( flip ) + { + // Not flipping the feature ids because they just need to match and flipping is consistent. + b3Manifold* manifold = contact->manifolds + 0; + manifold->normal = b3Neg( manifold->normal ); + int pointCount = manifold->pointCount; + for ( int i = 0; i < pointCount; ++i ) + { + b3ManifoldPoint* mp = manifold->points + i; + B3_SWAP( mp->anchorA, mp->anchorB ); + } + } + + const b3SurfaceMaterial* materialA = shapeA->materials + 0; + const b3SurfaceMaterial* materialB = shapeB->materials + 0; + + // Keep these updated in case the values on the shapes are modified + contact->friction = + world->frictionCallback( materialA->friction, materialA->userMaterialId, materialB->friction, materialB->userMaterialId ); + contact->restitution = world->restitutionCallback( materialA->restitution, materialA->userMaterialId, materialB->restitution, + materialB->userMaterialId ); + + if ( materialA->rollingResistance > 0.0f || materialB->rollingResistance > 0.0f ) + { + b3ShapeType typeA = shapeA->type; + b3ShapeType typeB = shapeB->type; + + float radiusA = 0.0f; + if ( typeA == b3_sphereShape ) + { + radiusA = shapeA->sphere.radius; + } + else if ( typeA == b3_capsuleShape ) + { + radiusA = shapeA->capsule.radius; + } + else if ( typeA == b3_hullShape ) + { + radiusA = 0.25f * shapeA->hull->innerRadius; + } + + float radiusB = 0.0f; + if ( typeB == b3_sphereShape ) + { + radiusB = shapeB->sphere.radius; + } + else if ( typeB == b3_capsuleShape ) + { + radiusB = shapeB->capsule.radius; + } + else if ( typeB == b3_hullShape ) + { + radiusB = 0.25f * shapeB->hull->innerRadius; + } + + float maxRadius = b3MaxFloat( radiusA, radiusB ); + contact->rollingResistance = b3MaxFloat( materialA->rollingResistance, materialB->rollingResistance ) * maxRadius; + } + else + { + contact->rollingResistance = 0.0f; + } + + b3Vec3 tangentVelocityA = b3RotateVector( xfA.q, materialA->tangentVelocity ); + b3Vec3 tangentVelocityB = b3RotateVector( xfB.q, materialB->tangentVelocity ); + contact->tangentVelocity = b3Sub( tangentVelocityA, tangentVelocityB ); + + if ( world->preSolveFcn && ( contact->flags & b3_simEnablePreSolveEvents ) != 0 ) + { + b3ShapeId shapeIdA = { shapeA->id + 1, world->worldId, shapeA->generation }; + b3ShapeId shapeIdB = { shapeB->id + 1, world->worldId, shapeB->generation }; + + // this call assumes thread safety + b3Vec3 point = b3Add( contact->manifolds[0].points[0].anchorA, xfA.p ); + b3Vec3 normal = contact->manifolds[0].normal; + touching = world->preSolveFcn( shapeIdA, shapeIdB, point, normal, world->preSolveContext ); + if ( touching == false ) + { + // disable contact + b3FreeManifolds( world, contact->manifolds, contact->manifoldCount ); + contact->manifolds = NULL; + contact->manifoldCount = 0; + return false; + } + } + + if ( shapeA->enableHitEvents || shapeB->enableHitEvents ) + { + contact->flags |= b3_simEnableHitEvent; + } + else + { + contact->flags &= ~b3_simEnableHitEvent; + } + + return true; +} + +// Update the contact manifold and touching status. +// Note: do not assume the shape AABBs are overlapping or are valid. +bool b3UpdateContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3Vec3 localCenterA, b3Transform xfA, + b3Shape* shapeB, b3Vec3 localCenterB, b3Transform xfB, bool isFast, b3Arena arena ) +{ + bool touching; + + B3_ASSERT( shapeB->type != b3_compoundShape ); + + if ( shapeA->type == b3_compoundShape ) + { + int childIndex = contact->childIndex; + b3ChildShape child = b3GetCompoundChild( shapeA->compound, childIndex ); + + // Temporary child shape to match existing function signatures + b3Shape childShapeA; + memcpy( &childShapeA, shapeA, sizeof( b3Shape ) ); + + childShapeA.type = child.type; + + if ( child.type == b3_capsuleShape ) + { + childShapeA.capsule = child.capsule; + if ( shapeB->type == b3_hullShape ) + { + // Flip + bool flip = true; + touching = b3UpdateConvexContact( world, workerIndex, contact, shapeB, xfB, &childShapeA, xfA, flip, arena ); + } + else + { + bool flip = false; + touching = b3UpdateConvexContact( world, workerIndex, contact, &childShapeA, xfA, shapeB, xfB, flip, arena ); + } + } + else if ( child.type == b3_hullShape ) + { + childShapeA.hull = child.hull; + b3Transform xfChild = b3MulTransforms( xfA, child.transform ); + bool flip = false; + touching = b3UpdateConvexContact( world, workerIndex, contact, &childShapeA, xfChild, shapeB, xfB, flip, arena ); + } + else if ( child.type == b3_meshShape ) + { + childShapeA.mesh = child.mesh; + b3Transform xfChild = b3MulTransforms( xfA, child.transform ); + + touching = b3ComputeMeshManifolds( world, workerIndex, contact, &childShapeA, child.materialIndices, xfChild, shapeB, + xfB, isFast, arena ); + + if ( touching && ( shapeA->enableHitEvents || shapeB->enableHitEvents ) ) + { + contact->flags |= b3_simEnableHitEvent; + } + else + { + contact->flags &= ~b3_simEnableHitEvent; + } + + B3_ASSERT( ( touching == true && contact->manifoldCount > 0 ) || + ( touching == false && contact->manifoldCount == 0 ) ); + } + else + { + B3_ASSERT( child.type == b3_sphereShape ); + + childShapeA.sphere = child.sphere; + if ( shapeB->type == b3_capsuleShape || shapeB->type == b3_hullShape ) + { + // Flip + bool flip = true; + touching = b3UpdateConvexContact( world, workerIndex, contact, shapeB, xfB, &childShapeA, xfA, flip, arena ); + } + else + { + bool flip = false; + touching = b3UpdateConvexContact( world, workerIndex, contact, &childShapeA, xfA, shapeB, xfB, flip, arena ); + } + } + + // The anchor is relative to the child origin but oriented in world space. + // Offset the anchor to be relative to the compound origin. + int manifoldCount = contact->manifoldCount; + b3Vec3 offset = b3RotateVector( xfA.q, child.transform.p ); + for ( int i = 0; i < manifoldCount; ++i ) + { + b3Manifold* manifold = contact->manifolds + i; + int pointCount = manifold->pointCount; + for ( int j = 0; j < pointCount; ++j ) + { + b3ManifoldPoint* mp = manifold->points + j; + mp->anchorA = b3Add( mp->anchorA, offset ); + } + } + } + else if ( shapeA->type == b3_meshShape || shapeA->type == b3_heightShape ) + { + // Does this contact touch a mesh or height-field? + + // Compute mesh manifolds + touching = b3ComputeMeshManifolds( world, workerIndex, contact, shapeA, NULL, xfA, shapeB, xfB, isFast, arena ); + + if ( touching && ( shapeA->enableHitEvents || shapeB->enableHitEvents ) ) + { + contact->flags |= b3_simEnableHitEvent; + } + else + { + contact->flags &= ~b3_simEnableHitEvent; + } + + // B3_ASSERT( ( touching == true && contact->manifoldCount > 0 ) || ( touching == false && contact->manifoldCount == 0 ) + // ); + B3_ASSERT( ( touching == true && contact->manifoldCount > 0 ) || ( touching == false && contact->manifoldCount == 0 ) ); + } + else + { + // Convex-vs-convex + bool flip = false; + touching = b3UpdateConvexContact( world, workerIndex, contact, shapeA, xfA, shapeB, xfB, flip, arena ); + } + + if ( touching ) + { + b3Vec3 centerA = b3RotateVector( xfA.q, localCenterA ); + b3Vec3 centerB = b3RotateVector( xfB.q, localCenterB ); + + // Adjust anchors to be relative to center of mass + for ( int i = 0; i < contact->manifoldCount; ++i ) + { + b3Manifold* manifold = contact->manifolds + i; + for ( int j = 0; j < manifold->pointCount; ++j ) + { + b3ManifoldPoint* mp = manifold->points + j; + mp->anchorA = b3Sub( mp->anchorA, centerA ); + mp->anchorB = b3Sub( mp->anchorB, centerB ); + } + } + + contact->flags |= b3_simTouchingFlag; + } + else + { + contact->flags &= ~b3_simTouchingFlag; + } + + return touching; +} diff --git a/src/contact.h b/src/contact.h new file mode 100644 index 0000000..1b8cbed --- /dev/null +++ b/src/contact.h @@ -0,0 +1,185 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "arena_allocator.h" +#include "container.h" + +#include "box3d/collision.h" +#include "box3d/types.h" + +#define B3_FORCE_GHOST_COLLISIONS 0 + +typedef struct b3Shape b3Shape; +typedef struct b3World b3World; + +typedef union b3ContactCache +{ + b3SATCache satCache; + b3SimplexCache simplexCache; +} b3ContactCache; + +typedef struct b3TriangleCache +{ + int triangleIndex; + b3ContactCache cache; +} b3TriangleCache; + +b3DeclareArray( b3TriangleCache ); + +enum b3ContactFlags +{ + // Set when the solid shapes are touching. + b3_contactTouchingFlag = 0x00000001, + + // Contact has a hit event + b3_contactHitEventFlag = 0x00000002, + + // This contact wants contact events + b3_contactEnableContactEvents = 0x00000004, + + // This is contact is between a dynamic and static body + b3_contactStaticFlag = 0x00000008, + + // Set when the shapes are touching + b3_simTouchingFlag = 0x00010000, + + // This contact no longer has overlapping AABBs + b3_simDisjoint = 0x00020000, + + // This contact started touching + b3_simStartedTouching = 0x00040000, + + // This contact stopped touching + b3_simStoppedTouching = 0x00080000, + + // This contact has a hit event + b3_simEnableHitEvent = 0x00100000, + + // This contact wants pre-solve events + b3_simEnablePreSolveEvents = 0x00200000, + + // This is a mesh contact + b3_simMeshContact = 0x00400000, + + b3_relativeTransformValid = 0x00800000, +}; + +// 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 b3ContactEdge +{ + int bodyId; + int prevKey; + int nextKey; +} b3ContactEdge; + +typedef struct b3MeshContact +{ + // todo use block allocator for this for faster shutdown + b3ArrayC( b3TriangleCache ) triangleCache; + b3AABB queryBounds; +} b3MeshContact; + +typedef struct b3ConvexContact +{ + b3ContactCache cache; +} b3ConvexContact; + +// Represents the persistent interaction between two shapes +typedef struct b3Contact +{ + // index of simulation set stored in b3World + // B3_NULL_INDEX when slot is free + int setIndex; + + // index into the constraint graph color array + // B3_NULL_INDEX for non-touching or sleeping contacts + // B3_NULL_INDEX when slot is free + int colorIndex; + + // contact index within set or graph color + // B3_NULL_INDEX when slot is free + int localIndex; + + b3ContactEdge edges[2]; + int shapeIdA; + int shapeIdB; + int childIndex; + + // A contact only belongs to an island if touching, otherwise B3_NULL_INDEX. + int islandId; + + // Index into the island's contacts array for O(1) swap-removal. + // B3_NULL_INDEX when not in an island. + int islandIndex; + + // Back index into b3World::contacts + int contactId; + + // These are transient and cached for improved performance. B3_NULL_INDEX for static bodies. + int bodySimIndexA; + int bodySimIndexB; + + // b3ContactFlags + uint32_t flags; + + b3Manifold* manifolds; + int manifoldCount; + + b3Transform cachedTransformA; + b3Transform cachedTransformB; + + // Mixed friction and restitution + float friction; + + // Usage determined by b3_simMeshContact in simFlags + union + { + b3ConvexContact convexContact; + b3MeshContact meshContact; + }; + + float restitution; + float rollingResistance; + b3Vec3 tangentVelocity; + + // This is monotonically advanced when a contact is allocated in this slot + // Used to check for invalid b3ContactId + uint32_t generation; +} b3Contact; + +typedef struct b3ContactSpec +{ + int contactId; + + // Start of the global manifold constraint array + int manifoldStart; + uint16_t manifoldCount; +} b3ContactSpec; + +b3DeclareArray( b3ContactSpec ); + +#ifdef __cplusplus +extern "C" +{ +#endif + +void b3InitializeContactRegisters( void ); + +void b3CreateContact( b3World* world, b3Shape* shapeA, b3Shape* shapeB, int childIndex ); +void b3DestroyContact( b3World* world, b3Contact* contact, bool wakeBodies ); + +bool b3UpdateContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3Vec3 localCenterA, b3Transform xfA, + b3Shape* shapeB, b3Vec3 localCenterB, b3Transform xfB, bool isFast, b3Arena arena ); + +bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact, const b3Shape* shapeA, const int* materialMap, + b3Transform xfA, const b3Shape* shapeB, b3Transform xfB, bool isFast, b3Arena arena ); + +#ifdef __cplusplus +} +#endif diff --git a/src/contact_solver.c b/src/contact_solver.c new file mode 100644 index 0000000..218dbb8 --- /dev/null +++ b/src/contact_solver.c @@ -0,0 +1,2428 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "contact_solver.h" + +#include "body.h" +#include "constraint_graph.h" +#include "contact.h" +#include "core.h" +#include "math_internal.h" +#include "physics_world.h" +#include "platform.h" +#include "solver_set.h" + +#if B3_ENABLE_VALIDATION +#include "shape.h" +#endif + +#define FIXED_ANCHORS 1 + +// 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) + +// Prepare a mesh constraints +void b3PrepareContacts_Mesh( b3SolverBlock block, b3StepContext* context ) +{ + b3TracyCZoneNC( prepare_contact, "Prepare Contact", b3_colorYellow, true ); + + b3World* world = context->world; + b3BodySim* bodySims = context->sims; + b3BodyState* bodyStates = context->states; + + float warmStartScale = world->enableWarmStarting ? 1.0f : 0.0f; + + // Need to use spans in order to find the associated b2Contact, which is per color + b3ContactPrepareSpan* spans = context->contactPrepareSpans; + b3ManifoldConstraint* manifoldBase = context->manifoldConstraints; + b3ContactConstraint* base = context->contactConstraints; + + if ( block.blockType == b3_overflowBlock ) + { + b3GraphColor* overflow = world->constraintGraph.colors + B3_OVERFLOW_INDEX; + spans = context->overflowSpans; + manifoldBase = overflow->manifoldConstraints; + base = overflow->contactConstraints; + } + + int index = block.startIndex; + int endIndex = block.startIndex + block.count; + + // Find color for start index. Linear search but fast. + int colorIndex = 0; + while ( spans[colorIndex + 1].start <= index ) + { + colorIndex += 1; + } + + // Loop over block + while ( index < endIndex ) + { + int colorStart = spans[colorIndex].start; + int colorEndIndex = b3MinInt( spans[colorIndex + 1].start, endIndex ); + b3ContactSpec* specs = spans[colorIndex].contacts; + + // Loop over color + for ( ; index < colorEndIndex; ++index ) + { + b3ContactConstraint* contactConstraint = base + index; + + int localIndex = index - colorStart; + B3_ASSERT( 0 <= localIndex && localIndex < spans[colorIndex].count ); + int contactId = specs[localIndex].contactId; + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + + int indexA = contact->bodySimIndexA; + int indexB = contact->bodySimIndexB; + +#if B3_ENABLE_VALIDATION + if ( indexA != B3_NULL_INDEX ) + { + b3Body* bodyA = b3Array_Get( world->bodies, contact->edges[0].bodyId ); + B3_ASSERT( indexA == bodyA->localIndex ); + } + + if ( indexB != B3_NULL_INDEX ) + { + b3Body* bodyB = b3Array_Get( world->bodies, contact->edges[1].bodyId ); + B3_ASSERT( indexB == bodyB->localIndex ); + } +#endif + + // Body A data + float mA; + b3Matrix3 iA; + b3Vec3 vA; + b3Vec3 wA; + + if ( indexA == B3_NULL_INDEX ) + { + mA = 0.0f; + iA = b3Mat3_zero; + vA = b3Vec3_zero; + wA = b3Vec3_zero; + } + else + { + b3BodySim* simA = bodySims + indexA; + mA = simA->invMass; + iA = simA->invInertiaWorld; + + b3BodyState* stateA = bodyStates + indexA; + vA = stateA->linearVelocity; + wA = stateA->angularVelocity; + } + + // Body B data + float mB; + b3Matrix3 iB; + b3Vec3 vB; + b3Vec3 wB; + + if ( indexB == B3_NULL_INDEX ) + { + mB = 0.0f; + iB = b3Mat3_zero; + vB = b3Vec3_zero; + wB = b3Vec3_zero; + } + else + { + b3BodySim* simB = bodySims + indexB; + mB = simB->invMass; + iB = simB->invInertiaWorld; + + b3BodyState* stateB = bodyStates + indexB; + vB = stateB->linearVelocity; + wB = stateB->angularVelocity; + } + + int manifoldCount = contact->manifoldCount; + contactConstraint->contact = contact; + contactConstraint->manifoldCount = manifoldCount; + contactConstraint->indexA = indexA; + contactConstraint->indexB = indexB; + contactConstraint->invIA = iA; + contactConstraint->invMassA = mA; + contactConstraint->invIB = iB; + contactConstraint->invMassB = mB; + contactConstraint->rollingMass = b3InvertMatrix( b3AddMM( iA, iB ) ); + contactConstraint->softness = + ( contact->flags & b3_contactStaticFlag ) != 0 ? context->staticSoftness : context->contactSoftness; + contactConstraint->friction = contact->friction; + contactConstraint->restitution = contact->restitution; + contactConstraint->rollingResistance = contact->rollingResistance; + + b3ManifoldConstraint* manifoldConstraints = manifoldBase + specs[localIndex].manifoldStart; + contactConstraint->constraints = manifoldConstraints; + + for ( int manifoldIndex = 0; manifoldIndex < manifoldCount; ++manifoldIndex ) + { + b3Manifold* manifold = contact->manifolds + manifoldIndex; + b3ManifoldConstraint* constraint = manifoldConstraints + manifoldIndex; + int pointCount = manifold->pointCount; + b3Vec3 normal = manifold->normal; + b3Vec3 tangent1 = b3Perp( normal ); + b3Vec3 tangent2 = b3Cross( tangent1, normal ); + + constraint->pointCount = pointCount; + constraint->normal = normal; + constraint->tangent1 = tangent1; + constraint->tangent2 = tangent2; + + // Stiffer for static contacts to avoid bodies getting pushed through the ground + constraint->tangentVelocity1 = b3Dot( contact->tangentVelocity, constraint->tangent1 ); + constraint->tangentVelocity2 = b3Dot( contact->tangentVelocity, constraint->tangent2 ); + + b3Vec3 centerA = b3Vec3_zero; + b3Vec3 centerB = b3Vec3_zero; + + for ( int pointIndex = 0; pointIndex < pointCount; ++pointIndex ) + { + b3ManifoldConstraintPoint* cp = constraint->points + pointIndex; + + // Copy data from manifold point + b3ManifoldPoint* mp = manifold->points + pointIndex; + cp->rA = mp->anchorA; + cp->rB = mp->anchorB; + cp->baseSeparation = mp->separation - b3Dot( b3Sub( cp->rB, cp->rA ), normal ); + cp->normalImpulse = warmStartScale * mp->normalImpulse; + cp->totalNormalImpulse = 0.0f; + + b3Vec3 rA = cp->rA; + b3Vec3 rB = cp->rB; + + b3Vec3 rnA = b3Cross( rA, normal ); + b3Vec3 rnB = b3Cross( rB, normal ); + float kNormal = mA + mB + b3Dot( rnA, b3MulMV( iA, rnA ) ) + b3Dot( rnB, b3MulMV( iB, rnB ) ); + cp->normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; + + // Save relative velocity for restitution + b3Vec3 vrA = b3Add( vA, b3Cross( wA, rA ) ); + b3Vec3 vrB = b3Add( vB, b3Cross( wB, rB ) ); + cp->relativeVelocity = b3Dot( normal, b3Sub( vrB, vrA ) ); + + centerA = b3Add( centerA, rA ); + centerB = b3Add( centerB, rB ); + } + + float invCount = 1.0f / pointCount; + centerA = b3MulSV( invCount, centerA ); + centerB = b3MulSV( invCount, centerB ); + constraint->originA = centerA; + constraint->originB = centerB; + + for ( int pointIndex = 0; pointIndex < pointCount; ++pointIndex ) + { + b3ManifoldConstraintPoint* cp = constraint->points + pointIndex; + cp->leverArm = b3Distance( cp->rA, centerA ); + } + + b3Vec3 rtA1 = b3Cross( centerA, tangent1 ); + b3Vec3 rtA2 = b3Cross( centerA, tangent2 ); + b3Vec3 rtB1 = b3Cross( centerB, tangent1 ); + b3Vec3 rtB2 = b3Cross( centerB, tangent2 ); + + { + b3Matrix2 k; + k.cx.x = mA + mB + b3Dot( rtA1, b3MulMV( iA, rtA1 ) ) + b3Dot( rtB1, b3MulMV( iB, rtB1 ) ); + k.cy.y = mA + mB + b3Dot( rtA2, b3MulMV( iA, rtA2 ) ) + b3Dot( rtB2, b3MulMV( iB, rtB2 ) ); + k.cx.y = k.cy.x = b3Dot( rtA1, b3MulMV( iA, rtA2 ) ) + b3Dot( rtB1, b3MulMV( iB, rtB2 ) ); + + constraint->tangentMass = b3Invert2( k ); + constraint->frictionImpulse.x = warmStartScale * b3Dot( manifold->frictionImpulse, tangent1 ); + constraint->frictionImpulse.y = warmStartScale * b3Dot( manifold->frictionImpulse, tangent2 ); + } + + { + float k = b3Dot( normal, b3MulMV( b3AddMM( iA, iB ), normal ) ); + constraint->twistMass = k > 0.0f ? 1.0f / k : 0.0f; + constraint->twistImpulse = warmStartScale * manifold->twistImpulse; + } + + { + constraint->rollingImpulse = b3MulSV( warmStartScale, manifold->rollingImpulse ); + } + } + } + + // Advance to next color + colorIndex += 1; + } + + b3TracyCZoneEnd( prepare_contact ); +} + +void b3WarmStartContacts_Mesh( b3SolverBlock block, b3StepContext* context ) +{ + b3World* world = context->world; + b3GraphColor* color = world->constraintGraph.colors + block.colorIndex; + b3SolverSet* awakeSet = b3Array_Get( world->solverSets, b3_awakeSet ); + b3BodyState* states = awakeSet->bodyStates.data; + b3ContactConstraint* constraints = color->contactConstraints; + + // This is a dummy state to represent a static body because static bodies don't have a solver body. + b3BodyState dummyState = b3_identityBodyState; + + int startIndex = block.startIndex; + int endIndex = startIndex + block.count; + + for ( int constraintIndex = startIndex; constraintIndex < endIndex; ++constraintIndex ) + { + const b3ContactConstraint* contactConstraint = constraints + constraintIndex; + int indexA = contactConstraint->indexA; + int indexB = contactConstraint->indexB; + + b3BodyState* stateA = indexA == B3_NULL_INDEX ? &dummyState : states + indexA; + b3BodyState* stateB = indexB == B3_NULL_INDEX ? &dummyState : states + indexB; + + b3Vec3 vA = stateA->linearVelocity; + b3Vec3 wA = stateA->angularVelocity; + b3Vec3 vB = stateB->linearVelocity; + b3Vec3 wB = stateB->angularVelocity; + + float mA = contactConstraint->invMassA; + b3Matrix3 iA = contactConstraint->invIA; + float mB = contactConstraint->invMassB; + b3Matrix3 iB = contactConstraint->invIB; + + int manifoldCount = contactConstraint->manifoldCount; + for ( int manifoldIndex = 0; manifoldIndex < manifoldCount; ++manifoldIndex ) + { + b3ManifoldConstraint* constraint = contactConstraint->constraints + manifoldIndex; + + // Normal impulses + b3Vec3 normal = constraint->normal; + int pointCount = constraint->pointCount; + for ( int j = 0; j < pointCount; ++j ) + { + const b3ManifoldConstraintPoint* cp = constraint->points + j; + + // fixed anchors + b3Vec3 rA = cp->rA; + b3Vec3 rB = cp->rB; + + b3Vec3 impulse = b3MulSV( cp->normalImpulse, normal ); + wA = b3Sub( wA, b3MulMV( iA, b3Cross( rA, impulse ) ) ); + vA = b3MulSub( vA, mA, impulse ); + wB = b3Add( wB, b3MulMV( iB, b3Cross( rB, impulse ) ) ); + vB = b3MulAdd( vB, mB, impulse ); + } + + // Central friction + { + b3Vec3 rA = constraint->originA; + b3Vec3 rB = constraint->originB; + b3Vec3 impulse = b3MulSV( constraint->frictionImpulse.x, constraint->tangent1 ); + impulse = b3Add( impulse, b3MulSV( constraint->frictionImpulse.y, constraint->tangent2 ) ); + + wA = b3Sub( wA, b3MulMV( iA, b3Cross( rA, impulse ) ) ); + vA = b3MulSub( vA, mA, impulse ); + wB = b3Add( wB, b3MulMV( iB, b3Cross( rB, impulse ) ) ); + vB = b3MulAdd( vB, mB, impulse ); + } + + // Central twist friction + { + b3Vec3 impulse = b3MulSV( constraint->twistImpulse, constraint->normal ); + wA = b3Sub( wA, b3MulMV( iA, impulse ) ); + wB = b3Add( wB, b3MulMV( iB, impulse ) ); + } + + // Rolling resistance + { + b3Vec3 impulse = constraint->rollingImpulse; + wA = b3Sub( wA, b3MulMV( iA, impulse ) ); + wB = b3Add( wB, b3MulMV( iB, impulse ) ); + } + } + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->linearVelocity = vA; + stateA->angularVelocity = wA; + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->linearVelocity = vB; + stateB->angularVelocity = wB; + } + } +} + +// Merged normal and friction loops. This is much more stable for the Jenga stack. +void b3SolveContacts_Mesh( b3SolverBlock block, b3StepContext* context, bool useBias ) +{ + b3World* world = context->world; + b3GraphColor* color = world->constraintGraph.colors + block.colorIndex; + b3ContactConstraint* contactConstraints = color->contactConstraints; + b3BodyState* states = context->states; + + // This is a dummy state to represent a static body because static bodies don't have a solver body. + b3BodyState dummyState = b3_identityBodyState; + + // The last block might not be full + int startIndex = block.startIndex; + int endIndex = startIndex + block.count; + + float inv_h = context->inv_h; + const float contactSpeed = context->world->contactSpeed; + + for ( int i = startIndex; i < endIndex; ++i ) + { + b3ContactConstraint* contactConstraint = contactConstraints + i; + int manifoldCount = contactConstraint->manifoldCount; + + int indexA = contactConstraint->indexA; + int indexB = contactConstraint->indexB; + + float mA = contactConstraint->invMassA; + b3Matrix3 iA = contactConstraint->invIA; + float mB = contactConstraint->invMassB; + b3Matrix3 iB = contactConstraint->invIB; + + b3BodyState* stateA = indexA == B3_NULL_INDEX ? &dummyState : states + indexA; + b3Vec3 vA = stateA->linearVelocity; + b3Vec3 wA = stateA->angularVelocity; + b3Quat dqA = stateA->deltaRotation; + + b3BodyState* stateB = indexB == B3_NULL_INDEX ? &dummyState : states + indexB; + b3Vec3 vB = stateB->linearVelocity; + b3Vec3 wB = stateB->angularVelocity; + b3Quat dqB = stateB->deltaRotation; + + b3Vec3 dp = b3Sub( stateB->deltaPosition, stateA->deltaPosition ); + b3Softness softness = contactConstraint->softness; + float friction = contactConstraint->friction; + float rollingResistance = contactConstraint->rollingResistance; + + for ( int j = 0; j < manifoldCount; ++j ) + { + b3ManifoldConstraint* constraint = contactConstraint->constraints + j; + + int pointCount = constraint->pointCount; + b3Vec3 normal = constraint->normal; + + float totalNormalImpulse = 0.0f; + float totalTwistLimit = 0.0f; + + for ( int pointIndex = 0; pointIndex < pointCount; ++pointIndex ) + { + b3ManifoldConstraintPoint* cp = constraint->points + pointIndex; + + // Fixed anchor points for applying impulses + b3Vec3 rA = cp->rA; + b3Vec3 rB = cp->rB; + + // compute current separation + // this is subject to round-off error if the anchor is far from the body center of mass + b3Vec3 ds = b3Add( dp, b3Sub( b3RotateVector( dqB, rB ), b3RotateVector( dqA, rA ) ) ); + float s = b3Dot( ds, normal ) + cp->baseSeparation; + + 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 = b3MaxFloat( softness.massScale * softness.biasRate * s, -contactSpeed ); + massScale = softness.massScale; + impulseScale = softness.impulseScale; + } + + // relative normal velocity at contact + b3Vec3 vrA = b3Add( vA, b3Cross( wA, rA ) ); + b3Vec3 vrB = b3Add( vB, b3Cross( wB, rB ) ); + float vn = b3Dot( b3Sub( vrB, vrA ), normal ); + + // incremental normal impulse + float deltaImpulse = -cp->normalMass * ( massScale * vn + velocityBias ) - impulseScale * cp->normalImpulse; + + // clamp the accumulated impulse + float newImpulse = b3MaxFloat( cp->normalImpulse + deltaImpulse, 0.0f ); + deltaImpulse = newImpulse - cp->normalImpulse; + cp->normalImpulse = newImpulse; + cp->totalNormalImpulse += newImpulse; + + totalNormalImpulse += newImpulse; + totalTwistLimit += cp->leverArm * cp->normalImpulse; + + // apply normal impulse + b3Vec3 P = b3MulSV( deltaImpulse, normal ); + vA = b3MulSub( vA, mA, P ); + wA = b3Sub( wA, b3MulMV( iA, b3Cross( rA, P ) ) ); + + vB = b3MulAdd( vB, mB, P ); + wB = b3Add( wB, b3MulMV( iB, b3Cross( rB, P ) ) ); + } + + // No friction when applying bias + if ( useBias == true ) + { + // Go to next manifold + continue; + } + + // Central twist friction + { + float twistSpeed = b3Dot( constraint->normal, b3Sub( wB, wA ) ); + float maxImpulse = friction * totalTwistLimit; + float deltaImpulse = -constraint->twistMass * twistSpeed; + float oldImpulse = constraint->twistImpulse; + constraint->twistImpulse = b3ClampFloat( oldImpulse + deltaImpulse, -maxImpulse, maxImpulse ); + deltaImpulse = constraint->twistImpulse - oldImpulse; + + wA = b3Sub( wA, b3MulMV( iA, b3MulSV( deltaImpulse, constraint->normal ) ) ); + wB = b3Add( wB, b3MulMV( iB, b3MulSV( deltaImpulse, constraint->normal ) ) ); + } + + // Rolling resistance + if ( rollingResistance > 0.0f ) + { + b3Vec3 deltaImpulse = b3Neg( b3MulMV( contactConstraint->rollingMass, b3Sub( wB, wA ) ) ); + b3Vec3 oldImpulse = constraint->rollingImpulse; + constraint->rollingImpulse = b3Add( oldImpulse, deltaImpulse ); + + float maxImpulse = rollingResistance * totalNormalImpulse; + float magSqr = b3Dot( constraint->rollingImpulse, constraint->rollingImpulse ); + if ( magSqr > maxImpulse * maxImpulse + FLT_EPSILON ) + { + constraint->rollingImpulse = b3MulSV( maxImpulse / sqrtf( magSqr ), constraint->rollingImpulse ); + } + + deltaImpulse = b3Sub( constraint->rollingImpulse, oldImpulse ); + + wA = b3Sub( wA, b3MulMV( iA, deltaImpulse ) ); + wB = b3Add( wB, b3MulMV( iB, deltaImpulse ) ); + } + + // Central friction + { + b3Vec3 tangent1 = constraint->tangent1; + b3Vec3 tangent2 = constraint->tangent2; + + // Fixed anchor points for applying impulses + b3Vec3 rA = constraint->originA; + b3Vec3 rB = constraint->originB; + + // Relative tangent velocity at contact + b3Vec3 vrA = b3Add( vA, b3Cross( wA, rA ) ); + b3Vec3 vrB = b3Add( vB, b3Cross( wB, rB ) ); + b3Vec3 vr = b3Sub( vrB, vrA ); + b3Vec2 vt = { + b3Dot( vr, tangent1 ) - constraint->tangentVelocity1, + b3Dot( vr, tangent2 ) - constraint->tangentVelocity2, + }; + + // Incremental tangent impulse + b3Vec2 tm = b3MulMV2( constraint->tangentMass, vt ); + b3Vec2 deltaImpulse = { -tm.x, -tm.y }; + b3Vec2 newImpulse = { + constraint->frictionImpulse.x + deltaImpulse.x, + constraint->frictionImpulse.y + deltaImpulse.y, + }; + + float maxImpulse = friction * totalNormalImpulse; + + // Clamp the accumulated impulse + float lengthSquared = b3Dot2( newImpulse, newImpulse ); + if ( lengthSquared > maxImpulse * maxImpulse ) + { + float scale = maxImpulse / sqrtf( lengthSquared ); + newImpulse.x *= scale; + newImpulse.y *= scale; + } + deltaImpulse = b3Sub2( newImpulse, constraint->frictionImpulse ); + constraint->frictionImpulse = newImpulse; + + // Apply delta impulse + b3Vec3 P = b3Blend2( deltaImpulse.x, tangent1, deltaImpulse.y, tangent2 ); + vA = b3MulSub( vA, mA, P ); + wA = b3Sub( wA, b3MulMV( iA, b3Cross( rA, P ) ) ); + vB = b3MulAdd( vB, mB, P ); + wB = b3Add( wB, b3MulMV( iB, b3Cross( rB, P ) ) ); + } + } + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->linearVelocity = vA; + stateA->angularVelocity = wA; + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->linearVelocity = vB; + stateB->angularVelocity = wB; + } + } +} + +void b3ApplyRestitution_Mesh( b3SolverBlock block, b3StepContext* context ) +{ + b3World* world = context->world; + b3GraphColor* color = world->constraintGraph.colors + block.colorIndex; + b3BodyState* states = context->states; + b3ContactConstraint* constraints = color->contactConstraints; + + // This is a dummy state to represent a static body because static bodies don't have a solver body. + b3BodyState dummyState = b3_identityBodyState; + + int startIndex = block.startIndex; + int endIndex = startIndex + block.count; + + float threshold = context->world->restitutionThreshold; + + for ( int constraintIndex = startIndex; constraintIndex < endIndex; ++constraintIndex ) + { + const b3ContactConstraint* contactConstraint = constraints + constraintIndex; + float restitution = contactConstraint->restitution; + if ( restitution == 0.0f ) + { + continue; + } + + int indexA = contactConstraint->indexA; + int indexB = contactConstraint->indexB; + + b3BodyState* stateA = indexA == B3_NULL_INDEX ? &dummyState : states + indexA; + b3BodyState* stateB = indexB == B3_NULL_INDEX ? &dummyState : states + indexB; + + b3Vec3 vA = stateA->linearVelocity; + b3Vec3 wA = stateA->angularVelocity; + b3Vec3 vB = stateB->linearVelocity; + b3Vec3 wB = stateB->angularVelocity; + + float mA = contactConstraint->invMassA; + b3Matrix3 iA = contactConstraint->invIA; + float mB = contactConstraint->invMassB; + b3Matrix3 iB = contactConstraint->invIB; + + int manifoldCount = contactConstraint->manifoldCount; + for ( int manifoldIndex = 0; manifoldIndex < manifoldCount; ++manifoldIndex ) + { + b3ManifoldConstraint* cm = contactConstraint->constraints + manifoldIndex; + + b3Vec3 normal = cm->normal; + int pointCount = cm->pointCount; + B3_ASSERT( 0 < pointCount && pointCount <= B3_MAX_MANIFOLD_POINTS ); + + for ( int pointIndex = 0; pointIndex < pointCount; ++pointIndex ) + { + b3ManifoldConstraintPoint* cp = cm->points + pointIndex; + + // If the total 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 + b3Vec3 rA = cp->rA; + b3Vec3 rB = cp->rB; + + // relative normal velocity at contact + b3Vec3 vrB = b3Add( vB, b3Cross( wB, rB ) ); + b3Vec3 vrA = b3Add( vA, b3Cross( wA, rA ) ); + float vn = b3Dot( b3Sub( vrB, vrA ), normal ); + + // compute normal impulse + float impulse = -cp->normalMass * ( vn + restitution * cp->relativeVelocity ); + + // clamp the accumulated impulse + float newImpulse = b3MaxFloat( cp->normalImpulse + impulse, 0.0f ); + impulse = newImpulse - cp->normalImpulse; + cp->normalImpulse = newImpulse; + cp->totalNormalImpulse += impulse; + + // apply contact impulse + b3Vec3 P = b3MulSV( impulse, normal ); + vA = b3MulSub( vA, mA, P ); + wA = b3Sub( wA, b3MulMV( iA, b3Cross( rA, P ) ) ); + vB = b3MulAdd( vB, mB, P ); + wB = b3Add( wB, b3MulMV( iB, b3Cross( rB, P ) ) ); + } + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->linearVelocity = vA; + stateA->angularVelocity = wA; + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->linearVelocity = vB; + stateB->angularVelocity = wB; + } + } + } +} + +// Don't need to use spans for colors for this because the constraint to contact association +// is already linked by pointer. +void b3StoreImpulses_Mesh( b3SolverBlock block, b3StepContext* context, int workerIndex ) +{ + b3World* world = context->world; + b3ContactConstraint* base = context->contactConstraints; + b3TaskContext* taskContext = world->taskContexts.data + workerIndex; + b3BitSet* hitEventBitSet = &taskContext->hitEventBitSet; + bool hasHitEvents = taskContext->hasHitEvents; + float negHitThreshold = -world->hitEventThreshold; + + for ( int i = block.startIndex; i < block.startIndex + block.count; ++i ) + { + b3ContactConstraint* contactConstraint = base + i; + + // Having this contact pointer simplifies impulse storage + b3Contact* contact = contactConstraint->contact; + + int manifoldCount = contactConstraint->manifoldCount; + B3_ASSERT( manifoldCount == contact->manifoldCount ); + + bool checkHitEvents = ( contact->flags & b3_simEnableHitEvent ) != 0; + bool flagged = false; + + for ( int manifoldIndex = 0; manifoldIndex < manifoldCount; ++manifoldIndex ) + { + b3Manifold* manifold = contact->manifolds + manifoldIndex; + b3ManifoldConstraint* constraint = contactConstraint->constraints + manifoldIndex; + manifold->twistImpulse = constraint->twistImpulse; + manifold->frictionImpulse = b3Blend2( constraint->frictionImpulse.x, constraint->tangent1, + constraint->frictionImpulse.y, constraint->tangent2 ); + manifold->rollingImpulse = constraint->rollingImpulse; + + int count = constraint->pointCount; + B3_ASSERT( count == manifold->pointCount ); + for ( int pointIndex = 0; pointIndex < count; ++pointIndex ) + { + b3ManifoldConstraintPoint* cp = constraint->points + pointIndex; + b3ManifoldPoint* mp = manifold->points + pointIndex; + mp->normalImpulse = cp->normalImpulse; + mp->totalNormalImpulse = cp->totalNormalImpulse; + mp->normalVelocity = cp->relativeVelocity; + + if ( checkHitEvents && flagged == false && + mp->normalVelocity < negHitThreshold && mp->totalNormalImpulse > 0.0f ) + { + b3SetBit( hitEventBitSet, contact->contactId ); + hasHitEvents = true; + flagged = true; + } + } + } + } + + taskContext->hasHitEvents = hasHitEvents; +} + +#if defined( B3_SIMD_NEON ) + +#include + +// wide float holds 4 numbers +typedef float32x4_t b3FloatW; + +#elif defined( B3_SIMD_SSE2 ) + +#include + +// wide float holds 4 numbers +typedef __m128 b3FloatW; + +#else + +// scalar math +typedef struct b3FloatW +{ + float x, y, z, w; +} b3FloatW; + +#endif + +// Wide vec2 +typedef struct b3Vec2W +{ + b3FloatW x, y; +} b3Vec2W; + +// Wide vec3 +typedef struct b3Vec3W +{ + b3FloatW X, Y, Z; +} b3Vec3W; + +// Wide quaternion +typedef struct b3QuatW +{ + b3Vec3W V; + b3FloatW S; +} b3QuatW; + +// Wide symmetric matrix2 +typedef struct b3SymMatrix2W +{ + b3FloatW cxx, cxy, cyy; +} b3SymMatrix2W; + +// Wide symmetric matrix3 +typedef struct b3SymMatrix3W +{ + b3FloatW cxx, cxy, cxz, cyy, cyz, czz; +} b3SymMatrix3W; + +#if defined( B3_SIMD_NEON ) + +static inline b3FloatW b3ZeroW( void ) +{ + return vdupq_n_f32( 0.0f ); +} + +static inline b3FloatW b3SplatW( float scalar ) +{ + return vdupq_n_f32( scalar ); +} + +static inline b3FloatW b3NegW( b3FloatW a ) +{ + return vnegq_f32( a ); +} + +static inline b3FloatW b3SetW( float a, float b, float c, float d ) +{ + float32_t array[4] = { a, b, c, d }; + return vld1q_f32( array ); +} + +static inline b3FloatW b3AddW( b3FloatW a, b3FloatW b ) +{ + return vaddq_f32( a, b ); +} + +static inline b3FloatW b3SubW( b3FloatW a, b3FloatW b ) +{ + return vsubq_f32( a, b ); +} + +static inline b3FloatW b3MulW( b3FloatW a, b3FloatW b ) +{ + return vmulq_f32( a, b ); +} + +static inline b3FloatW b3DivW( b3FloatW a, b3FloatW b ) +{ + return vdivq_f32( a, b ); +} + +static inline b3FloatW b3SqrtW( b3FloatW a ) +{ + return vsqrtq_f32( a ); +} + +// Cannot use real FMA because it doesn't match the non-SIMD path +static inline b3FloatW b3MulAddW( b3FloatW a, b3FloatW b, b3FloatW c ) +{ + return vaddq_f32( a, vmulq_f32( b, c ) ); +} + +// static inline b3FloatW b3MulSubW( b3FloatW a, b3FloatW b, b3FloatW c ) +//{ +// return vsubq_f32( a, vmulq_f32( b, c ) ); +// } + +static inline b3FloatW b3MinW( b3FloatW a, b3FloatW b ) +{ + return vminq_f32( a, b ); +} + +static inline b3FloatW b3MaxW( b3FloatW a, b3FloatW b ) +{ + return vmaxq_f32( a, b ); +} + +// clamp a to [-b, b] +static inline b3FloatW b3SymClampW( b3FloatW a, b3FloatW b ) +{ + b3FloatW nb = b3NegW( b ); + b3FloatW c = b3MaxW( nb, a ); + return b3MinW( c, b ); +} + +static inline b3FloatW b3OrW( b3FloatW a, b3FloatW b ) +{ + return vreinterpretq_f32_u32( vorrq_u32( vreinterpretq_u32_f32( a ), vreinterpretq_u32_f32( b ) ) ); +} + +static inline b3FloatW b3GreaterThanW( b3FloatW a, b3FloatW b ) +{ + return vreinterpretq_f32_u32( vcgtq_f32( a, b ) ); +} + +static inline b3FloatW b3EqualsW( b3FloatW a, b3FloatW b ) +{ + return vreinterpretq_f32_u32( vceqq_f32( a, b ) ); +} + +static inline bool b3AllZeroW( b3FloatW a ) +{ + // Create a zero vector for comparison + b3FloatW 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 b3FloatW b3BlendW( b3FloatW a, b3FloatW b, b3FloatW mask ) +{ + uint32x4_t mask32 = vreinterpretq_u32_f32( mask ); + return vbslq_f32( mask32, b, a ); +} + +#elif defined( B3_SIMD_SSE2 ) + +static inline b3FloatW b3ZeroW( void ) +{ + return _mm_setzero_ps(); +} + +static inline b3FloatW b3SplatW( float scalar ) +{ + return _mm_set1_ps( scalar ); +} + +static inline b3FloatW b3NegW( b3FloatW a ) +{ + // 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 + return _mm_xor_ps( a, mask ); +} + +static inline b3FloatW b3SetW( float a, float b, float c, float d ) +{ + return _mm_setr_ps( a, b, c, d ); +} + +static inline b3FloatW b3AddW( b3FloatW a, b3FloatW b ) +{ + return _mm_add_ps( a, b ); +} + +static inline b3FloatW b3SubW( b3FloatW a, b3FloatW b ) +{ + return _mm_sub_ps( a, b ); +} + +static inline b3FloatW b3MulW( b3FloatW a, b3FloatW b ) +{ + return _mm_mul_ps( a, b ); +} + +static inline b3FloatW b3DivW( b3FloatW a, b3FloatW b ) +{ + return _mm_div_ps( a, b ); +} + +static inline b3FloatW b3SqrtW( b3FloatW a ) +{ + return _mm_sqrt_ps( a ); +} + +static inline b3FloatW b3MulAddW( b3FloatW a, b3FloatW b, b3FloatW c ) +{ + return _mm_add_ps( a, _mm_mul_ps( b, c ) ); +} + +// static inline b3FloatW b3MulSubW( b3FloatW a, b3FloatW b, b3FloatW c ) +//{ +// return _mm_sub_ps( a, _mm_mul_ps( b, c ) ); +// } + +static inline b3FloatW b3MinW( b3FloatW a, b3FloatW b ) +{ + return _mm_min_ps( a, b ); +} + +static inline b3FloatW b3MaxW( b3FloatW a, b3FloatW b ) +{ + return _mm_max_ps( a, b ); +} + +// clamp a to [-b, b] +static inline b3FloatW b3SymClampW( b3FloatW a, b3FloatW b ) +{ + b3FloatW nb = b3NegW( b ); + b3FloatW c = b3MaxW( nb, a ); + return b3MinW( c, b ); +} + +static inline b3FloatW b3OrW( b3FloatW a, b3FloatW b ) +{ + return _mm_or_ps( a, b ); +} + +static inline b3FloatW b3GreaterThanW( b3FloatW a, b3FloatW b ) +{ + return _mm_cmpgt_ps( a, b ); +} + +static inline b3FloatW b3EqualsW( b3FloatW a, b3FloatW b ) +{ + return _mm_cmpeq_ps( a, b ); +} + +static inline bool b3AllZeroW( b3FloatW a ) +{ + // Compare each element with zero + b3FloatW zero = _mm_setzero_ps(); + b3FloatW 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 b3FloatW b3BlendW( b3FloatW a, b3FloatW b, b3FloatW mask ) +{ + return _mm_or_ps( _mm_and_ps( mask, b ), _mm_andnot_ps( mask, a ) ); +} + +#else + +static inline b3FloatW b3ZeroW( void ) +{ + return (b3FloatW){ 0.0f, 0.0f, 0.0f, 0.0f }; +} + +static inline b3FloatW b3SplatW( float scalar ) +{ + return (b3FloatW){ scalar, scalar, scalar, scalar }; +} + +static inline b3FloatW b3NegW( b3FloatW a ) +{ + return (b3FloatW){ -a.x, -a.y, -a.z, -a.w }; +} + +static inline b3FloatW b3AddW( b3FloatW a, b3FloatW b ) +{ + return (b3FloatW){ a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w }; +} + +static inline b3FloatW b3SubW( b3FloatW a, b3FloatW b ) +{ + return (b3FloatW){ a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w }; +} + +static inline b3FloatW b3MulW( b3FloatW a, b3FloatW b ) +{ + return (b3FloatW){ a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w }; +} + +static inline b3FloatW b3DivW( b3FloatW a, b3FloatW b ) +{ + return (b3FloatW){ a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w }; +} + +static inline b3FloatW b3SqrtW( b3FloatW a ) +{ + return (b3FloatW){ sqrtf( a.x ), sqrtf( a.y ), sqrtf( a.z ), sqrtf( a.w ) }; +} + +static inline b3FloatW b3MulAddW( b3FloatW a, b3FloatW b, b3FloatW c ) +{ + return (b3FloatW){ 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 b3FloatW b3MulSubW( b3FloatW a, b3FloatW b, b3FloatW c ) +//{ +// return { 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 b3FloatW b3MinW( b3FloatW a, b3FloatW b ) +//{ +// b3FloatW 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 b3FloatW b3MaxW( b3FloatW a, b3FloatW b ) +{ + b3FloatW 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; +} + +// clamp a to [-b, b] +static inline b3FloatW b3SymClampW( b3FloatW a, b3FloatW b ) +{ + b3FloatW 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; + r.x = r.x <= -b.x ? -b.x : r.x; + r.y = r.y <= -b.y ? -b.y : r.y; + r.z = r.z <= -b.z ? -b.z : r.z; + r.w = r.w <= -b.w ? -b.w : r.w; + return r; +} + +static inline b3FloatW b3OrW( b3FloatW a, b3FloatW b ) +{ + b3FloatW 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 b3FloatW b3GreaterThanW( b3FloatW a, b3FloatW b ) +{ + b3FloatW 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 b3FloatW b3EqualsW( b3FloatW a, b3FloatW b ) +{ + b3FloatW 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 b3AllZeroW( b3FloatW 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 b3FloatW b3BlendW( b3FloatW a, b3FloatW b, b3FloatW mask ) +{ + b3FloatW 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 + +// s * a +static inline b3Vec3W b3MulSVW( b3FloatW s, b3Vec3W a ) +{ + return (b3Vec3W){ b3MulW( s, a.X ), b3MulW( s, a.Y ), b3MulW( s, a.Z ) }; +} + +// a - s * b +static inline b3Vec3W b3MulSubSVW( b3Vec3W a, b3FloatW s, b3Vec3W b ) +{ + return (b3Vec3W){ b3SubW( a.X, b3MulW( s, b.X ) ), b3SubW( a.Y, b3MulW( s, b.Y ) ), b3SubW( a.Z, b3MulW( s, b.Z ) ) }; +} + +// a + s * b +static inline b3Vec3W b3MulAddSVW( b3Vec3W a, b3FloatW s, b3Vec3W b ) +{ + return (b3Vec3W){ b3AddW( a.X, b3MulW( s, b.X ) ), b3AddW( a.Y, b3MulW( s, b.Y ) ), b3AddW( a.Z, b3MulW( s, b.Z ) ) }; +} + +// a + b +static inline b3Vec2W b3AddV2W( b3Vec2W a, b3Vec2W b ) +{ + return (b3Vec2W){ + b3AddW( a.x, b.x ), + b3AddW( a.y, b.y ), + }; +} + +// a - b +static inline b3Vec3W b3SubVW( b3Vec3W a, b3Vec3W b ) +{ + return (b3Vec3W){ + b3SubW( a.X, b.X ), + b3SubW( a.Y, b.Y ), + b3SubW( a.Z, b.Z ), + }; +} + +// a + b +static inline b3Vec3W b3AddVW( b3Vec3W a, b3Vec3W b ) +{ + return (b3Vec3W){ + b3AddW( a.X, b.X ), + b3AddW( a.Y, b.Y ), + b3AddW( a.Z, b.Z ), + }; +} + +// m * a +static inline b3Vec2W b3MulMV2W( b3SymMatrix2W m, b3Vec2W a ) +{ + b3Vec2W b = { + b3AddW( b3MulW( m.cxx, a.x ), b3MulW( m.cxy, a.y ) ), + b3AddW( b3MulW( m.cxy, a.x ), b3MulW( m.cyy, a.y ) ), + }; + + return b; +} + +// m * a +static inline b3Vec3W b3MulMVW( b3SymMatrix3W m, b3Vec3W a ) +{ + b3Vec3W b = { + b3AddW( b3MulW( m.cxx, a.X ), b3AddW( b3MulW( m.cxy, a.Y ), b3MulW( m.cxz, a.Z ) ) ), + b3AddW( b3MulW( m.cxy, a.X ), b3AddW( b3MulW( m.cyy, a.Y ), b3MulW( m.cyz, a.Z ) ) ), + b3AddW( b3MulW( m.cxz, a.X ), b3AddW( b3MulW( m.cyz, a.Y ), b3MulW( m.czz, a.Z ) ) ), + }; + + return b; +} + +// a - m * b +static inline b3Vec3W b3MulSubMVW( b3Vec3W a, b3SymMatrix3W m, b3Vec3W b ) +{ + b3Vec3W c = { + b3AddW( b3MulW( m.cxx, b.X ), b3AddW( b3MulW( m.cxy, b.Y ), b3MulW( m.cxz, b.Z ) ) ), + b3AddW( b3MulW( m.cxy, b.X ), b3AddW( b3MulW( m.cyy, b.Y ), b3MulW( m.cyz, b.Z ) ) ), + b3AddW( b3MulW( m.cxz, b.X ), b3AddW( b3MulW( m.cyz, b.Y ), b3MulW( m.czz, b.Z ) ) ), + }; + + return (b3Vec3W){ b3SubW( a.X, c.X ), b3SubW( a.Y, c.Y ), b3SubW( a.Z, c.Z ) }; +} + +// a + m * b +static inline b3Vec3W b3MulAddMVW( b3Vec3W a, b3SymMatrix3W m, b3Vec3W b ) +{ + b3Vec3W c = { + b3AddW( b3MulW( m.cxx, b.X ), b3AddW( b3MulW( m.cxy, b.Y ), b3MulW( m.cxz, b.Z ) ) ), + b3AddW( b3MulW( m.cxy, b.X ), b3AddW( b3MulW( m.cyy, b.Y ), b3MulW( m.cyz, b.Z ) ) ), + b3AddW( b3MulW( m.cxz, b.X ), b3AddW( b3MulW( m.cyz, b.Y ), b3MulW( m.czz, b.Z ) ) ), + }; + + return (b3Vec3W){ b3AddW( a.X, c.X ), b3AddW( a.Y, c.Y ), b3AddW( a.Z, c.Z ) }; +} + +static inline b3FloatW b3DotW( b3Vec3W a, b3Vec3W b ) +{ + return b3AddW( b3AddW( b3MulW( a.X, b.X ), b3MulW( a.Y, b.Y ) ), b3MulW( a.Z, b.Z ) ); +} + +static inline b3Vec3W b3CrossW( b3Vec3W a, b3Vec3W b ) +{ + b3Vec3W c; + c.X = b3SubW( b3MulW( a.Y, b.Z ), b3MulW( a.Z, b.Y ) ); + c.Y = b3SubW( b3MulW( a.Z, b.X ), b3MulW( a.X, b.Z ) ); + c.Z = b3SubW( b3MulW( a.X, b.Y ), b3MulW( a.Y, b.X ) ); + return c; +} + +static inline b3Vec3W b3RotateVectorW( b3QuatW q, b3Vec3W a ) +{ + b3Vec3W t1 = b3CrossW( q.V, a ); + b3Vec3W t2; + t2.X = b3MulAddW( t1.X, q.S, a.X ); + t2.Y = b3MulAddW( t1.Y, q.S, a.Y ); + t2.Z = b3MulAddW( t1.Z, q.S, a.Z ); + b3Vec3W t3 = b3CrossW( q.V, t2 ); + b3FloatW two = b3SplatW( 2.0f ); + b3Vec3W b; + b.X = b3MulAddW( a.X, two, t3.X ); + b.Y = b3MulAddW( a.Y, two, t3.Y ); + b.Z = b3MulAddW( a.Z, two, t3.Z ); + return b; +} + +// 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 b3ContactConstraintPointWide +{ + b3Vec3W anchorAs, anchorBs; + b3FloatW baseSeparations; + b3FloatW normalImpulses; + b3FloatW totalNormalImpulses; + b3FloatW normalMasses; + b3FloatW leverArms; + b3FloatW relativeVelocities; +} b3ContactConstraintPointWide; + +// Solves four points +typedef struct b3ContactConstraintWide +{ + // These are base 1 + int indexA[B3_SIMD_WIDTH]; + int indexB[B3_SIMD_WIDTH]; + + b3FloatW invMassA, invMassB; + b3SymMatrix3W invIA, invIB; + b3Vec3W normal; + + // todo test computing the tangents on the fly, at least tangent2 + b3Vec3W tangent1; + b3Vec3W tangent2; + + b3Vec3W originA, originB; + b3FloatW twistMass; + b3FloatW twistImpulse; + b3SymMatrix2W tangentMass; + b3Vec2W frictionImpulse; + b3SymMatrix3W rollingMass; + b3Vec3W rollingImpulse; + b3FloatW friction; + b3FloatW rollingResistance; + b3FloatW tangentVelocity1; + b3FloatW tangentVelocity2; + + b3FloatW biasRate; + b3FloatW massScale; + b3FloatW impulseScale; + b3FloatW restitution; + + b3Manifold* manifolds[B3_SIMD_WIDTH]; + + // todo store the maximum point count per wide constraint + // to make this work I need zero initialization which is too + // expensive for all the wide constraint data. Instead + // the graph color should store the point count as a compact secondary + // transient array with zero initialization. + b3ContactConstraintPointWide points[B3_MAX_MANIFOLD_POINTS]; + +} b3ContactConstraintWide; + +int b3GetWideContactConstraintByteCount( void ) +{ + return sizeof( b3ContactConstraintWide ); +} + +// wide version of b3BodyState +typedef struct b3BodyStateW +{ + b3Vec3W v; + b3Vec3W w; + b3Vec3W dp; + b3QuatW dq; +} b3BodyStateW; + +#if defined( B3_SIMD_SSE2 ) || defined( B3_SIMD_NEON ) + +static b3BodyStateW b3GatherBodies( const b3BodyState* states, int* indices ) +{ + b3BodyState dummy = { 0 }; + dummy.deltaRotation.s = 1.0f; + + // Indices are 0 for null + b3BodyState b1 = indices[0] == 0 ? dummy : states[indices[0] - 1]; + b3BodyState b2 = indices[1] == 0 ? dummy : states[indices[1] - 1]; + b3BodyState b3 = indices[2] == 0 ? dummy : states[indices[2] - 1]; + b3BodyState b4 = indices[3] == 0 ? dummy : states[indices[3] - 1]; + + b3BodyStateW s; + s.v.X = b3SetW( b1.linearVelocity.x, b2.linearVelocity.x, b3.linearVelocity.x, b4.linearVelocity.x ); + s.v.Y = b3SetW( b1.linearVelocity.y, b2.linearVelocity.y, b3.linearVelocity.y, b4.linearVelocity.y ); + s.v.Z = b3SetW( b1.linearVelocity.z, b2.linearVelocity.z, b3.linearVelocity.z, b4.linearVelocity.z ); + + s.w.X = b3SetW( b1.angularVelocity.x, b2.angularVelocity.x, b3.angularVelocity.x, b4.angularVelocity.x ); + s.w.Y = b3SetW( b1.angularVelocity.y, b2.angularVelocity.y, b3.angularVelocity.y, b4.angularVelocity.y ); + s.w.Z = b3SetW( b1.angularVelocity.z, b2.angularVelocity.z, b3.angularVelocity.z, b4.angularVelocity.z ); + + s.dp.X = b3SetW( b1.deltaPosition.x, b2.deltaPosition.x, b3.deltaPosition.x, b4.deltaPosition.x ); + s.dp.Y = b3SetW( b1.deltaPosition.y, b2.deltaPosition.y, b3.deltaPosition.y, b4.deltaPosition.y ); + s.dp.Z = b3SetW( b1.deltaPosition.z, b2.deltaPosition.z, b3.deltaPosition.z, b4.deltaPosition.z ); + + s.dq.V.X = b3SetW( b1.deltaRotation.v.x, b2.deltaRotation.v.x, b3.deltaRotation.v.x, b4.deltaRotation.v.x ); + s.dq.V.Y = b3SetW( b1.deltaRotation.v.y, b2.deltaRotation.v.y, b3.deltaRotation.v.y, b4.deltaRotation.v.y ); + s.dq.V.Z = b3SetW( b1.deltaRotation.v.z, b2.deltaRotation.v.z, b3.deltaRotation.v.z, b4.deltaRotation.v.z ); + s.dq.S = b3SetW( b1.deltaRotation.s, b2.deltaRotation.s, b3.deltaRotation.s, b4.deltaRotation.s ); + return s; +} + +// This writes only the velocities back to the solver bodies +static void b3ScatterBodies( b3BodyState* states, int* indices, const b3BodyStateW* simdBody ) +{ + const float* vx = (const float*)&simdBody->v.X; + const float* vy = (const float*)&simdBody->v.Y; + const float* vz = (const float*)&simdBody->v.Z; + const float* wx = (const float*)&simdBody->w.X; + const float* wy = (const float*)&simdBody->w.Y; + const float* wz = (const float*)&simdBody->w.Z; + + // I don't use any dummy body in the body array because this will lead to multithreaded sharing and the + // associated cache flushing. + + // Warning: indices start at 1 with 0 indicating null + + if ( indices[0] != 0 && ( states[indices[0] - 1].flags & b3_dynamicFlag ) != 0 ) + { + b3BodyState* s = states + ( indices[0] - 1 ); + + b3Vec3 v = { vx[0], vy[0], vz[0] }; + b3Vec3 w = { wx[0], wy[0], wz[0] }; + + uint32_t flags = s->flags; + if ( flags & b3_allLocks ) + { + v.x = ( flags & b3_lockLinearX ) ? 0.0f : v.x; + v.y = ( flags & b3_lockLinearY ) ? 0.0f : v.y; + v.z = ( flags & b3_lockLinearZ ) ? 0.0f : v.z; + w.x = ( flags & b3_lockAngularX ) ? 0.0f : w.x; + w.y = ( flags & b3_lockAngularY ) ? 0.0f : w.y; + w.z = ( flags & b3_lockAngularZ ) ? 0.0f : w.z; + } + + s->linearVelocity = v; + s->angularVelocity = w; + } + + if ( indices[1] != 0 && ( states[indices[1] - 1].flags & b3_dynamicFlag ) != 0 ) + { + b3BodyState* s = states + ( indices[1] - 1 ); + + b3Vec3 v = { vx[1], vy[1], vz[1] }; + b3Vec3 w = { wx[1], wy[1], wz[1] }; + + uint32_t flags = s->flags; + if ( flags & b3_allLocks ) + { + v.x = ( flags & b3_lockLinearX ) ? 0.0f : v.x; + v.y = ( flags & b3_lockLinearY ) ? 0.0f : v.y; + v.z = ( flags & b3_lockLinearZ ) ? 0.0f : v.z; + w.x = ( flags & b3_lockAngularX ) ? 0.0f : w.x; + w.y = ( flags & b3_lockAngularY ) ? 0.0f : w.y; + w.z = ( flags & b3_lockAngularZ ) ? 0.0f : w.z; + } + + s->linearVelocity = v; + s->angularVelocity = w; + } + + if ( indices[2] != 0 && ( states[indices[2] - 1].flags & b3_dynamicFlag ) != 0 ) + { + b3BodyState* s = states + ( indices[2] - 1 ); + + b3Vec3 v = { vx[2], vy[2], vz[2] }; + b3Vec3 w = { wx[2], wy[2], wz[2] }; + + uint32_t flags = s->flags; + if ( flags & b3_allLocks ) + { + v.x = ( flags & b3_lockLinearX ) ? 0.0f : v.x; + v.y = ( flags & b3_lockLinearY ) ? 0.0f : v.y; + v.z = ( flags & b3_lockLinearZ ) ? 0.0f : v.z; + w.x = ( flags & b3_lockAngularX ) ? 0.0f : w.x; + w.y = ( flags & b3_lockAngularY ) ? 0.0f : w.y; + w.z = ( flags & b3_lockAngularZ ) ? 0.0f : w.z; + } + + s->linearVelocity = v; + s->angularVelocity = w; + } + + if ( indices[3] != 0 && ( states[indices[3] - 1].flags & b3_dynamicFlag ) != 0 ) + { + b3BodyState* s = states + ( indices[3] - 1 ); + + b3Vec3 v = { vx[3], vy[3], vz[3] }; + b3Vec3 w = { wx[3], wy[3], wz[3] }; + + uint32_t flags = s->flags; + if ( flags & b3_allLocks ) + { + v.x = ( flags & b3_lockLinearX ) ? 0.0f : v.x; + v.y = ( flags & b3_lockLinearY ) ? 0.0f : v.y; + v.z = ( flags & b3_lockLinearZ ) ? 0.0f : v.z; + w.x = ( flags & b3_lockAngularX ) ? 0.0f : w.x; + w.y = ( flags & b3_lockAngularY ) ? 0.0f : w.y; + w.z = ( flags & b3_lockAngularZ ) ? 0.0f : w.z; + } + + s->linearVelocity = v; + s->angularVelocity = w; + } +} + +#else // non-simd + +static b3BodyStateW b3GatherBodies( const b3BodyState* states, int* indices ) +{ + b3BodyState identity = b3_identityBodyState; + + b3BodyState s1 = indices[0] == 0 ? identity : states[indices[0] - 1]; + b3BodyState s2 = indices[1] == 0 ? identity : states[indices[1] - 1]; + b3BodyState s3 = indices[2] == 0 ? identity : states[indices[2] - 1]; + b3BodyState s4 = indices[3] == 0 ? identity : states[indices[3] - 1]; + + b3BodyStateW simdBody; + simdBody.v.X = (b3FloatW){ s1.linearVelocity.x, s2.linearVelocity.x, s3.linearVelocity.x, s4.linearVelocity.x }; + simdBody.v.Y = (b3FloatW){ s1.linearVelocity.y, s2.linearVelocity.y, s3.linearVelocity.y, s4.linearVelocity.y }; + simdBody.v.Z = (b3FloatW){ s1.linearVelocity.z, s2.linearVelocity.z, s3.linearVelocity.z, s4.linearVelocity.z }; + simdBody.w.X = (b3FloatW){ s1.angularVelocity.x, s2.angularVelocity.x, s3.angularVelocity.x, s4.angularVelocity.x }; + simdBody.w.Y = (b3FloatW){ s1.angularVelocity.y, s2.angularVelocity.y, s3.angularVelocity.y, s4.angularVelocity.y }; + simdBody.w.Z = (b3FloatW){ s1.angularVelocity.z, s2.angularVelocity.z, s3.angularVelocity.z, s4.angularVelocity.z }; + simdBody.dp.X = (b3FloatW){ s1.deltaPosition.x, s2.deltaPosition.x, s3.deltaPosition.x, s4.deltaPosition.x }; + simdBody.dp.Y = (b3FloatW){ s1.deltaPosition.y, s2.deltaPosition.y, s3.deltaPosition.y, s4.deltaPosition.y }; + simdBody.dp.Z = (b3FloatW){ s1.deltaPosition.z, s2.deltaPosition.z, s3.deltaPosition.z, s4.deltaPosition.z }; + simdBody.dq.V.X = (b3FloatW){ s1.deltaRotation.v.x, s2.deltaRotation.v.x, s3.deltaRotation.v.x, s4.deltaRotation.v.x }; + simdBody.dq.V.Y = (b3FloatW){ s1.deltaRotation.v.y, s2.deltaRotation.v.y, s3.deltaRotation.v.y, s4.deltaRotation.v.y }; + simdBody.dq.V.Z = (b3FloatW){ s1.deltaRotation.v.z, s2.deltaRotation.v.z, s3.deltaRotation.v.z, s4.deltaRotation.v.z }; + simdBody.dq.S = (b3FloatW){ 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 b3ScatterBodies( b3BodyState* states, int* indices, const b3BodyStateW* simdBody ) +{ + int index1 = indices[0] - 1; + if ( index1 != -1 && ( states[index1].flags & b3_dynamicFlag ) != 0 ) + { + b3BodyState* state = states + index1; + state->linearVelocity.x = simdBody->v.X.x; + state->linearVelocity.y = simdBody->v.Y.x; + state->linearVelocity.z = simdBody->v.Z.x; + state->angularVelocity.x = simdBody->w.X.x; + state->angularVelocity.y = simdBody->w.Y.x; + state->angularVelocity.z = simdBody->w.Z.x; + } + + int index2 = indices[1] - 1; + if ( index2 != -1 && ( states[index2].flags & b3_dynamicFlag ) != 0 ) + { + b3BodyState* state = states + index2; + state->linearVelocity.x = simdBody->v.X.y; + state->linearVelocity.y = simdBody->v.Y.y; + state->linearVelocity.z = simdBody->v.Z.y; + state->angularVelocity.x = simdBody->w.X.y; + state->angularVelocity.y = simdBody->w.Y.y; + state->angularVelocity.z = simdBody->w.Z.y; + } + + int index3 = indices[2] - 1; + if ( index3 != -1 && ( states[index3].flags & b3_dynamicFlag ) != 0 ) + { + b3BodyState* state = states + index3; + state->linearVelocity.x = simdBody->v.X.z; + state->linearVelocity.y = simdBody->v.Y.z; + state->linearVelocity.z = simdBody->v.Z.z; + state->angularVelocity.x = simdBody->w.X.z; + state->angularVelocity.y = simdBody->w.Y.z; + state->angularVelocity.z = simdBody->w.Z.z; + } + + int index4 = indices[3] - 1; + if ( index4 != -1 && ( states[index4].flags & b3_dynamicFlag ) != 0 ) + { + b3BodyState* state = states + index4; + state->linearVelocity.x = simdBody->v.X.w; + state->linearVelocity.y = simdBody->v.Y.w; + state->linearVelocity.z = simdBody->v.Z.w; + state->angularVelocity.x = simdBody->w.X.w; + state->angularVelocity.y = simdBody->w.Y.w; + state->angularVelocity.z = simdBody->w.Z.w; + } +} +#endif + +// Prepare convex contact constraints +void b3PrepareContacts_Convex( b3SolverBlock block, b3StepContext* context ) +{ + b3TracyCZoneNC( prepare_contact, "Prepare Contact", b3_colorYellow, true ); + b3World* world = context->world; + b3BodySim* sims = context->sims; + b3BodyState* states = context->states; +#if B3_ENABLE_VALIDATION + b3Body* bodies = world->bodies.data; +#endif + b3WidePrepareSpan* spans = context->widePrepareSpans; + b3ContactConstraintWide* wideBase = context->wideConstraints; + + // Stiffer for static contacts to avoid bodies getting pushed through the ground + b3Softness contactSoftness = context->contactSoftness; + b3Softness staticSoftness = context->staticSoftness; + + float warmStartScale = world->enableWarmStarting ? 1.0f : 0.0f; + + int wideIndex = block.startIndex; + int endWideIndex = block.startIndex + block.count; + + // Find color for start index. Linear search but fast. + int colorIndex = 0; + while ( spans[colorIndex + 1].start <= wideIndex ) + { + colorIndex += 1; + } + + // Loop over block + while ( wideIndex < endWideIndex ) + { + int colorWideStart = spans[colorIndex].start; + int colorWideEndIndex = b3MinInt( spans[colorIndex + 1].start, endWideIndex ); + int colorContactCount = spans[colorIndex].count; + int* contactIds = spans[colorIndex].contacts; + + // Loop over color + for ( ; wideIndex < colorWideEndIndex; ++wideIndex ) + { + b3ContactConstraintWide* constraint = wideBase + wideIndex; + int localWideIndex = wideIndex - colorWideStart; + + for ( int lane = 0; lane < B3_SIMD_WIDTH; ++lane ) + { + int contactIndex = B3_SIMD_WIDTH * localWideIndex + lane; + if ( contactIndex >= colorContactCount ) + { + // Remainder lanes were zeroed in solver setup. + break; + } + + int contactId = contactIds[contactIndex]; + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + B3_ASSERT( contact->manifoldCount == 1 ); + b3Manifold* manifold = contact->manifolds + 0; + + int indexA = contact->bodySimIndexA; + int indexB = contact->bodySimIndexB; + +#if B3_ENABLE_VALIDATION + b3Body* bodyA = bodies + contact->edges[0].bodyId; + int validIndexA = bodyA->setIndex == b3_awakeSet ? bodyA->localIndex : B3_NULL_INDEX; + b3Body* bodyB = bodies + contact->edges[1].bodyId; + int validIndexB = bodyB->setIndex == b3_awakeSet ? bodyB->localIndex : B3_NULL_INDEX; + B3_ASSERT( indexA == validIndexA ); + B3_ASSERT( indexB == validIndexB ); +#endif + + // 0 for null + constraint->indexA[lane] = indexA + 1; + constraint->indexB[lane] = indexB + 1; + constraint->manifolds[lane] = manifold; + + // Body A data + float mA; + b3Matrix3 iA; + b3Vec3 vA; + b3Vec3 wA; + + if ( indexA == B3_NULL_INDEX ) + { + mA = 0.0f; + iA = b3Mat3_zero; + vA = b3Vec3_zero; + wA = b3Vec3_zero; + } + else + { + b3BodySim* simA = sims + indexA; + mA = simA->invMass; + iA = simA->invInertiaWorld; + + b3BodyState* stateA = states + indexA; + vA = stateA->linearVelocity; + wA = stateA->angularVelocity; + } + + // Body B data + float mB; + b3Matrix3 iB; + b3Vec3 vB; + b3Vec3 wB; + + if ( indexB == B3_NULL_INDEX ) + { + mB = 0.0f; + iB = b3Mat3_zero; + vB = b3Vec3_zero; + wB = b3Vec3_zero; + } + else + { + b3BodySim* simB = sims + indexB; + mB = simB->invMass; + iB = simB->invInertiaWorld; + + b3BodyState* stateB = states + indexB; + vB = stateB->linearVelocity; + wB = stateB->angularVelocity; + } + + ( (float*)&constraint->invMassA )[lane] = mA; + ( (float*)&constraint->invMassB )[lane] = mB; + + ( (float*)&constraint->invIA.cxx )[lane] = iA.cx.x; + ( (float*)&constraint->invIA.cxy )[lane] = iA.cx.y; + ( (float*)&constraint->invIA.cxz )[lane] = iA.cx.z; + ( (float*)&constraint->invIA.cyy )[lane] = iA.cy.y; + ( (float*)&constraint->invIA.cyz )[lane] = iA.cy.z; + ( (float*)&constraint->invIA.czz )[lane] = iA.cz.z; + + ( (float*)&constraint->invIB.cxx )[lane] = iB.cx.x; + ( (float*)&constraint->invIB.cxy )[lane] = iB.cx.y; + ( (float*)&constraint->invIB.cxz )[lane] = iB.cx.z; + ( (float*)&constraint->invIB.cyy )[lane] = iB.cy.y; + ( (float*)&constraint->invIB.cyz )[lane] = iB.cy.z; + ( (float*)&constraint->invIB.czz )[lane] = iB.cz.z; + + b3Softness soft = ( indexA == B3_NULL_INDEX || indexB == B3_NULL_INDEX ) ? staticSoftness : contactSoftness; + + b3Vec3 normal = manifold->normal; + ( (float*)&constraint->normal.X )[lane] = normal.x; + ( (float*)&constraint->normal.Y )[lane] = normal.y; + ( (float*)&constraint->normal.Z )[lane] = normal.z; + + b3Vec3 tangent1 = b3Perp( normal ); + ( (float*)&constraint->tangent1.X )[lane] = tangent1.x; + ( (float*)&constraint->tangent1.Y )[lane] = tangent1.y; + ( (float*)&constraint->tangent1.Z )[lane] = tangent1.z; + + b3Vec3 tangent2 = b3Cross( tangent1, normal ); + ( (float*)&constraint->tangent2.X )[lane] = tangent2.x; + ( (float*)&constraint->tangent2.Y )[lane] = tangent2.y; + ( (float*)&constraint->tangent2.Z )[lane] = tangent2.z; + + ( (float*)&constraint->friction )[lane] = contact->friction; + ( (float*)&constraint->restitution )[lane] = contact->restitution; + ( (float*)&constraint->rollingResistance )[lane] = contact->rollingResistance; + + ( (float*)&constraint->tangentVelocity1 )[lane] = b3Dot( contact->tangentVelocity, tangent1 ); + ( (float*)&constraint->tangentVelocity2 )[lane] = b3Dot( contact->tangentVelocity, tangent2 ); + + ( (float*)&constraint->biasRate )[lane] = soft.biasRate; + ( (float*)&constraint->massScale )[lane] = soft.massScale; + ( (float*)&constraint->impulseScale )[lane] = soft.impulseScale; + + int pointCount = manifold->pointCount; + b3Vec3 originA = b3Vec3_zero; + b3Vec3 originB = b3Vec3_zero; + + for ( int pointIndex = 0; pointIndex < pointCount; ++pointIndex ) + { + const b3ManifoldPoint* mp = manifold->points + pointIndex; + b3ContactConstraintPointWide* cp = constraint->points + pointIndex; + + b3Vec3 rA = mp->anchorA; + b3Vec3 rB = mp->anchorB; + originA = b3Add( originA, rA ); + originB = b3Add( originB, rB ); + + ( (float*)&cp->anchorAs.X )[lane] = rA.x; + ( (float*)&cp->anchorAs.Y )[lane] = rA.y; + ( (float*)&cp->anchorAs.Z )[lane] = rA.z; + + ( (float*)&cp->anchorBs.X )[lane] = rB.x; + ( (float*)&cp->anchorBs.Y )[lane] = rB.y; + ( (float*)&cp->anchorBs.Z )[lane] = rB.z; + + float baseSeparation = mp->separation - b3Dot( b3Sub( rB, rA ), normal ); + ( (float*)&cp->baseSeparations )[lane] = baseSeparation; + + ( (float*)&cp->normalImpulses )[lane] = warmStartScale * mp->normalImpulse; + ( (float*)&cp->totalNormalImpulses )[lane] = 0.0f; + + b3Vec3 rnA = b3Cross( rA, normal ); + b3Vec3 rnB = b3Cross( rB, normal ); + float kNormal = mA + mB + b3Dot( rnA, b3MulMV( iA, rnA ) ) + b3Dot( rnB, b3MulMV( iB, rnB ) ); + ( (float*)&cp->normalMasses )[lane] = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; + + // Save relative velocity for restitution + b3Vec3 vrA = b3Add( vA, b3Cross( wA, rA ) ); + b3Vec3 vrB = b3Add( vB, b3Cross( wB, rB ) ); + ( (float*)&cp->relativeVelocities )[lane] = b3Dot( normal, b3Sub( vrB, vrA ) ); + } + + float invCount = 1.0f / pointCount; + originA = b3MulSV( invCount, originA ); + originB = b3MulSV( invCount, originB ); + + ( (float*)&constraint->originA.X )[lane] = originA.x; + ( (float*)&constraint->originA.Y )[lane] = originA.y; + ( (float*)&constraint->originA.Z )[lane] = originA.z; + ( (float*)&constraint->originB.X )[lane] = originB.x; + ( (float*)&constraint->originB.Y )[lane] = originB.y; + ( (float*)&constraint->originB.Z )[lane] = originB.z; + + for ( int pointIndex = 0; pointIndex < pointCount; ++pointIndex ) + { + const b3ManifoldPoint* mp = manifold->points + pointIndex; + b3ContactConstraintPointWide* cp = constraint->points + pointIndex; + ( (float*)&cp->leverArms )[lane] = b3Distance( mp->anchorA, originA ); + } + + b3Vec3 rtA1 = b3Cross( originA, tangent1 ); + b3Vec3 rtA2 = b3Cross( originA, tangent2 ); + + b3Vec3 rtB1 = b3Cross( originB, tangent1 ); + b3Vec3 rtB2 = b3Cross( originB, tangent2 ); + + { + b3Matrix2 k; + k.cx.x = mA + mB + b3Dot( rtA1, b3MulMV( iA, rtA1 ) ) + b3Dot( rtB1, b3MulMV( iB, rtB1 ) ); + k.cy.y = mA + mB + b3Dot( rtA2, b3MulMV( iA, rtA2 ) ) + b3Dot( rtB2, b3MulMV( iB, rtB2 ) ); + k.cx.y = k.cy.x = b3Dot( rtA1, b3MulMV( iA, rtA2 ) ) + b3Dot( rtB1, b3MulMV( iB, rtB2 ) ); + b3Matrix2 tangentMass = b3Invert2( k ); + + ( (float*)&constraint->tangentMass.cxx )[lane] = tangentMass.cx.x; + ( (float*)&constraint->tangentMass.cxy )[lane] = tangentMass.cx.y; + ( (float*)&constraint->tangentMass.cyy )[lane] = tangentMass.cy.y; + + ( (float*)&constraint->frictionImpulse.x )[lane] = + warmStartScale * b3Dot( manifold->frictionImpulse, tangent1 ); + ( (float*)&constraint->frictionImpulse.y )[lane] = + warmStartScale * b3Dot( manifold->frictionImpulse, tangent2 ); + } + + { + float k = b3Dot( normal, b3MulMV( b3AddMM( iA, iB ), normal ) ); + ( (float*)&constraint->twistMass )[lane] = k > 0.0f ? 1.0f / k : 0.0f; + ( (float*)&constraint->twistImpulse )[lane] = warmStartScale * manifold->twistImpulse; + } + + { + b3Matrix3 rollingMass = b3InvertMatrix( b3AddMM( iA, iB ) ); + + ( (float*)&constraint->rollingMass.cxx )[lane] = rollingMass.cx.x; + ( (float*)&constraint->rollingMass.cxy )[lane] = rollingMass.cx.y; + ( (float*)&constraint->rollingMass.cxz )[lane] = rollingMass.cx.z; + ( (float*)&constraint->rollingMass.cyy )[lane] = rollingMass.cy.y; + ( (float*)&constraint->rollingMass.cyz )[lane] = rollingMass.cy.z; + ( (float*)&constraint->rollingMass.czz )[lane] = rollingMass.cz.z; + + ( (float*)&constraint->rollingImpulse.X )[lane] = warmStartScale * manifold->rollingImpulse.x; + ( (float*)&constraint->rollingImpulse.Y )[lane] = warmStartScale * manifold->rollingImpulse.y; + ( (float*)&constraint->rollingImpulse.Z )[lane] = warmStartScale * manifold->rollingImpulse.z; + } + + // zero remaining points + for ( int pointIndex = pointCount; pointIndex < B3_MAX_MANIFOLD_POINTS; ++pointIndex ) + { + b3ContactConstraintPointWide* cp = constraint->points + pointIndex; + ( (float*)&cp->anchorAs.X )[lane] = 0.0f; + ( (float*)&cp->anchorAs.Y )[lane] = 0.0f; + ( (float*)&cp->anchorAs.Z )[lane] = 0.0f; + ( (float*)&cp->anchorBs.X )[lane] = 0.0f; + ( (float*)&cp->anchorBs.Y )[lane] = 0.0f; + ( (float*)&cp->anchorBs.Z )[lane] = 0.0f; + ( (float*)&cp->baseSeparations )[lane] = 0.0f; + ( (float*)&cp->normalImpulses )[lane] = 0.0f; + ( (float*)&cp->totalNormalImpulses )[lane] = 0.0f; + ( (float*)&cp->normalMasses )[lane] = 0.0f; + ( (float*)&cp->relativeVelocities )[lane] = 0.0f; + ( (float*)&cp->leverArms )[lane] = 0.0f; + } + } + } + + // Advance to next color + colorIndex += 1; + } + + b3TracyCZoneEnd( prepare_contact ); +} + +void b3WarmStartContacts_Convex( b3SolverBlock block, b3StepContext* context ) +{ + b3TracyCZoneNC( warm_start_contact, "Warm Start", b3_colorGreen, true ); + + b3BodyState* states = context->states; + b3ContactConstraintWide* constraints = context->graph->colors[block.colorIndex].wideConstraints; + + for ( int i = block.startIndex; i < block.startIndex + block.count; ++i ) + { + b3ContactConstraintWide* c = constraints + i; + b3BodyStateW bA = b3GatherBodies( states, c->indexA ); + b3BodyStateW bB = b3GatherBodies( states, c->indexB ); + + // Normal impulses + for ( int j = 0; j < B3_MAX_MANIFOLD_POINTS; ++j ) + { + b3ContactConstraintPointWide* cp = c->points + j; + + b3Vec3W rA = cp->anchorAs; + b3Vec3W rB = cp->anchorBs; + + b3Vec3W impulse; + impulse.X = b3MulW( cp->normalImpulses, c->normal.X ); + impulse.Y = b3MulW( cp->normalImpulses, c->normal.Y ); + impulse.Z = b3MulW( cp->normalImpulses, c->normal.Z ); + + bA.w = b3MulSubMVW( bA.w, c->invIA, b3CrossW( rA, impulse ) ); + bA.v = b3MulSubSVW( bA.v, c->invMassA, impulse ); + bB.w = b3MulAddMVW( bB.w, c->invIB, b3CrossW( rB, impulse ) ); + bB.v = b3MulAddSVW( bB.v, c->invMassB, impulse ); + } + + // Central friction + { + b3Vec3W rA = c->originA; + b3Vec3W rB = c->originB; + b3Vec3W impulse = b3MulSVW( c->frictionImpulse.x, c->tangent1 ); + impulse = b3MulAddSVW( impulse, c->frictionImpulse.y, c->tangent2 ); + + bA.w = b3MulSubMVW( bA.w, c->invIA, b3CrossW( rA, impulse ) ); + bA.v = b3MulSubSVW( bA.v, c->invMassA, impulse ); + bB.w = b3MulAddMVW( bB.w, c->invIB, b3CrossW( rB, impulse ) ); + bB.v = b3MulAddSVW( bB.v, c->invMassB, impulse ); + } + + // Central twist friction + { + b3Vec3W impulse = b3MulSVW( c->twistImpulse, c->normal ); + bA.w = b3MulSubMVW( bA.w, c->invIA, impulse ); + bB.w = b3MulAddMVW( bB.w, c->invIB, impulse ); + } + + // Rolling resistance + { + b3Vec3W impulse = c->rollingImpulse; + bA.w = b3MulSubMVW( bA.w, c->invIA, impulse ); + bB.w = b3MulAddMVW( bB.w, c->invIB, impulse ); + } + + b3ScatterBodies( states, c->indexA, &bA ); + b3ScatterBodies( states, c->indexB, &bB ); + } + + b3TracyCZoneEnd( warm_start_contact ); +} + +void b3SolveContacts_Convex( b3SolverBlock block, b3StepContext* context, bool useBias ) +{ + b3TracyCZoneNC( solve_contact, "Solve Contact", b3_colorAliceBlue, true ); + + b3BodyState* states = context->states; + b3ContactConstraintWide* constraints = context->graph->colors[block.colorIndex].wideConstraints; + b3FloatW inv_h = b3SplatW( context->inv_h ); + b3FloatW contactSpeed = b3SplatW( -context->world->contactSpeed ); + b3FloatW oneW = b3SplatW( 1.0f ); + b3FloatW epsilonW = b3SplatW( FLT_EPSILON ); + + for ( int wideIndex = block.startIndex; wideIndex < block.startIndex + block.count; ++wideIndex ) + { + b3ContactConstraintWide* c = constraints + wideIndex; + + b3BodyStateW bA = b3GatherBodies( states, c->indexA ); + b3BodyStateW bB = b3GatherBodies( states, c->indexB ); + + b3FloatW biasRate, massScale, impulseScale; + if ( useBias ) + { + biasRate = b3MulW( c->massScale, c->biasRate ); + massScale = c->massScale; + impulseScale = c->impulseScale; + } + else + { + biasRate = b3ZeroW(); + massScale = oneW; + impulseScale = b3ZeroW(); + } + + b3Vec3W dp = b3SubVW( bB.dp, bA.dp ); + + b3FloatW totalNormalImpulse = b3ZeroW(); + b3FloatW totalTwistLimit = b3ZeroW(); + + // todo_erin use the max point count of the four manifolds + for ( int pointIndex = 0; pointIndex < B3_MAX_MANIFOLD_POINTS; ++pointIndex ) + { + b3ContactConstraintPointWide* cp = c->points + pointIndex; + + // Fixed anchor points for applying impulses + b3Vec3W rA = cp->anchorAs; + b3Vec3W rB = cp->anchorBs; + + // Moving anchors for current separation + // todo speed this up using matrices + b3Vec3W rsA = b3RotateVectorW( bA.dq, rA ); + b3Vec3W rsB = b3RotateVectorW( bB.dq, rB ); + + // compute current separation + // this is subject to round-off error if the anchor is far from the body center of mass + b3Vec3W ds = b3AddVW( dp, b3SubVW( rsB, rsA ) ); + b3FloatW s = b3AddW( b3DotW( c->normal, ds ), cp->baseSeparations ); + + // Apply speculative bias if separation is greater than zero, otherwise apply soft constraint bias + b3FloatW mask = b3GreaterThanW( s, b3ZeroW() ); + b3FloatW specBias = b3MulW( s, inv_h ); + b3FloatW softBias = b3MaxW( b3MulW( biasRate, s ), contactSpeed ); + b3FloatW bias = b3BlendW( softBias, specBias, mask ); + + b3FloatW pointMassScale = b3BlendW( massScale, oneW, mask ); + b3FloatW pointImpulseScale = b3BlendW( impulseScale, b3ZeroW(), mask ); + + // Relative velocity at contact + b3Vec3W vrA = b3AddVW( bA.v, b3CrossW( bA.w, rA ) ); + b3Vec3W vrB = b3AddVW( bB.v, b3CrossW( bB.w, rB ) ); + b3FloatW vn = b3DotW( b3SubVW( vrB, vrA ), c->normal ); + + // Compute normal impulse + b3FloatW negImpulse = b3AddW( b3MulW( cp->normalMasses, b3AddW( b3MulW( pointMassScale, vn ), bias ) ), + b3MulW( pointImpulseScale, cp->normalImpulses ) ); + + // Clamp the accumulated impulse + b3FloatW newImpulse = b3MaxW( b3SubW( cp->normalImpulses, negImpulse ), b3ZeroW() ); + b3FloatW deltaImpulse = b3SubW( newImpulse, cp->normalImpulses ); + cp->normalImpulses = newImpulse; + cp->totalNormalImpulses = b3AddW( cp->totalNormalImpulses, newImpulse ); + + totalNormalImpulse = b3AddW( totalNormalImpulse, newImpulse ); + totalTwistLimit = b3AddW( totalTwistLimit, b3MulW( cp->leverArms, newImpulse ) ); + + // Apply contact impulse + b3Vec3W P = b3MulSVW( deltaImpulse, c->normal ); + bA.w = b3MulSubMVW( bA.w, c->invIA, b3CrossW( rA, P ) ); + bA.v = b3MulSubSVW( bA.v, c->invMassA, P ); + bB.w = b3MulAddMVW( bB.w, c->invIB, b3CrossW( rB, P ) ); + bB.v = b3MulAddSVW( bB.v, c->invMassB, P ); + } + + // No friction when applying bias + if ( useBias == false ) + { + // Rolling resistance + if ( b3AllZeroW( c->rollingResistance ) == false ) + { + // flip A/B order to negate + b3Vec3W deltaImpulse = b3MulMVW( c->rollingMass, b3SubVW( bA.w, bB.w ) ); + b3Vec3W oldImpulse = c->rollingImpulse; + c->rollingImpulse = b3AddVW( oldImpulse, deltaImpulse ); + + b3FloatW maxImpulse = b3MulW( c->rollingResistance, totalNormalImpulse ); + b3FloatW lengthSquared = b3DotW( c->rollingImpulse, c->rollingImpulse ); + + // if ( magSqr > maxLambda * maxLambda + FLT_EPSILON ) + //{ + // c->rollingImpulse *= maxLambda / sqrtf( magSqr ); + // } + + b3FloatW mask = b3GreaterThanW( lengthSquared, b3MulAddW( epsilonW, maxImpulse, maxImpulse ) ); + + // No approximate _mm_rsqrt_ps here to maintain cross-platform determinism + b3FloatW normalize = b3DivW( maxImpulse, b3AddW( b3SqrtW( lengthSquared ), epsilonW ) ); + b3FloatW scale = b3BlendW( oneW, normalize, mask ); + + // Ensure zero rolling resistance yields no impulse + b3FloatW rollingMask = b3GreaterThanW( c->rollingResistance, b3ZeroW() ); + scale = b3BlendW( b3ZeroW(), scale, rollingMask ); + + c->rollingImpulse = b3MulSVW( scale, c->rollingImpulse ); + + deltaImpulse = b3SubVW( c->rollingImpulse, oldImpulse ); + + bA.w = b3MulSubMVW( bA.w, c->invIA, deltaImpulse ); + bB.w = b3MulAddMVW( bB.w, c->invIB, deltaImpulse ); + } + + // Central twist friction + { + b3FloatW twistSpeed = b3DotW( c->normal, b3SubVW( bB.w, bA.w ) ); + b3FloatW maxLambda = b3MulW( c->friction, totalTwistLimit ); + b3FloatW deltaImpulse = b3NegW( b3MulW( c->twistMass, twistSpeed ) ); + b3FloatW oldImpulse = c->twistImpulse; + c->twistImpulse = b3SymClampW( b3AddW( oldImpulse, deltaImpulse ), maxLambda ); + deltaImpulse = b3SubW( c->twistImpulse, oldImpulse ); + + b3Vec3W L = b3MulSVW( deltaImpulse, c->normal ); + bA.w = b3MulSubMVW( bA.w, c->invIA, L ); + bB.w = b3MulAddMVW( bB.w, c->invIB, L ); + } + + // Central friction + { + b3Vec3W tangent1 = c->tangent1; + b3Vec3W tangent2 = c->tangent2; + + // Fixed anchor points for applying impulses + b3Vec3W rA = c->originA; + b3Vec3W rB = c->originB; + + // Relative tangent velocity at contact + b3Vec3W vrA = b3AddVW( bA.v, b3CrossW( bA.w, rA ) ); + b3Vec3W vrB = b3AddVW( bB.v, b3CrossW( bB.w, rB ) ); + b3Vec3W vr = b3SubVW( vrB, vrA ); + b3Vec2W vt = { + b3SubW( b3DotW( vr, tangent1 ), c->tangentVelocity1 ), + b3SubW( b3DotW( vr, tangent2 ), c->tangentVelocity2 ), + }; + + // Incremental tangent impulse + b3Vec2W deltaImpulse = b3MulMV2W( c->tangentMass, vt ); + deltaImpulse = (b3Vec2W){ b3NegW( deltaImpulse.x ), b3NegW( deltaImpulse.y ) }; + b3Vec2W newImpulse = b3AddV2W( c->frictionImpulse, deltaImpulse ); + + b3FloatW friction = c->friction; + b3FloatW maxImpulse = b3MulW( friction, totalNormalImpulse ); + + // Clamp the accumulated impulse + b3FloatW lengthSquared = b3AddW( b3MulW( newImpulse.x, newImpulse.x ), b3MulW( newImpulse.y, newImpulse.y ) ); + + // Max impulse can be zero + b3FloatW mask = b3GreaterThanW( lengthSquared, b3MulW( maxImpulse, maxImpulse ) ); + + // No approximate _mm_rsqrt_ps here to maintain cross-platform determinism. Add epsilon to avoid divide by + // zero. + b3FloatW normalize = b3DivW( maxImpulse, b3AddW( b3SqrtW( lengthSquared ), epsilonW ) ); + b3FloatW scale = b3BlendW( oneW, normalize, mask ); + newImpulse = (b3Vec2W){ + b3MulW( scale, newImpulse.x ), + b3MulW( scale, newImpulse.y ), + }; + + deltaImpulse = (b3Vec2W){ + b3SubW( newImpulse.x, c->frictionImpulse.x ), + b3SubW( newImpulse.y, c->frictionImpulse.y ), + }; + + c->frictionImpulse = newImpulse; + + // Apply delta impulse + b3Vec3W P = b3AddVW( b3MulSVW( deltaImpulse.x, tangent1 ), b3MulSVW( deltaImpulse.y, tangent2 ) ); + bA.w = b3MulSubMVW( bA.w, c->invIA, b3CrossW( rA, P ) ); + bA.v = b3MulSubSVW( bA.v, c->invMassA, P ); + bB.w = b3MulAddMVW( bB.w, c->invIB, b3CrossW( rB, P ) ); + bB.v = b3MulAddSVW( bB.v, c->invMassB, P ); + } + } + + b3ScatterBodies( states, c->indexA, &bA ); + b3ScatterBodies( states, c->indexB, &bB ); + } + + b3TracyCZoneEnd( solve_contact ); +} + +void b3ApplyRestitution_Convex( b3SolverBlock block, b3StepContext* context ) +{ + b3TracyCZoneNC( restitution, "Restitution", b3_colorDodgerBlue, true ); + + b3BodyState* states = context->states; + b3ContactConstraintWide* constraints = context->graph->colors[block.colorIndex].wideConstraints; + b3FloatW threshold = b3SplatW( context->world->restitutionThreshold ); + b3FloatW zero = b3ZeroW(); + + for ( int i = block.startIndex; i < block.startIndex + block.count; ++i ) + { + b3ContactConstraintWide* c = constraints + i; + + if ( b3AllZeroW( c->restitution ) ) + { + // No lanes have restitution. Common case. + continue; + } + + // Single gather for all manifolds + b3BodyStateW bA = b3GatherBodies( states, c->indexA ); + b3BodyStateW bB = b3GatherBodies( states, c->indexB ); + + // Create a mask based on restitution so that lanes with no restitution are not affected + // by the calculations below. + b3FloatW restitutionMask = b3EqualsW( c->restitution, zero ); + + for ( int pointIndex = 0; pointIndex < B3_MAX_MANIFOLD_POINTS; ++pointIndex ) + { + b3ContactConstraintPointWide* cp = c->points + pointIndex; + + // Set effective mass to zero if restitution should not be applied + b3FloatW mask1 = b3GreaterThanW( b3AddW( cp->relativeVelocities, threshold ), zero ); + b3FloatW mask2 = b3EqualsW( cp->totalNormalImpulses, zero ); + b3FloatW mask = b3OrW( b3OrW( mask1, mask2 ), restitutionMask ); + b3FloatW mass = b3BlendW( cp->normalMasses, zero, mask ); + + // Fixed anchors for impulses + b3Vec3W rA = cp->anchorAs; + b3Vec3W rB = cp->anchorBs; + + // Relative velocity at contact + b3Vec3W vrA = b3AddVW( bA.v, b3CrossW( bA.w, rA ) ); + b3Vec3W vrB = b3AddVW( bB.v, b3CrossW( bB.w, rB ) ); + b3FloatW vn = b3DotW( b3SubVW( vrB, vrA ), c->normal ); + + // Compute normal impulse + b3FloatW negImpulse = b3MulW( mass, b3AddW( vn, b3MulW( c->restitution, cp->relativeVelocities ) ) ); + + // Clamp the accumulated impulse + b3FloatW newImpulse = b3MaxW( b3SubW( cp->normalImpulses, negImpulse ), b3ZeroW() ); + b3FloatW deltaImpulse = b3SubW( newImpulse, cp->normalImpulses ); + cp->normalImpulses = newImpulse; + cp->totalNormalImpulses = b3AddW( cp->totalNormalImpulses, deltaImpulse ); + + // Apply contact impulse + b3Vec3W P = b3MulSVW( deltaImpulse, c->normal ); + bA.w = b3MulSubMVW( bA.w, c->invIA, b3CrossW( rA, P ) ); + bA.v = b3MulSubSVW( bA.v, c->invMassA, P ); + bB.w = b3MulAddMVW( bB.w, c->invIB, b3CrossW( rB, P ) ); + bB.v = b3MulAddSVW( bB.v, c->invMassB, P ); + } + + b3ScatterBodies( states, c->indexA, &bA ); + b3ScatterBodies( states, c->indexB, &bB ); + } + + b3TracyCZoneEnd( restitution ); +} + +// Store impulses by contact constraint +void b3StoreImpulses_Convex( b3SolverBlock block, b3StepContext* context, int workerIndex ) +{ + b3TracyCZoneNC( store_impulses, "Store", b3_colorFireBrick, true ); + + b3World* world = context->world; + b3WidePrepareSpan* spans = context->widePrepareSpans; + const b3ContactConstraintWide* wideBase = context->wideConstraints; + b3TaskContext* taskContext = world->taskContexts.data + workerIndex; + b3BitSet* hitEventBitSet = &taskContext->hitEventBitSet; + bool hasHitEvents = taskContext->hasHitEvents; + float negHitThreshold = -world->hitEventThreshold; + + int wideIndex = block.startIndex; + int endWideIndex = block.startIndex + block.count; + + // Find color for start index + int colorIndex = 0; + while ( spans[colorIndex + 1].start <= wideIndex ) + { + colorIndex += 1; + } + + while ( wideIndex < endWideIndex ) + { + int colorWideStart = spans[colorIndex].start; + int colorWideEndIndex = b3MinInt( spans[colorIndex + 1].start, endWideIndex ); + int colorContactCount = spans[colorIndex].count; + int* contactIds = spans[colorIndex].contacts; + + for ( ; wideIndex < colorWideEndIndex; ++wideIndex ) + { + const b3ContactConstraintWide* c = wideBase + wideIndex; + const float* frictionImpulse1 = (float*)&c->frictionImpulse.x; + const float* frictionImpulse2 = (float*)&c->frictionImpulse.y; + const float* tangent1X = (float*)&c->tangent1.X; + const float* tangent1Y = (float*)&c->tangent1.Y; + const float* tangent1Z = (float*)&c->tangent1.Z; + const float* tangent2X = (float*)&c->tangent2.X; + const float* tangent2Y = (float*)&c->tangent2.Y; + const float* tangent2Z = (float*)&c->tangent2.Z; + const float* twistImpulse = (float*)&c->twistImpulse; + const float* rollingImpulseX = (float*)&c->rollingImpulse.X; + const float* rollingImpulseY = (float*)&c->rollingImpulse.Y; + const float* rollingImpulseZ = (float*)&c->rollingImpulse.Z; + + int localWideIndex = wideIndex - colorWideStart; + + for ( int lane = 0; lane < B3_SIMD_WIDTH; ++lane ) + { + int contactIndex = B3_SIMD_WIDTH * localWideIndex + lane; + if ( contactIndex >= colorContactCount ) + { + break; + } + + b3Manifold* m = c->manifolds[lane]; + if ( m == NULL ) + { + continue; + } + + float f1 = frictionImpulse1[lane]; + float f2 = frictionImpulse2[lane]; + m->frictionImpulse = (b3Vec3){ + f1 * tangent1X[lane] + f2 * tangent2X[lane], + f1 * tangent1Y[lane] + f2 * tangent2Y[lane], + f1 * tangent1Z[lane] + f2 * tangent2Z[lane], + }; + m->twistImpulse = twistImpulse[lane]; + m->rollingImpulse = (b3Vec3){ + rollingImpulseX[lane], + rollingImpulseY[lane], + rollingImpulseZ[lane], + }; + + int pointCount = m->pointCount; + for ( int pointIndex = 0; pointIndex < pointCount; ++pointIndex ) + { + const b3ContactConstraintPointWide* cp = c->points + pointIndex; + const float* normalImpulse = (float*)&cp->normalImpulses; + const float* totalNormalImpulse = (float*)&cp->totalNormalImpulses; + const float* normalVelocity = (float*)&cp->relativeVelocities; + + b3ManifoldPoint* mp = m->points + pointIndex; + mp->normalImpulse = normalImpulse[lane]; + mp->totalNormalImpulse = totalNormalImpulse[lane]; + mp->normalVelocity = normalVelocity[lane]; + } + + int contactId = contactIds[contactIndex]; + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + if ( ( contact->flags & b3_simEnableHitEvent ) != 0 ) + { + for ( int k = 0; k < pointCount; ++k ) + { + b3ManifoldPoint* mp = m->points + k; + + // Need to check total impulse because the point may be speculative and not colliding + if ( mp->normalVelocity < negHitThreshold && mp->totalNormalImpulse > 0.0f ) + { + b3SetBit( hitEventBitSet, contact->contactId ); + hasHitEvents = true; + break; + } + } + } + } + } + + colorIndex += 1; + } + + taskContext->hasHitEvents = hasHitEvents; + + b3TracyCZoneEnd( store_impulses ); +} + +void b3PrepareContacts_Overflow( b3StepContext* context ) +{ + b3ConstraintGraph* graph = context->graph; + b3GraphColor* color = graph->colors + B3_OVERFLOW_INDEX; + + uint16_t count = (uint16_t)color->contacts.count; + if (count == 0) + { + return; + } + + b3SolverBlock block = { + .startIndex = 0, + .count = count, + .blockType = b3_overflowBlock, + .colorIndex = B3_OVERFLOW_INDEX, + }; + + b3PrepareContacts_Mesh( block, context ); +} + +void b3WarmStartContacts_Overflow( b3StepContext* context ) +{ + b3ConstraintGraph* graph = context->graph; + b3GraphColor* color = graph->colors + B3_OVERFLOW_INDEX; + + uint16_t count = (uint16_t)color->contacts.count; + if ( count == 0 ) + { + return; + } + + b3SolverBlock block = { + .startIndex = 0, + .count = count, + .blockType = b3_overflowBlock, + .colorIndex = B3_OVERFLOW_INDEX, + }; + + b3WarmStartContacts_Mesh( block, context ); +} + +void b3SolveContacts_Overflow( b3StepContext* context, bool useBias ) +{ + b3ConstraintGraph* graph = context->graph; + b3GraphColor* color = graph->colors + B3_OVERFLOW_INDEX; + + uint16_t count = (uint16_t)color->contacts.count; + if ( count == 0 ) + { + return; + } + + b3SolverBlock block = { + .startIndex = 0, + .count = count, + .blockType = b3_overflowBlock, + .colorIndex = B3_OVERFLOW_INDEX, + }; + + b3SolveContacts_Mesh( block, context, useBias ); +} + +void b3ApplyRestitution_Overflow( b3StepContext* context ) +{ + b3ConstraintGraph* graph = context->graph; + b3GraphColor* color = graph->colors + B3_OVERFLOW_INDEX; + + uint16_t count = (uint16_t)color->contacts.count; + if ( count == 0 ) + { + return; + } + + b3SolverBlock block = { + .startIndex = 0, + .count = count, + .blockType = b3_overflowBlock, + .colorIndex = B3_OVERFLOW_INDEX, + }; + + b3ApplyRestitution_Mesh( block, context ); +} + +void b3StoreImpulses_Overflow( b3StepContext* context ) +{ + b3ConstraintGraph* graph = context->graph; + b3GraphColor* color = graph->colors + B3_OVERFLOW_INDEX; + + uint16_t count = (uint16_t)color->contacts.count; + if ( count == 0 ) + { + return; + } + + b3SolverBlock block = { + .startIndex = 0, + .count = count, + .blockType = b3_overflowBlock, + .colorIndex = B3_OVERFLOW_INDEX, + }; + + // Overflow runs serially on the orchestrator (worker 0) + b3StoreImpulses_Mesh( block, context, 0 ); +} diff --git a/src/contact_solver.h b/src/contact_solver.h new file mode 100644 index 0000000..67c767f --- /dev/null +++ b/src/contact_solver.h @@ -0,0 +1,82 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "math_internal.h" +#include "solver.h" + +typedef struct b3ManifoldConstraintPoint +{ + b3Vec3 rA, rB; + float baseSeparation; + float relativeVelocity; + float normalImpulse; + float totalNormalImpulse; + float normalMass; + float leverArm; +} b3ManifoldConstraintPoint; + +typedef struct b3ManifoldConstraint +{ + // todo use pointer buffer + b3ManifoldConstraintPoint points[4]; + int pointCount; + b3Vec3 normal; + b3Vec3 tangent1; + b3Vec3 tangent2; + b3Vec3 originA, originB; + float twistMass; + float twistImpulse; + b3Matrix2 tangentMass; + b3Vec2 frictionImpulse; + b3Vec3 rollingImpulse; + float tangentVelocity1; + float tangentVelocity2; +} b3ManifoldConstraint; + +typedef struct b3ContactConstraint +{ + b3ManifoldConstraint* constraints; + struct b3Contact* contact; + int indexA; + int indexB; + float invMassA, invMassB; + b3Matrix3 invIA, invIB; + b3Softness softness; + b3Matrix3 rollingMass; + float friction; + float restitution; + float rollingResistance; + int manifoldCount; +} b3ContactConstraint; + +#ifdef __cplusplus +extern "C" +{ +#endif + +int b3GetWideContactConstraintByteCount( void ); + +// Overflow contacts don't fit into the constraint graph coloring +void b3PrepareContacts_Overflow( b3StepContext* context ); +void b3WarmStartContacts_Overflow( b3StepContext* context ); +void b3SolveContacts_Overflow( b3StepContext* context, bool useBias ); +void b3ApplyRestitution_Overflow( b3StepContext* context ); +void b3StoreImpulses_Overflow( b3StepContext* context ); + +void b3PrepareContacts_Mesh( b3SolverBlock block, b3StepContext* context ); +void b3WarmStartContacts_Mesh( b3SolverBlock block, b3StepContext* context ); +void b3SolveContacts_Mesh( b3SolverBlock block, b3StepContext* context, bool useBias ); +void b3ApplyRestitution_Mesh( b3SolverBlock block, b3StepContext* context ); +void b3StoreImpulses_Mesh( b3SolverBlock block, b3StepContext* context, int workerIndex ); + +void b3PrepareContacts_Convex( b3SolverBlock block, b3StepContext* context ); +void b3WarmStartContacts_Convex( b3SolverBlock block, b3StepContext* context ); +void b3SolveContacts_Convex( b3SolverBlock block, b3StepContext* context, bool useBias ); +void b3ApplyRestitution_Convex( b3SolverBlock block, b3StepContext* context ); +void b3StoreImpulses_Convex( b3SolverBlock block, b3StepContext* context, int workerIndex ); + +#ifdef __cplusplus +} +#endif diff --git a/src/container.h b/src/container.h new file mode 100644 index 0000000..77f484f --- /dev/null +++ b/src/container.h @@ -0,0 +1,184 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "algorithm.h" +#include "core.h" + +#include +#include + +#define b3DeclareArray( T ) \ + typedef struct b3DynamicArray_##T \ + { \ + struct T* data; \ + int count; \ + int capacity; \ + } b3DynamicArray_##T + +#define b3DeclareArrayNative( T ) \ + typedef struct b3DynamicArray_##T \ + { \ + T* data; \ + int count; \ + int capacity; \ + } b3DynamicArray_##T + +// Define an array. +// It may be zero initialized: +// b3ArrayC(int) myArray = { 0 }; +#define b3ArrayC( T ) b3DynamicArray_##T + +// Alternative to zero initialization +#define b3Array_Create( a ) \ + do \ + { \ + ( a ).data = NULL; \ + ( a ).count = 0; \ + ( a ).capacity = 0; \ + } \ + while ( 0 ) + +#define b3Array_CreateN( a, n ) \ + do \ + { \ + ( a ).data = ( n ) > 0 ? (B3_TYPE_OF( ( a ).data ))b3GrowAlloc( NULL, 0, ( n ) * sizeof( *( a ).data ) ) : NULL; \ + ( a ).count = 0; \ + ( a ).capacity = ( n ); \ + } \ + while ( 0 ) + +#define b3Array_Destroy( a ) \ + do \ + { \ + b3Free( ( a ).data, ( a ).capacity * sizeof( *( a ).data ) ); \ + ( a ).data = NULL; \ + ( a ).count = 0; \ + ( a ).capacity = 0; \ + } \ + while ( 0 ) + +#define b3Array_Reserve( a, n ) \ + do \ + { \ + if ( ( a ).capacity < n ) \ + { \ + int oldSize = ( a ).capacity * sizeof( *( a ).data ); \ + int newSize = ( n ) * sizeof( *( a ).data ); \ + ( a ).data = (B3_TYPE_OF( ( a ).data ))b3GrowAlloc( ( a ).data, oldSize, newSize ); \ + ( a ).capacity = ( n ); \ + } \ + } \ + while ( 0 ) + +#define b3Array_Resize( a, n ) \ + do \ + { \ + b3Array_Reserve( a, n ); \ + ( a ).count = ( n ); \ + } \ + while ( 0 ) + +// Push a new element by value +#define b3Array_Push( a, value ) \ + do \ + { \ + if ( ( a ).count >= ( a ).capacity ) \ + { \ + int oldSize = ( a ).capacity * sizeof( *( a ).data ); \ + int newCapacity = ( a ).capacity == 0 ? 8 : 2 * ( a ).capacity; \ + int newSize = newCapacity * sizeof( *( a ).data ); \ + ( a ).data = (B3_TYPE_OF( ( a ).data ))b3GrowAlloc( ( a ).data, oldSize, newSize ); \ + ( a ).capacity = newCapacity; \ + } \ + ( a ).data[( a ).count++] = ( value ); \ + } \ + while ( 0 ) + +// Get a pointer to an element +#define b3Array_Get( a, index ) ( B3_ASSERT( 0 <= ( index ) && ( index ) < ( a ).count ), ( a ).data + ( index ) ) + +// Create a new uninitialized element and return a pointer to it +#define b3Array_Emplace( a ) \ + ( (B3_TYPE_OF( ( a ).data ))b3EmplaceHelper( (void**)&( a ).data, &( a ).count, &( a ).capacity, sizeof( *( a ).data ) ) ) + +// Remove the last element and return it by value. +#define b3Array_Pop( a ) ( B3_ASSERT( 0 < ( a ).count ), ( a ).data[-1 + ( a ).count--] ) + +// Add an uninitialized element and return its index. +#define b3Array_AddIndex( a ) \ + ( b3EmplaceHelper( (void**)&( a ).data, &( a ).count, &( a ).capacity, sizeof( *( a ).data ) ), ( a ).count - 1 ) + +// Append a contiguous run of values. +#define b3Array_Append( a, src, n ) \ + do \ + { \ + int b3_n = ( n ); \ + if ( ( a ).count + b3_n > ( a ).capacity ) \ + { \ + int req = ( a ).count + b3_n; \ + int newCapacity = req > 2 ? req + ( req >> 1 ) : 8; \ + int oldSize = ( a ).capacity * sizeof( *( a ).data ); \ + int newSize = newCapacity * sizeof( *( a ).data ); \ + ( a ).data = (B3_TYPE_OF( ( a ).data ))b3GrowAlloc( ( a ).data, oldSize, newSize ); \ + ( a ).capacity = newCapacity; \ + } \ + memcpy( ( a ).data + ( a ).count, ( src ), b3_n * sizeof( *( a ).data ) ); \ + ( a ).count += b3_n; \ + } \ + while ( 0 ) + +// Zero the entire allocated buffer (capacity, not just count). +#define b3Array_MemZero( a ) \ + do \ + { \ + if ( ( a ).capacity > 0 ) \ + { \ + memset( ( a ).data, 0, ( a ).capacity * sizeof( *( a ).data ) ); \ + } \ + } \ + while ( 0 ) + +// Remove and element by swapping with the last element. If the index is the last element it returns +// B3_NULL_INDEX, otherwise it returns the index of the last element (which is now out of bounds). +#define b3Array_RemoveSwap( a, index ) b3RemoveHelper( ( a ).data, &( a ).count, ( index ), sizeof( *( a ).data ) ) + +B3_INLINE void* b3EmplaceHelper( void** data, int* count, int* capacity, int elem_size ) +{ + if ( *count >= *capacity ) + { + int oldCapacity = *capacity; + int oldSize = oldCapacity * elem_size; + int newCapacity = ( oldCapacity == 0 ? 16 : 2 * oldCapacity ); + int newSize = newCapacity * elem_size; + *data = b3GrowAlloc( *data, oldSize, newSize ); + *capacity = newCapacity; + } + return (char*)*data + ( *count )++ * elem_size; +} + +B3_INLINE int b3RemoveHelper( void* data, int* count, int index, int elementSize ) +{ + B3_ASSERT( 0 <= index && index < *count && "Array index out of bounds" ); + + ( *count )--; + if ( index != *count ) + { + memcpy( (char*)data + index * elementSize, (char*)data + ( *count ) * elementSize, elementSize ); + return *count; + } + + return B3_NULL_INDEX; +} + +#define b3Array_Clear( a ) \ + do \ + { \ + ( a ).count = 0; \ + } \ + while ( 0 ) + +#define b3Array_ByteCount( a ) ( ( a ).capacity * (int)sizeof( *( a ).data ) ) + +b3DeclareArrayNative( int ); diff --git a/src/convex_manifold.c b/src/convex_manifold.c new file mode 100644 index 0000000..6639539 --- /dev/null +++ b/src/convex_manifold.c @@ -0,0 +1,1603 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "algorithm.h" +#include "manifold.h" +#include "shape.h" + +#include "box3d/base.h" +#include "box3d/collision.h" +#include "box3d/constants.h" + +#include +#include + +static inline bool b3IsMinkowskiFaceIsolated( b3Vec3 a, b3Vec3 b, b3Vec3 n ) +{ + // An isolated edge (e.g. like in a capsule) defines a circle through the + // origin on the Gauss map. So testing for overlap between this circle and + // the arc AB simplifies to a simple plane test. + float an = b3Dot( a, n ); + float bn = b3Dot( b, n ); + + return an * bn <= 0.0f; +} + +// bxa = cross(b, a) and dxc = cross(d, c) +// but in practice we use the edge vector between the faces for robustness +static inline bool b3IsMinkowskiFace( b3Vec3 a, b3Vec3 b, b3Vec3 bxa, b3Vec3 c, b3Vec3 d, b3Vec3 dxc ) +{ + // Two edges build a face on the Minkowski sum if the associated arcs ab and cd intersect on the Gauss map. + // The associated arcs are defined by the adjacent face normals of each edge. + float cba = b3Dot( c, bxa ); + float dba = b3Dot( d, bxa ); + float adc = b3Dot( a, dxc ); + float bdc = b3Dot( b, dxc ); + + return cba * dba < 0.0f && adc * bdc < 0.0f && cba * bdc > 0.0f; +} + +static int b3ClipSegment( b3ClipVertex segment[2], b3Plane plane ) +{ + int vertexCount = 0; + b3ClipVertex vertex1 = segment[0]; + b3ClipVertex vertex2 = segment[1]; + + float distance1 = b3PlaneSeparation( plane, vertex1.position ); + float distance2 = b3PlaneSeparation( plane, vertex2.position ); + + // If the points are behind the plane + if ( distance1 <= 0.0f ) + { + segment[vertexCount++] = vertex1; + } + if ( distance2 <= 0.0f ) + { + segment[vertexCount++] = vertex2; + } + + // If the points are on different sides of the plane + if ( distance1 * distance2 < 0.0f ) + { + // Find intersection point of edge and plane + float t = distance1 / ( distance1 - distance2 ); + segment[vertexCount].position = b3Add( b3MulSV( 1.0f - t, vertex1.position ), b3MulSV( t, vertex2.position ) ); + segment[vertexCount].pair = distance1 > 0.0f ? vertex1.pair : vertex2.pair; + vertexCount++; + } + + return vertexCount; +} + +static int b3ClipSegmentToHullFace( b3ClipVertex segment[2], const b3Hull* hull, int refFace ) +{ + const b3HullFace* faces = b3GetHullFaces( hull ); + const b3Plane* planes = b3GetHullPlanes( hull ); + const b3HullHalfEdge* edges = b3GetHullEdges( hull ); + const b3Vec3* points = b3GetHullPoints( hull ); + + b3Plane refPlane = planes[refFace]; + + const b3HullFace* face = faces + refFace; + + int edgeIndex = face->edge; + + do + { + const b3HullHalfEdge* edge = edges + edgeIndex; + int nextEdgeIndex = edge->next; + const b3HullHalfEdge* next = edges + nextEdgeIndex; + + b3Vec3 vertex1 = points[edge->origin]; + b3Vec3 vertex2 = points[next->origin]; + b3Vec3 tangent = b3Normalize( b3Sub( vertex2, vertex1 ) ); + b3Vec3 binormal = b3Cross( tangent, refPlane.normal ); + + int pointCount = b3ClipSegment( segment, b3MakePlaneFromNormalAndPoint( binormal, vertex1 ) ); + if ( pointCount < 2 ) + { + return 0; + } + + edgeIndex = nextEdgeIndex; + } + while ( edgeIndex != face->edge ); + + return 2; +} + +static b3FaceQuery b3QueryFaceDirectionHullAndCapsule( const b3Hull* hull, const b3Capsule* capsule, + b3Transform capsuleTransform ) +{ + int maxFaceIndex = -1; + int maxVertexIndex = -1; + float maxFaceSeparation = -FLT_MAX; + const b3Plane* planes = b3GetHullPlanes( hull ); + + b3Vec3 capsulePoints[2] = { + b3TransformPoint( capsuleTransform, capsule->center1 ), + b3TransformPoint( capsuleTransform, capsule->center2 ), + }; + + for ( int faceIndex = 0; faceIndex < hull->faceCount; ++faceIndex ) + { + b3Plane plane = planes[faceIndex]; + + int vertexIndex = b3GetPointSupport( capsulePoints, 2, b3Neg( plane.normal ) ); + b3Vec3 support = capsulePoints[vertexIndex]; + float separation = b3PlaneSeparation( plane, support ); + if ( separation > maxFaceSeparation ) + { + maxVertexIndex = vertexIndex; + maxFaceIndex = faceIndex; + maxFaceSeparation = separation; + } + } + + return (b3FaceQuery){ + .separation = maxFaceSeparation, + .faceIndex = (uint8_t)maxFaceIndex, + .vertexIndex = (uint8_t)maxVertexIndex, + }; +} + +static b3FaceQuery b3QueryFaceDirections( const b3Hull* hullA, const b3Hull* hullB, b3Transform relativeTransform ) +{ + // We perform all computations in local space of the second hull + b3Transform transform = b3InvertTransform( relativeTransform ); + const b3Plane* planesA = b3GetHullPlanes( hullA ); + const b3Vec3* pointsB = b3GetHullPoints( hullB ); + + int maxFaceIndex = -1; + int maxVertexIndex = -1; + float maxFaceSeparation = -FLT_MAX; + + for ( int faceIndex = 0; faceIndex < hullA->faceCount; ++faceIndex ) + { + b3Plane plane = b3TransformPlane( transform, planesA[faceIndex] ); + + int vertexIndex = b3FindHullSupportVertex( hullB, b3Neg( plane.normal ) ); + b3Vec3 support = pointsB[vertexIndex]; + float separation = b3PlaneSeparation( plane, support ); + if ( separation > maxFaceSeparation ) + { + maxFaceIndex = faceIndex; + maxVertexIndex = vertexIndex; + maxFaceSeparation = separation; + } + } + + return (b3FaceQuery){ + .separation = maxFaceSeparation, + .faceIndex = (uint8_t)maxFaceIndex, + .vertexIndex = (uint8_t)maxVertexIndex, + }; +} + +static b3EdgeQuery b3QueryEdgeDirectionHullAndCapsule( const b3Hull* hull, const b3Capsule* capsule, + b3Transform capsuleTransform ) +{ + // Find axis of minimum penetration + float maxSeparation = -FLT_MAX; + int maxIndex1 = -1; + int maxIndex2 = -1; + + // We perform all computations in local space of the hull + b3Vec3 p1 = b3TransformPoint( capsuleTransform, capsule->center1 ); + b3Vec3 q1 = b3TransformPoint( capsuleTransform, capsule->center2 ); + b3Vec3 e1 = b3Sub( q1, p1 ); + + const b3HullHalfEdge* edges = b3GetHullEdges( hull ); + const b3Vec3* points = b3GetHullPoints( hull ); + const b3Plane* planes = b3GetHullPlanes( hull ); + + for ( int index = 0; index < hull->edgeCount; index += 2 ) + { + const b3HullHalfEdge* edge = edges + index; + const b3HullHalfEdge* twin = edges + index + 1; + B3_ASSERT( edge->twin == index + 1 && twin->twin == index ); + + b3Vec3 p2 = points[edge->origin]; + b3Vec3 q2 = points[twin->origin]; + b3Vec3 e2 = b3Sub( q2, p2 ); + + b3Vec3 u2 = planes[edge->face].normal; + b3Vec3 v2 = planes[twin->face].normal; + + if ( b3IsMinkowskiFaceIsolated( u2, v2, e1 ) ) + { + // We can pass any point on the edge and choose + // the edge centers for better numerical precision. + b3Vec3 c1 = b3MulSV( 0.5f, b3Add( q1, p1 ) ); + b3Vec3 c2 = hull->center; + float separation = b3EdgeEdgeSeparation( q1, e1, c1, q2, e2, c2 ); + if ( separation > maxSeparation ) + { + // Note: We don't exit early if we find a separating axis here since we want to + // find the best one for caching and account for the convex radius later. + maxSeparation = separation; + maxIndex1 = 0; + maxIndex2 = index; + } + } + } + + // Save result + return (b3EdgeQuery){ + .separation = maxSeparation, + .indexA = (uint8_t)maxIndex1, + .indexB = (uint8_t)maxIndex2, + }; +} + +static b3EdgeQuery b3QueryEdgeDirections( const b3Hull* hullA, const b3Hull* hullB, b3Transform transformBtoA ) +{ + // Find axis of minimum penetration + float maxSeparation = -FLT_MAX; + int maxIndexA = B3_NULL_INDEX; + int maxIndexB = B3_NULL_INDEX; + + const b3HullHalfEdge* edgesA = b3GetHullEdges( hullA ); + const b3Vec3* pointsA = b3GetHullPoints( hullA ); + const b3Plane* planesA = b3GetHullPlanes( hullA ); + const b3HullHalfEdge* edgesB = b3GetHullEdges( hullB ); + const b3Vec3* pointsB = b3GetHullPoints( hullB ); + const b3Plane* planesB = b3GetHullPlanes( hullB ); + + // Work in frame A + b3Matrix3 matrix = b3MakeMatrixFromQuat( transformBtoA.q ); + + // Arranged to minimize transform operations + for ( int indexB = 0; indexB < hullB->edgeCount; indexB += 2 ) + { + const b3HullHalfEdge* edgeB = edgesB + indexB; + const b3HullHalfEdge* twinB = edgesB + indexB + 1; + B3_ASSERT( edgeB->twin == indexB + 1 && twinB->twin == indexB ); + + b3Vec3 qB = pointsB[twinB->origin]; + b3Vec3 eB = b3MulMV( matrix, b3Sub( qB, pointsB[edgeB->origin] ) ); + qB = b3Add( b3MulMV( matrix, qB ), transformBtoA.p ); + + b3Vec3 uB = b3MulMV( matrix, planesB[edgeB->face].normal ); + b3Vec3 vB = b3MulMV( matrix, planesB[twinB->face].normal ); + + for ( int indexA = 0; indexA < hullA->edgeCount; indexA += 2 ) + { + const b3HullHalfEdge* edgeA = edgesA + indexA; + const b3HullHalfEdge* twinA = edgesA + indexA + 1; + B3_ASSERT( edgeA->twin == indexA + 1 && twinA->twin == indexA ); + + b3Vec3 qA = pointsA[twinA->origin]; + b3Vec3 eA = b3Sub( qA, pointsA[edgeA->origin] ); + b3Vec3 uA = planesA[edgeA->face].normal; + b3Vec3 vA = planesA[twinA->face].normal; + + bool isMinkowski; + { + // Two edges build a face on the Minkowski sum if the associated arcs AB and CD intersect on the Gauss map. + // The associated arcs are defined by the adjacent face normals of each edge. + float cba = b3Dot( uB, eA ); + float dba = b3Dot( vB, eA ); + float adc = -b3Dot( uA, eB ); + float bdc = -b3Dot( vA, eB ); + + isMinkowski = cba * dba < 0.0f && adc * bdc < 0.0f && cba * bdc > 0.0f; + } + + if ( isMinkowski ) + { + b3Vec3 centerA = hullA->center; + b3Vec3 centerB = b3TransformPoint( transformBtoA, hullB->center ); + float separation = b3EdgeEdgeSeparation( qA, eA, centerA, qB, eB, centerB ); + + if ( separation > maxSeparation ) + { + // Continues to find the maximum separating axis + maxSeparation = separation; + maxIndexA = indexA; + maxIndexB = indexB; + } + } + } + } + + return (b3EdgeQuery){ + .separation = maxSeparation, + .indexA = maxIndexA, + .indexB = maxIndexB, + }; +} + +// Reduce the manifold points to a maximum of 4 points. +// Note: this modifies the input point array to improve performance +static void b3ReduceManifoldPoints( b3LocalManifold* manifold, int capacity, b3LocalManifoldPoint* points, int count ) +{ + if ( capacity < 4 ) + { + return; + } + + if ( count <= 4 ) + { + for ( int i = 0; i < count; ++i ) + { + manifold->points[i] = points[i]; + } + + manifold->pointCount = count; + return; + } + + b3Vec3 normal = manifold->normal; + // float linearSlop = B3_LINEAR_SLOP; + float speculativeDistance = B3_SPECULATIVE_DISTANCE; + float tolSqr = speculativeDistance * speculativeDistance; + + // This bias is very important for contact point consistency across time steps. + // It creates a pecking order to avoid flickering between candidates with similar scores. + float bias = 0.95f; + + // Step 1: find extreme point that is touching + int bestIndex = B3_NULL_INDEX; + float bestScore = -FLT_MAX; + + // Arbitrary tangent direction + // b3Vec3 perp1 = b3Perp( normal ); + // b3Vec3 perp2 = b3Cross( perp1, normal ); + // b3Vec3 searchDirection = -0.4535961214255773f * perp1 + 0.8912073600614354f * perp2; + b3Vec3 searchDirection = b3ArbitraryPerp( normal ); + for ( int index = 0; index < count; ++index ) + { + b3LocalManifoldPoint* pt = points + index; + + if ( pt->separation > speculativeDistance ) + { + continue; + } + + // The deeper the better + float score = -pt->separation + b3Dot( searchDirection, pt->point ); + if ( bias * score > bestScore ) + { + bestIndex = index; + bestScore = score; + } + } + + B3_VALIDATE( 0 <= bestIndex && bestIndex < count ); + if ( bestIndex == B3_NULL_INDEX ) + { + manifold->pointCount = 0; + return; + } + + manifold->points[0] = points[bestIndex]; + manifold->pointCount = 1; + + // Remove best point from array + points[bestIndex] = points[count - 1]; + count -= 1; + + b3Vec3 a = manifold->points[0].point; + + // Step 2: Find farthest point in 2D + bestScore = 0.0f; + bestIndex = B3_NULL_INDEX; + float maxDistanceSquared = 0.0f; + + for ( int index = 0; index < count; ++index ) + { + b3Vec3 p = points[index].point; + b3Vec3 d = b3Sub( p, a ); + b3Vec3 v = b3MulSub( d, b3Dot( d, normal ), normal ); + float distanceSquared = b3LengthSquared( v ); + maxDistanceSquared = b3MaxFloat( maxDistanceSquared, distanceSquared ); + float separation = b3MaxFloat( 0.0f, -points[index].separation ); + float score = distanceSquared + 4.0f * separation * separation; + if ( bias * score > bestScore ) + { + bestScore = score; + bestIndex = index; + } + } + + if ( bestScore < tolSqr ) + { + return; + } + + B3_ASSERT( 0 <= bestIndex && bestIndex < count ); + manifold->points[1] = points[bestIndex]; + manifold->pointCount = 2; + + // Remove best point from array + points[bestIndex] = points[count - 1]; + count -= 1; + + b3Vec3 b = manifold->points[1].point; + + // Step 3: Find the point with the maximum triangular area + bestScore = tolSqr; + bestIndex = B3_NULL_INDEX; + float bestSignedArea = 0.0f; + b3Vec3 ba = b3Sub( b, a ); + for ( int index = 0; index < count; ++index ) + { + b3Vec3 p = points[index].point; + float signedArea = b3Dot( normal, b3Cross( ba, b3Sub( p, a ) ) ); + float score = b3AbsFloat( signedArea ); + if ( bias * score >= bestScore ) + { + bestScore = score; + bestIndex = index; + bestSignedArea = signedArea; + } + } + + if ( bestIndex == B3_NULL_INDEX ) + { + return; + } + + B3_ASSERT( bestIndex != B3_NULL_INDEX ); + + manifold->points[2] = points[bestIndex]; + manifold->pointCount = 3; + points[bestIndex] = points[count - 1]; + count -= 1; + + b3Vec3 c = manifold->points[2].point; + + // Step 4: get the point that adds the most area outside the current triangle + bestScore = tolSqr; + bestIndex = B3_NULL_INDEX; + float sign = bestSignedArea < 0.0f ? -1.0f : 1.0f; + for ( int index = 0; index < count; ++index ) + { + b3Vec3 p = points[index].point; + float u1 = sign * b3Dot( normal, b3Cross( b3Sub( p, a ), ba ) ); + float u2 = sign * b3Dot( normal, b3Cross( b3Sub( p, b ), b3Sub( c, b ) ) ); + float u3 = sign * b3Dot( normal, b3Cross( b3Sub( p, c ), b3Sub( a, c ) ) ); + float score = b3MaxFloat( u1, b3MaxFloat( u2, u3 ) ); + + if ( bias * score > bestScore ) + { + bestScore = score; + bestIndex = index; + } + } + + if ( bestIndex != B3_NULL_INDEX ) + { + manifold->points[manifold->pointCount] = points[bestIndex]; + manifold->pointCount += 1; + } +} + +void b3CollideSpheres( b3LocalManifold* manifold, int capacity, const b3Sphere* sphereA, const b3Sphere* sphereB, + b3Transform transformBtoA ) +{ + if ( capacity == 0 ) + { + return; + } + + // Work in shapeB coordinates + b3Vec3 center1 = sphereA->center; + b3Vec3 center2 = b3TransformPoint( transformBtoA, sphereB->center ); + + float totalRadius = sphereA->radius + sphereB->radius; + b3Vec3 offset = b3Sub( center2, center1 ); + float distanceSq = b3LengthSquared( offset ); + + if ( distanceSq > totalRadius * totalRadius ) + { + // We found a separating axis + return; + } + + b3Vec3 normal = { 0.0f, 1.0f, 0.0f }; + float distance = sqrtf( distanceSq ); + if ( distance * distance > 1000.0f * FLT_MIN ) + { + normal = b3MulSV( 1.0f / distance, offset ); + } + + // Contact at the midpoint + // 0.5 * ( ((c1 + rA*n) + c2) - rB*n ) + b3Vec3 point = + b3MulSV( 0.5f, b3MulSub( b3Add( b3MulAdd( center1, sphereA->radius, normal ), center2 ), sphereB->radius, normal ) ); + + // Manifold in frame B + manifold->normal = normal; + manifold->pointCount = 1; + + b3LocalManifoldPoint* pt = manifold->points + 0; + pt->point = point; + pt->separation = distance - totalRadius; + pt->pair = b3FeaturePair_single; +} + +void b3CollideCapsuleAndSphere( b3LocalManifold* manifold, int capacity, const b3Capsule* capsuleA, const b3Sphere* sphereB, + b3Transform transformBtoA ) +{ + manifold->pointCount = 0; + + if ( capacity < 1 ) + { + return; + } + + // Work in shape B coordinates + b3Vec3 center = b3TransformPoint( transformBtoA, sphereB->center ); + b3Vec3 center1 = capsuleA->center1; + b3Vec3 center2 = capsuleA->center2; + + float totalRadius = sphereB->radius + capsuleA->radius; + + b3Vec3 closestPoint = b3ClosestPointOnSegment( center1, center2, center ); + b3Vec3 offset = b3Sub( center, closestPoint ); + float distanceSq = b3LengthSquared( offset ); + + if ( distanceSq > totalRadius * totalRadius ) + { + // We found a separating axis + return; + } + + b3Vec3 normal = { 0.0f, 1.0f, 0.0f }; + float distance = sqrtf( distanceSq ); + if ( distance * distance > 1000.0f * FLT_MIN ) + { + normal = b3MulSV( 1.0f / distance, offset ); + } + + // Contact at the midpoint + // 0.5 * (((center - sB*n) + closestPoint) + cA*n) + b3Vec3 point = + b3MulSV( 0.5f, b3MulAdd( b3Add( b3MulSub( center, sphereB->radius, normal ), closestPoint ), capsuleA->radius, normal ) ); + + // Manifold in frame B + manifold->normal = normal; + manifold->pointCount = 1; + + b3LocalManifoldPoint* pt = manifold->points + 0; + pt->point = point; + pt->separation = distance - totalRadius; + pt->pair = b3FeaturePair_single; +} + +void b3CollideHullAndSphere( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Sphere* sphereB, + b3Transform transformBtoA, b3SimplexCache* cache ) +{ + manifold->pointCount = 0; + + if ( capacity == 0 ) + { + return; + } + + b3Vec3 center = b3TransformPoint( transformBtoA, sphereB->center ); + + const float speculativeDistance = B3_SPECULATIVE_DISTANCE; + + // Work in shapeA coordinates + + b3DistanceInput distanceInput; + distanceInput.proxyA = (b3ShapeProxy){ b3GetHullPoints( hullA ), hullA->vertexCount, 0.0f }; + distanceInput.proxyB = (b3ShapeProxy){ ¢er, 1, 0.0f }; + distanceInput.transformA = b3Transform_identity; + distanceInput.transformB = b3Transform_identity; + distanceInput.useRadii = false; + + float radiusA = 0.0f; + float radiusB = sphereB->radius; + float radius = radiusA + radiusB; + + b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, cache, NULL, 0 ); + + if ( distanceOutput.distance > radius + speculativeDistance ) + { + // We found a separating axis + *cache = (b3SimplexCache){ 0 }; + return; + } + + if ( distanceOutput.distance > 100.0f * FLT_EPSILON ) + { + // Shallow penetration + b3Vec3 normal = b3Normalize( b3Sub( distanceOutput.pointB, distanceOutput.pointA ) ); + + // cA is the projection of the sphere center onto to the hull (pointA if radiusA == 0). + b3Vec3 cA = b3MulAdd( center, radiusA - b3Dot( b3Sub( center, distanceOutput.pointA ), normal ), normal ); + + // cB is the deepest point on the sphere with respect to the reference f + b3Vec3 cB = b3MulSub( center, radiusB, normal ); + + b3Vec3 point = b3Lerp( cA, cB, 0.5f ); + + // Manifold in frame A + manifold->normal = normal; + manifold->pointCount = 1; + + b3LocalManifoldPoint* pt = manifold->points + 0; + pt->point = point; + pt->separation = distanceOutput.distance - radius; + pt->pair = b3FeaturePair_single; + } + else + { + // Deep penetration + int bestIndex = -1; + float bestDistance = -FLT_MAX; + const b3Plane* planes = b3GetHullPlanes( hullA ); + + for ( int index = 0; index < hullA->faceCount; ++index ) + { + b3Plane plane = planes[index]; + + float distance = b3PlaneSeparation( plane, center ); + if ( distance > bestDistance ) + { + bestIndex = index; + bestDistance = distance; + } + } + B3_ASSERT( bestIndex >= 0 ); + + b3Vec3 normal = planes[bestIndex].normal; + + // cA is the projection of the sphere center onto to the hull + b3Vec3 cA = b3MulAdd( center, radiusA - b3Dot( b3Sub( center, distanceOutput.pointA ), normal ), normal ); + + // cB is the deepest point on the sphere with respect to the reference f + b3Vec3 cB = b3MulSub( center, radiusB, normal ); + + b3Vec3 point = b3Lerp( cA, cB, 0.5f ); + + // Manifold in frame A + manifold->normal = normal; + manifold->pointCount = 1; + + b3LocalManifoldPoint* pt = manifold->points + 0; + pt->point = point; + pt->separation = bestDistance - radius; + pt->pair = b3FeaturePair_single; + } +} + +void b3CollideCapsules( b3LocalManifold* manifold, int capacity, const b3Capsule* capsuleA, const b3Capsule* capsuleB, + b3Transform transformBtoA ) +{ + manifold->pointCount = 0; + + if ( capacity < 2 ) + { + return; + } + + // Work in shapeA coordinates + b3Vec3 centerA1 = capsuleA->center1; + b3Vec3 centerA2 = capsuleA->center2; + b3Vec3 centerB1 = b3TransformPoint( transformBtoA, capsuleB->center1 ); + b3Vec3 centerB2 = b3TransformPoint( transformBtoA, capsuleB->center2 ); + + float radius = capsuleA->radius + capsuleB->radius; + float maxDistance = radius + B3_SPECULATIVE_DISTANCE; + + b3ClosestApproachResult result = b3ClosestApproachSegments( centerA1, centerA2, centerB1, centerB2 ); + b3Vec3 offset = b3Sub( result.point2, result.point1 ); + float distanceSquared = b3LengthSquared( offset ); + float linearSlop = B3_LINEAR_SLOP; + float minDistance = 0.01f * linearSlop; + + if ( distanceSquared > maxDistance * maxDistance || distanceSquared < minDistance * minDistance ) + { + // We found a separating axis + return; + } + + float lengthA; + b3Vec3 segmentA = b3Sub( centerA2, centerA1 ); + b3Vec3 edgeA = b3GetLengthAndNormalize( &lengthA, segmentA ); + if ( lengthA < B3_MIN_CAPSULE_LENGTH ) + { + return; + } + + float lengthB; + b3Vec3 segmentB = b3Sub( centerB2, centerB1 ); + b3Vec3 edgeB = b3GetLengthAndNormalize( &lengthB, segmentB ); + if ( lengthB < B3_MIN_CAPSULE_LENGTH ) + { + return; + } + + // Parallel edges: |eA x eB| = sin(alpha) + const float alphaTol = 0.05f; + const float alphaTolSqr = alphaTol * alphaTol; + b3Vec3 axis = b3Cross( edgeA, edgeB ); + + // Try to create two contact points if the capsules are nearly parallel + if ( b3LengthSquared( axis ) < alphaTolSqr ) + { + // Clip segment B against side planes of segment A + + // Sides planes of A + b3Plane planesA[2]; + planesA[0].normal = b3Neg( edgeA ); + planesA[0].offset = -b3Dot( edgeA, capsuleA->center1 ); + planesA[1].normal = edgeA; + planesA[1].offset = b3Dot( edgeA, capsuleA->center2 ); + + // Clip points for B + b3ClipVertex verticesB[2]; + verticesB[0].position = centerB1; + verticesB[0].separation = 0.0f; + verticesB[0].pair = b3MakeFeaturePair( b3_featureShapeA, 0, b3_featureShapeA, 0 ); + verticesB[1].position = centerB2; + verticesB[1].separation = 0.0f; + verticesB[1].pair = b3MakeFeaturePair( b3_featureShapeA, 1, b3_featureShapeA, 1 ); + + int pointCount = b3ClipSegment( verticesB, planesA[0] ); + if ( pointCount == 2 ) + { + pointCount = b3ClipSegment( verticesB, planesA[1] ); + } + + if ( pointCount == 2 ) + { + // Closest points on A to the clipped points on B. + b3Vec3 closestPoint1 = b3ClosestPointOnSegment( centerA1, centerA2, verticesB[0].position ); + b3Vec3 closestPoint2 = b3ClosestPointOnSegment( centerA1, centerA2, verticesB[1].position ); + + float distance1 = b3Distance( closestPoint1, verticesB[0].position ); + float distance2 = b3Distance( closestPoint2, verticesB[1].position ); + if ( distance1 <= radius && distance2 <= radius ) + { + if ( distance1 < minDistance || distance2 < minDistance ) + { + // Avoid divide by zero + return; + } + + b3Vec3 normal1 = b3MulSV( 1.0f / distance1, b3Sub( closestPoint1, verticesB[0].position ) ); + b3Vec3 normal2 = b3MulSV( 1.0f / distance2, b3Sub( closestPoint2, verticesB[1].position ) ); + b3Vec3 normal = b3Normalize( b3Add( normal1, normal2 ) ); + float radiusA = capsuleA->radius; + float radiusB = capsuleB->radius; + + // Contact is at the midpoint: 0.5 * (((vB.pos + rA*nK) + cP) - rB*n) + b3Vec3 point1 = + b3MulSV( 0.5f, b3MulSub( b3Add( b3MulAdd( verticesB[0].position, radiusA, normal1 ), closestPoint1 ), radiusB, + normal ) ); + b3Vec3 point2 = + b3MulSV( 0.5f, b3MulSub( b3Add( b3MulAdd( verticesB[1].position, radiusA, normal2 ), closestPoint2 ), radiusB, + normal ) ); + + // Manifold in frame A + manifold->normal = normal; + manifold->pointCount = 2; + + b3LocalManifoldPoint* pt1 = manifold->points + 0; + pt1->point = point1; + pt1->separation = distance1 - radius; + pt1->pair = verticesB[0].pair; + + b3LocalManifoldPoint* pt2 = manifold->points + 1; + pt2->point = point2; + pt2->separation = distance2 - radius; + pt2->pair = verticesB[1].pair; + + return; + } + } + } + + float distance; + b3Vec3 normal = b3GetLengthAndNormalize( &distance, offset ); + // Contact at the midpoint 0.5 * (((p1 + rA*n) + p2) - rB*n) + b3Vec3 point = b3MulSV( + 0.5f, b3MulSub( b3Add( b3MulAdd( result.point1, capsuleA->radius, normal ), result.point2 ), capsuleB->radius, normal ) ); + + // Manifold in frame A + manifold->normal = normal; + manifold->pointCount = 1; + + b3LocalManifoldPoint* pt = manifold->points + 0; + pt->point = point; + pt->separation = distance - radius; + pt->pair = b3FeaturePair_single; +} + +static bool b3BuildHullFaceAndCapsuleContact( b3LocalManifold* manifold, const b3Hull* hullA, const b3Capsule* capsuleB, + b3Transform transformBtoA, b3FaceQuery query ) +{ + // Work in shapeA coordinates + const b3Plane* planes = b3GetHullPlanes( hullA ); + + // Clip the capsule edge against the side planes of the reference face + int refFace = query.faceIndex; + b3Plane refPlane = planes[refFace]; + + b3ClipVertex segmentB[2]; + segmentB[0].position = b3TransformPoint( transformBtoA, capsuleB->center1 ); + segmentB[0].separation = 0.0f; + segmentB[0].pair = b3MakeFeaturePair( b3_featureShapeA, 0, b3_featureShapeA, 0 ); + segmentB[1].position = b3TransformPoint( transformBtoA, capsuleB->center2 ); + segmentB[1].separation = 0.0f; + segmentB[1].pair = b3MakeFeaturePair( b3_featureShapeA, 1, b3_featureShapeA, 1 ); + + int pointCount = b3ClipSegmentToHullFace( segmentB, hullA, refFace ); + if ( pointCount < 2 ) + { + return false; + } + + float distance1 = b3PlaneSeparation( refPlane, segmentB[0].position ); + float distance2 = b3PlaneSeparation( refPlane, segmentB[1].position ); + const float speculativeDistance = B3_SPECULATIVE_DISTANCE; + + if ( distance1 <= speculativeDistance || distance2 <= speculativeDistance ) + { + b3Vec3 normal = refPlane.normal; + b3Vec3 point1 = b3MulSub( segmentB[0].position, 0.5f * ( distance1 + capsuleB->radius ), normal ); + b3Vec3 point2 = b3MulSub( segmentB[1].position, 0.5f * ( distance2 + capsuleB->radius ), normal ); + + // Manifold in frame A + manifold->normal = normal; + manifold->pointCount = 2; + + b3LocalManifoldPoint* pt1 = manifold->points + 0; + pt1->point = point1; + pt1->separation = distance1 - capsuleB->radius; + pt1->pair = segmentB[0].pair; + + b3LocalManifoldPoint* pt2 = manifold->points + 1; + pt2->point = point2; + pt2->separation = distance2 - capsuleB->radius; + pt2->pair = segmentB[1].pair; + + return true; + } + + return false; +} + +static inline float b3DeepestPointSeparation( const b3LocalManifold* manifold ) +{ + // Deepest point + float minSeparation = FLT_MAX; + int pointCount = manifold->pointCount; + for ( int i = 0; i < pointCount; ++i ) + { + minSeparation = b3MinFloat( minSeparation, manifold->points[i].separation ); + } + + return minSeparation; +} + +static bool b3BuildHullAndCapsuleEdgeContact( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, + const b3Capsule* capsuleB, b3Transform transformBtoA, b3EdgeQuery query ) +{ + if ( capacity < 1 ) + { + return false; + } + + // Work in shapeA coordinates + + b3Vec3 pc = b3TransformPoint( transformBtoA, capsuleB->center1 ); + b3Vec3 qc = b3TransformPoint( transformBtoA, capsuleB->center2 ); + b3Vec3 ec = b3Sub( qc, pc ); + + const b3HullHalfEdge* edges = b3GetHullEdges( hullA ); + const b3Vec3* points = b3GetHullPoints( hullA ); + + const b3HullHalfEdge* edge2 = edges + query.indexB; + const b3HullHalfEdge* twin2 = edges + edge2->twin; + b3Vec3 ch = hullA->center; + b3Vec3 ph = points[edge2->origin]; + b3Vec3 qh = points[twin2->origin]; + b3Vec3 eh = b3Sub( qh, ph ); + + b3Vec3 normal = b3Cross( ec, eh ); + normal = b3Normalize( normal ); + + // Normal should point outward from hull + if ( b3Dot( normal, b3Sub( ph, ch ) ) < 0.0f ) + { + normal = b3Neg( normal ); + } + + b3ClosestApproachResult result = b3ClosestApproachLines( ph, eh, pc, ec ); + + if ( b3IsWithinSegments( &result ) == false ) + { + // closest point beyond end points + return false; + } + + b3Vec3 point = b3MulSV( 0.5f, b3Add( b3MulSub( result.point1, capsuleB->radius, normal ), result.point2 ) ); + + float separation = b3Dot( normal, b3Sub( result.point2, result.point1 ) ); + B3_VALIDATE( b3AbsFloat( separation - query.separation ) < B3_LINEAR_SLOP ); + + // Manifold in frame A + manifold->normal = normal; + manifold->pointCount = 1; + + b3LocalManifoldPoint* pt = manifold->points + 0; + pt->point = point; + pt->separation = separation - capsuleB->radius; + pt->pair = b3MakeFeaturePair( b3_featureShapeA, query.indexA, b3_featureShapeB, query.indexB ); + return true; +} + +void b3CollideHullAndCapsule( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Capsule* capsuleB, + b3Transform transformBtoA, b3SimplexCache* cache ) +{ + manifold->pointCount = 0; + + if ( capacity < 2 ) + { + return; + } + + // Work in shapeA coordinates + b3DistanceInput distanceInput; + distanceInput.proxyA = (b3ShapeProxy){ b3GetHullPoints( hullA ), hullA->vertexCount, 0.0f }; + distanceInput.proxyB = (b3ShapeProxy){ &capsuleB->center1, 2, 0.0f }; + distanceInput.transformA = b3Transform_identity; + distanceInput.transformB = transformBtoA; + distanceInput.useRadii = false; + + b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, cache, NULL, 0 ); + const float speculativeDistance = B3_SPECULATIVE_DISTANCE; + + if ( distanceOutput.distance > capsuleB->radius + speculativeDistance ) + { + // We found a separating axis + *cache = (b3SimplexCache){ 0 }; + return; + } + + if ( distanceOutput.distance > 100.0f * FLT_EPSILON ) + { + const b3Plane* planes = b3GetHullPlanes( hullA ); + + // Shallow penetration + b3Vec3 delta = distanceOutput.normal; + int refFace = b3FindHullSupportFace( hullA, delta ); + b3Plane refPlane = planes[refFace]; + + // Try to create two contact points if closest + // points difference is nearly parallel to face normal + const float kTolerance = 0.998f; + if ( b3AbsFloat( b3Dot( refPlane.normal, delta ) ) > kTolerance ) + { + // Clip capsule segment against side planes of reference face + b3ClipVertex verticesB[2]; + verticesB[0].position = b3TransformPoint( transformBtoA, capsuleB->center1 ); + verticesB[0].separation = 0.0f; + verticesB[0].pair = b3MakeFeaturePair( b3_featureShapeA, 0, b3_featureShapeA, 0 ); + verticesB[1].position = b3TransformPoint( transformBtoA, capsuleB->center2 ); + verticesB[1].separation = 0.0f; + verticesB[1].pair = b3MakeFeaturePair( b3_featureShapeA, 1, b3_featureShapeA, 1 ); + + int pointCount = b3ClipSegmentToHullFace( verticesB, hullA, refFace ); + + if ( pointCount == 2 ) + { + float distance1 = b3PlaneSeparation( refPlane, verticesB[0].position ); + float distance2 = b3PlaneSeparation( refPlane, verticesB[1].position ); + if ( distance1 <= capsuleB->radius + speculativeDistance || distance2 <= capsuleB->radius + speculativeDistance ) + { + b3Vec3 normal = refPlane.normal; + b3Vec3 point1 = b3MulSub( verticesB[0].position, 0.5f * ( capsuleB->radius + distance1 ), normal ); + b3Vec3 point2 = b3MulSub( verticesB[1].position, 0.5f * ( capsuleB->radius + distance2 ), normal ); + + // Manifold in frame A + manifold->normal = normal; + manifold->pointCount = 2; + + b3LocalManifoldPoint* pt1 = manifold->points + 0; + pt1->point = point1; + pt1->separation = distance1 - capsuleB->radius; + pt1->pair = verticesB[0].pair; + + b3LocalManifoldPoint* pt2 = manifold->points + 1; + pt2->point = point2; + pt2->separation = distance2 - capsuleB->radius; + pt2->pair = verticesB[1].pair; + + return; + } + } + } + + // Create contact from closest points + b3Vec3 point = + b3MulSV( 0.5f, b3Add( b3MulSub( distanceOutput.pointA, capsuleB->radius, delta ), distanceOutput.pointB ) ); + + // Manifold in frame A + manifold->normal = delta; + manifold->pointCount = 1; + + b3LocalManifoldPoint* pt = manifold->points + 0; + pt->point = point; + pt->separation = distanceOutput.distance - capsuleB->radius; + pt->pair = b3FeaturePair_single; + return; + } + + // Deep penetration + + b3FaceQuery faceQuery = b3QueryFaceDirectionHullAndCapsule( hullA, capsuleB, transformBtoA ); + if ( faceQuery.separation > capsuleB->radius ) + { + // We found a separating axis + return; + } + + b3EdgeQuery edgeQuery = b3QueryEdgeDirectionHullAndCapsule( hullA, capsuleB, transformBtoA ); + if ( edgeQuery.separation > capsuleB->radius ) + { + // We found a separating axis + return; + } + + // Create face contact + float faceSeparation = faceQuery.separation - capsuleB->radius; + b3BuildHullFaceAndCapsuleContact( manifold, hullA, capsuleB, transformBtoA, faceQuery ); + if ( manifold->pointCount > 1 ) + { + // If ( Out.PointCount <= 1 ) -> Compare with unclipped separation + // If ( Out.PointCount > 1 ) -> Be aggressive and compare with clipped separation + // Face contact can be empty if it does not realize the axis of minimum penetration + faceSeparation = b3DeepestPointSeparation( manifold ); + } + B3_VALIDATE( faceSeparation <= 0.0f ); + + // Face contact can be empty if it does not realize the axis of minimum penetration. + // Create edge contact if face contact fails or edge contact is significantly better! + const float kRelEdgeTolerance = 0.90f; + const float kAbsTolerance = 0.5f * B3_LINEAR_SLOP; + float edgeSeparation = edgeQuery.separation - capsuleB->radius; + if ( manifold->pointCount == 0 || edgeSeparation > kRelEdgeTolerance * faceSeparation + kAbsTolerance ) + { + // Edge contact + b3BuildHullAndCapsuleEdgeContact( manifold, capacity, hullA, capsuleB, transformBtoA, edgeQuery ); + } +} + +static int b3BuildPolygon( b3ClipVertex* out, b3Transform transform, const b3Hull* hull, int incFace, b3Plane refPlane ) +{ + const b3HullFace* faces = b3GetHullFaces( hull ); + const b3HullHalfEdge* edges = b3GetHullEdges( hull ); + const b3Vec3* points = b3GetHullPoints( hull ); + + const b3HullFace* face = faces + incFace; + int edgeIndex = face->edge; + B3_ASSERT( edges[edgeIndex].face == incFace ); + + int outCount = 0; + + b3Matrix3 matrix = b3MakeMatrixFromQuat( transform.q ); + + do + { + const b3HullHalfEdge* edge = edges + edgeIndex; + + int nextEdgeIndex = edge->next; + const b3HullHalfEdge* next = edges + nextEdgeIndex; + + b3ClipVertex vertex; + vertex.position = b3Add( b3MulMV( matrix, points[next->origin] ), transform.p ); + vertex.separation = b3PlaneSeparation( refPlane, vertex.position ); + vertex.pair = b3MakeFeaturePair( b3_featureShapeB, edgeIndex, b3_featureShapeB, nextEdgeIndex ); + + out[outCount] = vertex; + outCount += 1; + + edgeIndex = nextEdgeIndex; + } + while ( edgeIndex != face->edge && outCount < B3_MAX_CLIP_POINTS ); + + B3_VALIDATE( b3ValidatePolygon( out, outCount ) ); + + return outCount; +} + +static bool b3BuildFaceAContact( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Hull* hullB, + b3Transform transformBtoA, b3FaceQuery query, b3SATCache* cache ) +{ + const b3HullFace* facesA = b3GetHullFaces( hullA ); + const b3HullHalfEdge* edgesA = b3GetHullEdges( hullA ); + const b3Plane* planesA = b3GetHullPlanes( hullA ); + const b3Vec3* pointsA = b3GetHullPoints( hullA ); + + // Reference face + int refFace = query.faceIndex; + b3Plane refPlane = planesA[refFace]; + + // Find incident face + b3Vec3 refNormalInB = b3InvRotateVector( transformBtoA.q, refPlane.normal ); + int incFace = b3FindIncidentFace( hullB, refNormalInB, query.vertexIndex ); + + // Build clip polygon from incident face in frame A + b3ClipVertex buffer1[B3_MAX_CLIP_POINTS], buffer2[B3_MAX_CLIP_POINTS]; + int pointCount = b3BuildPolygon( buffer1, transformBtoA, hullB, incFace, refPlane ); + + // Clip incident face against side planes of reference face + b3ClipVertex* input = buffer1; + b3ClipVertex* output = buffer2; + + const b3HullFace* face = facesA + refFace; + int edgeIndex = face->edge; + + do + { + const b3HullHalfEdge* edge = edgesA + edgeIndex; + int nextEdgeIndex = edge->next; + const b3HullHalfEdge* next = edgesA + nextEdgeIndex; + b3Vec3 vertex1 = pointsA[edge->origin]; + b3Vec3 vertex2 = pointsA[next->origin]; + b3Vec3 tangent = b3Normalize( b3Sub( vertex2, vertex1 ) ); + b3Vec3 binormal = b3Cross( tangent, refPlane.normal ); + + b3Plane clipPlane = b3MakePlaneFromNormalAndPoint( binormal, vertex1 ); + + pointCount = b3ClipPolygon( output, input, pointCount, clipPlane, edgeIndex, refPlane ); + B3_ASSERT( pointCount <= B3_MAX_CLIP_POINTS ); + + B3_SWAP( output, input ); + + if ( pointCount < 3 ) + { + *cache = (b3SATCache){ 0 }; + return false; + } + + edgeIndex = nextEdgeIndex; + } + while ( edgeIndex != face->edge ); + + pointCount = b3MinInt( pointCount, B3_MAX_CLIP_POINTS ); + + b3LocalManifoldPoint points[B3_MAX_CLIP_POINTS]; + float minSeparation = FLT_MAX; + + manifold->normal = refPlane.normal; + + for ( int i = 0; i < pointCount; ++i ) + { + b3ClipVertex* clipPoint = input + i; + b3LocalManifoldPoint* pt = points + i; + *pt = (b3LocalManifoldPoint){ 0 }; + + // Using the half-way point keeps the points in the same position when swapping reference face from A to B. + b3Vec3 point = b3MulSub( clipPoint->position, 0.5f * clipPoint->separation, refPlane.normal ); + + // Old way of pushing onto the reference face. + // b3Vec3 point = clipPoint->position - clipPoint->separation * refPlane.normal; + + pt->normal = manifold->normal; + pt->point = point; + pt->separation = clipPoint->separation; + pt->pair = clipPoint->pair; + + minSeparation = b3MinFloat( minSeparation, clipPoint->separation ); + } + + if ( minSeparation >= B3_SPECULATIVE_DISTANCE ) + { + *cache = (b3SATCache){ 0 }; + return false; + } + + b3ReduceManifoldPoints( manifold, capacity, points, pointCount ); + + // Save cache + cache->separation = minSeparation; + cache->type = (uint8_t)b3_faceAxisA; + cache->indexA = (uint8_t)query.faceIndex; + cache->indexB = (uint8_t)query.vertexIndex; + + return true; +} + +static bool b3BuildFaceBContact( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Hull* hullB, + b3Transform transformBtoA, b3FaceQuery query, b3SATCache* cache ) +{ + b3Transform transformAtoB = b3InvertTransform( transformBtoA ); + bool touching = b3BuildFaceAContact( manifold, capacity, hullB, hullA, transformAtoB, query, cache ); + if ( touching == false ) + { + return false; + } + + // Results are in frame B, need to transform them into frame A + b3Matrix3 matrix = b3MakeMatrixFromQuat( transformBtoA.q ); + + // Transform and flip normal so it points from A to B, even though the B has the reference face. + manifold->normal = b3Neg( b3MulMV( matrix, manifold->normal ) ); + cache->type = (uint8_t)b3_faceAxisB; + cache->indexA = (uint8_t)query.vertexIndex; + cache->indexB = (uint8_t)query.faceIndex; + + // Transform points from frame B to frame A. + // Also flip the pairs to ensure correct matches. + for ( int i = 0; i < manifold->pointCount; ++i ) + { + b3LocalManifoldPoint* pt = manifold->points + i; + pt->point = b3Add( b3MulMV( matrix, pt->point ), transformBtoA.p ); + pt->pair = b3FlipPair( pt->pair ); + } + + return true; +} + +static bool b3BuildEdgeContact( b3LocalManifold* manifold, const b3Hull* hullA, const b3Hull* hullB, b3Transform transformBtoA, + b3EdgeQuery query, b3SATCache* cache ) +{ + // Work in shapeA coordinates + const b3HullHalfEdge* edgesA = b3GetHullEdges( hullA ); + const b3Vec3* pointsA = b3GetHullPoints( hullA ); + + const b3HullHalfEdge* edgesB = b3GetHullEdges( hullB ); + const b3Vec3* pointsB = b3GetHullPoints( hullB ); + + // B3_VALIDATE( query.separation <= 2.0f * B3_SPECULATIVE_DISTANCE ); + + const b3HullHalfEdge* edgeA = edgesA + query.indexA; + const b3HullHalfEdge* twinA = edgesA + edgeA->twin; + b3Vec3 centerA = hullA->center; + b3Vec3 pA = pointsA[edgeA->origin]; + b3Vec3 qA = pointsA[twinA->origin]; + b3Vec3 eA = b3Sub( qA, pA ); + + const b3HullHalfEdge* edgeB = edgesB + query.indexB; + const b3HullHalfEdge* twinB = edgesB + edgeB->twin; + b3Vec3 pB = b3TransformPoint( transformBtoA, pointsB[edgeB->origin] ); + b3Vec3 qB = b3TransformPoint( transformBtoA, pointsB[twinB->origin] ); + b3Vec3 eB = b3Sub( qB, pB ); + + b3Vec3 normal = b3Cross( eA, eB ); + normal = b3Normalize( normal ); + + if ( b3Dot( normal, b3Sub( pA, centerA ) ) < 0.0f ) + { + normal = b3Neg( normal ); + } + + b3ClosestApproachResult result = b3ClosestApproachLines( pA, eA, pB, eB ); + + if ( b3IsWithinSegments( &result ) == false ) + { + *cache = (b3SATCache){ 0 }; + return false; + } + + // This can slide off the end from caching + float separation = b3Dot( normal, b3Sub( result.point2, result.point1 ) ); + + // todo I suspect this could trip if the cache becomes invalid + // B3_VALIDATE( b3AbsFloat( separation - query.separation ) < B3_LINEAR_SLOP ); + + b3Vec3 point = b3MulSV( 0.5f, b3Add( result.point1, result.point2 ) ); + + // Result in frame A + manifold->normal = normal; + manifold->pointCount = 1; + + b3LocalManifoldPoint* pt = manifold->points + 0; + pt->point = point; + pt->separation = separation; + pt->pair = b3MakeFeaturePair( b3_featureShapeA, query.indexA, b3_featureShapeB, query.indexB ); + + // Save cache + cache->separation = separation; + cache->type = (uint8_t)b3_edgePairAxis; + cache->indexA = (uint8_t)query.indexA; + cache->indexB = (uint8_t)query.indexB; + + return true; +} + +void b3CollideHulls( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Hull* hullB, b3Transform transformBtoA, + b3SATCache* cache ) +{ + manifold->pointCount = 0; + + if ( capacity < 4 ) + { + return; + } + + // Work in shapeA coordinates + float speculativeDistance = B3_SPECULATIVE_DISTANCE; + + float linearSlop = B3_LINEAR_SLOP; + const b3HullHalfEdge* edgesA = b3GetHullEdges( hullA ); + const b3Plane* planesA = b3GetHullPlanes( hullA ); + const b3Vec3* pointsA = b3GetHullPoints( hullA ); + + const b3HullHalfEdge* edgesB = b3GetHullEdges( hullB ); + const b3Plane* planesB = b3GetHullPlanes( hullB ); + const b3Vec3* pointsB = b3GetHullPoints( hullB ); + + // Attempt to use the cache to speed up collision + switch ( cache->type ) + { + case b3_invalidAxis: + *cache = (b3SATCache){ 0 }; + break; + + case b3_faceAxisA: + { + B3_ASSERT( cache->indexA < hullA->faceCount ); + + // Check for separation using cached face + b3Plane plane = planesA[cache->indexA]; + b3Vec3 searchDirectionInB = b3Neg( b3InvRotateVector( transformBtoA.q, plane.normal ) ); + int vertexIndex = b3FindHullSupportVertex( hullB, searchDirectionInB ); + b3Vec3 support = b3TransformPoint( transformBtoA, pointsB[vertexIndex] ); + float separation = b3PlaneSeparation( plane, support ); + + if ( separation >= speculativeDistance ) + { + // Cache hit, shapes are separated + return; + } + + // if ( cache->separation < speculativeDistance ) + { + // Attempt face contact using cached feature + b3FaceQuery faceQuery; + faceQuery.separation = 0.0f; + faceQuery.faceIndex = cache->indexA; + faceQuery.vertexIndex = vertexIndex; + + b3SATCache localCache = { 0 }; + bool touching = b3BuildFaceAContact( manifold, capacity, hullA, hullB, transformBtoA, faceQuery, &localCache ); + if ( touching == true && b3AbsFloat( cache->separation - localCache.separation ) < linearSlop ) + { + // Cache hit, contact points generated + return; + } + } + } + break; + + case b3_faceAxisB: + { + B3_ASSERT( cache->indexB < hullB->faceCount ); + + // Check for separation using cached face + b3Plane plane = planesB[cache->indexB]; + b3Vec3 searchDirectionInA = b3Neg( b3RotateVector( transformBtoA.q, plane.normal ) ); + int vertexIndex = b3FindHullSupportVertex( hullA, searchDirectionInA ); + b3Vec3 support = b3InvTransformPoint( transformBtoA, pointsA[vertexIndex] ); + float separation = b3PlaneSeparation( plane, support ); + + if ( separation >= speculativeDistance ) + { + // Cache hit, shapes are separated + return; + } + + // if ( cache->separation < speculativeDistance ) + { + // Attempt face contact using cached feature + b3FaceQuery faceQuery; + faceQuery.separation = 0.0f; + faceQuery.faceIndex = cache->indexB; + faceQuery.vertexIndex = vertexIndex; + + b3SATCache localCache = { 0 }; + bool touching = b3BuildFaceBContact( manifold, capacity, hullA, hullB, transformBtoA, faceQuery, &localCache ); + if ( touching == true && b3AbsFloat( cache->separation - localCache.separation ) < linearSlop ) + { + // Cache hit, contact points generated + return; + } + } + } + break; + + case b3_edgePairAxis: + { + int index1 = cache->indexA; + const b3HullHalfEdge* edge1 = edgesA + index1; + const b3HullHalfEdge* twin1 = edgesA + index1 + 1; + B3_ASSERT( edge1->twin == index1 + 1 && twin1->twin == index1 ); + + b3Vec3 p1 = pointsA[edge1->origin]; + b3Vec3 q1 = pointsA[twin1->origin]; + b3Vec3 e1 = b3Sub( q1, p1 ); + + b3Vec3 u1 = planesA[edge1->face].normal; + b3Vec3 v1 = planesA[twin1->face].normal; + + int index2 = cache->indexB; + const b3HullHalfEdge* edge2 = edgesB + index2; + const b3HullHalfEdge* twin2 = edgesB + index2 + 1; + B3_ASSERT( edge2->twin == index2 + 1 && twin2->twin == index2 ); + + b3Vec3 p2 = b3TransformPoint( transformBtoA, pointsB[edge2->origin] ); + b3Vec3 q2 = b3TransformPoint( transformBtoA, pointsB[twin2->origin] ); + b3Vec3 e2 = b3Sub( q2, p2 ); + + b3Vec3 u2 = b3RotateVector( transformBtoA.q, planesB[edge2->face].normal ); + b3Vec3 v2 = b3RotateVector( transformBtoA.q, planesB[twin2->face].normal ); + + // flipping the signs of u2 and v2 + // cross(v2, u2) == cross(-v2, -u2) + // so we still use -e2 + // but we can also use e1 = cross(u1, v1) and e2 = cross(u2, v2) + bool isMinkowski = b3IsMinkowskiFace( u1, v1, e1, b3Neg( u2 ), b3Neg( v2 ), e2 ); + if ( isMinkowski == true ) + { + // Transform reference center of the first hull into local space of the second hull + b3Vec3 c1 = hullA->center; + b3Vec3 c2 = b3TransformPoint( transformBtoA, hullB->center ); + + float separation = b3EdgeEdgeSeparation( p1, e1, c1, p2, e2, c2 ); + if ( separation > speculativeDistance ) + { + // Cache hit, shapes are separated + return; + } + + // if ( cache->separation <= speculativeDistance ) + { + // Try to rebuild contact from last features + b3EdgeQuery edgeQuery; + edgeQuery.indexA = cache->indexA; + edgeQuery.indexB = cache->indexB; + edgeQuery.separation = 0.0f; + + b3SATCache localCache = { 0 }; + bool touching = b3BuildEdgeContact( manifold, hullA, hullB, transformBtoA, edgeQuery, &localCache ); + if ( touching && b3AbsFloat( cache->separation - localCache.separation ) < linearSlop ) + { + // Cache hit, contact point generated + return; + } + } + } + } + break; + + // This case is for testing + case b3_manualFaceAxisA: + { + b3FaceQuery faceQueryA = b3QueryFaceDirections( hullA, hullB, transformBtoA ); + b3BuildFaceAContact( manifold, capacity, hullA, hullB, transformBtoA, faceQueryA, cache ); + return; + } + + // This case is for testing + case b3_manualFaceAxisB: + { + b3FaceQuery faceQueryB = b3QueryFaceDirections( hullB, hullA, b3InvertTransform( transformBtoA ) ); + b3BuildFaceBContact( manifold, capacity, hullA, hullB, transformBtoA, faceQueryB, cache ); + return; + } + + // This case is for testing + case b3_manualEdgePairAxis: + { + b3EdgeQuery edgeQuery = b3QueryEdgeDirections( hullA, hullB, transformBtoA ); + if ( edgeQuery.indexA != B3_NULL_INDEX ) + { + b3BuildEdgeContact( manifold, hullA, hullB, transformBtoA, edgeQuery, cache ); + } + return; + } + + default: + B3_ASSERT( false ); + break; + } + + manifold->pointCount = 0; + *cache = (b3SATCache){ 0 }; + + // Find axis of minimum penetration + b3FaceQuery faceQueryA = b3QueryFaceDirections( hullA, hullB, transformBtoA ); + if ( faceQueryA.separation > speculativeDistance ) + { + B3_ASSERT( faceQueryA.faceIndex < hullA->faceCount ); + B3_ASSERT( faceQueryA.vertexIndex < hullB->vertexCount ); + + // We found a separating axis + cache->separation = faceQueryA.separation; + cache->type = (uint8_t)b3_faceAxisA; + cache->indexA = (uint8_t)faceQueryA.faceIndex; + cache->indexB = (uint8_t)faceQueryA.vertexIndex; + return; + } + + b3FaceQuery faceQueryB = b3QueryFaceDirections( hullB, hullA, b3InvertTransform( transformBtoA ) ); + if ( faceQueryB.separation > speculativeDistance ) + { + B3_ASSERT( faceQueryB.faceIndex < hullB->faceCount ); + B3_ASSERT( faceQueryB.vertexIndex < hullA->vertexCount ); + + // We found a separating axis + cache->separation = faceQueryB.separation; + cache->type = (uint8_t)b3_faceAxisB; + cache->indexA = (uint8_t)faceQueryB.vertexIndex; + cache->indexB = (uint8_t)faceQueryB.faceIndex; + return; + } + + b3EdgeQuery edgeQuery = b3QueryEdgeDirections( hullA, hullB, transformBtoA ); + if ( edgeQuery.separation > speculativeDistance ) + { + // We found a separating axis + cache->separation = edgeQuery.separation; + cache->type = (uint8_t)b3_edgePairAxis; + cache->indexA = (uint8_t)edgeQuery.indexA; + cache->indexB = (uint8_t)edgeQuery.indexB; + return; + } + + // Always build a face contact (e.g. Jenga problem) + float faceSeparationA = faceQueryA.separation; + float faceSeparationB = faceQueryB.separation; + B3_VALIDATE( faceSeparationA <= speculativeDistance && faceSeparationB <= speculativeDistance ); + + if ( faceSeparationB > faceSeparationA + 0.5f * linearSlop ) + { + // Face contact B + b3BuildFaceBContact( manifold, capacity, hullA, hullB, transformBtoA, faceQueryB, cache ); + } + else + { + // Face contact A + b3BuildFaceAContact( manifold, capacity, hullA, hullB, transformBtoA, faceQueryA, cache ); + } + + if ( edgeQuery.indexA == B3_NULL_INDEX ) + { + // There are no valid edge pairs (all edges parallel) + return; + } + + float clippedFaceSeparation = cache->separation; + + B3_VALIDATE( edgeQuery.separation <= speculativeDistance ); + + // todo get rid of relative tolerance + const float kRelEdgeTolerance = 0.90f; + // const float kRelFaceTolerance = 0.98f; + const float kAbsTolerance = 0.5f * linearSlop; + + // Face contact can be empty if it does not realize the axis of minimum penetration. + // Create edge contact if face contact fails or edge contact is significantly better! + if ( manifold->pointCount == 0 || edgeQuery.separation > kRelEdgeTolerance * clippedFaceSeparation + kAbsTolerance ) + { + // Edge contact + b3LocalManifold edgeManifold = { 0 }; + b3LocalManifoldPoint edgePoint = { 0 }; + edgeManifold.points = &edgePoint; + + b3BuildEdgeContact( &edgeManifold, hullA, hullB, transformBtoA, edgeQuery, cache ); + + // It is possible with speculation to have vertex-vertex collision that is missed by SAT. + // todo I doubt this backup scheme matters because I'm using the clipped face separation. + // B3_VALIDATE( edgeManifold.pointCount == 1 ); + + if ( edgeManifold.pointCount == 1 ) + { + // Copy edge manifold out, being careful to preserve manifold point buffer. + b3LocalManifoldPoint* points = manifold->points; + *manifold = edgeManifold; + manifold->points = points; + manifold->points[0] = edgePoint; + } + } +} diff --git a/src/core.c b/src/core.c new file mode 100644 index 0000000..63fd099 --- /dev/null +++ b/src/core.c @@ -0,0 +1,345 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#if defined( B3_COMPILER_MSVC ) +// CRTDBG requires these to be included first +#define _CRTDBG_MAP_ALLOC +#include +#include +#else +#include +#endif + +#include "core.h" + +#include "box3d/constants.h" +#include "box3d/math_functions.h" + +#include +#include + +#ifdef BOX2D_PROFILE + +#include +#define b3TracyCAlloc( ptr, size ) TracyCAlloc( ptr, size ) +#define b3TracyCFree( ptr ) TracyCFree( ptr ) + +#else + +#define b3TracyCAlloc( ptr, size ) +#define b3TracyCFree( ptr ) + +#endif + +#include "platform.h" + +#include + +// This allows the user to change the length units at runtime +float b3_lengthUnitsPerMeter = 1.0f; + +void b3SetLengthUnitsPerMeter( float lengthUnits ) +{ + B3_ASSERT( b3IsValidFloat( lengthUnits ) && lengthUnits > 0.0f ); + b3_lengthUnitsPerMeter = lengthUnits; +} + +float b3GetLengthUnitsPerMeter( void ) +{ + return b3_lengthUnitsPerMeter; +} + +static int b3DefaultAssertFcn( const char* condition, const char* fileName, int lineNumber ) +{ + printf( "BOX3D ASSERTION: %s, %s, line %d\n", condition, fileName, lineNumber ); + + // return non-zero to break to debugger + return 1; +} + +b3AssertFcn* b3AssertHandler = b3DefaultAssertFcn; + +void b3SetAssertFcn( b3AssertFcn* assertFcn ) +{ + B3_ASSERT( assertFcn != NULL ); + b3AssertHandler = assertFcn; +} + +#if !defined( NDEBUG ) || defined( B3_ENABLE_ASSERT ) +int b3InternalAssert( const char* condition, const char* fileName, int lineNumber ) +{ + int result = b3AssertHandler( condition, fileName, lineNumber ); + if ( result ) + { + B3_BREAKPOINT; + } + return result; +} +#endif + +static void b3DefaultLogFcn( const char* message ) +{ + printf( "Box3D: %s\n", message ); +} + +b3LogFcn* b3LogHandler = b3DefaultLogFcn; + +void b3SetLogFcn( b3LogFcn* logFcn ) +{ + B3_ASSERT( logFcn != NULL ); + b3LogHandler = logFcn; +} + +void b3Log( const char* format, ... ) +{ + va_list args; + va_start( args, format ); + char buffer[512]; + vsnprintf( buffer, sizeof( buffer ), format, args ); + b3LogHandler( buffer ); + va_end( args ); +} + +b3Version b3GetVersion( void ) +{ + return (b3Version){ 0, 2, 0 }; +} + +static b3AllocFcn* b3_allocFcn = NULL; +static b3FreeFcn* b3_freeFcn = NULL; + +b3AtomicInt b3_byteCount; + +void b3SetAllocator( b3AllocFcn* allocFcn, b3FreeFcn* freeFcn ) +{ + b3_allocFcn = allocFcn; + b3_freeFcn = freeFcn; +} + +// Use 64 byte alignment for everything to align to 64 byte cache line and works with 256bit SIMD. +#define B3_ALIGNMENT 64 + +void* b3Alloc( size_t size ) +{ + if ( size == 0 ) + { + return NULL; + } + + // This could cause some sharing issues, however Box3D rarely calls b3Alloc. + // todo this is not true, Box3D allocates a lot. + b3AtomicFetchAddInt( &b3_byteCount, (int)size ); + + // Allocation must be a multiple of 32 or risk a seg fault + // https://en.cppreference.com/w/c/memory/aligned_alloc + int size64 = ( ( (int)size - 1 ) | 0x3F ) + 1; + + if ( b3_allocFcn != NULL ) + { + void* ptr = b3_allocFcn( size64, B3_ALIGNMENT ); + b3TracyCAlloc( ptr, size ); + + B3_ASSERT( ptr != NULL ); + B3_ASSERT( ( (uintptr_t)ptr & 0x3F ) == 0 ); + + return ptr; + } + +#ifdef B3_PLATFORM_WINDOWS + void* ptr = _aligned_malloc( size64, B3_ALIGNMENT ); +#elif defined( B3_PLATFORM_ANDROID ) + void* ptr = NULL; + if ( posix_memalign( &ptr, B3_ALIGNMENT, size64 ) != 0 ) + { + // allocation failed, exit the application + exit( EXIT_FAILURE ); + } +#else + void* ptr = aligned_alloc( B3_ALIGNMENT, size64 ); +#endif + + b3TracyCAlloc( ptr, size ); + + B3_ASSERT( ptr != NULL ); + B3_ASSERT( ( (uintptr_t)ptr & 0x3F ) == 0 ); + + return ptr; +} + +void b3Free( void* mem, size_t size ) +{ + if ( mem == NULL ) + { + return; + } + + b3TracyCFree( mem ); + + if ( b3_freeFcn != NULL ) + { + b3_freeFcn( mem ); + } + else + { +#ifdef B3_PLATFORM_WINDOWS + _aligned_free( mem ); +#else + free( mem ); +#endif + } + + b3AtomicFetchAddInt( &b3_byteCount, -(int)size ); +} + +void* b3GrowAlloc( void* oldMem, int oldSize, int newSize ) +{ + // todo try _aligned_realloc + + B3_ASSERT( newSize > oldSize ); + void* newMem = b3Alloc( newSize ); + if ( oldSize > 0 ) + { + memcpy( newMem, oldMem, oldSize ); + b3Free( oldMem, oldSize ); + } + return newMem; +} + +int b3GetByteCount( void ) +{ + return b3AtomicLoadInt( &b3_byteCount ); +} + +void* b3AllocZeroed( size_t size ) +{ + void* mem = b3Alloc( size ); + memset( mem, 0, size ); + return mem; +} + +static FILE* b3OpenFile( const char* fileName, const char* mode ) +{ + FILE* file = NULL; + +#if defined( _MSC_VER ) + errno_t e = fopen_s( &file, fileName, mode ); + if ( e != 0 ) + { + return NULL; + } +#else + file = fopen( fileName, mode ); + if ( file == NULL ) + { + return NULL; + } +#endif + + return file; +} + +FILE* b3_dumpFile = NULL; +int b3_meshIndex = 0; + +void b3OpenDump( const char* fileName ) +{ + B3_ASSERT( b3_dumpFile == NULL ); + b3_dumpFile = b3OpenFile( fileName, "w" ); +} + +void b3Dump( const char* string, ... ) +{ + if ( b3_dumpFile == NULL ) + { + return; + } + + va_list args; + va_start( args, string ); + vfprintf( b3_dumpFile, string, args ); + va_end( args ); +} + +void b3CloseDump( void ) +{ + fclose( b3_dumpFile ); + b3_dumpFile = NULL; +} + +int b3FetchAddMeshDumpIndex( void ) +{ + int result = b3_meshIndex; + b3_meshIndex += 1; + return result; +} + +void b3WriteBinaryFile( void* data, int size, const char* fileName ) +{ + if ( data == NULL || size <= 0 || fileName == NULL ) + { + return; + } + + FILE* file = b3OpenFile( fileName, "wb" ); + if ( file == NULL ) + { + return; + } + + // Write binary blob; ignore partial-write errors for simplicity + (void)fwrite( data, 1, (size_t)size, file ); + fclose( file ); +} + +void* b3ReadBinaryFile( const char* prefix, const char* fileName, int* memSize ) +{ + *memSize = 0; + + if ( prefix == NULL || fileName == NULL ) + { + return NULL; + } + + char buffer[128]; + snprintf( buffer, sizeof( buffer ), "%s%s", prefix, fileName ); + + FILE* file = b3OpenFile( buffer, "rb" ); + if ( file == NULL ) + { + return NULL; + } + + // Determine file size + if ( fseek( file, 0, SEEK_END ) != 0 ) + { + fclose( file ); + return NULL; + } + + long size = ftell( file ); + if ( size <= 0 ) + { + fclose( file ); + return NULL; + } + + // Rewind + if ( fseek( file, 0, SEEK_SET ) != 0 ) + { + fclose( file ); + return NULL; + } + + void* data = b3Alloc( (size_t)size ); + size_t readCount = fread( data, 1, (size_t)size, file ); + fclose( file ); + + if ( readCount != (size_t)size ) + { + b3Free( data, (size_t)size ); + return NULL; + } + + *memSize = (int)size; + return data; +} diff --git a/src/core.h b/src/core.h new file mode 100644 index 0000000..a4d8599 --- /dev/null +++ b/src/core.h @@ -0,0 +1,166 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "box3d/base.h" + +#include + +// clang-format off + +#ifdef NDEBUG + #define B3_DEBUG 0 +#else + #define B3_DEBUG 1 +#endif + +// Define platform +#if defined(_WIN32) || defined(_WIN64) + #define B3_PLATFORM_WINDOWS +#elif defined( __ANDROID__ ) + #define B3_PLATFORM_ANDROID +#elif defined( __linux__ ) + #define B3_PLATFORM_LINUX +#elif defined( __APPLE__ ) + #include + #if defined( TARGET_OS_IPHONE ) && !TARGET_OS_IPHONE + #define B3_PLATFORM_MACOS + #else + #define B3_PLATFORM_IOS + #endif +#elif defined( __EMSCRIPTEN__ ) + #define B3_PLATFORM_WASM +#else + #define B3_PLATFORM_UNKNOWN +#endif + +// Define CPU +#if defined( __x86_64__ ) || defined( _M_X64 ) || defined( __i386__ ) || defined( _M_IX86 ) + #define B3_CPU_X86_X64 +#elif defined( __aarch64__ ) || defined( _M_ARM64 ) || defined( __arm__ ) || defined( _M_ARM ) + #define B3_CPU_ARM +#elif defined( __EMSCRIPTEN__ ) + #define B3_CPU_WASM +#else + #define B3_CPU_UNKNOWN +#endif + +// Define SIMD +#if defined( BOX3D_DISABLE_SIMD ) + #define B3_SIMD_NONE + #define B3_SIMD_WIDTH 4 + //#pragma message("B3_SIMD_NONE") +#else + #if defined( B3_CPU_X86_X64 ) + #define B3_SIMD_SSE2 + #define B3_SIMD_WIDTH 4 + //#pragma message("B3_SIMD_SSE2") + #elif defined( B3_CPU_ARM ) + #define B3_SIMD_NEON + #define B3_SIMD_WIDTH 4 + //#pragma message("B3_SIMD_NEON") + #elif defined( B3_CPU_WASM ) + #define B3_CPU_WASM + #define B3_SIMD_SSE2 + #define B3_SIMD_WIDTH 4 + //#pragma message("B3_SIMD_SSE2") + #else + #define B3_SIMD_NONE + #define B3_SIMD_WIDTH 4 + //#pragma message("B3_SIMD_NONE") + #endif +#endif + +// Define compiler +#if defined( __clang__ ) + #define B3_COMPILER_CLANG +#elif defined( __GNUC__ ) + #define B3_COMPILER_GCC +#elif defined( _MSC_VER ) + #define B3_COMPILER_MSVC +#endif + +/// Tracy profiler instrumentation +/// https://github.com/wolfpld/tracy +#ifdef BOX3D_PROFILE + #include + #define b3TracyCZoneC( ctx, color, active ) TracyCZoneC( ctx, color, active ) + #define b3TracyCZoneNC( ctx, name, color, active ) TracyCZoneNC( ctx, name, color, active ) + #define b3TracyCZoneEnd( ctx ) TracyCZoneEnd( ctx ) + #define b3TracyCFrame TracyCFrameMark +#else + #define b3TracyCZoneC( ctx, color, active ) + #define b3TracyCZoneNC( ctx, name, color, active ) + #define b3TracyCZoneEnd( ctx ) + #define b3TracyCFrame +#endif + +// clang-format on + +typedef struct b3AtomicInt +{ + int value; +} b3AtomicInt; + +typedef struct b3AtomicU32 +{ + uint32_t value; +} b3AtomicU32; + +// Returns the number of elements of an array +#define B3_ARRAY_COUNT( A ) (int)( sizeof( A ) / sizeof( A[0] ) ) + +// Used to prevent the compiler from warning about unused variables +#define B3_UNUSED( ... ) (void)sizeof( ( __VA_ARGS__, 0 ) ) + +// Use to validate definitions. Do not take my cookie. +#define B3_SECRET_COOKIE 1152023 + +#define B3_CHECK_DEF( DEF ) B3_ASSERT( DEF->internalValue == B3_SECRET_COOKIE ) +#define B3_CHECK_JOINT_DEF( DEF ) B3_ASSERT( DEF->base.internalValue == B3_SECRET_COOKIE ) + +// These macros help avoid sizeof bugs +#define B3_ALLOC( T, N ) (T*)b3Alloc( N * sizeof( T ) ); +#define B3_FREE( M, T, N ) b3Free( M, N * sizeof( T ) ); + + +#ifdef __cplusplus +extern "C" +{ +#endif + +void* b3Alloc( size_t size ); +void* b3AllocZeroed( size_t size ); +void b3Free( void* mem, size_t size ); +void* b3GrowAlloc( void* oldMem, int oldSize, int newSize ); + +void b3Log( const char* format, ... ); + +typedef struct b3Mutex b3Mutex; +b3Mutex* b3CreateMutex( void ); +void b3DestroyMutex( b3Mutex* m ); +void b3LockMutex( b3Mutex* m ); +void b3UnlockMutex( b3Mutex* m ); + +typedef struct b3Semaphore b3Semaphore; +b3Semaphore* b3CreateSemaphore( int initCount ); +void b3DestroySemaphore( b3Semaphore* s ); +void b3WaitSemaphore( b3Semaphore* s ); +void b3SignalSemaphore( b3Semaphore* s ); + +typedef void b3ThreadFunction( void* context ); +typedef struct b3Thread b3Thread; +// Name may be NULL, otherwise it is copied. +b3Thread* b3CreateThread( b3ThreadFunction* function, void* context, const char* name ); +void b3JoinThread( b3Thread* t ); + +// Dump to a file. Only one dump file allowed at a time. +void b3OpenDump( const char* fileName ); +void b3Dump( const char* string, ... ); +void b3CloseDump( void ); +int b3FetchAddMeshDumpIndex( void ); + +#ifdef __cplusplus +} +#endif diff --git a/src/ctz.h b/src/ctz.h new file mode 100644 index 0000000..cfdc23f --- /dev/null +++ b/src/ctz.h @@ -0,0 +1,131 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#if defined( _MSC_VER ) && !defined( __clang__ ) + +#include + +// https://en.wikipedia.org/wiki/Find_first_set + +B3_INLINE uint32_t b3CTZ32( 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. +B3_INLINE uint32_t b3CLZ32( uint32_t value ) +{ +#if 0 + + // 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 +} + +B3_INLINE uint32_t b3CTZ64( 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; +} + +B3_INLINE int b3PopCount64( uint64_t block ) +{ + return (int)__popcnt64( block ); +} + +#else + +B3_INLINE uint32_t b3CTZ32( uint32_t block ) +{ + return __builtin_ctz( block ); +} + +B3_INLINE uint32_t b3CLZ32( uint32_t value ) +{ + return __builtin_clz( value ); +} + +B3_INLINE uint32_t b3CTZ64( uint64_t block ) +{ + return __builtin_ctzll( block ); +} + +B3_INLINE int b3PopCount64( uint64_t block ) +{ + return __builtin_popcountll( block ); +} + +#endif + +B3_INLINE bool b3IsPowerOf2( int x ) +{ + return ( x & ( x - 1 ) ) == 0; +} + +B3_INLINE int b3BoundingPowerOf2( int x ) +{ + if ( x <= 1 ) + { + return 1; + } + + return 32 - (int)b3CLZ32( (uint32_t)x - 1 ); +} + +B3_INLINE int b3RoundUpPowerOf2( int x ) +{ + if ( x <= 1 ) + { + return 1; + } + + return 1 << ( 32 - (int)b3CLZ32( (uint32_t)x - 1 ) ); +} + +B3_INLINE int b3LowerPowerOf2Exponent( int x ) +{ + B3_ASSERT( x > 0 ); + int clz = (int)b3CLZ32( (uint32_t)x ); + + // Position of most significant bit = floor(log2(M)) + return 31 - clz; +} diff --git a/src/distance.c b/src/distance.c new file mode 100644 index 0000000..b0fc17e --- /dev/null +++ b/src/distance.c @@ -0,0 +1,1994 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +// Dirk Gregorius contributed portions of this code + +#include "math_internal.h" + +#include "box3d/collision.h" +#include "box3d/constants.h" + +#define B3_MAX_SIMPLEX_VERTICES 4 +#define B3_MAX_GJK_ITERATIONS 32 + +int b3GetProxySupport( const b3ShapeProxy* proxy, b3Vec3 axis ) +{ + int count = proxy->count; + const b3Vec3* points = proxy->points; + + B3_ASSERT( count > 0 ); + B3_ASSERT( points != NULL ); + + // We move the first vertex into the origin for improved precision. + // This is necessary since we don't have shape transforms and + // vertices can potentially be far away from the origin (large). + b3Vec3 origin = points[0]; + int maxIndex = 0; + float maxProjection = 0.0f; + + for ( int index = 1; index < count; ++index ) + { + // We subtract the first vertex since we are shifting into the origin. + float projection = b3Dot( axis, b3Sub( points[index], origin ) ); + if ( projection > maxProjection ) + { + maxIndex = index; + maxProjection = projection; + } + } + + return maxIndex; +} + +int b3GetPointSupport( const b3Vec3* points, int count, b3Vec3 axis ) +{ + B3_ASSERT( count > 0 ); + B3_ASSERT( points != NULL ); + + // We move the first vertex into the origin for improved precision. + // This is necessary since we don't have shape transforms and + // vertices can potentially be far away from the origin (large). + b3Vec3 origin = points[0]; + int maxIndex = 0; + float maxProjection = 0.0f; + + for ( int index = 1; index < count; ++index ) + { + // We subtract the first vertex since we are shifting into the origin. + float projection = b3Dot( axis, b3Sub( points[index], origin ) ); + if ( projection > maxProjection ) + { + maxIndex = index; + maxProjection = projection; + } + } + + return maxIndex; +} + +// Similar to Real-time Collision Detection, p179. +// todo try https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection.html +bool b3IntersectRayAndAABB( b3Vec3 lowerBound, b3Vec3 upperBound, b3Vec3 p1, b3Vec3 p2, float* minFraction, + float* maxFraction ) +{ + // Ray direction and length + b3Vec3 d = b3Sub( p2, p1 ); + float rayLength = b3Length( d ); + + // Handle degenerate ray + if ( rayLength < FLT_EPSILON ) + { + // Check if point is inside AABB + if ( p1.x >= lowerBound.x && p1.x <= upperBound.x && p1.y >= lowerBound.y && p1.y <= upperBound.y && + p1.z >= lowerBound.z && p1.z <= upperBound.z ) + { + *minFraction = 0.0f; + *maxFraction = 0.0f; + return true; + } + else + { + return false; + } + } + + b3Vec3 rayDir = b3MulSV( 1.0f / rayLength, d ); + + // Slab method for ray-AABB intersection + float tMin = 0.0f; + float tMax = rayLength; + + // Test each axis + for ( int i = 0; i < 3; ++i ) + { + float rayComponent = b3GetByIndex( rayDir, i ); + float rayStart = b3GetByIndex( p1, i ); + float boxMin = b3GetByIndex( lowerBound, i ); + float boxMax = b3GetByIndex( upperBound, i ); + + if ( b3AbsFloat( rayComponent ) < FLT_EPSILON ) + { + // Ray is parallel to slab, check if ray origin is within slab + if ( rayStart < boxMin || rayStart > boxMax ) + { + return false; + } + } + else + { + // Compute intersection distances + float t1 = ( boxMin - rayStart ) / rayComponent; + float t2 = ( boxMax - rayStart ) / rayComponent; + + // Ensure t1 <= t2 + if ( t1 > t2 ) + { + float temp = t1; + t1 = t2; + t2 = temp; + } + + // Update intersection interval + tMin = b3MaxFloat( tMin, t1 ); + tMax = b3MinFloat( tMax, t2 ); + + // Check for no intersection + if ( tMin > tMax ) + { + return false; + } + } + } + + // Check if intersection is behind ray start + if ( tMax < 0.0f ) + { + return false; + } + + // Convert distances to fractions + *minFraction = b3ClampFloat( tMin / rayLength, 0.0f, 1.0f ); + *maxFraction = b3ClampFloat( tMax / rayLength, 0.0f, 1.0f ); + + return true; +} + +static void b3BarycentricCoordsEdge( float out[3], b3Vec3 a, b3Vec3 b ) +{ + b3Vec3 ab = b3Sub( b, a ); + + // Last element is divisor + float divisor = b3Dot( ab, ab ); + + out[0] = b3Dot( b, ab ); + out[1] = -b3Dot( a, ab ); + out[2] = divisor; +} + +static void b3BarycentricCoordsTri( float out[4], b3Vec3 a, b3Vec3 b, b3Vec3 c ) +{ + b3Vec3 ab = b3Sub( b, a ); + b3Vec3 ac = b3Sub( c, a ); + + b3Vec3 bXC = b3Cross( b, c ); + b3Vec3 cXA = b3Cross( c, a ); + b3Vec3 aXB = b3Cross( a, b ); + + b3Vec3 abXAc = b3Cross( ab, ac ); + + // Last element is divisor + float divisor = b3Dot( abXAc, abXAc ); + + out[0] = b3Dot( bXC, abXAc ); + out[1] = b3Dot( cXA, abXAc ); + out[2] = b3Dot( aXB, abXAc ); + out[3] = divisor; +} + +static void b3BarycentricCoordsTet( float out[5], b3Vec3 a, b3Vec3 b, b3Vec3 c, b3Vec3 d ) +{ + b3Vec3 ab = b3Sub( b, a ); + b3Vec3 ac = b3Sub( c, a ); + b3Vec3 ad = b3Sub( d, a ); + + // Last element is divisor (forced to be positive) + float divisor = b3ScalarTripleProduct( ab, ac, ad ); + + float sign = divisor < 0.0f ? -1.0f : 1.0f; + out[0] = sign * b3ScalarTripleProduct( b, c, d ); + out[1] = sign * b3ScalarTripleProduct( a, d, c ); + out[2] = sign * b3ScalarTripleProduct( a, b, d ); + out[3] = sign * b3ScalarTripleProduct( a, c, b ); + out[4] = sign * divisor; +} + +static float b3GetMetric( const b3Simplex* simplex ) +{ + int count = simplex->count; + B3_ASSERT( 1 <= count && count <= 4 ); + + const b3SimplexVertex* vertices = simplex->vertices; + + switch ( count ) + { + case 1: + { + return 0.0f; + } + + case 2: + { + b3Vec3 a = vertices[0].w; + b3Vec3 b = vertices[1].w; + return b3Distance( a, b ); + } + + case 3: + { + b3Vec3 a = vertices[0].w; + b3Vec3 b = vertices[1].w; + b3Vec3 c = vertices[2].w; + return b3Length( b3Cross( b3Sub( b, a ), b3Sub( c, a ) ) ) / 2.0f; + } + + case 4: + { + b3Vec3 a = vertices[0].w; + b3Vec3 b = vertices[1].w; + b3Vec3 c = vertices[2].w; + b3Vec3 d = vertices[3].w; + return b3ScalarTripleProduct( b3Sub( b, a ), b3Sub( c, a ), b3Sub( d, a ) ) / 6.0f; + } + + default: + B3_ASSERT( !"Should never get here!" ); + break; + } + + return 0.0f; +} + +static void b3WriteCache( b3SimplexCache* cache, const b3Simplex* simplex ) +{ + int count = simplex->count; + cache->metric = b3GetMetric( simplex ); + cache->count = (uint16_t)count; + for ( int index = 0; index < count; ++index ) + { + cache->indexA[index] = (uint8_t)simplex->vertices[index].indexA; + cache->indexB[index] = (uint8_t)simplex->vertices[index].indexB; + } +} + +static bool b3SolveSimplex2( b3Simplex* simplex ) +{ + b3SimplexVertex* vs = simplex->vertices; + B3_ASSERT( simplex->count == 2 ); + + // Vertex regions + //float wAB[3]; + + b3Vec3 a = vs[0].w; + b3Vec3 b = vs[1].w; + b3Vec3 ab = b3Sub( b, a ); + + // Last element is divisor + float divisor = b3Dot( ab, ab ); + + float u = b3Dot( b, ab ); + float v = -b3Dot( a, ab ); + //wAB[2] = divisor; + + // V( A ) + if ( v <= 0.0f ) + { + // Reduce simplex + simplex->count = 1; + vs[0].a = 1.0f; + + return true; + } + + // V( B ) + if ( u <= 0.0f ) + { + // Reduce simplex + simplex->count = 1; + vs[0] = vs[1]; + vs[0].a = 1.0f; + + return true; + } + + // Edge region + if ( divisor <= 0.0f ) + { + return false; + } + + // VR( AB ) + float denominator = 1.0f / divisor; + vs[0].a = denominator * u; + vs[1].a = denominator * v; + + return true; +} + +static bool b3SolveSimplex3( b3Simplex* simplex ) +{ + b3SimplexVertex* vs = simplex->vertices; + B3_ASSERT( simplex->count == 3 ); + + // Get simplex (be aware of aliasing here!) + b3SimplexVertex v1 = vs[0]; + b3SimplexVertex v2 = vs[1]; + b3SimplexVertex v3 = vs[2]; + + // Vertex regions + float wAB[3], wBC[3], wCA[3]; + b3BarycentricCoordsEdge( wAB, v1.w, v2.w ); + b3BarycentricCoordsEdge( wBC, v2.w, v3.w ); + b3BarycentricCoordsEdge( wCA, v3.w, v1.w ); + + // VR( A ) + if ( wAB[1] <= 0.0f && wCA[0] <= 0.0f ) + { + // Reduce simplex + simplex->count = 1; + vs[0] = v1; + vs[0].a = 1.0f; + + return true; + } + + // VR( B ) + if ( wBC[1] <= 0.0f && wAB[0] <= 0.0f ) + { + // Reduce simplex + simplex->count = 1; + vs[0] = v2; + vs[0].a = 1.0f; + + return true; + } + + // VR( C ) + if ( wCA[1] <= 0.0f && wBC[0] <= 0.0f ) + { + // Reduce simplex + simplex->count = 1; + vs[0] = v3; + vs[0].a = 1.0f; + + return true; + } + + // Edge regions + float wABC[4]; + b3BarycentricCoordsTri( wABC, v1.w, v2.w, v3.w ); + + // VR( AB ) + if ( wABC[2] <= 0.0f && wAB[0] > 0.0f && wAB[1] > 0.0f ) + { + // Reduce simplex + simplex->count = 2; + vs[0] = v1; + vs[1] = v2; + + // Normalize + float divisor = wAB[2]; + if ( divisor <= 0.0f ) + { + return false; + } + + vs[0].a = wAB[0] / divisor; + vs[1].a = wAB[1] / divisor; + + return true; + } + + // VR( BC ) + if ( wABC[0] <= 0.0f && wBC[0] > 0.0f && wBC[1] > 0.0f ) + { + // Reduce simplex + simplex->count = 2; + vs[0] = v2; + vs[1] = v3; + + // Normalize + float divisor = wBC[2]; + if ( divisor <= 0.0f ) + { + return false; + } + + vs[0].a = wBC[0] / divisor; + vs[1].a = wBC[1] / divisor; + + return true; + } + + // VR( CA ) + if ( wABC[1] <= 0.0f && wCA[0] > 0.0f && wCA[1] > 0.0f ) + { + // Reduce simplex + simplex->count = 2; + vs[0] = v3; + vs[1] = v1; + + // Normalize + float divisor = wCA[2]; + if ( divisor <= 0.0f ) + { + return false; + } + + vs[0].a = wCA[0] / divisor; + vs[1].a = wCA[1] / divisor; + + return true; + } + + // Face region + float divisor = wABC[3]; + if ( divisor <= 0.0f ) + { + return false; + } + + // VR( ABC ) + vs[0].a = wABC[0] / divisor; + vs[1].a = wABC[1] / divisor; + vs[2].a = wABC[2] / divisor; + + return true; +} + +static bool b3SolveSimplex4( b3Simplex* simplex ) +{ + b3SimplexVertex* vs = simplex->vertices; + + // Get simplex (be aware of aliasing here!) + B3_ASSERT( simplex->count == 4 ); + b3SimplexVertex vertexA = vs[0]; + b3SimplexVertex vertexB = vs[1]; + b3SimplexVertex vertexC = vs[2]; + b3SimplexVertex vertexD = vs[3]; + + // Vertex region + float wAB[3], wAC[3], wAD[3], wBC[3], wCD[3], wDB[3]; + b3BarycentricCoordsEdge( wAB, vertexA.w, vertexB.w ); + b3BarycentricCoordsEdge( wAC, vertexA.w, vertexC.w ); + b3BarycentricCoordsEdge( wAD, vertexA.w, vertexD.w ); + b3BarycentricCoordsEdge( wBC, vertexB.w, vertexC.w ); + b3BarycentricCoordsEdge( wCD, vertexC.w, vertexD.w ); + b3BarycentricCoordsEdge( wDB, vertexD.w, vertexB.w ); + + // VR( A ) + if ( wAB[1] <= 0.0f && wAC[1] <= 0.0f && wAD[1] <= 0.0f ) + { + // Reduce simplex + simplex->count = 1; + vs[0] = vertexA; + + vs[0].a = 1.0f; + + return true; + } + + // VR( B ) + if ( wAB[0] <= 0.0f && wDB[0] <= 0.0f && wBC[1] <= 0.0f ) + { + // Reduce simplex + simplex->count = 1; + vs[0] = vertexB; + + vs[0].a = 1.0f; + + return true; + } + + // VR( C ) + if ( wAC[0] <= 0.0f && wBC[0] <= 0.0f && wCD[1] <= 0.0f ) + { + // Reduce simplex + simplex->count = 1; + vs[0] = vertexC; + + vs[0].a = 1.0f; + + return true; + } + + // VR( D ) + if ( wAD[0] <= 0.0f && wCD[0] <= 0.0f && wDB[1] <= 0.0f ) + { + // Reduce simplex + simplex->count = 1; + vs[0] = vertexD; + + vs[0].a = 1.0f; + + return true; + } + + // Edge region + float wACB[4], wABD[4], wADC[4], wBCD[4]; + b3BarycentricCoordsTri( wACB, vertexA.w, vertexC.w, vertexB.w ); + b3BarycentricCoordsTri( wABD, vertexA.w, vertexB.w, vertexD.w ); + b3BarycentricCoordsTri( wADC, vertexA.w, vertexD.w, vertexC.w ); + b3BarycentricCoordsTri( wBCD, vertexB.w, vertexC.w, vertexD.w ); + + // VR( AB ) + if ( wABD[2] <= 0.0f && wACB[1] <= 0.0f && wAB[0] > 0.0f && wAB[1] > 0.0f ) + { + // Reduce simplex + simplex->count = 2; + vs[0] = vertexA; + vs[1] = vertexB; + + // Normalize + float divisor = wAB[2]; + if ( divisor <= 0.0f ) + { + return false; + } + + vs[0].a = wAB[0] / divisor; + vs[1].a = wAB[1] / divisor; + + return true; + } + + // VR( AC ) + if ( wACB[2] <= 0.0f && wADC[1] <= 0.0f && wAC[0] > 0.0f && wAC[1] > 0.0f ) + { + // Reduce simplex + simplex->count = 2; + vs[0] = vertexA; + vs[1] = vertexC; + + // Normalize + float divisor = wAC[2]; + if ( divisor <= 0.0f ) + { + return false; + } + + vs[0].a = wAC[0] / divisor; + vs[1].a = wAC[1] / divisor; + + return true; + } + + // VR( AD ) + if ( wADC[2] <= 0.0f && wABD[1] <= 0.0f && wAD[0] > 0.0f && wAD[1] > 0.0f ) + { + // Reduce simplex + simplex->count = 2; + vs[0] = vertexA; + vs[1] = vertexD; + + // Normalize + float divisor = wAD[2]; + if ( divisor <= 0.0f ) + { + return false; + } + + vs[0].a = wAD[0] / divisor; + vs[1].a = wAD[1] / divisor; + + return true; + } + + // VR( BC ) + if ( wACB[0] <= 0.0f && wBCD[2] <= 0.0f && wBC[0] > 0.0f && wBC[1] > 0.0f ) + { + // Reduce simplex + simplex->count = 2; + vs[0] = vertexB; + vs[1] = vertexC; + + // Normalize + float divisor = wBC[2]; + if ( divisor <= 0.0f ) + { + return false; + } + + vs[0].a = wBC[0] / divisor; + vs[1].a = wBC[1] / divisor; + + return true; + } + + // VR( CD ) + if ( wADC[0] <= 0.0f && wBCD[0] <= 0.0f && wCD[0] > 0.0f && wCD[1] > 0.0f ) + { + // Reduce simplex + simplex->count = 2; + vs[0] = vertexC; + vs[1] = vertexD; + + // Normalize + float divisor = wCD[2]; + if ( divisor <= 0.0f ) + { + return false; + } + + vs[0].a = wCD[0] / divisor; + vs[1].a = wCD[1] / divisor; + + return true; + } + + // VR( DB ) + if ( wABD[0] <= 0.0f && wBCD[1] <= 0.0f && wDB[0] > 0.0f && wDB[1] > 0.0f ) + { + // Reduce simplex + simplex->count = 2; + vs[0] = vertexD; + vs[1] = vertexB; + + // Normalize + float divisor = wDB[2]; + if ( divisor <= 0.0f ) + { + return false; + } + + vs[0].a = wDB[0] / divisor; + vs[1].a = wDB[1] / divisor; + + return true; + } + + // Face regions + float wABCD[5]; + b3BarycentricCoordsTet( wABCD, vertexA.w, vertexB.w, vertexC.w, vertexD.w ); + + // VR( ACB ) + if ( wABCD[3] < 0.0f && wACB[0] > 0.0f && wACB[1] > 0.0f && wACB[2] > 0.0f ) + { + // Reduce simplex + simplex->count = 3; + vs[0] = vertexA; + vs[1] = vertexC; + vs[2] = vertexB; + + // Normalize + float divisor = wACB[3]; + if ( divisor <= 0.0f ) + { + return false; + } + + vs[0].a = wACB[0] / divisor; + vs[1].a = wACB[1] / divisor; + vs[2].a = wACB[2] / divisor; + + return true; + } + + // VR( ABD ) + if ( wABCD[2] < 0.0f && wABD[0] > 0.0f && wABD[1] > 0.0f && wABD[2] > 0.0f ) + { + // Reduce simplex + simplex->count = 3; + vs[0] = vertexA; + vs[1] = vertexB; + vs[2] = vertexD; + + // Normalize + float divisor = wABD[3]; + if ( divisor <= 0.0f ) + { + return false; + } + + vs[0].a = wABD[0] / divisor; + vs[1].a = wABD[1] / divisor; + vs[2].a = wABD[2] / divisor; + + return true; + } + + // VR( ADC ) + if ( wABCD[1] < 0.0f && wADC[0] > 0.0f && wADC[1] > 0.0f && wADC[2] > 0.0f ) + { + // Reduce simplex + simplex->count = 3; + vs[0] = vertexA; + vs[1] = vertexD; + vs[2] = vertexC; + + // Normalize + float divisor = wADC[3]; + if ( divisor <= 0.0f ) + { + return false; + } + + vs[0].a = wADC[0] / divisor; + vs[1].a = wADC[1] / divisor; + vs[2].a = wADC[2] / divisor; + + return true; + } + + // VR( BCD ) + if ( wABCD[0] < 0.0f && wBCD[0] > 0.0f && wBCD[1] > 0.0f && wBCD[2] > 0.0f ) + { + // Reduce simplex + simplex->count = 3; + vs[0] = vertexB; + vs[1] = vertexC; + vs[2] = vertexD; + + // Normalize + float divisor = wBCD[3]; + if ( divisor <= 0.0f ) + { + return false; + } + + vs[0].a = wBCD[0] / divisor; + vs[1].a = wBCD[1] / divisor; + vs[2].a = wBCD[2] / divisor; + + return true; + } + + // *** Inside tetrahedron *** + float divisor = wABCD[4]; + if ( divisor <= 0.0f ) + { + return false; + } + + // VR( ABCD ) + vs[0].a = wABCD[0] / divisor; + vs[1].a = wABCD[1] / divisor; + vs[2].a = wABCD[2] / divisor; + vs[3].a = wABCD[3] / divisor; + + return true; +} + +static void b3ComputeWitnessPoints( const b3Simplex* simplex, b3Vec3* vertexA, b3Vec3* vertexB ) +{ + const b3SimplexVertex* vs = simplex->vertices; + int count = simplex->count; + B3_ASSERT( 1 <= count && count <= 4 ); + + switch ( count ) + { + case 1: + *vertexA = vs[0].wA; + *vertexB = vs[0].wB; + break; + + case 2: + *vertexA = b3Blend2( vs[0].a, vs[0].wA, vs[1].a, vs[1].wA ); + *vertexB = b3Blend2( vs[0].a, vs[0].wB, vs[1].a, vs[1].wB ); + break; + + case 3: + *vertexA = b3Blend3( vs[0].a, vs[0].wA, vs[1].a, vs[1].wA, vs[2].a, vs[2].wA ); + *vertexB = b3Blend3( vs[0].a, vs[0].wB, vs[1].a, vs[1].wB, vs[2].a, vs[2].wB ); + break; + + case 4: + { + // Force identical points and *zero* distance + b3Vec3 sum = b3Add( b3Blend2( vs[0].a, vs[0].wA, vs[1].a, vs[1].wA ), + b3Blend2( vs[2].a, vs[2].wA, vs[3].a, vs[3].wA ) ); + *vertexA = sum; + *vertexB = sum; + } + break; + + default: + B3_ASSERT( !"Should never get here!" ); + break; + } +} + +b3DistanceOutput b3ShapeDistance( const b3DistanceInput* input, b3SimplexCache* cache, b3Simplex* simplexes, int simplexCapacity ) +{ + // Build initial simplex + b3Transform transformA = input->transformA; + b3Transform transformB = input->transformB; + + // Work in relative space + b3Transform xf = b3InvMulTransforms( transformA, transformB ); + + // Use matrices for faster math + b3Matrix3 m = b3MakeMatrixFromQuat( xf.q ); + b3Matrix3 mt = b3Transpose( m ); + b3Matrix3 mA = b3MakeMatrixFromQuat( transformA.q ); + + const b3ShapeProxy* proxyA = &input->proxyA; + const b3ShapeProxy* proxyB = &input->proxyB; + + // Compute initial simplex from cache + B3_ASSERT( cache->count <= B3_MAX_SIMPLEX_VERTICES ); + + b3Simplex simplex = { 0 }; + b3SimplexVertex* vs = simplex.vertices; + + simplex.count = cache->count; + for ( int i = 0; i < cache->count; ++i ) + { + int index1 = cache->indexA[i]; + int index2 = cache->indexB[i]; + + B3_ASSERT( 0 <= index1 && index1 < proxyA->count ); + B3_ASSERT( 0 <= index2 && index2 < proxyB->count ); + + b3Vec3 vertex1 = proxyA->points[index1]; + b3Vec3 vertex2 = b3Add( b3MulMV( m, proxyB->points[index2] ), xf.p ); + + vs[i].indexA = index1; + vs[i].indexB = index2; + vs[i].wA = vertex1; + vs[i].wB = vertex2; + vs[i].w = b3Sub( vertex2, vertex1 ); + vs[i].a = 0.0f; + } + + // Compute the new simplex metric, if it is substantially + // different than the old metric flush the simplex. + if ( simplex.count > 0 ) + { + float metric1 = cache->metric; + float metric2 = b3GetMetric( &simplex ); + + // todo the tetrahedron metric can be negative + if ( 2.0f * metric1 < metric2 || metric2 < 0.5f * metric1 || metric2 < FLT_EPSILON ) + { + // Flush the simplex + simplex.count = 0; + } + } + + // If the cache is invalid or empty + if ( simplex.count == 0 ) + { + b3Vec3 vertex1 = proxyA->points[0]; + b3Vec3 vertex2 = b3Add( b3MulMV( m, proxyB->points[0] ), xf.p ); + + simplex.count = 1; + simplex.vertices[0].indexA = 0; + simplex.vertices[0].indexB = 0; + simplex.vertices[0].wA = vertex1; + simplex.vertices[0].wB = vertex2; + simplex.vertices[0].w = b3Sub( vertex2, vertex1 ); + simplex.vertices[0].a = 0.0f; + } + + b3Simplex backup = { 0 }; + + int simplexIndex = 0; + if ( simplexes != NULL && simplexIndex < simplexCapacity ) + { + simplexes[simplexIndex] = simplex; + simplexIndex += 1; + } + + b3DistanceOutput distanceOutput = { 0 }; + + // Keep track of squared distance + float distanceSq = FLT_MAX; + + b3Vec3 normal = b3Vec3_zero; + + // Run GJK + int iteration = 0; + for ( ; iteration < B3_MAX_GJK_ITERATIONS; ++iteration ) + { + // Solve simplex + bool solved = false; + switch ( simplex.count ) + { + case 1: + simplex.vertices[0].a = 1.0f; + solved = true; + break; + + case 2: + solved = b3SolveSimplex2( &simplex ); + break; + + case 3: + solved = b3SolveSimplex3( &simplex ); + break; + + case 4: + solved = b3SolveSimplex4( &simplex ); + break; + + default: + B3_ASSERT( !"Should never get here!" ); + break; + } + + if ( solved == false ) + { + // No progress - reconstruct last simplex + B3_ASSERT( backup.count != 0 ); + simplex = backup; + break; + } + + if ( simplexes != NULL && simplexIndex < simplexCapacity ) + { + simplexes[simplexIndex] = simplex; + simplexIndex += 1; + distanceOutput.iterations = iteration; + distanceOutput.simplexCount = simplexIndex; + } + + if ( simplex.count == B3_MAX_SIMPLEX_VERTICES ) + { + // Overlap + b3Vec3 localPointA, localPointB; + b3ComputeWitnessPoints( &simplex, &localPointA, &localPointB ); + distanceOutput.pointA = b3Add( b3MulMV( mA, localPointA ), transformA.p ); + distanceOutput.pointB = b3Add( b3MulMV( mA, localPointB ), transformA.p ); + return distanceOutput; + } + + // Assure distance progression + float oldDistanceSq = distanceSq; + + // Compute closest point + b3Vec3 closestPoint = { 0 }; + + switch ( simplex.count ) + { + case 1: + closestPoint = vs[0].w; + break; + + case 2: + closestPoint = b3Blend2( vs[0].a, vs[0].w, vs[1].a, vs[1].w ); + break; + + case 3: + closestPoint = b3Blend3( vs[0].a, vs[0].w, vs[1].a, vs[1].w, vs[2].a, vs[2].w ); + break; + + case 4: + closestPoint = b3Add( b3Blend2( vs[0].a, vs[0].w, vs[1].a, vs[1].w ), + b3Blend2( vs[2].a, vs[2].w, vs[3].a, vs[3].w ) ); + break; + + default: + B3_ASSERT( !"Should never get here!" ); + break; + } + + distanceSq = b3Dot( closestPoint, closestPoint ); + + if ( distanceSq >= oldDistanceSq ) + { + // No progress - reconstruct last simplex + B3_ASSERT( backup.count != 0 ); + simplex = backup; + break; + } + + // Build new tentative support point + b3Vec3 searchDirection = { 0 }; + + switch ( simplex.count ) + { + case 1: + { + // v = -A + searchDirection = b3Neg( vs[0].w ); + } + break; + + case 2: + { + // v = (AB x AO) x AB + b3Vec3 a = vs[0].w; + b3Vec3 b = vs[1].w; + + b3Vec3 ab = b3Sub( b, a ); + + searchDirection = b3Cross( b3Cross( ab, b3Neg( a ) ), ab ); + } + break; + + case 3: + { + // v = AB x AC or v = AC x AB + b3Vec3 a = vs[0].w; + b3Vec3 b = vs[1].w; + b3Vec3 c = vs[2].w; + + b3Vec3 ab = b3Sub( b, a ); + b3Vec3 ac = b3Sub( c, a ); + + b3Vec3 n = b3Cross( ab, ac ); + + searchDirection = b3Dot( n, a ) < 0.0f ? n : b3Neg( n ); + } + break; + + default: + B3_ASSERT( !"Should never get here!" ); + break; + } + + if ( b3LengthSquared( searchDirection ) < 1000.0f * FLT_MIN ) + { + // The origin is probably contained by a line segment or triangle. + // Thus the shapes are overlapped. + b3Vec3 localPointA, localPointB; + b3ComputeWitnessPoints( &simplex, &localPointA, &localPointB ); + distanceOutput.pointA = b3Add( b3MulMV( mA, localPointA ), transformA.p ); + distanceOutput.pointB = b3Add( b3MulMV( mA, localPointB ), transformA.p ); + B3_VALIDATE( b3Distance( localPointA, localPointB ) < FLT_EPSILON ); + return distanceOutput; + } + + normal = b3Neg( searchDirection ); + + // Get new support points + b3Vec3 searchDirection1 = searchDirection; + int indexA = b3GetProxySupport( &input->proxyA, b3Neg( searchDirection1 ) ); + b3Vec3 supportA = input->proxyA.points[indexA]; + b3Vec3 searchDirection2 = b3MulMV( mt, searchDirection ); + int indexB = b3GetProxySupport( &input->proxyB, searchDirection2 ); + b3Vec3 supportB = b3Add( b3MulMV( m, input->proxyB.points[indexB] ), xf.p ); + + // Save current simplex and add new vertex - this can fail if we detect cycling + backup = simplex; + + // Check for duplicate support points. This is the main termination criteria. + bool duplicate = false; + for ( int i = 0; i < simplex.count; ++i ) + { + if ( vs[i].indexA == indexA && vs[i].indexB == indexB ) + { + duplicate = true; + break; + } + } + + if ( duplicate ) + { + break; + } + + vs[simplex.count].indexA = indexA; + vs[simplex.count].indexB = indexB; + vs[simplex.count].wA = supportA; + vs[simplex.count].wB = supportB; + vs[simplex.count].w = b3Sub( supportB, supportA ); + simplex.count += 1; + } + + normal = b3Normalize( normal ); + if ( b3IsNormalized( normal ) == false ) + { + // Treat as overlap + return distanceOutput; + } + + // Build witness points and safe cache + b3Vec3 localPointA, localPointB; + b3ComputeWitnessPoints( &simplex, &localPointA, &localPointB ); + b3WriteCache( cache, &simplex ); + + // Convert results from frame A into world space + normal = b3MulMV( mA, normal ); + distanceOutput.pointA = b3Add( b3MulMV( mA, localPointA ), transformA.p ); + distanceOutput.pointB = b3Add( b3MulMV( mA, localPointB ), transformA.p ); + distanceOutput.distance = b3Distance( localPointA, localPointB ); + distanceOutput.normal = normal; + distanceOutput.iterations = iteration; + distanceOutput.simplexCount = simplexIndex; + + // Apply radii if requested + if ( input->useRadii ) + { + float rA = input->proxyA.radius; + float rB = input->proxyB.radius; + distanceOutput.distance = b3MaxFloat( 0.0f, distanceOutput.distance - rA - rB ); + + // Keep closest points on perimeter even if overlapped, this way the points move smoothly. + distanceOutput.pointA = b3Add( distanceOutput.pointA, b3MulSV( rA, normal ) ); + distanceOutput.pointB = b3Sub( distanceOutput.pointB, b3MulSV( rB, normal ) ); + } + + return distanceOutput; +} + + +// Separation function: +// f(t) = (c2 + t * dp2 - c1 - t * dp1 ) * n + +// Root finding : f(t) - target = 0 +// (c2 + t * dp2 - c1 - t * dp1 ) * n - target = 0 +// (c2 - c1) * n + t * (dp2 - dp1) * n - target = 0 +// t = [target - (c2 - c1) * n] / [(dp2 - dp1) * n] +// t = (target - d) / [(dp2 - dp1) * n] + +b3CastOutput b3ShapeCast( const b3ShapeCastPairInput* input ) +{ + // Compute tolerance + float linearSlop = B3_LINEAR_SLOP; + float totalRadius = input->proxyA.radius + input->proxyB.radius; + float target = b3MaxFloat( linearSlop, totalRadius - linearSlop ); + float tolerance = 0.25f * linearSlop; + + B3_ASSERT( target > tolerance ); + + // Prepare input for distance query + b3SimplexCache cache = { 0 }; + + float alpha = 0.0f; + + b3DistanceInput distanceInput = { 0 }; + distanceInput.proxyA = input->proxyA; + distanceInput.proxyB = input->proxyB; + distanceInput.transformA = input->transformA; + distanceInput.transformB = input->transformB; + distanceInput.useRadii = false; + + b3Vec3 delta2 = input->translationB; + b3DistanceOutput distanceOutput = { 0 }; + b3CastOutput output = { 0 }; + output.triangleIndex = B3_NULL_INDEX; + + int iteration = 0; + const int maxIterations = 20; + + for ( ; iteration < maxIterations; ++iteration ) + { + output.iterations += 1; + + distanceOutput = b3ShapeDistance( &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 + b3Vec3 c1 = b3MulAdd( distanceOutput.pointA, input->proxyA.radius, distanceOutput.normal ); + b3Vec3 c2 = b3MulAdd( distanceOutput.pointB, -input->proxyB.radius, distanceOutput.normal ); + output.point = b3Lerp( c1, c2, 0.5f ); + return output; + } + } + else + { + // Logging for bad input data + if ( distanceOutput.distance > 0.0f && b3IsNormalized( distanceOutput.normal ) == false ) + { + for ( int i = 0; i < input->proxyA.count; ++i ) + { + b3Vec3 p = input->proxyA.points[i]; + b3Log( "pointA[%d] = {%.9f, %.9f, %.9f}", i, p.x, p.y, p.z ); + } + b3Log( "radiusA = %.9f", input->proxyA.radius ); + + for ( int i = 0; i < input->proxyB.count; ++i ) + { + b3Vec3 p = input->proxyB.points[i]; + b3Log( "pointB[%d] = {%.9f, %.9f, %.9f}", i, p.x, p.y, p.z ); + } + b3Log( "radiusB = %.9f", input->proxyB.radius ); + + { + b3Transform xfA = input->transformA; + b3Log( "xfA = {{%.9f, %.9f, %.9f}, {{%.9f, %.9f, %.9f}, %.9f}", xfA.p.x, xfA.p.y, xfA.p.z, xfA.q.v.x, + xfA.q.v.y, xfA.q.v.z, xfA.q.s ); + } + { + b3Transform xfB = input->transformB; + b3Log( "xfB = {{%.9f, %.9f, %.9f}, {{%.9f, %.9f, %.9f}, %.9f}", xfB.p.x, xfB.p.y, xfB.p.z, xfB.q.v.x, + xfB.q.v.y, xfB.q.v.z, xfB.q.s ); + } + + { + b3Vec3 t = input->translationB; + b3Log( "t = {%.9f, %.9f, %.9f}", t.x, t.y, t.z ); + } + + b3Log( "maxFraction = %.9f, canEncroach = %d", input->maxFraction, input->canEncroach ); + + // Numerical problem. Likely extreme input. + return output; + } + + // Hitting this assert implies that the algorithm brought the shapes too close. + // B3_ASSERT( distanceOutput.distance > 0.0f && b3IsNormalized( distanceOutput.normal ) ); + + output.fraction = alpha; + output.point = b3MulAdd( distanceOutput.pointA, input->proxyA.radius, distanceOutput.normal ); + output.normal = distanceOutput.normal; + output.hit = true; + return output; + } + } + + B3_ASSERT( distanceOutput.distance > 0.0f ); + B3_ASSERT( b3IsNormalized( distanceOutput.normal ) ); + + // Check if shapes are approaching each other + float denominator = b3Dot( delta2, distanceOutput.normal ); + if ( denominator >= 0.0f ) + { + // Miss + return output; + } + + // Advance sweep + alpha += ( target - distanceOutput.distance ) / denominator; + if ( alpha >= input->maxFraction ) + { + // Success! + return output; + } + + distanceInput.transformB.p = b3MulAdd( input->transformB.p, alpha, delta2 ); + } + + // Failure! + return output; +} + +b3Transform b3GetSweepTransform( const b3Sweep* sweep, float time ) +{ + b3Transform transform; + transform.q = b3NLerp( sweep->q1, sweep->q2, time ); + transform.p = b3Sub( b3Lerp( sweep->c1, sweep->c2, time ), b3RotateVector( transform.q, sweep->localCenter ) ); + return transform; +} + +static inline b3Transform b3GetFinalSweepTransform( const b3Sweep* sweep ) +{ + b3Transform transform; + transform.q = sweep->q2; + transform.p = b3Sub( sweep->c2, b3RotateVector( transform.q, sweep->localCenter ) ); + return transform; +} + +static int b3UniqueCount( int vertexCount, int vertices[3] ) +{ + B3_ASSERT( 1 <= vertexCount && vertexCount <= 3 ); + + switch ( vertexCount ) + { + case 1: + return 1; + + case 2: + return vertices[0] != vertices[1] ? 2 : 1; + + case 3: + if ( vertices[0] != vertices[1] && vertices[0] != vertices[2] && vertices[1] != vertices[2] ) + { + // All different + return 3; + } + + if ( vertices[0] == vertices[1] && vertices[0] == vertices[2] && vertices[1] == vertices[2] ) + { + // All equal + return 1; + } + + return 2; + + default: + B3_ASSERT( !"Should never get here!" ); + break; + } + + return 0; +} + +// This checks if the cross product of two edges switches direction. +static inline bool b3CheckFastEdges( b3Transform xfA, b3Vec3 localEdgeA, b3Transform xfB, b3Vec3 localEdgeB, b3Vec3 axis0 ) +{ + // By taking the local witness axes we make sure that we + // get the correct orientations (e.g. if one axis was flipped)! + b3Vec3 edgeA = b3RotateVector( xfA.q, localEdgeA ); + b3Vec3 edgeB = b3RotateVector( xfB.q, localEdgeB ); + b3Vec3 axis = b3Cross( edgeA, edgeB ); + return b3Dot( axis, axis0 ) < 0.0f; +} + +typedef enum b3SeparationType +{ + b3_separationUnknown = 0, + b3_separationVertices, + b3_separationEdges, + b3_separationFaceA, + b3_separationFaceB, +} b3SeparationType; + +typedef struct b3SeparationFunction +{ + const b3ShapeProxy* proxyA; + const b3ShapeProxy* proxyB; + b3Sweep sweepA; + b3Sweep sweepB; + + // These are associated with different bodies depending on the separation function type. + // It could be two local vectors/points on the same body (for example, both on bodyA). + b3Vec3 witness1; + b3Vec3 witness2; + + b3SeparationType type; +} b3SeparationFunction; + +static b3SeparationFunction b3MakeSeparationFunction( const b3SimplexCache cache, const b3ShapeProxy* proxyA, + const b3Sweep* sweepA, const b3ShapeProxy* proxyB, const b3Sweep* sweepB, + const b3DistanceOutput* query, float t1 ) +{ + B3_ASSERT( 1 <= cache.count && cache.count <= 3 ); + B3_VALIDATE( b3IsNormalized( query->normal ) ); + + b3SeparationFunction fcn = { 0 }; + fcn.proxyA = proxyA; + fcn.proxyB = proxyB; + fcn.sweepA = *sweepA; + fcn.sweepB = *sweepB; + fcn.type = b3_separationUnknown; + + int indexA[3] = { cache.indexA[0], cache.indexA[1], cache.indexA[2] }; + int indexB[3] = { cache.indexB[0], cache.indexB[1], cache.indexB[2] }; + + int uniqueCountA = b3UniqueCount( cache.count, indexA ); + int uniqueCountB = b3UniqueCount( cache.count, indexB ); + + b3Transform xfA1 = b3GetSweepTransform( sweepA, t1 ); + b3Transform xfB1 = b3GetSweepTransform( sweepB, t1 ); + + b3Quat qA = xfA1.q; + b3Quat qB = xfB1.q; + + // Minimize round-off + b3Vec3 deltaP = b3Sub( xfB1.p, xfA1.p ); + + switch ( cache.count ) + { + case 1: + { + // Witness is the world space direction + fcn.type = b3_separationVertices; + fcn.witness1 = query->normal; + } + break; + + case 2: + { + if ( uniqueCountA == 2 && uniqueCountB == 2 ) + { + // Edge/Edge + b3Vec3 vA1 = proxyA->points[indexA[0]]; + b3Vec3 localEdgeA = b3Sub( proxyA->points[indexA[1]], vA1 ); + localEdgeA = b3Normalize( localEdgeA ); + b3Vec3 edgeA = b3RotateVector( qA, localEdgeA ); + + b3Vec3 vB1 = proxyB->points[indexB[0]]; + b3Vec3 localEdgeB = b3Sub( proxyB->points[indexB[1]], vB1 ); + localEdgeB = b3Normalize( localEdgeB ); + b3Vec3 edgeB = b3RotateVector( qB, localEdgeB ); + + b3Vec3 axis = b3Cross( edgeA, edgeB ); + float lengthSquared = b3LengthSquared( axis ); + + // Skip near parallel edges: |e1 x e1| = sin(alpha) * |e1| * |e2| + const float kToleranceSquared = 0.05f * 0.05f; + if ( lengthSquared < kToleranceSquared ) + { + // The axis is not safe to normalize so we use a world axis instead! + fcn.type = b3_separationVertices; + fcn.witness1 = query->normal; + } + else + { + b3Vec3 delta = b3Add( b3Sub( b3RotateVector( qB, vB1 ), b3RotateVector( qA, vA1 ) ), deltaP ); + if ( b3Dot( delta, axis ) < 0.0f ) + { + // Make axis point from A to B + axis = b3Neg( axis ); + localEdgeB = b3Neg( localEdgeB ); + } + + // Check for possible sign flip in edge/edge cross product + b3Transform xfA2 = b3GetFinalSweepTransform( sweepA ); + b3Transform xfB2 = b3GetFinalSweepTransform( sweepB ); + bool fastEdges = b3CheckFastEdges( xfA2, localEdgeA, xfB2, localEdgeB, axis ); + if ( fastEdges == true ) + { + // Not safe to use local edges, fall back to initial world space axis instead + fcn.type = b3_separationVertices; + fcn.witness1 = b3Normalize( axis ); + } + else + { + // Edge cross product is safe. This converges faster than a fixed axis. + fcn.type = b3_separationEdges; + fcn.witness1 = localEdgeA; + fcn.witness2 = localEdgeB; + } + } + } + else + { + B3_VALIDATE( b3IsNormalized( query->normal ) ); + + // Vertex versus edge, use world axis witness + fcn.type = b3_separationVertices; + fcn.witness1 = query->normal; + } + } + break; + + case 3: + { + if ( uniqueCountA == 3 ) + { + b3Vec3 vA1 = proxyA->points[indexA[0]]; + b3Vec3 vA2 = proxyA->points[indexA[1]]; + b3Vec3 vA3 = proxyA->points[indexA[2]]; + b3Vec3 localAxisA = b3Cross( b3Sub( vA2, vA1 ), b3Sub( vA3, vA1 ) ); + localAxisA = b3Normalize( localAxisA ); + b3Vec3 axisA = b3RotateVector( qA, localAxisA ); + + b3Vec3 localPointA = b3MulSV( 1.0f / 3.0f, b3Add( b3Add( vA1, vA2 ), vA3 ) ); + b3Vec3 localPointB = proxyB->points[indexB[0]]; + b3Vec3 delta = b3Add( b3Sub( b3RotateVector( qB, localPointB ), b3RotateVector( qA, localPointA ) ), deltaP ); + + if ( b3Dot( delta, axisA ) < 0.0f ) + { + // Make axis point from A to B + localAxisA = b3Neg( localAxisA ); + } + + // Witness is the local plane of faceA + fcn.type = b3_separationFaceA; + fcn.witness1 = localAxisA; + fcn.witness2 = localPointA; + } + else if ( uniqueCountB == 3 ) + { + b3Vec3 vB1 = proxyB->points[indexB[0]]; + b3Vec3 vB2 = proxyB->points[indexB[1]]; + b3Vec3 vB3 = proxyB->points[indexB[2]]; + b3Vec3 localAxisB = b3Cross( b3Sub( vB2, vB1 ), b3Sub( vB3, vB1 ) ); + localAxisB = b3Normalize( localAxisB ); + b3Vec3 axisB = b3RotateVector( qB, localAxisB ); + + b3Vec3 localPointA = proxyA->points[indexA[0]]; + b3Vec3 localPointB = b3MulSV( 1.0f / 3.0f, b3Add( b3Add( vB1, vB2 ), vB3 ) ); + b3Vec3 delta = b3Sub( b3Sub( b3RotateVector( qA, localPointA ), b3RotateVector( qB, localPointB ) ), deltaP ); + + if ( b3Dot( delta, axisB ) < 0.0f ) + { + // Make axis point from B to A + localAxisB = b3Neg( localAxisB ); + } + + // Witness is the local plane of faceB + fcn.type = b3_separationFaceB; + fcn.witness1 = localAxisB; + fcn.witness2 = localPointB; + } + else + { + B3_ASSERT( uniqueCountA == 2 && uniqueCountB == 2 ); + + if ( indexA[0] == indexA[1] ) + { + // Make first two indices are unique + indexA[1] = indexA[2]; + B3_ASSERT( indexA[0] != indexA[1] ); + } + + b3Vec3 vA1 = proxyA->points[indexA[0]]; + b3Vec3 vA2 = proxyA->points[indexA[1]]; + b3Vec3 localEdgeA = b3Normalize( b3Sub( vA2, vA1 ) ); + b3Vec3 edgeA = b3RotateVector( qA, localEdgeA ); + + if ( indexB[0] == indexB[1] ) + { + // Make first two indices are unique + indexB[1] = indexB[2]; + B3_ASSERT( indexB[0] != indexB[1] ); + } + + b3Vec3 vB1 = proxyB->points[indexB[0]]; + b3Vec3 vB2 = proxyB->points[indexB[1]]; + b3Vec3 localEdgeB = b3Normalize( b3Sub( vB2, vB1 ) ); + b3Vec3 edgeB = b3RotateVector( qB, localEdgeB ); + + b3Vec3 axis = b3Cross( edgeA, edgeB ); + float lengthSquared = b3LengthSquared( axis ); + + // Skip near parallel edges: |e1 x e1| = sin(alpha) * |e1| * |e2| + const float kToleranceSquared = 0.005f * 0.005f; + if ( lengthSquared < kToleranceSquared ) + { + // The axis is not safe to normalize so we use a world axis instead! + fcn.type = b3_separationVertices; + fcn.witness1 = query->normal; + } + else + { + b3Vec3 delta = b3Add( b3Sub( b3RotateVector( qB, vB1 ), b3RotateVector( qA, vA1 ) ), deltaP ); + if ( b3Dot( delta, axis ) < 0.0f ) + { + // Make axis point from A to B + axis = b3Neg( axis ); + localEdgeB = b3Neg( localEdgeB ); + } + + // Check for possible sign flip in edge/edge cross product + b3Transform xfA2 = b3GetFinalSweepTransform( sweepA ); + b3Transform xfB2 = b3GetFinalSweepTransform( sweepB ); + bool fastEdges = b3CheckFastEdges( xfA2, localEdgeA, xfB2, localEdgeB, axis ); + if ( fastEdges ) + { + // Not safe to use local edges, fall back to initial world space axis instead + fcn.type = b3_separationVertices; + fcn.witness1 = b3Normalize( axis ); + } + else + { + // Edge cross product is safe. This converges faster than a fixed axis. + fcn.type = b3_separationEdges; + fcn.witness1 = localEdgeA; + fcn.witness2 = localEdgeB; + } + } + } + } + break; + + default: + B3_ASSERT( !"Should never get here!" ); + break; + } + + return fcn; +} + +static float b3FindMinSeparation( b3SeparationFunction* fcn, int* indexA, int* indexB, float t ) +{ + b3Transform xfA = b3GetSweepTransform( &fcn->sweepA, t ); + b3Transform xfB = b3GetSweepTransform( &fcn->sweepB, t ); + + switch ( fcn->type ) + { + case b3_separationVertices: + { + b3Vec3 axis = fcn->witness1; + + b3Vec3 localAxisA = b3InvRotateVector( xfA.q, axis ); + b3Vec3 localAxisB = b3InvRotateVector( xfB.q, b3Neg( axis ) ); + + *indexA = b3GetPointSupport( fcn->proxyA->points, fcn->proxyA->count, localAxisA ); + *indexB = b3GetPointSupport( fcn->proxyB->points, fcn->proxyB->count, localAxisB ); + + b3Vec3 deltaP = b3Sub( xfB.p, xfA.p ); + b3Vec3 localPointA = fcn->proxyA->points[*indexA]; + b3Vec3 localPointB = fcn->proxyB->points[*indexB]; + b3Vec3 delta = b3Add( b3Sub( b3RotateVector( xfB.q, localPointB ), b3RotateVector( xfA.q, localPointA ) ), deltaP ); + return b3Dot( delta, axis ); + } + + case b3_separationEdges: + { + b3Vec3 edgeA = b3RotateVector( xfA.q, fcn->witness1 ); + b3Vec3 edgeB = b3RotateVector( xfB.q, fcn->witness2 ); + b3Vec3 axis = b3Cross( edgeA, edgeB ); + B3_ASSERT( axis.x != 0.0f || axis.y != 0.0f || axis.z != 0.0f ); + axis = b3Normalize( axis ); + + b3Vec3 axisA = b3InvRotateVector( xfA.q, axis ); + *indexA = b3GetPointSupport( fcn->proxyA->points, fcn->proxyA->count, axisA ); + + b3Vec3 axisB = b3InvRotateVector( xfB.q, axis ); + *indexB = b3GetPointSupport( fcn->proxyB->points, fcn->proxyB->count, b3Neg( axisB ) ); + + b3Vec3 deltaP = b3Sub( xfB.p, xfA.p ); + b3Vec3 localPointA = fcn->proxyA->points[*indexA]; + b3Vec3 localPointB = fcn->proxyB->points[*indexB]; + b3Vec3 delta = b3Add( b3Sub( b3RotateVector( xfB.q, localPointB ), b3RotateVector( xfA.q, localPointA ) ), deltaP ); + + return b3Dot( delta, axis ); + } + + case b3_separationFaceA: + { + b3Vec3 normal = b3RotateVector( xfA.q, fcn->witness1 ); + *indexA = -1; + b3Vec3 pointA = b3TransformPoint( xfA, fcn->witness2 ); + + b3Vec3 axisB = b3InvRotateVector( xfB.q, normal ); + *indexB = b3GetPointSupport( fcn->proxyB->points, fcn->proxyB->count, b3Neg( axisB ) ); + b3Vec3 pointB = b3TransformPoint( xfB, fcn->proxyB->points[*indexB] ); + + return b3Dot( b3Sub( pointB, pointA ), normal ); + } + + case b3_separationFaceB: + { + b3Vec3 normal = b3RotateVector( xfB.q, fcn->witness1 ); + + b3Vec3 axisA = b3InvRotateVector( xfA.q, normal ); + *indexA = b3GetPointSupport( fcn->proxyA->points, fcn->proxyA->count, b3Neg( axisA ) ); + b3Vec3 pointA = b3TransformPoint( xfA, fcn->proxyA->points[*indexA] ); + + *indexB = -1; + b3Vec3 pointB = b3TransformPoint( xfB, fcn->witness2 ); + + return b3Dot( b3Sub( pointA, pointB ), normal ); + } + + default: + B3_ASSERT( !"Should never get here!" ); + break; + } + + return 0.0f; +} + +static float b3EvaluateSeparation( b3SeparationFunction* fcn, int index1, int index2, float beta ) +{ + b3Transform transform1 = b3GetSweepTransform( &fcn->sweepA, beta ); + b3Transform transform2 = b3GetSweepTransform( &fcn->sweepB, beta ); + + switch ( fcn->type ) + { + case b3_separationVertices: + { + b3Vec3 axis = fcn->witness1; + + b3Vec3 point1 = b3TransformPoint( transform1, fcn->proxyA->points[index1] ); + b3Vec3 point2 = b3TransformPoint( transform2, fcn->proxyB->points[index2] ); + + return b3Dot( b3Sub( point2, point1 ), axis ); + } + + case b3_separationEdges: + { + b3Vec3 edge1 = b3RotateVector( transform1.q, fcn->witness1 ); + b3Vec3 edge2 = b3RotateVector( transform2.q, fcn->witness2 ); + b3Vec3 axis = b3Cross( edge1, edge2 ); + axis = b3Normalize( axis ); + + b3Vec3 point1 = b3TransformPoint( transform1, fcn->proxyA->points[index1] ); + b3Vec3 point2 = b3TransformPoint( transform2, fcn->proxyB->points[index2] ); + + return b3Dot( b3Sub( point2, point1 ), axis ); + } + + case b3_separationFaceA: + { + b3Vec3 axis = b3RotateVector( transform1.q, fcn->witness1 ); + + b3Vec3 point1 = b3TransformPoint( transform1, fcn->witness2 ); + b3Vec3 point2 = b3TransformPoint( transform2, fcn->proxyB->points[index2] ); + + return b3Dot( b3Sub( point2, point1 ), axis ); + } + + case b3_separationFaceB: + { + b3Vec3 axis = b3RotateVector( transform2.q, fcn->witness1 ); + + b3Vec3 point1 = b3TransformPoint( transform1, fcn->proxyA->points[index1] ); + b3Vec3 point2 = b3TransformPoint( transform2, fcn->witness2 ); + + return b3Dot( b3Sub( point1, point2 ), axis ); + } + + default: + B3_ASSERT( !"Should never get here!" ); + break; + } + + return 0.0f; +} + +static void b3ForceFixedAxis( b3SeparationFunction* fcn, float beta ) +{ + B3_ASSERT( fcn->type == b3_separationEdges ); + + b3Transform transform1 = b3GetSweepTransform( &fcn->sweepA, beta ); + b3Transform transform2 = b3GetSweepTransform( &fcn->sweepB, beta ); + + b3Vec3 edge1 = b3RotateVector( transform1.q, fcn->witness1 ); + b3Vec3 edge2 = b3RotateVector( transform2.q, fcn->witness2 ); + b3Vec3 axis = b3Cross( edge1, edge2 ); + axis = b3Normalize( axis ); + + fcn->type = b3_separationVertices; + fcn->witness1 = axis; + fcn->witness2 = b3Vec3_zero; +} + +// Time of Impact using root finding +b3TOIOutput b3TimeOfImpact( const b3TOIInput* input ) +{ + b3TOIOutput output = { 0 }; + + // Set these to invalid values so they can be validated on exit + output.state = b3_toiStateUnknown; + output.fraction = -1.0f; + + b3Sweep sweepA = input->sweepA; + b3Sweep sweepB = input->sweepB; + + // Shift to origin + b3Vec3 origin = sweepA.c1; + sweepA.c1 = b3Vec3_zero; + sweepA.c2 = b3Sub( sweepA.c2, origin ); + sweepB.c1 = b3Sub( sweepB.c1, origin ); + sweepB.c2 = b3Sub( sweepB.c2, origin ); + + b3ShapeProxy proxyA = input->proxyA; + b3ShapeProxy proxyB = input->proxyB; + + int maxPushBackIterations = proxyA.count + proxyB.count; + float tMax = input->maxFraction; + + // Setup target distance and tolerance + float linearSlop = B3_LINEAR_SLOP; + float totalRadius = proxyA.radius + proxyB.radius; + float target = b3MaxFloat( linearSlop, totalRadius - linearSlop ); + float tolerance = 0.25f * linearSlop; + B3_ASSERT( target > tolerance ); + + float t1 = 0.0f; + const int maxIterations = 25; + int distanceIterations = 0; + + // Prepare input for distance query. + b3SimplexCache cache = { 0 }; + b3DistanceInput distanceInput = { 0 }; + distanceInput.proxyA = proxyA; + distanceInput.proxyB = 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 ( ;; ) + { + // Get the distance between shapes. We can also use the results to get a separating axis. + distanceInput.transformA = b3GetSweepTransform( &sweepA, t1 ); + distanceInput.transformB = b3GetSweepTransform( &sweepB, t1 ); + b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, &cache, NULL, 0 ); + output.distance = distanceOutput.distance; + + output.distanceIterations += 1; + distanceIterations += 1; + + // If the shapes are overlapped, we give up on continuous collision. + if ( distanceOutput.distance <= 0.0f ) + { + output.state = b3_toiStateOverlapped; + output.fraction = 0.0f; + break; + } + + if ( distanceOutput.distance <= target + tolerance ) + { + // Success! + output.state = b3_toiStateHit; + + // Averaged hit point + b3Vec3 pA = b3MulAdd( distanceOutput.pointA, proxyA.radius, distanceOutput.normal ); + b3Vec3 pB = b3MulAdd( distanceOutput.pointB, -proxyB.radius, distanceOutput.normal ); + output.point = b3Lerp( pA, pB, 0.5f ); + output.point = b3Add( output.point, origin ); + output.normal = distanceOutput.normal; + output.fraction = t1; + break; + } + + if ( distanceIterations == maxIterations ) + { + // Progress too slow. This can happen when a capsule rotates around a + // triangle vertex. + output.state = b3_toiStateFailed; + output.fraction = t1; + + // Averaged hit point + b3Vec3 pA = b3MulAdd( distanceOutput.pointA, input->proxyA.radius, distanceOutput.normal ); + b3Vec3 pB = b3MulAdd( distanceOutput.pointB, -input->proxyB.radius, distanceOutput.normal ); + output.point = b3Lerp( pA, pB, 0.5f ); + output.point = b3Add( output.point, origin ); + output.normal = distanceOutput.normal; + break; + } + + // Initialize the separating axis. + b3SeparationFunction function = + b3MakeSeparationFunction( cache, &proxyA, &sweepA, &proxyB, &sweepB, &distanceOutput, t1 ); + +#if B3_ENABLE_VALIDATION && 0 + // todo this can give a negative value for diagonal edge contact on faces, typical GJK problem + // to fix this I think the separation function would need to identify faces + { + int index1, index2; + float minSeparation = b3FindMinSeparation( &function, &index1, &index2, t1 ); + // SAT should give a closer result than GJK + B3_VALIDATE( minSeparation > target - tolerance && minSeparation - distanceOutput.distance < 0.1f * B3_LINEAR_SLOP ); + } +#endif + + // Compute the TOI on the separating axis. We do this by successively resolving the deepest point. + bool done = false; + float t2 = tMax; + int pushBackIterations = 0; + for ( ;; ) + { + int indexA, indexB; + float s2 = b3FindMinSeparation( &function, &indexA, &indexB, t2 ); + + // Dump the function seen by the root finder + // for ( int Step = 0; Step <= 100; ++Step ) + // { + // float Alpha = 0.01f * Step; + // float Separation = Function.Evaluate( Index1, Index2, Alpha ); + // + // b3Report( "s(%4.2g) = %g\n", Alpha, Separation ); + // } + + // Is the final configuration separated? + if ( s2 - target > tolerance ) + { + // Success! + output.state = b3_toiStateSeparated; + output.fraction = input->maxFraction; + 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 = b3EvaluateSeparation( &function, indexA, indexB, t1 ); + + // Check for overlap. This might happen if the root finder runs out of iterations. + if ( s1 < target - tolerance ) + { + // Failed! + B3_VALIDATE( false ); + output.state = b3_toiStateFailed; + output.fraction = t1; + done = true; + break; + } + + // Has the separation reached tolerance? + if ( s1 <= target + tolerance ) + { + // Success! t1 should hold the TOI (could be 0.0) + output.state = b3_toiStateHit; + output.fraction = t1; + done = true; + break; + } + + // Compute 1D root of: f(x) - target = 0 + int rootIterationCount = 0; + int maxRootIterations = 50; + float a1 = t1; + float a2 = t2; + for ( ;; ) + { + // Use a mix of false position and bisection. + float t; + if ( rootIterationCount & 1 ) + { + // False position to improve convergence. + t = a1 + ( target - s1 ) * ( a2 - a1 ) / ( s2 - s1 ); + } + else + { + // Bisection to guarantee progress. + t = 0.5f * ( a1 + a2 ); + } + + output.rootIterations += 1; + rootIterationCount += 1; + + float s = b3EvaluateSeparation( &function, indexA, indexB, t ); + + // Has the separation reached tolerance? + if ( b3AbsFloat( 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 == maxRootIterations ) + { + B3_VALIDATE( false ); + break; + } + } + + // Restart the inner loop if we have a failing edge case. + if ( rootIterationCount == maxRootIterations - 1 && function.type == b3_separationEdges ) + { + B3_VALIDATE( false ); + + rootIterationCount = 0; + t2 = input->maxFraction; + b3ForceFixedAxis( &function, t1 ); + B3_ASSERT( function.type != b3_separationEdges ); + } + + output.pushBackIterations += 1; + pushBackIterations += 1; + + if ( pushBackIterations == maxPushBackIterations ) + { + break; + } + } + + if ( done ) + { + // Averaged hit point + b3Vec3 pA = b3MulAdd( distanceOutput.pointA, input->proxyA.radius, distanceOutput.normal ); + b3Vec3 pB = b3MulAdd( distanceOutput.pointB, -input->proxyB.radius, distanceOutput.normal ); + output.point = b3Lerp( pA, pB, 0.5f ); + output.point = b3Add( output.point, origin ); + output.normal = distanceOutput.normal; + break; + } + } + + // It is expected that the state and fraction are set before reaching this + B3_ASSERT( output.state != b3_toiStateUnknown ); + B3_ASSERT( output.fraction >= 0.0f ); + + return output; +} diff --git a/src/distance_joint.c b/src/distance_joint.c new file mode 100644 index 0000000..382b80f --- /dev/null +++ b/src/distance_joint.c @@ -0,0 +1,558 @@ +// SPDX-FileCopyrightText: 2025 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 "box3d/box3d.h" + +void b3DistanceJoint_SetLength( b3JointId jointId, float length ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + b3DistanceJoint* joint = &base->distanceJoint; + + joint->length = b3ClampFloat( length, B3_LINEAR_SLOP, B3_HUGE ); + joint->impulse = 0.0f; + joint->lowerImpulse = 0.0f; + joint->upperImpulse = 0.0f; +} + +float b3DistanceJoint_GetLength( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + b3DistanceJoint* joint = &base->distanceJoint; + return joint->length; +} + +void b3DistanceJoint_EnableLimit( b3JointId jointId, bool enableLimit ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + b3DistanceJoint* joint = &base->distanceJoint; + joint->enableLimit = enableLimit; +} + +bool b3DistanceJoint_IsLimitEnabled( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + return joint->distanceJoint.enableLimit; +} + +void b3DistanceJoint_SetLengthRange( b3JointId jointId, float minLength, float maxLength ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + b3DistanceJoint* joint = &base->distanceJoint; + + minLength = b3ClampFloat( minLength, B3_LINEAR_SLOP, B3_HUGE ); + maxLength = b3ClampFloat( maxLength, B3_LINEAR_SLOP, B3_HUGE ); + joint->minLength = b3MinFloat( minLength, maxLength ); + joint->maxLength = b3MaxFloat( minLength, maxLength ); + joint->impulse = 0.0f; + joint->lowerImpulse = 0.0f; + joint->upperImpulse = 0.0f; +} + +float b3DistanceJoint_GetMinLength( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + b3DistanceJoint* joint = &base->distanceJoint; + return joint->minLength; +} + +float b3DistanceJoint_GetMaxLength( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + b3DistanceJoint* joint = &base->distanceJoint; + return joint->maxLength; +} + +float b3DistanceJoint_GetCurrentLength( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + + b3World* world = b3GetUnlockedWorld( jointId.world0 ); + if ( world == NULL ) + { + return 0.0f; + } + + b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA ); + b3Transform transformB = b3GetBodyTransform( world, base->bodyIdB ); + + b3Vec3 pA = b3TransformPoint( transformA, base->localFrameA.p ); + b3Vec3 pB = b3TransformPoint( transformB, base->localFrameB.p ); + b3Vec3 d = b3Sub( pB, pA ); + float length = b3Length( d ); + return length; +} + +void b3DistanceJoint_EnableSpring( b3JointId jointId, bool enableSpring ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + base->distanceJoint.enableSpring = enableSpring; +} + +bool b3DistanceJoint_IsSpringEnabled( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + return base->distanceJoint.enableSpring; +} + + +void b3DistanceJoint_SetSpringForceRange( b3JointId jointId, float lowerForce, float upperForce ) +{ + B3_ASSERT( lowerForce <= upperForce ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + base->distanceJoint.lowerSpringForce = lowerForce; + base->distanceJoint.upperSpringForce = upperForce; +} + +void b3DistanceJoint_GetSpringForceRange( b3JointId jointId, float* lowerForce, float* upperForce ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + *lowerForce = base->distanceJoint.lowerSpringForce; + *upperForce = base->distanceJoint.upperSpringForce; +} + +void b3DistanceJoint_SetSpringHertz( b3JointId jointId, float hertz ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + base->distanceJoint.hertz = hertz; +} + +void b3DistanceJoint_SetSpringDampingRatio( b3JointId jointId, float dampingRatio ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + base->distanceJoint.dampingRatio = dampingRatio; +} + +float b3DistanceJoint_GetSpringHertz( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + b3DistanceJoint* joint = &base->distanceJoint; + return joint->hertz; +} + +float b3DistanceJoint_GetSpringDampingRatio( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + b3DistanceJoint* joint = &base->distanceJoint; + return joint->dampingRatio; +} + +void b3DistanceJoint_EnableMotor( b3JointId jointId, bool enableMotor ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + if ( enableMotor != joint->distanceJoint.enableMotor ) + { + joint->distanceJoint.enableMotor = enableMotor; + joint->distanceJoint.motorImpulse = 0.0f; + } +} + +bool b3DistanceJoint_IsMotorEnabled( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + return joint->distanceJoint.enableMotor; +} + +void b3DistanceJoint_SetMotorSpeed( b3JointId jointId, float motorSpeed ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + joint->distanceJoint.motorSpeed = motorSpeed; +} + +float b3DistanceJoint_GetMotorSpeed( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + return joint->distanceJoint.motorSpeed; +} + +float b3DistanceJoint_GetMotorForce( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + return world->inv_h * base->distanceJoint.motorImpulse; +} + +void b3DistanceJoint_SetMaxMotorForce( b3JointId jointId, float force ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + joint->distanceJoint.maxMotorForce = force; +} + +float b3DistanceJoint_GetMaxMotorForce( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_distanceJoint ); + return joint->distanceJoint.maxMotorForce; +} + +b3Vec3 b3GetDistanceJointForce( b3World* world, b3JointSim* base ) +{ + b3DistanceJoint* joint = &base->distanceJoint; + + b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA ); + b3Transform transformB = b3GetBodyTransform( world, base->bodyIdB ); + + b3Vec3 pA = b3TransformPoint( transformA, base->localFrameA.p ); + b3Vec3 pB = b3TransformPoint( transformB, base->localFrameB.p ); + b3Vec3 d = b3Sub( pB, pA ); + b3Vec3 axis = b3Normalize( d ); + float force = ( joint->impulse + joint->lowerImpulse - joint->upperImpulse + joint->motorImpulse ) * world->inv_h; + return b3MulSV( 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 b3PrepareDistanceJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_distanceJoint ); + + // chase body id to the solver set where the body lives + int idA = base->bodyIdA; + int idB = base->bodyIdB; + + b3World* world = context->world; + b3Body* bodyA = b3Array_Get( world->bodies, idA ); + b3Body* bodyB = b3Array_Get( world->bodies, idB ); + + B3_ASSERT( bodyA->setIndex == b3_awakeSet || bodyB->setIndex == b3_awakeSet ); + + b3SolverSet* setA = b3Array_Get( world->solverSets, bodyA->setIndex ); + b3SolverSet* setB = b3Array_Get( world->solverSets, bodyB->setIndex ); + + int localIndexA = bodyA->localIndex; + int localIndexB = bodyB->localIndex; + + b3BodySim* bodySimA = b3Array_Get( setA->bodySims, localIndexA ); + b3BodySim* bodySimB = b3Array_Get( setB->bodySims, localIndexB ); + + float mA = bodySimA->invMass; + b3Matrix3 iA = bodySimA->invInertiaWorld; + float mB = bodySimB->invMass; + b3Matrix3 iB = bodySimB->invInertiaWorld; + + base->invMassA = mA; + base->invMassB = mB; + base->invIA = iA; + base->invIB = iB; + + b3DistanceJoint* joint = &base->distanceJoint; + + joint->indexA = bodyA->setIndex == b3_awakeSet ? localIndexA : B3_NULL_INDEX; + joint->indexB = bodyB->setIndex == b3_awakeSet ? localIndexB : B3_NULL_INDEX; + + // initial anchors in world space + joint->anchorA = b3RotateVector( bodySimA->transform.q, b3Sub( base->localFrameA.p, bodySimA->localCenter ) ); + joint->anchorB = b3RotateVector( bodySimB->transform.q, b3Sub( base->localFrameB.p, bodySimB->localCenter ) ); + joint->deltaCenter = b3Sub( bodySimB->center, bodySimA->center ); + + b3Vec3 rA = joint->anchorA; + b3Vec3 rB = joint->anchorB; + b3Vec3 separation = b3Add( b3Sub( rB, rA ), joint->deltaCenter ); + b3Vec3 axis = b3Normalize( separation ); + + // compute effective mass + b3Vec3 crA = b3Cross( rA, axis ); + b3Vec3 crB = b3Cross( rB, axis ); + float k = mA + mB + b3Dot( crA, b3MulMV( iA, crA ) ) + b3Dot( crB, b3MulMV( iB, crB ) ); + joint->axialMass = k > 0.0f ? 1.0f / k : 0.0f; + + joint->distanceSoftness = b3MakeSoft( 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 b3WarmStartDistanceJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_distanceJoint ); + + float mA = base->invMassA; + float mB = base->invMassB; + b3Matrix3 iA = base->invIA; + b3Matrix3 iB = base->invIB; + + // dummy state for static bodies + b3BodyState dummyState = b3_identityBodyState; + + b3DistanceJoint* joint = &base->distanceJoint; + b3BodyState* stateA = joint->indexA == B3_NULL_INDEX ? &dummyState : context->states + joint->indexA; + b3BodyState* stateB = joint->indexB == B3_NULL_INDEX ? &dummyState : context->states + joint->indexB; + + b3Vec3 rA = b3RotateVector( stateA->deltaRotation, joint->anchorA ); + b3Vec3 rB = b3RotateVector( stateB->deltaRotation, joint->anchorB ); + + b3Vec3 ds = b3Add( b3Sub( stateB->deltaPosition, stateA->deltaPosition ), b3Sub( rB, rA ) ); + b3Vec3 separation = b3Add( joint->deltaCenter, ds ); + b3Vec3 axis = b3Normalize( separation ); + + float axialImpulse = joint->impulse + joint->lowerImpulse - joint->upperImpulse + joint->motorImpulse; + b3Vec3 P = b3MulSV( axialImpulse, axis ); + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->linearVelocity = b3MulSub( stateA->linearVelocity, mA, P ); + stateA->angularVelocity = b3Sub( stateA->angularVelocity, b3MulMV( iA, b3Cross( rA, P ) ) ); + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->linearVelocity = b3MulAdd( stateB->linearVelocity, mB, P ); + stateB->angularVelocity = b3Add( stateB->angularVelocity, b3MulMV( iB, b3Cross( rB, P ) ) ); + } +} + +void b3SolveDistanceJoint( b3JointSim* base, b3StepContext* context, bool useBias ) +{ + B3_ASSERT( base->type == b3_distanceJoint ); + + float mA = base->invMassA; + float mB = base->invMassB; + b3Matrix3 iA = base->invIA; + b3Matrix3 iB = base->invIB; + + // dummy state for static bodies + b3BodyState dummyState = b3_identityBodyState; + + b3DistanceJoint* joint = &base->distanceJoint; + b3BodyState* stateA = joint->indexA == B3_NULL_INDEX ? &dummyState : context->states + joint->indexA; + b3BodyState* stateB = joint->indexB == B3_NULL_INDEX ? &dummyState : context->states + joint->indexB; + + b3Vec3 vA = stateA->linearVelocity; + b3Vec3 wA = stateA->angularVelocity; + b3Vec3 vB = stateB->linearVelocity; + b3Vec3 wB = stateB->angularVelocity; + + // current anchors + b3Vec3 rA = b3RotateVector( stateA->deltaRotation, joint->anchorA ); + b3Vec3 rB = b3RotateVector( stateB->deltaRotation, joint->anchorB ); + + // current separation + b3Vec3 ds = b3Add( b3Sub( stateB->deltaPosition, stateA->deltaPosition ), b3Sub( rB, rA ) ); + b3Vec3 separation = b3Add( joint->deltaCenter, ds ); + + float length = b3Length( separation ); + b3Vec3 axis = b3Normalize( 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)) + b3Vec3 vr = b3Add( b3Sub( vB, vA ), b3Sub( b3Cross( wB, rB ), b3Cross( wA, rA ) ) ); + float Cdot = b3Dot( 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 = b3ClampFloat( joint->impulse + impulse, joint->lowerSpringForce * h, joint->upperSpringForce * h ); + impulse = joint->impulse - oldImpulse; + + b3Vec3 P = b3MulSV( impulse, axis ); + vA = b3MulSub( vA, mA, P ); + wA = b3Sub( wA, b3MulMV( iA, b3Cross( rA, P ) ) ); + vB = b3MulAdd( vB, mB, P ); + wB = b3Add( wB, b3MulMV( iB, b3Cross( rB, P ) ) ); + } + + if ( joint->enableLimit ) + { + // lower limit + { + b3Vec3 vr = b3Add( b3Sub( vB, vA ), b3Sub( b3Cross( wB, rB ), b3Cross( wA, rA ) ) ); + float Cdot = b3Dot( 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 = b3MaxFloat( 0.0f, joint->lowerImpulse + impulse ); + impulse = newImpulse - joint->lowerImpulse; + joint->lowerImpulse = newImpulse; + + b3Vec3 P = b3MulSV( impulse, axis ); + vA = b3MulSub( vA, mA, P ); + wA = b3Sub( wA, b3MulMV( iA, b3Cross( rA, P ) ) ); + vB = b3MulAdd( vB, mB, P ); + wB = b3Add( wB, b3MulMV( iB, b3Cross( rB, P ) ) ); + } + + // upper + { + b3Vec3 vr = b3Add( b3Sub( vA, vB ), b3Sub( b3Cross( wA, rA ), b3Cross( wB, rB ) ) ); + float Cdot = b3Dot( 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 = b3MaxFloat( 0.0f, joint->upperImpulse + impulse ); + impulse = newImpulse - joint->upperImpulse; + joint->upperImpulse = newImpulse; + + b3Vec3 P = b3MulSV( -impulse, axis ); + vA = b3MulSub( vA, mA, P ); + wA = b3Sub( wA, b3MulMV( iA, b3Cross( rA, P ) ) ); + vB = b3MulAdd( vB, mB, P ); + wB = b3Add( wB, b3MulMV( iB, b3Cross( rB, P ) ) ); + } + } + + if ( joint->enableMotor ) + { + b3Vec3 vr = b3Add( b3Sub( vB, vA ), b3Sub( b3Cross( wB, rB ), b3Cross( wA, rA ) ) ); + float Cdot = b3Dot( axis, vr ); + float impulse = joint->axialMass * ( joint->motorSpeed - Cdot ); + float oldImpulse = joint->motorImpulse; + float maxImpulse = context->h * joint->maxMotorForce; + joint->motorImpulse = b3ClampFloat( joint->motorImpulse + impulse, -maxImpulse, maxImpulse ); + impulse = joint->motorImpulse - oldImpulse; + + b3Vec3 P = b3MulSV( impulse, axis ); + vA = b3MulSub( vA, mA, P ); + wA = b3Sub( wA, b3MulMV( iA, b3Cross( rA, P ) ) ); + vB = b3MulAdd( vB, mB, P ); + wB = b3Add( wB, b3MulMV( iB, b3Cross( rB, P ) ) ); + } + } + else + { + // rigid constraint + b3Vec3 vr = b3Add( b3Sub( vB, vA ), b3Sub( b3Cross( wB, rB ), b3Cross( wA, rA ) ) ); + float Cdot = b3Dot( 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; + + b3Vec3 P = b3MulSV( impulse, axis ); + vA = b3MulSub( vA, mA, P ); + wA = b3Sub( wA, b3MulMV( iA, b3Cross( rA, P ) ) ); + vB = b3MulAdd( vB, mB, P ); + wB = b3Add( wB, b3MulMV( iB, b3Cross( rB, P ) ) ); + } + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->linearVelocity = vA; + stateA->angularVelocity = wA; + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->linearVelocity = vB; + stateB->angularVelocity = wB; + } +} + +void b3DrawDistanceJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB ) +{ + B3_ASSERT( base->type == b3_distanceJoint ); + + b3DistanceJoint* joint = &base->distanceJoint; + + b3Vec3 pA = b3TransformPoint( transformA, base->localFrameA.p ); + b3Vec3 pB = b3TransformPoint( transformB, base->localFrameB.p ); + + b3Vec3 axis = b3Normalize( b3Sub( pB, pA ) ); + + if ( joint->minLength < joint->maxLength && joint->enableLimit ) + { + b3Vec3 pMin = b3MulAdd( pA, joint->minLength, axis ); + b3Vec3 pMax = b3MulAdd( pA, joint->maxLength, axis ); + + if ( joint->minLength > B3_LINEAR_SLOP ) + { + draw->DrawPointFcn( pMin, 6.0f, b3_colorLightGreen, draw->context ); + } + + if ( joint->maxLength < B3_HUGE ) + { + draw->DrawPointFcn(pMax, 6.0f, b3_colorRed, draw->context); + } + + if ( joint->minLength > B3_LINEAR_SLOP && joint->maxLength < B3_HUGE ) + { + draw->DrawSegmentFcn( pMin, pMax, b3_colorGray, draw->context ); + } + } + + draw->DrawSegmentFcn( pA, pB, b3_colorWhite, draw->context ); + draw->DrawPointFcn( pA, 4.0f, b3_colorWhite, draw->context ); + draw->DrawPointFcn( pB, 4.0f, b3_colorWhite, draw->context ); + + if ( joint->hertz > 0.0f && joint->enableSpring ) + { + b3Vec3 pRest = b3MulAdd( pA, joint->length, axis ); + draw->DrawPointFcn( pRest, 4.0f, b3_colorBlue, draw->context ); + } +} diff --git a/src/dynamic_tree.c b/src/dynamic_tree.c new file mode 100644 index 0000000..3f34b67 --- /dev/null +++ b/src/dynamic_tree.c @@ -0,0 +1,2217 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "aabb.h" +#include "core.h" +#include "joint.h" +#include "simd.h" + +#include "box3d/collision.h" +#include "box3d/constants.h" +#include "box3d/math_functions.h" + +#include +#include +#include + +#define B3_TREE_STACK_SIZE 1024 + +static b3TreeNode b3_defaultTreeNode = { + .aabb = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } }, + .categoryBits = B3_DEFAULT_CATEGORY_BITS, + .children = + { + .child1 = B3_NULL_INDEX, + .child2 = B3_NULL_INDEX, + }, + .parent = B3_NULL_INDEX, + .height = 0, + .flags = b3_allocatedNode, +}; + +static inline bool b3IsLeaf( const b3TreeNode* node ) +{ + return node->flags & b3_leafNode; +} + +static inline bool b3IsAllocated( const b3TreeNode* node ) +{ + return node->flags & b3_allocatedNode; +} + +static inline uint16_t b3MaxUInt16( uint16_t a, uint16_t b ) +{ + return a > b ? a : b; +} + +b3DynamicTree b3DynamicTree_Create( int proxyCapacity ) +{ + int capacity = b3MaxInt( proxyCapacity, 16 ); + + b3DynamicTree tree; + + // memset needed for deterministic serialization + memset( &tree, 0, sizeof( b3DynamicTree ) ); + + tree.version = B3_DYNAMIC_TREE_VERSION; + tree.root = B3_NULL_INDEX; + + // maximum node count for a full binary tree is 2 * leafCount - 1 + tree.nodeCapacity = 2 * capacity - 1; + tree.nodeCount = 0; + + tree.nodes = (b3TreeNode*)b3Alloc( tree.nodeCapacity * sizeof( b3TreeNode ) ); + + // Better to have 64 byte alignment + B3_VALIDATE( ( (uintptr_t)tree.nodes & 0x3F ) == 0 ); + + memset( tree.nodes, 0, tree.nodeCapacity * sizeof( b3TreeNode ) ); + + // Build a linked list for the free list. + // todo use a bump allocator until the capacity is consumed (see b3PoolAllocator) + for ( int i = 0; i < tree.nodeCapacity - 1; ++i ) + { + tree.nodes[i].next = i + 1; + } + + tree.nodes[tree.nodeCapacity - 1].next = B3_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 b3DynamicTree_Destroy( b3DynamicTree* tree ) +{ + b3Free( tree->nodes, tree->nodeCapacity * sizeof( b3TreeNode ) ); + b3Free( tree->leafIndices, tree->rebuildCapacity * sizeof( int ) ); + b3Free( tree->leafBoxes, tree->rebuildCapacity * sizeof( b3AABB ) ); + b3Free( tree->leafCenters, tree->rebuildCapacity * sizeof( b3Vec3 ) ); + b3Free( tree->binIndices, tree->rebuildCapacity * sizeof( int ) ); + + memset( tree, 0, sizeof( b3DynamicTree ) ); +} + +// Allocate a node from the pool. Grow the pool if necessary. +static int b3AllocateNode( b3DynamicTree* tree ) +{ + // Expand the node pool as needed. + if ( tree->freeList == B3_NULL_INDEX ) + { + B3_ASSERT( tree->nodeCount == tree->nodeCapacity ); + + // The free list is empty. Rebuild a bigger pool. + b3TreeNode* oldNodes = tree->nodes; + int oldCapacity = tree->nodeCapacity; + tree->nodeCapacity += oldCapacity >> 1; + tree->nodes = (b3TreeNode*)b3Alloc( tree->nodeCapacity * sizeof( b3TreeNode ) ); + B3_ASSERT( oldNodes != NULL ); + memcpy( tree->nodes, oldNodes, tree->nodeCount * sizeof( b3TreeNode ) ); + memset( tree->nodes + tree->nodeCount, 0, ( tree->nodeCapacity - tree->nodeCount ) * sizeof( b3TreeNode ) ); + b3Free( oldNodes, oldCapacity * sizeof( b3TreeNode ) ); + + // 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 = B3_NULL_INDEX; + tree->freeList = tree->nodeCount; + } + + // Peel a node off the free list. + int nodeIndex = tree->freeList; + b3TreeNode* node = tree->nodes + nodeIndex; + tree->freeList = node->next; + *node = b3_defaultTreeNode; + ++tree->nodeCount; + return nodeIndex; +} + +// Return a node to the pool. +static void b3FreeNode( b3DynamicTree* tree, int nodeId ) +{ + B3_ASSERT( 0 <= nodeId && nodeId < tree->nodeCapacity ); + B3_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 b3FindBestSibling( const b3DynamicTree* tree, b3AABB boxD ) +{ + b3Vec3 centerD = b3AABB_Center( boxD ); + float areaD = b3Perimeter( boxD ); + + const b3TreeNode* nodes = tree->nodes; + int rootIndex = tree->root; + + b3AABB rootBox = nodes[rootIndex].aabb; + + // Area of current node + float areaBase = b3Perimeter( rootBox ); + + // Area of inflated node + float directCost = b3Perimeter( b3AABB_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 ( b3IsLeaf( nodes + index ) == false ) + { + 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 = b3IsLeaf( nodes + child1 ); + bool leaf2 = b3IsLeaf( nodes + child2 ); + + // Cost of descending into child 1 + float lowerCost1 = FLT_MAX; + b3AABB box1 = nodes[child1].aabb; + float directCost1 = b3Perimeter( b3AABB_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 = b3Perimeter( box1 ); + + // Lower bound cost of inserting under child 1. + lowerCost1 = inheritedCost + directCost1 + b3MinFloat( areaD - area1, 0.0f ); + } + + // Cost of descending into child 2 + float lowerCost2 = FLT_MAX; + b3AABB box2 = nodes[child2].aabb; + float directCost2 = b3Perimeter( b3AABB_Union( box2, boxD ) ); + float area2 = 0.0f; + if ( leaf2 ) + { + // Child 2 is a leaf + // Cost of creating new node and increasing area of node P + float cost2 = directCost2 + inheritedCost; + + // Need this here due to while condition above + if ( cost2 < bestCost ) + { + bestSibling = child2; + bestCost = cost2; + } + } + else + { + // Child 2 is an internal node + area2 = b3Perimeter( box2 ); + + // Lower bound cost of inserting under child 2. This is not the cost + // of child 2, it is the best we can hope for under child 2. + lowerCost2 = inheritedCost + directCost2 + b3MinFloat( 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 ) + { + B3_ASSERT( lowerCost1 < FLT_MAX ); + B3_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. + b3Vec3 d1 = b3Sub( b3AABB_Center( box1 ), centerD ); + b3Vec3 d2 = b3Sub( b3AABB_Center( box2 ), centerD ); + lowerCost1 = b3LengthSquared( d1 ); + lowerCost2 = b3LengthSquared( d2 ); + } + + // Descend + if ( lowerCost1 < lowerCost2 && leaf1 == false ) + { + index = child1; + areaBase = area1; + directCost = directCost1; + } + else + { + index = child2; + areaBase = area2; + directCost = directCost2; + } + + B3_ASSERT( b3IsLeaf( nodes + index ) == false ); + } + + return bestSibling; +} + +enum b3RotateType +{ + b3_rotateNone, + b3_rotateBF, + b3_rotateBG, + b3_rotateCD, + b3_rotateCE +}; + +// Perform a left or right rotation if node A is imbalanced. +// Returns the new root index. +static void b3RotateNodes( b3DynamicTree* tree, int iA ) +{ + B3_ASSERT( iA != B3_NULL_INDEX ); + + b3TreeNode* nodes = tree->nodes; + + b3TreeNode* A = nodes + iA; + if ( b3IsLeaf( A ) == true ) + { + return; + } + + int iB = A->children.child1; + int iC = A->children.child2; + B3_ASSERT( 0 <= iB && iB < tree->nodeCapacity ); + B3_ASSERT( 0 <= iC && iC < tree->nodeCapacity ); + + b3TreeNode* B = nodes + iB; + b3TreeNode* C = nodes + iC; + + bool isLeafB = b3IsLeaf( B ); + bool isLeafC = b3IsLeaf( C ); + + if ( isLeafB == true && isLeafC == false ) + { + int iF = C->children.child1; + int iG = C->children.child2; + b3TreeNode* F = nodes + iF; + b3TreeNode* G = nodes + iG; + B3_ASSERT( 0 <= iF && iF < tree->nodeCapacity ); + B3_ASSERT( 0 <= iG && iG < tree->nodeCapacity ); + + // Base cost + float costBase = b3Perimeter( C->aabb ); + + // Cost of swapping B and F + b3AABB aabbBG = b3AABB_Union( B->aabb, G->aabb ); + float costBF = b3Perimeter( aabbBG ); + + // Cost of swapping B and G + b3AABB aabbBF = b3AABB_Union( B->aabb, F->aabb ); + float costBG = b3Perimeter( 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 + b3MaxUInt16( B->height, G->height ); + A->height = 1 + b3MaxUInt16( C->height, F->height ); + C->categoryBits = B->categoryBits | G->categoryBits; + A->categoryBits = C->categoryBits | F->categoryBits; + C->flags |= ( B->flags | G->flags ) & b3_enlargedNode; + A->flags |= ( C->flags | F->flags ) & b3_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 + b3MaxUInt16( B->height, F->height ); + A->height = 1 + b3MaxUInt16( C->height, G->height ); + C->categoryBits = B->categoryBits | F->categoryBits; + A->categoryBits = C->categoryBits | G->categoryBits; + C->flags |= ( B->flags | F->flags ) & b3_enlargedNode; + A->flags |= ( C->flags | G->flags ) & b3_enlargedNode; + } + } + else if ( isLeafC == true && isLeafB == false ) + { + // C is a leaf and B is internal + + int iD = B->children.child1; + int iE = B->children.child2; + b3TreeNode* D = nodes + iD; + b3TreeNode* E = nodes + iE; + B3_ASSERT( 0 <= iD && iD < tree->nodeCapacity ); + B3_ASSERT( 0 <= iE && iE < tree->nodeCapacity ); + + // Base cost + float costBase = b3Perimeter( B->aabb ); + + // Cost of swapping C and D + b3AABB aabbCE = b3AABB_Union( C->aabb, E->aabb ); + float costCD = b3Perimeter( aabbCE ); + + // Cost of swapping C and E + b3AABB aabbCD = b3AABB_Union( C->aabb, D->aabb ); + float costCE = b3Perimeter( 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 + b3MaxUInt16( C->height, E->height ); + A->height = 1 + b3MaxUInt16( B->height, D->height ); + B->categoryBits = C->categoryBits | E->categoryBits; + A->categoryBits = B->categoryBits | D->categoryBits; + B->flags |= ( C->flags | E->flags ) & b3_enlargedNode; + A->flags |= ( B->flags | D->flags ) & b3_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 + b3MaxUInt16( C->height, D->height ); + A->height = 1 + b3MaxUInt16( B->height, E->height ); + B->categoryBits = C->categoryBits | D->categoryBits; + A->categoryBits = B->categoryBits | E->categoryBits; + B->flags |= ( C->flags | D->flags ) & b3_enlargedNode; + A->flags |= ( B->flags | E->flags ) & b3_enlargedNode; + } + } + else if ( isLeafB == false && isLeafC == false ) + { + // All grand children exist so there are many options for rotation + int iD = B->children.child1; + int iE = B->children.child2; + int iF = C->children.child1; + int iG = C->children.child2; + + B3_ASSERT( 0 <= iD && iD < tree->nodeCapacity ); + B3_ASSERT( 0 <= iE && iE < tree->nodeCapacity ); + B3_ASSERT( 0 <= iF && iF < tree->nodeCapacity ); + B3_ASSERT( 0 <= iG && iG < tree->nodeCapacity ); + + b3TreeNode* D = nodes + iD; + b3TreeNode* E = nodes + iE; + b3TreeNode* F = nodes + iF; + b3TreeNode* G = nodes + iG; + + // Base cost + float areaB = b3Perimeter( B->aabb ); + float areaC = b3Perimeter( C->aabb ); + float costBase = areaB + areaC; + enum b3RotateType bestRotation = b3_rotateNone; + float bestCost = costBase; + + // Cost of swapping B and F + b3AABB aabbBG = b3AABB_Union( B->aabb, G->aabb ); + float costBF = areaB + b3Perimeter( aabbBG ); + if ( costBF < bestCost ) + { + bestRotation = b3_rotateBF; + bestCost = costBF; + } + + // Cost of swapping B and G + b3AABB aabbBF = b3AABB_Union( B->aabb, F->aabb ); + float costBG = areaB + b3Perimeter( aabbBF ); + if ( costBG < bestCost ) + { + bestRotation = b3_rotateBG; + bestCost = costBG; + } + + // Cost of swapping C and D + b3AABB aabbCE = b3AABB_Union( C->aabb, E->aabb ); + float costCD = areaC + b3Perimeter( aabbCE ); + if ( costCD < bestCost ) + { + bestRotation = b3_rotateCD; + bestCost = costCD; + } + + // Cost of swapping C and E + b3AABB aabbCD = b3AABB_Union( C->aabb, D->aabb ); + float costCE = areaC + b3Perimeter( aabbCD ); + if ( costCE < bestCost ) + { + bestRotation = b3_rotateCE; + // bestCost = costCE; + } + + switch ( bestRotation ) + { + case b3_rotateNone: + break; + + case b3_rotateBF: + A->children.child1 = iF; + C->children.child1 = iB; + + B->parent = iC; + F->parent = iA; + + C->aabb = aabbBG; + + C->height = 1 + b3MaxUInt16( B->height, G->height ); + A->height = 1 + b3MaxUInt16( C->height, F->height ); + C->categoryBits = B->categoryBits | G->categoryBits; + A->categoryBits = C->categoryBits | F->categoryBits; + C->flags |= ( B->flags | G->flags ) & b3_enlargedNode; + A->flags |= ( C->flags | F->flags ) & b3_enlargedNode; + break; + + case b3_rotateBG: + A->children.child1 = iG; + C->children.child2 = iB; + + B->parent = iC; + G->parent = iA; + + C->aabb = aabbBF; + + C->height = 1 + b3MaxUInt16( B->height, F->height ); + A->height = 1 + b3MaxUInt16( C->height, G->height ); + C->categoryBits = B->categoryBits | F->categoryBits; + A->categoryBits = C->categoryBits | G->categoryBits; + C->flags |= ( B->flags | F->flags ) & b3_enlargedNode; + A->flags |= ( C->flags | G->flags ) & b3_enlargedNode; + break; + + case b3_rotateCD: + A->children.child2 = iD; + B->children.child1 = iC; + + C->parent = iB; + D->parent = iA; + + B->aabb = aabbCE; + + B->height = 1 + b3MaxUInt16( C->height, E->height ); + A->height = 1 + b3MaxUInt16( B->height, D->height ); + B->categoryBits = C->categoryBits | E->categoryBits; + A->categoryBits = B->categoryBits | D->categoryBits; + B->flags |= ( C->flags | E->flags ) & b3_enlargedNode; + A->flags |= ( B->flags | D->flags ) & b3_enlargedNode; + break; + + case b3_rotateCE: + A->children.child2 = iE; + B->children.child2 = iC; + + C->parent = iB; + E->parent = iA; + + B->aabb = aabbCD; + + B->height = 1 + b3MaxUInt16( C->height, D->height ); + A->height = 1 + b3MaxUInt16( B->height, E->height ); + B->categoryBits = C->categoryBits | D->categoryBits; + A->categoryBits = B->categoryBits | E->categoryBits; + B->flags |= ( C->flags | D->flags ) & b3_enlargedNode; + A->flags |= ( B->flags | E->flags ) & b3_enlargedNode; + break; + + default: + B3_ASSERT( false ); + break; + } + } +} + +// It would be nicer if the root had zero height but maintaining this would drastically increase +// insertion cost because whole sub-trees would need the height to be updated. +static void b3InsertLeaf( b3DynamicTree* tree, int leaf, bool shouldRotate ) +{ + if ( tree->root == B3_NULL_INDEX ) + { + tree->root = leaf; + tree->nodes[tree->root].parent = B3_NULL_INDEX; + return; + } + + // Stage 1: find the best sibling for this node + b3AABB leafAABB = tree->nodes[leaf].aabb; + int sibling = b3FindBestSibling( tree, leafAABB ); + + // Stage 2: create a new parent for the leaf and sibling + int oldParent = tree->nodes[sibling].parent; + int newParent = b3AllocateNode( tree ); + + // warning: node pointer can change after allocation + b3TreeNode* nodes = tree->nodes; + nodes[newParent].parent = oldParent; + nodes[newParent].userData = UINT64_MAX; + nodes[newParent].aabb = b3AABB_Union( leafAABB, nodes[sibling].aabb ); + nodes[newParent].categoryBits = nodes[leaf].categoryBits | nodes[sibling].categoryBits; + nodes[newParent].height = nodes[sibling].height + 1; + + if ( oldParent != B3_NULL_INDEX ) + { + // The sibling was not the root. + if ( nodes[oldParent].children.child1 == sibling ) + { + nodes[oldParent].children.child1 = newParent; + } + else + { + nodes[oldParent].children.child2 = newParent; + } + + nodes[newParent].children.child1 = sibling; + nodes[newParent].children.child2 = leaf; + nodes[sibling].parent = newParent; + nodes[leaf].parent = newParent; + } + else + { + // The sibling was the root. + nodes[newParent].children.child1 = sibling; + nodes[newParent].children.child2 = leaf; + nodes[sibling].parent = newParent; + nodes[leaf].parent = newParent; + tree->root = newParent; + } + + // Stage 3: walk back up the tree fixing heights and AABBs + int index = nodes[leaf].parent; + while ( index != B3_NULL_INDEX ) + { + int child1 = nodes[index].children.child1; + int child2 = nodes[index].children.child2; + + B3_ASSERT( child1 != B3_NULL_INDEX ); + B3_ASSERT( child2 != B3_NULL_INDEX ); + + nodes[index].aabb = b3AABB_Union( nodes[child1].aabb, nodes[child2].aabb ); + nodes[index].categoryBits = nodes[child1].categoryBits | nodes[child2].categoryBits; + nodes[index].height = 1 + b3MaxUInt16( nodes[child1].height, nodes[child2].height ); + nodes[index].flags |= ( nodes[child1].flags | nodes[child2].flags ) & b3_enlargedNode; + + if ( shouldRotate ) + { + b3RotateNodes( tree, index ); + } + + index = nodes[index].parent; + } +} + +static void b3RemoveLeaf( b3DynamicTree* tree, int leaf ) +{ + if ( leaf == tree->root ) + { + tree->root = B3_NULL_INDEX; + return; + } + + b3TreeNode* 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 != B3_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; + b3FreeNode( tree, parent ); + + // Adjust ancestor bounds. + int index = grandParent; + while ( index != B3_NULL_INDEX ) + { + b3TreeNode* node = nodes + index; + b3TreeNode* child1 = nodes + node->children.child1; + b3TreeNode* 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 = b3AABB_Union( child1->aabb, child2->aabb ); + node->categoryBits = child1->categoryBits | child2->categoryBits; + node->height = 1 + b3MaxUInt16( child1->height, child2->height ); + + index = node->parent; + } + } + else + { + tree->root = sibling; + tree->nodes[sibling].parent = B3_NULL_INDEX; + b3FreeNode( 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 b3DynamicTree_CreateProxy( b3DynamicTree* tree, b3AABB aabb, uint64_t categoryBits, uint64_t userData ) +{ + B3_ASSERT( b3IsValidAABB( aabb ) ); + B3_VALIDATE( -B3_HUGE < aabb.lowerBound.x && aabb.lowerBound.x < B3_HUGE ); + B3_VALIDATE( -B3_HUGE < aabb.lowerBound.y && aabb.lowerBound.y < B3_HUGE ); + B3_VALIDATE( -B3_HUGE < aabb.lowerBound.z && aabb.lowerBound.z < B3_HUGE ); + B3_VALIDATE( -B3_HUGE < aabb.upperBound.x && aabb.upperBound.x < B3_HUGE ); + B3_VALIDATE( -B3_HUGE < aabb.upperBound.y && aabb.upperBound.y < B3_HUGE ); + B3_VALIDATE( -B3_HUGE < aabb.upperBound.z && aabb.upperBound.z < B3_HUGE ); + + int proxyId = b3AllocateNode( tree ); + b3TreeNode* node = tree->nodes + proxyId; + + node->aabb = aabb; + node->userData = userData; + node->categoryBits = categoryBits; + node->height = 0; + node->flags = b3_allocatedNode | b3_leafNode; + + bool shouldRotate = true; + b3InsertLeaf( tree, proxyId, shouldRotate ); + + tree->proxyCount += 1; + + return proxyId; +} + +void b3DynamicTree_DestroyProxy( b3DynamicTree* tree, int proxyId ) +{ + B3_ASSERT( 0 <= proxyId && proxyId < tree->nodeCapacity ); + B3_ASSERT( b3IsLeaf( tree->nodes + proxyId ) ); + + b3RemoveLeaf( tree, proxyId ); + b3FreeNode( tree, proxyId ); + + B3_ASSERT( tree->proxyCount > 0 ); + tree->proxyCount -= 1; +} + +int b3DynamicTree_GetProxyCount( const b3DynamicTree* tree ) +{ + return tree->proxyCount; +} + +void b3DynamicTree_MoveProxy( b3DynamicTree* tree, int proxyId, b3AABB aabb ) +{ + B3_ASSERT( b3IsValidAABB( aabb ) ); + B3_VALIDATE( -B3_HUGE < aabb.lowerBound.x && aabb.lowerBound.x < B3_HUGE ); + B3_VALIDATE( -B3_HUGE < aabb.lowerBound.y && aabb.lowerBound.y < B3_HUGE ); + B3_VALIDATE( -B3_HUGE < aabb.lowerBound.z && aabb.lowerBound.z < B3_HUGE ); + B3_VALIDATE( -B3_HUGE < aabb.upperBound.x && aabb.upperBound.x < B3_HUGE ); + B3_VALIDATE( -B3_HUGE < aabb.upperBound.y && aabb.upperBound.y < B3_HUGE ); + B3_VALIDATE( -B3_HUGE < aabb.upperBound.z && aabb.upperBound.z < B3_HUGE ); + B3_ASSERT( 0 <= proxyId && proxyId < tree->nodeCapacity ); + B3_ASSERT( b3IsLeaf( tree->nodes + proxyId ) ); + + b3RemoveLeaf( tree, proxyId ); + + tree->nodes[proxyId].aabb = aabb; + + bool shouldRotate = false; + b3InsertLeaf( tree, proxyId, shouldRotate ); +} + +void b3DynamicTree_EnlargeProxy( b3DynamicTree* tree, int proxyId, b3AABB aabb ) +{ + b3TreeNode* nodes = tree->nodes; + B3_VALIDATE( b3IsValidAABB( aabb ) ); + B3_VALIDATE( aabb.upperBound.x - aabb.lowerBound.x < B3_HUGE ); + B3_VALIDATE( aabb.upperBound.y - aabb.lowerBound.y < B3_HUGE ); + B3_VALIDATE( aabb.upperBound.z - aabb.lowerBound.z < B3_HUGE ); + B3_ASSERT( 0 <= proxyId && proxyId < tree->nodeCapacity ); + B3_VALIDATE( b3IsLeaf( tree->nodes + proxyId ) ); + + // Caller must ensure this + B3_VALIDATE( b3AABB_Contains( nodes[proxyId].aabb, aabb ) == false ); + + b3TreeNode* node = nodes + proxyId; + node->aabb = aabb; + + int parentIndex = node->parent; + while ( parentIndex != B3_NULL_INDEX ) + { + node = nodes + parentIndex; + bool changed = b3EnlargeAABB( &node->aabb, aabb ); + + // todo not sure why this node is marked as enlarged even if it didn't change + node->flags |= b3_enlargedNode; + + parentIndex = node->parent; + + if ( changed == false ) + { + break; + } + } + + while ( parentIndex != B3_NULL_INDEX ) + { + node = nodes + parentIndex; + if ( node->flags & b3_enlargedNode ) + { + // early out because this ancestor was previously ascended and marked as enlarged + break; + } + + node->flags |= b3_enlargedNode; + parentIndex = node->parent; + } +} + +void b3DynamicTree_SetCategoryBits( b3DynamicTree* tree, int proxyId, uint64_t categoryBits ) +{ + b3TreeNode* nodes = tree->nodes; + + B3_ASSERT( b3IsLeaf( nodes + proxyId ) ); + + nodes[proxyId].categoryBits = categoryBits; + + // Fix up category bits in ancestor internal nodes + int nodeIndex = nodes[proxyId].parent; + while ( nodeIndex != B3_NULL_INDEX ) + { + b3TreeNode* node = nodes + nodeIndex; + int child1 = node->children.child1; + B3_ASSERT( child1 != B3_NULL_INDEX ); + int child2 = node->children.child2; + B3_ASSERT( child2 != B3_NULL_INDEX ); + node->categoryBits = nodes[child1].categoryBits | nodes[child2].categoryBits; + + nodeIndex = node->parent; + } +} + +uint64_t b3DynamicTree_GetCategoryBits( b3DynamicTree* tree, int proxyId ) +{ + B3_ASSERT( 0 <= proxyId && proxyId < tree->nodeCapacity ); + return tree->nodes[proxyId].categoryBits; +} + +int b3DynamicTree_GetHeight( const b3DynamicTree* tree ) +{ + if ( tree->root == B3_NULL_INDEX ) + { + return 0; + } + + return tree->nodes[tree->root].height; +} + +float b3DynamicTree_GetAreaRatio( const b3DynamicTree* tree ) +{ + if ( tree->root == B3_NULL_INDEX ) + { + return 0.0f; + } + + const b3TreeNode* root = tree->nodes + tree->root; + float rootArea = b3Perimeter( root->aabb ); + + float totalArea = 0.0f; + for ( int i = 0; i < tree->nodeCapacity; ++i ) + { + const b3TreeNode* node = tree->nodes + i; + if ( b3IsAllocated( node ) == false || b3IsLeaf( node ) || i == tree->root ) + { + continue; + } + + totalArea += b3Perimeter( node->aabb ); + } + + return totalArea / rootArea; +} + +b3AABB b3DynamicTree_GetRootBounds( const b3DynamicTree* tree ) +{ + if ( tree->root != B3_NULL_INDEX ) + { + return tree->nodes[tree->root].aabb; + } + + b3AABB empty = { b3Vec3_zero, b3Vec3_zero }; + return empty; +} + +#if B3_ENABLE_VALIDATION +// Compute the height of a sub-tree. +static int b3ComputeHeightRecurse( const b3DynamicTree* tree, int nodeId ) +{ + B3_ASSERT( 0 <= nodeId && nodeId < tree->nodeCapacity ); + b3TreeNode* node = tree->nodes + nodeId; + + if ( b3IsLeaf( node ) ) + { + return 0; + } + + int height1 = b3ComputeHeightRecurse( tree, node->children.child1 ); + int height2 = b3ComputeHeightRecurse( tree, node->children.child2 ); + return 1 + b3MaxInt( height1, height2 ); +} + +static int b3ComputeHeight( const b3DynamicTree* tree ) +{ + int height = b3ComputeHeightRecurse( tree, tree->root ); + return height; +} + +static void b3ValidateStructure( const b3DynamicTree* tree, int index ) +{ + if ( index == B3_NULL_INDEX ) + { + return; + } + + if ( index == tree->root ) + { + B3_ASSERT( tree->nodes[index].parent == B3_NULL_INDEX ); + } + + const b3TreeNode* node = tree->nodes + index; + + B3_ASSERT( node->flags == 0 || ( node->flags & b3_allocatedNode ) != 0 ); + + if ( b3IsLeaf( node ) ) + { + B3_ASSERT( node->height == 0 ); + return; + } + + int child1 = node->children.child1; + int child2 = node->children.child2; + + B3_ASSERT( 0 <= child1 && child1 < tree->nodeCapacity ); + B3_ASSERT( 0 <= child2 && child2 < tree->nodeCapacity ); + + B3_ASSERT( tree->nodes[child1].parent == index ); + B3_ASSERT( tree->nodes[child2].parent == index ); + + if ( ( tree->nodes[child1].flags | tree->nodes[child2].flags ) & b3_enlargedNode ) + { + B3_ASSERT( node->flags & b3_enlargedNode ); + } + + b3ValidateStructure( tree, child1 ); + b3ValidateStructure( tree, child2 ); +} + +static void b3ValidateMetrics( const b3DynamicTree* tree, int index ) +{ + if ( index == B3_NULL_INDEX ) + { + return; + } + + const b3TreeNode* node = tree->nodes + index; + + B3_VALIDATE( b3IsSaneAABB( node->aabb ) ); + + if ( b3IsLeaf( node ) ) + { + B3_ASSERT( node->height == 0 ); + return; + } + + int child1 = node->children.child1; + int child2 = node->children.child2; + + B3_ASSERT( 0 <= child1 && child1 < tree->nodeCapacity ); + B3_ASSERT( 0 <= child2 && child2 < tree->nodeCapacity ); + + int height1 = tree->nodes[child1].height; + int height2 = tree->nodes[child2].height; + int height = 1 + b3MaxInt( height1, height2 ); + B3_ASSERT( node->height == height ); + + // b3AABB aabb = b3AABB_Union(tree->nodes[child1].aabb, tree->nodes[child2].aabb); + + B3_ASSERT( b3AABB_Contains( node->aabb, tree->nodes[child1].aabb ) ); + B3_ASSERT( b3AABB_Contains( node->aabb, tree->nodes[child2].aabb ) ); + + // B3_ASSERT(aabb.lowerBound.x == node->aabb.lowerBound.x); + // B3_ASSERT(aabb.lowerBound.y == node->aabb.lowerBound.y); + // B3_ASSERT(aabb.upperBound.x == node->aabb.upperBound.x); + // B3_ASSERT(aabb.upperBound.y == node->aabb.upperBound.y); + + uint64_t categoryBits = tree->nodes[child1].categoryBits | tree->nodes[child2].categoryBits; + B3_ASSERT( node->categoryBits == categoryBits ); + + b3ValidateMetrics( tree, child1 ); + b3ValidateMetrics( tree, child2 ); +} +#endif + +void b3DynamicTree_Validate( const b3DynamicTree* tree ) +{ +#if B3_ENABLE_VALIDATION + if ( tree->root == B3_NULL_INDEX ) + { + return; + } + + b3ValidateStructure( tree, tree->root ); + b3ValidateMetrics( tree, tree->root ); + + int freeCount = 0; + int freeIndex = tree->freeList; + while ( freeIndex != B3_NULL_INDEX ) + { + B3_ASSERT( 0 <= freeIndex && freeIndex < tree->nodeCapacity ); + freeIndex = tree->nodes[freeIndex].next; + ++freeCount; + } + + int height = b3DynamicTree_GetHeight( tree ); + int computedHeight = b3ComputeHeight( tree ); + B3_ASSERT( height == computedHeight ); + + B3_ASSERT( tree->nodeCount + freeCount == tree->nodeCapacity ); +#else + B3_UNUSED( tree ); +#endif +} + +void b3DynamicTree_ValidateNoEnlarged( const b3DynamicTree* tree ) +{ +#if B3_ENABLE_VALIDATION == 1 + int capacity = tree->nodeCapacity; + const b3TreeNode* nodes = tree->nodes; + for ( int i = 0; i < capacity; ++i ) + { + const b3TreeNode* node = nodes + i; + if ( node->flags & b3_allocatedNode ) + { + B3_ASSERT( ( node->flags & b3_enlargedNode ) == 0 ); + } + } +#else + B3_UNUSED( tree ); +#endif +} + +int b3DynamicTree_GetByteCount( const b3DynamicTree* tree ) +{ + size_t size = sizeof( b3DynamicTree ) + sizeof( b3TreeNode ) * tree->nodeCapacity + + tree->rebuildCapacity * ( sizeof( int ) + sizeof( b3AABB ) + sizeof( b3Vec3 ) + sizeof( int ) ); + + return (int)size; +} + +b3TreeStats b3DynamicTree_Query( const b3DynamicTree* tree, b3AABB aabb, uint64_t maskBits, bool requireAllBits, + b3TreeQueryCallbackFcn* callback, void* context ) +{ + b3TreeStats result = { 0 }; + + if ( tree->nodeCount == 0 ) + { + return result; + } + + int stack[B3_TREE_STACK_SIZE]; + int stackCount = 0; + stack[stackCount++] = tree->root; + + while ( stackCount > 0 ) + { + int nodeId = stack[--stackCount]; + if ( nodeId == B3_NULL_INDEX ) + { + // todo huh? + B3_ASSERT( false ); + continue; + } + + const b3TreeNode* node = tree->nodes + nodeId; + result.nodeVisits += 1; + + // Assuming branch prediction deals with requireAllBits well + uint64_t bitMatch = requireAllBits ? ( node->categoryBits & maskBits ) == maskBits : ( node->categoryBits & maskBits ); + + if ( bitMatch && b3AABB_Overlaps( node->aabb, aabb ) ) + { + if ( b3IsLeaf( node ) ) + { + // callback to user code with proxy id + bool proceed = callback( nodeId, node->userData, context ); + result.leafVisits += 1; + + if ( proceed == false ) + { + return result; + } + } + else + { + B3_ASSERT( stackCount < B3_TREE_STACK_SIZE - 1 ); + if ( stackCount < B3_TREE_STACK_SIZE - 1 ) + { + stack[stackCount++] = node->children.child1; + stack[stackCount++] = node->children.child2; + } + } + } + } + + return result; +} + +B3_FORCE_INLINE float b3DistanceToNodeSqr( b3Vec3 point, const b3TreeNode* node ) +{ + b3Vec3 r = b3Sub( point, b3Clamp( point, node->aabb.lowerBound, node->aabb.upperBound ) ); + return b3Dot( r, r ); +} + +struct b3QueryClosestItem +{ + int nodeIndex; + float distanceToNodeSqr; +}; + +b3TreeStats b3DynamicTree_QueryClosest( const b3DynamicTree* tree, b3Vec3 point, uint64_t maskBits, bool requireAllBits, + b3TreeQueryClosestCallbackFcn* callback, void* context, float* minDistanceSqr ) +{ + b3TreeStats result = { 0 }; + + if ( tree->nodeCount == 0 ) + { + return result; + } + + float minSqr = *minDistanceSqr; + struct b3QueryClosestItem stack[B3_TREE_STACK_SIZE]; + int stackCount = 0; + + float rootDistanceSqr = b3DistanceToNodeSqr( point, tree->nodes + tree->root ); + stack[stackCount++] = (struct b3QueryClosestItem){ + .nodeIndex = tree->root, + .distanceToNodeSqr = rootDistanceSqr, + }; + + while ( stackCount > 0 ) + { + struct b3QueryClosestItem item = stack[--stackCount]; + const b3TreeNode* node = tree->nodes + item.nodeIndex; + result.nodeVisits += 1; + + uint64_t bitMatch = requireAllBits ? ( node->categoryBits & maskBits ) == maskBits : ( node->categoryBits & maskBits ); + + if ( bitMatch ) + { + if ( item.distanceToNodeSqr < minSqr ) + { + if ( b3IsLeaf( node ) ) + { + // callback to user code with minimum distance squared so far and proxy id + float dd = callback( minSqr, item.nodeIndex, node->userData, context ); + + if ( dd < minSqr ) + { + minSqr = dd; + } + + result.leafVisits += 1; + } + else + { + B3_ASSERT( stackCount < B3_TREE_STACK_SIZE - 1 ); + if ( stackCount < B3_TREE_STACK_SIZE - 1 ) + { + int child1 = node->children.child1; + int child2 = node->children.child2; + + // Store the distance to node in the stack instead of recomputing after pop + struct b3QueryClosestItem item1 = { + .nodeIndex = child1, + .distanceToNodeSqr = b3DistanceToNodeSqr( point, tree->nodes + child1 ), + }; + + struct b3QueryClosestItem item2 = { + .nodeIndex = child2, + .distanceToNodeSqr = b3DistanceToNodeSqr( point, tree->nodes + child2 ), + }; + + // Ensure we iterate the closest child first as we pop off the stack + if ( item2.distanceToNodeSqr < item1.distanceToNodeSqr ) + { + stack[stackCount++] = item1; + stack[stackCount++] = item2; + } + else + { + stack[stackCount++] = item2; + stack[stackCount++] = item1; + } + } + } + } + } + } + + *minDistanceSqr = minSqr; + + return result; +} + +b3TreeStats b3DynamicTree_RayCast( const b3DynamicTree* tree, const b3RayCastInput* input, uint64_t maskBits, bool requireAllBits, + b3TreeRayCastCallbackFcn* callback, void* context ) +{ + b3TreeStats result = { 0 }; + + if ( tree->nodeCount == 0 ) + { + return result; + } + + b3Vec3 p1 = input->origin; + b3Vec3 d = input->translation; + + b3V32 pv1 = b3LoadV( &p1.x ); + b3V32 dv = b3LoadV( &d.x ); + + float maxFraction = input->maxFraction; + + b3Vec3 p2 = b3MulAdd( p1, maxFraction, d ); + + // Build a bounding box for the segment. + b3AABB segmentAABB = { b3Min( p1, p2 ), b3Max( p1, p2 ) }; + + int stack[B3_TREE_STACK_SIZE]; + int stackCount = 0; + stack[stackCount++] = tree->root; + + const b3TreeNode* nodes = tree->nodes; + + b3RayCastInput subInput = *input; + + while ( stackCount > 0 ) + { + int nodeId = stack[--stackCount]; + if ( nodeId == B3_NULL_INDEX ) + { + // todo is this possible? + B3_ASSERT( false ); + continue; + } + + const b3TreeNode* node = nodes + nodeId; + result.nodeVisits += 1; + + b3AABB nodeAABB = node->aabb; + + // todo look at disassembly + uint64_t bitMatch = requireAllBits ? ( node->categoryBits & maskBits ) == maskBits : ( node->categoryBits & maskBits ); + + if ( bitMatch == 0 || b3AABB_Overlaps( nodeAABB, segmentAABB ) == false ) + { + continue; + } + + b3V32 lower = b3LoadV( &nodeAABB.lowerBound.x ); + b3V32 upper = b3LoadV( &nodeAABB.upperBound.x ); + + bool edgeOverlap = b3TestBoundsRayOverlap( lower, upper, pv1, dv ); + if ( edgeOverlap == false ) + { + continue; + } + + if ( b3IsLeaf( 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 = b3MulAdd( p1, maxFraction, d ); + segmentAABB.lowerBound = b3Min( p1, p2 ); + segmentAABB.upperBound = b3Max( p1, p2 ); + } + } + else + { + B3_ASSERT( stackCount < B3_TREE_STACK_SIZE - 1 ); + if ( stackCount < B3_TREE_STACK_SIZE - 1 ) + { + b3Vec3 c1 = b3AABB_Center( nodes[node->children.child1].aabb ); + b3Vec3 c2 = b3AABB_Center( nodes[node->children.child2].aabb ); + if ( b3DistanceSquared( c1, p1 ) < b3DistanceSquared( c2, p1 ) ) + { + stack[stackCount++] = node->children.child2; + stack[stackCount++] = node->children.child1; + } + else + { + stack[stackCount++] = node->children.child1; + stack[stackCount++] = node->children.child2; + } + } + } + } + + return result; +} + +b3TreeStats b3DynamicTree_ShapeCast( const b3DynamicTree* tree, const b3ShapeCastInput* input, uint64_t maskBits, + bool requireAllBits, b3TreeShapeCastCallbackFcn* callback, void* context ) +{ + b3TreeStats stats = { 0 }; + + if ( tree->nodeCount == 0 || input->proxy.count == 0 ) + { + return stats; + } + + b3AABB originAABB = { input->proxy.points[0], input->proxy.points[0] }; + for ( int i = 1; i < input->proxy.count; ++i ) + { + originAABB.lowerBound = b3Min( originAABB.lowerBound, input->proxy.points[i] ); + originAABB.upperBound = b3Max( originAABB.upperBound, input->proxy.points[i] ); + } + + b3Vec3 radius = { input->proxy.radius, input->proxy.radius, input->proxy.radius }; + + originAABB.lowerBound = b3Sub( originAABB.lowerBound, radius ); + originAABB.upperBound = b3Add( originAABB.upperBound, radius ); + + b3Vec3 p1 = b3AABB_Center( originAABB ); + b3Vec3 extension = b3AABB_Extents( originAABB ); + + // v is perpendicular to the segment. + b3Vec3 d = input->translation; + + b3V32 pv1 = b3LoadV( &p1.x ); + b3V32 dv = b3LoadV( &d.x ); + b3V32 ev = b3LoadV( &extension.x ); + + float maxFraction = input->maxFraction; + + // Build total box for the shape cast + b3Vec3 t = b3MulSV( maxFraction, input->translation ); + b3AABB totalAABB = { + b3Min( originAABB.lowerBound, b3Add( originAABB.lowerBound, t ) ), + b3Max( originAABB.upperBound, b3Add( originAABB.upperBound, t ) ), + }; + + b3ShapeCastInput subInput = *input; + const b3TreeNode* nodes = tree->nodes; + + int stack[B3_TREE_STACK_SIZE]; + int stackCount = 0; + stack[stackCount++] = tree->root; + + while ( stackCount > 0 ) + { + int nodeId = stack[--stackCount]; + if ( nodeId == B3_NULL_INDEX ) + { + // todo is this possible? + B3_ASSERT( false ); + continue; + } + + const b3TreeNode* node = nodes + nodeId; + stats.nodeVisits += 1; + + // todo look at disassembly + uint64_t bitMatch = requireAllBits ? ( node->categoryBits & maskBits ) == maskBits : ( node->categoryBits & maskBits ); + + if ( bitMatch == 0 || b3AABB_Overlaps( node->aabb, totalAABB ) == false ) + { + continue; + } + + // radius extension is added to the node in this case + b3V32 lower = b3SubV( b3LoadV( &node->aabb.lowerBound.x ), ev ); + b3V32 upper = b3AddV( b3LoadV( &node->aabb.upperBound.x ), ev ); + bool edgeOverlap = b3TestBoundsRayOverlap( lower, upper, pv1, dv ); + if ( edgeOverlap == false ) + { + continue; + } + + if ( b3IsLeaf( 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 = b3MulSV( maxFraction, input->translation ); + totalAABB.lowerBound = b3Min( originAABB.lowerBound, b3Add( originAABB.lowerBound, t ) ); + totalAABB.upperBound = b3Max( originAABB.upperBound, b3Add( originAABB.upperBound, t ) ); + } + } + else + { + B3_ASSERT( stackCount < B3_TREE_STACK_SIZE - 1 ); + if ( stackCount < B3_TREE_STACK_SIZE - 1 ) + { + b3Vec3 c1 = b3AABB_Center( nodes[node->children.child1].aabb ); + b3Vec3 c2 = b3AABB_Center( nodes[node->children.child2].aabb ); + if ( b3DistanceSquared( c1, p1 ) < b3DistanceSquared( c2, p1 ) ) + { + stack[stackCount++] = node->children.child2; + stack[stackCount++] = node->children.child1; + } + else + { + stack[stackCount++] = node->children.child1; + stack[stackCount++] = node->children.child2; + } + } + } + } + + return stats; +} + +// Median split == 0, Surface area heuristic == 1 +#define B3_TREE_HEURISTIC 0 + +#if B3_TREE_HEURISTIC == 0 + +// Median split heuristic +static int b3PartitionMid( int* indices, b3Vec3* centers, int count ) +{ + // Handle trivial case + if ( count <= 2 ) + { + return count / 2; + } + + b3Vec3 lowerBound = centers[0]; + b3Vec3 upperBound = centers[0]; + + for ( int i = 1; i < count; ++i ) + { + lowerBound = b3Min( lowerBound, centers[i] ); + upperBound = b3Max( upperBound, centers[i] ); + } + + b3Vec3 d = b3Sub( upperBound, lowerBound ); + b3Vec3 c = b3MulSV( 0.5f, b3Add( lowerBound, upperBound ) ); + + // 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 && d.x >= d.z ) + { + 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 + { + b3Vec3 temp = centers[i1]; + centers[i1] = centers[i2 - 1]; + centers[i2 - 1] = temp; + } + + i1 += 1; + i2 -= 1; + } + } + } + else if ( d.y >= d.z ) + { + 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 + { + b3Vec3 temp = centers[i1]; + centers[i1] = centers[i2 - 1]; + centers[i2 - 1] = temp; + } + + i1 += 1; + i2 -= 1; + } + } + } + else + { + float pivot = c.z; + + while ( i1 < i2 ) + { + while ( i1 < i2 && centers[i1].z < pivot ) + { + i1 += 1; + }; + + while ( i1 < i2 && centers[i2 - 1].z >= pivot ) + { + i2 -= 1; + }; + + if ( i1 < i2 ) + { + // Swap indices + { + int temp = indices[i1]; + indices[i1] = indices[i2 - 1]; + indices[i2 - 1] = temp; + } + + // Swap centers + { + b3Vec3 temp = centers[i1]; + centers[i1] = centers[i2 - 1]; + centers[i2 - 1] = temp; + } + + i1 += 1; + i2 -= 1; + } + } + } + B3_ASSERT( i1 == i2 ); + + if ( i1 > 0 && i1 < count ) + { + return i1; + } + + return count / 2; +} + +#else + +#define B3_BIN_COUNT 8 + +typedef struct b3TreeBin +{ + b3AABB aabb; + int count; +} b3TreeBin; + +typedef struct b3TreePlane +{ + b3AABB leftAABB; + b3AABB rightAABB; + int leftCount; + int rightCount; +} b3TreePlane; + +// "On Fast Construction of SAH-based Bounding Volume Hierarchies" by Ingo Wald +// Returns the left child count +static int b3PartitionSAH( int* indices, int* binIndices, b3AABB* boxes, int count ) +{ + B3_ASSERT( count > 0 ); + + b3TreeBin bins[B3_BIN_COUNT]; + b3TreePlane planes[B3_BIN_COUNT - 1]; + + b3Vec3 center = b3AABB_Center( boxes[0] ); + b3AABB centroidAABB; + centroidAABB.lowerBound = center; + centroidAABB.upperBound = center; + + for ( int i = 1; i < count; ++i ) + { + center = b3AABB_Center( boxes[i] ); + centroidAABB.lowerBound = b3Min( centroidAABB.lowerBound, center ); + centroidAABB.upperBound = b3Max( centroidAABB.upperBound, center ); + } + + b3Vec3 d = b3Sub( 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 < B3_BIN_COUNT; ++i ) + { + bins[i].aabb.lowerBound = (b3Vec3){ FLT_MAX, FLT_MAX }; + bins[i].aabb.upperBound = (b3Vec3){ -FLT_MAX, -FLT_MAX }; + bins[i].count = 0; + } + + // Assign boxes to bins and compute bin boxes + // TODO_ERIN optimize + float binCount = B3_BIN_COUNT; + float lowerBoundArray[2] = { centroidAABB.lowerBound.x, centroidAABB.lowerBound.y }; + float minC = lowerBoundArray[axisIndex]; + for ( int i = 0; i < count; ++i ) + { + b3Vec3 c = b3AABB_Center( boxes[i] ); + float cArray[2] = { c.x, c.y }; + int binIndex = (int)( binCount * ( cArray[axisIndex] - minC ) * invD ); + binIndex = b3ClampInt( binIndex, 0, B3_BIN_COUNT - 1 ); + binIndices[i] = binIndex; + bins[binIndex].count += 1; + bins[binIndex].aabb = b3AABB_Union( bins[binIndex].aabb, boxes[i] ); + } + + int planeCount = B3_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 = b3AABB_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 = b3AABB_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 = b3Perimeter( planes[i].leftAABB ); + float rightArea = b3Perimeter( 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 + { + b3AABB temp = boxes[i1]; + boxes[i1] = boxes[i2 - 1]; + boxes[i2 - 1] = temp; + } + + i1 += 1; + i2 -= 1; + } + } + B3_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 b3RebuildItem +{ + int nodeIndex; + int childCount; + + // Leaf indices + int startIndex; + int splitIndex; + int endIndex; +}; + +// Returns root node index +static int b3BuildTree( b3DynamicTree* tree, int leafCount ) +{ + b3TreeNode* nodes = tree->nodes; + int* leafIndices = tree->leafIndices; + + if ( leafCount == 1 ) + { + nodes[leafIndices[0]].parent = B3_NULL_INDEX; + return leafIndices[0]; + } + +#if B3_TREE_HEURISTIC == 0 + b3Vec3* leafCenters = tree->leafCenters; +#else + b3AABB* leafBoxes = tree->leafBoxes; + int* binIndices = tree->binIndices; +#endif + + // todo large stack item + struct b3RebuildItem stack[B3_TREE_STACK_SIZE]; + int top = 0; + + stack[0].nodeIndex = b3AllocateNode( tree ); + stack[0].childCount = -1; + stack[0].startIndex = 0; + stack[0].endIndex = leafCount; +#if B3_TREE_HEURISTIC == 0 + stack[0].splitIndex = b3PartitionMid( leafIndices, leafCenters, leafCount ); +#else + stack[0].splitIndex = b3PartitionSAH( leafIndices, binIndices, leafBoxes, leafCount ); +#endif + + while ( true ) + { + struct b3RebuildItem* item = stack + top; + + item->childCount += 1; + + if ( item->childCount == 2 ) + { + // This internal node has both children established + + if ( top == 0 ) + { + // all done + break; + } + + struct b3RebuildItem* parentItem = stack + ( top - 1 ); + b3TreeNode* parentNode = nodes + parentItem->nodeIndex; + + if ( parentItem->childCount == 0 ) + { + B3_ASSERT( parentNode->children.child1 == B3_NULL_INDEX ); + parentNode->children.child1 = item->nodeIndex; + } + else + { + B3_ASSERT( parentItem->childCount == 1 ); + B3_ASSERT( parentNode->children.child2 == B3_NULL_INDEX ); + parentNode->children.child2 = item->nodeIndex; + } + + b3TreeNode* node = nodes + item->nodeIndex; + + B3_ASSERT( node->parent == B3_NULL_INDEX ); + node->parent = parentItem->nodeIndex; + + B3_ASSERT( node->children.child1 != B3_NULL_INDEX ); + B3_ASSERT( node->children.child2 != B3_NULL_INDEX ); + b3TreeNode* child1 = nodes + node->children.child1; + b3TreeNode* child2 = nodes + node->children.child2; + + node->aabb = b3AABB_Union( child1->aabb, child2->aabb ); + node->height = 1 + b3MaxUInt16( 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 + { + B3_ASSERT( item->childCount == 1 ); + startIndex = item->splitIndex; + endIndex = item->endIndex; + } + + int count = endIndex - startIndex; + + if ( count == 1 ) + { + int childIndex = leafIndices[startIndex]; + b3TreeNode* node = nodes + item->nodeIndex; + + if ( item->childCount == 0 ) + { + B3_ASSERT( node->children.child1 == B3_NULL_INDEX ); + node->children.child1 = childIndex; + } + else + { + B3_ASSERT( item->childCount == 1 ); + B3_ASSERT( node->children.child2 == B3_NULL_INDEX ); + node->children.child2 = childIndex; + } + + b3TreeNode* childNode = nodes + childIndex; + B3_ASSERT( childNode->parent == B3_NULL_INDEX ); + childNode->parent = item->nodeIndex; + } + else + { + B3_ASSERT( count > 0 ); + B3_ASSERT( top < B3_TREE_STACK_SIZE ); + + top += 1; + struct b3RebuildItem* newItem = stack + top; + newItem->nodeIndex = b3AllocateNode( tree ); + newItem->childCount = -1; + newItem->startIndex = startIndex; + newItem->endIndex = endIndex; +#if B3_TREE_HEURISTIC == 0 + newItem->splitIndex = b3PartitionMid( leafIndices + startIndex, leafCenters + startIndex, count ); +#else + newItem->splitIndex = + b3PartitionSAH( leafIndices + startIndex, binIndices + startIndex, leafBoxes + startIndex, count ); +#endif + newItem->splitIndex += startIndex; + } + } + } + + b3TreeNode* rootNode = nodes + stack[0].nodeIndex; + B3_ASSERT( rootNode->parent == B3_NULL_INDEX ); + B3_ASSERT( rootNode->children.child1 != B3_NULL_INDEX ); + B3_ASSERT( rootNode->children.child2 != B3_NULL_INDEX ); + + b3TreeNode* child1 = nodes + rootNode->children.child1; + b3TreeNode* child2 = nodes + rootNode->children.child2; + + rootNode->aabb = b3AABB_Union( child1->aabb, child2->aabb ); + rootNode->height = 1 + b3MaxUInt16( 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 b3DynamicTree_Rebuild( b3DynamicTree* 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; + + b3Free( tree->leafIndices, tree->rebuildCapacity * sizeof( int ) ); + tree->leafIndices = (int*)b3Alloc( newCapacity * sizeof( int ) ); + +#if B3_TREE_HEURISTIC == 0 + b3Free( tree->leafCenters, tree->rebuildCapacity * sizeof( b3Vec3 ) ); + tree->leafCenters = (b3Vec3*)b3Alloc( newCapacity * sizeof( b3Vec3 ) ); +#else + b3Free( tree->leafBoxes, tree->rebuildCapacity * sizeof( b3AABB ) ); + tree->leafBoxes = (b3AABB*)b3Alloc( newCapacity * sizeof( b3AABB ) ); + b3Free( tree->binIndices, tree->rebuildCapacity * sizeof( int ) ); + tree->binIndices = (int*)b3Alloc( newCapacity * sizeof( int ) ); +#endif + tree->rebuildCapacity = newCapacity; + } + + int leafCount = 0; + int stack[B3_TREE_STACK_SIZE]; + int stackCount = 0; + + int nodeIndex = tree->root; + b3TreeNode* nodes = tree->nodes; + b3TreeNode* 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 B3_TREE_HEURISTIC == 0 + b3Vec3* leafCenters = tree->leafCenters; +#else + b3AABB* 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 b3_aabbMargin + while ( true ) + { + if ( b3IsLeaf( node ) == true || ( ( node->flags & b3_enlargedNode ) == 0 && fullBuild == false ) ) + { + leafIndices[leafCount] = nodeIndex; +#if B3_TREE_HEURISTIC == 0 + leafCenters[leafCount] = b3AABB_Center( node->aabb ); +#else + leafBoxes[leafCount] = node->aabb; +#endif + leafCount += 1; + + // Detach + node->parent = B3_NULL_INDEX; + } + else + { + int doomedNodeIndex = nodeIndex; + + // Handle children + nodeIndex = node->children.child1; + + B3_ASSERT( stackCount < B3_TREE_STACK_SIZE ); + if ( stackCount < B3_TREE_STACK_SIZE ) + { + stack[stackCount++] = node->children.child2; + } + + node = nodes + nodeIndex; + + // Remove doomed node + b3FreeNode( tree, doomedNodeIndex ); + + continue; + } + + if ( stackCount == 0 ) + { + break; + } + + nodeIndex = stack[--stackCount]; + node = nodes + nodeIndex; + } + +#if B3_ENABLE_VALIDATION == 1 + int capacity = tree->nodeCapacity; + for ( int i = 0; i < capacity; ++i ) + { + if ( nodes[i].flags & b3_allocatedNode ) + { + B3_ASSERT( ( nodes[i].flags & b3_enlargedNode ) == 0 ); + } + } +#endif + + B3_ASSERT( leafCount <= proxyCount ); + + tree->root = b3BuildTree( tree, leafCount ); + + b3DynamicTree_Validate( tree ); + + return leafCount; +} + +static FILE* b3OpenTreeFile( const char* fileName, const char* mode ) +{ + FILE* file = NULL; + +#if defined( _MSC_VER ) + errno_t e = fopen_s( &file, fileName, mode ); + if ( e != 0 ) + { + return NULL; + } +#else + file = fopen( fileName, mode ); + if ( file == NULL ) + { + return NULL; + } +#endif + + return file; +} + +void b3DynamicTree_Save( const b3DynamicTree* tree, const char* fileName ) +{ + FILE* file = b3OpenTreeFile( fileName, "wb" ); + if ( file == NULL ) + { + return; + } + + // Copy to allow setting some fields to zero + b3DynamicTree temp = *tree; + + // Zero pointers and temp data + temp.nodes = NULL; + temp.leafIndices = NULL; + temp.leafBoxes = NULL; + temp.leafCenters = NULL; + temp.binIndices = NULL; + temp.rebuildCapacity = 0; + + // Write tree struct + fwrite( &temp, sizeof( b3DynamicTree ), 1, file ); + + // Write the node array, this includes the free list + if ( tree->nodeCapacity > 0 && tree->nodes != NULL ) + { + fwrite( tree->nodes, sizeof( b3TreeNode ), tree->nodeCapacity, file ); + } + + fclose( file ); +} + +b3DynamicTree b3DynamicTree_Load( const char* fileName, float scale ) +{ + b3DynamicTree tree = { 0 }; + + FILE* file = b3OpenTreeFile( fileName, "rb" ); + if ( file == NULL ) + { + return tree; + } + + int readCount = (int)fread( &tree, sizeof( b3DynamicTree ), 1, file ); + if ( readCount != 1 ) + { + fclose( file ); + return tree; + } + + if ( tree.version != B3_DYNAMIC_TREE_VERSION ) + { + fclose( file ); + memset( &tree, 0, sizeof( b3DynamicTree ) ); + return tree; + } + + if ( tree.nodeCapacity > 0 ) + { + tree.nodes = (b3TreeNode*)b3Alloc( tree.nodeCapacity * sizeof( b3TreeNode ) ); + readCount = (int)fread( tree.nodes, sizeof( b3TreeNode ), tree.nodeCapacity, file ); + if ( readCount != tree.nodeCapacity ) + { + b3Free( tree.nodes, tree.nodeCapacity * sizeof( b3TreeNode ) ); + fclose( file ); + memset( &tree, 0, sizeof( b3DynamicTree ) ); + return tree; + } + + for ( int i = 0; i < tree.nodeCapacity; ++i ) + { + b3TreeNode* node = tree.nodes + i; + node->aabb.lowerBound = b3MulSV( scale, node->aabb.lowerBound ); + node->aabb.upperBound = b3MulSV( scale, node->aabb.upperBound ); + } + } + else + { + tree.nodes = NULL; + } + + // Zero temp data fields + tree.leafIndices = NULL; + tree.leafBoxes = NULL; + tree.leafCenters = NULL; + tree.binIndices = NULL; + tree.rebuildCapacity = 0; + + fclose( file ); + + return tree; +} diff --git a/src/height_field.c b/src/height_field.c new file mode 100644 index 0000000..93d2462 --- /dev/null +++ b/src/height_field.c @@ -0,0 +1,1601 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "algorithm.h" +#include "body.h" +#include "core.h" +#include "shape.h" +#include "simd.h" + +#include "box3d/collision.h" +#include "box3d/constants.h" +#include "box3d/math_functions.h" + +#include +#include +#include + +/* + Convention + + index = row * columnCount + column + height = minHeight + heightScale * compressedHeights[index]; + + column = index % columnCount; + row = index / columnCount; + + x-axis : columns + z-axis : rows + + 00 --- 01 --- 02 --- 03 X + | 0 | 1 | 2 | + 04 --- 05 --- 06 --- 07 + | 3 | 4 | 5 | + 08 --- 09 --- 10 --- 11 + | 6 | 7 | 8 | + 12 --- 13 --- 14 --- 15 + Z + + The quads exist before the column and row ends: row < rowCount - 1 and column < columnCount - 1 + quadIndex = row * (columnCount - 1) + column + + Quad origin index from quad index (needs row): + index = quadIndex + row * columnCount + + Triangle index is related to the quad index + triangleIndex = 2 * quadIndex + (0/1) + quadIndex = triangleIndex / 2 + + Row and column from quad index: + row = quadIndex / (columnCount - 1) + column = quadIndex - row * (columnCount - 1) + + The triangle diagonal is fixed. + + triangle0 = {00, 04, 01} -> {11, 21, 12} + triangle1 = {04, 05, 01} -> {22, 12, 21} + + 11 12 + 00 ---- 01 + | / | + | 0 / 1 | 1 + | / | + 04 ---- 05 + 21 22 + + For adjacency we have + + NA + 00 ---- 01 ---- 02 + | / | / | + NA | 0 / 1 | 2 / 3 | + | / | / | + 04 ---- 05 ---- 06 + | / | / | + NA | 6 / 7 | 8 / 9 | + | / | / | + 08 ---- 09 ---- 10 + + 0: NA, NA, 1 + 1: 0, 6, 2 + + Triangle layouts + + 11 3 12 + 1 ---- 3 + | / + 1 | 0 / 2 + | / + 2 + 21 + + 12 + 2 + / | + 2 / 1 | 1 + / | + 3 ---- 1 + 21 3 22 + */ + +b3HeightField* b3CreateHeightField( const b3HeightFieldDef* data ) +{ + b3HeightField* hf = (b3HeightField*)b3Alloc( sizeof( b3HeightField ) ); + + int columnCount = data->countX; + int rowCount = data->countZ; + + hf->scale = data->scale; + hf->columnCount = columnCount; + hf->rowCount = rowCount; + + int heightCount = columnCount * rowCount; + B3_ASSERT( heightCount >= 4 ); + + hf->compressedHeights = (uint16_t*)b3Alloc( heightCount * sizeof( uint16_t ) ); + + const float* heights = data->heights; + + B3_ASSERT( data->globalMinimumHeight <= data->globalMaximumHeight ); + hf->minHeight = data->globalMinimumHeight; + hf->maxHeight = data->globalMaximumHeight; + + float height = b3MaxFloat( hf->maxHeight - hf->minHeight, B3_LINEAR_SLOP ); + hf->heightScale = height / UINT16_MAX; + + float lowerHeightBound = hf->maxHeight; + float upperHeightBound = hf->minHeight; + + float invHeightScale = 1.0f / hf->heightScale; + for ( int i = 0; i < heightCount; ++i ) + { + float clampedHeight = b3ClampFloat( heights[i], hf->minHeight, hf->maxHeight ); + float scaledHeight = ( clampedHeight - hf->minHeight ) * invHeightScale; + hf->compressedHeights[i] = (uint16_t)( b3MinFloat( scaledHeight, (float)UINT16_MAX ) ); + + lowerHeightBound = b3MinFloat( lowerHeightBound, clampedHeight ); + upperHeightBound = b3MaxFloat( upperHeightBound, clampedHeight ); + } + + // Use decompressed heights for accurate convexity metrics. + float* decompressedHeights = (float*)b3Alloc( heightCount * sizeof( float ) ); + for ( int i = 0; i < heightCount; ++i ) + { + decompressedHeights[i] = hf->minHeight + hf->heightScale * hf->compressedHeights[i]; + } + heights = decompressedHeights; + + int cellCount = ( hf->columnCount - 1 ) * ( hf->rowCount - 1 ); + + hf->materialIndices = (uint8_t*)b3Alloc( cellCount * sizeof( uint8_t ) ); + + if ( data->materialIndices != NULL ) + { + for ( int i = 0; i < cellCount; ++i ) + { + hf->materialIndices[i] = data->materialIndices[i]; + } + } + else + { + for ( int i = 0; i < cellCount; ++i ) + { + hf->materialIndices[i] = 0; + } + } + + hf->aabb.lowerBound = (b3Vec3){ 0.0f, hf->scale.y * lowerHeightBound, 0.0f }; + hf->aabb.upperBound = + (b3Vec3){ hf->scale.x * ( hf->columnCount - 1 ), hf->scale.y * upperHeightBound, hf->scale.z * ( hf->rowCount - 1 ) }; + + hf->version = B3_HEIGHT_FIELD_VERSION; + + hf->clockwise = data->clockwiseWinding; + + int triangleCount = 2 * cellCount; + hf->flags = (uint8_t*)b3Alloc( triangleCount * sizeof( uint8_t ) ); + + memset( hf->flags, 0, triangleCount * sizeof( uint8_t ) ); + + float cos5Deg = 0.9962f; + b3Vec3 scale = hf->scale; + + int triangleIndex = 0; + for ( int row = 0; row < rowCount - 1; ++row ) + { + for ( int column = 0; column < columnCount - 1; ++column ) + { + // todo compute convexity flags + // This requires a couple things + // - determine all 3 adjacent triangles for each triangle + // - consider clockwise winding + // - consider borders where there is no adjacent triangle + + int triangleIndex1 = triangleIndex; + int triangleIndex2 = triangleIndex + 1; + triangleIndex += 2; + + int cellIndex = row * ( columnCount - 1 ) + column; + + if ( hf->materialIndices[cellIndex] == B3_HEIGHT_FIELD_HOLE ) + { + continue; + } + + int flags1 = 0; + int flags2 = 0; + + b3Plane plane1, plane2; + b3Vec3 center1, center2; + + int index11 = row * columnCount + column; + int index12 = index11 + 1; + int index21 = ( row + 1 ) * columnCount + column; + int index22 = index21 + 1; + + { + float height11 = heights[index11]; + float height12 = heights[index12]; + float height21 = heights[index21]; + float height22 = heights[index22]; + + float x1 = (float)( column ); + float x2 = (float)( column + 1 ); + float z1 = (float)( row ); + float z2 = (float)( row + 1 ); + + // triangle 0 : 11, 21, 12 + b3Vec3 vs0[3]; + vs0[0] = b3Mul( scale, (b3Vec3){ x1, height11, z1 } ); + vs0[1] = b3Mul( scale, (b3Vec3){ x1, height21, z2 } ); + vs0[2] = b3Mul( scale, (b3Vec3){ x2, height12, z1 } ); + plane1 = b3MakePlaneFromPoints( vs0[0], vs0[1], vs0[2] ); + + center1 = b3MulSV( 1.0f / 3.0f, b3Add( b3Add( vs0[0], vs0[1] ), vs0[2] ) ); + + // triangle 1 : 22, 12, 21 + b3Vec3 vs1[3]; + vs1[0] = b3Mul( scale, (b3Vec3){ x2, height22, z2 } ); + vs1[1] = b3Mul( scale, (b3Vec3){ x2, height12, z1 } ); + vs1[2] = b3Mul( scale, (b3Vec3){ x1, height21, z2 } ); + plane2 = b3MakePlaneFromPoints( vs1[0], vs1[1], vs1[2] ); + + center2 = b3MulSV( 1.0f / 3.0f, b3Add( b3Add( vs1[0], vs1[1] ), vs1[2] ) ); + + float separation = b3PlaneSeparation( plane1, vs1[0] ); + float cosAngle = b3Dot( plane1.normal, plane2.normal ); + if ( separation > 0.0f || cosAngle > cos5Deg ) + { + flags1 |= b3_concaveEdge2; + flags2 |= b3_concaveEdge2; + } + } + + B3_UNUSED( center1 ); + B3_UNUSED( center2 ); + + // top + int topCellIndex = ( row - 1 ) * ( columnCount - 1 ) + column; + if ( row > 0 && hf->materialIndices[topCellIndex] != B3_HEIGHT_FIELD_HOLE ) + { + B3_ASSERT( 0 <= topCellIndex && topCellIndex < cellCount ); + + int r = row - 1; + int c = column; + + int i11 = r * columnCount + c; + int i12 = i11 + 1; + int i21 = ( r + 1 ) * columnCount + c; + int i22 = i21 + 1; + + B3_ASSERT( i21 == index11 ); + B3_ASSERT( i22 == index12 ); + + // float h11 = heights[i11]; + float h12 = heights[i12]; + float h21 = heights[i21]; + float h22 = heights[i22]; + + float x1 = (float)( c ); + float x2 = (float)( c + 1 ); + float z1 = (float)( r ); + float z2 = (float)( r + 1 ); + + // triangle 1 + b3Vec3 vs[3]; + vs[0] = b3Mul( scale, (b3Vec3){ x2, h22, z2 } ); + vs[1] = b3Mul( scale, (b3Vec3){ x2, h12, z1 } ); + vs[2] = b3Mul( scale, (b3Vec3){ x1, h21, z2 } ); + + b3Vec3 n = b3Normalize( b3Cross( b3Sub( vs[1], vs[0] ), b3Sub( vs[2], vs[0] ) ) ); + + float separation = b3PlaneSeparation( plane1, vs[1] ); + float cosAngle = b3Dot( plane1.normal, n ); + if ( separation > 0.0f || cosAngle > cos5Deg ) + { + flags1 |= b3_concaveEdge3; + } + } + + int bottomCellIndex = ( row + 1 ) * ( columnCount - 1 ) + column; + if ( row + 1 < rowCount - 1 && hf->materialIndices[bottomCellIndex] != B3_HEIGHT_FIELD_HOLE ) + { + B3_ASSERT( 0 <= bottomCellIndex && bottomCellIndex < cellCount ); + + int r = row + 1; + int c = column; + + int i11 = r * columnCount + c; + int i12 = i11 + 1; + int i21 = ( r + 1 ) * columnCount + c; + // int i22 = i21 + 1; + + B3_ASSERT( i11 == index21 ); + B3_ASSERT( i12 == index22 ); + + float h11 = heights[i11]; + float h12 = heights[i12]; + float h21 = heights[i21]; + // float h22 = heights[i22]; + + float x1 = (float)( c ); + float x2 = (float)( c + 1 ); + float z1 = (float)( r ); + float z2 = (float)( r + 1 ); + + // triangle 0 + b3Vec3 vs[3]; + vs[0] = b3Mul( scale, (b3Vec3){ x1, h11, z1 } ); + vs[1] = b3Mul( scale, (b3Vec3){ x1, h21, z2 } ); + vs[2] = b3Mul( scale, (b3Vec3){ x2, h12, z1 } ); + + b3Vec3 n = b3Normalize( b3Cross( b3Sub( vs[1], vs[0] ), b3Sub( vs[2], vs[0] ) ) ); + + float separation = b3PlaneSeparation( plane2, vs[1] ); + float cosAngle = b3Dot( plane2.normal, n ); + if ( separation > 0.0f || cosAngle > cos5Deg ) + { + flags2 |= b3_concaveEdge3; + } + } + + int leftCellIndex = row * ( columnCount - 1 ) + column - 1; + if ( column - 1 >= 0 && hf->materialIndices[leftCellIndex] != B3_HEIGHT_FIELD_HOLE ) + { + B3_ASSERT( 0 <= leftCellIndex && leftCellIndex < cellCount ); + + int r = row; + int c = column - 1; + + int i11 = r * columnCount + c; + int i12 = i11 + 1; + int i21 = ( r + 1 ) * columnCount + c; + int i22 = i21 + 1; + + B3_ASSERT( i12 == index11 ); + B3_ASSERT( i22 == index21 ); + + // float h11 = heights[i11]; + float h12 = heights[i12]; + float h21 = heights[i21]; + float h22 = heights[i22]; + + float x1 = (float)( c ); + float x2 = (float)( c + 1 ); + float z1 = (float)( r ); + float z2 = (float)( r + 1 ); + + // triangle 1 + b3Vec3 vs[3]; + vs[0] = b3Mul( scale, (b3Vec3){ x2, h22, z2 } ); + vs[1] = b3Mul( scale, (b3Vec3){ x2, h12, z1 } ); + vs[2] = b3Mul( scale, (b3Vec3){ x1, h21, z2 } ); + + b3Vec3 n = b3Normalize( b3Cross( b3Sub( vs[1], vs[0] ), b3Sub( vs[2], vs[0] ) ) ); + + float separation = b3PlaneSeparation( plane1, vs[2] ); + float cosAngle = b3Dot( plane1.normal, n ); + if ( separation > 0.0f || cosAngle > cos5Deg ) + { + flags1 |= b3_concaveEdge1; + } + } + + int rightCellIndex = row * ( columnCount - 1 ) + column + 1; + if ( column + 1 < columnCount - 1 && hf->materialIndices[rightCellIndex] != B3_HEIGHT_FIELD_HOLE ) + { + B3_ASSERT( 0 <= rightCellIndex && rightCellIndex < cellCount ); + + int r = row; + int c = column + 1; + + int i11 = r * columnCount + c; + int i12 = i11 + 1; + int i21 = ( r + 1 ) * columnCount + c; + // int i22 = i21 + 1; + + B3_ASSERT( i11 == index12 ); + B3_ASSERT( i21 == index22 ); + + float h11 = heights[i11]; + float h12 = heights[i12]; + float h21 = heights[i21]; + // float h22 = heights[i22]; + + float x1 = (float)( c ); + float x2 = (float)( c + 1 ); + float z1 = (float)( r ); + float z2 = (float)( r + 1 ); + + // triangle 0 + b3Vec3 vs[3]; + vs[0] = b3Mul( scale, (b3Vec3){ x1, h11, z1 } ); + vs[1] = b3Mul( scale, (b3Vec3){ x1, h21, z2 } ); + vs[2] = b3Mul( scale, (b3Vec3){ x2, h12, z1 } ); + + b3Vec3 n = b3Normalize( b3Cross( b3Sub( vs[1], vs[0] ), b3Sub( vs[2], vs[0] ) ) ); + + float separation = b3PlaneSeparation( plane2, vs[2] ); + float cosAngle = b3Dot( plane2.normal, n ); + if ( separation > 0.0f || cosAngle > cos5Deg ) + { + flags2 |= b3_concaveEdge1; + } + } + + B3_ASSERT( 0 <= flags1 && flags1 <= UINT8_MAX ); + B3_ASSERT( 0 <= flags2 && flags2 <= UINT8_MAX ); + + hf->flags[triangleIndex1] = (uint8_t)flags1; + hf->flags[triangleIndex2] = (uint8_t)flags2; + } + } + + B3_ASSERT( triangleIndex == triangleCount ); + + b3Free( decompressedHeights, heightCount * sizeof( float ) ); + + hf->hash = 0; + uint32_t h = B3_HASH_INIT; + h = b3Hash( h, (const uint8_t*)hf->compressedHeights, heightCount * (int)sizeof( uint16_t ) ); + h = b3Hash( h, (const uint8_t*)hf->materialIndices, cellCount * (int)sizeof( uint8_t ) ); + h = b3Hash( h, (const uint8_t*)hf->flags, triangleCount * (int)sizeof( uint8_t ) ); + h = b3Hash( h, (const uint8_t*)&hf->aabb, (int)( sizeof( b3HeightField ) - offsetof( b3HeightField, aabb ) ) ); + hf->hash = h; + + return hf; +} + +_Static_assert( b3_concaveEdge3 == 4 * b3_concaveEdge1, "bit math" ); +_Static_assert( b3_inverseConcaveEdge3 == 4 * b3_inverseConcaveEdge1, "bit math" ); + +b3Triangle b3GetHeightFieldTriangle( const b3HeightField* heightField, int triangleIndex ) +{ + B3_ASSERT( 0 <= triangleIndex ); + B3_ASSERT( triangleIndex < 2 * ( heightField->columnCount - 1 ) * ( heightField->rowCount - 1 ) ); + + b3Triangle triangle; + triangle.flags = heightField->flags[triangleIndex]; + + int columnCount = heightField->columnCount; + int quadIndex = triangleIndex >> 1; + int row = quadIndex / ( columnCount - 1 ); + int column = quadIndex - row * ( columnCount - 1 ); + + int index11 = row * columnCount + column; + int index12 = index11 + 1; + int index21 = ( row + 1 ) * columnCount + column; + int index22 = index21 + 1; + + int cellIndex = row * ( columnCount - 1 ) + column; + + B3_ASSERT( quadIndex == cellIndex ); + B3_ASSERT( heightField->materialIndices[cellIndex] != B3_HEIGHT_FIELD_HOLE ); + B3_UNUSED( cellIndex ); + + float minHeight = heightField->minHeight; + float heightScale = heightField->heightScale; + const uint16_t* heights = heightField->compressedHeights; + + float height11 = minHeight + heightScale * heights[index11]; + float height12 = minHeight + heightScale * heights[index12]; + float height21 = minHeight + heightScale * heights[index21]; + float height22 = minHeight + heightScale * heights[index22]; + + float x1 = (float)( column ); + float x2 = (float)( column + 1 ); + float z1 = (float)( row ); + float z2 = (float)( row + 1 ); + + b3Vec3 scale = heightField->scale; + if ( ( triangleIndex & 1 ) == 0 ) + { + triangle.vertices[0] = b3Mul( scale, (b3Vec3){ x1, height11, z1 } ); + triangle.vertices[1] = b3Mul( scale, (b3Vec3){ x1, height21, z2 } ); + triangle.vertices[2] = b3Mul( scale, (b3Vec3){ x2, height12, z1 } ); + triangle.i1 = index11; + triangle.i2 = index21; + triangle.i3 = index12; + } + else + { + triangle.vertices[0] = b3Mul( scale, (b3Vec3){ x2, height22, z2 } ); + triangle.vertices[1] = b3Mul( scale, (b3Vec3){ x2, height12, z1 } ); + triangle.vertices[2] = b3Mul( scale, (b3Vec3){ x1, height21, z2 } ); + triangle.i1 = index22; + triangle.i2 = index12; + triangle.i3 = index21; + } + + if ( heightField->clockwise ) + { + B3_SWAP( triangle.vertices[1], triangle.vertices[2] ); + B3_SWAP( triangle.i2, triangle.i3 ); + + // Reversing winding swaps edge1 and edge3; edge2 (the diagonal) is preserved. + int flags = triangle.flags; + int edge1Bits = flags & ( b3_concaveEdge1 | b3_inverseConcaveEdge1 ); + int edge3Bits = flags & ( b3_concaveEdge3 | b3_inverseConcaveEdge3 ); + flags &= ~( b3_concaveEdge1 | b3_concaveEdge3 | b3_inverseConcaveEdge1 | b3_inverseConcaveEdge3 ); + flags |= edge1Bits << 2; + flags |= edge3Bits >> 2; + triangle.flags = flags; + } + + return triangle; +} + +int b3GetHeightFieldMaterial( const b3HeightField* heightField, int triangleIndex ) +{ + B3_ASSERT( 0 <= triangleIndex ); + B3_ASSERT( triangleIndex < 2 * ( heightField->columnCount - 1 ) * ( heightField->rowCount - 1 ) ); + + int cellIndex = triangleIndex >> 1; + return heightField->materialIndices[cellIndex]; +} + +b3AABB b3ComputeHeightFieldAABB( const b3HeightField* shape, b3Transform transform ) +{ + return b3AABB_Transform( transform, shape->aabb ); +} + +b3CastOutput b3RayCastHeightField( const b3HeightField* heightField, const b3RayCastInput* input ) +{ + b3ShapeCastInput shapeCastInput = { 0 }; + shapeCastInput.proxy = (b3ShapeProxy){ &input->origin, 1, 0.0f }; + shapeCastInput.translation = input->translation; + shapeCastInput.maxFraction = input->maxFraction; + + return b3ShapeCastHeightField( heightField, &shapeCastInput ); +} + +// todo advance cast to the grid border immediately if it starts outside the row/column range +// todo terminate the cast immediately if it leaves the row/column range +b3CastOutput b3ShapeCastHeightField( const b3HeightField* heightField, const b3ShapeCastInput* input ) +{ + b3AABB shapeBounds = b3MakeAABB( input->proxy.points, input->proxy.count, input->proxy.radius ); + b3Vec3 shapeTranslation = input->translation; + b3Vec3 scale = heightField->scale; + + b3Vec3 shapeStart = b3AABB_Center( shapeBounds ); + b3Vec3 shapeDelta = b3MulSV( input->maxFraction, shapeTranslation ); + b3Vec3 shapeEnd = b3Add( shapeStart, shapeDelta ); + + b3CastOutput result = { 0 }; + + b3Vec3 shapeExtents = b3AABB_Extents( shapeBounds ); + b3Vec3 margin = { B3_AABB_MARGIN, B3_AABB_MARGIN, B3_AABB_MARGIN }; + b3AABB combinedBounds = { b3Sub( b3Sub( heightField->aabb.lowerBound, shapeExtents ), margin ), + b3Add( b3Add( heightField->aabb.upperBound, shapeExtents ), margin ) }; + + float minFraction, maxFraction; + bool intersects = b3IntersectRayAndAABB( combinedBounds.lowerBound, combinedBounds.upperBound, shapeStart, shapeEnd, + &minFraction, &maxFraction ); + if ( intersects == false ) + { + return result; + } + + // These are for walking the grid, not the triangle cast. + // The triangle cast uses the unclamped ray and fraction. + b3Vec3 clampedStart = b3MulAdd( shapeStart, minFraction, shapeDelta ); + b3Vec3 clampedDelta = b3MulSV( maxFraction - minFraction, shapeDelta ); + b3Vec3 clampedEnd = b3Add( clampedStart, clampedDelta ); + + // The grid traversal starts from the leading shape bounds corner + float signX, signZ; + if ( shapeTranslation.x >= 0.0f ) + { + clampedStart.x += shapeExtents.x; + signX = 1.0f; + } + else + { + clampedStart.x -= shapeExtents.x; + signX = -1.0f; + } + + if ( shapeTranslation.z >= 0.0f ) + { + clampedStart.z += shapeExtents.z; + signZ = 1.0f; + } + else + { + clampedStart.z -= shapeExtents.z; + signZ = -1.0f; + } + + // Shift the end as well + clampedEnd = b3Add( clampedStart, clampedDelta ); + + // Row and column range for the shape cast + int columnStart = (int)floorf( clampedStart.x / scale.x ); + int columnEnd = (int)floorf( clampedEnd.x / scale.x ); + int rowStart = (int)floorf( clampedStart.z / scale.z ); + int rowEnd = (int)floorf( clampedEnd.z / scale.z ); + + b3Vec3 absClampedDelta = b3Abs( clampedDelta ); + + // Precompute increments for row and column traversal. + // The ray can be slightly tilted yet remain within a single row or column + // once rasterized. + float deltaAlphaX; + float nextFractionX; + int deltaColumn; + + if ( columnStart < columnEnd ) + { + B3_ASSERT( absClampedDelta.x > 0.0f ); + + // Going forward on x columns + deltaAlphaX = scale.x / absClampedDelta.x; + nextFractionX = ( scale.x * ( columnStart + 1 ) - clampedStart.x ) / absClampedDelta.x; + deltaColumn = 1; + } + else if ( columnEnd < columnStart ) + { + B3_ASSERT( absClampedDelta.x > 0.0f ); + + // Going backwards on x columns + deltaAlphaX = scale.x / absClampedDelta.x; + nextFractionX = ( clampedStart.x - scale.x * columnStart ) / absClampedDelta.x; + deltaColumn = -1; + } + else + { + // Cast stays in a single column + deltaAlphaX = 0.0f; + nextFractionX = FLT_MAX; + deltaColumn = 0; + } + + float deltaAlphaZ; + float nextFractionZ; + int deltaRow; + + if ( rowStart < rowEnd ) + { + B3_ASSERT( absClampedDelta.z > 0.0f ); + + // Going forward on z rows + deltaAlphaZ = scale.z / absClampedDelta.z; + nextFractionZ = ( scale.z * ( rowStart + 1 ) - clampedStart.z ) / absClampedDelta.z; + deltaRow = 1; + } + else if ( rowEnd < rowStart ) + { + B3_ASSERT( absClampedDelta.z > 0.0f ); + + // Going backwards on z rows + deltaAlphaZ = scale.z / absClampedDelta.z; + nextFractionZ = ( clampedStart.z - scale.z * rowStart ) / absClampedDelta.z; + deltaRow = -1; + } + else + { + // Cast stays in a single row + deltaAlphaZ = 0.0f; + nextFractionZ = FLT_MAX; + deltaRow = 0; + } + + // Column and row range for 2D projected initial shape bounds + int boxColumnHead = columnStart; + int boxRowHead = rowStart; + + int boxColumnTail = (int)floorf( ( clampedStart.x - 2.0f * signX * shapeExtents.x ) / scale.x ); + int boxRowTail = (int)floorf( ( clampedStart.z - 2.0f * signZ * shapeExtents.z ) / scale.z ); + + float bestFraction = input->maxFraction; + + int rowCount = heightField->rowCount; + int columnCount = heightField->columnCount; + int cellCount = ( heightField->rowCount - 1 ) * ( heightField->columnCount - 1 ); + B3_UNUSED( cellCount ); + + float minHeight = heightField->minHeight; + float heightScale = heightField->heightScale; + const uint16_t* heights = heightField->compressedHeights; + + b3ShapeCastPairInput pairInput = { 0 }; + pairInput.transformA = b3Transform_identity; + pairInput.proxyB = input->proxy; + pairInput.transformB = b3Transform_identity; + pairInput.translationB = input->translation; + pairInput.canEncroach = input->canEncroach; + + b3AABB castBounds; + castBounds.lowerBound = b3Sub( b3Min( clampedStart, clampedEnd ), shapeExtents ); + castBounds.upperBound = b3Add( b3Max( clampedStart, clampedEnd ), shapeExtents ); + + b3V32 rayOrigin = b3LoadV( &shapeStart.x ); + b3V32 rayTranslation = b3LoadV( &shapeTranslation.x ); + + while ( true ) + { + int column1, column2; + if ( boxColumnTail < boxColumnHead ) + { + column1 = boxColumnTail; + column2 = boxColumnHead; + } + else + { + column1 = boxColumnHead; + column2 = boxColumnTail; + } + + int row1, row2; + if ( boxRowTail < boxRowHead ) + { + row1 = boxRowTail; + row2 = boxRowHead; + } + else + { + row1 = boxRowHead; + row2 = boxRowTail; + } + + for ( int row = row1; row <= row2; ++row ) + { + if ( row < 0 || rowCount - 1 <= row ) + { + continue; + } + + for ( int column = column1; column <= column2; ++column ) + { + if ( column < 0 || columnCount - 1 <= column ) + { + continue; + } + + int cellIndex = row * ( columnCount - 1 ) + column; + B3_ASSERT( cellIndex < cellCount ); + + uint8_t materialIndex = heightField->materialIndices[cellIndex]; + if ( materialIndex == B3_HEIGHT_FIELD_HOLE ) + { + continue; + } + + // index = row * columnCount + column + int index11 = row * columnCount + column; + + int index12 = index11 + 1; + int index21 = ( row + 1 ) * columnCount + column; + int index22 = index21 + 1; + + float height11 = minHeight + heightScale * heights[index11]; + float height12 = minHeight + heightScale * heights[index12]; + float height21 = minHeight + heightScale * heights[index21]; + float height22 = minHeight + heightScale * heights[index22]; + + float x1 = (float)( column ); + float x2 = (float)( column + 1 ); + float z1 = (float)( row ); + float z2 = (float)( row + 1 ); + + b3Vec3 point11 = b3Mul( scale, (b3Vec3){ x1, height11, z1 } ); + b3Vec3 point12 = b3Mul( scale, (b3Vec3){ x2, height12, z1 } ); + b3Vec3 point21 = b3Mul( scale, (b3Vec3){ x1, height21, z2 } ); + b3Vec3 point22 = b3Mul( scale, (b3Vec3){ x2, height22, z2 } ); + + // I know the min/max x and z values, but not the min/max heights. + b3AABB bounds; + bounds.lowerBound = b3Min( b3Min( point11, point12 ), b3Min( point21, point22 ) ); + bounds.upperBound = b3Max( b3Max( point11, point12 ), b3Max( point21, point22 ) ); + + if ( b3AABB_Overlaps( castBounds, bounds ) == false ) + { + continue; + } + + int quadIndex = row * ( columnCount - 1 ) + column; + int triangleIndex1 = 2 * quadIndex; + int triangleIndex2 = triangleIndex1 + 1; + + if ( input->proxy.count == 1 && input->proxy.radius == 0.0f ) + { + // Ray cast + { + b3V32 vertex1 = b3LoadV( &point11.x ); + b3V32 vertex2, vertex3; + + if ( heightField->clockwise ) + { + vertex2 = b3LoadV( &point12.x ); + vertex3 = b3LoadV( &point21.x ); + } + else + { + vertex2 = b3LoadV( &point21.x ); + vertex3 = b3LoadV( &point12.x ); + } + + float alpha = b3IntersectRayTriangle( rayOrigin, rayTranslation, vertex1, vertex2, vertex3 ); + B3_ASSERT( 0 <= alpha && alpha <= 1.0f ); + + if ( alpha < bestFraction ) + { + b3Vec3 edge1 = b3Sub( point21, point11 ); + b3Vec3 edge2 = b3Sub( point12, point11 ); + b3Vec3 normal = heightField->clockwise ? b3Cross( edge2, edge1 ) : b3Cross( edge1, edge2 ); + + result.point = b3MulAdd( shapeStart, alpha, shapeTranslation ); + result.normal = b3Normalize( normal ); + result.fraction = alpha; + result.triangleIndex = triangleIndex1; + result.materialIndex = materialIndex; + result.hit = true; + bestFraction = alpha; + } + } + + { + b3V32 vertex1 = b3LoadV( &point22.x ); + b3V32 vertex2, vertex3; + + if ( heightField->clockwise ) + { + vertex2 = b3LoadV( &point21.x ); + vertex3 = b3LoadV( &point12.x ); + } + else + { + vertex2 = b3LoadV( &point12.x ); + vertex3 = b3LoadV( &point21.x ); + } + + float alpha = b3IntersectRayTriangle( rayOrigin, rayTranslation, vertex1, vertex2, vertex3 ); + B3_ASSERT( 0 <= alpha && alpha <= 1.0f ); + + if ( alpha < bestFraction ) + { + b3Vec3 edge1 = b3Sub( point22, point21 ); + b3Vec3 edge2 = b3Sub( point12, point21 ); + b3Vec3 normal = heightField->clockwise ? b3Cross( edge2, edge1 ) : b3Cross( edge1, edge2 ); + + result.point = b3MulAdd( shapeStart, alpha, shapeTranslation ); + result.normal = b3Normalize( normal ); + result.fraction = alpha; + result.triangleIndex = triangleIndex2; + result.materialIndex = materialIndex; + result.hit = true; + bestFraction = alpha; + } + } + } + else + { + // Shape cast + // todo back-side culling + { + // Shift origin to first vertex + b3Vec3 origin = point11; + b3Vec3 triangleVertices[] = { b3Vec3_zero, b3Sub( point21, origin ), b3Sub( point12, origin ) }; + pairInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f }; + pairInput.maxFraction = bestFraction; + pairInput.transformB.p = b3Neg( origin ); + + b3CastOutput pairOutput = b3ShapeCast( &pairInput ); + + if ( pairOutput.hit ) + { + bestFraction = pairOutput.fraction; + result = pairOutput; + result.point = b3Add( result.point, origin ); + result.triangleIndex = triangleIndex1; + result.materialIndex = materialIndex; + } + } + + { + // Shift origin to first vertex + b3Vec3 origin = point21; + b3Vec3 triangleVertices[] = { b3Vec3_zero, b3Sub( point22, origin ), b3Sub( point12, origin ) }; + pairInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f }; + pairInput.maxFraction = bestFraction; + pairInput.transformB.p = b3Neg( origin ); + + b3CastOutput pairOutput = b3ShapeCast( &pairInput ); + + if ( pairOutput.hit ) + { + bestFraction = pairOutput.fraction; + result = pairOutput; + result.point = b3Add( result.point, origin ); + result.triangleIndex = triangleIndex2; + result.materialIndex = materialIndex; + } + } + } + } + } + + // These fractions always increase to guarantee the loop eventually exits + if ( nextFractionX > bestFraction && nextFractionZ > bestFraction ) + { + break; + } + + // Advance the cast to the next column or row + if ( nextFractionX <= nextFractionZ ) + { + if ( boxColumnHead == columnEnd ) + { + // Hit the end already + break; + } + + // Advance to next column + boxColumnHead += deltaColumn; + + // Build a single column to cast + boxColumnTail = boxColumnHead; + + if ( shapeExtents.z == 0.0f ) + { + // Single row + boxRowTail = boxRowHead; + } + else + { + // Rasterize shape row + float rowIntercept = clampedStart.z + nextFractionX * clampedDelta.z; + boxRowTail = (int)floorf( ( rowIntercept - 2.0f * signZ * shapeExtents.z ) / scale.z ); + } + + nextFractionX += deltaAlphaX; + } + else + { + if ( boxRowHead == rowEnd ) + { + // Hit the end already + break; + } + + // Advance to next row + boxRowHead += deltaRow; + + // Build a single row to cast + boxRowTail = boxRowHead; + + if ( shapeExtents.x == 0.0f ) + { + // Single column + boxColumnTail = boxColumnHead; + } + else + { + // Rasterize shape column + float columnIntercept = clampedStart.x + nextFractionZ * clampedDelta.x; + boxColumnTail = (int)floorf( ( columnIntercept - 2.0f * signX * shapeExtents.x ) / scale.x ); + } + + nextFractionZ += deltaAlphaZ; + } + } + + return result; +} + +bool b3OverlapHeightField( const b3HeightField* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy ) +{ + b3Vec3 buffer[B3_MAX_SHAPE_CAST_POINTS]; + b3ShapeProxy localProxy = b3MakeLocalProxy( proxy, shapeTransform, buffer ); + b3AABB aabb = b3ComputeProxyAABB( &localProxy ); + + b3Vec3 scale = shape->scale; + int minRow = (int)floorf( aabb.lowerBound.z / scale.z ); + int maxRow = (int)floorf( aabb.upperBound.z / scale.z ); + int minCol = (int)floorf( aabb.lowerBound.x / scale.x ); + int maxCol = (int)floorf( aabb.upperBound.x / scale.x ); + + b3V32 boundsMin = b3LoadV( &aabb.lowerBound.x ); + b3V32 boundsMax = b3LoadV( &aabb.upperBound.x ); + b3V32 boundsCenter = b3MulV( b3_halfV, b3AddV( boundsMin, boundsMax ) ); + b3V32 boundsExtent = b3SubV( boundsMax, boundsCenter ); + + b3DistanceInput input; + input.proxyB = localProxy; + input.transformA = b3Transform_identity; + input.transformB = b3Transform_identity; + input.useRadii = true; + + b3SimplexCache cache = { 0 }; + + float minHeight = shape->minHeight; + float heightScale = shape->heightScale; + + const uint16_t* heights = shape->compressedHeights; + + // Outer loop on rows and inner loop on columns so that triangle indices + // increase monotonically. + for ( int row = minRow; row <= maxRow; ++row ) + { + if ( row < 0 || shape->rowCount - 1 <= row ) + { + continue; + } + + for ( int column = minCol; column <= maxCol; ++column ) + { + if ( column < 0 || shape->columnCount - 1 <= column ) + { + continue; + } + + int cellIndex = row * ( shape->columnCount - 1 ) + column; + B3_ASSERT( cellIndex < ( shape->rowCount - 1 ) * ( shape->columnCount - 1 ) ); + uint8_t material = shape->materialIndices[cellIndex]; + if ( material == B3_HEIGHT_FIELD_HOLE ) + { + continue; + } + + // index = row * columnCount + column + int index11 = row * shape->columnCount + column; + int index12 = index11 + 1; + int index21 = ( row + 1 ) * shape->columnCount + column; + int index22 = index21 + 1; + + float height11 = minHeight + heightScale * heights[index11]; + float height12 = minHeight + heightScale * heights[index12]; + float height21 = minHeight + heightScale * heights[index21]; + float height22 = minHeight + heightScale * heights[index22]; + + float x1 = (float)( column ); + float x2 = (float)( column + 1 ); + float z1 = (float)( row ); + float z2 = (float)( row + 1 ); + + b3Vec3 point11 = b3Mul( scale, (b3Vec3){ x1, height11, z1 } ); + b3Vec3 point12 = b3Mul( scale, (b3Vec3){ x2, height12, z1 } ); + b3Vec3 point21 = b3Mul( scale, (b3Vec3){ x1, height21, z2 } ); + b3Vec3 point22 = b3Mul( scale, (b3Vec3){ x2, height22, z2 } ); + + b3V32 v11 = b3LoadV( &point11.x ); + b3V32 v12 = b3LoadV( &point12.x ); + b3V32 v21 = b3LoadV( &point21.x ); + b3V32 v22 = b3LoadV( &point22.x ); + + if ( b3TestBoundsTriangleOverlap( boundsCenter, boundsExtent, v11, v21, v12 ) ) + { + b3Vec3 triangleVertices[] = { point11, point21, point12 }; + input.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f }; + + // reset the cache + cache.count = 0; + + // get distance between triangle and query shape + b3DistanceOutput output = b3ShapeDistance( &input, &cache, NULL, 0 ); + + float tolerance = 0.1f * B3_LINEAR_SLOP; + if ( output.distance < tolerance ) + { + // overlap detected + return true; + } + } + + if ( b3TestBoundsTriangleOverlap( boundsCenter, boundsExtent, v21, v22, v12 ) ) + { + b3Vec3 triangleVertices[] = { point22, point12, point21 }; + input.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f }; + + // reset the cache + cache.count = 0; + + // get distance between triangle and query shape + b3DistanceOutput output = b3ShapeDistance( &input, &cache, NULL, 0 ); + + float tolerance = 0.1f * B3_LINEAR_SLOP; + if ( output.distance < tolerance ) + { + // overlap detected + return true; + } + } + } + } + + return false; +} + +void b3QueryHeightField( const b3HeightField* heightField, b3AABB bounds, b3MeshQueryFcn* fcn, void* context ) +{ + b3Vec3 scale = heightField->scale; + + int minRow = (int)floorf( bounds.lowerBound.z / scale.z ); + int maxRow = (int)floorf( bounds.upperBound.z / scale.z ); + int minCol = (int)floorf( bounds.lowerBound.x / scale.x ); + int maxCol = (int)floorf( bounds.upperBound.x / scale.x ); + + float minHeight = heightField->minHeight; + float heightScale = heightField->heightScale; + + const uint16_t* heights = heightField->compressedHeights; + + // Outer loop on rows and inner loop on columns so that triangle indices + // increase monotonically. + for ( int row = minRow; row <= maxRow; ++row ) + { + if ( row < 0 || heightField->rowCount - 1 <= row ) + { + continue; + } + + for ( int column = minCol; column <= maxCol; ++column ) + { + if ( column < 0 || heightField->columnCount - 1 <= column ) + { + continue; + } + + int cellIndex = row * ( heightField->columnCount - 1 ) + column; + B3_ASSERT( cellIndex < ( heightField->rowCount - 1 ) * ( heightField->columnCount - 1 ) ); + uint8_t material = heightField->materialIndices[cellIndex]; + if ( material == B3_HEIGHT_FIELD_HOLE ) + { + continue; + } + + // index = row * columnCount + column + int index11 = row * heightField->columnCount + column; + int index12 = index11 + 1; + int index21 = ( row + 1 ) * heightField->columnCount + column; + int index22 = index21 + 1; + + float height11 = minHeight + heightScale * heights[index11]; + float height12 = minHeight + heightScale * heights[index12]; + float height21 = minHeight + heightScale * heights[index21]; + float height22 = minHeight + heightScale * heights[index22]; + + float x1 = (float)( column ); + float x2 = (float)( column + 1 ); + float z1 = (float)( row ); + float z2 = (float)( row + 1 ); + + b3Vec3 point11 = b3Mul( scale, (b3Vec3){ x1, height11, z1 } ); + b3Vec3 point12 = b3Mul( scale, (b3Vec3){ x2, height12, z1 } ); + b3Vec3 point21 = b3Mul( scale, (b3Vec3){ x1, height21, z2 } ); + b3Vec3 point22 = b3Mul( scale, (b3Vec3){ x2, height22, z2 } ); + + // I know the min/max x and z values, but not the min/max heights. + // This could be done with no branching in SIMD. + b3AABB cellBound; + cellBound.lowerBound = b3Min( b3Min( point11, point12 ), b3Min( point21, point22 ) ); + cellBound.upperBound = b3Max( b3Max( point11, point12 ), b3Max( point21, point22 ) ); + + if ( b3AABB_Overlaps( bounds, cellBound ) ) + { + int quadIndex = row * ( heightField->columnCount - 1 ) + column; + int triangleIndex = 2 * quadIndex; + + if ( heightField->clockwise ) + { + fcn( point11, point12, point21, triangleIndex, context ); + fcn( point22, point21, point12, triangleIndex + 1, context ); + } + else + { + fcn( point11, point21, point12, triangleIndex, context ); + fcn( point22, point12, point21, triangleIndex + 1, context ); + } + } + } + } +} + +int b3CollideMoverAndHeightField( b3PlaneResult* planes, int capacity, const b3HeightField* shape, const b3Capsule* mover ) +{ + b3DistanceInput distanceInput = { 0 }; + distanceInput.proxyB = (b3ShapeProxy){ &mover->center1, 2, 0.0f }; + distanceInput.transformA = b3Transform_identity; + distanceInput.transformB = b3Transform_identity; + distanceInput.useRadii = false; + + b3SimplexCache cache = { 0 }; + + float radius = mover->radius; + b3V32 center1 = b3LoadV( &mover->center1.x ); + b3V32 center2 = b3LoadV( &mover->center2.x ); + b3V32 r = b3SplatV( radius ); + b3V32 boundsMin = b3SubV( b3MinV( center1, center2 ), r ); + b3V32 boundsMax = b3AddV( b3MaxV( center1, center2 ), r ); + b3V32 boundsCenter = b3MulV( b3_halfV, b3AddV( boundsMin, boundsMax ) ); + b3V32 boundsExtent = b3SubV( boundsMax, boundsCenter ); + + float localMinX = b3GetXV( boundsMin ); + float localMinZ = b3GetZV( boundsMin ); + float localMaxX = b3GetXV( boundsMax ); + float localMaxZ = b3GetZV( boundsMax ); + + b3Vec3 scale = shape->scale; + int minRow = (int)floorf( localMinZ / scale.z ); + int maxRow = (int)floorf( localMaxZ / scale.z ); + int minCol = (int)floorf( localMinX / scale.x ); + int maxCol = (int)floorf( localMaxX / scale.x ); + + float minHeight = shape->minHeight; + float heightScale = shape->heightScale; + const uint16_t* heights = shape->compressedHeights; + int planeCount = 0; + + // Outer loop on rows and inner loop on columns so that triangle indices + // increase monotonically. + for ( int row = minRow; row <= maxRow; ++row ) + { + if ( row < 0 || shape->rowCount - 1 <= row ) + { + continue; + } + + for ( int column = minCol; column <= maxCol; ++column ) + { + if ( column < 0 || shape->columnCount - 1 <= column ) + { + continue; + } + + int cellIndex = row * ( shape->columnCount - 1 ) + column; + B3_ASSERT( cellIndex < ( shape->rowCount - 1 ) * ( shape->columnCount - 1 ) ); + uint8_t material = shape->materialIndices[cellIndex]; + if ( material == B3_HEIGHT_FIELD_HOLE ) + { + continue; + } + + // index = row * columnCount + column + int index11 = row * shape->columnCount + column; + int index12 = index11 + 1; + int index21 = ( row + 1 ) * shape->columnCount + column; + int index22 = index21 + 1; + + float height11 = minHeight + heightScale * heights[index11]; + float height12 = minHeight + heightScale * heights[index12]; + float height21 = minHeight + heightScale * heights[index21]; + float height22 = minHeight + heightScale * heights[index22]; + + float x1 = (float)( column ); + float x2 = (float)( column + 1 ); + float z1 = (float)( row ); + float z2 = (float)( row + 1 ); + + b3Vec3 point11 = b3Mul( scale, (b3Vec3){ x1, height11, z1 } ); + b3Vec3 point12 = b3Mul( scale, (b3Vec3){ x2, height12, z1 } ); + b3Vec3 point21 = b3Mul( scale, (b3Vec3){ x1, height21, z2 } ); + b3Vec3 point22 = b3Mul( scale, (b3Vec3){ x2, height22, z2 } ); + + b3V32 v11 = b3LoadV( &point11.x ); + b3V32 v12 = b3LoadV( &point12.x ); + b3V32 v21 = b3LoadV( &point21.x ); + b3V32 v22 = b3LoadV( &point22.x ); + + if ( b3TestBoundsTriangleOverlap( boundsCenter, boundsExtent, v11, v21, v12 ) ) + { + b3Vec3 triangleVertices[] = { point11, point21, point12 }; + distanceInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f }; + + // reset the cache + cache.count = 0; + + // get distance between triangle and mover + b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, &cache, NULL, 0 ); + + if ( distanceOutput.distance == 0.0f ) + { + // todo SAT + } + else if ( distanceOutput.distance <= mover->radius ) + { + b3Plane plane = { distanceOutput.normal, mover->radius - distanceOutput.distance }; + planes[planeCount] = (b3PlaneResult){ plane, distanceOutput.pointA }; + planeCount += 1; + + if ( planeCount == capacity ) + { + return planeCount; + } + } + } + + if ( b3TestBoundsTriangleOverlap( boundsCenter, boundsExtent, v21, v22, v12 ) ) + { + b3Vec3 triangleVertices[] = { point22, point12, point21 }; + distanceInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f }; + + // reset the cache + cache.count = 0; + + // get distance between triangle and mover + b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, &cache, NULL, 0 ); + + if ( distanceOutput.distance == 0.0f ) + { + // todo SAT + } + else if ( distanceOutput.distance <= mover->radius ) + { + b3Plane plane = { distanceOutput.normal, mover->radius - distanceOutput.distance }; + planes[planeCount] = (b3PlaneResult){ plane, distanceOutput.pointA }; + planeCount += 1; + + if ( planeCount == capacity ) + { + return planeCount; + } + } + } + } + } + + return planeCount; +} + +b3HeightField* b3CreateGrid( int rowCount, int columnCount, b3Vec3 scale, bool makeHoles ) +{ + int heightCount = rowCount * columnCount; + float* heights = (float*)b3Alloc( heightCount * sizeof( float ) ); + + for ( int i = 0; i < rowCount; ++i ) + { + for ( int j = 0; j < columnCount; ++j ) + { + int k = i * columnCount + j; + heights[k] = 0.0f; + } + } + + int cellCount = ( rowCount - 1 ) * ( columnCount - 1 ); + uint8_t* materialIndices = (uint8_t*)b3Alloc( cellCount * sizeof( uint8_t ) ); + + for ( int i = 0; i < rowCount - 1; ++i ) + { + for ( int j = 0; j < columnCount - 1; ++j ) + { + int k = i * ( columnCount - 1 ) + j; + + if ( makeHoles && k > 0 && k % 16 == 0 ) + { + materialIndices[k] = B3_HEIGHT_FIELD_HOLE; + } + else + { + materialIndices[k] = 0; + } + } + } + + b3HeightFieldDef data = { 0 }; + data.heights = heights; + data.materialIndices = materialIndices; + data.scale = scale; + data.countX = columnCount; + data.countZ = rowCount; + data.globalMinimumHeight = -256.0f; + data.globalMaximumHeight = 256.0f; + data.clockwiseWinding = false; + + b3HeightField* heightField = b3CreateHeightField( &data ); + + b3Free( heights, heightCount * sizeof( float ) ); + b3Free( materialIndices, cellCount * sizeof( uint8_t ) ); + + return heightField; +} + +b3HeightField* b3CreateWave( int rowCount, int columnCount, b3Vec3 scale, float rowFrequency, float columnFrequency, + bool makeHoles ) +{ + int heightCount = rowCount * columnCount; + float* heights = (float*)b3Alloc( heightCount * sizeof( float ) ); + + float omegaZ = 2.0f * B3_PI * rowFrequency; + float omegaX = 2.0f * B3_PI * columnFrequency; + + for ( int i = 0; i < rowCount; ++i ) + { + float rowHeight = sinf( omegaZ * i ); + + for ( int j = 0; j < columnCount; ++j ) + { + int k = i * columnCount + j; + float columnHeight = sinf( omegaX * j ); + heights[k] = rowHeight * columnHeight; + } + } + + int cellCount = ( rowCount - 1 ) * ( columnCount - 1 ); + uint8_t* materialIndices = (uint8_t*)b3Alloc( cellCount * sizeof( uint8_t ) ); + + for ( int i = 0; i < rowCount - 1; ++i ) + { + for ( int j = 0; j < columnCount - 1; ++j ) + { + int k = i * ( columnCount - 1 ) + j; + + if ( makeHoles && k > 0 && k % 16 == 0 ) + { + materialIndices[k] = B3_HEIGHT_FIELD_HOLE; + } + else + { + int materialCount = 3; + materialIndices[k] = (uint8_t)( ( i + j ) % materialCount ); + } + } + } + + b3HeightFieldDef data = { 0 }; + data.heights = heights; + data.materialIndices = materialIndices; + data.scale = scale; + data.countX = columnCount; + data.countZ = rowCount; + data.globalMinimumHeight = -256.0f; + data.globalMaximumHeight = 256.0f; + data.clockwiseWinding = false; + + b3HeightField* heightField = b3CreateHeightField( &data ); + + b3Free( heights, heightCount * sizeof( float ) ); + b3Free( materialIndices, cellCount * sizeof( uint8_t ) ); + + return heightField; +} + +void b3DestroyHeightField( b3HeightField* heightField ) +{ + int heightCount = heightField->rowCount * heightField->columnCount; + b3Free( heightField->compressedHeights, heightCount * sizeof( uint16_t ) ); + + int cellCount = ( heightField->rowCount - 1 ) * ( heightField->columnCount - 1 ); + b3Free( heightField->materialIndices, cellCount * sizeof( uint8_t ) ); + + int triangleCount = 2 * cellCount; + b3Free( heightField->flags, triangleCount * sizeof( uint8_t ) ); + + b3Free( heightField, sizeof( b3HeightField ) ); +} + +void b3DumpHeightData( const b3HeightFieldDef* data, const char* fileName ) +{ + FILE* file = NULL; + +#if defined( _MSC_VER ) + errno_t e = fopen_s( &file, fileName, "w" ); + if ( e != 0 ) + { + return; + } +#else + file = fopen( fileName, "w" ); + if ( file == NULL ) + { + return; + } +#endif + + fprintf( file, "%d %d\n", data->countX, data->countZ ); + fprintf( file, "%.9f %.9f %.9f\n", data->scale.x, data->scale.y, data->scale.z ); + fprintf( file, "%.9f %.9f\n", data->globalMinimumHeight, data->globalMaximumHeight ); + fprintf( file, "%d\n", data->clockwiseWinding ); + + int heightCount = data->countX * data->countZ; + for ( int i = 0; i < heightCount; ++i ) + { + fprintf( file, "%.9f\n", data->heights[i] ); + } + + int materialCount = ( data->countX - 1 ) * ( data->countZ - 1 ); + for ( int i = 0; i < materialCount; ++i ) + { + fprintf( file, "%d\n", data->materialIndices[i] ); + } + + fclose( file ); +} + +#if defined( _MSC_VER ) +#define B3_FILE_SCAN fscanf_s +#else +#define B3_FILE_SCAN fscanf +#endif + +b3HeightField* b3LoadHeightField( const char* fileName ) +{ + FILE* file = NULL; + +#if defined( _MSC_VER ) + errno_t e = fopen_s( &file, fileName, "r" ); + if ( e != 0 ) + { + return NULL; + } +#else + file = fopen( fileName, "r" ); + if ( file == NULL ) + { + return NULL; + } +#endif + + b3HeightFieldDef data = { 0 }; + + // Read dimensions + if ( B3_FILE_SCAN( file, "%d %d", &data.countX, &data.countZ ) != 2 ) + { + fclose( file ); + return NULL; + } + + // Read scale + if ( B3_FILE_SCAN( file, "%f %f %f", &data.scale.x, &data.scale.y, &data.scale.z ) != 3 ) + { + fclose( file ); + return NULL; + } + + // Read global height bounds + if ( B3_FILE_SCAN( file, "%f %f", &data.globalMinimumHeight, &data.globalMaximumHeight ) != 2 ) + { + fclose( file ); + return NULL; + } + + // Read clockwise winding + int clockwise; + if ( B3_FILE_SCAN( file, "%d", &clockwise ) != 1 ) + { + fclose( file ); + return NULL; + } + data.clockwiseWinding = clockwise != 0; + + // Allocate and read height data + int heightCount = data.countX * data.countZ; + data.heights = (float*)b3Alloc( heightCount * sizeof( float ) ); + + for ( int i = 0; i < heightCount; ++i ) + { + if ( B3_FILE_SCAN( file, "%f", &data.heights[i] ) != 1 ) + { + b3Free( data.heights, heightCount * sizeof( float ) ); + fclose( file ); + return NULL; + } + } + + // Allocate and read material indices + int materialCount = ( data.countX - 1 ) * ( data.countZ - 1 ); + data.materialIndices = (uint8_t*)b3Alloc( materialCount * sizeof( uint8_t ) ); + + for ( int i = 0; i < materialCount; ++i ) + { + int materialIndex; + if ( B3_FILE_SCAN( file, "%d", &materialIndex ) != 1 ) + { + b3Free( data.heights, heightCount * sizeof( float ) ); + b3Free( data.materialIndices, materialCount * sizeof( uint8_t ) ); + fclose( file ); + return NULL; + } + data.materialIndices[i] = (uint8_t)materialIndex; + } + + fclose( file ); + + // Create height field from loaded data + b3HeightField* heightField = b3CreateHeightField( &data ); + + // Clean up temporary allocations + b3Free( data.heights, heightCount * sizeof( float ) ); + b3Free( data.materialIndices, materialCount * sizeof( uint8_t ) ); + + return heightField; +} diff --git a/src/hull.c b/src/hull.c new file mode 100644 index 0000000..47f0d39 --- /dev/null +++ b/src/hull.c @@ -0,0 +1,2910 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +// Dirk Gregorius contributed portions of this code + +#include "algorithm.h" +#include "math_internal.h" +#include "shape.h" + +#include "box3d/collision.h" +#include "box3d/constants.h" +#include "box3d/math_functions.h" + +#include +#include +#include +#include +#include +#include + +#define B3_AXIS_X 0 +#define B3_AXIS_Y 1 +#define B3_AXIS_Z 2 + +#define B3_MARK_VISIBLE 0 +#define B3_MARK_DELETE 1 + +// Final hull is index-encoded with uint8_t, so vertex/edge/face counts are capped at UINT8_MAX. +#define B3_HULL_LIMIT UINT8_MAX + +typedef struct b3QHListNode +{ + struct b3QHListNode* prev; + struct b3QHListNode* next; +} b3QHListNode; + +typedef struct b3QHFace b3QHFace; + +typedef struct b3QHVertex +{ + // Intrusive list link. Must be first so (b3QHVertex*)nodePtr is valid. + b3QHListNode link; + + b3QHFace* conflictFace; + b3Vec3 position; + + // Index in the finalized hull, stamped during emit. B3_NULL_INDEX until then. + int finalIndex; + bool reachable; +} b3QHVertex; + +typedef struct b3QHHalfEdge +{ + // Edge ring (CCW) around the owning face. Not an external list. + struct b3QHHalfEdge* prev; + struct b3QHHalfEdge* next; + + b3QHVertex* origin; + b3QHFace* face; + struct b3QHHalfEdge* twin; + + // Index in the finalized hull, stamped during emit. B3_NULL_INDEX until then. + int finalIndex; +} b3QHHalfEdge; + +struct b3QHFace +{ + // Intrusive list link. Must be first so (b3QHFace*)nodePtr is valid. + b3QHListNode link; + + b3QHHalfEdge* edge; + + int mark; + float area; + b3Plane plane; + b3Vec3 centroid; + float maxConflictDistance; + + // Sentinel head for this face's conflict list of b3QHVertex. + b3QHVertex conflictListHead; + + // Cached farthest conflict vertex (above b3HullBuilder::minOutside). + // NULL when no conflict above threshold; maxConflictDistance is then minOutside. + b3QHVertex* maxConflict; + + // Index in the finalized hull, stamped during emit. B3_NULL_INDEX until then. + int finalIndex; + bool flipped; +}; + +// One frame of the iterative horizon DFS. Replaces a recursive call to b3HullBuilder_BuildHorizon. +typedef struct b3HorizonFrame +{ + b3QHFace* face; + b3QHHalfEdge* startEdge; // ring termination sentinel + b3QHHalfEdge* edge; // next edge to process + bool started; // false until the first edge of this ring has been processed +} b3HorizonFrame; + +// All working memory for one hull build, carved from a single b3Alloc block. +typedef struct b3HullBuilder +{ + float tolerance; + float minRadius; + float minOutside; + + b3Vec3 interiorPoint; + + // List sentinels. Only the link is meaningful; other fields are unused. + b3QHVertex orphanedList; + b3QHVertex vertexList; + b3QHFace faceList; + + // Bump-allocated pools with pointer-based free lists for faces and edges. + b3QHVertex* vertexBase; + int vertexCapacity; + int vertexCount; + + b3QHHalfEdge* edgeBase; + int edgeCapacity; + int edgeCount; + b3QHHalfEdge* edgeFreeHead; // LIFO free list; overlays edge->next + + b3QHFace* faceBase; + int faceCapacity; + int faceCount; + b3QHFace* faceFreeHead; // LIFO free list; overlays face->link.next + + // Reusable scratch buffers. + b3QHHalfEdge** horizon; + int horizonCapacity; + int horizonCount; + + b3QHFace** cone; + int coneCapacity; + int coneCount; + + b3QHFace** mergedFaces; + int mergedFacesCapacity; + int mergedFacesCount; + + // DFS stack used by the iterative b3HullBuilder_BuildHorizon. Depth bounded by live faces. + b3HorizonFrame* horizonStack; + int horizonStackCapacity; + + // Final counts of the constructed hull (vertexList / faceList / half-edges around faces). + // Populated by CleanHull; zero until then. + int finalVertexCount; + int finalHalfEdgeCount; + int finalFaceCount; +} b3HullBuilder; + +static inline void b3QHList_Init( b3QHListNode* head ) +{ + head->prev = head; + head->next = head; +} + +static inline bool b3QHList_Empty( const b3QHListNode* head ) +{ + return head->next == head; +} + +static inline bool b3QHList_Contains( const b3QHListNode* node ) +{ + return node->prev != NULL && node->next != NULL; +} + +// Insert node before `where`. +static inline void b3QHList_Insert( b3QHListNode* node, b3QHListNode* where ) +{ + B3_ASSERT( !b3QHList_Contains( node ) && b3QHList_Contains( where ) ); + + node->prev = where->prev; + node->next = where; + + node->prev->next = node; + node->next->prev = node; +} + +static inline void b3QHList_Remove( b3QHListNode* node ) +{ + B3_ASSERT( b3QHList_Contains( node ) ); + + node->prev->next = node->next; + node->next->prev = node->prev; + + node->prev = NULL; + node->next = NULL; +} + +static inline void b3QHList_PushBack( b3QHListNode* head, b3QHListNode* node ) +{ + b3QHList_Insert( node, head->prev ); +} + +static b3QHVertex* b3HullBuilder_NewVertex( b3HullBuilder* b, b3Vec3 position) +{ + B3_ASSERT( b->vertexCount < b->vertexCapacity ); + b3QHVertex* vertex = b->vertexBase + b->vertexCount++; + + vertex->link.prev = NULL; + vertex->link.next = NULL; + vertex->conflictFace = NULL; + vertex->position = position; + vertex->finalIndex = B3_NULL_INDEX; + vertex->reachable = false; + + return vertex; +} + +static b3QHHalfEdge* b3HullBuilder_NewEdge( b3HullBuilder* b ) +{ + b3QHHalfEdge* edge; + if ( b->edgeFreeHead != NULL ) + { + edge = b->edgeFreeHead; + b->edgeFreeHead = edge->next; + } + else + { + B3_ASSERT( b->edgeCount < b->edgeCapacity ); + edge = b->edgeBase + b->edgeCount++; + } + // All other fields (prev/next/origin/face/twin) are written by NewFace immediately after. + edge->finalIndex = B3_NULL_INDEX; + return edge; +} + +static void b3HullBuilder_RetireEdge( b3HullBuilder* b, b3QHHalfEdge* edge ) +{ + edge->next = b->edgeFreeHead; + b->edgeFreeHead = edge; +} + +static b3QHFace* b3HullBuilder_NewFace( b3HullBuilder* b, b3QHVertex* v1, b3QHVertex* v2, b3QHVertex* v3 ) +{ + b3QHFace* face; + if ( b->faceFreeHead != NULL ) + { + face = b->faceFreeHead; + // link.next was used as free-list pointer; recover next head before we clobber. + b->faceFreeHead = (b3QHFace*)face->link.next; + } + else + { + B3_ASSERT( b->faceCount < b->faceCapacity ); + face = b->faceBase + b->faceCount++; + } + + // link.prev: NULL on retired faces (cleared by Remove); NULL here so PushBack's + // !b3QHList_Contains assert holds for fresh bump slots too. + // link.next: was the free-list pointer on reused slots, now stale; PushBack overwrites. + face->link.prev = NULL; + face->link.next = NULL; + face->maxConflict = NULL; + face->maxConflictDistance = 0.0f; + face->finalIndex = B3_NULL_INDEX; + + b3QHHalfEdge* edge1 = b3HullBuilder_NewEdge( b ); + b3QHHalfEdge* edge2 = b3HullBuilder_NewEdge( b ); + b3QHHalfEdge* edge3 = b3HullBuilder_NewEdge( b ); + + b3Vec3 p1 = v1->position; + b3Vec3 p2 = v2->position; + b3Vec3 p3 = v3->position; + + b3Plane plane; + plane.normal = b3Cross( b3Sub( p2, p1 ), b3Sub( p3, p1 ) ); + float length; + plane.normal = b3GetLengthAndNormalize( &length, plane.normal ); + plane.offset = b3Dot( plane.normal, p1 ); + + float area = 0.5f * length; + + face->edge = edge1; + face->mark = B3_MARK_VISIBLE; + face->area = area; + face->centroid = b3MulSV( 1.0f / 3.0f, b3Add( v1->position, b3Add( v2->position, v3->position ) ) ); + face->plane = plane; + face->flipped = b3PlaneSeparation( plane, b->interiorPoint ) > 0.0f; + b3QHList_Init( &face->conflictListHead.link ); + + edge1->prev = edge3; + edge1->next = edge2; + edge1->origin = v1; + edge1->face = face; + edge1->twin = NULL; + + edge2->prev = edge1; + edge2->next = edge3; + edge2->origin = v2; + edge2->face = face; + edge2->twin = NULL; + + edge3->prev = edge2; + edge3->next = edge1; + edge3->origin = v3; + edge3->face = face; + edge3->twin = NULL; + + return face; +} + +// Remove face from faceList if still linked, clear its edge pointer, then push onto faceFreeHead. +// Uses face->link.next as the free-list next pointer (link.prev stays NULL, so b3QHList_Contains +// returns false on a free slot, as required by the retire-guard in ResolveFaces). +static void b3HullBuilder_RetireFace( b3HullBuilder* b, b3QHFace* face ) +{ + if ( b3QHList_Contains( &face->link ) ) + { + b3QHList_Remove( &face->link ); + } + face->edge = NULL; + // link.prev is already NULL after Remove (or was never set). link.next holds free-list ptr. + face->link.next = (b3QHListNode*)b->faceFreeHead; + b->faceFreeHead = face; +} + +static b3AABB b3BuildBounds( int vertexCount, const b3Vec3* vertices ) +{ + b3AABB bounds = B3_BOUNDS3_EMPTY; + for ( int i = 0; i < vertexCount; ++i ) + { + bounds.lowerBound = b3Min( bounds.lowerBound, vertices[i] ); + bounds.upperBound = b3Max( bounds.upperBound, vertices[i] ); + } + return bounds; +} + +static void b3FindFarthestPointsAlongCardinalAxes( int* index1Out, int* index2Out, float tolerance, int vertexCount, + const b3Vec3* vertexBase ) +{ + *index1Out = B3_NULL_INDEX; + *index2Out = B3_NULL_INDEX; + + b3Vec3 v0 = vertexBase[0]; + b3Vec3 minPt[3] = { v0, v0, v0 }; + b3Vec3 maxPt[3] = { v0, v0, v0 }; + + int minIndex[3] = { 0, 0, 0 }; + int maxIndex[3] = { 0, 0, 0 }; + + for ( int i = 1; i < vertexCount; ++i ) + { + b3Vec3 v = vertexBase[i]; + + if ( v.x < minPt[B3_AXIS_X].x ) + { + minPt[B3_AXIS_X] = v; + minIndex[B3_AXIS_X] = i; + } + else if ( v.x > maxPt[B3_AXIS_X].x ) + { + maxPt[B3_AXIS_X] = v; + maxIndex[B3_AXIS_X] = i; + } + + if ( v.y < minPt[B3_AXIS_Y].y ) + { + minPt[B3_AXIS_Y] = v; + minIndex[B3_AXIS_Y] = i; + } + else if ( v.y > maxPt[B3_AXIS_Y].y ) + { + maxPt[B3_AXIS_Y] = v; + maxIndex[B3_AXIS_Y] = i; + } + + if ( v.z < minPt[B3_AXIS_Z].z ) + { + minPt[B3_AXIS_Z] = v; + minIndex[B3_AXIS_Z] = i; + } + else if ( v.z > maxPt[B3_AXIS_Z].z ) + { + maxPt[B3_AXIS_Z] = v; + maxIndex[B3_AXIS_Z] = i; + } + } + + b3Vec3 distance; + distance.x = maxPt[B3_AXIS_X].x - minPt[B3_AXIS_X].x; + distance.y = maxPt[B3_AXIS_Y].y - minPt[B3_AXIS_Y].y; + distance.z = maxPt[B3_AXIS_Z].z - minPt[B3_AXIS_Z].z; + + float distanceArray[3] = { distance.x, distance.y, distance.z }; + int maxElement = b3MaxElementIndex( distance ); + + if ( distanceArray[maxElement] > 2.0f * tolerance ) + { + *index1Out = minIndex[maxElement]; + *index2Out = maxIndex[maxElement]; + } +} + +static int b3FindFarthestPointFromLine( int index1, int index2, float tolerance, int vertexCount, const b3Vec3* vertexBase ) +{ + b3Vec3 a = vertexBase[index1]; + b3Vec3 b = vertexBase[index2]; + + // |ap x ab|^2 / |ab|^2 is the squared perpendicular distance from p to the line. + // Compares against (2 * tolerance)^2 + b3Vec3 ab = b3Sub( b, a ); + float abLengthSqr = b3Dot( ab, ab ); + B3_ASSERT( abLengthSqr > 0.0f ); + + float invAbLengthSqr = 1.0f / abLengthSqr; + float maxDistanceSqr = 4.0f * tolerance * tolerance; + int maxIndex = B3_NULL_INDEX; + + for ( int i = 0; i < vertexCount; ++i ) + { + if ( i == index1 || i == index2 ) + { + continue; + } + + b3Vec3 ap = b3Sub( vertexBase[i], a ); + b3Vec3 cross = b3Cross( ap, ab ); + float distanceSqr = b3Dot( cross, cross ) * invAbLengthSqr; + if ( distanceSqr > maxDistanceSqr ) + { + maxDistanceSqr = distanceSqr; + maxIndex = i; + } + } + + return maxIndex; +} + +static int b3FindFarthestPointFromPlane( int index1, int index2, int index3, float tolerance, int vertexCount, + const b3Vec3* vertexBase ) +{ + b3Vec3 a = vertexBase[index1]; + b3Vec3 b = vertexBase[index2]; + b3Vec3 c = vertexBase[index3]; + + b3Plane plane = b3MakePlaneFromPoints( a, b, c ); + + float maxDistance = 2.0f * tolerance; + int maxIndex = B3_NULL_INDEX; + + for ( int i = 0; i < vertexCount; ++i ) + { + if ( i == index1 || i == index2 || i == index3 ) + { + continue; + } + + float distance = b3AbsFloat( b3PlaneSeparation( plane, vertexBase[i] ) ); + if ( distance > maxDistance ) + { + maxDistance = distance; + maxIndex = i; + } + } + + return maxIndex; +} + +static bool b3IsEdgeConvex( const b3QHHalfEdge* edge, float tolerance ) +{ + float distance = b3PlaneSeparation( edge->face->plane, edge->twin->face->centroid ); + return distance < -tolerance; +} + +static bool b3IsEdgeConcave( const b3QHHalfEdge* edge, float tolerance ) +{ + float distance = b3PlaneSeparation( edge->face->plane, edge->twin->face->centroid ); + return distance > tolerance; +} + +static int b3VertexCountOfFace( const b3QHFace* face ) +{ + int count = 0; + const b3QHHalfEdge* edge = face->edge; + do + { + count++; + edge = edge->next; + } + while ( edge != face->edge ); + + return count; +} + +static void b3LinkFace( b3QHFace* face, int index, b3QHHalfEdge* twin ) +{ + B3_ASSERT( face != twin->face ); + + b3QHHalfEdge* edge = face->edge; + while ( index-- > 0 ) + { + B3_ASSERT( edge->face == face ); + edge = edge->next; + } + + B3_ASSERT( edge != twin ); + edge->twin = twin; + twin->twin = edge; +} + +static void b3LinkFaces( b3QHFace* face1, int index1, b3QHFace* face2, int index2 ) +{ + B3_ASSERT( face1 != face2 ); + + b3QHHalfEdge* edge1 = face1->edge; + while ( index1-- > 0 ) + { + edge1 = edge1->next; + } + + b3QHHalfEdge* edge2 = face2->edge; + while ( index2-- > 0 ) + { + edge2 = edge2->next; + } + + B3_ASSERT( edge1 != edge2 ); + edge1->twin = edge2; + edge2->twin = edge1; +} + +static void b3NewellPlane( b3QHFace* face ) +{ + int count = 0; + b3Vec3 centroid = b3Vec3_zero; + b3Vec3 normal = b3Vec3_zero; + + b3QHHalfEdge* edge = face->edge; + B3_ASSERT( edge->face == face ); + + // Use the first vertex as the origin to reduce round-off + b3Vec3 origin = edge->origin->position; + + do + { + b3QHHalfEdge* twin = edge->twin; + B3_ASSERT( twin->twin == edge ); + + b3Vec3 v1 = b3Sub( edge->origin->position, origin ); + b3Vec3 v2 = b3Sub( twin->origin->position, origin ); + + count++; + centroid = b3Add( centroid, v1 ); + normal.x += ( v1.y - v2.y ) * ( v1.z + v2.z ); + normal.y += ( v1.z - v2.z ) * ( v1.x + v2.x ); + normal.z += ( v1.x - v2.x ) * ( v1.y + v2.y ); + + edge = edge->next; + } + while ( edge != face->edge ); + + B3_ASSERT( count > 0 ); + centroid = b3MulSV( 1.0f / (float)count, centroid ); + centroid = b3Add( centroid, origin ); + + float length = b3Length( normal ); + B3_VALIDATE( length > 0.0f ); + normal = b3MulSV( 1.0f / length, normal ); + + face->centroid = centroid; + face->plane = b3MakePlaneFromNormalAndPoint( normal, centroid ); + face->area = 0.5f * length; +} + +#if B3_DEBUG +static bool b3CheckConsistency( const b3QHFace* face ) +{ + if ( face->mark == B3_MARK_DELETE ) + { + return false; + } + + if ( b3VertexCountOfFace( face ) < 3 ) + { + return false; + } + + const b3QHHalfEdge* edge = face->edge; + + do + { + const b3QHHalfEdge* twin = edge->twin; + + if ( twin == NULL ) + { + return false; + } + if ( twin->face == NULL ) + { + return false; + } + if ( twin->face == face ) + { + return false; + } + if ( twin->face->mark == B3_MARK_DELETE ) + { + return false; + } + if ( twin->twin != edge ) + { + return false; + } + if ( edge->next->origin != twin->origin ) + { + return false; + } + if ( edge->origin != twin->next->origin ) + { + return false; + } + if ( edge->face != face ) + { + return false; + } + + edge = edge->next; + } + while ( edge != face->edge ); + + return true; +} +#endif + +static void b3HullBuilder_ComputeTolerance( b3HullBuilder* b, int pointCount, const b3Vec3* points ) +{ + b3AABB bounds = b3BuildBounds( pointCount, points ); + b3Vec3 maxAbs = b3Max( b3Abs( bounds.lowerBound ), b3Abs( bounds.upperBound ) ); + + float maxSum = maxAbs.x + maxAbs.y + maxAbs.z; + float maxCoord = b3MaxFloat( maxAbs.x, b3MaxFloat( maxAbs.y, maxAbs.z ) ); + float maxDistance = b3MinFloat( B3_SQRT3 * maxCoord, maxSum ); + + float tolerance = ( 3.0f * maxDistance * 1.01f + maxCoord ) * FLT_EPSILON; + + b->tolerance = tolerance; + b->minRadius = 4.0f * b->tolerance; + b->minOutside = 2.0f * b->minRadius; + B3_ASSERT( b->minRadius < b->minOutside + 3.0f * FLT_EPSILON ); +} + +static bool b3HullBuilder_BuildInitialHull( b3HullBuilder* b, int pointCount, const b3Vec3* points ) +{ + int index1, index2; + b3FindFarthestPointsAlongCardinalAxes( &index1, &index2, b->tolerance, pointCount, points ); + if ( index1 < 0 || index2 < 0 ) + { + return false; + } + + int index3 = b3FindFarthestPointFromLine( index1, index2, b->tolerance, pointCount, points ); + if ( index3 < 0 ) + { + return false; + } + + int index4 = b3FindFarthestPointFromPlane( index1, index2, index3, b->tolerance, pointCount, points ); + if ( index4 < 0 ) + { + return false; + } + + b3Vec3 v1 = b3Sub( points[index1], points[index4] ); + b3Vec3 v2 = b3Sub( points[index2], points[index4] ); + b3Vec3 v3 = b3Sub( points[index3], points[index4] ); + + if ( b3ScalarTripleProduct( v1, v2, v3 ) < 0.0f ) + { + int temp = index2; + index2 = index3; + index3 = temp; + } + + b->interiorPoint = b3Vec3_zero; + b->interiorPoint = b3Add( b->interiorPoint, points[index1] ); + b->interiorPoint = b3Add( b->interiorPoint, points[index2] ); + b->interiorPoint = b3Add( b->interiorPoint, points[index3] ); + b->interiorPoint = b3Add( b->interiorPoint, points[index4] ); + b->interiorPoint = b3MulSV( 0.25f, b->interiorPoint ); + + b3QHVertex* vertex1 = b3HullBuilder_NewVertex( b, points[index1] ); + b3QHList_PushBack( &b->vertexList.link, &vertex1->link ); + b3QHVertex* vertex2 = b3HullBuilder_NewVertex( b, points[index2] ); + b3QHList_PushBack( &b->vertexList.link, &vertex2->link ); + b3QHVertex* vertex3 = b3HullBuilder_NewVertex( b, points[index3] ); + b3QHList_PushBack( &b->vertexList.link, &vertex3->link ); + b3QHVertex* vertex4 = b3HullBuilder_NewVertex( b, points[index4] ); + b3QHList_PushBack( &b->vertexList.link, &vertex4->link ); + + b3QHFace* face1 = b3HullBuilder_NewFace( b, vertex1, vertex2, vertex3 ); + b3QHList_PushBack( &b->faceList.link, &face1->link ); + b3QHFace* face2 = b3HullBuilder_NewFace( b, vertex4, vertex2, vertex1 ); + b3QHList_PushBack( &b->faceList.link, &face2->link ); + b3QHFace* face3 = b3HullBuilder_NewFace( b, vertex4, vertex3, vertex2 ); + b3QHList_PushBack( &b->faceList.link, &face3->link ); + b3QHFace* face4 = b3HullBuilder_NewFace( b, vertex4, vertex1, vertex3 ); + b3QHList_PushBack( &b->faceList.link, &face4->link ); + + b3LinkFaces( face1, 0, face2, 1 ); + b3LinkFaces( face1, 1, face3, 1 ); + b3LinkFaces( face1, 2, face4, 1 ); + + b3LinkFaces( face2, 0, face3, 2 ); + b3LinkFaces( face3, 0, face4, 2 ); + b3LinkFaces( face4, 0, face2, 2 ); + +#if B3_DEBUG + B3_ASSERT( b3CheckConsistency( face1 ) ); + B3_ASSERT( b3CheckConsistency( face2 ) ); + B3_ASSERT( b3CheckConsistency( face3 ) ); + B3_ASSERT( b3CheckConsistency( face4 ) ); +#endif + + for ( int index = 0; index < pointCount; ++index ) + { + if ( index == index1 || index == index2 || index == index3 || index == index4 ) + { + continue; + } + + b3Vec3 point = points[index]; + + float maxDistance = b->minOutside; + b3QHFace* maxFace = NULL; + + for ( b3QHListNode* node = b->faceList.link.next; node != &b->faceList.link; node = node->next ) + { + b3QHFace* face = (b3QHFace*)node; + float distance = b3PlaneSeparation( face->plane, point ); + if ( distance > maxDistance ) + { + maxDistance = distance; + maxFace = face; + } + } + + if ( maxFace != NULL ) + { + b3QHVertex* vertex = b3HullBuilder_NewVertex( b, point ); + vertex->conflictFace = maxFace; + b3QHList_PushBack( &maxFace->conflictListHead.link, &vertex->link ); + if ( maxDistance > maxFace->maxConflictDistance ) + { + maxFace->maxConflictDistance = maxDistance; + maxFace->maxConflict = vertex; + } + } + } + + return true; +} + +// Recompute the farthest-conflict cache after a face's plane changes. +// Walks the existing conflict list once; cost is bounded by that list, not the global pool. +static void b3HullBuilder_RecacheConflicts( b3QHFace* face, float minOutside ) +{ + b3QHVertex* maxVertex = NULL; + float maxDistance = minOutside; + + for ( b3QHListNode* node = face->conflictListHead.link.next; node != &face->conflictListHead.link; node = node->next ) + { + b3QHVertex* vertex = (b3QHVertex*)node; + float distance = b3PlaneSeparation( face->plane, vertex->position ); + if ( distance > maxDistance ) + { + maxDistance = distance; + maxVertex = vertex; + } + } + + face->maxConflict = maxVertex; + face->maxConflictDistance = maxDistance; +} + +static b3QHVertex* b3HullBuilder_NextConflictVertex( const b3HullBuilder* b ) +{ + b3QHVertex* maxVertex = NULL; + float maxDistance = b->minOutside; + + for ( const b3QHListNode* faceNode = b->faceList.link.next; faceNode != &b->faceList.link; faceNode = faceNode->next ) + { + const b3QHFace* face = (const b3QHFace*)faceNode; + if ( face->maxConflict != NULL && face->maxConflictDistance > maxDistance ) + { + maxDistance = face->maxConflictDistance; + maxVertex = face->maxConflict; + } + } + + return maxVertex; +} + +// Move every conflict vertex of `face` onto the orphaned list and clear their conflictFace. +static void b3HullBuilder_DrainConflictList( b3HullBuilder* b, b3QHFace* face ) +{ + b3QHListNode* node = face->conflictListHead.link.next; + while ( node != &face->conflictListHead.link ) + { + b3QHVertex* orphan = (b3QHVertex*)node; + node = node->next; + + orphan->conflictFace = NULL; + b3QHList_Remove( &orphan->link ); + b3QHList_PushBack( &b->orphanedList.link, &orphan->link ); + } + B3_ASSERT( b3QHList_Empty( &face->conflictListHead.link ) ); +} + +// Mark a face for deletion, drain its conflict list, and populate a fresh DFS frame for it. +// `entryEdge` is the half-edge in `face` whose twin lies in the just-deleted parent face, or +// NULL for the seed. The frame skips `entryEdge` on recursive entries (it would be ignored +// anyway since the parent's mark is now DELETE, but skipping saves one iteration). +static void b3HullBuilder_EnterHorizonFace( b3HullBuilder* b, b3QHFace* face, b3QHHalfEdge* entryEdge, + b3HorizonFrame* frameOut ) +{ + face->mark = B3_MARK_DELETE; + b3HullBuilder_DrainConflictList( b, face ); + + frameOut->face = face; + frameOut->started = false; + if ( entryEdge != NULL ) + { + frameOut->startEdge = entryEdge; + frameOut->edge = entryEdge->next; + } + else + { + frameOut->startEdge = face->edge; + frameOut->edge = face->edge; + } +} + +static void b3HullBuilder_BuildHorizon( b3HullBuilder* b, b3QHVertex* apex, b3QHFace* seed ) +{ + b3HorizonFrame* stack = b->horizonStack; + int top = 0; + + B3_ASSERT( top < b->horizonStackCapacity ); + b3HullBuilder_EnterHorizonFace( b, seed, NULL, &stack[top++] ); + + while ( top > 0 ) + { + b3HorizonFrame* f = &stack[top - 1]; + + if ( f->started && f->edge == f->startEdge ) + { + top--; + continue; + } + f->started = true; + + b3QHHalfEdge* edge = f->edge; + b3QHHalfEdge* twin = edge->twin; + f->edge = edge->next; + + if ( twin->face->mark != B3_MARK_VISIBLE ) + { + continue; + } + + float distance = b3PlaneSeparation( twin->face->plane, apex->position ); + if ( distance > b->minRadius ) + { + B3_ASSERT( top < b->horizonStackCapacity ); + b3HullBuilder_EnterHorizonFace( b, twin->face, twin, &stack[top++] ); + } + else + { + B3_ASSERT( b->horizonCount < b->horizonCapacity ); + b->horizon[b->horizonCount++] = edge; + } + } +} + +static void b3HullBuilder_BuildCone( b3HullBuilder* b, b3QHVertex* apex ) +{ + for ( int i = 0; i < b->horizonCount; ++i ) + { + b3QHHalfEdge* edge = b->horizon[i]; + B3_ASSERT( edge->twin->twin == edge ); + + b3QHFace* face = b3HullBuilder_NewFace( b, apex, edge->origin, edge->twin->origin ); + B3_ASSERT( b->coneCount < b->coneCapacity ); + b->cone[b->coneCount++] = face; + + b3LinkFace( face, 1, edge->twin ); + } + + b3QHFace* face1 = b->cone[b->coneCount - 1]; + for ( int i = 0; i < b->coneCount; ++i ) + { + b3QHFace* face2 = b->cone[i]; + b3LinkFaces( face1, 2, face2, 0 ); + face1 = face2; + } +} + +// Retire half-edges in the half-open ring range [begin, end) by pushing each onto edgeFreeHead. +// The caller has already detached these edges from the live face ring (rewire happens before +// destroy), so they are unreachable from the live hull. +static void b3HullBuilder_DestroyEdges( b3HullBuilder* b, b3QHHalfEdge* begin, b3QHHalfEdge* end ) +{ + b3QHHalfEdge* edge = begin; + while ( edge != end ) + { + b3QHHalfEdge* next = edge->next; + b3HullBuilder_RetireEdge( b, edge ); + edge = next; + } +} + +static void b3HullBuilder_ConnectEdges( b3HullBuilder* b, b3QHHalfEdge* prev, b3QHHalfEdge* next ) +{ + B3_ASSERT( prev != next ); + B3_ASSERT( prev->face == next->face ); + + // If both shared neighbors are the same face, prev and next together would orphan that face. + if ( prev->twin->face == next->twin->face ) + { + // next is redundant. + if ( next->face->edge == next ) + { + next->face->edge = prev; + } + + b3QHHalfEdge* twin; + if ( b3VertexCountOfFace( prev->twin->face ) == 3 ) + { + // Capture all 3 half-edges of the dead triangle before the rewire overwrites prev->twin. + b3QHHalfEdge* deadEdge0 = prev->twin; // prev->twin (will be rewired below) + b3QHHalfEdge* deadEdge1 = next->twin; // next->twin + b3QHHalfEdge* deadEdge2 = next->twin->prev; // third edge of the dead triangle + + twin = deadEdge2->twin; + B3_ASSERT( twin->face->mark != B3_MARK_DELETE ); + + b3QHFace* opposingFace = prev->twin->face; + opposingFace->mark = B3_MARK_DELETE; + B3_ASSERT( b->mergedFacesCount < b->mergedFacesCapacity ); + b->mergedFaces[b->mergedFacesCount++] = opposingFace; + + prev->next = next->next; + prev->next->prev = prev; + + prev->twin = twin; + twin->twin = prev; + + // Drop the redundant vertex (slot abandoned in the bump allocator). + b3QHList_Remove( &next->origin->link ); + + // Retire the 3 half-edges of the dead triangle now that the rewire is complete. + b3HullBuilder_RetireEdge( b, deadEdge0 ); + b3HullBuilder_RetireEdge( b, deadEdge1 ); + b3HullBuilder_RetireEdge( b, deadEdge2 ); + } + else + { + twin = next->twin; + + if ( twin->face->edge == prev->twin ) + { + twin->face->edge = twin; + } + + twin->next = prev->twin->next; + twin->next->prev = twin; + // prev->twin slot is retired to the edge free list. + b3HullBuilder_RetireEdge( b, prev->twin ); + + prev->next = next->next; + prev->next->prev = prev; + + prev->twin = twin; + twin->twin = prev; + + // Drop the redundant vertex (slot abandoned in the bump allocator). + b3QHList_Remove( &next->origin->link ); + } + + // Twin->face changed shape; recompute its plane and refresh its cached max conflict. + b3NewellPlane( twin->face ); + b3HullBuilder_RecacheConflicts( twin->face, b->minOutside ); + } + else + { + prev->next = next; + next->prev = prev; + } +} + + +static void b3HullBuilder_AbsorbFaces( b3HullBuilder* b, b3QHFace* face ) +{ + for ( int i = 0; i < b->mergedFacesCount; ++i ) + { + B3_ASSERT( b->mergedFaces[i]->mark == B3_MARK_DELETE ); + b3QHListNode* head = &b->mergedFaces[i]->conflictListHead.link; + + b3QHListNode* node = head->next; + while ( node != head ) + { + b3QHVertex* vertex = (b3QHVertex*)node; + node = node->next; + + b3QHList_Remove( &vertex->link ); + + float distance = b3PlaneSeparation( face->plane, vertex->position ); + if ( distance > b->minOutside ) + { + b3QHList_PushBack( &face->conflictListHead.link, &vertex->link ); + vertex->conflictFace = face; + if ( distance > face->maxConflictDistance ) + { + face->maxConflictDistance = distance; + face->maxConflict = vertex; + } + } + else + { + b3QHList_PushBack( &b->orphanedList.link, &vertex->link ); + vertex->conflictFace = NULL; + } + } + + B3_ASSERT( b3QHList_Empty( head ) ); + + // Conflict list is now drained. Retire this face to the free list. + b3HullBuilder_RetireFace( b, b->mergedFaces[i] ); + } +} + +static void b3HullBuilder_ConnectFaces( b3HullBuilder* b, b3QHHalfEdge* edge ) +{ + b3QHFace* face = edge->face; + + b3QHHalfEdge* twin = edge->twin; + + b3QHHalfEdge* edgePrev = edge->prev; + b3QHHalfEdge* edgeNext = edge->next; + b3QHHalfEdge* twinPrev = twin->prev; + b3QHHalfEdge* twinNext = twin->next; + + while ( edgePrev->twin->face == twin->face ) + { + B3_ASSERT( edgePrev->twin == twinNext ); + B3_ASSERT( twinNext->twin == edgePrev ); + + edgePrev = edgePrev->prev; + twinNext = twinNext->next; + } + B3_ASSERT( edgePrev->face != twinNext->face ); + + while ( edgeNext->twin->face == twin->face ) + { + B3_ASSERT( edgeNext->twin == twinPrev ); + B3_ASSERT( twinPrev->twin == edgeNext ); + + edgeNext = edgeNext->next; + twinPrev = twinPrev->prev; + } + B3_ASSERT( edgeNext->face != twinPrev->face ); + + face->edge = edgePrev; + + // Discard opposing face. mergedFaces is single-buffered: ConnectFaces does not nest. + b->mergedFacesCount = 0; + B3_ASSERT( b->mergedFacesCount < b->mergedFacesCapacity ); + b->mergedFaces[b->mergedFacesCount++] = twin->face; + twin->face->mark = B3_MARK_DELETE; + twin->face->edge = NULL; + + for ( b3QHHalfEdge* absorbed = twinNext; absorbed != twinPrev->next; absorbed = absorbed->next ) + { + absorbed->face = face; + } + + b3HullBuilder_DestroyEdges( b, edgePrev->next, edgeNext ); + b3HullBuilder_DestroyEdges( b, twinPrev->next, twinNext ); + + b3HullBuilder_ConnectEdges( b, edgePrev, twinNext ); + b3HullBuilder_ConnectEdges( b, twinPrev, edgeNext ); + + b3NewellPlane( face ); + // Existing conflicts now have stale distances under the new plane; AbsorbFaces will then + // add more incrementally and update the cache as it goes. + b3HullBuilder_RecacheConflicts( face, b->minOutside ); +#if B3_DEBUG + B3_ASSERT( b3CheckConsistency( face ) ); +#endif + + b3HullBuilder_AbsorbFaces( b, face ); +} + +static bool b3HullBuilder_MergeConcave( b3HullBuilder* b, b3QHFace* face ) +{ + b3QHHalfEdge* edge = face->edge; + + do + { + b3QHHalfEdge* twin = edge->twin; + + if ( b3IsEdgeConcave( edge, b->minRadius ) || b3IsEdgeConcave( twin, b->minRadius ) ) + { + b3HullBuilder_ConnectFaces( b, edge ); + return true; + } + + edge = edge->next; + } + while ( edge != face->edge ); + + return false; +} + +static bool b3HullBuilder_MergeCoplanar( b3HullBuilder* b, b3QHFace* face ) +{ + b3QHHalfEdge* edge = face->edge; + + do + { + b3QHHalfEdge* twin = edge->twin; + + if ( !b3IsEdgeConvex( edge, b->minRadius ) || !b3IsEdgeConvex( twin, b->minRadius ) ) + { + b3HullBuilder_ConnectFaces( b, edge ); + return true; + } + + edge = edge->next; + } + while ( edge != face->edge ); + + return false; +} + +static void b3HullBuilder_MergeFaces( b3HullBuilder* b ) +{ + for ( int i = 0; i < b->coneCount; ++i ) + { + b3QHFace* face = b->cone[i]; + if ( face->mark == B3_MARK_VISIBLE && face->flipped ) + { + face->flipped = false; + + float bestArea = 0; + b3QHHalfEdge* bestEdge = NULL; + + b3QHHalfEdge* edge = face->edge; + do + { + b3QHHalfEdge* twin = edge->twin; + float area = twin->face->area; + if ( area > bestArea ) + { + bestArea = area; + bestEdge = edge; + } + + edge = edge->next; + } + while ( edge != face->edge ); + + B3_ASSERT( bestEdge != NULL ); + b3HullBuilder_ConnectFaces( b, bestEdge ); + } + } + + for ( int i = 0; i < b->coneCount; ++i ) + { + b3QHFace* face = b->cone[i]; + if ( face->mark == B3_MARK_VISIBLE ) + { + while ( b3HullBuilder_MergeConcave( b, face ) ) + { + } + } + } + + for ( int i = 0; i < b->coneCount; ++i ) + { + b3QHFace* face = b->cone[i]; + if ( face->mark == B3_MARK_VISIBLE ) + { + while ( b3HullBuilder_MergeCoplanar( b, face ) ) + { + } + } + } +} + +static void b3HullBuilder_ResolveVertices( b3HullBuilder* b ) +{ + b3QHListNode* node = b->orphanedList.link.next; + while ( node != &b->orphanedList.link ) + { + b3QHVertex* vertex = (b3QHVertex*)node; + node = node->next; + b3QHList_Remove( &vertex->link ); + + float maxDistance = b->minOutside; + b3QHFace* maxFace = NULL; + + for ( int i = 0; i < b->coneCount; ++i ) + { + if ( b->cone[i]->mark == B3_MARK_VISIBLE ) + { + float distance = b3PlaneSeparation( b->cone[i]->plane, vertex->position ); + if ( distance > maxDistance ) + { + maxDistance = distance; + maxFace = b->cone[i]; + } + } + } + + if ( maxFace != NULL ) + { + B3_ASSERT( maxFace->mark == B3_MARK_VISIBLE ); + b3QHList_PushBack( &maxFace->conflictListHead.link, &vertex->link ); + vertex->conflictFace = maxFace; + if ( maxDistance > maxFace->maxConflictDistance ) + { + maxFace->maxConflictDistance = maxDistance; + maxFace->maxConflict = vertex; + } + } + // Otherwise: vertex is interior to the hull. Its slot in the bump pool is abandoned. + } + + B3_ASSERT( b3QHList_Empty( &b->orphanedList.link ) ); +} + +static void b3HullBuilder_ResolveFaces( b3HullBuilder* b ) +{ + // Splice deleted faces out of the face list. Faces already retired by AbsorbFaces are no + // longer on faceList, so we guard with b3QHList_Contains before removing. + b3QHListNode* node = b->faceList.link.next; + while ( node != &b->faceList.link ) + { + b3QHFace* face = (b3QHFace*)node; + node = node->next; + + if ( face->mark == B3_MARK_DELETE && b3QHList_Contains( &face->link ) ) + { + B3_ASSERT( b3QHList_Empty( &face->conflictListHead.link ) ); + b3QHList_Remove( &face->link ); + } + } + + for ( int i = 0; i < b->coneCount; ++i ) + { + b3QHFace* face = b->cone[i]; + if ( face->mark == B3_MARK_DELETE ) + { + continue; + } + b3QHList_PushBack( &b->faceList.link, &face->link ); + } +} + +static void b3HullBuilder_AddVertexToHull( b3HullBuilder* b, b3QHVertex* vertex ) +{ + b3QHFace* face = vertex->conflictFace; + vertex->conflictFace = NULL; + b3QHList_Remove( &vertex->link ); + b3QHList_PushBack( &b->vertexList.link, &vertex->link ); + + b->horizonCount = 0; + b3HullBuilder_BuildHorizon( b, vertex, face ); + B3_ASSERT( b->horizonCount >= 3 ); + + b->coneCount = 0; + b3HullBuilder_BuildCone( b, vertex ); + B3_ASSERT( b->coneCount >= 3 ); + + b3HullBuilder_MergeFaces( b ); + b3HullBuilder_ResolveVertices( b ); + b3HullBuilder_ResolveFaces( b ); +} + +static void b3HullBuilder_CleanHull( b3HullBuilder* b, b3Vec3 origin ) +{ + int faceCount = 0; + int halfEdgeCount = 0; + + for ( b3QHListNode* faceNode = b->faceList.link.next; faceNode != &b->faceList.link; faceNode = faceNode->next ) + { + b3QHFace* face = (b3QHFace*)faceNode; + b3QHHalfEdge* edge = face->edge; + + do + { + edge->origin->reachable = true; + edge = edge->next; + halfEdgeCount++; + } + while ( edge != face->edge ); + + face->plane.offset += b3Dot( face->plane.normal, origin ); + face->centroid = b3Add( face->centroid, origin ); + faceCount++; + } + + int vertexCount = 0; + b3QHListNode* node = b->vertexList.link.next; + while ( node != &b->vertexList.link ) + { + b3QHVertex* vertex = (b3QHVertex*)node; + node = node->next; + + if ( !vertex->reachable ) + { + b3QHList_Remove( &vertex->link ); + } + else + { + vertex->position = b3Add( vertex->position, origin ); + vertexCount++; + } + } + + b->interiorPoint = b3Add( b->interiorPoint, origin ); + + b->finalVertexCount = vertexCount; + b->finalHalfEdgeCount = halfEdgeCount; + b->finalFaceCount = faceCount; +} + +#if B3_DEBUG +static bool b3HullBuilder_IsConsistent( const b3HullBuilder* b ) +{ + int v = b->finalVertexCount; + int e = b->finalHalfEdgeCount / 2; + int f = b->finalFaceCount; + + if ( v - e + f != 2 ) + { + return false; + } + + for ( const b3QHListNode* faceNode = b->faceList.link.next; faceNode != &b->faceList.link; faceNode = faceNode->next ) + { + const b3QHFace* face = (const b3QHFace*)faceNode; + if ( face->edge->face != face ) + { + return false; + } + + if ( !b3CheckConsistency( face ) ) + { + return false; + } + + if ( b3PlaneSeparation( face->plane, b->interiorPoint ) > 0 ) + { + return false; + } + + if ( face->mark != B3_MARK_VISIBLE ) + { + return false; + } + + const b3QHHalfEdge* edge = face->edge; + + do + { + if ( edge->next->origin != edge->twin->origin ) + { + return false; + } + if ( edge->prev->next != edge ) + { + return false; + } + if ( edge->next->prev != edge ) + { + return false; + } + if ( edge->twin->twin != edge ) + { + return false; + } + if ( edge->face != face ) + { + return false; + } + if ( b3DistanceSquared( edge->origin->position, edge->twin->origin->position ) < 1000.0f * FLT_MIN ) + { + return false; + } + + edge = edge->next; + } + while ( edge != face->edge ); + } + + return true; +} +#endif + +static bool b3HullBuilder_HasHull( const b3HullBuilder* b ) +{ + int v = b->finalVertexCount; + int e = b->finalHalfEdgeCount / 2; + int f = b->finalFaceCount; + return v - e + f == 2 && f >= 4; +} + +// Build the entire hull. Returns true iff the result satisfies Euler's identity. +static bool b3HullBuilder_Construct( b3HullBuilder* b, const b3Vec3* points, int pointCount, int maxVertexCount, b3Vec3 origin, + b3Vec3* shiftedPoints ) +{ + if ( pointCount < 4 ) + { + return false; + } + + for ( int i = 0; i < pointCount; ++i ) + { + shiftedPoints[i] = b3Sub( points[i], origin ); + } + + b3HullBuilder_ComputeTolerance( b, pointCount, shiftedPoints ); + if ( !b3HullBuilder_BuildInitialHull( b, pointCount, shiftedPoints ) ) + { + return false; + } + + int budget = b3ClampInt( maxVertexCount - 4, 0, B3_HULL_LIMIT - 4 ); + + b3QHVertex* vertex = b3HullBuilder_NextConflictVertex( b ); + while ( vertex && budget > 0 ) + { + b3HullBuilder_AddVertexToHull( b, vertex ); + vertex = b3HullBuilder_NextConflictVertex( b ); + budget -= 1; + } + + b3HullBuilder_CleanHull( b, origin ); + +#if B3_DEBUG + B3_ASSERT( b3HullBuilder_IsConsistent( b ) ); +#endif + + return b3HullBuilder_HasHull( b ); +} + +static inline size_t b3AlignUp8( size_t x ) +{ + return ( x + 7u ) & ~(size_t)7u; +} + +typedef struct b3HullWorkSizes +{ + int N; // pointCount + int M; // clamped maxVertexCount, in [4, B3_HULL_LIMIT] + int vertexCapacity; + int edgeCapacity; + int faceCapacity; + int horizonCapacity; + int coneCapacity; + int mergedFacesCapacity; + int horizonStackCapacity; + size_t totalBytes; + + size_t offsetVertex; + size_t offsetEdge; + size_t offsetFace; + size_t offsetHorizon; + size_t offsetCone; + size_t offsetMergedFaces; + size_t offsetHorizonStack; + size_t offsetShiftedPoints; +} b3HullWorkSizes; + +static b3HullWorkSizes b3ComputeHullWorkSizes( int pointCount, int clampedMaxCount ) +{ + b3HullWorkSizes s; + s.N = pointCount; + s.M = clampedMaxCount; + + // Vertices: 4 initial hull vertices + at most one per remaining input point. No free list. + s.vertexCapacity = pointCount + 4; + + // Edges and faces use free-list recycling; capacity is proportional to live hull size. + // edgeCapacity: peak is ~twice live edges plus cone edges; floor 48. + s.edgeCapacity = 24 * s.M - 48; + if ( s.edgeCapacity < 48 ) + { + s.edgeCapacity = 48; + } + + // faceCapacity: peak intermediate state live faces (<=2*M-4) plus full cone (<=3*M-6); floor 16. + s.faceCapacity = 5 * s.M - 10; + if ( s.faceCapacity < 16 ) + { + s.faceCapacity = 16; + } + + // Horizon/cone bounded by current half-edge count; mergedFaces by face count. + s.horizonCapacity = 3 * s.M - 6; + if ( s.horizonCapacity < 6 ) + { + s.horizonCapacity = 6; + } + s.coneCapacity = s.horizonCapacity; + s.mergedFacesCapacity = 2 * s.M - 4; + if ( s.mergedFacesCapacity < 4 ) + { + s.mergedFacesCapacity = 4; + } + + // Horizon DFS depth is bounded by the number of live faces (Euler: <=2*M-4). + s.horizonStackCapacity = 2 * s.M - 4; + if ( s.horizonStackCapacity < 4 ) + { + s.horizonStackCapacity = 4; + } + + size_t offset = 0; + + s.offsetVertex = offset; + offset = b3AlignUp8( offset + (size_t)s.vertexCapacity * sizeof( b3QHVertex ) ); + + s.offsetEdge = offset; + offset = b3AlignUp8( offset + (size_t)s.edgeCapacity * sizeof( b3QHHalfEdge ) ); + + s.offsetFace = offset; + offset = b3AlignUp8( offset + (size_t)s.faceCapacity * sizeof( b3QHFace ) ); + + s.offsetHorizon = offset; + offset = b3AlignUp8( offset + (size_t)s.horizonCapacity * sizeof( b3QHHalfEdge* ) ); + + s.offsetCone = offset; + offset = b3AlignUp8( offset + (size_t)s.coneCapacity * sizeof( b3QHFace* ) ); + + s.offsetMergedFaces = offset; + offset = b3AlignUp8( offset + (size_t)s.mergedFacesCapacity * sizeof( b3QHFace* ) ); + + s.offsetHorizonStack = offset; + offset = b3AlignUp8( offset + (size_t)s.horizonStackCapacity * sizeof( b3HorizonFrame ) ); + + s.offsetShiftedPoints = offset; + offset += (size_t)pointCount * sizeof( b3Vec3 ); + + s.totalBytes = offset; + return s; +} + +static void b3HullBuilder_Init( b3HullBuilder* b, char* mem, const b3HullWorkSizes* s ) +{ + memset( b, 0, sizeof( *b ) ); + b3QHList_Init( &b->orphanedList.link ); + b3QHList_Init( &b->vertexList.link ); + b3QHList_Init( &b->faceList.link ); + + b->vertexBase = (b3QHVertex*)( mem + s->offsetVertex ); + b->vertexCapacity = s->vertexCapacity; + + b->edgeBase = (b3QHHalfEdge*)( mem + s->offsetEdge ); + b->edgeCapacity = s->edgeCapacity; + + b->faceBase = (b3QHFace*)( mem + s->offsetFace ); + b->faceCapacity = s->faceCapacity; + + b->horizon = (b3QHHalfEdge**)( mem + s->offsetHorizon ); + b->horizonCapacity = s->horizonCapacity; + + b->cone = (b3QHFace**)( mem + s->offsetCone ); + b->coneCapacity = s->coneCapacity; + + b->mergedFaces = (b3QHFace**)( mem + s->offsetMergedFaces ); + b->mergedFacesCapacity = s->mergedFacesCapacity; + + b->horizonStack = (b3HorizonFrame*)( mem + s->offsetHorizonStack ); + b->horizonStackCapacity = s->horizonStackCapacity; +} + +static b3Vec3* b3GetHullPointsWrite( b3Hull* hull ) +{ + if ( hull->pointOffset == 0 ) + { + return NULL; + } + return (b3Vec3*)( (intptr_t)hull + hull->pointOffset ); +} + +static b3Plane* b3GetHullPlanesWrite( b3Hull* hull ) +{ + if ( hull->planeOffset == 0 ) + { + return NULL; + } + return (b3Plane*)( (intptr_t)hull + hull->planeOffset ); +} + +static b3HullVertex* b3GetHullVerticesWrite( b3Hull* hull ) +{ + if ( hull->vertexOffset == 0 ) + { + return NULL; + } + return (b3HullVertex*)( (intptr_t)hull + hull->vertexOffset ); +} + +static b3HullHalfEdge* b3GetHullEdgesWrite( b3Hull* hull ) +{ + if ( hull->edgeOffset == 0 ) + { + return NULL; + } + return (b3HullHalfEdge*)( (intptr_t)hull + hull->edgeOffset ); +} + +int b3FindHullSupportVertex( const b3Hull* hull, b3Vec3 direction ) +{ + int bestIndex = B3_NULL_INDEX; + float bestDot = -FLT_MAX; + + int vertexCount = hull->vertexCount; + const b3Vec3* points = b3GetHullPoints( hull ); + + for ( int index = 0; index < vertexCount; ++index ) + { + float dot = b3Dot( direction, points[index] ); + if ( dot > bestDot ) + { + bestIndex = index; + bestDot = dot; + } + } + B3_ASSERT( bestIndex >= 0 ); + + return bestIndex; +} + +int b3FindHullSupportFace( const b3Hull* hull, b3Vec3 direction ) +{ + int bestIndex = B3_NULL_INDEX; + float bestDot = -FLT_MAX; + + int faceCount = hull->faceCount; + const b3Plane* planes = b3GetHullPlanes( hull ); + + for ( int index = 0; index < faceCount; ++index ) + { + float dot = b3Dot( planes[index].normal, direction ); + if ( dot > bestDot ) + { + bestDot = dot; + bestIndex = index; + } + } + B3_ASSERT( bestIndex >= 0 ); + + return bestIndex; +} + +#if B3_ENABLE_VALIDATION + +bool b3IsValidHull( const b3Hull* hull ) +{ + if ( hull->version != B3_HULL_VERSION ) + { + return false; + } + + int v = hull->vertexCount; + int e = hull->edgeCount / 2; + int f = hull->faceCount; + + if ( v - e + f != 2 ) + { + return false; + } + + const b3HullVertex* vertices = b3GetHullVertices( hull ); + const b3HullHalfEdge* edges = b3GetHullEdges( hull ); + for ( int index = 0; index < hull->vertexCount; ++index ) + { + const b3HullVertex* vertex = vertices + index; + const b3HullHalfEdge* edge = edges + vertex->edge; + + if ( edge->origin != index ) + { + return false; + } + } + + for ( int index = 0; index < hull->edgeCount; index += 2 ) + { + const b3HullHalfEdge* edge = edges + index + 0; + const b3HullHalfEdge* twin = edges + index + 1; + + if ( edge->twin != index + 1 ) + { + return false; + } + + if ( twin->twin != index + 0 ) + { + return false; + } + } + + const b3HullFace* faces = b3GetHullFaces( hull ); + const b3Plane* planes = b3GetHullPlanes( hull ); + for ( int faceIndex = 0; faceIndex < hull->faceCount; ++faceIndex ) + { + const b3HullFace* face = faces + faceIndex; + + int baseEdgeIndex = face->edge; + const b3HullHalfEdge* edge = edges + baseEdgeIndex; + + b3Plane plane = planes[faceIndex]; + if ( b3PlaneSeparation( plane, hull->center ) >= 0.0f ) + { + return false; + } + + int edgeIndex = baseEdgeIndex; + do + { + edge = edges + edgeIndex; + const b3HullHalfEdge* next = edges + edge->next; + const b3HullHalfEdge* twin = edges + edge->twin; + + if ( edge->face != faceIndex ) + { + return false; + } + + if ( twin->twin != edgeIndex ) + { + return false; + } + + if ( next->origin != twin->origin ) + { + return false; + } + + edgeIndex = edge->next; + } + while ( edgeIndex != baseEdgeIndex ); + } + + if ( hull->volume <= 0.0f ) + { + return false; + } + + if ( hull->surfaceArea <= 0.0f ) + { + return false; + } + + if ( hull->innerRadius <= 0.0f ) + { + return false; + } + + return true; +} + +#else + +bool b3IsValidHull( const b3Hull* hull ) +{ + B3_UNUSED( hull ); + return true; +} + +#endif + +b3Hull* b3CreateCylinder( float height, float radius, float yOffset, int sides ) +{ + B3_ASSERT( height > 0.0f ); + B3_ASSERT( radius > 0.0f ); + B3_ASSERT( 3 <= sides && sides <= 32 ); + + int pointCount = 2 * sides; + b3Vec3* points = (b3Vec3*)b3Alloc( pointCount * sizeof( b3Vec3 ) ); + B3_ASSERT( points != NULL ); + + float alpha = 0.0f; + float deltaAlpha = 2.0f * B3_PI / sides; + + for ( int index = 0; index < sides; ++index ) + { + float sinAlpha = b3Sin( alpha ); + float cosAlpha = b3Cos( alpha ); + + points[2 * index + 0] = (b3Vec3){ radius * cosAlpha, yOffset, radius * sinAlpha }; + points[2 * index + 1] = (b3Vec3){ radius * cosAlpha, yOffset + height, radius * sinAlpha }; + + alpha += deltaAlpha; + } + + b3Hull* hull = b3CreateHull( points, pointCount, pointCount ); + B3_ASSERT( hull->vertexCount == pointCount ); + B3_ASSERT( hull->edgeCount == 6 * sides ); + B3_ASSERT( hull->faceCount == sides + 2 ); + + b3Free( points, pointCount * sizeof( b3Vec3 ) ); + + return hull; +} + +b3Hull* b3CreateCone( float height, float radius1, float radius2, int slices ) +{ + B3_ASSERT( height > 0.0f ); + B3_ASSERT( radius1 > 0.0f ); + B3_ASSERT( radius2 > 0.0f ); + B3_ASSERT( 4 <= slices && slices <= 32 ); + + int pointCount = 2 * slices; + b3Vec3* points = (b3Vec3*)b3Alloc( pointCount * sizeof( b3Vec3 ) ); + B3_ASSERT( points != NULL ); + + float alpha = 0.0f; + float deltaAlpha = 2.0f * B3_PI / slices; + + for ( int index = 0; index < slices; ++index ) + { + float sinAlpha = b3Sin( alpha ); + float cosAlpha = b3Cos( alpha ); + + points[2 * index + 0] = (b3Vec3){ radius1 * cosAlpha, 0.0f, radius1 * sinAlpha }; + points[2 * index + 1] = (b3Vec3){ radius2 * cosAlpha, height, radius2 * sinAlpha }; + + alpha += deltaAlpha; + } + + b3Hull* hull = b3CreateHull( points, pointCount, pointCount ); + B3_ASSERT( hull->vertexCount == pointCount ); + B3_ASSERT( hull->edgeCount == 6 * slices ); + B3_ASSERT( hull->faceCount == slices + 2 ); + + b3Free( points, pointCount * sizeof( b3Vec3 ) ); + + return hull; +} + +static void b3UpdateHullBounds( b3Hull* hull ) +{ + const b3Vec3* points = b3GetHullPoints( hull ); + int vertexCount = hull->vertexCount; + + B3_ASSERT( vertexCount > 0 ); + b3AABB bounds; + bounds.lowerBound = points[0]; + bounds.upperBound = points[0]; + + for ( int i = 1; i < vertexCount; ++i ) + { + b3Vec3 p = points[i]; + bounds.lowerBound = b3Min( bounds.lowerBound, p ); + bounds.upperBound = b3Max( bounds.upperBound, p ); + } + + hull->aabb = bounds; +} + +// M. Kallay - "Computing the Moment of Inertia of a Solid Defined by a Triangle Mesh" +static bool b3UpdateHullBulkProperties( b3Hull* hull ) +{ + const b3Vec3* points = b3GetHullPoints( hull ); + const b3HullFace* faces = b3GetHullFaces( hull ); + const b3HullHalfEdge* edges = b3GetHullEdges( hull ); + const b3Plane* planes = b3GetHullPlanes( hull ); + + float area = 0.0f; + float volume = 0.0f; + b3Vec3 center = b3Vec3_zero; + + // Use the first vertex to reduce round-off errors. + b3Vec3 origin = points[0]; + + float xx = 0.0f; + float xy = 0.0f; + float yy = 0.0f; + float xz = 0.0f; + float zz = 0.0f; + float yz = 0.0f; + + int faceCount = hull->faceCount; + + for ( int faceIndex = 0; faceIndex < faceCount; ++faceIndex ) + { + const b3HullFace* face = faces + faceIndex; + const b3HullHalfEdge* edge1 = edges + face->edge; + const b3HullHalfEdge* edge2 = edges + edge1->next; + const b3HullHalfEdge* edge3 = edges + edge2->next; + + B3_ASSERT( edge1 != edge3 ); + B3_ASSERT( edge1->origin < hull->vertexCount ); + + b3Vec3 v1 = b3Sub( points[edge1->origin], origin ); + + do + { + B3_ASSERT( edge2->origin < hull->vertexCount ); + B3_ASSERT( edge3->origin < hull->vertexCount ); + + b3Vec3 v2 = b3Sub( points[edge2->origin], origin ); + b3Vec3 v3 = b3Sub( points[edge3->origin], origin ); + + area += b3Length( b3Cross( b3Sub( v2, v1 ), b3Sub( v3, v1 ) ) ); + + float det = b3ScalarTripleProduct( v1, v2, v3 ); + + volume += det; + + b3Vec3 v4 = b3Add( v1, b3Add( v2, v3 ) ); + center = b3Add( center, b3MulSV( det, v4 ) ); + + xx += det * ( v1.x * v1.x + v2.x * v2.x + v3.x * v3.x + v4.x * v4.x ); + yy += det * ( v1.y * v1.y + v2.y * v2.y + v3.y * v3.y + v4.y * v4.y ); + zz += det * ( v1.z * v1.z + v2.z * v2.z + v3.z * v3.z + v4.z * v4.z ); + xy += det * ( v1.x * v1.y + v2.x * v2.y + v3.x * v3.y + v4.x * v4.y ); + xz += det * ( v1.x * v1.z + v2.x * v2.z + v3.x * v3.z + v4.x * v4.z ); + yz += det * ( v1.y * v1.z + v2.y * v2.z + v3.y * v3.z + v4.y * v4.z ); + + edge2 = edge3; + edge3 = edges + edge3->next; + } + while ( edge1 != edge3 ); + } + + B3_VALIDATE( volume > 0.0f ); + + b3Vec3 localCenter = volume > 0.0f ? b3MulSV( 0.25f / volume, center ) : b3Vec3_zero; + center = b3Add( localCenter, origin ); + + float radius = FLT_MAX; + for ( int faceIndex = 0; faceIndex < faceCount; ++faceIndex ) + { + b3Plane plane = planes[faceIndex]; + float distance = b3PlaneSeparation( plane, center ); + B3_VALIDATE( distance < 0.0f ); + + radius = b3MinFloat( radius, -distance ); + } + + B3_VALIDATE( 0.0f < radius && radius < FLT_MAX ); + + b3Matrix3 inertia; + inertia.cx.x = yy + zz; + inertia.cy.x = -xy; + inertia.cz.x = -xz; + inertia.cx.y = -xy; + inertia.cy.y = xx + zz; + inertia.cz.y = -yz; + inertia.cx.z = -xz; + inertia.cy.z = -yz; + inertia.cz.z = xx + yy; + + float mass = volume / 6.0f; + + b3Matrix3 centralInertia = b3MulSM( 1.0f / 120.0f, inertia ); + centralInertia = b3SubMM( centralInertia, b3Steiner( mass, localCenter ) ); + + hull->center = center; + hull->centralInertia = centralInertia; + hull->volume = mass; + hull->surfaceArea = 0.5f * area; + hull->innerRadius = radius; + + if ( mass <= 0.0f ) + { + return false; + } + + if ( volume <= 0.0f ) + { + return false; + } + + if ( area <= 0.0f ) + { + return false; + } + + if ( radius <= 0.0f ) + { + return false; + } + + return true; +} + +b3Hull* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount ) +{ + if ( pointCount < 4 ) + { + return NULL; + } + + b3Vec3 origin = points[0]; + int clampedMaxCount = b3ClampInt( maxVertexCount, 4, B3_HULL_LIMIT ); + + // Single allocation for all working memory. + b3HullWorkSizes sizes = b3ComputeHullWorkSizes( pointCount, clampedMaxCount ); + char* work = b3Alloc( sizes.totalBytes ); + + b3HullBuilder builder; + b3HullBuilder_Init( &builder, work, &sizes ); + + b3Vec3* shiftedPoints = (b3Vec3*)( work + sizes.offsetShiftedPoints ); + + bool ok = b3HullBuilder_Construct( &builder, points, pointCount, clampedMaxCount, origin, shiftedPoints ); + if ( !ok ) + { + b3Free( work, sizes.totalBytes ); + return NULL; + } + + if (builder.finalVertexCount >= B3_HULL_LIMIT) + { + b3Log( "hull final vertex count of %d exceeds limit of %d", builder.finalVertexCount, B3_HULL_LIMIT ); + b3Free( work, sizes.totalBytes ); + return NULL; + } + + if (builder.finalFaceCount >= B3_HULL_LIMIT) + { + b3Log( "hull final face count of %d exceeds limit of %d", builder.finalFaceCount, B3_HULL_LIMIT ); + b3Free( work, sizes.totalBytes ); + return NULL; + } + + if (builder.finalHalfEdgeCount >= B3_HULL_LIMIT) + { + b3Log( "hull final half edge count of %d exceeds limit of %d", builder.finalHalfEdgeCount, B3_HULL_LIMIT ); + b3Free( work, sizes.totalBytes ); + return NULL; + } + + // Walk lists into temp arrays bounded by B3_HULL_LIMIT, stamping finalIndex on each node so + // the resolution pass below is O(E + F) instead of O(E^2 + F^2). + const b3QHVertex* tempVertices[B3_HULL_LIMIT]; + int vertexCount = 0; + for ( b3QHListNode* node = builder.vertexList.link.next; node != &builder.vertexList.link; node = node->next ) + { + B3_ASSERT( vertexCount <= B3_HULL_LIMIT - 1 ); + + b3QHVertex* vertex = (b3QHVertex*)node; + vertex->finalIndex = vertexCount; + tempVertices[vertexCount++] = vertex; + } + + // Collect edges in twin-paired order (i, i+1) by stamping each pair as we discover it. + // Replaces b3SortEdges' O(E^2) twin pairing. + const b3QHFace* tempFaces[B3_HULL_LIMIT]; + const b3QHHalfEdge* tempEdges[B3_HULL_LIMIT]; + int faceCount = 0; + int edgeCount = 0; + + for ( b3QHListNode* faceNode = builder.faceList.link.next; faceNode != &builder.faceList.link; faceNode = faceNode->next ) + { + B3_ASSERT( faceCount <= B3_HULL_LIMIT - 1 ); + + b3QHFace* face = (b3QHFace*)faceNode; + face->finalIndex = faceCount; + tempFaces[faceCount++] = face; + + b3QHHalfEdge* edge = face->edge; + do + { + if ( edge->finalIndex < 0 ) + { + B3_ASSERT( edgeCount + 1 <= B3_HULL_LIMIT - 1 ); + + edge->finalIndex = edgeCount; + tempEdges[edgeCount++] = edge; + edge->twin->finalIndex = edgeCount; + tempEdges[edgeCount++] = edge->twin; + } + edge = edge->next; + } + while ( edge != face->edge ); + } + + // Allocate the hull. Arrays hang off the end. + int byteCount = (int)sizeof( b3Hull ); + int vertexOffset = byteCount; + byteCount += vertexCount * (int)sizeof( b3HullVertex ); + int pointOffset = byteCount; + byteCount += vertexCount * (int)sizeof( b3Vec3 ); + int edgeOffset = byteCount; + byteCount += edgeCount * (int)sizeof( b3HullHalfEdge ); + int faceOffset = byteCount; + byteCount += faceCount * (int)sizeof( b3HullFace ); + int planeOffset = byteCount; + byteCount += faceCount * (int)sizeof( b3Plane ); + + b3Hull* hull = b3Alloc( byteCount ); + memset( hull, 0, byteCount ); + + hull->version = B3_HULL_VERSION; + hull->vertexOffset = vertexOffset; + hull->pointOffset = pointOffset; + hull->edgeOffset = edgeOffset; + hull->faceOffset = faceOffset; + hull->planeOffset = planeOffset; + + hull->vertexCount = vertexCount; + hull->edgeCount = edgeCount; + hull->faceCount = faceCount; + + hull->byteCount = byteCount; + + b3HullVertex* vertices = b3GetHullVerticesWrite( hull ); + b3HullHalfEdge* edges = b3GetHullEdgesWrite( hull ); + b3HullFace* faces = (b3HullFace*)( (intptr_t)hull + hull->faceOffset ); + b3Vec3* finalPoints = b3GetHullPointsWrite( hull ); + b3Plane* planes = b3GetHullPlanesWrite( hull ); + + for ( int index = 0; index < vertexCount; ++index ) + { + vertices[index].edge = 0; + finalPoints[index] = tempVertices[index]->position; + } + + for ( int index = 0; index < edgeCount; ++index ) + { + const b3QHHalfEdge* edge = tempEdges[index]; + B3_ASSERT( 0 <= edge->next->finalIndex && edge->next->finalIndex <= UINT8_MAX ); + B3_ASSERT( 0 <= edge->twin->finalIndex && edge->twin->finalIndex <= UINT8_MAX ); + B3_ASSERT( 0 <= edge->face->finalIndex && edge->face->finalIndex <= UINT8_MAX ); + B3_ASSERT( 0 <= edge->origin->finalIndex && edge->origin->finalIndex <= UINT8_MAX ); + + edges[index].next = (uint8_t)edge->next->finalIndex; + edges[index].twin = (uint8_t)edge->twin->finalIndex; + edges[index].face = (uint8_t)edge->face->finalIndex; + edges[index].origin = (uint8_t)edge->origin->finalIndex; + + vertices[edge->origin->finalIndex].edge = (uint8_t)index; + } + + for ( int index = 0; index < faceCount; ++index ) + { + const b3QHFace* face = tempFaces[index]; + B3_ASSERT( 0 <= face->edge->finalIndex && face->edge->finalIndex <= UINT8_MAX ); + + faces[index].edge = (uint8_t)face->edge->finalIndex; + planes[index] = face->plane; + } + + // All builder pointers are dead from here on. + b3Free( work, sizes.totalBytes ); + + b3UpdateHullBounds( hull ); + bool success = b3UpdateHullBulkProperties( hull ); + if ( success == false ) + { + b3DestroyHull( hull ); + return NULL; + } + + if ( b3IsValidHull( hull ) == false ) + { + b3DestroyHull( hull ); + return NULL; + } + + hull->hash = 0; + hull->hash = b3Hash( B3_HASH_INIT, (uint8_t*)hull, hull->byteCount ); + + return hull; +} + +b3Hull* b3CloneHull( const b3Hull* hull ) +{ + if ( hull == NULL || b3IsValidHull( hull ) == false ) + { + return NULL; + } + + b3Hull* clone = (b3Hull*)b3Alloc( hull->byteCount ); + memcpy( clone, hull, hull->byteCount ); + + return clone; +} + +b3Hull* b3CloneAndTransformHull( const b3Hull* original, b3Transform transform, b3Vec3 scale ) +{ + if ( original == NULL || b3IsValidHull( original ) == false ) + { + return NULL; + } + + b3Hull* hull = (b3Hull*)b3Alloc( original->byteCount ); + memcpy( hull, original, original->byteCount ); + + b3Vec3 safeScale = b3SafeScale( scale ); + + b3HullHalfEdge* edges = b3GetHullEdgesWrite( hull ); + const b3HullFace* faces = b3GetHullFaces( hull ); + int faceCount = hull->faceCount; + int vertexCount = hull->vertexCount; + + if ( safeScale.x * safeScale.y * safeScale.z < 0.0f ) + { + // Reflected: reverse edge winding for each face. + for ( int i = 0; i < faceCount; ++i ) + { + const b3HullFace* face = faces + i; + + uint8_t startEdgeIndex = face->edge; + uint8_t currentEdgeIndex = startEdgeIndex; + uint8_t prevEdgeIndex = UINT8_MAX; + + do + { + b3HullHalfEdge* edge = edges + currentEdgeIndex; + + if ( edge->next == startEdgeIndex ) + { + prevEdgeIndex = currentEdgeIndex; + break; + } + + currentEdgeIndex = edge->next; + } + while ( currentEdgeIndex != startEdgeIndex ); + + B3_ASSERT( prevEdgeIndex != UINT8_MAX ); + + currentEdgeIndex = startEdgeIndex; + + do + { + b3HullHalfEdge* edge = edges + currentEdgeIndex; + uint8_t nextIndex = edge->next; + edge->next = prevEdgeIndex; + + if ( currentEdgeIndex < edge->twin ) + { + b3HullHalfEdge* twin = edges + edge->twin; + B3_SWAP( edge->origin, twin->origin ); + } + + prevEdgeIndex = currentEdgeIndex; + currentEdgeIndex = nextIndex; + } + while ( currentEdgeIndex != startEdgeIndex ); + } + + b3HullVertex* vertices = b3GetHullVerticesWrite( hull ); + + for ( int i = 0; i < vertexCount; ++i ) + { + b3HullVertex* vertex = vertices + i; + const b3HullHalfEdge* edge = edges + vertex->edge; + vertex->edge = edge->twin; + } + } + + b3Matrix3 matrix = b3MakeMatrixFromQuat( transform.q ); + b3Vec3* points = b3GetHullPointsWrite( hull ); + + for ( int i = 0; i < vertexCount; ++i ) + { + points[i] = b3Add( b3MulMV( matrix, b3Mul( safeScale, points[i] ) ), transform.p ); + } + + b3Plane* planes = b3GetHullPlanesWrite( hull ); + + for ( int i = 0; i < faceCount; ++i ) + { + int count = 0; + b3Vec3 centroid = b3Vec3_zero; + b3Vec3 normal = b3Vec3_zero; + + const b3HullFace* face = faces + i; + uint8_t startEdgeIndex = face->edge; + uint8_t currentEdgeIndex = startEdgeIndex; + + const b3HullHalfEdge* startEdge = edges + currentEdgeIndex; + B3_ASSERT( startEdge->face == i ); + B3_ASSERT( startEdge->origin < vertexCount ); + + b3Vec3 origin = points[startEdge->origin]; + + do + { + b3HullHalfEdge* edge = edges + currentEdgeIndex; + b3HullHalfEdge* twin = edges + edge->twin; + B3_ASSERT( twin->twin == currentEdgeIndex ); + + b3Vec3 v1 = b3Sub( points[edge->origin], origin ); + b3Vec3 v2 = b3Sub( points[twin->origin], origin ); + + count++; + centroid = b3Add( centroid, v1 ); + normal.x += ( v1.y - v2.y ) * ( v1.z + v2.z ); + normal.y += ( v1.z - v2.z ) * ( v1.x + v2.x ); + normal.z += ( v1.x - v2.x ) * ( v1.y + v2.y ); + + currentEdgeIndex = edge->next; + } + while ( currentEdgeIndex != startEdgeIndex ); + + B3_ASSERT( count > 0 ); + centroid = b3MulSV( 1.0f / (float)count, centroid ); + centroid = b3Add( centroid, origin ); + + float area = b3Length( normal ); + B3_ASSERT( area > 0.0f ); + normal = b3MulSV( 1.0f / area, normal ); + + planes[i] = b3MakePlaneFromNormalAndPoint( normal, centroid ); + } + + b3UpdateHullBounds( hull ); + bool success = b3UpdateHullBulkProperties( hull ); + if ( success == false ) + { + b3Free( hull, original->byteCount ); + return NULL; + } + + hull->hash = 0; + hull->hash = b3Hash( B3_HASH_INIT, (uint8_t*)hull, hull->byteCount ); + + B3_VALIDATE( b3IsValidHull( hull ) ); + + return hull; +} + +void b3DestroyHull( b3Hull* hull ) +{ + b3Free( hull, hull->byteCount ); +} + +b3MassData b3ComputeHullMass( const b3Hull* shape, float density ) +{ + b3MassData out; + out.mass = density * shape->volume; + out.center = shape->center; + + // todo_erin switch to central + out.inertia = b3AddMM( b3MulSM( density, shape->centralInertia ), b3Steiner( out.mass, out.center ) ); + return out; +} + +b3AABB b3ComputeHullAABB( const b3Hull* shape, b3Transform transform ) +{ + return b3AABB_Transform( transform, shape->aabb ); +} + +b3AABB b3ComputeSweptHullAABB( const b3Hull* shape, b3Transform xf1, b3Transform xf2 ) +{ + b3AABB aabb1 = b3AABB_Transform( xf1, shape->aabb ); + b3AABB aabb2 = b3AABB_Transform( xf2, shape->aabb ); + return b3AABB_Union( aabb1, aabb2 ); +} + +bool b3OverlapHull( const b3Hull* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy ) +{ + const b3Vec3* points = b3GetHullPoints( shape ); + + b3DistanceInput input; + input.proxyA = (b3ShapeProxy){ points, shape->vertexCount, 0.0f }; + input.proxyB = *proxy; + input.transformA = shapeTransform; + input.transformB = b3Transform_identity; + input.useRadii = true; + + b3SimplexCache cache = { 0 }; + b3DistanceOutput output = b3ShapeDistance( &input, &cache, NULL, 0 ); + return output.distance < B3_OVERLAP_SLOP; +} + +b3CastOutput b3RayCastHull( const b3Hull* shape, const b3RayCastInput* input ) +{ + B3_ASSERT( b3IsValidRay( input ) ); + b3CastOutput output = { 0 }; + + float lower = 0.0f; + float upper = input->maxFraction; + int bestFace = B3_NULL_INDEX; + + const b3Plane* planes = b3GetHullPlanes( shape ); + + for ( int faceIndex = 0; faceIndex < shape->faceCount; ++faceIndex ) + { + b3Plane plane = planes[faceIndex]; + + float distance = plane.offset - b3Dot( plane.normal, input->origin ); + float denominator = b3Dot( plane.normal, input->translation ); + + if ( denominator == 0.0f ) + { + if ( distance < 0.0f ) + { + return output; + } + } + else + { + float fraction = distance / denominator; + + if ( denominator < 0.0f ) + { + if ( fraction > lower ) + { + bestFace = faceIndex; + lower = fraction; + } + } + else + { + if ( fraction < upper ) + { + upper = fraction; + } + } + + if ( upper < lower ) + { + return output; + } + } + } + + if ( bestFace >= 0 ) + { + output.point = b3Add( input->origin, b3MulSV( lower, input->translation ) ); + output.normal = planes[bestFace].normal; + output.fraction = lower; + output.hit = true; + } + else + { + output.point = input->origin; + output.hit = true; + } + + return output; +} + +b3CastOutput b3ShapeCastHull( const b3Hull* shape, const b3ShapeCastInput* input ) +{ + const b3Vec3* points = b3GetHullPoints( shape ); + + b3ShapeCastPairInput pairInput; + pairInput.proxyA = (b3ShapeProxy){ points, shape->vertexCount, 0.0f }; + pairInput.proxyB = input->proxy; + pairInput.transformA = b3Transform_identity; + pairInput.transformB = b3Transform_identity; + pairInput.translationB = input->translation; + pairInput.maxFraction = input->maxFraction; + pairInput.canEncroach = input->canEncroach; + + b3CastOutput output = b3ShapeCast( &pairInput ); + return output; +} + +int b3CollideMoverAndHull( b3PlaneResult* result, const b3Hull* shape, const b3Capsule* mover ) +{ + const b3Vec3* points = b3GetHullPoints( shape ); + b3DistanceInput distanceInput; + distanceInput.proxyA = (b3ShapeProxy){ points, shape->vertexCount, 0.0f }; + distanceInput.proxyB = (b3ShapeProxy){ &mover->center1, 2, mover->radius }; + distanceInput.transformA = b3Transform_identity; + distanceInput.transformB = b3Transform_identity; + distanceInput.useRadii = false; + + float totalRadius = mover->radius; + + b3SimplexCache cache = { 0 }; + b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, &cache, NULL, 0 ); + + if ( distanceOutput.distance <= totalRadius ) + { + b3Plane plane = { distanceOutput.normal, totalRadius - distanceOutput.distance }; + *result = (b3PlaneResult){ plane, distanceOutput.pointA }; + return 1; + } + + return 0; +} + +b3ShapeExtent b3ComputeHullExtent( const b3Hull* hull, b3Vec3 origin ) +{ + const b3Vec3* points = b3GetHullPoints( hull ); + + b3ShapeExtent extent; + extent.minExtent = hull->innerRadius; + extent.maxExtent = b3Vec3_zero; + for ( int index = 0; index < hull->vertexCount; ++index ) + { + b3Vec3 point = points[index]; + extent.maxExtent = b3Max( extent.maxExtent, b3Abs( b3Sub( point, origin ) ) ); + } + + return extent; +} + +float b3ComputeHullProjectedArea( const b3Hull* hull, b3Vec3 direction ) +{ + float area = 0.0f; + + int faceCount = hull->faceCount; + const b3HullFace* hullFaces = b3GetHullFaces( hull ); + const b3HullHalfEdge* hullEdges = b3GetHullEdges( hull ); + const b3Vec3* hullPoints = b3GetHullPoints( hull ); + + for ( int i = 0; i < faceCount; ++i ) + { + const b3HullFace* face = hullFaces + i; + + int baseEdge = face->edge; + const b3HullHalfEdge* edge = hullEdges + baseEdge; + b3Vec3 p1 = hullPoints[edge->origin]; + + int edgeIndex = edge->next; + edge = hullEdges + edgeIndex; + b3Vec3 p2 = hullPoints[edge->origin]; + + edgeIndex = edge->next; + + do + { + edge = hullEdges + edgeIndex; + b3Vec3 p3 = hullPoints[edge->origin]; + + b3Vec3 e1 = b3Sub( p2, p1 ); + b3Vec3 e2 = b3Sub( p3, p1 ); + b3Vec3 n = b3Cross( e1, e2 ); + float a = b3Dot( n, direction ); + area += b3MaxFloat( a, 0.0f ); + + p2 = p3; + edgeIndex = edge->next; + } + while ( edgeIndex != baseEdge ); + } + + return 0.5f * area; +} + +// Constant template box (vertex/edge/face/topology). b3MakeTransformedBoxHull copies and +// fills in the runtime-dependent fields (boxPoints, boxPlanes, aabb, mass properties, hash). +static const b3BoxHull s_boxHull = { + .base = { + .version = B3_HULL_VERSION, + .byteCount = sizeof( b3BoxHull ), + .hash = 0, + .vertexCount = 8, + .edgeCount = 24, + .faceCount = 6, + .vertexOffset = offsetof( b3BoxHull, boxVertices ), + .pointOffset = offsetof( b3BoxHull, boxPoints ), + .edgeOffset = offsetof( b3BoxHull, boxEdges ), + .faceOffset = offsetof( b3BoxHull, boxFaces ), + .planeOffset = offsetof( b3BoxHull, boxPlanes ), + }, + .boxVertices = { + [0] = { .edge = 8 }, + [1] = { .edge = 1 }, + [2] = { .edge = 0 }, + [3] = { .edge = 9 }, + [4] = { .edge = 13 }, + [5] = { .edge = 3 }, + [6] = { .edge = 5 }, + [7] = { .edge = 11 }, + }, + .boxEdges = { + [0] = { 2, 1, 2, 0 }, + [1] = { 17, 0, 1, 5 }, + [2] = { 4, 3, 1, 0 }, + [3] = { 20, 2, 5, 3 }, + [4] = { 6, 5, 5, 0 }, + [5] = { 23, 4, 6, 4 }, + [6] = { 0, 7, 6, 0 }, + [7] = { 18, 6, 2, 2 }, + [8] = { 10, 9, 0, 1 }, + [9] = { 21, 8, 3, 5 }, + [10] = { 12, 11, 3, 1 }, + [11] = { 16, 10, 7, 2 }, + [12] = { 14, 13, 7, 1 }, + [13] = { 19, 12, 4, 4 }, + [14] = { 8, 15, 4, 1 }, + [15] = { 22, 14, 0, 3 }, + [16] = { 7, 17, 3, 2 }, + [17] = { 9, 16, 2, 5 }, + [18] = { 11, 19, 6, 2 }, + [19] = { 5, 18, 7, 4 }, + [20] = { 15, 21, 1, 3 }, + [21] = { 1, 20, 0, 5 }, + [22] = { 3, 23, 4, 3 }, + [23] = { 13, 22, 5, 4 }, + }, + .boxFaces = { + [0] = { .edge = 0 }, + [1] = { .edge = 8 }, + [2] = { .edge = 16 }, + [3] = { .edge = 20 }, + [4] = { .edge = 19 }, + [5] = { .edge = 21 }, + }, +}; + +b3BoxHull b3MakeTransformedBoxHull( float hx, float hy, float hz, b3Transform transform ) +{ + b3BoxHull boxHull = s_boxHull; + + float minH = 0.2f * B3_LINEAR_SLOP; + b3Vec3 h = b3Max( (b3Vec3){ minH, minH, minH }, (b3Vec3){ hx, hy, hz } ); + + boxHull.base.aabb = b3AABB_Transform( transform, (b3AABB){ b3Neg( h ), h } ); + boxHull.base.surfaceArea = 8.0f * ( h.x * h.y + h.x * h.z + h.y * h.z ); + boxHull.base.volume = 8.0f * h.x * h.y * h.z; + boxHull.base.innerRadius = b3MinFloat( h.x, b3MinFloat( h.y, h.z ) ); + boxHull.base.center = transform.p; + + b3Matrix3 boxInertia = b3BoxInertia( boxHull.base.volume, b3Neg( h ), h ); + boxHull.base.centralInertia = b3RotateInertia( transform.q, boxInertia ); + + b3Vec3 lower = b3Neg( h ); + b3Vec3 upper = h; + + boxHull.boxPlanes[0] = b3TransformPlane( transform, b3MakePlaneFromNormalAndPoint( b3Neg( b3Vec3_axisX ), lower ) ); + boxHull.boxPlanes[1] = b3TransformPlane( transform, b3MakePlaneFromNormalAndPoint( b3Vec3_axisX, upper ) ); + boxHull.boxPlanes[2] = b3TransformPlane( transform, b3MakePlaneFromNormalAndPoint( b3Neg( b3Vec3_axisY ), lower ) ); + boxHull.boxPlanes[3] = b3TransformPlane( transform, b3MakePlaneFromNormalAndPoint( b3Vec3_axisY, upper ) ); + boxHull.boxPlanes[4] = b3TransformPlane( transform, b3MakePlaneFromNormalAndPoint( b3Neg( b3Vec3_axisZ ), lower ) ); + boxHull.boxPlanes[5] = b3TransformPlane( transform, b3MakePlaneFromNormalAndPoint( b3Vec3_axisZ, upper ) ); + + boxHull.boxPoints[0] = b3TransformPoint( transform, (b3Vec3){ h.x, h.y, h.z } ); + boxHull.boxPoints[1] = b3TransformPoint( transform, (b3Vec3){ -h.x, h.y, h.z } ); + boxHull.boxPoints[2] = b3TransformPoint( transform, (b3Vec3){ -h.x, -h.y, h.z } ); + boxHull.boxPoints[3] = b3TransformPoint( transform, (b3Vec3){ h.x, -h.y, h.z } ); + boxHull.boxPoints[4] = b3TransformPoint( transform, (b3Vec3){ h.x, h.y, -h.z } ); + boxHull.boxPoints[5] = b3TransformPoint( transform, (b3Vec3){ -h.x, h.y, -h.z } ); + boxHull.boxPoints[6] = b3TransformPoint( transform, (b3Vec3){ -h.x, -h.y, -h.z } ); + boxHull.boxPoints[7] = b3TransformPoint( transform, (b3Vec3){ h.x, -h.y, -h.z } ); + + boxHull.base.hash = 0; + boxHull.base.hash = b3Hash( B3_HASH_INIT, (uint8_t*)&boxHull, sizeof( b3BoxHull ) ); + + return boxHull; +} + +b3BoxHull b3MakeCubeHull( float halfWidth ) +{ + return b3MakeBoxHull( halfWidth, halfWidth, halfWidth ); +} + +b3BoxHull b3MakeOffsetBoxHull( float hx, float hy, float hz, b3Vec3 offset ) +{ + b3Transform transform = { .p = offset, .q = b3Quat_identity }; + return b3MakeTransformedBoxHull( hx, hy, hz, transform ); +} + +b3BoxHull b3MakeBoxHull( float hx, float hy, float hz ) +{ + return b3MakeTransformedBoxHull( hx, hy, hz, b3Transform_identity ); +} + +void b3ScaleBox( b3Vec3* halfWidths, b3Transform* transform, b3Vec3 postScale, float minHalfWidth ) +{ + B3_ASSERT( b3IsValidFloat( minHalfWidth ) && minHalfWidth > 0.0f ); + + b3Quat q = transform->q; + + if ( postScale.x < 0.0f || postScale.y < 0.0f || postScale.z < 0.0f ) + { + // todo this might be unnecessary if rotation is identity + // todo compare with polar decomposition (much more expensive) + b3Matrix3 m = b3MakeMatrixFromQuat( q ); + m.cx.x *= postScale.x; + m.cy.x *= postScale.x; + m.cz.x *= postScale.x; + m.cx.y *= postScale.y; + m.cy.y *= postScale.y; + m.cz.y *= postScale.y; + m.cx.z *= postScale.z; + m.cy.z *= postScale.z; + m.cz.z *= postScale.z; + m.cx = b3Normalize( m.cx ); + m.cy = b3Normalize( m.cy ); + m.cz = b3Normalize( m.cz ); + m.cx = postScale.x < 0.0f ? b3Neg( m.cx ) : m.cx; + m.cy = postScale.y < 0.0f ? b3Neg( m.cy ) : m.cy; + m.cz = postScale.z < 0.0f ? b3Neg( m.cz ) : m.cz; + q = b3MakeQuatFromMatrix( &m ); + } + + b3Vec3 absScale = b3Abs( postScale ); + + b3Vec3 h = *halfWidths; + b3Vec3 p1 = b3Mul( absScale, b3RotateVector( q, b3Neg( h ) ) ); + b3Vec3 p2 = b3Mul( absScale, b3RotateVector( q, h ) ); + + b3Vec3 localP1 = b3InvRotateVector( q, p1 ); + b3Vec3 localP2 = b3InvRotateVector( q, p2 ); + + b3Vec3 lower = b3Min( localP1, localP2 ); + b3Vec3 upper = b3Max( localP1, localP2 ); + + b3Vec3 scaledHalfWidth = b3MulSV( 0.5f, b3Sub( upper, lower ) ); + + b3Vec3 mLimit = { minHalfWidth, minHalfWidth, minHalfWidth }; + *halfWidths = b3Max( scaledHalfWidth, mLimit ); + transform->p = b3Mul( postScale, transform->p ); + transform->q = q; +} + +// todo use new hull scaling technique +b3BoxHull b3MakeScaledBoxHull( b3Vec3 halfWidths, b3Transform transform, b3Vec3 postScale ) +{ + b3Vec3 h = halfWidths; + b3Transform xf = transform; + b3ScaleBox( &h, &xf, postScale, 4.0f * B3_LINEAR_SLOP ); + return b3MakeTransformedBoxHull( h.x, h.y, h.z, xf ); +} + +// ============================================================================= +// 2D hull (Andrew's monotone chain) +// ============================================================================= + +// cross(b - a, c - a) +static inline float b3Cross2D( b3Vec2 a, b3Vec2 b, b3Vec2 c ) +{ + return ( b.x - a.x ) * ( c.y - a.y ) - ( b.y - a.y ) * ( c.x - a.x ); +} + +// Iteratively remove the vertices contributing the least area. +int b3SimplifyHull2D( b3Point2D* hull, int count1, int target ) +{ + B3_ASSERT( target >= 3 ); + + if ( count1 <= 3 ) + { + return count1; + } + + float linearSlop = B3_LINEAR_SLOP; + float areaTol = 0.25f * linearSlop * linearSlop; + int count2 = count1; + + for ( ;; ) + { + float minArea = FLT_MAX; + int minIndex = B3_NULL_INDEX; + + for ( int i = 0; i < count2; i++ ) + { + int prev = ( i + count2 - 1 ) % count2; + int next = ( i + 1 ) % count2; + float area = b3Cross2D( hull[prev].p, hull[i].p, hull[next].p ); + B3_VALIDATE( area >= -FLT_EPSILON ); + + if ( area + areaTol < minArea ) + { + minArea = area; + minIndex = i; + } + } + + if ( minArea > areaTol && count2 <= target ) + { + break; + } + + B3_ASSERT( minIndex != B3_NULL_INDEX ); + + count2 -= 1; + if ( minIndex < count2 ) + { + memmove( hull + minIndex, hull + ( minIndex + 1 ), ( count2 - minIndex ) * sizeof( b3Point2D ) ); + } + } + + return count2; +} + +// Sort comparator: by x, then by y. Insertion since n is typically 20 or less. +static void b3Sort2D( b3Point2D* pts, int count ) +{ + for ( int i = 1; i < count; ++i ) + { + b3Point2D base = pts[i]; + int j = i - 1; + while ( j >= 0 && ( pts[j].p.x > base.p.x || ( pts[j].p.x == base.p.x && pts[j].p.y > base.p.y ) ) ) + { + pts[j + 1] = pts[j]; + j -= 1; + } + pts[j + 1] = base; + } +} + +// Welds points that have been sorted O(n) time +static int b3Weld2D( b3Point2D* pts, int count1 ) +{ + if ( count1 <= 1 ) + { + return count1; + } + + float linearSlop = 0.25f * B3_LINEAR_SLOP; + float tolSqr = linearSlop * linearSlop; + + int count2 = 1; + int baseIndex = 0; + for ( int i = 1; i < count1; i++ ) + { + float distanceSqr = b3DistanceSquared2( pts[i].p, pts[baseIndex].p ); + if ( distanceSqr < tolSqr ) + { + if ( pts[i].originalIndex < pts[baseIndex].originalIndex ) + { + pts[baseIndex] = pts[i]; + } + } + else + { + pts[count2] = pts[i]; + baseIndex = count2; + count2 += 1; + } + } + + return count2; +} + +// Andrew's monotone chain convex hull algorithm +// hull must have space for 2 * count1 points +int b3Hull2D( b3Point2D* pts, int count1, b3Point2D* hull ) +{ + if ( count1 <= 0 ) + { + return 0; + } + + if ( count1 == 1 ) + { + hull[0] = pts[0]; + return 1; + } + + b3Sort2D( pts, count1 ); + count1 = b3Weld2D( pts, count1 ); + + if ( count1 == 1 ) + { + hull[0] = pts[0]; + return 1; + } + + if ( count1 == 2 ) + { + hull[0] = pts[0]; + hull[1] = pts[1]; + return 2; + } + + int count2 = 0; + + for ( int i = 0; i < count1; i++ ) + { + while ( count2 >= 2 ) + { + float area = b3Cross2D( hull[count2 - 2].p, hull[count2 - 1].p, pts[i].p ); + if ( area > 0.0f ) + { + break; + } + + count2 -= 1; + } + + B3_VALIDATE( count2 < 2 * count1 ); + hull[count2] = pts[i]; + count2 += 1; + } + + int lowerCount = count2 + 1; + + for ( int i = count1 - 2; i >= 0; i-- ) + { + while ( count2 >= lowerCount ) + { + float area = b3Cross2D( hull[count2 - 2].p, hull[count2 - 1].p, pts[i].p ); + if ( area > 0.0f ) + { + break; + } + + count2 -= 1; + } + + B3_VALIDATE( count2 < 2 * count1 ); + hull[count2] = pts[i]; + count2 += 1; + } + + B3_VALIDATE( hull[0].originalIndex == hull[count2 - 1].originalIndex ); + return count2 - 1; +} diff --git a/src/id_pool.c b/src/id_pool.c new file mode 100644 index 0000000..185b6ee --- /dev/null +++ b/src/id_pool.c @@ -0,0 +1,73 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "id_pool.h" + +b3IdPool b3CreateIdPool( void ) +{ + b3IdPool pool = { 0 }; + b3Array_Reserve( pool.freeArray, 32 ); + return pool; +} + +void b3DestroyIdPool( b3IdPool* pool ) +{ + b3Array_Destroy( pool->freeArray ); + *pool = (b3IdPool){ 0 }; +} + +int b3AllocId( b3IdPool* pool ) +{ + int count = pool->freeArray.count; + if ( count > 0 ) + { + int id = b3Array_Pop( pool->freeArray ); + return id; + } + + int id = pool->nextIndex; + pool->nextIndex += 1; + return id; +} + +void b3FreeId( b3IdPool* pool, int id ) +{ + B3_ASSERT( pool->nextIndex > 0 ); + B3_ASSERT( 0 <= id && id < pool->nextIndex ); + + // todo does not work with assertion above + // should probably be `id == pool->nextIndex - 1` + if ( id == pool->nextIndex ) + { + pool->nextIndex -= 1; + return; + } + + b3Array_Push( pool->freeArray, id ); +} + +#if B3_ENABLE_VALIDATION + +void b3ValidateFreeId( const b3IdPool* pool, int id ) +{ + int freeCount = pool->freeArray.count; + for ( int i = 0; i < freeCount; ++i ) + { + if ( pool->freeArray.data[i] == id ) + { + return; + } + } + + B3_ASSERT( 0 ); +} + +#else + +void b3ValidateFreeId( const b3IdPool* pool, int id ) +{ + B3_UNUSED( pool ); + B3_UNUSED( id ); +} + +#endif diff --git a/src/id_pool.h b/src/id_pool.h new file mode 100644 index 0000000..7659a38 --- /dev/null +++ b/src/id_pool.h @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "container.h" + +typedef struct b3IdPool +{ + b3ArrayC( int ) freeArray; + int nextIndex; +} b3IdPool; + +#ifdef __cplusplus +extern "C" +{ +#endif + +b3IdPool b3CreateIdPool( void ); +void b3DestroyIdPool( b3IdPool* pool ); + +int b3AllocId( b3IdPool* pool ); +void b3FreeId( b3IdPool* pool, int id ); +void b3ValidateFreeId( const b3IdPool* pool, int id ); + +#ifdef __cplusplus +} +#endif + +B3_INLINE int b3GetIdCount( const b3IdPool* pool ) +{ + return pool->nextIndex - pool->freeArray.count; +} + +B3_INLINE int b3GetIdCapacity( const b3IdPool* pool ) +{ + return pool->nextIndex; +} + +B3_INLINE int b3GetIdBytes( const b3IdPool* pool ) +{ + return b3Array_ByteCount( pool->freeArray ); +} diff --git a/src/island.c b/src/island.c new file mode 100644 index 0000000..625a1b3 --- /dev/null +++ b/src/island.c @@ -0,0 +1,735 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "island.h" + +#include "body.h" +#include "contact.h" +#include "core.h" +#include "id_pool.h" +#include "joint.h" +#include "physics_world.h" +#include "solver_set.h" + +#include + +b3Island* b3CreateIsland( b3World* world, int setIndex ) +{ + B3_ASSERT( setIndex == b3_awakeSet || setIndex >= b3_firstSleepingSet ); + + int islandId = b3AllocId( &world->islandIdPool ); + + if ( islandId == world->islands.count ) + { + b3Island emptyIsland = { 0 }; + b3Array_Push( world->islands, emptyIsland ); + } + else + { + B3_ASSERT( world->islands.data[islandId].setIndex == B3_NULL_INDEX ); + } + + b3SolverSet* set = b3Array_Get( world->solverSets, setIndex ); + + b3Island* island = b3Array_Get( world->islands, islandId ); + island->setIndex = setIndex; + island->localIndex = set->islandSims.count; + island->islandId = islandId; + b3Array_Create( island->bodies ); + b3Array_Create( island->contacts ); + b3Array_Create( island->joints ); + island->constraintRemoveCount = 0; + + b3IslandSim* islandSim = b3Array_Emplace( set->islandSims ); + islandSim->islandId = islandId; + + return island; +} + +void b3DestroyIsland( b3World* world, int islandId ) +{ + if ( world->splitIslandId == islandId ) + { + world->splitIslandId = B3_NULL_INDEX; + } + + // assume island is empty + b3Island* island = b3Array_Get( world->islands, islandId ); + b3SolverSet* set = b3Array_Get( world->solverSets, island->setIndex ); + { + int localIndex = island->localIndex; + int lastIndex = set->islandSims.count - 1; + B3_ASSERT( 0 <= localIndex && localIndex <= lastIndex ); + int moveIslandId = set->islandSims.data[lastIndex].islandId; + set->islandSims.data[localIndex] = set->islandSims.data[lastIndex]; + world->islands.data[moveIslandId].localIndex = localIndex; + set->islandSims.count -= 1; + } + + // Free island and id (preserve island generation) + b3Array_Destroy( island->bodies ); + b3Array_Destroy( island->contacts ); + b3Array_Destroy( island->joints ); + island->constraintRemoveCount = 0; + island->localIndex = B3_NULL_INDEX; + island->islandId = B3_NULL_INDEX; + island->setIndex = B3_NULL_INDEX; + + b3FreeId( &world->islandIdPool, islandId ); +} + +static int b3MergeIslands( b3World* world, int islandIdA, int islandIdB ) +{ + if ( islandIdA == islandIdB ) + { + return islandIdA; + } + + if ( islandIdA == B3_NULL_INDEX ) + { + B3_ASSERT( islandIdB != B3_NULL_INDEX ); + return islandIdB; + } + + if ( islandIdB == B3_NULL_INDEX ) + { + B3_ASSERT( islandIdA != B3_NULL_INDEX ); + return islandIdA; + } + + b3Island* smallIsland; + b3Island* bigIsland; + { + b3Island* islandA = b3Array_Get( world->islands, islandIdA ); + b3Island* islandB = b3Array_Get( world->islands, islandIdB ); + + // Keep the biggest island to reduce cache misses + if ( islandA->bodies.count >= islandB->bodies.count ) + { + bigIsland = islandA; + smallIsland = islandB; + } + else + { + bigIsland = islandB; + smallIsland = islandA; + } + } + + int bigIslandId = bigIsland->islandId; + b3Array_Reserve( bigIsland->bodies, bigIsland->bodies.count + smallIsland->bodies.count ); + + // Move bodies from smaller island to larger island + for ( int i = 0; i < smallIsland->bodies.count; ++i ) + { + int bodyId = smallIsland->bodies.data[i]; + b3Body* body = b3Array_Get( world->bodies, bodyId ); + B3_VALIDATE( body->islandId == smallIsland->islandId ); + body->islandId = bigIslandId; + body->islandIndex = bigIsland->bodies.count; + b3Array_Push( bigIsland->bodies, bodyId ); + } + + // Migrate contacts from smaller island to larger island + if ( smallIsland->contacts.count > 0 ) + { + b3Array_Reserve( bigIsland->contacts, bigIsland->contacts.count + smallIsland->contacts.count ); + + for ( int i = 0; i < smallIsland->contacts.count; ++i ) + { + b3ContactLink* link = smallIsland->contacts.data + i; + b3Contact* contact = b3Array_Get( world->contacts, link->contactId ); + contact->islandId = bigIslandId; + contact->islandIndex = bigIsland->contacts.count; + b3Array_Push( bigIsland->contacts, *link ); + } + } + + // Migrate joints from smaller island to larger island + if ( smallIsland->joints.count > 0 ) + { + b3Array_Reserve( bigIsland->joints, bigIsland->joints.count + smallIsland->joints.count ); + + for ( int i = 0; i < smallIsland->joints.count; ++i ) + { + b3JointLink* link = smallIsland->joints.data + i; + b3Joint* joint = b3Array_Get( world->joints, link->jointId ); + joint->islandId = bigIslandId; + joint->islandIndex = bigIsland->joints.count; + b3Array_Push( bigIsland->joints, *link ); + } + } + + // Track removed constraints + bigIsland->constraintRemoveCount += smallIsland->constraintRemoveCount; + + b3DestroyIsland( world, smallIsland->islandId ); + + b3ValidateIsland( world, bigIslandId ); + + return bigIslandId; +} + +static void b3AddContactToIsland( b3World* world, int islandId, b3Contact* contact ) +{ + B3_ASSERT( contact->islandId == B3_NULL_INDEX ); + B3_ASSERT( contact->islandIndex == B3_NULL_INDEX ); + + b3Island* island = b3Array_Get( world->islands, islandId ); + + contact->islandId = islandId; + contact->islandIndex = island->contacts.count; + + b3ContactLink link; + link.contactId = contact->contactId; + link.bodyIdA = contact->edges[0].bodyId; + link.bodyIdB = contact->edges[1].bodyId; + b3Array_Push( island->contacts, link ); + + b3ValidateIsland( world, islandId ); +} + +// Link a contact into an island. +void b3LinkContact( b3World* world, b3Contact* contact ) +{ + B3_ASSERT( ( contact->flags & b3_contactTouchingFlag ) != 0 ); + + int bodyIdA = contact->edges[0].bodyId; + int bodyIdB = contact->edges[1].bodyId; + + b3Body* bodyA = b3Array_Get( world->bodies, bodyIdA ); + b3Body* bodyB = b3Array_Get( world->bodies, bodyIdB ); + + B3_ASSERT( bodyA->setIndex != b3_disabledSet && bodyB->setIndex != b3_disabledSet ); + B3_ASSERT( bodyA->setIndex != b3_staticSet || bodyB->setIndex != b3_staticSet ); + + // Wake bodyB if bodyA is awake and bodyB is sleeping + if ( bodyA->setIndex == b3_awakeSet && bodyB->setIndex >= b3_firstSleepingSet ) + { + b3WakeSolverSet( world, bodyB->setIndex ); + } + + // Wake bodyA if bodyB is awake and bodyA is sleeping + if ( bodyB->setIndex == b3_awakeSet && bodyA->setIndex >= b3_firstSleepingSet ) + { + b3WakeSolverSet( world, bodyA->setIndex ); + } + + int islandIdA = bodyA->islandId; + int islandIdB = bodyB->islandId; + + // Static bodies have null island indices. + B3_ASSERT( bodyA->setIndex != b3_staticSet || islandIdA == B3_NULL_INDEX ); + B3_ASSERT( bodyB->setIndex != b3_staticSet || islandIdB == B3_NULL_INDEX ); + B3_ASSERT( islandIdA != B3_NULL_INDEX || islandIdB != B3_NULL_INDEX ); + + // Merge islands. This will destroy one of the islands. + int finalIslandId = b3MergeIslands( world, islandIdA, islandIdB ); + + // Add contact to the island that survived + b3AddContactToIsland( world, finalIslandId, contact ); +} + +// This is called when a contact no longer has contact points or when a contact is destroyed. +void b3UnlinkContact( b3World* world, b3Contact* contact ) +{ + B3_ASSERT( contact->islandId != B3_NULL_INDEX ); + + // remove from island + int islandId = contact->islandId; + b3Island* island = b3Array_Get( world->islands, islandId ); + + int removeIndex = contact->islandIndex; + B3_ASSERT( 0 <= removeIndex && removeIndex < island->contacts.count ); + B3_ASSERT( island->contacts.data[removeIndex].contactId == contact->contactId ); + + int movedIndex = b3Array_RemoveSwap( island->contacts, removeIndex ); + if ( movedIndex != B3_NULL_INDEX ) + { + // Fix islandIndex on the contact that was swapped into removeIndex + b3ContactLink* movedLink = island->contacts.data + removeIndex; + b3Contact* movedContact = b3Array_Get( world->contacts, movedLink->contactId ); + B3_ASSERT( movedContact->islandIndex == movedIndex ); + movedContact->islandIndex = removeIndex; + } + + contact->islandId = B3_NULL_INDEX; + contact->islandIndex = B3_NULL_INDEX; + island->constraintRemoveCount += 1; + + b3ValidateIsland( world, islandId ); +} + +static void b3AddJointToIsland( b3World* world, int islandId, b3Joint* joint ) +{ + B3_ASSERT( joint->islandId == B3_NULL_INDEX ); + B3_ASSERT( joint->islandIndex == B3_NULL_INDEX ); + + b3Island* island = b3Array_Get( world->islands, islandId ); + + joint->islandId = islandId; + joint->islandIndex = island->joints.count; + + b3JointLink link; + link.jointId = joint->jointId; + link.bodyIdA = joint->edges[0].bodyId; + link.bodyIdB = joint->edges[1].bodyId; + b3Array_Push( island->joints, link ); + + b3ValidateIsland( world, islandId ); +} + +void b3LinkJoint( b3World* world, b3Joint* joint ) +{ + b3Body* bodyA = b3Array_Get( world->bodies, joint->edges[0].bodyId ); + b3Body* bodyB = b3Array_Get( world->bodies, joint->edges[1].bodyId ); + + B3_ASSERT( bodyA->type == b3_dynamicBody || bodyB->type == b3_dynamicBody ); + + if ( bodyA->setIndex == b3_awakeSet && bodyB->setIndex >= b3_firstSleepingSet ) + { + b3WakeSolverSet( world, bodyB->setIndex ); + } + else if ( bodyB->setIndex == b3_awakeSet && bodyA->setIndex >= b3_firstSleepingSet ) + { + b3WakeSolverSet( world, bodyA->setIndex ); + } + + int islandIdA = bodyA->islandId; + int islandIdB = bodyB->islandId; + + B3_ASSERT( islandIdA != B3_NULL_INDEX || islandIdB != B3_NULL_INDEX ); + + // Merge islands. This will destroy one of the islands. + int finalIslandId = b3MergeIslands( world, islandIdA, islandIdB ); + + // Add joint the island that survived + b3AddJointToIsland( world, finalIslandId, joint ); +} + +void b3UnlinkJoint( b3World* world, b3Joint* joint ) +{ + if ( joint->islandId == B3_NULL_INDEX ) + { + return; + } + + // remove from island + int islandId = joint->islandId; + b3Island* island = b3Array_Get( world->islands, islandId ); + + int removeIndex = joint->islandIndex; + B3_ASSERT( 0 <= removeIndex && removeIndex < island->joints.count ); + B3_ASSERT( island->joints.data[removeIndex].jointId == joint->jointId ); + + int movedIndex = b3Array_RemoveSwap( island->joints, removeIndex ); + if ( movedIndex != B3_NULL_INDEX ) + { + // Fix islandIndex on the joint that was swapped into removeIndex + b3JointLink* movedLink = island->joints.data + removeIndex; + b3Joint* movedJoint = b3Array_Get( world->joints, movedLink->jointId ); + B3_ASSERT( movedJoint->islandIndex == movedIndex ); + movedJoint->islandIndex = removeIndex; + } + + joint->islandId = B3_NULL_INDEX; + joint->islandIndex = B3_NULL_INDEX; + island->constraintRemoveCount += 1; + + b3ValidateIsland( world, islandId ); +} + +// Find parent of a node. Use path halving to speed up further queries. +static inline int b3IslandFindParent( int* parents, int node ) +{ + // Walk the chain of parents to find the node that is its own parent (the root) + while ( parents[node] != node ) + { + int grandParent = parents[parents[node]]; + parents[node] = grandParent; + node = grandParent; + } + + return node; +} + +// Connect the components containing node1 and node2. +// Uses rank to keep tree balanced. Tracks per-component contact and joint counts. +static inline void b3IslandUnion( int* parents, int* ranks, int node1, int node2, int* contactCounts, int* jointCounts ) +{ + int root1 = b3IslandFindParent( parents, node1 ); + int root2 = b3IslandFindParent( parents, node2 ); + if ( root1 != root2 ) + { + if ( ranks[root1] < ranks[root2] ) + { + parents[root1] = root2; + contactCounts[root2] += contactCounts[root1]; + jointCounts[root2] += jointCounts[root1]; + } + else if ( ranks[root1] > ranks[root2] ) + { + parents[root2] = root1; + contactCounts[root1] += contactCounts[root2]; + jointCounts[root1] += jointCounts[root2]; + } + else + { + parents[root2] = root1; + ranks[root1] += 1; + contactCounts[root1] += contactCounts[root2]; + jointCounts[root1] += jointCounts[root2]; + } + } +} + +// This uses union-find. +// https://en.wikipedia.org/wiki/Disjoint-set_data_structure +void b3SplitIsland( b3World* world, int baseId ) +{ + b3Island* baseIsland = b3Array_Get( world->islands, baseId ); + B3_ASSERT( baseIsland->constraintRemoveCount > 0 ); + B3_ASSERT( baseIsland->setIndex == b3_awakeSet ); + + b3ValidateIsland( world, baseId ); + + // Cache base island fields before b3CreateIsland, which may reallocate + // world->islands and invalidate the baseIsland pointer. + int baseBodyCount = baseIsland->bodies.count; + int* baseBodyIds = baseIsland->bodies.data; + int baseBodyCapacity = baseIsland->bodies.capacity; + + int baseContactCount = baseIsland->contacts.count; + b3ContactLink* baseContacts = baseIsland->contacts.data; + int baseContactCapacity = baseIsland->contacts.capacity; + + int baseJointCount = baseIsland->joints.count; + b3JointLink* baseJoints = baseIsland->joints.data; + int baseJointCapacity = baseIsland->joints.capacity; + + b3Stack* alloc = &world->stack; + + // No lock is needed because I ensure the allocator is not used while this task is active. + // Allocate contactCounts and jointCounts before ranks so ranks can be freed first (LIFO arena). + int* parents = b3StackAlloc( alloc, baseBodyCount * sizeof( int ), "parents" ); + int* contactCounts = b3StackAlloc( alloc, baseBodyCount * sizeof( int ), "contact counts" ); + int* jointCounts = b3StackAlloc( alloc, baseBodyCount * sizeof( int ), "joint counts" ); + int* ranks = b3StackAlloc( alloc, baseBodyCount * sizeof( int ), "ranks" ); + for ( int i = 0; i < baseBodyCount; ++i ) + { + parents[i] = i; + ranks[i] = 0; + contactCounts[i] = 0; + jointCounts[i] = 0; + } + + b3Body* bodies = world->bodies.data; + + // Union over contacts, tracking per-component contact counts + for ( int i = 0; i < baseContactCount; ++i ) + { + int bodyIdA = baseContacts[i].bodyIdA; + int bodyIdB = baseContacts[i].bodyIdB; + B3_VALIDATE( 0 <= bodyIdA && bodyIdA < world->bodies.count ); + B3_VALIDATE( 0 <= bodyIdB && bodyIdB < world->bodies.count ); + b3Body* bodyA = bodies + bodyIdA; + b3Body* bodyB = bodies + bodyIdB; + int islandIndexA = bodyA->islandIndex; + int islandIndexB = bodyB->islandIndex; + + // Only connect non-static bodies + if ( islandIndexA != B3_NULL_INDEX && islandIndexB != B3_NULL_INDEX ) + { + B3_VALIDATE( 0 <= islandIndexA && islandIndexA < baseBodyCount ); + B3_VALIDATE( 0 <= islandIndexB && islandIndexB < baseBodyCount ); + b3IslandUnion( parents, ranks, islandIndexA, islandIndexB, contactCounts, jointCounts ); + int root = b3IslandFindParent( parents, islandIndexA ); + contactCounts[root] += 1; + } + else + { + int islandIndex = islandIndexA != B3_NULL_INDEX ? islandIndexA : islandIndexB; + int root = b3IslandFindParent( parents, islandIndex ); + contactCounts[root] += 1; + } + } + + // Union over joints, tracking per-component joint counts + for ( int i = 0; i < baseJointCount; ++i ) + { + int bodyIdA = baseJoints[i].bodyIdA; + int bodyIdB = baseJoints[i].bodyIdB; + B3_VALIDATE( 0 <= bodyIdA && bodyIdA < world->bodies.count ); + B3_VALIDATE( 0 <= bodyIdB && bodyIdB < world->bodies.count ); + b3Body* bodyA = bodies + bodyIdA; + b3Body* bodyB = bodies + bodyIdB; + int islandIndexA = bodyA->islandIndex; + int islandIndexB = bodyB->islandIndex; + + // Only connect non-static bodies + if ( islandIndexA != B3_NULL_INDEX && islandIndexB != B3_NULL_INDEX ) + { + B3_VALIDATE( 0 <= islandIndexA && islandIndexA < baseBodyCount ); + B3_VALIDATE( 0 <= islandIndexB && islandIndexB < baseBodyCount ); + b3IslandUnion( parents, ranks, islandIndexA, islandIndexB, contactCounts, jointCounts ); + int root = b3IslandFindParent( parents, islandIndexA ); + jointCounts[root] += 1; + } + else + { + int islandIndex = islandIndexA != B3_NULL_INDEX ? islandIndexA : islandIndexB; + int root = b3IslandFindParent( parents, islandIndex ); + jointCounts[root] += 1; + } + } + + // Done with ranks + b3StackFree( alloc, ranks ); + ranks = NULL; + + // Flatten all parent indices and count connected components. + int componentCount = 0; + for ( int i = 0; i < baseBodyCount; ++i ) + { + parents[i] = b3IslandFindParent( parents, i ); + if ( parents[i] == i ) + { + componentCount += 1; + } + } + + // Early return — island is still fully connected, no split needed. + if ( componentCount == 1 ) + { + baseIsland->constraintRemoveCount = 0; + b3StackFree( alloc, jointCounts ); + b3StackFree( alloc, contactCounts ); + b3StackFree( alloc, parents ); + return; + } + + // Detach body/contact/joint arrays from base island so b3DestroyIsland won't free them + baseIsland->bodies.data = NULL; + baseIsland->bodies.count = 0; + baseIsland->bodies.capacity = 0; + + baseIsland->contacts.data = NULL; + baseIsland->contacts.count = 0; + baseIsland->contacts.capacity = 0; + + baseIsland->joints.data = NULL; + baseIsland->joints.count = 0; + baseIsland->joints.capacity = 0; + + // Null so code below doesn't accidentally use this. + baseIsland = NULL; + + // Map from body index to new island index. Only set for root bodies. + int* rootMap = b3StackAlloc( alloc, baseBodyCount * sizeof( int ), "root map" ); + for ( int i = 0; i < baseBodyCount; ++i ) + { + rootMap[i] = B3_NULL_INDEX; + } + + int* componentBodyCounts = b3StackAlloc( alloc, componentCount * sizeof( int ), "component body counts" ); + int* componentContactCounts = b3StackAlloc( alloc, componentCount * sizeof( int ), "component contact counts" ); + int* componentJointCounts = b3StackAlloc( alloc, componentCount * sizeof( int ), "component joint counts" ); + int islandCount = 0; + + // Find the root body for each body and create islands as needed. + // Extract per-component counts from the root nodes' accumulated counts. + for ( int i = 0; i < baseBodyCount; ++i ) + { + int rootIndex = parents[i]; + if ( rootMap[rootIndex] == B3_NULL_INDEX ) + { + rootMap[rootIndex] = islandCount; + componentBodyCounts[islandCount] = 0; + componentContactCounts[islandCount] = contactCounts[rootIndex]; + componentJointCounts[islandCount] = jointCounts[rootIndex]; + islandCount += 1; + } + + componentBodyCounts[rootMap[rootIndex]] += 1; + } + + B3_ASSERT( islandCount == componentCount ); + + // Map from new island index to island id + int* islandIds = b3StackAlloc( alloc, islandCount * sizeof( int ), "island ids" ); + + // Create new islands and reserve body/contact/joint arrays + for ( int i = 0; i < islandCount; ++i ) + { + // WARNING: this invalidates baseIsland pointer + b3Island* newIsland = b3CreateIsland( world, b3_awakeSet ); + islandIds[i] = newIsland->islandId; + + // Reserve arrays to avoid wasteful growth and memcpy. + b3Array_Reserve( newIsland->bodies, componentBodyCounts[i] ); + b3Array_Reserve( newIsland->contacts, componentContactCounts[i] ); + b3Array_Reserve( newIsland->joints, componentJointCounts[i] ); + } + + // Assign bodies to new islands + for ( int i = 0; i < baseBodyCount; ++i ) + { + int bodyId = baseBodyIds[i]; + int root = b3IslandFindParent( parents, i ); + int newIslandId = islandIds[rootMap[root]]; + + b3Body* body = b3Array_Get( world->bodies, bodyId ); + b3Island* newIsland = b3Array_Get( world->islands, newIslandId ); + + body->islandId = newIslandId; + body->islandIndex = newIsland->bodies.count; + + // Ensure the array has the correct capacity + B3_VALIDATE( newIsland->bodies.count < newIsland->bodies.capacity ); + b3Array_Push( newIsland->bodies, bodyId ); + } + + // Assign contacts to the island of their bodies + for ( int i = 0; i < baseContactCount; ++i ) + { + b3ContactLink* link = baseContacts + i; + b3Contact* contact = b3Array_Get( world->contacts, link->contactId ); + + // Static bodies don't have an island id. + b3Body* bodyA = b3Array_Get( world->bodies, link->bodyIdA ); + b3Body* bodyB = b3Array_Get( world->bodies, link->bodyIdB ); + int targetIslandId = bodyA->islandId != B3_NULL_INDEX ? bodyA->islandId : bodyB->islandId; + + b3Island* targetIsland = b3Array_Get( world->islands, targetIslandId ); + contact->islandId = targetIslandId; + contact->islandIndex = targetIsland->contacts.count; + + // Ensure the array has the correct capacity + B3_VALIDATE( targetIsland->contacts.count < targetIsland->contacts.capacity ); + b3Array_Push( targetIsland->contacts, *link ); + } + + // Assign joints to the island of their bodies + for ( int i = 0; i < baseJointCount; ++i ) + { + b3JointLink* link = baseJoints + i; + b3Joint* joint = b3Array_Get( world->joints, link->jointId ); + + // Static bodies don't have an island id. + b3Body* bodyA = b3Array_Get( world->bodies, link->bodyIdA ); + b3Body* bodyB = b3Array_Get( world->bodies, link->bodyIdB ); + int targetIslandId = bodyA->islandId != B3_NULL_INDEX ? bodyA->islandId : bodyB->islandId; + + b3Island* targetIsland = b3Array_Get( world->islands, targetIslandId ); + joint->islandId = targetIslandId; + joint->islandIndex = targetIsland->joints.count; + + // Ensure the array has the correct capacity + B3_VALIDATE( targetIsland->joints.count < targetIsland->joints.capacity ); + b3Array_Push( targetIsland->joints, *link ); + } + + // Destroy the base island + b3DestroyIsland( world, baseId ); + + // Free the detached arrays manually + b3Free( baseBodyIds, baseBodyCapacity * sizeof( int ) ); + b3Free( baseContacts, baseContactCapacity * sizeof( b3ContactLink ) ); + b3Free( baseJoints, baseJointCapacity * sizeof( b3JointLink ) ); + + // Free arena items in LIFO order + b3StackFree( alloc, islandIds ); + b3StackFree( alloc, componentJointCounts ); + b3StackFree( alloc, componentContactCounts ); + b3StackFree( alloc, componentBodyCounts ); + b3StackFree( alloc, rootMap ); + b3StackFree( alloc, jointCounts ); + b3StackFree( alloc, contactCounts ); + b3StackFree( alloc, parents ); +} + +// 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 union find and +// touches a lot of memory, so it can be 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 b3SplitIslandTask( void* context ) +{ + b3TracyCZoneNC( split, "Split Island", b3_colorOlive, true ); + + uint64_t ticks = b3GetTicks(); + b3World* world = context; + + B3_ASSERT( world->splitIslandId != B3_NULL_INDEX ); + + b3SplitIsland( world, world->splitIslandId ); + + world->splitIslandId = B3_NULL_INDEX; + world->profile.splitIslands += b3GetMilliseconds( ticks ); + b3TracyCZoneEnd( split ); +} + +#if B3_ENABLE_VALIDATION +void b3ValidateIsland( b3World* world, int islandId ) +{ + if ( islandId == B3_NULL_INDEX ) + { + return; + } + + b3Island* island = b3Array_Get( world->islands, islandId ); + B3_ASSERT( island->islandId == islandId ); + B3_ASSERT( island->setIndex != B3_NULL_INDEX ); + + { + B3_ASSERT( island->bodies.count > 0 ); + B3_ASSERT( island->bodies.count <= b3GetIdCount( &world->bodyIdPool ) ); + + for ( int i = 0; i < island->bodies.count; ++i ) + { + b3Body* body = b3Array_Get( world->bodies, island->bodies.data[i] ); + B3_ASSERT( body->islandId == islandId ); + B3_ASSERT( body->islandIndex == i ); + B3_ASSERT( body->setIndex == island->setIndex ); + } + } + + if ( island->contacts.count > 0 ) + { + B3_ASSERT( island->contacts.count <= b3GetIdCount( &world->contactIdPool ) ); + + for ( int i = 0; i < island->contacts.count; ++i ) + { + b3ContactLink* link = island->contacts.data + i; + b3Contact* contact = b3Array_Get( world->contacts, link->contactId ); + B3_ASSERT( contact->setIndex == island->setIndex ); + B3_ASSERT( contact->islandId == islandId ); + B3_ASSERT( contact->islandIndex == i ); + } + } + + if ( island->joints.count > 0 ) + { + B3_ASSERT( island->joints.count <= b3GetIdCount( &world->jointIdPool ) ); + + for ( int i = 0; i < island->joints.count; ++i ) + { + b3JointLink* link = island->joints.data + i; + b3Joint* joint = b3Array_Get( world->joints, link->jointId ); + B3_ASSERT( joint->setIndex == island->setIndex ); + B3_ASSERT( joint->islandId == islandId ); + B3_ASSERT( joint->islandIndex == i ); + } + } +} + +#else + +void b3ValidateIsland( b3World* world, int islandId ) +{ + B3_UNUSED( world ); + B3_UNUSED( islandId ); +} +#endif diff --git a/src/island.h b/src/island.h new file mode 100644 index 0000000..d37bb09 --- /dev/null +++ b/src/island.h @@ -0,0 +1,110 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "container.h" + +#include + +typedef struct b3Contact b3Contact; +typedef struct b3Joint b3Joint; +typedef struct b3World b3World; + +// Cached contact data stored in the island for fast contiguous iteration. +// Avoids touching b3Contact during union-find in b3SplitIsland. +typedef struct b3ContactLink +{ + int contactId; + int bodyIdA; + int bodyIdB; +} b3ContactLink; + +b3DeclareArray( b3ContactLink ); + +// Cached joint data stored in the island for fast contiguous iteration. +typedef struct b3JointLink +{ + int jointId; + int bodyIdA; + int bodyIdB; +} b3JointLink; + +b3DeclareArray( b3JointLink ); + +// 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. +// Contacts are touching. +// Contacts and joints may connect to static bodies, but static bodies are not in the island. +// https://en.wikipedia.org/wiki/Component_(graph_theory) +// https://en.wikipedia.org/wiki/Dynamic_connectivity +typedef struct b3Island +{ + // index of solver set stored in b3World + // may be B3_NULL_INDEX + int setIndex; + + // island index within set + // may be B3_NULL_INDEX + int localIndex; + + int islandId; + + // 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; + + // I tried using a stack array for this but the data pointer goes out of + // sync when the world island array grows. + b3ArrayC( int ) bodies; + + // Contacts and joints that belong to this island. May connect to static + // bodies not in the island. + // Each link has the two body ids so that b3SplitIsland's union-find pass + // never needs to touch b3Contact/b3Joint. + b3ArrayC( b3ContactLink ) contacts; + b3ArrayC( b3JointLink ) joints; + +} b3Island; + +// This is used to move islands across solver sets +typedef struct b3IslandSim +{ + int islandId; +} b3IslandSim; + +#ifdef __cplusplus +extern "C" +{ +#endif + +b3Island* b3CreateIsland( b3World* world, int setIndex ); +void b3DestroyIsland( b3World* world, int islandId ); + +// Link contacts into the island graph when it starts having contact points +void b3LinkContact( b3World* world, b3Contact* contact ); + +// Unlink contact from the island graph when it stops having contact points +void b3UnlinkContact( b3World* world, b3Contact* contact ); + +// Link a joint into the island graph when it is created +void b3LinkJoint( b3World* world, b3Joint* joint ); + +// Unlink a joint from the island graph when it is destroyed +void b3UnlinkJoint( b3World* world, b3Joint* joint ); + +void b3SplitIsland( b3World* world, int baseId ); +void b3SplitIslandTask( void* context ); + +void b3ValidateIsland( b3World* world, int islandId ); + +#ifdef __cplusplus +} +#endif diff --git a/src/joint.c b/src/joint.c new file mode 100644 index 0000000..3a7e832 --- /dev/null +++ b/src/joint.c @@ -0,0 +1,1725 @@ +// SPDX-FileCopyrightText: 2025 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 "box3d/box3d.h" + +#include +#include +#include + +static b3JointDef b3DefaultJointDef( void ) +{ + b3JointDef def = { 0 }; + def.localFrameA.q = b3Quat_identity; + def.localFrameB.q = b3Quat_identity; + def.forceThreshold = FLT_MAX; + def.torqueThreshold = FLT_MAX; + def.constraintHertz = 60.0f; + def.constraintDampingRatio = 2.0f; + def.drawScale = b3GetLengthUnitsPerMeter(); + def.internalValue = B3_SECRET_COOKIE; + return def; +} + +b3ParallelJointDef b3DefaultParallelJointDef( void ) +{ + b3ParallelJointDef def = { 0 }; + def.base = b3DefaultJointDef(); + def.hertz = 1.0f; + def.dampingRatio = 1.0f; + def.maxTorque = FLT_MAX; + return def; +} + +b3DistanceJointDef b3DefaultDistanceJointDef( void ) +{ + b3DistanceJointDef def = { 0 }; + def.base = b3DefaultJointDef(); + def.lowerSpringForce = -FLT_MAX; + def.upperSpringForce = FLT_MAX; + def.length = 1.0f; + def.maxLength = B3_HUGE; + return def; +} + +b3MotorJointDef b3DefaultMotorJointDef( void ) +{ + b3MotorJointDef def = { 0 }; + def.base = b3DefaultJointDef(); + return def; +} + +b3FilterJointDef b3DefaultFilterJointDef( void ) +{ + b3FilterJointDef def = { 0 }; + def.base = b3DefaultJointDef(); + return def; +} + +b3PrismaticJointDef b3DefaultPrismaticJointDef( void ) +{ + b3PrismaticJointDef def = { 0 }; + def.base = b3DefaultJointDef(); + return def; +} + +b3RevoluteJointDef b3DefaultRevoluteJointDef( void ) +{ + b3RevoluteJointDef def = { 0 }; + def.base = b3DefaultJointDef(); + return def; +} + +b3SphericalJointDef b3DefaultSphericalJointDef( void ) +{ + b3SphericalJointDef def = { 0 }; + def.base = b3DefaultJointDef(); + def.targetRotation = b3Quat_identity; + return def; +} + +b3WeldJointDef b3DefaultWeldJointDef( void ) +{ + b3WeldJointDef def = { 0 }; + def.base = b3DefaultJointDef(); + return def; +} + +b3WheelJointDef b3DefaultWheelJointDef( void ) +{ + b3WheelJointDef def = { 0 }; + def.base = b3DefaultJointDef(); + def.enableSuspensionSpring = true; + def.suspensionHertz = 1.0f; + def.suspensionDampingRatio = 0.7f; + def.steeringHertz = 1.0f; + def.steeringDampingRatio = 0.7f; + return def; +} + +b3ExplosionDef b3DefaultExplosionDef( void ) +{ + b3ExplosionDef def = { 0 }; + def.maskBits = B3_DEFAULT_MASK_BITS; + return def; +} + +b3Joint* b3GetJointFullId( b3World* world, b3JointId jointId ) +{ + int id = jointId.index1 - 1; + b3Joint* joint = b3Array_Get( world->joints, id ); + B3_ASSERT( joint->jointId == id && joint->generation == jointId.generation ); + return joint; +} + +b3JointSim* b3GetJointSim( b3World* world, b3Joint* joint ) +{ + if ( joint->setIndex == b3_awakeSet ) + { + B3_ASSERT( 0 <= joint->colorIndex && joint->colorIndex < B3_GRAPH_COLOR_COUNT ); + b3GraphColor* color = world->constraintGraph.colors + joint->colorIndex; + return b3Array_Get( color->jointSims, joint->localIndex ); + } + + b3SolverSet* set = b3Array_Get( world->solverSets, joint->setIndex ); + return b3Array_Get( set->jointSims, joint->localIndex ); +} + +b3JointSim* b3GetJointSimCheckType( b3JointId jointId, b3JointType type ) +{ + B3_UNUSED( type ); + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + B3_ASSERT( joint->type == type ); + b3JointSim* jointSim = b3GetJointSim( world, joint ); + B3_ASSERT( jointSim->type == type ); + return jointSim; +} + +typedef struct b3JointPair +{ + b3Joint* joint; + b3JointSim* jointSim; +} b3JointPair; + +static b3JointPair b3CreateJoint( b3World* world, const b3JointDef* def, b3JointType type ) +{ + B3_ASSERT( b3IsValidTransform( def->localFrameA ) ); + B3_ASSERT( b3IsValidTransform( def->localFrameB ) ); + + b3Body* bodyA = b3GetBodyFullId( world, def->bodyIdA ); + b3Body* bodyB = b3GetBodyFullId( world, def->bodyIdB ); + + int bodyIdA = bodyA->id; + int bodyIdB = bodyB->id; + int maxSetIndex = b3MaxInt( bodyA->setIndex, bodyB->setIndex ); + + // Create joint id and joint + int jointId = b3AllocId( &world->jointIdPool ); + if ( jointId == world->joints.count ) + { + b3Array_Push( world->joints, (b3Joint){ 0 } ); + } + + b3Joint* joint = b3Array_Get( world->joints, jointId ); + joint->jointId = jointId; + joint->userData = def->userData; + joint->generation += 1; + joint->setIndex = B3_NULL_INDEX; + joint->colorIndex = B3_NULL_INDEX; + joint->localIndex = B3_NULL_INDEX; + joint->islandId = B3_NULL_INDEX; + joint->islandIndex = B3_NULL_INDEX; + joint->drawScale = def->drawScale; + joint->type = type; + joint->collideConnected = def->collideConnected; + + // Doubly linked list on bodyA + joint->edges[0].bodyId = bodyIdA; + joint->edges[0].prevKey = B3_NULL_INDEX; + joint->edges[0].nextKey = bodyA->headJointKey; + + int keyA = ( jointId << 1 ) | 0; + if ( bodyA->headJointKey != B3_NULL_INDEX ) + { + b3Joint* jointA = b3Array_Get( world->joints, bodyA->headJointKey >> 1 ); + b3JointEdge* 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 = B3_NULL_INDEX; + joint->edges[1].nextKey = bodyB->headJointKey; + + int keyB = ( jointId << 1 ) | 1; + if ( bodyB->headJointKey != B3_NULL_INDEX ) + { + b3Joint* jointB = b3Array_Get( world->joints, bodyB->headJointKey >> 1 ); + b3JointEdge* edgeB = jointB->edges + ( bodyB->headJointKey & 1 ); + edgeB->prevKey = keyB; + } + bodyB->headJointKey = keyB; + bodyB->jointCount += 1; + + b3JointSim* jointSim; + + if ( bodyA->setIndex == b3_disabledSet || bodyB->setIndex == b3_disabledSet ) + { + // if either body is disabled, create in disabled set + b3SolverSet* set = b3Array_Get( world->solverSets, b3_disabledSet ); + joint->setIndex = b3_disabledSet; + joint->localIndex = set->jointSims.count; + + jointSim = b3Array_Emplace( set->jointSims ); + memset( jointSim, 0, sizeof( b3JointSim ) ); + + jointSim->jointId = jointId; + jointSim->bodyIdA = bodyIdA; + jointSim->bodyIdB = bodyIdB; + } + else if ( bodyA->type != b3_dynamicBody && bodyB->type != b3_dynamicBody ) + { + // joint is not attached to a dynamic body + b3SolverSet* set = b3Array_Get( world->solverSets, b3_staticSet ); + joint->setIndex = b3_staticSet; + joint->localIndex = set->jointSims.count; + + jointSim = b3Array_Emplace( set->jointSims ); + memset( jointSim, 0, sizeof( b3JointSim ) ); + + jointSim->jointId = jointId; + jointSim->bodyIdA = bodyIdA; + jointSim->bodyIdB = bodyIdB; + } + else if ( bodyA->setIndex == b3_awakeSet || bodyB->setIndex == b3_awakeSet ) + { + // if either body is sleeping, wake it + if ( maxSetIndex >= b3_firstSleepingSet ) + { + b3WakeSolverSet( world, maxSetIndex ); + } + + joint->setIndex = b3_awakeSet; + + jointSim = b3CreateJointInGraph( world, joint ); + jointSim->jointId = jointId; + jointSim->bodyIdA = bodyIdA; + jointSim->bodyIdB = bodyIdB; + } + else + { + // joint connected between sleeping and/or static bodies + B3_ASSERT( bodyA->setIndex >= b3_firstSleepingSet || bodyB->setIndex >= b3_firstSleepingSet ); + B3_ASSERT( bodyA->setIndex != b3_staticSet || bodyB->setIndex != b3_staticSet ); + + // joint should go into the sleeping set (not static set) + int setIndex = maxSetIndex; + + b3SolverSet* set = b3Array_Get( world->solverSets, setIndex ); + joint->setIndex = setIndex; + joint->localIndex = set->jointSims.count; + + jointSim = b3Array_Emplace( set->jointSims ); + memset( jointSim, 0, sizeof( b3JointSim ) ); + + jointSim->jointId = jointId; + jointSim->bodyIdA = bodyIdA; + jointSim->bodyIdB = bodyIdB; + + if ( bodyA->setIndex != bodyB->setIndex && bodyA->setIndex >= b3_firstSleepingSet && + bodyB->setIndex >= b3_firstSleepingSet ) + { + // merge sleeping sets + b3MergeSolverSets( world, bodyA->setIndex, bodyB->setIndex ); + B3_ASSERT( bodyA->setIndex == bodyB->setIndex ); + + // fix potentially invalid set index + setIndex = bodyA->setIndex; + + b3SolverSet* mergedSet = b3Array_Get( world->solverSets, setIndex ); + + // Careful! The joint sim pointer was orphaned by the set merge. + jointSim = b3Array_Get( mergedSet->jointSims, joint->localIndex ); + } + + B3_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 = (b3Softness){ + .biasRate = 0.0f, + .massScale = 1.0f, + .impulseScale = 0.0f, + }; + + B3_ASSERT( b3IsValidFloat( def->forceThreshold ) && def->forceThreshold >= 0.0f ); + B3_ASSERT( b3IsValidFloat( def->torqueThreshold ) && def->torqueThreshold >= 0.0f ); + + jointSim->forceThreshold = def->forceThreshold; + jointSim->torqueThreshold = def->torqueThreshold; + + B3_ASSERT( jointSim->jointId == jointId ); + B3_ASSERT( jointSim->bodyIdA == bodyIdA ); + B3_ASSERT( jointSim->bodyIdB == bodyIdB ); + + if ( joint->setIndex > b3_disabledSet ) + { + // Add edge to island graph + b3LinkJoint( world, joint ); + } + + b3ValidateSolverSets( world ); + + return (b3JointPair){ joint, jointSim }; +} + +static void b3DestroyContactsBetweenBodies( b3World* world, b3Body* bodyA, b3Body* 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 != B3_NULL_INDEX ) + { + int contactId = contactKey >> 1; + int edgeIndex = contactKey & 1; + + b3Contact* contact = b3Array_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 + b3DestroyContact( world, contact, wakeBodies ); + } + } + + b3ValidateSolverSets( world ); +} + +void b3Joint_SetConstraintTuning( b3JointId jointId, float hertz, float dampingRatio ) +{ + B3_ASSERT( b3IsValidFloat( hertz ) && hertz >= 0.0f ); + B3_ASSERT( b3IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f ); + + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + b3JointSim* base = b3GetJointSim( world, joint ); + base->constraintHertz = hertz; + base->constraintDampingRatio = dampingRatio; +} + +void b3Joint_GetConstraintTuning( b3JointId jointId, float* hertz, float* dampingRatio ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + b3JointSim* base = b3GetJointSim( world, joint ); + *hertz = base->constraintHertz; + *dampingRatio = base->constraintDampingRatio; +} + +void b3Joint_SetForceThreshold( b3JointId jointId, float threshold ) +{ + B3_ASSERT( b3IsValidFloat( threshold ) && threshold >= 0.0f ); + + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + b3JointSim* base = b3GetJointSim( world, joint ); + base->forceThreshold = threshold; +} + +float b3Joint_GetForceThreshold( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + b3JointSim* base = b3GetJointSim( world, joint ); + return base->forceThreshold; +} + +void b3Joint_SetTorqueThreshold( b3JointId jointId, float threshold ) +{ + B3_ASSERT( b3IsValidFloat( threshold ) && threshold >= 0.0f ); + + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + b3JointSim* base = b3GetJointSim( world, joint ); + base->torqueThreshold = threshold; +} + +float b3Joint_GetTorqueThreshold( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + b3JointSim* base = b3GetJointSim( world, joint ); + return base->torqueThreshold; +} + +b3JointId b3CreateDistanceJoint( b3WorldId worldId, const b3DistanceJointDef* def ) +{ + B3_CHECK_JOINT_DEF( def ); + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if (world == NULL) + { + return (b3JointId){ 0 }; + } + + B3_ASSERT( b3IsValidFloat( def->length ) && def->length > 0.0f ); + B3_ASSERT( def->lowerSpringForce <= def->upperSpringForce ); + + b3JointPair pair = b3CreateJoint( world, &def->base, b3_distanceJoint ); + + b3JointSim* joint = pair.jointSim; + + joint->distanceJoint = (b3DistanceJoint){ 0 }; + joint->distanceJoint.length = b3MaxFloat( def->length, B3_LINEAR_SLOP ); + joint->distanceJoint.hertz = def->hertz; + joint->distanceJoint.dampingRatio = def->dampingRatio; + joint->distanceJoint.lowerSpringForce = def->lowerSpringForce; + joint->distanceJoint.upperSpringForce = def->upperSpringForce; + joint->distanceJoint.minLength = b3MaxFloat( def->minLength, B3_LINEAR_SLOP ); + joint->distanceJoint.maxLength = b3MaxFloat( def->minLength, def->maxLength ); + joint->distanceJoint.maxMotorForce = def->maxMotorForce; + joint->distanceJoint.motorSpeed = def->motorSpeed; + joint->distanceJoint.enableSpring = def->enableSpring; + 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; + + b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation }; + return jointId; +} + +b3JointId b3CreateMotorJoint( b3WorldId worldId, const b3MotorJointDef* def ) +{ + B3_CHECK_JOINT_DEF( def ); + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return (b3JointId){ 0 }; + } + + b3JointPair pair = b3CreateJoint( world, &def->base, b3_motorJoint ); + b3JointSim* joint = pair.jointSim; + + joint->motorJoint = (b3MotorJoint){ 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; + + b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation }; + return jointId; +} + +b3JointId b3CreateFilterJoint( b3WorldId worldId, const b3FilterJointDef* def ) +{ + B3_CHECK_JOINT_DEF( def ); + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if (world == NULL) + { + return (b3JointId){ 0 }; + } + + b3JointPair pair = b3CreateJoint( world, &def->base, b3_filterJoint ); + + b3JointSim* joint = pair.jointSim; + + b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation }; + return jointId; +} + +b3JointId b3CreateParallelJoint( b3WorldId worldId, const b3ParallelJointDef* def ) +{ + B3_CHECK_JOINT_DEF( def ); + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if (world == NULL) + { + return (b3JointId){ 0 }; + } + + B3_ASSERT( b3IsValidFloat( def->hertz ) && def->hertz >= 0.0f ); + B3_ASSERT( b3IsValidFloat( def->dampingRatio ) && def->dampingRatio >= 0.0f ); + B3_ASSERT( b3IsValidFloat( def->maxTorque ) && def->maxTorque >= 0.0f ); + + b3JointPair pair = b3CreateJoint( world, &def->base, b3_parallelJoint ); + + b3JointSim* joint = pair.jointSim; + + joint->parallelJoint = (b3ParallelJoint){ 0 }; + joint->parallelJoint.hertz = def->hertz; + joint->parallelJoint.dampingRatio = def->dampingRatio; + joint->parallelJoint.maxTorque = def->maxTorque; + + b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation }; + return jointId; +} + +b3JointId b3CreatePrismaticJoint( b3WorldId worldId, const b3PrismaticJointDef* def ) +{ + B3_CHECK_JOINT_DEF( def ); + B3_ASSERT( def->lowerTranslation <= def->upperTranslation ); + + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if (world == NULL) + { + return (b3JointId){ 0 }; + } + + b3JointPair pair = b3CreateJoint( world, &def->base, b3_prismaticJoint ); + + b3JointSim* joint = pair.jointSim; + + joint->prismaticJoint = (b3PrismaticJoint){ 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; + + b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation }; + return jointId; +} + +b3JointId b3CreateRevoluteJoint( b3WorldId worldId, const b3RevoluteJointDef* def ) +{ + B3_CHECK_JOINT_DEF( def ); + B3_ASSERT( def->lowerAngle <= def->upperAngle ); + B3_ASSERT( def->lowerAngle >= -0.99f * B3_PI ); + B3_ASSERT( def->upperAngle <= 0.99f * B3_PI ); + + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if (world == NULL) + { + return (b3JointId){ 0 }; + } + + b3JointPair pair = b3CreateJoint( world, &def->base, b3_revoluteJoint ); + + b3JointSim* joint = pair.jointSim; + + joint->revoluteJoint = (b3RevoluteJoint){ 0 }; + joint->revoluteJoint.hertz = def->hertz; + joint->revoluteJoint.dampingRatio = def->dampingRatio; + joint->revoluteJoint.targetAngle = b3ClampFloat( def->targetAngle, -B3_PI, B3_PI ); + joint->revoluteJoint.lowerAngle = b3MinFloat( def->lowerAngle, def->upperAngle ); + joint->revoluteJoint.upperAngle = b3MaxFloat( def->lowerAngle, def->upperAngle ); + joint->revoluteJoint.lowerAngle = b3ClampFloat( joint->revoluteJoint.lowerAngle, -B3_PI, B3_PI ); + joint->revoluteJoint.upperAngle = b3ClampFloat( joint->revoluteJoint.upperAngle, -B3_PI, B3_PI ); + 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; + + b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation }; + return jointId; +} + +b3JointId b3CreateSphericalJoint( b3WorldId worldId, const b3SphericalJointDef* def ) +{ + B3_CHECK_JOINT_DEF( def ); + B3_ASSERT( def->lowerTwistAngle <= def->upperTwistAngle ); + B3_ASSERT( def->lowerTwistAngle >= -0.99f * B3_PI ); + B3_ASSERT( def->upperTwistAngle <= 0.99f * B3_PI ); + B3_ASSERT( 0.0f <= def->coneAngle && def->coneAngle <= 0.99f * B3_PI ); + B3_ASSERT( b3IsValidQuat( def->targetRotation ) ); + + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if (world == NULL) + { + return (b3JointId){ 0 }; + } + + b3JointPair pair = b3CreateJoint( world, &def->base, b3_sphericalJoint ); + + b3JointSim* joint = pair.jointSim; + + joint->sphericalJoint = (b3SphericalJoint){ 0 }; + joint->sphericalJoint.hertz = def->hertz; + joint->sphericalJoint.dampingRatio = def->dampingRatio; + joint->sphericalJoint.targetRotation = def->targetRotation; + joint->sphericalJoint.coneAngle = b3ClampFloat( def->coneAngle, 0.0f, 0.5f * B3_PI ); + joint->sphericalJoint.lowerTwistAngle = b3MinFloat( def->lowerTwistAngle, def->upperTwistAngle ); + joint->sphericalJoint.upperTwistAngle = b3MaxFloat( def->lowerTwistAngle, def->upperTwistAngle ); + joint->sphericalJoint.lowerTwistAngle = b3ClampFloat( joint->sphericalJoint.lowerTwistAngle, -B3_PI, B3_PI ); + joint->sphericalJoint.upperTwistAngle = b3ClampFloat( joint->sphericalJoint.upperTwistAngle, -B3_PI, B3_PI ); + joint->sphericalJoint.maxMotorTorque = def->maxMotorTorque; + joint->sphericalJoint.motorVelocity = def->motorVelocity; + joint->sphericalJoint.enableSpring = def->enableSpring; + joint->sphericalJoint.enableConeLimit = def->enableConeLimit; + joint->sphericalJoint.enableTwistLimit = def->enableTwistLimit; + joint->sphericalJoint.enableMotor = def->enableMotor; + + b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation }; + return jointId; +} + +b3JointId b3CreateWeldJoint( b3WorldId worldId, const b3WeldJointDef* def ) +{ + B3_CHECK_JOINT_DEF( def ); + B3_ASSERT( 0.0f <= def->angularHertz ); + B3_ASSERT( 0.0f <= def->angularDampingRatio ); + B3_ASSERT( 0.0f <= def->linearHertz ); + B3_ASSERT( 0.0f <= def->linearDampingRatio ); + + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if (world == NULL) + { + return (b3JointId){ 0 }; + } + + b3JointPair pair = b3CreateJoint( world, &def->base, b3_weldJoint ); + + b3JointSim* joint = pair.jointSim; + + joint->weldJoint = (b3WeldJoint){ 0 }; + joint->weldJoint.linearHertz = def->linearHertz; + joint->weldJoint.linearDampingRatio = def->linearDampingRatio; + joint->weldJoint.angularHertz = def->angularHertz; + joint->weldJoint.angularDampingRatio = def->angularDampingRatio; + + b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation }; + return jointId; +} + +b3JointId b3CreateWheelJoint( b3WorldId worldId, const b3WheelJointDef* def ) +{ + B3_CHECK_JOINT_DEF( def ); + B3_ASSERT( def->lowerSuspensionLimit <= def->upperSuspensionLimit ); + + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if (world == NULL) + { + return (b3JointId){ 0 }; + } + + b3JointPair pair = b3CreateJoint( world, &def->base, b3_wheelJoint ); + + b3JointSim* joint = pair.jointSim; + + joint->wheelJoint = (b3WheelJoint){ 0 }; + joint->wheelJoint.enableSuspensionSpring = def->enableSuspensionSpring; + joint->wheelJoint.suspensionHertz = def->suspensionHertz; + joint->wheelJoint.suspensionDampingRatio = def->suspensionDampingRatio; + joint->wheelJoint.enableSuspensionLimit = def->enableSuspensionLimit; + joint->wheelJoint.lowerSuspensionLimit = def->lowerSuspensionLimit; + joint->wheelJoint.upperSuspensionLimit = def->upperSuspensionLimit; + joint->wheelJoint.enableSpinMotor = def->enableSpinMotor; + joint->wheelJoint.maxSpinTorque = def->maxSpinTorque; + joint->wheelJoint.spinSpeed = def->spinSpeed; + + joint->wheelJoint.enableSteering = def->enableSteering; + joint->wheelJoint.steeringHertz = def->steeringHertz; + joint->wheelJoint.steeringDampingRatio = def->steeringDampingRatio; + joint->wheelJoint.targetSteeringAngle = def->targetSteeringAngle; + joint->wheelJoint.maxSteeringTorque = def->maxSteeringTorque; + joint->wheelJoint.enableSteeringLimit = def->enableSteeringLimit; + joint->wheelJoint.lowerSteeringLimit = def->lowerSteeringLimit; + joint->wheelJoint.upperSteeringLimit = def->upperSteeringLimit; + + b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation }; + return jointId; +} + +void b3DestroyJointInternal( b3World* world, b3Joint* joint, bool wakeBodies ) +{ + int jointId = joint->jointId; + + b3JointEdge* edgeA = joint->edges + 0; + b3JointEdge* edgeB = joint->edges + 1; + + int idA = edgeA->bodyId; + int idB = edgeB->bodyId; + b3Body* bodyA = b3Array_Get( world->bodies, idA ); + b3Body* bodyB = b3Array_Get( world->bodies, idB ); + + // Remove from body A + if ( edgeA->prevKey != B3_NULL_INDEX ) + { + b3Joint* prevJoint = b3Array_Get( world->joints, edgeA->prevKey >> 1 ); + b3JointEdge* prevEdge = prevJoint->edges + ( edgeA->prevKey & 1 ); + prevEdge->nextKey = edgeA->nextKey; + } + + if ( edgeA->nextKey != B3_NULL_INDEX ) + { + b3Joint* nextJoint = b3Array_Get( world->joints, edgeA->nextKey >> 1 ); + b3JointEdge* 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 != B3_NULL_INDEX ) + { + b3Joint* prevJoint = b3Array_Get( world->joints, edgeB->prevKey >> 1 ); + b3JointEdge* prevEdge = prevJoint->edges + ( edgeB->prevKey & 1 ); + prevEdge->nextKey = edgeB->nextKey; + } + + if ( edgeB->nextKey != B3_NULL_INDEX ) + { + b3Joint* nextJoint = b3Array_Get( world->joints, edgeB->nextKey >> 1 ); + b3JointEdge* 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 != B3_NULL_INDEX ) + { + B3_ASSERT( joint->setIndex > b3_disabledSet ); + b3UnlinkJoint( world, joint ); + } + else + { + B3_ASSERT( joint->setIndex <= b3_disabledSet ); + } + + // Remove joint from solver set that owns it + int setIndex = joint->setIndex; + int localIndex = joint->localIndex; + + if ( setIndex == b3_awakeSet ) + { + b3RemoveJointFromGraph( world, joint->edges[0].bodyId, joint->edges[1].bodyId, joint->colorIndex, localIndex ); + } + else + { + b3SolverSet* set = b3Array_Get( world->solverSets, setIndex ); + int movedIndex = b3Array_RemoveSwap( set->jointSims, localIndex ); + if ( movedIndex != B3_NULL_INDEX ) + { + // Fix moved joint + b3JointSim* movedJointSim = set->jointSims.data + localIndex; + int movedId = movedJointSim->jointId; + b3Joint* movedJoint = b3Array_Get( world->joints, movedId ); + B3_ASSERT( movedJoint->localIndex == movedIndex ); + movedJoint->localIndex = localIndex; + } + } + + // Free joint and id (preserve joint revision) + joint->setIndex = B3_NULL_INDEX; + joint->localIndex = B3_NULL_INDEX; + joint->colorIndex = B3_NULL_INDEX; + joint->jointId = B3_NULL_INDEX; + b3FreeId( &world->jointIdPool, jointId ); + + if ( wakeBodies ) + { + b3WakeBody( world, bodyA ); + b3WakeBody( world, bodyB ); + } + + b3ValidateSolverSets( world ); +} + +void b3DestroyJoint( b3JointId jointId, bool wakeAttached ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + if ( world == NULL ) + { + return; + } + + b3Joint* joint = b3GetJointFullId( world, jointId ); + + b3DestroyJointInternal( world, joint, wakeAttached ); +} + +b3JointType b3Joint_GetType( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + return joint->type; +} + +b3BodyId b3Joint_GetBodyA( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + return b3MakeBodyId( world, joint->edges[0].bodyId ); +} + +b3BodyId b3Joint_GetBodyB( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + return b3MakeBodyId( world, joint->edges[1].bodyId ); +} + +b3WorldId b3Joint_GetWorld( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + return (b3WorldId){ (uint16_t)( jointId.world0 + 1 ), world->generation }; +} + +void b3Joint_SetLocalFrameA( b3JointId jointId, b3Transform localFrame ) +{ + B3_ASSERT( b3IsValidTransform( localFrame ) ); + + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + b3JointSim* jointSim = b3GetJointSim( world, joint ); + jointSim->localFrameA = localFrame; +} + +b3Transform b3Joint_GetLocalFrameA( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + b3JointSim* jointSim = b3GetJointSim( world, joint ); + return jointSim->localFrameA; +} + +void b3Joint_SetLocalFrameB( b3JointId jointId, b3Transform localFrame ) +{ + B3_ASSERT( b3IsValidTransform( localFrame ) ); + + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + b3JointSim* jointSim = b3GetJointSim( world, joint ); + jointSim->localFrameB = localFrame; +} + +b3Transform b3Joint_GetLocalFrameB( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + b3JointSim* jointSim = b3GetJointSim( world, joint ); + return jointSim->localFrameB; +} + +void b3Joint_SetCollideConnected( b3JointId jointId, bool shouldCollide ) +{ + b3World* world = b3GetUnlockedWorld( jointId.world0 ); + if ( world == NULL ) + { + return; + } + + b3Joint* joint = b3GetJointFullId( world, jointId ); + if ( joint->collideConnected == shouldCollide ) + { + return; + } + + joint->collideConnected = shouldCollide; + + b3Body* bodyA = b3Array_Get( world->bodies, joint->edges[0].bodyId ); + b3Body* bodyB = b3Array_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 != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + + if ( shape->proxyKey != B3_NULL_INDEX ) + { + b3BufferMove( &world->broadPhase, shape->proxyKey ); + } + + shapeId = shape->nextShapeId; + } + } + else + { + b3DestroyContactsBetweenBodies( world, bodyA, bodyB ); + } +} + +bool b3Joint_GetCollideConnected( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + return joint->collideConnected; +} + +void b3Joint_SetUserData( b3JointId jointId, void* userData ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + joint->userData = userData; +} + +void* b3Joint_GetUserData( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + return joint->userData; +} + +void b3Joint_WakeBodies( b3JointId jointId ) +{ + b3World* world = b3GetUnlockedWorld( jointId.world0 ); + if ( world == NULL ) + { + return; + } + + world->locked = true; + + b3Joint* joint = b3GetJointFullId( world, jointId ); + b3Body* bodyA = b3Array_Get( world->bodies, joint->edges[0].bodyId ); + b3Body* bodyB = b3Array_Get( world->bodies, joint->edges[1].bodyId ); + + b3WakeBody( world, bodyA ); + b3WakeBody( world, bodyB ); + + world->locked = false; +} + +void b3GetJointReaction( b3World* world, b3JointSim* sim, float invTimeStep, float* force, float* torque ) +{ + float linearImpulse = 0.0f; + float angularImpulse = 0.0f; + + switch ( sim->type ) + { + case b3_parallelJoint: + { + b3ParallelJoint* joint = &sim->parallelJoint; + b3Vec3 impulse = { + .x = joint->perpImpulse.x, + .y = joint->perpImpulse.y, + .z = 0.0f, + }; + angularImpulse = b3Length( impulse ); + } + break; + + case b3_distanceJoint: + { + b3DistanceJoint* joint = &sim->distanceJoint; + linearImpulse = b3AbsFloat( joint->impulse + joint->lowerImpulse - joint->upperImpulse + joint->motorImpulse ); + } + break; + + case b3_motorJoint: + { + b3MotorJoint* joint = &sim->motorJoint; + linearImpulse = b3Length( b3Add( joint->linearVelocityImpulse, joint->linearSpringImpulse ) ); + angularImpulse = b3Length( b3Add( joint->angularVelocityImpulse, joint->angularSpringImpulse ) ); + } + break; + + case b3_prismaticJoint: + { + b3PrismaticJoint* joint = &sim->prismaticJoint; + b3Vec3 impulse = { + .x = joint->motorImpulse + joint->lowerImpulse - joint->upperImpulse, + .y = joint->perpImpulse.x, + .z = joint->perpImpulse.y, + }; + linearImpulse = b3Length( impulse ); + angularImpulse = b3Length( joint->angularImpulse ); + } + break; + + case b3_revoluteJoint: + { + b3RevoluteJoint* joint = &sim->revoluteJoint; + linearImpulse = b3Length( joint->linearImpulse ); + b3Vec3 impulse = { + .x = joint->perpImpulse.x, + .y = joint->perpImpulse.y, + .z = joint->motorImpulse + joint->lowerImpulse - joint->upperImpulse, + }; + angularImpulse = b3Length( impulse ); + } + break; + + case b3_sphericalJoint: + { + // todo improve performance + b3SphericalJoint* joint = &sim->sphericalJoint; + linearImpulse = b3Length( joint->linearImpulse ); + + b3Transform xfA = b3GetBodyTransform( world, sim->bodyIdA ); + b3Transform xfB = b3GetBodyTransform( world, sim->bodyIdB ); + b3Quat qA = b3MulQuat( xfA.q, sim->localFrameA.q ); + b3Quat qB = b3MulQuat( xfB.q, sim->localFrameB.q ); + + // Cone axis is the z-axis of body A. + b3Vec3 coneAxis = b3RotateVector( qA, b3Vec3_axisZ ); + b3Vec3 twistAxis = b3RotateVector( qB, b3Vec3_axisZ ); + b3Vec3 swingAxis = b3Normalize( b3Cross( coneAxis, twistAxis ) ); + + b3Vec3 impulse = b3Add( joint->springImpulse, joint->motorImpulse ); + impulse = b3MulAdd( impulse, joint->lowerTwistImpulse - joint->upperTwistImpulse, twistAxis ); + impulse = b3MulAdd( impulse, joint->swingImpulse, swingAxis ); + + angularImpulse = b3Length( impulse ); + } + break; + + case b3_weldJoint: + { + b3WeldJoint* joint = &sim->weldJoint; + linearImpulse = b3Length( joint->linearImpulse ); + angularImpulse = b3Length( joint->angularImpulse ); + } + break; + + case b3_wheelJoint: + { + // todo probably wrong + b3WheelJoint* joint = &sim->wheelJoint; + b3Vec2 perpImpulse = joint->linearImpulse; + float axialImpulse = joint->suspensionSpringImpulse + joint->lowerSuspensionImpulse - joint->upperSuspensionImpulse; + linearImpulse = sqrtf( perpImpulse.x * perpImpulse.x + perpImpulse.y * perpImpulse.y + axialImpulse * axialImpulse ); + angularImpulse = b3AbsFloat( joint->spinImpulse ); + } + break; + + default: + break; + } + + *force = linearImpulse * invTimeStep; + *torque = angularImpulse * invTimeStep; +} + +static b3Vec3 b3GetJointConstraintForce( b3World* world, b3Joint* joint ) +{ + b3JointSim* base = b3GetJointSim( world, joint ); + + switch ( joint->type ) + { + case b3_parallelJoint: + return b3Vec3_zero; + + case b3_distanceJoint: + return b3GetDistanceJointForce( world, base ); + + case b3_filterJoint: + return b3Vec3_zero; + + case b3_motorJoint: + return b3GetMotorJointForce( world, base ); + + case b3_prismaticJoint: + return b3GetPrismaticJointForce( world, base ); + + case b3_revoluteJoint: + return b3GetRevoluteJointForce( world, base ); + + case b3_sphericalJoint: + return b3GetSphericalJointForce( world, base ); + + case b3_weldJoint: + return b3GetWeldJointForce( world, base ); + + case b3_wheelJoint: + return b3GetWheelJointForce( world, base ); + + default: + B3_ASSERT( false ); + return b3Vec3_zero; + } +} + +static b3Vec3 b3GetJointConstraintTorque( b3World* world, b3Joint* joint ) +{ + b3JointSim* base = b3GetJointSim( world, joint ); + + switch ( joint->type ) + { + case b3_distanceJoint: + return b3Vec3_zero; + + case b3_filterJoint: + return b3Vec3_zero; + + case b3_motorJoint: + return b3GetMotorJointTorque( world, base ); + + case b3_prismaticJoint: + return b3GetPrismaticJointTorque( world, base ); + + case b3_revoluteJoint: + return b3GetRevoluteJointTorque( world, base ); + + case b3_sphericalJoint: + return b3GetSphericalJointTorque( world, base ); + + case b3_weldJoint: + return b3GetWeldJointTorque( world, base ); + + case b3_wheelJoint: + return b3GetWheelJointTorque( world, base ); + + default: + B3_ASSERT( false ); + return b3Vec3_zero; + } +} + +b3Vec3 b3Joint_GetConstraintForce( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + return b3GetJointConstraintForce( world, joint ); +} + +b3Vec3 b3Joint_GetConstraintTorque( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + return b3GetJointConstraintTorque( world, joint ); +} + +float b3Joint_GetLinearSeparation( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + b3JointSim* base = b3GetJointSim( world, joint ); + + b3Transform xfA = b3GetBodyTransform( world, joint->edges[0].bodyId ); + b3Transform xfB = b3GetBodyTransform( world, joint->edges[1].bodyId ); + + b3Vec3 pA = b3TransformPoint( xfA, base->localFrameA.p ); + b3Vec3 pB = b3TransformPoint( xfB, base->localFrameB.p ); + b3Vec3 dp = b3Sub( pB, pA ); + + switch ( joint->type ) + { + case b3_parallelJoint: + return 0.0f; + + case b3_distanceJoint: + { + b3DistanceJoint* distanceJoint = &base->distanceJoint; + float length = b3Length( 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 b3AbsFloat( length - distanceJoint->length ); + } + + case b3_motorJoint: + return 0.0f; + + case b3_filterJoint: + return 0.0f; + + case b3_prismaticJoint: + { + b3PrismaticJoint* prismaticJoint = &base->prismaticJoint; + b3Vec3 axisA = b3RotateVector( xfA.q, b3Vec3_axisX ); + b3Vec3 perpA = b3Perp( axisA ); + float perpendicularSeparation = b3AbsFloat( b3Dot( perpA, dp ) ); + float limitSeparation = 0.0f; + + if ( prismaticJoint->enableLimit ) + { + float translation = b3Dot( 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 b3_revoluteJoint: + return b3Length( dp ); + + case b3_sphericalJoint: + return b3Length( dp ); + + case b3_weldJoint: + { + b3WeldJoint* weldJoint = &base->weldJoint; + if ( weldJoint->linearHertz == 0.0f ) + { + return b3Length( dp ); + } + + return 0.0f; + } + + case b3_wheelJoint: + { + b3WheelJoint* wheelJoint = &base->wheelJoint; + b3Vec3 axisA = b3RotateVector( xfA.q, b3Vec3_axisX ); + b3Vec3 perpA = b3Perp( axisA ); + float perpendicularSeparation = b3AbsFloat( b3Dot( perpA, dp ) ); + float limitSeparation = 0.0f; + + if ( wheelJoint->enableSuspensionLimit ) + { + float translation = b3Dot( axisA, dp ); + if ( translation < wheelJoint->lowerSuspensionLimit ) + { + limitSeparation = wheelJoint->lowerSuspensionLimit - translation; + } + + if ( wheelJoint->upperSuspensionLimit < translation ) + { + limitSeparation = translation - wheelJoint->upperSuspensionLimit; + } + } + + return sqrtf( perpendicularSeparation * perpendicularSeparation + limitSeparation * limitSeparation ); + } + + default: + B3_ASSERT( false ); + return 0.0f; + } +} + +float b3Joint_GetAngularSeparation( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + b3JointSim* base = b3GetJointSim( world, joint ); + + b3Transform xfA = b3GetBodyTransform( world, joint->edges[0].bodyId ); + b3Transform xfB = b3GetBodyTransform( world, joint->edges[1].bodyId ); + + b3Quat relQ = b3InvMulQuat( xfA.q, xfB.q ); + + switch ( joint->type ) + { + case b3_parallelJoint: + { + // Remove hinge angle + relQ.v.z = 0.0f; + return b3GetQuatAngle( relQ ); + } + + case b3_distanceJoint: + return 0.0f; + + case b3_motorJoint: + return 0.0f; + + case b3_filterJoint: + return 0.0f; + + case b3_prismaticJoint: + return b3GetQuatAngle( relQ ); + + case b3_revoluteJoint: + { + b3RevoluteJoint* revoluteJoint = &base->revoluteJoint; + if ( revoluteJoint->enableLimit ) + { + float angle = b3GetTwistAngle( relQ ); + if ( angle < revoluteJoint->lowerAngle ) + { + return b3GetQuatAngle( relQ ); + } + + if ( revoluteJoint->upperAngle < angle ) + { + return b3GetQuatAngle( relQ ); + } + } + + // Remove hinge angle + relQ.v.z = 0.0f; + return b3GetQuatAngle( relQ ); + } + + case b3_sphericalJoint: + { + b3SphericalJoint* sphericalJoint = &base->sphericalJoint; + float sum = 0.0f; + if ( sphericalJoint->enableConeLimit ) + { + float swingAngle = b3GetSwingAngle( relQ ); + sum += b3MaxFloat( 0.0f, swingAngle - sphericalJoint->coneAngle ); + } + + if ( sphericalJoint->enableTwistLimit ) + { + float twistAngle = b3GetTwistAngle( relQ ); + sum += b3MaxFloat( 0.0f, sphericalJoint->lowerTwistAngle - twistAngle ); + sum += b3MaxFloat( 0.0f, twistAngle - sphericalJoint->upperTwistAngle ); + } + + return sum; + } + + case b3_weldJoint: + { + b3WeldJoint* weldJoint = &base->weldJoint; + if ( weldJoint->angularHertz == 0.0f ) + { + return b3GetQuatAngle( relQ ); + } + + return 0.0f; + } + + case b3_wheelJoint: + // todo + B3_ASSERT( false ); + return 0.0f; + + default: + B3_ASSERT( false ); + return 0.0f; + } +} + +#if 0 +void b3Joint_SetSpringRotationTarget( b3JointId jointId, b3Quat relativeBodyRotation, float hertz ) +{ + B3_ASSERT( b3IsValidQuat( relativeBodyRotation ) ); + B3_ASSERT( b3IsValidFloat( hertz ) && hertz > 0.0f ); + + b3World* world = b3GetWorld( jointId.world0 ); + b3Joint* joint = b3GetJointFullId( world, jointId ); + b3JointSim* base = b3GetJointSim( world, joint ); + + b3Quat qA = base->localFrameA.q; + b3Quat qB = b3MulQuat( relativeBodyRotation, base->localFrameB.q ); + + // This keeps the twist angle in the range [-pi, pi] + if ( b3DotQuat( qA, qB ) < 0.0f ) + { + qA = -qA; + } + + b3Quat relQ = b3InvMulQuat( qA, qB ); + + switch ( joint->type ) + { + case b3_revoluteJoint: + base->revoluteJoint.targetAngle = b3GetTwistAngle( relQ ); + base->revoluteJoint.hertz = hertz; + break; + + case b3_sphericalJoint: + base->sphericalJoint.targetRotation = relQ; + base->sphericalJoint.hertz = hertz; + break; + + default: + break; + } +} +#endif + +void b3PrepareJoint( b3JointSim* joint, b3StepContext* context ) +{ + // Clamp joint hertz based on the time step to reduce jitter. + float hertz = b3MinFloat( joint->constraintHertz, 0.25f * context->inv_h ); + joint->constraintSoftness = b3MakeSoft( hertz, joint->constraintDampingRatio, context->h ); + + switch ( joint->type ) + { + case b3_parallelJoint: + b3PrepareParallelJoint( joint, context ); + break; + + case b3_distanceJoint: + b3PrepareDistanceJoint( joint, context ); + break; + + case b3_filterJoint: + break; + + case b3_motorJoint: + b3PrepareMotorJoint( joint, context ); + break; + + case b3_prismaticJoint: + b3PreparePrismaticJoint( joint, context ); + break; + + case b3_revoluteJoint: + b3PrepareRevoluteJoint( joint, context ); + break; + + case b3_sphericalJoint: + b3PrepareSphericalJoint( joint, context ); + break; + + case b3_weldJoint: + b3PrepareWeldJoint( joint, context ); + break; + + case b3_wheelJoint: + b3PrepareWheelJoint( joint, context ); + break; + + default: + B3_ASSERT( false ); + } +} + +void b3WarmStartJoint( b3JointSim* joint, b3StepContext* context ) +{ + switch ( joint->type ) + { + case b3_parallelJoint: + b3WarmStartParallelJoint( joint, context ); + break; + + case b3_distanceJoint: + b3WarmStartDistanceJoint( joint, context ); + break; + + case b3_filterJoint: + break; + + case b3_motorJoint: + b3WarmStartMotorJoint( joint, context ); + break; + + case b3_prismaticJoint: + b3WarmStartPrismaticJoint( joint, context ); + break; + + case b3_revoluteJoint: + b3WarmStartRevoluteJoint( joint, context ); + break; + + case b3_sphericalJoint: + b3WarmStartSphericalJoint( joint, context ); + break; + + case b3_weldJoint: + b3WarmStartWeldJoint( joint, context ); + break; + + case b3_wheelJoint: + b3WarmStartWheelJoint( joint, context ); + break; + + default: + B3_ASSERT( false ); + } +} + +void b3SolveJoint( b3JointSim* joint, b3StepContext* context, bool useBias ) +{ + B3_UNUSED( useBias ); + + switch ( joint->type ) + { + case b3_parallelJoint: + b3SolveParallelJoint( joint, context ); + break; + + case b3_distanceJoint: + b3SolveDistanceJoint( joint, context, useBias ); + break; + + case b3_filterJoint: + break; + + case b3_motorJoint: + b3SolveMotorJoint( joint, context ); + break; + + case b3_prismaticJoint: + b3SolvePrismaticJoint( joint, context, useBias ); + break; + + case b3_revoluteJoint: + b3SolveRevoluteJoint( joint, context, useBias ); + break; + + case b3_sphericalJoint: + b3SolveSphericalJoint( joint, context, useBias ); + break; + + case b3_weldJoint: + b3SolveWeldJoint( joint, context, useBias ); + break; + + case b3_wheelJoint: + b3SolveWheelJoint( joint, context, useBias ); + break; + + default: + B3_ASSERT( false ); + } +} + +void b3PrepareJoints_Overflow( b3StepContext* context ) +{ + b3TracyCZoneNC( prepare_joints, "PrepJoints", b3_colorOldLace, true ); + + b3ConstraintGraph* graph = context->graph; + b3JointSim* joints = graph->colors[B3_OVERFLOW_INDEX].jointSims.data; + int jointCount = graph->colors[B3_OVERFLOW_INDEX].jointSims.count; + + for ( int i = 0; i < jointCount; ++i ) + { + b3JointSim* joint = joints + i; + b3PrepareJoint( joint, context ); + } + + b3TracyCZoneEnd( prepare_joints ); +} + +void b3WarmStartJoints_Overflow( b3StepContext* context ) +{ + b3TracyCZoneNC( prepare_joints, "PrepJoints", b3_colorOldLace, true ); + + b3ConstraintGraph* graph = context->graph; + b3JointSim* joints = graph->colors[B3_OVERFLOW_INDEX].jointSims.data; + int jointCount = graph->colors[B3_OVERFLOW_INDEX].jointSims.count; + + for ( int i = 0; i < jointCount; ++i ) + { + b3JointSim* joint = joints + i; + b3WarmStartJoint( joint, context ); + } + + b3TracyCZoneEnd( prepare_joints ); +} + +void b3SolveJoints_Overflow( b3StepContext* context, bool useBias ) +{ + b3TracyCZoneNC( solve_joints, "SolveJoints", b3_colorLemonChiffon, true ); + + b3ConstraintGraph* graph = context->graph; + b3JointSim* joints = graph->colors[B3_OVERFLOW_INDEX].jointSims.data; + int jointCount = graph->colors[B3_OVERFLOW_INDEX].jointSims.count; + + for ( int i = 0; i < jointCount; ++i ) + { + b3JointSim* joint = joints + i; + b3SolveJoint( joint, context, useBias ); + } + + b3TracyCZoneEnd( solve_joints ); +} + +void b3DrawJoint( b3DebugDraw* draw, b3World* world, b3Joint* joint ) +{ + b3Body* bodyA = b3Array_Get( world->bodies, joint->edges[0].bodyId ); + b3Body* bodyB = b3Array_Get( world->bodies, joint->edges[1].bodyId ); + if ( bodyA->setIndex == b3_disabledSet || bodyB->setIndex == b3_disabledSet ) + { + return; + } + + b3JointSim* jointSim = b3GetJointSim( world, joint ); + + b3Transform transformA = b3GetBodyTransformQuick( world, bodyA ); + b3Transform transformB = b3GetBodyTransformQuick( world, bodyB ); + b3Vec3 pA = b3TransformPoint( transformA, jointSim->localFrameA.p ); + b3Vec3 pB = b3TransformPoint( transformB, jointSim->localFrameB.p ); + + b3HexColor color = b3_colorDarkSeaGreen; + + float scale = b3MaxFloat( 0.0001f, draw->jointScale * joint->drawScale ); + + switch ( joint->type ) + { + case b3_parallelJoint: + b3DrawParallelJoint( draw, jointSim, transformA, transformB, scale ); + break; + + case b3_distanceJoint: + b3DrawDistanceJoint( draw, jointSim, transformA, transformB ); + break; + + case b3_filterJoint: + draw->DrawSegmentFcn( pA, pB, b3_colorGold, draw->context ); + break; + + case b3_motorJoint: + draw->DrawPointFcn( pA, 8.0f, b3_colorYellowGreen, draw->context ); + draw->DrawPointFcn( pB, 8.0f, b3_colorPlum, draw->context ); + break; + + case b3_prismaticJoint: + b3DrawPrismaticJoint( draw, jointSim, transformA, transformB, scale ); + break; + + case b3_revoluteJoint: + b3DrawRevoluteJoint( draw, jointSim, transformA, transformB, scale ); + break; + + case b3_sphericalJoint: + b3DrawSphericalJoint( draw, jointSim, transformA, transformB, scale ); + break; + + case b3_weldJoint: + b3DrawWeldJoint( draw, jointSim, transformA, transformB, scale ); + break; + + case b3_wheelJoint: + b3DrawWheelJoint( draw, jointSim, transformA, transformB, scale ); + break; + + default: + draw->DrawSegmentFcn( transformA.p, pA, color, draw->context ); + draw->DrawSegmentFcn( pA, pB, color, draw->context ); + draw->DrawSegmentFcn( transformB.p, pB, color, draw->context ); + break; + } + + if ( draw->drawGraphColors ) + { + b3HexColor graphColors[B3_GRAPH_COLOR_COUNT] = { + b3_colorRed, b3_colorOrange, b3_colorYellow, b3_colorGreen, b3_colorCyan, b3_colorBlue, + b3_colorViolet, b3_colorPink, b3_colorChocolate, b3_colorGoldenRod, b3_colorCoral, b3_colorRosyBrown, + b3_colorAqua, b3_colorPeru, b3_colorLime, b3_colorGold, b3_colorPlum, b3_colorSnow, + b3_colorTeal, b3_colorKhaki, b3_colorSalmon, b3_colorPeachPuff, b3_colorHoneyDew, b3_colorBlack, + }; + + int colorIndex = joint->colorIndex; + if ( colorIndex != B3_NULL_INDEX ) + { + b3Vec3 p = b3Lerp( pA, pB, 0.5f ); + draw->DrawPointFcn( p, 5.0f, graphColors[colorIndex], draw->context ); + } + } + + if ( draw->drawJointExtras ) + { + b3Vec3 force = b3GetJointConstraintForce( world, joint ); + b3Vec3 torque = b3GetJointConstraintTorque( world, joint ); + b3Vec3 p = b3Lerp( pA, pB, 0.5f ); + + draw->DrawSegmentFcn( p, b3MulAdd( p, 0.001f, force ), b3_colorAzure, draw->context ); + + char buffer[64]; + snprintf( buffer, 64, "f = %g, t = %g", b3Length( force ), b3Length( torque ) ); + draw->DrawStringFcn( p, buffer, b3_colorAzure, draw->context ); + } +} diff --git a/src/joint.h b/src/joint.h new file mode 100644 index 0000000..49af3f4 --- /dev/null +++ b/src/joint.h @@ -0,0 +1,424 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "math_internal.h" +#include "solver.h" + +#include "box3d/types.h" + +typedef struct b3DebugDraw b3DebugDraw; +typedef struct b3StepContext b3StepContext; +typedef struct b3World b3World; + +/// 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 b3JointEdge +{ + int bodyId; + int prevKey; + int nextKey; +} b3JointEdge; + +// Map from b3JointId to b3Joint in the solver sets +typedef struct b3Joint +{ + void* userData; + + // index of simulation set stored in b3World + // B3_NULL_INDEX when slot is free + int setIndex; + + // index into the constraint graph color array, may be B3_NULL_INDEX for sleeping/disabled joints + // B3_NULL_INDEX when slot is free + int colorIndex; + + // joint index within set or graph color + // B3_NULL_INDEX when slot is free + int localIndex; + + b3JointEdge edges[2]; + + int jointId; + int islandId; + + // Index into the island's joints array for O(1) swap-removal. + // B3_NULL_INDEX when not in an island. + int islandIndex; + + float drawScale; + + b3JointType type; + + // This is monotonically advanced when a body is allocated in this slot + // Used to check for invalid b3JointId + uint16_t generation; + + bool collideConnected; +} b3Joint; + +typedef struct b3DistanceJoint +{ + 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; + b3Vec3 anchorA; + b3Vec3 anchorB; + b3Vec3 deltaCenter; + b3Softness distanceSoftness; + float axialMass; + + bool enableSpring; + bool enableLimit; + bool enableMotor; +} b3DistanceJoint; + +typedef struct b3MotorJoint +{ + b3Vec3 linearVelocity; + b3Vec3 angularVelocity; + float maxVelocityForce; + float maxVelocityTorque; + float linearHertz; + float linearDampingRatio; + float maxSpringForce; + float angularHertz; + float angularDampingRatio; + float maxSpringTorque; + + b3Vec3 linearVelocityImpulse; + b3Vec3 angularVelocityImpulse; + b3Vec3 linearSpringImpulse; + b3Vec3 angularSpringImpulse; + + b3Softness linearSpring; + b3Softness angularSpring; + + int indexA; + int indexB; + b3Transform frameA; + b3Transform frameB; + b3Vec3 deltaCenter; + b3Matrix3 angularMass; +} b3MotorJoint; + +typedef struct b3ParallelJoint +{ + float hertz; + float dampingRatio; + float maxTorque; + + b3Vec2 perpImpulse; + b3Vec3 perpAxisX; + b3Vec3 perpAxisY; + + b3Quat quatA; + b3Quat quatB; + int indexA; + int indexB; + b3Softness softness; +} b3ParallelJoint; + +typedef struct b3PrismaticJoint +{ + b3Vec2 perpImpulse; + b3Vec3 angularImpulse; + float springImpulse; + float motorImpulse; + float lowerImpulse; + float upperImpulse; + float hertz; + float dampingRatio; + float maxMotorForce; + float motorSpeed; + float targetTranslation; + float lowerTranslation; + float upperTranslation; + + int indexA; + int indexB; + b3Transform frameA; + b3Transform frameB; + b3Vec3 jointAxis; + b3Vec3 perpAxisY; + b3Vec3 perpAxisZ; + b3Vec3 deltaCenter; + float deltaAngle; + b3Matrix3 rotationMass; + b3Softness springSoftness; + + bool enableSpring; + bool enableLimit; + bool enableMotor; +} b3PrismaticJoint; + +typedef struct b3RevoluteJoint +{ + b3Vec3 linearImpulse; + b3Vec2 perpImpulse; + float springImpulse; + float motorImpulse; + float lowerImpulse; + float upperImpulse; + float hertz; + float dampingRatio; + float maxMotorTorque; + float motorSpeed; + float targetAngle; + float lowerAngle; + float upperAngle; + + int indexA; + int indexB; + b3Transform frameA; + b3Transform frameB; + b3Vec3 rotationAxisZ; + b3Vec3 perpAxisX; + b3Vec3 perpAxisY; + b3Vec3 deltaCenter; + float deltaAngle; + float axialMass; + b3Softness springSoftness; + + bool enableSpring; + bool enableMotor; + bool enableLimit; +} b3RevoluteJoint; + +typedef struct b3SphericalJoint +{ + b3Vec3 linearImpulse; + b3Vec3 springImpulse; + b3Vec3 motorImpulse; + float lowerTwistImpulse; + float upperTwistImpulse; + float swingImpulse; + float hertz; + float dampingRatio; + float maxMotorTorque; + b3Vec3 motorVelocity; + float lowerTwistAngle; + float upperTwistAngle; + float coneAngle; + b3Quat targetRotation; + + int indexA; + int indexB; + b3Transform frameA; + b3Transform frameB; + b3Vec3 deltaCenter; + b3Vec3 swingAxis; + b3Vec3 twistJacobian; + + b3Matrix3 rotationMass; + float swingMass; + float twistMass; + b3Softness springSoftness; + + bool enableSpring; + bool enableMotor; + bool enableConeLimit; + bool enableTwistLimit; +} b3SphericalJoint; + +typedef struct b3WeldJoint +{ + float linearHertz; + float linearDampingRatio; + float angularHertz; + float angularDampingRatio; + + b3Softness linearSpring; + b3Softness angularSpring; + b3Vec3 linearImpulse; + b3Vec3 angularImpulse; + + int indexA; + int indexB; + b3Transform frameA; + b3Transform frameB; + b3Vec3 deltaCenter; + + b3Matrix3 angularMass; +} b3WeldJoint; + +typedef struct b3WheelJoint +{ + b3Vec2 linearImpulse; + b3Vec2 angularImpulse; + float spinImpulse; + float maxSpinTorque; + float spinSpeed; + float suspensionSpringImpulse; + float lowerSuspensionImpulse; + float upperSuspensionImpulse; + float lowerSuspensionLimit; + float upperSuspensionLimit; + float suspensionHertz; + float suspensionDampingRatio; + float steeringSpringImpulse; + float lowerSteeringImpulse; + float upperSteeringImpulse; + float lowerSteeringLimit; + float upperSteeringLimit; + float targetSteeringAngle; + float maxSteeringTorque; + float steeringHertz; + float steeringDampingRatio; + + int indexA; + int indexB; + b3Transform frameA; + b3Transform frameB; + b3Vec3 deltaCenter; + float spinMass; + float suspensionMass; + float steeringMass; + b3Softness suspensionSoftness; + b3Softness steeringSoftness; + + bool enableSpinMotor; + bool enableSuspensionSpring; + bool enableSuspensionLimit; + bool enableSteering; + bool enableSteeringLimit; + bool enableSteeringMotor; +} b3WheelJoint; + +/// The base joint class. Joints are used to constraint two bodies together in +/// various fashions. Some joints also feature limits and motors. +typedef struct b3JointSim +{ + int jointId; + + int bodyIdA; + int bodyIdB; + + b3JointType type; + + // Joint frames local to body origin + b3Transform localFrameA; + b3Transform localFrameB; + + float invMassA, invMassB; + b3Matrix3 invIA, invIB; + + float constraintHertz; + float constraintDampingRatio; + + b3Softness constraintSoftness; + + float forceThreshold; + float torqueThreshold; + + bool fixedRotation; + + union + { + b3DistanceJoint distanceJoint; + b3MotorJoint motorJoint; + b3ParallelJoint parallelJoint; + b3RevoluteJoint revoluteJoint; + b3SphericalJoint sphericalJoint; + b3PrismaticJoint prismaticJoint; + b3WeldJoint weldJoint; + b3WheelJoint wheelJoint; + }; +} b3JointSim; + +#ifdef __cplusplus +extern "C" +{ +#endif + +void b3DestroyJointInternal( b3World* world, b3Joint* joint, bool wakeBodies ); + +b3Joint* b3GetJointFullId( b3World* world, b3JointId jointId ); +b3JointSim* b3GetJointSim( b3World* world, b3Joint* joint ); +b3JointSim* b3GetJointSimCheckType( b3JointId jointId, b3JointType type ); + +void b3PrepareJoint( b3JointSim* joint, b3StepContext* context ); +void b3WarmStartJoint( b3JointSim* joint, b3StepContext* context ); +void b3SolveJoint( b3JointSim* joint, b3StepContext* context, bool useBias ); + +void b3PrepareJoints_Overflow( b3StepContext* context ); +void b3WarmStartJoints_Overflow( b3StepContext* context ); +void b3SolveJoints_Overflow( b3StepContext* context, bool useBias ); + +void b3GetJointReaction( b3World* world, b3JointSim* sim, float invTimeStep, float* force, float* torque ); + +void b3DrawJoint( b3DebugDraw* draw, b3World* world, b3Joint* joint ); + +b3Vec3 b3GetDistanceJointForce( b3World* world, b3JointSim* base ); +b3Vec3 b3GetMotorJointForce( b3World* world, b3JointSim* base ); +b3Vec3 b3GetPrismaticJointForce( b3World* world, b3JointSim* base ); +b3Vec3 b3GetRevoluteJointForce( b3World* world, b3JointSim* base ); +b3Vec3 b3GetSphericalJointForce( b3World* world, b3JointSim* base ); +b3Vec3 b3GetWeldJointForce( b3World* world, b3JointSim* base ); +b3Vec3 b3GetWheelJointForce( b3World* world, b3JointSim* base ); + +b3Vec3 b3GetMotorJointTorque( b3World* world, b3JointSim* base ); +b3Vec3 b3GetParallelJointTorque( b3World* world, b3JointSim* base ); +b3Vec3 b3GetPrismaticJointTorque( b3World* world, b3JointSim* base ); +b3Vec3 b3GetRevoluteJointTorque( b3World* world, b3JointSim* base ); +b3Vec3 b3GetSphericalJointTorque( b3World* world, b3JointSim* base ); +b3Vec3 b3GetWeldJointTorque( b3World* world, b3JointSim* base ); +b3Vec3 b3GetWheelJointTorque( b3World* world, b3JointSim* base ); + +void b3PrepareDistanceJoint( b3JointSim* base, b3StepContext* context ); +void b3PrepareMotorJoint( b3JointSim* base, b3StepContext* context ); +void b3PrepareParallelJoint( b3JointSim* base, b3StepContext* context ); +void b3PreparePrismaticJoint( b3JointSim* base, b3StepContext* context ); +void b3PrepareRevoluteJoint( b3JointSim* base, b3StepContext* context ); +void b3PrepareSphericalJoint( b3JointSim* base, b3StepContext* context ); +void b3PrepareWeldJoint( b3JointSim* base, b3StepContext* context ); +void b3PrepareWheelJoint( b3JointSim* base, b3StepContext* context ); + +void b3WarmStartDistanceJoint( b3JointSim* base, b3StepContext* context ); +void b3WarmStartMotorJoint( b3JointSim* base, b3StepContext* context ); +void b3WarmStartParallelJoint( b3JointSim* base, b3StepContext* context ); +void b3WarmStartPrismaticJoint( b3JointSim* base, b3StepContext* context ); +void b3WarmStartRevoluteJoint( b3JointSim* base, b3StepContext* context ); +void b3WarmStartSphericalJoint( b3JointSim* base, b3StepContext* context ); +void b3WarmStartWeldJoint( b3JointSim* base, b3StepContext* context ); +void b3WarmStartWheelJoint( b3JointSim* base, b3StepContext* context ); + +void b3SolveDistanceJoint( b3JointSim* base, b3StepContext* context, bool useBias ); +void b3SolveMotorJoint( b3JointSim* base, b3StepContext* context ); +void b3SolveParallelJoint( b3JointSim* base, b3StepContext* context ); +void b3SolvePrismaticJoint( b3JointSim* base, b3StepContext* context, bool useBias ); +void b3SolveRevoluteJoint( b3JointSim* base, b3StepContext* context, bool useBias ); +void b3SolveSphericalJoint( b3JointSim* base, b3StepContext* context, bool useBias ); +void b3SolveWeldJoint( b3JointSim* base, b3StepContext* context, bool useBias ); +void b3SolveWheelJoint( b3JointSim* base, b3StepContext* context, bool useBias ); + +void b3DrawDistanceJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB ); +void b3DrawParallelJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale ); +void b3DrawPrismaticJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale ); +void b3DrawRevoluteJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale ); +void b3DrawSphericalJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale ); +void b3DrawWeldJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale ); +void b3DrawWheelJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale ); + +#ifdef __cplusplus +} +#endif diff --git a/src/manifold.c b/src/manifold.c new file mode 100644 index 0000000..6d4a6b2 --- /dev/null +++ b/src/manifold.c @@ -0,0 +1,246 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +// Dirk Gregorius contributed portions of this code + +#include "manifold.h" + +#include "algorithm.h" +#include "shape.h" + +#include "box3d/math_functions.h" + +// p1 : origin on edge 1 +// e1 : edge 1 +// c1 : shape 1 centroid +// p2 : origin on edge 2 +// e2 : edge 2 +// c2 : shape 2 centroid +float b3EdgeEdgeSeparation( b3Vec3 p1, b3Vec3 e1, b3Vec3 c1, b3Vec3 p2, b3Vec3 e2, b3Vec3 c2 ) +{ + // Build search direction + b3Vec3 u = b3Cross( e1, e2 ); + float length = b3Length( u ); + + // Skip near parallel edges: |e1 x e1| = sin(alpha) * |e1| * |e2| + const float kTolerance = 0.005f; + if ( length < kTolerance * sqrtf( b3LengthSquared( e1 ) * b3LengthSquared( e2 ) ) ) + { + return -FLT_MAX; + } + + if ( length * length < 1000.0f * FLT_MIN ) + { + return -FLT_MAX; + } + + b3Vec3 n = b3MulSV( 1.0f / length, u ); + + // Make sure normal points away from the first shape + // For a triangle, it is possible that N is aligned with the triangle normal and the sign + // value can be close to zero and flicker between small negative and positive values, leading to + // an incorrect separation value. So we assume the other hull has some volume and pick the most + // significant sign value to orient N. + float sign1 = b3Dot( n, b3Sub( p1, c1 ) ); + float sign2 = b3Dot( n, b3Sub( p2, c2 ) ); + if ( b3AbsFloat( sign1 ) > b3AbsFloat( sign2 ) ) + { + if ( sign1 < 0.0f ) + { + n = b3Neg( n ); + } + } + else + { + if ( sign2 > 0.0f ) + { + n = b3Neg( n ); + } + } + + // s = Dot(n, p2) - d = Dot(n, p2) - Dot(n, p1) = Dot(n, p2 - p1) + return b3Dot( n, b3Sub( p2, p1 ) ); +} + +// This was extended to make the wedge shape get the correct incident face. +// Instead of looking directly for the most anti-parallel face, we first find the closest vertex (passed in). +// Then we look for all edges coming out of that vertex and look for the edge that is +// most perpendicular to the reference normal. +// Then from that edge, we select the adjacent face that is most anti-parallel to the reference normal. +int b3FindIncidentFace( const b3Hull* hull, b3Vec3 refNormal, int vertexIndex ) +{ + const b3HullVertex* vertices = b3GetHullVertices( hull ); + const b3HullHalfEdge* edges = b3GetHullEdges( hull ); + const b3Plane* planes = b3GetHullPlanes( hull ); + const b3Vec3* points = b3GetHullPoints( hull ); + + int minEdgeIndex = -1; + float minEdgeProjection = FLT_MAX; + + const b3HullVertex* vertex = vertices + vertexIndex; + B3_ASSERT( vertex ); + + int edgeIndex = vertex->edge; + const b3HullHalfEdge* edge = edges + edgeIndex; + b3Vec3 edgeOrigin = points[edge->origin]; + B3_ASSERT( edge->origin == vertexIndex ); + + do + { + const b3HullHalfEdge* twin = edges + edge->twin; + b3Vec3 twinOrigin = points[twin->origin]; + + b3Vec3 axis = b3Normalize( b3Sub( twinOrigin, edgeOrigin ) ); + float edgeProjection = b3AbsFloat( b3Dot( axis, refNormal ) ); + if ( edgeProjection < minEdgeProjection ) + { + minEdgeIndex = edgeIndex; + minEdgeProjection = edgeProjection; + } + + edgeIndex = twin->next; + edge = edges + edgeIndex; + B3_ASSERT( edge->origin == vertexIndex ); + } + while ( edge != edges + vertex->edge ); + B3_ASSERT( minEdgeIndex >= 0 ); + + const b3HullHalfEdge* minEdge = edges + minEdgeIndex; + int minFaceIndex1 = minEdge->face; + b3Plane minPlane1 = planes[minFaceIndex1]; + + const b3HullHalfEdge* minTwin = edges + minEdge->twin; + int minFaceIndex2 = minTwin->face; + b3Plane minPlane2 = planes[minFaceIndex2]; + + return b3Dot( minPlane1.normal, refNormal ) < b3Dot( minPlane2.normal, refNormal ) ? minFaceIndex1 : minFaceIndex2; +} + +b3FeaturePair b3MakeFeaturePair( b3FeatureOwner owner1, int index1, b3FeatureOwner owner2, int index2 ) +{ + B3_ASSERT( 0 <= index1 && index1 <= UINT8_MAX ); + B3_ASSERT( 0 <= index2 && index2 <= UINT8_MAX ); + + b3FeaturePair pair; + pair.index1 = (uint8_t)index1; + pair.owner1 = (uint8_t)owner1; + pair.index2 = (uint8_t)index2; + pair.owner2 = (uint8_t)owner2; + return pair; +} + +// This logic seems wrong but it is designed so that choosing +// face A or B as the reference face does not change the resulting +// feature pair. This way the contact impulses are persisted even +// if there is reference face flip-flop. This is verified in the +// HullAndHull sample using the b3SATCache with a manual feature +// specified such as b3_manualFaceAxisA. +b3FeaturePair b3FlipPair( b3FeaturePair pair ) +{ + B3_ASSERT( pair.owner1 == 0 || pair.owner1 == 1 ); + B3_ASSERT( pair.owner2 == 0 || pair.owner2 == 1 ); + B3_SWAP( pair.owner1, pair.owner2 ); + pair.owner1 = 1 - pair.owner1; + pair.owner2 = 1 - pair.owner2; + B3_SWAP( pair.index1, pair.index2 ); + return pair; +} + +#if B3_ENABLE_VALIDATION +bool b3ValidatePolygon( b3ClipVertex* polygon, int count ) +{ + // Empty polygons are valid (we can clip away all points when re-constructing manifolds from cache) + if ( count == 0 ) + { + return true; + } + + // Validate that incoming and outgoing edges match + b3ClipVertex vertex1 = polygon[count - 1]; + for ( int i = 0; i < count; ++i ) + { + b3ClipVertex vertex2 = polygon[i]; + + if ( vertex1.pair.owner2 != vertex2.pair.owner1 ) + { + return false; + } + + if ( vertex1.pair.index2 != vertex2.pair.index1 ) + { + return false; + } + + vertex1 = vertex2; + } + + return true; +} +#endif + +int b3ClipPolygon( b3ClipVertex* out, b3ClipVertex* polygon, int count, b3Plane clipPlane, int edge, b3Plane refPlane ) +{ + B3_ASSERT( count >= 3 ); + + b3ClipVertex vertex1 = polygon[count - 1]; + float distance1 = b3PlaneSeparation( clipPlane, vertex1.position ); + int outCount = 0; + + for ( int index = 0; index < count; ++index ) + { + b3ClipVertex vertex2 = polygon[index]; + float distance2 = b3PlaneSeparation( clipPlane, vertex2.position ); + + // Clip edge against plane (Sutherland-Hodgman clipping) + if ( distance1 <= 0.0f && distance2 <= 0.0f ) + { + // Both vertices are behind the plane - keep vertex2 + out[outCount] = vertex2; + outCount += 1; + } + else if ( distance1 <= 0.0f && distance2 > 0.0f ) + { + // Vertex1 is behind of the plane, vertex2 is in front -> intersection point + float fraction = distance1 / ( distance1 - distance2 ); + b3Vec3 position = b3MulAdd( vertex1.position, fraction, b3Sub( vertex2.position, vertex1.position ) ); + + // Keep intersection point and adjust outgoing edge + b3ClipVertex vertex; + vertex.position = position; + vertex.separation = b3PlaneSeparation( refPlane, position ); + vertex.pair = vertex2.pair; + vertex.pair.owner2 = b3_featureShapeA; + vertex.pair.index2 = (uint8_t)edge; + out[outCount] = vertex; + outCount += 1; + } + else if ( distance2 <= 0.0f && distance1 > 0.0f ) + { + // Vertex1 is in front, vertex2 is behind of the plane, -> intersection point + float fraction = distance1 / ( distance1 - distance2 ); + b3Vec3 position = b3MulAdd( vertex1.position, fraction, b3Sub( vertex2.position, vertex1.position ) ); + + // Keep intersection point and adjust incoming edge + b3ClipVertex vertex; + vertex.position = position; + vertex.separation = b3PlaneSeparation( refPlane, position ); + vertex.pair = vertex1.pair; + vertex.pair.owner1 = b3_featureShapeA; + vertex.pair.index1 = (uint8_t)edge; + out[outCount] = vertex; + outCount += 1; + + // And also keep vertex2 + out[outCount] = vertex2; + outCount += 1; + } + + // Keep vertex2 as starting vertex for next edge + vertex1 = vertex2; + distance1 = distance2; + } + + B3_VALIDATE( b3ValidatePolygon( out, outCount ) ); + + return outCount; +} diff --git a/src/manifold.h b/src/manifold.h new file mode 100644 index 0000000..1ff93ed --- /dev/null +++ b/src/manifold.h @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "box3d/collision.h" +#include "box3d/math_functions.h" + +#define B3_MAX_CLIP_POINTS 64 + +typedef struct b3FaceQuery +{ + float separation; + int faceIndex; + int vertexIndex; +} b3FaceQuery; + +typedef struct b3EdgeQuery +{ + float separation; + int indexA; + int indexB; +} b3EdgeQuery; + +typedef struct b3ClipVertex +{ + b3Vec3 position; + float separation; + b3FeaturePair pair; +} b3ClipVertex; + +typedef enum b3FeatureOwner +{ + b3_featureShapeA = 0, + b3_featureShapeB = 1 +} b3FeatureOwner; + +#ifdef __cplusplus +extern "C" +{ +#endif + +float b3EdgeEdgeSeparation( b3Vec3 p1, b3Vec3 e1, b3Vec3 c1, b3Vec3 p2, b3Vec3 e2, b3Vec3 c2 ); +int b3FindIncidentFace( const b3Hull* hull, b3Vec3 refNormal, int vertexIndex ); +b3FeaturePair b3MakeFeaturePair( b3FeatureOwner owner1, int index1, b3FeatureOwner owner2, int index2 ); + +b3FeaturePair b3FlipPair( b3FeaturePair pair ); + +int b3ClipPolygon( b3ClipVertex* out, b3ClipVertex* polygon, int count, b3Plane clipPlane, int edge, b3Plane refPlane ); + +#if B3_ENABLE_VALIDATION +bool b3ValidatePolygon( b3ClipVertex* polygon, int count ); +#endif + +#ifdef __cplusplus +} +#endif + +// For single point contact, such as sphere-sphere, sphere-capsule, sphere-triangle +static const b3FeaturePair b3FeaturePair_single = { 0 }; + +B3_INLINE uint32_t b3MakeFeatureId( b3FeaturePair pair ) +{ + return ( (uint32_t)pair.owner1 << 24 ) | ( (uint32_t)pair.index1 << 16 ) | ( (uint32_t)pair.owner2 << 8 ) | + (uint32_t)pair.index2; +} diff --git a/src/math_functions.c b/src/math_functions.c new file mode 100644 index 0000000..a458767 --- /dev/null +++ b/src/math_functions.c @@ -0,0 +1,587 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "box3d/math_functions.h" + +#include "math_internal.h" + +#include "box3d/collision.h" +#include "box3d/constants.h" + +#include +#include + +bool b3IsValidFloat( float a ) +{ + if ( isnan( a ) ) + { + return false; + } + + if ( isinf( a ) ) + { + return false; + } + + return true; +} + +bool b3IsValidVec3( b3Vec3 a ) +{ + if ( isnan( a.x ) || isnan( a.y ) || isnan( a.z ) ) + { + return false; + } + + if ( isinf( a.x ) || isinf( a.y ) || isinf( a.z ) ) + { + return false; + } + + return true; +} + +bool b3IsValidQuat( b3Quat a ) +{ + if ( isnan( a.v.x ) || isnan( a.v.y ) || isnan( a.v.z ) || isnan( a.s ) ) + { + return false; + } + + if ( isinf( a.v.x ) || isinf( a.v.y ) || isinf( a.v.z ) || isinf( a.s ) ) + { + return false; + } + + return b3IsNormalizedQuat( a ); +} + +bool b3IsValidTransform( b3Transform a ) +{ + return b3IsValidVec3( a.p ) && b3IsValidQuat( a.q ); +} + +bool b3IsValidMatrix3( b3Matrix3 a ) +{ + return b3IsValidVec3( a.cx ) && b3IsValidVec3( a.cy ) && b3IsValidVec3( a.cz ); +} + +bool b3IsValidAABB( b3AABB a ) +{ + if ( b3IsValidVec3( a.lowerBound ) == false ) + { + return false; + } + + if ( b3IsValidVec3( a.upperBound ) == false ) + { + return false; + } + + if ( a.lowerBound.x > a.upperBound.x ) + { + return false; + } + + if ( a.lowerBound.y > a.upperBound.y ) + { + return false; + } + + if ( a.lowerBound.z > a.upperBound.z ) + { + return false; + } + + return true; +} + +bool b3IsSaneAABB( b3AABB a ) +{ + if ( b3IsValidAABB( a ) == false ) + { + return false; + } + + if ( a.lowerBound.x < -B3_HUGE || a.lowerBound.y < -B3_HUGE || a.lowerBound.z < -B3_HUGE ) + { + return false; + } + + if ( a.upperBound.x > B3_HUGE || a.upperBound.y > B3_HUGE || a.upperBound.z > B3_HUGE ) + { + return false; + } + + return true; +} + +bool b3IsValidPlane( b3Plane a ) +{ + if ( b3IsValidVec3( a.normal ) == false ) + { + return false; + } + + if ( b3IsNormalized( a.normal ) == false ) + { + return false; + } + + return b3IsValidFloat( a.offset ); +} + +// https://stackoverflow.com/questions/46210708/atan2-approximation-with-11bits-in-mantissa-on-x86with-sse2-and-armwith-vfpv4 +float b3Atan2( 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 = b3AbsFloat( x ); + float ay = b3AbsFloat( y ); + float mx = b3MaxFloat( ay, ax ); + float mn = b3MinFloat( 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 +b3CosSin b3ComputeCosSin( float radians ) +{ +#if 0 + return { + cosf( radians ), + sinf( radians ), + }; +#else + float x = b3UnwindAngle( radians ); + float pi2 = B3_PI * B3_PI; + + // cosine needs angle in [-pi/2, pi/2] + float c; + if ( x < -0.5f * B3_PI ) + { + float y = x + B3_PI; + float y2 = y * y; + c = -( pi2 - 4.0f * y2 ) / ( pi2 + y2 ); + } + else if ( x > 0.5f * B3_PI ) + { + float y = x - B3_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 + B3_PI; + s = -16.0f * y * ( B3_PI - y ) / ( 5.0f * pi2 - 4.0f * y * ( B3_PI - y ) ); + } + else + { + s = 16.0f * x * ( B3_PI - x ) / ( 5.0f * pi2 - 4.0f * x * ( B3_PI - x ) ); + } + + float mag = sqrtf( s * s + c * c ); + float invMag = mag > 0.0f ? 1.0f / mag : 0.0f; + b3CosSin cs = { c * invMag, s * invMag }; + return cs; +#endif +} + +b3Quat b3MakeQuatFromMatrix( const b3Matrix3* m ) +{ + b3Vec3 c1 = m->cx; + b3Vec3 c2 = m->cy; + b3Vec3 c3 = m->cz; + + b3Quat q; + + float trace = b3Trace( *m ); + if ( trace >= 0.0f ) + { + q.v.x = c2.z - c3.y; + q.v.y = c3.x - c1.z; + q.v.z = c1.y - c2.x; + q.s = trace + 1.0f; + } + else + { + if ( c1.x > c2.y && c1.x > c3.z ) + { + q.v.x = c1.x - c2.y - c3.z + 1.0f; + q.v.y = c2.x + c1.y; + q.v.z = c3.x + c1.z; + q.s = c2.z - c3.y; + } + else if ( c2.y > c3.z ) + { + q.v.x = c1.y + c2.x; + q.v.y = c2.y - c3.z - c1.x + 1.0f; + q.v.z = c3.y + c2.z; + q.s = c3.x - c1.z; + } + else + { + q.v.x = c1.z + c3.x; + q.v.y = c2.z + c3.y; + q.v.z = c3.z - c1.x - c2.y + 1.0f; + q.s = c1.y - c2.x; + } + } + + // The algorithm is simplified and made more accurate by normalizing at the end + return b3NormalizeQuat( q ); +} + +b3Quat b3ComputeQuatBetweenUnitVectors( b3Vec3 v1, b3Vec3 v2 ) +{ + B3_ASSERT( b3IsNormalized( v1 ) ); + B3_ASSERT( b3IsNormalized( v2 ) ); + + b3Quat out; + + b3Vec3 m = b3Lerp( v1, v2, 0.5f ); + float tolerance = 100.0f * FLT_EPSILON; + if ( b3LengthSquared( m ) > tolerance * tolerance ) + { + out.v = b3Cross( v1, m ); + out.s = b3Dot( v1, m ); + } + else + { + // Anti-parallel: Use a perpendicular vector + if ( b3AbsFloat( v1.x ) > 0.5f ) + { + out.v.x = v1.y; + out.v.y = -v1.x; + out.v.z = 0.0f; + } + else + { + out.v.x = 0.0f; + out.v.y = v1.z; + out.v.z = -v1.y; + } + + out.s = 0.0f; + } + + // The algorithm is simplified and made more accurate by normalizing at the end + return b3NormalizeQuat( out ); +} + +//-------------------------------------------------------------------------------------------------- +// Collision utilities +//-------------------------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------------------------- +b3ClosestApproachResult b3ClosestApproachLines( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3 d2 ) +{ + b3ClosestApproachResult result; + + // Solve A*x = b + float a11 = b3Dot( d1, d1 ); + float a12 = -b3Dot( d1, d2 ); + float a21 = b3Dot( d2, d1 ); + float a22 = -b3Dot( d2, d2 ); + + b3Vec3 w = b3Sub( p1, p2 ); + float b1 = -b3Dot( d1, w ); + float b2 = -b3Dot( d2, w ); + + float det = a11 * a22 - a12 * a21; + if ( det * det < 1000.0f * FLT_MIN ) + { + // Lines are parallel - project p2 onto line L1: x1 = p1 + s1 * d1 + float s1 = b3Dot( b3Sub( p2, p1 ), d1 ) / b3Dot( d1, d1 ); + float s2 = 0.0f; + + result.point1 = b3MulAdd( p1, s1, d1 ); + result.lambda1 = s1; + result.point2 = b3MulAdd( p2, s2, d2 ); + result.lambda2 = s2; + + return result; + } + + float s1 = ( a22 * b1 - a12 * b2 ) / det; + float s2 = ( a11 * b2 - a21 * b1 ) / det; + + result.point1 = b3MulAdd( p1, s1, d1 ); + result.lambda1 = s1; + result.point2 = b3MulAdd( p2, s2, d2 ); + result.lambda2 = s2; + return result; +} + +//-------------------------------------------------------------------------------------------------- +b3ClosestApproachResult b3ClosestApproachSegments( b3Vec3 p1, b3Vec3 q1, b3Vec3 p2, b3Vec3 q2 ) +{ + b3ClosestApproachResult result; + + b3Vec3 d1 = b3Sub( q1, p1 ); + b3Vec3 d2 = b3Sub( q2, p2 ); + b3Vec3 r = b3Sub( p1, p2 ); + + float a = b3Dot( d1, d1 ); + float b = b3Dot( d1, d2 ); + float c = b3Dot( d1, r ); + float e = b3Dot( d2, d2 ); + float f = b3Dot( d2, r ); + + // Check if one of the segments degenerates into a point + if ( a < 100.0f * FLT_EPSILON && e < 100.0f * FLT_EPSILON ) + { + // Both segments degenerate into points + result.point1 = p1; + result.lambda1 = 0.0f; + result.point2 = p2; + result.lambda2 = 0.0f; + + return result; + } + + if ( a < 100.0f * FLT_EPSILON ) + { + // First segment degenerates into a point + float s2 = b3ClampFloat( f / e, 0.0f, 1.0f ); + + result.point1 = p1; + result.lambda1 = 0.0f; + result.point2 = b3MulAdd( p2, s2, d2 ); + result.lambda2 = s2; + + return result; + } + + if ( e < 100.0f * FLT_EPSILON ) + { + // Second segment degenerates into a point + float s1 = b3ClampFloat( -c / a, 0.0f, 1.0f ); + + result.point1 = b3MulAdd( p1, s1, d1 ); + result.lambda1 = s1; + result.point2 = p2; + result.lambda2 = 0.0f; + + return result; + } + + // Non-degenerate case + float denom = a * e - b * b; + float s1 = denom > 1000.0f * FLT_MIN ? b3ClampFloat( ( b * f - c * e ) / denom, 0.0f, 1.0f ) : 0.0f; + float s2 = ( b * s1 + f ) / e; + + // Clamp lambda2 and recompute lambda1 if necessary + if ( s2 < 0.0f ) + { + s1 = b3ClampFloat( -c / a, 0.0f, 1.0f ); + s2 = 0.0f; + } + else if ( s2 > 1.0f ) + { + s1 = b3ClampFloat( ( b - c ) / a, 0.0f, 1.0f ); + s2 = 1.0f; + } + + result.point1 = b3MulAdd( p1, s1, d1 ); + result.lambda1 = s1; + result.point2 = b3MulAdd( p2, s2, d2 ); + result.lambda2 = s2; + + return result; +} + +b3Vec3 b3ClosestPointOnSegment( b3Vec3 a, b3Vec3 b, b3Vec3 q ) +{ + b3Vec3 ab = b3Sub( b, a ); + b3Vec3 aq = b3Sub( q, a ); + + float alpha = b3Dot( ab, aq ); + + if ( alpha <= 0.0f ) + { + // q projects outside interval [a, b] on the side of a + return a; + } + else + { + float denominator = b3Dot( ab, ab ); + if ( alpha > denominator ) + { + // q projects outside interval [a, b] on the side of b + return b; + } + else + { + // q projects inside interval [a, b] + alpha /= denominator; + return b3MulAdd( a, alpha, ab ); + } + } +} + +b3TrianglePoint b3ClosestPointOnTriangle( b3Vec3 a, b3Vec3 b, b3Vec3 c, b3Vec3 q ) +{ + // Check if P lies in vertex region of A + b3Vec3 ab = b3Sub( b, a ); + b3Vec3 ac = b3Sub( c, a ); + b3Vec3 aq = b3Sub( q, a ); + + float d1 = b3Dot( ab, aq ); + float d2 = b3Dot( ac, aq ); + if ( d1 <= 0.0f && d2 <= 0.0f ) + { + return (b3TrianglePoint){ a, b3_featureVertex1 }; + } + + // Check if P lies in vertex region of B + b3Vec3 bq = b3Sub( q, b ); + + float d3 = b3Dot( ab, bq ); + float d4 = b3Dot( ac, bq ); + if ( d3 > 0.0f && d4 <= d3 ) + { + return (b3TrianglePoint){ b, b3_featureVertex2 }; + } + + // Check if P lies in edge region AB + float vc = d1 * d4 - d3 * d2; + if ( vc <= 0.0f && d1 >= 0.0f && d3 <= 0.0f ) + { + float t = d1 / ( d1 - d3 ); + return (b3TrianglePoint){ b3MulAdd( a, t, ab ), b3_featureEdge1 }; + } + + // Check if P lies in vertex region of C + b3Vec3 cq = b3Sub( q, c ); + + float d5 = b3Dot( ab, cq ); + float d6 = b3Dot( ac, cq ); + if ( d6 >= 0.0f && d5 <= d6 ) + { + return (b3TrianglePoint){ c, b3_featureVertex3 }; + } + + // Check if P lies in edge region AC + float vb = d5 * d2 - d1 * d6; + if ( vb <= 0.0f && d2 >= 0.0f && d6 <= 0.0f ) + { + float t = d2 / ( d2 - d6 ); + return (b3TrianglePoint){ b3MulAdd( a, t, ac ), b3_featureEdge3 }; + } + + // Check if P lies in edge region of BC + float va = d3 * d6 - d5 * d4; + if ( va <= 0.0f && d4 >= d3 && d5 >= d6 ) + { + b3Vec3 bc = b3Sub( c, b ); + + float t = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ); + return (b3TrianglePoint){ b3MulAdd( b, t, bc ), b3_featureEdge2 }; + } + + // P inside face region ABC + float t1 = vb / ( va + vb + vc ); + float t2 = vc / ( va + vb + vc ); + + b3Vec3 p = b3MulAdd( a, t1, ab ); + p = b3MulAdd( p, t2, ac ); + return (b3TrianglePoint){ p, b3_featureTriangleFace }; +} + +b3Matrix3 b3SphereInertia( float mass, float radius ) +{ + float i = 0.4f * mass * radius * radius; + return b3MakeDiagonalMatrix( i, i, i ); +} + +b3Matrix3 b3CylinderInertia( float mass, float radius, float height ) +{ + float ixx = mass * ( 3 * radius * radius + height * height ) / 12.0f; + float iyy = 0.5f * mass * radius * radius; + return b3MakeDiagonalMatrix( ixx, iyy, ixx ); +} + +b3Matrix3 b3BoxInertia( float mass, b3Vec3 min, b3Vec3 max ) +{ + b3Vec3 delta = b3Sub( max, min ); + float ixx = mass * ( delta.y * delta.y + delta.z * delta.z ) / 12.0f; + float iyy = mass * ( delta.x * delta.x + delta.z * delta.z ) / 12.0f; + float izz = mass * ( delta.x * delta.x + delta.y * delta.y ) / 12.0f; + + return b3MakeDiagonalMatrix( ixx, iyy, izz ); +} + +// https://en.wikipedia.org/wiki/Parallel_axis_theorem +b3Matrix3 b3Steiner( float mass, b3Vec3 origin ) +{ + // Usage: Io = Ic + Is and Ic = Io - Is + float ixx = mass * ( origin.y * origin.y + origin.z * origin.z ); + float iyy = mass * ( origin.x * origin.x + origin.z * origin.z ); + float izz = mass * ( origin.x * origin.x + origin.y * origin.y ); + float ixy = -mass * origin.x * origin.y; + float ixz = -mass * origin.x * origin.z; + float iyz = -mass * origin.y * origin.z; + + // Write + b3Matrix3 out; + out.cx.x = ixx; + out.cy.x = ixy; + out.cz.x = ixz; + out.cx.y = ixy; + out.cy.y = iyy; + out.cz.y = iyz; + out.cx.z = ixz; + out.cy.z = iyz; + out.cz.z = izz; + + return out; +} + +bool b3IsValidRay( const b3RayCastInput* input ) +{ + bool isValid = b3IsValidVec3( input->origin ) && b3IsValidVec3( input->translation ) && + b3IsValidFloat( input->maxFraction ) && 0.0f <= input->maxFraction && input->maxFraction < B3_HUGE; + return isValid; +} diff --git a/src/math_internal.h b/src/math_internal.h new file mode 100644 index 0000000..40b8d54 --- /dev/null +++ b/src/math_internal.h @@ -0,0 +1,513 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "core.h" + +#include "box3d/collision.h" +#include "box3d/math_functions.h" + +struct b3Sweep; +struct b3Plane; + +#define B3_TWO_PI 6.283185307f +#define B3_PI_OVER_TWO 1.570796327f +#define B3_PI_OVER_FOUR 0.785398163f +#define B3_SQRT3 1.732050808f + +// todo eliminate this +static const b3AABB B3_BOUNDS3_EMPTY = { { FLT_MAX, FLT_MAX, FLT_MAX }, { -FLT_MAX, -FLT_MAX, -FLT_MAX } }; + +typedef struct b3Matrix2 +{ + b3Vec2 cx, cy; +} b3Matrix2; + +typedef struct b3Triangle +{ + b3Vec3 vertices[3]; + int i1, i2, i3; + int flags; +} b3Triangle; + +typedef struct +{ + b3Vec3 point; + b3TriangleFeature feature; +} b3TrianglePoint; + +typedef struct b3ShapeExtent +{ + float minExtent; + b3Vec3 maxExtent; +} b3ShapeExtent; + +#ifdef __cplusplus +extern "C" +{ +#endif + +b3TrianglePoint b3ClosestPointOnTriangle( b3Vec3 a, b3Vec3 b, b3Vec3 c, b3Vec3 q ); + +float b3IntersectSegmentTriangle( b3Vec3 p, b3Vec3 q, b3Vec3 a, b3Vec3 b, b3Vec3 c ); +float b3IntersectSegmentSphere( b3Vec3 p, b3Vec3 q, b3Vec3 c, float r ); + +b3MassData b3ComputeMassProperties( int triangleCount, const int* triangles, int vertexCount, const b3Vec3* vertices, + float density ); + +bool b3IsValidMassData( const b3MassData* massData ); + +b3Matrix3 b3SphereInertia( float mass, float radius ); +b3Matrix3 b3CylinderInertia( float mass, float radius, float height ); +b3Matrix3 b3BoxInertia( float mass, b3Vec3 min, b3Vec3 max ); + +// Inertia helper (Io = Ic + Is and Ic = Io - Is) +b3Matrix3 b3Steiner( float mass, b3Vec3 origin ); +int b3GetProxySupport( const b3ShapeProxy* proxy, b3Vec3 axis ); +int b3GetPointSupport( const b3Vec3* points, int count, b3Vec3 axis ); + +bool b3IntersectRayAndAABB( b3Vec3 lowerBound, b3Vec3 upperBound, b3Vec3 p1, b3Vec3 p2, float* minFraction, float* maxFraction ); + +#ifdef __cplusplus +} +#endif + +// https://en.wikipedia.org/wiki/Floor_and_ceiling_functions +B3_INLINE int b3CeilingInt( int numerator, int denominator ) +{ + B3_VALIDATE( denominator > 0 ); + return ( numerator + denominator - 1 ) / denominator; +} + +// Assumes denominator == 2^exponent +B3_INLINE int b3CeilingPow2( int numerator, int denominator, int exponent ) +{ + B3_VALIDATE( exponent > 0 && ( denominator == 1 << exponent ) ); + return ( numerator + denominator - 1 ) >> exponent; +} + +bool b3IsSweepNormalized( b3Sweep* sweep ); + +B3_INLINE float b3Dot2( b3Vec2 v1, b3Vec2 v2 ) +{ + return v1.x * v2.x + v1.y * v2.y; +} + +B3_INLINE float b3Length2( b3Vec2 v ) +{ + return sqrtf( b3Dot2( v, v ) ); +} + +B3_INLINE float b3LengthSquared2( b3Vec2 v ) +{ + return b3Dot2( v, v ); +} + +B3_INLINE b3Vec2 b3MinVec2( b3Vec2 v1, b3Vec2 v2 ) +{ + b3Vec2 v; + v.x = b3MinFloat( v1.x, v2.x ); + v.y = b3MinFloat( v1.y, v2.y ); + return v; +} + +B3_INLINE b3Vec2 b3MaxVec2( b3Vec2 v1, b3Vec2 v2 ) +{ + b3Vec2 v; + v.x = b3MaxFloat( v1.x, v2.x ); + v.y = b3MaxFloat( v1.y, v2.y ); + return v; +} + +B3_INLINE void b3Store( float* dst, b3Vec3 src ) +{ + dst[0] = src.x; + dst[1] = src.y; + dst[2] = src.z; +} + +B3_INLINE b3Vec3 b3ClampLength( b3Vec3 v, float maxLength ) +{ + float lengthSq = b3LengthSquared( v ); + if ( lengthSq <= maxLength * maxLength ) + { + return v; + } + + float length = sqrtf( lengthSq ); + return b3MulSV( maxLength / length, v ); +} + +// Assume v is a unit vector +B3_INLINE b3Vec3 b3ArbitraryPerp( b3Vec3 v ) +{ + // Suppose vector a has all equal components and is a unit vector: a = (s, s, s) + // Then 3*s*s = 1, s = sqrt(1/3) = 0.57735. This means that at least one component + // of a unit vector must be greater or equal to 0.57735. + b3Vec3 p; + if ( v.x < -0.5f || 0.5f < v.x ) + { + // x is non-zero and it should not go into the x component + // dot([ay + bz, cx, dx], [x, y, z]) = ayx + bzx + cxy + dzx + // for the dot product to be zero need: c = -a, d = -b + float a = 0.67f; + float b = -0.42f; + p = B3_LITERAL( b3Vec3 ){ a * v.y + b * v.z, -a * v.x, -b * v.x }; + } + else if ( v.y < -0.5f || 0.5f < v.y ) + { + // y is non-zero and it should not go into the y component + // p = [ay, bx + cz, dy] + // axy + bxy + cyz + dyz = 0 + // b = -a, d = -c + float a = 0.67f; + float c = -0.42f; + p = B3_LITERAL( b3Vec3 ){ a * v.y, -a * v.x + c * v.z, -c * v.y }; + } + else + { + // This would trip if the input is not a unit vector + B3_VALIDATE( v.z < -0.5f || 0.5f < v.z ); + + // z is non-zero and it should not go into the z component + // p = [az, bz, cx + dy] + // axz + byz + cxz + dyz = 0 + // c = -a, d = -b + float a = 0.67f; + float b = -0.42f; + p = B3_LITERAL( b3Vec3 ){ a * v.z, b * v.z, -a * v.x - b * v.y }; + } + + B3_VALIDATE( b3LengthSquared( p ) > 0.1f ); + B3_VALIDATE( b3AbsFloat( b3Dot( p, v ) ) < 100.0f * FLT_EPSILON ); + + return b3Normalize( p ); +} + +B3_INLINE b3Quat b3QuatFromExponentialMap( b3Vec3 v ) +{ + // Exponential map (Grassia) + float threshold = 0.018581361f; + + float angle = b3Length( v ); + if ( angle < threshold ) + { + // Taylor expansion + b3Quat out; + out.v = b3MulSV( 0.5f + angle * angle / 48.0f, v ); + out.s = b3Cos( 0.5f * angle ); + + return out; + } + + return b3MakeQuatFromAxisAngle( b3MulSV( 1.0f / angle, v ), angle ); +} + +/// Integrate rotation from angular velocity +/// @param q1 initial rotation +/// @param deltaRotation the angular displacement vector in radians (angular velocity multiplied by the time step) +/// q2 = q1 + 0.5 * omega * q1 +B3_INLINE b3Quat b3IntegrateRotation( b3Quat q1, b3Vec3 deltaRotation ) +{ + // https://fgiesen.wordpress.com/2012/08/24/quaternion-differentiation/ + b3Quat qd = { b3MulSV( 0.5f, deltaRotation ), 0.0f }; + qd = b3MulQuat( qd, q1 ); + b3Quat q2 = { b3Add( q1.v, qd.v ), qd.s + q1.s }; + q2 = b3NormalizeQuat( q2 ); + return q2; + + // return b3NormalizeQuat( b3MulQuat(b3QuatFromExponentialMap( deltaRotation ), q1) ); +} + +// Pseudo angular velocity from a quaternion target +// w = 2 * (target - q) * conj(q) +B3_INLINE b3Vec3 b3DeltaQuatToRotation(b3Quat q, b3Quat target) +{ + b3Quat s = q; + if (b3DotQuat(q, target) < 0.0f) + { + // Correct polarity + s = b3NegateQuat( q ); + } + + b3Quat diff = { b3Sub( target.v, s.v ), target.s - s.s }; + b3Quat product = b3MulQuat( diff, b3Conjugate( s ) ); + return b3MulSV( 2.0f, product.v ); +} + +B3_INLINE float b3ScalarTripleProduct( b3Vec3 a, b3Vec3 b, b3Vec3 c ) +{ + b3Vec3 d; + d.x = b.y * c.z - b.z * c.y; + d.y = b.z * c.x - b.x * c.z; + d.z = b.x * c.y - b.y * c.x; + return a.x * d.x + a.y * d.y + a.z * d.z; +} + +// Get a value by index. Avoid undefined behavior of code like (&v.x)[2]. +B3_INLINE float b3GetByIndex( b3Vec3 v, int index ) +{ + B3_ASSERT( 0 <= index && index < 3 ); + float temp[3] = { v.x, v.y, v.z }; + return temp[index]; +} + +B3_INLINE int b3MajorAxis( b3Vec3 v ) +{ + return v.x < v.y ? ( v.y < v.z ? 2 : 1 ) : ( v.x < v.z ? 2 : 0 ); +} + +B3_INLINE float b3MinElement( b3Vec3 v ) +{ + return b3MinFloat( v.x, b3MinFloat( v.y, v.z ) ); +} + +B3_INLINE float b3MaxElement( b3Vec3 v ) +{ + return b3MaxFloat( v.x, b3MaxFloat( v.y, v.z ) ); +} + +B3_INLINE int b3MaxElementIndex( b3Vec3 v ) +{ + return v.x < v.y ? ( v.y < v.z ? 2 : 1 ) : ( v.x < v.z ? 2 : 0 ); +} + +B3_INLINE b3Vec2 b3Add2( b3Vec2 a, b3Vec2 b ) +{ + b3Vec2 c = { a.x + b.x, a.y + b.y }; + return c; +} + +B3_INLINE b3Vec2 b3Sub2( b3Vec2 a, b3Vec2 b ) +{ + b3Vec2 c = { a.x - b.x, a.y - b.y }; + return c; +} + +B3_INLINE b3Vec2 b3Neg2( b3Vec2 v ) +{ + b3Vec2 c = { -v.x, -v.y }; + return c; +} + +B3_INLINE b3Vec2 b3MulSV2( float s, b3Vec2 v ) +{ + b3Vec2 c = { s * v.x, s * v.y }; + return c; +} + +// a + s * b +B3_INLINE b3Vec2 b3MulAdd2( b3Vec2 a, float s, b3Vec2 b ) +{ + b3Vec2 c = { a.x + s * b.x, a.y + s * b.y }; + return c; +} + +// a - s * b +B3_INLINE b3Vec2 b3MulSub2( b3Vec2 a, float s, b3Vec2 b ) +{ + b3Vec2 c = { a.x - s * b.x, a.y - s * b.y }; + return c; +} + +B3_INLINE float b3Cross2( b3Vec2 a, b3Vec2 b ) +{ + return a.x * b.y - a.y * b.x; +} + +B3_INLINE float b3DistanceSquared2( b3Vec2 a, b3Vec2 b ) +{ + float dx = b.x - a.x; + float dy = b.y - a.y; + return dx * dx + dy * dy; +} + +B3_INLINE b3Vec2 b3MulMV2( b3Matrix2 m, b3Vec2 a ) +{ + b3Vec2 b = { m.cx.x * a.x + m.cy.x * a.y, m.cx.y * a.x + m.cy.y * a.y }; + return b; +} + +B3_INLINE b3Matrix2 b3MulMM2( b3Matrix2 m1, b3Matrix2 m2 ) +{ + b3Matrix2 out; + out.cx = b3MulMV2( m1, m2.cx ); + out.cy = b3MulMV2( m1, m2.cy ); + return out; +} + +B3_INLINE float b3Det2( b3Matrix2 m ) +{ + return m.cx.x * m.cy.y - m.cx.y * m.cy.x; +} + +B3_INLINE b3Matrix2 b3Invert2( b3Matrix2 m ) +{ + float det = b3Det2( m ); + if ( b3AbsFloat( det ) > 1000.0f * FLT_MIN ) + { + float invDet = 1.0f / det; + return B3_LITERAL( b3Matrix2 ){ + { invDet * m.cy.y, -invDet * m.cx.y }, + { -invDet * m.cy.x, invDet * m.cx.x }, + }; + } + + return B3_LITERAL( b3Matrix2 ){ { 0.0f, 0.0f }, { 0.0f, 0.0f } }; +} + +// Assumes positive semi-definite +B3_INLINE b3Vec2 b3Solve2( b3Matrix2 m, b3Vec2 b ) +{ + float det = b3Det2( m ); + if ( det > 1000.0f * FLT_MIN ) + { + float invDet = 1.0f / det; + return B3_LITERAL( b3Vec2 ){ + invDet * m.cy.y * b.x - invDet * m.cy.x * b.y, + -invDet * m.cx.y * b.x + invDet * m.cx.x * b.y, + }; + } + + return B3_LITERAL( b3Vec2 ){ 0.0f, 0.0f }; +} + +B3_INLINE b3Vec3 b3ModifiedCross(b3Vec3 a, b3Vec3 b) +{ + b3Vec3 c; + c.x = a.y * b.z + a.z * b.y; + c.y = a.z * b.x + a.x * b.z; + c.z = a.x * b.y + a.y * b.x; + return c; +} + +B3_INLINE b3Plane b3NormalizePlane( b3Plane plane ) +{ + float invLength = 1.0f / b3Length( plane.normal ); + return B3_LITERAL( b3Plane ){ b3MulSV( invLength, plane.normal ), invLength * plane.offset }; +} + +// Negative if p is below the triangle v1-v2-v3 +B3_INLINE float b3SignedVolume( b3Vec3 v1, b3Vec3 v2, b3Vec3 v3, b3Vec3 p ) +{ + b3Vec3 e1 = b3Sub( v2, v1 ); + b3Vec3 e2 = b3Sub( v3, v1 ); + b3Vec3 n = b3Cross( e1, e2 ); + return b3Dot( n, b3Sub( p, v1 ) ); +} + +// todo eliminate this +B3_INLINE bool b3IsWithinSegments( const b3ClosestApproachResult* result ) +{ + return ( 0.0f <= result->lambda1 && result->lambda1 <= 1.0f ) && ( 0.0f <= result->lambda2 && result->lambda2 <= 1.0f ); +} + +B3_INLINE b3Matrix3 b3RotateInertia( b3Quat q, b3Matrix3 centralInertia ) +{ + b3Matrix3 rotationMatrix = b3MakeMatrixFromQuat( q ); + b3Matrix3 inertia = b3MulMM( rotationMatrix, b3MulMM( centralInertia, b3Transpose( rotationMatrix ) ) ); + return inertia; +} + +B3_INLINE b3Matrix3 b3TransformInertia( b3Transform transform, b3Matrix3 centralInertia, float mass ) +{ + b3Matrix3 inertia = b3RotateInertia( transform.q, centralInertia ); + inertia = b3AddMM( inertia, b3Steiner( mass, transform.p ) ); + return inertia; +} + +#ifdef __cplusplus + +B3_INLINE b3Vec2& operator+=( b3Vec2& a, b3Vec2 b ) +{ + a.x += b.x; + a.y += b.y; + return a; +} + +B3_INLINE b3Vec2& operator*=( b3Vec2& a, float s ) +{ + a.x *= s; + a.y *= s; + return a; +} + +B3_INLINE b3Vec2 operator-( b3Vec2 v ) +{ + return { -v.x, -v.y }; +} + +B3_INLINE b3Vec2 operator+( b3Vec2 v1, b3Vec2 v2 ) +{ + b3Vec2 out; + out.x = v1.x + v2.x; + out.y = v1.y + v2.y; + + return out; +} + +B3_INLINE b3Vec2 operator-( b3Vec2 v1, b3Vec2 v2 ) +{ + b3Vec2 out; + out.x = v1.x - v2.x; + out.y = v1.y - v2.y; + + return out; +} + +B3_INLINE b3Vec2 operator*( float f, b3Vec2 v ) +{ + b3Vec2 out; + out.x = f * v.x; + out.y = f * v.y; + + return out; +} + +B3_INLINE b3Vec2 operator*( b3Vec2 v, float f ) +{ + b3Vec2 out; + out.x = v.x * f; + out.y = v.y * f; + + return out; +} + +B3_INLINE b3Matrix2 operator+( b3Matrix2 m1, b3Matrix2 m2 ) +{ + b3Matrix2 out; + out.cx = m1.cx + m2.cx; + out.cy = m1.cy + m2.cy; + + return out; +} + +B3_INLINE b3Matrix2 operator-( b3Matrix2 m1, b3Matrix2 m2 ) +{ + b3Matrix2 out; + out.cx = m1.cx - m2.cx; + out.cy = m1.cy - m2.cy; + + return out; +} + +B3_INLINE b3Matrix2 operator*( float f, b3Matrix2 m ) +{ + b3Matrix2 out; + out.cx = f * m.cx; + out.cy = f * m.cy; + + return out; +} + +B3_INLINE b3Matrix2 operator*( b3Matrix2 m, float f ) +{ + b3Matrix2 out; + out.cx = m.cx * f; + out.cy = m.cy * f; + + return out; +} + +#endif diff --git a/src/mesh.c b/src/mesh.c new file mode 100644 index 0000000..80e7b41 --- /dev/null +++ b/src/mesh.c @@ -0,0 +1,2342 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +// Dirk Gregorius contributed portions of this code + +#include "container.h" +#include "math_internal.h" +#include "shape.h" +#include "simd.h" + +#include "box3d/collision.h" +#include "box3d/constants.h" + +#include + +b3DeclareArray( b3VertexNode ); +b3DeclareArray( b3MeshNode ); +b3DeclareArray( b3MeshTriangle ); +b3DeclareArray( b3Vec3 ); +b3DeclareArray( b3Primitive ); +b3DeclareArrayNative( uint8_t ); + +#define B3_BIN_COUNT 8 +#define B3_DESIRED_TRIANGLES_PER_LEAF 4 +#define B3_LEAF_NODE 3 +#define B3_MAXIMUM_TRIANGLES_PER_LEAF 8 +#define B3_MESH_STACK_SIZE 256 + +static bool b3IsLeaf( const b3MeshNode* node ) +{ + return node->data.asLeaf.type == B3_LEAF_NODE; +} + +static b3MeshNode* b3GetMeshNodesWrite( b3MeshData* mesh ) +{ + if ( mesh->nodeOffset == 0 ) + { + return NULL; + } + + return (b3MeshNode*)( (intptr_t)mesh + mesh->nodeOffset ); +} + +static b3MeshNode* b3GetLeftChildWrite( b3MeshNode* node ) +{ + // The left child follows its parent. + B3_ASSERT( !b3IsLeaf( node ) ); + return node + 1; +} + +static const b3MeshNode* b3GetLeftChild( const b3MeshNode* node ) +{ + // The left child follows its parent. + B3_ASSERT( !b3IsLeaf( node ) ); + return node + 1; +} + +static b3MeshNode* b3GetRightChildWrite( b3MeshNode* node ) +{ + // We store the offset of the right child relative to its parent + B3_ASSERT( !b3IsLeaf( node ) ); + return node + node->data.asNode.childOffset; +} + +static const b3MeshNode* b3GetRightChild( const b3MeshNode* node ) +{ + // We store the offset of the right child relative to its parent + B3_ASSERT( !b3IsLeaf( node ) ); + return node + node->data.asNode.childOffset; +} + +static const b3MeshNode* b3GetRoot( const b3MeshData* mesh ) +{ + // The first node is the root + return b3GetMeshNodes( mesh ); +} + +static b3MeshNode* b3GetRootWrite( b3MeshData* mesh ) +{ + // The first node is the root + return b3GetMeshNodesWrite( mesh ); +} + +static b3MeshTriangle* b3GetMeshTrianglesWrite( b3MeshData* mesh ) +{ + if ( mesh->triangleOffset == 0 ) + { + return NULL; + } + + return (b3MeshTriangle*)( (intptr_t)mesh + mesh->triangleOffset ); +} + +static b3Vec3* b3GetMeshVerticesWrite( b3MeshData* mesh ) +{ + if ( mesh->vertexOffset == 0 ) + { + return NULL; + } + + return (b3Vec3*)( (intptr_t)mesh + mesh->vertexOffset ); +} + +// static b3Vec3 b3GetVertex( b3MeshData& mesh, int vertexIndex ) +//{ +// B3_ASSERT( 0 <= vertexIndex && vertexIndex < mesh.vertexCount ); +// b3Vec3* vertices = b3GetMeshVertices( &mesh ); +// return vertices[vertexIndex]; +// } + +static uint8_t* b3GetMeshMaterialIndicesWrite( b3MeshData* mesh ) +{ + if ( mesh->materialOffset == 0 ) + { + return NULL; + } + + return (uint8_t*)( (intptr_t)mesh + mesh->materialOffset ); +} + +static uint8_t* b3GetMeshFlagsWrite( b3MeshData* mesh ) +{ + if ( mesh->flagsOffset == 0 ) + { + return NULL; + } + + return (uint8_t*)( (intptr_t)mesh + mesh->flagsOffset ); +} + +static int b3GetNodeHeight( const b3MeshNode* node ) +{ + if ( b3IsLeaf( node ) ) + { + return 0; + } + + const b3MeshNode* leftChild = b3GetLeftChild( node ); + int leftHeight = b3GetNodeHeight( leftChild ); + const b3MeshNode* rightChild = b3GetRightChild( node ); + int rightHeight = b3GetNodeHeight( rightChild ); + + return 1 + b3MaxInt( leftHeight, rightHeight ); +} + +int b3GetHeight( const b3MeshData* mesh ) +{ + const b3MeshNode* root = b3GetRoot( mesh ); + if ( root == NULL ) + { + return 0; + } + + return b3GetNodeHeight( root ); +} + +#if B3_ENABLE_VALIDATION == 1 +static bool b3IsDegenerate( b3Vec3 v1, b3Vec3 v2, b3Vec3 v3, float minArea ) +{ + b3Vec3 normal = b3Cross( b3Sub( v2, v1 ), b3Sub( v3, v1 ) ); + float lengthSq = b3LengthSquared( normal ); + return lengthSq < minArea * minArea; +} + +static bool b3IsNonDegenerate( const b3MeshData* mesh, float minArea ) +{ + const b3MeshTriangle* triangles = b3GetMeshTriangles( mesh ); + const b3Vec3* vertices = b3GetMeshVertices( mesh ); + + // Check triangles + for ( int index = 0; index < mesh->triangleCount; ++index ) + { + // Index range + b3MeshTriangle triangle = triangles[index]; + if ( triangle.index1 >= mesh->vertexCount ) + { + return false; + } + + if ( triangle.index2 >= mesh->vertexCount ) + { + return false; + } + + if ( triangle.index3 >= mesh->vertexCount ) + { + return false; + } + + // Degenerate topology + if ( triangle.index1 == triangle.index2 ) + { + return false; + } + if ( triangle.index1 == triangle.index3 ) + { + return false; + } + if ( triangle.index2 == triangle.index3 ) + { + return false; + } + + // Degenerate geometry + b3Vec3 vertex1 = vertices[triangle.index1]; + b3Vec3 vertex2 = vertices[triangle.index2]; + b3Vec3 vertex3 = vertices[triangle.index3]; + if ( b3IsDegenerate( vertex1, vertex2, vertex3, minArea ) ) + { + return false; + } + } + + return true; +} + +static inline b3AABB b3GetNodeAABB( const b3MeshNode* node ) +{ + return (b3AABB){ + node->lowerBound, + node->upperBound, + }; +} + +static bool b3IsConsistent( const b3MeshData* mesh ) +{ + const b3MeshTriangle* triangles = b3GetMeshTriangles( mesh ); + const b3Vec3* vertices = b3GetMeshVertices( mesh ); + + // Check nodes + int count = 0; + const b3MeshNode* stack[64]; + stack[count++] = b3GetRoot( mesh ); + + while ( count > 0 ) + { + const b3MeshNode* node = stack[--count]; + b3AABB nodeBounds = b3GetNodeAABB( node ); + + if ( b3IsLeaf( node ) == false ) + { + const b3MeshNode* child1 = b3GetLeftChild( node ); + b3AABB bounds1 = b3GetNodeAABB( child1 ); + const b3MeshNode* child2 = b3GetRightChild( node ); + b3AABB bounds2 = b3GetNodeAABB( child2 ); + + if ( !b3AABB_Contains( nodeBounds, bounds1 ) ) + { + return false; + } + + if ( !b3AABB_Contains( nodeBounds, bounds2 ) ) + { + return false; + } + + stack[count++] = child2; + stack[count++] = child1; + } + else + { + b3AABB triangleBounds = B3_BOUNDS3_EMPTY; + for ( uint32_t index = 0; index < node->data.asLeaf.triangleCount; ++index ) + { + int triangleIndex = node->triangleOffset + index; + B3_ASSERT( 0 <= triangleIndex && triangleIndex < mesh->triangleCount ); + + b3MeshTriangle triangle = triangles[triangleIndex]; + + b3AABB vertexBounds = B3_BOUNDS3_EMPTY; + vertexBounds = b3AABB_AddPoint( vertexBounds, vertices[triangle.index1] ); + vertexBounds = b3AABB_AddPoint( vertexBounds, vertices[triangle.index2] ); + vertexBounds = b3AABB_AddPoint( vertexBounds, vertices[triangle.index3] ); + + triangleBounds = b3AABB_Union( triangleBounds, vertexBounds ); + } + + if ( !b3AABB_Contains( nodeBounds, triangleBounds ) ) + { + return false; + } + } + } + + return true; +} + +bool b3IsValidMesh( const b3MeshData* meshData ) +{ + if ( meshData == NULL ) + { + return false; + } + + if ( meshData->version != B3_MESH_VERSION ) + { + return false; + } + + if ( meshData->byteCount < (int)sizeof( b3MeshData ) ) + { + return false; + } + + return b3IsConsistent( meshData ); +} + +#else + +bool b3IsValidMesh( const b3MeshData* meshData ) +{ + if ( meshData == NULL ) + { + return false; + } + + if ( meshData->version != B3_MESH_VERSION ) + { + return false; + } + + if ( meshData->byteCount < (int)sizeof( b3MeshData ) ) + { + return false; + } + + return true; +} + +#endif + +// Node for a vertex linked list +typedef struct b3VertexNode +{ + int32_t vertexIndex; + int nextNodeIndex; +} b3VertexNode; + +#define NAME b3VertexMap +#define KEY_TY uint64_t +#define VAL_TY int +#define HASH_FN vt_hash_integer +#define CMPR_FN vt_cmpr_integer +#define MALLOC_FN b3Alloc +#define FREE_FN b3Free +#include "verstable.h" + +typedef struct b3SpatialHash +{ + b3ArrayC( b3VertexNode ) nodes; + const b3Vec3* vertices; + int vertexCount; + b3VertexMap vertexMap; + float cellSize; + float tolerance; +} b3SpatialHash; + +static void b3SpatialHash_Create( b3SpatialHash* h, const b3Vec3* vertices, int vertexCount, float tolerance ) +{ + h->vertices = vertices; + h->vertexCount = vertexCount; + h->tolerance = tolerance; + h->cellSize = 2.0f * tolerance; + b3Array_CreateN( h->nodes, vertexCount ); + + b3VertexMap_init( &h->vertexMap ); + b3VertexMap_reserve( &h->vertexMap, vertexCount ); + + B3_ASSERT( h->cellSize > 0.0f ); +} + +static void b3SpatialHash_Destroy( b3SpatialHash* h ) +{ + b3VertexMap_cleanup( &h->vertexMap ); + b3Array_Destroy( h->nodes ); +} + +// Welding works by bucketing nearby vertices into identical keys in a hash table. +// Bucketing is done manually with an array. +static int32_t b3SpatialHash_FindDuplicate( b3SpatialHash* h, int32_t currentIndex ) +{ + B3_ASSERT( currentIndex < h->vertexCount ); + b3Vec3 vertex = h->vertices[currentIndex]; + float cellSize = h->cellSize; + float tolerance = h->tolerance; + + // Get the grid coordinates for the current vertex + int32_t baseX = (int32_t)( floorf( vertex.x / cellSize ) ); + int32_t baseY = (int32_t)( floorf( vertex.y / cellSize ) ); + int32_t baseZ = (int32_t)( floorf( vertex.z / cellSize ) ); + + // Check the current cell and all 26 neighboring cells (3x3x3 - 1) + for ( int dx = -1; dx <= 1; ++dx ) + { + for ( int dy = -1; dy <= 1; ++dy ) + { + for ( int dz = -1; dz <= 1; ++dz ) + { + int32_t x = baseX + dx; + int32_t y = baseY + dy; + int32_t z = baseZ + dz; + + // Compute hash for this neighboring cell (this is the key in the map) + uint64_t key = 0; + key ^= (uint64_t)( x ) + 0x9e3779b9 + ( key << 6 ) + ( key >> 2 ); + key ^= (uint64_t)( y ) + 0x9e3779b9 + ( key << 6 ) + ( key >> 2 ); + key ^= (uint64_t)( z ) + 0x9e3779b9 + ( key << 6 ) + ( key >> 2 ); + + b3VertexMap_itr it = b3VertexMap_get( &h->vertexMap, key ); + if ( b3VertexMap_is_end( it ) == false ) + { + // Check all vertices in this key + int nodeIndex = it.data->val; + + while ( nodeIndex != B3_NULL_INDEX ) + { + b3VertexNode node = h->nodes.data[nodeIndex]; + + int32_t existingIndex = node.vertexIndex; + B3_ASSERT( existingIndex < currentIndex ); + B3_ASSERT( existingIndex < h->vertexCount ); + + b3Vec3 other = h->vertices[existingIndex]; + + // IsEqual inlined: check if vertices are within tolerance + if ( fabsf( vertex.x - other.x ) <= tolerance && + fabsf( vertex.y - other.y ) <= tolerance && + fabsf( vertex.z - other.z ) <= tolerance ) + { + // Found duplicate + return existingIndex; + } + + nodeIndex = node.nextNodeIndex; + } + } + } + } + } + + // No duplicate found, add to hash table + uint64_t currentKey = 0; + currentKey ^= (uint64_t)( baseX ) + 0x9e3779b9 + ( currentKey << 6 ) + ( currentKey >> 2 ); + currentKey ^= (uint64_t)( baseY ) + 0x9e3779b9 + ( currentKey << 6 ) + ( currentKey >> 2 ); + currentKey ^= (uint64_t)( baseZ ) + 0x9e3779b9 + ( currentKey << 6 ) + ( currentKey >> 2 ); + + b3VertexMap_itr it = b3VertexMap_get( &h->vertexMap, currentKey ); + if ( b3VertexMap_is_end( it ) == false ) + { + int nodeIndex = it.data->val; + + b3VertexNode node = { + .vertexIndex = currentIndex, + .nextNodeIndex = nodeIndex, + }; + + it.data->val = h->nodes.count; + b3Array_Push( h->nodes, node ); + } + else + { + b3VertexNode node = { + .vertexIndex = currentIndex, + .nextNodeIndex = B3_NULL_INDEX, + }; + + b3VertexMap_insert( &h->vertexMap, currentKey, h->nodes.count ); + b3Array_Push( h->nodes, node ); + } + + // Not welded + return B3_NULL_INDEX; +} + +typedef struct b3WeldData +{ + const b3Vec3* srcVertices; + const int32_t* srcIndices; + + b3Vec3* dstVertices; + int32_t* dstIndices; + + int vertexCount; + int indexCount; +} b3WeldData; + +static int b3WeldVertices( b3WeldData* data, float tolerance ) +{ + int vertexCount = data->vertexCount; + int uniqueCount = 0; + + // Create spatial hash and find duplicates + b3SpatialHash spatialHash; + b3SpatialHash_Create( &spatialHash, data->srcVertices, vertexCount, tolerance ); + b3ArrayC( int ) vertexMapping = { 0 }; + b3Array_Resize( vertexMapping, vertexCount ); + + for ( int i = 0; i < vertexCount; ++i ) + { + int32_t duplicateIndex = b3SpatialHash_FindDuplicate( &spatialHash, i ); + + if ( duplicateIndex == B3_NULL_INDEX ) + { + // New unique vertex + vertexMapping.data[i] = uniqueCount; + data->dstVertices[uniqueCount] = data->srcVertices[i]; + uniqueCount += 1; + } + else + { + // Found duplicate, map to existing vertex + vertexMapping.data[i] = vertexMapping.data[duplicateIndex]; + } + } + + // Update indices to reference the new vertex array + int indexCount = data->indexCount; + for ( int i = 0; i < indexCount; ++i ) + { + int srcIndex = data->srcIndices[i]; + B3_ASSERT( srcIndex < vertexCount ); + data->dstIndices[i] = vertexMapping.data[srcIndex]; + } + + b3SpatialHash_Destroy( &spatialHash ); + b3Array_Destroy( vertexMapping ); + + return uniqueCount; +} + +static inline void b3StoreLeaf( b3MeshNode* node, const b3AABB* aabb, int triangleCount, int triangleOffset ) +{ + node->data.asLeaf.type = B3_LEAF_NODE; + node->data.asLeaf.triangleCount = triangleCount; + node->triangleOffset = triangleOffset; + node->lowerBound = aabb->lowerBound; + node->upperBound = aabb->upperBound; +} + +typedef struct b3Primitive +{ + b3AABB aabb; + b3Vec3 center; + int triangleIndex; +} b3Primitive; + +typedef struct b3Bucket +{ + int count; + b3AABB bounds; +} b3Bucket; + +typedef struct b3Split +{ + b3AABB leftBounds; + b3AABB rightBounds; + int axis; + int index; +} b3Split; + +static b3Split b3SplitBinnedSah( int count, b3Primitive* primitives ) +{ + b3Split split; + split.axis = -1; + split.index = -1; + + // Compute bounds of primitive centroids and choose split axis + b3AABB bounds = { primitives[0].center, primitives[0].center }; + for ( int i = 1; i < count; ++i ) + { + bounds = b3AABB_AddPoint( bounds, primitives[i].center ); + } + + // Compute costs for splitting after each bucket and keep track of best split + // This is a small O(n^2) loop. This can be further optimized, but it is already + // very fast and is kept for simplicity right now. + int bestBucket = -1; + float bestCost = FLT_MAX; + + for ( int axis = 0; axis < 3; ++axis ) + { + b3Vec3 extent = b3AABB_Extents( bounds ); + if ( b3GetByIndex( extent, axis ) < B3_LINEAR_SLOP ) + { + continue; + } + + // Initialize buckets + b3Bucket buckets[B3_BIN_COUNT]; + for ( int i = 0; i < B3_BIN_COUNT; ++i ) + { + buckets[i].count = 0; + buckets[i].bounds = B3_BOUNDS3_EMPTY; + } + + // Fill buckets + float factor = B3_BIN_COUNT * ( 1.0f - FLT_EPSILON ) / + ( b3GetByIndex( bounds.upperBound, axis ) - b3GetByIndex( bounds.lowerBound, axis ) ); + for ( int i = 0; i < count; ++i ) + { + b3Vec3 center = primitives[i].center; + int index = (int)( factor * ( b3GetByIndex( center, axis ) - b3GetByIndex( bounds.lowerBound, axis ) ) ); + B3_ASSERT( 0 <= index && index < B3_BIN_COUNT ); + + buckets[index].count++; + buckets[index].bounds = b3AABB_Union( buckets[index].bounds, primitives[i].aabb ); + } + + // Evaluate splits + for ( int i = 0; i < B3_BIN_COUNT - 1; ++i ) + { + int leftCount = 0; + b3AABB leftBounds = B3_BOUNDS3_EMPTY; + for ( int k = 0; k <= i; ++k ) + { + leftCount += buckets[k].count; + leftBounds = b3AABB_Union( leftBounds, buckets[k].bounds ); + } + + int rightCount = 0; + b3AABB rightBounds = B3_BOUNDS3_EMPTY; + for ( int k = i + 1; k < B3_BIN_COUNT; ++k ) + { + rightCount += buckets[k].count; + rightBounds = b3AABB_Union( rightBounds, buckets[k].bounds ); + } + + B3_ASSERT( leftCount + rightCount == count ); + if ( leftCount > 0 && rightCount > 0 ) + { + float cost = leftCount * b3AABB_Area( leftBounds ) + rightCount * b3AABB_Area( rightBounds ); + + if ( cost < bestCost ) + { + bestBucket = i; + bestCost = cost; + + split.axis = axis; + split.index = leftCount; + split.leftBounds = leftBounds; + split.rightBounds = rightBounds; + } + } + } + } + + // Partition + if ( bestBucket >= 0 ) + { + int axis = split.axis; + float factor = B3_BIN_COUNT * ( 1.0f - FLT_EPSILON ) / + ( b3GetByIndex( bounds.upperBound, axis ) - b3GetByIndex( bounds.lowerBound, axis ) ); + + int splitIndex = 0; + for ( int i = 0; i < count; ++i ) + { + b3Vec3 center = primitives[i].center; + int index = (int)( factor * ( b3GetByIndex( center, axis ) - b3GetByIndex( bounds.lowerBound, axis ) ) ); + + if ( index <= bestBucket ) + { + b3Primitive temp = primitives[i]; + primitives[i] = primitives[splitIndex]; + primitives[splitIndex] = temp; + splitIndex++; + } + } + B3_ASSERT( splitIndex == split.index ); + } + + return split; +} + +static b3Split b3SplitHalf( int count, b3Primitive* primitives ) +{ + // Split in the middle + int splitIndex = count / 2; + + b3AABB leftBounds = B3_BOUNDS3_EMPTY; + for ( int i = 0; i < splitIndex; ++i ) + { + leftBounds = b3AABB_Union( leftBounds, primitives[i].aabb ); + } + + b3AABB rightBounds = B3_BOUNDS3_EMPTY; + for ( int i = splitIndex; i < count; ++i ) + { + + rightBounds = b3AABB_Union( rightBounds, primitives[i].aabb ); + } + + b3AABB bounds = b3AABB_Union( leftBounds, rightBounds ); + int axis = b3MajorAxis( b3AABB_Extents( bounds ) ); + + b3Split split; + split.axis = axis; + split.index = splitIndex; + split.leftBounds = leftBounds; + split.rightBounds = rightBounds; + + return split; +} + +static b3Split b3SplitMedian( int count, b3Primitive* primitives ) +{ + B3_ASSERT( count > 2 ); + + b3Vec3 lowerBound = primitives[0].center; + b3Vec3 upperBound = primitives[0].center; + + for ( int i = 1; i < count; ++i ) + { + lowerBound = b3Min( lowerBound, primitives[i].center ); + upperBound = b3Max( upperBound, primitives[i].center ); + } + + b3Vec3 d = b3Sub( upperBound, lowerBound ); + b3Vec3 c = b3MulSV( 0.5f, b3Add( lowerBound, upperBound ) ); + + b3Split split = { 0 }; + split.index = -1; + + // 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 && d.x >= d.z ) + { + split.axis = 0; + + float pivot = c.x; + + while ( i1 < i2 ) + { + while ( i1 < i2 && primitives[i1].center.x < pivot ) + { + i1 += 1; + }; + + while ( i1 < i2 && primitives[i2 - 1].center.x >= pivot ) + { + i2 -= 1; + }; + + if ( i1 < i2 ) + { + // Swap primitives + b3Primitive temp = primitives[i1]; + primitives[i1] = primitives[i2 - 1]; + primitives[i2 - 1] = temp; + + i1 += 1; + i2 -= 1; + } + } + } + else if ( d.y >= d.z ) + { + split.axis = 1; + + float pivot = c.y; + + while ( i1 < i2 ) + { + while ( i1 < i2 && primitives[i1].center.y < pivot ) + { + i1 += 1; + }; + + while ( i1 < i2 && primitives[i2 - 1].center.y >= pivot ) + { + i2 -= 1; + }; + + if ( i1 < i2 ) + { + // Swap primitives + b3Primitive temp = primitives[i1]; + primitives[i1] = primitives[i2 - 1]; + primitives[i2 - 1] = temp; + + i1 += 1; + i2 -= 1; + } + } + } + else + { + split.axis = 2; + + float pivot = c.z; + + while ( i1 < i2 ) + { + while ( i1 < i2 && primitives[i1].center.z < pivot ) + { + i1 += 1; + }; + + while ( i1 < i2 && primitives[i2 - 1].center.z >= pivot ) + { + i2 -= 1; + }; + + if ( i1 < i2 ) + { + // Swap primitives + b3Primitive temp = primitives[i1]; + primitives[i1] = primitives[i2 - 1]; + primitives[i2 - 1] = temp; + + i1 += 1; + i2 -= 1; + } + } + } + B3_ASSERT( i1 == i2 ); + B3_ASSERT( 0 <= i1 && i1 < count ); + + if ( i1 == 0 || i1 == count - 1 ) + { + // failed to split + i1 = count / 2; + } + + b3AABB leftBounds = B3_BOUNDS3_EMPTY; + for ( int i = 0; i < i1; ++i ) + { + leftBounds = b3AABB_Union( leftBounds, primitives[i].aabb ); + } + + b3AABB rightBounds = B3_BOUNDS3_EMPTY; + for ( int i = i1; i < count; ++i ) + { + rightBounds = b3AABB_Union( rightBounds, primitives[i].aabb ); + } + + split.index = i1; + split.leftBounds = leftBounds; + split.rightBounds = rightBounds; + return split; +} + +#if B3_ENABLE_VALIDATION == 1 + +static bool b3ValidateSplit( int count, b3Primitive* primitives, const b3Split* split ) +{ + if ( split->axis < 0 ) + { + return false; + } + + for ( int i = 0; i < split->index; ++i ) + { + if ( !b3AABB_Contains( split->leftBounds, primitives[i].aabb ) ) + { + return false; + } + } + + for ( int i = split->index; i < count; ++i ) + { + if ( !b3AABB_Contains( split->rightBounds, primitives[i].aabb ) ) + { + return false; + } + } + + return true; +} + +#endif + +static int b3BuildRecursive( b3ArrayC( b3MeshNode ) * nodes, int count, b3Primitive* primitives, b3Primitive* base, + bool useMedianSplit, int* height ) +{ + if ( count > B3_DESIRED_TRIANGLES_PER_LEAF ) + { + // Try to split the input set using the SAH + b3Split split; + if ( useMedianSplit ) + { + split = b3SplitMedian( count, primitives ); + } + else + { + split = b3SplitBinnedSah( count, primitives ); + } + + if ( split.axis < 0 ) + { + if ( count > B3_MAXIMUM_TRIANGLES_PER_LEAF ) + { + // Re-split. This is a less optimal split and can create more false positives! + split = b3SplitHalf( count, primitives ); + } + else + { + b3AABB bounds = B3_BOUNDS3_EMPTY; + for ( int i = 0; i < count; ++i ) + { + bounds = b3AABB_Union( bounds, primitives[i].aabb ); + } + + // We have only a few triangles left. Create a leaf. + int index = b3Array_AddIndex( *nodes ); + b3StoreLeaf( &nodes->data[index], &bounds, count, (int)( primitives - base ) ); + + return index; + } + } + B3_VALIDATE( b3ValidateSplit( count, primitives, &split ) ); + + // Allocate node and recurse + int index = b3Array_AddIndex( *nodes ); + int heightLeft = 0, heightRight = 0; + int leftIndex = b3BuildRecursive( nodes, split.index, primitives, base, useMedianSplit, &heightLeft ); + int rightIndex = + b3BuildRecursive( nodes, count - split.index, primitives + split.index, base, useMedianSplit, &heightRight ); + + *height = b3MaxInt( heightLeft, heightRight ) + 1; + + B3_UNUSED( leftIndex ); + B3_ASSERT( leftIndex - index == 1 && rightIndex - index > 1 ); + + b3AABB aabb = b3AABB_Union( split.leftBounds, split.rightBounds ); + b3MeshNode* node = b3Array_Get( *nodes, index ); + node->data.asNode.axis = split.axis; + node->data.asNode.childOffset = rightIndex - index; + node->lowerBound = aabb.lowerBound; + node->upperBound = aabb.upperBound; + + return index; + } + + b3AABB aabb = B3_BOUNDS3_EMPTY; + for ( int i = 0; i < count; ++i ) + { + aabb = b3AABB_Union( aabb, primitives[i].aabb ); + } + + int index = b3Array_AddIndex( *nodes ); + b3StoreLeaf( &nodes->data[index], &aabb, count, (int)( primitives - base ) ); + + *height = 1; + + return index; +} + +static bool b3SortMeshTriangles( b3MeshData* mesh ) +{ + b3MeshTriangle* triangles = b3GetMeshTrianglesWrite( mesh ); + uint8_t* materialIndices = b3GetMeshMaterialIndicesWrite( mesh ); + + // Sort triangles in depth-first-order + int offset = 0; + b3ArrayC( b3MeshTriangle ) tempTriangles; + b3Array_CreateN( tempTriangles, mesh->triangleCount ); + + b3ArrayC( uint8_t ) tempMaterialIndices; + b3Array_CreateN( tempMaterialIndices, mesh->triangleCount ); + + int count = 0; + b3MeshNode* stack[B3_MESH_STACK_SIZE]; + stack[count++] = b3GetRootWrite( mesh ); + + while ( count > 0 ) + { + b3MeshNode* node = stack[--count]; + + if ( b3IsLeaf( node ) == false ) + { + if ( count >= B3_MESH_STACK_SIZE - 2 ) + { + return false; + } + + stack[count++] = b3GetRightChildWrite( node ); + stack[count++] = b3GetLeftChildWrite( node ); + } + else + { + int triangleCount = node->data.asLeaf.triangleCount; + int triangleOffset = node->triangleOffset; + + for ( int triangle = 0; triangle < triangleCount; ++triangle ) + { + int index = triangleOffset + triangle; + b3Array_Push( tempTriangles, triangles[index] ); + b3Array_Push( tempMaterialIndices, materialIndices[index] ); + } + + node->triangleOffset = offset; + offset += triangleCount; + } + } + + B3_ASSERT( offset == tempTriangles.count ); + B3_ASSERT( tempTriangles.count == mesh->triangleCount ); + B3_ASSERT( tempMaterialIndices.count == mesh->triangleCount ); + + // Copy sorted triangle array back to tree + memcpy( triangles, tempTriangles.data, mesh->triangleCount * sizeof( b3MeshTriangle ) ); + memcpy( materialIndices, tempMaterialIndices.data, mesh->triangleCount * sizeof( uint8_t ) ); + + b3Array_Destroy( tempTriangles ); + b3Array_Destroy( tempMaterialIndices ); + + return true; +} + +typedef struct +{ + int vertex1; + int vertex2; + int triangle1; + int triangle2; + uint16_t triangleCount; + + // The index of an edge within the parent triangle: 0, 1, or 2. 0xFF is unset + uint8_t triangleEdgeIndex1; + uint8_t triangleEdgeIndex2; +} b3MeshEdge; + +#define NAME b3EdgeMap +#define KEY_TY uint64_t +#define VAL_TY int +#define HASH_FN vt_hash_integer +#define CMPR_FN vt_cmpr_integer +#define MALLOC_FN b3Alloc +#define FREE_FN b3Free +#include "verstable.h" + +#if 0 +// todo this is for testing other hash tables +struct b3TestHash +{ + size_t operator()( uint64_t key ) const + { + key ^= key >> 23; + key *= 0x2127599bf4325c37ull; + key ^= key >> 47; + return (size_t)key; + } +}; +#endif + +// Results for MeshCreationBenchmark +// eastl::hash_map : 4.9703 ms and 5.1445ms with FastHash function +// std::unordered_map : 4.8755 ms and 4.4780ms with FastHash function +// verstable : 3.3968 ms with default FastHash +// no edge identification : 1.7396 ms +static void b3IdentifyEdges( b3MeshData* mesh ) +{ + b3MeshTriangle* triangles = b3GetMeshTrianglesWrite( mesh ); + const b3Vec3* vertices = b3GetMeshVertices( mesh ); + uint8_t* flags = b3GetMeshFlagsWrite( mesh ); + + int triangleCount = mesh->triangleCount; + int edgeCount = 3 * triangleCount; + b3MeshEdge* edges = B3_ALLOC( b3MeshEdge, edgeCount ); + b3Vec3* normals = B3_ALLOC( b3Vec3, triangleCount ); + + for ( int i = 0; i < triangleCount; ++i ) + { + b3MeshTriangle* triangle = triangles + i; + int i1 = triangle->index1; + int i2 = triangle->index2; + int i3 = triangle->index3; + + edges[3 * i + 0].vertex1 = b3MinInt( i1, i2 ); + edges[3 * i + 0].vertex2 = b3MaxInt( i1, i2 ); + edges[3 * i + 0].triangle1 = i; + edges[3 * i + 0].triangle2 = B3_NULL_INDEX; + edges[3 * i + 0].triangleEdgeIndex1 = 0; + edges[3 * i + 0].triangleEdgeIndex2 = 0xFF; + edges[3 * i + 0].triangleCount = 1; + + edges[3 * i + 1].vertex1 = b3MinInt( i2, i3 ); + edges[3 * i + 1].vertex2 = b3MaxInt( i2, i3 ); + edges[3 * i + 1].triangle1 = i; + edges[3 * i + 1].triangle2 = B3_NULL_INDEX; + edges[3 * i + 1].triangleEdgeIndex1 = 1; + edges[3 * i + 1].triangleEdgeIndex2 = 0xFF; + edges[3 * i + 1].triangleCount = 1; + + edges[3 * i + 2].vertex1 = b3MinInt( i3, i1 ); + edges[3 * i + 2].vertex2 = b3MaxInt( i3, i1 ); + edges[3 * i + 2].triangle1 = i; + edges[3 * i + 2].triangle2 = B3_NULL_INDEX; + edges[3 * i + 2].triangleEdgeIndex1 = 2; + edges[3 * i + 2].triangleEdgeIndex2 = 0xFF; + edges[3 * i + 2].triangleCount = 1; + + b3Vec3 v1 = vertices[i1]; + b3Vec3 v2 = vertices[i2]; + b3Vec3 v3 = vertices[i3]; + + b3Vec3 e1 = b3Sub( v2, v1 ); + b3Vec3 e2 = b3Sub( v3, v1 ); + b3Vec3 n = b3Cross( e1, e2 ); + + normals[i] = b3Normalize( n ); + } + + b3EdgeMap map; + b3EdgeMap_init( &map ); + b3EdgeMap_reserve( &map, edgeCount ); + + uint64_t key = (uint64_t)edges[0].vertex1 << 32 | (uint64_t)edges[0].vertex2; + b3EdgeMap_insert( &map, key, 0 ); + + // Find unique edges and assign adjacency + for ( int i = 1; i < edgeCount; ++i ) + { + b3MeshEdge* edge = edges + i; + key = (uint64_t)edge->vertex1 << 32 | (uint64_t)edge->vertex2; + b3EdgeMap_itr itr = b3EdgeMap_get( &map, key ); + + if ( b3EdgeMap_is_end( itr ) ) + { + b3EdgeMap_insert( &map, key, i ); + } + else + { + int otherIndex = itr.data->val; + B3_ASSERT( otherIndex < i ); + + b3MeshEdge* base = edges + otherIndex; + if ( base->triangleCount == 1 ) + { + base->triangle2 = edge->triangle1; + base->triangleEdgeIndex2 = edge->triangleEdgeIndex1; + } + + base->triangleCount += 1; + } + } + + b3EdgeMap_cleanup( &map ); + + for ( int i = 0; i < edgeCount; ++i ) + { + b3MeshEdge* edge = edges + i; + if ( edge->triangleCount != 2 ) + { + continue; + } + + B3_ASSERT( edge->triangleEdgeIndex1 < 3 ); + B3_ASSERT( edge->triangleEdgeIndex2 < 3 ); + + b3MeshTriangle* triangle1 = triangles + edge->triangle1; + b3MeshTriangle* triangle2 = triangles + edge->triangle2; + uint8_t* flag1 = flags + edge->triangle1; + uint8_t* flag2 = flags + edge->triangle2; + + int j1 = triangle2->index1; + int j2 = triangle2->index2; + int j3 = triangle2->index3; + + int opposite = B3_NULL_INDEX; + + switch ( edge->triangleEdgeIndex2 ) + { + case 0: + opposite = j3; + break; + + case 1: + opposite = j1; + break; + + case 2: + opposite = j2; + break; + + default: + B3_ASSERT( false ); + } + + int i1 = triangle1->index1; + int i2 = triangle1->index2; + int i3 = triangle1->index3; + + b3Vec3 v1 = vertices[i1]; + b3Vec3 v2 = vertices[i2]; + b3Vec3 v3 = vertices[i3]; + b3Vec3 p = vertices[opposite]; + + float cos5Deg = 0.9962f; + float signedVolume = b3SignedVolume( v1, v2, v3, p ); + b3Vec3 n1 = normals[edge->triangle1]; + b3Vec3 n2 = normals[edge->triangle2]; + float cosAngle = b3Dot( n1, n2 ); + if ( signedVolume > 0.0f || cosAngle > cos5Deg ) + { + int edgeFlags[3] = { b3_concaveEdge1, b3_concaveEdge2, b3_concaveEdge3 }; + *flag1 |= edgeFlags[edge->triangleEdgeIndex1]; + *flag2 |= edgeFlags[edge->triangleEdgeIndex2]; + } + + if ( signedVolume < 0.0f || cosAngle > cos5Deg ) + { + int edgeFlags[3] = { b3_inverseConcaveEdge1, b3_inverseConcaveEdge2, b3_inverseConcaveEdge3 }; + *flag1 |= edgeFlags[edge->triangleEdgeIndex1]; + *flag2 |= edgeFlags[edge->triangleEdgeIndex2]; + } + } + + B3_FREE( normals, b3Vec3, triangleCount ); + B3_FREE( edges, b3MeshEdge, edgeCount ); +} + +b3MeshData* b3CreateGridMesh( int xCount, int zCount, float cellWidth, int materialCount, bool identifyEdges ) +{ + B3_ASSERT( 0 <= materialCount && materialCount <= UINT8_MAX ); + + // Create vertices + int vertexCount = ( xCount + 1 ) * ( zCount + 1 ); + + b3ArrayC( b3Vec3 ) vertices = { 0 }; + b3Array_Resize( vertices, vertexCount ); + int index = 0; + + float xWidth = cellWidth * xCount; + float zWidth = cellWidth * zCount; + + float x = -0.5f * xWidth; + for ( int ix = 0; ix <= xCount; ++ix ) + { + float z = -0.5f * zWidth; + for ( int iz = 0; iz <= zCount; ++iz ) + { + vertices.data[index] = (b3Vec3){ x, 0.0f, z }; + z += cellWidth; + index += 1; + } + x += cellWidth; + } + B3_ASSERT( index == vertexCount ); + + // Triangles + int triangleCount = 2 * xCount * zCount; + + b3ArrayC( int ) indices = { 0 }; + b3Array_Resize( indices, 3 * triangleCount ); + + b3ArrayC( uint8_t ) materialIndices = { 0 }; + b3Array_Resize( materialIndices, triangleCount ); + + int materialIndex = 0; + index = 0; + for ( int ix = 0; ix < xCount; ++ix ) + { + for ( int iz = 0; iz < zCount; ++iz ) + { + int index1 = iz + ( zCount + 1 ) * ix; + int index2 = index1 + 1; + int index3 = index2 + ( zCount + 1 ); + int index4 = index3 - 1; + + B3_ASSERT( index1 < vertexCount ); + B3_ASSERT( index2 < vertexCount ); + B3_ASSERT( index3 < vertexCount ); + B3_ASSERT( index4 < vertexCount ); + + indices.data[index + 0] = index1; + indices.data[index + 1] = index2; + indices.data[index + 2] = index3; + + indices.data[index + 3] = index3; + indices.data[index + 4] = index4; + indices.data[index + 5] = index1; + + if ( materialCount > 0 ) + { + materialIndices.data[2 * materialIndex + 0] = (uint8_t)( materialIndex % materialCount ); + materialIndices.data[2 * materialIndex + 1] = (uint8_t)( materialIndex % materialCount ); + } + + materialIndex += 1; + index += 6; + } + } + B3_ASSERT( index == 3 * triangleCount ); + + b3MeshDef def = { 0 }; + def.vertexCount = vertices.count; + def.vertices = vertices.data; + def.triangleCount = indices.count / 3; + def.indices = indices.data; + def.materialIndices = materialCount > 0 ? materialIndices.data : NULL; + def.useMedianSplit = true; + def.identifyEdges = identifyEdges; + + b3MeshData* meshData = b3CreateMesh( &def, NULL, 0 ); + + b3Array_Destroy( indices ); + b3Array_Destroy( vertices ); + b3Array_Destroy( materialIndices ); + + return meshData; +} + +b3MeshData* b3CreateWaveMesh( int xCount, int zCount, float cellWidth, float amplitude, float rowFrequency, + float columnFrequency ) +{ + // Create vertices + int vertexCount = ( xCount + 1 ) * ( zCount + 1 ); + + b3ArrayC( b3Vec3 ) vertices = { 0 }; + b3Array_Resize( vertices, vertexCount ); + int index = 0; + + float xWidth = cellWidth * xCount; + float zWidth = cellWidth * zCount; + + float omegaZ = 2.0f * B3_PI * rowFrequency; + float omegaX = 2.0f * B3_PI * columnFrequency; + + float x = -0.5f * xWidth; + for ( int ix = 0; ix <= xCount; ++ix ) + { + float rowHeight = sinf( omegaX * ix ); + + float z = -0.5f * zWidth; + for ( int iz = 0; iz <= zCount; ++iz ) + { + float columnHeight = sinf( omegaZ * iz ); + + float y = amplitude * rowHeight * columnHeight; + vertices.data[index] = (b3Vec3){ x, y, z }; + z += cellWidth; + index += 1; + } + x += cellWidth; + } + B3_ASSERT( index == vertexCount ); + + // Triangles + int triangleCount = 2 * xCount * zCount; + + b3ArrayC( int ) indices = { 0 }; + b3Array_Resize( indices, 3 * triangleCount ); + + index = 0; + for ( int ix = 0; ix < xCount; ++ix ) + { + for ( int iz = 0; iz < zCount; ++iz ) + { + int index1 = iz + ( zCount + 1 ) * ix; + int index2 = index1 + 1; + int index3 = index2 + ( zCount + 1 ); + int index4 = index3 - 1; + + B3_ASSERT( index1 < vertexCount ); + B3_ASSERT( index2 < vertexCount ); + B3_ASSERT( index3 < vertexCount ); + B3_ASSERT( index4 < vertexCount ); + + indices.data[index + 0] = index1; + indices.data[index + 1] = index2; + indices.data[index + 2] = index3; + + indices.data[index + 3] = index3; + indices.data[index + 4] = index4; + indices.data[index + 5] = index1; + + index += 6; + } + } + B3_ASSERT( index == 3 * triangleCount ); + + b3MeshDef def = { 0 }; + def.vertexCount = vertices.count; + def.vertices = vertices.data; + def.triangleCount = indices.count / 3; + def.indices = indices.data; + def.useMedianSplit = true; + def.identifyEdges = true; + + b3MeshData* meshData = b3CreateMesh( &def, NULL, 0 ); + + b3Array_Destroy( indices ); + b3Array_Destroy( vertices ); + + return meshData; +} + +b3MeshData* b3CreateTorusMesh( int radialResolution, int tubularResolution, float radius, float thickness ) +{ + // Create vertices + b3ArrayC( b3Vec3 ) vertices = { 0 }; + + for ( int radialIndex = 0; radialIndex < radialResolution; radialIndex++ ) + { + for ( int tubularIndex = 0; tubularIndex < tubularResolution; tubularIndex++ ) + { + float u = (float)tubularIndex / tubularResolution * B3_TWO_PI; + float v = (float)radialIndex / radialResolution * B3_TWO_PI; + + float x = ( radius + thickness * b3Cos( v ) ) * b3Cos( u ); + float y = ( radius + thickness * b3Cos( v ) ) * b3Sin( u ); + float z = thickness * b3Sin( v ); + + b3Vec3 vertex = { x, y, z }; + b3Array_Push( vertices, vertex ); + } + } + + // Triangles + b3ArrayC( int ) indices = { 0 }; + for ( int radialIndex1 = 0; radialIndex1 < radialResolution; radialIndex1++ ) + { + int radialIndex2 = ( radialIndex1 + 1 ) % radialResolution; + for ( int tubularIndex1 = 0; tubularIndex1 < tubularResolution; tubularIndex1++ ) + { + int tubularIndex2 = ( tubularIndex1 + 1 ) % tubularResolution; + int index1 = radialIndex1 * tubularResolution + tubularIndex1; + int index2 = radialIndex1 * tubularResolution + tubularIndex2; + int index3 = radialIndex2 * tubularResolution + tubularIndex2; + int index4 = radialIndex2 * tubularResolution + tubularIndex1; + + b3Array_Push( indices, index1 ); + b3Array_Push( indices, index2 ); + b3Array_Push( indices, index3 ); + + b3Array_Push( indices, index3 ); + b3Array_Push( indices, index4 ); + b3Array_Push( indices, index1 ); + } + } + + b3MeshDef def = { 0 }; + def.vertexCount = vertices.count; + def.vertices = vertices.data; + def.triangleCount = indices.count / 3; + def.indices = indices.data; + def.useMedianSplit = false; + def.identifyEdges = true; + + b3MeshData* meshData = b3CreateMesh( &def, NULL, 0 ); + + b3Array_Destroy( vertices ); + b3Array_Destroy( indices ); + return meshData; +} + +b3MeshData* b3CreateBoxMesh( b3Vec3 center, b3Vec3 extent, bool identifyEdges ) +{ + float x = extent.x; + float y = extent.y; + float z = extent.z; + b3Vec3 vertices[] = { + { x, y, z }, { -x, y, z }, { -x, -y, z }, { x, -y, z }, { x, y, -z }, { -x, y, -z }, { -x, -y, -z }, { x, -y, -z }, + }; + + for ( int i = 0; i < 8; ++i ) + { + vertices[i] = b3Add( vertices[i], center ); + } + + int indices[] = { + 0, 1, 3, 1, 2, 3, // front + 0, 4, 1, 1, 4, 5, // top + 0, 3, 7, 4, 0, 7, // right + 4, 7, 5, 6, 5, 7, // back + 1, 5, 2, 6, 2, 5, // left + 3, 2, 7, 6, 7, 2, // bottom + }; + + b3MeshDef def = { 0 }; + def.vertexCount = 8; + def.vertices = vertices; + def.triangleCount = 12; + def.indices = indices; + def.useMedianSplit = false; + def.identifyEdges = identifyEdges; + + return b3CreateMesh( &def, NULL, 0 ); +} + +// todo this should fail if the mesh has a height greater than B3_MESH_STACK_SIZE +b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices, int degenerateCapacity ) +{ + if ( def->vertexCount < 3 || def->vertices == NULL || def->triangleCount <= 0 || def->indices == NULL ) + { + return NULL; + } + + int triangleCount = def->triangleCount; + if ( triangleCount == 0 ) + { + return NULL; + } + + int vertexCount = def->vertexCount; + + b3AABB meshBounds = B3_BOUNDS3_EMPTY; + + // Clone indices and vertices to support welding + b3ArrayC( int ) indices; + b3Array_CreateN( indices, 3 * triangleCount ); + + b3ArrayC( b3Vec3 ) vertices; + b3Array_CreateN( vertices, vertexCount ); + + if ( def->weldVertices && def->weldTolerance > 0.0f ) + { + b3Array_Resize( vertices, vertexCount ); + b3Array_Resize( indices, 3 * triangleCount ); + b3WeldData data = { + .srcVertices = def->vertices, + .srcIndices = def->indices, + .dstVertices = vertices.data, + .dstIndices = indices.data, + .vertexCount = vertexCount, + .indexCount = 3 * triangleCount, + }; + vertices.count = b3WeldVertices( &data, def->weldTolerance ); + vertexCount = vertices.count; + B3_ASSERT( vertexCount <= def->vertexCount ); + } + else + { + b3Array_Append( vertices, def->vertices, vertexCount ); + b3Array_Append( indices, def->indices, 3 * triangleCount ); + } + + b3ArrayC( b3Primitive ) primitives; + b3Array_CreateN( primitives, triangleCount ); + int degenerateCount = 0; + float minArea = 0.01f * B3_LINEAR_SLOP * B3_LINEAR_SLOP; + float surfaceArea = 0.0f; + int materialCount = 1; + + for ( int index = 0; index < triangleCount; ++index ) + { + int index1 = indices.data[3 * index + 0]; + int index2 = indices.data[3 * index + 1]; + int index3 = indices.data[3 * index + 2]; + + b3Vec3 vertex1 = vertices.data[index1]; + b3Vec3 vertex2 = vertices.data[index2]; + b3Vec3 vertex3 = vertices.data[index3]; + + b3Vec3 normal = b3Cross( b3Sub( vertex2, vertex1 ), b3Sub( vertex3, vertex1 ) ); + float area = 0.5f * b3Length( normal ); + + if ( area < minArea ) + { + // b3Log( "degenerate: %d %d %d\n", index1, index2, index3 ); + + if ( index1 != index2 && index1 != index3 && index2 != index3 ) + { + degenerateCount += 1; + if ( degenerateTriangleIndices != NULL && degenerateCount < degenerateCapacity ) + { + degenerateTriangleIndices[degenerateCount - 1] = index; + } + } + + continue; + } + + surfaceArea += area; + + b3AABB box = { + b3Min( vertex1, b3Min( vertex2, vertex3 ) ), + b3Max( vertex1, b3Max( vertex2, vertex3 ) ), + }; + + b3Vec3 center = b3AABB_Center( box ); + + b3Primitive primitive = { + .aabb = box, + .center = center, + .triangleIndex = index, + }; + b3Array_Push( primitives, primitive ); + + if ( def->materialIndices != NULL ) + { + materialCount = b3MaxInt( materialCount, def->materialIndices[index] + 1 ); + } + + meshBounds = b3AABB_Union( meshBounds, box ); + } + + // Update triangle count due to degenerates being skipped + triangleCount = primitives.count; + + if ( b3IsSaneAABB( meshBounds ) == false ) + { + b3Array_Destroy( primitives ); + return NULL; + } + + // Build the tree (this reorders the builder triangles) + b3ArrayC( b3MeshNode ) tempNodes; + b3Array_CreateN( tempNodes, 2 * triangleCount - 1 ); + + int treeHeight = 0; + b3BuildRecursive( &tempNodes, triangleCount, primitives.data, primitives.data, def->useMedianSplit, &treeHeight ); + + // Allocate the mesh + int byteCount = sizeof( b3MeshData ); + int nodeOffset = byteCount; + byteCount += tempNodes.count * sizeof( b3MeshNode ); + int vertexOffset = byteCount; + byteCount += vertexCount * sizeof( b3Vec3 ); + int triangleOffset = byteCount; + byteCount += triangleCount * sizeof( b3MeshTriangle ); + int materialIndicesOffset = byteCount; + byteCount += triangleCount * sizeof( uint8_t ); + int flagsOffset = byteCount; + byteCount += triangleCount * sizeof( uint8_t ); + + b3MeshData* mesh = (b3MeshData*)b3Alloc( byteCount ); + + // zero initialize for determinism + memset( mesh, 0, byteCount ); + + mesh->version = B3_MESH_VERSION; + mesh->byteCount = byteCount; + mesh->bounds = meshBounds; + mesh->surfaceArea = surfaceArea; + mesh->nodeCount = tempNodes.count; + mesh->treeHeight = treeHeight; + mesh->vertexCount = vertexCount; + mesh->triangleCount = triangleCount; + mesh->degenerateCount = degenerateCount; + mesh->nodeOffset = nodeOffset; + mesh->vertexOffset = vertexOffset; + mesh->triangleOffset = triangleOffset; + mesh->materialOffset = materialIndicesOffset; + mesh->materialCount = materialCount; + mesh->flagsOffset = flagsOffset; + + b3MeshNode* nodes = b3GetMeshNodesWrite( mesh ); + b3MeshTriangle* triangles = b3GetMeshTrianglesWrite( mesh ); + b3Vec3* meshVertices = b3GetMeshVerticesWrite( mesh ); + uint8_t* materialIndices = b3GetMeshMaterialIndicesWrite( mesh ); + uint8_t* flags = b3GetMeshFlagsWrite( mesh ); + + memcpy( nodes, tempNodes.data, tempNodes.count * sizeof( b3MeshNode ) ); + memcpy( meshVertices, vertices.data, vertexCount * sizeof( b3Vec3 ) ); + + for ( int index = 0; index < triangleCount; ++index ) + { + b3Primitive primitive = primitives.data[index]; + triangles[index].index1 = indices.data[3 * primitive.triangleIndex + 0]; + triangles[index].index2 = indices.data[3 * primitive.triangleIndex + 1]; + triangles[index].index3 = indices.data[3 * primitive.triangleIndex + 2]; + flags[index] = 0; + + // Copy material indices if they exist. Otherwise the material indices are all zeroes. + if ( def->materialIndices != NULL ) + { + uint8_t materialIndex = def->materialIndices[primitive.triangleIndex]; + materialIndices[index] = materialIndex; + } + } + + // Sort triangle in DFS order. Casts and volume queries will return sorted arrays. + // This also sorts material indices, but not the materials. + // This can fail if the BVH height is too large. + bool success = b3SortMeshTriangles( mesh ); + if ( success == false ) + { + b3Array_Destroy( tempNodes ); + b3Array_Destroy( primitives ); + return NULL; + } + + if ( def->identifyEdges ) + { + b3IdentifyEdges( mesh ); + } + + B3_VALIDATE( b3IsNonDegenerate( mesh, minArea ) ); + B3_VALIDATE( b3IsConsistent( mesh ) ); + + b3Array_Destroy( tempNodes ); + b3Array_Destroy( primitives ); + b3Array_Destroy( indices ); + b3Array_Destroy( vertices ); + + mesh->hash = 0; + mesh->hash = b3Hash( B3_HASH_INIT, (uint8_t*)mesh, mesh->byteCount ); + + return mesh; +} + +void b3DestroyMesh( b3MeshData* mesh ) +{ + b3Free( mesh, mesh->byteCount ); +} + +bool b3OverlapMesh( const b3Mesh* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy ) +{ + B3_ASSERT( proxy->count > 0 ); + b3SimplexCache cache = { 0 }; + + b3Vec3 buffer[B3_MAX_SHAPE_CAST_POINTS]; + b3ShapeProxy localProxy = b3MakeLocalProxy( proxy, shapeTransform, buffer ); + b3AABB aabb = b3ComputeProxyAABB( &localProxy ); + + b3Vec3 meshScale = shape->scale; + + // Scale may have reflection so min/max may become invalid when unscaled + b3V32 scale = b3LoadV( &meshScale.x ); + b3V32 invScale = b3DivV( b3_oneV, scale ); + b3V32 temp1 = b3MulV( invScale, b3LoadV( &aabb.lowerBound.x ) ); + b3V32 temp2 = b3MulV( invScale, b3LoadV( &aabb.upperBound.x ) ); + b3V32 invScaledBoundsMin = b3MinV( temp1, temp2 ); + b3V32 invScaledBoundsMax = b3MaxV( temp1, temp2 ); + b3V32 invScaledBoundsCenter = b3MulV( b3_halfV, b3AddV( invScaledBoundsMin, invScaledBoundsMax ) ); + b3V32 invScaledBoundsExtent = b3SubV( invScaledBoundsMax, invScaledBoundsCenter ); + + b3DistanceInput input; + input.proxyB = localProxy; + input.transformA = b3Transform_identity; + input.transformB = b3Transform_identity; + input.useRadii = true; + + int count = 0; + const b3MeshNode* stack[B3_MESH_STACK_SIZE]; + const b3MeshNode* node = b3GetRoot( shape->data ); + const b3MeshTriangle* triangles = b3GetMeshTriangles( shape->data ); + const b3Vec3* vertices = b3GetMeshVertices( shape->data ); + + while ( true ) + { + // Test node overlap in unscaled space + b3V32 nodeMin = b3LoadV( &node->lowerBound.x ); + b3V32 nodeMax = b3LoadV( &node->upperBound.x ); + if ( b3TestBoundsOverlap( nodeMin, nodeMax, invScaledBoundsMin, invScaledBoundsMax ) ) + { + if ( b3IsLeaf( node ) ) + { + int triangleCount = node->data.asLeaf.triangleCount; + int triangleOffset = node->triangleOffset; + + for ( int index = 0; index < triangleCount; ++index ) + { + int triangleIndex = triangleOffset + index; + b3MeshTriangle triangle = triangles[triangleIndex]; + + b3Vec3 vertex1 = vertices[triangle.index1]; + b3Vec3 vertex2 = vertices[triangle.index2]; + b3Vec3 vertex3 = vertices[triangle.index3]; + b3V32 v1 = b3LoadV( &vertex1.x ); + b3V32 v2 = b3LoadV( &vertex2.x ); + b3V32 v3 = b3LoadV( &vertex3.x ); + + // Bounding box overlap test in unscaled space + if ( b3TestBoundsTriangleOverlap( invScaledBoundsCenter, invScaledBoundsExtent, v1, v2, v3 ) ) + { + // Shape-triangle overlap test in scaled space. Winding order doesn't matter. + b3Vec3 triangleVertices[] = { b3Mul( meshScale, vertex1 ), b3Mul( meshScale, vertex2 ), b3Mul( meshScale, vertex3 ) }; + input.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f }; + + // reset the cache + cache.count = 0; + + // get distance between triangle and query shape + b3DistanceOutput output = b3ShapeDistance( &input, &cache, NULL, 0 ); + + float tolerance = 0.1f * B3_LINEAR_SLOP; + if ( output.distance < tolerance ) + { + // overlap detected + return true; + } + } + } + } + else + { + // Recurse + B3_ASSERT( count <= B3_MESH_STACK_SIZE - 1 ); + stack[count++] = b3GetRightChild( node ); + node = b3GetLeftChild( node ); + + continue; + } + } + + if ( count == 0 ) + { + break; + } + node = stack[--count]; + } + + return false; +} + +b3AABB b3ComputeMeshAABB( const b3MeshData* shape, b3Transform transform, b3Vec3 scale ) +{ + b3Vec3 scaledLower = b3Mul( scale, shape->bounds.lowerBound ); + b3Vec3 scaledUpper = b3Mul( scale, shape->bounds.upperBound ); + b3AABB bounds = { b3Min( scaledLower, scaledUpper ), b3Max( scaledLower, scaledUpper ) }; + return b3AABB_Transform( transform, bounds ); +} + +b3CastOutput b3RayCastMesh( const b3Mesh* mesh, const b3RayCastInput* input ) +{ + const b3MeshData* data = mesh->data; + b3Vec3 meshScale = mesh->scale; + + b3CastOutput bestOutput = { 0 }; + bestOutput.fraction = input->maxFraction; + bestOutput.triangleIndex = B3_NULL_INDEX; + + b3V32 lambda = b3SplatV( input->maxFraction ); + + b3V32 rayStart = b3LoadV( &input->origin.x ); + b3V32 rayDelta = b3LoadV( &input->translation.x ); + + b3V32 scale = b3LoadV( &meshScale.x ); + b3V32 invScale = b3DivV( b3_oneV, scale ); + bool clockwise = meshScale.x * meshScale.y * meshScale.z < 0.0f; + + // Use the inverse scaled ray for traversal of the BVH + b3V32 invScaledRayStart = b3MulV( invScale, rayStart ); + b3V32 invScaledRayDelta = b3MulV( invScale, rayDelta ); + b3V32 invScaledRayEnd = b3AddV( invScaledRayStart, b3MulV( lambda, invScaledRayDelta ) ); + b3V32 invScaledRayMin = b3MinV( invScaledRayStart, invScaledRayEnd ); + b3V32 invScaledRayMax = b3MaxV( invScaledRayStart, invScaledRayEnd ); + + int count = 0; + const b3MeshNode* stack[B3_MESH_STACK_SIZE]; + const b3MeshNode* node = b3GetRoot( data ); + const b3MeshTriangle* triangles = b3GetMeshTriangles( data ); + const b3Vec3* vertices = b3GetMeshVertices( data ); + const uint8_t* materialIndices = b3GetMeshMaterialIndices( data ); + + while ( true ) + { + // Test node/ray overlap using SAT + b3V32 nodeMin = b3LoadV( &node->lowerBound.x ); + b3V32 nodeMax = b3LoadV( &node->upperBound.x ); + if ( b3TestBoundsOverlap( nodeMin, nodeMax, invScaledRayMin, invScaledRayMax ) && + b3TestBoundsRayOverlap( nodeMin, nodeMax, invScaledRayStart, invScaledRayDelta ) ) + { + // SAT: The node and ray overlap - process leaf node or recurse + if ( b3IsLeaf( node ) ) + { + int triangleCount = node->data.asLeaf.triangleCount; + int triangleOffset = node->triangleOffset; + + for ( int index = 0; index < triangleCount; ++index ) + { + int triangleIndex = triangleOffset + index; + b3MeshTriangle triangle = triangles[triangleIndex]; + + // Collide ray with triangle in scaled space + b3Vec3 vertex1 = b3Mul( meshScale, vertices[triangle.index1] ); + b3Vec3 vertex2, vertex3; + + // The CPU should predict this branch + if ( clockwise ) + { + vertex2 = b3Mul( meshScale, vertices[triangle.index3] ); + vertex3 = b3Mul( meshScale, vertices[triangle.index2] ); + } + else + { + vertex2 = b3Mul( meshScale, vertices[triangle.index2] ); + vertex3 = b3Mul( meshScale, vertices[triangle.index3] ); + } + + // Collide ray with triangle in scaled space + b3V32 v1 = b3LoadV( &vertex1.x ); + b3V32 v2 = b3LoadV( &vertex2.x ); + b3V32 v3 = b3LoadV( &vertex3.x ); + + float alpha = b3IntersectRayTriangle( rayStart, rayDelta, v1, v2, v3 ); + B3_ASSERT( 0 <= alpha && alpha <= 1.0f ); + + if ( alpha < bestOutput.fraction ) + { + b3Vec3 edge1 = b3Sub( vertex2, vertex1 ); + b3Vec3 edge2 = b3Sub( vertex3, vertex1 ); + bestOutput.normal = b3Normalize( b3Cross( edge1, edge2 ) ); + bestOutput.point = b3Add( input->origin, b3MulSV( alpha, input->translation ) ); + bestOutput.fraction = alpha; + bestOutput.triangleIndex = triangleIndex; + bestOutput.materialIndex = materialIndices[triangleIndex]; + bestOutput.hit = true; + + // Update ray bounds in unscaled space + lambda = b3SplatV( alpha ); + invScaledRayEnd = b3AddV( invScaledRayStart, b3MulV( lambda, invScaledRayDelta ) ); + invScaledRayMin = b3MinV( invScaledRayStart, invScaledRayEnd ); + invScaledRayMax = b3MaxV( invScaledRayStart, invScaledRayEnd ); + } + } + } + else + { + // Determine traversal order (front -> back) and recurse + int axis = node->data.asNode.axis; + if ( b3GetV( invScaledRayDelta, axis ) > 0.0f ) + { + B3_ASSERT( count <= B3_MESH_STACK_SIZE - 1 ); + stack[count++] = b3GetRightChild( node ); + node = b3GetLeftChild( node ); + } + else + { + B3_ASSERT( count <= B3_MESH_STACK_SIZE - 1 ); + stack[count++] = b3GetLeftChild( node ); + node = b3GetRightChild( node ); + } + + continue; + } + } + + if ( count == 0 ) + { + break; + } + node = stack[--count]; + } + + return bestOutput; +} + +b3CastOutput b3ShapeCastMesh( const b3Mesh* mesh, const b3ShapeCastInput* input ) +{ + const b3MeshData* data = mesh->data; + b3Vec3 meshScale = mesh->scale; + + b3CastOutput bestOutput = { 0 }; + bestOutput.fraction = input->maxFraction; + bestOutput.triangleIndex = B3_NULL_INDEX; + + b3V32 lambda = b3SplatV( input->maxFraction ); + + b3AABB shapeBounds = b3MakeAABB( input->proxy.points, input->proxy.count, input->proxy.radius ); + b3Vec3 center = b3AABB_Center( shapeBounds ); + b3Vec3 extents = b3AABB_Extents( shapeBounds ); + b3V32 shapeExtent = b3LoadV( &extents.x ); + + b3V32 rayStart = b3LoadV( ¢er.x ); + b3V32 rayDelta = b3LoadV( &input->translation.x ); + b3V32 rayEnd = b3AddV( rayStart, b3MulV( lambda, rayDelta ) ); + b3V32 rayMin = b3MinV( rayStart, rayEnd ); + b3V32 rayMax = b3MaxV( rayStart, rayEnd ); + + b3V32 scale = b3LoadV( &meshScale.x ); + b3V32 invScale = b3DivV( b3_oneV, scale ); + b3V32 absInvScale = b3AbsV( invScale ); + bool clockwise = meshScale.x * meshScale.y * meshScale.z < 0.0f; + + // Use the inverse scaled shape cast for traversal of the BVH + b3V32 invScaledRayStart = b3MulV( invScale, rayStart ); + b3V32 invScaledRayDelta = b3MulV( invScale, rayDelta ); + b3V32 invScaledRayEnd = b3AddV( invScaledRayStart, b3MulV( lambda, invScaledRayDelta ) ); + b3V32 invScaledRayMin = b3MinV( invScaledRayStart, invScaledRayEnd ); + b3V32 invScaledRayMax = b3MaxV( invScaledRayStart, invScaledRayEnd ); + b3V32 invScaledShapeExtent = b3MulV( absInvScale, shapeExtent ); + + int count = 0; + const b3MeshNode* stack[B3_MESH_STACK_SIZE]; + const b3MeshNode* node = b3GetRoot( data ); + const b3MeshTriangle* triangles = b3GetMeshTriangles( data ); + const b3Vec3* vertices = b3GetMeshVertices( data ); + const uint8_t* materialIndices = b3GetMeshMaterialIndices( data ); + + while ( true ) + { + // Test node/ray overlap using SAT in unscaled space + b3V32 nodeMin = b3SubV( b3LoadV( &node->lowerBound.x ), invScaledShapeExtent ); + b3V32 nodeMax = b3AddV( b3LoadV( &node->upperBound.x ), invScaledShapeExtent ); + + if ( b3TestBoundsOverlap( nodeMin, nodeMax, invScaledRayMin, invScaledRayMax ) && + b3TestBoundsRayOverlap( nodeMin, nodeMax, invScaledRayStart, invScaledRayDelta ) ) + { + // SAT: The node and ray overlap - process leaf node or recurse + if ( b3IsLeaf( node ) ) + { + int triangleCount = node->data.asLeaf.triangleCount; + int triangleOffset = node->triangleOffset; + + for ( int index = 0; index < triangleCount; ++index ) + { + int triangleIndex = triangleOffset + index; + b3MeshTriangle triangle = triangles[triangleIndex]; + + // Collide ray with triangle in scaled space + b3Vec3 vertex1 = b3Mul( meshScale, vertices[triangle.index1] ); + b3Vec3 vertex2, vertex3; + + // The CPU should predict this branch + if ( clockwise ) + { + vertex2 = b3Mul( meshScale, vertices[triangle.index3] ); + vertex3 = b3Mul( meshScale, vertices[triangle.index2] ); + } + else + { + vertex2 = b3Mul( meshScale, vertices[triangle.index2] ); + vertex3 = b3Mul( meshScale, vertices[triangle.index3] ); + } + + b3V32 v1 = b3LoadV( &vertex1.x ); + b3V32 v2 = b3LoadV( &vertex2.x ); + b3V32 v3 = b3LoadV( &vertex3.x ); + + b3V32 triangleMin = b3SubV( b3MinV( v1, b3MinV( v2, v3 ) ), shapeExtent ); + b3V32 triangleMax = b3AddV( b3MaxV( v1, b3MaxV( v2, v3 ) ), shapeExtent ); + + // Test triangle-ray overlap in scaled space + if ( b3TestBoundsOverlap( triangleMin, triangleMax, rayMin, rayMax ) ) + { + // Collide shape with triangle in scaled space + b3Vec3 origin = vertex1; + b3Vec3 triangleVertices[] = { b3Vec3_zero, b3Sub( vertex2, origin ), b3Sub( vertex3, origin ) }; + b3Transform shiftedOrigin = { b3Neg( origin ), b3Quat_identity }; + + b3ShapeCastPairInput pairInput; + pairInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f }; + pairInput.proxyB = input->proxy; + pairInput.transformA = b3Transform_identity; + pairInput.transformB = shiftedOrigin; + pairInput.maxFraction = bestOutput.fraction; + pairInput.translationB = input->translation; + pairInput.canEncroach = input->canEncroach; + + b3CastOutput pairOutput = b3ShapeCast( &pairInput ); + + if ( pairOutput.hit ) + { + pairOutput.point = b3Add( pairOutput.point, origin ); + + bestOutput = pairOutput; + bestOutput.triangleIndex = triangleIndex; + bestOutput.materialIndex = materialIndices[triangleIndex]; + + // Update ray bounds in scaled space + lambda = b3SplatV( pairOutput.fraction ); + rayEnd = b3AddV( rayStart, b3MulV( lambda, rayDelta ) ); + rayMin = b3MinV( rayStart, rayEnd ); + rayMax = b3MaxV( rayStart, rayEnd ); + + // Ray bounds in unscaled space + invScaledRayEnd = b3AddV( invScaledRayStart, b3MulV( lambda, invScaledRayDelta ) ); + invScaledRayMin = b3MinV( invScaledRayStart, invScaledRayEnd ); + invScaledRayMax = b3MaxV( invScaledRayStart, invScaledRayEnd ); + } + } + } + } + else + { + // Determine traversal order (front -> back) and recurse + int axis = node->data.asNode.axis; + if ( b3GetV( invScaledRayDelta, axis ) > 0.0f ) + { + B3_ASSERT( count <= B3_MESH_STACK_SIZE - 1 ); + stack[count++] = b3GetRightChild( node ); + node = b3GetLeftChild( node ); + } + else + { + B3_ASSERT( count <= B3_MESH_STACK_SIZE - 1 ); + stack[count++] = b3GetLeftChild( node ); + node = b3GetRightChild( node ); + } + + continue; + } + } + + if ( count == 0 ) + { + break; + } + node = stack[--count]; + } + + return bestOutput; +} + +b3Triangle b3GetMeshTriangle( const b3Mesh* mesh, int triangleIndex ) +{ + B3_ASSERT( 0 <= triangleIndex && triangleIndex < mesh->data->triangleCount ); + + const b3MeshTriangle* triangles = b3GetMeshTriangles( mesh->data ); + const uint8_t* flags = b3GetMeshFlags( mesh->data ); + const b3Vec3* vertices = b3GetMeshVertices( mesh->data ); + + b3Triangle result; + b3MeshTriangle triangle = triangles[triangleIndex]; + uint8_t triangleFlags = flags[triangleIndex]; + + b3Vec3 scale = mesh->scale; + + result.vertices[0] = b3Mul( scale, vertices[triangle.index1] ); + result.i1 = triangle.index1; + + if ( scale.x * scale.y * scale.z < 0.0f ) + { + result.vertices[1] = b3Mul( scale, vertices[triangle.index3] ); + result.vertices[2] = b3Mul( scale, vertices[triangle.index2] ); + + result.i2 = triangle.index3; + result.i3 = triangle.index2; + + // mesh is inverted, so concave edges are now convex + result.flags = 0; + result.flags |= ( triangleFlags & b3_inverseConcaveEdge1 ) ? b3_concaveEdge1 : 0; + result.flags |= ( triangleFlags & b3_inverseConcaveEdge2 ) ? b3_concaveEdge2 : 0; + result.flags |= ( triangleFlags & b3_inverseConcaveEdge3 ) ? b3_concaveEdge3 : 0; + } + else + { + result.vertices[1] = b3Mul( scale, vertices[triangle.index2] ); + result.vertices[2] = b3Mul( scale, vertices[triangle.index3] ); + + result.i2 = triangle.index2; + result.i3 = triangle.index3; + result.flags = triangleFlags; + } + + return result; +} + +int b3CollideMoverAndMesh( b3PlaneResult* planes, int capacity, const b3Mesh* shape, const b3Capsule* mover ) +{ + if ( capacity == 0 ) + { + return 0; + } + + b3DistanceInput distanceInput = { 0 }; + distanceInput.proxyB = (b3ShapeProxy){ &mover->center1, 2, 0.0f }; + distanceInput.transformA = b3Transform_identity; + distanceInput.transformB = b3Transform_identity; + distanceInput.useRadii = false; + + b3SimplexCache cache = { 0 }; + float radius = mover->radius; + + b3V32 center1 = b3LoadV( &mover->center1.x ); + b3V32 center2 = b3LoadV( &mover->center2.x ); + b3V32 r = b3SplatV( radius ); + b3V32 boundsMin = b3SubV( b3MinV( center1, center2 ), r ); + b3V32 boundsMax = b3AddV( b3MaxV( center1, center2 ), r ); + + // Scale may have reflection so min/max may become invalid when unscaled + b3Vec3 meshScale = shape->scale; + b3V32 scale = b3LoadV( &meshScale.x ); + b3V32 invScale = b3DivV( b3_oneV, scale ); + b3V32 temp1 = b3MulV( invScale, boundsMin ); + b3V32 temp2 = b3MulV( invScale, boundsMax ); + b3V32 invScaledBoundsMin = b3MinV( temp1, temp2 ); + b3V32 invScaledBoundsMax = b3MaxV( temp1, temp2 ); + b3V32 invScaledBoundsCenter = b3MulV( b3_halfV, b3AddV( invScaledBoundsMin, invScaledBoundsMax ) ); + b3V32 invScaledBoundsExtent = b3SubV( invScaledBoundsMax, invScaledBoundsCenter ); + + int count = 0; + const b3MeshNode* stack[B3_MESH_STACK_SIZE]; + const b3MeshNode* node = b3GetRoot( shape->data ); + const b3MeshTriangle* triangles = b3GetMeshTriangles( shape->data ); + const b3Vec3* vertices = b3GetMeshVertices( shape->data ); + + int planeCount = 0; + while ( planeCount < capacity ) + { + // Test node overlap in unscaled space + b3V32 nodeMin = b3LoadV( &node->lowerBound.x ); + b3V32 nodeMax = b3LoadV( &node->upperBound.x ); + if ( b3TestBoundsOverlap( nodeMin, nodeMax, invScaledBoundsMin, invScaledBoundsMax ) ) + { + if ( b3IsLeaf( node ) ) + { + int triangleCount = node->data.asLeaf.triangleCount; + int triangleOffset = node->triangleOffset; + + for ( int index = 0; index < triangleCount; ++index ) + { + int triangleIndex = triangleOffset + index; + b3MeshTriangle triangle = triangles[triangleIndex]; + + b3Vec3 vertex1 = vertices[triangle.index1]; + b3Vec3 vertex2 = vertices[triangle.index2]; + b3Vec3 vertex3 = vertices[triangle.index3]; + b3V32 v1 = b3LoadV( &vertex1.x ); + b3V32 v2 = b3LoadV( &vertex2.x ); + b3V32 v3 = b3LoadV( &vertex3.x ); + + // Test triangle bounds overlap in unscaled space + if ( b3TestBoundsTriangleOverlap( invScaledBoundsCenter, invScaledBoundsExtent, v1, v2, v3 ) ) + { + // Compute shape distance in scaled space. Winding order doesn't matter. + // todo implement one-sided collision? + b3Vec3 triangleVertices[] = { b3Mul( meshScale, vertex1 ), b3Mul( meshScale, vertex2 ), b3Mul( meshScale, vertex3 ) }; + distanceInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f }; + + // reset the cache + cache.count = 0; + + // get distance between triangle and query shape + b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, &cache, NULL, 0 ); + + if ( distanceOutput.distance == 0.0f ) + { + // todo SAT + } + else if ( distanceOutput.distance <= mover->radius ) + { + b3Plane plane = { distanceOutput.normal, mover->radius - distanceOutput.distance }; + planes[planeCount] = (b3PlaneResult){ plane, distanceOutput.pointA }; + planeCount += 1; + + if ( planeCount == capacity ) + { + return planeCount; + } + } + } + } + } + else + { + // Recurse + B3_ASSERT( count <= B3_MESH_STACK_SIZE - 1 ); + stack[count++] = b3GetRightChild( node ); + node = b3GetLeftChild( node ); + + continue; + } + } + + if ( count == 0 ) + { + break; + } + node = stack[--count]; + } + + return planeCount; +} + +void b3QueryMesh( const b3Mesh* mesh, b3AABB bounds, b3MeshQueryFcn* fcn, void* context ) +{ + b3Vec3 meshScale = mesh->scale; + bool clockwise = meshScale.x * meshScale.y * meshScale.z > 0.0f; + + // Scale may have reflection so min/max may become invalid when unscaled + b3V32 scale = b3LoadV( &meshScale.x ); + b3V32 invScale = b3DivV( b3_oneV, scale ); + b3V32 temp1 = b3MulV( invScale, b3LoadV( &bounds.lowerBound.x ) ); + b3V32 temp2 = b3MulV( invScale, b3LoadV( &bounds.upperBound.x ) ); + b3V32 invScaledBoundsMin = b3MinV( temp1, temp2 ); + b3V32 invScaledBoundsMax = b3MaxV( temp1, temp2 ); + b3V32 invScaledBoundsCenter = b3MulV( b3_halfV, b3AddV( invScaledBoundsMin, invScaledBoundsMax ) ); + b3V32 invScaledBoundsExtent = b3SubV( invScaledBoundsMax, invScaledBoundsCenter ); + + const b3MeshData* data = mesh->data; + + int count = 0; + const b3MeshNode* stack[B3_MESH_STACK_SIZE]; + const b3MeshNode* node = b3GetRoot( data ); + const b3MeshTriangle* triangles = b3GetMeshTriangles( data ); + const b3Vec3* vertices = b3GetMeshVertices( data ); + + while ( true ) + { + // Test node overlap in unscaled space + b3V32 nodeMin = b3LoadV( &node->lowerBound.x ); + b3V32 nodeMax = b3LoadV( &node->upperBound.x ); + + if ( b3TestBoundsOverlap( nodeMin, nodeMax, invScaledBoundsMin, invScaledBoundsMax ) ) + { + if ( b3IsLeaf( node ) ) + { + int triangleCount = node->data.asLeaf.triangleCount; + int triangleOffset = node->triangleOffset; + + for ( int index = 0; index < triangleCount; ++index ) + { + int triangleIndex = triangleOffset + index; + b3MeshTriangle triangle = triangles[triangleIndex]; + + b3Vec3 vertex1 = vertices[triangle.index1]; + b3Vec3 vertex2 = vertices[triangle.index2]; + b3Vec3 vertex3 = vertices[triangle.index3]; + b3V32 v1 = b3LoadV( &vertex1.x ); + b3V32 v2 = b3LoadV( &vertex2.x ); + b3V32 v3 = b3LoadV( &vertex3.x ); + + // Perform triangle overlap test in unscaled space. Winding order doesn't matter. + // todo it is possible that some margins are getting scaled + if ( b3TestBoundsTriangleOverlap( invScaledBoundsCenter, invScaledBoundsExtent, v1, v2, v3 ) ) + { + b3Vec3 a = b3Mul( meshScale, vertex1 ); + b3Vec3 b, c; + if ( clockwise ) + { + b = b3Mul( meshScale, vertex2 ); + c = b3Mul( meshScale, vertex3 ); + } + else + { + b = b3Mul( meshScale, vertex3 ); + c = b3Mul( meshScale, vertex2 ); + } + + bool result = fcn( a, b, c, triangleIndex, context ); + if ( result == false ) + { + return; + } + } + } + } + else + { + // Recurse + B3_ASSERT( count <= B3_MESH_STACK_SIZE - 1 ); + stack[count++] = b3GetRightChild( node ); + node = b3GetLeftChild( node ); + + continue; + } + } + + if ( count == 0 ) + { + break; + } + node = stack[--count]; + } +} diff --git a/src/mesh_contact.c b/src/mesh_contact.c new file mode 100644 index 0000000..bcb74b4 --- /dev/null +++ b/src/mesh_contact.c @@ -0,0 +1,1130 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "contact.h" +#include "manifold.h" +#include "physics_world.h" +#include "qsort.h" +#include "shape.h" + +#include "box3d/types.h" + +#include + +#if B3_ENABLE_VALIDATION +static bool b3IsSorted( const int* array, int count ) +{ + for ( int i = 0; i < count - 1; ++i ) + { + if ( array[i] >= array[i + 1] ) + { + return false; + } + } + + return true; +} +#endif + +typedef struct b3TriangleQueryContext +{ + int* indices; + int capacity; + int count; +} b3TriangleQueryContext; + +static bool b3CollectTriangleIndicesCallback( b3Vec3 a, b3Vec3 b, b3Vec3 c, int triangleIndex, void* context ) +{ + B3_UNUSED( a, b, c ); + b3TriangleQueryContext* triangleContext = (b3TriangleQueryContext*)context; + if ( triangleContext->count == triangleContext->capacity ) + { + return false; + } + triangleContext->indices[triangleContext->count] = triangleIndex; + triangleContext->count += 1; + return triangleContext->count < triangleContext->capacity; +} + +static int b3QueryMeshTriangles( int* indices, int capacity, const b3Mesh* mesh, b3AABB bounds ) +{ + b3TriangleQueryContext context = { + .indices = indices, + .capacity = capacity, + .count = 0, + }; + + b3QueryMesh( mesh, bounds, b3CollectTriangleIndicesCallback, &context ); + return context.count; +} + +static int b3QueryHeightFieldTriangles( int* indices, int capacity, const b3HeightField* heightField, b3AABB bounds ) +{ + b3TriangleQueryContext context = { + .indices = indices, + .capacity = capacity, + .count = 0, + }; + + b3QueryHeightField( heightField, bounds, b3CollectTriangleIndicesCallback, &context ); + return context.count; +} + +static void b3RefreshCache( b3Contact* contact, const b3Shape* shapeA, b3Transform xfA, const b3AABB* bounds, b3Arena arena ) +{ + B3_ASSERT( shapeA->type == b3_meshShape || shapeA->type == b3_heightShape ); + + b3MeshContact* meshContact = &contact->meshContact; + + // If the dynamic body didn't move out of the cached query bounds we are done! + if ( b3AABB_Contains( meshContact->queryBounds, *bounds ) ) + { + if ( shapeA->type == b3_meshShape ) + { + for ( int i = 0; i < contact->meshContact.triangleCache.count; ++i ) + { + B3_ASSERT( 0 <= contact->meshContact.triangleCache.data[i].triangleIndex && + contact->meshContact.triangleCache.data[i].triangleIndex < shapeA->mesh.data->triangleCount ); + } + } + + return; + } + + // Enlarge to the query bounds to absorb small movement + float radius = B3_AABB_MARGIN + B3_SPECULATIVE_DISTANCE; + b3Vec3 extension = { radius, radius, radius }; + meshContact->queryBounds.lowerBound = b3Sub( bounds->lowerBound, extension ); + meshContact->queryBounds.upperBound = b3Add( bounds->upperBound, extension ); + + // Query triangles + int triangleCapacity = 256; + int* triangleIndices = (int*)b3Bump( &arena, triangleCapacity * sizeof( int ) ); + + // Bounds are in world space. Convert to the local mesh frame. + b3AABB localBounds = b3AABB_Transform( b3InvertTransform( xfA ), meshContact->queryBounds ); + int triangleCount; + if ( shapeA->type == b3_meshShape ) + { + triangleCount = b3QueryMeshTriangles( triangleIndices, triangleCapacity, &shapeA->mesh, localBounds ); + } + else + { + B3_ASSERT( shapeA->type == b3_heightShape ); + triangleCount = b3QueryHeightFieldTriangles( triangleIndices, triangleCapacity, shapeA->heightField, localBounds ); + } + + if ( triangleCount == triangleCapacity ) + { + b3Log( "WARNING: complex mesh detected, triangle buffer capacity of %d reached", triangleCapacity ); + B3_VALIDATE( false ); + } + + // Triangle indices must be sorted to match caches. + B3_VALIDATE( b3IsSorted( triangleIndices, triangleCount ) ); + + // Create new contact cache and match with old one + b3ContactCache* contactCache = (b3ContactCache*)b3Bump( &arena, triangleCount * sizeof( b3ContactCache ) ); + + int index2 = 0; + for ( int index1 = 0; index1 < triangleCount; ++index1 ) + { + contactCache[index1] = (b3ContactCache){ 0 }; + + while ( index2 < contact->meshContact.triangleCache.count && + contact->meshContact.triangleCache.data[index2].triangleIndex < triangleIndices[index1] ) + { + index2 += 1; + } + + if ( index2 < contact->meshContact.triangleCache.count && + contact->meshContact.triangleCache.data[index2].triangleIndex == triangleIndices[index1] ) + { + contactCache[index1] = contact->meshContact.triangleCache.data[index2].cache; + } + } + + // Save new cache + b3Array_Resize( contact->meshContact.triangleCache, triangleCount ); + for ( int i = 0; i < triangleCount; ++i ) + { + contact->meshContact.triangleCache.data[i] = (b3TriangleCache){ triangleIndices[i], contactCache[i] }; + + if ( shapeA->type == b3_meshShape ) + { + B3_ASSERT( 0 <= contact->meshContact.triangleCache.data[i].triangleIndex && + contact->meshContact.triangleCache.data[i].triangleIndex < shapeA->mesh.data->triangleCount ); + } + } +} + +typedef struct b3TentativeTriangle +{ + float squaredDistance; + int index; +} b3TentativeTriangle; + +#define B3_MAX_EDGE_COUNT 64 + +typedef struct b3FoundEdges +{ + uint64_t keys[B3_MAX_EDGE_COUNT]; + int count; +} b3FoundEdges; + +static inline bool b3AddEdge( b3FoundEdges* edges, int vertex1, int vertex2 ) +{ + uint64_t i1 = (uint64_t)b3MinInt( vertex1, vertex2 ); + uint64_t i2 = (uint64_t)b3MaxInt( vertex1, vertex2 ); + uint64_t key = i1 << 32 | i2; + + int count = edges->count; + for ( int i = 0; i < count; ++i ) + { + if ( edges->keys[i] == key ) + { + return false; + } + } + + if ( count == B3_MAX_EDGE_COUNT ) + { + // This will lead to a potential ghost collision + return true; + } + + edges->keys[count] = key; + edges->count += 1; + + return true; +} + +static inline bool b3FindEdge( b3FoundEdges* edges, int vertex1, int vertex2 ) +{ + uint64_t i1 = (uint64_t)b3MinInt( vertex1, vertex2 ); + uint64_t i2 = (uint64_t)b3MaxInt( vertex1, vertex2 ); + uint64_t key = i1 << 32 | i2; + + int count = edges->count; + for ( int i = 0; i < count; ++i ) + { + if ( edges->keys[i] == key ) + { + return true; + } + } + + return false; +} + +#if 0 +// Two triangles share an edge iff they share at least two vertex indices. +static inline bool b3TrianglesShareEdge( int a1, int a2, int a3, int b1, int b2, int b3 ) +{ + int matches = 0; + matches += ( a1 == b1 || a1 == b2 || a1 == b3 ); + matches += ( a2 == b1 || a2 == b2 || a2 == b3 ); + matches += ( a3 == b1 || a3 == b2 || a3 == b3 ); + return matches >= 2; +} +#endif + +#define B3_MAX_VERTEX_COUNT 64 + +typedef struct b3FoundVertices +{ + int keys[B3_MAX_VERTEX_COUNT]; + int count; +} b3FoundVertices; + +static inline bool b3AddVertex( b3FoundVertices* vertices, int vertex ) +{ + int key = vertex; + + int count = vertices->count; + for ( int i = 0; i < count; ++i ) + { + if ( vertices->keys[i] == key ) + { + return false; + } + } + + if ( count == B3_MAX_VERTEX_COUNT ) + { + // This will lead to a potential ghost collision + return true; + } + + vertices->keys[count] = key; + vertices->count += 1; + + return true; +} + +int b3CullPoints( b3Point2D* points, int count, int target ) +{ + if ( count <= 1 ) + { + return count; + } + + float tol = 0.25f * B3_LINEAR_SLOP; + float tolSqr = tol * tol; + + b3Point2D finalPoints[4]; + int count1 = count; + + // Step 1: the two points with the largest distance + float bestScore = 0.0f; + int bestIndex1 = B3_NULL_INDEX; + int bestIndex2 = B3_NULL_INDEX; + + for ( int i = 0; i < count1; ++i ) + { + b3Vec2 p1 = points[i].p; + for ( int j = i + 1; j < count1; ++j ) + { + float score = b3DistanceSquared2( p1, points[j].p ); + + // Use tolerance for welding and hysteresis + if ( score > bestScore + tolSqr ) + { + bestIndex1 = i; + bestIndex2 = j; + bestScore = score; + } + } + } + + if ( bestScore < tolSqr || target == 1 ) + { + // All points coincident. Just use first point. + return 1; + } + + finalPoints[0] = points[bestIndex1]; + finalPoints[1] = points[bestIndex2]; + + // Cull + points[bestIndex2] = points[count1 - 1]; + points[bestIndex1] = points[count1 - 2]; + count1 -= 2; + + if ( count1 == 0 || target == 2 ) + { + points[0] = finalPoints[0]; + points[1] = finalPoints[1]; + return 2; + } + + // First anchor point + b3Vec2 a = finalPoints[0].p; + + // Second anchor point + b3Vec2 b = finalPoints[1].p; + b3Vec2 ba = b3Sub2( b, a ); + // float length = b3Length2( ba ); + // float areaTol = tol * length; + + // Step 2: find the point with the maximum triangular area + bestScore = 0.0f; + int bestIndex = B3_NULL_INDEX; + float bestSignedArea = 0.0f; + for ( int i = 0; i < count1; ++i ) + { + b3Vec2 p = points[i].p; + float signedArea = b3Cross2( ba, b3Sub2( p, a ) ); + float score = b3AbsFloat( signedArea ); + + // Use the area tolerance for collinear points and hysteresis + if ( score > bestScore + tolSqr ) + { + bestSignedArea = signedArea; + bestScore = score; + bestIndex = i; + } + } + + if ( bestIndex == B3_NULL_INDEX ) + { + // All points collinear + points[0] = finalPoints[0]; + points[1] = finalPoints[1]; + return 2; + } + + // Store best point + finalPoints[2] = points[bestIndex]; + + if ( count1 == 1 || target == 3 ) + { + points[0] = finalPoints[0]; + points[1] = finalPoints[1]; + points[2] = finalPoints[2]; + return 3; + } + + // Cull + points[bestIndex] = points[count1 - 1]; + count1 -= 1; + + // Step 4: get the point that adds the most area outside the current triangle + + // Third anchor + b3Vec2 c = finalPoints[2].p; + + // Ensure CCW ordering + if ( bestSignedArea < 0.0f ) + { + B3_SWAP( b, c ); + ba = b3Sub2( b, a ); + } + + b3Vec2 cb = b3Sub2( c, b ); + b3Vec2 ac = b3Sub2( a, c ); + + bestScore = 0.0f; + bestIndex = B3_NULL_INDEX; + for ( int i = 0; i < count1; ++i ) + { + b3Vec2 p = points[i].p; + float u1 = b3Cross2( b3Sub2( p, a ), ba ); + float u2 = b3Cross2( b3Sub2( p, b ), cb ); + float u3 = b3Cross2( b3Sub2( p, c ), ac ); + float score = b3MaxFloat( u1, b3MaxFloat( u2, u3 ) ); + + // Use the area tolerance for collinear points and hysteresis + if ( score > bestScore + tolSqr ) + { + bestScore = score; + bestIndex = i; + } + } + + if ( bestIndex == B3_NULL_INDEX ) + { + // No additional area + points[0] = finalPoints[0]; + points[1] = finalPoints[1]; + points[2] = finalPoints[2]; + return 3; + } + + // Store best point + finalPoints[3] = points[bestIndex]; + + // Full quad + points[0] = finalPoints[0]; + points[1] = finalPoints[1]; + points[2] = finalPoints[2]; + points[3] = finalPoints[3]; + return 4; +} + +static int b3ReduceCluster( b3LocalManifoldPoint* points, int count1, b3Vec3 normal, b3Arena arena ) +{ + int targetCount = 1; + if ( count1 <= targetCount ) + { + return count1; + } + + b3Point2D* pts = (b3Point2D*)b3Bump( &arena, count1 * sizeof( b3Point2D ) ); + b3Vec3 u = b3Perp( normal ); + b3Vec3 v = b3Cross( normal, u ); + b3Vec3 origin = points[0].point; + + for ( int i = 0; i < count1; ++i ) + { + pts[i].originalIndex = (int16_t)i; + pts[i].separation = 0.0f; + + b3Vec3 d = b3Sub( points[i].point, origin ); + pts[i].p = (b3Vec2){ b3Dot( d, u ), b3Dot( d, v ) }; + pts[i].persisted = false; + } + + int count3 = b3CullPoints( pts, count1, 4 ); + + b3LocalManifoldPoint* finalPoints = (b3LocalManifoldPoint*)b3Bump( &arena, count3 * sizeof( b3LocalManifoldPoint ) ); + for ( int i = 0; i < count3; ++i ) + { + int index = pts[i].originalIndex; + B3_ASSERT( 0 <= index && index < count1 ); + finalPoints[i] = points[index]; + } + + memcpy( points, finalPoints, count3 * sizeof( b3LocalManifoldPoint ) ); + return count3; +} + +typedef struct b3Cluster +{ + b3Vec3 manifoldNormal; + b3Vec3 triangleNormal; + b3LocalManifoldPoint* points; + int pointCapacity; + int pointCount; +} b3Cluster; + +bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact, const b3Shape* shapeA, const int* materialMap, + b3Transform xfA, const b3Shape* shapeB, b3Transform xfB, bool isFast, b3Arena arena ) +{ + B3_ASSERT( shapeA->type == b3_meshShape || shapeA->type == b3_heightShape ); + B3_UNUSED( workerIndex ); + B3_UNUSED( isFast ); + B3_UNUSED( materialMap ); + + b3TaskContext* context = b3Array_Get( world->taskContexts, workerIndex ); + + // todo test using the shape local aabb + b3RefreshCache( contact, shapeA, xfA, &shapeB->aabb, arena ); + + // Collide with triangles and build manifolds + b3MeshContact* meshContact = &contact->meshContact; + int triangleCount = meshContact->triangleCache.count; + + b3LocalManifold** acceptedManifolds = (b3LocalManifold**)b3Bump( &arena, triangleCount * sizeof( b3LocalManifold* ) ); + int acceptedManifoldCount = 0; + b3LocalManifold** tentativeManifolds = (b3LocalManifold**)b3Bump( &arena, triangleCount * sizeof( b3LocalManifold* ) ); + int tentativeManifoldCount = 0; + b3TentativeTriangle* tentativeTriangles = + (b3TentativeTriangle*)b3Bump( &arena, triangleCount * sizeof( b3TentativeTriangle ) ); + int tentativeTriangleCount = 0; + + b3FoundEdges foundEdges; + b3FoundVertices foundVertices; + foundEdges.count = 0; + foundVertices.count = 0; + + // This transform converts from mesh frame into the shapeB frame + b3Transform transformAtoB = b3InvMulTransforms( xfB, xfA ); + b3Matrix3 relativeMatrix = b3MakeMatrixFromQuat( transformAtoB.q ); + float linearSlop = B3_LINEAR_SLOP; + + int pointBufferCapacity = 256; + b3LocalManifoldPoint* pointBuffer = + (b3LocalManifoldPoint*)b3Bump( &arena, pointBufferCapacity * sizeof( b3LocalManifoldPoint ) ); + int totalPointCount = 0; + + b3LocalManifold* manifoldBuffer = (b3LocalManifold*)b3Bump( &arena, triangleCount * sizeof( b3LocalManifold ) ); + int manifoldCount = 0; + + b3TriangleCache* triangleCaches = meshContact->triangleCache.data; + + for ( int index = 0; index < triangleCount && totalPointCount + 3 < pointBufferCapacity; ++index ) + { + int triangleIndex = triangleCaches[index].triangleIndex; + + b3Triangle triangle; + if ( shapeA->type == b3_meshShape ) + { + triangle = b3GetMeshTriangle( &shapeA->mesh, triangleIndex ); + } + else + { + B3_ASSERT( shapeA->type == b3_heightShape ); + triangle = b3GetHeightFieldTriangle( shapeA->heightField, triangleIndex ); + } + + // Transform triangle into the shape frame + b3Vec3 vertices[3]; + vertices[0] = b3Add( b3MulMV( relativeMatrix, triangle.vertices[0] ), transformAtoB.p ); + vertices[1] = b3Add( b3MulMV( relativeMatrix, triangle.vertices[1] ), transformAtoB.p ); + vertices[2] = b3Add( b3MulMV( relativeMatrix, triangle.vertices[2] ), transformAtoB.p ); + + b3ContactCache* cache = &triangleCaches[index].cache; + int pointCapacity = pointBufferCapacity - totalPointCount; + b3LocalManifold* manifold = manifoldBuffer + manifoldCount; + manifold->points = pointBuffer + totalPointCount; + manifold->pointCount = 0; + manifold->triangleFlags = triangle.flags; + manifold->feature = b3_featureNone; + + switch ( shapeB->type ) + { + case b3_capsuleShape: + b3CollideCapsuleAndTriangle( manifold, pointCapacity, &shapeB->capsule, vertices, &cache->simplexCache ); + break; + + case b3_hullShape: + // Cached edge contact is dangerous at high speed because the hull can rotate around the edge and tunnel + // through the triangle. + if ( isFast && cache->satCache.type == b3_edgePairAxis ) + { + cache->satCache = (b3SATCache){ 0 }; + } + + b3CollideHullAndTriangle( manifold, pointCapacity, shapeB->hull, vertices, triangle.flags, &cache->satCache ); + context->satCallCount += 1; + context->satCacheHitCount += cache->satCache.hit; + break; + + case b3_sphereShape: + b3CollideSphereAndTriangle( manifold, pointCapacity, &shapeB->sphere, vertices ); + break; + + default: + B3_ASSERT( false ); + return false; + } + + int manifoldPointCount = manifold->pointCount; + + if ( manifoldPointCount > 0 ) + { + B3_ASSERT( manifold->feature != b3_featureNone ); + + manifoldCount += 1; + totalPointCount += manifoldPointCount; + manifold->triangleIndex = triangleIndex; + manifold->trianglePlane = b3MakePlaneFromPoints( vertices[0], vertices[1], vertices[2] ); + manifold->i1 = triangle.i1; + manifold->i2 = triangle.i2; + manifold->i3 = triangle.i3; + + if ( manifold->feature == b3_featureTriangleFace || B3_FORCE_GHOST_COLLISIONS ) + { + (void)b3AddEdge( &foundEdges, triangle.i1, triangle.i2 ); + (void)b3AddEdge( &foundEdges, triangle.i2, triangle.i3 ); + (void)b3AddEdge( &foundEdges, triangle.i3, triangle.i1 ); + (void)b3AddVertex( &foundVertices, triangle.i1 ); + (void)b3AddVertex( &foundVertices, triangle.i2 ); + (void)b3AddVertex( &foundVertices, triangle.i3 ); + + acceptedManifolds[acceptedManifoldCount++] = manifold; + } + else if ( manifold->feature == b3_featureHullFace ) + { + float cosNormalAngle = b3Dot( manifold->trianglePlane.normal, manifold->normal ); + if ( cosNormalAngle > 0.5f ) + { + (void)b3AddEdge( &foundEdges, triangle.i1, triangle.i2 ); + (void)b3AddEdge( &foundEdges, triangle.i2, triangle.i3 ); + (void)b3AddEdge( &foundEdges, triangle.i3, triangle.i1 ); + (void)b3AddVertex( &foundVertices, triangle.i1 ); + (void)b3AddVertex( &foundVertices, triangle.i2 ); + (void)b3AddVertex( &foundVertices, triangle.i3 ); + + acceptedManifolds[acceptedManifoldCount++] = manifold; + } + else + { + float minSeparation = manifold->points[0].separation; + for ( int i = 1; i < manifoldPointCount; ++i ) + { + minSeparation = b3MinFloat( minSeparation, manifold->points[i].separation ); + } + + if ( minSeparation < -2.0f * linearSlop ) + { + // Deep overlap + (void)b3AddEdge( &foundEdges, triangle.i1, triangle.i2 ); + (void)b3AddEdge( &foundEdges, triangle.i2, triangle.i3 ); + (void)b3AddEdge( &foundEdges, triangle.i3, triangle.i1 ); + (void)b3AddVertex( &foundVertices, triangle.i1 ); + (void)b3AddVertex( &foundVertices, triangle.i2 ); + (void)b3AddVertex( &foundVertices, triangle.i3 ); + acceptedManifolds[acceptedManifoldCount++] = manifold; + } + else + { + b3TentativeTriangle tentativeTriangle = { .squaredDistance = manifold->squaredDistance, + .index = tentativeManifoldCount }; + tentativeTriangles[tentativeTriangleCount++] = tentativeTriangle; + tentativeManifolds[tentativeManifoldCount++] = manifold; + } + } + } + else + { + b3TentativeTriangle tentativeTriangle = { .squaredDistance = manifold->squaredDistance, + .index = tentativeManifoldCount }; + tentativeTriangles[tentativeTriangleCount++] = tentativeTriangle; + tentativeManifolds[tentativeManifoldCount++] = manifold; + } + } + } + + B3_ASSERT( acceptedManifoldCount <= triangleCount ); + B3_ASSERT( tentativeManifoldCount <= triangleCount ); + B3_ASSERT( tentativeTriangleCount <= triangleCount ); + + if ( shapeB->type == b3_sphereShape ) + { + // Sort triangles so the closest triangles are processed first + { +#define LESS( i, j ) tentativeTriangles[(int)i].squaredDistance < tentativeTriangles[(int)j].squaredDistance +#define SWAP( i, j ) \ + do \ + { \ + b3TentativeTriangle tmp = tentativeTriangles[(int)i]; \ + tentativeTriangles[(int)i] = tentativeTriangles[(int)j]; \ + tentativeTriangles[(int)j] = tmp; \ + } \ + while ( 0 ) + QSORT( tentativeTriangleCount, LESS, SWAP ); +#undef LESS +#undef SWAP + } + + // Add tentative manifolds in sorted order. Avoid adding manifolds that generate ghost collisions. + for ( int i = 0; i < tentativeTriangleCount; ++i ) + { + b3LocalManifold* m = tentativeManifolds[tentativeTriangles[i].index]; + + bool addedEdge1 = b3AddEdge( &foundEdges, m->i1, m->i2 ); + bool addedEdge2 = b3AddEdge( &foundEdges, m->i2, m->i3 ); + bool addedEdge3 = b3AddEdge( &foundEdges, m->i3, m->i1 ); + bool addedVertex1 = b3AddVertex( &foundVertices, m->i1 ); + bool addedVertex2 = b3AddVertex( &foundVertices, m->i2 ); + bool addedVertex3 = b3AddVertex( &foundVertices, m->i3 ); + + b3TriangleFeature feature = m->feature; + bool shouldCollide = false; + switch ( feature ) + { + case b3_featureNone: + case b3_featureTriangleFace: + B3_ASSERT( false ); + break; + + case b3_featureEdge1: + shouldCollide = addedEdge1; + break; + + case b3_featureEdge2: + shouldCollide = addedEdge2; + break; + + case b3_featureEdge3: + shouldCollide = addedEdge3; + break; + + case b3_featureVertex1: + shouldCollide = addedVertex1; + break; + + case b3_featureVertex2: + shouldCollide = addedVertex2; + break; + + case b3_featureVertex3: + shouldCollide = addedVertex3; + break; + + default: + B3_ASSERT( false ); + break; + } + + if ( shouldCollide == true ) + { + acceptedManifolds[acceptedManifoldCount++] = m; + } + } + } + else + { + // Problem: hull can tunnel if time of impact is at concave edge + // Example: flat box sliding down a ramp to a flat bottom + // Solution: only ignore flat edges + for ( int i = 0; i < tentativeManifoldCount; ++i ) + { + b3LocalManifold* m = tentativeManifolds[i]; + int triangleFlags = m->triangleFlags; + + if ( ( triangleFlags & b3_allFlatEdges ) == b3_allFlatEdges ) + { + continue; + } + + if ( ( triangleFlags & b3_flatEdge1 ) == b3_flatEdge1 ) + { + if ( b3FindEdge( &foundEdges, m->i1, m->i2 ) ) + { + continue; + } + } + + if ( ( triangleFlags & b3_flatEdge2 ) == b3_flatEdge2 ) + { + if ( b3FindEdge( &foundEdges, m->i2, m->i3 ) ) + { + continue; + } + } + + if ( ( triangleFlags & b3_flatEdge3 ) == b3_flatEdge3 ) + { + if ( b3FindEdge( &foundEdges, m->i3, m->i1 ) ) + { + continue; + } + } + + acceptedManifolds[acceptedManifoldCount++] = m; + } + } + + B3_ASSERT( acceptedManifoldCount <= triangleCount ); + + if ( acceptedManifoldCount == 0 ) + { + if ( contact->manifoldCount > 0 ) + { + b3FreeManifolds( world, contact->manifolds, contact->manifoldCount ); + contact->manifolds = NULL; + contact->manifoldCount = 0; + } + return false; + } + + // todo this should push apart shapes after a time of impact event + // todo consider doing this based on speed + // todo this must be constant or varied smoothly or there will be jitter + // In the past I've called this `polygon skin`, but PhysX and Unreal call it `rest offset` which + // seems appropriate in this case. + float restOffset = linearSlop; + + b3Cluster* clusters = (b3Cluster*)b3Bump( &arena, acceptedManifoldCount * sizeof( b3Cluster ) ); + int* clusterMemberships = (int*)b3Bump( &arena, acceptedManifoldCount * sizeof( int ) ); + + int clusterCount = 0; + // Cluster tolerance is tighter than the warm starting manifold matching tolerance. These + // serve different purposes. + const float clusterThreshold = 0.996f; + int pointCount2 = 0; + for ( int i = 0; i < acceptedManifoldCount; ++i ) + { + clusterMemberships[i] = B3_NULL_INDEX; + + const b3LocalManifold* manifold = acceptedManifolds[i]; + pointCount2 += manifold->pointCount; + + // Cluster based on the triangle normal and contact normal. + // The first cluster found is accepted because the tolerance is tight. + // todo consider requiring the triangles to be connect by an edge. + // todo consider looking for the best cluster instead of the first one within tolerance + // This bool is here to allow quick testing with and without clustering. + bool allowClustering = true; + b3Vec3 manifoldNormal = manifold->normal; + b3Vec3 triangleNormal = manifold->trianglePlane.normal; + int clusterIndex = B3_NULL_INDEX; + for ( int j = 0; j < clusterCount && allowClustering; ++j ) + { + float cosManifoldAngle = b3Dot( clusters[j].manifoldNormal, manifoldNormal ); + float cosTriangleAngle = b3Dot( clusters[j].triangleNormal, triangleNormal ); + if ( cosManifoldAngle <= clusterThreshold || cosTriangleAngle <= clusterThreshold ) + { + continue; + } + +#if 0 + // todo there could be later triangles that create the connection + // then failure to cluster breaks greedy impulse warm starting + bool edgeConnected = false; + + for ( int k = 0; k < i; ++k ) + { + if ( clusterMemberships[k] != j ) + { + continue; + } + + const b3LocalManifold* other = acceptedManifolds[k]; + if ( b3TrianglesShareEdge( manifold->i1, manifold->i2, manifold->i3, other->i1, other->i2, other->i3 ) ) + { + edgeConnected = true; + break; + } + } + + if ( edgeConnected ) + { + clusterIndex = j; + break; + } +#else + + // Found a cluster + clusterIndex = j; + break; +#endif + } + + if ( clusterIndex != B3_NULL_INDEX ) + { + clusterMemberships[i] = clusterIndex; + clusters[clusterIndex].pointCapacity += manifold->pointCount; + } + else + { + clusters[clusterCount].manifoldNormal = manifoldNormal; + clusters[clusterCount].triangleNormal = triangleNormal; + clusters[clusterCount].pointCapacity = manifold->pointCount; + clusterMemberships[i] = clusterCount; + clusterCount += 1; + } + } + + if ( pointCount2 == 0 ) + { + return false; + } + + // Setup clusters + b3LocalManifoldPoint* clusterPoints = (b3LocalManifoldPoint*)b3Bump( &arena, pointCount2 * sizeof( b3LocalManifoldPoint ) ); + int pointOffset = 0; + + for ( int i = 0; i < clusterCount; ++i ) + { + b3Cluster* cluster = clusters + i; + cluster->points = clusterPoints + pointOffset; + cluster->pointCount = 0; + pointOffset += cluster->pointCapacity; + } + + // Populate clusters + for ( int i = 0; i < acceptedManifoldCount; ++i ) + { + int clusterIndex = clusterMemberships[i]; + if ( clusterIndex == B3_NULL_INDEX ) + { + continue; + } + + B3_ASSERT( 0 <= clusterIndex && clusterIndex < clusterCount ); + + b3LocalManifold* am = acceptedManifolds[i]; + b3Cluster* cm = clusters + clusterIndex; + for ( int j = 0; j < am->pointCount; ++j ) + { + B3_ASSERT( cm->pointCount < cm->pointCapacity ); + b3LocalManifoldPoint* ap = am->points + j; + b3LocalManifoldPoint* cp = cm->points + cm->pointCount; + + // The contact normal may be different than the cluster normal (triangle normal) + cp->normal = am->normal; + cp->triangleIndex = am->triangleIndex; + cp->point = ap->point; + cp->separation = ap->separation; + cp->pair = ap->pair; + cm->pointCount += 1; + } + } + + // Simplify clusters + for ( int i = 0; i < clusterCount; ++i ) + { + b3Cluster* cm = clusters + i; + B3_ASSERT( cm->pointCount == cm->pointCapacity ); + int reducedCount = b3ReduceCluster( cm->points, cm->pointCount, cm->triangleNormal, arena ); + cm->pointCount = reducedCount; + } + + // Make a temporary copy of previous manifolds + int oldManifoldCount = contact->manifoldCount; + b3Manifold* oldManifolds = NULL; + if ( oldManifoldCount > 0 ) + { + oldManifolds = (b3Manifold*)b3Bump( &arena, oldManifoldCount * sizeof( b3Manifold ) ); + memcpy( oldManifolds, contact->manifolds, oldManifoldCount * sizeof( b3Manifold ) ); + } + + // Resize manifolds if needed + if ( oldManifoldCount != clusterCount ) + { + b3FreeManifolds( world, contact->manifolds, contact->manifoldCount ); + contact->manifolds = b3AllocateManifolds( world, clusterCount ); + contact->manifoldCount = (uint16_t)clusterCount; + } + else + { + // Mem zero manifolds + memset( contact->manifolds, 0, contact->manifoldCount * sizeof( b3Manifold ) ); + } + + bool* consumed = NULL; + if ( oldManifoldCount > 0 ) + { + consumed = (bool*)b3Bump( &arena, oldManifoldCount * sizeof( bool ) ); + memset( consumed, 0, oldManifoldCount * sizeof( bool ) ); + } + + b3Matrix3 matrixB = b3MakeMatrixFromQuat( xfB.q ); + b3Vec3 offsetA = b3Sub( xfB.p, xfA.p ); + + const float normalMatchTolerance = 0.995f; + for ( int i = 0; i < clusterCount; ++i ) + { + b3Cluster* cm = clusters + i; + int pointCount = cm->pointCount; + B3_ASSERT( 0 < pointCount && pointCount <= B3_MAX_MANIFOLD_POINTS ); + + b3Manifold* manifold = contact->manifolds + i; + manifold->pointCount = pointCount; + manifold->normal = b3MulMV( matrixB, cm->manifoldNormal ); + + b3Vec3 clusterNormal = b3MulMV( matrixB, cm->manifoldNormal ); + float bestDot = normalMatchTolerance; + int bestIndex = B3_NULL_INDEX; + + for ( int j = 0; j < oldManifoldCount; ++j ) + { + if ( consumed[j] == true ) + { + continue; + } + + float dot = b3Dot( oldManifolds[j].normal, clusterNormal ); + if ( dot > bestDot ) + { + bestIndex = j; + bestDot = dot; + } + } + + b3Manifold* matchedManifold = NULL; + if ( bestIndex != B3_NULL_INDEX ) + { + matchedManifold = oldManifolds + bestIndex; + manifold->frictionImpulse = matchedManifold->frictionImpulse; + manifold->rollingImpulse = matchedManifold->rollingImpulse; + manifold->twistImpulse = matchedManifold->twistImpulse; + consumed[bestIndex] = true; + } + + for ( int j = 0; j < pointCount; ++j ) + { + const b3LocalManifoldPoint* source = cm->points + j; + b3ManifoldPoint* target = manifold->points + j; + + // Contact points are computed in frame B + target->anchorB = b3MulMV( matrixB, source->point ); + target->anchorA = b3Add( target->anchorB, offsetA ); + target->separation = source->separation - restOffset; + target->featureId = b3MakeFeatureId( source->pair ); + target->triangleIndex = source->triangleIndex; + + // Preserve normal impulse if possible + if ( matchedManifold != NULL ) + { + int oldPointCount = matchedManifold->pointCount; + for ( int k = 0; k < oldPointCount; ++k ) + { + b3ManifoldPoint* oldPt = matchedManifold->points + k; + + if ( target->featureId == oldPt->featureId && target->triangleIndex == oldPt->triangleIndex ) + { + target->normalImpulse = oldPt->normalImpulse; + target->persisted = true; + + // claimed + oldPt->triangleIndex = B3_NULL_INDEX; + break; + } + } + } + } + } + + const b3SurfaceMaterial* materialB = shapeB->materials + 0; + b3Vec3 tangentVelocityA = b3Vec3_zero; + + // Update friction and restitution if the mesh has per triangle material + if ( shapeA->materialCount > 0 ) + { + float friction = 0.0f; + float restitution = 0.0f; + float sampleCount = 0.0f; + + const uint8_t* materialIndices; + if ( shapeA->type == b3_meshShape ) + { + materialIndices = b3GetMeshMaterialIndices( shapeA->mesh.data ); + } + else + { + materialIndices = shapeA->heightField->materialIndices; + } + + for ( int i = 0; i < clusterCount; ++i ) + { + b3Manifold* manifold = contact->manifolds + i; + int pointCount = manifold->pointCount; + for ( int j = 0; j < pointCount; ++j ) + { + int triangleIndex = manifold->points[j].triangleIndex; + int materialIndex; + if ( shapeA->type == b3_meshShape ) + { + materialIndex = materialIndices[triangleIndex]; + + if ( materialMap != NULL ) + { + materialIndex = materialMap[materialIndex]; + } + } + else + { + materialIndex = materialIndices[triangleIndex >> 1]; + } + + materialIndex = b3ClampInt( materialIndex, 0, shapeA->materialCount - 1 ); + b3SurfaceMaterial material = shapeA->materials[materialIndex]; + friction += world->frictionCallback( material.friction, material.userMaterialId, materialB->friction, + materialB->userMaterialId ); + restitution += world->restitutionCallback( material.restitution, material.userMaterialId, materialB->restitution, + materialB->userMaterialId ); + + tangentVelocityA = b3Add( tangentVelocityA, material.tangentVelocity ); + + sampleCount += 1.0f; + } + } + + if ( sampleCount > 0.0f ) + { + float invCount = 1.0f / sampleCount; + contact->friction = invCount * friction; + contact->restitution = invCount * restitution; + tangentVelocityA = b3MulSV( invCount, tangentVelocityA ); + } + + B3_ASSERT( b3IsValidFloat( contact->friction ) && contact->friction >= 0.0f ); + B3_ASSERT( b3IsValidFloat( contact->restitution ) && contact->restitution >= 0.0f ); + } + else + { + // Keep these updated in case the values on the shapes are modified + contact->friction = world->frictionCallback( shapeA->materials[0].friction, shapeA->materials[0].userMaterialId, + materialB->friction, materialB->userMaterialId ); + contact->restitution = world->restitutionCallback( shapeA->materials[0].restitution, shapeA->materials[0].userMaterialId, + materialB->restitution, materialB->userMaterialId ); + tangentVelocityA = shapeA->materials[0].tangentVelocity; + } + + tangentVelocityA = b3RotateVector( xfA.q, tangentVelocityA ); + + float radiusB = 0.0f; + if ( shapeB->type == b3_sphereShape ) + { + radiusB = shapeB->sphere.radius; + } + else if ( shapeB->type == b3_capsuleShape ) + { + radiusB = shapeB->capsule.radius; + } + else if ( shapeB->type == b3_hullShape ) + { + radiusB = shapeB->hull->innerRadius; + } + + contact->rollingResistance = shapeB->materials[0].rollingResistance * radiusB; + + b3Vec3 tangentVelocityB = b3RotateVector( xfB.q, materialB->tangentVelocity ); + contact->tangentVelocity = b3Sub( tangentVelocityA, tangentVelocityB ); + return true; +} diff --git a/src/motor_joint.c b/src/motor_joint.c new file mode 100644 index 0000000..1b4b584 --- /dev/null +++ b/src/motor_joint.c @@ -0,0 +1,437 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "body.h" +#include "core.h" +#include "joint.h" +#include "math_internal.h" +#include "physics_world.h" +#include "solver.h" +#include "solver_set.h" + +// needed for dll export +#include "box3d/box3d.h" + +void b3MotorJoint_SetLinearVelocity( b3JointId jointId, b3Vec3 velocity ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + joint->motorJoint.linearVelocity = velocity; +} + +b3Vec3 b3MotorJoint_GetLinearVelocity( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + return joint->motorJoint.linearVelocity; +} + +void b3MotorJoint_SetAngularVelocity( b3JointId jointId, b3Vec3 velocity ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + joint->motorJoint.angularVelocity = velocity; +} + +b3Vec3 b3MotorJoint_GetAngularVelocity( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + return joint->motorJoint.angularVelocity; +} + +void b3MotorJoint_SetMaxVelocityTorque( b3JointId jointId, float maxTorque ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + joint->motorJoint.maxVelocityTorque = maxTorque; +} + +float b3MotorJoint_GetMaxVelocityTorque( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + return joint->motorJoint.maxVelocityTorque; +} + +void b3MotorJoint_SetMaxVelocityForce( b3JointId jointId, float maxForce ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + joint->motorJoint.maxVelocityForce = maxForce; +} + +float b3MotorJoint_GetMaxVelocityForce( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + return joint->motorJoint.maxVelocityForce; +} + +void b3MotorJoint_SetLinearHertz( b3JointId jointId, float hertz ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + joint->motorJoint.linearHertz = hertz; +} + +float b3MotorJoint_GetLinearHertz( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + return joint->motorJoint.linearHertz; +} + +void b3MotorJoint_SetLinearDampingRatio( b3JointId jointId, float damping ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + joint->motorJoint.linearDampingRatio = damping; +} + +float b3MotorJoint_GetLinearDampingRatio( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + return joint->motorJoint.linearDampingRatio; +} + +void b3MotorJoint_SetAngularHertz( b3JointId jointId, float hertz ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + joint->motorJoint.angularHertz = hertz; +} + +float b3MotorJoint_GetAngularHertz( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + return joint->motorJoint.angularHertz; +} + +void b3MotorJoint_SetAngularDampingRatio( b3JointId jointId, float damping ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + joint->motorJoint.angularDampingRatio = damping; +} + +float b3MotorJoint_GetAngularDampingRatio( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + return joint->motorJoint.angularDampingRatio; +} + +void b3MotorJoint_SetMaxSpringForce( b3JointId jointId, float maxForce ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + joint->motorJoint.maxSpringForce = b3MaxFloat( 0.0f, maxForce ); +} + +float b3MotorJoint_GetMaxSpringForce( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + return joint->motorJoint.maxSpringForce; +} + +void b3MotorJoint_SetMaxSpringTorque( b3JointId jointId, float maxTorque ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + joint->motorJoint.maxSpringTorque = b3MaxFloat( 0.0f, maxTorque ); +} + +float b3MotorJoint_GetMaxSpringTorque( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint ); + return joint->motorJoint.maxSpringTorque; +} + +b3Vec3 b3GetMotorJointForce( b3World* world, b3JointSim* base ) +{ + b3Vec3 force = b3MulSV( world->inv_h, b3Add( base->motorJoint.linearVelocityImpulse, base->motorJoint.linearSpringImpulse ) ); + return force; +} + +b3Vec3 b3GetMotorJointTorque( b3World* world, b3JointSim* base ) +{ + return b3MulSV( world->inv_h, b3Add( 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 b3PrepareMotorJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_motorJoint ); + + // chase body id to the solver set where the body lives + int idA = base->bodyIdA; + int idB = base->bodyIdB; + + b3World* world = context->world; + + b3Body* bodyA = b3Array_Get( world->bodies, idA ); + b3Body* bodyB = b3Array_Get( world->bodies, idB ); + + B3_ASSERT( bodyA->setIndex == b3_awakeSet || bodyB->setIndex == b3_awakeSet ); + + b3SolverSet* setA = b3Array_Get( world->solverSets, bodyA->setIndex ); + b3SolverSet* setB = b3Array_Get( world->solverSets, bodyB->setIndex ); + + int localIndexA = bodyA->localIndex; + int localIndexB = bodyB->localIndex; + + b3BodySim* bodySimA = b3Array_Get( setA->bodySims, localIndexA ); + b3BodySim* bodySimB = b3Array_Get( setB->bodySims, localIndexB ); + + base->invMassA = bodySimA->invMass; + base->invMassB = bodySimB->invMass; + base->invIA = bodySimA->invInertiaWorld; + base->invIB = bodySimB->invInertiaWorld; + + b3Matrix3 invInertiaSum = b3AddMM( base->invIA, base->invIB ); + base->fixedRotation = b3Det( invInertiaSum ) < 1000.0f * FLT_MIN; + + b3MotorJoint* joint = &base->motorJoint; + joint->indexA = bodyA->setIndex == b3_awakeSet ? localIndexA : B3_NULL_INDEX; + joint->indexB = bodyB->setIndex == b3_awakeSet ? localIndexB : B3_NULL_INDEX; + + // Compute joint anchor frames with world space rotation, relative to center of mass + joint->frameA.q = b3MulQuat( bodySimA->transform.q, base->localFrameA.q ); + joint->frameA.p = b3RotateVector( bodySimA->transform.q, b3Sub( base->localFrameA.p, bodySimA->localCenter ) ); + joint->frameB.q = b3MulQuat( bodySimB->transform.q, base->localFrameB.q ); + joint->frameB.p = b3RotateVector( bodySimB->transform.q, b3Sub( base->localFrameB.p, bodySimB->localCenter ) ); + + // Compute the initial center delta. Incremental position updates are relative to this. + joint->deltaCenter = b3Sub( bodySimB->center, bodySimA->center ); + + joint->linearSpring = b3MakeSoft( joint->linearHertz, joint->linearDampingRatio, context->h ); + joint->angularSpring = b3MakeSoft( joint->angularHertz, joint->angularDampingRatio, context->h ); + + joint->angularMass = b3InvertMatrix( invInertiaSum ); + + if ( context->enableWarmStarting == false ) + { + joint->linearVelocityImpulse = b3Vec3_zero; + joint->angularVelocityImpulse = b3Vec3_zero; + joint->linearSpringImpulse = b3Vec3_zero; + joint->angularSpringImpulse = b3Vec3_zero; + } +} + +void b3WarmStartMotorJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_motorJoint ); + + float mA = base->invMassA; + float mB = base->invMassB; + b3Matrix3 iA = base->invIA; + b3Matrix3 iB = base->invIB; + + b3MotorJoint* joint = &base->motorJoint; + + // dummy state for static bodies + b3BodyState dummyState = b3_identityBodyState; + + b3BodyState* stateA = joint->indexA == B3_NULL_INDEX ? &dummyState : context->states + joint->indexA; + b3BodyState* stateB = joint->indexB == B3_NULL_INDEX ? &dummyState : context->states + joint->indexB; + + b3Vec3 rA = b3RotateVector( stateA->deltaRotation, joint->frameA.p ); + b3Vec3 rB = b3RotateVector( stateB->deltaRotation, joint->frameB.p ); + + b3Vec3 linearImpulse = b3Add( joint->linearVelocityImpulse, joint->linearSpringImpulse ); + b3Vec3 angularImpulse = b3Add( joint->angularVelocityImpulse, joint->angularSpringImpulse ); + + stateA->linearVelocity = b3MulSub( stateA->linearVelocity, mA, linearImpulse ); + stateA->angularVelocity = b3Sub( stateA->angularVelocity, b3MulMV( iA, b3Add( b3Cross( rA, linearImpulse ), angularImpulse ) ) ); + stateB->linearVelocity = b3MulAdd( stateB->linearVelocity, mB, linearImpulse ); + stateB->angularVelocity = b3Add( stateB->angularVelocity, b3MulMV( iB, b3Add( b3Cross( rB, linearImpulse ), angularImpulse ) ) ); +} + +void b3SolveMotorJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_motorJoint ); + + float mA = base->invMassA; + float mB = base->invMassB; + b3Matrix3 iA = base->invIA; + b3Matrix3 iB = base->invIB; + + // dummy state for static bodies + b3BodyState dummyState = b3_identityBodyState; + + b3MotorJoint* joint = &base->motorJoint; + b3BodyState* stateA = joint->indexA == B3_NULL_INDEX ? &dummyState : context->states + joint->indexA; + b3BodyState* stateB = joint->indexB == B3_NULL_INDEX ? &dummyState : context->states + joint->indexB; + + b3Vec3 vA = stateA->linearVelocity; + b3Vec3 wA = stateA->angularVelocity; + b3Vec3 vB = stateB->linearVelocity; + b3Vec3 wB = stateB->angularVelocity; + + b3Quat quatA = b3MulQuat( stateA->deltaRotation, joint->frameA.q ); + b3Quat quatB = b3MulQuat( stateB->deltaRotation, joint->frameB.q ); + + if ( b3DotQuat( quatA, quatB ) < 0.0f ) + { + // this keeps the rotation angle in the range [-pi, pi] + quatB = b3NegateQuat( quatB ); + } + + b3Quat relQ = b3InvMulQuat( quatA, quatB ); + + // angular spring + if ( joint->maxSpringTorque > 0.0f && joint->angularHertz > 0.0f ) + { + b3Quat targetQuat = b3Quat_identity; + b3Vec3 deltaRotation = b3DeltaQuatToRotation( relQ, targetQuat ); + b3Vec3 c = b3Neg( b3RotateVector( quatA, deltaRotation ) ); + + b3Vec3 bias = b3MulSV( joint->angularSpring.biasRate, c ); + float massScale = joint->angularSpring.massScale; + float impulseScale = joint->angularSpring.impulseScale; + + b3Vec3 cdot = b3Sub( wB, wA ); + + float maxImpulse = context->h * joint->maxSpringTorque; + b3Vec3 oldImpulse = joint->angularSpringImpulse; + b3Vec3 impulse = b3MulSub( b3MulSV( -massScale, b3MulMV( joint->angularMass, b3Add( cdot, bias ) ) ), impulseScale, oldImpulse ); + joint->angularSpringImpulse = b3Add( oldImpulse, impulse ); + if ( b3LengthSquared( joint->angularSpringImpulse ) > maxImpulse * maxImpulse ) + { + joint->angularSpringImpulse = b3MulSV( maxImpulse, b3Normalize( joint->angularSpringImpulse ) ); + } + impulse = b3Sub( joint->angularSpringImpulse, oldImpulse ); + + wA = b3Sub( wA, b3MulMV( iA, impulse ) ); + wB = b3Add( wB, b3MulMV( iB, impulse ) ); + } + + // angular velocity + if ( joint->maxVelocityTorque > 0.0 ) + { + b3Vec3 cdot = b3Sub( b3Sub( wB, wA ), joint->angularVelocity ); + b3Vec3 impulse = b3Neg( b3MulMV( joint->angularMass, cdot ) ); + + float maxImpulse = context->h * joint->maxVelocityTorque; + b3Vec3 oldImpulse = joint->angularVelocityImpulse; + joint->angularVelocityImpulse = b3Add( oldImpulse, impulse ); + if ( b3LengthSquared( joint->angularVelocityImpulse ) > maxImpulse * maxImpulse ) + { + joint->angularVelocityImpulse = b3MulSV( maxImpulse, b3Normalize( joint->angularVelocityImpulse ) ); + } + impulse = b3Sub( joint->angularVelocityImpulse, oldImpulse ); + + wA = b3Sub( wA, b3MulMV( iA, impulse ) ); + wB = b3Add( wB, b3MulMV( iB, impulse ) ); + } + + b3Vec3 rA = b3RotateVector( stateA->deltaRotation, joint->frameA.p ); + b3Vec3 rB = b3RotateVector( stateB->deltaRotation, joint->frameB.p ); + + // linear spring + if ( joint->maxSpringForce > 0.0f && joint->linearHertz > 0.0f ) + { + b3Vec3 dcA = stateA->deltaPosition; + b3Vec3 dcB = stateB->deltaPosition; + b3Vec3 c = b3Add( b3Add( b3Sub( dcB, dcA ), b3Sub( rB, rA ) ), joint->deltaCenter ); + + b3Vec3 bias = b3MulSV( joint->linearSpring.biasRate, c ); + float massScale = joint->linearSpring.massScale; + float impulseScale = joint->linearSpring.impulseScale; + + b3Vec3 cdot = b3Sub( b3Add( vB, b3Cross( wB, rB ) ), b3Add( vA, b3Cross( wA, rA ) ) ); + + //// K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] + b3Matrix3 sA = b3Skew( rA ); + b3Matrix3 sB = b3Skew( rB ); + b3Matrix3 kA = b3MulMM( sA, b3MulMM( base->invIA, sA ) ); + b3Matrix3 kB = b3MulMM( sB, b3MulMM( base->invIB, sB ) ); + b3Matrix3 k = b3NegateMat3( b3AddMM( kA, kB ) ); + k.cx.x += mA + mB; + k.cy.y += mA + mB; + k.cz.z += mA + mB; + + b3Vec3 b = b3Solve3( k, b3Add( cdot, bias ) ); + + b3Vec3 oldImpulse = joint->linearSpringImpulse; + b3Vec3 impulse = b3MulSub( b3MulSV( -massScale, b ), impulseScale, oldImpulse ); + float maxImpulse = context->h * joint->maxSpringForce; + joint->linearSpringImpulse = b3Add( joint->linearSpringImpulse, impulse ); + + if ( b3LengthSquared( joint->linearSpringImpulse ) > maxImpulse * maxImpulse ) + { + joint->linearSpringImpulse = b3MulSV( maxImpulse, b3Normalize( joint->linearSpringImpulse ) ); + } + + impulse = b3Sub( joint->linearSpringImpulse, oldImpulse ); + + vA = b3MulSub( vA, mA, impulse ); + wA = b3Sub( wA, b3MulMV( iA, b3Cross( rA, impulse ) ) ); + vB = b3MulAdd( vB, mB, impulse ); + wB = b3Add( wB, b3MulMV( iB, b3Cross( rB, impulse ) ) ); + } + + // linear velocity + if ( joint->maxVelocityForce > 0.0f ) + { + b3Vec3 cdot = b3Sub( b3Add( vB, b3Cross( wB, rB ) ), b3Add( vA, b3Cross( wA, rA ) ) ); + cdot = b3Sub( cdot, joint->linearVelocity ); + //// K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] + b3Matrix3 sA = b3Skew( rA ); + b3Matrix3 sB = b3Skew( rB ); + b3Matrix3 kA = b3MulMM( sA, b3MulMM( base->invIA, sA ) ); + b3Matrix3 kB = b3MulMM( sB, b3MulMM( base->invIB, sB ) ); + b3Matrix3 k = b3NegateMat3( b3AddMM( kA, kB ) ); + k.cx.x += mA + mB; + k.cy.y += mA + mB; + k.cz.z += mA + mB; + + b3Vec3 b = b3Solve3( k, cdot ); + b3Vec3 impulse = b3Neg( b ); + + b3Vec3 oldImpulse = joint->linearVelocityImpulse; + float maxImpulse = context->h * joint->maxVelocityForce; + joint->linearVelocityImpulse = b3Add( joint->linearVelocityImpulse, impulse ); + + if ( b3LengthSquared( joint->linearVelocityImpulse ) > maxImpulse * maxImpulse ) + { + joint->linearVelocityImpulse = b3MulSV( maxImpulse, b3Normalize( joint->linearVelocityImpulse ) ); + } + + impulse = b3Sub( joint->linearVelocityImpulse, oldImpulse ); + + vA = b3MulSub( vA, mA, impulse ); + wA = b3Sub( wA, b3MulMV( iA, b3Cross( rA, impulse ) ) ); + vB = b3MulAdd( vB, mB, impulse ); + wB = b3Add( wB, b3MulMV( iB, b3Cross( rB, impulse ) ) ); + } + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->linearVelocity = vA; + stateA->angularVelocity = wA; + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->linearVelocity = vB; + stateB->angularVelocity = wB; + } +} + +#if 0 +void b3DumpMotorJoint() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b3Dump(" b3MotorJointDef jd;\n"); + b3Dump(" jd.bodyA = sims[%d];\n", indexA); + b3Dump(" jd.bodyB = sims[%d];\n", indexB); + b3Dump(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b3Dump(" jd.localAnchorA.Set(%.9g, %.9g);\n", m_localAnchorA.x, m_localAnchorA.y); + b3Dump(" jd.localAnchorB.Set(%.9g, %.9g);\n", m_localAnchorB.x, m_localAnchorB.y); + b3Dump(" jd.referenceAngle = %.9g;\n", m_referenceAngle); + b3Dump(" jd.stiffness = %.9g;\n", m_stiffness); + b3Dump(" jd.damping = %.9g;\n", m_damping); + b3Dump(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} +#endif diff --git a/src/mover.c b/src/mover.c new file mode 100644 index 0000000..209426e --- /dev/null +++ b/src/mover.c @@ -0,0 +1,70 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "math_internal.h" + +#include "box3d/collision.h" +#include "box3d/constants.h" + +b3PlaneSolverResult b3SolvePlanes( b3Vec3 targetDelta, b3CollisionPlane* planes, int count ) +{ + for ( int i = 0; i < count; ++i ) + { + planes[i].push = 0.0f; + } + + b3Vec3 delta = targetDelta; + float tolerance = B3_LINEAR_SLOP; + + int iteration; + for ( iteration = 0; iteration < 20; ++iteration ) + { + float totalPush = 0.0f; + for ( int planeIndex = 0; planeIndex < count; ++planeIndex ) + { + b3CollisionPlane* plane = planes + planeIndex; + + // Add slop to prevent jitter + float separation = b3PlaneSeparation( plane->plane, delta ) + B3_LINEAR_SLOP; + + float push = -separation; + + // Clamp accumulated push + float accumulatedPush = plane->push; + plane->push = b3ClampFloat( plane->push + push, 0.0f, plane->pushLimit ); + push = plane->push - accumulatedPush; + delta = b3MulAdd( delta, push, plane->plane.normal ); + + // Track maximum push for convergence + totalPush += b3AbsFloat( push ); + } + + if ( totalPush < tolerance ) + { + break; + } + } + + return (b3PlaneSolverResult){ + .delta = delta, + .iterationCount = iteration, + }; +} + +b3Vec3 b3ClipVector( b3Vec3 vector, const b3CollisionPlane* planes, int count ) +{ + b3Vec3 v = vector; + + for ( int planeIndex = 0; planeIndex < count; ++planeIndex ) + { + const b3CollisionPlane* plane = planes + planeIndex; + if ( plane->push == 0.0f || plane->clipVelocity == false ) + { + continue; + } + + v = b3MulSub( v, b3MinFloat( 0.0f, b3Dot( v, plane->plane.normal ) ), plane->plane.normal ); + } + + return v; +} diff --git a/src/parallel_for.c b/src/parallel_for.c new file mode 100644 index 0000000..07d1c3f --- /dev/null +++ b/src/parallel_for.c @@ -0,0 +1,135 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#include "parallel_for.h" + +#include "core.h" +#include "physics_world.h" +#include "platform.h" + +#include "box3d/base.h" +#include "box3d/constants.h" + +#include + +// Shared state for one b3ParallelFor invocation. Workers race on nextBlock to +// claim work, so a slow chunk can't strand the other threads. +typedef struct b3ParallelForShared +{ + b3AtomicInt nextBlock; + int blockCount; + int blockSize; + int itemCount; + b3ParallelForCallback* callback; + void* context; +} b3ParallelForShared; + +typedef struct b3ParallelForTask +{ + b3ParallelForShared* shared; + int workerIndex; +} b3ParallelForTask; + +static void b3ParallelForTrampoline( void* taskContext ) +{ + b3ParallelForTask* task = (b3ParallelForTask*)taskContext; + b3ParallelForShared* shared = task->shared; + int workerIndex = task->workerIndex; + void* context = shared->context; + b3ParallelForCallback* callback = shared->callback; + + int blockCount = shared->blockCount; + int blockSize = shared->blockSize; + int itemCount = shared->itemCount; + + for ( ;; ) + { + int blockIndex = b3AtomicFetchAddInt( &shared->nextBlock, 1 ); + if ( blockIndex >= blockCount ) + { + break; + } + + int start = blockIndex * blockSize; + int end = start + blockSize; + if ( end > itemCount ) + { + end = itemCount; + } + + callback( start, end, workerIndex, context ); + } +} + +void b3ParallelFor( b3World* world, b3ParallelForCallback* callback, int itemCount, int minRange, void* context, + const char* name ) +{ + if ( itemCount <= 0 ) + { + return; + } + + B3_ASSERT( minRange > 0 ); + + int workerCount = world->workerCount; + B3_ASSERT( 0 < workerCount && workerCount <= B3_MAX_WORKERS ); + + // Target multiple blocks per worker to reduce thread stalls. + // block size grows once items exceed maxBlockCount * minRange + // so the block count stays bounded and per-block sync overhead stays low. + int blocksPerWorker = 4; + int maxBlockCount = blocksPerWorker * workerCount; + + int blockSize; + int blockCount; + if ( itemCount <= minRange * maxBlockCount ) + { + blockSize = minRange; + blockCount = ( itemCount + blockSize - 1 ) / blockSize; + } + else + { + blockSize = ( itemCount + maxBlockCount - 1 ) / maxBlockCount; + blockCount = ( itemCount + blockSize - 1 ) / blockSize; + } + B3_ASSERT( blockCount >= 1 ); + B3_ASSERT( blockSize * blockCount >= itemCount ); + + // No point enqueueing more tasks than blocks. + int taskCount = workerCount < blockCount ? workerCount : blockCount; + + b3ParallelForShared shared; + shared.blockCount = blockCount; + shared.blockSize = blockSize; + shared.itemCount = itemCount; + shared.callback = callback; + shared.context = context; + b3AtomicStoreInt( &shared.nextBlock, 0 ); + + b3ParallelForTask tasks[B3_MAX_WORKERS]; + void* handles[B3_MAX_WORKERS]; + for ( int i = 0; i < taskCount; ++i ) + { + tasks[i].shared = &shared; + tasks[i].workerIndex = i; + + if (world->taskCount < B3_MAX_TASKS) + { + handles[i] = world->enqueueTaskFcn( &b3ParallelForTrampoline, tasks + i, world->userTaskContext, name ); + world->taskCount += 1; + } + else + { + handles[i] = NULL; + b3ParallelForTrampoline( tasks + i ); + } + } + + for ( int i = 0; i < taskCount; ++i ) + { + if ( handles[i] != NULL ) + { + world->finishTaskFcn( handles[i], world->userTaskContext ); + } + } +} diff --git a/src/parallel_for.h b/src/parallel_for.h new file mode 100644 index 0000000..237621a --- /dev/null +++ b/src/parallel_for.h @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +typedef struct b3World b3World; + +// Callback invoked by b2ParallelFor to process a range of items. May be called +// multiple times per worker: work is divided into blocks that workers claim +// atomically, so a worker that finishes early picks up the next unclaimed +// block instead of sitting idle. workerIndex is the worker identity and is +// stable across all invocations from the same worker, so it is safe to use as +// an index into per-worker state (e.g. world->taskContexts.data + workerIndex). +typedef void b3ParallelForCallback( int startIndex, int endIndex, int workerIndex, void* context ); + +#ifdef __cplusplus +extern "C" +{ +#endif + +// Divide [0, itemCount) into blocks and process them with cooperative claiming: +// up to world->workerCount tasks are enqueued, and each task loops, atomically +// claiming the next unclaimed block until the range is drained. Blocks the +// caller until all work is complete. minRange is the minimum block size; block +// size grows once itemCount exceeds 4 * workerCount * minRange so block count +// stays bounded. +void b3ParallelFor( b3World* world, b3ParallelForCallback* callback, int itemCount, int minRange, void* context, + const char* name ); + +#ifdef __cplusplus +} +#endif diff --git a/src/parallel_joint.c b/src/parallel_joint.c new file mode 100644 index 0000000..b2123d2 --- /dev/null +++ b/src/parallel_joint.c @@ -0,0 +1,244 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "body.h" +#include "core.h" +#include "joint.h" +#include "math_internal.h" +#include "physics_world.h" +#include "solver.h" +#include "solver_set.h" + +// needed for dll export +#include "box3d/box3d.h" + +void b3ParallelJoint_SetSpringHertz( b3JointId jointId, float hertz ) +{ + B3_ASSERT( b3IsValidFloat( hertz ) && hertz >= 0.0f ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_parallelJoint ); + base->parallelJoint.hertz = hertz; +} + +float b3ParallelJoint_GetSpringHertz( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_parallelJoint ); + return base->parallelJoint.hertz; +} + +void b3ParallelJoint_SetSpringDampingRatio( b3JointId jointId, float dampingRatio ) +{ + B3_ASSERT( b3IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_parallelJoint ); + base->parallelJoint.dampingRatio = dampingRatio; +} + +float b3ParallelJoint_GetSpringDampingRatio( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_parallelJoint ); + return base->parallelJoint.dampingRatio; +} + +void b3ParallelJoint_SetMaxTorque( b3JointId jointId, float maxForce ) +{ + B3_ASSERT( b3IsValidFloat( maxForce ) && maxForce >= 0.0f ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_parallelJoint ); + base->parallelJoint.maxTorque = maxForce; +} + +float b3ParallelJoint_GetMaxTorque( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_parallelJoint ); + return base->parallelJoint.maxTorque; +} + +b3Vec3 b3GetParallelJointTorque( b3World* world, b3JointSim* base ) +{ + b3ParallelJoint* joint = &base->parallelJoint; + + b3Quat relQ = b3InvMulQuat( joint->quatA, joint->quatB ); + joint->perpAxisX = b3MulSV( 0.5f, b3RotateVector( joint->quatA, b3Add( b3MulSV( relQ.s, b3Vec3_axisX ), b3Cross( relQ.v, b3Vec3_axisX ) ) ) ); + joint->perpAxisY = b3MulSV( 0.5f, b3RotateVector( joint->quatA, b3Add( b3MulSV( relQ.s, b3Vec3_axisY ), b3Cross( relQ.v, b3Vec3_axisY ) ) ) ); + + b3Vec3 angularImpulse = b3Blend2( joint->perpImpulse.x, joint->perpAxisX, joint->perpImpulse.y, joint->perpAxisY ); + b3Vec3 torque = b3MulSV( world->inv_h, angularImpulse ); + return torque; +} + +void b3PrepareParallelJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_parallelJoint ); + + b3World* world = context->world; + + b3Body* bodyA = b3Array_Get( world->bodies, base->bodyIdA ); + b3Body* bodyB = b3Array_Get( world->bodies, base->bodyIdB ); + + B3_ASSERT( bodyA->setIndex == b3_awakeSet || bodyB->setIndex == b3_awakeSet ); + b3SolverSet* setA = b3Array_Get( world->solverSets, bodyA->setIndex ); + b3SolverSet* setB = b3Array_Get( world->solverSets, bodyB->setIndex ); + + int localIndexA = bodyA->localIndex; + int localIndexB = bodyB->localIndex; + + b3BodySim* bodySimA = b3Array_Get( setA->bodySims, localIndexA ); + b3BodySim* bodySimB = b3Array_Get( setB->bodySims, localIndexB ); + + base->invMassA = bodySimA->invMass; + base->invMassB = bodySimB->invMass; + base->invIA = bodySimA->invInertiaWorld; + base->invIB = bodySimB->invInertiaWorld; + + b3Matrix3 invInertiaSum = b3AddMM( base->invIA, base->invIB ); + base->fixedRotation = b3Det( invInertiaSum ) < 1000.0f * FLT_MIN; + + b3ParallelJoint* joint = &base->parallelJoint; + joint->indexA = bodyA->setIndex == b3_awakeSet ? localIndexA : B3_NULL_INDEX; + joint->indexB = bodyB->setIndex == b3_awakeSet ? localIndexB : B3_NULL_INDEX; + + // Compute joint anchor frames with world space rotation, relative to center of mass + joint->quatA = b3MulQuat( bodySimA->transform.q, base->localFrameA.q ); + joint->quatB = b3MulQuat( bodySimB->transform.q, base->localFrameB.q ); + + b3Quat relQ = b3InvMulQuat( joint->quatA, joint->quatB ); + + { + // These are needed for warm starting + joint->perpAxisX = b3MulSV( 0.5f, b3RotateVector( joint->quatA, b3Add( b3MulSV( relQ.s, b3Vec3_axisX ), b3Cross( relQ.v, b3Vec3_axisX ) ) ) ); + joint->perpAxisY = b3MulSV( 0.5f, b3RotateVector( joint->quatA, b3Add( b3MulSV( relQ.s, b3Vec3_axisY ), b3Cross( relQ.v, b3Vec3_axisY ) ) ) ); + } + + joint->softness = b3MakeSoft( joint->hertz, joint->dampingRatio, context->h ); + + if ( context->enableWarmStarting == false ) + { + joint->perpImpulse = (b3Vec2){ 0.0f, 0.0f }; + } +} + +void b3WarmStartParallelJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_parallelJoint ); + + b3Matrix3 iA = base->invIA; + b3Matrix3 iB = base->invIB; + + // dummy state for static bodies + b3BodyState dummyState = b3_identityBodyState; + + b3ParallelJoint* joint = &base->parallelJoint; + + b3BodyState* stateA = joint->indexA == B3_NULL_INDEX ? &dummyState : context->states + joint->indexA; + b3BodyState* stateB = joint->indexB == B3_NULL_INDEX ? &dummyState : context->states + joint->indexB; + + b3Vec3 wA = stateA->angularVelocity; + b3Vec3 wB = stateB->angularVelocity; + + b3Vec3 angularImpulse = b3Blend2( joint->perpImpulse.x, joint->perpAxisX, joint->perpImpulse.y, joint->perpAxisY ); + + wA = b3Sub( wA, b3MulMV( iA, angularImpulse ) ); + wB = b3Add( wB, b3MulMV( iB, angularImpulse ) ); + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->angularVelocity = wA; + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->angularVelocity = wB; + } +} + +void b3SolveParallelJoint( b3JointSim* base, b3StepContext* context ) +{ + b3Matrix3 iA = base->invIA; + b3Matrix3 iB = base->invIB; + + // dummy state for static bodies + b3BodyState dummyState = b3_identityBodyState; + + b3ParallelJoint* joint = &base->parallelJoint; + b3BodyState* stateA = joint->indexA == B3_NULL_INDEX ? &dummyState : context->states + joint->indexA; + b3BodyState* stateB = joint->indexB == B3_NULL_INDEX ? &dummyState : context->states + joint->indexB; + + b3Vec3 wA = stateA->angularVelocity; + b3Vec3 wB = stateB->angularVelocity; + + bool fixedRotation = base->fixedRotation; + b3Quat quatA = b3MulQuat( stateA->deltaRotation, joint->quatA ); + b3Quat quatB = b3MulQuat( stateB->deltaRotation, joint->quatB ); + + if ( b3DotQuat( quatA, quatB ) < 0.0f ) + { + // this keeps the rotation angle in the range [-pi, pi] + quatB = b3NegateQuat( quatB ); + } + + b3Quat relQ = b3InvMulQuat( quatA, quatB ); + + if ( fixedRotation == false && joint->maxTorque > 0.0f ) + { + b3Vec2 c = { relQ.v.x, relQ.v.y }; + b3Vec2 bias = { joint->softness.biasRate * c.x, joint->softness.biasRate * c.y }; + float massScale = joint->softness.massScale; + float impulseScale = joint->softness.impulseScale; + + // Collinearity constraint as 2-by-2 + b3Vec3 perpAxisX = b3MulSV( 0.5f, b3RotateVector( quatA, b3Add( b3MulSV( relQ.s, b3Vec3_axisX ), b3Cross( relQ.v, b3Vec3_axisX ) ) ) ); + b3Vec3 perpAxisY = b3MulSV( 0.5f, b3RotateVector( quatA, b3Add( b3MulSV( relQ.s, b3Vec3_axisY ), b3Cross( relQ.v, b3Vec3_axisY ) ) ) ); + joint->perpAxisX = perpAxisX; + joint->perpAxisY = perpAxisY; + + b3Matrix3 invInertiaSum = b3AddMM( iA, iB ); + float kxx = b3Dot( perpAxisX, b3MulMV( invInertiaSum, perpAxisX ) ); + float kyy = b3Dot( perpAxisY, b3MulMV( invInertiaSum, perpAxisY ) ); + float kxy = b3Dot( perpAxisX, b3MulMV( invInertiaSum, perpAxisY ) ); + + b3Matrix2 k = { { kxx, kxy }, { kxy, kyy } }; + + b3Vec3 wRel = b3Sub( wB, wA ); + b3Vec2 cdot = { b3Dot( wRel, perpAxisX ), b3Dot( wRel, perpAxisY ) }; + + float maxImpulse = context->h * joint->maxTorque; + b3Vec2 oldImpulse = joint->perpImpulse; + b3Vec2 cdotPlusBias = { cdot.x + bias.x, cdot.y + bias.y }; + b3Vec2 sol = b3Solve2( k, cdotPlusBias ); + b3Vec2 deltaImpulse = { + -massScale * sol.x - impulseScale * oldImpulse.x, + -massScale * sol.y - impulseScale * oldImpulse.y, + }; + joint->perpImpulse = (b3Vec2){ oldImpulse.x + deltaImpulse.x, oldImpulse.y + deltaImpulse.y }; + if ( b3LengthSquared2( joint->perpImpulse ) > maxImpulse * maxImpulse ) + { + float s = maxImpulse / b3Length2( joint->perpImpulse ); + joint->perpImpulse = (b3Vec2){ s * joint->perpImpulse.x, s * joint->perpImpulse.y }; + } + + deltaImpulse = b3Sub2( joint->perpImpulse, oldImpulse ); + + b3Vec3 angularImpulse = b3Blend2( deltaImpulse.x, perpAxisX, deltaImpulse.y, perpAxisY ); + wA = b3Sub( wA, b3MulMV( iA, angularImpulse ) ); + wB = b3Add( wB, b3MulMV( iB, angularImpulse ) ); + } + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->angularVelocity = wA; + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->angularVelocity = wB; + } +} + +void b3DrawParallelJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale ) +{ + float length = 0.1f * scale; + + b3Transform frameA = b3MulTransforms( transformA, base->localFrameA ); + draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, length, b3RotateVector( frameA.q, b3Vec3_axisZ ) ), b3_colorGreen, draw->context ); + + b3Transform frameB = b3MulTransforms( transformB, base->localFrameB ); + draw->DrawSegmentFcn( frameB.p, b3MulAdd( frameB.p, length, b3RotateVector( frameB.q, b3Vec3_axisZ ) ), b3_colorBlue, draw->context ); +} diff --git a/src/physics_world.c b/src/physics_world.c new file mode 100644 index 0000000..ebe53c5 --- /dev/null +++ b/src/physics_world.c @@ -0,0 +1,3627 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "physics_world.h" + +#include "arena_allocator.h" +#include "bitset.h" +#include "body.h" +#include "broad_phase.h" +#include "compound.h" +#include "constraint_graph.h" +#include "contact.h" +#include "core.h" +#include "ctz.h" +#include "island.h" +#include "joint.h" +#include "parallel_for.h" +#include "platform.h" +#include "scheduler.h" +#include "sensor.h" +#include "shape.h" +#include "solver.h" +#include "solver_set.h" + +#include "box3d/box3d.h" +#include "box3d/constants.h" + +#include +#include +#include + +_Static_assert( B3_MAX_WORLDS > 0, "must be 1 or more" ); +_Static_assert( B3_MAX_WORLDS < UINT16_MAX, "B3_MAX_WORLDS limit exceeded" ); +b3World b3_worlds[B3_MAX_WORLDS]; +b3AtomicInt b3_worldCount; +int b3_maxWorldCount; + +b3World* b3GetUnlockedWorldFromId( b3WorldId id ) +{ + B3_ASSERT( 1 <= id.index1 && id.index1 <= B3_MAX_WORLDS ); + b3World* world = b3_worlds + ( id.index1 - 1 ); + B3_ASSERT( id.index1 == world->worldId + 1 ); + B3_ASSERT( id.generation == world->generation ); + + // A world accessed from an id should not be locked + if ( world->locked ) + { + B3_ASSERT( false ); + return NULL; + } + return world; +} + +b3World* b3GetWorldFromId( b3WorldId id ) +{ + B3_ASSERT( 1 <= id.index1 && id.index1 <= B3_MAX_WORLDS ); + b3World* world = b3_worlds + ( id.index1 - 1 ); + B3_ASSERT( id.index1 == world->worldId + 1 ); + B3_ASSERT( id.generation == world->generation ); + return world; +} + +b3World* b3GetWorld( int index ) +{ + B3_ASSERT( 0 <= index && index < B3_MAX_WORLDS ); + b3World* world = b3_worlds + index; + B3_ASSERT( world->worldId == index ); + return world; +} + +b3World* b3GetUnlockedWorld( int index ) +{ + B3_ASSERT( 0 <= index && index < B3_MAX_WORLDS ); + b3World* world = b3_worlds + index; + B3_ASSERT( world->worldId == index ); + if ( world->locked ) + { + B3_ASSERT( false ); + return NULL; + } + + return world; +} + +static void* b3DefaultAddTaskFcn( b3TaskCallback* task, void* taskContext, void* userContext, const char* name ) +{ + B3_UNUSED( userContext, name ); + task( taskContext ); + return NULL; +} + +static void b3DefaultFinishTaskFcn( void* userTask, void* userContext ) +{ + B3_UNUSED( userTask ); + B3_UNUSED( userContext ); +} + +static float b3DefaultFrictionCallback( float frictionA, uint64_t materialA, float frictionB, uint64_t materialB ) +{ + B3_UNUSED( materialA, materialB ); + return sqrtf( frictionA * frictionB ); +} + +static float b3DefaultRestitutionCallback( float restitutionA, uint64_t materialA, float restitutionB, uint64_t materialB ) +{ + B3_UNUSED( materialA, materialB ); + return b3MaxFloat( restitutionA, restitutionB ); +} + +static void b3CreateWorkerContexts( b3World* world ) +{ + b3Array_Resize( world->taskContexts, world->workerCount ); + b3Array_MemZero( world->taskContexts ); + + b3Array_Resize( world->sensorTaskContexts, world->workerCount ); + b3Array_MemZero( world->sensorTaskContexts ); + + for ( int i = 0; i < world->workerCount; ++i ) + { + world->taskContexts.data[i].arena = b3CreateArena( 32 * 1024 ); + b3Array_Reserve( world->taskContexts.data[i].sensorHits, 8 ); + world->taskContexts.data[i].contactStateBitSet = b3CreateBitSet( 1024 ); + world->taskContexts.data[i].hitEventBitSet = b3CreateBitSet( 1024 ); + world->taskContexts.data[i].hasHitEvents = false; + world->taskContexts.data[i].jointStateBitSet = b3CreateBitSet( 1024 ); + world->taskContexts.data[i].enlargedSimBitSet = b3CreateBitSet( 256 ); + world->taskContexts.data[i].awakeIslandBitSet = b3CreateBitSet( 256 ); + world->taskContexts.data[i].splitIslandId = B3_NULL_INDEX; + + world->sensorTaskContexts.data[i].eventBits = b3CreateBitSet( 128 ); + } +} + +static void b3DestroyWorkerContexts( b3World* world ) +{ + for ( int i = 0; i < world->workerCount; ++i ) + { + b3DestroyArena( &world->taskContexts.data[i].arena ); + b3Array_Destroy( world->taskContexts.data[i].sensorHits ); + b3DestroyBitSet( &world->taskContexts.data[i].contactStateBitSet ); + b3DestroyBitSet( &world->taskContexts.data[i].hitEventBitSet ); + b3DestroyBitSet( &world->taskContexts.data[i].jointStateBitSet ); + b3DestroyBitSet( &world->taskContexts.data[i].enlargedSimBitSet ); + b3DestroyBitSet( &world->taskContexts.data[i].awakeIslandBitSet ); + + b3DestroyBitSet( &world->sensorTaskContexts.data[i].eventBits ); + } + + b3Array_Destroy( world->taskContexts ); + b3Array_Destroy( world->sensorTaskContexts ); +} + +b3WorldId b3CreateWorld( const b3WorldDef* def ) +{ + B3_CHECK_DEF( def ); + + int worldId = B3_NULL_INDEX; + for ( int i = 0; i < B3_MAX_WORLDS; ++i ) + { + if ( b3_worlds[i].inUse == false ) + { + worldId = i; + break; + } + } + + if ( worldId == B3_NULL_INDEX ) + { + b3Log( "B3_MAX_WORLDS of %d exceeded!!!", B3_MAX_WORLDS ); + B3_ASSERT( worldId != B3_NULL_INDEX ); + return (b3WorldId){ 0 }; + } + + // b3Log( "b3_lengthUnitsPerMeter = %g", b3_lengthUnitsPerMeter ); + + int oldCount = b3AtomicFetchAddInt( &b3_worldCount, 1 ); + b3_maxWorldCount = b3MaxInt( b3_maxWorldCount, oldCount + 1 ); + + // b3Log( "Created world %d", worldId ); + + b3InitializeContactRegisters(); + + b3World* world = b3_worlds + worldId; + uint16_t revision = world->generation; + + memset( world, 0, sizeof( b3World ) ); + + world->worldId = (uint16_t)worldId; + world->generation = revision; + world->inUse = true; + + world->stack = b3CreateStack( 2048 ); + + b3Array_Reserve( world->manifoldAllocators, 16 ); + world->manifoldAllocatorMutex = b3CreateMutex(); + + b3CreateBroadPhase( &world->broadPhase, &def->capacity ); + b3CreateGraph( &world->constraintGraph, 16 ); + + // pools + world->bodyIdPool = b3CreateIdPool(); + + int bodyCapacity = b3MaxInt( 16, def->capacity.staticBodyCount + def->capacity.dynamicBodyCount ); + b3Array_Reserve( world->bodies, bodyCapacity ); + b3Array_Reserve( world->solverSets, 8 ); + + // add empty static, active, and disabled body sets + world->solverSetIdPool = b3CreateIdPool(); + b3SolverSet set = { 0 }; + + // static set + set.setIndex = b3AllocId( &world->solverSetIdPool ); + b3Array_Push( world->solverSets, set ); + b3Array_Reserve( world->solverSets.data[b3_staticSet].bodySims, b3MaxInt( 16, def->capacity.staticBodyCount ) ); + B3_ASSERT( world->solverSets.data[b3_staticSet].setIndex == b3_staticSet ); + + // disabled set + set.setIndex = b3AllocId( &world->solverSetIdPool ); + b3Array_Push( world->solverSets, set ); + B3_ASSERT( world->solverSets.data[b3_disabledSet].setIndex == b3_disabledSet ); + + // awake set + set.setIndex = b3AllocId( &world->solverSetIdPool ); + b3Array_Push( world->solverSets, set ); + b3Array_Reserve( world->solverSets.data[b3_awakeSet].bodySims, b3MaxInt( 16, def->capacity.dynamicBodyCount ) ); + b3Array_Reserve( world->solverSets.data[b3_awakeSet].bodyStates, b3MaxInt( 16, def->capacity.dynamicBodyCount ) ); + b3Array_Reserve( world->solverSets.data[b3_awakeSet].contactIndices, b3MaxInt( 16, def->capacity.contactCount ) ); + B3_ASSERT( world->solverSets.data[b3_awakeSet].setIndex == b3_awakeSet ); + + world->shapeIdPool = b3CreateIdPool(); + + int shapeCapacity = b3MaxInt( 16, def->capacity.staticShapeCount + def->capacity.dynamicShapeCount ); + b3Array_Reserve( world->shapes, shapeCapacity ); + + world->contactIdPool = b3CreateIdPool(); + b3Array_Reserve( world->contacts, b3MaxInt( 16, def->capacity.contactCount ) ); + + world->jointIdPool = b3CreateIdPool(); + b3Array_Reserve( world->joints, 16 ); + + world->islandIdPool = b3CreateIdPool(); + b3Array_Reserve( world->islands, b3MaxInt( 16, def->capacity.dynamicBodyCount ) ); + + b3Array_Reserve( world->sensors, 4 ); + + b3Array_Reserve( world->bodyMoveEvents, 4 ); + b3Array_Reserve( world->sensorBeginEvents, 4 ); + b3Array_Reserve( world->sensorEndEvents[0], 4 ); + b3Array_Reserve( world->sensorEndEvents[1], 4 ); + b3Array_Reserve( world->contactBeginEvents, 4 ); + b3Array_Reserve( world->contactEndEvents[0], 4 ); + b3Array_Reserve( world->contactEndEvents[1], 4 ); + b3Array_Reserve( world->contactHitEvents, 4 ); + b3Array_Reserve( world->jointEvents, 4 ); + world->endEventArrayIndex = 0; + + world->stepIndex = 0; + world->splitIslandId = B3_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; + world->contactRecycleDistance = B3_CONTACT_RECYCLE_DISTANCE; + + if ( def->frictionCallback == NULL ) + { + world->frictionCallback = b3DefaultFrictionCallback; + } + else + { + world->frictionCallback = def->frictionCallback; + } + + if ( def->restitutionCallback == NULL ) + { + world->restitutionCallback = b3DefaultRestitutionCallback; + } + else + { + world->restitutionCallback = def->restitutionCallback; + } + + world->enableSleep = def->enableSleep; + world->locked = false; + world->enableWarmStarting = true; + world->enableContinuous = def->enableContinuous; + world->enableSpeculative = true; + world->userTreeTask = NULL; + world->userData = def->userData; + + if ( def->workerCount > 0 && def->enqueueTask != NULL && def->finishTask != NULL ) + { + // External task system + world->workerCount = b3MinInt( def->workerCount, B3_MAX_WORKERS ); + world->enqueueTaskFcn = def->enqueueTask; + world->finishTaskFcn = def->finishTask; + world->userTaskContext = def->userTaskContext; + world->scheduler = NULL; + } + else if ( def->workerCount > 1 ) + { + // Built-in scheduler + world->workerCount = b3MinInt( def->workerCount, B3_MAX_WORKERS ); + world->scheduler = b3CreateScheduler( world->workerCount ); + world->enqueueTaskFcn = b3SchedulerEnqueueTask; + world->finishTaskFcn = b3SchedulerFinishTask; + world->userTaskContext = world->scheduler; + } + else + { + // Serial fallback + world->workerCount = 1; + world->enqueueTaskFcn = b3DefaultAddTaskFcn; + world->finishTaskFcn = b3DefaultFinishTaskFcn; + world->userTaskContext = NULL; + world->scheduler = NULL; + } + + b3CreateWorkerContexts( world ); + + world->debugBodySet = b3CreateBitSet( 256 ); + world->debugJointSet = b3CreateBitSet( 256 ); + world->debugContactSet = b3CreateBitSet( 256 ); + world->debugIslandSet = b3CreateBitSet( 256 ); + world->createDebugShape = def->createDebugShape; + world->destroyDebugShape = def->destroyDebugShape; + world->userDebugShapeContext = def->userDebugShapeContext; + + // add one to worldId so that 0 represents a null b3WorldId + return (b3WorldId){ (uint16_t)( worldId + 1 ), world->generation }; +} + +void b3DestroyWorld( b3WorldId worldId ) +{ + b3AtomicFetchAddInt( &b3_worldCount, -1 ); + + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + world->locked = true; + + if ( world->scheduler != NULL ) + { + b3DestroyScheduler( world->scheduler ); + world->scheduler = NULL; + } + + b3DestroyBitSet( &world->debugBodySet ); + b3DestroyBitSet( &world->debugJointSet ); + b3DestroyBitSet( &world->debugContactSet ); + b3DestroyBitSet( &world->debugIslandSet ); + + b3DestroyWorkerContexts( world ); + + b3Array_Destroy( world->bodyMoveEvents ); + b3Array_Destroy( world->sensorBeginEvents ); + b3Array_Destroy( world->sensorEndEvents[0] ); + b3Array_Destroy( world->sensorEndEvents[1] ); + b3Array_Destroy( world->contactBeginEvents ); + b3Array_Destroy( world->contactEndEvents[0] ); + b3Array_Destroy( world->contactEndEvents[1] ); + b3Array_Destroy( world->contactHitEvents ); + b3Array_Destroy( world->jointEvents ); + + int sensorCount = world->sensors.count; + for ( int i = 0; i < sensorCount; ++i ) + { + b3Array_Destroy( world->sensors.data[i].hits ); + b3Array_Destroy( world->sensors.data[i].overlaps1 ); + b3Array_Destroy( world->sensors.data[i].overlaps2 ); + } + + b3Array_Destroy( world->sensors ); + b3Array_Destroy( world->bodies ); + + int shapeCapacity = world->shapes.count; + b3Shape* shapes = world->shapes.data; + for ( int i = 0; i < shapeCapacity; ++i ) + { + b3Shape* shape = shapes + i; + if ( shape->id != B3_NULL_INDEX ) + { + b3DestroyShapeAllocations( world, shapes + i ); + } + } + + int contactCapacity = world->contacts.count; + b3Contact* contacts = world->contacts.data; + for ( int i = 0; i < contactCapacity; ++i ) + { + b3Contact* contact = contacts + i; + if ( contact->contactId != B3_NULL_INDEX ) + { + if ( contact->flags & b3_simMeshContact ) + { + b3Array_Destroy( contact->meshContact.triangleCache ); + } + } + } + + b3Array_Destroy( world->shapes ); + b3Array_Destroy( world->contacts ); + b3Array_Destroy( world->joints ); + + for ( int i = 0; i < world->islands.count; ++i ) + { + b3Array_Destroy( world->islands.data[i].bodies ); + b3Array_Destroy( world->islands.data[i].contacts ); + b3Array_Destroy( world->islands.data[i].joints ); + } + b3Array_Destroy( world->islands ); + + // Destroy solver sets + int setCapacity = world->solverSets.count; + for ( int i = 0; i < setCapacity; ++i ) + { + b3SolverSet* set = world->solverSets.data + i; + if ( set->setIndex != B3_NULL_INDEX ) + { + b3DestroySolverSet( world, i ); + } + } + + b3Array_Destroy( world->solverSets ); + + b3DestroyGraph( &world->constraintGraph ); + b3DestroyBroadPhase( &world->broadPhase ); + + b3DestroyIdPool( &world->bodyIdPool ); + b3DestroyIdPool( &world->shapeIdPool ); + b3DestroyIdPool( &world->contactIdPool ); + b3DestroyIdPool( &world->jointIdPool ); + b3DestroyIdPool( &world->islandIdPool ); + b3DestroyIdPool( &world->solverSetIdPool ); + + for ( int i = 0; i < world->manifoldAllocators.count; ++i ) + { + b3DestroyBlockAllocator( world->manifoldAllocators.data + i ); + } + b3Array_Destroy( world->manifoldAllocators ); + b3DestroyMutex( world->manifoldAllocatorMutex ); + + b3DestroyStack( &world->stack ); + + // Wipe world but preserve generation + uint16_t generation = world->generation; + memset( world, 0, sizeof( b3World ) ); + world->generation = generation + 1; + + // b3Log( "Destroyed world %d", worldId.index1 - 1 ); +} + +int b3GetWorldCount( void ) +{ + return b3AtomicLoadInt( &b3_worldCount ); +} + +int b3GetMaxWorldCount( void ) +{ + return b3_maxWorldCount; +} + +// Issues T0 prefetches across the cache lines of a b3Contact (216 B / 4 lines). +// Used to hide the random-access latency of contact lookups while we work on an +// earlier index. +static inline void b3PrefetchContact( const b3Contact* contact ) +{ + const char* p = (const char*)contact; + b3Prefetch( p ); + b3Prefetch( p + 64 ); + b3Prefetch( p + 128 ); + b3Prefetch( p + 192 ); +} + +static void b3CollideTask( int startIndex, int endIndex, int workerIndex, void* context ) +{ + b3TracyCZoneNC( collide_task, "Collide Task", b3_colorDodgerBlue, true ); + + b3StepContext* stepContext = (b3StepContext*)context; + b3World* world = stepContext->world; + b3ConstraintGraph* graph = &world->constraintGraph; + b3TaskContext* taskContext = world->taskContexts.data + workerIndex; + int* contactIndices = stepContext->awakeContactIndices; + b3Contact* contacts = world->contacts.data; + b3Shape* shapes = world->shapes.data; + b3Body* bodies = world->bodies.data; + b3BodySim* awakeSims = world->solverSets.data[b3_awakeSet].bodySims.data; + b3BodySim* staticSims = world->solverSets.data[b3_staticSet].bodySims.data; + + B3_ASSERT( startIndex < endIndex ); + + float recycleDistance = world->contactRecycleDistance; + float speculativeDistance = B3_SPECULATIVE_DISTANCE; + float recycleDistanceNonTouching = b3MinFloat( recycleDistance, speculativeDistance ); + + // Prefetch contact[i + contactPrefetchDistance] each iteration so the random + // 216 B contact load lands in L1 by the time we reach it. Distance picked to + // cover ~200 cycles of memory latency without overshooting the L1 working set. + const int contactPrefetchDistance = 4; + int prefetchEnd = endIndex - contactPrefetchDistance; + + for ( int i = startIndex; i < endIndex; ++i ) + { + if ( i < prefetchEnd ) + { + b3PrefetchContact( contacts + contactIndices[i + contactPrefetchDistance] ); + } + + int contactIndex = contactIndices[i]; + B3_ASSERT( contactIndex < world->contacts.count ); + + b3Contact* contact = contacts + contactIndex; + B3_VALIDATE( contact->contactId == contactIndex ); + + b3Shape* shapeA = shapes + contact->shapeIdA; + b3Shape* shapeB = shapes + contact->shapeIdB; + + // Do proxies still overlap? + bool overlap = b3AABB_Overlaps( shapeA->fatAABB, shapeB->fatAABB ); + if ( overlap == false ) + { + // This contact will be destroyed + contact->flags |= b3_simDisjoint; + contact->flags &= ~b3_simTouchingFlag; + b3SetBit( &taskContext->contactStateBitSet, contactIndex ); + continue; + } + + // Update contact respecting shape/body order (A,B). Bodies behind awake-set + // contacts are always either awake or static - inline b3GetBodySim with that + // invariant to skip the cross-TU call and per-call solverSets indirection. + b3Body* bodyA = bodies + shapeA->bodyId; + b3Body* bodyB = bodies + shapeB->bodyId; + bool isStaticA = bodyA->type == b3_staticBody; + bool isStaticB = bodyB->type == b3_staticBody; + bool wasTouching = ( contact->flags & b3_simTouchingFlag ); + bool isMeshContact = ( contact->flags & b3_simMeshContact ); + b3BodySim* bodySimA; + b3BodySim* bodySimB; + if ( wasTouching ) + { + B3_ASSERT( bodyA->setIndex == b3_awakeSet || bodyA->setIndex == b3_staticSet ); + B3_ASSERT( bodyB->setIndex == b3_awakeSet || bodyB->setIndex == b3_staticSet ); + bodySimA = ( isStaticA ? staticSims : awakeSims ) + bodyA->localIndex; + bodySimB = ( isStaticB ? staticSims : awakeSims ) + bodyB->localIndex; + } + else + { + // There can be non-touching contacts between awake bodies and sleeping bodies. + { + b3SolverSet* set = b3Array_Get( world->solverSets, bodyA->setIndex ); + bodySimA = b3Array_Get( set->bodySims, bodyA->localIndex ); + } + { + b3SolverSet* set = b3Array_Get( world->solverSets, bodyB->setIndex ); + bodySimB = b3Array_Get( set->bodySims, bodyB->localIndex ); + } + } + + b3Transform transformA = bodySimA->transform; + b3Transform transformB = bodySimB->transform; + + bool isFast = ( bodySimA->flags & b3_isFast ) || ( bodySimB->flags & b3_isFast ); + + // These are used by the contact solver. If the contact is between an awake body + // and a sleeping body and the contact begins to touch, the these will be invalid + // but fixed when linked in the constraint graph. + contact->bodySimIndexA = isStaticA ? B3_NULL_INDEX : bodyA->localIndex; + contact->bodySimIndexB = isStaticB ? B3_NULL_INDEX : bodyB->localIndex; + float recycleTolerance = wasTouching ? recycleDistance : recycleDistanceNonTouching; + + // Contact recycling optimization. Please cite this library if you use this optimization. + // This is inspired by persistent contact manifolds used in some physics engines, such as PhysX. + // However, this allows larger relative motion and has fewer tuning parameters (just one). + if ( ( isFast == false || isMeshContact == false ) && recycleDistance > 0.0f && + contact->flags & b3_relativeTransformValid ) + { + b3Transform xf = b3InvMulTransforms( transformA, transformB ); + b3Transform xfc = b3InvMulTransforms( contact->cachedTransformA, contact->cachedTransformB ); + b3Vec3 maxExtentA = isStaticA ? b3Vec3_zero : bodySimA->maxExtent; + b3Vec3 maxExtentB = isStaticB ? b3Vec3_zero : bodySimB->maxExtent; + b3Vec3 maxExtent = b3Max( maxExtentA, maxExtentB ); + + // Variation of Conservative Advancement + // distance + 2 * length(modified_cross(|qr.v|, maxExtent)) < recycleTolerance. + // 2*|qr.v| == 2*|sin(theta/2)| ~= theta for small angles. + float distSquared = b3DistanceSquared( xf.p, xfc.p ); + + if ( distSquared < recycleTolerance * recycleTolerance ) + { + float distance = sqrtf( distSquared ); + float slack = recycleTolerance - distance; + + // qr = inv( inv(qA0) * qB0 ) * inv(qA) * qB + // = inv(qB0) * qA0 * inv(qA) * qB + // Suppose A is static + // qr = inv(qB0) * qA0 * inv(qA0) * qB + // = inv(qB0) * qB + // qB = qB0 * qr + // Therefore qr is associated with the local angular velocity of body B when A is static. + b3Quat qr = b3InvMulQuat( xfc.q, xf.q ); + b3Vec3 arc = b3ModifiedCross( b3Abs( qr.v ), maxExtent ); + + float arcSq = 4.0f * b3LengthSquared( arc ); + if ( arcSq < slack * slack ) + { + b3Quat dqA = b3MulQuat( transformA.q, b3Conjugate( contact->cachedTransformA.q ) ); + b3Quat dqB = b3MulQuat( transformB.q, b3Conjugate( contact->cachedTransformB.q ) ); + b3Matrix3 matrixA = b3MakeMatrixFromQuat( dqA ); + b3Matrix3 matrixB = b3MakeMatrixFromQuat( dqB ); + + // Minimize round-off + b3Vec3 dc = b3Sub( bodySimB->center, bodySimA->center ); + + int manifoldCount = contact->manifoldCount; + for ( int manifoldIndex = 0; manifoldIndex < manifoldCount; ++manifoldIndex ) + { + b3Manifold* manifold = contact->manifolds + manifoldIndex; + b3Vec3 normal = manifold->normal; + + int pointCount = manifold->pointCount; + for ( int pointIndex = 0; pointIndex < pointCount; ++pointIndex ) + { + // Keep anchors but update separation, same as sub-stepping. This eliminates jitter. + b3ManifoldPoint* mp = manifold->points + pointIndex; + b3Vec3 rA = b3MulMV( matrixA, mp->anchorA ); + b3Vec3 rB = b3MulMV( matrixB, mp->anchorB ); + b3Vec3 dp = b3Add( dc, b3Sub( rB, rA ) ); + mp->separation = mp->baseSeparation + b3Dot( dp, normal ); + mp->persisted = true; + } + } + + // Diagnostics + taskContext->recycledContactCount += 1; + int bucketIndex = b3MinInt( manifoldCount, B3_CONTACT_MANIFOLD_COUNT_BUCKETS - 1 ); + if ( bucketIndex > 0 ) + { + taskContext->manifoldCounts[bucketIndex - 1] += 1; + } + + // Contact is recycled. This also skips updating other aspects of the contact + // such as material parameters. + continue; + } + } + } + + // Caching for contact recycling. + contact->cachedTransformA = transformA; + contact->cachedTransformB = transformB; + contact->flags |= b3_relativeTransformValid; + + // This updates solid contacts + bool touching = b3UpdateContact( world, workerIndex, contact, shapeA, bodySimA->localCenter, transformA, shapeB, + bodySimB->localCenter, transformB, isFast, taskContext->arena ); + + int bucketIndex = b3MinInt( contact->manifoldCount, B3_CONTACT_MANIFOLD_COUNT_BUCKETS - 1 ); + if ( bucketIndex > 0 ) + { + taskContext->manifoldCounts[bucketIndex - 1] += 1; + } + + // Update the mesh contact spec + if ( touching == true && wasTouching == true && ( contact->flags & b3_simMeshContact ) ) + { + B3_ASSERT( contact->colorIndex != B3_NULL_INDEX ); + B3_ASSERT( 0 <= contact->colorIndex && contact->colorIndex < B3_GRAPH_COLOR_COUNT ); + b3GraphColor* color = graph->colors + contact->colorIndex; + b3ContactSpec* spec = b3Array_Get( color->contacts, contact->localIndex ); + spec->manifoldCount = (uint16_t)contact->manifoldCount; + } + + // State changes that affect island connectivity. Also affects contact events. + if ( touching == true && wasTouching == false ) + { + contact->flags |= b3_simStartedTouching; + b3SetBit( &taskContext->contactStateBitSet, contactIndex ); + } + else if ( touching == false && wasTouching == true ) + { + contact->flags |= b3_simStoppedTouching; + b3SetBit( &taskContext->contactStateBitSet, contactIndex ); + } + + for ( int manifoldIndex = 0; manifoldIndex < contact->manifoldCount; ++manifoldIndex ) + { + b3Manifold* manifold = contact->manifolds + manifoldIndex; + for ( int pointIndex = 0; pointIndex < manifold->pointCount; ++pointIndex ) + { + // Cache separation + b3ManifoldPoint* mp = manifold->points + pointIndex; + mp->baseSeparation = mp->separation; + } + } + } + + b3TracyCZoneEnd( collide_task ); +} + +static void b3AddNonTouchingContact( b3World* world, b3Contact* contact ) +{ + B3_ASSERT( contact->setIndex == b3_awakeSet ); + b3SolverSet* set = b3Array_Get( world->solverSets, b3_awakeSet ); + contact->colorIndex = B3_NULL_INDEX; + contact->localIndex = set->contactIndices.count; + contact->bodySimIndexA = B3_NULL_INDEX; + contact->bodySimIndexB = B3_NULL_INDEX; + b3Array_Push( set->contactIndices, contact->contactId ); +} + +static void b3RemoveNonTouchingContact( b3World* world, int setIndex, int localIndex ) +{ + b3SolverSet* set = b3Array_Get( world->solverSets, setIndex ); + int movedIndex = b3Array_RemoveSwap( set->contactIndices, localIndex ); + if ( movedIndex != B3_NULL_INDEX ) + { + int movedContactIndex = set->contactIndices.data[localIndex]; + b3Contact* movedContact = b3Array_Get( world->contacts, movedContactIndex ); + B3_ASSERT( movedContact->setIndex == setIndex ); + B3_ASSERT( movedContact->colorIndex == B3_NULL_INDEX ); + B3_ASSERT( movedContact->localIndex == movedIndex ); + movedContact->localIndex = localIndex; + } +} + +// Narrow-phase collision +static void b3Collide( b3StepContext* context ) +{ + b3World* world = context->world; + + B3_ASSERT( world->workerCount > 0 ); + + b3TracyCZoneNC( collide, "Collide", b3_colorDarkOrchid, true ); + + // Gather contacts from all the graph colors into a single array for easier parallel-for + int touchingCount = 0; + + b3GraphColor* graphColors = world->constraintGraph.colors; + for ( int i = 0; i < B3_GRAPH_COLOR_COUNT; ++i ) + { + touchingCount += graphColors[i].convexContacts.count + graphColors[i].contacts.count; + } + + b3SolverSet* awakeSet = b3Array_Get( world->solverSets, b3_awakeSet ); + int nonTouchingCount = awakeSet->contactIndices.count; + + int contactCount = touchingCount + nonTouchingCount; + + if ( contactCount == 0 ) + { + b3TracyCZoneEnd( collide ); + return; + } + + int* contactIndices = (int*)b3StackAlloc( &world->stack, contactCount * sizeof( int ), "contact indices" ); + + int contactIndex = 0; + for ( int i = 0; i < B3_GRAPH_COLOR_COUNT; ++i ) + { + b3GraphColor* color = graphColors + i; + int count = color->convexContacts.count; + for ( int j = 0; j < count; ++j ) + { + contactIndices[contactIndex] = color->convexContacts.data[j]; + contactIndex += 1; + } + + count = color->contacts.count; + for ( int j = 0; j < count; ++j ) + { + contactIndices[contactIndex] = color->contacts.data[j].contactId; + contactIndex += 1; + } + } + + B3_ASSERT( contactIndex == touchingCount ); + + if ( nonTouchingCount > 0 ) + { + int* nonTouchingIndices = awakeSet->contactIndices.data; + memcpy( contactIndices + touchingCount, nonTouchingIndices, nonTouchingCount * sizeof( int ) ); + } + + context->awakeContactIndices = contactIndices; + + // Contact bit set on ids because contact pointers are unstable as they move between touching and not touching. + int contactIdCapacity = b3GetIdCapacity( &world->contactIdPool ); + for ( int i = 0; i < world->workerCount; ++i ) + { + b3TaskContext* taskContext = world->taskContexts.data + i; + b3SetBitCountAndClear( &taskContext->contactStateBitSet, contactIdCapacity ); + taskContext->satCallCount = 0; + taskContext->satCacheHitCount = 0; + taskContext->recycledContactCount = 0; + memset( taskContext->manifoldCounts, 0, sizeof( taskContext->manifoldCounts ) ); + } + + // Task should take at least 40us on a 4GHz CPU (10K cycles) + int minRange = 20; + b3ParallelFor( world, b3CollideTask, contactCount, minRange, context, "collide" ); + + b3StackFree( &world->stack, contactIndices ); + context->awakeContactIndices = NULL; + contactIndices = NULL; + + // Serially update contact state + // todo bring this zone together with island merge + b3TracyCZoneNC( contact_state, "Contact State", b3_colorLightSlateGray, true ); + + int satMultiplier = context->dt > 0.0f ? 1 : 0; + + // Bitwise OR all contact bits + b3BitSet* bitSet = &world->taskContexts.data[0].contactStateBitSet; + world->satCallCount = satMultiplier * world->taskContexts.data[0].satCallCount; + world->satCacheHitCount = satMultiplier * world->taskContexts.data[0].satCacheHitCount; + memcpy( world->manifoldCounts, world->taskContexts.data[0].manifoldCounts, + B3_CONTACT_MANIFOLD_COUNT_BUCKETS * sizeof( int ) ); + + for ( int i = 1; i < world->workerCount; ++i ) + { + b3InPlaceUnion( bitSet, &world->taskContexts.data[i].contactStateBitSet ); + world->satCallCount += world->taskContexts.data[i].satCallCount; + world->satCacheHitCount += world->taskContexts.data[i].satCacheHitCount; + for ( int j = 0; j < B3_CONTACT_MANIFOLD_COUNT_BUCKETS; ++j ) + { + world->manifoldCounts[j] += world->taskContexts.data[i].manifoldCounts[j]; + } + } + + int endEventArrayIndex = world->endEventArrayIndex; + + const b3Shape* 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 = b3CTZ64( bits ); + int contactId = (int)( 64 * k + ctz ); + + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + B3_ASSERT( contact->setIndex == b3_awakeSet ); + + const b3Shape* shapeA = shapes + contact->shapeIdA; + const b3Shape* shapeB = shapes + contact->shapeIdB; + b3ShapeId shapeIdA = { shapeA->id + 1, worldId, shapeA->generation }; + b3ShapeId shapeIdB = { shapeB->id + 1, worldId, shapeB->generation }; + b3ContactId contactFullId = { + .index1 = contactId + 1, + .world0 = worldId, + .padding = 0, + .generation = contact->generation, + }; + uint32_t flags = contact->flags; + + if ( flags & b3_simDisjoint ) + { + // Bounding boxes no longer overlap + b3DestroyContact( world, contact, false ); + contact = NULL; + } + else if ( flags & b3_simStartedTouching ) + { + B3_ASSERT( contact->islandId == B3_NULL_INDEX ); + + if ( flags & b3_contactEnableContactEvents ) + { + b3ContactBeginTouchEvent event = { shapeIdA, shapeIdB, contactFullId }; + b3Array_Push( world->contactBeginEvents, event ); + } + + B3_ASSERT( contact->manifoldCount > 0 ); + B3_ASSERT( contact->setIndex == b3_awakeSet ); + + // Link first because this wakes colliding bodies and ensures the body sims + // are in the correct place. + contact->flags &= ~b3_simStartedTouching; + contact->flags |= b3_contactTouchingFlag; + b3LinkContact( world, contact ); + + // Make sure these didn't change + B3_ASSERT( contact->colorIndex == B3_NULL_INDEX ); + + // Contact sim pointer may have become orphaned due to awake set growth, + // so I just need to refresh it. + + int oldLocalIndex = contact->localIndex; + + b3AddContactToGraph( world, contact ); + b3RemoveNonTouchingContact( world, b3_awakeSet, oldLocalIndex ); + } + else if ( flags & b3_simStoppedTouching ) + { + contact->flags &= ~b3_simStoppedTouching; + contact->flags &= ~b3_contactTouchingFlag; + + if ( contact->flags & b3_contactEnableContactEvents ) + { + b3ContactEndTouchEvent event = { shapeIdA, shapeIdB, contactFullId }; + b3Array_Push( world->contactEndEvents[endEventArrayIndex], event ); + } + + B3_ASSERT( contact->manifoldCount == 0 ); + + // Cache these here for the remove below + int colorIndex = contact->colorIndex; + int localIndex = contact->localIndex; + + b3UnlinkContact( world, contact ); + int bodyIdA = contact->edges[0].bodyId; + int bodyIdB = contact->edges[1].bodyId; + + b3AddNonTouchingContact( world, contact ); + + bool isMeshContact = contact->flags & b3_simMeshContact; + b3RemoveContactFromGraph( world, bodyIdA, bodyIdB, colorIndex, localIndex, isMeshContact ); + contact = NULL; + } + + // Clear the smallest set bit + bits = bits & ( bits - 1 ); + } + } + + b3ValidateSolverSets( world ); + b3ValidateContacts( world ); + + b3TracyCZoneEnd( contact_state ); + b3TracyCZoneEnd( collide ); +} + +void b3World_Step( b3WorldId worldId, float timeStep, int subStepCount ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + world->locked = true; + + b3TracyCZoneNC( world_step, "Step", b3_colorBox2DGreen, true ); + + // Clear debug buffers + for ( int i = 0; i < world->workerCount; ++i ) + { + world->taskContexts.data[i].pointCount = 0; + world->taskContexts.data[i].lineCount = 0; + } + + // Prepare to capture events + // Ensure user does not access stale data if there is an early return + b3Array_Clear( world->bodyMoveEvents ); + b3Array_Clear( world->sensorBeginEvents ); + b3Array_Clear( world->contactBeginEvents ); + b3Array_Clear( world->contactHitEvents ); + b3Array_Clear( world->jointEvents ); + + world->profile = (b3Profile){ 0 }; + + + world->activeTaskCount = 0; + world->taskCount = 0; + + if ( world->scheduler != NULL ) + { + b3ResetScheduler( world->scheduler ); + } + + uint64_t stepTicks = b3GetTicks(); + + { + b3Capacity* c = &world->maxCapacity; + c->staticShapeCount = b3MaxInt( c->staticShapeCount, world->broadPhase.trees[b3_staticBody].proxyCount ); + c->dynamicShapeCount = b3MaxInt( c->dynamicShapeCount, world->broadPhase.trees[b3_dynamicBody].proxyCount ); + + int staticBodyCount = world->solverSets.data[b3_staticSet].bodySims.count; + c->staticBodyCount = b3MaxInt( c->staticBodyCount, staticBodyCount ); + + // this includes kinematic bodies + int totalBodyCount = b3GetIdCount( &world->bodyIdPool ); + c->dynamicBodyCount = b3MaxInt( c->dynamicBodyCount, totalBodyCount - staticBodyCount ); + + int totalContactCount = b3GetIdCount( &world->contactIdPool ); + c->contactCount = b3MaxInt( c->contactCount, totalContactCount ); + } + + // Update collision pairs and create contacts + { + uint64_t pairTicks = b3GetTicks(); + b3UpdateBroadPhasePairs( world ); + world->profile.pairs = b3GetMilliseconds( pairTicks ); + } + + b3SolverSet* awakeSet = b3Array_Get( world->solverSets, b3_awakeSet ); + + b3StepContext context = { 0 }; + context.world = world; + context.states = awakeSet->bodyStates.data; + context.dt = timeStep; + context.subStepCount = b3MaxInt( 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 = b3MinFloat( world->contactHertz, 0.125f * context.inv_h ); + context.contactSoftness = b3MakeSoft( contactHertz, world->contactDampingRatio, context.h ); + context.staticSoftness = b3MakeSoft( 2.0f * contactHertz, 0.5f * world->contactDampingRatio, context.h ); + + context.restitutionThreshold = world->restitutionThreshold; + context.maxLinearVelocity = world->maxLinearSpeed; + context.enableWarmStarting = world->enableWarmStarting; + + // Narrow phase : update contacts + { + uint64_t collideTicks = b3GetTicks(); + b3Collide( &context ); + world->profile.collide = b3GetMilliseconds( collideTicks ); + } + + // Integrate velocities, solve velocity constraints, and integrate positions. + if ( timeStep > 0.0f ) + { + uint64_t solveTicks = b3GetTicks(); + b3Solve( world, &context ); + world->profile.solve = b3GetMilliseconds( solveTicks ); + } + + // Finish the tree task in case b3Solve didn't finish it + if ( world->userTreeTask ) + { + world->finishTaskFcn( world->userTreeTask, world->userTaskContext ); + world->userTreeTask = NULL; + world->activeTaskCount -= 1; + } + + // Update sensors + { + uint64_t sensorTicks = b3GetTicks(); + b3OverlapSensors( world ); + world->profile.sensors = b3GetMilliseconds( sensorTicks ); + } + + world->profile.step = b3GetMilliseconds( stepTicks ); + + B3_ASSERT( world->stack.allocation == 0 ); + + // Ensure stack is large enough + b3GrowStack( &world->stack ); + + // Make sure all tasks that were started were also finished + B3_ASSERT( world->activeTaskCount == 0 ); + + + // Swap end event array buffers + world->endEventArrayIndex = 1 - world->endEventArrayIndex; + b3Array_Clear( world->sensorEndEvents[world->endEventArrayIndex] ); + b3Array_Clear( world->contactEndEvents[world->endEventArrayIndex] ); + world->locked = false; + + b3TracyCZoneEnd( world_step ); + b3TracyCFrame; +} + +typedef struct DrawContext +{ + b3World* world; + b3DebugDraw* draw; +} DrawContext; + +static bool DrawQueryCallback( int proxyId, uint64_t userData, void* context ) +{ + int shapeId = (int)userData; + + B3_UNUSED( proxyId ); + + struct DrawContext* drawContext = (DrawContext*)context; + b3World* world = drawContext->world; + b3DebugDraw* draw = drawContext->draw; + + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + B3_ASSERT( shape->id == shapeId ); + + b3SetBit( &world->debugBodySet, shape->bodyId ); + + if ( draw->drawShapes ) + { + b3Body* body = b3Array_Get( world->bodies, shape->bodyId ); + b3BodySim* bodySim = b3GetBodySim( world, body ); + + b3HexColor color; + + if ( shape->materials[0].customColor != 0 ) + { + color = (b3HexColor)shape->materials[0].customColor; + } + else if ( body->type == b3_dynamicBody && body->mass == 0.0f ) + { + // Bad body + color = b3_colorRed; + } + else if ( body->setIndex == b3_disabledSet ) + { + color = b3_colorSlateGray; + } + else if ( shape->sensorIndex != B3_NULL_INDEX ) + { + color = b3_colorWheat; + } + else if ( body->flags & b3_hadTimeOfImpact ) + { + color = b3_colorLime; + } + else if ( ( bodySim->flags & b3_isBullet ) && body->setIndex == b3_awakeSet ) + { + color = b3_colorTurquoise; + } + else if ( body->flags & b3_isSpeedCapped ) + { + color = b3_colorYellow; + } + else if ( bodySim->flags & b3_isFast ) + { + color = b3_colorSalmon; + } + else if ( body->type == b3_staticBody ) + { + color = b3_colorPaleGreen; + } + else if ( body->type == b3_kinematicBody ) + { + if ( body->setIndex == b3_awakeSet ) + { + color = b3_colorRoyalBlue; + } + else + { + color = b3_colorDarkBlue; + } + } + else if ( body->setIndex == b3_awakeSet ) + { + color = b3_colorPink; + } + else + { + color = b3_colorGray; + } + + if ( shape->userShape == NULL && world->createDebugShape != NULL ) + { + b3DebugShape debugShape = { 0 }; + debugShape.shapeId = (b3ShapeId){ + .world0 = world->worldId, + .index1 = shapeId + 1, + .generation = shape->generation, + }; + debugShape.type = shape->type; + + switch ( shape->type ) + { + case b3_capsuleShape: + debugShape.capsule = &shape->capsule; + shape->userShape = world->createDebugShape( &debugShape, world->userDebugShapeContext ); + break; + case b3_compoundShape: + debugShape.compound = shape->compound; + shape->userShape = world->createDebugShape( &debugShape, world->userDebugShapeContext ); + break; + case b3_heightShape: + debugShape.heightField = shape->heightField; + shape->userShape = world->createDebugShape( &debugShape, world->userDebugShapeContext ); + break; + case b3_hullShape: + debugShape.hull = shape->hull; + shape->userShape = world->createDebugShape( &debugShape, world->userDebugShapeContext ); + break; + case b3_meshShape: + debugShape.mesh = &shape->mesh; + shape->userShape = world->createDebugShape( &debugShape, world->userDebugShapeContext ); + break; + case b3_sphereShape: + debugShape.sphere = &shape->sphere; + shape->userShape = world->createDebugShape( &debugShape, world->userDebugShapeContext ); + break; + default: + B3_ASSERT( false ); + break; + } + } + + if ( shape->userShape != NULL ) + { + draw->DrawShapeFcn( shape->userShape, bodySim->transform, color, draw->context ); + } + } + + if ( draw->drawBounds ) + { + b3AABB aabb = shape->fatAABB; + draw->DrawBoundsFcn( aabb, b3_colorGold, draw->context ); + } + + return true; +} + +void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + B3_ASSERT( b3IsValidAABB( draw->drawingBounds ) ); + + const float axisScale = 0.3f * b3GetLengthUnitsPerMeter(); + b3HexColor farColor = b3_colorDarkBlue; + b3HexColor speculativeColor = b3_colorBlue; + b3HexColor addColor = b3_colorLimeGreen; + b3HexColor persistColor = b3_colorLightBlue; + // b3HexColor normalColors[3] = { b3_colorLightGray, b3_colorLightSalmon, b3_colorLightSeaGreen }; + b3HexColor impulseColor = b3_colorMagenta; + b3HexColor frictionColor = b3_colorYellow; + + b3HexColor graphColors[B3_GRAPH_COLOR_COUNT] = { + b3_colorRed, b3_colorOrange, b3_colorYellow, b3_colorGreen, b3_colorCyan, b3_colorBlue, + b3_colorViolet, b3_colorPink, b3_colorChocolate, b3_colorGoldenRod, b3_colorCoral, b3_colorRosyBrown, + b3_colorAqua, b3_colorPeru, b3_colorLime, b3_colorGold, b3_colorPlum, b3_colorSnow, + b3_colorTeal, b3_colorKhaki, b3_colorSalmon, b3_colorPeachPuff, b3_colorHoneyDew, b3_colorBlack, + }; + + int bodyCapacity = b3GetIdCapacity( &world->bodyIdPool ); + b3SetBitCountAndClear( &world->debugBodySet, bodyCapacity ); + + int jointCapacity = b3GetIdCapacity( &world->jointIdPool ); + b3SetBitCountAndClear( &world->debugJointSet, jointCapacity ); + + int contactCapacity = b3GetIdCapacity( &world->contactIdPool ); + b3SetBitCountAndClear( &world->debugContactSet, contactCapacity ); + + int islandCapacity = b3GetIdCapacity( &world->islandIdPool ); + b3SetBitCountAndClear( &world->debugIslandSet, islandCapacity ); + + struct DrawContext drawContext = { world, draw }; + + for ( int i = 0; i < b3_bodyTypeCount; ++i ) + { + b3DynamicTree_Query( world->broadPhase.trees + i, draw->drawingBounds, maskBits, false, DrawQueryCallback, &drawContext ); + } + + uint32_t wordCount = world->debugBodySet.blockCount; + uint64_t* bits = world->debugBodySet.bits; + for ( uint32_t wordIndex = 0; wordIndex < wordCount; ++wordIndex ) + { + uint64_t word = bits[wordIndex]; + while ( word != 0 ) + { + uint32_t ctz = b3CTZ64( word ); + int bodyId = (int)( 64 * wordIndex + ctz ); + + b3Body* body = b3Array_Get( world->bodies, bodyId ); + b3BodySim* bodySim = b3GetBodySim( world, body ); + + if ( draw->drawBodyNames && body->name[0] != 0 ) + { + b3Vec3 offset = { 0.05f, 0.05f, 0.05f }; + b3Transform transform = { bodySim->center, bodySim->transform.q }; + b3Vec3 p = b3TransformPoint( transform, offset ); + draw->DrawStringFcn( p, body->name, b3_colorOrange, draw->context ); + } + + if ( draw->drawMass && body->type == b3_dynamicBody ) + { + b3Vec3 offset = { 0.1f, 0.1f, 0.1f }; + + b3Transform transform = { bodySim->center, bodySim->transform.q }; + draw->DrawTransformFcn( transform, draw->context ); + b3Vec3 p = b3TransformPoint( transform, offset ); + + char buffer[32]; + snprintf( buffer, 32, " %.2f", body->mass ); + draw->DrawStringFcn( p, buffer, b3_colorWhite, draw->context ); + } + + if ( draw->drawJoints ) + { + int jointKey = body->headJointKey; + while ( jointKey != B3_NULL_INDEX ) + { + int jointId = jointKey >> 1; + int edgeIndex = jointKey & 1; + b3Joint* joint = b3Array_Get( world->joints, jointId ); + + // avoid double draw + if ( b3GetBit( &world->debugJointSet, jointId ) == false ) + { + b3DrawJoint( draw, world, joint ); + b3SetBit( &world->debugJointSet, jointId ); + } + + jointKey = joint->edges[edgeIndex].nextKey; + } + } + + const float speculativeDistance = B3_SPECULATIVE_DISTANCE; + if ( draw->drawContacts && body->type == b3_dynamicBody && body->setIndex == b3_awakeSet ) + { + int contactKey = body->headContactKey; + while ( contactKey != B3_NULL_INDEX ) + { + int contactId = contactKey >> 1; + int edgeIndex = contactKey & 1; + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + contactKey = contact->edges[edgeIndex].nextKey; + + if ( contact->setIndex != b3_awakeSet || contact->colorIndex == B3_NULL_INDEX ) + { + continue; + } + + // avoid double draw + if ( b3GetBit( &world->debugContactSet, contactId ) == false ) + { + b3Body* bodyA = b3Array_Get( world->bodies, contact->edges[0].bodyId ); + b3BodySim* bodySimA = b3GetBodySim( world, bodyA ); + b3Body* bodyB = b3Array_Get( world->bodies, contact->edges[1].bodyId ); + b3BodySim* bodySimB = b3GetBodySim( world, bodyB ); + + for ( int manifoldIndex = 0; manifoldIndex < contact->manifoldCount; ++manifoldIndex ) + { + const b3Manifold* manifold = contact->manifolds + manifoldIndex; + B3_ASSERT( manifold->pointCount > 0 ); + + b3Vec3 normal = manifold->normal; + b3Vec3 frictionCenter = b3Vec3_zero; + + const b3ManifoldPoint* points = manifold->points; + for ( int pointIndex = 0; pointIndex < manifold->pointCount; ++pointIndex ) + { + const b3ManifoldPoint* mp = points + pointIndex; + + char buffer[32]; + + b3Vec3 p; + if ( draw->drawAnchorA == 1 ) + { + p = b3Add( bodySimA->center, mp->anchorA ); + } + else + { + p = b3Add( bodySimB->center, mp->anchorB ); + } + + frictionCenter = b3Add( frictionCenter, p ); + + if ( draw->drawContactNormals ) + { + b3Vec3 p1 = p; + b3Vec3 p2 = b3MulAdd( p1, axisScale, normal ); + draw->DrawSegmentFcn( p1, p2, b3_colorLightGray, draw->context ); + + snprintf( buffer, B3_ARRAY_COUNT( buffer ), " %.2f", 100.0f * mp->separation ); + draw->DrawStringFcn( p, buffer, b3_colorWhite, draw->context ); + } + else if ( draw->drawContactForces ) + { + // Hack inv_dt for single step debugging + float inv_dt = world->inv_dt > 0.0f ? world->inv_dt : 60.0f; + // todo validate + // multiply by one-half due to relax iteration + float force = 0.5f * mp->totalNormalImpulse * inv_dt; + b3Vec3 p1 = p; + b3Vec3 p2 = b3MulAdd( p1, draw->forceScale * force, normal ); + draw->DrawSegmentFcn( p1, p2, impulseColor, draw->context ); + snprintf( buffer, B3_ARRAY_COUNT( buffer ), " %.1f", force ); + draw->DrawStringFcn( p1, buffer, b3_colorWhite, draw->context ); + } + else if ( draw->drawContactFeatures ) + { + snprintf( buffer, B3_ARRAY_COUNT( buffer ), " %#X", mp->featureId ); + draw->DrawStringFcn( p, buffer, b3_colorWhite, draw->context ); + } + + if ( draw->drawGraphColors ) + { + // graph color + float pointSize = contact->colorIndex == B3_OVERFLOW_INDEX ? 15.0f : 10.0f; + draw->DrawPointFcn( p, pointSize, graphColors[contact->colorIndex], draw->context ); + // g_draw.DrawString(point->position, "%d", point->color); + } + else if ( mp->persisted == false ) + { + // Add + draw->DrawPointFcn( p, 20.0f, addColor, draw->context ); + } + else if ( mp->separation > speculativeDistance ) + { + // Speculative + draw->DrawPointFcn( p, 10.0f, farColor, draw->context ); + } + else if ( mp->separation > 0.0f ) + { + // Speculative + draw->DrawPointFcn( p, 10.0f, speculativeColor, draw->context ); + } + else + { + // Persist + draw->DrawPointFcn( p, 10.0f, persistColor, draw->context ); + } + } + + if ( draw->drawContactForces ) + { + // Hack inv_dt for single step debugging + float inv_dt = world->inv_dt > 0.0f ? world->inv_dt : 60.0f; + + b3Vec3 p1 = b3MulSV( 1.0f / manifold->pointCount, frictionCenter ); + b3Vec3 frictionForce = b3MulSV( 0.5f * inv_dt, manifold->frictionImpulse ); + b3Vec3 p2 = b3MulAdd( p1, draw->forceScale, frictionForce ); + draw->DrawSegmentFcn( p1, p2, frictionColor, draw->context ); + draw->DrawPointFcn( p1, 5.0f, frictionColor, draw->context ); + + char buffer[32]; + snprintf( buffer, B3_ARRAY_COUNT( buffer ), " %.2f", b3Length( frictionForce ) ); + draw->DrawStringFcn( p1, buffer, b3_colorWhite, draw->context ); + } + } + + b3SetBit( &world->debugContactSet, contactId ); + } + + contactKey = contact->edges[edgeIndex].nextKey; + } + } + + if ( draw->drawIslands ) + { + int islandId = body->islandId; + if ( islandId != B3_NULL_INDEX && b3GetBit( &world->debugIslandSet, islandId ) == false ) + { + b3Island* island = world->islands.data + islandId; + if ( island->setIndex == B3_NULL_INDEX ) + { + continue; + } + + int shapeCount = 0; + b3AABB aabb = { + .lowerBound = { FLT_MAX, FLT_MAX, FLT_MAX }, + .upperBound = { -FLT_MAX, -FLT_MAX, -FLT_MAX }, + }; + + for ( int b = 0; b < island->bodies.count; ++b ) + { + int islandBodyId = island->bodies.data[b]; + b3Body* islandBody = b3Array_Get( world->bodies, islandBodyId ); + int shapeId = islandBody->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + aabb = b3AABB_Union( aabb, shape->fatAABB ); + shapeCount += 1; + shapeId = shape->nextShapeId; + } + } + + if ( shapeCount > 0 ) + { + draw->DrawBoundsFcn( aabb, b3_colorOrangeRed, draw->context ); + } + + b3SetBit( &world->debugIslandSet, islandId ); + } + } + + // Clear the smallest set bit + word = word & ( word - 1 ); + } + } + + char buffer[32] = { 0 }; + float lengthUnits = b3GetLengthUnitsPerMeter(); + b3Vec3 offset = { 0.002f * lengthUnits, 0.002f * lengthUnits, 0.002f * lengthUnits }; + for ( int i = 0; i < world->workerCount; ++i ) + { + int pointCount = world->taskContexts.data[i].pointCount; + b3DebugPoint* points = world->taskContexts.data[i].points; + for ( int j = 0; j < pointCount; ++j ) + { + b3DebugPoint* point = points + j; + draw->DrawPointFcn( point->p, 5.0f, point->color, draw->context ); + snprintf( buffer, 32, " %d, %.2f", point->label, point->value ); + b3Vec3 ps = b3Add( point->p, offset ); + draw->DrawStringFcn( ps, buffer, point->color, draw->context ); + } + + int lineCount = world->taskContexts.data[i].lineCount; + b3DebugLine* lines = world->taskContexts.data[i].lines; + for ( int j = 0; j < lineCount; ++j ) + { + b3DebugLine* line = lines + j; + draw->DrawSegmentFcn( line->p1, line->p2, line->color, draw->context ); + draw->DrawPointFcn( line->p1, 10.0f, line->color, draw->context ); + snprintf( buffer, 32, "%d", line->label ); + b3Vec3 ps = b3Add( line->p1, offset ); + draw->DrawStringFcn( ps, buffer, line->color, draw->context ); + } + } +} + +b3BodyEvents b3World_GetBodyEvents( b3WorldId worldId ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return (b3BodyEvents){ 0 }; + } + + int count = world->bodyMoveEvents.count; + b3BodyEvents events = { world->bodyMoveEvents.data, count }; + return events; +} + +b3SensorEvents b3World_GetSensorEvents( b3WorldId worldId ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return (b3SensorEvents){ 0 }; + } + + // Careful to use previous buffer + int endEventArrayIndex = 1 - world->endEventArrayIndex; + + int beginCount = world->sensorBeginEvents.count; + int endCount = world->sensorEndEvents[endEventArrayIndex].count; + + b3SensorEvents events = { + .beginEvents = world->sensorBeginEvents.data, + .endEvents = world->sensorEndEvents[endEventArrayIndex].data, + .beginCount = beginCount, + .endCount = endCount, + }; + return events; +} + +b3ContactEvents b3World_GetContactEvents( b3WorldId worldId ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return (b3ContactEvents){ 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; + + b3ContactEvents events = { + .beginEvents = world->contactBeginEvents.data, + .endEvents = world->contactEndEvents[endEventArrayIndex].data, + .hitEvents = world->contactHitEvents.data, + .beginCount = beginCount, + .endCount = endCount, + .hitCount = hitCount, + }; + + return events; +} + +b3JointEvents b3World_GetJointEvents( b3WorldId worldId ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return (b3JointEvents){ 0 }; + } + + int count = world->jointEvents.count; + b3JointEvents events = { world->jointEvents.data, count }; + return events; +} + +bool b3World_IsValid( b3WorldId id ) +{ + if ( id.index1 < 1 || B3_MAX_WORLDS < id.index1 ) + { + return false; + } + + b3World* world = b3_worlds + ( id.index1 - 1 ); + + if ( world->worldId != id.index1 - 1 ) + { + // world is not allocated + return false; + } + + return id.generation == world->generation; +} + +bool b3Body_IsValid( b3BodyId id ) +{ + if ( B3_MAX_WORLDS <= id.world0 ) + { + // invalid world + return false; + } + + b3World* world = b3_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; + } + + b3Body* body = world->bodies.data + ( id.index1 - 1 ); + if ( body->setIndex == B3_NULL_INDEX ) + { + // this was freed + return false; + } + + B3_ASSERT( body->localIndex != B3_NULL_INDEX ); + + if ( body->generation != id.generation ) + { + // this id is orphaned + return false; + } + + return true; +} + +bool b3Shape_IsValid( b3ShapeId id ) +{ + if ( B3_MAX_WORLDS <= id.world0 ) + { + return false; + } + + b3World* world = b3_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; + } + + b3Shape* shape = world->shapes.data + shapeId; + if ( shape->id == B3_NULL_INDEX ) + { + // shape is free + return false; + } + + B3_ASSERT( shape->id == shapeId ); + + return id.generation == shape->generation; +} + +bool b3Joint_IsValid( b3JointId id ) +{ + if ( B3_MAX_WORLDS <= id.world0 ) + { + return false; + } + + b3World* world = b3_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; + } + + b3Joint* joint = world->joints.data + jointId; + if ( joint->jointId == B3_NULL_INDEX ) + { + // joint is free + return false; + } + + B3_ASSERT( joint->jointId == jointId ); + + return id.generation == joint->generation; +} + +bool b3Contact_IsValid( b3ContactId id ) +{ + if ( B3_MAX_WORLDS <= id.world0 ) + { + return false; + } + + b3World* world = b3_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; + } + + b3Contact* contact = world->contacts.data + contactId; + if ( contact->contactId == B3_NULL_INDEX ) + { + // contact is free + return false; + } + + B3_ASSERT( contact->contactId == contactId ); + + return id.generation == contact->generation; +} + +void b3World_EnableSleeping( b3WorldId worldId, bool flag ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + if ( flag == world->enableSleep ) + { + return; + } + + world->enableSleep = flag; + + if ( flag == false ) + { + int setCount = world->solverSets.count; + for ( int i = b3_firstSleepingSet; i < setCount; ++i ) + { + b3SolverSet* set = b3Array_Get( world->solverSets, i ); + if ( set->bodySims.count > 0 ) + { + b3WakeSolverSet( world, i ); + } + } + } +} + +bool b3World_IsSleepingEnabled( b3WorldId worldId ) +{ + b3World* world = b3GetWorldFromId( worldId ); + return world->enableSleep; +} + +void b3World_EnableWarmStarting( b3WorldId worldId, bool flag ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + world->enableWarmStarting = flag; +} + +bool b3World_IsWarmStartingEnabled( b3WorldId worldId ) +{ + b3World* world = b3GetWorldFromId( worldId ); + return world->enableWarmStarting; +} + +int b3World_GetAwakeBodyCount( b3WorldId worldId ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return 0; + } + b3SolverSet* awakeSet = b3Array_Get( world->solverSets, b3_awakeSet ); + return awakeSet->bodySims.count; +} + +void b3World_EnableContinuous( b3WorldId worldId, bool flag ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + world->enableContinuous = flag; +} + +bool b3World_IsContinuousEnabled( b3WorldId worldId ) +{ + b3World* world = b3GetWorldFromId( worldId ); + return world->enableContinuous; +} + +void b3World_SetRestitutionThreshold( b3WorldId worldId, float value ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + world->restitutionThreshold = b3ClampFloat( value, 0.0f, FLT_MAX ); +} + +float b3World_GetRestitutionThreshold( b3WorldId worldId ) +{ + b3World* world = b3GetWorldFromId( worldId ); + return world->restitutionThreshold; +} + +void b3World_SetHitEventThreshold( b3WorldId worldId, float value ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + world->hitEventThreshold = b3ClampFloat( value, 0.0f, FLT_MAX ); +} + +float b3World_GetHitEventThreshold( b3WorldId worldId ) +{ + b3World* world = b3GetWorldFromId( worldId ); + return world->hitEventThreshold; +} + +void b3World_SetContactTuning( b3WorldId worldId, float hertz, float dampingRatio, float contactSpeed ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + world->contactHertz = b3ClampFloat( hertz, 0.0f, FLT_MAX ); + world->contactDampingRatio = b3ClampFloat( dampingRatio, 0.0f, FLT_MAX ); + world->contactSpeed = b3ClampFloat( contactSpeed, 0.0f, FLT_MAX ); +} + +void b3World_SetContactRecycleDistance( b3WorldId worldId, float recycleDistance ) +{ + b3World* world = b3GetWorldFromId( worldId ); + B3_ASSERT( world->locked == false ); + if ( world->locked ) + { + return; + } + + world->contactRecycleDistance = b3ClampFloat( recycleDistance, 0.0f, FLT_MAX ); +} + +float b3World_GetContactRecycleDistance( b3WorldId worldId ) +{ + b3World* world = b3GetWorldFromId( worldId ); + return world->contactRecycleDistance; +} + +void b3World_SetMaximumLinearSpeed( b3WorldId worldId, float maximumLinearSpeed ) +{ + B3_ASSERT( b3IsValidFloat( maximumLinearSpeed ) && maximumLinearSpeed > 0.0f ); + + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + world->maxLinearSpeed = maximumLinearSpeed; +} + +float b3World_GetMaximumLinearSpeed( b3WorldId worldId ) +{ + b3World* world = b3GetWorldFromId( worldId ); + return world->maxLinearSpeed; +} + +b3Profile b3World_GetProfile( b3WorldId worldId ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return (b3Profile){ 0 }; + } + return world->profile; +} + +b3Counters b3World_GetCounters( b3WorldId worldId ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return (b3Counters){ 0 }; + } + + b3Counters s = { 0 }; + s.bodyCount = b3GetIdCount( &world->bodyIdPool ); + s.shapeCount = b3GetIdCount( &world->shapeIdPool ); + s.contactCount = b3GetIdCount( &world->contactIdPool ); + s.jointCount = b3GetIdCount( &world->jointIdPool ); + s.islandCount = b3GetIdCount( &world->islandIdPool ); + + b3DynamicTree* staticTree = world->broadPhase.trees + b3_staticBody; + s.staticTreeHeight = b3DynamicTree_GetHeight( staticTree ); + + b3DynamicTree* dynamicTree = world->broadPhase.trees + b3_dynamicBody; + b3DynamicTree* kinematicTree = world->broadPhase.trees + b3_kinematicBody; + s.treeHeight = b3MaxInt( b3DynamicTree_GetHeight( dynamicTree ), b3DynamicTree_GetHeight( kinematicTree ) ); + + s.satCallCount = world->satCallCount; + s.satCacheHitCount = world->satCacheHitCount; + memcpy( s.manifoldCounts, world->manifoldCounts, B3_CONTACT_MANIFOLD_COUNT_BUCKETS * sizeof( int ) ); + s.stackUsed = world->stack.maxAllocation; + s.byteCount = b3GetByteCount(); + s.taskCount = world->taskCount; + + _Static_assert( B3_GRAPH_COLOR_COUNT == sizeof( s.colorCounts ) / sizeof( s.colorCounts[0] ), "colorCounts size mismatch" ); + + s.awakeContactCount = 0; + for ( int i = 0; i < B3_GRAPH_COLOR_COUNT; ++i ) + { + b3GraphColor* color = world->constraintGraph.colors + i; + int colorContactCount = color->convexContacts.count + color->contacts.count; + s.colorCounts[i] = colorContactCount + color->jointSims.count; + s.awakeContactCount += colorContactCount; + } + s.awakeContactCount += world->solverSets.data[b3_awakeSet].contactIndices.count; + + s.recycledContactCount = 0; + for ( int i = 0; i < world->workerCount; ++i ) + { + s.recycledContactCount += world->taskContexts.data[i].recycledContactCount; + } + + return s; +} + +b3Capacity b3World_GetMaxCapacity( b3WorldId worldId ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return (b3Capacity){ 0 }; + } + return world->maxCapacity; +} + +void b3World_SetUserData( b3WorldId worldId, void* userData ) +{ + b3World* world = b3GetWorldFromId( worldId ); + world->userData = userData; +} + +void* b3World_GetUserData( b3WorldId worldId ) +{ + b3World* world = b3GetWorldFromId( worldId ); + return world->userData; +} + +void b3World_SetWorkerCount( b3WorldId worldId, int count ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + if ( count == world->workerCount ) + { + return; + } + + b3DestroyWorkerContexts( world ); + world->workerCount = b3ClampInt( count, 1, B3_MAX_WORKERS ); + b3CreateWorkerContexts( world ); +} + +int b3World_GetWorkerCount( b3WorldId worldId ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return 0; + } + + return world->workerCount; +} + +static FILE* b3OpenFile( const char* fileName ) +{ + FILE* file = NULL; + +#if defined( _MSC_VER ) + errno_t e = fopen_s( &file, fileName, "w" ); + if ( e != 0 ) + { + return NULL; + } +#else + file = fopen( fileName, "w" ); +#endif + + return file; +} + +void b3World_DumpMemoryStats( b3WorldId worldId ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + FILE* file = b3OpenFile( "box3d_memory.txt" ); + if ( file == NULL ) + { + return; + } + + // id pools + fprintf( file, "id pools\n" ); + fprintf( file, "body ids: %d\n", b3GetIdBytes( &world->bodyIdPool ) ); + fprintf( file, "solver set ids: %d\n", b3GetIdBytes( &world->solverSetIdPool ) ); + fprintf( file, "joint ids: %d\n", b3GetIdBytes( &world->jointIdPool ) ); + fprintf( file, "contact ids: %d\n", b3GetIdBytes( &world->contactIdPool ) ); + fprintf( file, "island ids: %d\n", b3GetIdBytes( &world->islandIdPool ) ); + fprintf( file, "shape ids: %d\n", b3GetIdBytes( &world->shapeIdPool ) ); + fprintf( file, "\n" ); + + // world arrays + fprintf( file, "world arrays\n" ); + fprintf( file, "bodies: %d\n", b3Array_ByteCount( world->bodies ) ); + fprintf( file, "solver sets: %d\n", b3Array_ByteCount( world->solverSets ) ); + fprintf( file, "joints: %d\n", b3Array_ByteCount( world->joints ) ); + fprintf( file, "contacts: %d\n", b3Array_ByteCount( world->contacts ) ); + fprintf( file, "islands: %d\n", b3Array_ByteCount( world->islands ) ); + fprintf( file, "shapes: %d\n", b3Array_ByteCount( world->shapes ) ); + fprintf( file, "\n" ); + + // broad-phase + fprintf( file, "broad-phase\n" ); + fprintf( file, "static tree: %d\n", b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_staticBody ) ); + fprintf( file, "kinematic tree: %d\n", b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_kinematicBody ) ); + fprintf( file, "dynamic tree: %d\n", b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_dynamicBody ) ); + b3HashSet* moveSet = &world->broadPhase.moveSet; + fprintf( file, "moveSet: %d (%d, %d)\n", b3GetHashSetBytes( moveSet ), moveSet->count, moveSet->capacity ); + fprintf( file, "moveArray: %d\n", b3Array_ByteCount( world->broadPhase.moveArray ) ); + b3HashSet* pairSet = &world->broadPhase.pairSet; + fprintf( file, "pairSet: %d (%d, %d)\n", b3GetHashSetBytes( pairSet ), pairSet->count, pairSet->capacity ); + fprintf( file, "\n" ); + + // solver sets + int bodySimCapacity = 0; + int bodyStateCapacity = 0; + int jointSimCapacity = 0; + int contactIndexCapacity = 0; + int islandSimCapacity = 0; + int solverSetCapacity = world->solverSets.count; + for ( int i = 0; i < solverSetCapacity; ++i ) + { + b3SolverSet* set = world->solverSets.data + i; + if ( set->setIndex == B3_NULL_INDEX ) + { + continue; + } + + bodySimCapacity += set->bodySims.capacity; + bodyStateCapacity += set->bodyStates.capacity; + jointSimCapacity += set->jointSims.capacity; + contactIndexCapacity += set->contactIndices.capacity; + islandSimCapacity += set->islandSims.capacity; + } + + fprintf( file, "solver sets\n" ); + fprintf( file, "body sim: %d\n", bodySimCapacity * (int)sizeof( b3BodySim ) ); + fprintf( file, "body state: %d\n", bodyStateCapacity * (int)sizeof( b3BodyState ) ); + fprintf( file, "joint sim: %d\n", jointSimCapacity * (int)sizeof( b3JointSim ) ); + fprintf( file, "contact sim: %d\n", contactIndexCapacity * (int)sizeof( int ) ); + fprintf( file, "island sim: %d\n", islandSimCapacity * (int)sizeof( islandSimCapacity ) ); + fprintf( file, "\n" ); + + // constraint graph + int bodyBitSetBytes = 0; + int contactSpecCapacity = 0; + jointSimCapacity = 0; + for ( int i = 0; i < B3_GRAPH_COLOR_COUNT; ++i ) + { + b3GraphColor* c = world->constraintGraph.colors + i; + bodyBitSetBytes += b3GetBitSetBytes( &c->bodySet ); + contactSpecCapacity += c->convexContacts.capacity + c->contacts.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( b3JointSim ) ); + fprintf( file, "contact sim: %d\n", contactSpecCapacity * (int)sizeof( int ) ); + fprintf( file, "\n" ); + + // stack allocator + fprintf( file, "stack allocator: %d\n\n", world->stack.capacity ); + + fclose( file ); +} + +void b3World_DumpShapeBounds( b3WorldId worldId, b3BodyType type ) +{ + B3_ASSERT( b3_staticBody <= type && type <= b3_dynamicBody ); + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + FILE* file = b3OpenFile( "box3d_bounds.txt" ); + if ( file == NULL ) + { + return; + } + + b3DynamicTree* tree = world->broadPhase.trees + type; + b3TreeNode* nodes = tree->nodes; + + uint16_t requiredFlags = b3_allocatedNode | b3_leafNode; + int capacity = tree->nodeCapacity; + for ( int i = 0; i < capacity; ++i ) + { + b3TreeNode* node = nodes + i; + if ( ( node->flags & requiredFlags ) != requiredFlags ) + { + // skip internal and free nodes + continue; + } + + b3Vec3 a = node->aabb.lowerBound; + b3Vec3 b = node->aabb.upperBound; + fprintf( file, "%.9f %.9f %.9f %.9f %.9f %.9f\n", a.x, a.y, a.z, b.x, b.y, b.z ); + } + + fclose( file ); +} + +typedef struct WorldQueryContext +{ + b3World* world; + b3OverlapResultFcn* fcn; + b3QueryFilter filter; + void* userContext; +} WorldQueryContext; + +static bool TreeQueryCallback( int proxyId, uint64_t userData, void* context ) +{ + B3_UNUSED( proxyId ); + + int shapeId = (int)userData; + WorldQueryContext* worldContext = (WorldQueryContext*)context; + b3World* world = worldContext->world; + + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + + b3Filter shapeFilter = shape->filter; + b3QueryFilter queryFilter = worldContext->filter; + + if ( b3ShouldQueryCollide( &shapeFilter, &queryFilter ) == false ) + { + return true; + } + + b3ShapeId id = { shapeId + 1, world->worldId, shape->generation }; + bool result = worldContext->fcn( id, worldContext->userContext ); + return result; +} + +b3TreeStats b3World_OverlapAABB( b3WorldId worldId, b3AABB aabb, b3QueryFilter filter, b3OverlapResultFcn* fcn, void* context ) +{ + b3TreeStats treeStats = { 0 }; + + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return treeStats; + } + + B3_ASSERT( b3IsValidAABB( aabb ) ); + + WorldQueryContext worldContext = { world, fcn, filter, context }; + + for ( int i = 0; i < b3_bodyTypeCount; ++i ) + { + b3TreeStats treeResult = + b3DynamicTree_Query( world->broadPhase.trees + i, aabb, filter.maskBits, false, TreeQueryCallback, &worldContext ); + + treeStats.nodeVisits += treeResult.nodeVisits; + treeStats.leafVisits += treeResult.leafVisits; + } + + return treeStats; +} + +typedef struct WorldOverlapContext +{ + b3World* world; + b3OverlapResultFcn* fcn; + b3QueryFilter filter; + b3ShapeProxy proxy; + void* userContext; +} WorldOverlapContext; + +static bool b3TreeOverlapCallback( int proxyId, uint64_t userData, void* context ) +{ + B3_UNUSED( proxyId ); + + int shapeId = (int)userData; + WorldOverlapContext* worldContext = (WorldOverlapContext*)context; + b3World* world = worldContext->world; + + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + + b3Filter shapeFilter = shape->filter; + b3QueryFilter queryFilter = worldContext->filter; + + if ( b3ShouldQueryCollide( &shapeFilter, &queryFilter ) == false ) + { + return true; + } + + b3Body* body = b3Array_Get( world->bodies, shape->bodyId ); + b3Transform transform = b3GetBodyTransformQuick( world, body ); + + bool overlapping = b3OverlapShape( shape, transform, &worldContext->proxy ); + if ( overlapping == false ) + { + return true; + } + + b3ShapeId id = { shape->id + 1, world->worldId, shape->generation }; + bool result = worldContext->fcn( id, worldContext->userContext ); + return result; +} + +b3TreeStats b3World_OverlapShape( b3WorldId worldId, const b3ShapeProxy* proxy, b3QueryFilter filter, b3OverlapResultFcn* fcn, + void* context ) +{ + b3TreeStats treeStats = { 0 }; + + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return treeStats; + } + + b3AABB aabb = b3MakeAABB( proxy->points, proxy->count, proxy->radius ); + WorldOverlapContext worldContext = { + world, fcn, filter, *proxy, context, + }; + + for ( int i = 0; i < b3_bodyTypeCount; ++i ) + { + b3TreeStats treeResult = b3DynamicTree_Query( world->broadPhase.trees + i, aabb, filter.maskBits, false, + b3TreeOverlapCallback, &worldContext ); + + treeStats.nodeVisits += treeResult.nodeVisits; + treeStats.leafVisits += treeResult.leafVisits; + } + + return treeStats; +} + +typedef struct WorldMoverContext +{ + b3World* world; + b3PlaneResultFcn* fcn; + b3QueryFilter filter; + b3Capsule mover; + void* userContext; +} WorldMoverContext; + +static bool TreeCollideCallback( int proxyId, uint64_t userData, void* context ) +{ + B3_UNUSED( proxyId ); + + int shapeId = (int)userData; + WorldMoverContext* worldContext = (WorldMoverContext*)context; + b3World* world = worldContext->world; + + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + + b3Filter shapeFilter = shape->filter; + b3QueryFilter queryFilter = worldContext->filter; + + if ( b3ShouldQueryCollide( &shapeFilter, &queryFilter ) == false ) + { + return true; + } + + b3Body* body = b3Array_Get( world->bodies, shape->bodyId ); + b3Transform transform = b3GetBodyTransformQuick( world, body ); + + b3PlaneResult buffer[64]; + int count = b3CollideMover( buffer, 64, shape, transform, &worldContext->mover ); + + if ( count > 0 ) + { + b3ShapeId id = { shape->id + 1, world->worldId, shape->generation }; + return worldContext->fcn( id, buffer, count, 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 b3World_CollideMover( b3WorldId worldId, const b3Capsule* mover, b3QueryFilter filter, b3PlaneResultFcn* fcn, void* context ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + b3Vec3 r = { mover->radius, mover->radius, mover->radius }; + + b3AABB aabb; + aabb.lowerBound = b3Sub( b3Min( mover->center1, mover->center2 ), r ); + aabb.upperBound = b3Add( b3Max( mover->center1, mover->center2 ), r ); + + WorldMoverContext worldContext = { + world, fcn, filter, *mover, context, + }; + + for ( int i = 0; i < b3_bodyTypeCount; ++i ) + { + b3DynamicTree_Query( world->broadPhase.trees + i, aabb, filter.maskBits, false, TreeCollideCallback, &worldContext ); + } +} + +typedef struct WorldRayCastContext +{ + b3World* world; + b3CastResultFcn* fcn; + b3QueryFilter filter; + float fraction; + void* userContext; +} WorldRayCastContext; + +static float RayCastCallback( const b3RayCastInput* input, int proxyId, uint64_t userData, void* context ) +{ + B3_UNUSED( proxyId ); + + int shapeId = (int)userData; + WorldRayCastContext* worldContext = (WorldRayCastContext*)context; + b3World* world = worldContext->world; + + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + b3Filter shapeFilter = shape->filter; + b3QueryFilter queryFilter = worldContext->filter; + + if ( b3ShouldQueryCollide( &shapeFilter, &queryFilter ) == false ) + { + return input->maxFraction; + } + + b3Body* body = b3Array_Get( world->bodies, shape->bodyId ); + b3Transform transform = b3GetBodyTransformQuick( world, body ); + b3CastOutput output = b3RayCastShape( shape, transform, input ); + + if ( output.hit ) + { + B3_ASSERT( output.fraction <= input->maxFraction ); + + b3ShapeId id = { shapeId + 1, world->worldId, shape->generation }; + + int materialIndex = b3ClampInt( output.materialIndex, 0, shape->materialCount - 1 ); + uint64_t userMaterialId = shape->materials[materialIndex].userMaterialId; + + int triangleIndex = output.triangleIndex; + int childIndex = output.childIndex; + float fraction = worldContext->fcn( id, output.point, output.normal, output.fraction, userMaterialId, triangleIndex, + childIndex, 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; +} + +b3TreeStats b3World_CastRay( b3WorldId worldId, b3Vec3 origin, b3Vec3 translation, b3QueryFilter filter, b3CastResultFcn* fcn, + void* context ) +{ + b3TreeStats treeStats = { 0 }; + + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return treeStats; + } + + B3_ASSERT( b3IsValidVec3( origin ) ); + B3_ASSERT( b3IsValidVec3( translation ) ); + + b3RayCastInput input = { origin, translation, 1.0f }; + + WorldRayCastContext worldContext = { world, fcn, filter, 1.0f, context }; + + for ( int i = 0; i < b3_bodyTypeCount; ++i ) + { + b3TreeStats treeResult = + b3DynamicTree_RayCast( world->broadPhase.trees + i, &input, filter.maskBits, false, 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 b3RayCastClosestFcn( b3ShapeId shapeId, b3Vec3 point, b3Vec3 normal, float fraction, uint64_t userMaterialId, + int triangleIndex, int childIndex, void* context ) +{ + // Ignore initial overlap + if ( fraction == 0.0f ) + { + return -1.0f; + } + + b3RayResult* rayResult = (b3RayResult*)context; + rayResult->shapeId = shapeId; + rayResult->point = point; + rayResult->normal = normal; + rayResult->fraction = fraction; + rayResult->userMaterialId = userMaterialId; + rayResult->triangleIndex = triangleIndex; + rayResult->childIndex = childIndex; + rayResult->hit = true; + return fraction; +} + +b3RayResult b3World_CastRayClosest( b3WorldId worldId, b3Vec3 origin, b3Vec3 translation, b3QueryFilter filter ) +{ + b3RayResult result = { 0 }; + + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return result; + } + + B3_ASSERT( b3IsValidVec3( origin ) ); + B3_ASSERT( b3IsValidVec3( translation ) ); + + b3RayCastInput input = { origin, translation, 1.0f }; + WorldRayCastContext worldContext = { + .world = world, + .fcn = b3RayCastClosestFcn, + .filter = filter, + .fraction = 1.0f, + .userContext = &result, + }; + + for ( int i = 0; i < b3_bodyTypeCount; ++i ) + { + b3TreeStats treeResult = + b3DynamicTree_RayCast( world->broadPhase.trees + i, &input, filter.maskBits, false, 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 b3ShapeCastCallback( const b3ShapeCastInput* input, int proxyId, uint64_t userData, void* context ) +{ + B3_UNUSED( proxyId ); + + int shapeId = (int)userData; + WorldRayCastContext* worldContext = (WorldRayCastContext*)context; + b3World* world = worldContext->world; + + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + b3Filter shapeFilter = shape->filter; + b3QueryFilter queryFilter = worldContext->filter; + + if ( b3ShouldQueryCollide( &shapeFilter, &queryFilter ) == false ) + { + return input->maxFraction; + } + + b3Body* body = b3Array_Get( world->bodies, shape->bodyId ); + b3Transform transform = b3GetBodyTransformQuick( world, body ); + + b3CastOutput output = b3ShapeCastShape( shape, transform, input ); + + if ( output.hit ) + { + b3ShapeId id = { shapeId + 1, world->worldId, shape->generation }; + int materialIndex = b3ClampInt( output.materialIndex, 0, shape->materialCount - 1 ); + uint64_t userMaterialId = shape->materials[materialIndex].userMaterialId; + + int triangleIndex = output.triangleIndex; + int childIndex = output.childIndex; + float fraction = worldContext->fcn( id, output.point, output.normal, output.fraction, userMaterialId, triangleIndex, + childIndex, 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; +} + +b3TreeStats b3World_CastShape( b3WorldId worldId, const b3ShapeProxy* proxy, b3Vec3 translation, b3QueryFilter filter, + b3CastResultFcn* fcn, void* context ) +{ + b3TreeStats treeStats = { 0 }; + + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return treeStats; + } + + B3_ASSERT( b3IsValidVec3( translation ) ); + + b3ShapeCastInput input; + input.proxy = *proxy; + input.translation = translation; + input.maxFraction = 1.0f; + input.canEncroach = false; + + WorldRayCastContext worldContext = { world, fcn, filter, 1.0f, context }; + + for ( int i = 0; i < b3_bodyTypeCount; ++i ) + { + b3TreeStats treeResult = b3DynamicTree_ShapeCast( world->broadPhase.trees + i, &input, filter.maskBits, false, + b3ShapeCastCallback, &worldContext ); + treeStats.nodeVisits += treeResult.nodeVisits; + treeStats.leafVisits += treeResult.leafVisits; + + if ( worldContext.fraction == 0.0f ) + { + return treeStats; + } + + input.maxFraction = worldContext.fraction; + } + + return treeStats; +} + +typedef struct WorldMoverCastContext +{ + b3World* world; + b3MoverFilterFcn* fcn; + b3QueryFilter filter; + float fraction; + void* userContext; +} WorldMoverCastContext; + +static float MoverCastCallback( const b3ShapeCastInput* input, int proxyId, uint64_t userData, void* context ) +{ + B3_UNUSED( proxyId ); + + int shapeId = (int)userData; + WorldMoverCastContext* worldContext = (WorldMoverCastContext*)context; + b3World* world = worldContext->world; + + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + b3Filter shapeFilter = shape->filter; + b3QueryFilter queryFilter = worldContext->filter; + + if ( b3ShouldQueryCollide( &shapeFilter, &queryFilter ) == false ) + { + return worldContext->fraction; + } + + if ( worldContext->fcn != NULL ) + { + b3ShapeId id = { shapeId + 1, world->worldId, shape->generation }; + bool shouldCollide = worldContext->fcn( id, worldContext->userContext ); + if ( shouldCollide == false ) + { + return worldContext->fraction; + } + } + + b3Body* body = b3Array_Get( world->bodies, shape->bodyId ); + b3Transform transform = b3GetBodyTransformQuick( world, body ); + + b3CastOutput output = b3ShapeCastShape( shape, transform, input ); + if ( output.fraction == 0.0f ) + { + // Ignore overlapping shapes + return worldContext->fraction; + } + + worldContext->fraction = output.fraction; + return output.fraction; +} + +float b3World_CastMover( b3WorldId worldId, const b3Capsule* mover, b3Vec3 translation, b3QueryFilter filter, + b3MoverFilterFcn* fcn, void* context ) +{ + B3_ASSERT( b3IsValidVec3( translation ) ); + + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return 1.0f; + } + + b3ShapeCastInput input; + input.proxy = (b3ShapeProxy){ &mover->center1, 2, mover->radius }; + input.translation = translation; + input.maxFraction = 1.0f; + input.canEncroach = mover->radius > 0.0f; + + WorldMoverCastContext worldContext = { + .world = world, + .fcn = fcn, + .filter = filter, + .fraction = 1.0f, + .userContext = context, + }; + + for ( int i = 0; i < b3_bodyTypeCount; ++i ) + { + b3DynamicTree_ShapeCast( world->broadPhase.trees + i, &input, filter.maskBits, false, MoverCastCallback, &worldContext ); + + if ( worldContext.fraction == 0.0f ) + { + return 0.0f; + } + + input.maxFraction = worldContext.fraction; + } + + return worldContext.fraction; +} + +void b3World_SetCustomFilterCallback( b3WorldId worldId, b3CustomFilterFcn* fcn, void* context ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + world->customFilterFcn = fcn; + world->customFilterContext = context; +} + +void b3World_SetPreSolveCallback( b3WorldId worldId, b3PreSolveFcn* fcn, void* context ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + world->preSolveFcn = fcn; + world->preSolveContext = context; +} + +void b3World_SetGravity( b3WorldId worldId, b3Vec3 gravity ) +{ + b3World* world = b3GetWorldFromId( worldId ); + world->gravity = gravity; +} + +b3Vec3 b3World_GetGravity( b3WorldId worldId ) +{ + b3World* world = b3GetWorldFromId( worldId ); + return world->gravity; +} + +typedef struct ExplosionContext +{ + b3World* world; + b3Vec3 position; + float radius; + float falloff; + float impulsePerArea; +} ExplosionContext; + +static bool ExplosionCallback( int proxyId, uint64_t userData, void* context ) +{ + B3_UNUSED( proxyId ); + + int shapeId = (int)userData; + ExplosionContext* explosionContext = (ExplosionContext*)context; + b3World* world = explosionContext->world; + + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + if ( shape->explosionScale == 0.0f ) + { + return true; + } + + b3Body* body = b3Array_Get( world->bodies, shape->bodyId ); + B3_ASSERT( body->type == b3_dynamicBody ); + + b3Transform transform = b3GetBodyTransformQuick( world, body ); + + b3DistanceInput input; + input.proxyA = b3MakeShapeProxy( shape ); + input.proxyB = (b3ShapeProxy){ &explosionContext->position, 1, 0.0f }; + input.transformA = transform; + input.transformB = b3Transform_identity; + input.useRadii = true; + + b3SimplexCache cache = { 0 }; + b3DistanceOutput output = b3ShapeDistance( &input, &cache, NULL, 0 ); + + float radius = explosionContext->radius; + float falloff = explosionContext->falloff; + if ( output.distance > radius + falloff ) + { + return true; + } + + b3WakeBody( world, body ); + + if ( body->setIndex != b3_awakeSet ) + { + return true; + } + + b3Vec3 closestPoint = output.pointA; + if ( output.distance == 0.0f ) + { + b3Vec3 localCentroid = b3GetShapeCentroid( shape ); + closestPoint = b3TransformPoint( transform, localCentroid ); + } + + b3Vec3 direction = b3Sub( closestPoint, explosionContext->position ); + if ( b3LengthSquared( direction ) > 100.0f * FLT_EPSILON * FLT_EPSILON ) + { + direction = b3Normalize( direction ); + } + else + { + direction = (b3Vec3){ 1.0f, 0.0f, 0.0f }; + } + + float area = b3GetShapeProjectedArea( shape, direction ); + float scale = 1.0f; + if ( output.distance > radius && falloff > 0.0f ) + { + scale = b3ClampFloat( ( radius + falloff - output.distance ) / falloff, 0.0f, 1.0f ); + } + + float magnitude = explosionContext->impulsePerArea * area * scale * shape->explosionScale; + b3Vec3 impulse = b3MulSV( magnitude, direction ); + + int localIndex = body->localIndex; + b3SolverSet* set = b3Array_Get( world->solverSets, b3_awakeSet ); + b3BodyState* state = b3Array_Get( set->bodyStates, localIndex ); + b3BodySim* bodySim = b3Array_Get( set->bodySims, localIndex ); + state->linearVelocity = b3MulAdd( state->linearVelocity, bodySim->invMass, impulse ); + state->angularVelocity = b3Add( + state->angularVelocity, b3MulMV( bodySim->invInertiaWorld, b3Cross( b3Sub( closestPoint, bodySim->center ), impulse ) ) ); + + return true; +} + +void b3World_Explode( b3WorldId worldId, const b3ExplosionDef* explosionDef ) +{ + uint64_t maskBits = explosionDef->maskBits; + b3Vec3 position = explosionDef->position; + float radius = explosionDef->radius; + float falloff = explosionDef->falloff; + float impulsePerArea = explosionDef->impulsePerArea; + + B3_ASSERT( b3IsValidVec3( position ) ); + B3_ASSERT( b3IsValidFloat( radius ) && radius >= 0.0f ); + B3_ASSERT( b3IsValidFloat( falloff ) && falloff >= 0.0f ); + B3_ASSERT( b3IsValidFloat( impulsePerArea ) ); + + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + // Locked due to waking + world->locked = true; + + struct ExplosionContext explosionContext = { world, position, radius, falloff, impulsePerArea }; + + float totalRadius = radius + falloff; + b3Vec3 r = { totalRadius, totalRadius, totalRadius }; + b3AABB aabb = { b3Sub( position, r ), b3Add( position, r ) }; + + b3DynamicTree_Query( world->broadPhase.trees + b3_dynamicBody, aabb, maskBits, false, ExplosionCallback, &explosionContext ); + + world->locked = false; +} + +void b3World_RebuildStaticTree( b3WorldId worldId ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + b3DynamicTree* staticTree = world->broadPhase.trees + b3_staticBody; + b3DynamicTree_Rebuild( staticTree, true ); +} + +void b3World_EnableSpeculative( b3WorldId worldId, bool flag ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + world->enableSpeculative = flag; +} + +#if B3_ENABLE_VALIDATION +// This validates island graph connectivity for each body +void b3ValidateConnectivity( b3World* world ) +{ + b3Body* bodies = world->bodies.data; + int bodyCapacity = world->bodies.count; + + for ( int bodyIndex = 0; bodyIndex < bodyCapacity; ++bodyIndex ) + { + b3Body* body = bodies + bodyIndex; + if ( body->id == B3_NULL_INDEX ) + { + b3ValidateFreeId( &world->bodyIdPool, bodyIndex ); + continue; + } + + B3_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 != B3_NULL_INDEX ) + { + int contactId = contactKey >> 1; + int edgeIndex = contactKey & 1; + + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + + bool touching = ( contact->flags & b3_contactTouchingFlag ) != 0; + if ( touching ) + { + if ( bodySetIndex != b3_staticSet ) + { + int contactIslandId = contact->islandId; + B3_ASSERT( contactIslandId == bodyIslandId ); + } + } + else + { + B3_ASSERT( contact->islandId == B3_NULL_INDEX ); + } + + contactKey = contact->edges[edgeIndex].nextKey; + } + + int jointKey = body->headJointKey; + while ( jointKey != B3_NULL_INDEX ) + { + int jointId = jointKey >> 1; + int edgeIndex = jointKey & 1; + + b3Joint* joint = b3Array_Get( world->joints, jointId ); + + int otherEdgeIndex = edgeIndex ^ 1; + + b3Body* otherBody = b3Array_Get( world->bodies, joint->edges[otherEdgeIndex].bodyId ); + + if ( bodySetIndex == b3_disabledSet || otherBody->setIndex == b3_disabledSet ) + { + B3_ASSERT( joint->islandId == B3_NULL_INDEX ); + } + else if ( bodySetIndex == b3_staticSet ) + { + // Intentional nesting + if ( otherBody->setIndex == b3_staticSet ) + { + B3_ASSERT( joint->islandId == B3_NULL_INDEX ); + } + } + else if ( body->type != b3_dynamicBody && otherBody->type != b3_dynamicBody ) + { + B3_ASSERT( joint->islandId == B3_NULL_INDEX ); + } + else + { + int jointIslandId = joint->islandId; + B3_ASSERT( jointIslandId == bodyIslandId ); + } + + jointKey = joint->edges[edgeIndex].nextKey; + } + } +} + +// Validates solver sets, but not island connectivity +void b3ValidateSolverSets( b3World* world ) +{ + B3_ASSERT( b3GetIdCapacity( &world->bodyIdPool ) == world->bodies.count ); + B3_ASSERT( b3GetIdCapacity( &world->contactIdPool ) == world->contacts.count ); + B3_ASSERT( b3GetIdCapacity( &world->jointIdPool ) == world->joints.count ); + B3_ASSERT( b3GetIdCapacity( &world->islandIdPool ) == world->islands.count ); + B3_ASSERT( b3GetIdCapacity( &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 ) + { + b3SolverSet* set = world->solverSets.data + setIndex; + if ( set->setIndex != B3_NULL_INDEX ) + { + activeSetCount += 1; + + if ( setIndex == b3_staticSet ) + { + B3_ASSERT( set->contactIndices.count == 0 ); + B3_ASSERT( set->islandSims.count == 0 ); + B3_ASSERT( set->bodyStates.count == 0 ); + } + else if ( setIndex == b3_disabledSet ) + { + B3_ASSERT( set->islandSims.count == 0 ); + B3_ASSERT( set->bodyStates.count == 0 ); + } + else if ( setIndex == b3_awakeSet ) + { + B3_ASSERT( set->bodySims.count == set->bodyStates.count ); + B3_ASSERT( set->jointSims.count == 0 ); + } + else + { + B3_ASSERT( set->bodyStates.count == 0 ); + } + + // Validate bodies + { + b3Body* bodies = world->bodies.data; + B3_ASSERT( set->bodySims.count >= 0 ); + totalBodyCount += set->bodySims.count; + for ( int i = 0; i < set->bodySims.count; ++i ) + { + b3BodySim* bodySim = set->bodySims.data + i; + + int bodyId = bodySim->bodyId; + B3_ASSERT( 0 <= bodyId && bodyId < world->bodies.count ); + b3Body* body = bodies + bodyId; + B3_ASSERT( body->setIndex == setIndex ); + B3_ASSERT( body->localIndex == i ); + B3_ASSERT( body->generation == body->generation ); + + if ( body->type == b3_dynamicBody ) + { + B3_ASSERT( body->flags & b3_dynamicFlag ); + } + + if ( setIndex == b3_disabledSet ) + { + B3_ASSERT( body->headContactKey == B3_NULL_INDEX ); + } + + // Validate body shapes + int prevShapeId = B3_NULL_INDEX; + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + B3_ASSERT( shape->id == shapeId ); + B3_ASSERT( shape->prevShapeId == prevShapeId ); + + if ( setIndex == b3_disabledSet ) + { + B3_ASSERT( shape->proxyKey == B3_NULL_INDEX ); + } + else if ( setIndex == b3_staticSet ) + { + B3_ASSERT( B3_PROXY_TYPE( shape->proxyKey ) == b3_staticBody ); + } + else + { + b3BodyType proxyType = B3_PROXY_TYPE( shape->proxyKey ); + B3_ASSERT( proxyType == b3_kinematicBody || proxyType == b3_dynamicBody ); + } + + prevShapeId = shapeId; + shapeId = shape->nextShapeId; + } + + // Validate body contacts + int contactKey = body->headContactKey; + while ( contactKey != B3_NULL_INDEX ) + { + int contactId = contactKey >> 1; + int edgeIndex = contactKey & 1; + + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + B3_ASSERT( contact->setIndex != b3_staticSet ); + B3_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 != B3_NULL_INDEX ) + { + int jointId = jointKey >> 1; + int edgeIndex = jointKey & 1; + + b3Joint* joint = b3Array_Get( world->joints, jointId ); + + int otherEdgeIndex = edgeIndex ^ 1; + + b3Body* otherBody = b3Array_Get( world->bodies, joint->edges[otherEdgeIndex].bodyId ); + + if ( setIndex == b3_disabledSet || otherBody->setIndex == b3_disabledSet ) + { + B3_ASSERT( joint->setIndex == b3_disabledSet ); + } + else if ( setIndex == b3_staticSet && otherBody->setIndex == b3_staticSet ) + { + B3_ASSERT( joint->setIndex == b3_staticSet ); + } + else if ( body->type != b3_dynamicBody && otherBody->type != b3_dynamicBody ) + { + B3_ASSERT( joint->setIndex == b3_staticSet ); + } + else if ( setIndex == b3_awakeSet ) + { + B3_ASSERT( joint->setIndex == b3_awakeSet ); + } + else if ( setIndex >= b3_firstSleepingSet ) + { + B3_ASSERT( joint->setIndex == setIndex ); + } + + b3JointSim* jointSim = b3GetJointSim( world, joint ); + B3_ASSERT( jointSim->jointId == jointId ); + B3_ASSERT( jointSim->bodyIdA == joint->edges[0].bodyId ); + B3_ASSERT( jointSim->bodyIdB == joint->edges[1].bodyId ); + + jointKey = joint->edges[edgeIndex].nextKey; + } + } + } + + // Validate contacts + { + B3_ASSERT( set->contactIndices.count >= 0 ); + totalContactCount += set->contactIndices.count; + for ( int i = 0; i < set->contactIndices.count; ++i ) + { + int contactIndex = set->contactIndices.data[i]; + b3Contact* contact = b3Array_Get( world->contacts, contactIndex ); + if ( setIndex == b3_awakeSet ) + { + // contact should be non-touching if awake + // or it could be this contact hasn't been transferred yet + B3_ASSERT( contact->manifoldCount == 0 || ( contact->flags & b3_simStartedTouching ) != 0 ); + } + B3_ASSERT( contact->setIndex == setIndex ); + B3_ASSERT( contact->colorIndex == B3_NULL_INDEX ); + B3_ASSERT( contact->localIndex == i ); + } + } + + // Validate joints + { + B3_ASSERT( set->jointSims.count >= 0 ); + totalJointCount += set->jointSims.count; + for ( int i = 0; i < set->jointSims.count; ++i ) + { + b3JointSim* jointSim = set->jointSims.data + i; + b3Joint* joint = b3Array_Get( world->joints, jointSim->jointId ); + B3_ASSERT( joint->setIndex == setIndex ); + B3_ASSERT( joint->colorIndex == B3_NULL_INDEX ); + B3_ASSERT( joint->localIndex == i ); + } + } + + // Validate islands + { + B3_ASSERT( set->islandSims.count >= 0 ); + totalIslandCount += set->islandSims.count; + for ( int i = 0; i < set->islandSims.count; ++i ) + { + b3IslandSim* islandSim = set->islandSims.data + i; + b3Island* island = b3Array_Get( world->islands, islandSim->islandId ); + B3_ASSERT( island->setIndex == setIndex ); + B3_ASSERT( island->localIndex == i ); + } + } + } + else + { + B3_ASSERT( set->bodySims.count == 0 ); + B3_ASSERT( set->contactIndices.count == 0 ); + B3_ASSERT( set->jointSims.count == 0 ); + B3_ASSERT( set->islandSims.count == 0 ); + B3_ASSERT( set->bodyStates.count == 0 ); + } + } + + int setIdCount = b3GetIdCount( &world->solverSetIdPool ); + B3_ASSERT( activeSetCount == setIdCount ); + + int bodyIdCount = b3GetIdCount( &world->bodyIdPool ); + B3_ASSERT( totalBodyCount == bodyIdCount ); + + int islandIdCount = b3GetIdCount( &world->islandIdPool ); + B3_ASSERT( totalIslandCount == islandIdCount ); + + // Validate constraint graph + for ( int colorIndex = 0; colorIndex < B3_GRAPH_COLOR_COUNT; ++colorIndex ) + { + b3GraphColor* color = world->constraintGraph.colors + colorIndex; + int bitCount = 0; + + B3_ASSERT( color->convexContacts.count >= 0 ); + totalContactCount += color->convexContacts.count; + for ( int i = 0; i < color->convexContacts.count; ++i ) + { + int contactId = color->convexContacts.data[i]; + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + // contact should be touching in the constraint graph or awaiting transfer to non-touching + B3_ASSERT( contact->manifoldCount > 0 || ( contact->flags & ( b3_simStoppedTouching | b3_simDisjoint ) ) != 0 ); + B3_ASSERT( contact->setIndex == b3_awakeSet ); + B3_ASSERT( contact->colorIndex == colorIndex ); + B3_ASSERT( contact->localIndex == i ); + + int bodyIdA = contact->edges[0].bodyId; + int bodyIdB = contact->edges[1].bodyId; + + if ( colorIndex < B3_OVERFLOW_INDEX ) + { + b3Body* bodyA = b3Array_Get( world->bodies, bodyIdA ); + b3Body* bodyB = b3Array_Get( world->bodies, bodyIdB ); + B3_ASSERT( b3GetBit( &color->bodySet, bodyIdA ) == ( bodyA->type == b3_dynamicBody ) ); + B3_ASSERT( b3GetBit( &color->bodySet, bodyIdB ) == ( bodyB->type == b3_dynamicBody ) ); + + bitCount += bodyA->type == b3_dynamicBody ? 1 : 0; + bitCount += bodyB->type == b3_dynamicBody ? 1 : 0; + } + } + + totalContactCount += color->contacts.count; + for ( int i = 0; i < color->contacts.count; ++i ) + { + int contactId = color->contacts.data[i].contactId; + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + // contact should be touching in the constraint graph or awaiting transfer to non-touching + B3_ASSERT( contact->manifoldCount > 0 || ( contact->flags & ( b3_simStoppedTouching | b3_simDisjoint ) ) != 0 ); + B3_ASSERT( contact->setIndex == b3_awakeSet ); + B3_ASSERT( contact->colorIndex == colorIndex ); + B3_ASSERT( contact->localIndex == i ); + + int bodyIdA = contact->edges[0].bodyId; + int bodyIdB = contact->edges[1].bodyId; + + if ( colorIndex < B3_OVERFLOW_INDEX ) + { + b3Body* bodyA = b3Array_Get( world->bodies, bodyIdA ); + b3Body* bodyB = b3Array_Get( world->bodies, bodyIdB ); + B3_ASSERT( b3GetBit( &color->bodySet, bodyIdA ) == ( bodyA->type == b3_dynamicBody ) ); + B3_ASSERT( b3GetBit( &color->bodySet, bodyIdB ) == ( bodyB->type == b3_dynamicBody ) ); + + bitCount += bodyA->type == b3_dynamicBody ? 1 : 0; + bitCount += bodyB->type == b3_dynamicBody ? 1 : 0; + } + } + + B3_ASSERT( color->jointSims.count >= 0 ); + totalJointCount += color->jointSims.count; + for ( int i = 0; i < color->jointSims.count; ++i ) + { + b3JointSim* jointSim = color->jointSims.data + i; + b3Joint* joint = b3Array_Get( world->joints, jointSim->jointId ); + B3_ASSERT( joint->setIndex == b3_awakeSet ); + B3_ASSERT( joint->colorIndex == colorIndex ); + B3_ASSERT( joint->localIndex == i ); + + int bodyIdA = joint->edges[0].bodyId; + int bodyIdB = joint->edges[1].bodyId; + + if ( colorIndex < B3_OVERFLOW_INDEX ) + { + b3Body* bodyA = b3Array_Get( world->bodies, bodyIdA ); + b3Body* bodyB = b3Array_Get( world->bodies, bodyIdB ); + B3_ASSERT( b3GetBit( &color->bodySet, bodyIdA ) == ( bodyA->type == b3_dynamicBody ) ); + B3_ASSERT( b3GetBit( &color->bodySet, bodyIdB ) == ( bodyB->type == b3_dynamicBody ) ); + + bitCount += bodyA->type == b3_dynamicBody ? 1 : 0; + bitCount += bodyB->type == b3_dynamicBody ? 1 : 0; + } + } + + // Validate the bit population for this graph color + B3_ASSERT( bitCount == b3CountSetBits( &color->bodySet ) ); + } + + int contactIdCount = b3GetIdCount( &world->contactIdPool ); + B3_ASSERT( totalContactCount == contactIdCount ); + B3_ASSERT( totalContactCount == (int)world->broadPhase.pairSet.count ); + + int jointIdCount = b3GetIdCount( &world->jointIdPool ); + B3_ASSERT( totalJointCount == jointIdCount ); + +// Validate shapes +// This is very slow on compounds +#if 0 + int shapeCapacity = b3Array(world->shapeArray).count; + for (int shapeIndex = 0; shapeIndex < shapeCapacity; shapeIndex += 1) + { + b3Shape* shape = world->shapeArray + shapeIndex; + if (shape->id != shapeIndex) + { + continue; + } + + B3_ASSERT(0 <= shape->bodyId && shape->bodyId < b3Array(world->bodyArray).count); + + b3Body* body = world->bodyArray + shape->bodyId; + B3_ASSERT(0 <= body->setIndex && body->setIndex < b3Array(world->solverSetArray).count); + + b3SolverSet* set = world->solverSetArray + body->setIndex; + B3_ASSERT(0 <= body->localIndex && body->localIndex < set->sims.count); + + b3BodySim* bodySim = set->sims.mData + body->localIndex; + B3_ASSERT(bodySim->bodyId == shape->bodyId); + + bool found = false; + int shapeCount = 0; + int index = body->headShapeId; + while (index != B3_NULL_INDEX) + { + b3CheckId(world->shapeArray, index); + b3Shape* s = world->shapeArray + index; + if (index == shapeIndex) + { + found = true; + } + + index = s->nextShapeId; + shapeCount += 1; + } + + B3_ASSERT(found); + B3_ASSERT(shapeCount == body->shapeCount); + } +#endif +} + +// Validate contact touching status. +void b3ValidateContacts( b3World* world ) +{ + b3ConstraintGraph* graph = &world->constraintGraph; + int contactCount = world->contacts.count; + B3_ASSERT( contactCount == b3GetIdCapacity( &world->contactIdPool ) ); + int allocatedContactCount = 0; + + for ( int contactIndex = 0; contactIndex < contactCount; ++contactIndex ) + { + b3Contact* contact = b3Array_Get( world->contacts, contactIndex ); + if ( contact->contactId == B3_NULL_INDEX ) + { + continue; + } + + B3_ASSERT( contact->contactId == contactIndex ); + + allocatedContactCount += 1; + + bool touching = ( contact->flags & b3_contactTouchingFlag ) != 0; + + int setId = contact->setIndex; + b3SolverSet* set = b3Array_Get( world->solverSets, setId ); + + if ( setId == b3_awakeSet ) + { + if ( touching ) + { + B3_ASSERT( 0 <= contact->colorIndex && contact->colorIndex < B3_GRAPH_COLOR_COUNT ); + // Validate body sim indices + b3Shape* shapeA = b3Array_Get( world->shapes, contact->shapeIdA ); + b3Shape* shapeB = b3Array_Get( world->shapes, contact->shapeIdB ); + + b3Body* bodyA = b3Array_Get( world->bodies, shapeA->bodyId ); + b3Body* bodyB = b3Array_Get( world->bodies, shapeB->bodyId ); + + if ( bodyA->type == b3_staticBody ) + { + B3_ASSERT( contact->bodySimIndexA == B3_NULL_INDEX ); + } + else + { + B3_ASSERT( contact->bodySimIndexA == bodyA->localIndex ); + } + + if ( bodyB->type == b3_staticBody ) + { + B3_ASSERT( contact->bodySimIndexB == B3_NULL_INDEX ); + } + else + { + B3_ASSERT( contact->bodySimIndexB == bodyB->localIndex ); + } + + if ( ( contact->flags & b3_simMeshContact ) != 0 || contact->colorIndex == B3_OVERFLOW_INDEX ) + { + b3GraphColor* color = graph->colors + contact->colorIndex; + int contactId = b3Array_Get( color->contacts, contact->localIndex )->contactId; + B3_ASSERT( contactId == contactIndex ); + } + else + { + b3GraphColor* color = graph->colors + contact->colorIndex; + int contactId = *b3Array_Get( color->convexContacts, contact->localIndex ); + B3_ASSERT( contactId == contactIndex ); + } + } + else + { + B3_ASSERT( contact->colorIndex == B3_NULL_INDEX ); + B3_ASSERT( contact->manifolds == NULL ); + B3_ASSERT( contact->manifoldCount == 0 ); + + int* index = b3Array_Get( set->contactIndices, contact->localIndex ); + B3_ASSERT( *index == contactIndex ); + } + } + else if ( setId >= b3_firstSleepingSet ) + { + // Only touching contacts allowed in a sleeping set + B3_ASSERT( touching == true ); + B3_ASSERT( contact->manifolds != NULL ); + B3_ASSERT( contact->manifoldCount > 0 ); + int* index = b3Array_Get( set->contactIndices, contact->localIndex ); + B3_ASSERT( *index == contactIndex ); + } + else + { + // Sleeping and non-touching contacts belong in the disabled set + B3_ASSERT( touching == false && setId == b3_disabledSet ); + B3_ASSERT( contact->manifolds == NULL ); + B3_ASSERT( contact->manifoldCount == 0 ); + int* index = b3Array_Get( set->contactIndices, contact->localIndex ); + B3_ASSERT( *index == contactIndex ); + } + + if ( contact->flags & b3_simMeshContact ) + { + int cacheCount = contact->meshContact.triangleCache.count; + if ( cacheCount > 0 ) + { + B3_ASSERT( contact->meshContact.triangleCache.data != NULL ); + B3_ASSERT( contact->meshContact.triangleCache.capacity >= cacheCount ); + + b3Shape* shapeA = b3Array_Get( world->shapes, contact->shapeIdA ); + if ( shapeA->type == b3_meshShape ) + { + int triangleCount = shapeA->mesh.data->triangleCount; + for ( int i = 0; i < cacheCount; ++i ) + { + int triangleIndex = contact->meshContact.triangleCache.data[i].triangleIndex; + B3_ASSERT( 0 <= triangleIndex && triangleIndex < triangleCount ); + } + } + else if ( shapeA->type == b3_heightShape ) + { + int triangleCount = b3GetHeightFieldTriangleCount( shapeA->heightField ); + for ( int i = 0; i < cacheCount; ++i ) + { + int triangleIndex = contact->meshContact.triangleCache.data[i].triangleIndex; + B3_ASSERT( 0 <= triangleIndex && triangleIndex < triangleCount ); + } + } + else + { + B3_ASSERT( shapeA->type == b3_compoundShape ); + b3ChildShape child = b3GetCompoundChild( shapeA->compound, contact->childIndex ); + B3_ASSERT( child.type == b3_meshShape ); + + int triangleCount = child.mesh.data->triangleCount; + for ( int i = 0; i < cacheCount; ++i ) + { + int triangleIndex = contact->meshContact.triangleCache.data[i].triangleIndex; + B3_ASSERT( 0 <= triangleIndex && triangleIndex < triangleCount ); + } + } + } + } + } + + int contactIdCount = b3GetIdCount( &world->contactIdPool ); + B3_ASSERT( allocatedContactCount == contactIdCount ); +} + +#else + +void b3ValidateConnectivity( b3World* world ) +{ + B3_UNUSED( world ); +} + +void b3ValidateSolverSets( b3World* world ) +{ + B3_UNUSED( world ); +} + +void b3ValidateContacts( b3World* world ) +{ + B3_UNUSED( world ); +} + +#endif + +#define NAME int_set +#define KEY_TY int +#define MALLOC_FN b3Alloc +#define FREE_FN b3Free +#define HASH_FN vt_hash_integer +#define CMPR_FN vt_cmpr_integer +#include "verstable.h" + +void b3World_DumpAwake( b3WorldId worldId ) +{ + b3World* world = b3GetWorldFromId( worldId ); + if ( world->locked == true ) + { + return; + } + + b3OpenDump( "box3d_dump.inl" ); + + b3Vec3 g = world->gravity; + b3Dump( "b3Vec3 gravity = {%.9g, %.9g, %.9g};\n", g.x, g.y, g.z ); + b3Dump( "b3World_SetGravity(m_worldId, gravity);\n" ); + + b3Dump( "std::vector bodies;\n" ); + b3Dump( "std::vector joints;\n\n" ); + + int_set staticBodies; + int_set_init( &staticBodies ); + + b3Body* bodies = world->bodies.data; + for ( int i = 0; i < world->bodies.count; ++i ) + { + b3Body* body = bodies + i; + + if ( body->id == B3_NULL_INDEX ) + { + continue; + } + + if ( body->setIndex != b3_awakeSet ) + { + continue; + } + + b3DumpBody( world, body ); + + // Gather + int edgeKey = body->headContactKey; + while ( edgeKey != B3_NULL_INDEX ) + { + int contactId = edgeKey >> 1; + int edgeIndex = edgeKey & 1; + + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + edgeKey = contact->edges[edgeIndex].nextKey; + + if ( ( contact->flags & b3_contactTouchingFlag ) == 0 ) + { + continue; + } + + int otherIndex = 1 - edgeIndex; + b3Body* otherBody = b3Array_Get( world->bodies, contact->edges[otherIndex].bodyId ); + if ( otherBody->setIndex == b3_staticSet ) + { + (void)int_set_insert( &staticBodies, otherBody->id ); + } + } + } + + // Dump the bodies that are touching + for ( int_set_itr itr = int_set_first( &staticBodies ); int_set_is_end( itr ) == false; itr = int_set_next( itr ) ) + { + b3Body* body = b3Array_Get( world->bodies, itr.data->key ); + b3DumpBody( world, body ); + } + + int_set_cleanup( &staticBodies ); + + b3CloseDump(); +} + +void b3World_Dump( b3WorldId worldId ) +{ + b3World* world = b3GetWorldFromId( worldId ); + + if ( world->locked == true ) + { + return; + } + + b3OpenDump( "box3d_dump.inl" ); + + b3Vec3 g = world->gravity; + b3Dump( "b3Vec3 gravity = {%.9g, %.9g, %.9g};\n", g.x, g.y, g.z ); + b3Dump( "b3World_SetGravity(m_worldId, gravity);\n" ); + + b3Dump( "std::vector bodies;\n" ); + b3Dump( "std::vector joints;\n\n" ); + + b3Body* bodies = world->bodies.data; + for ( int i = 0; i < world->bodies.count; ++i ) + { + b3Body* body = bodies + i; + + if ( body->id == B3_NULL_INDEX ) + { + continue; + } + + if ( body->setIndex != b3_awakeSet ) + { + continue; + } + + b3DumpBody( world, body ); + } + + b3CloseDump(); +} diff --git a/src/physics_world.h b/src/physics_world.h new file mode 100644 index 0000000..c964d2f --- /dev/null +++ b/src/physics_world.h @@ -0,0 +1,333 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "arena_allocator.h" +#include "bitset.h" +#include "block_allocator.h" +#include "broad_phase.h" +#include "constraint_graph.h" +#include "id_pool.h" + +#include "box3d/types.h" + +#define B3_DEBUG_POINT_CAPACITY 64 +#define B3_DEBUG_LINE_CAPACITY 64 + +typedef struct b3Body b3Body; +typedef struct b3Contact b3Contact; +typedef struct b3Island b3Island; +typedef struct b3Joint b3Joint; +typedef struct b3Sensor b3Sensor; +typedef struct b3SensorTaskContext b3SensorTaskContext; +typedef struct b3SensorHit b3SensorHit; +typedef struct b3Shape b3Shape; +typedef struct b3SolverSet b3SolverSet; + +b3DeclareArray( b3BlockAllocator ); +b3DeclareArray( b3Body ); +b3DeclareArray( b3SolverSet ); +b3DeclareArray( b3Joint ); +b3DeclareArray( b3Contact ); +b3DeclareArray( b3Island ); +b3DeclareArray( b3Shape ); +b3DeclareArray( b3Sensor ); +b3DeclareArray( b3SensorTaskContext ); +b3DeclareArray( b3SensorHit ); +b3DeclareArray( b3BodyMoveEvent ); +b3DeclareArray( b3SensorBeginTouchEvent ); +b3DeclareArray( b3ContactBeginTouchEvent ); +b3DeclareArray( b3SensorEndTouchEvent ); +b3DeclareArray( b3ContactEndTouchEvent ); +b3DeclareArray( b3ContactHitEvent ); +b3DeclareArray( b3JointEvent ); + +enum b3SetType +{ + b3_staticSet = 0, + b3_disabledSet = 1, + b3_awakeSet = 2, + b3_firstSleepingSet = 3, +}; + +typedef struct b3DebugPoint +{ + b3Vec3 p; + int label; + float value; + b3HexColor color; +} b3DebugPoint; + +typedef struct b3DebugLine +{ + b3Vec3 p1, p2; + int label; + b3HexColor color; +} b3DebugLine; + +// Per thread task storage +typedef struct b3TaskContext +{ + b3Arena arena; + + // Collect per thread sensor continuous hit events. + b3ArrayC( b3SensorHit ) sensorHits; + + // These bits align with the b3ConstraintGraph::contactBlocks and signal a change in contact status + b3BitSet contactStateBitSet; + + // These bits align with the joint id capacity and signal a change in contact status + b3BitSet jointStateBitSet; + + // These bits align with the contact id capacity and signal a hit event. + b3BitSet hitEventBitSet; + + // Fast-path flag: true when this worker set at least one bit in hitEventBitSet this step. + bool hasHitEvents; + + // 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. + b3BitSet enlargedSimBitSet; + + // Used to put islands to sleep + b3BitSet awakeIslandBitSet; + + // Per worker split island candidate + float splitSleepTime; + int splitIslandId; + + // Profiling + int satCallCount; + int satCacheHitCount; + + b3DebugPoint points[B3_DEBUG_POINT_CAPACITY]; + int pointCount; + + b3DebugLine lines[B3_DEBUG_LINE_CAPACITY]; + int lineCount; + + int manifoldCounts[B3_CONTACT_MANIFOLD_COUNT_BUCKETS]; + + // Number of contacts recycled this step (collide pass). + int recycledContactCount; + + // Prevent false sharing + char cacheLine[64]; +} b3TaskContext; + +b3DeclareArray( b3TaskContext ); + +// The world struct manages all physics entities, dynamic simulation, and asynchronous queries. +// The world also contains efficient memory management facilities. +typedef struct b3World +{ + b3Stack stack; + b3BroadPhase broadPhase; + b3ConstraintGraph constraintGraph; + + // Manifold allocators have one allocator for each manifold count. + b3ArrayC( b3BlockAllocator ) manifoldAllocators; + b3Mutex* manifoldAllocatorMutex; + + // 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 b3Body. + b3IdPool 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. + b3ArrayC( b3Body ) bodies; + + // Provides free list for solver sets. + b3IdPool 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. + b3ArrayC( b3SolverSet ) solverSets; + + // Used to create stable ids for joints + b3IdPool jointIdPool; + + // This is a sparse array that maps joint ids to the joint data stored in the constraint graph + // or in the solver sets. + b3ArrayC( b3Joint ) joints; + + // Used to create stable ids for contacts + b3IdPool contactIdPool; + + // This is a sparse array that maps contact ids to the contact data stored in the constraint graph + // or in the solver sets. + b3ArrayC( b3Contact ) contacts; + + // Used to create stable ids for islands + b3IdPool islandIdPool; + + // This is a sparse array that maps island ids to the island data stored in the solver sets. + b3ArrayC( b3Island ) islands; + + b3IdPool shapeIdPool; + + // These are sparse arrays that point into the pools above + b3ArrayC( b3Shape ) shapes; + + // This is a dense array of sensor data. + b3ArrayC( b3Sensor ) sensors; + + // Per thread storage + b3ArrayC( b3TaskContext ) taskContexts; + b3ArrayC( b3SensorTaskContext ) sensorTaskContexts; + + b3ArrayC( b3BodyMoveEvent ) bodyMoveEvents; + b3ArrayC( b3SensorBeginTouchEvent ) sensorBeginEvents; + b3ArrayC( b3ContactBeginTouchEvent ) contactBeginEvents; + + // End events are double buffered so that the user doesn't need to flush events + b3ArrayC( b3SensorEndTouchEvent ) sensorEndEvents[2]; + b3ArrayC( b3ContactEndTouchEvent ) contactEndEvents[2]; + int endEventArrayIndex; + + b3ArrayC( b3ContactHitEvent ) contactHitEvents; + b3ArrayC( b3JointEvent ) jointEvents; + + // Used to track debug draw + b3BitSet debugBodySet; + b3BitSet debugJointSet; + b3BitSet debugContactSet; + b3BitSet debugIslandSet; + b3CreateDebugShapeCallback* createDebugShape; + b3DestroyDebugShapeCallback* destroyDebugShape; + void* userDebugShapeContext; + + // 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; + + b3Vec3 gravity; + float hitEventThreshold; + float restitutionThreshold; + float maxLinearSpeed; + float contactSpeed; + float contactHertz; + float contactDampingRatio; + float contactRecycleDistance; + + b3FrictionCallback* frictionCallback; + b3RestitutionCallback* restitutionCallback; + + uint16_t generation; + + b3Profile profile; + int satCallCount; + int satCacheHitCount; + int manifoldCounts[B3_CONTACT_MANIFOLD_COUNT_BUCKETS]; + + b3Capacity maxCapacity; + + b3PreSolveFcn* preSolveFcn; + void* preSolveContext; + + b3CustomFilterFcn* customFilterFcn; + void* customFilterContext; + + int workerCount; + b3EnqueueTaskCallback* enqueueTaskFcn; + b3FinishTaskCallback* finishTaskFcn; + void* userTaskContext; + void* userTreeTask; + + struct b3Scheduler* scheduler; + + void* userData; + + // latest inverse sub-step + float inv_h; + + // latest inverse full-step + float inv_dt; + + int activeTaskCount; + int taskCount; + + uint16_t worldId; + + bool enableSleep; + + // This indicates there is a world write operation in progress. This is for debugging and + // not a real mutex. This should have minimal performance impact. + bool locked; + + bool enableWarmStarting; + bool enableContinuous; + bool enableSpeculative; + bool inUse; +} b3World; + +#ifdef __cplusplus +extern "C" +{ +#endif + +b3World* b3GetUnlockedWorldFromId( b3WorldId id ); +b3World* b3GetWorldFromId( b3WorldId id ); + +b3World* b3GetUnlockedWorld( int index ); +b3World* b3GetWorld( int index ); + +void b3ValidateConnectivity( b3World* world ); +void b3ValidateSolverSets( b3World* world ); +void b3ValidateContacts( b3World* world ); + +#ifdef __cplusplus +} +#endif + +static inline b3Manifold* b3AllocateManifolds( b3World* world, int count ) +{ + if ( count == 0 ) + { + return NULL; + } + + int index = count - 1; + + // Need lock because this is called from the parallel narrow phase + b3LockMutex( world->manifoldAllocatorMutex ); + int currentCount = world->manifoldAllocators.count; + for ( int i = currentCount; i < count; ++i ) + { + b3BlockAllocator allocator = b3CreateBlockAllocator( ( i + 1 ) * sizeof( b3Manifold ), 2 * B3_BLOCK_SIZE ); + b3Array_Push( world->manifoldAllocators, allocator ); + } + + b3BlockAllocator* allocator = b3Array_Get( world->manifoldAllocators, index ); + b3Manifold* manifolds = (b3Manifold*)b3AllocateElement( allocator ); + b3UnlockMutex( world->manifoldAllocatorMutex ); + memset( manifolds, 0, count * sizeof( b3Manifold ) ); + return manifolds; +} + +static inline void b3FreeManifolds( b3World* world, b3Manifold* manifolds, int count ) +{ + if ( count == 0 ) + { + return; + } + + int index = count - 1; + b3LockMutex( world->manifoldAllocatorMutex ); + b3BlockAllocator* allocator = b3Array_Get( world->manifoldAllocators, index ); + b3FreeElement( allocator, manifolds ); + b3UnlockMutex( world->manifoldAllocatorMutex ); +} + diff --git a/src/platform.h b/src/platform.h new file mode 100644 index 0000000..cc5fd5e --- /dev/null +++ b/src/platform.h @@ -0,0 +1,88 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "core.h" + +#include +#include + +// Software prefetch hint. _MM_HINT_T0 brings the line into all cache levels. +// MSVC exposes _mm_prefetch via ; clang/gcc accept it via +// on x86 and provide __builtin_prefetch elsewhere. +#if defined( B3_COMPILER_MSVC ) +#include +#define b3Prefetch( addr ) _mm_prefetch( (const char*)( addr ), _MM_HINT_T0 ) +#elif defined( B3_COMPILER_CLANG ) || defined( B3_COMPILER_GCC ) +#define b3Prefetch( addr ) __builtin_prefetch( (const void*)( addr ), 0, 3 ) +#else +#define b3Prefetch( addr ) ( (void)( addr ) ) +#endif + +static inline void b3AtomicStoreInt( b3AtomicInt* 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 b3AtomicLoadInt( b3AtomicInt* 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 b3AtomicFetchAddInt( b3AtomicInt* 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 b3AtomicCompareExchangeInt( b3AtomicInt* 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 b3AtomicStoreU32( b3AtomicU32* 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 b3AtomicLoadU32( b3AtomicU32* 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 +} diff --git a/src/prismatic_joint.c b/src/prismatic_joint.c new file mode 100644 index 0000000..640d22d --- /dev/null +++ b/src/prismatic_joint.c @@ -0,0 +1,665 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "body.h" +#include "core.h" +#include "joint.h" +#include "math_internal.h" +#include "physics_world.h" +#include "solver.h" +#include "solver_set.h" + +// needed for dll export +#include "box3d/box3d.h" + +// Linear constraint (point-to-line) +// joint axis is along joint frame A local z-axis +// perpX and perpY are world vectors fixed in A +// +// d = pB - pA = xB + rB - xA - rA +// Cx = dot(perpX, d) +// Cy = dot(perpY, d) + +// CdotX = dot(d, cross(wA, perpX)) + dot(perpX, vB + cross(wB, rB) - vA - cross(wA, rA)) +// = -dot(perpX, vA) - dot(cross(d + rA, perpX), wA) + dot(perpX, vB) + dot(cross(rB, perpX), vB) +// Jx = [-perpX, -cross(d + rA, perpX), perpX, cross(rB, perpX)] +// similar for perpY +// +// Simplification dropping dot(d, cross(wA, perpX)) (todo needs testing) +// CdotXs = dot(perpX, vB + cross(wB, rB) - vA - cross(wA, rA)) +// Jxs = [-perpX, -cross(rA, perpX), perpX, cross(rB, perpX)] + +// Motor/limit/spring linear constraint +// axis is the world joint axis fixed in A + +// C = dot(axis, d) +// Cdot = dot(d, cross(wA, axis)) + dot(axis, vB + cross(wB, rB) - vA - cross(wA, rA)) +// Cdot = -dot(axis, vA) - dot(cross(d + rA, axis), wA) + dot(axis, vB) + dot(cross(rB, axis), vB) +// J = [-axis -cross(d + rA, axis) axis cross(rB, axis)] +// +// Simplified (todo needs testing) +// Cdot = -dot(axis, vA) - dot(cross(rA, axis), wA) + dot(axis, vB) + dot(cross(rB, axis), vB) +// J = [-axis -cross(rA, axis) axis cross(rB, axis)] + +// 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 + +void b3PrismaticJoint_EnableLimit( b3JointId jointId, bool enableLimit ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + if ( enableLimit != base->prismaticJoint.enableLimit ) + { + base->prismaticJoint.lowerImpulse = 0.0f; + base->prismaticJoint.upperImpulse = 0.0f; + } + base->prismaticJoint.enableLimit = enableLimit; +} + +bool b3PrismaticJoint_IsLimitEnabled( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + return base->prismaticJoint.enableLimit; +} + +float b3PrismaticJoint_GetLowerLimit( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + return base->prismaticJoint.lowerTranslation; +} + +float b3PrismaticJoint_GetUpperLimit( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + return base->prismaticJoint.upperTranslation; +} + +void b3PrismaticJoint_SetLimits( b3JointId jointId, float lower, float upper ) +{ + B3_ASSERT( b3IsValidFloat( lower ) && b3IsValidFloat( upper ) ); + float lowerAngle = b3MinFloat( lower, upper ); + float upperAngle = b3MaxFloat( lower, upper ); + + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + base->prismaticJoint.lowerTranslation = lowerAngle; + base->prismaticJoint.upperTranslation = upperAngle; +} + +float b3PrismaticJoint_GetTranslation( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA ); + b3Transform transformB = b3GetBodyTransform( world, base->bodyIdB ); + + b3Vec3 jointAxis = b3RotateVector( base->localFrameA.q, b3Vec3_axisX ); + jointAxis = b3RotateVector( transformA.q, jointAxis ); + + b3Vec3 anchorA = b3RotateVector( transformA.q, base->localFrameA.p ); + b3Vec3 anchorB = b3RotateVector( transformB.q, base->localFrameB.p ); + b3Vec3 d = b3Add( b3Sub( transformB.p, transformA.p ), b3Sub( anchorB, anchorA ) ); + float translation = b3Dot( d, jointAxis ); + return translation; +} + +void b3PrismaticJoint_EnableSpring( b3JointId jointId, bool enableSpring ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + if ( enableSpring != base->prismaticJoint.enableSpring ) + { + base->prismaticJoint.springImpulse = 0.0f; + } + base->prismaticJoint.enableSpring = enableSpring; +} + +bool b3PrismaticJoint_IsSpringEnabled( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + return base->prismaticJoint.enableSpring; +} + +void b3PrismaticJoint_SetTargetTranslation( b3JointId jointId, float targetTranslation ) +{ + B3_ASSERT( b3IsValidFloat( targetTranslation ) ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + base->prismaticJoint.targetTranslation = targetTranslation; +} + +float b3PrismaticJoint_GetTargetTranslation( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + return base->prismaticJoint.targetTranslation; +} + +void b3PrismaticJoint_SetSpringHertz( b3JointId jointId, float hertz ) +{ + B3_ASSERT( b3IsValidFloat( hertz ) && hertz >= 0.0f ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + base->prismaticJoint.hertz = hertz; +} + +float b3PrismaticJoint_GetSpringHertz( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + return base->prismaticJoint.hertz; +} + +void b3PrismaticJoint_SetSpringDampingRatio( b3JointId jointId, float dampingRatio ) +{ + B3_ASSERT( b3IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + base->prismaticJoint.dampingRatio = dampingRatio; +} + +float b3PrismaticJoint_GetSpringDampingRatio( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + return base->prismaticJoint.dampingRatio; +} + +void b3PrismaticJoint_EnableMotor( b3JointId jointId, bool enableMotor ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + if ( enableMotor != base->prismaticJoint.enableMotor ) + { + base->prismaticJoint.motorImpulse = 0.0f; + } + base->prismaticJoint.enableMotor = enableMotor; +} + +bool b3PrismaticJoint_IsMotorEnabled( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + return base->prismaticJoint.enableMotor; +} + +void b3PrismaticJoint_SetMotorSpeed( b3JointId jointId, float motorSpeed ) +{ + B3_ASSERT( b3IsValidFloat( motorSpeed ) ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + base->prismaticJoint.motorSpeed = motorSpeed; +} + +float b3PrismaticJoint_GetMotorSpeed( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + return base->prismaticJoint.motorSpeed; +} + +void b3PrismaticJoint_SetMaxMotorForce( b3JointId jointId, float maxForce ) +{ + B3_ASSERT( b3IsValidFloat( maxForce ) && maxForce >= 0.0f ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + base->prismaticJoint.maxMotorForce = maxForce; +} + +float b3PrismaticJoint_GetMaxMotorForce( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint ); + return base->prismaticJoint.maxMotorForce; +} + +b3Vec3 b3GetPrismaticJointForce( b3World* world, b3JointSim* base ) +{ + b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA ); + b3PrismaticJoint* joint = &base->prismaticJoint; + + // impulse in joint space + b3Vec3 impulse = { + joint->perpImpulse.x, + joint->perpImpulse.y, + joint->motorImpulse + joint->lowerImpulse + joint->upperImpulse + joint->springImpulse, + }; + + // convert impulse to force + b3Vec3 force = b3MulSV( world->inv_h, impulse ); + + // convert to body space + force = b3RotateVector( base->localFrameA.q, force ); + + // convert to world space + force = b3RotateVector( transformA.q, force ); + return force; +} + +b3Vec3 b3GetPrismaticJointTorque( b3World* world, b3JointSim* base ) +{ + b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA ); + b3PrismaticJoint* joint = &base->prismaticJoint; + + b3Vec3 torque = b3MulSV( world->inv_h, joint->angularImpulse ); + torque = b3RotateVector( base->localFrameA.q, torque ); + torque = b3RotateVector( transformA.q, torque ); + return torque; +} + +void b3PreparePrismaticJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_prismaticJoint ); + + b3World* world = context->world; + + b3Body* bodyA = b3Array_Get( world->bodies, base->bodyIdA ); + b3Body* bodyB = b3Array_Get( world->bodies, base->bodyIdB ); + + B3_ASSERT( bodyB->setIndex == b3_awakeSet ); + b3SolverSet* setA = b3Array_Get( world->solverSets, bodyA->setIndex ); + b3SolverSet* setB = b3Array_Get( world->solverSets, bodyB->setIndex ); + + int localIndexA = bodyA->localIndex; + int localIndexB = bodyB->localIndex; + + b3BodySim* bodySimA = b3Array_Get( setA->bodySims, localIndexA ); + b3BodySim* bodySimB = b3Array_Get( setB->bodySims, localIndexB ); + + base->invMassA = bodySimA->invMass; + base->invMassB = bodySimB->invMass; + base->invIA = bodySimA->invInertiaWorld; + base->invIB = bodySimB->invInertiaWorld; + + b3Matrix3 invInertiaSum = b3AddMM( base->invIA, base->invIB ); + base->fixedRotation = b3Det( invInertiaSum ) < 1000.0f * FLT_MIN; + + b3PrismaticJoint* joint = &base->prismaticJoint; + joint->indexA = bodyA->setIndex == b3_awakeSet ? localIndexA : B3_NULL_INDEX; + joint->indexB = bodyB->setIndex == b3_awakeSet ? localIndexB : B3_NULL_INDEX; + + // Compute joint anchor frames with world space rotation, relative to center of mass + joint->frameA.q = b3MulQuat( bodySimA->transform.q, base->localFrameA.q ); + joint->frameA.p = b3RotateVector( bodySimA->transform.q, b3Sub( base->localFrameA.p, bodySimA->localCenter ) ); + joint->frameB.q = b3MulQuat( bodySimB->transform.q, base->localFrameB.q ); + joint->frameB.p = b3RotateVector( bodySimB->transform.q, b3Sub( base->localFrameB.p, bodySimB->localCenter ) ); + + joint->deltaCenter = b3Sub( bodySimB->center, bodySimA->center ); + joint->rotationMass = b3InvertMatrix( invInertiaSum ); + + // Initial joint axes in world space + b3Matrix3 matrixA = b3MakeMatrixFromQuat( joint->frameA.q ); + joint->jointAxis = matrixA.cx; + joint->perpAxisY = matrixA.cy; + joint->perpAxisZ = matrixA.cz; + + joint->springSoftness = b3MakeSoft( joint->hertz, joint->dampingRatio, context->h ); + + if ( context->enableWarmStarting == false ) + { + joint->perpImpulse = (b3Vec2){ 0.0f, 0.0f }; + joint->angularImpulse = (b3Vec3){ 0.0f, 0.0f, 0.0f }; + joint->motorImpulse = 0.0f; + joint->springImpulse = 0.0f; + joint->lowerImpulse = 0.0f; + joint->upperImpulse = 0.0f; + } +} + +void b3WarmStartPrismaticJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_prismaticJoint ); + + float mA = base->invMassA; + float mB = base->invMassB; + b3Matrix3 iA = base->invIA; + b3Matrix3 iB = base->invIB; + + // dummy state for static bodies + b3BodyState dummyState = b3_identityBodyState; + + b3PrismaticJoint* joint = &base->prismaticJoint; + + b3BodyState* stateA = joint->indexA == B3_NULL_INDEX ? &dummyState : context->states + joint->indexA; + b3BodyState* stateB = joint->indexB == B3_NULL_INDEX ? &dummyState : context->states + joint->indexB; + + // todo make this code and the wheel joint more similar + + b3Vec3 rA = b3RotateVector( stateA->deltaRotation, joint->frameA.p ); + b3Vec3 rB = b3RotateVector( stateB->deltaRotation, joint->frameB.p ); + b3Vec3 d = b3Add( b3Add( b3Sub( stateB->deltaPosition, stateA->deltaPosition ), joint->deltaCenter ), b3Sub( rB, rA ) ); + b3Vec3 jointAxis = b3RotateVector( stateA->deltaRotation, joint->jointAxis ); + b3Vec3 sAx = b3Cross( b3Add( rA, d ), jointAxis ); + b3Vec3 sBx = b3Cross( rB, jointAxis ); + + b3Vec3 perpY = b3RotateVector( stateA->deltaRotation, joint->perpAxisY ); + b3Vec3 perpZ = b3RotateVector( stateA->deltaRotation, joint->perpAxisZ ); + b3Vec3 sAy = b3Cross( b3Add( rA, d ), perpY ); + b3Vec3 sBy = b3Cross( rB, perpY ); + b3Vec3 sAz = b3Cross( b3Add( rA, d ), perpZ ); + b3Vec3 sBz = b3Cross( rB, perpZ ); + + float axialImpulse = joint->springImpulse + joint->motorImpulse + joint->lowerImpulse - joint->upperImpulse; + b3Vec2 perpImpulse = joint->perpImpulse; + + b3Vec3 P = b3Blend3( axialImpulse, jointAxis, perpImpulse.x, perpY, perpImpulse.y, perpZ ); + b3Vec3 LA = b3Add( b3Blend3( axialImpulse, sAx, perpImpulse.x, sAy, perpImpulse.y, sAz ), joint->angularImpulse ); + b3Vec3 LB = b3Add( b3Blend3( axialImpulse, sBx, perpImpulse.x, sBy, perpImpulse.y, sBz ), joint->angularImpulse ); + + b3Vec3 vA = stateA->linearVelocity; + b3Vec3 wA = stateA->angularVelocity; + b3Vec3 vB = stateB->linearVelocity; + b3Vec3 wB = stateB->angularVelocity; + vA = b3MulSub( vA, mA, P ); + wA = b3Sub( wA, b3MulMV( iA, LA ) ); + vB = b3MulAdd( vB, mB, P ); + wB = b3Add( wB, b3MulMV( iB, LB ) ); + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->linearVelocity = vA; + stateA->angularVelocity = wA; + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->linearVelocity = vB; + stateB->angularVelocity = wB; + } +} + +void b3SolvePrismaticJoint( b3JointSim* base, b3StepContext* context, bool useBias ) +{ + float mA = base->invMassA; + float mB = base->invMassB; + b3Matrix3 iA = base->invIA; + b3Matrix3 iB = base->invIB; + + // dummy state for static bodies + b3BodyState dummyState = b3_identityBodyState; + + b3PrismaticJoint* joint = &base->prismaticJoint; + b3BodyState* stateA = joint->indexA == B3_NULL_INDEX ? &dummyState : context->states + joint->indexA; + b3BodyState* stateB = joint->indexB == B3_NULL_INDEX ? &dummyState : context->states + joint->indexB; + + b3Vec3 vA = stateA->linearVelocity; + b3Vec3 wA = stateA->angularVelocity; + b3Vec3 vB = stateB->linearVelocity; + b3Vec3 wB = stateB->angularVelocity; + + bool fixedRotation = base->fixedRotation; + b3Vec3 rA = b3RotateVector( stateA->deltaRotation, joint->frameA.p ); + b3Vec3 rB = b3RotateVector( stateB->deltaRotation, joint->frameB.p ); + + b3Vec3 dcA = stateA->deltaPosition; + b3Vec3 dcB = stateB->deltaPosition; + b3Vec3 d = b3Add( b3Add( b3Sub( dcB, dcA ), joint->deltaCenter ), b3Sub( rB, rA ) ); + + b3Vec3 jointAxis = b3RotateVector( stateA->deltaRotation, joint->jointAxis ); + b3Vec3 sAx = b3Cross( b3Add( rA, d ), jointAxis ); + b3Vec3 sBx = b3Cross( rB, jointAxis ); + float jointTranslation = b3Dot( d, jointAxis ); + float targetTranslation = joint->targetTranslation; + + // The axial effective mass must be fresh to avoid divergence when the joint is stressed + float ka = mA + mB + b3Dot( sAx, b3MulMV( iA, sAx ) ) + b3Dot( sBx, b3MulMV( iB, sBx ) ); + float axialMass = ka > 0.0f ? 1.0f / ka : 0.0f; + + // Solve spring + if ( joint->enableSpring && fixedRotation == false ) + { + // Get the substep relative rotation + float c = jointTranslation - targetTranslation; + + float bias = joint->springSoftness.biasRate * c; + float massScale = joint->springSoftness.massScale; + float impulseScale = joint->springSoftness.impulseScale; + + b3Vec3 vRel = b3Sub( b3Sub( b3Add( vB, b3Cross( wB, rB ) ), vA ), b3Cross( wA, b3Add( rA, d ) ) ); + float cdot = b3Dot( vRel, jointAxis ); + float deltaImpulse = -massScale * axialMass * ( cdot + bias ) - impulseScale * joint->springImpulse; + joint->springImpulse += deltaImpulse; + + b3Vec3 P = b3MulSV( deltaImpulse, jointAxis ); + b3Vec3 LA = b3MulSV( deltaImpulse, sAx ); + b3Vec3 LB = b3MulSV( deltaImpulse, sBx ); + + vA = b3MulSub( vA, mA, P ); + wA = b3Sub( wA, b3MulMV( iA, LA ) ); + vB = b3MulAdd( vB, mB, P ); + wB = b3Add( wB, b3MulMV( iB, LB ) ); + } + + if ( joint->enableMotor && fixedRotation == false ) + { + b3Vec3 vRel = b3Sub( b3Sub( b3Add( vB, b3Cross( wB, rB ) ), vA ), b3Cross( wA, b3Add( rA, d ) ) ); + float cdot = b3Dot( vRel, jointAxis ) - joint->motorSpeed; + + float deltaImpulse = -axialMass * cdot; + float newImpulse = joint->motorImpulse + deltaImpulse; + float maxImpulse = joint->maxMotorForce * context->h; + newImpulse = b3ClampFloat( newImpulse, -maxImpulse, maxImpulse ); + deltaImpulse = newImpulse - joint->motorImpulse; + joint->motorImpulse = newImpulse; + + b3Vec3 P = b3MulSV( deltaImpulse, jointAxis ); + b3Vec3 LA = b3MulSV( deltaImpulse, sAx ); + b3Vec3 LB = b3MulSV( deltaImpulse, sBx ); + + vA = b3MulSub( vA, mA, P ); + wA = b3Sub( wA, b3MulMV( iA, LA ) ); + vB = b3MulAdd( vB, mB, P ); + wB = b3Add( wB, b3MulMV( iB, LB ) ); + } + + if ( joint->enableLimit && fixedRotation == false ) + { + float speculativeDistance = 0.25f * ( joint->upperTranslation - joint->lowerTranslation ); + + // Lower limit + { + float C = jointTranslation - joint->lowerTranslation; + + if ( C < speculativeDistance ) + { + 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; + } + + b3Vec3 vRel = b3Sub( b3Sub( b3Add( vB, b3Cross( wB, rB ) ), vA ), b3Cross( wA, b3Add( rA, d ) ) ); + float cdot = b3Dot( vRel, jointAxis ); + float oldImpulse = joint->lowerImpulse; + float deltaImpulse = -massScale * axialMass * ( cdot + bias ) - impulseScale * oldImpulse; + joint->lowerImpulse = b3MaxFloat( oldImpulse + deltaImpulse, 0.0f ); + deltaImpulse = joint->lowerImpulse - oldImpulse; + + b3Vec3 P = b3MulSV( deltaImpulse, jointAxis ); + b3Vec3 LA = b3MulSV( deltaImpulse, sAx ); + b3Vec3 LB = b3MulSV( deltaImpulse, sBx ); + + vA = b3MulSub( vA, mA, P ); + wA = b3Sub( wA, b3MulMV( iA, LA ) ); + vB = b3MulAdd( vB, mB, P ); + wB = b3Add( wB, b3MulMV( iB, LB ) ); + } + else + { + joint->lowerImpulse = 0.0f; + } + } + + // Upper limit + { + float C = joint->upperTranslation - jointTranslation; + + if ( C < speculativeDistance ) + { + 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 + b3Vec3 vRel = b3Sub( b3Sub( b3Add( vB, b3Cross( wB, rB ) ), vA ), b3Cross( wA, b3Add( rA, d ) ) ); + float cdot = -b3Dot( vRel, jointAxis ); + float oldImpulse = joint->upperImpulse; + float deltaImpulse = -massScale * axialMass * ( cdot + bias ) - impulseScale * oldImpulse; + joint->upperImpulse = b3MaxFloat( oldImpulse + deltaImpulse, 0.0f ); + + // sign flipped on applied impulse + float negDeltaImpulse = oldImpulse - joint->upperImpulse; + b3Vec3 P = b3MulSV( negDeltaImpulse, jointAxis ); + b3Vec3 LA = b3MulSV( negDeltaImpulse, sAx ); + b3Vec3 LB = b3MulSV( negDeltaImpulse, sBx ); + + vA = b3MulSub( vA, mA, P ); + wA = b3Sub( wA, b3MulMV( iA, LA ) ); + vB = b3MulAdd( vB, mB, P ); + wB = b3Add( wB, b3MulMV( iB, LB ) ); + } + else + { + joint->upperImpulse = 0.0f; + } + } + } + + // Rotation constraint + if ( fixedRotation == false ) + { + b3Vec3 bias = { 0.0f, 0.0f, 0.0f }; + float massScale = 1.0f; + float impulseScale = 0.0f; + + if ( useBias ) + { + b3Quat quatA = b3MulQuat( stateA->deltaRotation, joint->frameA.q ); + b3Quat quatB = b3MulQuat( stateB->deltaRotation, joint->frameB.q ); + + b3Quat relQ = b3InvMulQuat( quatA, quatB ); + b3Quat targetQuat = b3Quat_identity; + b3Vec3 deltaRotation = b3DeltaQuatToRotation( relQ, targetQuat ); + b3Vec3 c = b3Neg( b3RotateVector( quatA, deltaRotation ) ); + + bias = b3MulSV( base->constraintSoftness.biasRate, c ); + massScale = base->constraintSoftness.massScale; + impulseScale = base->constraintSoftness.impulseScale; + } + + b3Vec3 cdot = b3Sub( wB, wA ); + b3Vec3 impulse = b3Sub( + b3MulSV( -massScale, b3MulMV( joint->rotationMass, b3Add( cdot, bias ) ) ), + b3MulSV( impulseScale, joint->angularImpulse ) ); + joint->angularImpulse = b3Add( joint->angularImpulse, impulse ); + + wA = b3Sub( wA, b3MulMV( iA, impulse ) ); + wB = b3Add( wB, b3MulMV( iB, impulse ) ); + } + + // Solve point-to-line constraint + { + b3Vec3 perpY = b3RotateVector( stateA->deltaRotation, joint->perpAxisY ); + b3Vec3 perpZ = b3RotateVector( stateA->deltaRotation, joint->perpAxisZ ); + + b3Vec2 bias = { 0.0f, 0.0f }; + float massScale = 1.0f; + float impulseScale = 0.0f; + if ( useBias ) + { + b3Vec2 c = { b3Dot( perpY, d ), b3Dot( perpZ, d ) }; + bias = b3MulSV2( base->constraintSoftness.biasRate, c ); + massScale = base->constraintSoftness.massScale; + impulseScale = base->constraintSoftness.impulseScale; + } + + b3Vec3 vRel = b3Sub( b3Sub( b3Add( vB, b3Cross( wB, rB ) ), vA ), b3Cross( wA, b3Add( rA, d ) ) ); + b3Vec2 cdot = { b3Dot( perpY, vRel ), b3Dot( perpZ, vRel ) }; + + // K = [(1/mA + 1/mB) * eye(2) - skew(rA) * invIA * skew(rA) - skew(rB) * invIB * skew(rB)] + // Jx = [-perpX, -cross(d + rA, perpX), perpX, cross(rB, perpX)] + b3Vec3 sAy = b3Cross( b3Add( rA, d ), perpY ); + b3Vec3 sBy = b3Cross( rB, perpY ); + b3Vec3 sAz = b3Cross( b3Add( rA, d ), perpZ ); + b3Vec3 sBz = b3Cross( rB, perpZ ); + + float kyy = mA + mB + b3Dot( sAy, b3MulMV( iA, sAy ) ) + b3Dot( sBy, b3MulMV( iB, sBy ) ); + float kyz = b3Dot( sAy, b3MulMV( iA, sAz ) ) + b3Dot( sBy, b3MulMV( iB, sBz ) ); + float kzz = mA + mB + b3Dot( sAz, b3MulMV( iA, sAz ) ) + b3Dot( sBz, b3MulMV( iB, sBz ) ); + + b3Matrix2 K = { { kyy, kyz }, { kyz, kzz } }; + + b3Vec2 oldImpulse = joint->perpImpulse; + b3Vec2 sol = b3Solve2( K, b3Add2( cdot, bias ) ); + b3Vec2 deltaImpulse = b3Sub2( b3MulSV2( -massScale, sol ), b3MulSV2( impulseScale, oldImpulse ) ); + joint->perpImpulse = b3Add2( oldImpulse, deltaImpulse ); + + b3Vec3 P = b3Blend2( deltaImpulse.x, perpY, deltaImpulse.y, perpZ ); + + vA = b3MulSub( vA, mA, P ); + wA = b3Sub( wA, b3MulMV( iA, b3Blend2( deltaImpulse.x, sAy, deltaImpulse.y, sAz ) ) ); + vB = b3MulAdd( vB, mB, P ); + wB = b3Add( wB, b3MulMV( iB, b3Blend2( deltaImpulse.x, sBy, deltaImpulse.y, sBz ) ) ); + } + + B3_ASSERT( b3IsValidVec3( vA ) ); + B3_ASSERT( b3IsValidVec3( wA ) ); + B3_ASSERT( b3IsValidVec3( vB ) ); + B3_ASSERT( b3IsValidVec3( wB ) ); + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->linearVelocity = vA; + stateA->angularVelocity = wA; + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->linearVelocity = vB; + stateB->angularVelocity = wB; + } +} + +void b3DrawPrismaticJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale ) +{ + b3Transform frameA = b3MulTransforms( transformA, base->localFrameA ); + b3Transform frameB = b3MulTransforms( transformB, base->localFrameB ); + + b3Matrix3 R = b3MakeMatrixFromQuat( frameA.q ); + b3Vec3 axis = R.cx; + b3Vec3 perpY = R.cy; + b3Vec3 perpZ = R.cz; + + float s = 0.2f * scale; + draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, s, perpY ), b3_colorGreen, draw->context ); + draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, s, perpZ ), b3_colorBlue, draw->context ); + + b3PrismaticJoint* joint = &base->prismaticJoint; + if ( joint->enableLimit ) + { + b3Vec3 p1 = b3MulAdd( frameA.p, joint->lowerTranslation, axis ); + b3Vec3 p2 = b3MulAdd( frameA.p, joint->upperTranslation, axis ); + draw->DrawSegmentFcn( p1, p2, b3_colorOrange, draw->context ); + draw->DrawPointFcn( p1, 10.0f, b3_colorGreen, draw->context ); + draw->DrawPointFcn( p2, 10.0f, b3_colorRed, draw->context ); + } + else + { + b3Vec3 p1 = b3MulSub( frameA.p, 0.5f * scale, axis ); + b3Vec3 p2 = b3MulAdd( frameA.p, 0.5f * scale, axis ); + draw->DrawSegmentFcn( p1, p2, b3_colorOrange, draw->context ); + } + + draw->DrawPointFcn( frameB.p, 8.0f, b3_colorViolet, draw->context ); +} diff --git a/src/qsort.h b/src/qsort.h new file mode 100644 index 0000000..9ab426b --- /dev/null +++ b/src/qsort.h @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2013, 2017 Alexey Tourbin + * + * 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. + */ + +/* + * This is a traditional Quicksort implementation which mostly follows + * [Sedgewick 1978]. Sorting is performed entirely on array indices, + * while actual access to the array elements is abstracted out with the + * user-defined `LESS` and `SWAP` primitives. + * + * Synopsis: + * QSORT(N, LESS, SWAP); + * where + * N - the number of elements in A[]; + * LESS(i, j) - compares A[i] to A[j]; + * SWAP(i, j) - exchanges A[i] with A[j]. + */ + +#ifndef QSORT_H +#define QSORT_H + +/* Sort 3 elements. */ +#define Q_SORT3(q_a1, q_a2, q_a3, Q_LESS, Q_SWAP) \ +do { \ + if (Q_LESS(q_a2, q_a1)) { \ + if (Q_LESS(q_a3, q_a2)) \ + Q_SWAP(q_a1, q_a3); \ + else { \ + Q_SWAP(q_a1, q_a2); \ + if (Q_LESS(q_a3, q_a2)) \ + Q_SWAP(q_a2, q_a3); \ + } \ + } \ + else if (Q_LESS(q_a3, q_a2)) { \ + Q_SWAP(q_a2, q_a3); \ + if (Q_LESS(q_a2, q_a1)) \ + Q_SWAP(q_a1, q_a2); \ + } \ +} while (0) + +/* Partition [q_l,q_r] around a pivot. After partitioning, + * [q_l,q_j] are the elements that are less than or equal to the pivot, + * while [q_i,q_r] are the elements greater than or equal to the pivot. */ +#define Q_PARTITION(q_l, q_r, q_i, q_j, Q_UINT, Q_LESS, Q_SWAP) \ +do { \ + /* The middle element, not to be confused with the median. */ \ + Q_UINT q_m = q_l + ((q_r - q_l) >> 1); \ + /* Reorder the second, the middle, and the last items. \ + * As [Edelkamp Weiss 2016] explain, using the second element \ + * instead of the first one helps avoid bad behaviour for \ + * decreasingly sorted arrays. This method is used in recent \ + * versions of gcc's std::sort, see gcc bug 58437#c13, although \ + * the details are somewhat different (cf. #c14). */ \ + Q_SORT3(q_l + 1, q_m, q_r, Q_LESS, Q_SWAP); \ + /* Place the median at the beginning. */ \ + Q_SWAP(q_l, q_m); \ + /* Partition [q_l+2, q_r-1] around the median which is in q_l. \ + * q_i and q_j are initially off by one, they get decremented \ + * in the do-while loops. */ \ + q_i = q_l + 1; q_j = q_r; \ + while (1) { \ + do q_i++; while (Q_LESS(q_i, q_l)); \ + do q_j--; while (Q_LESS(q_l, q_j)); \ + if (q_i >= q_j) break; /* Sedgewick says "until j < i" */ \ + Q_SWAP(q_i, q_j); \ + } \ + /* Compensate for the i==j case. */ \ + q_i = q_j + 1; \ + /* Put the median to its final place. */ \ + Q_SWAP(q_l, q_j); \ + /* The median is not part of the left subfile. */ \ + q_j--; \ +} while (0) + +/* Insertion sort is applied to small subfiles - this is contrary to + * Sedgewick's suggestion to run a separate insertion sort pass after + * the partitioning is done. The reason I don't like a separate pass + * is that it triggers extra comparisons, because it can't see that the + * medians are already in their final positions and need not be rechecked. + * Since I do not assume that comparisons are cheap, I also do not try + * to eliminate the (q_j > q_l) boundary check. */ +#define Q_INSERTION_SORT(q_l, q_r, Q_UINT, Q_LESS, Q_SWAP) \ +do { \ + Q_UINT q_i, q_j; \ + /* For each item starting with the second... */ \ + for (q_i = q_l + 1; q_i <= q_r; q_i++) \ + /* move it down the array so that the first part is sorted. */ \ + for (q_j = q_i; q_j > q_l && (Q_LESS(q_j, q_j - 1)); q_j--) \ + Q_SWAP(q_j, q_j - 1); \ +} while (0) + +/* When the size of [q_l,q_r], i.e. q_r-q_l+1, is greater than or equal to + * Q_THRESH, the algorithm performs recursive partitioning. When the size + * drops below Q_THRESH, the algorithm switches to insertion sort. + * The minimum valid value is probably 5 (with 5 items, the second and + * the middle items, the middle itself being rounded down, are distinct). */ +#define Q_THRESH 16 + +/* The main loop. */ +#define Q_LOOP(Q_UINT, Q_N, Q_LESS, Q_SWAP) \ +do { \ + Q_UINT q_l = 0; \ + Q_UINT q_r = (Q_N) - 1; \ + Q_UINT q_sp = 0; /* the number of frames pushed to the stack */ \ + struct { Q_UINT q_l, q_r; } \ + /* On 32-bit platforms, to sort a "char[3GB+]" array, \ + * it may take full 32 stack frames. On 64-bit CPUs, \ + * though, the address space is limited to 48 bits. \ + * The usage is further reduced if Q_N has a 32-bit type. */ \ + q_st[sizeof(Q_UINT) > 4 && sizeof(Q_N) > 4 ? 48 : 32]; \ + while (1) { \ + if (q_r - q_l + 1 >= Q_THRESH) { \ + Q_UINT q_i, q_j; \ + Q_PARTITION(q_l, q_r, q_i, q_j, Q_UINT, Q_LESS, Q_SWAP); \ + /* Now have two subfiles: [q_l,q_j] and [q_i,q_r]. \ + * Dealing with them depends on which one is bigger. */ \ + if (q_j - q_l >= q_r - q_i) \ + Q_SUBFILES(q_l, q_j, q_i, q_r); \ + else \ + Q_SUBFILES(q_i, q_r, q_l, q_j); \ + } \ + else { \ + Q_INSERTION_SORT(q_l, q_r, Q_UINT, Q_LESS, Q_SWAP); \ + /* Pop subfiles from the stack, until it gets empty. */ \ + if (q_sp == 0) break; \ + q_sp--; \ + q_l = q_st[q_sp].q_l; \ + q_r = q_st[q_sp].q_r; \ + } \ + } \ +} while (0) + +/* The missing part: dealing with subfiles. + * Assumes that the first subfile is not smaller than the second. */ +#define Q_SUBFILES(q_l1, q_r1, q_l2, q_r2) \ +do { \ + /* If the second subfile is only a single element, it needs \ + * no further processing. The first subfile will be processed \ + * on the next iteration (both subfiles cannot be only a single \ + * element, due to Q_THRESH). */ \ + if (q_l2 == q_r2) { \ + q_l = q_l1; \ + q_r = q_r1; \ + } \ + else { \ + /* Otherwise, both subfiles need processing. \ + * Push the larger subfile onto the stack. */ \ + q_st[q_sp].q_l = q_l1; \ + q_st[q_sp].q_r = q_r1; \ + q_sp++; \ + /* Process the smaller subfile on the next iteration. */ \ + q_l = q_l2; \ + q_r = q_r2; \ + } \ +} while (0) + +/* And now, ladies and gentlemen, may I proudly present to you... */ +#define QSORT(Q_N, Q_LESS, Q_SWAP) \ +do { \ + if ((Q_N) > 1) \ + /* We could check sizeof(Q_N) and use "unsigned", but at least \ + * on x86_64, this has the performance penalty of up to 5%. */ \ + Q_LOOP(unsigned long, Q_N, Q_LESS, Q_SWAP); \ +} while (0) + +#endif + +/* ex:set ts=8 sts=4 sw=4 noet: */ diff --git a/src/revolute_joint.c b/src/revolute_joint.c new file mode 100644 index 0000000..afe5958 --- /dev/null +++ b/src/revolute_joint.c @@ -0,0 +1,649 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "body.h" +#include "joint.h" +#include "math_internal.h" +#include "physics_world.h" +#include "solver.h" +#include "solver_set.h" + +// needed for dll export +#include "box3d/box3d.h" + +// Point-to-point linear constraint +// C = pB - pA +// Cdot = vB - vA +// = vB + cross(wB, rB) - vA - cross(wA, rA) +// Cdot = J * v +// J = [-E -skew(rA) E skew(rB) ] +// +// K = J * invM * JT +// = [(1/mA + 1/mB) * E - skew(rA) * invIA * skew(rA) - skew(rB) * invIB * skew(rB)] + +// Perpendicularity constraint +// frameA = qA * localFrameA +// frameB = qB * localFrameB +// qRel = conj(frameA) * frameB +// C = [qRel.x; qRel.y] +// qRelDot = 0.5 * conj(frameA) * (wB - wA) * frameB +// Cdot = [qRelDot.x, qRelDot.y] +// Pulling out wB and wA +// sr = qRel.s +// vr = qRel.v +// Jx = 0.5 * rotate(frameA, sr * ex + cross(vr, ex)) +// Jy = 0.5 * rotate(frameA, sr * ey + cross(vr, ey)) + +// Motor constraint +// Cdot = wB - wA +// J = [0 0 -E 0 0 E] +// K = invIA + invIB + +void b3RevoluteJoint_EnableLimit( b3JointId jointId, bool enableLimit ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + if ( enableLimit != base->revoluteJoint.enableLimit ) + { + base->revoluteJoint.lowerImpulse = 0.0f; + base->revoluteJoint.upperImpulse = 0.0f; + } + base->revoluteJoint.enableLimit = enableLimit; +} + +bool b3RevoluteJoint_IsLimitEnabled( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + return base->revoluteJoint.enableLimit; +} + +float b3RevoluteJoint_GetLowerLimit( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + return base->revoluteJoint.lowerAngle; +} + +float b3RevoluteJoint_GetUpperLimit( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + return base->revoluteJoint.upperAngle; +} + +void b3RevoluteJoint_SetLimits( b3JointId jointId, float lowerLimitRadians, float upperLimitRadians ) +{ + B3_ASSERT( lowerLimitRadians <= upperLimitRadians ); + B3_ASSERT( b3IsValidFloat( lowerLimitRadians ) && b3IsValidFloat( upperLimitRadians ) ); + float lowerAngle = b3ClampFloat( lowerLimitRadians, -B3_PI, B3_PI ); + float upperAngle = b3ClampFloat( upperLimitRadians, -B3_PI, B3_PI ); + + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + base->revoluteJoint.lowerAngle = lowerAngle; + base->revoluteJoint.upperAngle = upperAngle; + base->revoluteJoint.lowerImpulse = 0.0f; + base->revoluteJoint.upperImpulse = 0.0f; +} + +float b3RevoluteJoint_GetAngle( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA ); + b3Transform transformB = b3GetBodyTransform( world, base->bodyIdB ); + + b3Quat quatA = b3MulQuat( transformA.q, base->localFrameA.q ); + b3Quat quatB = b3MulQuat( transformB.q, base->localFrameB.q ); + + if ( b3DotQuat( quatA, quatB ) < 0.0f ) + { + // this keeps the twist angle in the range [-pi, pi] + quatB = b3NegateQuat( quatB ); + } + + b3Quat relQ = b3InvMulQuat( quatA, quatB ); + + return b3GetTwistAngle( relQ ); +} + +void b3RevoluteJoint_EnableSpring( b3JointId jointId, bool enableSpring ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + if ( enableSpring != base->revoluteJoint.enableSpring ) + { + base->revoluteJoint.springImpulse = 0.0f; + } + base->revoluteJoint.enableSpring = enableSpring; +} + +bool b3RevoluteJoint_IsSpringEnabled( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + return base->revoluteJoint.enableSpring; +} + +void b3RevoluteJoint_SetTargetAngle( b3JointId jointId, float targetRadians ) +{ + B3_ASSERT( b3IsValidFloat( targetRadians ) && -B3_PI <= targetRadians && targetRadians <= B3_PI ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + base->revoluteJoint.targetAngle = targetRadians; +} + +float b3RevoluteJoint_GetTargetAngle( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + return base->revoluteJoint.targetAngle; +} + +void b3RevoluteJoint_SetSpringHertz( b3JointId jointId, float hertz ) +{ + B3_ASSERT( b3IsValidFloat( hertz ) && hertz >= 0.0f ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + base->revoluteJoint.hertz = hertz; +} + +float b3RevoluteJoint_GetSpringHertz( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + return base->revoluteJoint.hertz; +} + +void b3RevoluteJoint_SetSpringDampingRatio( b3JointId jointId, float dampingRatio ) +{ + B3_ASSERT( b3IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + base->revoluteJoint.dampingRatio = dampingRatio; +} + +float b3RevoluteJoint_GetSpringDampingRatio( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + return base->revoluteJoint.dampingRatio; +} + +void b3RevoluteJoint_EnableMotor( b3JointId jointId, bool enableMotor ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + if ( enableMotor != base->revoluteJoint.enableMotor ) + { + base->revoluteJoint.motorImpulse = 0.0f; + } + base->revoluteJoint.enableMotor = enableMotor; +} + +bool b3RevoluteJoint_IsMotorEnabled( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + return base->revoluteJoint.enableMotor; +} + +void b3RevoluteJoint_SetMotorSpeed( b3JointId jointId, float motorSpeed ) +{ + B3_ASSERT( b3IsValidFloat( motorSpeed ) ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + base->revoluteJoint.motorSpeed = motorSpeed; +} + +float b3RevoluteJoint_GetMotorSpeed( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + return base->revoluteJoint.motorSpeed; +} + +void b3RevoluteJoint_SetMaxMotorTorque( b3JointId jointId, float maxForce ) +{ + B3_ASSERT( b3IsValidFloat( maxForce ) && maxForce >= 0.0f ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + base->revoluteJoint.maxMotorTorque = maxForce; +} + +float b3RevoluteJoint_GetMaxMotorTorque( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint ); + return base->revoluteJoint.maxMotorTorque; +} + +b3Vec3 b3GetRevoluteJointForce( b3World* world, b3JointSim* base ) +{ + b3Vec3 force = b3MulSV( world->inv_h, base->revoluteJoint.linearImpulse ); + return force; +} + +b3Vec3 b3GetRevoluteJointTorque( b3World* world, b3JointSim* base ) +{ + b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA ); + b3RevoluteJoint* joint = &base->revoluteJoint; + b3Vec3 axis = b3RotateVector( base->localFrameA.q, b3Vec3_axisZ ); + axis = b3RotateVector( transformA.q, axis ); + + b3Quat relQ = b3InvMulQuat( joint->frameA.q, joint->frameB.q ); + + // These are needed for warm starting + joint->perpAxisX = b3MulSV( + 0.5f, b3RotateVector( joint->frameA.q, b3Add( b3MulSV( relQ.s, b3Vec3_axisX ), b3Cross( relQ.v, b3Vec3_axisX ) ) ) ); + joint->perpAxisY = b3MulSV( + 0.5f, b3RotateVector( joint->frameA.q, b3Add( b3MulSV( relQ.s, b3Vec3_axisY ), b3Cross( relQ.v, b3Vec3_axisY ) ) ) ); + + float axialImpulse = joint->springImpulse + joint->motorImpulse + joint->lowerImpulse - joint->upperImpulse; + b3Vec3 angularImpulse = + b3Add( b3MulSV( joint->perpImpulse.x, joint->perpAxisX ), b3MulSV( joint->perpImpulse.y, joint->perpAxisY ) ); + angularImpulse = b3MulAdd( angularImpulse, axialImpulse, joint->rotationAxisZ ); + + // todo add pivot torque + b3Vec3 impulse = b3MulAdd( angularImpulse, + joint->springImpulse + joint->motorImpulse + joint->lowerImpulse - joint->upperImpulse, axis ); + b3Vec3 torque = b3MulSV( world->inv_h, impulse ); + return torque; +} + +void b3PrepareRevoluteJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_revoluteJoint ); + + b3World* world = context->world; + + b3Body* bodyA = b3Array_Get( world->bodies, base->bodyIdA ); + b3Body* bodyB = b3Array_Get( world->bodies, base->bodyIdB ); + + B3_ASSERT( bodyA->setIndex == b3_awakeSet || bodyB->setIndex == b3_awakeSet ); + b3SolverSet* setA = b3Array_Get( world->solverSets, bodyA->setIndex ); + b3SolverSet* setB = b3Array_Get( world->solverSets, bodyB->setIndex ); + + int localIndexA = bodyA->localIndex; + int localIndexB = bodyB->localIndex; + + b3BodySim* bodySimA = b3Array_Get( setA->bodySims, localIndexA ); + b3BodySim* bodySimB = b3Array_Get( setB->bodySims, localIndexB ); + + base->invMassA = bodySimA->invMass; + base->invMassB = bodySimB->invMass; + base->invIA = bodySimA->invInertiaWorld; + base->invIB = bodySimB->invInertiaWorld; + + b3Matrix3 invInertiaSum = b3AddMM( base->invIA, base->invIB ); + base->fixedRotation = b3Det( invInertiaSum ) < 1000.0f * FLT_MIN; + + b3RevoluteJoint* joint = &base->revoluteJoint; + joint->indexA = bodyA->setIndex == b3_awakeSet ? localIndexA : B3_NULL_INDEX; + joint->indexB = bodyB->setIndex == b3_awakeSet ? localIndexB : B3_NULL_INDEX; + + // Compute joint anchor frames with world space rotation, relative to center of mass + // Avoid round-off here as much as possible. + // b3Vec3 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 = b3MulQuat( bodySimA->transform.q, base->localFrameA.q ); + joint->frameA.p = b3RotateVector( bodySimA->transform.q, b3Sub( base->localFrameA.p, bodySimA->localCenter ) ); + joint->frameB.q = b3MulQuat( bodySimB->transform.q, base->localFrameB.q ); + joint->frameB.p = b3RotateVector( bodySimB->transform.q, b3Sub( base->localFrameB.p, bodySimB->localCenter ) ); + + joint->deltaCenter = b3Sub( bodySimB->center, bodySimA->center ); + + { + // Rotation axis is the z-axis of body A. + b3Vec3 rotationAxisZ = b3RotateVector( joint->frameA.q, b3Vec3_axisZ ); + float k = b3Dot( rotationAxisZ, b3MulMV( invInertiaSum, rotationAxisZ ) ); + joint->axialMass = k > 0.0f ? 1.0f / k : 0.0f; + joint->rotationAxisZ = rotationAxisZ; + } + + b3Quat relQ = b3InvMulQuat( joint->frameA.q, joint->frameB.q ); + + { + // These are needed for warm starting + joint->perpAxisX = b3MulSV( + 0.5f, b3RotateVector( joint->frameA.q, b3Add( b3MulSV( relQ.s, b3Vec3_axisX ), b3Cross( relQ.v, b3Vec3_axisX ) ) ) ); + joint->perpAxisY = b3MulSV( + 0.5f, b3RotateVector( joint->frameA.q, b3Add( b3MulSV( relQ.s, b3Vec3_axisY ), b3Cross( relQ.v, b3Vec3_axisY ) ) ) ); + } + + joint->springSoftness = b3MakeSoft( joint->hertz, joint->dampingRatio, context->h ); + + if ( context->enableWarmStarting == false ) + { + joint->linearImpulse = b3Vec3_zero; + joint->perpImpulse = (b3Vec2){ 0.0f, 0.0f }; + joint->motorImpulse = 0.0f; + joint->springImpulse = 0.0f; + joint->lowerImpulse = 0.0f; + joint->upperImpulse = 0.0f; + } +} + +void b3WarmStartRevoluteJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_revoluteJoint ); + + float mA = base->invMassA; + float mB = base->invMassB; + b3Matrix3 iA = base->invIA; + b3Matrix3 iB = base->invIB; + + // dummy state for static bodies + b3BodyState dummyState = b3_identityBodyState; + + b3RevoluteJoint* joint = &base->revoluteJoint; + + b3BodyState* stateA = joint->indexA == B3_NULL_INDEX ? &dummyState : context->states + joint->indexA; + b3BodyState* stateB = joint->indexB == B3_NULL_INDEX ? &dummyState : context->states + joint->indexB; + + b3Vec3 vA = stateA->linearVelocity; + b3Vec3 wA = stateA->angularVelocity; + b3Vec3 vB = stateB->linearVelocity; + b3Vec3 wB = stateB->angularVelocity; + + b3Vec3 rA = b3RotateVector( stateA->deltaRotation, joint->frameA.p ); + b3Vec3 rB = b3RotateVector( stateB->deltaRotation, joint->frameB.p ); + + float axialImpulse = joint->springImpulse + joint->motorImpulse + joint->lowerImpulse - joint->upperImpulse; + b3Vec3 angularImpulse = + b3Add( b3MulSV( joint->perpImpulse.x, joint->perpAxisX ), b3MulSV( joint->perpImpulse.y, joint->perpAxisY ) ); + angularImpulse = b3MulAdd( angularImpulse, axialImpulse, joint->rotationAxisZ ); + + vA = b3MulSub( vA, mA, joint->linearImpulse ); + wA = b3Sub( wA, b3MulMV( iA, b3Add( b3Cross( rA, joint->linearImpulse ), angularImpulse ) ) ); + + vB = b3MulAdd( vB, mB, joint->linearImpulse ); + wB = b3Add( wB, b3MulMV( iB, b3Add( b3Cross( rB, joint->linearImpulse ), angularImpulse ) ) ); + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->linearVelocity = vA; + stateA->angularVelocity = wA; + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->linearVelocity = vB; + stateB->angularVelocity = wB; + } +} + +void b3SolveRevoluteJoint( b3JointSim* base, b3StepContext* context, bool useBias ) +{ + float mA = base->invMassA; + float mB = base->invMassB; + b3Matrix3 iA = base->invIA; + b3Matrix3 iB = base->invIB; + + // dummy state for static bodies + b3BodyState dummyState = b3_identityBodyState; + + b3RevoluteJoint* joint = &base->revoluteJoint; + b3BodyState* stateA = joint->indexA == B3_NULL_INDEX ? &dummyState : context->states + joint->indexA; + b3BodyState* stateB = joint->indexB == B3_NULL_INDEX ? &dummyState : context->states + joint->indexB; + + b3Vec3 vA = stateA->linearVelocity; + b3Vec3 wA = stateA->angularVelocity; + b3Vec3 vB = stateB->linearVelocity; + b3Vec3 wB = stateB->angularVelocity; + + bool fixedRotation = base->fixedRotation; + b3Quat quatA = b3MulQuat( stateA->deltaRotation, joint->frameA.q ); + b3Quat quatB = b3MulQuat( stateB->deltaRotation, joint->frameB.q ); + + if ( b3DotQuat( quatA, quatB ) < 0.0f ) + { + // this keeps the rotation angle in the range [-pi, pi] + quatB = b3NegateQuat( quatB ); + } + + b3Quat relQ = b3InvMulQuat( quatA, quatB ); + + // Solve spring + if ( joint->enableSpring && fixedRotation == false ) + { + // Get the substep relative rotation + float targetAngle = joint->targetAngle; + float angle = b3GetTwistAngle( relQ ); + float c = angle - targetAngle; + + float bias = joint->springSoftness.biasRate * c; + float massScale = joint->springSoftness.massScale; + float impulseScale = joint->springSoftness.impulseScale; + float cdot = b3Dot( b3Sub( wB, wA ), joint->rotationAxisZ ); + + float deltaImpulse = -massScale * joint->axialMass * ( cdot + bias ) - impulseScale * joint->springImpulse; + joint->springImpulse += deltaImpulse; + + wA = b3MulSub( wA, deltaImpulse, b3MulMV( iA, joint->rotationAxisZ ) ); + wB = b3MulAdd( wB, deltaImpulse, b3MulMV( iB, joint->rotationAxisZ ) ); + } + + if ( joint->enableMotor && fixedRotation == false ) + { + float cdot = b3Dot( b3Sub( wB, wA ), joint->rotationAxisZ ) - joint->motorSpeed; + + float deltaImpulse = -joint->axialMass * cdot; + float newImpulse = joint->motorImpulse + deltaImpulse; + float maxImpulse = joint->maxMotorTorque * context->h; + newImpulse = b3ClampFloat( newImpulse, -maxImpulse, maxImpulse ); + deltaImpulse = newImpulse - joint->motorImpulse; + joint->motorImpulse = newImpulse; + + wA = b3MulSub( wA, deltaImpulse, b3MulMV( iA, joint->rotationAxisZ ) ); + wB = b3MulAdd( wB, deltaImpulse, b3MulMV( iB, joint->rotationAxisZ ) ); + } + + if ( joint->enableLimit && fixedRotation == false ) + { + float angle = b3GetTwistAngle( relQ ); + + // todo does an updated twist axis help? + + b3Vec3 axis = joint->rotationAxisZ; + + // Lower limit + { + float c = angle - 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 = b3Dot( b3Sub( wB, wA ), axis ); + float oldImpulse = joint->lowerImpulse; + float deltaImpulse = -massScale * joint->axialMass * ( cdot + bias ) - impulseScale * oldImpulse; + joint->lowerImpulse = b3MaxFloat( oldImpulse + deltaImpulse, 0.0f ); + deltaImpulse = joint->lowerImpulse - oldImpulse; + + wA = b3MulSub( wA, deltaImpulse, b3MulMV( iA, axis ) ); + wB = b3MulAdd( wB, deltaImpulse, b3MulMV( iB, axis ) ); + } + + // Upper limit + { + float c = joint->upperAngle - angle; + 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 = b3Dot( b3Sub( wA, wB ), axis ); + float oldImpulse = joint->upperImpulse; + float deltaImpulse = -massScale * joint->axialMass * ( cdot + bias ) - impulseScale * oldImpulse; + joint->upperImpulse = b3MaxFloat( oldImpulse + deltaImpulse, 0.0f ); + deltaImpulse = joint->upperImpulse - oldImpulse; + + // sign flipped on applied impulse + wA = b3MulAdd( wA, deltaImpulse, b3MulMV( iA, axis ) ); + wB = b3MulSub( wB, deltaImpulse, b3MulMV( iB, axis ) ); + } + } + + // Collinearity constraint + if ( fixedRotation == false ) + { + b3Vec2 bias = { 0.0f, 0.0f }; + float massScale = 1.0f; + float impulseScale = 0.0f; + + if ( useBias ) + { + b3Vec2 c = { relQ.v.x, relQ.v.y }; + bias = b3MulSV2( base->constraintSoftness.biasRate, c ); + massScale = base->constraintSoftness.massScale; + impulseScale = base->constraintSoftness.impulseScale; + } + + // Collinearity constraint as 2-by-2 + b3Vec3 perpAxisX = + b3MulSV( 0.5f, b3RotateVector( quatA, b3Add( b3MulSV( relQ.s, b3Vec3_axisX ), b3Cross( relQ.v, b3Vec3_axisX ) ) ) ); + b3Vec3 perpAxisY = + b3MulSV( 0.5f, b3RotateVector( quatA, b3Add( b3MulSV( relQ.s, b3Vec3_axisY ), b3Cross( relQ.v, b3Vec3_axisY ) ) ) ); + joint->perpAxisX = perpAxisX; + joint->perpAxisY = perpAxisY; + + b3Matrix3 invInertiaSum = b3AddMM( iA, iB ); + float kxx = b3Dot( perpAxisX, b3MulMV( invInertiaSum, perpAxisX ) ); + float kyy = b3Dot( perpAxisY, b3MulMV( invInertiaSum, perpAxisY ) ); + float kxy = b3Dot( perpAxisX, b3MulMV( invInertiaSum, perpAxisY ) ); + + b3Matrix2 k = { { kxx, kxy }, { kxy, kyy } }; + + b3Vec3 wRel = b3Sub( wB, wA ); + b3Vec2 cdot = { b3Dot( wRel, perpAxisX ), b3Dot( wRel, perpAxisY ) }; + b3Vec2 oldImpulse = joint->perpImpulse; + b3Vec2 sol = b3Solve2( k, b3Add2( cdot, bias ) ); + b3Vec2 deltaImpulse = b3Sub2( b3MulSV2( -massScale, sol ), b3MulSV2( impulseScale, oldImpulse ) ); + joint->perpImpulse = b3Add2( joint->perpImpulse, deltaImpulse ); + + b3Vec3 angularImpulse = b3Add( b3MulSV( deltaImpulse.x, perpAxisX ), b3MulSV( deltaImpulse.y, perpAxisY ) ); + wA = b3Sub( wA, b3MulMV( iA, angularImpulse ) ); + wB = b3Add( wB, b3MulMV( iB, angularImpulse ) ); + } + + // Solve point-to-point constraint + { + b3Vec3 rA = b3RotateVector( stateA->deltaRotation, joint->frameA.p ); + b3Vec3 rB = b3RotateVector( stateB->deltaRotation, joint->frameB.p ); + + b3Vec3 cdot = b3Sub( b3Sub( b3Add( vB, b3Cross( wB, rB ) ), vA ), b3Cross( wA, rA ) ); + + b3Vec3 bias = b3Vec3_zero; + float massScale = 1.0f; + float impulseScale = 0.0f; + if ( useBias ) + { + b3Vec3 dcA = stateA->deltaPosition; + b3Vec3 dcB = stateB->deltaPosition; + + b3Vec3 separation = b3Add( b3Add( b3Sub( dcB, dcA ), b3Sub( rB, rA ) ), joint->deltaCenter ); + + bias = b3MulSV( base->constraintSoftness.biasRate, separation ); + massScale = base->constraintSoftness.massScale; + impulseScale = base->constraintSoftness.impulseScale; + } + + //// K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] + b3Matrix3 sA = b3Skew( rA ); + b3Matrix3 sB = b3Skew( rB ); + b3Matrix3 kA = b3MulMM( sA, b3MulMM( base->invIA, sA ) ); + b3Matrix3 kB = b3MulMM( sB, b3MulMM( base->invIB, sB ) ); + b3Matrix3 k = b3NegateMat3( b3AddMM( kA, kB ) ); + k.cx.x += mA + mB; + k.cy.y += mA + mB; + k.cz.z += mA + mB; + + b3Vec3 b = b3Solve3( k, b3Add( cdot, bias ) ); + + b3Vec3 impulse = b3Sub( b3MulSV( -massScale, b ), b3MulSV( impulseScale, joint->linearImpulse ) ); + joint->linearImpulse = b3Add( joint->linearImpulse, impulse ); + + vA = b3MulSub( vA, mA, impulse ); + wA = b3Sub( wA, b3MulMV( iA, b3Cross( rA, impulse ) ) ); + vB = b3MulAdd( vB, mB, impulse ); + wB = b3Add( wB, b3MulMV( iB, b3Cross( rB, impulse ) ) ); + } + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->linearVelocity = vA; + stateA->angularVelocity = wA; + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->linearVelocity = vB; + stateB->angularVelocity = wB; + } +} + +void b3DrawRevoluteJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale ) +{ + b3Transform frameA = b3MulTransforms( transformA, base->localFrameA ); + + float length1 = 0.1f * scale; + draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, length1, b3RotateVector( frameA.q, b3Vec3_axisX ) ), b3_colorRed, + draw->context ); + draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, length1, b3RotateVector( frameA.q, b3Vec3_axisY ) ), b3_colorGreen, + draw->context ); + draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, length1, b3RotateVector( frameA.q, b3Vec3_axisZ ) ), b3_colorBlue, + draw->context ); + + b3Transform frameB = b3MulTransforms( transformB, base->localFrameB ); + + b3RevoluteJoint* joint = &base->revoluteJoint; + enum { kSliceCount = 16 }; + + // Twist limit + if ( joint->enableLimit ) + { + b3Quat quatA = frameA.q; + b3Quat quatB = frameB.q; + + if ( b3DotQuat( quatA, quatB ) < 0.0f ) + { + // this keeps the twist angle in the range [-pi, pi] + quatB = b3NegateQuat( quatB ); + } + + b3Quat relQ = b3InvMulQuat( quatA, quatB ); + + const float wedgeRadius = 0.2f * scale; + for ( int index = 0; index < kSliceCount; ++index ) + { + float t1 = (float)( index + 0 ) / kSliceCount; + float alpha1 = ( 1.0f - t1 ) * joint->lowerAngle + t1 * joint->upperAngle; + float t2 = (float)( index + 1 ) / kSliceCount; + float alpha2 = ( 1.0f - t2 ) * joint->lowerAngle + t2 * joint->upperAngle; + + b3Vec3 vertex1 = { wedgeRadius * b3Cos( alpha1 ), wedgeRadius * b3Sin( alpha1 ), 0.0f }; + b3Vec3 vertex2 = { wedgeRadius * b3Cos( alpha2 ), wedgeRadius * b3Sin( alpha2 ), 0.0f }; + + if ( index == 0 ) + { + draw->DrawSegmentFcn( frameA.p, b3TransformPoint( frameA, vertex1 ), b3_colorCyan, draw->context ); + } + + if ( index == kSliceCount - 1 ) + { + draw->DrawSegmentFcn( b3TransformPoint( frameA, vertex2 ), frameA.p, b3_colorCyan, draw->context ); + } + draw->DrawSegmentFcn( b3TransformPoint( frameA, vertex1 ), b3TransformPoint( frameA, vertex2 ), b3_colorCyan, + draw->context ); + } + + float twistAngle = b3GetTwistAngle( relQ ); + b3Vec3 p2 = { wedgeRadius * b3Cos( twistAngle ), wedgeRadius * b3Sin( twistAngle ), 0.0f }; + draw->DrawSegmentFcn( frameA.p, b3TransformPoint( frameA, p2 ), b3_colorYellow, draw->context ); + } +} diff --git a/src/scheduler.c b/src/scheduler.c new file mode 100644 index 0000000..7bcde42 --- /dev/null +++ b/src/scheduler.c @@ -0,0 +1,198 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#include "platform.h" +#include "core.h" +#include "scheduler.h" + +#include "box3d/base.h" +#include "box3d/constants.h" + +#include +#include +#include + +enum b3SchedulerTaskStatus +{ + b3_schedulerFree = 0, + b3_schedulerPending = 1, + b3_schedulerClaimed = 2, + b3_schedulerComplete = 3, +}; + +typedef struct b3SchedulerTask +{ + b3TaskCallback* callback; + void* taskContext; + b3AtomicInt status; +} b3SchedulerTask; + +typedef struct b3SchedulerWorkerContext +{ + struct b3Scheduler* scheduler; + int threadIndex; +} b3SchedulerWorkerContext; + +typedef struct b3Scheduler +{ + b3Thread* threads[B3_MAX_WORKERS]; + b3SchedulerWorkerContext workerContexts[B3_MAX_WORKERS]; + + // total workers including main thread + int workerCount; + + // threads created = workerCount - 1 + int threadCount; + + b3SchedulerTask tasks[B3_MAX_TASKS]; + b3AtomicInt nextSlot; + + b3Semaphore* taskSemaphore; + b3AtomicInt shutdown; +} b3Scheduler; + +// Try to claim and execute one pending task. +// Returns true if work was performed, false otherwise. +static bool b3SchedulerExecuteOne( b3Scheduler* scheduler ) +{ + int taskCount = b3AtomicLoadInt( &scheduler->nextSlot ); + for ( int t = 0; t < taskCount; ++t ) + { + b3SchedulerTask* task = scheduler->tasks + t; + if ( b3AtomicLoadInt( &task->status ) != b3_schedulerPending ) + { + continue; + } + + if ( b3AtomicCompareExchangeInt( &task->status, b3_schedulerPending, b3_schedulerClaimed ) == false ) + { + continue; + } + + task->callback( task->taskContext ); + + b3AtomicStoreInt( &task->status, b3_schedulerComplete ); + return true; + } + + return false; +} + +// Background worker thread entry point. +static void b3SchedulerWorkerMain( void* context ) +{ + b3SchedulerWorkerContext* workerContext = context; + b3Scheduler* scheduler = workerContext->scheduler; + + while ( true ) + { + b3WaitSemaphore( scheduler->taskSemaphore ); + + if ( b3AtomicLoadInt( &scheduler->shutdown ) != 0 ) + { + break; + } + + // Claim and execute all available work + while ( b3SchedulerExecuteOne( scheduler ) ) + { + } + } +} + +b3Scheduler* b3CreateScheduler( int workerCount ) +{ + B3_ASSERT( 0 < workerCount && workerCount <= B3_MAX_WORKERS ); + + b3Scheduler* scheduler = b3Alloc( sizeof( b3Scheduler ) ); + memset( scheduler, 0, sizeof( b3Scheduler ) ); + + scheduler->workerCount = workerCount; + int threadCount = workerCount - 1; + scheduler->threadCount = threadCount; + scheduler->taskSemaphore = b3CreateSemaphore( 0 ); + b3AtomicStoreInt( &scheduler->shutdown, 0 ); + b3AtomicStoreInt( &scheduler->nextSlot, 0 ); + + // Background threads use indices 1..workerCount-1. + // Main thread uses index 0. + for ( int i = 0; i < threadCount; ++i ) + { + scheduler->workerContexts[i].scheduler = scheduler; + scheduler->workerContexts[i].threadIndex = i + 1; + + char name[16]; + snprintf( name, sizeof( name ), "box2d_worker_%02d", i + 1 ); + scheduler->threads[i] = b3CreateThread( b3SchedulerWorkerMain, scheduler->workerContexts + i, name ); + } + + return scheduler; +} + +void b3DestroyScheduler( b3Scheduler* scheduler ) +{ + b3AtomicStoreInt( &scheduler->shutdown, 1 ); + + // Wake all background threads so they see the shutdown flag + for ( int i = 0; i < scheduler->threadCount; ++i ) + { + b3SignalSemaphore( scheduler->taskSemaphore ); + } + + for ( int i = 0; i < scheduler->threadCount; ++i ) + { + b3JoinThread( scheduler->threads[i] ); + scheduler->threads[i] = NULL; + } + + b3DestroySemaphore( scheduler->taskSemaphore ); + b3Free( scheduler, sizeof( b3Scheduler ) ); +} + +void b3ResetScheduler( b3Scheduler* scheduler ) +{ + b3AtomicStoreInt( &scheduler->nextSlot, 0 ); +} + +void* b3SchedulerEnqueueTask( b3TaskCallback* task, void* taskContext, void* userContext, const char* name ) +{ + B3_UNUSED( name ); + b3Scheduler* scheduler = userContext; + + int slot = b3AtomicFetchAddInt( &scheduler->nextSlot, 1 ); + B3_ASSERT( slot < B3_MAX_TASKS ); + + b3SchedulerTask* schedulerTask = scheduler->tasks + slot; + schedulerTask->callback = task; + schedulerTask->taskContext = taskContext; + + // Memory fence: status must be published after callback and context are written + b3AtomicStoreInt( &schedulerTask->status, b3_schedulerPending ); + + // One wake per enqueue is enough: at most one worker picks up each task. + b3SignalSemaphore( scheduler->taskSemaphore ); + + return schedulerTask; +} + +void b3SchedulerFinishTask( void* userTask, void* userContext ) +{ + if ( userTask == NULL ) + { + return; + } + + b3Scheduler* scheduler = userContext; + b3SchedulerTask* waitTask = userTask; + + // Main thread helps execute any available work while waiting for the + // target task to complete. This keeps the main thread from idling when + // background threads are busy on other tasks from the same phase. + while ( b3AtomicLoadInt( &waitTask->status ) != b3_schedulerComplete ) + { + if ( b3SchedulerExecuteOne( scheduler ) == false ) + { + b3Yield(); + } + } +} diff --git a/src/scheduler.h b/src/scheduler.h new file mode 100644 index 0000000..7a08e6e --- /dev/null +++ b/src/scheduler.h @@ -0,0 +1,24 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +typedef void b3TaskCallback( void* taskContext ); +typedef struct b3Scheduler b3Scheduler; + +#ifdef __cplusplus +extern "C" +{ +#endif + +b3Scheduler* b3CreateScheduler( int workerCount ); +void b3DestroyScheduler( b3Scheduler* scheduler ); +void b3ResetScheduler( b3Scheduler* scheduler ); + +// See b3EnqueueTaskCallback and b3FinishTaskCallback +void* b3SchedulerEnqueueTask( b3TaskCallback* task, void* taskContext, void* userContext, const char* name ); +void b3SchedulerFinishTask( void* userTask, void* userContext ); + +#ifdef __cplusplus +} +#endif diff --git a/src/sensor.c b/src/sensor.c new file mode 100644 index 0000000..c28f2ca --- /dev/null +++ b/src/sensor.c @@ -0,0 +1,452 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "sensor.h" + +#include "body.h" +#include "contact.h" +#include "ctz.h" +#include "physics_world.h" +#include "shape.h" + +#include "box3d/collision.h" + +// for qsort +#include "parallel_for.h" + +#include + +typedef struct b3SensorQueryContext +{ + b3World* world; + b3SensorTaskContext* taskContext; + b3Sensor* sensor; + b3Shape* sensorShape; + b3Transform transform; +} b3SensorQueryContext; + +static bool b3OverlapSensor( b3Shape* sensorShape, b3Transform sensorTransform, b3Shape* visitorShape, + b3Transform visitorTransform ) +{ + b3ShapeType type = sensorShape->type; + + b3ShapeProxy proxy = b3MakeShapeProxy( visitorShape ); + + // Get the visitor shape in the frame of the sensor + b3Transform relativeTransform = b3InvMulTransforms( sensorTransform, visitorTransform ); + + b3Vec3 localPoints[B3_MAX_SHAPE_CAST_POINTS]; + b3ShapeProxy localProxy; + + localProxy.count = b3MinInt( proxy.count, B3_MAX_SHAPE_CAST_POINTS ); + for ( int i = 0; i < localProxy.count; ++i ) + { + localPoints[i] = b3TransformPoint( relativeTransform, proxy.points[i] ); + } + + localProxy.points = localPoints; + localProxy.radius = proxy.radius; + + switch ( type ) + { + case b3_capsuleShape: + return b3OverlapCapsule( &sensorShape->capsule, b3Transform_identity, &localProxy ); + + case b3_compoundShape: + return b3OverlapCompound( sensorShape->compound , b3Transform_identity, &localProxy ); + + case b3_heightShape: + return b3OverlapHeightField( sensorShape->heightField, b3Transform_identity, &localProxy ); + + case b3_hullShape: + return b3OverlapHull( sensorShape->hull, b3Transform_identity, &localProxy ); + + case b3_meshShape: + return b3OverlapMesh( &sensorShape->mesh, b3Transform_identity, &localProxy ); + + case b3_sphereShape: + return b3OverlapSphere( &sensorShape->sphere, b3Transform_identity, &localProxy ); + + default: + B3_ASSERT( false ); + return false; + } +} + +// 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 b3SensorQueryCallback( int proxyId, uint64_t userData, void* context ) +{ + B3_UNUSED( proxyId ); + + int shapeId = (int)userData; + + b3SensorQueryContext* queryContext = (b3SensorQueryContext*)context; + b3Shape* sensorShape = queryContext->sensorShape; + int sensorShapeId = sensorShape->id; + + if ( shapeId == sensorShapeId ) + { + return true; + } + + b3World* world = queryContext->world; + b3Shape* otherShape = b3Array_Get( world->shapes, shapeId ); + + // Mesh vs mesh is not supported + if ( ( otherShape->type == b3_meshShape || otherShape->type == b3_heightShape ) && + ( sensorShape->type == b3_meshShape || sensorShape->type == b3_heightShape ) ) + { + return true; + } + + // 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 ( b3ShouldShapesCollide( sensorShape->filter, otherShape->filter ) == false ) + { + return true; + } + + // Custom user filter + if ( sensorShape->enableCustomFiltering || otherShape->enableCustomFiltering ) + { + b3CustomFilterFcn* customFilterFcn = queryContext->world->customFilterFcn; + if ( customFilterFcn != NULL ) + { + b3ShapeId idA = { sensorShapeId + 1, world->worldId, sensorShape->generation }; + b3ShapeId idB = { shapeId + 1, world->worldId, otherShape->generation }; + bool shouldCollide = customFilterFcn( idA, idB, queryContext->world->customFilterContext ); + if ( shouldCollide == false ) + { + return true; + } + } + } + + b3Transform otherTransform = b3GetBodyTransform( world, otherShape->bodyId ); + + bool overlap = b3OverlapSensor( sensorShape, queryContext->transform, otherShape, otherTransform ); + if ( overlap == false ) + { + return true; + } + + // Record the overlap + b3Sensor* sensor = queryContext->sensor; + b3Visitor* shapeRef = b3Array_Emplace( sensor->overlaps2 ); + shapeRef->shapeId = shapeId; + shapeRef->generation = otherShape->generation; + + return true; +} + +static int b3CompareVisitors( const void* a, const void* b ) +{ + const b3Visitor* sa = (const b3Visitor*)a; + const b3Visitor* sb = (const b3Visitor*)b; + + if ( sa->shapeId < sb->shapeId ) + { + return -1; + } + + return 1; +} + +static void b3SensorTask( int startIndex, int endIndex, int workerIndex, void* context ) +{ + b3TracyCZoneNC( sensor_task, "Overlap", b3_colorBrown, true ); + + b3World* world = (b3World*)context; + B3_ASSERT( (int)workerIndex < world->workerCount ); + b3SensorTaskContext* taskContext = world->sensorTaskContexts.data + workerIndex; + + B3_ASSERT( startIndex < endIndex ); + + b3DynamicTree* trees = world->broadPhase.trees; + for ( int sensorIndex = startIndex; sensorIndex < endIndex; ++sensorIndex ) + { + b3Sensor* sensor = b3Array_Get( world->sensors, sensorIndex ); + b3Shape* sensorShape = b3Array_Get( world->shapes, sensor->shapeId ); + + // Swap overlap arrays + b3ArrayC( b3Visitor ) temp = sensor->overlaps1; + sensor->overlaps1 = sensor->overlaps2; + sensor->overlaps2 = temp; + b3Array_Clear( sensor->overlaps2 ); + + // Append sensor hits + b3Array_Append( sensor->overlaps2, sensor->hits.data, sensor->hits.count ); + + // Clear the hits + b3Array_Clear( sensor->hits ); + + b3Body* body = b3Array_Get( world->bodies, sensorShape->bodyId ); + if ( body->setIndex == b3_disabledSet || sensorShape->enableSensorEvents == false ) + { + if ( sensor->overlaps1.count != 0 ) + { + // This sensor is dropping all overlaps because it has been disabled. + b3SetBit( &taskContext->eventBits, sensorIndex ); + } + continue; + } + + b3Transform transform = b3GetBodyTransformQuick( world, body ); + + b3SensorQueryContext queryContext = { + .world = world, + .taskContext = taskContext, + .sensor = sensor, + .sensorShape = sensorShape, + .transform = transform, + }; + + B3_ASSERT( sensorShape->sensorIndex == sensorIndex ); + b3AABB queryBounds = sensorShape->aabb; + + // Query all trees + b3DynamicTree_Query( trees + 0, queryBounds, sensorShape->filter.maskBits, false, b3SensorQueryCallback, &queryContext ); + b3DynamicTree_Query( trees + 1, queryBounds, sensorShape->filter.maskBits, false, b3SensorQueryCallback, &queryContext ); + b3DynamicTree_Query( trees + 2, queryBounds, sensorShape->filter.maskBits, false, b3SensorQueryCallback, &queryContext ); + + // Sort the overlaps to enable finding begin and end events. + qsort( sensor->overlaps2.data, sensor->overlaps2.count, sizeof( b3Visitor ), b3CompareVisitors ); + + // Remove duplicates from overlaps2 (sorted). Duplicates are possible due to the hit events appended earlier. + int uniqueCount = 0; + int overlapCount = sensor->overlaps2.count; + b3Visitor* 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 + b3SetBit( &taskContext->eventBits, sensorIndex ); + } + else + { + for ( int i = 0; i < count1; ++i ) + { + b3Visitor* s1 = sensor->overlaps1.data + i; + b3Visitor* s2 = sensor->overlaps2.data + i; + + if ( s1->shapeId != s2->shapeId || s1->generation != s2->generation ) + { + // something changed + b3SetBit( &taskContext->eventBits, sensorIndex ); + break; + } + } + } + } + + b3TracyCZoneEnd( sensor_task ); +} + +void b3OverlapSensors( b3World* world ) +{ + int sensorCount = world->sensors.count; + if ( sensorCount == 0 ) + { + return; + } + + B3_ASSERT( world->workerCount > 0 ); + + b3TracyCZoneNC( overlap_sensors, "Sensors", b3_colorMediumPurple, true ); + + for ( int i = 0; i < world->workerCount; ++i ) + { + b3SetBitCountAndClear( &world->sensorTaskContexts.data[i].eventBits, sensorCount ); + } + + // Parallel-for sensors overlaps + int minRange = 16; + b3ParallelFor( world, b3SensorTask, sensorCount, minRange, world, "sensors" ); + + b3TracyCZoneNC( sensor_state, "Events", b3_colorLightSlateGray, true ); + + b3BitSet* bitSet = &world->sensorTaskContexts.data[0].eventBits; + for ( int i = 1; i < world->workerCount; ++i ) + { + b3InPlaceUnion( 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 = b3CTZ64( word ); + int sensorIndex = (int)( 64 * k + ctz ); + + b3Sensor* sensor = b3Array_Get( world->sensors, sensorIndex ); + b3Shape* sensorShape = b3Array_Get( world->shapes, sensor->shapeId ); + b3ShapeId sensorId = { sensor->shapeId + 1, world->worldId, sensorShape->generation }; + + int count1 = sensor->overlaps1.count; + int count2 = sensor->overlaps2.count; + const b3Visitor* refs1 = sensor->overlaps1.data; + const b3Visitor* 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 b3Visitor* r1 = refs1 + index1; + const b3Visitor* r2 = refs2 + index2; + if ( r1->shapeId == r2->shapeId ) + { + if ( r1->generation < r2->generation ) + { + // end + b3ShapeId visitorId = { r1->shapeId + 1, world->worldId, r1->generation }; + b3SensorEndTouchEvent event = { + .sensorShapeId = sensorId, + .visitorShapeId = visitorId, + }; + b3Array_Push( world->sensorEndEvents[world->endEventArrayIndex], event ); + index1 += 1; + } + else if ( r1->generation > r2->generation ) + { + // begin + b3ShapeId visitorId = { r2->shapeId + 1, world->worldId, r2->generation }; + b3SensorBeginTouchEvent event = { sensorId, visitorId }; + b3Array_Push( world->sensorBeginEvents, event ); + index2 += 1; + } + else + { + // persisted + index1 += 1; + index2 += 1; + } + } + else if ( r1->shapeId < r2->shapeId ) + { + // end + b3ShapeId visitorId = { r1->shapeId + 1, world->worldId, r1->generation }; + b3SensorEndTouchEvent event = { sensorId, visitorId }; + b3Array_Push( world->sensorEndEvents[world->endEventArrayIndex], event ); + index1 += 1; + } + else + { + // begin + b3ShapeId visitorId = { r2->shapeId + 1, world->worldId, r2->generation }; + b3SensorBeginTouchEvent event = { sensorId, visitorId }; + b3Array_Push( world->sensorBeginEvents, event ); + index2 += 1; + } + } + + while ( index1 < count1 ) + { + // end + const b3Visitor* r1 = refs1 + index1; + b3ShapeId visitorId = { r1->shapeId + 1, world->worldId, r1->generation }; + b3SensorEndTouchEvent event = { sensorId, visitorId }; + b3Array_Push( world->sensorEndEvents[world->endEventArrayIndex], event ); + index1 += 1; + } + + while ( index2 < count2 ) + { + // begin + const b3Visitor* r2 = refs2 + index2; + b3ShapeId visitorId = { r2->shapeId + 1, world->worldId, r2->generation }; + b3SensorBeginTouchEvent event = { sensorId, visitorId }; + b3Array_Push( world->sensorBeginEvents, event ); + index2 += 1; + } + + // Clear the smallest set bit + word = word & ( word - 1 ); + } + } + + b3TracyCZoneEnd( sensor_state ); + b3TracyCZoneEnd( overlap_sensors ); +} + +void b3DestroySensor( b3World* world, b3Shape* sensorShape ) +{ + b3Sensor* sensor = b3Array_Get( world->sensors, sensorShape->sensorIndex ); + for ( int i = 0; i < sensor->overlaps2.count; ++i ) + { + b3Visitor* ref = sensor->overlaps2.data + i; + b3SensorEndTouchEvent event = { + .sensorShapeId = + { + .index1 = sensorShape->id + 1, + .world0 = world->worldId, + .generation = sensorShape->generation, + }, + .visitorShapeId = + { + .index1 = ref->shapeId + 1, + .world0 = world->worldId, + .generation = ref->generation, + }, + }; + + b3Array_Push( world->sensorEndEvents[world->endEventArrayIndex], event ); + } + + // Destroy sensor + b3Array_Destroy( sensor->hits ); + b3Array_Destroy( sensor->overlaps1 ); + b3Array_Destroy( sensor->overlaps2 ); + + int movedIndex = b3Array_RemoveSwap( world->sensors, sensorShape->sensorIndex ); + if ( movedIndex != B3_NULL_INDEX ) + { + // Fixup moved sensor + b3Sensor* movedSensor = b3Array_Get( world->sensors, sensorShape->sensorIndex ); + b3Shape* otherSensorShape = b3Array_Get( world->shapes, movedSensor->shapeId ); + otherSensorShape->sensorIndex = sensorShape->sensorIndex; + } +} diff --git a/src/sensor.h b/src/sensor.h new file mode 100644 index 0000000..038d076 --- /dev/null +++ b/src/sensor.h @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "bitset.h" +#include "container.h" + +typedef struct b3Shape b3Shape; +typedef struct b3World b3World; + +// Used to track shapes that hit sensors using time of impact +typedef struct b3SensorHit +{ + int sensorId; + int visitorId; +} b3SensorHit; + +typedef struct b3Visitor +{ + int shapeId; + uint16_t generation; +} b3Visitor; + +b3DeclareArray( b3Visitor ); + +typedef struct b3Sensor +{ + b3ArrayC( b3Visitor ) hits; + b3ArrayC( b3Visitor ) overlaps1; + b3ArrayC( b3Visitor ) overlaps2; + int shapeId; +} b3Sensor; + +typedef struct b3SensorTaskContext +{ + b3BitSet eventBits; +} b3SensorTaskContext; + +#ifdef __cplusplus +extern "C" +{ +#endif + +void b3OverlapSensors( b3World* world ); + +void b3DestroySensor( b3World* world, b3Shape* sensorShape ); + +#ifdef __cplusplus +} +#endif diff --git a/src/shape.c b/src/shape.c new file mode 100644 index 0000000..ba9b923 --- /dev/null +++ b/src/shape.c @@ -0,0 +1,2340 @@ +// SPDX-FileCopyrightText: 2025 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 "aabb.h" +#include "compound.h" + +#include "box3d/box3d.h" + +#include +#include + +static b3Shape* b3GetShape( b3World* world, b3ShapeId shapeId ) +{ + int id = shapeId.index1 - 1; + b3Shape* shape = b3Array_Get( world->shapes, id ); + B3_ASSERT( shape->id == id && shape->generation == shapeId.generation ); + return shape; +} + +static void b3UpdateShapeAABBs( b3Shape* shape, b3Transform transform, b3BodyType proxyType ) +{ + // Compute a bounding box with a speculative margin + const float speculativeDistance = B3_SPECULATIVE_DISTANCE; + const float aabbMargin = B3_AABB_MARGIN; + + b3AABB aabb = b3ComputeShapeAABB( shape, transform ); + aabb.lowerBound.x -= speculativeDistance; + aabb.lowerBound.y -= speculativeDistance; + aabb.lowerBound.z -= speculativeDistance; + aabb.upperBound.x += speculativeDistance; + aabb.upperBound.y += speculativeDistance; + aabb.upperBound.z += speculativeDistance; + shape->aabb = aabb; + + // Smaller margin for static bodies. Cannot be zero due to TOI tolerance. + float margin = proxyType == b3_staticBody ? speculativeDistance : aabbMargin; + b3AABB fatAABB; + fatAABB.lowerBound.x = aabb.lowerBound.x - margin; + fatAABB.lowerBound.y = aabb.lowerBound.y - margin; + fatAABB.lowerBound.z = aabb.lowerBound.z - margin; + fatAABB.upperBound.x = aabb.upperBound.x + margin; + fatAABB.upperBound.y = aabb.upperBound.y + margin; + fatAABB.upperBound.z = aabb.upperBound.z + margin; + shape->fatAABB = fatAABB; + + B3_VALIDATE( b3IsSaneAABB( fatAABB ) ); +} + +static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3Transform bodyTransform, const b3ShapeDef* def, + const void* geometry, b3ShapeType shapeType, b3Transform shapeTransform, b3Vec3 scale, + bool haveShapeTransform ) +{ + int shapeId = b3AllocId( &world->shapeIdPool ); + + if ( shapeId == world->shapes.count ) + { + b3Array_Push( world->shapes, (b3Shape){ 0 } ); + } + else + { + B3_ASSERT( world->shapes.data[shapeId].id == B3_NULL_INDEX ); + } + + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + + switch ( shapeType ) + { + case b3_capsuleShape: + shape->capsule = *(b3Capsule*)geometry; + break; + + case b3_compoundShape: + // Compounds must be a static and not a sensor + B3_ASSERT( body->type == b3_staticBody ); + B3_ASSERT( def->isSensor == false ); + shape->compound = (b3Compound*)geometry; + break; + + case b3_sphereShape: + shape->sphere = *(b3Sphere*)geometry; + break; + + case b3_hullShape: + if ( haveShapeTransform ) + { + shape->hull = b3CloneAndTransformHull( (b3Hull*)geometry, shapeTransform, scale ); + if ( shape->hull == NULL ) + { + // This can fail to produce a valid hull in extreme cases + b3FreeId( &world->shapeIdPool, shapeId ); + shape->id = B3_NULL_INDEX; + return NULL; + } + } + else + { + shape->hull = b3CloneHull( (b3Hull*)geometry ); + } + break; + + case b3_meshShape: + { + shape->mesh.data = (b3MeshData*)geometry; + shape->mesh.scale = b3SafeScale( scale ); + } + break; + + case b3_heightShape: + shape->heightField = (b3HeightField*)geometry; + break; + + default: + B3_ASSERT( false ); + break; + } + + shape->id = shapeId; + shape->bodyId = body->id; + shape->type = shapeType; + shape->density = def->density; + shape->explosionScale = def->explosionScale; + shape->filter = def->filter; + shape->userData = def->userData; + shape->userShape = NULL; + 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 = B3_NULL_INDEX; + shape->localCentroid = b3GetShapeCentroid( shape ); + shape->aabb = (b3AABB){ b3Vec3_zero, b3Vec3_zero }; + shape->fatAABB = (b3AABB){ b3Vec3_zero, b3Vec3_zero }; + shape->generation += 1; + + if ( def->name ) + { + size_t length = strlen( def->name ) + 1; + shape->name = (char*)b3Alloc( length * sizeof( char ) ); + memcpy( shape->name, def->name, length ); + } + else + { + shape->name = NULL; + } + + if ( shape->type == b3_compoundShape ) + { + // Unfortunate const removal + shape->materials = (b3SurfaceMaterial*)b3GetCompoundMaterials( shape->compound ); + shape->materialCount = shape->compound->materialCount; + } + else if ( def->materialCount > 0 && def->materials != NULL ) + { + b3SurfaceMaterial* materials = (b3SurfaceMaterial*)b3Alloc( def->materialCount * sizeof( b3SurfaceMaterial ) ); + memcpy( materials, def->materials, def->materialCount * sizeof( b3SurfaceMaterial ) ); + shape->materials = materials; + shape->materialCount = def->materialCount; + } + else + { + b3SurfaceMaterial* materials = (b3SurfaceMaterial*)b3Alloc( sizeof( b3SurfaceMaterial ) ); + memcpy( materials, &def->baseMaterial, sizeof( b3SurfaceMaterial ) ); + shape->materials = materials; + shape->materialCount = 1; + } + + if ( body->setIndex != b3_disabledSet ) + { + b3BodyType proxyType = body->type; + bool forcePairCreation = def->invokeContactCreation && shape->type != b3_compoundShape; + b3CreateShapeProxy( shape, &world->broadPhase, proxyType, bodyTransform, forcePairCreation ); + } + + // Add to shape doubly linked list + if ( body->headShapeId != B3_NULL_INDEX ) + { + b3Shape* headShape = b3Array_Get( world->shapes, body->headShapeId ); + headShape->prevShapeId = shapeId; + } + + shape->prevShapeId = B3_NULL_INDEX; + shape->nextShapeId = body->headShapeId; + body->headShapeId = shapeId; + body->shapeCount += 1; + + if ( def->isSensor ) + { + shape->sensorIndex = world->sensors.count; + b3Sensor* sensor = b3Array_Emplace( world->sensors ); + b3Array_CreateN( sensor->hits, 4 ); + b3Array_CreateN( sensor->overlaps1, 16 ); + b3Array_CreateN( sensor->overlaps2, 16 ); + sensor->shapeId = shapeId; + } + else + { + shape->sensorIndex = B3_NULL_INDEX; + } + + b3ValidateSolverSets( world ); + + return shape; +} + +static b3ShapeId b3CreateShape( b3BodyId bodyId, const b3ShapeDef* def, const void* geometry, b3ShapeType shapeType, + b3Transform transform, b3Vec3 scale, bool haveTransform ) +{ + B3_CHECK_DEF( def ); + B3_ASSERT( b3IsValidFloat( def->density ) && def->density >= 0.0f ); + B3_ASSERT( b3IsValidFloat( def->baseMaterial.friction ) && def->baseMaterial.friction >= 0.0f ); + B3_ASSERT( b3IsValidFloat( def->baseMaterial.restitution ) && def->baseMaterial.restitution >= 0.0f ); + + b3World* world = b3GetUnlockedWorld( bodyId.world0 ); + if ( world == NULL ) + { + return (b3ShapeId){ 0 }; + } + + if ( world->shapes.count == B3_MAX_SHAPES && world->shapeIdPool.freeArray.count == 0 ) + { + B3_ASSERT( false ); + return b3_nullShapeId; + } + + b3Body* body = b3GetBodyFullId( world, bodyId ); + if ( body->type != b3_staticBody && ( shapeType == b3_compoundShape || shapeType == b3_heightShape ) ) + { + // Compound and height shapes must be on static bodies. + return b3_nullShapeId; + } + + world->locked = true; + + b3Transform bodyTransform = b3GetBodyTransformQuick( world, body ); + + b3Shape* shape = + b3CreateShapeInternal( world, body, bodyTransform, def, geometry, shapeType, transform, scale, haveTransform ); + + if ( shape == NULL ) + { + world->locked = false; + return b3_nullShapeId; + } + + if ( def->updateBodyMass == true ) + { + b3UpdateBodyMassData( world, body ); + } + + b3ValidateSolverSets( world ); + + b3ShapeId id = { shape->id + 1, bodyId.world0, shape->generation }; + + world->locked = false; + + return id; +} + +b3ShapeId b3CreateSphereShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Sphere* sphere ) +{ + return b3CreateShape( bodyId, def, sphere, b3_sphereShape, b3Transform_identity, b3Vec3_one, false ); +} + +b3ShapeId b3CreateCapsuleShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Capsule* capsule ) +{ + float lengthSqr = b3DistanceSquared( capsule->center1, capsule->center2 ); + if ( lengthSqr <= B3_LINEAR_SLOP * B3_LINEAR_SLOP ) + { + b3Sphere sphere = { b3Lerp( capsule->center1, capsule->center2, 0.5f ), capsule->radius }; + return b3CreateShape( bodyId, def, &sphere, b3_sphereShape, b3Transform_identity, b3Vec3_one, false ); + } + + return b3CreateShape( bodyId, def, capsule, b3_capsuleShape, b3Transform_identity, b3Vec3_one, false ); +} + +b3ShapeId b3CreateHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Hull* hull ) +{ + B3_VALIDATE( b3IsValidHull( hull ) ); + B3_VALIDATE( hull->hash != 0 ); + return b3CreateShape( bodyId, def, hull, b3_hullShape, b3Transform_identity, b3Vec3_one, false ); +} + +b3ShapeId b3CreateTransformedHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Hull* hull, b3Transform transform, + b3Vec3 scale ) +{ + B3_VALIDATE( b3IsValidHull( hull ) ); + return b3CreateShape( bodyId, def, hull, b3_hullShape, transform, scale, true ); +} + +b3ShapeId b3CreateMeshShape( b3BodyId bodyId, const b3ShapeDef* def, const b3MeshData* mesh, b3Vec3 scale ) +{ + B3_VALIDATE( b3IsValidMesh( mesh ) ); + B3_VALIDATE( mesh->hash != 0 ); + return b3CreateShape( bodyId, def, mesh, b3_meshShape, b3Transform_identity, scale, true ); +} + +b3ShapeId b3CreateHeightFieldShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HeightField* heightField ) +{ + B3_VALIDATE( heightField->hash != 0 ); + return b3CreateShape( bodyId, def, heightField, b3_heightShape, b3Transform_identity, b3Vec3_one, false ); +} + +b3ShapeId b3CreateCompoundShape( b3BodyId bodyId, b3ShapeDef* def, const b3Compound* compound ) +{ + return b3CreateShape( bodyId, def, compound, b3_compoundShape, b3Transform_identity, b3Vec3_one, false ); +} + +// Destroy a shape on a body. This doesn't need to be called when destroying a body. +static void b3DestroyShapeInternal( b3World* world, b3Shape* shape, b3Body* body, bool wakeBodies ) +{ + int shapeId = shape->id; + + // Remove the shape from the body's doubly linked list. + if ( shape->prevShapeId != B3_NULL_INDEX ) + { + b3Shape* prevShape = b3Array_Get( world->shapes, shape->prevShapeId ); + prevShape->nextShapeId = shape->nextShapeId; + } + + if ( shape->nextShapeId != B3_NULL_INDEX ) + { + b3Shape* nextShape = b3Array_Get( world->shapes, shape->nextShapeId ); + nextShape->prevShapeId = shape->prevShapeId; + } + + if ( shapeId == body->headShapeId ) + { + body->headShapeId = shape->nextShapeId; + } + + body->shapeCount -= 1; + + // Remove from broad-phase. + b3DestroyShapeProxy( shape, &world->broadPhase ); + + // Destroy any contacts associated with the shape. + int contactKey = body->headContactKey; + while ( contactKey != B3_NULL_INDEX ) + { + int contactId = contactKey >> 1; + int edgeIndex = contactKey & 1; + + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + contactKey = contact->edges[edgeIndex].nextKey; + + if ( contact->shapeIdA == shapeId || contact->shapeIdB == shapeId ) + { + b3DestroyContact( world, contact, wakeBodies ); + } + } + + if ( shape->sensorIndex != B3_NULL_INDEX ) + { + b3Sensor* sensor = b3Array_Get( world->sensors, shape->sensorIndex ); + for ( int i = 0; i < sensor->overlaps2.count; ++i ) + { + b3Visitor* ref = sensor->overlaps2.data + i; + b3SensorEndTouchEvent event = { + .sensorShapeId = + { + .index1 = shapeId + 1, + .world0 = world->worldId, + .generation = shape->generation, + }, + .visitorShapeId = + { + .index1 = ref->shapeId + 1, + .world0 = world->worldId, + .generation = ref->generation, + }, + }; + + b3Array_Push( world->sensorEndEvents[world->endEventArrayIndex], event ); + } + + // Destroy sensor + b3Array_Destroy( sensor->hits ); + b3Array_Destroy( sensor->overlaps1 ); + b3Array_Destroy( sensor->overlaps2 ); + + int movedIndex = b3Array_RemoveSwap( world->sensors, shape->sensorIndex ); + if ( movedIndex != B3_NULL_INDEX ) + { + // Fixup moved sensor + b3Sensor* movedSensor = b3Array_Get( world->sensors, shape->sensorIndex ); + b3Shape* otherSensorShape = b3Array_Get( world->shapes, movedSensor->shapeId ); + otherSensorShape->sensorIndex = shape->sensorIndex; + } + } + + // Destroy every shape member from b3Alloc + b3DestroyShapeAllocations( world, shape ); + + // Return shape to free list. + b3FreeId( &world->shapeIdPool, shapeId ); + shape->id = B3_NULL_INDEX; + + b3ValidateSolverSets( world ); +} + +void b3DestroyShape( b3ShapeId shapeId, bool updateBodyMass ) +{ + b3World* world = b3GetUnlockedWorld( shapeId.world0 ); + if ( world == NULL ) + { + return; + } + + world->locked = true; + + b3Shape* shape = b3GetShape( world, shapeId ); + + // need to wake bodies because this might be a static body + bool wakeBodies = true; + + b3Body* body = b3Array_Get( world->bodies, shape->bodyId ); + b3DestroyShapeInternal( world, shape, body, wakeBodies ); + + if ( updateBodyMass == true ) + { + b3UpdateBodyMassData( world, body ); + } + + world->locked = false; +} + +b3AABB b3ComputeShapeAABB( const b3Shape* shape, b3Transform transform ) +{ + switch ( shape->type ) + { + case b3_capsuleShape: + return b3ComputeCapsuleAABB( &shape->capsule, transform ); + + case b3_compoundShape: + return b3ComputeCompoundAABB( shape->compound, transform ); + + case b3_heightShape: + return b3ComputeHeightFieldAABB( shape->heightField, transform ); + + case b3_hullShape: + return b3ComputeHullAABB( shape->hull, transform ); + + case b3_meshShape: + return b3ComputeMeshAABB( shape->mesh.data, transform, shape->mesh.scale ); + + case b3_sphereShape: + return b3ComputeSphereAABB( &shape->sphere, transform ); + + default: + { + B3_ASSERT( false ); + b3AABB empty = { transform.p, transform.p }; + return empty; + } + } +} + +b3AABB b3ComputeSweptShapeAABB( const b3Shape* shape, const b3Sweep* sweep, float time ) +{ + B3_ASSERT( 0.0f <= time && time <= 1.0f ); + b3Transform xf1 = { b3Sub( sweep->c1, b3RotateVector( sweep->q1, sweep->localCenter ) ), sweep->q1 }; + b3Transform xf2 = b3GetSweepTransform( sweep, time ); + + switch ( shape->type ) + { + case b3_capsuleShape: + return b3ComputeSweptCapsuleAABB( &shape->capsule, xf1, xf2 ); + + case b3_hullShape: + return b3ComputeSweptHullAABB( shape->hull, xf1, xf2 ); + + case b3_sphereShape: + return b3ComputeSweptSphereAABB( &shape->sphere, xf1, xf2 ); + + default: + B3_ASSERT( false ); + return (b3AABB){ xf1.p, xf1.p }; + } +} + +b3Vec3 b3GetShapeCentroid( const b3Shape* shape ) +{ + switch ( shape->type ) + { + case b3_capsuleShape: + return b3Lerp( shape->capsule.center1, shape->capsule.center2, 0.5f ); + case b3_compoundShape: + { + b3AABB aabb = b3ComputeCompoundAABB( shape->compound, b3Transform_identity ); + return b3AABB_Center( aabb ); + } + case b3_sphereShape: + return shape->sphere.center; + case b3_hullShape: + return shape->hull->center; + case b3_meshShape: + { + b3AABB aabb = b3ComputeMeshAABB( shape->mesh.data, b3Transform_identity, shape->mesh.scale ); + return b3AABB_Center( aabb ); + } + case b3_heightShape: + { + b3AABB aabb = b3ComputeHeightFieldAABB( shape->heightField, b3Transform_identity ); + return b3AABB_Center( aabb ); + } + default: + return b3Vec3_zero; + } +} + +float b3GetShapeArea( const b3Shape* shape ) +{ + // todo_erin fix these + switch ( shape->type ) + { + case b3_capsuleShape: + return 2.0f * b3Length( b3Sub( shape->capsule.center1, shape->capsule.center2 ) ) + + 2.0f * B3_PI * shape->capsule.radius; + + case b3_hullShape: + return shape->hull->surfaceArea; + + case b3_sphereShape: + return 2.0f * B3_PI * shape->sphere.radius; + + default: + return 0.0f; + } +} + +// This projects the shape surface area onto a plane +float b3GetShapeProjectedArea( const b3Shape* shape, b3Vec3 planeNormal ) +{ + switch ( shape->type ) + { + case b3_capsuleShape: + { + float radius = shape->capsule.radius; + b3Vec3 axis = b3Sub( shape->capsule.center2, shape->capsule.center1 ); + float projectedLength = b3Length( b3Cross( axis, planeNormal ) ); + float cylinderArea = 2.0f * radius * projectedLength; + float sphereArea = B3_PI * radius * radius; + return sphereArea + cylinderArea; + } + + case b3_hullShape: + return b3ComputeHullProjectedArea( shape->hull, planeNormal ); + + case b3_sphereShape: + return B3_PI * shape->sphere.radius * shape->sphere.radius; + + default: + return 0.0f; + } +} + +b3MassData b3ComputeShapeMass( const b3Shape* shape ) +{ + switch ( shape->type ) + { + case b3_capsuleShape: + return b3ComputeCapsuleMass( &shape->capsule, shape->density ); + + case b3_hullShape: + return b3ComputeHullMass( shape->hull, shape->density ); + + case b3_sphereShape: + return b3ComputeSphereMass( &shape->sphere, shape->density ); + + default: + return (b3MassData){ 0 }; + } +} + +b3ShapeExtent b3ComputeShapeExtent( const b3Shape* shape, b3Vec3 localCenter ) +{ + b3ShapeExtent extent = { 0 }; + + switch ( shape->type ) + { + case b3_capsuleShape: + { + float radius = shape->capsule.radius; + extent.minExtent = radius; + b3Vec3 c1 = b3Sub( shape->capsule.center1, localCenter ); + b3Vec3 c2 = b3Sub( shape->capsule.center2, localCenter ); + b3Vec3 r = { radius, radius, radius }; + extent.maxExtent = b3Add( b3Max( c1, c2 ), r ); + } + break; + + case b3_compoundShape: + { + // This is shouldn't be needed but here for completeness + b3AABB aabb = b3ComputeCompoundAABB( shape->compound, b3Transform_identity ); + float r1 = b3Length( b3Sub( aabb.lowerBound, localCenter ) ); + float r2 = b3Length( b3Sub( aabb.upperBound, localCenter ) ); + extent.minExtent = b3MinFloat( r1, r2 ); + b3Vec3 p = b3FarthestPointOnAABB( aabb, localCenter ); + extent.maxExtent = b3Abs( b3Sub( p, localCenter ) ); + } + break; + + case b3_sphereShape: + { + float radius = shape->sphere.radius; + extent.minExtent = radius; + b3Vec3 r = { radius, radius, radius }; + b3Vec3 p = b3Add( b3Sub( shape->sphere.center, localCenter ), r ); + extent.maxExtent = b3Abs( b3Sub( p, localCenter ) ); + } + break; + + case b3_hullShape: + extent = b3ComputeHullExtent( shape->hull, localCenter ); + break; + + case b3_meshShape: + { + // This is needed for kinematic mesh sleeping + b3AABB aabb = b3ComputeMeshAABB( shape->mesh.data, b3Transform_identity, shape->mesh.scale ); + float r1 = b3Length( b3Sub( aabb.lowerBound, localCenter ) ); + float r2 = b3Length( b3Sub( aabb.upperBound, localCenter ) ); + extent.minExtent = b3MinFloat( r1, r2 ); + b3Vec3 p = b3FarthestPointOnAABB( aabb, localCenter ); + extent.maxExtent = b3Abs( p ); + } + break; + + default: + break; + } + + return extent; +} + +b3CastOutput b3RayCastShape( const b3Shape* shape, b3Transform transform, const b3RayCastInput* input ) +{ + b3RayCastInput localInput = *input; + localInput.origin = b3InvTransformPoint( transform, input->origin ); + localInput.translation = b3InvRotateVector( transform.q, input->translation ); + + b3CastOutput output = { 0 }; + switch ( shape->type ) + { + case b3_capsuleShape: + output = b3RayCastCapsule( &shape->capsule, &localInput ); + break; + case b3_compoundShape: + output = b3RayCastCompound( shape->compound, &localInput ); + break; + case b3_sphereShape: + output = b3RayCastSphere( &shape->sphere, &localInput ); + break; + case b3_hullShape: + output = b3RayCastHull( shape->hull, &localInput ); + break; + case b3_meshShape: + output = b3RayCastMesh( &shape->mesh, &localInput ); + break; + case b3_heightShape: + output = b3RayCastHeightField( shape->heightField, &localInput ); + break; + default: + return output; + } + + output.point = b3TransformPoint( transform, output.point ); + output.normal = b3RotateVector( transform.q, output.normal ); + return output; +} + +b3CastOutput b3ShapeCastShape( const b3Shape* shape, b3Transform transform, const b3ShapeCastInput* input ) +{ + b3ShapeCastInput localInput = *input; + b3Vec3 localPoints[B3_MAX_SHAPE_CAST_POINTS]; + + localInput.proxy.count = b3MinInt( input->proxy.count, B3_MAX_SHAPE_CAST_POINTS ); + for ( int i = 0; i < localInput.proxy.count; ++i ) + { + localPoints[i] = b3InvTransformPoint( transform, input->proxy.points[i] ); + } + + localInput.proxy.points = localPoints; + localInput.translation = b3InvRotateVector( transform.q, input->translation ); + + b3CastOutput output = { 0 }; + switch ( shape->type ) + { + case b3_capsuleShape: + output = b3ShapeCastCapsule( &shape->capsule, &localInput ); + break; + + case b3_compoundShape: + output = b3ShapeCastCompound( shape->compound, &localInput ); + break; + + case b3_heightShape: + output = b3ShapeCastHeightField( shape->heightField, &localInput ); + break; + + case b3_hullShape: + output = b3ShapeCastHull( shape->hull, &localInput ); + break; + + case b3_meshShape: + output = b3ShapeCastMesh( &shape->mesh, &localInput ); + break; + + case b3_sphereShape: + output = b3ShapeCastSphere( &shape->sphere, &localInput ); + break; + default: + return output; + } + + output.point = b3TransformPoint( transform, output.point ); + output.normal = b3RotateVector( transform.q, output.normal ); + return output; +} + +bool b3OverlapShape( const b3Shape* shape, b3Transform transform, const b3ShapeProxy* proxy ) +{ + b3ShapeType type = shape->type; + switch ( type ) + { + case b3_capsuleShape: + return b3OverlapCapsule( &shape->capsule, transform, proxy ); + + case b3_compoundShape: + return b3OverlapCompound( shape->compound, transform, proxy ); + + case b3_heightShape: + return b3OverlapHeightField( shape->heightField, transform, proxy ); + + case b3_hullShape: + return b3OverlapHull( shape->hull, transform, proxy ); + + case b3_meshShape: + return b3OverlapMesh( &shape->mesh, transform, proxy ); + + case b3_sphereShape: + return b3OverlapSphere( &shape->sphere, transform, proxy ); + + default: + B3_ASSERT( false ); + return false; + } + +#if 0 + b3Vec3 localPoints[B3_MAX_SHAPE_CAST_POINTS]; + b3ShapeProxy localProxy; + + b3Transform invTransform = b3InvertTransform( transform ); + b3Matrix3 R = b3MakeMatrixFromQuat( invTransform.q ); + + localProxy.count = b3MinInt( proxy->count, B3_MAX_SHAPE_CAST_POINTS ); + for ( int i = 0; i < localProxy.count; ++i ) + { + localPoints[i] = b3Add( b3MulMV( R, proxy->points[i] ), invTransform.p ); + } + + localProxy.points = localPoints; + localProxy.radius = proxy->radius; + + if ( type == b3_meshShape ) + { + return b3OverlapMesh( &localProxy, shape->mesh.data, shape->mesh.scale ); + } + + B3_ASSERT( type == b3_heightShape ); + + return b3OverlapHeightField( &localProxy, shape->heightField ); +#endif +} + +int b3CollideMover( b3PlaneResult* planes, int planeCapacity, const b3Shape* shape, b3Transform transform, + const b3Capsule* mover ) +{ + if ( planeCapacity == 0 ) + { + return 0; + } + + b3Capsule localMover; + localMover.center1 = b3InvTransformPoint( transform, mover->center1 ); + localMover.center2 = b3InvTransformPoint( transform, mover->center2 ); + localMover.radius = mover->radius; + + int planeCount = 0; + switch ( shape->type ) + { + case b3_capsuleShape: + planeCount = b3CollideMoverAndCapsule( planes, &shape->capsule, &localMover ); + break; + + case b3_compoundShape: + planeCount = b3CollideMoverAndCompound( planes, planeCapacity, shape->compound, &localMover ); + break; + + case b3_sphereShape: + planeCount = b3CollideMoverAndSphere( planes, &shape->sphere, &localMover ); + break; + + case b3_hullShape: + planeCount = b3CollideMoverAndHull( planes, shape->hull, &localMover ); + break; + + case b3_meshShape: + planeCount = b3CollideMoverAndMesh( planes, planeCapacity, &shape->mesh, &localMover ); + break; + + case b3_heightShape: + planeCount = b3CollideMoverAndHeightField( planes, planeCapacity, shape->heightField, &localMover ); + break; + + default: + B3_ASSERT( false ); + break; + } + + for ( int i = 0; i < planeCount; ++i ) + { + planes[i].plane.normal = b3RotateVector( transform.q, planes[i].plane.normal ); + planes[i].point = b3TransformPoint( transform, planes[i].point ); + } + + return planeCount; +} + +void b3CreateShapeProxy( b3Shape* shape, b3BroadPhase* bp, b3BodyType type, b3Transform transform, bool forcePairCreation ) +{ + B3_ASSERT( shape->proxyKey == B3_NULL_INDEX ); + + b3UpdateShapeAABBs( shape, transform, type ); + + // Create proxies in the broad-phase. + shape->proxyKey = + b3BroadPhase_CreateProxy( bp, type, shape->fatAABB, shape->filter.categoryBits, shape->id, forcePairCreation ); + B3_ASSERT( B3_PROXY_TYPE( shape->proxyKey ) < b3_bodyTypeCount ); +} + +void b3DestroyShapeProxy( b3Shape* shape, b3BroadPhase* bp ) +{ + if ( shape->proxyKey != B3_NULL_INDEX ) + { + b3BroadPhase_DestroyProxy( bp, shape->proxyKey ); + shape->proxyKey = B3_NULL_INDEX; + } +} + +static void b3DestroyShapeAllocationForShapeChange( b3World* world, b3Shape* shape ) +{ + b3ShapeType type = shape->type; + switch ( type ) + { + case b3_hullShape: + b3DestroyHull( (b3Hull*)shape->hull ); + shape->hull = NULL; + break; + + default: + break; + } + + if ( shape->userShape != NULL ) + { + world->destroyDebugShape( shape->userShape, world->userDebugShapeContext ); + shape->userShape = NULL; + } +} + +void b3DestroyShapeAllocations( b3World* world, b3Shape* shape ) +{ + b3DestroyShapeAllocationForShapeChange( world, shape ); + + if ( shape->materials != NULL && shape->type != b3_compoundShape ) + { + B3_ASSERT( shape->materialCount > 0 ); + b3Free( shape->materials, shape->materialCount * sizeof( b3SurfaceMaterial ) ); + shape->materials = NULL; + shape->materialCount = 0; + } + + if ( shape->name != NULL ) + { + b3Free( shape->name, ( strlen( shape->name ) + 1 ) * sizeof( char ) ); + shape->name = NULL; + } + + // Sensor data is destroyed elsewhere +} + +b3ShapeProxy b3MakeShapeProxy( const b3Shape* shape ) +{ + switch ( shape->type ) + { + case b3_capsuleShape: + return (b3ShapeProxy){ &shape->capsule.center1, 2, shape->capsule.radius }; + + case b3_sphereShape: + return (b3ShapeProxy){ &shape->sphere.center, 1, shape->sphere.radius }; + + case b3_hullShape: + { + const b3Vec3* points = b3GetHullPoints( shape->hull ); + return (b3ShapeProxy){ points, shape->hull->vertexCount, 0.0f }; + } + + default: + { + B3_ASSERT( false ); + return (b3ShapeProxy){ 0 }; + } + } +} + +b3ShapeProxy b3MakeLocalProxy( const b3ShapeProxy* proxy, b3Transform transform, b3Vec3* buffer ) +{ + b3Transform invTransform = b3InvertTransform( transform ); + b3Matrix3 R = b3MakeMatrixFromQuat( invTransform.q ); + + int count = b3MinInt( proxy->count, B3_MAX_SHAPE_CAST_POINTS ); + for ( int i = 0; i < count; ++i ) + { + buffer[i] = b3Add( b3MulMV( R, proxy->points[i] ), invTransform.p ); + } + + return (b3ShapeProxy){ + .points = buffer, + .count = count, + .radius = proxy->radius, + }; +} + +b3AABB b3ComputeProxyAABB( const b3ShapeProxy* proxy ) +{ + const b3Vec3* points = proxy->points; + b3AABB aabb = { + .lowerBound = points[0], + .upperBound = points[0], + }; + + for ( int i = 1; i < proxy->count; ++i ) + { + aabb.lowerBound = b3Min( aabb.lowerBound, points[i] ); + aabb.upperBound = b3Max( aabb.upperBound, points[i] ); + } + + b3Vec3 r = { proxy->radius, proxy->radius, proxy->radius }; + aabb.lowerBound = b3Sub( aabb.lowerBound, r ); + aabb.upperBound = b3Add( aabb.upperBound, r ); + return aabb; +} + +b3BodyId b3Shape_GetBody( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + return b3MakeBodyId( world, shape->bodyId ); +} + +b3WorldId b3Shape_GetWorld( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + return (b3WorldId){ (uint16_t)( shapeId.world0 + 1 ), world->generation }; +} + +void b3Shape_SetUserData( b3ShapeId shapeId, void* userData ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + shape->userData = userData; +} + +void* b3Shape_GetUserData( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + return shape->userData; +} + +bool b3Shape_IsSensor( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + return shape->sensorIndex != B3_NULL_INDEX; +} + +void b3Shape_SetName( b3ShapeId shapeId, const char* name ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + + if ( shape->name != NULL ) + { + b3Free( shape->name, ( strlen( shape->name ) + 1 ) * sizeof( char ) ); + shape->name = NULL; + } + + if ( name != NULL ) + { + size_t length = strlen( name ) + 1; + shape->name = (char*)b3Alloc( length * sizeof( char ) ); + memcpy( shape->name, name, length ); + } +} + +const char* b3Shape_GetName( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + return shape->name; +} + +// todo no tests +b3CastOutput b3Shape_RayCast( b3ShapeId shapeId, const b3RayCastInput* input ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + + b3Transform transform = b3GetBodyTransform( world, shape->bodyId ); + + // input in local coordinates + b3RayCastInput localInput; + localInput.origin = b3InvTransformPoint( transform, input->origin ); + localInput.translation = b3InvRotateVector( transform.q, input->translation ); + localInput.maxFraction = input->maxFraction; + + b3CastOutput output = { 0 }; + switch ( shape->type ) + { + case b3_capsuleShape: + output = b3RayCastCapsule( &shape->capsule, &localInput ); + break; + + case b3_compoundShape: + output = b3RayCastCompound( shape->compound, &localInput ); + break; + + case b3_sphereShape: + output = b3RayCastSphere( &shape->sphere, &localInput ); + break; + + case b3_meshShape: + output = b3RayCastMesh( &shape->mesh, &localInput ); + break; + + case b3_hullShape: + output = b3RayCastHull( shape->hull, &localInput ); + break; + + case b3_heightShape: + output = b3RayCastHeightField( shape->heightField, &localInput ); + break; + + default: + B3_ASSERT( false ); + return output; + } + + if ( output.hit ) + { + // convert to world coordinates + output.normal = b3RotateVector( transform.q, output.normal ); + output.point = b3TransformPoint( transform, output.point ); + } + + return output; +} + +void b3Shape_SetDensity( b3ShapeId shapeId, float density, bool updateBodyMass ) +{ + B3_ASSERT( b3IsValidFloat( density ) && density >= 0.0f ); + + b3World* world = b3GetUnlockedWorld( shapeId.world0 ); + if ( world == NULL ) + { + return; + } + + b3Shape* shape = b3GetShape( world, shapeId ); + if ( density == shape->density ) + { + // early return to avoid expensive function + return; + } + + shape->density = density; + + if ( updateBodyMass == true ) + { + b3Body* body = b3Array_Get( world->bodies, shape->bodyId ); + b3UpdateBodyMassData( world, body ); + } +} + +float b3Shape_GetDensity( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + return shape->density; +} + +void b3Shape_SetFriction( b3ShapeId shapeId, float friction ) +{ + B3_ASSERT( b3IsValidFloat( friction ) && friction >= 0.0f ); + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + B3_ASSERT( shape->type != b3_compoundShape ); + shape->materials[0].friction = friction; +} + +float b3Shape_GetFriction( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + return shape->materials[0].friction; +} + +void b3Shape_SetRestitution( b3ShapeId shapeId, float restitution ) +{ + B3_ASSERT( b3IsValidFloat( restitution ) && restitution >= 0.0f ); + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + B3_ASSERT( shape->type != b3_compoundShape ); + shape->materials[0].restitution = restitution; +} + +float b3Shape_GetRestitution( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + return shape->materials[0].restitution; +} + +void b3Shape_SetSurfaceMaterial( b3ShapeId shapeId, b3SurfaceMaterial surfaceMaterial ) +{ + B3_ASSERT( b3IsValidFloat( surfaceMaterial.friction ) && surfaceMaterial.friction >= 0.0f ); + B3_ASSERT( b3IsValidFloat( surfaceMaterial.restitution ) && surfaceMaterial.restitution >= 0.0f ); + B3_ASSERT( b3IsValidFloat( surfaceMaterial.rollingResistance ) && surfaceMaterial.rollingResistance >= 0.0f ); + B3_ASSERT( b3IsValidVec3( surfaceMaterial.tangentVelocity ) ); + + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + B3_ASSERT( shape->type != b3_compoundShape ); + shape->materials[0] = surfaceMaterial; +} + +b3SurfaceMaterial b3Shape_GetSurfaceMaterial( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + return shape->materials[0]; +} + +int b3Shape_GetMeshMaterialCount( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + return shape->materialCount; +} + +void b3Shape_SetMeshMaterial( b3ShapeId shapeId, b3SurfaceMaterial surfaceMaterial, int index ) +{ + B3_ASSERT( b3IsValidFloat( surfaceMaterial.friction ) && surfaceMaterial.friction >= 0.0f ); + B3_ASSERT( b3IsValidFloat( surfaceMaterial.restitution ) && surfaceMaterial.restitution >= 0.0f ); + B3_ASSERT( b3IsValidFloat( surfaceMaterial.rollingResistance ) && surfaceMaterial.rollingResistance >= 0.0f ); + B3_ASSERT( b3IsValidVec3( surfaceMaterial.tangentVelocity ) ); + + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + + B3_ASSERT( 0 <= index && index < shape->materialCount ); + B3_ASSERT( shape->type != b3_compoundShape ); + shape->materials[index] = surfaceMaterial; +} + +b3SurfaceMaterial b3Shape_GetMeshSurfaceMaterial( b3ShapeId shapeId, int index ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + B3_ASSERT( 0 <= index && index < shape->materialCount ); + return shape->materials[index]; +} + +b3Filter b3Shape_GetFilter( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + return shape->filter; +} + +static void b3ResetProxy( b3World* world, b3Shape* shape, bool wakeBodies, bool destroyProxy ) +{ + b3Body* body = b3Array_Get( world->bodies, shape->bodyId ); + + int shapeId = shape->id; + + // destroy all contacts associated with this shape + int contactKey = body->headContactKey; + while ( contactKey != B3_NULL_INDEX ) + { + int contactId = contactKey >> 1; + int edgeIndex = contactKey & 1; + + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + contactKey = contact->edges[edgeIndex].nextKey; + + if ( contact->shapeIdA == shapeId || contact->shapeIdB == shapeId ) + { + b3DestroyContact( world, contact, wakeBodies ); + } + } + + b3Transform transform = b3GetBodyTransformQuick( world, body ); + if ( shape->proxyKey != B3_NULL_INDEX ) + { + b3BodyType proxyType = B3_PROXY_TYPE( shape->proxyKey ); + b3UpdateShapeAABBs( shape, transform, proxyType ); + + if ( destroyProxy ) + { + b3BroadPhase_DestroyProxy( &world->broadPhase, shape->proxyKey ); + + bool forcePairCreation = true; + shape->proxyKey = b3BroadPhase_CreateProxy( &world->broadPhase, proxyType, shape->fatAABB, shape->filter.categoryBits, + shapeId, forcePairCreation ); + } + else + { + b3BroadPhase_MoveProxy( &world->broadPhase, shape->proxyKey, shape->fatAABB ); + } + } + else + { + b3BodyType proxyType = body->type; + b3UpdateShapeAABBs( shape, transform, proxyType ); + } + + b3ValidateSolverSets( world ); +} + +void b3Shape_SetFilter( b3ShapeId shapeId, b3Filter filter, bool invokeContacts ) +{ + b3World* world = b3GetUnlockedWorld( shapeId.world0 ); + if ( world == NULL ) + { + return; + } + + b3Shape* shape = b3GetShape( world, shapeId ); + if ( filter.maskBits == shape->filter.maskBits && filter.categoryBits == shape->filter.categoryBits && + filter.groupIndex == shape->filter.groupIndex ) + { + return; + } + + shape->filter = filter; + + if ( invokeContacts ) + { + world->locked = true; + bool wakeBodies = true; + + // If the category bits change, I need to destroy the proxy because it affects the tree sorting. + bool destroyProxy = filter.categoryBits == shape->filter.categoryBits; + + // need to wake bodies because a filter change may destroy contacts + b3ResetProxy( world, shape, wakeBodies, destroyProxy ); + world->locked = false; + } + + // note: this does not immediately update sensor overlaps. Instead sensor + // overlaps are updated the next time step +} + +void b3Shape_EnableSensorEvents( b3ShapeId shapeId, bool flag ) +{ + b3World* world = b3GetUnlockedWorld( shapeId.world0 ); + if ( world == NULL ) + { + return; + } + + b3Shape* shape = b3GetShape( world, shapeId ); + shape->enableSensorEvents = flag; +} + +bool b3Shape_AreSensorEventsEnabled( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + return shape->enableSensorEvents; +} + +void b3Shape_EnableContactEvents( b3ShapeId shapeId, bool flag ) +{ + b3World* world = b3GetUnlockedWorld( shapeId.world0 ); + if ( world == NULL ) + { + return; + } + + b3Shape* shape = b3GetShape( world, shapeId ); + shape->enableContactEvents = flag; +} + +bool b3Shape_AreContactEventsEnabled( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + return shape->enableContactEvents; +} + +void b3Shape_EnablePreSolveEvents( b3ShapeId shapeId, bool flag ) +{ + b3World* world = b3GetUnlockedWorld( shapeId.world0 ); + if ( world == NULL ) + { + return; + } + + b3Shape* shape = b3GetShape( world, shapeId ); + shape->enablePreSolveEvents = flag; +} + +bool b3Shape_ArePreSolveEventsEnabled( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + return shape->enablePreSolveEvents; +} + +void b3Shape_EnableHitEvents( b3ShapeId shapeId, bool flag ) +{ + b3World* world = b3GetUnlockedWorld( shapeId.world0 ); + if ( world == NULL ) + { + return; + } + + b3Shape* shape = b3GetShape( world, shapeId ); + shape->enableHitEvents = flag; +} + +bool b3Shape_AreHitEventsEnabled( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + return shape->enableHitEvents; +} + +b3ShapeType b3Shape_GetType( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + return shape->type; +} + +b3Sphere b3Shape_GetSphere( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + B3_ASSERT( shape->type == b3_sphereShape ); + return shape->sphere; +} + +b3Capsule b3Shape_GetCapsule( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + B3_ASSERT( shape->type == b3_capsuleShape ); + return shape->capsule; +} + +const b3Hull* b3Shape_GetHull( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + B3_ASSERT( shape->type == b3_hullShape ); + return shape->hull; +} + +b3Mesh b3Shape_GetMesh( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + B3_ASSERT( shape->type == b3_meshShape ); + return shape->mesh; +} + +const b3HeightField* b3Shape_GetHeightField( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + b3Shape* shape = b3GetShape( world, shapeId ); + B3_ASSERT( shape->type == b3_heightShape ); + return shape->heightField; +} + +void b3Shape_SetSphere( b3ShapeId shapeId, const b3Sphere* sphere ) +{ + b3World* world = b3GetUnlockedWorld( shapeId.world0 ); + if ( world == NULL ) + { + return; + } + + world->locked = true; + + b3Shape* shape = b3GetShape( world, shapeId ); + + b3DestroyShapeAllocationForShapeChange( world, shape ); + + shape->sphere = *sphere; + shape->type = b3_sphereShape; + + // need to wake bodies so they can react to the shape change + bool wakeBodies = true; + bool destroyProxy = true; + b3ResetProxy( world, shape, wakeBodies, destroyProxy ); + + world->locked = false; +} + +void b3Shape_SetCapsule( b3ShapeId shapeId, const b3Capsule* capsule ) +{ + b3World* world = b3GetUnlockedWorld( shapeId.world0 ); + if ( world == NULL ) + { + return; + } + + world->locked = true; + + b3Shape* shape = b3GetShape( world, shapeId ); + + b3DestroyShapeAllocationForShapeChange( world, shape ); + + shape->capsule = *capsule; + shape->type = b3_capsuleShape; + + // need to wake bodies so they can react to the shape change + bool wakeBodies = true; + bool destroyProxy = true; + b3ResetProxy( world, shape, wakeBodies, destroyProxy ); + + world->locked = false; +} + +void b3Shape_SetHull( b3ShapeId shapeId, const b3Hull* hull ) +{ + b3World* world = b3GetUnlockedWorld( shapeId.world0 ); + if ( world == NULL ) + { + return; + } + + world->locked = true; + + b3Shape* shape = b3GetShape( world, shapeId ); + + b3DestroyShapeAllocationForShapeChange( world, shape ); + + shape->hull = b3CloneHull( hull ); + shape->type = b3_hullShape; + + // need to wake bodies so they can react to the shape change + bool wakeBodies = true; + bool destroyProxy = true; + b3ResetProxy( world, shape, wakeBodies, destroyProxy ); + + world->locked = false; +} + +void b3Shape_SetMesh( b3ShapeId shapeId, const b3MeshData* meshData, b3Vec3 scale ) +{ + B3_ASSERT( b3IsValidVec3( scale ) ); + B3_ASSERT( meshData != NULL && b3IsValidMesh( meshData ) ); + + b3World* world = b3GetUnlockedWorld( shapeId.world0 ); + if ( world == NULL ) + { + return; + } + + world->locked = true; + + b3Shape* shape = b3GetShape( world, shapeId ); + + b3DestroyShapeAllocationForShapeChange( world, shape ); + + shape->mesh.data = meshData; + shape->mesh.scale = b3SafeScale( scale ); + shape->type = b3_meshShape; + + // need to wake bodies so they can react to the shape change + bool wakeBodies = true; + bool destroyProxy = true; + b3ResetProxy( world, shape, wakeBodies, destroyProxy ); + + world->locked = false; +} + +int b3Shape_GetContactCapacity( b3ShapeId shapeId ) +{ + b3World* world = b3GetUnlockedWorld( shapeId.world0 ); + if ( world == NULL ) + { + return 0; + } + + b3Shape* shape = b3GetShape( world, shapeId ); + if ( shape->sensorIndex != B3_NULL_INDEX ) + { + return 0; + } + + b3Body* body = b3Array_Get( world->bodies, shape->bodyId ); + + // Conservative and fast + return body->contactCount; +} + +int b3Shape_GetContactData( b3ShapeId shapeId, b3ContactData* contactData, int capacity ) +{ + b3World* world = b3GetUnlockedWorld( shapeId.world0 ); + if ( world == NULL ) + { + return 0; + } + + b3Shape* shape = b3GetShape( world, shapeId ); + if ( shape->sensorIndex != B3_NULL_INDEX ) + { + return 0; + } + + b3Body* body = b3Array_Get( world->bodies, shape->bodyId ); + int contactKey = body->headContactKey; + int index = 0; + while ( contactKey != B3_NULL_INDEX && index < capacity ) + { + int contactId = contactKey >> 1; + int edgeIndex = contactKey & 1; + + b3Contact* contact = b3Array_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 & b3_contactTouchingFlag ) != 0 ) + { + b3Shape* shapeA = world->shapes.data + contact->shapeIdA; + b3Shape* shapeB = world->shapes.data + contact->shapeIdB; + + contactData[index].contactId = (b3ContactId){ contact->contactId + 1, shapeId.world0, 0, contact->generation }; + contactData[index].shapeIdA = (b3ShapeId){ shapeA->id + 1, shapeId.world0, shapeA->generation }; + contactData[index].shapeIdB = (b3ShapeId){ shapeB->id + 1, shapeId.world0, shapeB->generation }; + contactData[index].manifolds = contact->manifolds; + contactData[index].manifoldCount = contact->manifoldCount; + index += 1; + } + + contactKey = contact->edges[edgeIndex].nextKey; + } + + B3_ASSERT( index <= capacity ); + + return index; +} + +int b3Shape_GetSensorCapacity( b3ShapeId shapeId ) +{ + b3World* world = b3GetUnlockedWorld( shapeId.world0 ); + if ( world == NULL ) + { + return 0; + } + + b3Shape* shape = b3GetShape( world, shapeId ); + if ( shape->sensorIndex == B3_NULL_INDEX ) + { + return 0; + } + + b3Sensor* sensor = b3Array_Get( world->sensors, shape->sensorIndex ); + return sensor->overlaps2.count; +} + +int b3Shape_GetSensorData( b3ShapeId shapeId, b3ShapeId* visitorIds, int capacity ) +{ + b3World* world = b3GetUnlockedWorld( shapeId.world0 ); + if ( world == NULL ) + { + return 0; + } + + b3Shape* shape = b3GetShape( world, shapeId ); + if ( shape->sensorIndex == B3_NULL_INDEX ) + { + return 0; + } + + b3Sensor* sensor = b3Array_Get( world->sensors, shape->sensorIndex ); + + int count = b3MinInt( sensor->overlaps2.count, capacity ); + b3Visitor* refs = sensor->overlaps2.data; + for ( int i = 0; i < count; ++i ) + { + b3ShapeId visitorId = { + .index1 = refs[i].shapeId + 1, + .world0 = shapeId.world0, + .generation = refs[i].generation, + }; + + visitorIds[i] = visitorId; + } + + return count; +} + +b3AABB b3Shape_GetAABB( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + if ( world == NULL ) + { + return (b3AABB){ 0 }; + } + + b3Shape* shape = b3GetShape( world, shapeId ); + return shape->aabb; +} + +b3MassData b3Shape_ComputeMassData( b3ShapeId shapeId ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + if ( world == NULL ) + { + return (b3MassData){ 0 }; + } + + b3Shape* shape = b3GetShape( world, shapeId ); + return b3ComputeShapeMass( shape ); +} + +b3Vec3 b3Shape_GetClosestPoint( b3ShapeId shapeId, b3Vec3 target ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + if ( world == NULL ) + { + return b3Vec3_zero; + } + + b3Shape* shape = b3GetShape( world, shapeId ); + b3Body* body = b3Array_Get( world->bodies, shape->bodyId ); + b3Transform transform = b3GetBodyTransformQuick( world, body ); + + b3DistanceInput input; + input.proxyA = b3MakeShapeProxy( shape ); + input.proxyB = (b3ShapeProxy){ &target, 1, 0.0f }; + input.transformA = transform; + input.transformB = b3Transform_identity; + input.useRadii = true; + + b3SimplexCache cache = { 0 }; + b3DistanceOutput output = b3ShapeDistance( &input, &cache, NULL, 0 ); + + return output.pointA; +} + +#define B3_DEBUG_WIND 0 + +// 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 b3Shape_ApplyWind( b3ShapeId shapeId, b3Vec3 wind, float drag, float lift, float maxSpeed, bool wake ) +{ + b3World* world = b3GetWorld( shapeId.world0 ); + if ( world == NULL ) + { + return; + } + + b3Shape* shape = b3GetShape( world, shapeId ); + + b3ShapeType shapeType = shape->type; + if ( shapeType != b3_sphereShape && shapeType != b3_capsuleShape && shapeType != b3_hullShape ) + { + return; + } + + b3Body* body = b3Array_Get( world->bodies, shape->bodyId ); + + if ( body->type != b3_dynamicBody ) + { + return; + } + + if ( body->setIndex == b3_disabledSet ) + { + return; + } + + if ( body->setIndex >= b3_firstSleepingSet && wake == false ) + { + return; + } + + b3BodySim* sim = b3GetBodySim( world, body ); + + if ( body->setIndex != b3_awakeSet ) + { + // Must wake for state to exist + b3WakeBodyWithLock( world, body ); + } + + B3_ASSERT( body->setIndex == b3_awakeSet ); + + b3BodyState* state = b3GetBodyState( world, body ); + b3Transform transform = sim->transform; + + float lengthUnits = b3GetLengthUnitsPerMeter(); + float volumeUnits = lengthUnits * lengthUnits * lengthUnits; + + float airDensity = 1.2250f / ( volumeUnits ); + + b3Vec3 force = { 0 }; + b3Vec3 torque = { 0 }; + + switch ( shape->type ) + { + case b3_sphereShape: + { + float radius = shape->sphere.radius; + b3Vec3 centroid = shape->localCentroid; + b3Vec3 lever = b3RotateVector( transform.q, b3Sub( centroid, sim->localCenter ) ); + b3Vec3 shapeVelocity = b3Add( state->linearVelocity, b3Cross( state->angularVelocity, lever ) ); + b3Vec3 relativeVelocity = b3MulSub( wind, drag, shapeVelocity ); + float speed; + b3Vec3 direction = b3GetLengthAndNormalize( &speed, relativeVelocity ); + speed = b3MinFloat( speed, maxSpeed ); + float projectedArea = B3_PI * radius * radius; + force = b3MulSV( 0.5f * airDensity * projectedArea * speed * speed, direction ); + torque = b3Cross( lever, force ); + } + break; + + case b3_capsuleShape: + { + b3Vec3 centroid = shape->localCentroid; + b3Vec3 lever = b3RotateVector( transform.q, b3Sub( centroid, sim->localCenter ) ); + b3Vec3 shapeVelocity = b3Add( state->linearVelocity, b3Cross( state->angularVelocity, lever ) ); + b3Vec3 relativeVelocity = b3MulSub( wind, drag, shapeVelocity ); + float speed; + b3Vec3 direction = b3GetLengthAndNormalize( &speed, relativeVelocity ); + speed = b3MinFloat( speed, maxSpeed ); + + b3Vec3 d = b3Sub( shape->capsule.center2, shape->capsule.center1 ); + d = b3RotateVector( transform.q, d ); + + float radius = shape->capsule.radius; + float projectedArea = B3_PI * radius * radius + 2.0f * radius * b3Length( b3Cross( d, direction ) ); + + // Normal that opposes the wind + b3Vec3 e = b3Normalize( d ); + b3Vec3 normal = b3Sub( b3MulSV( b3Dot( direction, e ), e ), direction ); + + // portion of wind that is perpendicular to surface + b3Vec3 liftDirection = b3Cross( b3Cross( normal, direction ), direction ); + + float forceMagnitude = 0.5f * airDensity * projectedArea * speed * speed; + force = b3MulSV( forceMagnitude, b3MulAdd( direction, lift, liftDirection ) ); + + b3Vec3 edgeLever = b3MulAdd( lever, radius, normal ); + torque = b3Cross( edgeLever, force ); + } + break; + + case b3_hullShape: + { + b3Matrix3 matrix = b3MakeMatrixFromQuat( transform.q ); + + int faceCount = shape->hull->faceCount; + const b3Vec3* points = b3GetHullPoints( shape->hull ); + const b3HullFace* faces = b3GetHullFaces( shape->hull ); + const b3HullHalfEdge* edges = b3GetHullEdges( shape->hull ); + const b3Plane* planes = b3GetHullPlanes( shape->hull ); + + b3Vec3 linearVelocity = state->linearVelocity; + b3Vec3 angularVelocity = state->angularVelocity; + b3Vec3 localCenterOfMass = sim->localCenter; + + for ( int i = 0; i < faceCount; ++i ) + { + const b3HullFace* face = faces + i; + const b3HullHalfEdge* edge1 = edges + face->edge; + const b3HullHalfEdge* edge2 = edges + edge1->next; + const b3HullHalfEdge* edge3 = edges + edge2->next; + + B3_ASSERT( edge1 != edge3 ); + B3_ASSERT( edge1->origin < shape->hull->vertexCount ); + B3_ASSERT( edge2->origin < shape->hull->vertexCount ); + + b3Vec3 localPoint1 = points[edge1->origin]; + b3Vec3 localPoint2 = points[edge2->origin]; + b3Vec3 v1 = b3MulMV( matrix, localPoint1 ); + b3Vec3 v2 = b3MulMV( matrix, localPoint2 ); + b3Vec3 normal = b3MulMV( matrix, planes[i].normal ); + + do + { + B3_ASSERT( edge3->origin < shape->hull->vertexCount ); + b3Vec3 localPoint3 = points[edge3->origin]; + b3Vec3 v3 = b3MulMV( matrix, localPoint3 ); + + // Triangle center + b3Vec3 localCenter = b3MulSV( 0.333333f, b3Add( localPoint1, b3Add( localPoint2, localPoint3 ) ) ); + + // Lever arm from center of mass to triangle center in world space + b3Vec3 lever = b3MulMV( matrix, b3Sub( localCenter, localCenterOfMass ) ); + + // Velocity of the triangle center in world space + b3Vec3 centerVelocity = b3Add( linearVelocity, b3Cross( angularVelocity, lever ) ); + + b3Vec3 relativeVelocity = b3MulSub( wind, drag, centerVelocity ); + float speed; + b3Vec3 direction = b3GetLengthAndNormalize( &speed, relativeVelocity ); + + // Check for back-side + if ( b3Dot( normal, direction ) < -FLT_EPSILON ) + { + float projectedArea = -0.5f * b3Dot( b3Cross( b3Sub( v2, v1 ), b3Sub( v3, v1 ) ), direction ); + B3_VALIDATE( projectedArea >= -FLT_EPSILON ); + + b3Vec3 liftDirection = b3Cross( b3Cross( normal, direction ), direction ); + + speed = b3MinFloat( speed, maxSpeed ); + + float forceMagnitude = 0.5f * airDensity * projectedArea * speed * speed; + b3Vec3 deltaForce = b3MulSV( forceMagnitude, b3MulAdd( direction, lift, liftDirection ) ); + b3Vec3 deltaTorque = b3Cross( lever, deltaForce ); + + force = b3Add( force, deltaForce ); + torque = b3Add( torque, deltaTorque ); + +#if B3_DEBUG_WIND + int lineIndex = world->taskContexts.data[0].lineCount; + if ( lineIndex < B3_DEBUG_LINE_CAPACITY ) + { + b3DebugLine* line = world->taskContexts.data[0].lines + lineIndex; + line->p1 = b3Add( b3MulMV( matrix, localCenter ), transform.p ); + line->p2 = b3Add( line->p1, deltaForce ); + line->label = i; + line->color = b3_colorBlanchedAlmond; + world->taskContexts.data[0].lineCount += 1; + } +#endif + } + + edge2 = edge3; + edge3 = edges + edge3->next; + v2 = v3; + localPoint2 = localPoint3; + } + while ( edge1 != edge3 ); + } + } + break; + + default: + break; + } + + sim->force = b3Add( sim->force, force ); + sim->torque = b3Add( sim->torque, torque ); +} + +typedef struct b3MeshImpactContext +{ + b3TOIInput toiInput; + b3TOIOutput toiOutput; + // Centroid of shape in body B local space + b3Vec3 localCentroidB; + // Centroid of shape at beginning and end of sweep in mesh local space. Used for early out. + b3Vec3 meshLocalCentroidB1, meshLocalCentroidB2; + float fallbackRadius; + bool isSensor; +} b3MeshImpactContext; + +static bool b3MeshTimeOfImpactFcn( b3Vec3 a, b3Vec3 b, b3Vec3 c, int triangleIndex, void* context ) +{ + B3_UNUSED( triangleIndex ); + + b3MeshImpactContext* toiContext = (b3MeshImpactContext*)context; + + // Early out for parallel movement + b3Vec3 c1 = toiContext->meshLocalCentroidB1; + b3Vec3 c2 = toiContext->meshLocalCentroidB2; + + b3Vec3 n = b3Normalize( b3Cross( b3Sub( b, a ), b3Sub( c, a ) ) ); + float offset1 = b3Dot( n, b3Sub( c1, a ) ); + float offset2 = b3Dot( n, b3Sub( c2, a ) ); + + if ( offset1 < 0.0f ) + { + // Started behind or finished in front + return true; + } + + if ( toiContext->isSensor == false && offset1 - offset2 < toiContext->fallbackRadius && offset2 > toiContext->fallbackRadius ) + { + // Finished in front + return true; + } + + b3Vec3 triangle[3] = { a, b, c }; + toiContext->toiInput.proxyA.points = triangle; + toiContext->toiInput.proxyA.count = 3; + + b3TOIOutput output = b3TimeOfImpact( &toiContext->toiInput ); + + // It is possible for a hit at fraction == 0 + + if ( 0.0f < output.fraction && output.fraction < toiContext->toiInput.maxFraction ) + { + toiContext->toiOutput = output; + toiContext->toiInput.maxFraction = output.fraction; + } + else if ( 0.0f == output.fraction ) + { + // fallback to TOI of a small circle around the fast shape centroid + b3TOIInput fallbackInput = toiContext->toiInput; + fallbackInput.proxyB = (b3ShapeProxy){ &toiContext->localCentroidB, 1, toiContext->fallbackRadius + B3_LINEAR_SLOP }; + output = b3TimeOfImpact( &fallbackInput ); + + if ( 0.0f < output.fraction && output.fraction < toiContext->toiInput.maxFraction ) + { + toiContext->toiOutput = output; + toiContext->toiInput.maxFraction = output.fraction; + toiContext->toiOutput.usedFallback = true; + } + } + + // Continue the query + return true; +} + +typedef struct b3CompoundImpactContext +{ + b3TOIInput toiInput; + b3TOIOutput toiOutput; + b3Transform compoundTransform; + + // Bounds local to compound + b3AABB localSweepBoundsB; + + // Centroid of shape in body B local space + b3Vec3 localCentroidB; + float fallbackRadius; +} b3CompoundImpactContext; + +// Implements b3CompoundQueryFcn +static bool b3CompoundTimeOfImpactFcn( const b3Compound* compound, int childIndex, void* context ) +{ + b3CompoundImpactContext* toiContext = (b3CompoundImpactContext*)context; + + b3ChildShape child = b3GetCompoundChild( compound, childIndex ); + + b3TOIOutput output = { 0 }; + toiContext->toiInput.sweepA = b3MakeCompoundChildSweep( toiContext->compoundTransform, child.transform ); + + switch ( child.type ) + { + case b3_capsuleShape: + { + toiContext->toiInput.proxyA.points = &child.capsule.center1; + toiContext->toiInput.proxyA.count = 2; + toiContext->toiInput.proxyA.radius = child.capsule.radius; + output = b3TimeOfImpact( &toiContext->toiInput ); + } + break; + + case b3_hullShape: + { + toiContext->toiInput.proxyA.points = b3GetHullPoints( child.hull ); + toiContext->toiInput.proxyA.count = child.hull->vertexCount; + toiContext->toiInput.proxyA.radius = 0.0f; + output = b3TimeOfImpact( &toiContext->toiInput ); + } + break; + + case b3_meshShape: + { + b3MeshImpactContext meshContext = { 0 }; + meshContext.toiInput = toiContext->toiInput; + meshContext.isSensor = false; + meshContext.localCentroidB = toiContext->localCentroidB; + meshContext.fallbackRadius = toiContext->fallbackRadius; + + b3Transform meshWorldTransform = b3MulTransforms( toiContext->compoundTransform, child.transform ); + + const b3Sweep* sweepB = &toiContext->toiInput.sweepB; + b3Transform xfB1 = { + .p = b3Sub( sweepB->c1, b3RotateVector( sweepB->q1, sweepB->localCenter ) ), + .q = sweepB->q1, + }; + + b3Transform xfB2 = { + .p = b3Sub( sweepB->c2, b3RotateVector( sweepB->q2, sweepB->localCenter ) ), + .q = sweepB->q2, + }; + + meshContext.meshLocalCentroidB1 = + b3InvTransformPoint( meshWorldTransform, b3TransformPoint( xfB1, meshContext.localCentroidB ) ); + meshContext.meshLocalCentroidB2 = + b3InvTransformPoint( meshWorldTransform, b3TransformPoint( xfB2, meshContext.localCentroidB ) ); + + // Bounds local to mesh + b3AABB localBounds = b3AABB_Transform( b3InvertTransform( child.transform ), toiContext->localSweepBoundsB ); + + b3QueryMesh( &child.mesh, localBounds, b3MeshTimeOfImpactFcn, &meshContext ); + + output = meshContext.toiOutput; + } + break; + + case b3_sphereShape: + { + toiContext->toiInput.proxyA.points = &child.sphere.center; + toiContext->toiInput.proxyA.count = 1; + toiContext->toiInput.proxyA.radius = child.sphere.radius; + output = b3TimeOfImpact( &toiContext->toiInput ); + } + break; + + default: + B3_ASSERT( false ); + break; + } + + if ( 0.0f < output.fraction && output.fraction < toiContext->toiInput.maxFraction ) + { + toiContext->toiOutput = output; + toiContext->toiInput.maxFraction = output.fraction; + } + + // Clear this to be safe + toiContext->toiInput.proxyA = (b3ShapeProxy){ 0 }; + + // Continue the query + return true; +} + +b3TOIOutput b3ShapeTimeOfImpact( b3Shape* shapeA, b3Shape* shapeB, b3Sweep* sweepA, b3Sweep* sweepB, float maxFraction ) +{ + bool isSensor = shapeA->sensorIndex != B3_NULL_INDEX; + + b3ShapeType typeA = shapeA->type; + if ( typeA == b3_compoundShape ) + { + // todo implement b3CompoundTimeOfImpact + b3CompoundImpactContext context = { 0 }; + context.toiInput.proxyB = b3MakeShapeProxy( shapeB ); + context.toiInput.sweepB = *sweepB; + context.toiInput.maxFraction = maxFraction; + + context.compoundTransform = (b3Transform){ + .p = sweepA->c1, + .q = sweepA->q1, + }; + + b3Vec3 localCentroidB = b3GetShapeCentroid( shapeB ); + context.localCentroidB = localCentroidB; + + b3ShapeExtent extents = b3ComputeShapeExtent( shapeB, context.localCentroidB ); + context.fallbackRadius = b3MaxFloat( 0.75f * extents.minExtent, B3_SPECULATIVE_DISTANCE ); + + // Swept bounds of shapeB + b3AABB bounds = b3ComputeSweptShapeAABB( shapeB, sweepB, maxFraction ); + + // Bounds local to mesh + b3AABB localBounds = b3AABB_Transform( b3InvertTransform( context.compoundTransform ), bounds ); + context.localSweepBoundsB = localBounds; + + b3QueryCompound( shapeA->compound, localBounds, b3CompoundTimeOfImpactFcn, &context ); + + return context.toiOutput; + } + + if ( typeA == b3_heightShape || typeA == b3_meshShape ) + { + // todo implement b3MeshTimeOfImpact and b3HeightFieldTimeOfImpact + // Note: assuming mesh is static + + b3MeshImpactContext context = { 0 }; + context.toiInput.sweepA = *sweepA; + context.toiInput.proxyA.count = 3; + context.toiInput.proxyB = b3MakeShapeProxy( shapeB ); + context.toiInput.sweepB = *sweepB; + context.toiInput.maxFraction = maxFraction; + context.isSensor = isSensor; + + b3Vec3 localCentroidB = b3GetShapeCentroid( shapeB ); + context.localCentroidB = localCentroidB; + + // Assume mesh is static + b3Transform xfA = { + .p = b3Sub( sweepA->c1, b3RotateVector( sweepA->q1, sweepA->localCenter ) ), + .q = sweepA->q1, + }; + + b3Transform xfB1 = { + .p = b3Sub( sweepB->c1, b3RotateVector( sweepB->q1, sweepB->localCenter ) ), + .q = sweepB->q1, + }; + + b3Transform xfB2 = { + .p = b3Sub( sweepB->c2, b3RotateVector( sweepB->q2, sweepB->localCenter ) ), + .q = sweepB->q2, + }; + + // b3Vec3 centroidB1 = b3InvRotateVector( xfA.q, b3RotateVector( sweepB->q1, localCentroidB - sweepB->localCenter ) + + // ( sweepB->c1 - xfA.p ) ); + // b3Vec3 centroidB2 = b3InvRotateVector( xfA.q, b3RotateVector( sweepB->q2, localCentroidB - sweepB->localCenter ) + + // ( sweepB->c2 - xfA.p ) ); + + context.meshLocalCentroidB1 = b3InvTransformPoint( xfA, b3TransformPoint( xfB1, localCentroidB ) ); + context.meshLocalCentroidB2 = b3InvTransformPoint( xfA, b3TransformPoint( xfB2, localCentroidB ) ); + + b3ShapeExtent extents = b3ComputeShapeExtent( shapeB, context.localCentroidB ); + context.fallbackRadius = b3MaxFloat( 0.5f * extents.minExtent, B3_LINEAR_SLOP ); + + // Swept bounds of shapeB + // todo pass in xfA to get local bounds directly + b3AABB bounds = b3ComputeSweptShapeAABB( shapeB, sweepB, maxFraction ); + + // Bounds local to mesh + b3AABB localBounds = b3AABB_Transform( b3InvertTransform( xfA ), bounds ); + + if ( typeA == b3_meshShape ) + { + b3QueryMesh( &shapeA->mesh, localBounds, b3MeshTimeOfImpactFcn, &context ); + } + else if ( typeA == b3_heightShape ) + { + b3QueryHeightField( shapeA->heightField, localBounds, b3MeshTimeOfImpactFcn, &context ); + } + + return context.toiOutput; + } + + B3_ASSERT( shapeB->type != b3_compoundShape && shapeB->type != b3_meshShape && shapeB->type != b3_heightShape ); + + b3TOIInput input; + input.proxyA = b3MakeShapeProxy( shapeA ); + input.proxyB = b3MakeShapeProxy( shapeB ); + input.sweepA = *sweepA; + input.sweepB = *sweepB; + input.maxFraction = maxFraction; + + b3TOIOutput output = b3TimeOfImpact( &input ); + +#if 0 + // todo I'm not sure this is worth it for convex vs convex. + if (0.0f < output.fraction && output.fraction < maxFraction) + { + return output; + } + + if (0.0f == output.fraction) + { + // fallback to TOI of a small circle around the fast shape centroid + b3Vec3 centroid = b3GetShapeCentroid( shapeB ); + input.proxyB = ( b3ShapeProxy ){ ¢roid, 1, B3_SPECULATIVE_DISTANCE }; + output = b3TimeOfImpact( &input ); + return output; + } +#endif + + return output; +} + +// Resolve the user material id for a hit point on the given shape. Mesh/heightfield shapes +// use the manifold-point triangleIndex to pick a per-triangle material. Compound shapes use +// the contact's childIndex to find the participating child, then for a mesh child apply the +// child's materialIndices indirection on top of the per-triangle index. Convex shapes fall +// back to materials[0]. childIndex is unused for non-compound shapes. +uint64_t b3GetShapeUserMaterialId( const b3Shape* shape, int childIndex, int triangleIndex ) +{ + if ( shape->materialCount == 0 ) + { + return 0; + } + + int materialIndex = 0; + if ( shape->type == b3_meshShape ) + { + const uint8_t* indices = b3GetMeshMaterialIndices( shape->mesh.data ); + if ( indices != NULL ) + { + materialIndex = indices[triangleIndex]; + } + } + else if ( shape->type == b3_heightShape ) + { + materialIndex = b3GetHeightFieldMaterial( shape->heightField, triangleIndex ); + } + else if ( shape->type == b3_compoundShape ) + { + b3ChildShape child = b3GetCompoundChild( shape->compound, childIndex ); + if ( child.type == b3_meshShape ) + { + const uint8_t* indices = b3GetMeshMaterialIndices( child.mesh.data ); + int meshMaterialIndex = indices != NULL ? indices[triangleIndex] : 0; + meshMaterialIndex = b3ClampInt( meshMaterialIndex, 0, B3_MAX_COMPOUND_MESH_MATERIALS - 1 ); + materialIndex = child.materialIndices[meshMaterialIndex]; + } + else + { + materialIndex = child.materialIndices[0]; + } + } + + materialIndex = b3ClampInt( materialIndex, 0, shape->materialCount - 1 ); + return shape->materials[materialIndex].userMaterialId; +} + +void b3DumpShape( b3World* world, int shapeIndex ) +{ + b3Shape* shape = b3Array_Get( world->shapes, shapeIndex ); + + b3Dump( " b3ShapeDef sd = b3DefaultShapeDef();\n" ); + + if ( shape->name != NULL ) + { + b3Dump( " sd.name = \"%s\";\n", shape->name ); + } + + // printf("%" PRIx64 ";\n", t); + b3Dump( " sd.density = %.9g;\n", shape->density ); + b3Dump( " sd.isSensor = bool(%d);\n", shape->sensorIndex != B3_NULL_INDEX ); + b3Dump( " sd.filter.categoryBits = 0x%" PRIx64 ";\n", shape->filter.categoryBits ); + b3Dump( " sd.filter.maskBits = 0x%" PRIx64 ";\n", shape->filter.maskBits ); + b3Dump( " sd.filter.groupIndex = %d;\n", shape->filter.groupIndex ); + + B3_ASSERT( shape->materialCount >= 1 ); + b3SurfaceMaterial* m = shape->materials + 0; + b3Dump( " sd.baseMaterial.friction = %.9g;\n", m->friction ); + b3Dump( " sd.baseMaterial.restitution = %.9g;\n", m->restitution ); + b3Dump( " sd.baseMaterial.rollingResistance = %.9g;\n", m->rollingResistance ); + + switch ( shape->type ) + { + case b3_capsuleShape: + { + b3Capsule* s = &shape->capsule; + b3Dump( " b3CapsuleShape shape;\n" ); + b3Dump( " shape.center1 = {%.9g, %.9g, %.9g};\n", s->center1.x, s->center1.y, s->center1.z ); + b3Dump( " shape.center2 = {%.9g, %.9g, %.9g};\n", s->center2.x, s->center2.y, s->center2.z ); + b3Dump( " shape.radius = %.9g;\n", s->radius ); + b3Dump( " b3CreateCapsuleShape(bodyId, &sd, &shape);\n" ); + } + break; + + case b3_compoundShape: + { + // todo + } + break; + + case b3_heightShape: + { + // todo + } + break; + + case b3_hullShape: + { + const b3Hull* s = shape->hull; + int vertexCount = s->vertexCount; + const b3Vec3* vs = b3GetHullPoints( s ); + b3Dump( " b3Vec3 vs[%d];\n", vertexCount ); + for ( int i = 0; i < vertexCount; ++i ) + { + b3Dump( " vs[%d] = {%.9g, %.9g, %.9g};\n", i, vs[i].x, vs[i].y, vs[i].z ); + } + b3Dump( " b3Hull* hull = b3CreateHull(vs, %d);\n", vertexCount ); + b3Dump( " b3CreateHullShape(bodyId, &sd, hull);\n" ); + b3Dump( " b3DestroyHull(hull);\n" ); + } + break; + + case b3_meshShape: + { + const b3MeshData* s = shape->mesh.data; + b3Vec3 scale = shape->mesh.scale; + int meshIndex = b3FetchAddMeshDumpIndex(); + char buffer[64]; + snprintf( buffer, 64, "mesh_dump_%d.b3m", meshIndex ); + b3WriteBinaryFile( (void*)s, s->byteCount, buffer ); + + b3Dump( " int dataSize = 0;\n" ); + b3Dump( " b3MeshData* data = (b3MeshData*)b3ReadBinaryFile(dumpPrefix, \"%s\", &dataSize);\n", buffer ); + b3Dump( " if (data == nullptr || data->version != B3_MESH_VERSION || data->byteCount != dataSize)\n" ); + b3Dump( " {\n" ); + b3Dump( " return;\n" ); + b3Dump( " }\n" ); + b3Dump( " b3Vec3 scale = { %.9g, %.9g, %.9g };\n", scale.x, scale.y, scale.z ); + b3Dump( " b3CreateMeshShape(bodyId, &sd, data, scale);\n" ); + // Host code must have this container and destroy the mesh data when the world is destroyed. + b3Dump( " m_meshes.push_back(data);\n" ); + } + break; + + case b3_sphereShape: + { + b3Sphere* s = &shape->sphere; + b3Dump( " b3SphereShape shape;\n" ); + b3Dump( " shape.center = {%.9g, %.9g, %.9g};\n", s->center.x, s->center.y, s->center.z ); + b3Dump( " shape.radius = %.9g;\n", s->radius ); + b3Dump( " b3CreateSphereShape(bodyId, &sd, &shape);\n" ); + } + break; + + default: + return; + } +} diff --git a/src/shape.h b/src/shape.h new file mode 100644 index 0000000..57b6301 --- /dev/null +++ b/src/shape.h @@ -0,0 +1,143 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "math_internal.h" + +#include "box3d/types.h" + +#include + +typedef struct b3BroadPhase b3BroadPhase; +typedef struct b3World b3World; + +typedef struct b3Shape +{ + int id; + int bodyId; + int prevShapeId; + int nextShapeId; + int sensorIndex; + int proxyKey; + b3ShapeType type; + float density; + float explosionScale; + + b3AABB aabb; + b3AABB fatAABB; + b3Vec3 localCentroid; + + int materialCount; + b3SurfaceMaterial* materials; + + b3Filter filter; + char* name; + void* userData; + void* userShape; + + uint16_t generation; + bool enableSensorEvents; + bool enableContactEvents; + bool enableCustomFiltering; + bool enableHitEvents; + bool enablePreSolveEvents; + bool enlargedAABB; + + union + { + b3Capsule capsule; + b3Sphere sphere; + const b3Hull* hull; + b3Mesh mesh; + const b3HeightField* heightField; + const b3Compound* compound; + }; + +} b3Shape; + +#ifdef __cplusplus +extern "C" +{ +#endif + +void b3CreateShapeProxy( b3Shape* shape, b3BroadPhase* bp, b3BodyType type, b3Transform transform, bool forcePairCreation ); +void b3DestroyShapeProxy( b3Shape* shape, b3BroadPhase* bp ); + +void b3DestroyShapeAllocations( b3World* world, b3Shape* shape ); + +b3MassData b3ComputeShapeMass( const b3Shape* shape ); +b3ShapeExtent b3ComputeShapeExtent( const b3Shape* shape, b3Vec3 localCenter ); + +b3AABB b3ComputeSweptSphereAABB( const b3Sphere* shape, b3Transform xf1, b3Transform xf2 ); +b3AABB b3ComputeSweptCapsuleAABB( const b3Capsule* shape, b3Transform xf1, b3Transform xf2 ); + +b3AABB b3ComputeShapeAABB( const b3Shape* shape, b3Transform transform ); +b3AABB b3ComputeSweptShapeAABB( const b3Shape* shape, const b3Sweep* sweep, float time ); +b3Vec3 b3GetShapeCentroid( const b3Shape* shape ); +float b3GetShapeArea( const b3Shape* shape ); +float b3GetShapeProjectedArea( const b3Shape* shape, b3Vec3 planeNormal ); +uint64_t b3GetShapeUserMaterialId( const b3Shape* shape, int childIndex, int triangleIndex ); + +b3ShapeProxy b3MakeShapeProxy( const b3Shape* shape ); +b3ShapeProxy b3MakeLocalProxy( const b3ShapeProxy* proxy, b3Transform transform, b3Vec3* buffer ); +b3AABB b3ComputeProxyAABB( const b3ShapeProxy* proxy ); + +b3CastOutput b3RayCastShape( const b3Shape* shape, b3Transform transform, const b3RayCastInput* input ); +b3CastOutput b3ShapeCastShape( const b3Shape* shape, b3Transform transform, const b3ShapeCastInput* input ); +bool b3OverlapShape( const b3Shape* shape, b3Transform transform, const b3ShapeProxy* proxy ); + +float b3GetShapeArea( const b3Shape* shape ); +float b3GetShapeProjectedArea( const b3Shape* shape, b3Vec3 planeNormal ); +b3TOIOutput b3ShapeTimeOfImpact( b3Shape* shapeA, b3Shape* shapeB, b3Sweep* sweepA, b3Sweep* sweepB, float maxFraction ); + +int b3CollideMoverAndSphere( b3PlaneResult* result, const b3Sphere* shape, const b3Capsule* mover ); +int b3CollideMoverAndCapsule( b3PlaneResult* result, const b3Capsule* shape, const b3Capsule* mover ); +int b3CollideMoverAndHull( b3PlaneResult* result, const b3Hull* shape, const b3Capsule* mover ); +int b3CollideMoverAndMesh( b3PlaneResult* planes, int capacity, const b3Mesh* shape, const b3Capsule* mover ); +int b3CollideMoverAndHeightField( b3PlaneResult* results, int capacity, const b3HeightField* shape, const b3Capsule* mover ); +int b3CollideMover( b3PlaneResult* planes, int planeCapacity, const b3Shape* shape, b3Transform transform, + const b3Capsule* mover ); + +// Hull +int b3FindHullSupportVertex( const b3Hull* hull, b3Vec3 direction ); +int b3FindHullSupportFace( const b3Hull* hull, b3Vec3 direction ); +bool b3IsValidHull( const b3Hull* hull ); +b3AABB b3ComputeSweptHullAABB( const b3Hull* shape, b3Transform xf1, b3Transform xf2 ); +b3ShapeExtent b3ComputeHullExtent( const b3Hull* hull, b3Vec3 origin ); +float b3ComputeHullProjectedArea( const b3Hull* hull, b3Vec3 direction ); + +// Height field +b3Triangle b3GetHeightFieldTriangle( const b3HeightField* heightField, int triangleIndex ); +int b3GetHeightFieldMaterial( const b3HeightField* heightField, int triangleIndex ); + +B3_INLINE int b3GetHeightFieldTriangleCount( const b3HeightField* heightField ) +{ + int cellCount = ( heightField->rowCount - 1 ) * ( heightField->columnCount - 1 ); + return 2 * cellCount; +} + +// Mesh +b3Triangle b3GetMeshTriangle( const b3Mesh* mesh, int triangleIndex ); +bool b3IsValidMesh( const b3MeshData* meshData ); +void b3DumpShape( b3World* world, int shapeIndex ); + +#ifdef __cplusplus +} +#endif + +B3_INLINE bool b3ShouldShapesCollide( b3Filter filterA, b3Filter filterB ) +{ + if ( filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0 ) + { + return filterA.groupIndex > 0; + } + + return ( filterA.maskBits & filterB.categoryBits ) != 0 && ( filterA.categoryBits & filterB.maskBits ) != 0; +} + +B3_INLINE bool b3ShouldQueryCollide( const b3Filter* shapeFilter, const b3QueryFilter* queryFilter ) +{ + return ( shapeFilter->categoryBits & queryFilter->maskBits ) != 0 && + ( shapeFilter->maskBits & queryFilter->categoryBits ) != 0; +} diff --git a/src/simd.c b/src/simd.c new file mode 100644 index 0000000..6a9faac --- /dev/null +++ b/src/simd.c @@ -0,0 +1,202 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +// Dirk Gregorius contributed portions of this code + +#include "simd.h" + +#if defined( B3_SIMD_SSE2 ) + +#define B3_TRANSPOSE3( C1, C2, C3 ) \ + { \ + b3V32 T1 = _mm_unpacklo_ps( ( C1 ), ( C2 ) ); \ + b3V32 T2 = _mm_unpackhi_ps( ( C1 ), ( C2 ) ); \ + ( C1 ) = _mm_shuffle_ps( ( T1 ), ( C3 ), _MM_SHUFFLE( 0, 0, 1, 0 ) ); \ + ( C2 ) = _mm_shuffle_ps( ( T1 ), ( C3 ), _MM_SHUFFLE( 1, 1, 3, 2 ) ); \ + ( C3 ) = _mm_shuffle_ps( ( T2 ), ( C3 ), _MM_SHUFFLE( 2, 2, 1, 0 ) ); \ + } + +static inline b3V32 b3SplatXV( b3V32 v ) +{ + return _mm_shuffle_ps( v, v, _MM_SHUFFLE( 0, 0, 0, 0 ) ); +} + +static inline b3V32 b3SplatYV( b3V32 v ) +{ + return _mm_shuffle_ps( v, v, _MM_SHUFFLE( 1, 1, 1, 1 ) ); +} + +static inline b3V32 b3SplatZV( b3V32 v ) +{ + return _mm_shuffle_ps( v, v, _MM_SHUFFLE( 2, 2, 2, 2 ) ); +} + +static inline bool b3AnyGreaterEq3V( b3V32 a, b3V32 b ) +{ + b3V32 v = _mm_cmpge_ps( a, b ); + return ( _mm_movemask_ps( v ) & 0x07 ) != 0; +} + +static inline b3V32 b3Dot3V( b3V32 a, b3V32 b ) +{ + b3V32 m = _mm_mul_ps( a, b ); + b3V32 x = _mm_shuffle_ps( m, m, _MM_SHUFFLE( 0, 0, 0, 0 ) ); + b3V32 y = _mm_shuffle_ps( m, m, _MM_SHUFFLE( 1, 1, 1, 1 ) ); + b3V32 z = _mm_shuffle_ps( m, m, _MM_SHUFFLE( 2, 2, 2, 2 ) ); + + return _mm_add_ps( _mm_add_ps( x, y ), z ); +} + +#else + +#define B3_TRANSPOSE3( C1, C2, C3 ) \ + { \ + float temp1 = C1.y; \ + float temp2 = C1.z; \ + float temp3 = C2.z; \ + \ + C1.y = C2.x; \ + C1.z = C3.x; \ + C2.z = C3.y; \ + \ + C2.x = temp1; \ + C3.x = temp2; \ + C3.y = temp3; \ + } + +static inline b3V32 b3SplatXV( b3V32 a ) +{ + return B3_LITERAL( b3V32 ){ a.x, a.x, a.x }; +} + +static inline b3V32 b3SplatYV( b3V32 a ) +{ + return B3_LITERAL( b3V32 ){ a.y, a.y, a.y }; +} + +static inline b3V32 b3SplatZV( b3V32 a ) +{ + return B3_LITERAL( b3V32 ){ a.z, a.z, a.z }; +} + +static inline bool b3AnyGreaterEq3V( b3V32 a, b3V32 b ) +{ + return a.x >= b.x || a.y >= b.y || a.z >= b.z; +} + +static inline b3V32 b3Dot3V( b3V32 a, b3V32 b ) +{ + float d = a.x * b.x + a.y * b.y + a.z * b.z; + return B3_LITERAL( b3V32 ){ d, d, d }; +} + +#endif + +bool b3TestBoundsTriangleOverlap( b3V32 nodeCenter, b3V32 nodeExtent, b3V32 vertex1, b3V32 vertex2, b3V32 vertex3 ) +{ + b3V32 two = b3SplatV( 2.0f ); + + // Setup triangle + vertex1 = b3SubV( vertex1, nodeCenter ); + vertex2 = b3SubV( vertex2, nodeCenter ); + vertex3 = b3SubV( vertex3, nodeCenter ); + + // Face separation + b3V32 triangleMin = b3MinV( vertex1, b3MinV( vertex2, vertex3 ) ); + b3V32 triangleMax = b3MaxV( vertex1, b3MaxV( vertex2, vertex3 ) ); + + b3V32 separation1 = b3SubV( triangleMin, nodeExtent ); + b3V32 separation2 = b3AddV( triangleMax, nodeExtent ); + + b3V32 faceSeparation = b3MaxV( separation1, b3NegV( separation2 ) ); + if ( b3AnyGreater3V( faceSeparation, b3_zeroV ) ) + { + return false; + } + + // SAT: Face separation + b3V32 edge1 = b3SubV( vertex2, vertex1 ); + b3V32 edge2 = b3SubV( vertex3, vertex2 ); + b3V32 edge3 = b3SubV( vertex1, vertex3 ); + + b3V32 normal = b3CrossV( edge1, edge2 ); + + b3V32 triangleSeparation = b3SubV( b3AbsV( b3Dot3V( normal, vertex1 ) ), b3Dot3V( b3AbsV( normal ), nodeExtent ) ); + if ( b3AnyGreater3V( triangleSeparation, b3_zeroV ) ) + { + return false; + } + + // SAT: Edge separation + b3V32 edgeSeparation1 = b3SubV( b3SubV( b3AbsV( b3CrossV( edge1, b3AddV( vertex1, vertex3 ) ) ), b3AbsV( b3CrossV( edge1, edge3 ) ) ), + b3MulV( two, b3ModifiedCrossV( b3AbsV( edge1 ), nodeExtent ) ) ); + if ( b3AnyGreater3V( edgeSeparation1, b3_zeroV ) ) + { + return false; + } + + b3V32 edgeSeparation2 = b3SubV( b3SubV( b3AbsV( b3CrossV( edge2, b3AddV( vertex1, vertex2 ) ) ), b3AbsV( b3CrossV( edge2, edge1 ) ) ), + b3MulV( two, b3ModifiedCrossV( b3AbsV( edge2 ), nodeExtent ) ) ); + if ( b3AnyGreater3V( edgeSeparation2, b3_zeroV ) ) + { + return false; + } + + b3V32 edgeSeparation3 = b3SubV( b3SubV( b3AbsV( b3CrossV( edge3, b3AddV( vertex2, vertex3 ) ) ), b3AbsV( b3CrossV( edge3, edge2 ) ) ), + b3MulV( two, b3ModifiedCrossV( b3AbsV( edge3 ), nodeExtent ) ) ); + if ( b3AnyGreater3V( edgeSeparation3, b3_zeroV ) ) + { + return false; + } + + return true; +} + +float b3IntersectRayTriangle( b3V32 rayStart, b3V32 rayDelta, b3V32 vertex1, b3V32 vertex2, b3V32 vertex3 ) +{ + // Test if ray intersects this triangle sharing same calculations for each triangle + { + b3V32 edge1 = b3SubV( vertex3, vertex2 ); + b3V32 edge2 = b3SubV( vertex1, vertex3 ); + b3V32 edge3 = b3SubV( vertex2, vertex1 ); + + b3V32 midPoint1 = b3MulV( b3_halfV, b3AddV( vertex2, vertex3 ) ); + b3V32 midPoint2 = b3MulV( b3_halfV, b3AddV( vertex3, vertex1 ) ); + b3V32 midPoint3 = b3MulV( b3_halfV, b3AddV( vertex1, vertex2 ) ); + + b3V32 normal1 = b3CrossV( edge1, b3SubV( midPoint1, rayStart ) ); + b3V32 normal2 = b3CrossV( edge2, b3SubV( midPoint2, rayStart ) ); + b3V32 normal3 = b3CrossV( edge3, b3SubV( midPoint3, rayStart ) ); + B3_TRANSPOSE3( normal1, normal2, normal3 ); + + b3V32 rayDeltaX = b3SplatXV( rayDelta ); + b3V32 rayDeltaY = b3SplatYV( rayDelta ); + b3V32 rayDeltaZ = b3SplatZV( rayDelta ); + + b3V32 volumes = b3AddV( b3AddV( b3MulV( normal1, rayDeltaX ), b3MulV( normal2, rayDeltaY ) ), b3MulV( normal3, rayDeltaZ ) ); + if ( b3AnyLess3V( volumes, b3_zeroV ) ) + { + return 1.0f; + } + } + + // Compute intersection with triangle plane + b3V32 edge1 = b3SubV( vertex2, vertex1 ); + b3V32 edge2 = b3SubV( vertex3, vertex1 ); + b3V32 normal = b3CrossV( edge1, edge2 ); + + b3V32 denominator = b3Dot3V( normal, rayDelta ); + if ( b3AnyGreaterEq3V( denominator, b3_zeroV ) ) + { + return 1.0f; + } + + b3V32 lambda = b3DivV( b3Dot3V( normal, b3SubV( vertex1, rayStart ) ), denominator ); + if ( b3AnyLessEq3V( lambda, b3_zeroV ) ) + { + return 1.0f; + } + + lambda = b3MinV( lambda, b3_oneV ); + return b3GetXV( lambda ); +} diff --git a/src/simd.h b/src/simd.h new file mode 100644 index 0000000..ec9399c --- /dev/null +++ b/src/simd.h @@ -0,0 +1,374 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "core.h" + +#include + +#if defined( B3_SIMD_SSE2 ) + +#include + +// wide float holds 4 numbers +typedef __m128 b3V32; + +typedef union b3128 +{ + b3V32 v; + float f[4]; +} b3128; + +#if defined( _MSC_VER ) && !defined( __clang__ ) + +static const b3V32 b3_zeroV = { { 0.0f, 0.0f, 0.0f, 0.0f } }; +static const b3V32 b3_halfV = { { 0.5f, 0.5f, 0.5f, 0.5f } }; +static const b3V32 b3_oneV = { { 1.0f, 1.0f, 1.0f, 1.0f } }; + +#else + +static const b3V32 b3_zeroV = { 0.0f, 0.0f, 0.0f, 0.0f }; +static const b3V32 b3_halfV = { 0.5f, 0.5f, 0.5f, 0.5f }; +static const b3V32 b3_oneV = { 1.0f, 1.0f, 1.0f, 1.0f }; + +#endif + +static inline b3V32 b3AddV( b3V32 a, b3V32 b ) +{ + return _mm_add_ps( a, b ); +} + +static inline b3V32 b3SubV( b3V32 a, b3V32 b ) +{ + return _mm_sub_ps( a, b ); +} + +static inline b3V32 b3MulV( b3V32 a, b3V32 b ) +{ + return _mm_mul_ps( a, b ); +} + +static inline b3V32 b3DivV( b3V32 a, b3V32 b ) +{ + return _mm_div_ps( a, b ); +} + +static inline b3V32 b3NegV( b3V32 a ) +{ + return _mm_sub_ps( _mm_setzero_ps(), a ); +} + +// Unaligned loads are much faster on recent hardware with little to no penalty +// Note: This may read one extra float beyond a b3Vec3 for performance. Address sanitizer +// is disabled for this function as the extra read is intentional and safe. +#if defined( __linux__ ) || defined( __APPLE__ ) || defined( __clang__ ) +__attribute__( ( no_sanitize_address ) ) +#elif defined( _MSC_VER ) +__declspec( no_sanitize_address ) +#endif +static inline b3V32 +b3LoadV( const float* src ) +{ + const __m128i masK3 = _mm_setr_epi32( 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0 ); + + // Read an extra float which gets zeroed (to avoid NaN or Inf) + b3V32 a = _mm_loadu_ps( src ); + return _mm_and_ps( a, _mm_castsi128_ps( masK3 ) ); +} + +static inline b3V32 b3ZeroV( void ) +{ + return _mm_setzero_ps(); +} + +static inline float b3GetXV( b3V32 a ) +{ + return _mm_cvtss_f32( a ); +} + +static inline float b3GetYV( b3V32 a ) +{ + return _mm_cvtss_f32( _mm_shuffle_ps( a, a, _MM_SHUFFLE( 1, 1, 1, 1 ) ) ); +} + +static inline float b3GetZV( b3V32 a ) +{ + return _mm_cvtss_f32( _mm_shuffle_ps( a, a, _MM_SHUFFLE( 2, 2, 2, 2 ) ) ); +} + +static inline float b3GetV( b3V32 a, int index ) +{ + b3128 b; + b.v = a; + return b.f[index]; +} + +static inline b3V32 b3SplatV( float x ) +{ + return _mm_set_ps1( x ); +} + +static inline b3V32 b3AbsV( b3V32 a ) +{ + // Abs( V ) = Max( -V, V ) + b3V32 zero = _mm_setzero_ps(); + return _mm_max_ps( _mm_sub_ps( zero, a ), a ); +} + +static inline b3V32 b3MinV( b3V32 a, b3V32 b ) +{ + return _mm_min_ps( a, b ); +} + +static inline b3V32 b3MaxV( b3V32 a, b3V32 b ) +{ + return _mm_max_ps( a, b ); +} + +static inline b3V32 b3CrossV( b3V32 a, b3V32 b ) +{ + b3V32 yzX1 = _mm_shuffle_ps( a, a, _MM_SHUFFLE( 3, 0, 2, 1 ) ); + b3V32 zxY1 = _mm_shuffle_ps( a, a, _MM_SHUFFLE( 3, 1, 0, 2 ) ); + b3V32 yzX2 = _mm_shuffle_ps( b, b, _MM_SHUFFLE( 3, 0, 2, 1 ) ); + b3V32 zxY2 = _mm_shuffle_ps( b, b, _MM_SHUFFLE( 3, 1, 0, 2 ) ); + + return _mm_sub_ps( _mm_mul_ps( yzX1, zxY2 ), _mm_mul_ps( zxY1, yzX2 ) ); +} + +static inline b3V32 b3ModifiedCrossV( b3V32 a, b3V32 b ) +{ + b3V32 yzX1 = _mm_shuffle_ps( a, a, _MM_SHUFFLE( 3, 0, 2, 1 ) ); + b3V32 zxY1 = _mm_shuffle_ps( a, a, _MM_SHUFFLE( 3, 1, 0, 2 ) ); + b3V32 yzX2 = _mm_shuffle_ps( b, b, _MM_SHUFFLE( 3, 0, 2, 1 ) ); + b3V32 zxY2 = _mm_shuffle_ps( b, b, _MM_SHUFFLE( 3, 1, 0, 2 ) ); + + return _mm_add_ps( _mm_mul_ps( yzX1, zxY2 ), _mm_mul_ps( zxY1, yzX2 ) ); +} + +static inline bool b3AnyLess3V( b3V32 a, b3V32 b ) +{ + b3V32 v = _mm_cmplt_ps( a, b ); + return ( _mm_movemask_ps( v ) & 0x07 ) != 0; +} + +static inline bool b3AnyLessEq3V( b3V32 a, b3V32 b ) +{ + b3V32 v = _mm_cmple_ps( a, b ); + return ( _mm_movemask_ps( v ) & 0x07 ) != 0; +} + +static inline bool b3AnyGreater3V( b3V32 a, b3V32 b ) +{ + b3V32 v = _mm_cmpgt_ps( a, b ); + return ( _mm_movemask_ps( v ) & 0x07 ) != 0; +} + +static inline bool b3AllLessEq3V( b3V32 a, b3V32 b ) +{ + b3V32 v = _mm_cmple_ps( a, b ); + return ( _mm_movemask_ps( v ) & 0x07 ) == 0x07; +} + +#else + +// I don't expect the use case of b3V32 to benefit from Neon code. +// In particular the cross product is very complex in Neon. + +// scalar math +typedef struct b3V32 +{ + float x, y, z; +} b3V32; + +typedef union b3128 +{ + b3V32 v; + float f[3]; +} b3128; + +static const b3V32 b3_zeroV = { 0.0f, 0.0f, 0.0f }; +static const b3V32 b3_halfV = { 0.5f, 0.5f, 0.5f }; +static const b3V32 b3_oneV = { 1.0f, 1.0f, 1.0f }; + +static inline b3V32 b3AddV( b3V32 a, b3V32 b ) +{ + return B3_LITERAL( b3V32 ){ + a.x + b.x, + a.y + b.y, + a.z + b.z, + }; +} + +static inline b3V32 b3SubV( b3V32 a, b3V32 b ) +{ + return B3_LITERAL( b3V32 ){ + a.x - b.x, + a.y - b.y, + a.z - b.z, + }; +} + +static inline b3V32 b3MulV( b3V32 a, b3V32 b ) +{ + return B3_LITERAL( b3V32 ){ + a.x * b.x, + a.y * b.y, + a.z * b.z, + }; +} + +static inline b3V32 b3DivV( b3V32 a, b3V32 b ) +{ + return B3_LITERAL( b3V32 ){ + a.x / b.x, + a.y / b.y, + a.z / b.z, + }; +} + +static inline b3V32 b3NegV( b3V32 a ) +{ + return B3_LITERAL( b3V32 ){ + -a.x, + -a.y, + -a.z, + }; +} + +// Unaligned loads are much faster on recent hardware with little to no penalty +static inline b3V32 b3LoadV( const float* src ) +{ + return B3_LITERAL( b3V32 ){ src[0], src[1], src[2] }; +} + +static inline b3V32 b3ZeroV( void ) +{ + return B3_LITERAL( b3V32 ){ 0.0f, 0.0f, 0.0f }; +} + +static inline float b3GetXV( b3V32 a ) +{ + return a.x; +} + +static inline float b3GetYV( b3V32 a ) +{ + return a.y; +} + +static inline float b3GetZV( b3V32 a ) +{ + return a.z; +} + +static inline float b3GetV( b3V32 a, int index ) +{ + b3128 b; + b.v = a; + return b.f[index]; +} + +static inline b3V32 b3SplatV( float x ) +{ + return B3_LITERAL( b3V32 ){ x, x, x }; +} + +static inline b3V32 b3AbsV( b3V32 a ) +{ + return B3_LITERAL( b3V32 ){ + a.x < 0.0f ? -a.x : a.x, + a.y < 0.0f ? -a.y : a.y, + a.z < 0.0f ? -a.z : a.z, + }; +} + +static inline b3V32 b3MinV( b3V32 a, b3V32 b ) +{ + return B3_LITERAL( b3V32 ){ + a.x < b.x ? a.x : b.x, + a.y < b.y ? a.y : b.y, + a.z < b.z ? a.z : b.z, + }; +} + +static inline b3V32 b3MaxV( b3V32 a, b3V32 b ) +{ + return B3_LITERAL( b3V32 ){ + a.x > b.x ? a.x : b.x, + a.y > b.y ? a.y : b.y, + a.z > b.z ? a.z : b.z, + }; +} + +static inline b3V32 b3CrossV( b3V32 a, b3V32 b ) +{ + b3V32 c; + c.x = a.y * b.z - a.z * b.y; + c.y = a.z * b.x - a.x * b.z; + c.z = a.x * b.y - a.y * b.x; + return c; +} + +static inline b3V32 b3ModifiedCrossV( b3V32 a, b3V32 b ) +{ + b3V32 c; + c.x = a.y * b.z + a.z * b.y; + c.y = a.z * b.x + a.x * b.z; + c.z = a.x * b.y + a.y * b.x; + return c; +} + +static inline bool b3AnyLess3V( b3V32 a, b3V32 b ) +{ + return a.x < b.x || a.y < b.y || a.z < b.z; +} + +static inline bool b3AnyLessEq3V( b3V32 a, b3V32 b ) +{ + return a.x <= b.x || a.y <= b.y || a.z <= b.z; +} + +static inline bool b3AnyGreater3V( b3V32 a, b3V32 b ) +{ + return a.x > b.x || a.y > b.y || a.z > b.z; +} + +static inline bool b3AllLessEq3V( b3V32 a, b3V32 b ) +{ + return a.x <= b.x && a.y <= b.y && a.z <= b.z; +} + +#endif + +static inline bool b3TestBoundsOverlap( b3V32 nodeMin1, b3V32 nodeMax1, b3V32 nodeMin2, b3V32 nodeMax2 ) +{ + b3V32 separation = b3MaxV( b3SubV( nodeMin2, nodeMax1 ), b3SubV( nodeMin1, nodeMax2 ) ); + return b3AllLessEq3V( separation, b3_zeroV ); +} + +// Test a ray for edge separation with an AABB (Gino, p80). +static inline bool b3TestBoundsRayOverlap( b3V32 nodeMin, b3V32 nodeMax, b3V32 rayStart, b3V32 rayDelta ) +{ + // Setup node + b3V32 nodeCenter = b3MulV( b3_halfV, b3AddV( nodeMin, nodeMax ) ); + b3V32 nodeExtent = b3SubV( nodeMax, nodeCenter ); + + // Setup ray + rayStart = b3SubV( rayStart, nodeCenter ); + + // SAT: Edge separation + b3V32 edgeSeparation = b3SubV( b3AbsV( b3CrossV( rayDelta, rayStart ) ), b3ModifiedCrossV( b3AbsV( rayDelta ), nodeExtent ) ); + return b3AllLessEq3V( edgeSeparation, b3_zeroV ); +} + +#ifdef __cplusplus +extern "C" { +#endif + +bool b3TestBoundsTriangleOverlap( b3V32 nodeCenter, b3V32 nodeExtent, b3V32 vertex1, b3V32 vertex2, b3V32 vertex3 ); +float b3IntersectRayTriangle( b3V32 rayStart, b3V32 rayDelta, b3V32 vertex1, b3V32 vertex2, b3V32 vertex3 ); + +#ifdef __cplusplus +} +#endif diff --git a/src/solver.c b/src/solver.c new file mode 100644 index 0000000..2edddf3 --- /dev/null +++ b/src/solver.c @@ -0,0 +1,2292 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "solver.h" + +#include "arena_allocator.h" +#include "bitset.h" +#include "body.h" +#include "compound.h" +#include "contact.h" +#include "contact_solver.h" +#include "core.h" +#include "ctz.h" +#include "island.h" +#include "joint.h" +#include "parallel_for.h" +#include "physics_world.h" +#include "platform.h" +#include "sensor.h" +#include "shape.h" +#include "solver_set.h" + +#include +#include +#include + +// these are useful for solver testing +#define ITERATIONS 1 +#define RELAX_ITERATIONS 1 + +#if ( defined( __GNUC__ ) || defined( __clang__ ) ) && ( defined( __i386__ ) || defined( __x86_64__ ) ) +static void b3Pause( void ) +{ + __asm__ __volatile__( "pause\n" ); +} +#elif ( defined( __arm__ ) && defined( __ARM_ARCH ) && __ARM_ARCH >= 7 ) || defined( __aarch64__ ) +static void b3Pause( void ) +{ + __asm__ __volatile__( "yield" ::: "memory" ); +} +#elif defined( _MSC_VER ) && ( defined( _M_IX86 ) || defined( _M_X64 ) ) +static void b3Pause( void ) +{ + _mm_pause(); +} +#elif defined( _MSC_VER ) && ( defined( _M_ARM ) || defined( _M_ARM64 ) ) +static void b3Pause( void ) +{ + __yield(); +} +#else +static void b3Pause( void ) +{ +} +#endif + +typedef struct b3WorkerContext +{ + b3StepContext* context; + int workerIndex; + void* userTask; +} b3WorkerContext; + +// Integrate velocities, apply damping, and gyroscopic torque +static void b3IntegrateVelocitiesTask( b3SolverBlock block, b3StepContext* context ) +{ + b3TracyCZoneNC( integrate_velocity, "IntVel", b3_colorDeepPink, true ); + + B3_VALIDATE( block.startIndex + block.count <= context->world->solverSets.data[b3_awakeSet].bodyStates.count ); + + b3BodyState* states = context->states; + b3BodySim* sims = context->sims; + + b3Vec3 gravity = context->world->gravity; + float h = context->h; + + for ( int i = block.startIndex; i < block.startIndex + block.count; ++i ) + { + b3BodySim* sim = sims + i; + b3BodyState* state = states + i; + + b3Vec3 v = state->linearVelocity; + b3Vec3 w = state->angularVelocity; + + // Damping math + // 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; + + b3Vec3 linearVelocityDelta = b3Blend2( h * sim->invMass, sim->force, h * gravityScale, gravity ); + v = b3MulAdd( linearVelocityDelta, linearDamping, v ); + + b3Vec3 angularVelocityDelta = b3MulSV( h, b3MulMV( sim->invInertiaWorld, sim->torque ) ); + w = b3MulAdd( angularVelocityDelta, angularDamping, w ); + + // Gyroscopic torque by solving this nonlinear equation using Newton-Raphson. + // I * (w2 - w1) + h * cross(w2, I * w2) = 0 + // This is all done in local coordinates where the Jacobian is easier to compute. + // This improves the simulation of long skinny bodies. + { + // Get current rotation. + b3Quat q0 = sim->transform.q; + b3Quat q = b3MulQuat( state->deltaRotation, q0 ); + + // todo wasteful computation + b3Matrix3 inertiaLocal = b3InvertMatrix( sim->invInertiaLocal ); + + // Compute local angular velocity + b3Vec3 omega1 = b3InvRotateVector( q, w ); + b3Vec3 omega2 = omega1; + + // Symmetric inertia tensor: 6 unique entries (column-major) + const float i00 = inertiaLocal.cx.x; + const float i01 = inertiaLocal.cy.x; + const float i02 = inertiaLocal.cz.x; + const float i11 = inertiaLocal.cy.y; + const float i12 = inertiaLocal.cz.y; + const float i22 = inertiaLocal.cz.z; + + for ( int gyroIteration = 0; gyroIteration < 1; ++gyroIteration ) + { + const float w1 = omega2.x; + const float w2 = omega2.y; + const float w3 = omega2.z; + + // Iw = I * omega2 (shared between residual and Jacobian) + const float Iw1 = i00 * w1 + i01 * w2 + i02 * w3; + const float Iw2 = i01 * w1 + i11 * w2 + i12 * w3; + const float Iw3 = i02 * w1 + i12 * w2 + i22 * w3; + + // Residual: b = I*(omega2 - omega1) + h * (omega2 × I*omega2) + const b3Vec3 dw = b3Sub( omega2, omega1 ); + b3Vec3 b = { + i00 * dw.x + i01 * dw.y + i02 * dw.z + h * ( w2 * Iw3 - w3 * Iw2 ), + i01 * dw.x + i11 * dw.y + i12 * dw.z + h * ( w3 * Iw1 - w1 * Iw3 ), + i02 * dw.x + i12 * dw.y + i22 * dw.z + h * ( w1 * Iw2 - w2 * Iw1 ), + }; + + // Jacobian J = I + h * (skew(omega2) * I - skew(I*omega2)) + // Jacobian derived by Erin Catto, Ph.D. Do not attempt to do this without a Ph.D. + // Doubled inertia terms above fold into Iw, e.g. row 2 col 1: i00*w3 - i02*w1 - Iw3. + b3Matrix3 J = { + { i00 + h * ( w2 * i02 - w3 * i01 ), + i01 + h * ( w3 * i00 - w1 * i02 - Iw3 ), + i02 + h * ( w1 * i01 - w2 * i00 + Iw2 ) }, + { i01 + h * ( w2 * i12 - w3 * i11 + Iw3 ), + i11 + h * ( w3 * i01 - w1 * i12 ), + i12 + h * ( w1 * i11 - w2 * i01 - Iw1 ) }, + { i02 + h * ( w2 * i22 - w3 * i12 - Iw2 ), + i12 + h * ( w3 * i02 - w1 * i22 + Iw1 ), + i22 + h * ( w1 * i12 - w2 * i02 ) }, + }; + + omega2 = b3Sub( omega2, b3Solve3( J, b ) ); + } + + w = b3RotateVector( q, omega2 ); + } + + state->linearVelocity = v; + state->angularVelocity = w; + } + + b3TracyCZoneEnd( integrate_velocity ); +} + +static void b3IntegratePositionsTask( b3SolverBlock block, b3StepContext* context ) +{ + b3TracyCZoneNC( integrate_positions, "IntPos", b3_colorDarkSeaGreen, true ); + + B3_VALIDATE( block.startIndex + block.count <= context->world->solverSets.data[b3_awakeSet].bodyStates.count ); + + b3BodyState* states = context->states; + float h = context->h; + float maxLinearSpeed = context->maxLinearVelocity; + float maxAngularSpeed = B3_MAX_ROTATION * context->inv_dt; + float maxLinearSpeedSquared = maxLinearSpeed * maxLinearSpeed; + float maxAngularSpeedSquared = maxAngularSpeed * maxAngularSpeed; + + for ( int i = block.startIndex; i < block.startIndex + block.count; ++i ) + { + b3BodyState* state = states + i; + + b3Vec3 v = state->linearVelocity; + b3Vec3 w = state->angularVelocity; + + // Motion locks - these can be viewed as a constraint that come last + v.x = ( state->flags & b3_lockLinearX ) ? 0.0f : v.x; + v.y = ( state->flags & b3_lockLinearY ) ? 0.0f : v.y; + v.z = ( state->flags & b3_lockLinearZ ) ? 0.0f : v.z; + w.x = ( state->flags & b3_lockAngularX ) ? 0.0f : w.x; + w.y = ( state->flags & b3_lockAngularY ) ? 0.0f : w.y; + w.z = ( state->flags & b3_lockAngularZ ) ? 0.0f : w.z; + + // Clamp to max linear speed + if ( b3Dot( v, v ) > maxLinearSpeedSquared ) + { + float ratio = maxLinearSpeed / b3Length( v ); + v = b3MulSV( ratio, v ); + state->flags |= b3_isSpeedCapped; + } + + // Clamp to max angular speed + if ( b3Dot( w, w ) > maxAngularSpeedSquared && ( state->flags & b3_allowFastRotation ) == 0 ) + { + float ratio = maxAngularSpeed / b3Length( w ); + w = b3MulSV( ratio, w ); + state->flags |= b3_isSpeedCapped; + } + + state->linearVelocity = v; + state->angularVelocity = w; + state->deltaPosition = b3MulAdd( state->deltaPosition, h, v ); + state->deltaRotation = b3IntegrateRotation( state->deltaRotation, b3MulSV( h, w ) ); + } + + b3TracyCZoneEnd( integrate_positions ); +} + +static void b3PrepareJointsTask( b3SolverBlock block, b3StepContext* context ) +{ + b3TracyCZoneNC( prepare_joints, "PrepJoints", b3_colorOldLace, true ); + + b3JointPrepareSpan* spans = context->jointPrepareSpans; + + int index = block.startIndex; + int endIndex = block.startIndex + block.count; + + // Find color for start index. Linear search but fast. + int colorIndex = 0; + while ( spans[colorIndex + 1].start <= index ) + { + colorIndex += 1; + } + + // Loop over block + while ( index < endIndex ) + { + int colorStart = spans[colorIndex].start; + int colorEndIndex = b3MinInt( spans[colorIndex + 1].start, endIndex ); + b3JointSim* joints = spans[colorIndex].joints; + + // Loop over color + for ( ; index < colorEndIndex; ++index ) + { + B3_ASSERT( 0 <= index - colorStart && index - colorStart < spans[colorIndex].count ); + b3JointSim* joint = joints + ( index - colorStart ); + b3PrepareJoint( joint, context ); + } + + // Advance to next color + colorIndex += 1; + } + + b3TracyCZoneEnd( prepare_joints ); +} + +static void b3WarmStartJointsTask( b3SolverBlock block, b3StepContext* context ) +{ + b3TracyCZoneNC( warm_joints, "WarmJoints", b3_colorGold, true ); + + b3GraphColor* color = context->graph->colors + block.colorIndex; + b3JointSim* joints = color->jointSims.data; + + for ( int i = block.startIndex; i < block.startIndex + block.count; ++i ) + { + b3JointSim* joint = joints + i; + b3WarmStartJoint( joint, context ); + } + + b3TracyCZoneEnd( warm_joints ); +} + +static void b3SolveJointsTask( b3SolverBlock block, b3StepContext* context, bool useBias, int workerIndex ) +{ + b3TracyCZoneNC( solve_joints, "SolveJoints", b3_colorLemonChiffon, true ); + + b3GraphColor* color = context->graph->colors + block.colorIndex; + b3JointSim* joints = color->jointSims.data; + + B3_ASSERT( 0 <= block.startIndex && block.startIndex + block.count <= color->jointSims.count ); + + b3BitSet* jointStateBitSet = &context->world->taskContexts.data[workerIndex].jointStateBitSet; + + for ( int i = block.startIndex; i < block.startIndex + block.count; ++i ) + { + b3JointSim* joint = joints + i; + b3SolveJoint( joint, context, useBias ); + + if ( useBias && ( joint->forceThreshold < FLT_MAX || joint->torqueThreshold < FLT_MAX ) && + b3GetBit( jointStateBitSet, joint->jointId ) == false ) + { + float force, torque; + b3GetJointReaction( context->world, 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. + b3SetBit( jointStateBitSet, joint->jointId ); + } + } + } + + b3TracyCZoneEnd( solve_joints ); +} + +#define B2_MAX_CONTINUOUS_SENSOR_HITS 8 + +typedef struct b3ContinuousContext +{ + b3World* world; + b3BodySim* fastBodySim; + b3Shape* fastShape; + b3Vec3 centroid1, centroid2; + b3Sweep sweep; + float fraction; + b3SensorHit sensorHits[B2_MAX_CONTINUOUS_SENSOR_HITS]; + float sensorFractions[B2_MAX_CONTINUOUS_SENSOR_HITS]; + int sensorCount; +} b3ContinuousContext; + +// This is called from b3DynamicTree_Query for continuous collision +static bool b3ContinuousQueryCallback( int proxyId, uint64_t userData, void* context ) +{ + B3_UNUSED( proxyId ); + + int shapeId = (int)userData; + b3ContinuousContext* continuousContext = (b3ContinuousContext*)context; + b3Shape* fastShape = continuousContext->fastShape; + b3BodySim* fastBodySim = continuousContext->fastBodySim; + + B3_ASSERT( fastShape->sensorIndex == B3_NULL_INDEX ); + + // Skip same shape + if ( shapeId == fastShape->id ) + { + return true; + } + + b3World* world = continuousContext->world; + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + + // Skip same body + if ( shape->bodyId == fastShape->bodyId ) + { + return true; + } + + // Skip sensors unless the shapes want sensor events + bool isSensor = shape->sensorIndex != B3_NULL_INDEX; + if ( isSensor && ( shape->enableSensorEvents == false || fastShape->enableSensorEvents == false ) ) + { + return true; + } + + // Skip filtered shapes + bool canCollide = b3ShouldShapesCollide( fastShape->filter, shape->filter ); + if ( canCollide == false ) + { + return true; + } + + b3Body* body = b3Array_Get( world->bodies, shape->bodyId ); + + b3BodySim* bodySim = b3GetBodySim( world, body ); + B3_ASSERT( body->type == b3_staticBody || ( fastBodySim->flags & b3_isBullet ) ); + + // Skip bullets + if ( bodySim->flags & b3_isBullet ) + { + return true; + } + + // Skip filtered bodies + b3Body* fastBody = b3Array_Get( world->bodies, fastBodySim->bodyId ); + canCollide = b3ShouldBodiesCollide( world, fastBody, body ); + if ( canCollide == false ) + { + return true; + } + + // Custom user filtering + if ( shape->enableCustomFiltering || fastShape->enableCustomFiltering ) + { + b3CustomFilterFcn* customFilterFcn = world->customFilterFcn; + if ( customFilterFcn != NULL ) + { + b3ShapeId idA = { shape->id + 1, world->worldId, shape->generation }; + b3ShapeId idB = { fastShape->id + 1, world->worldId, fastShape->generation }; + canCollide = customFilterFcn( idA, idB, world->customFilterContext ); + if ( canCollide == false ) + { + return true; + } + } + } + + // todo does having a sweep on shapeA help with bullets? + b3Sweep sweepA = b3MakeSweep( bodySim ); + + // Time of impact versus shape. Supports all shape types + b3TOIOutput output = b3ShapeTimeOfImpact( shape, fastShape, &sweepA, &continuousContext->sweep, continuousContext->fraction ); + 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 + b3SensorHit sensorHit = { + .sensorId = shape->id, + .visitorId = fastShape->id, + }; + + continuousContext->sensorHits[index] = sensorHit; + continuousContext->sensorFractions[index] = output.fraction; + continuousContext->sensorCount += 1; + } + } + else if ( 0.0f < output.fraction && output.fraction < continuousContext->fraction ) + { + bool didHit = true; + + if ( didHit && ( shape->enablePreSolveEvents || fastShape->enablePreSolveEvents ) ) + { + b3ShapeId shapeIdA = { shape->id + 1, world->worldId, shape->generation }; + b3ShapeId shapeIdB = { fastShape->id + 1, world->worldId, fastShape->generation }; + didHit = world->preSolveFcn( shapeIdA, shapeIdB, output.point, output.normal, world->preSolveContext ); + } + + if ( didHit ) + { + fastBodySim->flags |= b3_hadTimeOfImpact; + continuousContext->fraction = output.fraction; + + // if (output.usedFallback == true) + //{ + // // help out the solver + // b3BodyState* state = b3GetBodyState( world, fastBody ); + // B3_ASSERT( state != NULL ); + // state->angularVelocity = b3Vec3_zero; + // } + } + } + + // Continue query + return true; +} + +// Continuous collision of dynamic versus static +static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext* taskContext ) +{ + b3TracyCZoneNC( ccd, "CCD", b3_colorDarkGoldenRod, true ); + + b3SolverSet* awakeSet = b3Array_Get( world->solverSets, b3_awakeSet ); + b3BodySim* fastBodySim = b3Array_Get( awakeSet->bodySims, bodySimIndex ); + B3_ASSERT( fastBodySim->flags & b3_isFast ); + + b3Sweep sweep = b3MakeSweep( fastBodySim ); + + b3Transform xf1; + xf1.q = sweep.q1; + xf1.p = b3Sub( sweep.c1, b3RotateVector( sweep.q1, sweep.localCenter ) ); + + b3Transform xf2; + xf2.q = sweep.q2; + xf2.p = b3Sub( sweep.c2, b3RotateVector( sweep.q2, sweep.localCenter ) ); + + b3DynamicTree* staticTree = world->broadPhase.trees + b3_staticBody; + b3DynamicTree* kinematicTree = world->broadPhase.trees + b3_kinematicBody; + b3DynamicTree* dynamicTree = world->broadPhase.trees + b3_dynamicBody; + b3Body* fastBody = b3Array_Get( world->bodies, fastBodySim->bodyId ); + + b3ContinuousContext context = { 0 }; + context.world = world; + context.sweep = sweep; + context.fastBodySim = fastBodySim; + context.fraction = 1.0f; + + bool isBullet = ( fastBodySim->flags & b3_isBullet ) != 0; + + int shapeId = fastBody->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* fastShape = b3Array_Get( world->shapes, shapeId ); + shapeId = fastShape->nextShapeId; + + context.fastShape = fastShape; + context.centroid1 = b3TransformPoint( xf1, fastShape->localCentroid ); + context.centroid2 = b3TransformPoint( xf2, fastShape->localCentroid ); + + b3AABB box1 = fastShape->aabb; + b3AABB box2 = b3ComputeShapeAABB( fastShape, xf2 ); + + // Store this to avoid double computation in the case there is no impact event + fastShape->aabb = box2; + + // No continuous collision for meshes + if ( fastShape->type == b3_meshShape || fastShape->type == b3_heightShape ) + { + continue; + } + + // No continuous collision for sensors + if ( fastShape->sensorIndex != B3_NULL_INDEX ) + { + continue; + } + + b3AABB sweptBox = b3AABB_Union( box1, box2 ); + b3DynamicTree_Query( staticTree, sweptBox, B3_DEFAULT_MASK_BITS, false, b3ContinuousQueryCallback, &context ); + + if ( isBullet ) + { + b3DynamicTree_Query( kinematicTree, sweptBox, B3_DEFAULT_MASK_BITS, false, b3ContinuousQueryCallback, &context ); + b3DynamicTree_Query( dynamicTree, sweptBox, B3_DEFAULT_MASK_BITS, false, b3ContinuousQueryCallback, &context ); + } + } + + const float speculativeScalar = B3_SPECULATIVE_DISTANCE; + const b3Vec3 speculativeMargin = { speculativeScalar, speculativeScalar, speculativeScalar }; + + // todo implement per shape margin as in Box2D + const float marginScalar = B3_AABB_MARGIN; + const b3Vec3 aabbMargin = { marginScalar, marginScalar, marginScalar }; + + if ( context.fraction < 1.0f ) + { + // Handle time of impact event + b3Quat q = b3NLerp( sweep.q1, sweep.q2, context.fraction ); + b3Vec3 c = b3Lerp( sweep.c1, sweep.c2, context.fraction ); + b3Vec3 origin = b3Sub( c, b3RotateVector( q, sweep.localCenter ) ); + + // Advance body + b3Transform transform = { origin, q }; + fastBodySim->transform = transform; + fastBodySim->center = c; + fastBodySim->rotation0 = q; + fastBodySim->center0 = c; + + // 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 != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + + // Must recompute aabb at the interpolated transform + b3AABB aabb = b3ComputeShapeAABB( shape, transform ); + aabb.lowerBound = b3Sub( aabb.lowerBound, speculativeMargin ); + aabb.upperBound = b3Add( aabb.upperBound, speculativeMargin ); + shape->aabb = aabb; + + if ( b3AABB_Contains( shape->fatAABB, aabb ) == false ) + { + shape->fatAABB = (b3AABB){ b3Sub( aabb.lowerBound, aabbMargin ), b3Add( aabb.upperBound, aabbMargin ) }; + + shape->enlargedAABB = true; + fastBodySim->flags |= b3_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 != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + + // shape->aabb is still valid from above + + if ( b3AABB_Contains( shape->fatAABB, shape->aabb ) == false ) + { + shape->fatAABB = (b3AABB){ + .lowerBound = b3Sub( shape->aabb.lowerBound, aabbMargin ), + .upperBound = b3Add( shape->aabb.upperBound, aabbMargin ), + }; + + if ( b3IsSaneAABB( shape->fatAABB ) == false ) + { + b3Vec3 c = fastBodySim->center; + b3Log( "body %s out of bounds at %g %g %g", fastBody->name, c.x, c.y, c.z ); + } + + shape->enlargedAABB = true; + fastBodySim->flags |= b3_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 ) + { + b3Array_Push( taskContext->sensorHits, context.sensorHits[i] ); + } + } + + b3TracyCZoneEnd( ccd ); +} + +// Implements b3ParallelForCallback +static void b3FinalizeBodiesTask( int startIndex, int endIndex, int workerIndex, void* context ) +{ + b3TracyCZoneNC( finalize_bodies, "Finalize", b3_colorMediumSeaGreen, true ); + + b3StepContext* stepContext = (b3StepContext*)context; + b3World* world = stepContext->world; + b3Body* bodies = world->bodies.data; + b3BodySim* sims = stepContext->sims; + b3BodyState* states = stepContext->states; + + B3_ASSERT( endIndex <= world->bodyMoveEvents.count ); + + bool enableSleep = world->enableSleep; + bool enableContinuous = world->enableContinuous; + float timeStep = stepContext->dt; + float invTimeStep = stepContext->inv_dt; + uint16_t worldId = world->worldId; + + // The body move event array has should already have the correct size + b3BodyMoveEvent* moveEvents = world->bodyMoveEvents.data; + + b3TaskContext* taskContext = world->taskContexts.data + workerIndex; + b3BitSet* enlargedSimBitSet = &taskContext->enlargedSimBitSet; + b3BitSet* awakeIslandBitSet = &taskContext->awakeIslandBitSet; + + const float speculativeScalar = B3_SPECULATIVE_DISTANCE; + const b3Vec3 speculativeMargin = { speculativeScalar, speculativeScalar, speculativeScalar }; + + // todo per shape margin + const float marginScalar = B3_AABB_MARGIN; + const b3Vec3 aabbMargin = { marginScalar, marginScalar, marginScalar }; + + for ( int simIndex = startIndex; simIndex < endIndex; ++simIndex ) + { + b3BodyState* state = states + simIndex; + b3BodySim* sim = sims + simIndex; + + b3Vec3 v = state->linearVelocity; + b3Vec3 w = state->angularVelocity; + b3Vec3 localOmega = b3InvRotateVector( sim->transform.q, w ); + b3Vec3 localDeltaRotation = b3InvRotateVector( sim->transform.q, state->deltaRotation.v ); + + if ( b3IsValidVec3( v ) == false || b3IsValidVec3( w ) == false ) + { + b3Log( "unstable: %s", bodies[sim->bodyId].name ); + } + + B3_ASSERT( b3IsValidVec3( v ) ); + B3_ASSERT( b3IsValidVec3( w ) ); + + sim->center = b3Add( sim->center, state->deltaPosition ); + sim->transform.q = b3NormalizeQuat( b3MulQuat( state->deltaRotation, sim->transform.q ) ); + + // Use the velocity of the farthest point on the body to account for rotation. + b3Vec3 velocityArc = b3ModifiedCross( b3Abs( localOmega ), sim->maxExtent ); + float maxVelocity = b3Length( v ) + b3Length( velocityArc ); + + // Sleep needs to observe position correction as well as true velocity. + // q = [sin(theta/2) * v, cos(theta/2)] + // for small angles abs(theta) ~= 2 * length(sin(theta/2) * v) + b3Vec3 rotationArc = b3ModifiedCross( b3Abs( localDeltaRotation ), sim->maxExtent ); + float maxDeltaPosition = b3Length( state->deltaPosition ) + 2.0f * b3Length(rotationArc); + + // Position correction is not as important for sleep as true velocity. + float positionSleepFactor = 0.5f; + float sleepVelocity = b3MaxFloat( maxVelocity, positionSleepFactor * invTimeStep * maxDeltaPosition ); + + // reset state deltas + state->deltaPosition = b3Vec3_zero; + state->deltaRotation = b3Quat_identity; + + sim->transform.p = b3Sub( sim->center, b3RotateVector( sim->transform.q, sim->localCenter ) ); + + // cache miss here, however I need the shape list below + b3Body* body = bodies + sim->bodyId; + body->bodyMoveIndex = simIndex; + moveEvents[simIndex].userData = body->userData; + moveEvents[simIndex].transform = sim->transform; + moveEvents[simIndex].bodyId = (b3BodyId){ sim->bodyId + 1, worldId, body->generation }; + moveEvents[simIndex].fellAsleep = false; + + // reset applied force and torque + sim->force = b3Vec3_zero; + sim->torque = b3Vec3_zero; + + body->flags &= ~( b3_isFast | b3_isSpeedCapped | b3_hadTimeOfImpact ); + body->flags |= ( sim->flags & ( b3_isSpeedCapped | b3_hadTimeOfImpact ) ); + body->flags |= ( state->flags & ( b3_isSpeedCapped | b3_hadTimeOfImpact ) ); + sim->flags &= ~( b3_isFast | b3_isSpeedCapped | b3_hadTimeOfImpact ); + state->flags &= ~( b3_isFast | b3_isSpeedCapped | b3_hadTimeOfImpact ); + + if ( enableSleep == false || body->enableSleep == false || sleepVelocity > body->sleepThreshold ) + { + // Body is not sleepy + body->sleepTime = 0.0f; + + const float safetyFactor = 0.5f; + float maxMotion = b3MaxFloat( maxDeltaPosition, maxVelocity * timeStep ); + if ( body->type == b3_dynamicBody && enableContinuous && maxMotion > safetyFactor * sim->minExtent ) + { + // This flag is only retained for debug draw + sim->flags |= b3_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 & b3_isBullet ) + { + int bulletIndex = b3AtomicFetchAddInt( &stepContext->bulletBodyCount, 1 ); + stepContext->bulletBodies[bulletIndex] = simIndex; + } + else + { + b3SolveContinuous( 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; + } + + // Update world space inverse inertia tensor. + b3Matrix3 rotationMatrix = b3MakeMatrixFromQuat( sim->transform.q ); + sim->invInertiaWorld = b3MulMM( b3MulMM( rotationMatrix, sim->invInertiaLocal ), b3Transpose( rotationMatrix ) ); + + // Any single body in an island can keep it awake + b3Island* island = b3Array_Get( world->islands, body->islandId ); + if ( body->sleepTime < B3_TIME_TO_SLEEP ) + { + // keep island awake + int islandIndex = island->localIndex; + b3SetBit( 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 + b3Transform transform = sim->transform; + bool isFast = ( sim->flags & b3_isFast ) != 0; + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* shape = b3Array_Get( world->shapes, shapeId ); + + if ( isFast ) + { + // For fast non-bullet bodies the AABB has already been updated in b3SolveContinuous + // 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 + b3SetBit( enlargedSimBitSet, simIndex ); + } + else + { + b3AABB aabb = b3ComputeShapeAABB( shape, transform ); + aabb.lowerBound = b3Sub( aabb.lowerBound, speculativeMargin ); + aabb.upperBound = b3Add( aabb.upperBound, speculativeMargin ); + shape->aabb = aabb; + + B3_ASSERT( shape->enlargedAABB == false ); + + if ( b3AABB_Contains( shape->fatAABB, aabb ) == false ) + { + shape->fatAABB = (b3AABB){ b3Sub( aabb.lowerBound, aabbMargin ), b3Add( aabb.upperBound, aabbMargin ) }; + shape->enlargedAABB = true; + + // Bit-set to keep the move array sorted + b3SetBit( enlargedSimBitSet, simIndex ); + } + } + + shapeId = shape->nextShapeId; + } + } + + b3TracyCZoneEnd( finalize_bodies ); +} + +typedef struct b3BlockDim +{ + // number of items per block (except last block) + int size; + + // total number of blocks + int count; +} b3BlockDim; + +// 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. +static inline b3BlockDim b3ComputeBlockCount( int itemCount, int minSize, int maxBlockCount ) +{ + b3BlockDim dim = { 0 }; + if ( itemCount == 0 ) + { + return dim; + } + + if ( itemCount <= minSize * maxBlockCount ) + { + dim.size = minSize; + } + else + { + dim.size = ( itemCount + maxBlockCount - 1 ) / maxBlockCount; + } + + dim.count = ( itemCount + dim.size - 1 ) / dim.size; + + B3_ASSERT( dim.count >= 1 ); + B3_ASSERT( dim.size * dim.count >= itemCount ); + + return dim; +} + +// Initialize solver blocks for a contiguous range of items. Computes block size internally +// from the same parameters used by b3ComputeBlockCount. The atomic claim counter is zeroed +// so workers can CAS (0, 1) on the first stage that owns these blocks. +static void b3InitBlocks( b3SyncBlock* blocks, b3BlockDim dim, int itemCount, uint8_t blockType, uint8_t colorIndex ) +{ + if ( dim.count == 0 ) + { + return; + } + + B3_ASSERT( itemCount >= dim.count ); + + // Compute the number of elements per block + int blockSize = dim.size; + + // Simulation too big + B3_ASSERT( blockSize <= UINT16_MAX ); + + for ( int i = 0; i < dim.count; ++i ) + { + blocks[i].block.startIndex = i * blockSize; + blocks[i].block.count = (uint16_t)blockSize; + blocks[i].block.blockType = blockType; + blocks[i].block.colorIndex = colorIndex; + b3AtomicStoreInt( &blocks[i].syncIndex, 0 ); + } + + // The last block may not be full + blocks[dim.count - 1].block.count = (uint16_t)( itemCount - ( dim.count - 1 ) * blockSize ); + + B3_VALIDATE( blocks[dim.count - 1].block.count <= blockSize ); + B3_VALIDATE( ( dim.count - 1 ) * dim.size + blocks[dim.count - 1].block.count == itemCount ); +} + +static inline b3SolverStage* b3InitStage( b3SolverStage* stage, b3SolverStageType type, b3SyncBlock* blocks, int blockCount, + uint8_t colorIndex ) +{ + stage->type = type; + stage->blocks = blocks; + stage->blockCount = blockCount; + stage->colorIndex = colorIndex; + b3AtomicStoreInt( &stage->completionCount, 0 ); + return stage + 1; +} + +// Initialize one stage per color for each iteration. Used for warm start, solve, relax, and restitution. +// All iterations of a given color share the same b3SyncBlock array so the per-block syncIndex +// grows monotonically across stages within that color. +static b3SolverStage* b3InitColorStages( b3SolverStage* stage, b3SolverStageType type, int iterations, int activeColorCount, + b3SyncBlock** colorBlocks, int* colorBlockCounts, int* activeColorIndices ) +{ + for ( int j = 0; j < iterations; ++j ) + { + for ( int i = 0; i < activeColorCount; ++i ) + { + stage = b3InitStage( stage, type, colorBlocks[i], colorBlockCounts[i], (uint8_t)activeColorIndices[i] ); + } + } + return stage; +} + +static void b3ExecuteBlock( b3SolverStage* stage, b3StepContext* context, b3SolverBlock block, int workerIndex ) +{ + b3SolverStageType stageType = stage->type; + b3SolverBlockType blockType = (b3SolverBlockType)block.blockType; + + switch ( stageType ) + { + case b3_stagePrepareJoints: + b3PrepareJointsTask( block, context ); + break; + + case b3_stagePrepareWideContacts: + b3PrepareContacts_Convex( block, context ); + break; + + case b3_stagePrepareContacts: + b3PrepareContacts_Mesh( block, context ); + break; + + case b3_stageIntegrateVelocities: + b3IntegrateVelocitiesTask( block, context ); + break; + + case b3_stageWarmStart: + if ( blockType == b3_graphJointBlock ) + { + b3WarmStartJointsTask( block, context ); + } + else if ( blockType == b3_graphWideContactBlock ) + { + b3WarmStartContacts_Convex( block, context ); + } + else + { + b3WarmStartContacts_Mesh( block, context ); + } + break; + + case b3_stageSolve: + if ( blockType == b3_graphJointBlock ) + { + bool useBias = true; + b3SolveJointsTask( block, context, useBias, workerIndex ); + } + else if ( blockType == b3_graphWideContactBlock ) + { + bool useBias = true; + b3SolveContacts_Convex( block, context, useBias ); + } + else + { + bool useBias = true; + b3SolveContacts_Mesh( block, context, useBias ); + } + break; + + case b3_stageIntegratePositions: + b3IntegratePositionsTask( block, context ); + break; + + case b3_stageRelax: + if ( blockType == b3_graphJointBlock ) + { + bool useBias = false; + b3SolveJointsTask( block, context, useBias, workerIndex ); + } + else if ( blockType == b3_graphWideContactBlock ) + { + bool useBias = false; + b3SolveContacts_Convex( block, context, useBias ); + } + else + { + bool useBias = false; + b3SolveContacts_Mesh( block, context, useBias ); + } + break; + + case b3_stageRestitution: + if ( blockType == b3_graphWideContactBlock ) + { + b3ApplyRestitution_Convex( block, context ); + } + else if ( blockType == b3_graphContactBlock ) + { + b3ApplyRestitution_Mesh( block, context ); + } + break; + + case b3_stageStoreWideImpulses: + b3StoreImpulses_Convex( block, context, workerIndex ); + break; + + case b3_stageStoreImpulses: + b3StoreImpulses_Mesh( block, context, workerIndex ); + break; + } +} + +// This staggers the worker start indices so they avoid touching the same solver blocks +static inline int GetWorkerStartIndex( int workerIndex, int blockCount, int workerCount ) +{ + if ( blockCount <= workerCount ) + { + return workerIndex < blockCount ? workerIndex : B3_NULL_INDEX; + } + + int blocksPerWorker = blockCount / workerCount; + int remainder = blockCount - blocksPerWorker * workerCount; + return blocksPerWorker * workerIndex + b3MinInt( remainder, workerIndex ); +} + +// Execute a stage, which is an array of solver blocks, each controlled with an atomic sync index. +// Each worker starts at its home index and sweeps the ring, CAS-claiming any unclaimed blocks. +static void b3ExecuteStage( b3SolverStage* stage, b3StepContext* context, int previousSyncIndex, int syncIndex, int workerIndex ) +{ + int completedCount = 0; + b3SyncBlock* blocks = stage->blocks; + int blockCount = stage->blockCount; + + int startIndex = GetWorkerStartIndex( workerIndex, blockCount, context->workerCount ); + if ( startIndex == B3_NULL_INDEX ) + { + return; + } + + B3_ASSERT( 0 <= startIndex && startIndex < blockCount ); + + int blockIndex = startIndex; + for ( int i = 0; i < blockCount; ++i ) + { + if ( b3AtomicCompareExchangeInt( &blocks[blockIndex].syncIndex, previousSyncIndex, syncIndex ) ) + { + B3_ASSERT( completedCount < blockCount ); + + // Pass the descriptor by value -- the wrapping b3SyncBlock holds the atomic + // syncIndex but we only copy .block, so the struct copy never aliases the CAS target. + b3ExecuteBlock( stage, context, blocks[blockIndex].block, workerIndex ); + completedCount += 1; + } + + blockIndex += 1; + if ( blockIndex >= blockCount ) + { + blockIndex = 0; + } + } + + (void)b3AtomicFetchAddInt( &stage->completionCount, completedCount ); +} + +// Execute a stage on worker 0 (main thread). +static void b3ExecuteMainStage( b3SolverStage* stage, b3StepContext* context, uint32_t syncBits ) +{ + int blockCount = stage->blockCount; + if ( blockCount == 0 ) + { + return; + } + + const int workerIndex = 0; + + if ( blockCount == 1 ) + { + b3ExecuteBlock( stage, context, stage->blocks[0].block, workerIndex ); + } + else + { + b3AtomicStoreU32( &context->atomicSyncBits, syncBits ); + + int syncIndex = ( syncBits >> 16 ) & 0xFFFF; + B3_ASSERT( syncIndex > 0 ); + int previousSyncIndex = syncIndex - 1; + + b3ExecuteStage( stage, context, previousSyncIndex, syncIndex, workerIndex ); + + // Spin waiting for thieves to finish + while ( b3AtomicLoadInt( &stage->completionCount ) != blockCount ) + { + b3Pause(); + } + + b3AtomicStoreInt( &stage->completionCount, 0 ); + } +} + +// Parallel solver task +static void b3SolverTask( void* taskContext ) +{ + b3WorkerContext* workerContext = (b3WorkerContext*)taskContext; + int workerIndex = workerContext->workerIndex; + b3StepContext* context = workerContext->context; + int activeColorCount = context->activeColorCount; + b3SolverStage* stages = context->stages; + b3Profile* profile = &context->world->profile; + + if ( workerIndex == 0 ) + { + // The orchestrator slot is a race. The calling thread of b3World_Step also enters here + // as worker 0, so progress is guaranteed even if the user's task system schedules tasks + // out of order, has fewer threads than workerCount, or runs the task synchronously + // inside enqueueTaskFcn. Whoever wins the CAS becomes the orchestrator; the loser + // returns and lets the spinner-only path handle workers >0. + if ( b3AtomicCompareExchangeInt( &context->mainClaimed, 0, 1 ) == false ) + { + return; + } + + // Main thread synchronizes the workers and does work itself. + // + // This needs to be a task for the main thread because the user's task system may execute + // the tasks serially and this is the first task. This single task is able to fully + // complete all work even if all other workers are blocked. + + // Stages are re-used by loops so that I don't need more stages for large substep 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. + + /* + b3_stagePrepareJoints, + b3_stagePrepareContacts, + b3_stageIntegrateVelocities, + b3_stageWarmStart, + b3_stageSolve, + b3_stageIntegratePositions, + b3_stageRelax, + b3_stageRestitution, + b3_stageStoreImpulses + */ + + uint64_t ticks = b3GetTicks(); + + int bodySyncIndex = 1; + int stageIndex = 0; + + // Prepare joint constraints + uint32_t jointSyncIndex = 1; + uint32_t syncBits = ( jointSyncIndex << 16 ) | stageIndex; + B3_ASSERT( stages[stageIndex].type == b3_stagePrepareJoints ); + b3ExecuteMainStage( stages + stageIndex, context, syncBits ); + stageIndex += 1; + jointSyncIndex += 1; + + // Prepare convex contact constraints + uint32_t convexSyncIndex = 1; + syncBits = ( convexSyncIndex << 16 ) | stageIndex; + B3_ASSERT( stages[stageIndex].type == b3_stagePrepareWideContacts ); + b3ExecuteMainStage( stages + stageIndex, context, syncBits ); + stageIndex += 1; + convexSyncIndex += 1; + + // Prepare mesh contact constraints + uint32_t meshSyncIndex = 1; + syncBits = ( meshSyncIndex << 16 ) | stageIndex; + B3_ASSERT( stages[stageIndex].type == b3_stagePrepareContacts ); + b3ExecuteMainStage( stages + stageIndex, context, syncBits ); + stageIndex += 1; + meshSyncIndex += 1; + + // Single-threaded overflow work. These constraints don't fit in the graph coloring. + b3PrepareJoints_Overflow( context ); + b3PrepareContacts_Overflow( context ); + + profile->prepareConstraints += b3GetMillisecondsAndReset( &ticks ); + + int graphSyncIndex = 1; + int subStepCount = context->subStepCount; + for ( int subStepIndex = 0; subStepIndex < subStepCount; ++subStepIndex ) + { + // stageIndex restarted each iteration + // syncBits still increases monotonically because the upper bits increase each iteration + int iterationStageIndex = stageIndex; + + // Integrate velocities + syncBits = ( bodySyncIndex << 16 ) | iterationStageIndex; + B3_ASSERT( stages[iterationStageIndex].type == b3_stageIntegrateVelocities ); + b3ExecuteMainStage( stages + iterationStageIndex, context, syncBits ); + iterationStageIndex += 1; + bodySyncIndex += 1; + + profile->integrateVelocities += b3GetMillisecondsAndReset( &ticks ); + + // Warm start constraints + b3WarmStartJoints_Overflow( context ); + b3WarmStartContacts_Overflow( context ); + + for ( int colorIndex = 0; colorIndex < activeColorCount; ++colorIndex ) + { + syncBits = ( graphSyncIndex << 16 ) | iterationStageIndex; + B3_ASSERT( stages[iterationStageIndex].type == b3_stageWarmStart ); + b3ExecuteMainStage( stages + iterationStageIndex, context, syncBits ); + iterationStageIndex += 1; + } + graphSyncIndex += 1; + + profile->warmStart += b3GetMillisecondsAndReset( &ticks ); + + // Solve constraints + bool useBias = true; + for ( int j = 0; j < ITERATIONS; ++j ) + { + // Overflow constraints have lower priority. Typically these are dynamic-vs-dynamic. + b3SolveJoints_Overflow( context, useBias ); + b3SolveContacts_Overflow( context, useBias ); + + for ( int colorIndex = 0; colorIndex < activeColorCount; ++colorIndex ) + { + syncBits = ( graphSyncIndex << 16 ) | iterationStageIndex; + B3_ASSERT( stages[iterationStageIndex].type == b3_stageSolve ); + b3ExecuteMainStage( stages + iterationStageIndex, context, syncBits ); + iterationStageIndex += 1; + } + graphSyncIndex += 1; + } + + profile->solveImpulses += b3GetMillisecondsAndReset( &ticks ); + + // Integrate positions + B3_ASSERT( stages[iterationStageIndex].type == b3_stageIntegratePositions ); + syncBits = ( bodySyncIndex << 16 ) | iterationStageIndex; + b3ExecuteMainStage( stages + iterationStageIndex, context, syncBits ); + iterationStageIndex += 1; + bodySyncIndex += 1; + + profile->integratePositions += b3GetMillisecondsAndReset( &ticks ); + + // Relax constraints + useBias = false; + for ( int j = 0; j < RELAX_ITERATIONS; ++j ) + { + b3SolveJoints_Overflow( context, useBias ); + b3SolveContacts_Overflow( context, useBias ); + + for ( int colorIndex = 0; colorIndex < activeColorCount; ++colorIndex ) + { + syncBits = ( graphSyncIndex << 16 ) | iterationStageIndex; + B3_ASSERT( stages[iterationStageIndex].type == b3_stageRelax ); + b3ExecuteMainStage( stages + iterationStageIndex, context, syncBits ); + iterationStageIndex += 1; + } + graphSyncIndex += 1; + } + + profile->relaxImpulses += b3GetMillisecondsAndReset( &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 + { + b3ApplyRestitution_Overflow( context ); + + int iterStageIndex = stageIndex; + for ( int colorIndex = 0; colorIndex < activeColorCount; ++colorIndex ) + { + syncBits = ( graphSyncIndex << 16 ) | iterStageIndex; + B3_ASSERT( stages[iterStageIndex].type == b3_stageRestitution ); + b3ExecuteMainStage( stages + iterStageIndex, context, syncBits ); + iterStageIndex += 1; + } + // graphSyncIndex += 1; + stageIndex += activeColorCount; + } + + profile->applyRestitution += b3GetMillisecondsAndReset( &ticks ); + + // Store impulses + b3StoreImpulses_Overflow( context ); + + syncBits = ( convexSyncIndex << 16 ) | stageIndex; + B3_ASSERT( stages[stageIndex].type == b3_stageStoreWideImpulses ); + b3ExecuteMainStage( stages + stageIndex, context, syncBits ); + stageIndex += 1; + + syncBits = ( meshSyncIndex << 16 ) | stageIndex; + B3_ASSERT( stages[stageIndex].type == b3_stageStoreImpulses ); + b3ExecuteMainStage( stages + stageIndex, context, syncBits ); + stageIndex += 1; + + profile->storeImpulses += b3GetMillisecondsAndReset( &ticks ); + + // Signal workers to finish + b3AtomicStoreU32( &context->atomicSyncBits, UINT_MAX ); + + B3_ASSERT( stageIndex == 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. + // todo improve this spinner + uint32_t syncBits; + int spinCount = 0; + while ( ( syncBits = b3AtomicLoadU32( &context->atomicSyncBits ) ) == lastSyncBits ) + { + if ( spinCount > 5 ) + { + b3Yield(); + 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 + //{ + // b3Pause(); + //} + // while ((__rdtsc() - prev) < maxSpinTime); + // maxSpinTime += 10; + b3Pause(); + b3Pause(); + spinCount += 1; + } + } + + if ( syncBits == UINT_MAX ) + { + // sentinel hit + break; + } + + int stageIndex = syncBits & 0xFFFF; + B3_ASSERT( stageIndex < context->stageCount ); + + int syncIndex = ( syncBits >> 16 ) & 0xFFFF; + B3_ASSERT( syncIndex > 0 ); + + int previousSyncIndex = syncIndex - 1; + + b3SolverStage* stage = stages + stageIndex; + b3ExecuteStage( stage, context, previousSyncIndex, syncIndex, workerIndex ); + + lastSyncBits = syncBits; + } +} + +static void b3BulletBodyTask( int startIndex, int endIndex, int workerIndex, void* context ) +{ + b3TracyCZoneNC( bullet_body_task, "Bullet Body Task", b3_colorLightSkyBlue, true ); + + b3StepContext* stepContext = (b3StepContext*)context; + b3TaskContext* taskContext = b3Array_Get( stepContext->world->taskContexts, workerIndex ); + + B3_ASSERT( startIndex <= endIndex ); + + for ( int i = startIndex; i < endIndex; ++i ) + { + int simIndex = stepContext->bulletBodies[i]; + b3SolveContinuous( stepContext->world, simIndex, taskContext ); + } + + b3TracyCZoneEnd( bullet_body_task ); +} + +#if B3_SIMD_WIDTH == 4 +#define B3_SIMD_SHIFT 2 +#else +#define B3_SIMD_SHIFT 0 +#endif + +// Solve with graph coloring +void b3Solve( b3World* world, b3StepContext* stepContext ) +{ + // Only count steps that advance the simulation + world->stepIndex += 1; + + b3SolverSet* awakeSet = b3Array_Get( world->solverSets, b3_awakeSet ); + int awakeBodyCount = awakeSet->bodySims.count; + if ( awakeBodyCount == 0 ) + { + b3ValidateNoEnlarged( &world->broadPhase ); + return; + } + + // Solve constraints using graph coloring + { + b3TracyCZoneNC( solver_setup, "Solver Setup", b3_colorDarkOrange, true ); + uint64_t setupTicks = b3GetTicks(); + + // Prepare buffers for continuous collision (fast bodies) + b3AtomicStoreInt( &stepContext->bulletBodyCount, 0 ); + stepContext->bulletBodies = (int*)b3StackAlloc( &world->stack, awakeBodyCount * sizeof( int ), "bullet bodies" ); + + b3ConstraintGraph* graph = &world->constraintGraph; + b3GraphColor* colors = graph->colors; + + stepContext->sims = awakeSet->bodySims.data; + stepContext->states = awakeSet->bodyStates.data; + + // count contacts, joints, and colors + int activeColorCount = 0; + for ( int i = 0; i < B3_GRAPH_COLOR_COUNT - 1; ++i ) + { + int perColorContactCount = colors[i].convexContacts.count + colors[i].contacts.count; + int perColorJointCount = colors[i].jointSims.count; + int occupancyCount = perColorContactCount + perColorJointCount; + activeColorCount += occupancyCount > 0 ? 1 : 0; + } + + // prepare for move events + b3Array_Resize( world->bodyMoveEvents, awakeBodyCount ); + + int workerCount = world->workerCount; + + // Target 4 blocks per worker to allow work stealing + const int maxBlockCount = 4 * workerCount; + + // Body blocks are for parallel iteration over bodies directly (integration, update transforms) + int minBodiesPerBlock = 32; + b3BlockDim bodyDim = b3ComputeBlockCount( awakeBodyCount, minBodiesPerBlock, maxBlockCount ); + + const int minContactsPerBlock = 4; + const int minJointsPerBlock = 4; + + // Configure blocks for tasks parallel-for each active graph color + // The blocks are a mix of convex contact, mesh contact, and joint blocks + int activeColorIndices[B3_GRAPH_COLOR_COUNT]; + int colorWideContactCounts[B3_GRAPH_COLOR_COUNT]; + int colorContactCounts[B3_GRAPH_COLOR_COUNT]; + // int colorManifoldCounts[B3_GRAPH_COLOR_COUNT]; + int colorJointCounts[B3_GRAPH_COLOR_COUNT]; + b3BlockDim graphWideContactDims[B3_GRAPH_COLOR_COUNT]; + b3BlockDim graphContactDims[B3_GRAPH_COLOR_COUNT]; + b3BlockDim graphJointDims[B3_GRAPH_COLOR_COUNT]; + int graphBlockCount = 0; + + // c is the active color index + int wideContactCount = 0; + int contactCount = 0; + int manifoldCount = 0; + int jointCount = 0; + int c = 0; + for ( int i = 0; i < B3_GRAPH_COLOR_COUNT - 1; ++i ) + { + b3GraphColor* color = colors + i; + int colorConvexContactCount = color->convexContacts.count; + int colorContactCount = color->contacts.count; + int colorJointCount = color->jointSims.count; + + if ( colorConvexContactCount + colorContactCount + colorJointCount == 0 ) + { + continue; + } + + activeColorIndices[c] = i; + + // Ceiling for wide constraint count + int colorWideConstraintCount = + colorConvexContactCount > 0 ? ( ( colorConvexContactCount - 1 ) >> B3_SIMD_SHIFT ) + 1 : 0; + wideContactCount += colorWideConstraintCount; + colorWideContactCounts[c] = colorWideConstraintCount; + + colorContactCounts[c] = colorContactCount; + contactCount += colorContactCount; + + // Compute manifold starts and accumulate manifold count + for ( int j = 0; j < colorContactCount; ++j ) + { + color->contacts.data[j].manifoldStart = manifoldCount; + manifoldCount += color->contacts.data[j].manifoldCount; + } + + colorJointCounts[c] = colorJointCount; + jointCount += colorJointCount; + + // Solver block dimensions + graphWideContactDims[c] = b3ComputeBlockCount( colorWideConstraintCount, minContactsPerBlock, maxBlockCount ); + graphContactDims[c] = b3ComputeBlockCount( colorContactCount, minContactsPerBlock, maxBlockCount ); + graphJointDims[c] = b3ComputeBlockCount( colorJointCount, minJointsPerBlock, maxBlockCount ); + graphBlockCount += graphWideContactDims[c].count + graphContactDims[c].count + graphJointDims[c].count; + + c += 1; + } + activeColorCount = c; + + // Prepare and store run as one flat parallel-for over the entire wide constraint range, + // partitioned into uniformly sized blocks. Color info is consulted inside the task via + // a small span array, so blocks do not need to honor color boundaries here. + b3BlockDim convexPrepareDim = b3ComputeBlockCount( wideContactCount, minContactsPerBlock, maxBlockCount ); + b3BlockDim meshPrepareDim = b3ComputeBlockCount( contactCount, minContactsPerBlock, maxBlockCount ); + b3BlockDim jointPrepareDim = b3ComputeBlockCount( jointCount, minJointsPerBlock, maxBlockCount ); + + int wideContactByteCount = b3GetWideContactConstraintByteCount(); + b3ContactConstraintWide* wideConstraints = + (b3ContactConstraintWide*)b3StackAlloc( &world->stack, wideContactCount * wideContactByteCount, "wide contacts" ); + b3ContactConstraint* contactConstraints = + (b3ContactConstraint*)b3StackAlloc( &world->stack, contactCount * sizeof( b3ContactConstraint ), "contacts" ); + b3ManifoldConstraint* manifoldConstraints = (b3ManifoldConstraint*)b3StackAlloc( + &world->stack, manifoldCount * sizeof( b3ManifoldConstraint ), "manifold constraints" ); + + b3GraphColor* overflow = colors + B3_OVERFLOW_INDEX; + int overflowCount = overflow->contacts.count; + int overflowManifoldCount = 0; + for ( int i = 0; i < overflowCount; ++i ) + { + overflow->contacts.data[i].manifoldStart = overflowManifoldCount; + overflowManifoldCount += overflow->contacts.data[i].manifoldCount; + } + + overflow->contactConstraints = (b3ContactConstraint*)b3StackAlloc( + &world->stack, overflowCount * sizeof( b3ContactConstraint ), "overflow contacts" ); + overflow->manifoldConstraints = (b3ManifoldConstraint*)b3StackAlloc( + &world->stack, overflowManifoldCount * sizeof( b3ManifoldConstraint ), "overflow manifolds" ); + + // Build the span table for the flat prepare/store parallel-for while I slice the + // wide constraint buffer across colors. One entry per active color plus a sentinel + // at wideContactCount. + b3WidePrepareSpan widePrepareSpans[B3_GRAPH_COLOR_COUNT + 1]; + b3ContactPrepareSpan contactPrepareSpans[B3_GRAPH_COLOR_COUNT + 1]; + b3JointPrepareSpan jointPrepareSpans[B3_GRAPH_COLOR_COUNT + 1]; + + // Distribute transient constraints to each graph color and prepare spans + // todo it might be simpler for solver blocks to index into the global arrays + { + int wideBase = 0; + int contactBase = 0; + int jointBase = 0; + for ( int i = 0; i < activeColorCount; ++i ) + { + int j = activeColorIndices[i]; + b3GraphColor* color = colors + j; + + int colorConvexContactCount = color->convexContacts.count; + widePrepareSpans[i].start = wideBase; + widePrepareSpans[i].count = colorConvexContactCount; + widePrepareSpans[i].contacts = color->convexContacts.data; + + if ( colorConvexContactCount == 0 ) + { + color->wideConstraints = NULL; + color->wideConstraintCount = 0; + } + else + { + color->wideConstraints = + (b3ContactConstraintWide*)( (uint8_t*)wideConstraints + wideBase * wideContactByteCount ); + + int colorContactCountW = ( ( colorConvexContactCount - 1 ) >> B3_SIMD_SHIFT ) + 1; + color->wideConstraintCount = colorContactCountW; + + // Zero remainder lanes in the tail wide slot so prepare workers don't need to + // initialize them. + if ( ( colorConvexContactCount & ( B3_SIMD_WIDTH - 1 ) ) != 0 ) + { + memset( (uint8_t*)color->wideConstraints + ( colorContactCountW - 1 ) * wideContactByteCount, 0, + wideContactByteCount ); + } + + wideBase += colorContactCountW; + } + + int colorContactCount = color->contacts.count; + contactPrepareSpans[i].start = contactBase; + contactPrepareSpans[i].count = colorContactCount; + contactPrepareSpans[i].contacts = color->contacts.data; + + if ( colorContactCount == 0 ) + { + color->contactConstraints = NULL; + color->contactConstraintCount = 0; + } + else + { + color->contactConstraints = contactConstraints + contactBase; + color->contactConstraintCount = colorContactCount; + contactBase += colorContactCount; + } + + jointPrepareSpans[i].start = jointBase; + jointPrepareSpans[i].count = color->jointSims.count; + jointPrepareSpans[i].joints = color->jointSims.data; + jointBase += color->jointSims.count; + } + + // Sentinels + widePrepareSpans[activeColorCount].start = wideContactCount; + widePrepareSpans[activeColorCount].count = 0; + widePrepareSpans[activeColorCount].contacts = NULL; + B3_ASSERT( wideBase == wideContactCount ); + + contactPrepareSpans[activeColorCount].start = contactCount; + contactPrepareSpans[activeColorCount].count = 0; + contactPrepareSpans[activeColorCount].contacts = NULL; + B3_ASSERT( contactBase == contactCount ); + + jointPrepareSpans[activeColorCount].start = jointCount; + jointPrepareSpans[activeColorCount].count = 0; + jointPrepareSpans[activeColorCount].joints = NULL; + B3_ASSERT( jointBase == jointCount ); + } + + //// Special span for overflow to allow for function re-use + b3ContactPrepareSpan overflowSpans[2] = { 0 }; + overflowSpans[0].start = 0; + overflowSpans[0].count = overflow->contacts.count; + overflowSpans[0].contacts = overflow->contacts.data; + overflowSpans[1].start = overflow->contacts.count; + overflowSpans[1].count = 0; + overflowSpans[1].contacts = NULL; + + int stageCount = 0; + + // b3_stagePrepareJoints + stageCount += 1; + // b3_stagePrepareWideContacts + stageCount += 1; + // b3_stagePrepareContacts + stageCount += 1; + // b3_stageIntegrateVelocities + stageCount += 1; + // b3_stageWarmStart + stageCount += activeColorCount; + // b3_stageSolve + stageCount += ITERATIONS * activeColorCount; + // b3_stageIntegratePositions + stageCount += 1; + // b3_stageRelax + stageCount += RELAX_ITERATIONS * activeColorCount; + // b3_stageRestitution + stageCount += activeColorCount; + // b3_stageStoreWideImpulses + stageCount += 1; + // b3_stageStoreImpulses + stageCount += 1; + + b3SolverStage* stages = (b3SolverStage*)b3StackAlloc( &world->stack, stageCount * sizeof( b3SolverStage ), "stages" ); + b3SyncBlock* bodyBlocks = + (b3SyncBlock*)b3StackAlloc( &world->stack, bodyDim.count * sizeof( b3SyncBlock ), "body blocks" ); + b3SyncBlock* convexBlocks = + (b3SyncBlock*)b3StackAlloc( &world->stack, convexPrepareDim.count * sizeof( b3SyncBlock ), "convex blocks" ); + b3SyncBlock* meshBlocks = + (b3SyncBlock*)b3StackAlloc( &world->stack, meshPrepareDim.count * sizeof( b3SyncBlock ), "mesh blocks" ); + b3SyncBlock* jointBlocks = + (b3SyncBlock*)b3StackAlloc( &world->stack, jointPrepareDim.count * sizeof( b3SyncBlock ), "joint blocks" ); + b3SyncBlock* graphBlocks = + (b3SyncBlock*)b3StackAlloc( &world->stack, graphBlockCount * sizeof( b3SyncBlock ), "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 != B3_NULL_INDEX ) + { + if ( world->taskCount < B3_MAX_TASKS ) + { + splitIslandTask = world->enqueueTaskFcn( &b3SplitIslandTask, world, world->userTaskContext, "split" ); + world->taskCount += 1; + world->activeTaskCount += splitIslandTask == NULL ? 0 : 1; + } + else + { + b3SplitIslandTask( world ); + } + } + + // Prepare body blocks + b3InitBlocks( bodyBlocks, bodyDim, awakeBodyCount, b3_bodyBlock, UINT8_MAX ); + + // Prepare blocks as a single flat parallel-for over the whole constraint range. + // The task walks spans to decode flat slot indices back to per-color arrays. + b3InitBlocks( convexBlocks, convexPrepareDim, wideContactCount, b3_wideContactBlock, UINT8_MAX ); + b3InitBlocks( meshBlocks, meshPrepareDim, contactCount, b3_contactBlock, UINT8_MAX ); + b3InitBlocks( jointBlocks, jointPrepareDim, jointCount, b3_jointBlock, UINT8_MAX ); + + // Prepare graph work blocks. Each color gets joint blocks followed by contact blocks. + b3SyncBlock* graphColorBlocks[B3_GRAPH_COLOR_COUNT] = { 0 }; + b3SyncBlock* baseGraphBlock = graphBlocks; + int graphBlockCounts[B3_GRAPH_COLOR_COUNT] = { 0 }; + for ( int i = 0; i < activeColorCount; ++i ) + { + graphColorBlocks[i] = baseGraphBlock; + + uint8_t colorIndex = (uint8_t)activeColorIndices[i]; + b3InitBlocks( baseGraphBlock, graphJointDims[i], colorJointCounts[i], b3_graphJointBlock, colorIndex ); + baseGraphBlock += graphJointDims[i].count; + + b3InitBlocks( baseGraphBlock, graphWideContactDims[i], colorWideContactCounts[i], b3_graphWideContactBlock, + colorIndex ); + baseGraphBlock += graphWideContactDims[i].count; + + b3InitBlocks( baseGraphBlock, graphContactDims[i], colorContactCounts[i], b3_graphContactBlock, colorIndex ); + baseGraphBlock += graphContactDims[i].count; + + graphBlockCounts[i] = graphJointDims[i].count + graphWideContactDims[i].count + graphContactDims[i].count; + } + + B3_ASSERT( (ptrdiff_t)( baseGraphBlock - graphBlocks ) == graphBlockCount ); + + b3SolverStage* stage = stages; + stage = b3InitStage( stage, b3_stagePrepareJoints, jointBlocks, jointPrepareDim.count, UINT8_MAX ); + stage = b3InitStage( stage, b3_stagePrepareWideContacts, convexBlocks, convexPrepareDim.count, UINT8_MAX ); + stage = b3InitStage( stage, b3_stagePrepareContacts, meshBlocks, meshPrepareDim.count, UINT8_MAX ); + stage = b3InitStage( stage, b3_stageIntegrateVelocities, bodyBlocks, bodyDim.count, UINT8_MAX ); + stage = b3InitColorStages( stage, b3_stageWarmStart, 1, activeColorCount, graphColorBlocks, graphBlockCounts, + activeColorIndices ); + stage = b3InitColorStages( stage, b3_stageSolve, ITERATIONS, activeColorCount, graphColorBlocks, graphBlockCounts, + activeColorIndices ); + stage = b3InitStage( stage, b3_stageIntegratePositions, bodyBlocks, bodyDim.count, UINT8_MAX ); + stage = b3InitColorStages( stage, b3_stageRelax, RELAX_ITERATIONS, activeColorCount, graphColorBlocks, graphBlockCounts, + activeColorIndices ); + // Note: joint blocks mixed in, could have joint limit restitution + stage = b3InitColorStages( stage, b3_stageRestitution, 1, activeColorCount, graphColorBlocks, graphBlockCounts, + activeColorIndices ); + stage = b3InitStage( stage, b3_stageStoreWideImpulses, convexBlocks, convexPrepareDim.count, UINT8_MAX ); + stage = b3InitStage( stage, b3_stageStoreImpulses, meshBlocks, meshPrepareDim.count, UINT8_MAX ); + + B3_ASSERT( (int)( stage - stages ) == stageCount ); + + B3_ASSERT( workerCount <= B3_MAX_WORKERS ); + b3WorkerContext workerContext[B3_MAX_WORKERS]; + + stepContext->graph = graph; + stepContext->activeColorCount = activeColorCount; + stepContext->workerCount = workerCount; + stepContext->stageCount = stageCount; + stepContext->stages = stages; + stepContext->wideConstraints = wideConstraints; + stepContext->widePrepareSpans = widePrepareSpans; + stepContext->wideContactCount = wideContactCount; + stepContext->manifoldConstraints = manifoldConstraints; + stepContext->contactConstraints = contactConstraints; + stepContext->contactPrepareSpans = contactPrepareSpans; + stepContext->overflowSpans = overflowSpans; + stepContext->jointPrepareSpans = jointPrepareSpans; + b3AtomicStoreU32( &stepContext->atomicSyncBits, 0 ); + b3AtomicStoreInt( &stepContext->mainClaimed, 0 ); + + world->profile.solverSetup = b3GetMillisecondsAndReset( &setupTicks ); + b3TracyCZoneEnd( solver_setup ); + + b3TracyCZoneNC( solve_constraints, "Solve Constraints", b3_colorIndigo, true ); + uint64_t constraintTicks = b3GetTicks(); + + int jointIdCapacity = b3GetIdCapacity( &world->jointIdPool ); + int contactIdCapacity = b3GetIdCapacity( &world->contactIdPool ); + for ( int i = 0; i < workerCount; ++i ) + { + b3TaskContext* taskContext = b3Array_Get( world->taskContexts, i ); + b3SetBitCountAndClear( &taskContext->jointStateBitSet, jointIdCapacity ); + b3SetBitCountAndClear( &taskContext->hitEventBitSet, contactIdCapacity ); + taskContext->hasHitEvents = false; + + workerContext[i].context = stepContext; + workerContext[i].workerIndex = i; + + if ( world->taskCount < B3_MAX_TASKS ) + { + char buffer[16]; + snprintf( buffer, sizeof(buffer), "solve[%d]", i ); + workerContext[i].userTask = world->enqueueTaskFcn( &b3SolverTask, workerContext + i, world->userTaskContext, buffer ); + world->taskCount += 1; + world->activeTaskCount += workerContext[i].userTask == NULL ? 0 : 1; + } + else + { + workerContext[i].userTask = NULL; + b3SolverTask( workerContext + i ); + } + } + + // The calling thread of b2World_Step also enters b2SolverTask as worker 0 and races for the + // orchestrator slot via the CAS inside. This guarantees progress even when the user's task + // system can't run the queued worker 0 promptly: it might schedule out of order, have fewer + // threads than workerCount, or invert priority by parking the calling thread in finishTaskFcn. + // Whoever wins the CAS becomes the orchestrator; the loser returns and lets the spinner-only + // path handle workers >0. + b3WorkerContext callerContext = { stepContext, 0, NULL }; + b3SolverTask( &callerContext ); + + // 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; + } + } + + // Finish island split + if ( splitIslandTask != NULL ) + { + world->finishTaskFcn( splitIslandTask, world->userTaskContext ); + world->activeTaskCount -= 1; + } + world->splitIslandId = B3_NULL_INDEX; + + world->profile.constraints = b3GetMillisecondsAndReset( &constraintTicks ); + b3TracyCZoneEnd( solve_constraints ); + + b3TracyCZoneNC( update_transforms, "Update Transforms", b3_colorMediumSeaGreen, true ); + uint64_t transformTicks = b3GetTicks(); + + // 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 ) + { + b3TaskContext* taskContext = world->taskContexts.data + i; + b3Array_Clear( taskContext->sensorHits ); + b3SetBitCountAndClear( &taskContext->enlargedSimBitSet, awakeBodyCount ); + b3SetBitCountAndClear( &taskContext->awakeIslandBitSet, awakeIslandCount ); + taskContext->splitIslandId = B3_NULL_INDEX; + taskContext->splitSleepTime = 0.0f; + } + + // Finalize bodies. Must happen after the constraint solver and after island splitting. + b3ParallelFor( world, &b3FinalizeBodiesTask, awakeBodyCount, 64, stepContext, "ccd" ); + + // Free in reverse order + b3StackFree( &world->stack, graphBlocks ); + b3StackFree( &world->stack, jointBlocks ); + b3StackFree( &world->stack, meshBlocks ); + b3StackFree( &world->stack, convexBlocks ); + b3StackFree( &world->stack, bodyBlocks ); + b3StackFree( &world->stack, stages ); + b3StackFree( &world->stack, overflow->manifoldConstraints ); + b3StackFree( &world->stack, overflow->contactConstraints ); + b3StackFree( &world->stack, manifoldConstraints ); + b3StackFree( &world->stack, contactConstraints ); + b3StackFree( &world->stack, wideConstraints ); + + world->profile.transforms = b3GetMilliseconds( transformTicks ); + b3TracyCZoneEnd( update_transforms ); + } + + // Report joint events + { + b3TracyCZoneNC( joint_events, "Joint Events", b3_colorPeru, true ); + uint64_t jointEventTicks = b3GetTicks(); + + // Gather bits for all joints that have force/torque events + b3BitSet* jointStateBitSet = &world->taskContexts.data[0].jointStateBitSet; + for ( int i = 1; i < world->workerCount; ++i ) + { + b3InPlaceUnion( jointStateBitSet, &world->taskContexts.data[i].jointStateBitSet ); + } + + { + uint32_t wordCount = jointStateBitSet->blockCount; + uint64_t* bits = jointStateBitSet->bits; + + b3Joint* 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 = b3CTZ64( word ); + int jointId = (int)( 64 * k + ctz ); + + B3_ASSERT( jointId < world->joints.capacity ); + + b3Joint* joint = jointArray + jointId; + + B3_ASSERT( joint->setIndex == b3_awakeSet ); + + b3JointEvent event = { + .jointId = + { + .index1 = jointId + 1, + .world0 = worldIndex0, + .generation = joint->generation, + }, + .userData = joint->userData, + }; + + b3Array_Push( world->jointEvents, event ); + + // Clear the smallest set bit + word = word & ( word - 1 ); + } + } + } + + world->profile.jointEvents = b3GetMilliseconds( jointEventTicks ); + b3TracyCZoneEnd( joint_events ); + } + + // Report hit events + { + b3TracyCZoneNC( hit_events, "Hit Events", b3_colorRosyBrown, true ); + uint64_t hitTicks = b3GetTicks(); + + B3_ASSERT( world->contactHitEvents.count == 0 ); + + // Fast path: if no worker flagged any hit-event candidates during b2StoreImpulsesTask, skip entirely. + bool anyHitEvents = false; + for ( int i = 0; i < world->workerCount; ++i ) + { + if ( world->taskContexts.data[i].hasHitEvents ) + { + anyHitEvents = true; + break; + } + } + + if ( anyHitEvents ) + { + // Union per-worker bits into worker 0's bit set. + b3BitSet* hitEventBitSet = &world->taskContexts.data[0].hitEventBitSet; + for ( int i = 1; i < world->workerCount; ++i ) + { + if ( world->taskContexts.data[i].hasHitEvents ) + { + b3InPlaceUnion( hitEventBitSet, &world->taskContexts.data[i].hitEventBitSet ); + } + } + + float threshold = world->hitEventThreshold; + b3Contact* contactArray = world->contacts.data; + uint16_t worldId = world->worldId; + + uint32_t wordCount = hitEventBitSet->blockCount; + uint64_t* bits = hitEventBitSet->bits; + for ( uint32_t k = 0; k < wordCount; ++k ) + { + uint64_t word = bits[k]; + while ( word != 0 ) + { + uint32_t ctz = b3CTZ64( word ); + int contactId = (int)( 64 * k + ctz ); + + b3Contact* contact = contactArray + contactId; + B3_ASSERT( contact->setIndex == b3_awakeSet && contact->colorIndex != B3_NULL_INDEX ); + + b3Shape* shapeA = b3Array_Get( world->shapes, contact->shapeIdA ); + b3Shape* shapeB = b3Array_Get( world->shapes, contact->shapeIdB ); + b3Body* bodyA = b3Array_Get( world->bodies, shapeA->bodyId ); + b3Body* bodyB = b3Array_Get( world->bodies, shapeB->bodyId ); + b3BodySim* simA = b3GetBodySim( world, bodyA ); + b3BodySim* simB = b3GetBodySim( world, bodyB ); + b3Vec3 midCenter = b3Lerp( simA->center, simB->center, 0.5f ); + + b3ContactHitEvent event = { 0 }; + event.approachSpeed = threshold; + + bool found = false; + int triangleIndex = 0; + int manifoldCount = contact->manifoldCount; + for ( int i = 0; i < manifoldCount; ++i ) + { + b3Manifold* manifold = contact->manifolds + i; + int pointCount = manifold->pointCount; + for ( int p = 0; p < pointCount; ++p ) + { + b3ManifoldPoint* mp = manifold->points + p; + 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 = b3Add( midCenter, b3Lerp( mp->anchorA, mp->anchorB, 0.5f ) ); + event.normal = manifold->normal; + triangleIndex = mp->triangleIndex; + found = true; + } + } + } + + if ( found == true ) + { + event.shapeIdA = (b3ShapeId){ shapeA->id + 1, worldId, shapeA->generation }; + event.shapeIdB = (b3ShapeId){ shapeB->id + 1, worldId, shapeB->generation }; + + event.contactId = (b3ContactId){ + .index1 = contact->contactId + 1, + .world0 = worldId, + .padding = 0, + .generation = contact->generation, + }; + + // shapeB is never a compound today (asserted in b3CreateContact), so the + // childIndex argument is irrelevant for it. shapeA carries the compound. + event.userMaterialIdA = b3GetShapeUserMaterialId( shapeA, contact->childIndex, triangleIndex ); + event.userMaterialIdB = b3GetShapeUserMaterialId( shapeB, 0, triangleIndex ); + + b3Array_Push( world->contactHitEvents, event ); + } + + // Clear the smallest set bit + word = word & ( word - 1 ); + } + } + } + + world->profile.hitEvents = b3GetMilliseconds( hitTicks ); + b3TracyCZoneEnd( hit_events ); + } + + { + b3TracyCZoneNC( refit_bvh, "Refit BVH", b3_colorFireBrick, true ); + uint64_t refitTicks = b3GetTicks(); + + // 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; + } + + b3ValidateNoEnlarged( &world->broadPhase ); + + // Gather bits for all sim bodies that have enlarged AABBs + b3BitSet* enlargedBodyBitSet = &world->taskContexts.data[0].enlargedSimBitSet; + for ( int i = 1; i < world->workerCount; ++i ) + { + b3InPlaceUnion( 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. + { + b3BroadPhase* broadPhase = &world->broadPhase; + uint32_t wordCount = enlargedBodyBitSet->blockCount; + uint64_t* bits = enlargedBodyBitSet->bits; + + // Fast array access is important here + b3Body* bodyArray = world->bodies.data; + b3BodySim* bodySimArray = awakeSet->bodySims.data; + b3Shape* shapeArray = world->shapes.data; + + for ( uint32_t k = 0; k < wordCount; ++k ) + { + uint64_t word = bits[k]; + while ( word != 0 ) + { + uint32_t ctz = b3CTZ64( word ); + uint32_t bodySimIndex = 64 * k + ctz; + + b3BodySim* bodySim = bodySimArray + bodySimIndex; + + b3Body* body = bodyArray + bodySim->bodyId; + + int shapeId = body->headShapeId; + if ( ( bodySim->flags & ( b3_isBullet | b3_isFast ) ) == ( b3_isBullet | b3_isFast ) ) + { + // Fast bullet bodies don't have their final AABB yet + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* 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. + b3BufferMove( broadPhase, shape->proxyKey ); + + shapeId = shape->nextShapeId; + } + } + else + { + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* 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 ) + { + B3_VALIDATE( b3IsSaneAABB( shape->fatAABB ) ); + + b3BroadPhase_EnlargeProxy( broadPhase, shape->proxyKey, shape->fatAABB ); + shape->enlargedAABB = false; + } + + shapeId = shape->nextShapeId; + } + } + + // Clear the smallest set bit + word = word & ( word - 1 ); + } + } + } + + b3ValidateBroadphase( &world->broadPhase ); + + world->profile.refit = b3GetMilliseconds( refitTicks ); + b3TracyCZoneEnd( refit_bvh ); + } + + int bulletBodyCount = b3AtomicLoadInt( &stepContext->bulletBodyCount ); + if ( bulletBodyCount > 0 ) + { + b3TracyCZoneNC( bullets, "Bullets", b3_colorDarkGoldenRod, true ); + uint64_t bulletTicks = b3GetTicks(); + + // Fast bullet bodies + // Note: a bullet body may be moving slow + int minRange = 8; + b3ParallelFor( world, &b3BulletBodyTask, bulletBodyCount, minRange, stepContext, "bullets" ); + + // Serially enlarge broad-phase proxies for bullet shapes + b3BroadPhase* broadPhase = &world->broadPhase; + b3DynamicTree* dynamicTree = broadPhase->trees + b3_dynamicBody; + + // Fast array access is important here + b3Body* bodyArray = world->bodies.data; + b3BodySim* bodySimArray = awakeSet->bodySims.data; + b3Shape* 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 ) + { + b3BodySim* bulletBodySim = bodySimArray + bulletBodySimIndices[i]; + if ( ( bulletBodySim->flags & b3_enlargeBounds ) == 0 ) + { + continue; + } + + // Clear flag + bulletBodySim->flags &= ~b3_enlargeBounds; + + int bodyId = bulletBodySim->bodyId; + B3_ASSERT( 0 <= bodyId && bodyId < world->bodies.count ); + b3Body* bulletBody = bodyArray + bodyId; + + int shapeId = bulletBody->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + b3Shape* shape = shapeArray + shapeId; + if ( shape->enlargedAABB == false ) + { + shapeId = shape->nextShapeId; + continue; + } + + // clear flag + shape->enlargedAABB = false; + + int proxyKey = shape->proxyKey; + int proxyId = B3_PROXY_ID( proxyKey ); + B3_ASSERT( B3_PROXY_TYPE( proxyKey ) == b3_dynamicBody ); + + // all fast bullet shapes should already be in the move buffer + B3_ASSERT( b3ContainsKey( &broadPhase->moveSet, proxyKey + 1 ) ); + + b3DynamicTree_EnlargeProxy( dynamicTree, proxyId, shape->fatAABB ); + + shapeId = shape->nextShapeId; + } + } + + world->profile.bullets = b3GetMilliseconds( bulletTicks ); + b3TracyCZoneEnd( bullets ); + } + + b3StackFree( &world->stack, stepContext->bulletBodies ); + stepContext->bulletBodies = NULL; + b3AtomicStoreInt( &stepContext->bulletBodyCount, 0 ); + + // Report sensor hits. This may include bullets sensor hits. + { + b3TracyCZoneNC( sensor_hits, "Sensor Hits", b3_colorPowderBlue, true ); + uint64_t sensorHitTicks = b3GetTicks(); + + int workerCount = world->workerCount; + B3_ASSERT( workerCount == world->taskContexts.count ); + + for ( int i = 0; i < workerCount; ++i ) + { + b3TaskContext* taskContext = world->taskContexts.data + i; + int hitCount = taskContext->sensorHits.count; + b3SensorHit* hits = taskContext->sensorHits.data; + + for ( int j = 0; j < hitCount; ++j ) + { + b3SensorHit hit = hits[j]; + b3Shape* sensorShape = b3Array_Get( world->shapes, hit.sensorId ); + b3Shape* visitor = b3Array_Get( world->shapes, hit.visitorId ); + + b3Sensor* sensor = b3Array_Get( world->sensors, sensorShape->sensorIndex ); + b3Visitor shapeRef = { + .shapeId = hit.visitorId, + .generation = visitor->generation, + }; + b3Array_Push( sensor->hits, shapeRef ); + } + } + + world->profile.sensorHits = b3GetMilliseconds( sensorHitTicks ); + b3TracyCZoneEnd( 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 ) + { + b3TracyCZoneNC( sleep_islands, "Island Sleep", b3_colorLightSlateGray, true ); + uint64_t sleepTicks = b3GetTicks(); + + // Collect split island candidate for the next time step. No need to split if sleeping is disabled. + B3_ASSERT( world->splitIslandId == B3_NULL_INDEX ); + float splitSleepTimer = 0.0f; + for ( int i = 0; i < world->workerCount; ++i ) + { + b3TaskContext* taskContext = world->taskContexts.data + i; + if ( taskContext->splitIslandId != B3_NULL_INDEX && taskContext->splitSleepTime >= splitSleepTimer ) + { + B3_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; + } + } + + b3BitSet* awakeIslandBitSet = &world->taskContexts.data[0].awakeIslandBitSet; + for ( int i = 1; i < world->workerCount; ++i ) + { + b3InPlaceUnion( awakeIslandBitSet, &world->taskContexts.data[i].awakeIslandBitSet ); + } + + // Need to process in reverse because this moves islands to sleeping solver sets. + b3IslandSim* islands = awakeSet->islandSims.data; + int count = awakeSet->islandSims.count; + for ( int islandIndex = count - 1; islandIndex >= 0; islandIndex -= 1 ) + { + if ( b3GetBit( awakeIslandBitSet, islandIndex ) == true ) + { + // this island is still awake + continue; + } + + b3IslandSim* island = islands + islandIndex; + int islandId = island->islandId; + + b3TrySleepIsland( world, islandId ); + } + + b3ValidateSolverSets( world ); + + world->profile.sleepIslands = b3GetMilliseconds( sleepTicks ); + b3TracyCZoneEnd( sleep_islands ); + } +} diff --git a/src/solver.h b/src/solver.h new file mode 100644 index 0000000..db4c324 --- /dev/null +++ b/src/solver.h @@ -0,0 +1,315 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +// Solver work is partitioned into fixed-size blocks that worker threads claim +// in parallel via atomic CAS on a per-block syncIndex. The descriptor (b3SolverBlock) +// and the atomic counter sit in a wrapping b3SyncBlock so the CAS-winner can +// pass the descriptor by value into stage tasks without aliasing the atomic +// memory other threads are CAS-writing. Three properties of this design +// matter for performance: +// +// 1. Distributed contention. Per-block atomic syncIndex avoids the cache line stampede +// that a single shared fetch_add counter would cause. Once a worker +// settles into a block range, its CAS targets live in its own L1. +// +// 2. Monotonic syncIndex across iterations. Iterative stages (warm start, +// solve, relax) reuse the same block array every sub-step iteration. +// syncIndex grows each iteration; workers CAS (prev, prev+1), so the +// main thread never touches any per-block state between iterations. +// Non-iterative stages simply use syncIndex 1. +// +// 3. L2 affinity across iterations. Each worker picks a start offset from +// its workerIndex, then scans forward and (after wrap) backward: +// +// blocks: [0] [1] [2] [3] [4] [5] [6] [7] +// ^ ^ ^ ^ +// W0 W1 W2 W3 <- start offsets +// +// W0 claims 0,1,2,3 (forward), W1 claims 4,5, etc. Under balanced load +// each worker re-hits the same block range every iteration, keeping that +// range's hot data resident in its L2. A failed CAS means a neighbour +// already claimed the block, so the stealing worker stops -- preserving +// locality under mild imbalance while still draining the queue. +// +// A graph color stage lays out joint blocks first, then contact blocks: +// +// stage->blocks -> +// +------+------+------+------+------+------+------+ +// | J0 | J1 | J2 | C0 | C1 | C2 | C3 | +// +------+------+------+------+------+------+------+ +// <-- graphJointBlocks --><---- graphContactBlocks ----> +// +// Each block carries its type so the dispatcher routes J-blocks to the joint +// solver and C-blocks to the SIMD contact solver; both kinds run concurrently +// within the stage -- no barrier between them. The type tag lives on the +// block (not the stage) so that mixed-type stages can keep the concurrency. +// +// The solver threading model is inspired by https://github.com/bepu/bepuphysics2 + +#pragma once + +#include "container.h" +#include "core.h" + +#include "box3d/math_functions.h" + +#include + +typedef struct b3BodySim b3BodySim; +typedef struct b3BodyState b3BodyState; +typedef struct b3ContactConstraint b3ContactConstraint; +typedef struct b3ContactConstraintWide b3ContactConstraintWide; +typedef struct b3ContactSpec b3ContactSpec; +typedef struct b3JointSim b3JointSim; +typedef struct b3Manifold b3Manifold; +typedef struct b3ManifoldConstraint b3ManifoldConstraint; +typedef struct b3World b3World; + +// Solver stages +typedef enum b3SolverStageType +{ + b3_stagePrepareJoints, + b3_stagePrepareWideContacts, + b3_stagePrepareContacts, + b3_stageIntegrateVelocities, + b3_stageWarmStart, + b3_stageSolve, + b3_stageIntegratePositions, + b3_stageRelax, + b3_stageRestitution, + b3_stageStoreWideImpulses, + b3_stageStoreImpulses, +} b3SolverStageType; + +typedef enum b3SolverBlockType +{ + // Block for iterating across bodies. + b3_bodyBlock, + + // Block for iterating across joints. For prepare. + b3_jointBlock, + + // Block for iterating across wide contacts. For prepare and store. + b3_wideContactBlock, + + // Block for iterating across contacts. For prepare and store. + b3_contactBlock, + + // Block for iterating across joints of a single graph color. + b3_graphJointBlock, + + // Block for iterating across wide contacts of a single graph color. + b3_graphWideContactBlock, + + // Block for iterating across contacts of a single graph color. + b3_graphContactBlock, + + // Block for processing overflow constraints + b3_overflowBlock, +} b3SolverBlockType; + +// Solver block describes a multithreaded unit of work. +typedef struct b3SolverBlock +{ + int startIndex; + uint16_t count; + // b3SolverBlockType + uint8_t blockType; + uint8_t colorIndex; +} b3SolverBlock; + +// A unit of multithreaded work along with atomic synchronization. The syncIndex grows +// monotonically allowing the solver block to be re-used across sub-steps. +typedef struct b3SyncBlock +{ + b3SolverBlock block; + b3AtomicInt syncIndex; +} b3SyncBlock; + +// 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 b3SolverStage +{ + b3SyncBlock* blocks; + b3SolverStageType type; + int blockCount; + uint8_t colorIndex; + b3AtomicInt completionCount; +} b3SolverStage; + +// Constraint softness +typedef struct b3Softness +{ + float biasRate; + float massScale; + float impulseScale; +} b3Softness; + +// Prepare/store run as a flat parallel-for over the whole wide-constraint +// range. Each span maps a slice of that range back to the owning color's +// contacts so workers can decode flat wide-slot indices without touching +// graph state. The spans array has one entry per active color plus a sentinel +// whose start == wideContactCount. +typedef struct b3WidePrepareSpan +{ + int start; + int count; + int* contacts; +} b3WidePrepareSpan; + +typedef struct b3ContactPrepareSpan +{ + int start; + int count; + b3ContactSpec* contacts; +} b3ContactPrepareSpan; + +typedef struct b3JointPrepareSpan +{ + int start; + int count; + b3JointSim* joints; +} b3JointPrepareSpan; + +// Context for a time step. Recreated each time step. +typedef struct b3StepContext +{ + // time step + float dt; + + // inverse time step (0 if dt == 0). + float inv_dt; + + // sub-step + float h; + float inv_h; + + int subStepCount; + + b3Softness contactSoftness; + b3Softness staticSoftness; + + float restitutionThreshold; + float maxLinearVelocity; + + struct b3World* world; + struct b3ConstraintGraph* graph; + + // shortcut to body states from awake set + b3BodyState* states; + + // shortcut to body sims from awake set + b3BodySim* 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; + b3AtomicInt bulletBodyCount; + + // Contact ids for simplified parallel-for access. Used in narrow-phase. + // These contacts may or may not be touching. They are associated with awake bodies. + int* awakeContactIndices; + + // Flat view of the wide contact constraint array used by prepare and store. + // prepareSpans has activeColorCount + 1 entries, the last being a sentinel + // at wideContactCount. wideContactConstraints is the contiguous base + // pointer; per-color slices live at colors[i].wideConstraints. + struct b3ContactConstraintWide* wideConstraints; + b3WidePrepareSpan* widePrepareSpans; + int wideContactCount; + + // Similar for mesh/overflow contact constraints + struct b3ManifoldConstraint* manifoldConstraints; + struct b3ContactConstraint* contactConstraints; + b3ContactPrepareSpan* contactPrepareSpans; + b3ContactPrepareSpan* overflowSpans; + b3JointPrepareSpan* jointPrepareSpans; + + int activeColorCount; + int workerCount; + + b3SolverStage* stages; + int stageCount; + bool enableWarmStarting; + + // padding to prevent false sharing + char padding1[64]; + + // This atomic is central to multi-threaded solver task synchronization. + // It prevents ABA problems by monotonically growing as the solver advances. + // This means a delayed worker thread will catch up without repeating already completed + // work (causing a race condition). + // sync index (16-bits) | stage type (16-bits) + b3AtomicU32 atomicSyncBits; + + // padding to prevent false sharing + char padding2[64]; + + // Race flag claimed by whichever runner reaches b3SolverTask with workerIndex 0 first. + // The calling thread of b2World_Step also races for this slot so the orchestrator can + // always make progress, regardless of how the user's task system schedules tasks (out + // of order, fewer threads than workers, or synchronously inside enqueueTaskFcn). The + // loser of the race no-ops as workerIndex 0. + b3AtomicInt mainClaimed; + + // padding to prevent false sharing + char padding3[64]; +} b3StepContext; + +#ifdef __cplusplus +extern "C" +{ +#endif + +void b3Solve( b3World* world, b3StepContext* stepContext ); + +#ifdef __cplusplus +} +#endif + +B3_INLINE b3Softness b3MakeSoft( float hertz, float zeta, float h ) +{ + if ( hertz == 0.0f ) + { + return B3_LITERAL( b3Softness ){ + .biasRate = 0.0f, + .massScale = 0.0f, + .impulseScale = 0.0f, + }; + } + + float omega = 2.0f * B3_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 B3_LITERAL( b3Softness ){ + .biasRate = omega / a1, + .massScale = a2 * a3, + .impulseScale = a3, + }; +} diff --git a/src/solver_set.c b/src/solver_set.c new file mode 100644 index 0000000..f050a86 --- /dev/null +++ b/src/solver_set.c @@ -0,0 +1,633 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "solver_set.h" + +#include "body.h" +#include "constraint_graph.h" +#include "contact.h" +#include "island.h" +#include "joint.h" +#include "physics_world.h" + +#include + +void b3DestroySolverSet( b3World* world, int setIndex ) +{ + b3SolverSet* set = b3Array_Get( world->solverSets, setIndex ); + + b3Array_Destroy( set->bodySims ); + b3Array_Destroy( set->bodyStates ); + b3Array_Destroy( set->contactIndices ); + b3Array_Destroy( set->jointSims ); + b3Array_Destroy( set->islandSims ); + + b3FreeId( &world->solverSetIdPool, setIndex ); + *set = (b3SolverSet){ 0 }; + set->setIndex = B3_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 b3WakeSolverSet( b3World* world, int setIndex ) +{ + B3_ASSERT( setIndex >= b3_firstSleepingSet ); + b3SolverSet* set = b3Array_Get( world->solverSets, setIndex ); + b3SolverSet* awakeSet = b3Array_Get( world->solverSets, b3_awakeSet ); + b3SolverSet* disabledSet = b3Array_Get( world->solverSets, b3_disabledSet ); + + b3Body* bodies = world->bodies.data; + + int bodyCount = set->bodySims.count; + for ( int i = 0; i < bodyCount; ++i ) + { + b3BodySim* simSrc = set->bodySims.data + i; + + b3Body* body = bodies + simSrc->bodyId; + B3_ASSERT( body->setIndex == setIndex ); + body->setIndex = b3_awakeSet; + body->localIndex = awakeSet->bodySims.count; + + // Reset sleep timer + body->sleepTime = 0.0f; + + b3BodySim* simDst = b3Array_Emplace( awakeSet->bodySims ); + memcpy( simDst, simSrc, sizeof( b3BodySim ) ); + + b3BodyState* state = b3Array_Emplace( awakeSet->bodyStates ); + *state = b3_identityBodyState; + state->flags = body->flags; + + // move non-touching contacts from disabled set to awake set + int contactKey = body->headContactKey; + while ( contactKey != B3_NULL_INDEX ) + { + int edgeIndex = contactKey & 1; + int contactId = contactKey >> 1; + + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + contactKey = contact->edges[edgeIndex].nextKey; + + if ( contact->setIndex != b3_disabledSet ) + { + B3_ASSERT( contact->setIndex == b3_awakeSet || contact->setIndex == setIndex ); + continue; + } + + int localIndex = contact->localIndex; + + B3_ASSERT( 0 <= localIndex && localIndex < disabledSet->contactIndices.count ); + B3_ASSERT( disabledSet->contactIndices.data[localIndex] == contactId ); + + B3_ASSERT( ( contact->flags & b3_contactTouchingFlag ) == 0 && contact->manifoldCount == 0 ); + + contact->setIndex = b3_awakeSet; + contact->localIndex = awakeSet->contactIndices.count; + b3Array_Push( awakeSet->contactIndices, contactId ); + + int movedLocalIndex = b3Array_RemoveSwap( disabledSet->contactIndices, localIndex ); + if ( movedLocalIndex != B3_NULL_INDEX ) + { + // fix moved element + int movedContactIndex = disabledSet->contactIndices.data[localIndex]; + b3Contact* movedContact = b3Array_Get( world->contacts, movedContactIndex ); + B3_ASSERT( movedContact->localIndex == movedLocalIndex ); + movedContact->localIndex = localIndex; + } + } + } + + // Transfer touching contacts from sleeping set to constraint graph. + { + int contactCount = set->contactIndices.count; + for ( int i = 0; i < contactCount; ++i ) + { + int contactIndex = set->contactIndices.data[i]; + b3Contact* contact = b3Array_Get( world->contacts, contactIndex ); + B3_ASSERT( contact->flags & b3_contactTouchingFlag ); + B3_ASSERT( contact->flags & b3_simTouchingFlag ); + B3_ASSERT( contact->setIndex == setIndex ); + b3AddContactToGraph( world, contact ); + contact->setIndex = b3_awakeSet; + } + } + + // transfer joints from sleeping set to awake set + { + int jointCount = set->jointSims.count; + for ( int i = 0; i < jointCount; ++i ) + { + b3JointSim* jointSim = set->jointSims.data + i; + b3Joint* joint = b3Array_Get( world->joints, jointSim->jointId ); + B3_ASSERT( joint->setIndex == setIndex ); + b3AddJointToGraph( world, jointSim, joint ); + joint->setIndex = b3_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 ) + { + b3IslandSim* islandSrc = set->islandSims.data + i; + b3Island* island = b3Array_Get( world->islands, islandSrc->islandId ); + island->setIndex = b3_awakeSet; + island->localIndex = awakeSet->islandSims.count; + b3IslandSim* islandDst = b3Array_Emplace( awakeSet->islandSims ); + memcpy( islandDst, islandSrc, sizeof( b3IslandSim ) ); + } + } + + // destroy the sleeping set + b3DestroySolverSet( world, setIndex ); +} + +void b3TrySleepIsland( b3World* world, int islandId ) +{ + b3Island* island = b3Array_Get( world->islands, islandId ); + B3_ASSERT( island->setIndex == b3_awakeSet ); + + // Cannot put an island to sleep while it has a pending split and more than one body. + if ( island->constraintRemoveCount > 0 && island->bodies.count > 1 ) + { + 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 = b3AllocId( &world->solverSetIdPool ); + if ( sleepSetId == world->solverSets.count ) + { + b3SolverSet set = { 0 }; + set.setIndex = B3_NULL_INDEX; + b3Array_Push( world->solverSets, set ); + } + + b3SolverSet* sleepSet = b3Array_Get( world->solverSets, sleepSetId ); + *sleepSet = (b3SolverSet){ 0 }; + + // grab awake set after creating the sleep set because the solver set array may have been resized + b3SolverSet* awakeSet = b3Array_Get( world->solverSets, b3_awakeSet ); + b3SolverSet* disabledSet = b3Array_Get( world->solverSets, b3_disabledSet ); + B3_ASSERT( 0 <= island->localIndex && island->localIndex < awakeSet->islandSims.count ); + + sleepSet->setIndex = sleepSetId; + b3Array_Reserve( sleepSet->bodySims, island->bodies.count ); + b3Array_Reserve( sleepSet->contactIndices, island->contacts.count ); + b3Array_Reserve( sleepSet->jointSims, island->joints.count ); + + // move awake bodies to sleeping set + // this shuffles around bodies in the awake set + { + for ( int i = 0; i < island->bodies.count; ++i ) + { + int bodyId = island->bodies.data[i]; + b3Body* body = b3Array_Get( world->bodies, bodyId ); + B3_ASSERT( body->setIndex == b3_awakeSet ); + B3_ASSERT( body->islandId == islandId ); + B3_ASSERT( body->islandIndex == i ); + + // 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 != B3_NULL_INDEX ) + { + b3BodyMoveEvent* moveEvent = b3Array_Get( world->bodyMoveEvents, body->bodyMoveIndex ); + B3_ASSERT( moveEvent->bodyId.index1 - 1 == bodyId ); + B3_ASSERT( moveEvent->bodyId.generation == body->generation ); + moveEvent->fellAsleep = true; + body->bodyMoveIndex = B3_NULL_INDEX; + } + + int awakeBodyIndex = body->localIndex; + b3BodySim* awakeSim = b3Array_Get( awakeSet->bodySims, awakeBodyIndex ); + + // move body sim to sleep set + int sleepBodyIndex = sleepSet->bodySims.count; + b3BodySim* sleepBodySim = b3Array_Emplace( sleepSet->bodySims ); + memcpy( sleepBodySim, awakeSim, sizeof( b3BodySim ) ); + + int movedIndex = b3Array_RemoveSwap( awakeSet->bodySims, awakeBodyIndex ); + if ( movedIndex != B3_NULL_INDEX ) + { + // fix local index on moved element + b3BodySim* movedSim = awakeSet->bodySims.data + awakeBodyIndex; + int movedId = movedSim->bodyId; + b3Body* movedBody = b3Array_Get( world->bodies, movedId ); + B3_ASSERT( movedBody->localIndex == movedIndex ); + movedBody->localIndex = awakeBodyIndex; + } + + // destroy state, no need to clone + b3Array_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 != B3_NULL_INDEX ) + { + int contactId = contactKey >> 1; + int edgeIndex = contactKey & 1; + + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + + B3_ASSERT( contact->setIndex == b3_awakeSet || contact->setIndex == b3_disabledSet ); + contactKey = contact->edges[edgeIndex].nextKey; + + if ( contact->setIndex == b3_disabledSet ) + { + // already moved to disabled set by another body in the island + continue; + } + + if ( contact->colorIndex != B3_NULL_INDEX ) + { + // contact is touching and will be moved separately + B3_ASSERT( ( contact->flags & b3_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; + b3Body* otherBody = b3Array_Get( world->bodies, otherBodyId ); + if ( otherBody->setIndex == b3_awakeSet ) + { + continue; + } + + int localIndex = contact->localIndex; + B3_ASSERT( awakeSet->contactIndices.data[localIndex] == contactId ); + + B3_ASSERT( contact->manifoldCount == 0 ); + B3_ASSERT( ( contact->flags & b3_contactTouchingFlag ) == 0 ); + + // Move the non-touching contact to the disabled set. + contact->setIndex = b3_disabledSet; + + // This is mandatory for validation to work correctly + contact->localIndex = disabledSet->contactIndices.count; + b3Array_Push( disabledSet->contactIndices, contact->contactId ); + + int movedLocalIndex = b3Array_RemoveSwap( awakeSet->contactIndices, localIndex ); + if ( movedLocalIndex != B3_NULL_INDEX ) + { + // fix moved element + int movedContactIndex = awakeSet->contactIndices.data[localIndex]; + b3Contact* movedContact = b3Array_Get( world->contacts, movedContactIndex ); + B3_ASSERT( movedContact->localIndex == movedLocalIndex ); + movedContact->localIndex = localIndex; + } + } + } + } + + // move touching contacts to sleeping set + // this shuffles contacts in the awake set + { + for ( int i = 0; i < island->contacts.count; ++i ) + { + int contactId = island->contacts.data[i].contactId; + b3Contact* contact = b3Array_Get( world->contacts, contactId ); + B3_ASSERT( contact->setIndex == b3_awakeSet ); + B3_ASSERT( contact->islandId == islandId ); + B3_ASSERT( contact->islandIndex == i ); + int colorIndex = contact->colorIndex; + B3_ASSERT( 0 <= colorIndex && colorIndex < B3_GRAPH_COLOR_COUNT ); + + b3GraphColor* color = world->constraintGraph.colors + colorIndex; + + // Remove bodies from graph coloring associated with this constraint + if ( colorIndex != B3_OVERFLOW_INDEX ) + { + // might clear a bit for a static body, but this has no effect + b3ClearBit( &color->bodySet, contact->edges[0].bodyId ); + b3ClearBit( &color->bodySet, contact->edges[1].bodyId ); + } + + int sleepContactIndex = sleepSet->contactIndices.count; + b3Array_Push( sleepSet->contactIndices, contactId ); + + int localIndex = contact->localIndex; + if ( ( contact->flags & b3_simMeshContact ) || colorIndex == B3_OVERFLOW_INDEX ) + { + int movedLocalIndex = b3Array_RemoveSwap( color->contacts, localIndex ); + if ( movedLocalIndex != B3_NULL_INDEX ) + { + // fix moved element + int movedContactId = color->contacts.data[localIndex].contactId; + b3Contact* movedContact = b3Array_Get( world->contacts, movedContactId ); + B3_ASSERT( movedContact->localIndex == movedLocalIndex ); + movedContact->localIndex = localIndex; + } + } + else + { + int movedLocalIndex = b3Array_RemoveSwap( color->convexContacts, localIndex ); + if ( movedLocalIndex != B3_NULL_INDEX ) + { + // fix moved element + int movedContactId = color->convexContacts.data[localIndex]; + b3Contact* movedContact = b3Array_Get( world->contacts, movedContactId ); + B3_ASSERT( movedContact->localIndex == movedLocalIndex ); + movedContact->localIndex = localIndex; + } + } + + contact->setIndex = sleepSetId; + contact->colorIndex = B3_NULL_INDEX; + contact->localIndex = sleepContactIndex; + } + } + + // move joints + // this shuffles joints in the awake set + { + for ( int i = 0; i < island->joints.count; ++i ) + { + int jointId = island->joints.data[i].jointId; + b3Joint* joint = b3Array_Get( world->joints, jointId ); + B3_ASSERT( joint->setIndex == b3_awakeSet ); + B3_ASSERT( joint->islandId == islandId ); + B3_ASSERT( joint->islandIndex == i ); + int colorIndex = joint->colorIndex; + int localIndex = joint->localIndex; + + B3_ASSERT( 0 <= colorIndex && colorIndex < B3_GRAPH_COLOR_COUNT ); + + b3GraphColor* color = world->constraintGraph.colors + colorIndex; + + b3JointSim* awakeJointSim = b3Array_Get( color->jointSims, localIndex ); + + if ( colorIndex != B3_OVERFLOW_INDEX ) + { + // might clear a bit for a static body, but this has no effect + b3ClearBit( &color->bodySet, joint->edges[0].bodyId ); + b3ClearBit( &color->bodySet, joint->edges[1].bodyId ); + } + + int sleepJointIndex = sleepSet->jointSims.count; + b3JointSim* sleepJointSim = b3Array_Emplace( sleepSet->jointSims ); + memcpy( sleepJointSim, awakeJointSim, sizeof( b3JointSim ) ); + + int movedIndex = b3Array_RemoveSwap( color->jointSims, localIndex ); + if ( movedIndex != B3_NULL_INDEX ) + { + // fix moved element + b3JointSim* movedJointSim = color->jointSims.data + localIndex; + int movedId = movedJointSim->jointId; + b3Joint* movedJoint = b3Array_Get( world->joints, movedId ); + B3_ASSERT( movedJoint->localIndex == movedIndex ); + movedJoint->localIndex = localIndex; + } + + joint->setIndex = sleepSetId; + joint->colorIndex = B3_NULL_INDEX; + joint->localIndex = sleepJointIndex; + } + } + + // move island struct + { + B3_ASSERT( island->setIndex == b3_awakeSet ); + + int islandIndex = island->localIndex; + b3IslandSim* sleepIsland = b3Array_Emplace( sleepSet->islandSims ); + sleepIsland->islandId = islandId; + + int movedIslandIndex = b3Array_RemoveSwap( awakeSet->islandSims, islandIndex ); + if ( movedIslandIndex != B3_NULL_INDEX ) + { + // fix index on moved element + b3IslandSim* movedIslandSim = awakeSet->islandSims.data + islandIndex; + int movedIslandId = movedIslandSim->islandId; + b3Island* movedIsland = b3Array_Get( world->islands, movedIslandId ); + B3_ASSERT( movedIsland->localIndex == movedIslandIndex ); + movedIsland->localIndex = islandIndex; + } + + island->setIndex = sleepSetId; + island->localIndex = 0; + } + + if ( world->splitIslandId == islandId ) + { + world->splitIslandId = B3_NULL_INDEX; + } + + b3ValidateSolverSets( 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 woke. +void b3MergeSolverSets( b3World* world, int setId1, int setId2 ) +{ + B3_ASSERT( setId1 >= b3_firstSleepingSet ); + B3_ASSERT( setId2 >= b3_firstSleepingSet ); + b3SolverSet* set1 = b3Array_Get( world->solverSets, setId1 ); + b3SolverSet* set2 = b3Array_Get( world->solverSets, setId2 ); + + // Move the fewest number of bodies + if ( set1->bodySims.count < set2->bodySims.count ) + { + b3SolverSet* tempSet = set1; + set1 = set2; + set2 = tempSet; + + int tempId = setId1; + setId1 = setId2; + setId2 = tempId; + } + + // transfer bodies + { + b3Body* bodies = world->bodies.data; + int bodyCount = set2->bodySims.count; + for ( int i = 0; i < bodyCount; ++i ) + { + b3BodySim* simSrc = set2->bodySims.data + i; + + b3Body* body = bodies + simSrc->bodyId; + B3_ASSERT( body->setIndex == setId2 ); + body->setIndex = setId1; + body->localIndex = set1->bodySims.count; + + b3BodySim* simDst = b3Array_Emplace( set1->bodySims ); + memcpy( simDst, simSrc, sizeof( b3BodySim ) ); + } + } + + // transfer contacts + { + int contactCount = set2->contactIndices.count; + for ( int i = 0; i < contactCount; ++i ) + { + int contactIndex = set2->contactIndices.data[i]; + b3Contact* contact = b3Array_Get( world->contacts, contactIndex ); + B3_ASSERT( contact->setIndex == setId2 ); + contact->setIndex = setId1; + contact->localIndex = set1->contactIndices.count; + b3Array_Push( set1->contactIndices, contactIndex ); + } + } + + // transfer joints + { + int jointCount = set2->jointSims.count; + for ( int i = 0; i < jointCount; ++i ) + { + b3JointSim* jointSrc = set2->jointSims.data + i; + + b3Joint* joint = b3Array_Get( world->joints, jointSrc->jointId ); + B3_ASSERT( joint->setIndex == setId2 ); + joint->setIndex = setId1; + joint->localIndex = set1->jointSims.count; + + b3JointSim* jointDst = b3Array_Emplace( set1->jointSims ); + memcpy( jointDst, jointSrc, sizeof( b3JointSim ) ); + } + } + + // transfer islands + { + int islandCount = set2->islandSims.count; + for ( int i = 0; i < islandCount; ++i ) + { + b3IslandSim* islandSrc = set2->islandSims.data + i; + int islandId = islandSrc->islandId; + + b3Island* island = b3Array_Get( world->islands, islandId ); + island->setIndex = setId1; + island->localIndex = set1->islandSims.count; + + b3IslandSim* islandDst = b3Array_Emplace( set1->islandSims ); + memcpy( islandDst, islandSrc, sizeof( b3IslandSim ) ); + } + } + + // destroy the merged set + // Warning: need to be careful not to destroy things that got transferred, like triangle caches. + b3DestroySolverSet( world, setId2 ); + + b3ValidateSolverSets( world ); +} + +void b3TransferBody( b3World* world, b3SolverSet* targetSet, b3SolverSet* sourceSet, b3Body* body ) +{ + if ( targetSet == sourceSet ) + { + return; + } + + int sourceIndex = body->localIndex; + b3BodySim* sourceSim = b3Array_Get( sourceSet->bodySims, sourceIndex ); + + int targetIndex = targetSet->bodySims.count; + b3BodySim* targetSim = b3Array_Emplace( targetSet->bodySims ); + memcpy( targetSim, sourceSim, sizeof( b3BodySim ) ); + + // Clear transient body flags + targetSim->flags &= ~( b3_isFast | b3_isSpeedCapped | b3_hadTimeOfImpact ); + + // Remove body sim from solver set that owns it + int movedIndex = b3Array_RemoveSwap( sourceSet->bodySims, sourceIndex ); + if ( movedIndex != B3_NULL_INDEX ) + { + // Fix moved body index + b3BodySim* movedSim = sourceSet->bodySims.data + sourceIndex; + int movedId = movedSim->bodyId; + b3Body* movedBody = b3Array_Get( world->bodies, movedId ); + B3_ASSERT( movedBody->localIndex == movedIndex ); + movedBody->localIndex = sourceIndex; + } + + if ( sourceSet->setIndex == b3_awakeSet ) + { + b3Array_RemoveSwap( sourceSet->bodyStates, sourceIndex ); + } + else if ( targetSet->setIndex == b3_awakeSet ) + { + b3BodyState* state = b3Array_Emplace( targetSet->bodyStates ); + *state = b3_identityBodyState; + state->flags = body->flags; + } + + body->setIndex = targetSet->setIndex; + body->localIndex = targetIndex; +} + +void b3TransferJoint( b3World* world, b3SolverSet* targetSet, b3SolverSet* sourceSet, b3Joint* joint ) +{ + if ( targetSet == sourceSet ) + { + return; + } + + int localIndex = joint->localIndex; + int colorIndex = joint->colorIndex; + + // Retrieve source. + b3JointSim* sourceSim; + if ( sourceSet->setIndex == b3_awakeSet ) + { + B3_ASSERT( 0 <= colorIndex && colorIndex < B3_GRAPH_COLOR_COUNT ); + b3GraphColor* color = world->constraintGraph.colors + colorIndex; + + sourceSim = b3Array_Get( color->jointSims, localIndex ); + } + else + { + B3_ASSERT( colorIndex == B3_NULL_INDEX ); + sourceSim = b3Array_Get( sourceSet->jointSims, localIndex ); + } + + // Create target and copy. Fix joint. + if ( targetSet->setIndex == b3_awakeSet ) + { + b3AddJointToGraph( world, sourceSim, joint ); + joint->setIndex = b3_awakeSet; + } + else + { + joint->setIndex = targetSet->setIndex; + joint->localIndex = targetSet->jointSims.count; + joint->colorIndex = B3_NULL_INDEX; + + b3JointSim* targetSim = b3Array_Emplace( targetSet->jointSims ); + memcpy( targetSim, sourceSim, sizeof( b3JointSim ) ); + } + + // Destroy source. + if ( sourceSet->setIndex == b3_awakeSet ) + { + b3RemoveJointFromGraph( world, joint->edges[0].bodyId, joint->edges[1].bodyId, colorIndex, localIndex ); + } + else + { + int movedIndex = b3Array_RemoveSwap( sourceSet->jointSims, localIndex ); + if ( movedIndex != B3_NULL_INDEX ) + { + // fix swapped element + b3JointSim* movedJointSim = sourceSet->jointSims.data + localIndex; + int movedId = movedJointSim->jointId; + b3Joint* movedJoint = b3Array_Get( world->joints, movedId ); + movedJoint->localIndex = localIndex; + } + } +} diff --git a/src/solver_set.h b/src/solver_set.h new file mode 100644 index 0000000..b916fcc --- /dev/null +++ b/src/solver_set.h @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "container.h" +#include "contact.h" + +typedef struct b3Body b3Body; +typedef struct b3BodySim b3BodySim; +typedef struct b3BodyState b3BodyState; +typedef struct b3IslandSim b3IslandSim; +typedef struct b3Joint b3Joint; +typedef struct b3JointSim b3JointSim; +typedef struct b3World b3World; + +b3DeclareArray( b3BodySim ); +b3DeclareArray( b3BodyState ); +b3DeclareArray( b3JointSim ); +b3DeclareArray( b3IslandSim ); + +// 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 b3SolverSet +{ + // Body array. Empty for unused set. + b3ArrayC( b3BodySim ) bodySims; + + // Body state only exists for active set + b3ArrayC( b3BodyState ) bodyStates; + + // This holds sleeping/disabled joints. Empty for static/active set. + b3ArrayC( b3JointSim ) jointSims; + + // This holds all contacts for sleeping sets. + // This holds non-touching contacts for the awake set. + // This should be empty for the static and disabled sets. + b3ArrayC( int ) contactIndices; + + // 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. + b3ArrayC( b3IslandSim ) islandSims; + + // Aligns with b3World::solverSetIdPool. Used to create a stable id for body/contact/joint/islands. + int setIndex; +} b3SolverSet; + +#ifdef __cplusplus +extern "C" +{ +#endif + +void b3DestroySolverSet( b3World* world, int setIndex ); + +void b3WakeSolverSet( b3World* world, int setIndex ); +void b3TrySleepIsland( b3World* world, int islandId ); + +// Merge set 2 into set 1 then destroy set 2. +// Warning: any pointers into these sets will be orphaned. +void b3MergeSolverSets( b3World* world, int setIndex1, int setIndex2 ); + +void b3TransferBody( b3World* world, b3SolverSet* targetSet, b3SolverSet* sourceSet, b3Body* body ); +void b3TransferJoint( b3World* world, b3SolverSet* targetSet, b3SolverSet* sourceSet, b3Joint* joint ); + +#ifdef __cplusplus +} +#endif diff --git a/src/sphere.c b/src/sphere.c new file mode 100644 index 0000000..5b659ef --- /dev/null +++ b/src/sphere.c @@ -0,0 +1,241 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +// Dirk Gregorius contributed portions of this code + +#include "math_internal.h" +#include "shape.h" + +#include "box3d/base.h" +#include "box3d/collision.h" +#include "box3d/constants.h" + +b3MassData b3ComputeSphereMass( const b3Sphere* shape, float density ) +{ + b3Vec3 center = shape->center; + float radius = shape->radius; + + float volume = 4.0f / 3.0f * B3_PI * radius * radius * radius; + float mass = volume * density; + float ixx = 0.4f * mass * radius * radius; + + b3MassData out; + out.mass = mass; + out.center = center; + out.inertia = b3AddMM( b3MakeDiagonalMatrix( ixx, ixx, ixx ), b3Steiner( mass, center ) ); + return out; +} + +b3AABB b3ComputeSphereAABB( const b3Sphere* shape, b3Transform transform ) +{ + b3Vec3 center = b3TransformPoint( transform, shape->center ); + float radius = shape->radius; + b3Vec3 extent = { radius, radius, radius }; + return ( b3AABB ){ b3Sub( center, extent ), b3Add( center, extent ) }; +} + +b3AABB b3ComputeSweptSphereAABB( const b3Sphere* shape, b3Transform xf1, b3Transform xf2 ) +{ + b3Vec3 r = { shape->radius, shape->radius, shape->radius }; + b3Vec3 center1 = b3TransformPoint( xf1, shape->center ); + b3Vec3 center2 = b3TransformPoint( xf2, shape->center ); + return ( b3AABB ){ b3Sub( b3Min( center1, center2 ), r ), b3Add( b3Max( center1, center2 ), r ) }; +} + +bool b3OverlapSphere( const b3Sphere* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy ) +{ + b3DistanceInput input; + input.proxyA = ( b3ShapeProxy ){ &shape->center, 1, shape->radius }; + input.proxyB = *proxy; + input.transformA = shapeTransform; + input.transformB = b3Transform_identity; + input.useRadii = true; + + b3SimplexCache cache = { 0 }; + b3DistanceOutput output = b3ShapeDistance( &input, &cache, NULL, 0 ); + return output.distance < B3_OVERLAP_SLOP; +} + +// Precision Improvements for Ray / Sphere Intersection - Ray Tracing Gems 2019 +// http://www.codercorner.com/blog/?p=321 +b3CastOutput b3RayCastSphere(const b3Sphere* shape, const b3RayCastInput* input ) +{ + B3_ASSERT( b3IsValidRay( input ) ); + b3CastOutput output = { 0 }; + + b3Vec3 p = shape->center; + + // Shift ray so sphere center is the origin + b3Vec3 s = b3Sub( input->origin, p ); + + float r = shape->radius; + float rr = r * r; + + float length; + b3Vec3 d = b3GetLengthAndNormalize( &length, input->translation ); + if ( length == 0.0f ) + { + // zero length ray + + if ( b3LengthSquared( 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 = -b3Dot( s, d ); + + // c is the closest point on the line to the origin + b3Vec3 c = b3MulAdd( s, t, d ); + + float cc = b3Dot( c, c ); + + if ( cc > rr ) + { + // closest point is outside the sphere + 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 ( b3LengthSquared( s ) < rr ) + { + // initial overlap + output.point = input->origin; + output.hit = true; + } + + return output; + } + + b3Vec3 hitPoint = b3MulAdd( s, fraction, d ); + + output.fraction = fraction / length; + + if ( output.fraction > input->maxFraction ) + { + b3Log( "sphere input fraction = %g, output fraction = %g", input->maxFraction, output.fraction ); + output.fraction = input->maxFraction; + } + + output.normal = b3Normalize( hitPoint ); + output.point = b3MulAdd( p, shape->radius, output.normal ); + output.hit = true; + + return output; +} + +// Precision Improvements for Ray / Sphere Intersection - Ray Tracing Gems 2019 +// http://www.codercorner.com/blog/?p=321 +// This will do interior hits. +b3CastOutput b3RayCastHollowSphere( const b3Sphere* sphere, const b3RayCastInput* input ) +{ + b3Vec3 p = sphere->center; + + b3CastOutput output = { 0 }; + + // Shift ray so sphere center is the origin + b3Vec3 s = b3Sub( input->origin, p ); + b3Vec3 d = b3Normalize( input->translation ); + + // Find closest point on ray to origin + + // solve: dot(s + t * d, d) = 0 + float t = -b3Dot( s, d ); + + // c is the closest point on the line to the origin + b3Vec3 c = b3MulAdd( s, t, d ); + + float cc = b3Dot( c, c ); + float r = sphere->radius; + float rr = r * r; + + if ( cc > rr ) + { + // closest point is outside the sphere + return output; + } + + // Pythagoras + float h = sqrtf( rr - cc ); + + float fraction = t - h; + + if ( fraction < 0.0f ) + { + fraction = t + h; + } + + if ( fraction < 0.0f ) + { + // behind the ray + return output; + } + + if (fraction > input->maxFraction) + { + return output; + } + + b3Vec3 hitPoint = b3MulAdd( s, fraction, d ); + + output.fraction = fraction; + output.normal = b3Normalize( hitPoint ); + output.point = b3MulAdd( p, sphere->radius, output.normal ); + output.hit = true; + + return output; +} + +b3CastOutput b3ShapeCastSphere( const b3Sphere* sphere, const b3ShapeCastInput* input ) +{ + b3ShapeCastPairInput pairInput; + pairInput.proxyA = ( b3ShapeProxy ){ &sphere->center, 1, sphere->radius }; + pairInput.proxyB = input->proxy; + pairInput.transformA = b3Transform_identity; + pairInput.transformB = b3Transform_identity; + pairInput.translationB = input->translation; + pairInput.maxFraction = input->maxFraction; + pairInput.canEncroach = input->canEncroach; + + b3CastOutput output = b3ShapeCast( &pairInput ); + return output; +} + +int b3CollideMoverAndSphere( b3PlaneResult* result, const b3Sphere* shape, const b3Capsule* mover ) +{ + b3DistanceInput distanceInput; + distanceInput.proxyA = ( b3ShapeProxy ){ &shape->center, 1, 0.0f }; + distanceInput.proxyB = ( b3ShapeProxy ){ &mover->center1, 2, mover->radius }; + distanceInput.transformA = b3Transform_identity; + distanceInput.transformB = b3Transform_identity; + distanceInput.useRadii = false; + + float totalRadius = mover->radius + shape->radius; + + b3SimplexCache cache = { 0 }; + b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, &cache, NULL, 0 ); + + if ( distanceOutput.distance <= totalRadius ) + { + b3Plane plane = { distanceOutput.normal, totalRadius - distanceOutput.distance }; + *result = ( b3PlaneResult ){ plane, distanceOutput.pointA }; + return 1; + } + + return 0; +} diff --git a/src/spherical_joint.c b/src/spherical_joint.c new file mode 100644 index 0000000..8442101 --- /dev/null +++ b/src/spherical_joint.c @@ -0,0 +1,717 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "body.h" +#include "core.h" +#include "joint.h" +#include "math_internal.h" +#include "physics_world.h" +#include "solver.h" +#include "solver_set.h" + +// needed for dll export +#include "box3d/box3d.h" + +void b3SphericalJoint_EnableConeLimit( b3JointId jointId, bool enableLimit ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + if ( enableLimit != base->sphericalJoint.enableConeLimit ) + { + base->sphericalJoint.swingImpulse = 0.0f; + } + base->sphericalJoint.enableConeLimit = enableLimit; +} + +bool b3SphericalJoint_IsConeLimitEnabled( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + return base->sphericalJoint.enableConeLimit; +} + +float b3SphericalJoint_GetConeLimit( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + return base->sphericalJoint.coneAngle; +} + +void b3SphericalJoint_SetConeLimit( b3JointId jointId, float angleRadians ) +{ + B3_ASSERT( b3IsValidFloat( angleRadians ) && 0 <= angleRadians && angleRadians <= 0.5f * B3_PI ); + + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + base->sphericalJoint.coneAngle = angleRadians; +} + +float b3SphericalJoint_GetConeAngle( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA ); + b3Transform transformB = b3GetBodyTransform( world, base->bodyIdB ); + + b3Quat quatA = b3MulQuat( transformA.q, base->localFrameA.q ); + b3Quat quatB = b3MulQuat( transformB.q, base->localFrameB.q ); + + if ( b3DotQuat( quatA, quatB ) < 0.0f ) + { + // this keeps the swing angle in the range [0, pi] + quatB = b3NegateQuat( quatB ); + } + + b3Quat relQ = b3InvMulQuat( quatA, quatB ); + + return b3GetSwingAngle( relQ ); +} + +void b3SphericalJoint_EnableTwistLimit( b3JointId jointId, bool enableLimit ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + if ( enableLimit != base->sphericalJoint.enableTwistLimit ) + { + base->sphericalJoint.lowerTwistImpulse = 0.0f; + base->sphericalJoint.upperTwistImpulse = 0.0f; + } + base->sphericalJoint.enableTwistLimit = enableLimit; +} + +bool b3SphericalJoint_IsTwistLimitEnabled( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + return base->sphericalJoint.enableTwistLimit; +} + +float b3SphericalJoint_GetLowerTwistLimit( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + return base->sphericalJoint.lowerTwistAngle; +} + +float b3SphericalJoint_GetUpperTwistLimit( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + return base->sphericalJoint.upperTwistAngle; +} + +void b3SphericalJoint_SetTwistLimits( b3JointId jointId, float lowerLimitRadians, float upperLimitRadians ) +{ + B3_ASSERT( b3IsValidFloat( lowerLimitRadians ) && b3IsValidFloat( upperLimitRadians ) ); + float lowerTwistAngle = b3MinFloat( lowerLimitRadians, upperLimitRadians ); + float upperTwistAngle = b3MaxFloat( lowerLimitRadians, upperLimitRadians ); + lowerTwistAngle = b3ClampFloat( lowerTwistAngle, -B3_PI, B3_PI ); + upperTwistAngle = b3ClampFloat( upperTwistAngle, -B3_PI, B3_PI ); + + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + base->sphericalJoint.lowerTwistAngle = lowerTwistAngle; + base->sphericalJoint.upperTwistAngle = upperTwistAngle; +} + +float b3SphericalJoint_GetTwistAngle( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA ); + b3Transform transformB = b3GetBodyTransform( world, base->bodyIdB ); + + b3Quat quatA = b3MulQuat( transformA.q, base->localFrameA.q ); + b3Quat quatB = b3MulQuat( transformB.q, base->localFrameB.q ); + + if ( b3DotQuat( quatA, quatB ) < 0.0f ) + { + // this keeps the twist angle in the range [-pi, pi] + quatB = b3NegateQuat( quatB ); + } + + b3Quat relQ = b3InvMulQuat( quatA, quatB ); + + return b3GetTwistAngle( relQ ); +} + +void b3SphericalJoint_EnableSpring( b3JointId jointId, bool enableSpring ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + if ( enableSpring != base->sphericalJoint.enableSpring ) + { + base->sphericalJoint.springImpulse = b3Vec3_zero; + } + base->sphericalJoint.enableSpring = enableSpring; +} + +bool b3SphericalJoint_IsSpringEnabled( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + return base->sphericalJoint.enableSpring; +} + +void b3SphericalJoint_SetTargetRotation( b3JointId jointId, b3Quat targetRotation ) +{ + B3_ASSERT( b3IsValidQuat( targetRotation ) ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + base->sphericalJoint.targetRotation = targetRotation; +} + +b3Quat b3SphericalJoint_GetTargetRotation( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + return base->sphericalJoint.targetRotation; +} + +void b3SphericalJoint_SetSpringHertz( b3JointId jointId, float hertz ) +{ + B3_ASSERT( b3IsValidFloat( hertz ) && hertz >= 0.0f ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + base->sphericalJoint.hertz = hertz; +} + +float b3SphericalJoint_GetSpringHertz( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + return base->sphericalJoint.hertz; +} + +void b3SphericalJoint_SetSpringDampingRatio( b3JointId jointId, float dampingRatio ) +{ + B3_ASSERT( b3IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + base->sphericalJoint.dampingRatio = dampingRatio; +} + +float b3SphericalJoint_GetSpringDampingRatio( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + return base->sphericalJoint.dampingRatio; +} + +void b3SphericalJoint_EnableMotor( b3JointId jointId, bool enableMotor ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + if ( enableMotor != base->sphericalJoint.enableMotor ) + { + base->sphericalJoint.motorImpulse = b3Vec3_zero; + } + base->sphericalJoint.enableMotor = enableMotor; +} + +bool b3SphericalJoint_IsMotorEnabled( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + return base->sphericalJoint.enableMotor; +} + +void b3SphericalJoint_SetMotorVelocity( b3JointId jointId, b3Vec3 motorVelocity ) +{ + B3_ASSERT( b3IsValidVec3( motorVelocity ) ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + base->sphericalJoint.motorVelocity = motorVelocity; +} + +b3Vec3 b3SphericalJoint_GetMotorVelocity( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + return base->sphericalJoint.motorVelocity; +} + +void b3SphericalJoint_SetMaxMotorTorque( b3JointId jointId, float maxForce ) +{ + B3_ASSERT( b3IsValidFloat( maxForce ) && maxForce >= 0.0f ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + base->sphericalJoint.maxMotorTorque = maxForce; +} + +float b3SphericalJoint_GetMaxMotorTorque( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint ); + return base->sphericalJoint.maxMotorTorque; +} + +b3Vec3 b3GetSphericalJointForce( b3World* world, b3JointSim* base ) +{ + b3Vec3 force = b3MulSV( world->inv_h, base->sphericalJoint.linearImpulse ); + return force; +} + +b3Vec3 b3GetSphericalJointTorque( b3World* world, b3JointSim* base ) +{ + b3Transform xfA = b3GetBodyTransform( world, base->bodyIdA ); + b3Transform xfB = b3GetBodyTransform( world, base->bodyIdB ); + b3Quat qA = b3MulQuat( xfA.q, base->localFrameA.q ); + b3Quat qB = b3MulQuat( xfB.q, base->localFrameB.q ); + + // Cone axis is the z-axis of body A. + b3Vec3 coneAxis = b3RotateVector( qA, b3Vec3_axisZ ); + b3Vec3 twistAxis = b3RotateVector( qB, b3Vec3_axisZ ); + b3Vec3 swingAxis = b3Normalize( b3Cross( coneAxis, twistAxis ) ); + + b3SphericalJoint* joint = &base->sphericalJoint; + b3Vec3 impulse = b3Add( joint->springImpulse, joint->motorImpulse ); + impulse = b3MulAdd( impulse, joint->lowerTwistImpulse - joint->upperTwistImpulse, twistAxis ); + impulse = b3MulAdd( impulse, joint->swingImpulse, swingAxis ); + b3Vec3 torque = b3MulSV( world->inv_h, impulse ); + return torque; +} + +// 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 ] +// K = J * invM * transpose(J) +// transpose(skew(r)) = -skew(r) +// K = diag(1/m1 + 1/m2) - r1_skew * invI1 * r1_skew - r2_skew * invI2 * r2_skew + +// r_skew = R * skew(r_local) * RT +// invI = R * invI_local * RT +// r_skew * invI * r_skew = R * skew(r_local) * RT * R * invI_local * RT * R * r_skew * RT +// = R * ( skew(r_local) * invI_local * skew(r_local) ) * RT + +void b3PrepareSphericalJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_sphericalJoint ); + + b3World* world = context->world; + + b3Body* bodyA = b3Array_Get( world->bodies, base->bodyIdA ); + b3Body* bodyB = b3Array_Get( world->bodies, base->bodyIdB ); + + B3_ASSERT( bodyA->setIndex == b3_awakeSet || bodyB->setIndex == b3_awakeSet ); + b3SolverSet* setA = b3Array_Get( world->solverSets, bodyA->setIndex ); + b3SolverSet* setB = b3Array_Get( world->solverSets, bodyB->setIndex ); + + int localIndexA = bodyA->localIndex; + int localIndexB = bodyB->localIndex; + + b3BodySim* bodySimA = b3Array_Get( setA->bodySims, localIndexA ); + b3BodySim* bodySimB = b3Array_Get( setB->bodySims, localIndexB ); + + base->invMassA = bodySimA->invMass; + base->invMassB = bodySimB->invMass; + base->invIA = bodySimA->invInertiaWorld; + base->invIB = bodySimB->invInertiaWorld; + + b3Matrix3 invInertiaSum = b3AddMM( base->invIA, base->invIB ); + base->fixedRotation = b3Det( invInertiaSum ) < 1000.0f * FLT_MIN; + + b3SphericalJoint* joint = &base->sphericalJoint; + joint->indexA = bodyA->setIndex == b3_awakeSet ? localIndexA : B3_NULL_INDEX; + joint->indexB = bodyB->setIndex == b3_awakeSet ? localIndexB : B3_NULL_INDEX; + + // Compute joint anchor frames with world space rotation, relative to center of mass + joint->frameA.q = b3MulQuat( bodySimA->transform.q, base->localFrameA.q ); + joint->frameA.p = b3RotateVector( bodySimA->transform.q, b3Sub( base->localFrameA.p, bodySimA->localCenter ) ); + joint->frameB.q = b3MulQuat( bodySimB->transform.q, base->localFrameB.q ); + joint->frameB.p = b3RotateVector( bodySimB->transform.q, b3Sub( base->localFrameB.p, bodySimB->localCenter ) ); + + joint->deltaCenter = b3Sub( bodySimB->center, bodySimA->center ); + + // Cone axis is the z-axis of body A. + b3Vec3 coneAxis = b3RotateVector( joint->frameA.q, b3Vec3_axisZ ); + + // Twist axis is the z-axis of body B. + b3Vec3 twistAxis = b3RotateVector( joint->frameB.q, b3Vec3_axisZ ); + + if ( joint->enableConeLimit ) + { + // Swing axis may be zero + b3Vec3 swingAxis = b3Normalize( b3Cross( coneAxis, twistAxis ) ); + float k = b3Dot( swingAxis, b3MulMV( invInertiaSum, swingAxis ) ); + joint->swingMass = k > 0.0f ? 1.0f / k : 0.0f; + joint->swingAxis = swingAxis; + } + + if ( joint->enableTwistLimit ) + { + b3Quat relQ = b3InvMulQuat( joint->frameA.q, joint->frameB.q ); + float tanThetaOver2 = sqrtf( ( relQ.v.x * relQ.v.x + relQ.v.y * relQ.v.y ) / ( relQ.v.z * relQ.v.z + relQ.s * relQ.s ) ); + + // todo verify this Jacobian using a finite difference, unit test? + b3Vec3 swingAxis = b3Normalize( b3Cross( coneAxis, twistAxis ) ); + b3Vec3 perpAxis = b3Cross( swingAxis, coneAxis ); + b3Vec3 twistJacobian = b3MulAdd( coneAxis, tanThetaOver2, perpAxis ); + float k = b3Dot( twistJacobian, b3MulMV( invInertiaSum, twistJacobian ) ); + joint->twistMass = k > 0.0f ? 1.0f / k : 0.0f; + joint->twistJacobian = twistJacobian; + } + + if ( base->fixedRotation == false ) + { + joint->rotationMass = b3InvertMatrix( invInertiaSum ); + } + else + { + joint->rotationMass = b3Mat3_zero; + } + + joint->springSoftness = b3MakeSoft( joint->hertz, joint->dampingRatio, context->h ); + + if ( context->enableWarmStarting == false ) + { + joint->linearImpulse = b3Vec3_zero; + joint->motorImpulse = b3Vec3_zero; + joint->springImpulse = b3Vec3_zero; + joint->swingImpulse = 0.0f; + joint->lowerTwistImpulse = 0.0f; + joint->upperTwistImpulse = 0.0f; + } +} + +void b3WarmStartSphericalJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_sphericalJoint ); + + float mA = base->invMassA; + float mB = base->invMassB; + b3Matrix3 iA = base->invIA; + b3Matrix3 iB = base->invIB; + + // dummy state for static bodies + b3BodyState dummyState = b3_identityBodyState; + + b3SphericalJoint* joint = &base->sphericalJoint; + + b3BodyState* stateA = joint->indexA == B3_NULL_INDEX ? &dummyState : context->states + joint->indexA; + b3BodyState* stateB = joint->indexB == B3_NULL_INDEX ? &dummyState : context->states + joint->indexB; + + b3Vec3 vA = stateA->linearVelocity; + b3Vec3 wA = stateA->angularVelocity; + b3Vec3 vB = stateB->linearVelocity; + b3Vec3 wB = stateB->angularVelocity; + + b3Vec3 rA = b3RotateVector( stateA->deltaRotation, joint->frameA.p ); + b3Vec3 rB = b3RotateVector( stateB->deltaRotation, joint->frameB.p ); + + b3Vec3 angularImpulse = b3Add( joint->springImpulse, joint->motorImpulse ); + angularImpulse = b3MulSub( angularImpulse, joint->swingImpulse, joint->swingAxis ); + angularImpulse = b3MulAdd( angularImpulse, joint->lowerTwistImpulse - joint->upperTwistImpulse, joint->twistJacobian ); + + vA = b3MulSub( vA, mA, joint->linearImpulse ); + wA = b3Sub( wA, b3MulMV( iA, b3Add( b3Cross( rA, joint->linearImpulse ), angularImpulse ) ) ); + + vB = b3MulAdd( vB, mB, joint->linearImpulse ); + wB = b3Add( wB, b3MulMV( iB, b3Add( b3Cross( rB, joint->linearImpulse ), angularImpulse ) ) ); + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->linearVelocity = vA; + stateA->angularVelocity = wA; + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->linearVelocity = vB; + stateB->angularVelocity = wB; + } +} + +void b3SolveSphericalJoint( b3JointSim* base, b3StepContext* context, bool useBias ) +{ + float mA = base->invMassA; + float mB = base->invMassB; + b3Matrix3 iA = base->invIA; + b3Matrix3 iB = base->invIB; + + // dummy state for static bodies + b3BodyState dummyState = b3_identityBodyState; + + b3SphericalJoint* joint = &base->sphericalJoint; + b3BodyState* stateA = joint->indexA == B3_NULL_INDEX ? &dummyState : context->states + joint->indexA; + b3BodyState* stateB = joint->indexB == B3_NULL_INDEX ? &dummyState : context->states + joint->indexB; + + b3Vec3 vA = stateA->linearVelocity; + b3Vec3 wA = stateA->angularVelocity; + b3Vec3 vB = stateB->linearVelocity; + b3Vec3 wB = stateB->angularVelocity; + + bool fixedRotation = base->fixedRotation; + b3Quat quatA = b3MulQuat( stateA->deltaRotation, joint->frameA.q ); + b3Quat quatB = b3MulQuat( stateB->deltaRotation, joint->frameB.q ); + + b3Quat relQ = b3InvMulQuat( quatA, quatB ); + + // Solve spring + if ( joint->enableSpring && fixedRotation == false ) + { + // Rotation constraint error + b3Vec3 deltaRotation = b3DeltaQuatToRotation( relQ, joint->targetRotation ); + b3Vec3 c = b3Neg( b3RotateVector( quatA, deltaRotation ) ); + + b3Vec3 bias = b3MulSV( joint->springSoftness.biasRate, c ); + float massScale = joint->springSoftness.massScale; + float impulseScale = joint->springSoftness.impulseScale; + b3Vec3 cdot = b3Sub( wB, wA ); + + b3Vec3 impulse = b3MulSub( b3MulSV( -massScale, b3MulMV( joint->rotationMass, b3Add( cdot, bias ) ) ), + impulseScale, joint->springImpulse ); + joint->springImpulse = b3Add( joint->springImpulse, impulse ); + + wA = b3Sub( wA, b3MulMV( iA, impulse ) ); + wB = b3Add( wB, b3MulMV( iB, impulse ) ); + } + + if ( joint->enableMotor && fixedRotation == false ) + { + b3Vec3 cdot = b3Sub( wB, wA ); + + b3Vec3 lambda = b3Neg( b3MulMV( joint->rotationMass, b3Sub( cdot, joint->motorVelocity ) ) ); + b3Vec3 newImpulse = b3Add( joint->motorImpulse, lambda ); + float length = b3Length( newImpulse ); + float maxImpulse = joint->maxMotorTorque * context->h; + if ( length > maxImpulse ) + { + newImpulse = b3MulSV( maxImpulse / length, newImpulse ); + } + + lambda = b3Sub( newImpulse, joint->motorImpulse ); + joint->motorImpulse = newImpulse; + + wA = b3Sub( wA, b3MulMV( iA, lambda ) ); + wB = b3Add( wB, b3MulMV( iB, lambda ) ); + } + + if ( joint->enableTwistLimit && fixedRotation == false ) + { + float twistAngle = b3GetTwistAngle( relQ ); + + // todo does an updated twist axis help? + + b3Vec3 twistJacobian = joint->twistJacobian; + + // Lower limit + { + float c = twistAngle - joint->lowerTwistAngle; + 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 = b3Dot( b3Sub( wB, wA ), twistJacobian ); + float oldImpulse = joint->lowerTwistImpulse; + float deltaImpulse = -massScale * joint->twistMass * ( cdot + bias ) - impulseScale * oldImpulse; + joint->lowerTwistImpulse = b3MaxFloat( oldImpulse + deltaImpulse, 0.0f ); + deltaImpulse = joint->lowerTwistImpulse - oldImpulse; + + wA = b3MulSub( wA, deltaImpulse, b3MulMV( iA, twistJacobian ) ); + wB = b3MulAdd( wB, deltaImpulse, b3MulMV( iB, twistJacobian ) ); + } + + // Upper limit + { + float c = joint->upperTwistAngle - twistAngle; + 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 = b3Dot( b3Sub( wA, wB ), twistJacobian ); + float oldImpulse = joint->upperTwistImpulse; + float deltaImpulse = -massScale * joint->twistMass * ( cdot + bias ) - impulseScale * oldImpulse; + joint->upperTwistImpulse = b3MaxFloat( oldImpulse + deltaImpulse, 0.0f ); + deltaImpulse = joint->upperTwistImpulse - oldImpulse; + + // sign flipped on applied impulse + wA = b3MulAdd( wA, deltaImpulse, b3MulMV( iA, twistJacobian ) ); + wB = b3MulSub( wB, deltaImpulse, b3MulMV( iB, twistJacobian ) ); + } + } + + if ( joint->enableConeLimit && fixedRotation == false ) + { + float swingAngle = b3GetSwingAngle( relQ ); + + // todo does an updated swing axis help? + // b3Vec3 axisA = b3RotateVector( quatA, b3Vec3_axisZ ); + // b3Vec3 axisB = b3RotateVector( quatB, b3Vec3_axisZ ); + // b3Vec3 swingAxis = b3Normalize( b3Cross( axisA, axisB ) ); + // joint->swingAxis = swingAxis; + + b3Vec3 swingAxis = joint->swingAxis; + + float c = joint->coneAngle - swingAngle; + 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 = b3Dot( b3Sub( wA, wB ), swingAxis ); + float oldImpulse = joint->swingImpulse; + float deltaImpulse = -massScale * joint->swingMass * ( cdot + bias ) - impulseScale * oldImpulse; + joint->swingImpulse = b3MaxFloat( oldImpulse + deltaImpulse, 0.0f ); + deltaImpulse = joint->swingImpulse - oldImpulse; + + // sign flipped on applied impulse + wA = b3MulAdd( wA, deltaImpulse, b3MulMV( iA, swingAxis ) ); + wB = b3MulSub( wB, deltaImpulse, b3MulMV( iB, swingAxis ) ); + } + + // Solve point-to-point constraint + { + b3Vec3 rA = b3RotateVector( stateA->deltaRotation, joint->frameA.p ); + b3Vec3 rB = b3RotateVector( stateB->deltaRotation, joint->frameB.p ); + + b3Vec3 cdot = b3Sub( b3Sub( b3Add( vB, b3Cross( wB, rB ) ), vA ), b3Cross( wA, rA ) ); + + b3Vec3 bias = b3Vec3_zero; + float massScale = 1.0f; + float impulseScale = 0.0f; + if ( useBias ) + { + b3Vec3 dcA = stateA->deltaPosition; + b3Vec3 dcB = stateB->deltaPosition; + + b3Vec3 separation = b3Add( b3Sub( dcB, dcA ), b3Sub( rB, rA ) ); + separation = b3Add( separation, joint->deltaCenter ); + + bias = b3MulSV( base->constraintSoftness.biasRate, separation ); + massScale = base->constraintSoftness.massScale; + impulseScale = base->constraintSoftness.impulseScale; + } + + //// K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] + b3Matrix3 sA = b3Skew( rA ); + b3Matrix3 sB = b3Skew( rB ); + b3Matrix3 kA = b3MulMM( sA, b3MulMM( base->invIA, sA ) ); + b3Matrix3 kB = b3MulMM( sB, b3MulMM( base->invIB, sB ) ); + b3Matrix3 k = b3NegateMat3( b3AddMM( kA, kB ) ); + k.cx.x += mA + mB; + k.cy.y += mA + mB; + k.cz.z += mA + mB; + + b3Vec3 b = b3Solve3( k, b3Add( cdot, bias ) ); + + b3Vec3 impulse = b3MulSub( b3MulSV( -massScale, b ), impulseScale, joint->linearImpulse ); + joint->linearImpulse = b3Add( joint->linearImpulse, impulse ); + + vA = b3MulSub( vA, mA, impulse ); + wA = b3Sub( wA, b3MulMV( iA, b3Cross( rA, impulse ) ) ); + vB = b3MulAdd( vB, mB, impulse ); + wB = b3Add( wB, b3MulMV( iB, b3Cross( rB, impulse ) ) ); + } + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->linearVelocity = vA; + stateA->angularVelocity = wA; + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->linearVelocity = vB; + stateB->angularVelocity = wB; + } +} + +void b3DrawSphericalJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale ) +{ + b3Transform frameA = b3MulTransforms( transformA, base->localFrameA ); + + float length1 = 0.1f * scale; + draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, length1, b3RotateVector( frameA.q, b3Vec3_axisX ) ), b3_colorRed, + draw->context ); + draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, length1, b3RotateVector( frameA.q, b3Vec3_axisY ) ), b3_colorGreen, + draw->context ); + draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, length1, b3RotateVector( frameA.q, b3Vec3_axisZ ) ), b3_colorBlue, + draw->context ); + + b3Transform frameB = b3MulTransforms( transformB, base->localFrameB ); + + float length2 = 0.2f * scale; + draw->DrawSegmentFcn( frameB.p, b3MulAdd( frameB.p, length2, b3RotateVector( frameB.q, b3Vec3_axisZ ) ), b3_colorOrange, + draw->context ); + + b3SphericalJoint* joint = &base->sphericalJoint; + enum { kSliceCount = 16 }; + + // Twist limit + if ( joint->enableTwistLimit ) + { + b3Quat quatA = frameA.q; + b3Quat quatB = frameB.q; + + if ( b3DotQuat( quatA, quatB ) < 0.0f ) + { + // this keeps the twist angle in the range [-pi, pi] + quatB = b3NegateQuat( quatB ); + } + + b3Quat relQ = b3InvMulQuat( quatA, quatB ); + + const float wedgeRadius = 0.1f * scale; + for ( int index = 0; index < kSliceCount; ++index ) + { + float t1 = (float)( index + 0 ) / kSliceCount; + float alpha1 = ( 1.0f - t1 ) * joint->lowerTwistAngle + t1 * joint->upperTwistAngle; + float t2 = (float)( index + 1 ) / kSliceCount; + float alpha2 = ( 1.0f - t2 ) * joint->lowerTwistAngle + t2 * joint->upperTwistAngle; + + b3Vec3 vertex1 = { wedgeRadius * b3Cos( alpha1 ), wedgeRadius * b3Sin( alpha1 ), 0.0f }; + b3Vec3 vertex2 = { wedgeRadius * b3Cos( alpha2 ), wedgeRadius * b3Sin( alpha2 ), 0.0f }; + + if ( index == 0 ) + { + draw->DrawSegmentFcn( frameA.p, b3TransformPoint( frameA, vertex1 ), b3_colorCyan, draw->context ); + } + + if ( index == kSliceCount - 1 ) + { + draw->DrawSegmentFcn( b3TransformPoint( frameA, vertex2 ), frameA.p, b3_colorCyan, draw->context ); + } + draw->DrawSegmentFcn( b3TransformPoint( frameA, vertex1 ), b3TransformPoint( frameA, vertex2 ), b3_colorCyan, + draw->context ); + } + + float twistAngle = b3GetTwistAngle( relQ ); + b3Vec3 p2 = { wedgeRadius * b3Cos( twistAngle ), wedgeRadius * b3Sin( twistAngle ), 0.0f }; + draw->DrawSegmentFcn( frameA.p, b3TransformPoint( frameA, p2 ), b3_colorYellow, draw->context ); + } + + // Swing limit + if ( joint->enableConeLimit ) + { + const float radius = 0.1f * scale; + float coneRadius = radius * b3Sin( joint->coneAngle ); + float coneHeight = radius * b3Cos( joint->coneAngle ); + + for ( int index = 0; index < kSliceCount; ++index ) + { + float phi1 = 2.0f * ( index + 0 ) / kSliceCount * B3_PI; + float phi2 = 2.0f * ( index + 1 ) / kSliceCount * B3_PI; + + b3Vec3 vertex1 = { coneRadius * b3Cos( phi1 ), coneRadius * b3Sin( phi1 ), coneHeight }; + b3Vec3 vertex2 = { coneRadius * b3Cos( phi2 ), coneRadius * b3Sin( phi2 ), coneHeight }; + + draw->DrawSegmentFcn( frameA.p, b3TransformPoint( frameA, vertex1 ), b3_colorCyan, draw->context ); + draw->DrawSegmentFcn( b3TransformPoint( frameA, vertex1 ), b3TransformPoint( frameA, vertex2 ), b3_colorCyan, + draw->context ); + } + } +} diff --git a/src/table.c b/src/table.c new file mode 100644 index 0000000..fb066b8 --- /dev/null +++ b/src/table.c @@ -0,0 +1,248 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "table.h" + +#include "bitset.h" +#include "core.h" +#include "ctz.h" +#include "platform.h" + +#include + +#if B3_DEBUG +b3AtomicInt b3_probeCount; +#endif + +_Static_assert( 2 * B3_SHAPE_POWER + B3_CHILD_POWER == 64, "compound power" ); +_Static_assert( B3_CHILD_POWER > 8, "compound child power" ); + +b3HashSet b3CreateSet( int32_t capacity ) +{ + b3HashSet set = { 0 }; + + // Capacity must be a power of 2 + if ( capacity > 16 ) + { + set.capacity = b3RoundUpPowerOf2( capacity ); + } + else + { + set.capacity = 16; + } + + set.count = 0; + set.items = (b3SetItem*)b3Alloc( set.capacity * sizeof( b3SetItem ) ); + memset( set.items, 0, set.capacity * sizeof( b3SetItem ) ); + + return set; +} + +void b3DestroySet( b3HashSet* set ) +{ + b3Free( set->items, set->capacity * sizeof( b3SetItem ) ); + set->items = NULL; + set->count = 0; + set->capacity = 0; +} + +void b3ClearSet( b3HashSet* set ) +{ + set->count = 0; + memset( set->items, 0, set->capacity * sizeof( b3SetItem ) ); +} + +// 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/ +static inline uint32_t b3KeyHash( uint64_t key ) +{ + uint64_t h = key; + h ^= h >> 33; + h *= 0xff51afd7ed558ccdL; + h ^= h >> 33; + h *= 0xc4ceb9fe1a85ec53L; + h ^= h >> 33; + + return (uint32_t)h; +} + +static int32_t b3FindSlot( const b3HashSet* set, uint64_t key, uint32_t hash ) +{ + uint32_t capacity = set->capacity; + int32_t index = hash & ( capacity - 1 ); + const b3SetItem* items = set->items; + while ( items[index].hash != 0 && items[index].key != key ) + { +#if B3_DEBUG + b3AtomicFetchAddInt( &b3_probeCount, 1 ); +#endif + index = ( index + 1 ) & ( capacity - 1 ); + } + + return index; +} + +static void b3AddKeyHaveCapacity( b3HashSet* set, uint64_t key, uint32_t hash ) +{ + int32_t index = b3FindSlot( set, key, hash ); + b3SetItem* items = set->items; + B3_ASSERT( items[index].hash == 0 ); + + items[index].key = key; + items[index].hash = hash; + set->count += 1; +} + +static void b3GrowTable( b3HashSet* set ) +{ + uint32_t oldCount = set->count; + B3_UNUSED( oldCount ); + + uint32_t oldCapacity = set->capacity; + b3SetItem* oldItems = set->items; + + set->count = 0; + // Capacity must be a power of 2 + set->capacity = 2 * oldCapacity; + set->items = (b3SetItem*)b3Alloc( set->capacity * sizeof( b3SetItem ) ); + memset( set->items, 0, set->capacity * sizeof( b3SetItem ) ); + + // Transfer items into new array + for ( uint32_t i = 0; i < oldCapacity; ++i ) + { + b3SetItem* item = oldItems + i; + if ( item->hash == 0 ) + { + // this item was empty + continue; + } + + b3AddKeyHaveCapacity( set, item->key, item->hash ); + } + + B3_ASSERT( set->count == oldCount ); + + b3Free( oldItems, oldCapacity * sizeof( b3SetItem ) ); +} + +bool b3ContainsKey( const b3HashSet* set, uint64_t key ) +{ + // key of zero is a sentinel + B3_ASSERT( key != 0 ); + uint32_t hash = b3KeyHash( key ); + int32_t index = b3FindSlot( set, key, hash ); + return set->items[index].key == key; +} + +int b3GetHashSetBytes( b3HashSet* set ) +{ + return set->capacity * (int)sizeof( b3SetItem ); +} + +bool b3AddKey( b3HashSet* set, uint64_t key ) +{ + // key of zero is a sentinel + B3_ASSERT( key != 0 ); + + uint32_t hash = b3KeyHash( key ); + B3_ASSERT( hash != 0 ); + + int32_t index = b3FindSlot( set, key, hash ); + if ( set->items[index].hash != 0 ) + { + // Already in set + B3_ASSERT( set->items[index].hash == hash && set->items[index].key == key ); + return true; + } + + if ( 2 * set->count >= set->capacity ) + { + b3GrowTable( set ); + } + + b3AddKeyHaveCapacity( set, key, hash ); + return false; +} + +// See https://en.wikipedia.org/wiki/Open_addressing +bool b3RemoveKey( b3HashSet* set, uint64_t key ) +{ + uint32_t hash = b3KeyHash( key ); + int32_t i = b3FindSlot( set, key, hash ); + b3SetItem* items = set->items; + if ( items[i].hash == 0 ) + { + // Not in set + return false; + } + + // Mark item i as unoccupied + items[i].key = 0; + items[i].hash = 0; + + B3_ASSERT( set->count > 0 ); + set->count -= 1; + + // Attempt to fill item i + int32_t j = i; + uint32_t capacity = set->capacity; + for ( ;; ) + { + j = ( j + 1 ) & ( capacity - 1 ); + if ( items[j].hash == 0 ) + { + break; + } + + // k is the first item for the hash of j + int32_t k = items[j].hash & ( 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; + items[j].hash = 0; + + i = j; + } + + return true; +} + +// This function is here because ctz.h is included by +// this file but not in bitset.c +int b3CountSetBits( b3BitSet* bitSet ) +{ + int popCount = 0; + uint32_t blockCount = bitSet->blockCount; + for ( uint32_t i = 0; i < blockCount; ++i ) + { + popCount += b3PopCount64( bitSet->bits[i] ); + } + + return popCount; +} diff --git a/src/table.h b/src/table.h new file mode 100644 index 0000000..2e54772 --- /dev/null +++ b/src/table.h @@ -0,0 +1,62 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "box3d/constants.h" + +#include +#include + +typedef struct b3SetItem +{ + uint64_t key; + uint32_t hash; +} b3SetItem; + +typedef struct b3HashSet +{ + b3SetItem* items; + uint32_t capacity; + uint32_t count; +} b3HashSet; + +#define B3_SHAPE_MASK ( B3_MAX_SHAPES - 1 ) +#define B3_CHILD_MASK ( B3_MAX_CHILD_SHAPES - 1 ) + +static inline uint64_t b3ShapePairKey( int s1, int s2, int c ) +{ + if (s1 < s2) + { + return ( (uint64_t)( B3_SHAPE_MASK & s1 ) << ( 64 - B3_SHAPE_POWER ) ) | + ( (uint64_t)( B3_SHAPE_MASK & s2 ) << ( 64 - 2 * B3_SHAPE_POWER ) ) | ( (uint64_t)( B3_CHILD_MASK & c ) ); + } + + return ( (uint64_t)( B3_SHAPE_MASK & s2 ) << ( 64 - B3_SHAPE_POWER ) ) | + ( (uint64_t)( B3_SHAPE_MASK & s1 ) << ( 64 - 2 * B3_SHAPE_POWER ) ) | + ( (uint64_t)( B3_CHILD_MASK & c ) ); +} + +#ifdef __cplusplus +extern "C" +{ +#endif + +b3HashSet b3CreateSet( int32_t capacity ); +void b3DestroySet( b3HashSet* set ); + +void b3ClearSet( b3HashSet* set ); + +// Returns true if key was already in set +bool b3AddKey( b3HashSet* set, uint64_t key ); + +// Returns true if the key was found +bool b3RemoveKey( b3HashSet* set, uint64_t key ); + +bool b3ContainsKey( const b3HashSet* set, uint64_t key ); + +int b3GetHashSetBytes( b3HashSet* set ); + +#ifdef __cplusplus +} +#endif diff --git a/src/timer.c b/src/timer.c new file mode 100644 index 0000000..3f02bf1 --- /dev/null +++ b/src/timer.c @@ -0,0 +1,671 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +// Required on Linux to expose pthread_setname_np. Must be defined before any +// system header is included. +#if defined( __linux__ ) && !defined( _GNU_SOURCE ) +#define _GNU_SOURCE +#endif + +#include "core.h" + +#include "box3d/base.h" + +#include +#include +#include + +#if defined( _WIN32 ) + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif + +#include +#include + +static double s_invFrequency = 0.0; + +uint64_t b3GetTicks( void ) +{ + LARGE_INTEGER counter; + QueryPerformanceCounter( &counter ); + return (uint64_t)counter.QuadPart; +} + +float b3GetMilliseconds( 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 = b3GetTicks(); + return (float)( s_invFrequency * ( ticksNow - ticks ) ); +} + +float b3GetMillisecondsAndReset( 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 = b3GetTicks(); + float ms = (float)( s_invFrequency * ( ticksNow - *ticks ) ); + *ticks = ticksNow; + return ms; +} + +void b3Yield( void ) +{ + SwitchToThread(); +} + +typedef struct b3Mutex +{ + CRITICAL_SECTION cs; +} b3Mutex; + +b3Mutex* b3CreateMutex( void ) +{ + b3Mutex* m = b3Alloc( sizeof( b3Mutex ) ); + InitializeCriticalSection( &m->cs ); + return m; +} + +void b3DestroyMutex( b3Mutex* m ) +{ + DeleteCriticalSection( &m->cs ); + *m = (b3Mutex){ 0 }; + b3Free( m, sizeof( b3Mutex ) ); +} + +void b3LockMutex( b3Mutex* m ) +{ + EnterCriticalSection( &m->cs ); +} + +void b3UnlockMutex( b3Mutex* m ) +{ + LeaveCriticalSection( &m->cs ); +} + +typedef struct b3Semaphore +{ + HANDLE semaphore; +} b3Semaphore; + +b3Semaphore* b3CreateSemaphore( int initCount ) +{ + b3Semaphore* s = b3Alloc( sizeof( b3Semaphore ) ); + s->semaphore = CreateSemaphoreExW( NULL, initCount, INT_MAX, NULL, 0, SEMAPHORE_ALL_ACCESS ); + return s; +} + +void b3DestroySemaphore( b3Semaphore* s ) +{ + CloseHandle( s->semaphore ); + *s = (b3Semaphore){ 0 }; + b3Free( s, sizeof( b3Semaphore ) ); +} + +void b3WaitSemaphore( b3Semaphore* s ) +{ + WaitForSingleObjectEx( s->semaphore, INFINITE, FALSE ); +} + +void b3SignalSemaphore( b3Semaphore* s ) +{ + ReleaseSemaphore( s->semaphore, 1, NULL ); +} + +typedef struct b3Thread +{ + HANDLE thread; + b3ThreadFunction* function; + void* context; + char name[32]; +} b3Thread; + +typedef HRESULT( WINAPI* b3SetThreadDescriptionFn )( HANDLE, PCWSTR ); + +// SetThreadDescription exists on Windows 10 1607+. Resolve it dynamically so +// older Windows versions still link. Resolved once, cached for subsequent calls. +static void b3SetCurrentThreadName( const char* name ) +{ + if ( name == NULL || name[0] == 0 ) + { + return; + } + + static b3SetThreadDescriptionFn pfn = NULL; + static int resolved = 0; + + if ( resolved == 0 ) + { + HMODULE kernel = GetModuleHandleW( L"kernel32.dll" ); + if ( kernel != NULL ) + { + // MSVC /Wall warns C4191 on every FARPROC function-pointer cast. + // This is the intended use of GetProcAddress, so suppress locally. +#pragma warning( push ) +#pragma warning( disable : 4191 ) + pfn = (b3SetThreadDescriptionFn)GetProcAddress( kernel, "SetThreadDescription" ); +#pragma warning( pop ) + } + resolved = 1; + } + + if ( pfn == NULL ) + { + return; + } + + wchar_t wide[32]; + int n = MultiByteToWideChar( CP_UTF8, 0, name, -1, wide, (int)( sizeof( wide ) / sizeof( wide[0] ) ) ); + if ( n > 0 ) + { + pfn( GetCurrentThread(), wide ); + } +} + +static DWORD WINAPI b3ThreadStart( LPVOID param ) +{ + b3Thread* t = (b3Thread*)param; + b3SetCurrentThreadName( t->name ); + t->function( t->context ); + return 0; +} + +b3Thread* b3CreateThread( b3ThreadFunction* function, void* context, const char* name ) +{ + b3Thread* t = b3Alloc( sizeof( b3Thread ) ); + t->function = function; + t->context = context; + if ( name != NULL ) + { + snprintf( t->name, sizeof( t->name ), "%s", name ); + } + else + { + t->name[0] = 0; + } + t->thread = CreateThread( NULL, 0, b3ThreadStart, t, 0, NULL ); + return t; +} + +void b3JoinThread( b3Thread* t ) +{ + WaitForSingleObject( t->thread, INFINITE ); + CloseHandle( t->thread ); + *t = (b3Thread){ 0 }; + b3Free( t, sizeof( b3Thread ) ); +} + +#elif defined( __linux__ ) || defined( __EMSCRIPTEN__ ) + +#include +#include + +uint64_t b3GetTicks( void ) +{ + struct timespec ts; + clock_gettime( CLOCK_MONOTONIC, &ts ); + return ts.tv_sec * 1000000000LL + ts.tv_nsec; +} + +float b3GetMilliseconds( uint64_t ticks ) +{ + uint64_t ticksNow = b3GetTicks(); + return (float)( ( ticksNow - ticks ) / 1000000.0 ); +} + +float b3GetMillisecondsAndReset( uint64_t* ticks ) +{ + uint64_t ticksNow = b3GetTicks(); + float ms = (float)( ( ticksNow - *ticks ) / 1000000.0 ); + *ticks = ticksNow; + return ms; +} + +void b3Yield( void ) +{ + sched_yield(); +} + +#include +typedef struct b3Mutex +{ + pthread_mutex_t mtx; +} b3Mutex; + +b3Mutex* b3CreateMutex( void ) +{ + b3Mutex* m = b3Alloc( sizeof( b3Mutex ) ); + pthread_mutex_init( &m->mtx, NULL ); + return m; +} + +void b3DestroyMutex( b3Mutex* m ) +{ + pthread_mutex_destroy( &m->mtx ); + *m = (b3Mutex){ 0 }; + b3Free( m, sizeof( b3Mutex ) ); +} + +void b3LockMutex( b3Mutex* m ) +{ + pthread_mutex_lock( &m->mtx ); +} + +void b3UnlockMutex( b3Mutex* m ) +{ + pthread_mutex_unlock( &m->mtx ); +} + +#include + +typedef struct b3Semaphore +{ + sem_t semaphore; +} b3Semaphore; + +b3Semaphore* b3CreateSemaphore( int initCount ) +{ + b3Semaphore* s = b3Alloc( sizeof( b3Semaphore ) ); + sem_init( &s->semaphore, 0, (unsigned int)initCount ); + return s; +} + +void b3DestroySemaphore( b3Semaphore* s ) +{ + sem_destroy( &s->semaphore ); + *s = (b3Semaphore){ 0 }; + b3Free( s, sizeof( b3Semaphore ) ); +} + +void b3WaitSemaphore( b3Semaphore* s ) +{ + sem_wait( &s->semaphore ); +} + +void b3SignalSemaphore( b3Semaphore* s ) +{ + sem_post( &s->semaphore ); +} + +typedef struct b3Thread +{ + pthread_t thread; + b3ThreadFunction* function; + void* context; + char name[32]; +} b3Thread; + +static void b3SetCurrentThreadName( const char* name ) +{ + if ( name == NULL || name[0] == 0 ) + { + return; + } + +#if defined( __linux__ ) + // Linux caps thread names at 15 chars + null terminator. + char truncated[16]; + snprintf( truncated, sizeof( truncated ), "%s", name ); + pthread_setname_np( pthread_self(), truncated ); +#else + (void)name; +#endif +} + +static void* b3ThreadStart( void* param ) +{ + b3Thread* t = (b3Thread*)param; + b3SetCurrentThreadName( t->name ); + t->function( t->context ); + return NULL; +} + +b3Thread* b3CreateThread( b3ThreadFunction* function, void* context, const char* name ) +{ + b3Thread* t = b3Alloc( sizeof( b3Thread ) ); + t->function = function; + t->context = context; + if ( name != NULL ) + { + snprintf( t->name, sizeof( t->name ), "%s", name ); + } + else + { + t->name[0] = 0; + } + pthread_create( &t->thread, NULL, b3ThreadStart, t ); + return t; +} + +void b3JoinThread( b3Thread* t ) +{ + pthread_join( t->thread, NULL ); + *t = (b3Thread){ 0 }; + b3Free( t, sizeof( b3Thread ) ); +} + +#elif defined( __APPLE__ ) + +#include +#include +#include + +static double s_invFrequency = 0.0; + +uint64_t b3GetTicks( void ) +{ + return mach_absolute_time(); +} + +float b3GetMilliseconds( 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 = b3GetTicks(); + return (float)( s_invFrequency * ( ticksNow - ticks ) ); +} + +float b3GetMillisecondsAndReset( 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 = b3GetTicks(); + float ms = (float)( s_invFrequency * ( ticksNow - *ticks ) ); + *ticks = ticksNow; + return ms; +} + +void b3Yield( void ) +{ + sched_yield(); +} + +#include +typedef struct b3Mutex +{ + pthread_mutex_t mtx; +} b3Mutex; + +b3Mutex* b3CreateMutex( void ) +{ + b3Mutex* m = b3Alloc( sizeof( b3Mutex ) ); + pthread_mutex_init( &m->mtx, NULL ); + return m; +} + +void b3DestroyMutex( b3Mutex* m ) +{ + pthread_mutex_destroy( &m->mtx ); + *m = (b3Mutex){ 0 }; + b3Free( m, sizeof( b3Mutex ) ); +} + +void b3LockMutex( b3Mutex* m ) +{ + pthread_mutex_lock( &m->mtx ); +} + +void b3UnlockMutex( b3Mutex* m ) +{ + pthread_mutex_unlock( &m->mtx ); +} + +#include + +typedef struct b3Semaphore +{ + dispatch_semaphore_t semaphore; + int initialCount; +} b3Semaphore; + +b3Semaphore* b3CreateSemaphore( int initCount ) +{ + b3Semaphore* s = b3Alloc( sizeof( b3Semaphore ) ); + s->semaphore = dispatch_semaphore_create( (long)initCount ); + s->initialCount = initCount; + return s; +} + +void b3DestroySemaphore( b3Semaphore* s ) +{ + // libdispatch aborts if the current count is less than the initial count at release time. + // Pad with signals so the invariant always holds; no one is waiting at this point. + for ( int i = 0; i < s->initialCount; ++i ) + { + dispatch_semaphore_signal( s->semaphore ); + } + dispatch_release( s->semaphore ); + *s = (b3Semaphore){ 0 }; + b3Free( s, sizeof( b3Semaphore ) ); +} + +void b3WaitSemaphore( b3Semaphore* s ) +{ + dispatch_semaphore_wait( s->semaphore, DISPATCH_TIME_FOREVER ); +} + +void b3SignalSemaphore( b3Semaphore* s ) +{ + dispatch_semaphore_signal( s->semaphore ); +} + +typedef struct b3Thread +{ + pthread_t thread; + b3ThreadFunction* function; + void* context; + char name[32]; +} b3Thread; + +// macOS pthread_setname_np takes only the name — it always names the calling thread. +static void b3SetCurrentThreadName( const char* name ) +{ + if ( name == NULL || name[0] == 0 ) + { + return; + } + pthread_setname_np( name ); +} + +static void* b3ThreadStart( void* param ) +{ + b3Thread* t = (b3Thread*)param; + b3SetCurrentThreadName( t->name ); + t->function( t->context ); + return NULL; +} + +b3Thread* b3CreateThread( b3ThreadFunction* function, void* context, const char* name ) +{ + b3Thread* t = b3Alloc( sizeof( b3Thread ) ); + t->function = function; + t->context = context; + if ( name != NULL ) + { + snprintf( t->name, sizeof( t->name ), "%s", name ); + } + else + { + t->name[0] = 0; + } + pthread_create( &t->thread, NULL, b3ThreadStart, t ); + return t; +} + +void b3JoinThread( b3Thread* t ) +{ + pthread_join( t->thread, NULL ); + *t = (b3Thread){ 0 }; + b3Free( t, sizeof( b3Thread ) ); +} + +#else + +uint64_t b3GetTicks( void ) +{ + return 0; +} + +float b3GetMilliseconds( uint64_t ticks ) +{ + ( (void)( ticks ) ); + return 0.0f; +} + +float b3GetMillisecondsAndReset( uint64_t* ticks ) +{ + ( (void)( ticks ) ); + return 0.0f; +} + +void b3Yield( void ) +{ +} + +typedef struct b3Mutex +{ + int dummy; +} b3Mutex; + +b3Mutex* b3CreateMutex( void ) +{ + b3Mutex* m = b3Alloc( sizeof( b3Mutex ) ); + m->dummy = 42; + return m; +} + +void b3DestroyMutex( b3Mutex* m ) +{ + *m = (b3Mutex){ 0 }; + b3Free( m, sizeof( b3Mutex ) ); +} + +void b3LockMutex( b3Mutex* m ) +{ + (void)m; +} + +void b3UnlockMutex( b3Mutex* m ) +{ + (void)m; +} + +typedef struct b3Semaphore +{ + int dummy; +} b3Semaphore; + +b3Semaphore* b3CreateSemaphore( int initCount ) +{ + b3Semaphore* s = b3Alloc( sizeof( b3Semaphore ) ); + (void)initCount; + s->dummy = 42; + return s; +} + +void b3DestroySemaphore( b3Semaphore* s ) +{ + *s = (b3Semaphore){ 0 }; + b3Free( s, sizeof( b3Semaphore ) ); +} + +void b3WaitSemaphore( b3Semaphore* s ) +{ + (void)s; +} + +void b3SignalSemaphore( b3Semaphore* s ) +{ + (void)s; +} + +typedef struct b3Thread +{ + int dummy; +} b3Thread; + +b3Thread* b3CreateThread( b3ThreadFunction* function, void* context, const char* name ) +{ + (void)name; + function( context ); + b3Thread* t = b3Alloc( sizeof( b3Thread ) ); + t->dummy = 42; + return t; +} + +void b3JoinThread( b3Thread* t ) +{ + *t = (b3Thread){ 0 }; + b3Free( t, sizeof( b3Thread ) ); +} + +#endif + +// djb2 hash, folded 8 bytes per iteration to shorten the dependency chain. +// memcpy lowers to a single load on most targets; on big-endian we byte-swap so +// the hash value is identical across endianness (preserving cross-platform determinism). +// Equivalent to byte-wise djb2 only in spirit; values differ from the original recurrence. +uint32_t b3Hash( uint32_t hash, const uint8_t* data, int count ) +{ + uint32_t result = hash; + int i = 0; + + while ( i + 8 <= count ) + { + uint64_t word; + memcpy( &word, data + i, sizeof( word ) ); +#if defined( __BYTE_ORDER__ ) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ + word = ( ( word & 0x00000000000000FFULL ) << 56 ) | ( ( word & 0x000000000000FF00ULL ) << 40 ) | + ( ( word & 0x0000000000FF0000ULL ) << 24 ) | ( ( word & 0x00000000FF000000ULL ) << 8 ) | + ( ( word & 0x000000FF00000000ULL ) >> 8 ) | ( ( word & 0x0000FF0000000000ULL ) >> 24 ) | + ( ( word & 0x00FF000000000000ULL ) >> 40 ) | ( ( word & 0xFF00000000000000ULL ) >> 56 ); +#endif + result = ( result << 5 ) + result + (uint32_t)word; + result = ( result << 5 ) + result + (uint32_t)( word >> 32 ); + i += 8; + } + + while ( i < count ) + { + result = ( result << 5 ) + result + data[i]; + i++; + } + + return result; +} diff --git a/src/triangle_manifold.c b/src/triangle_manifold.c new file mode 100644 index 0000000..8c11b95 --- /dev/null +++ b/src/triangle_manifold.c @@ -0,0 +1,1256 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "algorithm.h" +#include "contact.h" +#include "core.h" +#include "manifold.h" +#include "shape.h" + +#include "box3d/base.h" +#include "box3d/collision.h" +#include "box3d/constants.h" + +#include +#include + +typedef struct b3TriangleData +{ + b3Vec3 v1, v2, v3; + b3Vec3 e1, e2, e3; + b3Vec3 center; + b3Plane plane; + int flags; +} b3TriangleData; + +// Indexed by the 3-bit vertex mask +static const b3TriangleFeature s_triangleFeatures[8] = { + b3_featureNone, // 000 (unreachable) + b3_featureVertex1, // 001 + b3_featureVertex2, // 010 + b3_featureEdge1, // 011 v1,v2 + b3_featureVertex3, // 100 + b3_featureEdge3, // 101 v1,v3 + b3_featureEdge2, // 110 v2,v3 + b3_featureTriangleFace, // 111 +}; + +static b3TriangleFeature b3GetTriangleFeature( const b3SimplexCache* cache ) +{ + int count = cache->count; + B3_ASSERT( 0 < count && count < 4 ); + + // Bit i set means triangle vertex i participates in the simplex. + int mask = 0; + for ( int i = 0; i < count; ++i ) + { + B3_ASSERT( cache->indexA[i] < 3 ); + mask |= 1 << cache->indexA[i]; + } + + return s_triangleFeatures[mask]; +} + +void b3CollideSphereAndTriangle( b3LocalManifold* manifold, int capacity, const b3Sphere* sphereA, const b3Vec3* triangleB ) +{ + manifold->pointCount = 0; + + if ( capacity == 0 ) + { + return; + } + + b3Vec3 center = sphereA->center; + b3Vec3 v1 = triangleB[0], v2 = triangleB[1], v3 = triangleB[2]; + b3Plane plane = b3MakePlaneFromPoints( v1, v2, v3 ); + + float offset = b3PlaneSeparation( plane, center ); + if ( offset < 0.0f ) + { + // Cull back side collision + return; + } + + // Closest point on triangle to sphere center + b3TrianglePoint closest = b3ClosestPointOnTriangle( v1, v2, v3, center ); + + // Test separating axis + float squaredDistance = b3DistanceSquared( closest.point, center ); + float speculativeDistance = B3_SPECULATIVE_DISTANCE; + float maxDistance = sphereA->radius + speculativeDistance; + if ( squaredDistance > maxDistance * maxDistance ) + { + return; + } + + float distance = sqrtf( squaredDistance ); + b3Vec3 normal; + if ( distance * distance > 1000.0f * FLT_MIN ) + { + normal = b3MulSV( 1.0f / distance, b3Sub( center, closest.point ) ); + } + else + { + normal = b3Normalize( b3Cross( b3Sub( v2, v1 ), b3Sub( v3, v1 ) ) ); + } + + // contact point mid-way + b3Vec3 contactPoint = b3MulSV( 0.5f, b3Add( b3Sub( center, b3MulSV( sphereA->radius, normal ) ), closest.point ) ); + + manifold->normal = normal; + manifold->pointCount = 1; + manifold->feature = closest.feature; + manifold->squaredDistance = squaredDistance; + + b3LocalManifoldPoint* mp = manifold->points + 0; + mp->point = contactPoint; + mp->separation = distance - sphereA->radius; + mp->pair = b3FeaturePair_single; +} + +static bool b3ClipSegmentToTriangleFace( b3ClipVertex segment[2], const b3Vec3* points, b3Plane plane ) +{ + b3Vec3 vertex1 = points[2]; + for ( int i = 0; i < 3; ++i ) + { + b3Vec3 vertex2 = points[i]; + b3Vec3 tangent = b3Normalize( b3Sub( vertex2, vertex1 ) ); + b3Vec3 binormal = b3Cross( tangent, plane.normal ); + + b3Plane clipPlane = b3MakePlaneFromNormalAndPoint( binormal, vertex1 ); + + int vertexCount = 0; + b3ClipVertex p1 = segment[0]; + b3ClipVertex p2 = segment[1]; + + float distance1 = b3PlaneSeparation( clipPlane, p1.position ); + float distance2 = b3PlaneSeparation( clipPlane, p2.position ); + + // If the points are behind the plane + if ( distance1 <= 0.0f ) + { + segment[vertexCount++] = p1; + } + if ( distance2 <= 0.0f ) + { + segment[vertexCount++] = p2; + } + + // If the points are on different sides of the plane + if ( distance1 * distance2 < 0.0f ) + { + // Find intersection point of edge and plane + float t = distance1 / ( distance1 - distance2 ); + segment[vertexCount].position = b3Lerp( p1.position, p2.position, t ); + segment[vertexCount].pair = distance1 > 0.0f ? p1.pair : p2.pair; + vertexCount++; + } + + if ( vertexCount != 2 ) + { + return false; + } + + vertex1 = vertex2; + } + + return true; +} + +static b3FaceQuery b3QueryTriangleFaceAndCapsule( b3Plane plane, const b3Capsule* capsule ) +{ + float separation1 = b3PlaneSeparation( plane, capsule->center1 ); + float separation2 = b3PlaneSeparation( plane, capsule->center2 ); + + if ( separation1 < separation2 ) + { + return (b3FaceQuery){ + .separation = separation1, + .faceIndex = 0, + .vertexIndex = 0, + }; + } + + return (b3FaceQuery){ + .separation = separation2, + .faceIndex = 0, + .vertexIndex = 1, + }; +} + +static b3EdgeQuery b3QueryTriangleAndCapsuleEdges( const b3Vec3* vertices, const b3Capsule* capsule ) +{ + // Work in the local space of the capsule + b3Vec3 p1 = capsule->center1; + b3Vec3 p2 = capsule->center2; + b3Vec3 capsuleEdge = b3Sub( p2, p1 ); + + b3Vec3 capsuleCenter = b3Lerp( p1, p2, 0.5f ); + + b3Vec3 triangleCenter = b3MulSV( 1.0f / 3.0f, b3Add( vertices[0], b3Add( vertices[1], vertices[2] ) ) ); + + // Find axis of minimum penetration + float maxSeparation = -FLT_MAX; + int maxIndex1 = UINT8_MAX; + int maxIndex2 = UINT8_MAX; + + int edgeIndex = 2; + b3Vec3 v1 = vertices[2]; + for ( int index = 0; index < 3; ++index ) + { + b3Vec3 v2 = vertices[index]; + + b3Vec3 triangleEdge = b3Sub( v2, v1 ); + + float separation = b3EdgeEdgeSeparation( p1, capsuleEdge, capsuleCenter, v1, triangleEdge, triangleCenter ); + if ( separation > maxSeparation ) + { + // Note: We don't exit early if we find a separating axis here since we want to + // find the best one for caching and account for the convex radius later. + maxSeparation = separation; + maxIndex1 = edgeIndex; + maxIndex2 = 0; + } + + v1 = v2; + edgeIndex = index; + } + + // Save result + return (b3EdgeQuery){ + .separation = maxSeparation, + .indexA = (uint8_t)maxIndex1, + .indexB = (uint8_t)maxIndex2, + }; +} + +static void b3BuildTriangleAndCapsuleFaceContact( b3LocalManifold* manifold, const b3Vec3* triangle, b3Plane plane, + const b3Capsule* capsule ) +{ + B3_ASSERT( manifold->pointCount == 0 ); + + b3ClipVertex segment[2]; + segment[0].position = capsule->center1; + segment[0].separation = 0.0f; + segment[0].pair = b3MakeFeaturePair( b3_featureShapeA, 0, b3_featureShapeA, 0 ); + segment[1].position = capsule->center2; + segment[1].separation = 0.0f; + segment[1].pair = b3MakeFeaturePair( b3_featureShapeA, 1, b3_featureShapeA, 1 ); + + bool havePoints = b3ClipSegmentToTriangleFace( segment, triangle, plane ); + if ( havePoints == false ) + { + return; + } + + float distance1 = b3PlaneSeparation( plane, segment[0].position ); + float distance2 = b3PlaneSeparation( plane, segment[1].position ); + + float speculativeDistance = B3_SPECULATIVE_DISTANCE; + if ( distance1 > speculativeDistance && distance2 > speculativeDistance ) + { + return; + } + + // Average points. Half-way between capsule bottom and triangle plane. + b3Vec3 point1 = b3MulSub( segment[0].position, 0.5f * ( distance1 + capsule->radius ), plane.normal ); + b3Vec3 point2 = b3MulSub( segment[1].position, 0.5f * ( distance2 + capsule->radius ), plane.normal ); + + manifold->normal = plane.normal; + manifold->feature = b3_featureTriangleFace; + manifold->pointCount = 2; + + b3LocalManifoldPoint* pt = manifold->points + 0; + pt->point = point1; + pt->separation = distance1 - capsule->radius; + pt->pair = segment[0].pair; + + pt = manifold->points + 1; + pt->point = point2; + pt->separation = distance2 - capsule->radius; + pt->pair = segment[1].pair; +} + +static void b3BuildTriangleAndCapsuleEdgeContact( b3LocalManifold* manifold, const b3Vec3* triangle, const b3Capsule* capsule, + b3EdgeQuery query ) +{ + B3_ASSERT( 0 <= query.indexA && query.indexA < 3 ); + + b3Vec3 p1 = capsule->center1; + b3Vec3 p2 = capsule->center2; + b3Vec3 capsuleEdge = b3Sub( p2, p1 ); + + const b3Vec3* vs = triangle; + + b3Vec3 triangleCenter = b3MulSV( 1.0f / 3.0f, b3Add( vs[0], b3Add( vs[1], vs[2] ) ) ); + b3Vec3 v1 = vs[query.indexA]; + b3Vec3 v2 = vs[( query.indexA + 1 ) % 3]; + b3Vec3 triangleEdge = b3Sub( v2, v1 ); + + b3Vec3 normal = b3Cross( capsuleEdge, triangleEdge ); + normal = b3Normalize( normal ); + + // Normal should point away from triangle center + if ( b3Dot( normal, b3Sub( v1, triangleCenter ) ) < 0.0f ) + { + normal = b3Neg( normal ); + } + + b3ClosestApproachResult result = b3ClosestApproachLines( v1, triangleEdge, p1, capsuleEdge ); + + if ( result.lambda1 < 0.0f || 1.0f < result.lambda1 || result.lambda2 < 0.0f || 1.0f < result.lambda2 ) + { + // closest point beyond end points + return; + } + + b3Vec3 point = b3Lerp( b3MulSub( result.point1, capsule->radius, normal ), result.point2, 0.5f ); + + float separation = b3Dot( normal, b3Sub( result.point2, result.point1 ) ); + B3_VALIDATE( b3AbsFloat( separation - query.separation ) < B3_LINEAR_SLOP ); + + manifold->normal = normal; + manifold->pointCount = 1; + + b3TriangleFeature edgesFeatures[] = { b3_featureEdge1, b3_featureEdge2, b3_featureEdge3 }; + manifold->feature = edgesFeatures[query.indexA]; + + b3LocalManifoldPoint* pt = manifold->points + 0; + pt->point = point; + pt->separation = separation - capsule->radius; + pt->pair = b3MakeFeaturePair( b3_featureShapeA, query.indexA, b3_featureShapeB, query.indexB ); +} + +void b3CollideCapsuleAndTriangle( b3LocalManifold* manifold, int capacity, const b3Capsule* capsuleA, const b3Vec3* triangleB, + b3SimplexCache* cache ) +{ + manifold->pointCount = 0; + + if ( capacity < 2 ) + { + return; + } + + b3Vec3 v1 = triangleB[0], v2 = triangleB[1], v3 = triangleB[2]; + b3Plane plane = b3MakePlaneFromPoints( v1, v2, v3 ); + b3Vec3 capsuleCenter = b3Lerp( capsuleA->center1, capsuleA->center2, 0.5f ); + + float offset = b3PlaneSeparation( plane, capsuleCenter ); + if ( offset < 0.0f ) + { + // Cull back side collision + return; + } + + b3DistanceInput distanceInput; + distanceInput.proxyA = (b3ShapeProxy){ triangleB, 3, 0.0f }; + distanceInput.proxyB = (b3ShapeProxy){ &capsuleA->center1, 2, 0.0f }; + distanceInput.transformA = b3Transform_identity; + distanceInput.transformB = b3Transform_identity; + distanceInput.useRadii = false; + + b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, cache, NULL, 0 ); + + float radius = capsuleA->radius; + if ( distanceOutput.distance > radius + B3_SPECULATIVE_DISTANCE ) + { + // Shapes are separated, persist the cache + return; + } + + if ( distanceOutput.distance > 100.0f * FLT_EPSILON ) + { + // Shallow penetration + b3Vec3 delta = b3Normalize( b3Sub( distanceOutput.pointB, distanceOutput.pointA ) ); + + // Try to create two contact points if closest points difference is nearly parallel to face normal + const float kTolerance = 0.2f; + float cosAngle = b3AbsFloat( b3Dot( plane.normal, delta ) ); + if ( cosAngle > kTolerance ) + { + // Clip capsule segment against side planes of reference face + b3ClipVertex segment[2]; + segment[0].position = capsuleA->center1; + segment[0].separation = 0.0f; + segment[0].pair = b3MakeFeaturePair( b3_featureShapeA, 0, b3_featureShapeA, 0 ); + segment[1].position = capsuleA->center2; + segment[1].separation = 0.0f; + segment[1].pair = b3MakeFeaturePair( b3_featureShapeA, 1, b3_featureShapeA, 1 ); + + bool havePoints = b3ClipSegmentToTriangleFace( segment, triangleB, plane ); + + if ( havePoints == true ) + { + float distance1 = b3PlaneSeparation( plane, segment[0].position ); + float distance2 = b3PlaneSeparation( plane, segment[1].position ); + + b3Vec3 normal = plane.normal; + b3Vec3 point1 = b3MulSub( segment[0].position, 0.5f * ( radius + distance1 ), normal ); + b3Vec3 point2 = b3MulSub( segment[1].position, 0.5f * ( radius + distance2 ), normal ); + + manifold->normal = normal; + manifold->feature = b3_featureTriangleFace; + manifold->pointCount = 2; + + b3LocalManifoldPoint* mp = manifold->points + 0; + mp->point = point1; + mp->separation = distance1 - radius; + mp->pair = segment[0].pair; + + mp = manifold->points + 1; + mp->point = point2; + mp->separation = distance2 - radius; + mp->pair = segment[1].pair; + + return; + } + } + + // Create contact from closest points + b3Vec3 point = b3MulSV( 0.5f, b3Add( b3Sub( distanceOutput.pointA, b3MulSV( radius, delta ) ), distanceOutput.pointB ) ); + + manifold->normal = delta; + manifold->pointCount = 1; + manifold->feature = b3GetTriangleFeature( cache ); + + b3LocalManifoldPoint* mp = manifold->points + 0; + mp->point = point; + mp->separation = distanceOutput.distance - radius; + mp->pair = b3FeaturePair_single; + + return; + } + + // Deep penetration + + b3FaceQuery faceQuery = b3QueryTriangleFaceAndCapsule( plane, capsuleA ); + if ( faceQuery.separation > radius ) + { + // Shapes are separated + return; + } + + b3EdgeQuery edgeQuery = b3QueryTriangleAndCapsuleEdges( triangleB, capsuleA ); + if ( edgeQuery.separation > radius ) + { + // Shapes are separated + return; + } + + // Create face contact + float faceSeparation = faceQuery.separation - radius; + b3BuildTriangleAndCapsuleFaceContact( manifold, triangleB, plane, capsuleA ); + if ( manifold->pointCount == 2 ) + { + faceSeparation = b3MinFloat( manifold->points[0].separation, manifold->points[1].separation ); + } + B3_VALIDATE( faceSeparation <= 0.0f ); + + // Face contact can be empty if it does not realize the axis of minimum penetration. + // Create edge contact if face contact fails or edge contact is significantly better! + const float kRelEdgeTolerance = 0.50f; + const float kAbsTolerance = 1.0f * B3_LINEAR_SLOP; + float edgeSeparation = edgeQuery.separation - radius; + if ( manifold->pointCount == 0 || edgeSeparation > kRelEdgeTolerance * faceSeparation + kAbsTolerance ) + { + // Edge contact + b3BuildTriangleAndCapsuleEdgeContact( manifold, triangleB, capsuleA, edgeQuery ); + } +} + +static inline int b3GetTriangleSupport( b3Vec3* points, b3Vec3 direction ) +{ + int index = 0; + float distance = b3Dot( points[0], direction ); + + float d = b3Dot( points[1], direction ); + if ( d > distance ) + { + distance = d; + index = 1; + } + + d = b3Dot( points[2], direction ); + if ( d > distance ) + { + return 2; + } + + return index; +} + +static b3FaceQuery b3QueryTriangleFace( const b3TriangleData* triangle, const b3Hull* hull ) +{ + const b3Vec3* hullPoints = b3GetHullPoints( hull ); + b3Plane plane = triangle->plane; + int vertexIndex = b3FindHullSupportVertex( hull, b3Neg( plane.normal ) ); + b3Vec3 support = hullPoints[vertexIndex]; + float separation = b3PlaneSeparation( plane, support ); + + return (b3FaceQuery){ + .separation = separation, + .faceIndex = 0, + .vertexIndex = (uint8_t)vertexIndex, + }; +} + +static b3FaceQuery b3QueryHullFace( const b3TriangleData* triangle, const b3Hull* hull ) +{ + const b3Plane* hullPlanes = b3GetHullPlanes( hull ); + int faceCount = hull->faceCount; + + b3Vec3 trianglePoints[] = { triangle->v1, triangle->v2, triangle->v3 }; + + int maxFaceIndex = -1; + int maxVertexIndex = -1; + float maxFaceSeparation = -FLT_MAX; + + for ( int faceIndex = 0; faceIndex < faceCount; ++faceIndex ) + { + b3Plane plane = hullPlanes[faceIndex]; + + int vertexIndex = b3GetTriangleSupport( trianglePoints, b3Neg( plane.normal ) ); + b3Vec3 support = trianglePoints[vertexIndex]; + float separation = b3PlaneSeparation( plane, support ); + if ( separation > maxFaceSeparation ) + { + maxFaceIndex = faceIndex; + maxVertexIndex = vertexIndex; + maxFaceSeparation = separation; + } + } + + return (b3FaceQuery){ + .separation = maxFaceSeparation, + .faceIndex = maxFaceIndex, + .vertexIndex = maxVertexIndex, + }; +} + +static b3EdgeQuery b3TestEdgePairs( const b3TriangleData* triangle, const b3Hull* hull ) +{ + b3EdgeQuery result = { + .separation = -FLT_MAX, + .indexA = B3_NULL_INDEX, + .indexB = B3_NULL_INDEX, + }; + + b3Vec3 trianglePoints[] = { triangle->v1, triangle->v2, triangle->v3 }; + b3Vec3 triangleEdges[] = { triangle->e1, triangle->e2, triangle->e3 }; + // int edgeFlags[] = { b3_concaveEdge1, b3_concaveEdge1, b3_concaveEdge3 }; + +#if B3_FORCE_GHOST_COLLISIONS + int triangleFlags = 0xFF; +#else + int triangleFlags = triangle->flags; +#endif + (void)triangleFlags; + + b3Vec3 triNormal = triangle->plane.normal; + + const b3HullHalfEdge* hullEdges = b3GetHullEdges( hull ); + const b3Vec3* hullPoints = b3GetHullPoints( hull ); + const b3Plane* hullPlanes = b3GetHullPlanes( hull ); + int edgeCount = hull->edgeCount; + + for ( int i = 0; i < edgeCount; i += 2 ) + { + const b3HullHalfEdge* edge = hullEdges + i; + const b3HullHalfEdge* twin = hullEdges + i + 1; + B3_ASSERT( edge->twin == i + 1 && twin->twin == i ); + + b3Vec3 hullPoint = hullPoints[edge->origin]; + b3Vec3 hullEdge = b3Sub( hullPoints[twin->origin], hullPoint ); + + b3Vec3 hullNormal1 = hullPlanes[edge->face].normal; + b3Vec3 hullNormal2 = hullPlanes[twin->face].normal; + + for ( int j = 0; j < 3; ++j ) + { + b3Vec3 triEdge = triangleEdges[j]; + + float cab = b3Dot( hullNormal1, triEdge ); + float dab = b3Dot( hullNormal2, triEdge ); + float bcd = b3Dot( triNormal, hullEdge ); + if ( cab * dab >= 0.0f || cab * bcd <= 0.0f ) + { + continue; + } + + b3Vec3 triPoint = trianglePoints[j]; + float separation = b3EdgeEdgeSeparation( triPoint, triEdge, triangle->center, hullPoint, hullEdge, hull->center ); + + // if ( separation > result.separation && ( edgeFlags[j] & triangleFlags ) == 0 ) + if ( separation > result.separation ) + { + // Note: We don't exit early if we find a separating axis here since we want to + // find the best one for caching. + result.separation = separation; + result.indexA = j; + result.indexB = i; + } + } + } + + return result; +} + +static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, const b3TriangleData* triangle, const b3Hull* hull, + b3FaceQuery query, b3SATCache* cache ) +{ + manifold->pointCount = 0; + + const b3HullFace* hullFaces = b3GetHullFaces( hull ); + const b3HullHalfEdge* hullEdges = b3GetHullEdges( hull ); + const b3Plane* hullPlanes = b3GetHullPlanes( hull ); + const b3Vec3* hullPoints = b3GetHullPoints( hull ); + + // Reference hull face + int refFace = query.faceIndex; + b3Plane refPlane = hullPlanes[refFace]; + + // Build clip polygon from triangle face (the incident face) + b3ClipVertex buffer1[B3_MAX_CLIP_POINTS], buffer2[B3_MAX_CLIP_POINTS]; + + b3Vec3 v1 = triangle->v1; + b3Vec3 v2 = triangle->v2; + b3Vec3 v3 = triangle->v3; + buffer1[0].position = v1; + buffer1[0].separation = b3PlaneSeparation( refPlane, v1 ); + buffer1[0].pair = b3MakeFeaturePair( b3_featureShapeB, 2, b3_featureShapeB, 0 ); + buffer1[1].position = v2; + buffer1[1].separation = b3PlaneSeparation( refPlane, v2 ); + buffer1[1].pair = b3MakeFeaturePair( b3_featureShapeB, 0, b3_featureShapeB, 1 ); + buffer1[2].position = v3; + buffer1[2].separation = b3PlaneSeparation( refPlane, v3 ); + buffer1[2].pair = b3MakeFeaturePair( b3_featureShapeB, 1, b3_featureShapeB, 2 ); + int pointCount = 3; + + // Clip triangle face against side planes of reference face + b3ClipVertex* input = buffer1; + b3ClipVertex* output = buffer2; + + const b3HullFace* face = hullFaces + refFace; + int edgeIndex = face->edge; + + do + { + const b3HullHalfEdge* edge = hullEdges + edgeIndex; + int nextEdgeIndex = edge->next; + const b3HullHalfEdge* next = hullEdges + nextEdgeIndex; + b3Vec3 vertex1 = hullPoints[edge->origin]; + b3Vec3 vertex2 = hullPoints[next->origin]; + b3Vec3 tangent = b3Normalize( b3Sub( vertex2, vertex1 ) ); + b3Vec3 binormal = b3Cross( tangent, refPlane.normal ); + + b3Plane clipPlane = b3MakePlaneFromNormalAndPoint( binormal, vertex1 ); + + pointCount = b3ClipPolygon( output, input, pointCount, clipPlane, edgeIndex, refPlane ); + B3_ASSERT( pointCount <= B3_MAX_CLIP_POINTS ); + + if ( pointCount < 3 ) + { + // Using a stale cache + *cache = (b3SATCache){ 0 }; + return query.separation; + } + + // Swap buffers, output becomes input for the next clipping plane + B3_SWAP( output, input ); + edgeIndex = nextEdgeIndex; + } + while ( edgeIndex != face->edge ); + + pointCount = b3MinInt( pointCount, pointCapacity ); + float minSeparation = FLT_MAX; + + for ( int i = 0; i < pointCount; ++i ) + { + b3ClipVertex* clipPoint = input + i; + + // Move point onto hull face improved culling + b3Vec3 point = b3MulSub( clipPoint->position, clipPoint->separation, refPlane.normal ); + + b3LocalManifoldPoint* pt = manifold->points + i; + pt->point = point; + pt->separation = clipPoint->separation; + pt->pair = b3FlipPair( clipPoint->pair ); + + minSeparation = b3MinFloat( minSeparation, clipPoint->separation ); + } + + if ( minSeparation > B3_SPECULATIVE_DISTANCE ) + { + // This can occur with a stale SAT cache + manifold->pointCount = 0; + *cache = (b3SATCache){ 0 }; + return minSeparation; + } + + manifold->pointCount = pointCount; + manifold->normal = b3Neg( refPlane.normal ); + manifold->feature = b3_featureHullFace; + + // Save cache + cache->separation = minSeparation; + cache->type = b3_faceAxisB; + cache->indexA = (uint8_t)query.vertexIndex; + cache->indexB = (uint8_t)query.faceIndex; + return minSeparation; +} + +static float b3CollideTriangleFace( b3LocalManifold* manifold, int pointCapacity, const b3TriangleData* triangle, + const b3Hull* hull, b3FaceQuery query, b3SATCache* cache ) +{ + B3_VALIDATE( manifold->pointCount == 0 ); + + const b3HullFace* hullFaces = b3GetHullFaces( hull ); + const b3HullHalfEdge* hullEdges = b3GetHullEdges( hull ); + const b3Vec3* hullPoints = b3GetHullPoints( hull ); + + // Find incident face + B3_ASSERT( query.faceIndex == 0 ); + b3Plane refPlane = triangle->plane; + + int incFace = b3FindIncidentFace( hull, refPlane.normal, query.vertexIndex ); + + // Build clip polygon from incident face + b3ClipVertex buffer1[2 * B3_MAX_CLIP_POINTS], buffer2[2 * B3_MAX_CLIP_POINTS]; + int pointCount = 0; + const b3HullFace* face = hullFaces + incFace; + int hullEdgeIndex = face->edge; + + do + { + const b3HullHalfEdge* edge = hullEdges + hullEdgeIndex; + + int nextEdgeIndex = edge->next; + const b3HullHalfEdge* next = hullEdges + nextEdgeIndex; + + b3Vec3 hullPoint = hullPoints[next->origin]; + buffer1[pointCount].position = hullPoint; + buffer1[pointCount].separation = b3PlaneSeparation( refPlane, hullPoint ); + buffer1[pointCount].pair = b3MakeFeaturePair( b3_featureShapeB, hullEdgeIndex, b3_featureShapeB, nextEdgeIndex ); + + pointCount += 1; + hullEdgeIndex = nextEdgeIndex; + } + while ( hullEdgeIndex != face->edge && pointCount < 2 * B3_MAX_CLIP_POINTS ); + + B3_ASSERT( pointCount >= 3 ); + + // Clip incident face against side planes of reference face (triangle) + b3ClipVertex* input = buffer1; + b3ClipVertex* output = buffer2; + + b3Vec3 trianglePoints[] = { triangle->v1, triangle->v2, triangle->v3 }; + b3Vec3 triangleEdges[] = { triangle->e1, triangle->e2, triangle->e3 }; + + for ( int i = 0; i < 3 && pointCount > 0; ++i ) + { + b3Vec3 sideNormal = b3Cross( triangleEdges[i], refPlane.normal ); + sideNormal = b3Normalize( sideNormal ); + + b3Plane clipPlane = b3MakePlaneFromNormalAndPoint( sideNormal, trianglePoints[i] ); + + pointCount = b3ClipPolygon( output, input, pointCount, clipPlane, i, refPlane ); + B3_ASSERT( pointCount <= 2 * B3_MAX_CLIP_POINTS ); + + B3_SWAP( output, input ); + } + + if ( pointCount == 0 ) + { + // Triangle face clipped away. Invalidate cache. + *cache = (b3SATCache){ 0 }; + return FLT_MAX; + } + + pointCount = b3MinInt( pointCount, pointCapacity ); + + float minSeparation = FLT_MAX; + + for ( int i = 0; i < pointCount; ++i ) + { + b3ClipVertex* clipPoint = input + i; + + // Move point onto triangle surface for improved culling + // b3Vec3 point = b3MulSub( clipPoint->position, clipPoint->separation, refPlane.normal ); + b3Vec3 point = clipPoint->position; + + b3LocalManifoldPoint* pt = manifold->points + i; + pt->point = point; + pt->separation = clipPoint->separation; + pt->pair = clipPoint->pair; + + minSeparation = b3MinFloat( minSeparation, clipPoint->separation ); + } + + if ( minSeparation >= B3_SPECULATIVE_DISTANCE ) + { + // This can happens if the objects move a part while re-using a cached axis + *cache = (b3SATCache){ 0 }; + return minSeparation; + } + + manifold->pointCount = pointCount; + manifold->normal = refPlane.normal; + manifold->feature = b3_featureTriangleFace; + + // Save cache + cache->separation = minSeparation; + cache->type = b3_faceAxisA; + cache->indexA = (uint8_t)query.faceIndex; + cache->indexB = (uint8_t)query.vertexIndex; + return minSeparation; +} + +static void b3CollideHullAndTriangleEdges( b3LocalManifold* manifold, int capacity, b3Vec3 trianglePoint, b3Vec3 triangleEdge, + b3Vec3 triangleCenter, const b3Hull* hull, b3EdgeQuery query, b3SATCache* cache ) +{ + B3_VALIDATE( query.separation <= 2.0f * B3_SPECULATIVE_DISTANCE ); + B3_ASSERT( query.indexA < 3 ); + + b3Vec3 cA = triangleCenter; + b3Vec3 pA = trianglePoint; + b3Vec3 eA = triangleEdge; + + const b3HullHalfEdge* edgesB = b3GetHullEdges( hull ); + const b3Vec3* pointsB = b3GetHullPoints( hull ); + const b3HullHalfEdge* edgeB = edgesB + query.indexB; + const b3HullHalfEdge* twinB = edgesB + edgeB->twin; + b3Vec3 pB = pointsB[edgeB->origin]; + b3Vec3 qB = pointsB[twinB->origin]; + b3Vec3 eB = b3Sub( qB, pB ); + + b3Vec3 normal = b3Cross( eA, eB ); + normal = b3Normalize( normal ); + + // Ensure normal points outward from triangle center + float outwardA = b3Dot( normal, b3Sub( pA, cA ) ); + + // Ensure normal points towards hull center + float outwardB = b3Dot( normal, b3Sub( hull->center, pB ) ); + + // Use the largest magnitude. The triangle outward value + // may be unreliable as some angles. + if ( b3AbsFloat( outwardA ) > b3AbsFloat( outwardB ) ) + { + if ( outwardA < 0.0f ) + { + normal = b3Neg( normal ); + } + } + else + { + if ( outwardB < 0.0f ) + { + normal = b3Neg( normal ); + } + } + + // Get the closest points between the infinite edge lines + b3ClosestApproachResult result = b3ClosestApproachLines( pA, eA, pB, eB ); + + // Is one of the closest points outside of the associated edge segment? + if ( capacity == 0 || result.lambda1 < 0.0f || 1.0f < result.lambda1 || result.lambda2 < 0.0f || 1.0f < result.lambda2 ) + { + // Invalid edge pair, no points generated + B3_ASSERT( manifold->pointCount == 0 ); + *cache = (b3SATCache){ 0 }; + return; + } + + // This can slide off the end from caching + float separation = b3Dot( normal, b3Sub( result.point2, result.point1 ) ); + B3_VALIDATE( b3AbsFloat( separation - query.separation ) < B3_LINEAR_SLOP ); + + b3Vec3 point = b3MulSV( 0.5f, b3Add( result.point1, result.point2 ) ); + + b3LocalManifoldPoint* pt = manifold->points + 0; + pt->point = point; + pt->separation = separation; + pt->pair = b3MakeFeaturePair( b3_featureShapeA, query.indexA, b3_featureShapeB, query.indexB ); + + // Save cache + cache->separation = separation; + cache->type = b3_edgePairAxis; + cache->indexA = (uint8_t)query.indexA; + cache->indexB = (uint8_t)query.indexB; + + manifold->normal = normal; + manifold->pointCount = 1; + + b3TriangleFeature edgesFeatures[] = { b3_featureEdge1, b3_featureEdge2, b3_featureEdge3 }; + manifold->feature = edgesFeatures[query.indexA]; +} + +// See "Collision Detection of Convex Polyhedra Based on Duality Transformation" +// Simplified for triangle versus hull +static inline bool b3IsTriangleMinkowskiFace( b3Vec3 triNormal, b3Vec3 triEdge, b3Vec3 hullNormal1, b3Vec3 hullNormal2, + b3Vec3 hullEdge ) +{ + float cab = b3Dot( hullNormal1, triEdge ); + float dab = b3Dot( hullNormal2, triEdge ); + float bcd = b3Dot( triNormal, hullEdge ); + return cab * dab < 0.0f && cab * bcd > 0.0f; +} + +b3AtomicInt b3_triangleConvexCalls; +b3AtomicInt b3_triangleCacheHits; + +// Computes the manifold in the local space of the hull +void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Vec3* triangleB, + int triangleFlags, b3SATCache* cache ) +{ + manifold->pointCount = 0; + manifold->feature = b3_featureNone; + + if ( capacity < 4 ) + { + return; + } + + b3Vec3 v1 = triangleB[0], v2 = triangleB[1], v3 = triangleB[2]; + b3Plane trianglePlane = b3MakePlaneFromPoints( v1, v2, v3 ); + float linearSlop = B3_LINEAR_SLOP; + +#if 1 + float offset = b3PlaneSeparation( trianglePlane, hullA->center ); + if ( cache->type == b3_backsideAxis ) + { + // Use hysteresis to avoid jitter on wavy meshes + if ( b3AbsFloat( cache->separation - offset ) < linearSlop ) + { + return; + } + + cache->type = b3_invalidAxis; + } + + if ( offset < -linearSlop ) + { + // Cull back side collision. Cache offset to add hysteresis. + cache->type = b3_backsideAxis; + cache->separation = offset; + return; + } +#endif + + b3Vec3 triangleCenter = b3MulSV( 1.0f / 3.0f, b3Add( v1, b3Add( v2, v3 ) ) ); + b3Vec3 trianglePoints[] = { v1, v2, v3 }; + b3Vec3 triangleEdges[] = { b3Sub( v2, v1 ), b3Sub( v3, v2 ), b3Sub( v1, v3 ) }; + + b3TriangleData triangle = { + .v1 = v1, + .v2 = v2, + .v3 = v3, + .e1 = triangleEdges[0], + .e2 = triangleEdges[1], + .e3 = triangleEdges[2], + .center = triangleCenter, + .plane = trianglePlane, + .flags = triangleFlags, + }; + + const b3HullHalfEdge* edges = b3GetHullEdges( hullA ); + const b3Plane* hullPlanes = b3GetHullPlanes( hullA ); + const b3Vec3* hullPoints = b3GetHullPoints( hullA ); + + float speculativeDistance = B3_SPECULATIVE_DISTANCE; + cache->hit = 1; + + // Attempt to use the cache to speed up collision + switch ( cache->type ) + { + case b3_faceAxisA: + { + B3_ASSERT( cache->indexA == 0 ); + + int vertexIndex = b3FindHullSupportVertex( hullA, b3Neg( trianglePlane.normal ) ); + b3Vec3 support = hullPoints[vertexIndex]; + float separation = b3PlaneSeparation( trianglePlane, support ); + if ( separation >= speculativeDistance ) + { + // Cache hit, shapes are separated + return; + } + + b3FaceQuery faceQuery; + faceQuery.separation = separation; + faceQuery.faceIndex = cache->indexA; + faceQuery.vertexIndex = vertexIndex; + + // Read cache but don't modify it + b3SATCache localCache = *cache; + float clippedSeparation = b3CollideTriangleFace( manifold, capacity, &triangle, hullA, faceQuery, &localCache ); + + if ( manifold->pointCount > 0 && b3AbsFloat( cache->separation - clippedSeparation ) < linearSlop ) + { + // Cache hit, contact points generated + return; + } + + // Invalidate cache and fall through + manifold->pointCount = 0; + *cache = (b3SATCache){ 0 }; + } + break; + + case b3_faceAxisB: + { + B3_ASSERT( cache->indexB < hullA->faceCount ); + + b3Plane plane = hullPlanes[cache->indexB]; + + // Get triangle support point + int vertexIndex = 0; + float distance = -b3Dot( v1, plane.normal ); + for ( int i = 1; i < 3; ++i ) + { + float d = -b3Dot( trianglePoints[i], plane.normal ); + if ( d > distance ) + { + distance = d; + vertexIndex = i; + } + } + + b3Vec3 support = trianglePoints[vertexIndex]; + + // Separation of triangle support point with hull plane + float separation = b3PlaneSeparation( plane, support ); + if ( separation >= speculativeDistance ) + { + // Cache hit, shapes are separated + return; + } + + // Deep overlap may lead to an invalid cache + // todo confirm + bool isDeep = separation < -2.0f * linearSlop; + + // Don't persist deep cache or allow separation to change too much + if ( isDeep == false ) + { + // Try to rebuild contact from last features + b3FaceQuery faceQuery; + faceQuery.separation = separation; + faceQuery.faceIndex = cache->indexB; + faceQuery.vertexIndex = vertexIndex; + + // Read cache but don't modify it + b3SATCache localCache = *cache; + float clippedSeparation = b3CollideHullFace( manifold, capacity, &triangle, hullA, faceQuery, &localCache ); + + // Cache reuse is only successful if it creates contact points and the clipped separation didn't change much. + if ( manifold->pointCount > 0 && b3AbsFloat( cache->separation - clippedSeparation ) < linearSlop ) + { + // Cache hit, contact points generated + return; + } + } + + // Invalidate cache and fall through + manifold->pointCount = 0; + *cache = (b3SATCache){ 0 }; + } + break; + + case b3_edgePairAxis: + { + B3_ASSERT( cache->indexA < 3 ); + int indexA = cache->indexA; + + b3Vec3 triPoint = trianglePoints[indexA]; + b3Vec3 triEdge = triangleEdges[indexA]; + + B3_ASSERT( cache->indexB < hullA->edgeCount - 1 ); + int indexB = cache->indexB; + + const b3HullHalfEdge* edge2 = edges + indexB; + const b3HullHalfEdge* twin2 = edges + indexB + 1; + B3_ASSERT( edge2->twin == indexB + 1 && twin2->twin == indexB ); + + b3Vec3 hullPoint = hullPoints[edge2->origin]; + b3Vec3 hullEdge = b3Sub( hullPoints[twin2->origin], hullPoint ); + b3Vec3 hullNormal1 = hullPlanes[edge2->face].normal; + b3Vec3 hullNormal2 = hullPlanes[twin2->face].normal; + + // Confirm the edge pair is still a Minkowski face + bool isMinkowski = b3IsTriangleMinkowskiFace( trianglePlane.normal, triEdge, hullNormal1, hullNormal2, hullEdge ); + if ( isMinkowski ) + { + // Transform reference center of the first hull into local space of the second hull + float separation = b3EdgeEdgeSeparation( triPoint, triEdge, triangleCenter, hullPoint, hullEdge, hullA->center ); + if ( separation > speculativeDistance ) + { + // Cache hit, shapes are separated + return; + } + + if ( b3AbsFloat( cache->separation - separation ) < linearSlop ) + { + // Try to rebuild contact from last features + b3EdgeQuery edgeQuery; + edgeQuery.indexA = indexA; + edgeQuery.indexB = indexB; + edgeQuery.separation = separation; + + // Read cache but don't modify it + b3SATCache localCache = *cache; + b3CollideHullAndTriangleEdges( manifold, capacity, triPoint, triEdge, triangleCenter, hullA, edgeQuery, + &localCache ); + + if ( manifold->pointCount > 0 ) + { + // Cache hit, contact point generated + return; + } + } + } + + // Invalidate cache and fall through + *cache = (b3SATCache){ 0 }; + } + break; + + // This case is for testing + case b3_manualFaceAxisA: + { + b3FaceQuery faceQueryA = b3QueryTriangleFace( &triangle, hullA ); + b3CollideTriangleFace( manifold, capacity, &triangle, hullA, faceQueryA, cache ); + return; + } + + // This case is for testing + case b3_manualFaceAxisB: + { + b3FaceQuery faceQueryB = b3QueryHullFace( &triangle, hullA ); + b3CollideHullFace( manifold, capacity, &triangle, hullA, faceQueryB, cache ); + return; + } + + // This case is for testing + case b3_manualEdgePairAxis: + { + b3EdgeQuery edgeQuery = b3TestEdgePairs( &triangle, hullA ); + if ( edgeQuery.indexA != B3_NULL_INDEX ) + { + b3Vec3 trianglePoint = trianglePoints[edgeQuery.indexA]; + b3Vec3 triangleEdge = triangleEdges[edgeQuery.indexA]; + b3CollideHullAndTriangleEdges( manifold, capacity, trianglePoint, triangleEdge, triangleCenter, hullA, edgeQuery, + cache ); + } + return; + } + + default: + B3_ASSERT( cache->type == b3_invalidAxis ); + break; + } + + // Cache miss + cache->hit = 0; + + // Find axis of minimum penetration + b3FaceQuery faceQueryA = b3QueryTriangleFace( &triangle, hullA ); + if ( faceQueryA.separation > speculativeDistance ) + { + // Separating axis found + cache->separation = faceQueryA.separation; + cache->type = b3_faceAxisA; + cache->indexA = 0; + cache->indexB = UINT8_MAX; + return; + } + + b3FaceQuery faceQueryB = b3QueryHullFace( &triangle, hullA ); + if ( faceQueryB.separation > speculativeDistance ) + { + // Separating axis found + cache->separation = faceQueryB.separation; + cache->type = b3_faceAxisB; + cache->indexA = UINT8_MAX; + cache->indexB = (uint8_t)faceQueryB.faceIndex; + return; + } + + b3EdgeQuery edgeQuery = b3TestEdgePairs( &triangle, hullA ); + if ( edgeQuery.separation > speculativeDistance ) + { + // Separating axis found + cache->separation = edgeQuery.separation; + cache->type = b3_edgePairAxis; + cache->indexA = (uint8_t)edgeQuery.indexA; + cache->indexB = (uint8_t)edgeQuery.indexB; + return; + } + + float clippedFaceSeparation; + + // Don't allow a hull face opposed to the triangle face. + b3Vec3 hullNormal = hullPlanes[faceQueryB.faceIndex].normal; + bool pushingUp = b3Dot( hullNormal, trianglePlane.normal ) < 0.0f; + if ( faceQueryB.separation > faceQueryA.separation + linearSlop && pushingUp ) + { + clippedFaceSeparation = b3CollideHullFace( manifold, capacity, &triangle, hullA, faceQueryB, cache ); + } + else + { + clippedFaceSeparation = b3CollideTriangleFace( manifold, capacity, &triangle, hullA, faceQueryA, cache ); + } + + // Does an edge axis exist? + if ( edgeQuery.indexA != B3_NULL_INDEX ) + { + // Idea is to ignore the jenga problem when separated and just use the best axis + // bool separated = clippedFaceSeparation > 0.0f && edgeQuery.separation > 0.0f; + // float maxFaceSeparation = b3MaxFloat( faceQueryA.separation, faceQueryB.separation ); + + // Do edge contact if face contact yield no points or only one point with significantly deeper overlap. + if ( manifold->pointCount == 0 || + ( manifold->pointCount == 1 && edgeQuery.separation > clippedFaceSeparation + linearSlop ) ) + { + B3_ASSERT( 0 <= edgeQuery.indexA && edgeQuery.indexA < 3 ); + b3Vec3 trianglePoint = trianglePoints[edgeQuery.indexA]; + b3Vec3 triangleEdge = triangleEdges[edgeQuery.indexA]; + manifold->pointCount = 0; + b3CollideHullAndTriangleEdges( manifold, capacity, trianglePoint, triangleEdge, triangleCenter, hullA, edgeQuery, + cache ); + } + } + + // Using the speculative distance means that sometimes there are no valid contact points from SAT. + // In this fall back to GJK. This is important to prevent tunneling in rare cases. + if ( manifold->pointCount == 0 ) + { + b3DistanceInput input = { 0 }; + input.proxyA = (b3ShapeProxy){ + .points = triangleB, + .count = 3, + .radius = 0.0f, + }; + input.proxyB = (b3ShapeProxy){ .points = hullPoints, .count = hullA->vertexCount, .radius = 0.0f }; + input.transformA = b3Transform_identity; + input.transformB = b3Transform_identity; + input.useRadii = false; + + b3SimplexCache simplexCache = { 0 }; + b3DistanceOutput output = b3ShapeDistance( &input, &simplexCache, NULL, 0 ); + + if ( output.distance > 0.0f ) + { + B3_ASSERT( 0 < simplexCache.count && simplexCache.count <= 3 ); + + manifold->pointCount = 1; + manifold->feature = b3GetTriangleFeature( &simplexCache ); + manifold->normal = output.normal; + manifold->points[0].point = output.pointB; + manifold->points[0].separation = output.distance; + + // This feature pair not accurate but maybe it doesn't matter + manifold->points[0].pair = b3FeaturePair_single; + } + } +} diff --git a/src/types.c b/src/types.c new file mode 100644 index 0000000..2a89696 --- /dev/null +++ b/src/types.c @@ -0,0 +1,135 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "box3d/types.h" + +#include "core.h" + +#include "box3d/constants.h" + +b3WorldDef b3DefaultWorldDef( void ) +{ + float lengthUnits = b3GetLengthUnitsPerMeter(); + + b3WorldDef def = { 0 }; + def.gravity.x = 0.0f; + def.gravity.y = -10.0f; + def.hitEventThreshold = 1.0f * lengthUnits; + def.restitutionThreshold = 1.0f * lengthUnits; + def.contactSpeed = 3.0f * lengthUnits; + def.contactHertz = 30.0f; + def.contactDampingRatio = 10.0f; + + // 400 meters per second, faster than the speed of sound + def.maximumLinearSpeed = 400.0f * lengthUnits; + + def.enableSleep = true; + def.enableContinuous = true; + def.internalValue = B3_SECRET_COOKIE; + return def; +} + +b3BodyDef b3DefaultBodyDef( void ) +{ + b3BodyDef def = { 0 }; + def.type = b3_staticBody; + def.rotation = b3Quat_identity; + def.sleepThreshold = 0.05f * b3GetLengthUnitsPerMeter(); + def.gravityScale = 1.0f; + def.enableSleep = true; + def.isAwake = true; + def.isEnabled = true; + def.enableContinuousCollision = true; + def.internalValue = B3_SECRET_COOKIE; + return def; +} + +b3Filter b3DefaultFilter( void ) +{ + b3Filter filter = { B3_DEFAULT_CATEGORY_BITS, B3_DEFAULT_MASK_BITS, 0 }; + return filter; +} + +b3QueryFilter b3DefaultQueryFilter( void ) +{ + b3QueryFilter filter = { B3_DEFAULT_CATEGORY_BITS, B3_DEFAULT_MASK_BITS }; + return filter; +} + +b3SurfaceMaterial b3DefaultSurfaceMaterial( void ) +{ + b3SurfaceMaterial surfaceMaterial = { 0 }; + surfaceMaterial.friction = 0.6f; + return surfaceMaterial; +} + +b3ShapeDef b3DefaultShapeDef( void ) +{ + float lengthUnits = b3GetLengthUnitsPerMeter(); + + b3ShapeDef def = { 0 }; + def.baseMaterial = b3DefaultSurfaceMaterial(); + // density of water + def.density = 1000.0f / ( lengthUnits * lengthUnits * lengthUnits ); + def.explosionScale = 1.0f; + def.filter = b3DefaultFilter(); + def.updateBodyMass = true; + def.invokeContactCreation = true; + def.internalValue = B3_SECRET_COOKIE; + return def; +} + +static bool b3EmptyDrawShape( void* userShape, b3Transform transform, b3HexColor color, void* context ) +{ + B3_UNUSED( userShape, transform, color, context ); + return false; +} + +static void b3EmptyDrawSegment( b3Vec3 p1, b3Vec3 p2, b3HexColor color, void* context ) +{ + B3_UNUSED( p1, p2, color, context ); +} + +static void b3EmptyDrawTransform( b3Transform transform, void* context ) +{ + B3_UNUSED( transform, context ); +} + +static void b3EmptyDrawPoint( b3Vec3 p, float size, b3HexColor color, void* context ) +{ + B3_UNUSED( p, size, color, context ); +} + +static void b3EmptyDrawBounds( b3AABB aabb, b3HexColor color, void* context ) +{ + B3_UNUSED( aabb, color, context ); +} + +static void b3EmptyDrawBox( b3Vec3 extents, b3Transform transform, b3HexColor color, void* context ) +{ + B3_UNUSED( extents, transform, color, context ); +} + +static void b3EmptyDrawString( b3Vec3 p, const char* s, b3HexColor color, void* context ) +{ + B3_UNUSED( p, s, color, context ); +} + +b3DebugDraw b3DefaultDebugDraw( void ) +{ + b3DebugDraw draw = { 0 }; + + // These allow the user to skip some implementations and not hit null exceptions. + draw.DrawShapeFcn = b3EmptyDrawShape; + draw.DrawSegmentFcn = b3EmptyDrawSegment; + draw.DrawTransformFcn = b3EmptyDrawTransform; + draw.DrawPointFcn = b3EmptyDrawPoint; + draw.DrawBoundsFcn = b3EmptyDrawBounds; + draw.DrawBoxFcn = b3EmptyDrawBox; + draw.DrawStringFcn = b3EmptyDrawString; + + draw.jointScale = 1.0f; + draw.forceScale = 1.0f; + + return draw; +} diff --git a/src/verstable.h b/src/verstable.h new file mode 100644 index 0000000..c8601e6 --- /dev/null +++ b/src/verstable.h @@ -0,0 +1,2069 @@ +/*------------------------------------------------- VERSTABLE v2.2.1 --------------------------------------------------- + +Verstable is a C99-compatible, open-addressing hash table using quadratic probing and the following additions: + +* All keys that hash (i.e. "belong") to the same bucket (their "home bucket") are linked together by an 11-bit integer + specifying the quadratic displacement, relative to that bucket, of the next key in the chain. + +* If a chain of keys exists for a given bucket, then it always begins at that bucket. To maintain this policy, a 1-bit + flag is used to mark whether the key occupying a bucket belongs there. When inserting a new key, if the bucket it + belongs to is occupied by a key that does not belong there, then the occupying key is evicted and the new key takes + the bucket. + +* A 4-bit fragment of each key's hash code is also stored. + +* The aforementioned metadata associated with each bucket (the 4-bit hash fragment, the 1-bit flag, and the 11-bit link + to the next key in the chain) are stored together in a uint16_t array rather than in the bucket alongside the key and + (optionally) the value. + +One way to conceptualize this scheme is as a chained hash table in which overflowing keys are stored not in separate +memory allocations but in otherwise unused buckets. In this regard, it shares similarities with Malte Skarupke's Bytell +hash table (https://www.youtube.com/watch?v=M2fKMP47slQ) and traditional "coalesced hashing". + +Advantages of this scheme include: + +* Fast lookups impervious to load factor: If the table contains any key belonging to the lookup key's home bucket, then + that bucket contains the first in a traversable chain of all keys belonging to it. Hence, only the home bucket and + other buckets containing keys belonging to it are ever probed. Moreover, the stored hash fragments allow skipping most + non-matching keys in the chain without accessing the actual buckets array or calling the (potentially expensive) key + comparison function. + +* Fast insertions: Insertions are faster than they are in other schemes that move keys around (e.g. Robin Hood) because + they only move, at most, one existing key. + +* Fast, tombstone-free deletions: Deletions, which usually require tombstones in quadratic-probing hash tables, are + tombstone-free and only move, at most, one existing key. + +* Fast iteration: The separate metadata array allows keys in sparsely populated tables to be found without incurring the + frequent cache misses that would result from traversing the buckets array. + +Usage example: + + +---------------------------------------------------------+----------------------------------------------------------+ + | Using the generic macro API (C11 and later): | Using the prefixed functions API (C99 and later): | + +---------------------------------------------------------+----------------------------------------------------------+ + | #include | #include | + | | | + | // Instantiating a set template. | // Instantiating a set template. | + | #define NAME int_set | #define NAME int_set | + | #define KEY_TY int | #define KEY_TY int | + | #include "verstable.h" | #define HASH_FN vt_hash_integer | + | | #define CMPR_FN vt_cmpr_integer | + | // Instantiating a map template. | #include "verstable.h" | + | #define NAME int_int_map | | + | #define KEY_TY int | // Instantiating a map template. | + | #define VAL_TY int | #define NAME int_int_map | + | #include "verstable.h" | #define KEY_TY int | + | | #define VAL_TY int | + | int main( void ) | #define HASH_FN vt_hash_integer | + | { | #define CMPR_FN vt_cmpr_integer | + | // Set. | #include "verstable.h" | + | | | + | int_set our_set; | int main( void ) | + | vt_init( &our_set ); | { | + | | // Set. | + | // Inserting keys. | | + | for( int i = 0; i < 10; ++i ) | int_set our_set; | + | { | int_set_init( &our_set ); | + | int_set_itr itr = vt_insert( &our_set, i ); | | + | if( vt_is_end( itr ) ) | // Inserting keys. | + | { | for( int i = 0; i < 10; ++i ) | + | // Out of memory, so abort. | { | + | vt_cleanup( &our_set ); | int_set_itr itr = | + | return 1; | int_set_insert( &our_set, i ); | + | } | if( int_set_is_end( itr ) ) | + | } | { | + | | // Out of memory, so abort. | + | // Erasing keys. | int_set_cleanup( &our_set ); | + | for( int i = 0; i < 10; i += 3 ) | return 1; | + | vt_erase( &our_set, i ); | } | + | | } | + | // Retrieving keys. | | + | for( int i = 0; i < 10; ++i ) | // Erasing keys. | + | { | for( int i = 0; i < 10; i += 3 ) | + | int_set_itr itr = vt_get( &our_set, i ); | int_set_erase( &our_set, i ); | + | if( !vt_is_end( itr ) ) | | + | printf( "%d ", itr.data->key ); | // Retrieving keys. | + | } | for( int i = 0; i < 10; ++i ) | + | // Printed: 1 2 4 5 7 8 | { | + | | int_set_itr itr = int_set_get( &our_set, i ); | + | // Iteration. | if( !int_set_is_end( itr ) ) | + | for( | printf( "%d ", itr.data->key ); | + | int_set_itr itr = vt_first( &our_set ); | } | + | !vt_is_end( itr ); | // Printed: 1 2 4 5 7 8 | + | itr = vt_next( itr ) | | + | ) | // Iteration. | + | printf( "%d ", itr.data->key ); | for( | + | // Printed: 2 4 7 1 5 8 | int_set_itr itr = | + | | int_set_first( &our_set ); | + | vt_cleanup( &our_set ); | !int_set_is_end( itr ); | + | | itr = int_set_next( itr ) | + | // Map. | ) | + | | printf( "%d ", itr.data->key ); | + | int_int_map our_map; | // Printed: 2 4 7 1 5 8 | + | vt_init( &our_map ); | | + | | int_set_cleanup( &our_set ); | + | // Inserting keys and values. | | + | for( int i = 0; i < 10; ++i ) | // Map. | + | { | | + | int_int_map_itr itr = | int_int_map our_map; | + | vt_insert( &our_map, i, i + 1 ); | int_int_map_init( &our_map ); | + | if( vt_is_end( itr ) ) | | + | { | // Inserting keys and values. | + | // Out of memory, so abort. | for( int i = 0; i < 10; ++i ) | + | vt_cleanup( &our_map ); | { | + | return 1; | int_int_map_itr itr = | + | } | int_int_map_insert( &our_map, i, i + 1 ); | + | } | if( int_int_map_is_end( itr ) ) | + | | { | + | // Erasing keys and values. | // Out of memory, so abort. | + | for( int i = 0; i < 10; i += 3 ) | int_int_map_cleanup( &our_map ); | + | vt_erase( &our_map, i ); | return 1; | + | | } | + | // Retrieving keys and values. | } | + | for( int i = 0; i < 10; ++i ) | | + | { | // Erasing keys and values. | + | int_int_map_itr itr = vt_get( &our_map, i ); | for( int i = 0; i < 10; i += 3 ) | + | if( !vt_is_end( itr ) ) | int_int_map_erase( &our_map, i ); | + | printf( | | + | "%d:%d ", | // Retrieving keys and values. | + | itr.data->key, | for( int i = 0; i < 10; ++i ) | + | itr.data->val | { | + | ); | int_int_map_itr itr = | + | } | int_int_map_get( &our_map, i ); | + | // Printed: 1:2 2:3 4:5 5:6 7:8 8:9 | if( !int_int_map_is_end( itr ) ) | + | | printf( | + | // Iteration. | "%d:%d ", | + | for( | itr.data->key, | + | int_int_map_itr itr = vt_first( &our_map ); | itr.data->val | + | !vt_is_end( itr ); | ); | + | itr = vt_next( itr ) | } | + | ) | // Printed: 1:2 2:3 4:5 5:6 7:8 8:9 | + | printf( | | + | "%d:%d ", | // Iteration. | + | itr.data->key, | for( | + | itr.data->val | int_int_map_itr itr = | + | ); | int_int_map_first( &our_map ); | + | // Printed: 2:3 4:5 7:8 1:2 5:6 8:9 | !int_int_map_is_end( itr ); | + | | itr = int_int_map_next( itr ) | + | vt_cleanup( &our_map ); | ) | + | } | printf( | + | | "%d:%d ", | + | | itr.data->key, | + | | itr.data->val | + | | ); | + | | // Printed: 2:3 4:5 7:8 1:2 5:6 8:9 | + | | | + | | int_int_map_cleanup( &our_map ); | + | | } | + | | | + +---------------------------------------------------------+----------------------------------------------------------+ + +API: + + Instantiating a hash table template: + + Create a new hash table type in the following manner: + + #define NAME + #define KEY_TY + #include "verstable.h" + + The NAME macro specifies the name of hash table type that the library will declare, the prefix for the functions + associated with it, and the prefix for the associated iterator type. + + The KEY_TY macro specifies the key type. + + In C99, it is also always necessary to define HASH_FN and CMPR_FN (see below) before including the header. + + The following macros may also be defined before including the header: + + #define VAL_TY + + The type of the value associated with each key. + If this macro is defined, the hash table acts as a map associating keys with values. + Otherwise, it acts as a set containing only keys. + + #define HASH_FN + + The name of the existing function used to hash each key. + The function should have the signature uint64_t ( KEY_TY key ) and return a 64-bit hash code. + For best performance, the hash function should provide a high level of entropy across all bits. + There are two default hash functions: vt_hash_integer for all integer types up to 64 bits in size, and + vt_hash_string for NULL-terminated strings (i.e. char *). + When KEY_TY is one of such types and the compiler is in C11 mode or later, HASH_FN may be left undefined, in + which case the appropriate default function is inferred from KEY_TY. + Otherwise, HASH_FN must be defined. + + #define CMPR_FN + + The name of the existing function used to compare two keys. + The function should have the signature bool ( KEY_TY key_1, KEY_TY key_2 ) and return true if the two keys are + equal. + There are two default comparison functions: vt_cmpr_integer for all integer types up to 64 bits in size, and + vt_cmpr_string for NULL-terminated strings (i.e. char *). + As with the default hash functions, in C11 or later the appropriate default comparison function is inferred if + KEY_TY is one of such types and CMPR_FN is left undefined. + Otherwise, CMPR_FN must be defined. + + #define MAX_LOAD + + The floating-point load factor at which the hash table automatically doubles the size of its internal buckets + array. + The default is 0.9, i.e. 90%. + + #define KEY_DTOR_FN + + The name of the existing destructor function, with the signature void ( KEY_TY key ), called on a key when it is + erased from the table or replaced by a newly inserted key. + The API functions that may call the key destructor are NAME_insert, NAME_erase, NAME_erase_itr, NAME_clear, + and NAME_cleanup. + + #define VAL_DTOR_FN + + The name of the existing destructor function, with the signature void ( VAL_TY val ), called on a value when it + is erased from the table or replaced by a newly inserted value. + The API functions that may call the value destructor are NAME_insert, NAME_erase, NAME_erase_itr, NAME_clear, + and NAME_cleanup. + + #define CTX_TY + + The type of the hash table type's ctx (context) member. + This member only exists if CTX_TY was defined. + It is intended to be used in conjunction with MALLOC_FN and FREE_FN (see below). + + #define MALLOC_FN + + The name of the existing function used to allocate memory. + If CTX_TY was defined, the signature should be void *( size_t size, CTX_TY *ctx ), where size is the number of + bytes to allocate and ctx points to the table's ctx member. + Otherwise, the signature should be void *( size_t size ). + The default wraps stdlib.h's malloc. + + #define FREE_FN + + The name of the existing function used to free memory. + If CTX_TY was defined, the signature should be void ( void *ptr, size_t size, CTX_TY *ctx ), where ptr points to + the memory to free, size is the number of bytes that were allocated, and ctx points to the table's ctx member. + Otherwise, the signature should be void ( void *ptr, size_t size ). + The default wraps stdlib.h's free. + + #define HEADER_MODE + #define IMPLEMENTATION_MODE + + By default, all hash table functions are defined as static inline functions, the intent being that a given hash + table template should be instantiated once per translation unit; for best performance, this is the recommended + way to use the library. + However, it is also possible to separate the struct definitions and function declarations from the function + definitions such that one implementation can be shared across all translation units (as in a traditional header + and source file pair). + In that case, instantiate a template wherever it is needed by defining HEADER_MODE, along with only NAME, + KEY_TY, and (optionally) VAL_TY, CTX_TY, and header guards, and including the library, e.g.: + + #ifndef INT_INT_MAP_H + #define INT_INT_MAP_H + #define NAME int_int_map + #define KEY_TY int + #define VAL_TY int + #define HEADER_MODE + #include "verstable.h" + #endif + + In one source file, define IMPLEMENTATION_MODE, along with NAME, KEY_TY, and any of the aforementioned optional + macros, and include the library, e.g.: + + #define NAME int_int_map + #define KEY_TY int + #define VAL_TY int + #define HASH_FN vt_hash_integer // C99. + #define CMPR_FN vt_cmpr_integer // C99. + #define MAX_LOAD 0.8 + #define IMPLEMENTATION_MODE + #include "verstable.h" + + Including the library automatically undefines all the aforementioned macros after they have been used to instantiate + the template. + + Functions: + + The functions associated with a hash table type are all prefixed with the name the user supplied via the NAME macro. + In C11 and later, the generic "vt_"-prefixed macros may be used to automatically select the correct version of the + specified function based on the arguments. + + void NAME_init( NAME *table ) + void NAME_init( NAME *table, CTX_TY ctx ) + // C11 generic macro: vt_init. + + Initializes the table for use. + If CTX_TY was defined, ctx sets the table's ctx member. + + bool NAME_init_clone( NAME *table, NAME *source ) + bool NAME_init_clone( NAME *table, NAME *source, CTX_TY ctx ) + // C11 generic macro: vt_init_clone. + + Initializes the table as a shallow copy of the specified source table. + If CTX_TY was defined, ctx sets the table's ctx member. + Returns false in the case of memory allocation failure. + + size_t NAME_size( NAME *table ) // C11 generic macro: vt_size. + + Returns the number of keys currently in the table. + + size_t NAME_bucket_count( NAME *table ) // C11 generic macro: vt_bucket_count. + + Returns the table's current bucket count. + + NAME_itr NAME_insert( NAME *table, KEY_TY key ) + NAME_itr NAME_insert( NAME *table, KEY_TY key, VAL_TY val ) + // C11 generic macro: vt_insert. + + Inserts the specified key (and value, if VAL_TY was defined) into the hash table. + If the same key already exists, then the new key (and value) replaces the existing key (and value). + Returns an iterator to the new key, or an end iterator in the case of memory allocation failure. + + NAME_itr NAME_get_or_insert( NAME *table, KEY_TY key ) + NAME_itr NAME_get_or_insert( NAME *table, KEY_TY key, VAL_TY val ) + // C11 generic macro: vt_get_or_insert. + + Inserts the specified key (and value, if VAL_TY was defined) if it does not already exist in the table. + Returns an iterator to the new key if it was inserted, or an iterator to the existing key, or an end iterator if + the key did not exist but the new key could not be inserted because of memory allocation failure. + Determine whether the key was inserted by comparing the table's size before and after the call. + + NAME_itr NAME_get( NAME *table, KEY_TY key ) // C11 generic macro: vt_get. + + Returns a iterator to the specified key, or an end iterator if no such key exists. + + bool NAME_erase( NAME *table, KEY_TY key ) // C11 generic macro: vt_erase. + + Erases the specified key (and associated value, if VAL_TY was defined), if it exists. + Returns true if a key was erased. + + NAME_itr NAME_erase_itr( NAME *table, NAME_itr itr ) // C11 generic macro: vt_erase_itr. + + Erases the key (and associated value, if VAL_TY was defined) pointed to by the specified iterator. + Returns an iterator to the next key in the table, or an end iterator if the erased key was the last one. + + bool NAME_reserve( NAME *table, size_t size ) // C11 generic macro: vt_reserve. + + Ensures that the bucket count is large enough to support the specified key count (i.e. size) without rehashing. + Returns false if unsuccessful due to memory allocation failure. + + bool NAME_shrink( NAME *table ) // C11 generic macro: vt_shrink. + + Shrinks the bucket count to best accommodate the current size. + Returns false if unsuccessful due to memory allocation failure. + + NAME_itr NAME_first( NAME *table ) // C11 generic macro: vt_first. + + Returns an iterator to the first key in the table, or an end iterator if the table is empty. + + bool NAME_is_end( NAME_itr itr ) // C11 generic macro: vt_is_end. + + Returns true if the iterator is an end iterator. + + NAME_itr NAME_next( NAME_itr itr ) // C11 generic macro: vt_next. + + Returns an iterator to the key after the one pointed to by the specified iterator, or an end iterator if the + specified iterator points to the last key in the table. + + void NAME_clear( NAME *table ) // C11 generic macro: vt_clear. + + Erases all keys (and values, if VAL_TY was defined) in the table. + + void NAME_cleanup( NAME *table ) // C11 generic macro: vt_cleanup. + + Erases all keys (and values, if VAL_TY was defined) in the table, frees all memory associated with it, and + initializes it for reuse. + + Iterators: + + Access the key (and value, if VAL_TY was defined) that an iterator points to using the NAME_itr struct's data + member: + + itr.data->key + itr.data->val + + Functions that may insert new keys (NAME_insert and NAME_get_or_insert), erase keys (NAME_erase and NAME_erase_itr), + or reallocate the internal bucket array (NAME_reserve and NAME_shrink) invalidate all existing iterators. + To delete keys during iteration and resume iterating, use the return value of NAME_erase_itr. + +Version history: + + 06/05/2025 2.2.1: Fixed incorrect signature of NAME_is_end in documentation. + 18/04/2025 2.2.0: Added const qualifier to the table parameter of NAME_size, NAME_bucket_count, NAME_get, and + NAME_first and to the source parameter of NAME_init_clone. + Added default support for const char * strings. + Added support for -Wextra. + Replaced FNV-1a with Wyhash as the default string hash function. + 18/06/2024 2.1.1: Fixed a bug affecting iteration on big-endian platforms under MSVC. + 27/05/2024 2.1.0: Replaced the Murmur3 mixer with the fast-hash mixer as the default integer hash function. + Fixed a bug that could theoretically cause a crash on rehash (triggerable in testing using + NAME_shrink with a maximum load factor significantly higher than 1.0). + 06/02/2024 2.0.0: Improved custom allocator support by introducing the CTX_TY option and allowing user-supplied free + functions to receive the allocation size. + Improved documentation. + Introduced various optimizations, including storing the buckets-array size mask instead of the + bucket count, eliminating empty-table checks, combining the buckets memory and metadata memory into + one allocation, and adding branch prediction macros. + Fixed a bug that caused a key to be used after destruction during erasure. + 12/12/2023 1.0.0: Initial release. + +License (MIT): + + Copyright (c) 2023-2025 Jackson L. Allan + + 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. + +*/ + +/*--------------------------------------------------------------------------------------------------------------------*/ +/* Common header section */ +/*--------------------------------------------------------------------------------------------------------------------*/ + +#ifndef VERSTABLE_H +#define VERSTABLE_H + +#include +#include +#include +#include +#include +#include + +// Two-way concatenation macro. +#define VT_CAT_( a, b ) a##b +#define VT_CAT( a, b ) VT_CAT_( a, b ) + +// Branch optimization macros. +#ifdef __GNUC__ +#define VT_LIKELY( expression ) __builtin_expect( (bool)( expression ), true ) +#define VT_UNLIKELY( expression ) __builtin_expect( (bool)( expression ), false ) +#else +#define VT_LIKELY( expression ) ( expression ) +#define VT_UNLIKELY( expression ) ( expression ) +#endif + +// Masks for manipulating and extracting data from a bucket's uint16_t metadatum. +#define VT_EMPTY 0x0000 +#define VT_HASH_FRAG_MASK 0xF000 // 0b1111000000000000. +#define VT_IN_HOME_BUCKET_MASK 0x0800 // 0b0000100000000000. +#define VT_DISPLACEMENT_MASK 0x07FF // 0b0000011111111111, also denotes the displacement limit. Set to VT_LOAD to 1.0 + // to test proper handling of encroachment on the displacement limit during + // inserts. + +// Extracts a hash fragment from a uint64_t hash code. +// We take the highest four bits so that keys that map (via modulo) to the same bucket have distinct hash fragments. +static inline uint16_t vt_hashfrag( uint64_t hash ) +{ + return ( hash >> 48 ) & VT_HASH_FRAG_MASK; +} + +// Standard quadratic probing formula that guarantees that all buckets are visited when the bucket count is a power of +// two (at least in theory, because the displacement limit could terminate the search early when the bucket count is +// high). +static inline size_t vt_quadratic( uint16_t displacement ) +{ + return ( (size_t)displacement * displacement + displacement ) / 2; +} + +#define VT_MIN_NONZERO_BUCKET_COUNT 8 // Must be a power of two. + +// Function to find the left-most non-zero uint16_t in a uint64_t. +// This function is used when we scan four buckets at a time while iterating and relies on compiler intrinsics wherever +// possible. + +#if defined( __GNUC__ ) && ULLONG_MAX == 0xFFFFFFFFFFFFFFFF + +static inline int vt_first_nonzero_uint16( uint64_t val ) +{ + const uint16_t endian_checker = 0x0001; + if( *(const char *)&endian_checker ) // Little-endian (the compiler will optimize away the check at -O1 and above). + return __builtin_ctzll( val ) / 16; + + return __builtin_clzll( val ) / 16; +} + +#elif defined( _MSC_VER ) && ( defined( _M_X64 ) || defined( _M_ARM64 ) ) + +#include +#pragma intrinsic(_BitScanForward64) +#pragma intrinsic(_BitScanReverse64) + +static inline int vt_first_nonzero_uint16( uint64_t val ) +{ + unsigned long result; + + const uint16_t endian_checker = 0x0001; + if( *(const char *)&endian_checker ) + _BitScanForward64( &result, val ); + else + { + _BitScanReverse64( &result, val ); + result = 63 - result; + } + + return result / 16; +} + +#else + +static inline int vt_first_nonzero_uint16( uint64_t val ) +{ + int result = 0; + + uint32_t half; + memcpy( &half, &val, sizeof( uint32_t ) ); + if( !half ) + result += 2; + + uint16_t quarter; + memcpy( &quarter, (char *)&val + result * sizeof( uint16_t ), sizeof( uint16_t ) ); + if( !quarter ) + result += 1; + + return result; +} + +#endif + +// When the bucket count is zero, setting the metadata pointer to point to a VT_EMPTY placeholder, rather than NULL, +// allows us to avoid checking for a zero bucket count during insertion and lookup. +static const uint16_t vt_empty_placeholder_metadatum = VT_EMPTY; + +// Default hash and comparison functions. + +// Fast-hash, as described by https://jonkagstrom.com/bit-mixer-construction and +// https://code.google.com/archive/p/fast-hash. +// In testing, this hash function provided slightly better performance than the Murmur3 mixer. +static inline uint64_t vt_hash_integer( uint64_t key ) +{ + key ^= key >> 23; + key *= 0x2127599bf4325c37ull; + key ^= key >> 47; + return key; +} + +// For hashing strings, we use the public-domain Wyhash +// (https://github.com/wangyi-fudan/wyhash) with the following modifications: +// * We use a fixed seed and secret (the defaults suggested in the Wyhash repository). +// * We do not handle endianness, so the result will differ depending on the platform. +// * We omit the code optimized for 32-bit platforms. + +static inline void vt_wymum( uint64_t *a, uint64_t *b ) +{ +#if defined( __SIZEOF_INT128__ ) + __uint128_t r = *a; + r *= *b; + *a = (uint64_t)r; + *b = (uint64_t)( r >> 64 ); +#elif defined( _MSC_VER ) && defined( _M_X64 ) + *a = _umul128( *a, *b, b ); +#else + uint64_t ha = *a >> 32; + uint64_t hb = *b >> 32; + uint64_t la = (uint32_t)*a; + uint64_t lb = (uint32_t)*b; + uint64_t rh = ha * hb; + uint64_t rm0 = ha * lb; + uint64_t rm1 = hb * la; + uint64_t rl = la * lb; + uint64_t t = rl + ( rm0 << 32 ); + uint64_t c = t < rl; + uint64_t lo = t + ( rm1 << 32 ); + c += lo < t; + uint64_t hi = rh + ( rm0 >> 32 ) + ( rm1 >> 32 ) + c; + *a = lo; + *b = hi; +#endif +} + +static inline uint64_t vt_wymix( uint64_t a, uint64_t b ) +{ + vt_wymum( &a, &b ); + return a ^ b; +} + +static inline uint64_t vt_wyr8( const unsigned char *p ) +{ + uint64_t v; + memcpy( &v, p, 8 ); + return v; +} + +static inline uint64_t vt_wyr4( const unsigned char *p ) +{ + uint32_t v; + memcpy( &v, p, 4 ); + return v; +} + +static inline uint64_t vt_wyr3( const unsigned char *p, size_t k ) +{ + return ( ( (uint64_t)p[ 0 ] ) << 16 ) | ( ( (uint64_t)p[ k >> 1 ] ) << 8 ) | p[ k - 1 ]; +} + +static inline size_t vt_wyhash( const void *key, size_t len ) +{ + const unsigned char *p = (const unsigned char *)key; + uint64_t seed = 0xca813bf4c7abf0a9ull; + uint64_t a; + uint64_t b; + if( VT_LIKELY( len <= 16 ) ) + { + if( VT_LIKELY( len >= 4 ) ) + { + a = ( vt_wyr4( p ) << 32 ) | vt_wyr4( p + ( ( len >> 3 ) << 2 ) ); + b = ( vt_wyr4( p + len - 4 ) << 32 ) | vt_wyr4( p + len - 4 - ( ( len >> 3 ) << 2 ) ); + } + else if( VT_LIKELY( len > 0 ) ) + { + a = vt_wyr3( p, len ); + b = 0; + } + else + { + a = 0; + b = 0; + } + } + else + { + size_t i = len; + if( VT_UNLIKELY( i >= 48 ) ) + { + uint64_t see1 = seed; + uint64_t see2 = seed; + do{ + seed = vt_wymix( vt_wyr8( p ) ^ 0x8bb84b93962eacc9ull, vt_wyr8( p + 8 ) ^ seed ); + see1 = vt_wymix( vt_wyr8( p + 16 ) ^ 0x4b33a62ed433d4a3ull, vt_wyr8( p + 24 ) ^ see1 ); + see2 = vt_wymix( vt_wyr8( p + 32 ) ^ 0x4d5a2da51de1aa47ull, vt_wyr8( p + 40 ) ^ see2 ); + p += 48; + i -= 48; + } + while( VT_LIKELY( i >= 48 ) ); + seed ^= see1 ^ see2; + } + + while( VT_UNLIKELY( i > 16 ) ) + { + seed = vt_wymix( vt_wyr8( p ) ^ 0x8bb84b93962eacc9ull, vt_wyr8( p + 8 ) ^ seed ); + i -= 16; + p += 16; + } + + a = vt_wyr8( p + i - 16 ); + b = vt_wyr8( p + i - 8 ); + } + + a ^= 0x8bb84b93962eacc9ull; + b ^= seed; + vt_wymum( &a, &b ); + return (size_t)vt_wymix( a ^ 0x2d358dccaa6c78a5ull ^ len, b ^ 0x8bb84b93962eacc9ull ); +} + +static inline uint64_t vt_hash_string( const char *key ) +{ + return vt_wyhash( key, strlen( key ) ); +} + +static inline bool vt_cmpr_integer( uint64_t key_1, uint64_t key_2 ) +{ + return key_1 == key_2; +} + +static inline bool vt_cmpr_string( const char *key_1, const char *key_2 ) +{ + return strcmp( key_1, key_2 ) == 0; +} + +// Default allocation and free functions. + +static inline void *vt_malloc( size_t size ) +{ + return malloc( size ); +} + +static inline void vt_free( void *ptr, size_t size ) +{ + (void)size; + free( ptr ); +} + +static inline void *vt_malloc_with_ctx( size_t size, void *ctx ) +{ + (void)ctx; + return malloc( size ); +} + +static inline void vt_free_with_ctx( void *ptr, size_t size, void *ctx ) +{ + (void)size; + (void)ctx; + free( ptr ); +} + +// The rest of the common header section pertains to the C11 generic macro API. +// This interface is based on the extendible-_Generic mechanism documented in detail at +// https://github.com/JacksonAllan/CC/blob/main/articles/Better_C_Generics_Part_1_The_Extendible_Generic.md. +// In summary, instantiating a template also defines wrappers for the template's types and functions with names in the +// pattern of vt_table_NNNN and vt_init_NNNN, where NNNN is an automatically generated integer unique to the template +// instance in the current translation unit. +// These wrappers plug into _Generic-based API macros, which use preprocessor magic to automatically generate _Generic +// slots for every existing template instance. +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined( VT_NO_C11_GENERIC_API ) + +// Octal counter that supports up to 511 hash table templates. +#define VT_TEMPLATE_COUNT_D1 0 // Digit 1, i.e. least significant digit. +#define VT_TEMPLATE_COUNT_D2 0 +#define VT_TEMPLATE_COUNT_D3 0 + +// Four-way concatenation macro. +#define VT_CAT_4_( a, b, c, d ) a##b##c##d +#define VT_CAT_4( a, b, c, d ) VT_CAT_4_( a, b, c, d ) + +// Provides the current value of the counter as a three-digit octal number preceded by 0. +#define VT_TEMPLATE_COUNT VT_CAT_4( 0, VT_TEMPLATE_COUNT_D3, VT_TEMPLATE_COUNT_D2, VT_TEMPLATE_COUNT_D1 ) + +// _Generic-slot generation macros. + +#define VT_GENERIC_SLOT( ty, fn, n ) , VT_CAT( ty, n ): VT_CAT( fn, n ) +#define VT_R1_0( ty, fn, d3, d2 ) +#define VT_R1_1( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 0 ) ) +#define VT_R1_2( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 1 ) ) VT_R1_1( ty, fn, d3, d2 ) +#define VT_R1_3( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 2 ) ) VT_R1_2( ty, fn, d3, d2 ) +#define VT_R1_4( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 3 ) ) VT_R1_3( ty, fn, d3, d2 ) +#define VT_R1_5( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 4 ) ) VT_R1_4( ty, fn, d3, d2 ) +#define VT_R1_6( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 5 ) ) VT_R1_5( ty, fn, d3, d2 ) +#define VT_R1_7( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 6 ) ) VT_R1_6( ty, fn, d3, d2 ) +#define VT_R1_8( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 7 ) ) VT_R1_7( ty, fn, d3, d2 ) +#define VT_R2_0( ty, fn, d3 ) +#define VT_R2_1( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 0 ) +#define VT_R2_2( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 1 ) VT_R2_1( ty, fn, d3 ) +#define VT_R2_3( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 2 ) VT_R2_2( ty, fn, d3 ) +#define VT_R2_4( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 3 ) VT_R2_3( ty, fn, d3 ) +#define VT_R2_5( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 4 ) VT_R2_4( ty, fn, d3 ) +#define VT_R2_6( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 5 ) VT_R2_5( ty, fn, d3 ) +#define VT_R2_7( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 6 ) VT_R2_6( ty, fn, d3 ) +#define VT_R2_8( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 7 ) VT_R2_7( ty, fn, d3 ) +#define VT_R3_0( ty, fn ) +#define VT_R3_1( ty, fn ) VT_R2_8( ty, fn, 0 ) +#define VT_R3_2( ty, fn ) VT_R2_8( ty, fn, 1 ) VT_R3_1( ty, fn ) +#define VT_R3_3( ty, fn ) VT_R2_8( ty, fn, 2 ) VT_R3_2( ty, fn ) +#define VT_R3_4( ty, fn ) VT_R2_8( ty, fn, 3 ) VT_R3_3( ty, fn ) +#define VT_R3_5( ty, fn ) VT_R2_8( ty, fn, 4 ) VT_R3_4( ty, fn ) +#define VT_R3_6( ty, fn ) VT_R2_8( ty, fn, 5 ) VT_R3_5( ty, fn ) +#define VT_R3_7( ty, fn ) VT_R2_8( ty, fn, 6 ) VT_R3_6( ty, fn ) + +#define VT_GENERIC_SLOTS( ty, fn ) \ +VT_CAT( VT_R1_, VT_TEMPLATE_COUNT_D1 )( ty, fn, VT_TEMPLATE_COUNT_D3, VT_TEMPLATE_COUNT_D2 ) \ +VT_CAT( VT_R2_, VT_TEMPLATE_COUNT_D2 )( ty, fn, VT_TEMPLATE_COUNT_D3 ) \ +VT_CAT( VT_R3_, VT_TEMPLATE_COUNT_D3 )( ty, fn ) \ + +// Actual generic API macros. + +// vt_init must be handled as a special case because it could take one or two arguments, depending on whether CTX_TY +// was defined. +#define VT_ARG_3( _1, _2, _3, ... ) _3 +#define vt_init( ... ) VT_ARG_3( __VA_ARGS__, vt_init_with_ctx, vt_init_without_ctx, )( __VA_ARGS__ ) +#define vt_init_without_ctx( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_init_ ) )( table ) +#define vt_init_with_ctx( table, ... ) _Generic( *( table ) \ + VT_GENERIC_SLOTS( vt_table_, vt_init_ ) \ +)( table, __VA_ARGS__ ) \ + +#define vt_init_clone( table, ... ) _Generic( *( table ) \ + VT_GENERIC_SLOTS( vt_table_, vt_init_clone_ ) \ +)( table, __VA_ARGS__ ) \ + +#define vt_size( table )_Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_size_ ) )( table ) + +#define vt_bucket_count( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_bucket_count_ ) )( table ) + +#define vt_is_end( itr ) _Generic( itr VT_GENERIC_SLOTS( vt_table_itr_, vt_is_end_ ) )( itr ) + +#define vt_insert( table, ... ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_insert_ ) )( table, __VA_ARGS__ ) + +#define vt_get_or_insert( table, ... ) _Generic( *( table ) \ + VT_GENERIC_SLOTS( vt_table_, vt_get_or_insert_ ) \ +)( table, __VA_ARGS__ ) \ + +#define vt_get( table, ... ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_get_ ) )( table, __VA_ARGS__ ) + +#define vt_erase( table, ... ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_erase_ ) )( table, __VA_ARGS__ ) + +#define vt_next( itr ) _Generic( itr VT_GENERIC_SLOTS( vt_table_itr_, vt_next_ ) )( itr ) + +#define vt_erase_itr( table, ... ) _Generic( *( table ) \ + VT_GENERIC_SLOTS( vt_table_, vt_erase_itr_ ) \ +)( table, __VA_ARGS__ ) \ + +#define vt_reserve( table, ... ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_reserve_ ) )( table, __VA_ARGS__ ) + +#define vt_shrink( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_shrink_ ) )( table ) + +#define vt_first( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_first_ ) )( table ) + +#define vt_clear( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_clear_ ) )( table ) + +#define vt_cleanup( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_cleanup_ ) )( table ) + +#endif + +#endif + +/*--------------------------------------------------------------------------------------------------------------------*/ +/* Prefixed structs */ +/*--------------------------------------------------------------------------------------------------------------------*/ + +#ifndef IMPLEMENTATION_MODE + +typedef struct +{ + KEY_TY key; + #ifdef VAL_TY + VAL_TY val; + #endif +} VT_CAT( NAME, _bucket ); + +typedef struct +{ + VT_CAT( NAME, _bucket ) *data; + uint16_t *metadatum; + uint16_t *metadata_end; // Iterators carry an internal end pointer so that NAME_is_end does not need the table to be + // passed in as an argument. + // This also allows for the zero-bucket-count check to occur once in NAME_first, rather than + // repeatedly in NAME_is_end. + size_t home_bucket; // SIZE_MAX if home bucket is unknown. +} VT_CAT( NAME, _itr ); + +typedef struct +{ + size_t key_count; + size_t buckets_mask; // Rather than storing the bucket count directly, we store the bit mask used to reduce a hash + // code or displacement-derived bucket index to the buckets array, i.e. the bucket count minus + // one. + // Consequently, a zero bucket count (i.e. when .metadata points to the placeholder) constitutes + // a special case, represented by all bits unset (i.e. zero). + VT_CAT( NAME, _bucket ) *buckets; + uint16_t *metadata; // As described above, each metadatum consists of a 4-bit hash-code fragment (X), a 1-bit flag + // indicating whether the key in this bucket begins a chain associated with the bucket (Y), and + // an 11-bit value indicating the quadratic displacement of the next key in the chain (Z): + // XXXXYZZZZZZZZZZZ. + #ifdef CTX_TY + CTX_TY ctx; + #endif +} NAME; + +#endif + +/*--------------------------------------------------------------------------------------------------------------------*/ +/* Function prototypes */ +/*--------------------------------------------------------------------------------------------------------------------*/ + +#if defined( HEADER_MODE ) || defined( IMPLEMENTATION_MODE ) +#define VT_API_FN_QUALIFIERS +#else +#define VT_API_FN_QUALIFIERS static inline +#endif + +#ifndef IMPLEMENTATION_MODE + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _init )( + NAME * + #ifdef CTX_TY + , CTX_TY + #endif +); + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _init_clone )( + NAME *, + const NAME * + #ifdef CTX_TY + , CTX_TY + #endif +); + +VT_API_FN_QUALIFIERS size_t VT_CAT( NAME, _size )( const NAME * ); + +VT_API_FN_QUALIFIERS size_t VT_CAT( NAME, _bucket_count )( const NAME * ); + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _is_end )( VT_CAT( NAME, _itr ) ); + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _insert )( + NAME *, + KEY_TY + #ifdef VAL_TY + , VAL_TY + #endif +); + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _get_or_insert )( + NAME *, + KEY_TY + #ifdef VAL_TY + , VAL_TY + #endif +); + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _get )( + const NAME *table, + KEY_TY key +); + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase )( NAME *, KEY_TY ); + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _next )( VT_CAT( NAME, _itr ) ); + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _reserve )( NAME *, size_t ); + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _shrink )( NAME * ); + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _first )( const NAME * ); + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _clear )( NAME * ); + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _cleanup )( NAME * ); + +// Not an API function, but must be prototyped anyway because it is called by the inline NAME_erase_itr below. +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase_itr_raw ) ( NAME *, VT_CAT( NAME, _itr ) ); + +// Erases the key pointed to by itr and returns an iterator to the next key in the table. +// This function must be inlined to ensure that the compiler optimizes away the NAME_fast_forward call if the returned +// iterator is discarded. +#ifdef __GNUC__ +static inline __attribute__((always_inline)) +#elif defined( _MSC_VER ) +static __forceinline +#else +static inline +#endif +VT_CAT( NAME, _itr ) VT_CAT( NAME, _erase_itr )( NAME *table, VT_CAT( NAME, _itr ) itr ) +{ + if( VT_CAT( NAME, _erase_itr_raw )( table, itr ) ) + return VT_CAT( NAME, _next )( itr ); + + return itr; +} + +#endif + +/*--------------------------------------------------------------------------------------------------------------------*/ +/* Function implementations */ +/*--------------------------------------------------------------------------------------------------------------------*/ + +#ifndef HEADER_MODE + +// Default settings. + +#ifndef MAX_LOAD +#define MAX_LOAD 0.9 +#endif + +#ifndef MALLOC_FN +#ifdef CTX_TY +#define MALLOC_FN vt_malloc_with_ctx +#else +#define MALLOC_FN vt_malloc +#endif +#endif + +#ifndef FREE_FN +#ifdef CTX_TY +#define FREE_FN vt_free_with_ctx +#else +#define FREE_FN vt_free +#endif +#endif + +#ifndef HASH_FN +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L +#ifdef _MSC_VER // In MSVC, the compound literal in the _Generic triggers a warning about unused local variables at /W4. +#define HASH_FN \ +_Pragma( "warning( push )" ) \ +_Pragma( "warning( disable: 4189 )" ) \ +_Generic( ( KEY_TY ){ 0 }, char *: vt_hash_string, const char*: vt_hash_string, default: vt_hash_integer ) \ +_Pragma( "warning( pop )" ) +#else +#define HASH_FN _Generic( ( KEY_TY ){ 0 }, \ + char *: vt_hash_string, \ + const char*: vt_hash_string, \ + default: vt_hash_integer \ +) +#endif +#else +#error Hash function inference is only available in C11 and later. In C99, you need to define HASH_FN manually to \ +vt_hash_integer, vt_hash_string, or your own custom function with the signature uint64_t ( KEY_TY ). +#endif +#endif + +#ifndef CMPR_FN +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L +#ifdef _MSC_VER +#define CMPR_FN \ +_Pragma( "warning( push )" ) \ +_Pragma( "warning( disable: 4189 )" ) \ +_Generic( ( KEY_TY ){ 0 }, char *: vt_cmpr_string, const char*: vt_cmpr_string, default: vt_cmpr_integer ) \ +_Pragma( "warning( pop )" ) +#else +#define CMPR_FN _Generic( ( KEY_TY ){ 0 }, \ + char *: vt_cmpr_string, \ + const char*: vt_cmpr_string, \ + default: vt_cmpr_integer \ +) +#endif +#else +#error Comparison function inference is only available in C11 and later. In C99, you need to define CMPR_FN manually \ +to vt_cmpr_integer, vt_cmpr_string, or your own custom function with the signature bool ( KEY_TY, KEY_TY ). +#endif +#endif + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _init )( + NAME *table + #ifdef CTX_TY + , CTX_TY ctx + #endif +) +{ + table->key_count = 0; + table->buckets_mask = 0x0000000000000000ull; + table->buckets = NULL; + table->metadata = (uint16_t *)&vt_empty_placeholder_metadatum; + #ifdef CTX_TY + table->ctx = ctx; + #endif +} + +// For efficiency, especially in the case of a small table, the buckets array and metadata share the same dynamic memory +// allocation: +// +-----------------------------+-----+----------------+--------+ +// | Buckets | Pad | Metadata | Excess | +// +-----------------------------+-----+----------------+--------+ +// Any allocated metadata array requires four excess elements to ensure that iteration functions, which read four +// metadata at a time, never read beyond the end of it. +// This function returns the offset of the beginning of the metadata, i.e. the size of the buckets array plus the +// (usually zero) padding. +// It assumes that the bucket count is not zero. +static inline size_t VT_CAT( NAME, _metadata_offset )( NAME *table ) +{ + // Use sizeof, rather than alignof, for C99 compatibility. + return ( ( ( table->buckets_mask + 1 ) * sizeof( VT_CAT( NAME, _bucket ) ) + sizeof( uint16_t ) - 1 ) / + sizeof( uint16_t ) ) * sizeof( uint16_t ); +} + +// Returns the total allocation size, including the buckets array, padding, metadata, and excess metadata. +// As above, this function assumes that the bucket count is not zero. +static inline size_t VT_CAT( NAME, _total_alloc_size )( NAME *table ) +{ + return VT_CAT( NAME, _metadata_offset )( table ) + ( table->buckets_mask + 1 + 4 ) * sizeof( uint16_t ); +} + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _init_clone )( + NAME *table, + const NAME *source + #ifdef CTX_TY + , CTX_TY ctx + #endif +) +{ + table->key_count = source->key_count; + table->buckets_mask = source->buckets_mask; + #ifdef CTX_TY + table->ctx = ctx; + #endif + + if( !source->buckets_mask ) + { + table->metadata = (uint16_t *)&vt_empty_placeholder_metadatum; + table->buckets = NULL; + return true; + } + + void *allocation = MALLOC_FN( + VT_CAT( NAME, _total_alloc_size )( table ) + #ifdef CTX_TY + , &table->ctx + #endif + ); + + if( VT_UNLIKELY( !allocation ) ) + return false; + + table->buckets = (VT_CAT( NAME, _bucket ) *)allocation; + table->metadata = (uint16_t *)( (unsigned char *)allocation + VT_CAT( NAME, _metadata_offset )( table ) ); + memcpy( allocation, source->buckets, VT_CAT( NAME, _total_alloc_size )( table ) ); + + return true; +} + +VT_API_FN_QUALIFIERS size_t VT_CAT( NAME, _size )( const NAME *table ) +{ + return table->key_count; +} + +VT_API_FN_QUALIFIERS size_t VT_CAT( NAME, _bucket_count )( const NAME *table ) +{ + // If the bucket count is zero, buckets_mask will be zero, not the bucket count minus one. + // We account for this special case by adding (bool)buckets_mask rather than one. + return table->buckets_mask + (bool)table->buckets_mask; +} + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _is_end )( VT_CAT( NAME, _itr ) itr ) +{ + return itr.metadatum == itr.metadata_end; +} + +// Finds the earliest empty bucket in which a key belonging to home_bucket can be placed, assuming that home_bucket +// is already occupied. +// The reason to begin the search at home_bucket, rather than the end of the existing chain, is that keys deleted from +// other chains might have freed up buckets that could fall in this chain before the final key. +// Returns true if an empty bucket within the range of the displacement limit was found, in which case the final two +// pointer arguments contain the index of the empty bucket and its quadratic displacement from home_bucket. +static inline bool VT_CAT( NAME, _find_first_empty )( + NAME *table, + size_t home_bucket, + size_t *empty, + uint16_t *displacement +) +{ + *displacement = 1; + size_t linear_dispacement = 1; + + while( true ) + { + *empty = ( home_bucket + linear_dispacement ) & table->buckets_mask; + if( table->metadata[ *empty ] == VT_EMPTY ) + return true; + + if( VT_UNLIKELY( ++*displacement == VT_DISPLACEMENT_MASK ) ) + return false; + + linear_dispacement += *displacement; + } +} + +// Finds the key in the chain beginning in home_bucket after which to link a new key with displacement_to_empty +// quadratic displacement and returns the index of the bucket containing that key. +// Although the new key could simply be linked to the end of the chain, keeping the chain ordered by displacement +// theoretically improves cache locality during lookups. +static inline size_t VT_CAT( NAME, _find_insert_location_in_chain )( + NAME *table, + size_t home_bucket, + uint16_t displacement_to_empty +) +{ + size_t candidate = home_bucket; + while( true ) + { + uint16_t displacement = table->metadata[ candidate ] & VT_DISPLACEMENT_MASK; + + if( displacement > displacement_to_empty ) + return candidate; + + candidate = ( home_bucket + vt_quadratic( displacement ) ) & table->buckets_mask; + } +} + +// Frees up a bucket occupied by a key not belonging there so that a new key belonging there can be placed there as the +// beginning of a new chain. +// This requires: +// * Finding the previous key in the chain to which the occupying key belongs by rehashing it and then traversing the +// chain. +// * Disconnecting the key from the chain. +// * Finding the appropriate empty bucket to which to move the key. +// * Moving the key (and value) data to the empty bucket. +// * Re-linking the key to the chain. +// Returns true if the eviction succeeded, or false if no empty bucket to which to evict the occupying key could be +// found within the displacement limit. +static inline bool VT_CAT( NAME, _evict )( NAME *table, size_t bucket ) +{ + // Find the previous key in chain. + size_t home_bucket = HASH_FN( table->buckets[ bucket ].key ) & table->buckets_mask; + size_t prev = home_bucket; + while( true ) + { + size_t next = ( home_bucket + vt_quadratic( table->metadata[ prev ] & VT_DISPLACEMENT_MASK ) ) & + table->buckets_mask; + + if( next == bucket ) + break; + + prev = next; + } + + // Disconnect the key from chain. + table->metadata[ prev ] = ( table->metadata[ prev ] & ~VT_DISPLACEMENT_MASK ) | ( table->metadata[ bucket ] & + VT_DISPLACEMENT_MASK ); + + // Find the empty bucket to which to move the key. + size_t empty; + uint16_t displacement; + if( VT_UNLIKELY( !VT_CAT( NAME, _find_first_empty )( table, home_bucket, &empty, &displacement ) ) ) + return false; + + // Find the key in the chain after which to link the moved key. + prev = VT_CAT( NAME, _find_insert_location_in_chain )( table, home_bucket, displacement ); + + // Move the key (and value) data. + table->buckets[ empty ] = table->buckets[ bucket ]; + + // Re-link the key to the chain from its new bucket. + table->metadata[ empty ] = ( table->metadata[ bucket ] & VT_HASH_FRAG_MASK ) | ( table->metadata[ prev ] & + VT_DISPLACEMENT_MASK ); + table->metadata[ prev ] = ( table->metadata[ prev ] & ~VT_DISPLACEMENT_MASK ) | displacement; + + return true; +} + +// Returns an end iterator, i.e. any iterator for which .metadatum == .metadata_end. +// This function just cleans up the library code in functions that return an end iterator as a failure indicator. +static inline VT_CAT( NAME, _itr ) VT_CAT( NAME, _end_itr )( void ) +{ + VT_CAT( NAME, _itr ) itr = { NULL, NULL, NULL, 0 }; + return itr; +} + +// Inserts a key, optionally replacing the existing key if it already exists. +// There are two main cases that must be handled: +// * If the key's home bucket is empty or occupied by a key that does not belong there, then the key is inserted there, +// evicting the occupying key if there is one. +// * Otherwise, the chain of keys beginning at the home bucket is (if unique is false) traversed in search of a matching +// key. +// If none is found, then the new key is inserted at the earliest available bucket, per quadratic probing from the +// home bucket, and then linked to the chain in a manner that maintains its quadratic order. +// The unique argument tells the function whether to skip searching for the key before inserting it (on rehashing, this +// step is unnecessary). +// The replace argument tells the function whether to replace an existing key. +// If replace is true, the function returns an iterator to the inserted key, or an end iterator if the key was not +// inserted because of the maximum load factor or displacement limit constraints. +// If replace is false, then the return value is as described above, except that if the key already exists, the function +// returns an iterator to the existing key. +static inline VT_CAT( NAME, _itr ) VT_CAT( NAME, _insert_raw )( + NAME *table, + KEY_TY key, + #ifdef VAL_TY + VAL_TY *val, + #endif + bool unique, + bool replace +) +{ + uint64_t hash = HASH_FN( key ); + uint16_t hashfrag = vt_hashfrag( hash ); + size_t home_bucket = hash & table->buckets_mask; + + // Case 1: The home bucket is empty or contains a key that doesn't belong there. + // This case also implicitly handles the case of a zero bucket count, since home_bucket will be zero and metadata[ 0 ] + // will be the empty placeholder. + // In that scenario, the zero buckets_mask triggers the below load-factor check. + if( !( table->metadata[ home_bucket ] & VT_IN_HOME_BUCKET_MASK ) ) + { + if( + // Load-factor check. + VT_UNLIKELY( table->key_count + 1 > VT_CAT( NAME, _bucket_count )( table ) * MAX_LOAD ) || + // Vacate the home bucket if it contains a key. + ( table->metadata[ home_bucket ] != VT_EMPTY && VT_UNLIKELY( !VT_CAT( NAME, _evict )( table, home_bucket ) ) ) + ) + return VT_CAT( NAME, _end_itr )(); + + table->buckets[ home_bucket ].key = key; + #ifdef VAL_TY + table->buckets[ home_bucket ].val = *val; + #endif + table->metadata[ home_bucket ] = hashfrag | VT_IN_HOME_BUCKET_MASK | VT_DISPLACEMENT_MASK; + + ++table->key_count; + + VT_CAT( NAME, _itr ) itr = { + table->buckets + home_bucket, + table->metadata + home_bucket, + table->metadata + table->buckets_mask + 1, // Iteration stopper (i.e. the first of the four excess metadata). + home_bucket + }; + return itr; + } + + // Case 2: The home bucket contains the beginning of a chain. + + // Optionally, check the existing chain. + if( !unique ) + { + size_t bucket = home_bucket; + while( true ) + { + if( + ( table->metadata[ bucket ] & VT_HASH_FRAG_MASK ) == hashfrag && + VT_LIKELY( CMPR_FN( table->buckets[ bucket ].key, key ) ) + ) + { + if( replace ) + { + #ifdef KEY_DTOR_FN + KEY_DTOR_FN( table->buckets[ bucket ].key ); + #endif + table->buckets[ bucket ].key = key; + + #ifdef VAL_TY + #ifdef VAL_DTOR_FN + VAL_DTOR_FN( table->buckets[ bucket ].val ); + #endif + table->buckets[ bucket ].val = *val; + #endif + } + + VT_CAT( NAME, _itr ) itr = { + table->buckets + bucket, + table->metadata + bucket, + table->metadata + table->buckets_mask + 1, + home_bucket + }; + return itr; + } + + uint16_t displacement = table->metadata[ bucket ] & VT_DISPLACEMENT_MASK; + if( displacement == VT_DISPLACEMENT_MASK ) + break; + + bucket = ( home_bucket + vt_quadratic( displacement ) ) & table->buckets_mask; + } + } + + size_t empty; + uint16_t displacement; + if( + VT_UNLIKELY( + // Load-factor check. + table->key_count + 1 > VT_CAT( NAME, _bucket_count )( table ) * MAX_LOAD || + // Find the earliest empty bucket, per quadratic probing. + !VT_CAT( NAME, _find_first_empty )( table, home_bucket, &empty, &displacement ) + ) + ) + return VT_CAT( NAME, _end_itr )(); + + // Insert the new key (and value) in the empty bucket and link it to the chain. + + size_t prev = VT_CAT( NAME, _find_insert_location_in_chain )( table, home_bucket, displacement ); + + table->buckets[ empty ].key = key; + #ifdef VAL_TY + table->buckets[ empty ].val = *val; + #endif + table->metadata[ empty ] = hashfrag | ( table->metadata[ prev ] & VT_DISPLACEMENT_MASK ); + table->metadata[ prev ] = ( table->metadata[ prev ] & ~VT_DISPLACEMENT_MASK ) | displacement; + + ++table->key_count; + + VT_CAT( NAME, _itr ) itr = { + table->buckets + empty, + table->metadata + empty, + table->metadata + table->buckets_mask + 1, + home_bucket + }; + return itr; +} + +// Resizes the bucket array. +// This function assumes that bucket_count is a power of two and large enough to accommodate all keys without violating +// the maximum load factor. +// Returns false in the case of allocation failure. +// As this function is called very rarely in _insert and _get_or_insert, ideally it should not be inlined into those +// functions. +// In testing, the no-inline approach showed a performance benefit when inserting existing keys (i.e. replacing). +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wattributes" // Silence warning about combining noinline with static inline. +__attribute__((noinline)) static inline +#elif defined( _MSC_VER ) +__declspec(noinline) static inline +#else +static inline +#endif +bool VT_CAT( NAME, _rehash )( NAME *table, size_t bucket_count ) +{ + // The attempt to resize the bucket array and rehash the keys must occur inside a loop that incrementally doubles the + // target bucket count because a failure could theoretically occur at any load factor due to the displacement limit. + while( true ) + { + NAME new_table = { + 0, + bucket_count - 1, + NULL, + NULL + #ifdef CTX_TY + , table->ctx + #endif + }; + + void *allocation = MALLOC_FN( + VT_CAT( NAME, _total_alloc_size )( &new_table ) + #ifdef CTX_TY + , &new_table.ctx + #endif + ); + + if( VT_UNLIKELY( !allocation ) ) + return false; + + new_table.buckets = (VT_CAT( NAME, _bucket ) *)allocation; + new_table.metadata = (uint16_t *)( (unsigned char *)allocation + VT_CAT( NAME, _metadata_offset )( &new_table ) ); + + memset( new_table.metadata, 0x00, ( bucket_count + 4 ) * sizeof( uint16_t ) ); + + // Iteration stopper at the end of the actual metadata array (i.e. the first of the four excess metadata). + new_table.metadata[ bucket_count ] = 0x01; + + for( size_t bucket = 0; bucket < VT_CAT( NAME, _bucket_count )( table ); ++bucket ) + if( table->metadata[ bucket ] != VT_EMPTY ) + { + VT_CAT( NAME, _itr ) itr = VT_CAT( NAME, _insert_raw )( + &new_table, + table->buckets[ bucket ].key, + #ifdef VAL_TY + &table->buckets[ bucket ].val, + #endif + true, + false + ); + + if( VT_UNLIKELY( VT_CAT( NAME, _is_end )( itr ) ) ) + break; + } + + // If a key could not be reinserted due to the displacement limit, double the bucket count and retry. + if( VT_UNLIKELY( new_table.key_count < table->key_count ) ) + { + FREE_FN( + new_table.buckets, + VT_CAT( NAME, _total_alloc_size )( &new_table ) + #ifdef CTX_TY + , &new_table.ctx + #endif + ); + + bucket_count *= 2; + continue; + } + + if( table->buckets_mask ) + FREE_FN( + table->buckets, + VT_CAT( NAME, _total_alloc_size )( table ) + #ifdef CTX_TY + , &table->ctx + #endif + ); + + *table = new_table; + return true; + } +} +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + +// Inserts a key, replacing the existing key if it already exists. +// This function wraps insert_raw in a loop that handles growing and rehashing the table if a new key cannot be inserted +// because of the maximum load factor or displacement limit constraints. +// Returns an iterator to the inserted key, or an end iterator in the case of allocation failure. +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _insert )( + NAME *table, + KEY_TY key + #ifdef VAL_TY + , VAL_TY val + #endif +) +{ + while( true ) + { + VT_CAT( NAME, _itr ) itr = VT_CAT( NAME, _insert_raw )( + table, + key, + #ifdef VAL_TY + &val, + #endif + false, + true + ); + + if( + // Lookup succeeded, in which case itr points to the found key. + VT_LIKELY( !VT_CAT( NAME, _is_end )( itr ) ) || + // Lookup failed and rehash also fails, in which case itr is an end iterator. + VT_UNLIKELY( + !VT_CAT( NAME, _rehash )( + table, table->buckets_mask ? VT_CAT( NAME, _bucket_count )( table ) * 2 : VT_MIN_NONZERO_BUCKET_COUNT + ) + ) + ) + return itr; + } +} + +// Same as NAME_insert, except that if the key already exists, no insertion occurs and the function returns an iterator +// to the existing key. +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _get_or_insert )( + NAME *table, + KEY_TY key + #ifdef VAL_TY + , VAL_TY val + #endif +) +{ + while( true ) + { + VT_CAT( NAME, _itr ) itr = VT_CAT( NAME, _insert_raw )( + table, + key, + #ifdef VAL_TY + &val, + #endif + false, + false + ); + + if( + // Lookup succeeded, in which case itr points to the found key. + VT_LIKELY( !VT_CAT( NAME, _is_end )( itr ) ) || + // Lookup failed and rehash also fails, in which case itr is an end iterator. + VT_UNLIKELY( + !VT_CAT( NAME, _rehash )( + table, table->buckets_mask ? VT_CAT( NAME, _bucket_count )( table ) * 2 : VT_MIN_NONZERO_BUCKET_COUNT + ) + ) + ) + return itr; + } +} + +// Returns an iterator pointing to the specified key, or an end iterator if the key does not exist. +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _get )( const NAME *table, KEY_TY key ) +{ + uint64_t hash = HASH_FN( key ); + size_t home_bucket = hash & table->buckets_mask; + + // If the home bucket is empty or contains a key that does not belong there, then our key does not exist. + // This check also implicitly handles the case of a zero bucket count, since home_bucket will be zero and + // metadata[ 0 ] will be the empty placeholder. + if( !( table->metadata[ home_bucket ] & VT_IN_HOME_BUCKET_MASK ) ) + return VT_CAT( NAME, _end_itr )(); + + // Traverse the chain of keys belonging to the home bucket. + uint16_t hashfrag = vt_hashfrag( hash ); + size_t bucket = home_bucket; + while( true ) + { + if( + ( table->metadata[ bucket ] & VT_HASH_FRAG_MASK ) == hashfrag && + VT_LIKELY( CMPR_FN( table->buckets[ bucket ].key, key ) ) + ) + { + VT_CAT( NAME, _itr ) itr = { + table->buckets + bucket, + table->metadata + bucket, + table->metadata + table->buckets_mask + 1, + home_bucket + }; + return itr; + } + + uint16_t displacement = table->metadata[ bucket ] & VT_DISPLACEMENT_MASK; + if( displacement == VT_DISPLACEMENT_MASK ) + return VT_CAT( NAME, _end_itr )(); + + bucket = ( home_bucket + vt_quadratic( displacement ) ) & table->buckets_mask; + } +} + +// Erases the key pointed to by the specified iterator. +// The erasure always occurs at the end of the chain to which the key belongs. +// If the key to be erased is not the last in the chain, it is swapped with the last so that erasure occurs at the end. +// This helps keep a chain's keys close to their home bucket for the sake of cache locality. +// Returns true if, in the case of iteration from first to end, NAME_next should now be called on the iterator to find +// the next key. +// This return value is necessary because at the iterator location, the erasure could result in an empty bucket, a +// bucket containing a moved key already visited during the iteration, or a bucket containing a moved key not yet +// visited. +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase_itr_raw )( NAME *table, VT_CAT( NAME, _itr ) itr ) +{ + --table->key_count; + size_t itr_bucket = itr.metadatum - table->metadata; + + // For now, we only call the value's destructor because the key may need to be hashed below to determine the home + // bucket. + #ifdef VAL_DTOR_FN + VAL_DTOR_FN( table->buckets[ itr_bucket ].val ); + #endif + + // Case 1: The key is the only one in its chain, so just remove it. + if( + table->metadata[ itr_bucket ] & VT_IN_HOME_BUCKET_MASK && + ( table->metadata[ itr_bucket ] & VT_DISPLACEMENT_MASK ) == VT_DISPLACEMENT_MASK + ) + { + #ifdef KEY_DTOR_FN + KEY_DTOR_FN( table->buckets[ itr_bucket ].key ); + #endif + table->metadata[ itr_bucket ] = VT_EMPTY; + return true; + } + + // Case 2 and 3 require that we know the key's home bucket, which the iterator may not have recorded. + if( itr.home_bucket == SIZE_MAX ) + { + if( table->metadata[ itr_bucket ] & VT_IN_HOME_BUCKET_MASK ) + itr.home_bucket = itr_bucket; + else + itr.home_bucket = HASH_FN( table->buckets[ itr_bucket ].key ) & table->buckets_mask; + } + + // The key can now be safely destructed for cases 2 and 3. + #ifdef KEY_DTOR_FN + KEY_DTOR_FN( table->buckets[ itr_bucket ].key ); + #endif + + // Case 2: The key is the last in a multi-key chain. + // Traverse the chain from the beginning and find the penultimate key. + // Then disconnect the key and erase. + if( ( table->metadata[ itr_bucket ] & VT_DISPLACEMENT_MASK ) == VT_DISPLACEMENT_MASK ) + { + size_t bucket = itr.home_bucket; + while( true ) + { + uint16_t displacement = table->metadata[ bucket ] & VT_DISPLACEMENT_MASK; + size_t next = ( itr.home_bucket + vt_quadratic( displacement ) ) & table->buckets_mask; + if( next == itr_bucket ) + { + table->metadata[ bucket ] |= VT_DISPLACEMENT_MASK; + table->metadata[ itr_bucket ] = VT_EMPTY; + return true; + } + + bucket = next; + } + } + + // Case 3: The chain has multiple keys, and the key is not the last one. + // Traverse the chain from the key to be erased and find the last and penultimate keys. + // Disconnect the last key from the chain, and swap it with the key to erase. + size_t bucket = itr_bucket; + while( true ) + { + size_t prev = bucket; + bucket = ( itr.home_bucket + vt_quadratic( table->metadata[ bucket ] & VT_DISPLACEMENT_MASK ) ) & + table->buckets_mask; + + if( ( table->metadata[ bucket ] & VT_DISPLACEMENT_MASK ) == VT_DISPLACEMENT_MASK ) + { + table->buckets[ itr_bucket ] = table->buckets[ bucket ]; + + table->metadata[ itr_bucket ] = ( table->metadata[ itr_bucket ] & ~VT_HASH_FRAG_MASK ) | ( + table->metadata[ bucket ] & VT_HASH_FRAG_MASK ); + + table->metadata[ prev ] |= VT_DISPLACEMENT_MASK; + table->metadata[ bucket ] = VT_EMPTY; + + // Whether the iterator should be advanced depends on whether the key moved to the iterator bucket came from + // before or after that bucket. + // In the former case, the iteration would already have hit the moved key, so the iterator should still be + // advanced. + if( bucket > itr_bucket ) + return false; + + return true; + } + } +} + +// Erases the specified key, if it exists. +// Returns true if a key was erased. +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase )( NAME *table, KEY_TY key ) +{ + VT_CAT( NAME, _itr ) itr = VT_CAT( NAME, _get)( table, key ); + if( VT_CAT( NAME, _is_end )( itr ) ) + return false; + + VT_CAT( NAME, _erase_itr_raw )( table, itr ); + return true; +} + +// Finds the first occupied bucket at or after the bucket pointed to by itr. +// This function scans four buckets at a time, ideally using intrinsics. +static inline void VT_CAT( NAME, _fast_forward )( VT_CAT( NAME, _itr ) *itr ) +{ + while( true ) + { + uint64_t metadata; + memcpy( &metadata, itr->metadatum, sizeof( uint64_t ) ); + if( metadata ) + { + int offset = vt_first_nonzero_uint16( metadata ); + itr->data += offset; + itr->metadatum += offset; + itr->home_bucket = SIZE_MAX; + return; + } + + itr->data += 4; + itr->metadatum += 4; + } +} + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _next )( VT_CAT( NAME, _itr ) itr ) +{ + ++itr.data; + ++itr.metadatum; + VT_CAT( NAME, _fast_forward )( &itr ); + return itr; +} + +// Returns the minimum bucket count required to accommodate a certain number of keys, which is governed by the maximum +// load factor. +static inline size_t VT_CAT( NAME, _min_bucket_count_for_size )( size_t size ) +{ + if( size == 0 ) + return 0; + + // Round up to a power of two. + size_t bucket_count = VT_MIN_NONZERO_BUCKET_COUNT; + while( size > bucket_count * MAX_LOAD ) + bucket_count *= 2; + + return bucket_count; +} + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _reserve )( NAME *table, size_t size ) +{ + size_t bucket_count = VT_CAT( NAME, _min_bucket_count_for_size )( size ); + + if( bucket_count <= VT_CAT( NAME, _bucket_count )( table ) ) + return true; + + return VT_CAT( NAME, _rehash )( table, bucket_count ); +} + +VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _shrink )( NAME *table ) +{ + size_t bucket_count = VT_CAT( NAME, _min_bucket_count_for_size )( table->key_count ); + + if( bucket_count == VT_CAT( NAME, _bucket_count )( table ) ) // Shrink unnecessary. + return true; + + if( bucket_count == 0 ) + { + FREE_FN( + table->buckets, + VT_CAT( NAME, _total_alloc_size )( table ) + #ifdef CTX_TY + , &table->ctx + #endif + ); + + table->buckets_mask = 0x0000000000000000ull; + table->metadata = (uint16_t *)&vt_empty_placeholder_metadatum; + return true; + } + + return VT_CAT( NAME, _rehash )( table, bucket_count ); +} + +VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _first )( const NAME *table ) +{ + if( !table->key_count ) + return VT_CAT( NAME, _end_itr )(); + + VT_CAT( NAME, _itr ) itr = { table->buckets, table->metadata, table->metadata + table->buckets_mask + 1, SIZE_MAX }; + VT_CAT( NAME, _fast_forward )( &itr ); + return itr; +} + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _clear )( NAME *table ) +{ + if( !table->key_count ) + return; + + for( size_t i = 0; i < VT_CAT( NAME, _bucket_count )( table ); ++i ) + { + if( table->metadata[ i ] != VT_EMPTY ) + { + #ifdef KEY_DTOR_FN + KEY_DTOR_FN( table->buckets[ i ].key ); + #endif + #ifdef VAL_DTOR_FN + VAL_DTOR_FN( table->buckets[ i ].val ); + #endif + } + + table->metadata[ i ] = VT_EMPTY; + } + + table->key_count = 0; +} + +VT_API_FN_QUALIFIERS void VT_CAT( NAME, _cleanup )( NAME *table ) +{ + if( !table->buckets_mask ) + return; + + #if defined( KEY_DTOR_FN ) || defined( VAL_DTOR_FN ) + VT_CAT( NAME, _clear )( table ); + #endif + + FREE_FN( + table->buckets, + VT_CAT( NAME, _total_alloc_size )( table ) + #ifdef CTX_TY + , &table->ctx + #endif + ); + + VT_CAT( NAME, _init )( + table + #ifdef CTX_TY + , table->ctx + #endif + ); +} + +#endif + +/*--------------------------------------------------------------------------------------------------------------------*/ +/* Wrapper types and functions for the C11 generic API */ +/*--------------------------------------------------------------------------------------------------------------------*/ + +#if defined(__STDC_VERSION__) && \ + __STDC_VERSION__ >= 201112L && \ + !defined( IMPLEMENTATION_MODE ) && \ + !defined( VT_NO_C11_GENERIC_API ) \ + +typedef NAME VT_CAT( vt_table_, VT_TEMPLATE_COUNT ); +typedef VT_CAT( NAME, _itr ) VT_CAT( vt_table_itr_, VT_TEMPLATE_COUNT ); + +static inline void VT_CAT( vt_init_, VT_TEMPLATE_COUNT )( + NAME *table + #ifdef CTX_TY + , CTX_TY ctx + #endif +) +{ + VT_CAT( NAME, _init )( + table + #ifdef CTX_TY + , ctx + #endif + ); +} + +static inline bool VT_CAT( vt_init_clone_, VT_TEMPLATE_COUNT )( + NAME *table, + const NAME* source + #ifdef CTX_TY + , CTX_TY ctx + #endif +) +{ + return VT_CAT( NAME, _init_clone )( + table, + source + #ifdef CTX_TY + , ctx + #endif + ); +} + +static inline size_t VT_CAT( vt_size_, VT_TEMPLATE_COUNT )( const NAME *table ) +{ + return VT_CAT( NAME, _size )( table ); +} + +static inline size_t VT_CAT( vt_bucket_count_, VT_TEMPLATE_COUNT )( const NAME *table ) +{ + return VT_CAT( NAME, _bucket_count )( table ); +} + +static inline bool VT_CAT( vt_is_end_, VT_TEMPLATE_COUNT )( VT_CAT( NAME, _itr ) itr ) +{ + return VT_CAT( NAME, _is_end )( itr ); +} + +static inline VT_CAT( NAME, _itr ) VT_CAT( vt_insert_, VT_TEMPLATE_COUNT )( + NAME *table, + KEY_TY key + #ifdef VAL_TY + , VAL_TY val + #endif +) +{ + return VT_CAT( NAME, _insert )( + table, + key + #ifdef VAL_TY + , val + #endif + ); +} + +static inline VT_CAT( NAME, _itr ) VT_CAT( vt_get_or_insert_, VT_TEMPLATE_COUNT )( + NAME *table, + KEY_TY key + #ifdef VAL_TY + , VAL_TY val + #endif +) +{ + return VT_CAT( NAME, _get_or_insert )( + table, + key + #ifdef VAL_TY + , val + #endif + ); +} + +static inline VT_CAT( NAME, _itr ) VT_CAT( vt_get_, VT_TEMPLATE_COUNT )( const NAME *table, KEY_TY key ) +{ + return VT_CAT( NAME, _get )( table, key ); +} + +static inline bool VT_CAT( vt_erase_, VT_TEMPLATE_COUNT )( NAME *table, KEY_TY key ) +{ + return VT_CAT( NAME, _erase )( table, key ); +} + +static inline VT_CAT( NAME, _itr ) VT_CAT( vt_next_, VT_TEMPLATE_COUNT )( VT_CAT( NAME, _itr ) itr ) +{ + return VT_CAT( NAME, _next )( itr ); +} + +static inline VT_CAT( NAME, _itr ) VT_CAT( vt_erase_itr_, VT_TEMPLATE_COUNT )( NAME *table, VT_CAT( NAME, _itr ) itr ) +{ + return VT_CAT( NAME, _erase_itr )( table, itr ); +} + +static inline bool VT_CAT( vt_reserve_, VT_TEMPLATE_COUNT )( NAME *table, size_t bucket_count ) +{ + return VT_CAT( NAME, _reserve )( table, bucket_count ); +} + +static inline bool VT_CAT( vt_shrink_, VT_TEMPLATE_COUNT )( NAME *table ) +{ + return VT_CAT( NAME, _shrink )( table ); +} + +static inline VT_CAT( NAME, _itr ) VT_CAT( vt_first_, VT_TEMPLATE_COUNT )( const NAME *table ) +{ + return VT_CAT( NAME, _first )( table ); +} + +static inline void VT_CAT( vt_clear_, VT_TEMPLATE_COUNT )( NAME *table ) +{ + VT_CAT( NAME, _clear )( table ); +} + +static inline void VT_CAT( vt_cleanup_, VT_TEMPLATE_COUNT )( NAME *table ) +{ + VT_CAT( NAME, _cleanup )( table ); +} + +// Increment the template counter. +#if VT_TEMPLATE_COUNT_D1 == 0 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 1 +#elif VT_TEMPLATE_COUNT_D1 == 1 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 2 +#elif VT_TEMPLATE_COUNT_D1 == 2 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 3 +#elif VT_TEMPLATE_COUNT_D1 == 3 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 4 +#elif VT_TEMPLATE_COUNT_D1 == 4 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 5 +#elif VT_TEMPLATE_COUNT_D1 == 5 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 6 +#elif VT_TEMPLATE_COUNT_D1 == 6 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 7 +#elif VT_TEMPLATE_COUNT_D1 == 7 +#undef VT_TEMPLATE_COUNT_D1 +#define VT_TEMPLATE_COUNT_D1 0 +#if VT_TEMPLATE_COUNT_D2 == 0 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 1 +#elif VT_TEMPLATE_COUNT_D2 == 1 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 2 +#elif VT_TEMPLATE_COUNT_D2 == 2 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 3 +#elif VT_TEMPLATE_COUNT_D2 == 3 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 4 +#elif VT_TEMPLATE_COUNT_D2 == 4 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 5 +#elif VT_TEMPLATE_COUNT_D2 == 5 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 6 +#elif VT_TEMPLATE_COUNT_D2 == 6 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 7 +#elif VT_TEMPLATE_COUNT_D2 == 7 +#undef VT_TEMPLATE_COUNT_D2 +#define VT_TEMPLATE_COUNT_D2 0 +#if VT_TEMPLATE_COUNT_D3 == 0 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 1 +#elif VT_TEMPLATE_COUNT_D3 == 1 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 2 +#elif VT_TEMPLATE_COUNT_D3 == 2 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 3 +#elif VT_TEMPLATE_COUNT_D3 == 3 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 4 +#elif VT_TEMPLATE_COUNT_D3 == 4 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 5 +#elif VT_TEMPLATE_COUNT_D3 == 5 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 6 +#elif VT_TEMPLATE_COUNT_D3 == 6 +#undef VT_TEMPLATE_COUNT_D3 +#define VT_TEMPLATE_COUNT_D3 7 +#elif VT_TEMPLATE_COUNT_D3 == 7 +#error Sorry, the number of template instances is limited to 511. Define VT_NO_C11_GENERIC_API globally and use the \ +C99 prefixed function API to circumvent this restriction. +#endif +#endif +#endif + +#endif + +#undef NAME +#undef KEY_TY +#undef VAL_TY +#undef HASH_FN +#undef CMPR_FN +#undef MAX_LOAD +#undef KEY_DTOR_FN +#undef VAL_DTOR_FN +#undef CTX_TY +#undef MALLOC_FN +#undef FREE_FN +#undef HEADER_MODE +#undef IMPLEMENTATION_MODE +#undef VT_API_FN_QUALIFIERS diff --git a/src/weld_joint.c b/src/weld_joint.c new file mode 100644 index 0000000..56467b3 --- /dev/null +++ b/src/weld_joint.c @@ -0,0 +1,305 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "body.h" +#include "joint.h" +#include "physics_world.h" +#include "solver.h" +#include "solver_set.h" + +// needed for dll export +#include "box3d/box3d.h" + +void b3WeldJoint_SetLinearHertz( b3JointId jointId, float hertz ) +{ + B3_ASSERT( b3IsValidFloat( hertz ) && hertz >= 0.0f ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_weldJoint ); + base->weldJoint.linearHertz = hertz; +} + +float b3WeldJoint_GetLinearHertz( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_weldJoint ); + return base->weldJoint.linearHertz; +} + +void b3WeldJoint_SetLinearDampingRatio( b3JointId jointId, float dampingRatio ) +{ + B3_ASSERT( b3IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_weldJoint ); + base->weldJoint.linearDampingRatio = dampingRatio; +} + +float b3WeldJoint_GetLinearDampingRatio( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_weldJoint ); + return base->weldJoint.linearDampingRatio; +} + +void b3WeldJoint_SetAngularHertz( b3JointId jointId, float hertz ) +{ + B3_ASSERT( b3IsValidFloat( hertz ) && hertz >= 0.0f ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_weldJoint ); + base->weldJoint.angularHertz = hertz; +} + +float b3WeldJoint_GetAngularHertz( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_weldJoint ); + return base->weldJoint.angularHertz; +} + +void b3WeldJoint_SetAngularDampingRatio( b3JointId jointId, float dampingRatio ) +{ + B3_ASSERT( b3IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_weldJoint ); + base->weldJoint.angularDampingRatio = dampingRatio; +} + +float b3WeldJoint_GetAngularDampingRatio( b3JointId jointId ) +{ + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_weldJoint ); + return base->weldJoint.angularDampingRatio; +} + +b3Vec3 b3GetWeldJointForce( b3World* world, b3JointSim* base ) +{ + b3Vec3 force = b3MulSV( world->inv_h, base->weldJoint.linearImpulse ); + return force; +} + +b3Vec3 b3GetWeldJointTorque( b3World* world, b3JointSim* base ) +{ + return b3MulSV( world->inv_h, base->weldJoint.angularImpulse ); +} + +void b3PrepareWeldJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_weldJoint ); + + b3World* world = context->world; + + b3Body* bodyA = b3Array_Get( world->bodies, base->bodyIdA ); + b3Body* bodyB = b3Array_Get( world->bodies, base->bodyIdB ); + + B3_ASSERT( bodyB->setIndex == b3_awakeSet ); + b3SolverSet* setA = b3Array_Get( world->solverSets, bodyA->setIndex ); + b3SolverSet* setB = b3Array_Get( world->solverSets, bodyB->setIndex ); + + int localIndexA = bodyA->localIndex; + int localIndexB = bodyB->localIndex; + + b3BodySim* bodySimA = b3Array_Get( setA->bodySims, localIndexA ); + b3BodySim* bodySimB = b3Array_Get( setB->bodySims, localIndexB ); + + base->invMassA = bodySimA->invMass; + base->invMassB = bodySimB->invMass; + base->invIA = bodySimA->invInertiaWorld; + base->invIB = bodySimB->invInertiaWorld; + + b3Matrix3 invInertiaSum = b3AddMM( base->invIA, base->invIB ); + base->fixedRotation = b3Det( invInertiaSum ) < 1000.0f * FLT_MIN; + + b3WeldJoint* joint = &base->weldJoint; + joint->indexA = bodyA->setIndex == b3_awakeSet ? localIndexA : B3_NULL_INDEX; + joint->indexB = bodyB->setIndex == b3_awakeSet ? localIndexB : B3_NULL_INDEX; + + // Compute joint anchor frames with world space rotation, relative to center of mass + joint->frameA.q = b3MulQuat( bodySimA->transform.q, base->localFrameA.q ); + joint->frameA.p = b3RotateVector( bodySimA->transform.q, b3Sub( base->localFrameA.p, bodySimA->localCenter ) ); + joint->frameB.q = b3MulQuat( bodySimB->transform.q, base->localFrameB.q ); + joint->frameB.p = b3RotateVector( bodySimB->transform.q, b3Sub( base->localFrameB.p, bodySimB->localCenter ) ); + + joint->deltaCenter = b3Sub( bodySimB->center, bodySimA->center ); + joint->angularMass = b3InvertMatrix( invInertiaSum ); + + if ( joint->linearHertz == 0.0f ) + { + joint->linearSpring = base->constraintSoftness; + } + else + { + joint->linearSpring = b3MakeSoft( joint->linearHertz, joint->linearDampingRatio, context->h ); + } + + if ( joint->angularHertz == 0.0f ) + { + joint->angularSpring = base->constraintSoftness; + } + else + { + joint->angularSpring = b3MakeSoft( joint->angularHertz, joint->angularDampingRatio, context->h ); + } + + if ( context->enableWarmStarting == false ) + { + joint->linearImpulse = b3Vec3_zero; + joint->angularImpulse = b3Vec3_zero; + } +} + +void b3WarmStartWeldJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_weldJoint ); + + float mA = base->invMassA; + float mB = base->invMassB; + b3Matrix3 iA = base->invIA; + b3Matrix3 iB = base->invIB; + + // dummy state for static bodies + b3BodyState dummyState = b3_identityBodyState; + + b3WeldJoint* joint = &base->weldJoint; + + b3BodyState* stateA = joint->indexA == B3_NULL_INDEX ? &dummyState : context->states + joint->indexA; + b3BodyState* stateB = joint->indexB == B3_NULL_INDEX ? &dummyState : context->states + joint->indexB; + + b3Vec3 vA = stateA->linearVelocity; + b3Vec3 wA = stateA->angularVelocity; + b3Vec3 vB = stateB->linearVelocity; + b3Vec3 wB = stateB->angularVelocity; + + b3Vec3 rA = b3RotateVector( stateA->deltaRotation, joint->frameA.p ); + b3Vec3 rB = b3RotateVector( stateB->deltaRotation, joint->frameB.p ); + + vA = b3MulSub( vA, mA, joint->linearImpulse ); + wA = b3Sub( wA, b3MulMV( iA, b3Add( b3Cross( rA, joint->linearImpulse ), joint->angularImpulse ) ) ); + + vB = b3MulAdd( vB, mB, joint->linearImpulse ); + wB = b3Add( wB, b3MulMV( iB, b3Add( b3Cross( rB, joint->linearImpulse ), joint->angularImpulse ) ) ); + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->linearVelocity = vA; + stateA->angularVelocity = wA; + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->linearVelocity = vB; + stateB->angularVelocity = wB; + } +} + +void b3SolveWeldJoint( b3JointSim* base, b3StepContext* context, bool useBias ) +{ + float mA = base->invMassA; + float mB = base->invMassB; + b3Matrix3 iA = base->invIA; + b3Matrix3 iB = base->invIB; + + // dummy state for static bodies + b3BodyState dummyState = b3_identityBodyState; + + b3WeldJoint* joint = &base->weldJoint; + b3BodyState* stateA = joint->indexA == B3_NULL_INDEX ? &dummyState : context->states + joint->indexA; + b3BodyState* stateB = joint->indexB == B3_NULL_INDEX ? &dummyState : context->states + joint->indexB; + + b3Vec3 vA = stateA->linearVelocity; + b3Vec3 wA = stateA->angularVelocity; + b3Vec3 vB = stateB->linearVelocity; + b3Vec3 wB = stateB->angularVelocity; + + bool fixedRotation = base->fixedRotation; + b3Quat quatA = b3MulQuat( stateA->deltaRotation, joint->frameA.q ); + b3Quat quatB = b3MulQuat( stateB->deltaRotation, joint->frameB.q ); + + if ( b3DotQuat( quatA, quatB ) < 0.0f ) + { + // this keeps the rotation angle in the range [-pi, pi] + quatB = b3NegateQuat( quatB ); + } + + b3Quat relQ = b3InvMulQuat( quatA, quatB ); + + // angular constraint + if ( fixedRotation == false ) + { + b3Vec3 bias = b3Vec3_zero; + float massScale = 1.0f; + float impulseScale = 0.0f; + if ( useBias || joint->angularHertz > 0.0f ) + { + b3Quat targetQuat = b3Quat_identity; + b3Vec3 deltaRotation = b3DeltaQuatToRotation( relQ, targetQuat ); + b3Vec3 c = b3Neg( b3RotateVector( quatA, deltaRotation ) ); + + bias = b3MulSV( joint->angularSpring.biasRate, c ); + massScale = joint->angularSpring.massScale; + impulseScale = joint->angularSpring.impulseScale; + } + + b3Vec3 cdot = b3Sub( wB, wA ); + b3Vec3 impulse = b3MulSub( b3MulSV( -massScale, b3MulMV( joint->angularMass, b3Add( cdot, bias ) ) ), impulseScale, joint->angularImpulse ); + joint->angularImpulse = b3Add( joint->angularImpulse, impulse ); + + wA = b3Sub( wA, b3MulMV( iA, impulse ) ); + wB = b3Add( wB, b3MulMV( iB, impulse ) ); + } + + // linear constraint + { + b3Vec3 rA = b3RotateVector( stateA->deltaRotation, joint->frameA.p ); + b3Vec3 rB = b3RotateVector( stateB->deltaRotation, joint->frameB.p ); + + b3Vec3 cdot = b3Sub( b3Add( vB, b3Cross( wB, rB ) ), b3Add( vA, b3Cross( wA, rA ) ) ); + + b3Vec3 bias = b3Vec3_zero; + float massScale = 1.0f; + float impulseScale = 0.0f; + if ( useBias || joint->linearHertz > 0.0f ) + { + b3Vec3 dcA = stateA->deltaPosition; + b3Vec3 dcB = stateB->deltaPosition; + + b3Vec3 separation = b3Add( b3Add( b3Sub( dcB, dcA ), b3Sub( rB, rA ) ), joint->deltaCenter ); + + bias = b3MulSV( joint->linearSpring.biasRate, separation ); + massScale = joint->linearSpring.massScale; + impulseScale = joint->linearSpring.impulseScale; + } + + //// K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] + b3Matrix3 sA = b3Skew( rA ); + b3Matrix3 sB = b3Skew( rB ); + b3Matrix3 kA = b3MulMM( sA, b3MulMM( base->invIA, sA ) ); + b3Matrix3 kB = b3MulMM( sB, b3MulMM( base->invIB, sB ) ); + b3Matrix3 k = b3NegateMat3( b3AddMM( kA, kB ) ); + k.cx.x += mA + mB; + k.cy.y += mA + mB; + k.cz.z += mA + mB; + + b3Vec3 b = b3Solve3( k, b3Add( cdot, bias ) ); + + b3Vec3 impulse = b3MulSub( b3MulSV( -massScale, b ), impulseScale, joint->linearImpulse ); + joint->linearImpulse = b3Add( joint->linearImpulse, impulse ); + + vA = b3MulSub( vA, mA, impulse ); + wA = b3Sub( wA, b3MulMV( iA, b3Cross( rA, impulse ) ) ); + vB = b3MulAdd( vB, mB, impulse ); + wB = b3Add( wB, b3MulMV( iB, b3Cross( rB, impulse ) ) ); + } + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->linearVelocity = vA; + stateA->angularVelocity = wA; + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->linearVelocity = vB; + stateB->angularVelocity = wB; + } +} + +void b3DrawWeldJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale ) +{ + b3Transform frameA = b3MulTransforms( transformA, base->localFrameA ); + b3Transform frameB = b3MulTransforms( transformB, base->localFrameB ); + + b3Vec3 extents = { 0.1f * scale, 0.05f * scale, 0.025f * scale }; + draw->DrawBoxFcn( extents, frameA, b3_colorDarkOrange, draw->context ); + draw->DrawBoxFcn( extents, frameB, b3_colorDarkCyan, draw->context ); +} diff --git a/src/wheel_joint.c b/src/wheel_joint.c new file mode 100644 index 0000000..aa2e30a --- /dev/null +++ b/src/wheel_joint.c @@ -0,0 +1,1076 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "body.h" +#include "core.h" +#include "joint.h" +#include "math_internal.h" +#include "physics_world.h" +#include "solver.h" +#include "solver_set.h" + +// needed for dll export +#include "box3d/box3d.h" + +void b3WheelJoint_EnableSuspension( b3JointId jointId, bool enableSpring ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + + if ( enableSpring != joint->wheelJoint.enableSuspensionSpring ) + { + joint->wheelJoint.enableSuspensionSpring = enableSpring; + joint->wheelJoint.suspensionSpringImpulse = 0.0f; + } +} + +bool b3WheelJoint_IsSuspensionEnabled( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.enableSuspensionSpring; +} + +void b3WheelJoint_SetSuspensionHertz( b3JointId jointId, float hertz ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + joint->wheelJoint.suspensionHertz = hertz; +} + +float b3WheelJoint_GetSuspensionHertz( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.suspensionHertz; +} + +void b3WheelJoint_SetSuspensionDampingRatio( b3JointId jointId, float dampingRatio ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + joint->wheelJoint.suspensionDampingRatio = dampingRatio; +} + +float b3WheelJoint_GetSuspensionDampingRatio( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.suspensionDampingRatio; +} + +void b3WheelJoint_EnableSuspensionLimit( b3JointId jointId, bool enableLimit ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + if ( joint->wheelJoint.enableSuspensionLimit != enableLimit ) + { + joint->wheelJoint.lowerSuspensionImpulse = 0.0f; + joint->wheelJoint.upperSuspensionImpulse = 0.0f; + joint->wheelJoint.enableSuspensionLimit = enableLimit; + } +} + +bool b3WheelJoint_IsSuspensionLimitEnabled( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.enableSuspensionLimit; +} + +float b3WheelJoint_GetLowerSuspensionLimit( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.lowerSuspensionLimit; +} + +float b3WheelJoint_GetUpperSuspensionLimit( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.upperSuspensionLimit; +} + +void b3WheelJoint_SetSuspensionLimits( b3JointId jointId, float lower, float upper ) +{ + B3_ASSERT( lower <= upper ); + + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + if ( lower != joint->wheelJoint.lowerSuspensionLimit || upper != joint->wheelJoint.upperSuspensionLimit ) + { + joint->wheelJoint.lowerSuspensionLimit = lower; + joint->wheelJoint.upperSuspensionLimit = upper; + joint->wheelJoint.lowerSuspensionImpulse = 0.0f; + joint->wheelJoint.upperSuspensionImpulse = 0.0f; + } +} + +void b3WheelJoint_EnableSpinMotor( b3JointId jointId, bool enableMotor ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + if ( joint->wheelJoint.enableSpinMotor != enableMotor ) + { + joint->wheelJoint.spinImpulse = 0.0f; + joint->wheelJoint.enableSpinMotor = enableMotor; + } +} + +bool b3WheelJoint_IsSpinMotorEnabled( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.enableSpinMotor; +} + +void b3WheelJoint_SetSpinMotorSpeed( b3JointId jointId, float motorSpeed ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + joint->wheelJoint.spinSpeed = motorSpeed; +} + +float b3WheelJoint_GetSpinMotorSpeed( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.spinSpeed; +} + +void b3WheelJoint_SetMaxSpinTorque( b3JointId jointId, float torque ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + joint->wheelJoint.maxSpinTorque = torque; +} + +float b3WheelJoint_GetMaxSpinTorque( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.maxSpinTorque; +} + +void b3WheelJoint_EnableSteering( b3JointId jointId, bool flag ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + if ( joint->wheelJoint.enableSteering != flag ) + { + joint->wheelJoint.angularImpulse = (b3Vec2){ 0.0f, 0.0f }; + joint->wheelJoint.enableSteering = flag; + } +} + +bool b3WheelJoint_IsSteeringEnabled( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.enableSteering; +} + +void b3WheelJoint_SetSteeringHertz( b3JointId jointId, float hertz ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + joint->wheelJoint.steeringHertz = hertz; +} + +float b3WheelJoint_GetSteeringHertz( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.steeringHertz; +} + +void b3WheelJoint_SetSteeringDampingRatio( b3JointId jointId, float dampingRatio ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + joint->wheelJoint.steeringDampingRatio = dampingRatio; +} + +float b3WheelJoint_GetSteeringDampingRatio( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.steeringDampingRatio; +} + +void b3WheelJoint_SetMaxSteeringTorque( b3JointId jointId, float maxTorque ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + joint->wheelJoint.maxSteeringTorque = maxTorque; +} + +float b3WheelJoint_GetMaxSteeringTorque( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.maxSteeringTorque; +} + +void b3WheelJoint_EnableSteeringLimit( b3JointId jointId, bool flag ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + if ( joint->wheelJoint.enableSteeringLimit != flag ) + { + joint->wheelJoint.lowerSteeringImpulse = 0.0f; + joint->wheelJoint.upperSteeringImpulse = 0.0f; + joint->wheelJoint.enableSteeringLimit = flag; + } +} + +bool b3WheelJoint_IsSteeringLimitEnabled( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.enableSteeringLimit; +} + +float b3WheelJoint_GetLowerSteeringLimit( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.lowerSteeringLimit; +} + +float b3WheelJoint_GetUpperSteeringLimit( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.upperSteeringLimit; +} + +void b3WheelJoint_SetSteeringLimits( b3JointId jointId, float lowerRadians, float upperRadians ) +{ + B3_ASSERT( lowerRadians <= upperRadians ); + + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + joint->wheelJoint.lowerSteeringLimit = lowerRadians; + joint->wheelJoint.upperSteeringLimit = upperRadians; +} + +void b3WheelJoint_SetTargetSteeringAngle( b3JointId jointId, float radians ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + joint->wheelJoint.targetSteeringAngle = radians; +} + +float b3WheelJoint_GetTargetSteeringAngle( b3JointId jointId ) +{ + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return joint->wheelJoint.targetSteeringAngle; +} + +float b3WheelJoint_GetSpinSpeed( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + + int idA = base->bodyIdA; + int idB = base->bodyIdB; + + b3Body* bodyA = b3Array_Get( world->bodies, idA ); + b3Body* bodyB = b3Array_Get( world->bodies, idB ); + + b3SolverSet* setB = b3Array_Get( world->solverSets, bodyB->setIndex ); + int localIndexB = bodyB->localIndex; + b3BodySim* bodySimB = b3Array_Get( setB->bodySims, localIndexB ); + + b3Quat quatB = b3MulQuat( bodySimB->transform.q, base->localFrameB.q ); + b3Vec3 spinAxis = b3RotateVector( quatB, b3Vec3_axisZ ); + + b3Vec3 wA = b3Vec3_zero; + b3BodyState* stateA = b3GetBodyState( world, bodyA ); + if ( stateA != NULL ) + { + wA = stateA->angularVelocity; + } + + b3Vec3 wB = b3Vec3_zero; + b3BodyState* stateB = b3GetBodyState( world, bodyB ); + if ( stateB != NULL ) + { + wB = stateB->angularVelocity; + } + + float speed = b3Dot( b3Sub( wB, wA ), spinAxis ); + return speed; +} + +float b3WheelJoint_GetSpinTorque( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return world->inv_h * joint->wheelJoint.spinImpulse; +} + +float b3WheelJoint_GetSteeringAngle( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3JointSim* base = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + + int idA = base->bodyIdA; + int idB = base->bodyIdB; + + b3Body* bodyA = b3Array_Get( world->bodies, idA ); + b3Body* bodyB = b3Array_Get( world->bodies, idB ); + + b3SolverSet* setA = b3Array_Get( world->solverSets, bodyA->setIndex ); + b3SolverSet* setB = b3Array_Get( world->solverSets, bodyB->setIndex ); + + int localIndexA = bodyA->localIndex; + int localIndexB = bodyB->localIndex; + + b3BodySim* bodySimA = b3Array_Get( setA->bodySims, localIndexA ); + b3BodySim* bodySimB = b3Array_Get( setB->bodySims, localIndexB ); + + b3Quat quatA = b3MulQuat( bodySimA->transform.q, base->localFrameA.q ); + b3Quat quatB = b3MulQuat( bodySimB->transform.q, base->localFrameB.q ); + + b3Matrix3 matrixA = b3MakeMatrixFromQuat( quatA ); + b3Matrix3 matrixB = b3MakeMatrixFromQuat( quatB ); + + // Twist around x-axis + float cs = b3Dot( matrixB.cz, matrixA.cz ); + float ss = -b3Dot( matrixB.cz, matrixA.cy ); + + return b3Atan2( ss, cs ); +} + +float b3WheelJoint_GetSteeringTorque( b3JointId jointId ) +{ + b3World* world = b3GetWorld( jointId.world0 ); + b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint ); + return world->inv_h * joint->wheelJoint.steeringSpringImpulse; +} + +b3Vec3 b3GetWheelJointForce( b3World* world, b3JointSim* base ) +{ + b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA ); + b3WheelJoint* joint = &base->wheelJoint; + + // impulse in joint space + b3Vec3 impulse = { + joint->linearImpulse.x, + joint->linearImpulse.y, + joint->lowerSuspensionLimit + joint->upperSuspensionImpulse + joint->suspensionSpringImpulse, + }; + + // convert impulse to force + b3Vec3 force = b3MulSV( world->inv_h, impulse ); + + // convert to body space + force = b3RotateVector( base->localFrameA.q, force ); + + // convert to world space + force = b3RotateVector( transformA.q, force ); + return force; +} + +b3Vec3 b3GetWheelJointTorque( b3World* world, b3JointSim* base ) +{ + B3_ASSERT( base->type == b3_wheelJoint ); + + // chase body id to the solver set where the body lives + int idA = base->bodyIdA; + // int idB = base->bodyIdB; + + b3Body* bodyA = b3Array_Get( world->bodies, idA ); + // b3Body* bodyB = b3Array_Get( world->bodies, idB ); + + b3SolverSet* setA = b3Array_Get( world->solverSets, bodyA->setIndex ); + // b3SolverSet* setB = b3Array_Get( world->solverSets, bodyB->setIndex ); + + int localIndexA = bodyA->localIndex; + // int localIndexB = bodyB->localIndex; + + b3BodySim* bodySimA = b3Array_Get( setA->bodySims, localIndexA ); + // b3BodySim* bodySimB = b3Array_Get( setB->bodySims, localIndexB ); + + b3Quat qA = b3MulQuat( bodySimA->transform.q, base->localFrameA.q ); + + b3Matrix3 matrixA = b3MakeMatrixFromQuat( qA ); + + return b3MulSV( world->inv_h * base->wheelJoint.spinImpulse, matrixA.cz ); +} + +// See constraints.pdf + +void b3PrepareWheelJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_wheelJoint ); + + // chase body id to the solver set where the body lives + int idA = base->bodyIdA; + int idB = base->bodyIdB; + + b3World* world = context->world; + + b3Body* bodyA = b3Array_Get( world->bodies, idA ); + b3Body* bodyB = b3Array_Get( world->bodies, idB ); + + B3_ASSERT( bodyA->setIndex == b3_awakeSet || bodyB->setIndex == b3_awakeSet ); + b3SolverSet* setA = b3Array_Get( world->solverSets, bodyA->setIndex ); + b3SolverSet* setB = b3Array_Get( world->solverSets, bodyB->setIndex ); + + int localIndexA = bodyA->localIndex; + int localIndexB = bodyB->localIndex; + + b3BodySim* bodySimA = b3Array_Get( setA->bodySims, localIndexA ); + b3BodySim* bodySimB = b3Array_Get( setB->bodySims, localIndexB ); + + base->invMassA = bodySimA->invMass; + base->invMassB = bodySimB->invMass; + base->invIA = bodySimA->invInertiaWorld; + base->invIB = bodySimB->invInertiaWorld; + + b3Matrix3 invInertiaSum = b3AddMM( base->invIA, base->invIB ); + base->fixedRotation = b3Det( invInertiaSum ) < 1000.0f * FLT_MIN; + + b3WheelJoint* joint = &base->wheelJoint; + + joint->indexA = bodyA->setIndex == b3_awakeSet ? localIndexA : B3_NULL_INDEX; + joint->indexB = bodyB->setIndex == b3_awakeSet ? localIndexB : B3_NULL_INDEX; + + // Compute joint anchor frames with world space rotation, relative to center of mass + joint->frameA.q = b3MulQuat( bodySimA->transform.q, base->localFrameA.q ); + joint->frameA.p = b3RotateVector( bodySimA->transform.q, b3Sub( base->localFrameA.p, bodySimA->localCenter ) ); + joint->frameB.q = b3MulQuat( bodySimB->transform.q, base->localFrameB.q ); + joint->frameB.p = b3RotateVector( bodySimB->transform.q, b3Sub( base->localFrameB.p, bodySimB->localCenter ) ); + + // Compute the initial center delta. Incremental position updates are relative to this. + joint->deltaCenter = b3Sub( bodySimB->center, bodySimA->center ); + + b3Vec3 rA = joint->frameA.p; + b3Vec3 rB = joint->frameB.p; + + b3Matrix3 matrixA = b3MakeMatrixFromQuat( joint->frameA.q ); + b3Matrix3 matrixB = b3MakeMatrixFromQuat( joint->frameB.q ); + + // todo use fresh effective masses in the sub-step to avoid divergence like I saw for the prismatic joint + + { + b3Vec3 suspensionAxis = matrixA.cx; + b3Vec3 rAn = b3Cross( rA, suspensionAxis ); + b3Vec3 rBn = b3Cross( rB, suspensionAxis ); + + float k = base->invMassA + base->invMassB + b3Dot( rAn, b3MulMV( base->invIA, rAn ) ) + + b3Dot( rBn, b3MulMV( base->invIB, rBn ) ); + joint->suspensionMass = k > 0.0f ? 1.0f / k : 0.0f; + } + + joint->suspensionSoftness = b3MakeSoft( joint->suspensionHertz, joint->suspensionDampingRatio, context->h ); + joint->steeringSoftness = b3MakeSoft( joint->steeringHertz, joint->steeringDampingRatio, context->h ); + + { + // Rotation axis is the z-axis of body A. + b3Vec3 spinAxis = matrixB.cz; + float k = b3Dot( spinAxis, b3MulMV( invInertiaSum, spinAxis ) ); + joint->spinMass = k > 0.0f ? 1.0f / k : 0.0f; + } + + { + // Twist constraint around x-axis + float cs = b3Dot( matrixB.cz, matrixA.cz ); + float ss = -b3Dot( matrixB.cz, matrixA.cy ); + float den = cs * cs + ss * ss; + den = den > 0.0f ? 1.0f / den : 0.0f; + b3Vec3 steeringAxis = + b3MulSV( den, b3Cross( matrixB.cz, b3Sub( b3MulSV( -cs, matrixA.cy ), b3MulSV( ss, matrixA.cz ) ) ) ); + + float k = b3Dot( steeringAxis, b3MulMV( invInertiaSum, steeringAxis ) ); + joint->steeringMass = k > 0.0f ? 1.0f / k : 0.0f; + } + + if ( context->enableWarmStarting == false ) + { + joint->linearImpulse = (b3Vec2){ 0.0f, 0.0f }; + joint->angularImpulse = (b3Vec2){ 0.0f, 0.0f }; + joint->spinImpulse = 0.0f; + joint->suspensionSpringImpulse = 0.0f; + joint->lowerSuspensionImpulse = 0.0f; + joint->upperSuspensionImpulse = 0.0f; + joint->steeringSpringImpulse = 0.0f; + joint->lowerSteeringImpulse = 0.0f; + joint->upperSteeringImpulse = 0.0f; + } +} + +void b3WarmStartWheelJoint( b3JointSim* base, b3StepContext* context ) +{ + B3_ASSERT( base->type == b3_wheelJoint ); + + float mA = base->invMassA; + float mB = base->invMassB; + b3Matrix3 iA = base->invIA; + b3Matrix3 iB = base->invIB; + + // dummy state for static bodies + b3BodyState dummyState = b3_identityBodyState; + + b3WheelJoint* joint = &base->wheelJoint; + + b3BodyState* stateA = joint->indexA == B3_NULL_INDEX ? &dummyState : context->states + joint->indexA; + b3BodyState* stateB = joint->indexB == B3_NULL_INDEX ? &dummyState : context->states + joint->indexB; + + b3Vec3 rA = b3RotateVector( stateA->deltaRotation, joint->frameA.p ); + b3Vec3 rB = b3RotateVector( stateB->deltaRotation, joint->frameB.p ); + + b3Vec3 d = b3Add( b3Add( b3Sub( stateB->deltaPosition, stateA->deltaPosition ), joint->deltaCenter ), b3Sub( rB, rA ) ); + + b3Quat quatA = b3MulQuat( stateA->deltaRotation, joint->frameA.q ); + b3Quat quatB = b3MulQuat( stateB->deltaRotation, joint->frameB.q ); + if ( b3DotQuat( quatA, quatB ) < 0.0f ) + { + // this keeps the rotation angle in the range [-pi, pi] + quatB = b3NegateQuat( quatB ); + } + + b3Matrix3 matrixA = b3MakeMatrixFromQuat( quatA ); + b3Matrix3 matrixB = b3MakeMatrixFromQuat( quatB ); + + b3Vec3 sAx = b3Cross( b3Add( d, rA ), matrixA.cx ); + b3Vec3 sBx = b3Cross( rB, matrixA.cx ); + b3Vec3 sAy = b3Cross( b3Add( d, rA ), matrixA.cy ); + b3Vec3 sBy = b3Cross( rB, matrixA.cy ); + b3Vec3 sAz = b3Cross( b3Add( d, rA ), matrixA.cz ); + b3Vec3 sBz = b3Cross( rB, matrixA.cz ); + + float suspensionImpulse = joint->suspensionSpringImpulse + joint->lowerSuspensionImpulse - joint->upperSuspensionImpulse; + + float linearImpulseY = joint->linearImpulse.x; + float linearImpulseZ = joint->linearImpulse.y; + float angularImpulseX = joint->angularImpulse.x; + float angularImpulseY = joint->angularImpulse.y; + + b3Vec3 linearImpulse = b3Blend3( suspensionImpulse, matrixA.cx, linearImpulseY, matrixA.cy, linearImpulseZ, matrixA.cz ); + b3Vec3 angularImpulseA = b3Blend3( suspensionImpulse, sAx, linearImpulseY, sAy, linearImpulseZ, sAz ); + b3Vec3 angularImpulseB = b3Blend3( suspensionImpulse, sBx, linearImpulseY, sBy, linearImpulseZ, sBz ); + b3Vec3 angularImpulse = b3MulSV( joint->spinImpulse, matrixA.cz ); + + b3Vec3 spinAxis = matrixB.cz; + + if ( joint->enableSteering ) + { + // Twist constraint around x-axis + float cs = b3Dot( matrixB.cz, matrixA.cz ); + float ss = -b3Dot( matrixB.cz, matrixA.cy ); + float den = cs * cs + ss * ss; + den = den > 0.0f ? 1.0f / den : 0.0f; + b3Vec3 steeringAxis = + b3MulSV( den, b3Cross( matrixB.cz, b3Sub( b3MulSV( -cs, matrixA.cy ), b3MulSV( ss, matrixA.cz ) ) ) ); + + b3Vec3 perpAxis = b3Cross( spinAxis, matrixA.cx ); + float steeringImpulse = joint->steeringSpringImpulse + joint->lowerSteeringImpulse - joint->upperSteeringImpulse; + angularImpulse = b3Blend3( angularImpulseX, perpAxis, joint->spinImpulse, spinAxis, steeringImpulse, steeringAxis ); + } + else + { + b3Quat relQ = b3InvMulQuat( quatA, quatB ); + b3Vec3 perpAxisX = b3MulSV( + 0.5f, b3RotateVector( quatA, b3Add( b3MulSV( relQ.s, b3Vec3_axisX ), b3Cross( relQ.v, b3Vec3_axisX ) ) ) ); + b3Vec3 perpAxisY = b3MulSV( + 0.5f, b3RotateVector( quatA, b3Add( b3MulSV( relQ.s, b3Vec3_axisY ), b3Cross( relQ.v, b3Vec3_axisY ) ) ) ); + angularImpulse = b3Add( + angularImpulse, + b3Blend3( angularImpulseX, perpAxisX, angularImpulseY, perpAxisY, joint->spinImpulse, spinAxis ) ); + } + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->linearVelocity = b3MulSub( stateA->linearVelocity, mA, linearImpulse ); + stateA->angularVelocity = b3Sub( stateA->angularVelocity, b3MulMV( iA, b3Add( angularImpulseA, angularImpulse ) ) ); + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->linearVelocity = b3MulAdd( stateB->linearVelocity, mB, linearImpulse ); + stateB->angularVelocity = b3Add( stateB->angularVelocity, b3MulMV( iB, b3Add( angularImpulseB, angularImpulse ) ) ); + } +} + +void b3SolveWheelJoint( b3JointSim* base, b3StepContext* context, bool useBias ) +{ + B3_ASSERT( base->type == b3_wheelJoint ); + + float mA = base->invMassA; + float mB = base->invMassB; + b3Matrix3 iA = base->invIA; + b3Matrix3 iB = base->invIB; + + // dummy state for static bodies + b3BodyState dummyState = b3_identityBodyState; + + b3WheelJoint* joint = &base->wheelJoint; + + b3BodyState* stateA = joint->indexA == B3_NULL_INDEX ? &dummyState : context->states + joint->indexA; + b3BodyState* stateB = joint->indexB == B3_NULL_INDEX ? &dummyState : context->states + joint->indexB; + + b3Vec3 vA = stateA->linearVelocity; + b3Vec3 wA = stateA->angularVelocity; + b3Vec3 vB = stateB->linearVelocity; + b3Vec3 wB = stateB->angularVelocity; + + bool fixedRotation = base->fixedRotation; + + // current anchors + b3Vec3 rA = b3RotateVector( stateA->deltaRotation, joint->frameA.p ); + b3Vec3 rB = b3RotateVector( stateB->deltaRotation, joint->frameB.p ); + + b3Quat quatA = b3MulQuat( stateA->deltaRotation, joint->frameA.q ); + b3Quat quatB = b3MulQuat( stateB->deltaRotation, joint->frameB.q ); + + if ( b3DotQuat( quatA, quatB ) < 0.0f ) + { + // this keeps the rotation angle in the range [-pi, pi] + quatB = b3NegateQuat( quatB ); + } + + b3Quat relQ = b3InvMulQuat( quatA, quatB ); + b3Matrix3 matrixA = b3MakeMatrixFromQuat( quatA ); + b3Matrix3 matrixB = b3MakeMatrixFromQuat( quatB ); + + // b3Vec3 spinAxis = b3RotateVector( quatB, b3Vec3_axisZ ); + + b3Vec3 d = b3Add( b3Add( b3Sub( stateB->deltaPosition, stateA->deltaPosition ), joint->deltaCenter ), b3Sub( rB, rA ) ); + b3Vec3 sAx = b3Cross( b3Add( d, rA ), matrixA.cx ); + b3Vec3 sBx = b3Cross( rB, matrixA.cx ); + b3Vec3 sAy = b3Cross( b3Add( d, rA ), matrixA.cy ); + b3Vec3 sBy = b3Cross( rB, matrixA.cy ); + b3Vec3 sAz = b3Cross( b3Add( d, rA ), matrixA.cz ); + b3Vec3 sBz = b3Cross( rB, matrixA.cz ); + + float translation = b3Dot( matrixA.cx, d ); + + // Steering param ib = cz_b, ia = cz_a, ja = -cy_a + float cs = b3Dot( matrixB.cz, matrixA.cz ); + float ss = -b3Dot( matrixB.cz, matrixA.cy ); + float den = cs * cs + ss * ss; + den = den > 0.0f ? 1.0f / den : 0.0f; + b3Vec3 steeringAxis = + b3MulSV( den, b3Cross( matrixB.cz, b3Sub( b3MulSV( -cs, matrixA.cy ), b3MulSV( ss, matrixA.cz ) ) ) ); + + // motor constraint + if ( joint->enableSpinMotor && fixedRotation == false ) + { + b3Vec3 spinAxis = matrixB.cz; + float cdot = b3Dot( b3Sub( wB, wA ), spinAxis ) - joint->spinSpeed; + float impulse = -joint->spinMass * cdot; + float oldImpulse = joint->spinImpulse; + float maxImpulse = context->h * joint->maxSpinTorque; + joint->spinImpulse = b3ClampFloat( joint->spinImpulse + impulse, -maxImpulse, maxImpulse ); + impulse = joint->spinImpulse - oldImpulse; + + wA = b3Sub( wA, b3MulMV( iA, b3MulSV( impulse, spinAxis ) ) ); + wB = b3Add( wB, b3MulMV( iB, b3MulSV( impulse, spinAxis ) ) ); + } + + // suspension + if ( joint->enableSuspensionSpring ) + { + // This is a real spring and should be applied even during relax + float c = translation; + float bias = joint->suspensionSoftness.biasRate * c; + float massScale = joint->suspensionSoftness.massScale; + float impulseScale = joint->suspensionSoftness.impulseScale; + + float cdot = b3Dot( matrixA.cx, b3Sub( vB, vA ) ) + b3Dot( sBx, wB ) - b3Dot( sAx, wA ); + float impulse = -massScale * joint->suspensionMass * ( cdot + bias ) - impulseScale * joint->suspensionSpringImpulse; + joint->suspensionSpringImpulse += impulse; + + b3Vec3 linearImpulse = b3MulSV( impulse, matrixA.cx ); + b3Vec3 angularImpulseA = b3MulSV( impulse, sAx ); + b3Vec3 angularImpulseB = b3MulSV( impulse, sBx ); + + vA = b3MulSub( vA, mA, linearImpulse ); + wA = b3Sub( wA, b3MulMV( iA, angularImpulseA ) ); + vB = b3MulAdd( vB, mB, linearImpulse ); + wB = b3Add( wB, b3MulMV( iB, angularImpulseB ) ); + } + + // steering + if ( joint->enableSteering && fixedRotation == false ) + { + float steeringAngle = b3Atan2( ss, cs ); + + { + // This is a real spring and should be applied even during relax + float c = steeringAngle - joint->targetSteeringAngle; + float bias = joint->steeringSoftness.biasRate * c; + float massScale = joint->steeringSoftness.massScale; + float impulseScale = joint->steeringSoftness.impulseScale; + + float cdot = b3Dot( steeringAxis, b3Sub( wB, wA ) ); + float oldImpulse = joint->steeringSpringImpulse; + float impulse = -massScale * joint->steeringMass * ( cdot + bias ) - impulseScale * oldImpulse; + float maxImpulse = context->h * joint->maxSteeringTorque; + joint->steeringSpringImpulse = b3ClampFloat( oldImpulse + impulse, -maxImpulse, maxImpulse ); + impulse = joint->steeringSpringImpulse - oldImpulse; + + wA = b3Sub( wA, b3MulMV( iA, b3MulSV( impulse, steeringAxis ) ) ); + wB = b3Add( wB, b3MulMV( iB, b3MulSV( impulse, steeringAxis ) ) ); + } + + if ( joint->enableSteeringLimit ) + { + // Lower limit + { + float c = steeringAngle - joint->lowerSteeringLimit; + 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 = b3Dot( steeringAxis, b3Sub( wB, wA ) ); + float oldImpulse = joint->lowerSteeringImpulse; + float impulse = -massScale * joint->steeringMass * ( cdot + bias ) - impulseScale * oldImpulse; + joint->lowerSteeringImpulse = b3MaxFloat( oldImpulse + impulse, 0.0f ); + impulse = joint->lowerSteeringImpulse - oldImpulse; + + wA = b3Sub( wA, b3MulMV( iA, b3MulSV( impulse, steeringAxis ) ) ); + wB = b3Add( wB, b3MulMV( iB, b3MulSV( impulse, steeringAxis ) ) ); + } + + // 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->upperSteeringLimit - steeringAngle; + 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 = b3Dot( steeringAxis, b3Sub( wA, wB ) ); + float oldImpulse = joint->upperSteeringImpulse; + float impulse = -massScale * joint->steeringMass * ( cdot + bias ) - impulseScale * oldImpulse; + joint->upperSteeringImpulse = b3MaxFloat( oldImpulse + impulse, 0.0f ); + impulse = joint->upperSteeringImpulse - oldImpulse; + + // sign flipped on applied impulse + wA = b3Add( wA, b3MulMV( iA, b3MulSV( impulse, steeringAxis ) ) ); + wB = b3Sub( wB, b3MulMV( iB, b3MulSV( impulse, steeringAxis ) ) ); + } + } + } + + if ( joint->enableSuspensionLimit ) + { + // Lower limit + { + float c = translation - joint->lowerSuspensionLimit; + 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 = b3Dot( matrixA.cx, b3Sub( vB, vA ) ) + b3Dot( sBx, wB ) - b3Dot( sAx, wA ); + float impulse = -massScale * joint->suspensionMass * ( cdot + bias ) - impulseScale * joint->lowerSuspensionImpulse; + float oldImpulse = joint->lowerSuspensionImpulse; + joint->lowerSuspensionImpulse = b3MaxFloat( oldImpulse + impulse, 0.0f ); + impulse = joint->lowerSuspensionImpulse - oldImpulse; + + b3Vec3 linearImpulse = b3MulSV( impulse, matrixA.cx ); + b3Vec3 angularImpulseA = b3MulSV( impulse, sAx ); + b3Vec3 angularImpulseB = b3MulSV( impulse, sBx ); + + vA = b3MulSub( vA, mA, linearImpulse ); + wA = b3Sub( wA, b3MulMV( iA, angularImpulseA ) ); + vB = b3MulAdd( vB, mB, linearImpulse ); + wB = b3Add( wB, b3MulMV( iB, angularImpulseB ) ); + } + + // 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->upperSuspensionLimit - 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 = b3Dot( matrixA.cx, b3Sub( vA, vB ) ) + b3Dot( sAx, wA ) - b3Dot( sBx, wB ); + float impulse = -massScale * joint->suspensionMass * ( cdot + bias ) - impulseScale * joint->upperSuspensionImpulse; + float oldImpulse = joint->upperSuspensionImpulse; + joint->upperSuspensionImpulse = b3MaxFloat( oldImpulse + impulse, 0.0f ); + impulse = joint->upperSuspensionImpulse - oldImpulse; + + b3Vec3 linearImpulse = b3MulSV( impulse, matrixA.cx ); + b3Vec3 angularImpulseA = b3MulSV( impulse, sAx ); + b3Vec3 angularImpulseB = b3MulSV( impulse, sBx ); + + // sign flipped on applied impulse + vA = b3MulAdd( vA, mA, linearImpulse ); + wA = b3Add( wA, b3MulMV( iA, angularImpulseA ) ); + vB = b3MulSub( vB, mB, linearImpulse ); + wB = b3Sub( wB, b3MulMV( iB, angularImpulseB ) ); + } + } + + // Collinearity constraint + if ( fixedRotation == false ) + { + if ( joint->enableSteering == true ) + { + float bias = 0.0f; + float massScale = 1.0f; + float impulseScale = 0.0f; + if ( useBias ) + { + float c = b3Dot( matrixA.cx, matrixB.cz ); + + bias = base->constraintSoftness.biasRate * c; + massScale = base->constraintSoftness.massScale; + impulseScale = base->constraintSoftness.impulseScale; + } + + b3Vec3 u = b3Cross( matrixB.cz, matrixA.cx ); + float cdot = b3Dot( b3Sub( wB, wA ), u ); + + b3Matrix3 invInertiaSum = b3AddMM( iA, iB ); + float k = b3Dot( u, b3MulMV( invInertiaSum, u ) ); + float perpMass = k > 0.0f ? 1.0f / k : 0.0f; + + float deltaImpulse = -massScale * perpMass * ( cdot + bias ) - impulseScale * joint->angularImpulse.x; + joint->angularImpulse.x += deltaImpulse; + + wA = b3MulSub( wA, deltaImpulse, b3MulMV( iA, u ) ); + wB = b3MulAdd( wB, deltaImpulse, b3MulMV( iB, u ) ); + } + else + { + b3Vec2 bias = { 0.0f, 0.0f }; + float massScale = 1.0f; + float impulseScale = 0.0f; + + if ( useBias ) + { + b3Vec2 c = { relQ.v.x, relQ.v.y }; + bias = (b3Vec2){ base->constraintSoftness.biasRate * c.x, base->constraintSoftness.biasRate * c.y }; + massScale = base->constraintSoftness.massScale; + impulseScale = base->constraintSoftness.impulseScale; + } + + // Collinearity constraint as 2-by-2 + b3Vec3 perpAxisX = b3MulSV( + 0.5f, b3RotateVector( quatA, b3Add( b3MulSV( relQ.s, b3Vec3_axisX ), b3Cross( relQ.v, b3Vec3_axisX ) ) ) ); + b3Vec3 perpAxisY = b3MulSV( + 0.5f, b3RotateVector( quatA, b3Add( b3MulSV( relQ.s, b3Vec3_axisY ), b3Cross( relQ.v, b3Vec3_axisY ) ) ) ); + + b3Matrix3 invInertiaSum = b3AddMM( iA, iB ); + float kxx = b3Dot( perpAxisX, b3MulMV( invInertiaSum, perpAxisX ) ); + float kyy = b3Dot( perpAxisY, b3MulMV( invInertiaSum, perpAxisY ) ); + float kxy = b3Dot( perpAxisX, b3MulMV( invInertiaSum, perpAxisY ) ); + + b3Matrix2 k = { { kxx, kxy }, { kxy, kyy } }; + + b3Vec3 wRel = b3Sub( wB, wA ); + b3Vec2 cdot = { b3Dot( wRel, perpAxisX ), b3Dot( wRel, perpAxisY ) }; + b3Vec2 oldImpulse = joint->angularImpulse; + b3Vec2 cdotPlusBias = { cdot.x + bias.x, cdot.y + bias.y }; + b3Vec2 sol = b3Solve2( k, cdotPlusBias ); + b3Vec2 deltaImpulse = { + -massScale * sol.x - impulseScale * oldImpulse.x, + -massScale * sol.y - impulseScale * oldImpulse.y, + }; + joint->angularImpulse = (b3Vec2){ oldImpulse.x + deltaImpulse.x, oldImpulse.y + deltaImpulse.y }; + + b3Vec3 angularImpulse = b3Blend2( deltaImpulse.x, perpAxisX, deltaImpulse.y, perpAxisY ); + wA = b3Sub( wA, b3MulMV( iA, angularImpulse ) ); + wB = b3Add( wB, b3MulMV( iB, angularImpulse ) ); + } + } + + // Solve point-to-line constraint + { + b3Vec3 perpY = matrixA.cy; + b3Vec3 perpZ = matrixA.cz; + + b3Vec2 bias = { 0.0f, 0.0f }; + float massScale = 1.0f; + float impulseScale = 0.0f; + if ( useBias ) + { + b3Vec2 c = { b3Dot( perpY, d ), b3Dot( perpZ, d ) }; + bias = (b3Vec2){ base->constraintSoftness.biasRate * c.x, base->constraintSoftness.biasRate * c.y }; + massScale = base->constraintSoftness.massScale; + impulseScale = base->constraintSoftness.impulseScale; + } + + b3Vec3 vRel = b3Sub( b3Sub( b3Add( vB, b3Cross( wB, rB ) ), vA ), b3Cross( wA, b3Add( rA, d ) ) ); + b3Vec2 cdot = { b3Dot( perpY, vRel ), b3Dot( perpZ, vRel ) }; + + //// K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] + ///// Jx = [-perpX, -cross(d + rA, perpX), perpX, cross(rB, perpX)] + + float kyy = mA + mB + b3Dot( sAy, b3MulMV( iA, sAy ) ) + b3Dot( sBy, b3MulMV( iB, sBy ) ); + float kyz = b3Dot( sAy, b3MulMV( iA, sAz ) ) + b3Dot( sBy, b3MulMV( iB, sBz ) ); + float kzz = mA + mB + b3Dot( sAz, b3MulMV( iA, sAz ) ) + b3Dot( sBz, b3MulMV( iB, sBz ) ); + + b3Matrix2 k = { { kyy, kyz }, { kyz, kzz } }; + + b3Vec2 oldImpulse = joint->linearImpulse; + b3Vec2 cdotPlusBias = { cdot.x + bias.x, cdot.y + bias.y }; + b3Vec2 sol = b3Solve2( k, cdotPlusBias ); + b3Vec2 deltaImpulse = { + -massScale * sol.x - impulseScale * oldImpulse.x, + -massScale * sol.y - impulseScale * oldImpulse.y, + }; + joint->linearImpulse = (b3Vec2){ oldImpulse.x + deltaImpulse.x, oldImpulse.y + deltaImpulse.y }; + + b3Vec3 linearImpulse = b3Blend2( deltaImpulse.x, perpY, deltaImpulse.y, perpZ ); + + vA = b3MulSub( vA, mA, linearImpulse ); + wA = b3Sub( wA, b3MulMV( iA, b3Blend2( deltaImpulse.x, sAy, deltaImpulse.y, sAz ) ) ); + vB = b3MulAdd( vB, mB, linearImpulse ); + wB = b3Add( wB, b3MulMV( iB, b3Blend2( deltaImpulse.x, sBy, deltaImpulse.y, sBz ) ) ); + } + + if ( stateA->flags & b3_dynamicFlag ) + { + stateA->linearVelocity = vA; + stateA->angularVelocity = wA; + } + + if ( stateB->flags & b3_dynamicFlag ) + { + stateB->linearVelocity = vB; + stateB->angularVelocity = wB; + } +} + +#if 0 +void b3WheelJoint_Dump() +{ + int32 indexA = joint->bodyA->joint->islandIndex; + int32 indexB = joint->bodyB->joint->islandIndex; + + b3Dump(" b3WheelJointDef jd;\n"); + b3Dump(" jd.bodyA = sims[%d];\n", indexA); + b3Dump(" jd.bodyB = sims[%d];\n", indexB); + b3Dump(" jd.collideConnected = bool(%d);\n", joint->collideConnected); + b3Dump(" jd.localAnchorA.Set(%.9g, %.9g);\n", joint->localAnchorA.x, joint->localAnchorA.y); + b3Dump(" jd.localAnchorB.Set(%.9g, %.9g);\n", joint->localAnchorB.x, joint->localAnchorB.y); + b3Dump(" jd.referenceAngle = %.9g;\n", joint->referenceAngle); + b3Dump(" jd.enableLimit = bool(%d);\n", joint->enableLimit); + b3Dump(" jd.lowerAngle = %.9g;\n", joint->lowerAngle); + b3Dump(" jd.upperAngle = %.9g;\n", joint->upperAngle); + b3Dump(" jd.enableMotor = bool(%d);\n", joint->enableMotor); + b3Dump(" jd.motorSpeed = %.9g;\n", joint->motorSpeed); + b3Dump(" jd.maxMotorTorque = %.9g;\n", joint->maxMotorTorque); + b3Dump(" joints[%d] = joint->world->CreateJoint(&jd);\n", joint->index); +} +#endif + +void b3DrawWheelJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale ) +{ + B3_ASSERT( base->type == b3_wheelJoint ); + + b3WheelJoint* joint = &base->wheelJoint; + + b3Transform frameA = b3MulTransforms( transformA, base->localFrameA ); + b3Transform frameB = b3MulTransforms( transformB, base->localFrameB ); + + b3Matrix3 matrixA = b3MakeMatrixFromQuat( frameA.q ); + b3Matrix3 matrixB = b3MakeMatrixFromQuat( frameB.q ); + + draw->DrawSegmentFcn( frameA.p, frameB.p, b3_colorBlue, draw->context ); + + if ( joint->enableSuspensionLimit ) + { + b3Vec3 lower = b3MulAdd( frameA.p, joint->lowerSuspensionLimit, matrixA.cx ); + b3Vec3 upper = b3MulAdd( frameA.p, joint->upperSuspensionLimit, matrixA.cx ); + b3Vec3 perp = matrixA.cy; + draw->DrawSegmentFcn( lower, upper, b3_colorGray, draw->context ); + draw->DrawSegmentFcn( b3MulSub( lower, 0.1f * scale, perp ), b3MulAdd( lower, 0.1f * scale, perp ), b3_colorGreen, + draw->context ); + draw->DrawSegmentFcn( b3MulSub( upper, 0.1f * scale, perp ), b3MulAdd( upper, 0.1f * scale, perp ), b3_colorRed, + draw->context ); + } + else + { + draw->DrawSegmentFcn( b3MulSub( frameA.p, 1.0f * scale, matrixA.cx ), b3MulAdd( frameA.p, 1.0f * scale, matrixA.cx ), + b3_colorGray, draw->context ); + } + + if ( joint->enableSteering && joint->enableSteeringLimit ) + { + // b3Quat quatA = frameA.q; + // b3Quat quatB = frameB.q; + + // if ( b3DotQuat( quatA, quatB ) < 0.0f ) + //{ + // // this keeps the twist angle in the range [-pi, pi] + // quatB = -quatB; + // } + + // b3Quat relQ = b3InvMulQuat( quatA, quatB ); + + b3Transform frame = { + .p = frameB.p, + .q = frameA.q, + }; + + const float radius = 0.5f * scale; + const int sliceCount = 16; + float lower = joint->lowerSteeringLimit; + float upper = joint->upperSteeringLimit; + + b3CosSin cs = b3ComputeCosSin( lower ); + b3Vec3 vertex1 = b3TransformPoint( frame, (b3Vec3){ 0.0f, -radius * cs.sine, radius * cs.cosine } ); + + for ( int index = 0; index < sliceCount; ++index ) + { + float t2 = ( index + 1.0f ) / sliceCount; + float phi = b3LerpFloat( lower, upper, t2 ); + + cs = b3ComputeCosSin( phi ); + b3Vec3 vertex2 = b3TransformPoint( frame, (b3Vec3){ 0.0f, -radius * cs.sine, radius * cs.cosine } ); + + if ( index == 0 ) + { + draw->DrawSegmentFcn( frame.p, vertex1, b3_colorCyan, draw->context ); + } + + if ( index == sliceCount - 1 ) + { + draw->DrawSegmentFcn( vertex2, frame.p, b3_colorCyan, draw->context ); + } + draw->DrawSegmentFcn( vertex1, vertex2, b3_colorCyan, draw->context ); + + vertex1 = vertex2; + } + } + + draw->DrawSegmentFcn( b3MulSub( frameB.p, 0.5f * scale, matrixB.cz ), b3MulAdd( frameB.p, 0.5f * scale, matrixB.cz ), + b3_colorMagenta, draw->context ); + + draw->DrawPointFcn( frameA.p, 5.0f, b3_colorGray, draw->context ); + draw->DrawPointFcn( frameB.p, 5.0f, b3_colorDimGray, draw->context ); +} diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt new file mode 100644 index 0000000..9d19d35 --- /dev/null +++ b/test/CMakeLists.txt @@ -0,0 +1,40 @@ +# Box3D unit test app + +set(BOX3D_TEST_FILES + main.c + test_allocator.c + test_bitset.c + test_collision.c + test_compound.c + test_container.c + test_determinism.c + #test_distance.c + test_height_field.c + test_hull.c + test_id.c + test_macros.h + test_math.c + test_mover.c + test_shape.c + #test_table.c + test_world.c +) + +add_executable(test ${BOX3D_TEST_FILES}) + +set_target_properties(test PROPERTIES + C_STANDARD 17 + C_STANDARD_REQUIRED YES + C_EXTENSIONS NO +) + +# Special access to Box3D internals for testing +target_include_directories(test PRIVATE ${CMAKE_SOURCE_DIR}/src) + +if(BOX3D_VALIDATE) + target_compile_definitions(test PRIVATE BOX3D_VALIDATE) +endif() + +target_link_libraries(test PRIVATE box3d shared) + +source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}" PREFIX "" FILES ${BOX3D_TEST_FILES}) diff --git a/test/main.c b/test/main.c new file mode 100644 index 0000000..feb5125 --- /dev/null +++ b/test/main.c @@ -0,0 +1,122 @@ +// SPDX-FileCopyrightText: 2024 Erin Catto +// SPDX-License-Identifier: MIT + +#include "test_macros.h" +#include "box3d/base.h" + +#include + +#if defined( _WIN32 ) +#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 + +#ifdef TRACY_ENABLE +#include +#endif + +extern int AllocatorTest( void ); +extern int BitTest( void ); +extern int CollisionTest( void ); +extern int CompoundTest( void ); +extern int ContainerTest( void ); +extern int DeterminismTest( void ); +// extern int DistanceTest( void ); +extern int HeightFieldTest( void ); +extern int HullTest( void ); +extern int IdTest( void ); +extern int MathTest( void ); +extern int MoverTest( void ); +extern int ShapeTest( void ); +// extern int TableTest( void ); +extern int WorldTest( void ); + +// Filter-aware test runner: skips tests that don't match the filter +#define MAYBE_RUN_TEST( T ) \ + do \ + { \ + if ( filter != NULL && strcmp( filter, #T ) != 0 ) \ + { \ + printf( "test skipped: " #T "\n" ); \ + break; \ + } \ + RUN_TEST( T ); \ + } \ + while ( false ) + +int main( int argc, char** argv ) +{ +#if defined( _WIN32 ) + // Enable memory-leak reports + //_CrtSetBreakAlloc(196); + _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); +#endif + +#ifdef TRACY_ENABLE + ___tracy_startup_profiler(); +#endif + + const char* filter = NULL; + if ( argc > 1 ) + { + filter = argv[1]; + } + + uint64_t ticks = b3GetTicks(); + + printf( "Starting Box3D unit tests\n" ); + if ( filter != NULL ) + { + printf( "Filter: %s\n", filter ); + } + printf( "======================================\n" ); + + MAYBE_RUN_TEST( AllocatorTest ); + MAYBE_RUN_TEST( BitTest ); + MAYBE_RUN_TEST( CollisionTest ); + MAYBE_RUN_TEST( CompoundTest ); + MAYBE_RUN_TEST( ContainerTest ); + MAYBE_RUN_TEST( DeterminismTest ); + MAYBE_RUN_TEST( HeightFieldTest ); + MAYBE_RUN_TEST( HullTest ); + MAYBE_RUN_TEST( IdTest ); + MAYBE_RUN_TEST( MathTest ); + MAYBE_RUN_TEST( MoverTest ); + MAYBE_RUN_TEST( ShapeTest ); + MAYBE_RUN_TEST( WorldTest ); + + // RUN_TEST( DistanceTest ); + // RUN_TEST( TableTest ); + + printf( "======================================\n" ); + printf( "All Box3D tests passed!\n" ); + + float duration = b3GetMilliseconds( ticks ); + printf( "Test duration = %.2f s\n", 0.001f * duration ); + +#ifdef TRACY_ENABLE + ___tracy_shutdown_profiler(); +#endif + +#if defined( _WIN32 ) + if ( _CrtDumpMemoryLeaks() ) + { + return 1; + } +#endif + + return 0; +} diff --git a/test/test_allocator.c b/test/test_allocator.c new file mode 100644 index 0000000..ca7acaf --- /dev/null +++ b/test/test_allocator.c @@ -0,0 +1,49 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "block_allocator.h" +#include "test_macros.h" + +typedef struct +{ + int value1; + float value2; +} Foo; + +_Static_assert( sizeof( Foo ) >= sizeof( void* ), "too small" ); + +static int TestBlockAllocate( void ) +{ + b3BlockAllocator allocator = b3CreateBlockAllocator( (int)sizeof( Foo ), 2 ); + + Foo* item1 = b3AllocateElement( &allocator ); + ENSURE( item1 != NULL ); + + Foo* item2 = b3AllocateElement( &allocator ); + ENSURE( item2 != NULL ); + + b3DestroyBlockAllocator( &allocator ); + return 0; +} + +static int TestBlockClear( void ) +{ + b3BlockAllocator allocator = b3CreateBlockAllocator( (int)sizeof( Foo ), 0 ); + + Foo* item1 = b3AllocateElement( &allocator ); + Foo* item2 = b3AllocateElement( &allocator ); + + b3FreeElement( &allocator, item1 ); + b3FreeElement( &allocator, item2 ); + + b3DestroyBlockAllocator( &allocator ); + return 0; +} + +int AllocatorTest( void ) +{ + RUN_SUBTEST( TestBlockAllocate ); + RUN_SUBTEST( TestBlockClear ); + + return 0; +} diff --git a/test/test_bitset.c b/test/test_bitset.c new file mode 100644 index 0000000..893cdf8 --- /dev/null +++ b/test/test_bitset.c @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: 2023 Erin Catto +// SPDX-License-Identifier: MIT + +#include "bitset.h" +#include "ctz.h" +#include "test_macros.h" + +#include + +#define COUNT 169 + +int TestBitMath( void ) +{ + uint32_t r1 = b3CLZ32( 9 ); + ENSURE( r1 == 31 - 3 ); + + for (int i = 1; i < 1000; ++i) + { + int e1 = b3LowerPowerOf2Exponent( i ); + int e2 = (int)floorf( log2f( (float)i ) ); + ENSURE(e1 == e2); + } + + return 0; +} + +int TestBitSet( void ) +{ + struct b3BitSet bitSet = b3CreateBitSet( COUNT ); + + b3SetBitCountAndClear( &bitSet, COUNT ); + bool values[COUNT] = { false }; + + int32_t i1 = 0, i2 = 1; + b3SetBit( &bitSet, i1 ); + values[i1] = true; + + while ( i2 < COUNT ) + { + b3SetBit( &bitSet, i2 ); + values[i2] = true; + int32_t next = i1 + i2; + i1 = i2; + i2 = next; + } + + for ( int32_t i = 0; i < COUNT; ++i ) + { + bool value = b3GetBit( &bitSet, i ); + ENSURE( value == values[i] ); + } + + b3DestroyBitSet( &bitSet ); + + return 0; +} + +int BitTest( void ) +{ + RUN_SUBTEST( TestBitMath ); + RUN_SUBTEST( TestBitSet ); + return 0; +} diff --git a/test/test_collision.c b/test/test_collision.c new file mode 100644 index 0000000..87fcea2 --- /dev/null +++ b/test/test_collision.c @@ -0,0 +1,210 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "aabb.h" +#include "test_macros.h" + +#include "box3d/math_functions.h" + +static int AABBTest( void ) +{ + b3AABB a; + a.lowerBound = ( b3Vec3 ){ -1.0f, -1.0f, -1.0f }; + a.upperBound = ( b3Vec3 ){ -2.0f, -2.0f, -2.0f }; + + ENSURE( b3IsValidAABB( a ) == false ); + + a.upperBound = ( b3Vec3 ){ 1.0f, 1.0f }; + ENSURE( b3IsValidAABB( a ) == true ); + + b3AABB b = { { 2.0f, 2.0f }, { 4.0f, 4.0f } }; + ENSURE( b3AABB_Overlaps( a, b ) == false ); + ENSURE( b3AABB_Contains( a, b ) == false ); + + return 0; +} + +static int TestRayAABBIntersection( void ) +{ + // Test 1: Ray passing through center of AABB + { + b3Vec3 lowerBound = { -1.0f, -1.0f, -1.0f }; + b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f }; + b3Vec3 p1 = { -2.0f, 0.0f, 0.0f }; + b3Vec3 p2 = { 2.0f, 0.0f, 0.0f }; + float minFraction, maxFraction; + + bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction ); + + ENSURE( hit == true ); + ENSURE( b3AbsFloat( minFraction - 0.25f ) < 0.001f ); // Enters at 25% of ray + ENSURE( b3AbsFloat( maxFraction - 0.75f ) < 0.001f ); // Exits at 75% of ray + } + + // Test 2: Ray starting inside AABB + { + b3Vec3 lowerBound = { -1.0f, -1.0f, -1.0f }; + b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f }; + b3Vec3 p1 = { 0.0f, 0.0f, 0.0f }; + b3Vec3 p2 = { 2.0f, 0.0f, 0.0f }; + float minFraction, maxFraction; + + bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction ); + + ENSURE( hit == true ); + ENSURE( minFraction == 0.0f ); // Starts inside + ENSURE( b3AbsFloat( maxFraction - 0.5f ) < 0.001f ); // Exits at 50% of ray + } + + // Test 3: Ray ending inside AABB + { + b3Vec3 lowerBound = { -1.0f, -1.0f, -1.0f }; + b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f }; + b3Vec3 p1 = { -2.0f, 0.0f, 0.0f }; + b3Vec3 p2 = { 0.0f, 0.0f, 0.0f }; + float minFraction, maxFraction; + + bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction ); + + ENSURE( hit == true ); + ENSURE( b3AbsFloat( minFraction - 0.5f ) < 0.001f ); // Enters at 50% of ray + ENSURE( maxFraction == 1.0f ); // Ends inside + } + + // Test 4: Ray completely inside AABB + { + b3Vec3 lowerBound = { -2.0f, -2.0f, -2.0f }; + b3Vec3 upperBound = { 2.0f, 2.0f, 2.0f }; + b3Vec3 p1 = { -1.0f, 0.0f, 0.0f }; + b3Vec3 p2 = { 1.0f, 0.0f, 0.0f }; + float minFraction, maxFraction; + + bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction ); + + ENSURE( hit == true ); + ENSURE( minFraction == 0.0f ); + ENSURE( maxFraction == 1.0f ); + } + + // Test 5: Ray missing AABB + { + b3Vec3 lowerBound = { 0.0f, 0.0f, 0.0f }; + b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f }; + b3Vec3 p1 = { -1.0f, 2.0f, 0.5f }; + b3Vec3 p2 = { 2.0f, 2.0f, 0.5f }; + float minFraction, maxFraction; + + bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction ); + + ENSURE( hit == false ); + } + + // Test 6: Ray parallel to AABB face (no intersection) + { + b3Vec3 lowerBound = { 0.0f, 0.0f, 0.0f }; + b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f }; + b3Vec3 p1 = { -1.0f, 2.0f, 0.5f }; + b3Vec3 p2 = { 2.0f, 2.0f, 0.5f }; + float minFraction, maxFraction; + + bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction ); + + ENSURE( hit == false ); + } + + // Test 7: Ray parallel to AABB face (within bounds) + { + b3Vec3 lowerBound = { 0.0f, 0.0f, 0.0f }; + b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f }; + b3Vec3 p1 = { -1.0f, 0.5f, 0.5f }; + b3Vec3 p2 = { 2.0f, 0.5f, 0.5f }; + float minFraction, maxFraction; + + bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction ); + + ENSURE( hit == true ); + ENSURE( b3AbsFloat( minFraction - 1.0f / 3.0f ) < 0.001f ); + ENSURE( b3AbsFloat( maxFraction - 2.0f / 3.0f ) < 0.001f ); + } + + // Test 8: Degenerate ray (point) inside AABB + { + b3Vec3 lowerBound = { 0.0f, 0.0f, 0.0f }; + b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f }; + b3Vec3 p1 = { 0.5f, 0.5f, 0.5f }; + b3Vec3 p2 = { 0.5f, 0.5f, 0.5f }; + float minFraction, maxFraction; + + bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction ); + + ENSURE( hit == true ); + ENSURE( minFraction == 0.0f ); + ENSURE( maxFraction == 0.0f ); + } + + // Test 9: Degenerate ray (point) outside AABB + { + b3Vec3 lowerBound = { 0.0f, 0.0f, 0.0f }; + b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f }; + b3Vec3 p1 = { 2.0f, 2.0f, 2.0f }; + b3Vec3 p2 = { 2.0f, 2.0f, 2.0f }; + float minFraction, maxFraction; + + bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction ); + + ENSURE( hit == false ); + } + + // Test 10: Ray pointing away from AABB + { + b3Vec3 lowerBound = { 0.0f, 0.0f, 0.0f }; + b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f }; + b3Vec3 p1 = { -1.0f, 0.5f, 0.5f }; + b3Vec3 p2 = { -2.0f, 0.5f, 0.5f }; + float minFraction, maxFraction; + + bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction ); + + ENSURE( hit == false ); + } + + // Test 11: Ray hitting corner of AABB + { + b3Vec3 lowerBound = { 0.0f, 0.0f, 0.0f }; + b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f }; + b3Vec3 p1 = { -1.0f, -1.0f, -1.0f }; + b3Vec3 p2 = { 2.0f, 2.0f, 2.0f }; + float minFraction, maxFraction; + + bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction ); + + ENSURE( hit == true ); + ENSURE( b3AbsFloat( minFraction - 1.0f / 3.0f ) < 0.001f ); + ENSURE( b3AbsFloat( maxFraction - 2.0f / 3.0f ) < 0.001f ); + } + + // Test 12: Ray grazing edge of AABB + { + b3Vec3 lowerBound = { 0.0f, 0.0f, 0.0f }; + b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f }; + b3Vec3 p1 = { -1.0f, 0.0f, 0.5f }; + b3Vec3 p2 = { 2.0f, 0.0f, 0.5f }; + float minFraction, maxFraction; + + bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction ); + + ENSURE( hit == true ); + ENSURE( b3AbsFloat( minFraction - 1.0f / 3.0f ) < 0.001f ); + ENSURE( b3AbsFloat( maxFraction - 2.0f / 3.0f ) < 0.001f ); + } + + return 0; +} + +int CollisionTest( void ) +{ + RUN_SUBTEST( AABBTest ); + RUN_SUBTEST( TestRayAABBIntersection ); + + return 0; +} diff --git a/test/test_compound.c b/test/test_compound.c new file mode 100644 index 0000000..1dcb2ed --- /dev/null +++ b/test/test_compound.c @@ -0,0 +1,876 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#include "test_macros.h" + +// b3CollideMoverAndCompound, b3GetCompoundChild, b3QueryCompound are internal +#include "compound.h" + +#include "box3d/collision.h" +#include "box3d/math_functions.h" + +#include +#include +#include +#include + +static b3SurfaceMaterial MakeMaterial( float friction, uint64_t userId ) +{ + b3SurfaceMaterial m = b3DefaultSurfaceMaterial(); + m.friction = friction; + m.userMaterialId = userId; + return m; +} + +// --------------------------------------------------------------------------- +// Construction & layout +// --------------------------------------------------------------------------- + +static int CompoundCreateMixed( void ) +{ + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + + b3CompoundCapsuleDef capsules[1] = { + { .capsule = { { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, 0.25f }, .material = mat }, + }; + + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3CompoundHullDef hulls[1] = { + { .hull = &box.base, .transform = b3Transform_identity, .material = mat }, + }; + + b3MeshData* meshData = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 0.5f, 0.5f, 0.5f }, false ); + b3CompoundMeshDef meshes[1] = { + { + .meshData = meshData, + .transform = b3Transform_identity, + .scale = { 1.0f, 1.0f, 1.0f }, + .materials = &mat, + .materialCount = 1, + }, + }; + + b3CompoundSphereDef spheres[2] = { + { .sphere = { { 5.0f, 0.0f, 0.0f }, 0.5f }, .material = mat }, + { .sphere = { { -5.0f, 0.0f, 0.0f }, 0.5f }, .material = mat }, + }; + + b3CompoundDef def = { + .capsules = capsules, .capsuleCount = 1, + .hulls = hulls, .hullCount = 1, + .meshes = meshes, .meshCount = 1, + .spheres = spheres, .sphereCount = 2, + }; + + b3Compound* compound = b3CreateCompound( &def ); + ENSURE( compound != NULL ); + ENSURE( compound->version == B3_COMPOUND_VERSION ); + ENSURE( compound->byteCount > (int)sizeof( b3Compound ) ); + + ENSURE( compound->capsuleCount == 1 ); + ENSURE( compound->hullCount == 1 ); + ENSURE( compound->meshCount == 1 ); + ENSURE( compound->sphereCount == 2 ); + + ENSURE( compound->materialCount == 1 ); + ENSURE( compound->sharedHullCount == 1 ); + ENSURE( compound->sharedMeshCount == 1 ); + + ENSURE( compound->tree.nodeCount > 0 ); + ENSURE( compound->tree.nodes != NULL ); + + b3DestroyCompound( compound ); + b3DestroyMesh( meshData ); + return 0; +} + +static int CompoundCreateSingleType( void ) +{ + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + + // Capsule only + { + b3CompoundCapsuleDef cap = { .capsule = { { 0, 0, 0 }, { 1, 0, 0 }, 0.5f }, .material = mat }; + b3CompoundDef def = { .capsules = &cap, .capsuleCount = 1 }; + b3Compound* c = b3CreateCompound( &def ); + ENSURE( c != NULL && c->capsuleCount == 1 && c->hullCount == 0 && c->meshCount == 0 && c->sphereCount == 0 ); + b3DestroyCompound( c ); + } + + // Hull only + { + b3BoxHull box = b3MakeBoxHull( 1, 1, 1 ); + b3CompoundHullDef h = { .hull = &box.base, .transform = b3Transform_identity, .material = mat }; + b3CompoundDef def = { .hulls = &h, .hullCount = 1 }; + b3Compound* c = b3CreateCompound( &def ); + ENSURE( c != NULL && c->hullCount == 1 && c->sharedHullCount == 1 && c->capsuleCount == 0 ); + b3DestroyCompound( c ); + } + + // Mesh only + { + b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 1, 1, 1 }, false ); + b3CompoundMeshDef m = { + .meshData = md, + .transform = b3Transform_identity, + .scale = { 1, 1, 1 }, + .materials = &mat, + .materialCount = 1, + }; + b3CompoundDef def = { .meshes = &m, .meshCount = 1 }; + b3Compound* c = b3CreateCompound( &def ); + ENSURE( c != NULL && c->meshCount == 1 && c->sharedMeshCount == 1 ); + b3DestroyCompound( c ); + b3DestroyMesh( md ); + } + + // Sphere only + { + b3CompoundSphereDef s = { .sphere = { { 0, 0, 0 }, 1.0f }, .material = mat }; + b3CompoundDef def = { .spheres = &s, .sphereCount = 1 }; + b3Compound* c = b3CreateCompound( &def ); + ENSURE( c != NULL && c->sphereCount == 1 ); + b3DestroyCompound( c ); + } + + return 0; +} + +// --------------------------------------------------------------------------- +// Material deduplication +// --------------------------------------------------------------------------- + +static int CompoundMaterialDedup( void ) +{ + b3SurfaceMaterial mat = MakeMaterial( 0.4f, 7 ); + + b3CompoundCapsuleDef caps[3]; + for ( int i = 0; i < 3; ++i ) + { + caps[i].capsule = (b3Capsule){ { (float)i, 0, 0 }, { (float)i + 1, 0, 0 }, 0.25f }; + caps[i].material = mat; + } + + b3CompoundDef def = { .capsules = caps, .capsuleCount = 3 }; + b3Compound* c = b3CreateCompound( &def ); + ENSURE( c->materialCount == 1 ); + for ( int i = 0; i < 3; ++i ) + { + b3CompoundCapsule cc = b3GetCompoundCapsule( c, i ); + ENSURE( cc.materialIndex == 0 ); + } + b3DestroyCompound( c ); + return 0; +} + +static int CompoundMaterialDistinct( void ) +{ + b3CompoundCapsuleDef caps[3]; + for ( int i = 0; i < 3; ++i ) + { + caps[i].capsule = (b3Capsule){ { (float)i, 0, 0 }, { (float)i + 1, 0, 0 }, 0.25f }; + caps[i].material = MakeMaterial( 0.1f * (float)( i + 1 ), (uint64_t)( i + 1 ) ); + } + + b3CompoundDef def = { .capsules = caps, .capsuleCount = 3 }; + b3Compound* c = b3CreateCompound( &def ); + ENSURE( c->materialCount == 3 ); + + const b3SurfaceMaterial* mats = b3GetCompoundMaterials( c ); + ENSURE( mats != NULL ); + + for ( int i = 0; i < 3; ++i ) + { + b3CompoundCapsule cc = b3GetCompoundCapsule( c, i ); + ENSURE( cc.materialIndex >= 0 && cc.materialIndex < 3 ); + ENSURE( mats[cc.materialIndex].userMaterialId == (uint64_t)( i + 1 ) ); + } + + b3DestroyCompound( c ); + return 0; +} + +static int CompoundMaterialCrossShape( void ) +{ + // One material shared across capsule, hull, and sphere → 1 material slot. + b3SurfaceMaterial mat = MakeMaterial( 0.5f, 99 ); + + b3CompoundCapsuleDef cap = { .capsule = { { 0, 0, 0 }, { 1, 0, 0 }, 0.25f }, .material = mat }; + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3CompoundHullDef hull = { .hull = &box.base, .transform = b3Transform_identity, .material = mat }; + b3CompoundSphereDef sph = { .sphere = { { 5, 0, 0 }, 0.5f }, .material = mat }; + + b3CompoundDef def = { + .capsules = &cap, .capsuleCount = 1, + .hulls = &hull, .hullCount = 1, + .spheres = &sph, .sphereCount = 1, + }; + b3Compound* c = b3CreateCompound( &def ); + ENSURE( c->materialCount == 1 ); + + ENSURE( b3GetCompoundCapsule( c, 0 ).materialIndex == 0 ); + ENSURE( b3GetCompoundHull( c, 0 ).materialIndex == 0 ); + ENSURE( b3GetCompoundSphere( c, 0 ).materialIndex == 0 ); + + b3DestroyCompound( c ); + return 0; +} + +static int CompoundMaterialMeshShared( void ) +{ + // Mesh material entries are routed through the same material map as convex + // materials, so an identical material is deduped across mesh and convex. + // (The comment in compound.c about meshes "not being shared" refers to the + // per-instance materialIndices arrays, not the b3SurfaceMaterial table.) + b3SurfaceMaterial mat = MakeMaterial( 0.3f, 11 ); + + b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 1, 1, 1 }, false ); + ENSURE( md->materialCount == 1 ); + + b3CompoundSphereDef sph = { .sphere = { { 5, 0, 0 }, 0.5f }, .material = mat }; + b3CompoundMeshDef mesh = { + .meshData = md, + .transform = b3Transform_identity, + .scale = { 1, 1, 1 }, + .materials = &mat, + .materialCount = 1, + }; + + b3CompoundDef def = { + .meshes = &mesh, .meshCount = 1, + .spheres = &sph, .sphereCount = 1, + }; + b3Compound* c = b3CreateCompound( &def ); + ENSURE( c->materialCount == 1 ); + + b3DestroyCompound( c ); + b3DestroyMesh( md ); + return 0; +} + +// --------------------------------------------------------------------------- +// Hull / mesh blob sharing +// --------------------------------------------------------------------------- + +static int CompoundHullSharingPointer( void ) +{ + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + b3BoxHull box = b3MakeBoxHull( 1, 1, 1 ); + + b3CompoundHullDef hulls[3]; + for ( int i = 0; i < 3; ++i ) + { + hulls[i].hull = &box.base; + hulls[i].transform = b3Transform_identity; + hulls[i].transform.p.x = (float)( 4 * i ); + hulls[i].material = mat; + } + + b3CompoundDef def = { .hulls = hulls, .hullCount = 3 }; + b3Compound* c = b3CreateCompound( &def ); + ENSURE( c->hullCount == 3 ); + ENSURE( c->sharedHullCount == 1 ); + b3DestroyCompound( c ); + return 0; +} + +static int CompoundHullSharingContent( void ) +{ + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + + // Two box hulls built independently with identical args are byte-identical + // (b3MakeBoxHull is deterministic and the hash is computed over the bytes). + b3BoxHull boxA = b3MakeBoxHull( 1, 1, 1 ); + b3BoxHull boxB = b3MakeBoxHull( 1, 1, 1 ); + ENSURE( &boxA != &boxB ); + + b3CompoundHullDef hulls[2] = { + { .hull = &boxA.base, .transform = b3Transform_identity, .material = mat }, + { .hull = &boxB.base, .transform = b3Transform_identity, .material = mat }, + }; + hulls[1].transform.p.x = 5.0f; + + b3CompoundDef def = { .hulls = hulls, .hullCount = 2 }; + b3Compound* c = b3CreateCompound( &def ); + ENSURE( c->sharedHullCount == 1 ); + b3DestroyCompound( c ); + return 0; +} + +static int CompoundHullDistinct( void ) +{ + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + b3BoxHull boxA = b3MakeBoxHull( 1, 1, 1 ); + b3BoxHull boxB = b3MakeBoxHull( 2, 1, 1 ); + + b3CompoundHullDef hulls[2] = { + { .hull = &boxA.base, .transform = b3Transform_identity, .material = mat }, + { .hull = &boxB.base, .transform = b3Transform_identity, .material = mat }, + }; + hulls[1].transform.p.x = 5.0f; + + b3CompoundDef def = { .hulls = hulls, .hullCount = 2 }; + b3Compound* c = b3CreateCompound( &def ); + ENSURE( c->sharedHullCount == 2 ); + b3DestroyCompound( c ); + return 0; +} + +static int CompoundMeshSharingPointer( void ) +{ + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 1, 1, 1 }, false ); + + b3CompoundMeshDef meshes[3]; + for ( int i = 0; i < 3; ++i ) + { + meshes[i].meshData = md; + meshes[i].transform = b3Transform_identity; + meshes[i].transform.p.x = (float)( 4 * i ); + meshes[i].scale = (b3Vec3){ 1, 1, 1 }; + meshes[i].materials = &mat; + meshes[i].materialCount = 1; + } + + b3CompoundDef def = { .meshes = meshes, .meshCount = 3 }; + b3Compound* c = b3CreateCompound( &def ); + ENSURE( c->meshCount == 3 ); + ENSURE( c->sharedMeshCount == 1 ); + + b3DestroyCompound( c ); + b3DestroyMesh( md ); + return 0; +} + +static int CompoundMeshSharingContent( void ) +{ + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + b3MeshData* mdA = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 1, 1, 1 }, false ); + b3MeshData* mdB = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 1, 1, 1 }, false ); + ENSURE( mdA != mdB ); + + b3CompoundMeshDef meshes[2] = { + { .meshData = mdA, .transform = b3Transform_identity, .scale = { 1, 1, 1 }, .materials = &mat, .materialCount = 1 }, + { .meshData = mdB, .transform = b3Transform_identity, .scale = { 1, 1, 1 }, .materials = &mat, .materialCount = 1 }, + }; + meshes[1].transform.p.x = 5.0f; + + b3CompoundDef def = { .meshes = meshes, .meshCount = 2 }; + b3Compound* c = b3CreateCompound( &def ); + ENSURE( c->sharedMeshCount == 1 ); + + b3DestroyCompound( c ); + b3DestroyMesh( mdA ); + b3DestroyMesh( mdB ); + return 0; +} + +static int CompoundMeshDistinct( void ) +{ + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + b3MeshData* mdA = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 1, 1, 1 }, false ); + b3MeshData* mdB = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 2, 1, 1 }, false ); + + b3CompoundMeshDef meshes[2] = { + { .meshData = mdA, .transform = b3Transform_identity, .scale = { 1, 1, 1 }, .materials = &mat, .materialCount = 1 }, + { .meshData = mdB, .transform = b3Transform_identity, .scale = { 1, 1, 1 }, .materials = &mat, .materialCount = 1 }, + }; + meshes[1].transform.p.x = 5.0f; + + b3CompoundDef def = { .meshes = meshes, .meshCount = 2 }; + b3Compound* c = b3CreateCompound( &def ); + ENSURE( c->sharedMeshCount == 2 ); + + b3DestroyCompound( c ); + b3DestroyMesh( mdA ); + b3DestroyMesh( mdB ); + return 0; +} + +// --------------------------------------------------------------------------- +// Child accessors and dispatch +// --------------------------------------------------------------------------- + +static int CompoundChildDispatch( void ) +{ + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 0.5f, 0.5f, 0.5f }, false ); + + b3CompoundCapsuleDef caps[2] = { + { .capsule = { { 0, 0, 0 }, { 1, 0, 0 }, 0.2f }, .material = mat }, + { .capsule = { { 0, 2, 0 }, { 1, 2, 0 }, 0.2f }, .material = mat }, + }; + b3CompoundHullDef hulls[1] = { { .hull = &box.base, .transform = b3Transform_identity, .material = mat } }; + hulls[0].transform.p = (b3Vec3){ 5, 0, 0 }; + b3CompoundMeshDef meshes[1] = { { + .meshData = md, + .transform = b3Transform_identity, + .scale = { 1, 1, 1 }, + .materials = &mat, + .materialCount = 1, + } }; + meshes[0].transform.p = (b3Vec3){ 0, 0, 5 }; + b3CompoundSphereDef spheres[1] = { { .sphere = { { -5, 0, 0 }, 0.5f }, .material = mat } }; + + b3CompoundDef def = { + .capsules = caps, .capsuleCount = 2, + .hulls = hulls, .hullCount = 1, + .meshes = meshes, .meshCount = 1, + .spheres = spheres, .sphereCount = 1, + }; + b3Compound* c = b3CreateCompound( &def ); + + // Index ordering is capsules → hulls → meshes → spheres. + ENSURE( b3GetCompoundChild( c, 0 ).type == b3_capsuleShape ); + ENSURE( b3GetCompoundChild( c, 1 ).type == b3_capsuleShape ); + ENSURE( b3GetCompoundChild( c, 2 ).type == b3_hullShape ); + ENSURE( b3GetCompoundChild( c, 3 ).type == b3_meshShape ); + ENSURE( b3GetCompoundChild( c, 4 ).type == b3_sphereShape ); + + // Capsule and sphere children always report identity transform — the position + // is encoded in the shape itself (capsule->center{1,2}, sphere->center). + b3ChildShape cap0 = b3GetCompoundChild( c, 0 ); + ENSURE_SMALL( cap0.transform.p.x, FLT_EPSILON ); + ENSURE_SMALL( cap0.transform.p.y, FLT_EPSILON ); + ENSURE_SMALL( cap0.transform.p.z, FLT_EPSILON ); + ENSURE_SMALL( cap0.capsule.center2.x - 1.0f, FLT_EPSILON ); + + b3ChildShape sph = b3GetCompoundChild( c, 4 ); + ENSURE_SMALL( sph.transform.p.x, FLT_EPSILON ); + ENSURE_SMALL( sph.sphere.center.x + 5.0f, FLT_EPSILON ); + + // Hull and mesh children carry their stored transform. + b3ChildShape hull = b3GetCompoundChild( c, 2 ); + ENSURE_SMALL( hull.transform.p.x - 5.0f, FLT_EPSILON ); + + b3ChildShape mesh = b3GetCompoundChild( c, 3 ); + ENSURE_SMALL( mesh.transform.p.z - 5.0f, FLT_EPSILON ); + ENSURE( mesh.mesh.data != NULL ); + + b3DestroyCompound( c ); + b3DestroyMesh( md ); + return 0; +} + +// --------------------------------------------------------------------------- +// AABB +// --------------------------------------------------------------------------- + +static int CompoundAABBContainsChildren( void ) +{ + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + b3CompoundSphereDef spheres[2] = { + { .sphere = { { -3, 0, 0 }, 1.0f }, .material = mat }, + { .sphere = { { 4, 0, 0 }, 0.5f }, .material = mat }, + }; + b3CompoundDef def = { .spheres = spheres, .sphereCount = 2 }; + b3Compound* c = b3CreateCompound( &def ); + + b3AABB local = b3ComputeCompoundAABB( c, b3Transform_identity ); + ENSURE( local.lowerBound.x <= -4.0f + 1e-5f ); + ENSURE( local.upperBound.x >= 4.5f - 1e-5f ); + ENSURE( local.lowerBound.y <= -1.0f + 1e-5f ); + ENSURE( local.upperBound.y >= 1.0f - 1e-5f ); + + // Translation commutes through the bounding-box transform. + b3Transform xf = { .p = { 10, 20, 30 }, .q = b3Quat_identity }; + b3AABB world = b3ComputeCompoundAABB( c, xf ); + ENSURE_SMALL( world.lowerBound.x - ( local.lowerBound.x + 10.0f ), 1e-4f ); + ENSURE_SMALL( world.upperBound.y - ( local.upperBound.y + 20.0f ), 1e-4f ); + ENSURE_SMALL( world.lowerBound.z - ( local.lowerBound.z + 30.0f ), 1e-4f ); + + b3DestroyCompound( c ); + return 0; +} + +// --------------------------------------------------------------------------- +// Ray cast / shape cast +// --------------------------------------------------------------------------- + +static int CompoundRayCastMiss( void ) +{ + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + b3CompoundSphereDef sph = { .sphere = { { 0, 0, 0 }, 0.5f }, .material = mat }; + b3CompoundDef def = { .spheres = &sph, .sphereCount = 1 }; + b3Compound* c = b3CreateCompound( &def ); + + // Ray well above the sphere on a parallel path. + b3RayCastInput input = { .origin = { -5, 5, 0 }, .translation = { 10, 0, 0 }, .maxFraction = 1.0f }; + b3CastOutput out = b3RayCastCompound( c, &input ); + ENSURE( out.hit == false ); + + b3DestroyCompound( c ); + return 0; +} + +static int CompoundRayCastClosest( void ) +{ + b3SurfaceMaterial matA = MakeMaterial( 0.4f, 100 ); + b3SurfaceMaterial matB = MakeMaterial( 0.4f, 200 ); + + // Two unit spheres along +X. Ray from origin must hit the nearer one first. + b3CompoundSphereDef spheres[2] = { + { .sphere = { { 5, 0, 0 }, 1.0f }, .material = matA }, + { .sphere = { { 10, 0, 0 }, 1.0f }, .material = matB }, + }; + b3CompoundDef def = { .spheres = spheres, .sphereCount = 2 }; + b3Compound* c = b3CreateCompound( &def ); + + b3RayCastInput input = { .origin = { 0, 0, 0 }, .translation = { 20, 0, 0 }, .maxFraction = 1.0f }; + b3CastOutput out = b3RayCastCompound( c, &input ); + ENSURE( out.hit == true ); + + // Front face of the nearer sphere is at x=4 → fraction 4/20 = 0.2. + ENSURE_SMALL( out.fraction - 0.2f, 1e-4f ); + ENSURE_SMALL( out.normal.x + 1.0f, 1e-4f ); + ENSURE( out.childIndex == 0 ); + + const b3SurfaceMaterial* mats = b3GetCompoundMaterials( c ); + ENSURE( mats[out.materialIndex].userMaterialId == 100 ); + + b3DestroyCompound( c ); + return 0; +} + +static int CompoundRayCastHullNormalRotation( void ) +{ + // A unit box rotated 90° about Z, placed at compound +X. The ray hits the + // face that, in compound space, points back toward -X. Verifies that the + // normal returned by the cast has been rotated from hull-local space back + // into compound space. + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + b3BoxHull box = b3MakeBoxHull( 1, 1, 1 ); + + b3CompoundHullDef hull = { + .hull = &box.base, + .transform = { .p = { 5, 0, 0 }, .q = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.5f * B3_PI ) }, + .material = mat, + }; + b3CompoundDef def = { .hulls = &hull, .hullCount = 1 }; + b3Compound* c = b3CreateCompound( &def ); + + b3RayCastInput input = { .origin = { 0, 0, 0 }, .translation = { 20, 0, 0 }, .maxFraction = 1.0f }; + b3CastOutput out = b3RayCastCompound( c, &input ); + ENSURE( out.hit == true ); + // Box has |hx|=1; with the rotation a face still intersects the +X ray at x=4. + ENSURE_SMALL( out.fraction - 0.2f, 1e-4f ); + ENSURE_SMALL( out.normal.x + 1.0f, 1e-3f ); + ENSURE_SMALL( out.normal.y, 1e-3f ); + ENSURE_SMALL( out.normal.z, 1e-3f ); + + b3DestroyCompound( c ); + return 0; +} + +static int CompoundShapeCastClosest( void ) +{ + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + b3CompoundSphereDef spheres[2] = { + { .sphere = { { 5, 0, 0 }, 1.0f }, .material = mat }, + { .sphere = { { 10, 0, 0 }, 1.0f }, .material = mat }, + }; + b3CompoundDef def = { .spheres = spheres, .sphereCount = 2 }; + b3Compound* c = b3CreateCompound( &def ); + + b3Vec3 point = { 0, 0, 0 }; + b3ShapeCastInput input = { + .proxy = { .points = &point, .count = 1, .radius = 0.25f }, + .translation = { 20, 0, 0 }, + .maxFraction = 1.0f, + .canEncroach = false, + }; + b3CastOutput out = b3ShapeCastCompound( c, &input ); + ENSURE( out.hit == true ); + // Closest contact: caster radius 0.25 + sphere radius 1.0 → first contact at x ≈ 3.75. + ENSURE_SMALL( out.fraction - 3.75f / 20.0f, 1e-3f ); + ENSURE( out.childIndex == 0 ); + + b3DestroyCompound( c ); + return 0; +} + +// --------------------------------------------------------------------------- +// Overlap +// --------------------------------------------------------------------------- + +static int CompoundOverlap( void ) +{ + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + b3CompoundSphereDef spheres[2] = { + { .sphere = { { -3, 0, 0 }, 0.5f }, .material = mat }, + { .sphere = { { 3, 0, 0 }, 0.5f }, .material = mat }, + }; + b3CompoundDef def = { .spheres = spheres, .sphereCount = 2 }; + b3Compound* c = b3CreateCompound( &def ); + + // Proxy at the origin lies in the gap between the two spheres. + b3Vec3 origin = { 0, 0, 0 }; + b3ShapeProxy gap = { .points = &origin, .count = 1, .radius = 0.25f }; + ENSURE( b3OverlapCompound( c, b3Transform_identity, &gap ) == false ); + + // Proxy at the center of the second sphere overlaps it. + b3Vec3 onSecond = { 3, 0, 0 }; + b3ShapeProxy hit = { .points = &onSecond, .count = 1, .radius = 0.1f }; + ENSURE( b3OverlapCompound( c, b3Transform_identity, &hit ) == true ); + + b3DestroyCompound( c ); + return 0; +} + +// --------------------------------------------------------------------------- +// Query +// --------------------------------------------------------------------------- + +struct QueryAccum +{ + int childIndices[8]; + int count; + int stopAfter; // -1 = never stop early +}; + +static bool QueryCallback( const b3Compound* compound, int childIndex, void* context ) +{ + (void)compound; + struct QueryAccum* acc = context; + if ( acc->count < (int)( sizeof( acc->childIndices ) / sizeof( acc->childIndices[0] ) ) ) + { + acc->childIndices[acc->count++] = childIndex; + } + if ( acc->stopAfter >= 0 && acc->count >= acc->stopAfter ) + { + return false; + } + return true; +} + +static int CompoundQuery( void ) +{ + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + b3CompoundSphereDef spheres[3] = { + { .sphere = { { -10, 0, 0 }, 0.5f }, .material = mat }, + { .sphere = { { 0, 0, 0 }, 0.5f }, .material = mat }, + { .sphere = { { 10, 0, 0 }, 0.5f }, .material = mat }, + }; + b3CompoundDef def = { .spheres = spheres, .sphereCount = 3 }; + b3Compound* c = b3CreateCompound( &def ); + + // Tight box around the middle sphere — only it should be reported. + b3AABB middle = { { -1, -1, -1 }, { 1, 1, 1 } }; + struct QueryAccum acc = { .stopAfter = -1 }; + b3QueryCompound( c, middle, QueryCallback, &acc ); + ENSURE( acc.count == 1 ); + ENSURE( acc.childIndices[0] == 1 ); + + // Wide box overlapping all three; early-exit after the first reported child. + b3AABB wide = { { -20, -1, -1 }, { 20, 1, 1 } }; + struct QueryAccum stop = { .stopAfter = 1 }; + b3QueryCompound( c, wide, QueryCallback, &stop ); + ENSURE( stop.count == 1 ); + + // Without early-exit, all three are visited. + struct QueryAccum all = { .stopAfter = -1 }; + b3QueryCompound( c, wide, QueryCallback, &all ); + ENSURE( all.count == 3 ); + + b3DestroyCompound( c ); + return 0; +} + +// --------------------------------------------------------------------------- +// Mover +// --------------------------------------------------------------------------- + +static int CompoundMover( void ) +{ + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + + // Two boxes side-by-side along X, gap of 1 between them. + b3CompoundHullDef hulls[2] = { + { .hull = &box.base, .transform = { .p = { -1.0f, 0, 0 }, .q = b3Quat_identity }, .material = mat }, + { .hull = &box.base, .transform = { .p = { 1.0f, 0, 0 }, .q = b3Quat_identity }, .material = mat }, + }; + b3CompoundDef def = { .hulls = hulls, .hullCount = 2 }; + b3Compound* c = b3CreateCompound( &def ); + + // Small capsule mover sitting on top of the boxes, low enough to penetrate both. + b3Capsule mover = { { -1.0f, 0.6f, 0 }, { 1.0f, 0.6f, 0 }, 0.2f }; + + b3PlaneResult planes[8] = { 0 }; + int planeCount = b3CollideMoverAndCompound( planes, 8, c, &mover ); + + // Both boxes contribute at least one plane each; the +Y face of each box + // should produce a plane whose normal points roughly +Y in compound space. + ENSURE( planeCount >= 2 ); + + int upPlanes = 0; + for ( int i = 0; i < planeCount; ++i ) + { + if ( planes[i].plane.normal.y > 0.9f ) + { + upPlanes += 1; + } + } + ENSURE( upPlanes >= 2 ); + + // Capacity cap is honored: ask for 1 and the call must not exceed it. + b3PlaneResult one[1] = { 0 }; + int capped = b3CollideMoverAndCompound( one, 1, c, &mover ); + ENSURE( capped <= 1 ); + + b3DestroyCompound( c ); + return 0; +} + +// --------------------------------------------------------------------------- +// Serialization round-trip +// --------------------------------------------------------------------------- + +static b3Compound* BuildSerializableCompound( b3MeshData* md ) +{ + b3SurfaceMaterial mat = b3DefaultSurfaceMaterial(); + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + + b3CompoundCapsuleDef cap = { .capsule = { { -2, 0, 0 }, { -1, 0, 0 }, 0.2f }, .material = mat }; + b3CompoundHullDef hull = { .hull = &box.base, .transform = { .p = { 5, 0, 0 }, .q = b3Quat_identity }, .material = mat }; + b3CompoundMeshDef mesh = { + .meshData = md, + .transform = { .p = { 0, 0, 5 }, .q = b3Quat_identity }, + .scale = { 1, 1, 1 }, + .materials = &mat, + .materialCount = 1, + }; + b3CompoundSphereDef sph = { .sphere = { { -5, 0, 0 }, 0.5f }, .material = mat }; + + b3CompoundDef def = { + .capsules = &cap, .capsuleCount = 1, + .hulls = &hull, .hullCount = 1, + .meshes = &mesh, .meshCount = 1, + .spheres = &sph, .sphereCount = 1, + }; + return b3CreateCompound( &def ); +} + +static int CompoundSerializeRoundtrip( void ) +{ + b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 0.5f, 0.5f, 0.5f }, false ); + b3Compound* a = BuildSerializableCompound( md ); + + // Snapshot a few queries on the original. + b3AABB aabbA = b3ComputeCompoundAABB( a, b3Transform_identity ); + b3RayCastInput rayInput = { .origin = { 0, 0, 0 }, .translation = { 20, 0, 0 }, .maxFraction = 1.0f }; + b3CastOutput rayA = b3RayCastCompound( a, &rayInput ); + ENSURE( rayA.hit ); + + int byteCount = a->byteCount; + uint8_t* buffer = (uint8_t*)malloc( (size_t)byteCount ); + ENSURE( buffer != NULL ); + + uint8_t* serialized = b3ConvertCompoundToBytes( a ); + memcpy( buffer, serialized, (size_t)byteCount ); + b3DestroyCompound( a ); + + b3Compound* b = b3ConvertBytesToCompound( buffer, byteCount ); + ENSURE( b != NULL ); + ENSURE( b->byteCount == byteCount ); + ENSURE( b->capsuleCount == 1 ); + ENSURE( b->hullCount == 1 ); + ENSURE( b->meshCount == 1 ); + ENSURE( b->sphereCount == 1 ); + ENSURE( b->tree.nodes != NULL ); + + // Bounds and ray cast on the deserialized compound match the original. + b3AABB aabbB = b3ComputeCompoundAABB( b, b3Transform_identity ); + ENSURE_SMALL( aabbA.lowerBound.x - aabbB.lowerBound.x, 1e-5f ); + ENSURE_SMALL( aabbA.upperBound.z - aabbB.upperBound.z, 1e-5f ); + + b3CastOutput rayB = b3RayCastCompound( b, &rayInput ); + ENSURE( rayB.hit == rayA.hit ); + ENSURE_SMALL( rayB.fraction - rayA.fraction, 1e-5f ); + ENSURE( rayB.childIndex == rayA.childIndex ); + + free( buffer ); + b3DestroyMesh( md ); + return 0; +} + +static int CompoundSerializeBadVersion( void ) +{ + b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 0.5f, 0.5f, 0.5f }, false ); + b3Compound* a = BuildSerializableCompound( md ); + + int byteCount = a->byteCount; + uint8_t* buffer = (uint8_t*)malloc( (size_t)byteCount ); + memcpy( buffer, b3ConvertCompoundToBytes( a ), (size_t)byteCount ); + b3DestroyCompound( a ); + + // Corrupt the version word (first 8 bytes of b3Compound). + ((b3Compound*)buffer)->version ^= 0x1ull; + + b3Compound* b = b3ConvertBytesToCompound( buffer, byteCount ); + ENSURE( b == NULL ); + + free( buffer ); + b3DestroyMesh( md ); + return 0; +} + +static int CompoundSerializeWrongByteCount( void ) +{ + b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 0.5f, 0.5f, 0.5f }, false ); + b3Compound* a = BuildSerializableCompound( md ); + + int byteCount = a->byteCount; + uint8_t* buffer = (uint8_t*)malloc( (size_t)byteCount ); + memcpy( buffer, b3ConvertCompoundToBytes( a ), (size_t)byteCount ); + b3DestroyCompound( a ); + + // Off-by-one in the declared length is rejected. + b3Compound* b = b3ConvertBytesToCompound( buffer, byteCount + 1 ); + ENSURE( b == NULL ); + + free( buffer ); + b3DestroyMesh( md ); + return 0; +} + +// --------------------------------------------------------------------------- + +int CompoundTest( void ) +{ + RUN_SUBTEST( CompoundCreateMixed ); + RUN_SUBTEST( CompoundCreateSingleType ); + + RUN_SUBTEST( CompoundMaterialDedup ); + RUN_SUBTEST( CompoundMaterialDistinct ); + RUN_SUBTEST( CompoundMaterialCrossShape ); + RUN_SUBTEST( CompoundMaterialMeshShared ); + + RUN_SUBTEST( CompoundHullSharingPointer ); + RUN_SUBTEST( CompoundHullSharingContent ); + RUN_SUBTEST( CompoundHullDistinct ); + RUN_SUBTEST( CompoundMeshSharingPointer ); + RUN_SUBTEST( CompoundMeshSharingContent ); + RUN_SUBTEST( CompoundMeshDistinct ); + + RUN_SUBTEST( CompoundChildDispatch ); + + RUN_SUBTEST( CompoundAABBContainsChildren ); + + RUN_SUBTEST( CompoundRayCastMiss ); + RUN_SUBTEST( CompoundRayCastClosest ); + RUN_SUBTEST( CompoundRayCastHullNormalRotation ); + RUN_SUBTEST( CompoundShapeCastClosest ); + + RUN_SUBTEST( CompoundOverlap ); + RUN_SUBTEST( CompoundQuery ); + + RUN_SUBTEST( CompoundMover ); + + RUN_SUBTEST( CompoundSerializeRoundtrip ); + RUN_SUBTEST( CompoundSerializeBadVersion ); + RUN_SUBTEST( CompoundSerializeWrongByteCount ); + + return 0; +} diff --git a/test/test_container.c b/test/test_container.c new file mode 100644 index 0000000..51cc32b --- /dev/null +++ b/test/test_container.c @@ -0,0 +1,195 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "container.h" +#include "core.h" +#include "test_macros.h" + +#include +#include + +b3DeclareArrayNative( uint64_t ); +b3DeclareArrayNative( int16_t ); +b3DeclareArrayNative( uint8_t ); + +typedef struct Foo +{ + int a; + float b; +} Foo; + +b3DeclareArray( Foo ); + +typedef struct Bar +{ + b3ArrayC( int ) a; +} Bar; + +static int TestCreateDestroy( void ) +{ + b3ArrayC( int ) a; + b3Array_Create( a ); + b3Array_Destroy( a ); + return 0; +} + +static int TestAccess( void ) +{ + b3ArrayC( int ) a; + b3Array_Create( a ); + b3Array_Push( a, 42 ); + int* element = b3Array_Get( a, 0 ); + ENSURE( *element == 42 ); + b3Array_Destroy( a ); + return 0; +} + +static int TestIteration( void ) +{ + b3ArrayC( int ) a = { 0 }; + b3Array_Push( a, 1 ); + b3Array_Push( a, 2 ); + b3Array_Push( a, 3 ); + + int sum = 0; + for ( int i = 0; i < a.count; ++i ) + { + sum += a.data[i]; + } + + ENSURE( sum == 6 ); + b3Array_Destroy( a ); + return 0; +} + +static int TestArrayOfStruct( void ) +{ + b3ArrayC( Foo ) a; + b3Array_Create( a ); + b3Array_Push( a, ( (Foo){ .a = 1, .b = 5.0f } ) ); + b3Array_Push( a, ( (Foo){ .a = 2, .b = 6.0f } ) ); + b3Array_Push( a, ( (Foo){ .a = 3, .b = 7.0f } ) ); + + int sum1 = 0; + float sum2 = 0.0f; + for ( int i = 0; i < a.count; ++i ) + { + sum1 += a.data[i].a; + sum2 += a.data[i].b; + } + + ENSURE( sum1 == 6 ); + ENSURE( sum2 == 18.0f ); + + b3Array_Destroy( a ); + return 0; +} + +static int TestStructWithArray( void ) +{ + Bar a; + b3Array_Create( a.a ); + b3Array_Push( a.a, 1 ); + b3Array_Push( a.a, 2 ); + b3Array_Push( a.a, 3 ); + + int sum1 = 0; + for ( int i = 0; i < a.a.count; ++i ) + { + sum1 += a.a.data[i]; + } + + ENSURE( sum1 == 6 ); + + b3Array_Destroy( a.a ); + return 0; +} + +static int TestArrayEmplace( void ) +{ + b3ArrayC( int ) a = { 0 }; + + int n = 100; + for ( int i = 0; i < n; ++i ) + { + int* j = b3Array_Emplace( a ); + *j = i; + } + + int sum = 0; + for ( int i = 0; i < a.count; ++i ) + { + sum += a.data[i]; + } + + ENSURE( sum == n * (n - 1) / 2); + + b3Array_Destroy( a ); + return 0; +} + +static int TestArrayRemove( void ) +{ + b3ArrayC( int16_t ) a = { 0 }; + + int n = 100; + b3Array_Reserve( a, n ); + ENSURE( a.capacity == n && a.count == 0 ); + + for ( int i = 0; i < n; ++i ) + { + b3Array_Push( a, i ); + } + + int sum = 0; + for ( int i = 0; i < n; ++i ) + { + int16_t* value = b3Array_Get( a, 0 ); + sum += *value; + b3Array_RemoveSwap(a, 0); + } + + ENSURE( sum == n * ( n - 1 ) / 2 ); + + b3Array_Destroy( a ); + return 0; +} + +static int TestArrayPop( void ) +{ + b3ArrayC( int ) a = { 0 }; + + int n = 10; + b3Array_Resize( a, n ); + ENSURE( a.capacity == n && a.count == n ); + + for ( int i = 0; i < n; ++i ) + { + a.data[i] = i; + } + + int sum = 0; + while (a.count > 0) + { + sum += b3Array_Pop( a ); + } + + ENSURE( sum == n * ( n - 1 ) / 2 ); + + b3Array_Destroy( a ); + return 0; +} + +int ContainerTest( void ) +{ + RUN_SUBTEST( TestCreateDestroy ); + RUN_SUBTEST( TestAccess ); + RUN_SUBTEST( TestIteration ); + RUN_SUBTEST( TestArrayOfStruct ); + RUN_SUBTEST( TestStructWithArray ); + RUN_SUBTEST( TestArrayEmplace ); + RUN_SUBTEST( TestArrayRemove ); + RUN_SUBTEST( TestArrayPop ); + + return 0; +} diff --git a/test/test_determinism.c b/test/test_determinism.c new file mode 100644 index 0000000..1d97f8f --- /dev/null +++ b/test/test_determinism.c @@ -0,0 +1,113 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "box3d/box3d.h" +#include "determinism.h" +#include "test_macros.h" + +#include +#include + +#ifdef BOX3D_PROFILE + #include +#else + #define TracyCFrameMark +#endif + +#define EXPECTED_SLEEP_STEP 306 +#define EXPECTED_HASH 0xCBF958A1 + +static int SingleMultithreadingTest( int workerCount ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.workerCount = workerCount; + + b3WorldId worldId = b3CreateWorld( &worldDef ); + + FallingRagdollData data = CreateFallingRagdolls( worldId ); + + float timeStep = 1.0f / 60.0f; + + int stepLimit = 500; + for ( int i = 0; i < stepLimit; ++i ) + { + int subStepCount = 4; + b3World_Step( worldId, timeStep, subStepCount ); + TracyCFrameMark; + + bool done = UpdateFallingRagdolls( worldId, &data ); + if ( done ) + { + break; + } + } + + b3DestroyWorld( worldId ); + + if ( data.sleepStep != EXPECTED_SLEEP_STEP || data.hash != EXPECTED_HASH ) + { + printf( " workers=%d sleepStep=%d hash=0x%08X\n", workerCount, data.sleepStep, data.hash ); + } + + ENSURE( data.sleepStep == EXPECTED_SLEEP_STEP ); + ENSURE( data.hash == EXPECTED_HASH ); + + DestroyFallingRagdolls( &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 ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + FallingRagdollData data = CreateFallingRagdolls( worldId ); + + float timeStep = 1.0f / 60.0f; + + bool done = false; + while ( done == false ) + { + int subStepCount = 4; + b3World_Step( worldId, timeStep, subStepCount ); + TracyCFrameMark; + + done = UpdateFallingRagdolls( worldId, &data ); + } + + if ( data.sleepStep != EXPECTED_SLEEP_STEP || data.hash != EXPECTED_HASH ) + { + printf( " cross-platform sleepStep=%d hash=0x%08X\n", data.sleepStep, data.hash ); + } + + ENSURE( data.sleepStep == EXPECTED_SLEEP_STEP ); + ENSURE( data.hash == EXPECTED_HASH ); + + DestroyFallingRagdolls( &data ); + + b3DestroyWorld( worldId ); + + return 0; +} + +int DeterminismTest( void ) +{ + RUN_SUBTEST( MultithreadingTest ); + RUN_SUBTEST( CrossPlatformTest ); + + return 0; +} diff --git a/test/test_distance.c b/test/test_distance.c new file mode 100644 index 0000000..27cee4d --- /dev/null +++ b/test/test_distance.c @@ -0,0 +1,112 @@ +// 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; + + b2DistanceCache cache = { 0 }; + b2DistanceOutput output = b2ShapeDistance( &cache, &input, 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.tMax = 1.0f; + + b2TOIOutput output = b2TimeOfImpact( &input ); + + ENSURE( output.state == b2_toiStateHit ); + ENSURE_SMALL( output.t - 0.5f, 0.005f ); + + return 0; +} + +int DistanceTest( void ) +{ + RUN_SUBTEST( SegmentDistanceTest ); + RUN_SUBTEST( ShapeDistanceTest ); + RUN_SUBTEST( ShapeCastTest ); + RUN_SUBTEST( TimeOfImpactTest ); + + return 0; +} diff --git a/test/test_height_field.c b/test/test_height_field.c new file mode 100644 index 0000000..a664e68 --- /dev/null +++ b/test/test_height_field.c @@ -0,0 +1,246 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#include "test_macros.h" + +// b3GetHeightFieldTriangle is internal +#include "shape.h" + +#include "box3d/collision.h" +#include "box3d/math_functions.h" + +#include +#include + +static int HeightFieldCreate( void ) +{ + b3Vec3 scale = { 1.0f, 1.0f, 1.0f }; + b3HeightField* hf = b3CreateGrid( 4, 4, scale, false ); + + ENSURE( hf->rowCount == 4 ); + ENSURE( hf->columnCount == 4 ); + ENSURE( hf->clockwise == false ); + ENSURE( hf->version == B3_HEIGHT_FIELD_VERSION ); + + ENSURE_SMALL( hf->aabb.lowerBound.x, FLT_EPSILON ); + ENSURE_SMALL( hf->aabb.lowerBound.y, FLT_EPSILON ); + ENSURE_SMALL( hf->aabb.lowerBound.z, FLT_EPSILON ); + + ENSURE_SMALL( hf->aabb.upperBound.x - 3.0f, FLT_EPSILON ); + ENSURE_SMALL( hf->aabb.upperBound.y, FLT_EPSILON ); + ENSURE_SMALL( hf->aabb.upperBound.z - 3.0f, FLT_EPSILON ); + + b3DestroyHeightField( hf ); + return 0; +} + +static int HeightFieldTriangleIndex( void ) +{ + // Asymmetric grid (rows != cols) catches off-by-one errors between + // vertex stride (columnCount) and cell stride (columnCount - 1). + int rowCount = 4; + int columnCount = 5; + b3Vec3 scale = { 1.0f, 1.0f, 1.0f }; + b3HeightField* hf = b3CreateGrid( rowCount, columnCount, scale, false ); + + int triangleCount = 2 * ( rowCount - 1 ) * ( columnCount - 1 ); + + for ( int triangleIndex = 0; triangleIndex < triangleCount; ++triangleIndex ) + { + int quadIndex = triangleIndex >> 1; + int sub = triangleIndex & 1; + int row = quadIndex / ( columnCount - 1 ); + int column = quadIndex - row * ( columnCount - 1 ); + + int index11 = row * columnCount + column; + int index12 = index11 + 1; + int index21 = ( row + 1 ) * columnCount + column; + int index22 = index21 + 1; + + b3Triangle t = b3GetHeightFieldTriangle( hf, triangleIndex ); + + if ( sub == 0 ) + { + // Triangle 0 (CCW): {11, 21, 12} + ENSURE( t.i1 == index11 ); + ENSURE( t.i2 == index21 ); + ENSURE( t.i3 == index12 ); + } + else + { + // Triangle 1 (CCW): {22, 12, 21} + ENSURE( t.i1 == index22 ); + ENSURE( t.i2 == index12 ); + ENSURE( t.i3 == index21 ); + } + } + + b3DestroyHeightField( hf ); + return 0; +} + +static int HeightFieldWinding( void ) +{ + // Build the same flat 3x3 field with CCW and CW winding. The cross-product + // normal of triangle 0 must flip sign accordingly. + float heights[9] = { 0 }; + uint8_t materials[4] = { 0, 0, 0, 0 }; + + b3HeightFieldDef def = { 0 }; + def.heights = heights; + def.materialIndices = materials; + def.scale = (b3Vec3){ 1.0f, 1.0f, 1.0f }; + def.countX = 3; + def.countZ = 3; + def.globalMinimumHeight = -1.0f; + def.globalMaximumHeight = 1.0f; + + def.clockwiseWinding = false; + b3HeightField* ccw = b3CreateHeightField( &def ); + + def.clockwiseWinding = true; + b3HeightField* cw = b3CreateHeightField( &def ); + + b3Triangle ta = b3GetHeightFieldTriangle( ccw, 0 ); + b3Triangle tb = b3GetHeightFieldTriangle( cw, 0 ); + + b3Vec3 na = + b3Normalize( b3Cross( b3Sub( ta.vertices[1], ta.vertices[0] ), b3Sub( ta.vertices[2], ta.vertices[0] ) ) ); + b3Vec3 nb = + b3Normalize( b3Cross( b3Sub( tb.vertices[1], tb.vertices[0] ), b3Sub( tb.vertices[2], tb.vertices[0] ) ) ); + + ENSURE_SMALL( na.x, FLT_EPSILON ); + ENSURE_SMALL( na.y - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( na.z, FLT_EPSILON ); + + ENSURE_SMALL( nb.x, FLT_EPSILON ); + ENSURE_SMALL( nb.y + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( nb.z, FLT_EPSILON ); + + b3DestroyHeightField( ccw ); + b3DestroyHeightField( cw ); + return 0; +} + +static int RayCastFlatField( void ) +{ + // Build a flat 4x4 field with a tight quantization range so the recovered + // surface stays within ~1e-5 of y=0 (b3CreateGrid uses -256..256 which + // blows the 1/UINT16_MAX quantum up to ~4e-3 in y). + float heights[16] = { 0 }; + uint8_t materials[9] = { 0 }; + + b3HeightFieldDef def = { 0 }; + def.heights = heights; + def.materialIndices = materials; + def.scale = (b3Vec3){ 1.0f, 1.0f, 1.0f }; + def.countX = 4; + def.countZ = 4; + def.globalMinimumHeight = -1.0f; + def.globalMaximumHeight = 1.0f; + def.clockwiseWinding = false; + + b3HeightField* hf = b3CreateHeightField( &def ); + + // Origin sits clearly inside triangle 0 of cell (1, 1) — off the cell + // diagonal x+z = 3. The translation overshoots the surface so the hit + // fraction is strictly less than maxFraction. + b3RayCastInput input = { 0 }; + input.origin = (b3Vec3){ 1.25f, 10.0f, 1.25f }; + input.translation = (b3Vec3){ 0.0f, -20.0f, 0.0f }; + input.maxFraction = 1.0f; + + b3CastOutput out = b3RayCastHeightField( hf, &input ); + + ENSURE( out.hit == true ); + ENSURE_SMALL( out.fraction - 0.5f, 1e-5f ); + ENSURE_SMALL( out.normal.x, 1e-5f ); + ENSURE_SMALL( out.normal.y - 1.0f, 1e-5f ); + ENSURE_SMALL( out.normal.z, 1e-5f ); + + b3DestroyHeightField( hf ); + return 0; +} + +static int OverlapAtSurface( void ) +{ + b3Vec3 scale = { 1.0f, 1.0f, 1.0f }; + b3HeightField* hf = b3CreateGrid( 4, 4, scale, false ); + + // Sphere center 1.0 above the surface, radius 0.5 — clear gap. + b3Vec3 above = { 1.5f, 1.0f, 1.5f }; + b3ShapeProxy proxyAbove = { &above, 1, 0.5f }; + bool hitAbove = b3OverlapHeightField( hf, b3Transform_identity, &proxyAbove ); + ENSURE( hitAbove == false ); + + // Sphere centered on the surface — radius pokes through. + b3Vec3 through = { 1.5f, 0.0f, 1.5f }; + b3ShapeProxy proxyThrough = { &through, 1, 0.5f }; + bool hitThrough = b3OverlapHeightField( hf, b3Transform_identity, &proxyThrough ); + ENSURE( hitThrough == true ); + + b3DestroyHeightField( hf ); + return 0; +} + +static int FileRoundtrip( void ) +{ + float heights[9] = { 0.0f, 0.5f, -0.3f, 0.1f, 0.0f, 0.0f, 0.0f, 0.2f, 0.0f }; + uint8_t materials[4] = { 0, B3_HEIGHT_FIELD_HOLE, 1, 2 }; + + b3HeightFieldDef def = { 0 }; + def.heights = heights; + def.materialIndices = materials; + def.scale = (b3Vec3){ 1.5f, 2.0f, 0.75f }; + def.countX = 3; + def.countZ = 3; + def.globalMinimumHeight = -1.0f; + def.globalMaximumHeight = 1.0f; + def.clockwiseWinding = true; + + const char* path = "test_height_field_roundtrip.dat"; + b3DumpHeightData( &def, path ); + + b3HeightField* loaded = b3LoadHeightField( path ); + remove( path ); + + ENSURE( loaded != NULL ); + ENSURE( loaded->rowCount == def.countZ ); + ENSURE( loaded->columnCount == def.countX ); + ENSURE( loaded->clockwise == def.clockwiseWinding ); + + ENSURE_SMALL( loaded->scale.x - def.scale.x, FLT_EPSILON ); + ENSURE_SMALL( loaded->scale.y - def.scale.y, FLT_EPSILON ); + ENSURE_SMALL( loaded->scale.z - def.scale.z, FLT_EPSILON ); + ENSURE_SMALL( loaded->minHeight - def.globalMinimumHeight, FLT_EPSILON ); + ENSURE_SMALL( loaded->maxHeight - def.globalMaximumHeight, FLT_EPSILON ); + + int cellCount = ( def.countX - 1 ) * ( def.countZ - 1 ); + for ( int i = 0; i < cellCount; ++i ) + { + ENSURE( loaded->materialIndices[i] == materials[i] ); + } + + // Recovered heights round-trip within the quantization tolerance. + float quantum = ( def.globalMaximumHeight - def.globalMinimumHeight ) / (float)UINT16_MAX; + for ( int i = 0; i < def.countX * def.countZ; ++i ) + { + float recovered = loaded->minHeight + loaded->heightScale * loaded->compressedHeights[i]; + ENSURE_SMALL( recovered - heights[i], 2.0f * quantum ); + } + + b3DestroyHeightField( loaded ); + return 0; +} + +int HeightFieldTest( void ) +{ + RUN_SUBTEST( HeightFieldCreate ); + RUN_SUBTEST( HeightFieldTriangleIndex ); + RUN_SUBTEST( HeightFieldWinding ); + RUN_SUBTEST( RayCastFlatField ); + RUN_SUBTEST( OverlapAtSurface ); + RUN_SUBTEST( FileRoundtrip ); + + return 0; +} diff --git a/test/test_hull.c b/test/test_hull.c new file mode 100644 index 0000000..ac37252 --- /dev/null +++ b/test/test_hull.c @@ -0,0 +1,462 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#include "test_macros.h" + +#include "box3d/collision.h" +#include "box3d/math_functions.h" + +#include +#include +#include + +static const b3Vec3 s_cubeCorners[8] = { + { 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f }, { -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f }, + { 1.0f, 1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f }, { -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f }, +}; + +static int CreateHullCubeTest( void ) +{ + b3Hull* hull = b3CreateHull( s_cubeCorners, 8, 8 ); + ENSURE( hull != NULL ); + + ENSURE( hull->vertexCount == 8 ); + ENSURE( hull->edgeCount == 24 ); + ENSURE( hull->faceCount == 6 ); + + // Euler's identity for convex polyhedron + ENSURE( hull->vertexCount - hull->edgeCount / 2 + hull->faceCount == 2 ); + + b3BoxHull ref = b3MakeBoxHull( 1.0f, 1.0f, 1.0f ); + + ENSURE_SMALL( hull->volume - ref.base.volume, 1e-4f ); + ENSURE_SMALL( hull->surfaceArea - ref.base.surfaceArea, 1e-4f ); + ENSURE_SMALL( hull->innerRadius - ref.base.innerRadius, FLT_EPSILON ); + + ENSURE_SMALL( hull->center.x - ref.base.center.x, 1e-5f ); + ENSURE_SMALL( hull->center.y - ref.base.center.y, 1e-5f ); + ENSURE_SMALL( hull->center.z - ref.base.center.z, 1e-5f ); + + ENSURE_SMALL( hull->aabb.lowerBound.x + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.lowerBound.y + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.lowerBound.z + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.upperBound.x - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.upperBound.y - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.upperBound.z - 1.0f, FLT_EPSILON ); + + b3Matrix3 d = b3SubMM( hull->centralInertia, ref.base.centralInertia ); + ENSURE_SMALL( d.cx.x, 1e-4f ); + ENSURE_SMALL( d.cy.y, 1e-4f ); + ENSURE_SMALL( d.cz.z, 1e-4f ); + ENSURE_SMALL( d.cx.y, 1e-4f ); + ENSURE_SMALL( d.cx.z, 1e-4f ); + ENSURE_SMALL( d.cy.z, 1e-4f ); + ENSURE_SMALL( d.cy.x, 1e-4f ); + ENSURE_SMALL( d.cz.x, 1e-4f ); + ENSURE_SMALL( d.cz.y, 1e-4f ); + + b3DestroyHull( hull ); + return 0; +} + +static int CreateHullTetrahedronTest( void ) +{ + b3Vec3 points[4] = { + { 0.0f, 0.0f, 0.0f }, + { 1.0f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f }, + { 0.0f, 0.0f, 1.0f }, + }; + + b3Hull* hull = b3CreateHull( points, 4, 4 ); + ENSURE( hull != NULL ); + + ENSURE( hull->vertexCount == 4 ); + ENSURE( hull->edgeCount == 12 ); + ENSURE( hull->faceCount == 4 ); + ENSURE( hull->vertexCount - hull->edgeCount / 2 + hull->faceCount == 2 ); + + // Analytic values for the unit-corner tetrahedron at the origin. + float expectedVolume = 1.0f / 6.0f; + float expectedSurfaceArea = 1.5f + 0.5f * sqrtf( 3.0f ); + float expectedInnerRadius = 0.25f / sqrtf( 3.0f ); + + ENSURE_SMALL( hull->volume - expectedVolume, 1e-5f ); + ENSURE_SMALL( hull->surfaceArea - expectedSurfaceArea, 1e-5f ); + ENSURE_SMALL( hull->innerRadius - expectedInnerRadius, 1e-5f ); + + ENSURE_SMALL( hull->center.x - 0.25f, 1e-5f ); + ENSURE_SMALL( hull->center.y - 0.25f, 1e-5f ); + ENSURE_SMALL( hull->center.z - 0.25f, 1e-5f ); + + ENSURE_SMALL( hull->aabb.lowerBound.x, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.lowerBound.y, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.lowerBound.z, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.upperBound.x - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.upperBound.y - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.upperBound.z - 1.0f, FLT_EPSILON ); + + b3DestroyHull( hull ); + return 0; +} + +static int CreateHullDeterminismTest( void ) +{ + b3Hull* h1 = b3CreateHull( s_cubeCorners, 8, 8 ); + b3Hull* h2 = b3CreateHull( s_cubeCorners, 8, 8 ); + ENSURE( h1 != NULL && h2 != NULL ); + + ENSURE( h1->byteCount == h2->byteCount ); + ENSURE( h1->hash != 0 ); + ENSURE( h1->hash == h2->hash ); + ENSURE( memcmp( h1, h2, h1->byteCount ) == 0 ); + + b3DestroyHull( h1 ); + b3DestroyHull( h2 ); + return 0; +} + +#define SPHERE_N 6 + +static int CreateHullMaxVertexTest( void ) +{ + // Sphere-sampled point cloud, dense enough that the builder has room to grow. + b3Vec3 points[SPHERE_N * SPHERE_N]; + int index = 0; + for ( int i = 0; i < SPHERE_N; ++i ) + { + float theta = B3_PI * (float)i / (float)( SPHERE_N - 1 ); + for ( int j = 0; j < SPHERE_N; ++j ) + { + float phi = 2.0f * B3_PI * (float)j / (float)SPHERE_N; + points[index].x = sinf( theta ) * cosf( phi ); + points[index].y = sinf( theta ) * sinf( phi ); + points[index].z = cosf( theta ); + index += 1; + } + } + int count = SPHERE_N * SPHERE_N; + + // maxVertexCount honored as a strict cap. + b3Hull* h1 = b3CreateHull( points, count, 8 ); + ENSURE( h1 != NULL ); + ENSURE( h1->vertexCount <= 8 ); + b3DestroyHull( h1 ); + + // Below the floor: clamps up to 4. + b3Hull* h2 = b3CreateHull( points, count, 1 ); + ENSURE( h2 != NULL ); + ENSURE( h2->vertexCount >= 4 && h2->vertexCount <= 255 ); + b3DestroyHull( h2 ); + + // Above the ceiling: clamps down to 255. + b3Hull* h3 = b3CreateHull( points, count, 1000 ); + ENSURE( h3 != NULL ); + ENSURE( h3->vertexCount >= 4 && h3->vertexCount <= 255 ); + b3DestroyHull( h3 ); + + return 0; +} + +static int CreateHullRedundantInputTest( void ) +{ + // 8 cube corners + duplicates + interior points. Builder should produce the cube. + b3Vec3 points[20] = { + { 1.0f, 1.0f, 1.0f }, // corners + { -1.0f, 1.0f, 1.0f }, + { -1.0f, -1.0f, 1.0f }, + { 1.0f, -1.0f, 1.0f }, + { 1.0f, 1.0f, -1.0f }, + { -1.0f, 1.0f, -1.0f }, + { -1.0f, -1.0f, -1.0f }, + { 1.0f, -1.0f, -1.0f }, + { 1.0f, 1.0f, 1.0f }, // duplicates + { 1.0f, 1.0f, 1.0f }, + { 0.0f, 0.0f, 0.0f }, // interior points + { 0.5f, 0.0f, 0.0f }, + { 0.0f, 0.5f, 0.0f }, + { 0.0f, 0.0f, 0.5f }, + { -0.5f, 0.0f, 0.0f }, + { 0.0f, -0.5f, 0.0f }, + { 0.0f, 0.0f, -0.5f }, + { 0.25f, 0.25f, 0.25f }, + { -0.25f, -0.25f, -0.25f }, + { 0.5f, 0.5f, 0.5f }, + }; + + b3Hull* hull = b3CreateHull( points, 20, 8 ); + ENSURE( hull != NULL ); + + ENSURE( hull->vertexCount == 8 ); + ENSURE( hull->edgeCount == 24 ); + ENSURE( hull->faceCount == 6 ); + + b3BoxHull ref = b3MakeBoxHull( 1.0f, 1.0f, 1.0f ); + + ENSURE_SMALL( hull->volume - ref.base.volume, 1e-4f ); + ENSURE_SMALL( hull->surfaceArea - ref.base.surfaceArea, 1e-4f ); + ENSURE_SMALL( hull->innerRadius - ref.base.innerRadius, FLT_EPSILON ); + + ENSURE_SMALL( hull->center.x - ref.base.center.x, 1e-5f ); + ENSURE_SMALL( hull->center.y - ref.base.center.y, 1e-5f ); + ENSURE_SMALL( hull->center.z - ref.base.center.z, 1e-5f ); + + ENSURE_SMALL( hull->aabb.lowerBound.x + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.lowerBound.y + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.lowerBound.z + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.upperBound.x - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.upperBound.y - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.upperBound.z - 1.0f, FLT_EPSILON ); + + b3DestroyHull( hull ); + return 0; +} + +static int CreateHullCloneTest( void ) +{ + b3Hull* original = b3CreateHull( s_cubeCorners, 8, 8 ); + ENSURE( original != NULL ); + + b3Hull* clone = b3CloneHull( original ); + ENSURE( clone != NULL ); + ENSURE( clone->byteCount == original->byteCount ); + ENSURE( memcmp( clone, original, original->byteCount ) == 0 ); + + b3DestroyHull( clone ); + b3DestroyHull( original ); + return 0; +} + +static int CreateHullCylinderTest( void ) +{ + const float height = 2.0f; + const float radius = 1.0f; + const int sides = 8; + const float yOffset = 0.0f; + + b3Hull* hull = b3CreateCylinder( height, radius, yOffset, sides ); + ENSURE( hull != NULL ); + + ENSURE( hull->vertexCount == 2 * sides ); + ENSURE( hull->edgeCount == 6 * sides ); + ENSURE( hull->faceCount == sides + 2 ); + + // Analytic n-gon prism values (exact targets, not the circular cylinder approximations). + float halfAngle = B3_PI / (float)sides; + float capArea = (float)sides * 0.5f * radius * radius * sinf( 2.0f * halfAngle ); + float chordLen = 2.0f * radius * sinf( halfAngle ); + float lateralArea = (float)sides * chordLen * height; + + float expectedVolume = capArea * height; + float expectedSurfaceArea = 2.0f * capArea + lateralArea; + float expectedInnerRadius = radius * cosf( halfAngle ); + + ENSURE_SMALL( ( hull->volume - expectedVolume ) / expectedVolume, 1e-4f ); + ENSURE_SMALL( ( hull->surfaceArea - expectedSurfaceArea ) / expectedSurfaceArea, 1e-4f ); + ENSURE_SMALL( hull->innerRadius - expectedInnerRadius, 1e-5f ); + + ENSURE_SMALL( hull->center.x, 1e-5f ); + ENSURE_SMALL( hull->center.y - ( yOffset + 0.5f * height ), 1e-5f ); + ENSURE_SMALL( hull->center.z, 1e-5f ); + + ENSURE_SMALL( hull->aabb.lowerBound.x + radius, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.lowerBound.y - yOffset, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.lowerBound.z + radius, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.upperBound.x - radius, FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.upperBound.y - ( yOffset + height ), FLT_EPSILON ); + ENSURE_SMALL( hull->aabb.upperBound.z - radius, FLT_EPSILON ); + + b3DestroyHull( hull ); + return 0; +} + +// Inlined XorShift32 + Shoemake unit-vector recipe matches shared/utils.h exactly so +// generated points are bit-identical to samples that share the seed. +static void FillSphereSample( b3Vec3* points, int count, uint32_t seed ) +{ + const uint32_t RAND_LIMIT_LOCAL = 32767u; + for ( int i = 0; i < count; ++i ) + { + float u[3]; + for ( int k = 0; k < 3; ++k ) + { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + float r = (float)( seed & RAND_LIMIT_LOCAL ); + r /= (float)RAND_LIMIT_LOCAL; + u[k] = r; + } + float u1 = u[0]; + float u2 = 2.0f * B3_PI * u[1]; + float u3 = 2.0f * B3_PI * u[2]; + float sqrt1MinusU1 = sqrtf( 1.0f - u1 ); + float sqrtU1 = sqrtf( u1 ); + points[i].x = sqrt1MinusU1 * sinf( u2 ); + points[i].y = sqrt1MinusU1 * cosf( u2 ); + points[i].z = sqrtU1 * sinf( u3 ); + } +} + +// Reproduces the HullReduction sample (Sphere, 64 points, count=20) that used to assert on +// b->faceCount < b->faceCapacity. The free-list reclaim in NewFace/NewEdge keeps the bump +// counts proportional to the live hull instead of cumulative creations. +static int CreateHullSphereReductionTest( void ) +{ + b3Vec3 points[64]; + FillSphereSample( points, 64, 12345 ); // RAND_SEED + + b3Hull* hull = b3CreateHull( points, 64, 20 ); + ENSURE( hull != NULL ); + ENSURE( hull->vertexCount >= 4 && hull->vertexCount <= 20 ); + ENSURE( hull->vertexCount - hull->edgeCount / 2 + hull->faceCount == 2 ); + b3DestroyHull( hull ); + + return 0; +} + +// XorShift32 + uniform-cube point generator. Same engine as FillSphereSample. +static void FillCubeSample( b3Vec3* points, int count, uint32_t seed ) +{ + const uint32_t RAND_LIMIT_LOCAL = 32767u; + for ( int i = 0; i < count; ++i ) + { + float v[3]; + for ( int k = 0; k < 3; ++k ) + { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + float r = (float)( seed & RAND_LIMIT_LOCAL ); + r /= (float)RAND_LIMIT_LOCAL; + v[k] = 2.0f * r - 1.0f; + } + points[i].x = v[0]; + points[i].y = v[1]; + points[i].z = v[2]; + } +} + +// Pushes the working-stage bump capacities (faceCapacity = 5*M - 10, edgeCapacity = +// 24*M - 48 in src/hull.c::b3ComputeHullWorkSizes) close to their peak by sweeping M +// on a dense random sphere. If the peak face/edge count exceeds the cap and the free +// list fails to reclaim slots in time, the assertion at src/hull.c::NewFace/NewEdge +// fires (exit code 3). M is held <= 80 because the finalization stage caps the final +// hull's face/edge count at B3_HULL_LIMIT (255), and a fully-triangulated hull with +// V > 87 vertices has 3V - 6 > 255 edges (src/hull.c:2010 returns NULL). +static int CreateHullSphereStressTest( void ) +{ + enum { N = 512 }; + b3Vec3 points[N]; + + // Multiple seeds exercise different horizon-size / merge-cascade sequences. + const uint32_t seeds[] = { 12345u, 1u, 0xdeadbeefu, 0xcafef00du }; + + // M kept <= 40: random sphere inputs at higher M exceed the half edge limit of UINT8_MAX + const int M_values[] = { 16, 24, 32, 40 }; + + for ( int s = 0; s < ARRAY_COUNT( seeds ); ++s ) + { + FillSphereSample( points, N, seeds[s] ); + + for ( int m = 0; m < ARRAY_COUNT( M_values ); ++m ) + { + int M = M_values[m]; + b3Hull* hull = b3CreateHull( points, N, M ); + ENSURE( hull != NULL ); + ENSURE( hull->vertexCount >= 4 && hull->vertexCount <= M ); + ENSURE( hull->vertexCount - hull->edgeCount / 2 + hull->faceCount == 2 ); + ENSURE( hull->faceCount >= 4 ); + b3DestroyHull( hull ); + } + } + + return 0; +} + +// Random points inside a cube produce a small final hull (8 corners, 6 faces) but +// generate heavy internal churn: every interior point gets fed to the conflict-list +// machinery, and most cone faces created during apex insertion are then merged out +// when their newly-created neighbors are coplanar. Exercises the merge cascade in +// b3HullBuilder_ConnectEdges/ConnectFaces and the corresponding RetireFace/RetireEdge +// reclaim path much harder than the sphere case (which has few merges). +static int CreateHullMergeChurnStressTest( void ) +{ + enum { N = 4096 }; + static b3Vec3 points[N]; + + const uint32_t seeds[] = { 12345u, 0xdeadbeefu }; + + for ( int s = 0; s < ARRAY_COUNT( seeds ); ++s ) + { + FillCubeSample( points, N, seeds[s] ); + + // Stamp the 8 corners last so they're guaranteed extremes. + for ( int c = 0; c < 8; ++c ) + { + points[N - 8 + c].x = ( c & 1 ) ? 1.0f : -1.0f; + points[N - 8 + c].y = ( c & 2 ) ? 1.0f : -1.0f; + points[N - 8 + c].z = ( c & 4 ) ? 1.0f : -1.0f; + } + + b3Hull* hull = b3CreateHull( points, N, 64 ); + ENSURE( hull != NULL ); + ENSURE( hull->vertexCount == 8 ); + ENSURE( hull->edgeCount == 24 ); + ENSURE( hull->faceCount == 6 ); + b3DestroyHull( hull ); + } + + return 0; +} + +static int CreateHullDegenerateTest( void ) +{ + // Real (non-null) buffer; pointCount < 4 cases are guarded inside Construct(). + b3Vec3 collinear[8] = { + { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, { 2.0f, 0.0f, 0.0f }, { 3.0f, 0.0f, 0.0f }, + { 4.0f, 0.0f, 0.0f }, { 5.0f, 0.0f, 0.0f }, { 6.0f, 0.0f, 0.0f }, { 7.0f, 0.0f, 0.0f }, + }; + + // Empty input. + ENSURE( b3CreateHull( collinear, 0, 8 ) == NULL ); + + // Fewer than 4 points. + ENSURE( b3CreateHull( collinear, 3, 8 ) == NULL ); + + // 8 coincident points. + b3Vec3 coincident[8] = { + { 1.0f, 2.0f, 3.0f }, { 1.0f, 2.0f, 3.0f }, { 1.0f, 2.0f, 3.0f }, { 1.0f, 2.0f, 3.0f }, + { 1.0f, 2.0f, 3.0f }, { 1.0f, 2.0f, 3.0f }, { 1.0f, 2.0f, 3.0f }, { 1.0f, 2.0f, 3.0f }, + }; + ENSURE( b3CreateHull( coincident, 8, 8 ) == NULL ); + + // Collinear (along x-axis). + ENSURE( b3CreateHull( collinear, 8, 8 ) == NULL ); + + // Coplanar (in the xy-plane). + b3Vec3 coplanar[6] = { + { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, + { 1.0f, 1.0f, 0.0f }, { 2.0f, 0.5f, 0.0f }, { 0.5f, 2.0f, 0.0f }, + }; + ENSURE( b3CreateHull( coplanar, 6, 8 ) == NULL ); + + return 0; +} + +int HullTest( void ) +{ + RUN_SUBTEST( CreateHullCubeTest ); + RUN_SUBTEST( CreateHullTetrahedronTest ); + RUN_SUBTEST( CreateHullDeterminismTest ); + RUN_SUBTEST( CreateHullMaxVertexTest ); + RUN_SUBTEST( CreateHullRedundantInputTest ); + RUN_SUBTEST( CreateHullCloneTest ); + RUN_SUBTEST( CreateHullCylinderTest ); + RUN_SUBTEST( CreateHullSphereReductionTest ); + RUN_SUBTEST( CreateHullSphereStressTest ); + RUN_SUBTEST( CreateHullMergeChurnStressTest ); + RUN_SUBTEST( CreateHullDegenerateTest ); + + return 0; +} diff --git a/test/test_id.c b/test/test_id.c new file mode 100644 index 0000000..4736ca5 --- /dev/null +++ b/test/test_id.c @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: 2023 Erin Catto +// SPDX-License-Identifier: MIT + +#include "test_macros.h" + +#include "box3d/types.h" + +int IdTest( void ) +{ + uint64_t x = 0x0123456789ABCDEFull; + + { + b3BodyId id = b3LoadBodyId( x ); + uint64_t y = b3StoreBodyId( id ); + ENSURE( x == y ); + } + + { + b3ShapeId id = b3LoadShapeId( x ); + uint64_t y = b3StoreShapeId( id ); + ENSURE( x == y ); + } + + { + b3JointId id = b3LoadJointId( x ); + uint64_t y = b3StoreJointId( id ); + ENSURE( x == y ); + } + + return 0; +} diff --git a/test/test_macros.h b/test/test_macros.h new file mode 100644 index 0000000..95b4412 --- /dev/null +++ b/test/test_macros.h @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: 2024 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#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" ); \ + return 1; \ + } \ + } \ + while ( false ) + +#define ENSURE_SMALL( C, tol ) \ + do \ + { \ + if ( ( C ) < -( tol ) || ( tol ) < ( C ) ) \ + { \ + printf( "condition false: abs(" #C ") < %g\n", tol ); \ + 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 ) ) diff --git a/test/test_math.c b/test/test_math.c new file mode 100644 index 0000000..074fcef --- /dev/null +++ b/test/test_math.c @@ -0,0 +1,277 @@ +// SPDX-FileCopyrightText: 2023 Erin Catto +// SPDX-License-Identifier: MIT + +#include "math_internal.h" +#include "utils.h" +#include "test_macros.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 = B3_PI * t; + b3CosSin cs = b3ComputeCosSin( 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( cs.cosine - c, 0.002f ); + ENSURE_SMALL( cs.sine - s, 0.002f ); + + float xn = b3UnwindAngle( angle ); + float a = b3Atan2( s, c ); + ENSURE( b3IsValidFloat( a ) ); + + float diff = b3AbsFloat( a - xn ); + + // The two results can be off by 360 degrees (-pi and pi) + if ( diff > B3_PI ) + { + diff -= 2.0f * B3_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 = b3Atan2( y, x ); + float a2 = atan2f( y, x ); + float diff = b3AbsFloat( a1 - a2 ); + ENSURE( b3IsValidFloat( a1 ) ); + ENSURE_SMALL( diff, ATAN_TOL ); + } + } + + { + float a1 = b3Atan2( 1.0f, 0.0f ); + float a2 = atan2f( 1.0f, 0.0f ); + float diff = b3AbsFloat( a1 - a2 ); + ENSURE( b3IsValidFloat( a1 ) ); + ENSURE_SMALL( diff, ATAN_TOL ); + } + + { + float a1 = b3Atan2( -1.0f, 0.0f ); + float a2 = atan2f( -1.0f, 0.0f ); + float diff = b3AbsFloat( a1 - a2 ); + ENSURE( b3IsValidFloat( a1 ) ); + ENSURE_SMALL( diff, ATAN_TOL ); + } + + { + float a1 = b3Atan2( 0.0f, 1.0f ); + float a2 = atan2f( 0.0f, 1.0f ); + float diff = b3AbsFloat( a1 - a2 ); + ENSURE( b3IsValidFloat( a1 ) ); + ENSURE_SMALL( diff, ATAN_TOL ); + } + + { + float a1 = b3Atan2( 0.0f, -1.0f ); + float a2 = atan2f( 0.0f, -1.0f ); + float diff = b3AbsFloat( a1 - a2 ); + ENSURE( b3IsValidFloat( a1 ) ); + ENSURE_SMALL( diff, ATAN_TOL ); + } + + { + float a1 = b3Atan2( 0.0f, 0.0f ); + float a2 = atan2f( 0.0f, 0.0f ); + float diff = b3AbsFloat( a1 - a2 ); + ENSURE( b3IsValidFloat( a1 ) ); + ENSURE_SMALL( diff, ATAN_TOL ); + } + + b3Vec3 zero = { 0 }; + b3Vec3 one = { 1.0f, 1.0f, 1.0f }; + b3Vec3 two = { 2.0f, 2.0f, 2.0f }; + + b3Vec3 v = b3Add( one, two ); + ENSURE( v.x == 3.0f && v.y == 3.0f ); + + v = b3Sub( zero, two ); + ENSURE( v.x == -2.0f && v.y == -2.0f ); + + v = b3Add( two, two ); + ENSURE( v.x != 5.0f && v.y != 5.0f ); + + b3Vec3 axis = b3Normalize( (b3Vec3){ -0.75f, 0.5f, 1.0f } ); + b3Transform transform1 = { { -2.0f, 3.0f, 0.0f }, b3Quat_identity }; + b3Transform transform2 = { { 1.0f, 0.0f, 0.0f }, b3MakeQuatFromAxisAngle( axis, B3_PI ) }; + + b3Transform transform = b3MulTransforms( transform2, transform1 ); + + v = b3TransformPoint( transform2, b3TransformPoint( transform1, two ) ); + + b3Vec3 u = b3TransformPoint( transform, two ); + + ENSURE_SMALL( u.x - v.x, 10.0f * FLT_EPSILON ); + ENSURE_SMALL( u.y - v.y, 10.0f * FLT_EPSILON ); + + v = b3TransformPoint( transform1, two ); + v = b3InvTransformPoint( transform1, v ); + + ENSURE_SMALL( v.x - two.x, 8.0f * FLT_EPSILON ); + ENSURE_SMALL( v.y - two.y, 8.0f * FLT_EPSILON ); + + b3Transform relTransform = b3InvMulTransforms( transform1, transform2 ); + v = b3InvTransformPoint( transform1, b3TransformPoint( transform2, two ) ); + u = b3TransformPoint( relTransform, two ); + ENSURE_SMALL( u.x - v.x, 10.0f * FLT_EPSILON ); + ENSURE_SMALL( u.y - v.y, 10.0f * FLT_EPSILON ); + + { + axis = (b3Vec3){ 0.0f, 0.0f, 1.0f }; + b3Quat q1 = b3MakeQuatFromAxisAngle( axis, -0.5f * B3_PI ); + b3Quat q2 = b3ComputeQuatBetweenUnitVectors( (b3Vec3){ 1.0f, 0.0f, 0.0f }, (b3Vec3){ 0.0f, -1.0f, 0.0f } ); + + ENSURE_SMALL( q1.v.x - q2.v.x, FLT_EPSILON ); + ENSURE_SMALL( q1.v.y - q2.v.y, FLT_EPSILON ); + ENSURE_SMALL( q1.v.z - q2.v.z, FLT_EPSILON ); + ENSURE_SMALL( q1.s - q2.s, FLT_EPSILON ); + + b3Quat q3 = b3NormalizeQuat( (b3Quat){ { 1.0f, -2.0f, 3.0f }, 4.0f } ); + b3Quat q4 = b3InvMulQuat( q3, q1 ); + b3Quat q5 = b3MulQuat( q3, q4 ); + ENSURE_SMALL( q1.v.x - q5.v.x, FLT_EPSILON ); + ENSURE_SMALL( q1.v.y - q5.v.y, FLT_EPSILON ); + ENSURE_SMALL( q1.v.z - q5.v.z, FLT_EPSILON ); + ENSURE_SMALL( q1.s - q5.s, FLT_EPSILON ); + + b3Quat q6 = b3ComputeQuatBetweenUnitVectors( (b3Vec3){ 0.0f, 1.0f, 0.0f }, (b3Vec3){ 0.0f, -1.0f, 0.0f } ); + ENSURE_SMALL( q6.s, FLT_EPSILON ); + (void)q6; + } + + v = b3Normalize( (b3Vec3){ 0.2f, -0.5f, 3.0f } ); + for ( float z = -1.0f; z <= 1.0f; z += 0.02f ) + { + for ( float y = -1.0f; y <= 1.0f; y += 0.02f ) + { + for ( float x = -1.0f; x <= 1.0f; x += 0.02f ) + { + if ( x == 0.0f && y == 0.0f && z == 0.0f ) + { + continue; + } + + u = b3Normalize( (b3Vec3){ x, y, z } ); + + b3Quat r = b3ComputeQuatBetweenUnitVectors( v, u ); + ENSURE( b3IsValidQuat( r ) ); + + b3Vec3 w = b3RotateVector( r, v ); + + ENSURE_SMALL( b3Dot( r.v, b3Cross( u, w ) ) - b3ScalarTripleProduct( r.v, u, w ), FLT_EPSILON ); + + // The quaternion between vectors can have lots of round off error at large angles. + ENSURE_SMALL( w.x - u.x, 0.001f ); + ENSURE_SMALL( w.y - u.y, 0.001f ); + ENSURE_SMALL( w.z - u.z, 0.001f ); + + // Twist angle testing + float twist = r.s < 0.0f ? b3Atan2( -r.v.z, -r.s ) : b3Atan2( r.v.z, r.s ); + twist *= 2.0f; + ENSURE( -B3_PI <= twist && twist <= B3_PI ); + } + } + } + + { + // More twist angle testing + b3Quat q = { .v = { -0.0558656752f, -0.188799798f, 0.00689807534f }, .s = -0.980401039f }; + float twist = q.s < 0.0f ? b3Atan2( -q.v.z, -q.s ) : b3Atan2( q.v.z, q.s ); + twist *= 2.0f; + ENSURE( -B3_PI <= twist && twist <= B3_PI ); + } + + { + b3Matrix3 m = { { 3.0f, 1.0f, -1.0f }, { -1.0f, 3.0f, 1.0f }, { 1.0f, -1.0f, 3.0f } }; + b3Matrix3 invM = b3InvertMatrix( m ); + b3Matrix3 a = b3MulMM( m, invM ); + ENSURE_SMALL( a.cx.x - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( a.cx.y, FLT_EPSILON ); + ENSURE_SMALL( a.cx.z, FLT_EPSILON ); + ENSURE_SMALL( a.cy.x, FLT_EPSILON ); + ENSURE_SMALL( a.cy.y - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( a.cy.z, FLT_EPSILON ); + ENSURE_SMALL( a.cz.x, FLT_EPSILON ); + ENSURE_SMALL( a.cz.y, FLT_EPSILON ); + ENSURE_SMALL( a.cz.z - 1.0f, FLT_EPSILON ); + + v = (b3Vec3){ 1.0f, -2.0f, 3.0f }; + u = b3MulMV( invM, b3MulMV( m, v ) ); + ENSURE_SMALL( v.x - u.x, FLT_EPSILON ); + ENSURE_SMALL( v.y - u.y, FLT_EPSILON ); + ENSURE_SMALL( v.z - u.z, FLT_EPSILON ); + + b3Vec3 w = b3MulMV( invM, v ); + u = b3Solve3( m, v ); + ENSURE_SMALL( w.x - u.x, FLT_EPSILON ); + ENSURE_SMALL( w.y - u.y, FLT_EPSILON ); + ENSURE_SMALL( w.z - u.z, FLT_EPSILON ); + } + + { + b3Matrix2 m = { { 3.0f, 1.0f }, { -1.0f, 3.0f } }; + b3Matrix2 invM = b3Invert2( m ); + b3Matrix2 a = b3MulMM2( m, invM ); + ENSURE_SMALL( a.cx.x - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( a.cx.y, FLT_EPSILON ); + ENSURE_SMALL( a.cy.x, FLT_EPSILON ); + ENSURE_SMALL( a.cy.y - 1.0f, FLT_EPSILON ); + + b3Vec2 v2 = { 1.0f, -2.0f }; + b3Vec2 u2 = b3MulMV2( invM, b3MulMV2( m, v2 ) ); + ENSURE_SMALL( v2.x - u2.x, FLT_EPSILON ); + ENSURE_SMALL( v2.y - u2.y, FLT_EPSILON ); + + b3Vec2 w = b3MulMV2( invM, v2 ); + u2 = b3Solve2( m, v2 ); + ENSURE_SMALL( w.x - u2.x, FLT_EPSILON ); + ENSURE_SMALL( w.y - u2.y, FLT_EPSILON ); + + w = b3MulMV2( m, u2 ); + ENSURE_SMALL( w.x - v2.x, 10.0f * FLT_EPSILON ); + ENSURE_SMALL( w.y - v2.y, 10.0f * FLT_EPSILON ); + } + + for (int i = 0; i < 100; ++i) + { + float a = RandomFloat(); + double b = a; + float c = (float)b; + ENSURE( c == a ); + } + + b3Quat q1 = b3Quat_identity; + b3Quat q2 = b3MakeQuatFromAxisAngle(b3Vec3_axisZ, 0.5f * B3_PI ); + int n = 100; + for ( int i = 0; i <= n; ++i ) + { + float alpha = (float)i / (float)n; + b3Quat q = b3NLerp( q1, q2, alpha ); + float angle = b3GetTwistAngle( q ); + ENSURE_SMALL( alpha * 0.5f * B3_PI - angle, 1.0f * B3_DEG_TO_RAD ); + //printf( "angle = [%g %g %g]\n", alpha, alpha * 0.5f * B3_PI, angle ); + } + + { + b3Vec3 normal = { 0.504055440f, 0.621548057f, 0.599671543f }; + b3Vec3 perp = b3ArbitraryPerp( normal ); + ENSURE_SMALL( b3Dot( normal, perp ), 2.0f * FLT_EPSILON ); + } + + return 0; +} diff --git a/test/test_mover.c b/test/test_mover.c new file mode 100644 index 0000000..2844ae3 --- /dev/null +++ b/test/test_mover.c @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: 2025 Erin Catto +// SPDX-License-Identifier: MIT + +#include "test_macros.h" + +#include "box3d/collision.h" + +static int ParallelPlanes( void ) +{ + b3CollisionPlane planes[3] = { 0 }; + planes[0].plane.normal = (b3Vec3){ 0.0f, 0.0f, 1.0f }; + planes[0].plane.offset = 0.5f; + planes[0].pushLimit = FLT_MAX; + planes[1].plane.normal = (b3Vec3){ 0.0f, 0.0f, 1.0f }; + planes[1].plane.offset = 1.0f; + planes[1].pushLimit = FLT_MAX; + // planes[2].plane.normal = b3Normalize((b3Vec3){ 0.2f, 0.0f, 0.9f }); + // planes[2].plane.offset = 0.25f; + // planes[2].pushLimit = FLT_MAX; + + b3Vec3 target = { 0.0f, 0.0f, 0.0f }; + b3PlaneSolverResult result = b3SolvePlanes( target, planes, 2 ); + + ENSURE( result.iterationCount == 2 ); + ENSURE_SMALL( result.delta.z - 1.0f, 0.0055f ); + + return 0; +} + +static int GamePlanes( void ) +{ + // This scenario takes many iterations because the target is deep into the plane. + b3CollisionPlane planes[3] = { 0 }; + planes[0].plane.normal = (b3Vec3){ 0.0f, -0.23941046f, 0.970918416f }; + planes[0].plane.offset = 0.390724182f; + planes[0].pushLimit = FLT_MAX; + planes[1].plane.normal = (b3Vec3){ 0.0f, 0.0f, 1.0f }; + planes[1].plane.offset = 1.49998093f; + planes[1].pushLimit = FLT_MAX; + + b3Vec3 target = { -2.5390625f, 0.0f, -73.6880798f }; + + planes[0].plane.offset -= b3Dot( planes[0].plane.normal, target ); + planes[1].plane.offset -= b3Dot( planes[1].plane.normal, target ); + target = b3Vec3_zero; + + b3PlaneSolverResult result = b3SolvePlanes( target, planes, 2 ); + + ENSURE( result.iterationCount == 20 ); + + return 0; +} + +int MoverTest( void ) +{ + RUN_SUBTEST( GamePlanes ); + RUN_SUBTEST( ParallelPlanes ); + + return 0; +} diff --git a/test/test_shape.c b/test/test_shape.c new file mode 100644 index 0000000..436e5b3 --- /dev/null +++ b/test/test_shape.c @@ -0,0 +1,322 @@ +// SPDX-FileCopyrightText: 2023 Erin Catto +// SPDX-License-Identifier: MIT + +#include "test_macros.h" + +#include "box3d/collision.h" +#include "box3d/math_functions.h" + +#include + +static b3Capsule capsule = { { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, 1.0f }; +static b3Sphere sphere = { { 1.0f, 0.0f, 0.0f }, 1.0f }; +static b3BoxHull box = { 0 }; + +#define N 4 + +static int ShapeMassTest( void ) +{ + // Sphere + { + b3MassData md = b3ComputeSphereMass( &sphere, 1.0f ); + float mass = 4.0f / 3.0f * B3_PI; + ENSURE_SMALL( md.mass - mass, FLT_EPSILON ); + ENSURE( md.center.x == 1.0f && md.center.y == 0.0f ); + float inertia = 2.0f / 5.0f * mass; + float offsetInertia = inertia + mass; + ENSURE_SMALL( md.inertia.cx.x - inertia, FLT_EPSILON ); + ENSURE_SMALL( md.inertia.cy.y - offsetInertia, FLT_EPSILON ); + ENSURE_SMALL( md.inertia.cz.z - offsetInertia, FLT_EPSILON ); + } + + // Analytic box hull + { + b3MassData md = b3ComputeHullMass( &box.base, 1.0f ); + float mass = 2.0f * 2.0f * 2.0f; + ENSURE_SMALL( md.mass - mass, FLT_EPSILON ); + ENSURE_SMALL( md.center.x, FLT_EPSILON ); + ENSURE_SMALL( md.center.y, FLT_EPSILON ); + ENSURE_SMALL( md.center.z, FLT_EPSILON ); + float inertia = ( 1.0f / 12.0f ) * mass * ( 2.0f * 2.0f + 2.0f * 2.0f ); + ENSURE_SMALL( md.inertia.cx.x - inertia, 2.0f * FLT_EPSILON ); + ENSURE_SMALL( md.inertia.cy.y - inertia, 2.0f * FLT_EPSILON ); + ENSURE_SMALL( md.inertia.cz.z - inertia, 2.0f * FLT_EPSILON ); + } + + // Translated box + { + b3Vec3 offset = { 0.4f, -0.7f, 0.1f }; + b3Transform transform = { + .p = offset, + .q = b3Quat_identity, + }; + b3Vec3 h = { 0.25f, 0.5f, 0.3f }; + b3BoxHull b1 = b3MakeBoxHull( h.x, h.y, h.z ); + b3BoxHull b2 = b3MakeTransformedBoxHull( h.x, h.y, h.z, transform ); + + b3MassData m1 = b3ComputeHullMass( &b1.base, 1.0f ); + b3MassData m2 = b3ComputeHullMass( &b2.base, 1.0f ); + + ENSURE_SMALL( m1.mass - m2.mass, FLT_EPSILON ); + + b3Matrix3 d = b3SubMM( b1.base.centralInertia, b2.base.centralInertia ); + ENSURE_SMALL( d.cx.x, FLT_EPSILON ); + ENSURE_SMALL( d.cx.y, FLT_EPSILON ); + ENSURE_SMALL( d.cx.z, FLT_EPSILON ); + ENSURE_SMALL( d.cy.x, FLT_EPSILON ); + ENSURE_SMALL( d.cy.y, FLT_EPSILON ); + ENSURE_SMALL( d.cy.z, FLT_EPSILON ); + ENSURE_SMALL( d.cz.x, FLT_EPSILON ); + ENSURE_SMALL( d.cz.y, FLT_EPSILON ); + ENSURE_SMALL( d.cz.z, FLT_EPSILON ); + + ENSURE_SMALL( m2.center.x - offset.x, FLT_EPSILON ); + ENSURE_SMALL( m2.center.y - offset.y, FLT_EPSILON ); + ENSURE_SMALL( m2.center.z - offset.z, FLT_EPSILON ); + } + + // Rotated box + { + b3Vec3 h1 = { 0.25f, 0.5f, 0.3f }; + b3Vec3 h2 = { 0.25f, 0.3f, 0.5f }; + b3Quat q = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisY, b3Vec3_axisZ ); + b3Transform transform = { + .p = b3Vec3_zero, + .q = q, + }; + b3BoxHull b1 = b3MakeTransformedBoxHull( h1.x, h1.y, h1.z, transform ); + b3BoxHull b2 = b3MakeBoxHull( h2.x, h2.y, h2.z ); + + b3MassData m1 = b3ComputeHullMass( &b1.base, 1.0f ); + b3MassData m2 = b3ComputeHullMass( &b2.base, 1.0f ); + + ENSURE_SMALL( m1.mass - m2.mass, FLT_EPSILON ); + + b3Matrix3 d = b3SubMM( b1.base.centralInertia, b2.base.centralInertia ); + ENSURE_SMALL( d.cx.x, FLT_EPSILON ); + ENSURE_SMALL( d.cx.y, FLT_EPSILON ); + ENSURE_SMALL( d.cx.z, FLT_EPSILON ); + ENSURE_SMALL( d.cy.x, FLT_EPSILON ); + ENSURE_SMALL( d.cy.y, FLT_EPSILON ); + ENSURE_SMALL( d.cy.z, FLT_EPSILON ); + ENSURE_SMALL( d.cz.x, FLT_EPSILON ); + ENSURE_SMALL( d.cz.y, FLT_EPSILON ); + ENSURE_SMALL( d.cz.z, FLT_EPSILON ); + + ENSURE_SMALL( m1.center.x - m2.center.x, FLT_EPSILON ); + ENSURE_SMALL( m1.center.y - m2.center.y, FLT_EPSILON ); + ENSURE_SMALL( m1.center.z - m2.center.z, FLT_EPSILON ); + } + + // Transformed box + { + b3Vec3 offset = { 0.4f, -0.7f, 0.1f }; + b3Vec3 h1 = { 0.25f, 0.5f, 0.3f }; + b3Vec3 h2 = { 0.25f, 0.3f, 0.5f }; + b3Quat q = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisY, b3Vec3_axisZ ); + b3Transform transform = { + .p = offset, + .q = q, + }; + b3BoxHull b1 = b3MakeTransformedBoxHull( h1.x, h1.y, h1.z, transform ); + b3BoxHull b2 = b3MakeBoxHull( h2.x, h2.y, h2.z ); + + b3MassData m1 = b3ComputeHullMass( &b1.base, 1.0f ); + b3MassData m2 = b3ComputeHullMass( &b2.base, 1.0f ); + + ENSURE_SMALL( m1.mass - m2.mass, FLT_EPSILON ); + + b3Matrix3 d = b3SubMM( b1.base.centralInertia, b2.base.centralInertia ); + ENSURE_SMALL( d.cx.x, FLT_EPSILON ); + ENSURE_SMALL( d.cx.y, FLT_EPSILON ); + ENSURE_SMALL( d.cx.z, FLT_EPSILON ); + ENSURE_SMALL( d.cy.x, FLT_EPSILON ); + ENSURE_SMALL( d.cy.y, FLT_EPSILON ); + ENSURE_SMALL( d.cy.z, FLT_EPSILON ); + ENSURE_SMALL( d.cz.x, FLT_EPSILON ); + ENSURE_SMALL( d.cz.y, FLT_EPSILON ); + ENSURE_SMALL( d.cz.z, FLT_EPSILON ); + + ENSURE_SMALL( m1.center.x - offset.x, FLT_EPSILON ); + ENSURE_SMALL( m1.center.y - offset.y, FLT_EPSILON ); + ENSURE_SMALL( m1.center.z - offset.z, FLT_EPSILON ); + } + + // Capsule + { + float radius = capsule.radius; + float length = b3Distance( capsule.center1, capsule.center2 ); + + // Capsule along x-axis + b3MassData md = b3ComputeCapsuleMass( &capsule, 1.0f ); + + // Box that fully contains capsule. Upper bound on capsule mass. + b3BoxHull r = b3MakeBoxHull( radius + 0.5f * length, radius, radius ); + b3MassData mdUpper = b3ComputeHullMass( &r.base, 1.0f ); + + // Approximate capsule using convex hull. This should be a lower bound on the + // capsule mass. + b3Vec3 points[2 * N * N]; + float d = B3_PI / ( N - 1.0f ); + float angle1 = -0.5f * B3_PI; + int index = 0; + for ( int i = 0; i < N; ++i ) + { + float s1 = sinf( angle1 ); + float c1 = cosf( angle1 ); + float angle2 = -0.5f * B3_PI; + for ( int j = 0; j < N; ++j ) + { + points[index].x = 1.0f + radius * c1; + points[index].y = radius * s1 * cosf( angle2 ); + points[index].z = radius * s1 * sinf( angle2 ); + angle2 += d; + index += 1; + } + + angle1 += d; + } + + angle1 = 0.5f * B3_PI; + for ( int i = 0; i < N; ++i ) + { + float s1 = sinf( angle1 ); + float c1 = cosf( angle1 ); + float angle2 = -0.5f * B3_PI; + for ( int j = 0; j < N; ++j ) + { + points[index].x = -1.0f + radius * c1; + points[index].y = radius * s1 * cosf( angle2 ); + points[index].z = radius * s1 * sinf( angle2 ); + angle2 += d; + index += 1; + } + + angle1 += d; + } + + ENSURE( index == 2 * N * N ); + + b3Hull* hull = b3CreateHull( points, 2 * N * N, 2 * N * N ); + b3MassData mdLower = b3ComputeHullMass( hull, 1.0f ); + + ENSURE( mdLower.mass < md.mass && md.mass < mdUpper.mass ); + ENSURE( mdLower.inertia.cx.x < md.inertia.cx.x && md.inertia.cx.x < mdUpper.inertia.cx.x ); + ENSURE( mdLower.inertia.cy.y < md.inertia.cy.y && md.inertia.cy.y < mdUpper.inertia.cy.y ); + ENSURE( mdLower.inertia.cz.z < md.inertia.cz.z && md.inertia.cz.z < mdUpper.inertia.cz.z ); + + b3DestroyHull( hull ); + } + + return 0; +} + +static int ShapeAABBTest( void ) +{ + { + b3AABB b = b3ComputeSphereAABB( &sphere, b3Transform_identity ); + ENSURE_SMALL( b.lowerBound.x, FLT_EPSILON ); + ENSURE_SMALL( b.lowerBound.y + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( b.lowerBound.z + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( b.upperBound.x - 2.0f, FLT_EPSILON ); + ENSURE_SMALL( b.upperBound.y - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( b.upperBound.z - 1.0f, FLT_EPSILON ); + } + + { + b3AABB b = b3ComputeCapsuleAABB( &capsule, b3Transform_identity ); + ENSURE_SMALL( b.lowerBound.x + 2.0f, FLT_EPSILON ); + ENSURE_SMALL( b.lowerBound.y + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( b.lowerBound.z + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( b.upperBound.x - 2.0f, FLT_EPSILON ); + ENSURE_SMALL( b.upperBound.y - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( b.upperBound.z - 1.0f, FLT_EPSILON ); + } + { + b3AABB b = b3ComputeHullAABB( &box.base, b3Transform_identity ); + ENSURE_SMALL( b.lowerBound.x + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( b.lowerBound.y + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( b.lowerBound.z + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( b.upperBound.x - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( b.upperBound.y - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( b.upperBound.z - 1.0f, FLT_EPSILON ); + } + + return 0; +} + +#if 0 +static int PointInShapeTest( void ) +{ + b3Vec2 p1 = { 0.5f, 0.5f }; + b3Vec2 p2 = { 4.0f, -4.0f }; + + { + bool hit; + hit = b3PointInSphere( p1, &sphere ); + ENSURE( hit == true ); + hit = b3PointInSphere( p2, &sphere ); + ENSURE( hit == false ); + } + + { + bool hit; + hit = b3PointInPolygon( p1, &box ); + ENSURE( hit == true ); + hit = b3PointInPolygon( p2, &box ); + ENSURE( hit == false ); + } + + return 0; +} +#endif + +static int RayCastShapeTest( void ) +{ + b3RayCastInput input = { + .origin = { -4.0f, 0.0f, 0.0f }, + .translation = { 8.0f, 0.0f, 0.0f }, + .maxFraction = 1.0f, + }; + + { + b3CastOutput output = b3RayCastSphere( &sphere, &input ); + ENSURE( output.hit ); + ENSURE_SMALL( output.normal.x + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( output.normal.y, FLT_EPSILON ); + ENSURE_SMALL( output.normal.z, FLT_EPSILON ); + ENSURE_SMALL( output.fraction - 0.5f, FLT_EPSILON ); + } + + { + b3CastOutput output = b3RayCastCapsule( &capsule, &input ); + ENSURE( output.hit ); + ENSURE_SMALL( output.normal.x + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( output.normal.y, FLT_EPSILON ); + ENSURE_SMALL( output.normal.z, FLT_EPSILON ); + ENSURE_SMALL( output.fraction - 1.0f / 4.0f, FLT_EPSILON ); + } + + { + b3CastOutput output = b3RayCastHull( &box.base, &input ); + ENSURE( output.hit ); + ENSURE_SMALL( output.normal.x + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( output.normal.y, FLT_EPSILON ); + ENSURE_SMALL( output.normal.z, FLT_EPSILON ); + ENSURE_SMALL( output.fraction - 3.0f / 8.0f, FLT_EPSILON ); + } + + return 0; +} + +int ShapeTest( void ) +{ + box = b3MakeBoxHull( 1.0f, 1.0f, 1.0f ); + + RUN_SUBTEST( ShapeMassTest ); + RUN_SUBTEST( ShapeAABBTest ); + // RUN_SUBTEST( PointInShapeTest ); + RUN_SUBTEST( RayCastShapeTest ); + + return 0; +} diff --git a/test/test_table.c b/test/test_table.c new file mode 100644 index 0000000..3cfe788 --- /dev/null +++ b/test/test_table.c @@ -0,0 +1,113 @@ +// SPDX-FileCopyrightText: 2023 Erin Catto +// SPDX-License-Identifier: MIT + +#include "ctz.h" +#include "table.h" +#include "test_macros.h" + +#include "box2d/base.h" + +#include + +#define SET_SPAN 317 +#define ITEM_COUNT ( ( SET_SPAN * SET_SPAN - SET_SPAN ) / 2 ) + +int TableTest( void ) +{ + int power = b2BoundingPowerOf2( 3008 ); + ENSURE( power == 12 ); + + int nextPowerOf2 = b2RoundUpPowerOf2( 3008 ); + ENSURE( nextPowerOf2 == ( 1 << power ) ); + + const int32_t N = SET_SPAN; + const uint32_t itemCount = ITEM_COUNT; + bool removed[ITEM_COUNT] = { 0 }; + + for ( int32_t iter = 0; iter < 1; ++iter ) + { + b2HashSet set = b2CreateSet( 16 ); + + // Fill set + for ( int32_t i = 0; i < N; ++i ) + { + for ( int32_t j = i + 1; j < N; ++j ) + { + uint64_t key = B2_SHAPE_PAIR_KEY( i, j ); + b2AddKey( &set, key ); + } + } + + ENSURE( set.count == itemCount ); + + // Remove a portion of the set + int32_t k = 0; + uint32_t removeCount = 0; + for ( int32_t i = 0; i < N; ++i ) + { + for ( int32_t j = i + 1; j < N; ++j ) + { + if ( j == i + 1 ) + { + uint64_t key = B2_SHAPE_PAIR_KEY( i, j ); + b2RemoveKey( &set, key ); + removed[k++] = true; + removeCount += 1; + } + else + { + removed[k++] = false; + } + } + } + + ENSURE( set.count == ( itemCount - removeCount ) ); + +#ifndef NDEBUG + extern _Atomic int g_probeCount; + g_probeCount = 0; +#endif + + // Test key search + // ~5ns per search on an AMD 7950x + b2Timer timer = b2CreateTimer(); + + k = 0; + for ( int32_t i = 0; i < N; ++i ) + { + for ( int32_t j = i + 1; j < N; ++j ) + { + uint64_t key = B2_SHAPE_PAIR_KEY( j, i ); + ENSURE( b2ContainsKey( &set, key ) || removed[k] ); + k += 1; + } + } + + // uint64_t ticks = b2GetTicks(&timer); + // printf("set ticks = %llu\n", ticks); + + float ms = b2GetMilliseconds( &timer ); + printf( "set: count = %d, b2ContainsKey = %.5f ms, ave = %.5f us\n", itemCount, ms, 1000.0f * ms / itemCount ); + +#if !NDEBUG + float aveProbeCount = (float)g_probeCount / (float)itemCount; + printf( "item count = %d, probe count = %d, ave probe count %.2f\n", itemCount, g_probeCount, aveProbeCount ); +#endif + + // Remove all keys from set + for ( int32_t i = 0; i < N; ++i ) + { + for ( int32_t j = i + 1; j < N; ++j ) + { + uint64_t key = B2_SHAPE_PAIR_KEY( i, j ); + b2RemoveKey( &set, key ); + } + } + + ENSURE( set.count == 0 ); + + b2DestroySet( &set ); + } + + return 0; +} diff --git a/test/test_world.c b/test/test_world.c new file mode 100644 index 0000000..b82ef3d --- /dev/null +++ b/test/test_world.c @@ -0,0 +1,720 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#include "benchmarks.h" +#include "stability.h" +#include "test_macros.h" + +#include "box3d/box3d.h" +#include "box3d/collision.h" +#include "box3d/constants.h" +#include "box3d/math_functions.h" + +#include + +// This is a simple example of building and running a simulation +// using Box3D. Here we create a large ground box and a small dynamic +// box. +// There are no graphics for this example. Box3D 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. + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.gravity = (b3Vec3){ 0.0f, -10.0f, 0.0f }; + + b3WorldId worldId = b3CreateWorld( &worldDef ); + ENSURE( b3World_IsValid( worldId ) ); + + // Define the ground body. + b3BodyDef groundBodyDef = b3DefaultBodyDef(); + groundBodyDef.position = (b3Vec3){ 0.0f, -10.0f, 0.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. + b3BodyId groundId = b3CreateBody( worldId, &groundBodyDef ); + ENSURE( b3Body_IsValid( groundId ) ); + + // Define the ground box shape. The extents are the half-widths of the box. + b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 10.0f, 50.0f ); + + // Add the box shape to the ground body. + b3ShapeDef groundShapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &groundShapeDef, &groundBox.base ); + + // Define the dynamic body. We set its position and call the body factory. + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Vec3){ 0.0f, 4.0f, 0.0f }; + + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + + // Define another box shape for our dynamic body. + b3BoxHull dynamicBox = b3MakeCubeHull( 1.0f ); + + // Define the dynamic body shape + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + // Set the box density to be non-zero, so it will be dynamic. + shapeDef.density = 1.0f; + + // Override the default friction. + shapeDef.baseMaterial.friction = 0.3f; + + // Add the shape to the body. + b3CreateHullShape( bodyId, &shapeDef, &dynamicBox.base ); + + // 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; + + b3Vec3 position = b3Body_GetPosition( bodyId ); + b3Quat rotation = b3Body_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. + b3World_Step( worldId, timeStep, subStepCount ); + + // Now print the position and angle of the body. + position = b3Body_GetPosition( bodyId ); + rotation = b3Body_GetRotation( bodyId ); + + // printf("%4.2f %4.2f %4.2f\n", position.x, position.y, b3Rot_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. + b3DestroyWorld( worldId ); + + ENSURE_SMALL( position.y - 1.00f, 0.01f ); + ENSURE_SMALL( rotation.v.x, 0.01f ); + ENSURE_SMALL( rotation.v.z, 0.01f ); + + return 0; +} + +int EmptyWorld( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + ENSURE( b3World_IsValid( worldId ) == true ); + + float timeStep = 1.0f / 60.0f; + int subStepCount = 1; + + for ( int i = 0; i < 60; ++i ) + { + b3World_Step( worldId, timeStep, subStepCount ); + } + + b3DestroyWorld( worldId ); + + ENSURE( b3World_IsValid( worldId ) == false ); + + return 0; +} + +#define BODY_COUNT 10 +int DestroyAllBodiesWorld( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + ENSURE( b3World_IsValid( worldId ) == true ); + + int count = 0; + bool creating = true; + + b3BodyId bodyIds[BODY_COUNT]; + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + b3BoxHull cube = b3MakeCubeHull( 0.5f ); + + for ( int i = 0; i < 2 * BODY_COUNT + 10; ++i ) + { + if ( creating ) + { + if ( count < BODY_COUNT ) + { + bodyIds[count] = b3CreateBody( worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( bodyIds[count], &shapeDef, &cube.base ); + count += 1; + } + else + { + creating = false; + } + } + else if ( count > 0 ) + { + b3DestroyBody( bodyIds[count - 1] ); + bodyIds[count - 1] = b3_nullBodyId; + count -= 1; + } + + b3World_Step( worldId, 1.0f / 60.0f, 3 ); + } + + b3Counters counters = b3World_GetCounters( worldId ); + ENSURE( counters.bodyCount == 0 ); + + b3DestroyWorld( worldId ); + + ENSURE( b3World_IsValid( worldId ) == false ); + + return 0; +} + +static int TestIsValid( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + ENSURE( b3World_IsValid( worldId ) ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + + b3BodyId bodyId1 = b3CreateBody( worldId, &bodyDef ); + ENSURE( b3Body_IsValid( bodyId1 ) == true ); + + b3BodyId bodyId2 = b3CreateBody( worldId, &bodyDef ); + ENSURE( b3Body_IsValid( bodyId2 ) == true ); + + b3DestroyBody( bodyId1 ); + ENSURE( b3Body_IsValid( bodyId1 ) == false ); + + b3DestroyBody( bodyId2 ); + ENSURE( b3Body_IsValid( bodyId2 ) == false ); + + b3DestroyWorld( worldId ); + + ENSURE( b3World_IsValid( worldId ) == false ); + ENSURE( b3Body_IsValid( bodyId2 ) == false ); + ENSURE( b3Body_IsValid( bodyId1 ) == false ); + + return 0; +} + +#define WORLD_COUNT ( B3_MAX_WORLDS / 2 ) + +int TestWorldRecycle( void ) +{ + _Static_assert( WORLD_COUNT > 0, "world count" ); + + int count = 100; + + b3WorldId worldIds[WORLD_COUNT]; + + for ( int i = 0; i < count; ++i ) + { + b3WorldDef worldDef = b3DefaultWorldDef(); + for ( int j = 0; j < WORLD_COUNT; ++j ) + { + worldIds[j] = b3CreateWorld( &worldDef ); + ENSURE( b3World_IsValid( worldIds[j] ) == true ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3CreateBody( 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 ) + { + b3World_Step( worldIds[j], timeStep, subStepCount ); + } + } + + for ( int j = WORLD_COUNT - 1; j >= 0; --j ) + { + b3DestroyWorld( worldIds[j] ); + ENSURE( b3World_IsValid( worldIds[j] ) == false ); + worldIds[j] = b3_nullWorldId; + } + } + + return 0; +} + +static bool CustomFilter( b3ShapeId shapeIdA, b3ShapeId shapeIdB, void* context ) +{ + (void)shapeIdA; + (void)shapeIdB; + ENSURE( context == NULL ); + return true; +} + +static bool PreSolveStatic( b3ShapeId shapeIdA, b3ShapeId shapeIdB, b3Vec3 point, b3Vec3 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 ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + + b3WorldId worldId = b3CreateWorld( &worldDef ); + ENSURE( b3World_IsValid( worldId ) ); + + b3World_EnableSleeping( worldId, true ); + b3World_EnableSleeping( worldId, false ); + bool flag = b3World_IsSleepingEnabled( worldId ); + ENSURE( flag == false ); + + b3World_EnableContinuous( worldId, false ); + b3World_EnableContinuous( worldId, true ); + flag = b3World_IsContinuousEnabled( worldId ); + ENSURE( flag == true ); + + b3World_SetRestitutionThreshold( worldId, 0.0f ); + b3World_SetRestitutionThreshold( worldId, 2.0f ); + float value = b3World_GetRestitutionThreshold( worldId ); + ENSURE( value == 2.0f ); + + b3World_SetHitEventThreshold( worldId, 0.0f ); + b3World_SetHitEventThreshold( worldId, 100.0f ); + value = b3World_GetHitEventThreshold( worldId ); + ENSURE( value == 100.0f ); + + b3World_SetCustomFilterCallback( worldId, CustomFilter, NULL ); + b3World_SetPreSolveCallback( worldId, PreSolveStatic, NULL ); + + b3Vec3 g = { 1.0f, 2.0f }; + b3World_SetGravity( worldId, g ); + b3Vec3 v = b3World_GetGravity( worldId ); + ENSURE( v.x == g.x ); + ENSURE( v.y == g.y ); + + b3ExplosionDef explosionDef = b3DefaultExplosionDef(); + b3World_Explode( worldId, &explosionDef ); + + b3World_SetContactTuning( worldId, 10.0f, 2.0f, 4.0f ); + + b3World_SetMaximumLinearSpeed( worldId, 10.0f ); + value = b3World_GetMaximumLinearSpeed( worldId ); + ENSURE( value == 10.0f ); + + b3World_EnableWarmStarting( worldId, true ); + flag = b3World_IsWarmStartingEnabled( worldId ); + ENSURE( flag == true ); + + int count = b3World_GetAwakeBodyCount( worldId ); + ENSURE( count == 0 ); + + b3World_SetUserData( worldId, &value ); + void* userData = b3World_GetUserData( worldId ); + ENSURE( userData == &value ); + + b3World_Step( worldId, 1.0f, 1 ); + + b3DestroyWorld( worldId ); + + return 0; +} + +static int TestSensor( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + // Wall from x = 1 to x = 2 + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_staticBody; + bodyDef.position = (b3Vec3){ 1.5f, 11.0f, 0.0f }; + b3BodyId wallId = b3CreateBody( worldId, &bodyDef ); + b3BoxHull box = b3MakeBoxHull( 0.5f, 10.0f, 1.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.enableSensorEvents = true; + b3CreateHullShape( wallId, &shapeDef, &box.base ); + + // Bullet fired towards the wall + bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.isBullet = true; + bodyDef.gravityScale = 0.0f; + bodyDef.position = (b3Vec3){ 7.39814f, 4.0f, 0.0f }; + bodyDef.linearVelocity = (b3Vec3){ -20.0f, 0.0f, 0.0f }; + b3BodyId bulletId = b3CreateBody( worldId, &bodyDef ); + shapeDef = b3DefaultShapeDef(); + shapeDef.isSensor = true; + shapeDef.enableSensorEvents = true; + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.1f }; + b3CreateSphereShape( bulletId, &shapeDef, &sphere ); + + int beginCount = 0; + int endCount = 0; + + while ( true ) + { + float timeStep = 1.0f / 60.0f; + int subStepCount = 4; + b3World_Step( worldId, timeStep, subStepCount ); + + b3Vec3 bulletPos = b3Body_GetPosition( bulletId ); + // printf( "Bullet pos: %g %g\n", bulletPos.x, bulletPos.y ); + + b3SensorEvents events = b3World_GetSensorEvents( worldId ); + + if ( events.beginCount > 0 ) + { + beginCount += 1; + } + + if ( events.endCount > 0 ) + { + endCount += 1; + } + + if ( bulletPos.x < -1.0f ) + { + break; + } + } + + b3DestroyWorld( worldId ); + + ENSURE( beginCount == 1 ); + ENSURE( endCount == 1 ); + + return 0; +} + +static int TestContactEvents( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + // Static ground + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_staticBody; + bodyDef.position = (b3Vec3){ 0.0f, -0.5f, 0.0f }; + b3BodyId groundId = b3CreateBody( worldId, &bodyDef ); + b3BoxHull groundBox = b3MakeBoxHull( 10.0f, 0.5f, 10.0f ); + b3ShapeDef groundShapeDef = b3DefaultShapeDef(); + b3ShapeId groundShapeId = b3CreateHullShape( groundId, &groundShapeDef, &groundBox.base ); + + // Dynamic sphere dropped onto the ground; restitution causes it to bounce so we get end events + bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Vec3){ 0.0f, 5.0f, 0.0f }; + b3BodyId sphereBodyId = b3CreateBody( worldId, &bodyDef ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 1.0f; + shapeDef.enableContactEvents = true; + shapeDef.baseMaterial.restitution = 0.6f; + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f }; + b3ShapeId sphereShapeId = b3CreateSphereShape( sphereBodyId, &shapeDef, &sphere ); + + int beginCount = 0; + int endCount = 0; + bool idsChecked = false; + + for ( int i = 0; i < 120; ++i ) + { + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + + b3ContactEvents events = b3World_GetContactEvents( worldId ); + + if ( events.beginCount > 0 && idsChecked == false ) + { + b3ContactBeginTouchEvent be = events.beginEvents[0]; + bool aIsSphere = B3_ID_EQUALS( be.shapeIdA, sphereShapeId ); + bool bIsSphere = B3_ID_EQUALS( be.shapeIdB, sphereShapeId ); + bool aIsGround = B3_ID_EQUALS( be.shapeIdA, groundShapeId ); + bool bIsGround = B3_ID_EQUALS( be.shapeIdB, groundShapeId ); + ENSURE( ( aIsSphere && bIsGround ) || ( aIsGround && bIsSphere ) ); + ENSURE( b3Contact_IsValid( be.contactId ) ); + idsChecked = true; + } + + beginCount += events.beginCount; + endCount += events.endCount; + } + + b3DestroyWorld( worldId ); + + ENSURE( idsChecked ); + ENSURE( beginCount >= 1 ); + ENSURE( endCount >= 1 ); + + return 0; +} + +static int TestHitEvents( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.hitEventThreshold = 1.0f; + b3WorldId worldId = b3CreateWorld( &worldDef ); + + // Static ground + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_staticBody; + bodyDef.position = (b3Vec3){ 0.0f, -0.5f, 0.0f }; + b3BodyId groundId = b3CreateBody( worldId, &bodyDef ); + b3BoxHull groundBox = b3MakeBoxHull( 10.0f, 0.5f, 10.0f ); + b3ShapeDef groundShapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &groundShapeDef, &groundBox.base ); + + // Sphere driven into the ground fast enough to clear the hit threshold + bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.gravityScale = 0.0f; + bodyDef.position = (b3Vec3){ 0.0f, 2.0f, 0.0f }; + bodyDef.linearVelocity = (b3Vec3){ 0.0f, -30.0f, 0.0f }; + b3BodyId sphereBodyId = b3CreateBody( worldId, &bodyDef ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 1.0f; + shapeDef.enableHitEvents = true; + shapeDef.baseMaterial.userMaterialId = 7; + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f }; + b3CreateSphereShape( sphereBodyId, &shapeDef, &sphere ); + + int hitCount = 0; + float capturedSpeed = 0.0f; + uint64_t capturedMaterialA = 0; + uint64_t capturedMaterialB = 0; + b3Vec3 capturedNormal = { 0.0f, 0.0f, 0.0f }; + + for ( int i = 0; i < 30; ++i ) + { + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + + b3ContactEvents events = b3World_GetContactEvents( worldId ); + if ( events.hitCount > 0 && hitCount == 0 ) + { + b3ContactHitEvent hit = events.hitEvents[0]; + capturedSpeed = hit.approachSpeed; + capturedNormal = hit.normal; + capturedMaterialA = hit.userMaterialIdA; + capturedMaterialB = hit.userMaterialIdB; + } + + hitCount += events.hitCount; + } + + b3DestroyWorld( worldId ); + + ENSURE( hitCount >= 1 ); + ENSURE( capturedSpeed > 1.0f ); + // Head-on vertical impact: normal lies along Y + ENSURE_SMALL( capturedNormal.x, 0.01f ); + ENSURE_SMALL( capturedNormal.z, 0.01f ); + // One side of the contact carries the sphere's user material + ENSURE( capturedMaterialA == 7 || capturedMaterialB == 7 ); + + return 0; +} + +// Hit-event material lookup must respect the compound child that participated in the +// contact. Two children with distinct userMaterialIds at separated positions, dropped +// sphere strikes one specifically. Without the fix, both children would report +// materials[0] and the strike on hull 1 would be misattributed. +static int TestCompoundHitEvents( void ) +{ + const uint64_t kHullMaterialA = 11; + const uint64_t kHullMaterialB = 22; + const uint64_t kSphereMaterial = 99; + const float kHullCenterX = 3.0f; + + for ( int side = 0; side < 2; ++side ) + { + uint64_t expectedHullMaterial = ( side == 0 ) ? kHullMaterialA : kHullMaterialB; + float spawnX = ( side == 0 ) ? -kHullCenterX : kHullCenterX; + + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.hitEventThreshold = 1.0f; + b3WorldId worldId = b3CreateWorld( &worldDef ); + + // Build a compound with two hulls at opposite x positions, distinct userMaterialIds + b3BoxHull boxA = b3MakeBoxHull( 1.0f, 1.0f, 1.0f ); + b3BoxHull boxB = b3MakeBoxHull( 1.0f, 1.0f, 1.0f ); + + b3SurfaceMaterial matA = b3DefaultSurfaceMaterial(); + matA.userMaterialId = kHullMaterialA; + + b3SurfaceMaterial matB = b3DefaultSurfaceMaterial(); + matB.userMaterialId = kHullMaterialB; + + b3CompoundHullDef hulls[2]; + hulls[0].hull = &boxA.base; + hulls[0].transform = (b3Transform){ { -kHullCenterX, 0.0f, 0.0f }, b3Quat_identity }; + hulls[0].material = matA; + hulls[1].hull = &boxB.base; + hulls[1].transform = (b3Transform){ { kHullCenterX, 0.0f, 0.0f }, b3Quat_identity }; + hulls[1].material = matB; + + b3CompoundDef compoundDef = { 0 }; + compoundDef.hulls = hulls; + compoundDef.hullCount = 2; + b3Compound* compound = b3CreateCompound( &compoundDef ); + ENSURE( compound != NULL ); + + // Static body holds the compound + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_staticBody; + b3BodyId compoundBodyId = b3CreateBody( worldId, &bodyDef ); + b3ShapeDef compoundShapeDef = b3DefaultShapeDef(); + b3CreateCompoundShape( compoundBodyId, &compoundShapeDef, compound ); + + // Sphere driven straight down onto the chosen child + bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.gravityScale = 0.0f; + bodyDef.position = (b3Vec3){ spawnX, 3.0f, 0.0f }; + bodyDef.linearVelocity = (b3Vec3){ 0.0f, -30.0f, 0.0f }; + b3BodyId sphereBodyId = b3CreateBody( worldId, &bodyDef ); + b3ShapeDef sphereShapeDef = b3DefaultShapeDef(); + sphereShapeDef.density = 1.0f; + sphereShapeDef.enableHitEvents = true; + sphereShapeDef.baseMaterial.userMaterialId = kSphereMaterial; + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f }; + b3CreateSphereShape( sphereBodyId, &sphereShapeDef, &sphere ); + + int hitCount = 0; + uint64_t capturedMaterialA = 0; + uint64_t capturedMaterialB = 0; + + for ( int i = 0; i < 30; ++i ) + { + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + + b3ContactEvents events = b3World_GetContactEvents( worldId ); + if ( events.hitCount > 0 && hitCount == 0 ) + { + b3ContactHitEvent hit = events.hitEvents[0]; + capturedMaterialA = hit.userMaterialIdA; + capturedMaterialB = hit.userMaterialIdB; + } + hitCount += events.hitCount; + } + + b3DestroyWorld( worldId ); + b3DestroyCompound( compound ); + + ENSURE( hitCount >= 1 ); + // Sphere material on one side + ENSURE( capturedMaterialA == kSphereMaterial || capturedMaterialB == kSphereMaterial ); + // Struck compound child's material on the other side. The pre-fix code returned + // materials[0] (kHullMaterialA) for both sides, so a strike on the +x child would fail. + ENSURE( capturedMaterialA == expectedHullMaterial || capturedMaterialB == expectedHullMaterial ); + } + + return 0; +} + +#if 0 +static int TestSetWorkerCount( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.workerCount = 1; + b3WorldId worldId = b3CreateWorld( &worldDef ); + ENSURE( b3World_IsValid( worldId ) ); + ENSURE( b3World_GetWorkerCount( worldId ) == 1 ); + + CreateJunkyard( worldId ); + StepJunkyard( worldId, 1 ); + + b3World_SetWorkerCount( worldId, 4 ); + ENSURE( b3World_GetWorkerCount( worldId ) == 4 ); + + StepJunkyard( worldId, 2 ); + + b3World_SetWorkerCount( worldId, 4 ); + ENSURE( b3World_GetWorkerCount( worldId ) == 4 ); + + StepJunkyard( worldId, 3 ); + + b3World_SetWorkerCount( worldId, 0 ); + ENSURE( b3World_GetWorkerCount( worldId ) == 1 ); + + StepJunkyard( worldId, 4 ); + + b3World_SetWorkerCount( worldId, -5 ); + ENSURE( b3World_GetWorkerCount( worldId ) == 1 ); + + StepJunkyard( worldId, 5 ); + + b3World_SetWorkerCount( worldId, B2_MAX_WORKERS + 10 ); + ENSURE( b3World_GetWorkerCount( worldId ) == B2_MAX_WORKERS ); + + StepJunkyard( worldId, 2 ); + + b3DestroyWorld( worldId ); + + return 0; +} +#endif + +// This tests continuous collision and mesh contact stability +static int TestMeshDrop( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + // todo GetCoreCount + worldDef.workerCount = 4; + + b3WorldId worldId = b3CreateWorld( &worldDef ); + + MeshDropData data = CreateMeshDrop( worldId ); + + float timeStep = 1.0f / 60.0f; + + int stepIndex = 0; + int stepLimit = 400; + + while ( stepIndex < stepLimit ) + { + int subStepCount = 4; + b3World_Step( worldId, timeStep, subStepCount ); + + b3BodyEvents events = b3World_GetBodyEvents( worldId ); + if (events.moveCount == 0) + { + // All bodies sleeping + break; + } + + stepIndex += 1; + } + + printf( " TestMeshDrop stepIndex = %d\n", stepIndex ); + + DestroyMeshDrop( &data ); + b3DestroyWorld( worldId ); + + ENSURE( stepIndex < stepLimit ); + + 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 ); + RUN_SUBTEST( TestContactEvents ); + RUN_SUBTEST( TestHitEvents ); + RUN_SUBTEST( TestCompoundHitEvents ); + RUN_SUBTEST( TestMeshDrop ); + // RUN_SUBTEST( TestSetWorkerCount ); + + return 0; +}