From 69037feaba4debcd4bca7fc4398d25ab922eb4ce Mon Sep 17 00:00:00 2001 From: Erin Catto Date: Sun, 28 Jun 2026 10:44:34 -0700 Subject: [PATCH] Build polish (#18) Improve build process and documentation. Improved ray versus capsule accuracy. UI improvements --- CMakePresets.json | 41 ++ README.md | 49 ++ build.sh | 4 +- docs/images/rc_parallel_crosssection.svg | 65 +++ docs/images/rc_parallel_quadratic.svg | 55 +++ docs/images/rc_parallel_setup.svg | 64 +++ docs/raycast_capsule_parallel.md | 283 ++++++++++++ include/box3d/collision.h | 19 +- samples/earcut.h | 2 + samples/gfx/keycodes.h | 4 +- samples/main.cpp | 90 +++- samples/sample.cpp | 87 ++-- samples/sample.h | 19 + samples/sample_collision.cpp | 246 +++++++++- samples/sample_replay.cpp | 2 - src/CMakeLists.txt | 4 +- src/capsule.c | 297 +++++++----- src/core.c | 2 +- test/test_shape.c | 560 +++++++++++++++++++++++ 19 files changed, 1727 insertions(+), 166 deletions(-) create mode 100644 CMakePresets.json create mode 100644 docs/images/rc_parallel_crosssection.svg create mode 100644 docs/images/rc_parallel_quadratic.svg create mode 100644 docs/images/rc_parallel_setup.svg create mode 100644 docs/raycast_capsule_parallel.md diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 0000000..04b0cd2 --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,41 @@ +{ + "version": 3, + "cmakeMinimumRequired": { "major": 3, "minor": 21, "patch": 0 }, + "configurePresets": [ + { + "name": "windows", + "displayName": "Windows (default Visual Studio)", + "condition": { "type": "equals", "lhs": "${hostSystemName}", "rhs": "Windows" }, + "binaryDir": "${sourceDir}/build" + }, + { + "name": "linux-debug", + "displayName": "Linux Debug", + "condition": { "type": "equals", "lhs": "${hostSystemName}", "rhs": "Linux" }, + "binaryDir": "${sourceDir}/build", + "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug" } + }, + { + "name": "linux-release", + "displayName": "Linux Release", + "condition": { "type": "equals", "lhs": "${hostSystemName}", "rhs": "Linux" }, + "binaryDir": "${sourceDir}/build", + "cacheVariables": { "CMAKE_BUILD_TYPE": "Release" } + }, + { + "name": "macos", + "displayName": "macOS (Xcode)", + "generator": "Xcode", + "condition": { "type": "equals", "lhs": "${hostSystemName}", "rhs": "Darwin" }, + "binaryDir": "${sourceDir}/build" + } + ], + "buildPresets": [ + { "name": "windows-debug", "configurePreset": "windows", "configuration": "Debug" }, + { "name": "windows-release", "configurePreset": "windows", "configuration": "Release" }, + { "name": "linux-debug", "configurePreset": "linux-debug" }, + { "name": "linux-release", "configurePreset": "linux-release" }, + { "name": "macos-debug", "configurePreset": "macos", "configuration": "Debug" }, + { "name": "macos-release", "configurePreset": "macos", "configuration": "Release" } + ] +} diff --git a/README.md b/README.md index cf0a31f..60e0602 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,19 @@ Box3D is a 3D physics engine for games. - Install [git](https://git-scm.com/) - Ensure these run from the command line +## Building with CMake presets + +The presets in `CMakePresets.json` give one build flow on every platform and are picked up automatically by Visual Studio, VS Code, and CLion (open the folder and choose a preset). From the command line: + +- Windows: `cmake --preset windows` then `cmake --build --preset windows-release` +- Linux: `cmake --preset linux-release` then `cmake --build --preset linux-release` +- macOS: `cmake --preset macos` then `cmake --build --preset macos-release` + +Run the samples app (must be in the Box3D directory). + +- Bash: `./build/bin/Release/samples` +- Cmd: `.\build\bin\Release\samples.exe` + ## Building for Visual Studio - Install [Visual Studio](https://visualstudio.microsoft.com/) @@ -77,6 +90,42 @@ Box3D is a 3D physics engine for games. - cmake --build . --config Release - cmake --install . (might need sudo) +## Using Box3D in your project + +The core library has no dependencies beyond the C runtime (and `libm` on Unix). Linking it +gives you the `box3d::box3d` target. When Box3D is consumed as a subproject it builds the +library only; samples, tests, and benchmarks are skipped. + +The recommended path is FetchContent, which pins a tag and needs no separate install step: + +```cmake +include(FetchContent) +FetchContent_Declare(box3d + GIT_REPOSITORY https://github.com/erincatto/box3d.git + GIT_TAG v0.1.0) +FetchContent_MakeAvailable(box3d) + +target_link_libraries(my_app PRIVATE box3d::box3d) +``` + +For a vendored copy or git submodule, point `add_subdirectory` at it: + +```cmake +add_subdirectory(extern/box3d) + +target_link_libraries(my_app PRIVATE box3d::box3d) +``` + +To use a copy installed with `cmake --install`, find the package: + +```cmake +find_package(box3d 0.1 REQUIRED) + +target_link_libraries(my_app PRIVATE box3d::box3d) +``` + +See [`docs/hello.md`](docs/hello.md) for a minimal first program. + ## Compatibility The Box3D library and samples build and run on Windows, Linux, and Mac. diff --git a/build.sh b/build.sh index e678e44..c5a8592 100644 --- a/build.sh +++ b/build.sh @@ -3,7 +3,5 @@ # 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 -S . -B build cmake --build build diff --git a/docs/images/rc_parallel_crosssection.svg b/docs/images/rc_parallel_crosssection.svg new file mode 100644 index 0000000..959c775 --- /dev/null +++ b/docs/images/rc_parallel_crosssection.svg @@ -0,0 +1,65 @@ + + + + + + + + + Reduction to 2D: ray vs circle in the plane ⊥ to the axis + Project out the axis component. The infinite cylinder becomes a circle of radius r. + + + + circle of radius r + + + + + a₁ (out of page) + + + + r + + + + sc + + + + projected origin + + + + perp + + + + + + + near root → tr + + far root + + + + Quantities used by the branch + sc + = origin offset ⊥ axis, sc2 = |sc|² + perp + = a₂ − a₁₂ a₁ (ray dir ⊥ axis) + perp2 = |perp|² = det + β = sc · perp (signed, length) + γ = sc2 − r² ≥ 0 (origin outside) + disc = β² − perp2·γ + + β ≥ 0 → moving away → miss + disc < 0 → never reaches r → miss + otherwise: near root is the entry tr + + + In this plane the axis is a single point, so the problem is exactly “ray from an outside point hits a circle.” + Solving here never divides by the tiny det, which is what made the general solve fail. + diff --git a/docs/images/rc_parallel_quadratic.svg b/docs/images/rc_parallel_quadratic.svg new file mode 100644 index 0000000..bfeeffb --- /dev/null +++ b/docs/images/rc_parallel_quadratic.svg @@ -0,0 +1,55 @@ + + + + + + + The quadratic in tr, and the stable root + Squared distance from the moving ray point to the axis, as a function of ray distance tr. + + + + + tr + dist² + + + + + + + r² + + + + + + + + sc2 + tr = 0 + + + + + tr (entry) + + + + far root (exit) + + + + closest approach + + inside the cylinder (dist² < r²) + + + + Why tr = γ / (−β + √disc) rather than the textbook root + quadratic: perp2·tr² + 2β·tr + γ = 0 ( β = sc·perp, γ = sc2 − r², perp2 = det ) + textbook near root: tr = (−β − √disc) / perp2 + ray → parallel: perp2 → 0 and √disc → |β| = −β ⇒ −β − √disc → 0 (cancellation), ÷ tiny perp2 → 0/0 + used form: tr = γ / (−β + √disc) — denominator is a sum of two positives: no cancellation, no divide by det + diff --git a/docs/images/rc_parallel_setup.svg b/docs/images/rc_parallel_setup.svg new file mode 100644 index 0000000..1cf491a --- /dev/null +++ b/docs/images/rc_parallel_setup.svg @@ -0,0 +1,64 @@ + + + + + + + + + + + Near-parallel branch — side view (plane through the axis) + Ray almost parallel to the capsule axis; origin outside the infinite cylinder. + + + + + + infinite cylinder wall + + + + + + + + + + + a₁ (axis dir) + + + + c₁ + + c₂ + + + + r + + + + ray origin + + + + sc + |sc| > r + + + + a₂ (ray dir), nearly ∥ a₁ + + + + near hit on cylinder + + + tr (ray distance) + + + det = 1 − (a₁·a₂)² ≈ 0 here, so the Cramer's-rule closest-point solve divides by ~0 and loses all precision. + Fix: intersect the ray with the infinite cylinder using only the parts perpendicular to the axis (next figure). + diff --git a/docs/raycast_capsule_parallel.md b/docs/raycast_capsule_parallel.md new file mode 100644 index 0000000..71becd3 --- /dev/null +++ b/docs/raycast_capsule_parallel.md @@ -0,0 +1,283 @@ +# Ray vs capsule: the near-parallel branch + +This note explains the `det < FLT_EPSILON` block inside `b3RayCastCapsule` +(`src/capsule.c`). That block is the fallback used when the ray is almost parallel +to the capsule axis, where the normal closest-point solve falls apart numerically. + +```c +float det = 1.0f - a12 * a12; +if ( det < FLT_EPSILON ) +{ + // Ray nearly parallel to the capsule axis... + b3Vec3 perp = b3MulSub( a2, a12, a1 ); // a2 - a12*a1 + float perp2 = b3LengthSquared( perp ); + + float beta = b3Dot( sc, perp ); + float gamma = sc2 - r * r; + + float disc = beta * beta - perp2 * gamma; + if ( beta >= 0.0f || disc < 0.0f ) + { + return output; // miss + } + + tr = gamma / ( -beta + sqrtf( disc ) ); // near intersection distance +} +``` + +--- + +## 1. What is already known when we reach this block + +`b3RayCastCapsule` casts a ray against a capsule (a cylinder capped by two +hemispheres). By the time we reach line 232, several things are settled: + +| symbol | meaning | code | +|---|---|---| +| `c1`, `c2` | the two capsule centers (ends of the core segment) | `shape->center1/2` | +| `r` | capsule radius | `shape->radius` | +| `axis` = `a1` | **unit** vector along the capsule axis, `c2 − c1` normalized | line 127 | +| `s` | ray origin relative to `c1` | line 123 | +| `u` | how far the origin projects along the axis, `dot(s, a1)` | line 130 | +| `sc` | the part of `s` **perpendicular** to the axis (axis → origin) | line 136 | +| `sc2` | `|sc|²`, squared distance from origin to the infinite axis | line 139 | +| `a2` = `rayAxis` | **unit** ray direction | line 177 | +| `a12` | `dot(a1, a2)`, the cosine of the angle between ray and axis | line 226 | + +Two facts from the code above this branch matter a lot here: + +- **The origin is outside the infinite cylinder.** The earlier `sc2 < r*r` test + (line 142) already handled the inside case and returned. So here `sc2 ≥ r²`. +- **The ray has nonzero length** and was not rejected by the projected-extent early + out (line 187). + +`det = 1 − a12²`. Since `a12` is the cosine of the angle between the two unit axes, +`det = 1 − cos²θ = sin²θ`. It is the squared sine of the angle between the ray and +the capsule axis. + +--- + +## 2. Why a special case at all + +The general path (the `else` branch, lines 258–288) solves for the closest points +between the infinite ray and the infinite axis with Cramer's rule, dividing by +`det`: + +```c +float invDet = 1.0f / det; +float t1 = ( sa1 - a12 * sa2 ) * invDet; +float t2 = ( a12 * sa1 - sa2 ) * invDet; +``` + +When the ray is nearly parallel to the axis, `θ → 0`, so `det = sin²θ → 0` and +`1/det → ∞`. Every quantity computed through `invDet` is multiplied by a huge, +rounding-amplified number. The "closest point on the axis" becomes meaningless, and +a ray that is slowly closing in on the capsule side can be missed entirely. + +`FLT_EPSILON` (≈ 1.19e-7) is the cutoff, and the threshold is not arbitrary. `det` +is computed as `1 − a12*a12` with `a12 ≈ 1`, a subtraction of two nearly-equal +numbers. Its absolute rounding error is about one ulp of 1.0, i.e. `FLT_EPSILON`. So +once the true `det` shrinks to `~FLT_EPSILON`, the *computed* `det` has essentially no +correct bits left, and `1/det` (> 8 million here) faithfully amplifies that garbage. +Below the cutoff we branch to a method that **never forms `1/det`**. + +![Side view of the near-parallel configuration](images/rc_parallel_setup.svg) + +--- + +## 3. The idea: collapse the axis and solve ray-vs-circle + +When the ray is almost parallel to the axis, the interesting motion is not *along* +the axis, it is the slow drift *across* it. So drop the axis component entirely and +work in the 2D plane perpendicular to the axis. + +In that plane: + +- The infinite cylinder becomes a **circle of radius `r`**. +- The capsule axis collapses to a **single point** (the circle's center). +- The ray origin projects to a point at distance `√sc2 > r` (outside the circle). +- The ray's direction projects to the in-plane velocity `perp`. + +The 3D "ray vs infinite cylinder" problem becomes the flat "ray from an outside +point hits a circle" problem, which has no `det` in it. + +![Cross-section perpendicular to the axis](images/rc_parallel_crosssection.svg) + +--- + +## 4. Line by line + +### `perp = b3MulSub( a2, a12, a1 )` → `a2 − a12·a1` + +This is the ray direction with its along-axis part removed: the component of `a2` +perpendicular to the axis. The comment notes you could also get a perpendicular +vector with a cross product, but subtracting the parallel part is cheaper and is +exactly the in-plane velocity we want. It is dimensionless (built from unit vectors). + +A useful identity: because `a1` and `a2` are unit vectors, + +``` +|perp|² = |a2 − a12·a1|² + = 1 − 2·a12² + a12² + = 1 − a12² + = det +``` + +So **`perp2` is mathematically the same tiny number as `det`.** That is fine — we +never *divide* by it in the end (see §6); it only appears multiplied into `disc`, +where being tiny does no harm. + +### `perp2 = b3LengthSquared( perp )` + +The squared length of that in-plane velocity. Equal to `det`, as just shown. + +### `beta = b3Dot( sc, perp )` + +Project the origin's perpendicular offset `sc` onto the in-plane velocity `perp`. +`sc` has length units and `perp` is dimensionless, so **`beta` carries length units.** + +Its sign is what matters: `beta` is half the rate of change of the squared distance +to the axis at the start of the ray. `beta < 0` means the projected point is moving +**toward** the axis; `beta ≥ 0` means it is moving **away** (or tangent). + +### `gamma = sc2 − r*r` + +How far outside the cylinder the origin sits, in squared-length units. Because the +origin is outside, **`gamma ≥ 0`.** + +### `disc = beta*beta − perp2*gamma` + +The discriminant of the quadratic derived in §5. Sign units are length². If it is +negative, the (infinite) ray never gets within `r` of the axis. + +### The early out: `if ( beta >= 0.0f || disc < 0.0f ) return` + +Two distinct ways to miss: + +- **`beta ≥ 0`** — the origin is already outside and the ray is heading away from the + axis (or running tangent to it). It will never come back, so no side hit. +- **`disc < 0`** — the ray's closest approach to the axis is still more than `r` away. + The infinite cylinder is never reached. + +### `tr = gamma / ( -beta + sqrtf( disc ) )` + +The distance along the ray (in length units, since `a2` is a unit vector) to the +**near** intersection with the infinite cylinder — where the ray first crosses into +the circle. The unusual algebraic form is deliberate; §6 explains it. + +--- + +## 5. Where the quadratic comes from + +Walk a point along the ray and ask when its perpendicular distance to the axis equals +`r`. Relative to `c1`, the ray point at distance `tr` is `s + tr·a2`. Its component +perpendicular to the axis is the sum of the perpendicular parts of each term: + +``` +perp_offset(tr) = sc + tr·perp +``` + +(`sc` is the perpendicular part of `s`; `perp` is the perpendicular part of `a2`.) +Set its squared length equal to `r²`: + +``` +|sc + tr·perp|² = r² +sc2 + 2·tr·(sc·perp) + tr²·|perp|² = r² +perp2·tr² + 2·beta·tr + gamma = 0 (gamma = sc2 − r²) +``` + +A plain quadratic `A·tr² + B·tr + C = 0` with `A = perp2`, `B = 2·beta`, `C = gamma`. +Its discriminant (over 4) is `beta² − perp2·gamma`, i.e. `disc`. The two roots are the +entry and exit distances of the ray through the infinite cylinder; we want the near +(entry) one. + +![The quadratic and its roots](images/rc_parallel_quadratic.svg) + +--- + +## 6. Why the root is written `gamma / (−beta + √disc)` + +The textbook near root of `perp2·tr² + 2·beta·tr + gamma = 0` is + +``` +tr = (−beta − √disc) / perp2 +``` + +This is a trap exactly in the regime we are in: + +- `perp2 = det` is tiny, so dividing by it amplifies error. +- As the ray approaches parallel, `perp2·gamma → 0`, so `disc → beta²` and + `√disc → |beta|`. Since we already passed the `beta ≥ 0` test, here `beta < 0`, so + `|beta| = −beta`. The numerator `−beta − √disc → −beta − (−beta) = 0`: a + **catastrophic cancellation**. The expression collapses to `0 / 0`. + +Multiply numerator and denominator by the conjugate `(−beta + √disc)` (equivalently, +use the product-of-roots identity `tr_near · tr_far = gamma / perp2`): + +``` +tr = gamma / (−beta + √disc) +``` + +Now the denominator is a **sum of two positive quantities** (`−beta > 0` and +`√disc ≥ 0`), so there is no cancellation, and `perp2` has vanished from the +expression — no division by the tiny determinant. Because `gamma ≥ 0` and the +denominator is `> 0`, the result satisfies `tr ≥ 0` automatically. + +This mirrors the same trick used elsewhere in the file: `b3RayCastSphere` and the +`else` branch here both intersect relative to the closest point precisely to dodge +this kind of round-off. + +**Limiting sanity check.** If the ray is *exactly* parallel (`a12 = 1`), then +`perp = a2 − a1 = 0`, so `perp2 = 0` and `beta = dot(sc, 0) = 0`. The `beta ≥ 0` +test fires and we return a miss — the correct answer, since a parallel ray that +starts outside the cylinder can only ever hit an endcap, never the side. The +division is never reached, so `perp2 = 0` is harmless. + +--- + +## 7. Units recap + +Everything stays dimensionally consistent, which is a quick way to sanity-check the +algebra: + +| quantity | units | +|---|---| +| `perp`, `perp2`, `a12`, `det` | dimensionless | +| `beta = sc·perp` | length | +| `gamma = sc2 − r²` | length² | +| `disc = beta² − perp2·gamma` | length² | +| `tr = gamma / (−beta + √disc)` | length² / length = **length** | + +`tr` is a true distance along the ray, not a fraction — the same convention the rest +of the function uses before the final `fraction` is formed. + +--- + +## 8. What happens to `tr` afterward + +Both branches (parallel and general) converge on the same tail code, which treats +`tr` as a candidate hit distance on the **infinite** cylinder and then decides what +the capsule actually does there: + +1. **Range check** (line 291): reject if `tr < 0` or beyond the ray's max length. +2. **Map to the axis** (line 297): `tc = u + tr·a12` is where the hit projects along + the axis, measured from `c1`. +3. **Endcap handoff**: if `tc < 0` the hit is past the `c1` end, so cast against the + sphere at `c1`; if `tc > length`, cast against the sphere at `c2`. This is how the + near-parallel case still reports endcap hits correctly. +4. **Side hit** (lines 324–333): otherwise the hit is genuinely on the cylindrical + wall. Compute the point `c1 + s + tr·a2`, the outward normal (the point minus its + projection onto the axis, normalized), and the fraction. + +So this whole block has one job: produce a numerically trustworthy `tr` for the +cylinder intersection when the ray is nearly parallel. The shared tail does the rest. + +--- + +## Figures + +The three SVGs referenced above live in `docs/images/`: + +- `rc_parallel_setup.svg` — side view: why the parallel case is hard. +- `rc_parallel_crosssection.svg` — the 2D reduction to ray-vs-circle. +- `rc_parallel_quadratic.svg` — the quadratic, its roots, and the cancellation fix. diff --git a/include/box3d/collision.h b/include/box3d/collision.h index ae59ad4..30cc957 100644 --- a/include/box3d/collision.h +++ b/include/box3d/collision.h @@ -501,25 +501,30 @@ B3_API bool b3OverlapMesh( const b3Mesh* shape, b3Transform shapeTransform, cons /// 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. +/// Ray cast versus sphere in local space. A zero length ray is a point query. Initial overlap +/// reports a hit at the ray origin with zero fraction and zero normal. B3_API b3CastOutput b3RayCastSphere( const b3Sphere* shape, const b3RayCastInput* input ); -/// Ray cast versus hollow sphere in local space. +/// Ray cast versus a hollow sphere shell in local space. Unlike the solid sphere a ray starting +/// inside is not an overlap: it passes through and hits the far wall. B3_API b3CastOutput b3RayCastHollowSphere( const b3Sphere* shape, const b3RayCastInput* input ); -/// Ray cast versus capsule in local space. Initial overlap is treated as a miss. +/// Ray cast versus capsule in local space. A zero length ray is a point query. Initial overlap +/// reports a hit at the ray origin with zero fraction and zero normal. B3_API b3CastOutput b3RayCastCapsule( const b3Capsule* shape, const b3RayCastInput* input ); -/// Ray cast versus compound in local space. Initial overlap is treated as a miss. +/// Ray cast versus compound in local space. A zero length ray is a point query. Initial overlap +/// with a child reports a hit at the ray origin with zero fraction and zero normal. B3_API b3CastOutput b3RayCastCompound( const b3CompoundData* shape, const b3RayCastInput* input ); -/// Ray cast versus hull shape in local space. Initial overlap is treated as a miss. +/// Ray cast versus hull shape in local space. A zero length ray is a point query. Initial overlap +/// reports a hit at the ray origin with zero fraction and zero normal. B3_API b3CastOutput b3RayCastHull( const b3HullData* shape, const b3RayCastInput* input ); -/// Ray cast versus mesh in local space. +/// Ray cast versus mesh in local space. A thin surface with no interior, so there is no overlap case. B3_API b3CastOutput b3RayCastMesh( const b3Mesh* shape, const b3RayCastInput* input ); -/// Ray cast versus height field in local space. +/// Ray cast versus height field in local space. A thin surface with no interior, so there is no overlap case. B3_API b3CastOutput b3RayCastHeightField( const b3HeightFieldData* shape, const b3RayCastInput* input ); /// Shape cast versus a sphere. Initial overlap is treated as a miss. diff --git a/samples/earcut.h b/samples/earcut.h index 01bd7e9..31c50e4 100644 --- a/samples/earcut.h +++ b/samples/earcut.h @@ -6,6 +6,8 @@ #include #include +#include + namespace mapbox { namespace util { diff --git a/samples/gfx/keycodes.h b/samples/gfx/keycodes.h index 2789120..f883438 100644 --- a/samples/gfx/keycodes.h +++ b/samples/gfx/keycodes.h @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Erin Catto // SPDX-License-Identifier: MIT -// todo get rid of this file +// These mappings exist to make porting samples from Box2D easier. #pragma once @@ -19,6 +19,7 @@ enum KEY_M = SAPP_KEYCODE_M, KEY_O = SAPP_KEYCODE_O, KEY_P = SAPP_KEYCODE_P, + KEY_Q = SAPP_KEYCODE_Q, KEY_R = SAPP_KEYCODE_R, KEY_S = SAPP_KEYCODE_S, KEY_T = SAPP_KEYCODE_T, @@ -27,7 +28,6 @@ enum KEY_SPACE = SAPP_KEYCODE_SPACE, KEY_ESCAPE = SAPP_KEYCODE_ESCAPE, KEY_TAB = SAPP_KEYCODE_TAB, - KEY_HOME = SAPP_KEYCODE_HOME, KEY_LEFT_SHIFT = SAPP_KEYCODE_LEFT_SHIFT, KEY_LEFT_BRACKET = SAPP_KEYCODE_LEFT_BRACKET, KEY_RIGHT_BRACKET = SAPP_KEYCODE_RIGHT_BRACKET, diff --git a/samples/main.cpp b/samples/main.cpp index 4a7e522..2f86d8d 100644 --- a/samples/main.cpp +++ b/samples/main.cpp @@ -49,7 +49,21 @@ static int CompareSamples( const void* a, const void* b ) static void SortSamples() { + // Sorting reorders the table, so recover the replay viewer's slot by identity. + SampleCreateFcn* replayFcn = ( g_replayIndex >= 0 ) ? g_sampleEntries[g_replayIndex].CreateFcn : nullptr; qsort( g_sampleEntries, g_sampleCount, sizeof( SampleEntry ), CompareSamples ); + if ( replayFcn != nullptr ) + { + g_replayIndex = -1; + for ( int i = 0; i < g_sampleCount; ++i ) + { + if ( g_sampleEntries[i].CreateFcn == replayFcn ) + { + g_replayIndex = i; + break; + } + } + } } // Single host UI callback fired from inside StartUIFrame: menu bar, panels, and @@ -76,6 +90,9 @@ static void OnInit( void ) s_context.Load(); + // First run with no settings opens with the controls window up. + s_context.showControls = s_context.newUser; + int cores = (int)std::thread::hardware_concurrency(); s_context.workerCount = b3ClampInt( cores / 2, 1, 8 ); s_context.windowWidth = sapp_width(); @@ -83,9 +100,15 @@ static void OnInit( void ) SortSamples(); + // A first run with no settings opens straight into the replay viewer. + int index = s_context.sampleIndex; + if ( s_context.newUser && g_replayIndex >= 0 ) + { + index = g_replayIndex; + } + // --sample N selects a registered sample by sorted index, overriding the // persisted one. Lets a headless --frames run target a specific sample. - int index = s_context.sampleIndex; if ( s_sampleOverride >= 0 && s_sampleOverride < g_sampleCount ) { index = s_sampleOverride; @@ -96,12 +119,11 @@ static void OnInit( void ) static void OnEvent( const sapp_event* e ) { - // Esc quits even with ImGui focus so a text field can't trap the app. - if ( e->type == SAPP_EVENTTYPE_KEY_DOWN && e->key_code == SAPP_KEYCODE_ESCAPE ) - { - sapp_request_quit(); - return; - } + //if ( e->type == SAPP_EVENTTYPE_KEY_DOWN || e->type == SAPP_EVENTTYPE_CHAR ) + //{ + // volatile int dummy = 0; + // dummy = 32; + //} bool uiCaptured = false; if (s_context.camera.m_thirdPerson == false) @@ -142,6 +164,29 @@ static void OnEvent( const sapp_event* e ) s_context.showUI = !s_context.showUI; break; + case KEY_ESCAPE: + // Layered cancel. An open picker is an ImGui popup that + // already swallowed this. So peel the controls window, then + // the selection. Quit lives on Ctrl+Q now. + if ( s_context.showControls ) + { + s_context.showControls = false; + } + else + { + ClearSelection(); + } + break; + + case KEY_Q: + if ( mods & MOD_CTRL ) + { + sapp_request_quit(); + break; + } + s_context.sample->Keyboard( e->key_code, ACTION_PRESS, mods ); + break; + case KEY_O: if ( mods & MOD_CTRL ) { @@ -156,6 +201,9 @@ static void OnEvent( const sapp_event* e ) break; case KEY_P: + // Pause stays on P. Space is not bound here on purpose. Global + // keys are dispatched before the sample sees them, so claiming + // Space would steal jump from the Mover sample. s_context.pause = !s_context.pause; break; @@ -176,7 +224,6 @@ static void OnEvent( const sapp_event* e ) break; case KEY_F: - case KEY_HOME: { // Frame the selection, or let the sample frame its whole scene when nothing is // selected. A non-body selection such as a recorded query supplies its own bounds and @@ -216,6 +263,16 @@ static void OnEvent( const sapp_event* e ) SetKeyDown( e->key_code, false ); break; + case SAPP_EVENTTYPE_CHAR: + // ? toggles the controls window. Read the typed character so it works + // on any layout and a text field can still type a literal ?, since the + // picker captures the event before it reaches here. + if ( e->char_code == '?' && e->key_repeat == false ) + { + s_context.showControls = !s_context.showControls; + } + break; + case SAPP_EVENTTYPE_MOUSE_DOWN: s_context.mouseX = e->mouse_x; s_context.mouseY = e->mouse_y; @@ -294,6 +351,16 @@ static void OnFrame( void ) return; } + // Handle a deferred Replay > Open request before any GPU work this frame. + // The native picker blocks on a nested run loop. Running it here (no pass + // open, no buffers updated, no ImGui frame begun) keeps it from re-entering + // a half-built frame the way it did when invoked from inside the UI callback. + if ( s_context.openReplayPicker ) + { + s_context.openReplayPicker = false; + OpenReplayFileDialog( &s_context ); + } + const float dt = (float)sapp_frame_duration(); const int W = sapp_width(); const int H = sapp_height(); @@ -321,13 +388,6 @@ static void OnFrame( void ) SetTransparentDynamic( s_context.transparentDynamic ); s_context.sample->ResetText(); - // Pause banner only with the UI up, matching Box2D. - if ( s_context.pause && s_context.showUI ) - { - s_context.sample->DrawTextLine( "****PAUSED****" ); - s_context.sample->DrawTextLine( "" ); - } - s_context.sample->Step(); s_context.sample->Render(); diff --git a/samples/sample.cpp b/samples/sample.cpp index 553d74a..f5c9832 100644 --- a/samples/sample.cpp +++ b/samples/sample.cpp @@ -30,9 +30,8 @@ #include #include #include -// #include -#define INFO_PANEL_WIDTH 16.0f +#define INFO_PANEL_WIDTH 20.0f // Load a file. You must free the character array. static char* ReadFile( int& size, const char* filename ) @@ -95,7 +94,6 @@ void SampleContext::Save() fprintf( file, " \"drawShapes\": %s,\n", gd->drawShapes ? "true" : "false" ); fprintf( file, " \"drawJoints\": %s,\n", gd->drawJoints ? "true" : "false" ); fprintf( file, " \"drawContacts\": %s,\n", gd->drawContacts ? "true" : "false" ); - fprintf( file, " \"showDiagnostics\": %s,\n", showMetrics ? "true" : "false" ); fprintf( file, " \"enableShadows\": %s,\n", enableShadows ? "true" : "false" ); fprintf( file, " \"enableGtao\": %s,\n", enableGtao ? "true" : "false" ); fprintf( file, " \"gtaoQuality\": %d,\n", gtaoQuality ); @@ -134,6 +132,9 @@ void SampleContext::Load() return; } + // Settings file exists, so it is not a new user. + newUser = false; + jsmn_parser parser; jsmntok_t tokens[MAX_TOKENS]; @@ -178,11 +179,6 @@ void SampleContext::Load() const char* s = data + tokens[i + 1].start; GetGuiDraw()->drawContacts = strncmp( s, "true", 4 ) == 0; } - else if ( jsoneq( data, &tokens[i], "showDiagnostics" ) == 0 ) - { - const char* s = data + tokens[i + 1].start; - showMetrics = strncmp( s, "true", 4 ) == 0; - } else if ( jsoneq( data, &tokens[i], "enableShadows" ) == 0 ) { const char* s = data + tokens[i + 1].start; @@ -1339,6 +1335,25 @@ void SelectSample( SampleContext* context, int selection, bool restart ) context->restart = false; } +void OpenReplayFileDialog( SampleContext* context ) +{ + if ( g_replayIndex < 0 ) + { + return; + } + + NFD_Init(); + nfdu8char_t* outPath = nullptr; + nfdu8filteritem_t filter[1] = { { "Box3D recording", "b3rec" } }; + if ( NFD_OpenDialogU8( &outPath, filter, 1, nullptr ) == NFD_OKAY ) + { + snprintf( context->replayFile, sizeof( context->replayFile ), "%s", outPath ); + NFD_FreePathU8( outPath ); + SelectSample( context, g_replayIndex, false ); + } + NFD_Quit(); +} + // Subsequence fuzzy match. Returns a score (higher is better) or -1 if the // needle is not a subsequence of the haystack. Bonuses for a prefix match, a // word start, and a contiguous run, so "stack" ranks Pyramid > Stack sensibly. @@ -1672,38 +1687,33 @@ static void DrawMenuBar( SampleContext* context ) { if ( ImGui::MenuItem( "Open..." ) ) { - NFD_Init(); - nfdu8char_t* outPath = nullptr; - nfdu8filteritem_t filter[1] = { { "Box3D recording", "b3rec" } }; - if ( NFD_OpenDialogU8( &outPath, filter, 1, nullptr ) == NFD_OKAY ) - { - snprintf( context->replayFile, sizeof( context->replayFile ), "%s", outPath ); - NFD_FreePathU8( outPath ); - SelectSample( context, g_replayIndex, false ); - } - NFD_Quit(); + // Defer the native picker to the top of the next frame. Running it + // here would block on a nested run loop mid-frame (after the buffers + // were uploaded and the ImGui frame began), re-entering the render + // loop. See OpenReplayFileDialog and SampleContext::openReplayPicker. + context->openReplayPicker = true; } ImGui::EndMenu(); } - static bool showHelp = false; static bool showAbout = false; if ( ImGui::BeginMenu( "Help" ) ) { - ImGui::MenuItem( "Controls", nullptr, &showHelp ); + ImGui::MenuItem( "Controls", "?", &context->showControls ); ImGui::MenuItem( "About", nullptr, &showAbout ); ImGui::EndMenu(); } ImGui::EndMainMenuBar(); - if ( showHelp ) + if ( context->showControls ) { - ImGui::SetNextWindowPos( { context->camera.m_width * 0.5f, context->camera.m_height * 0.5f }, ImGuiCond_Appearing, + ImGui::SetNextWindowPos( { context->camera.m_width * 0.5f, context->camera.m_height * 0.35f }, ImGuiCond_Appearing, { 0.5f, 0.5f } ); ImGui::SetNextWindowSize( { 26.0f * fontSize, 0.0f }, ImGuiCond_Appearing ); - if ( ImGui::Begin( "Controls", &showHelp, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize ) ) + if ( ImGui::Begin( "Controls", &context->showControls, + ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize ) ) { ImGui::SeparatorText( "Keyboard" ); if ( ImGui::BeginTable( "keys", 2, ImGuiTableFlags_SizingFixedFit ) ) @@ -1715,17 +1725,21 @@ static void DrawMenuBar( SampleContext* context ) DrawRow( "R", "Restart sample" ); DrawRow( "[ ]", "Previous / next sample" ); DrawRow( "Ctrl+O", "Open sample picker" ); - DrawRow( "F / Home", "Frame selection / world" ); - DrawRow( "Esc", "Quit" ); + DrawRow( "F", "Frame selection / world" ); + DrawRow( "?", "Show / hide controls" ); + DrawRow( "Esc", "Cancel / close" ); + DrawRow( "Ctrl+Q", "Quit" ); ImGui::EndTable(); } ImGui::SeparatorText( "Mouse" ); if ( ImGui::BeginTable( "mouse", 2, ImGuiTableFlags_SizingFixedFit ) ) { - DrawRow( "Left drag", "Move bodies (mouse joint)" ); + DrawRow( "Left click", "Select body/shape" ); + DrawRow( "Ctrl + left drag", "Move bodies (mouse joint)" ); DrawRow( "Alt + left drag", "Orbit camera" ); DrawRow( "Alt + middle drag", "Pan camera" ); + DrawRow( "Alt + right drag", "Zoom (dolly)" ); DrawRow( "Right drag", "Fly look (WASD to move)" ); DrawRow( "Scroll", "Zoom" ); DrawRow( "Shift + left", "Shoot (Ctrl spin, Alt ragdoll)" ); @@ -1847,6 +1861,13 @@ static void DrawSamplePicker( SampleContext* context ) ImGui::CloseCurrentPopup(); } + // The active search field eats the first Esc, so dismiss here instead of + // relying on the popup's default nav close. + if ( ImGui::IsKeyPressed( ImGuiKey_Escape, false ) ) + { + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); } } @@ -1870,6 +1891,14 @@ static void DrawInfoPanel( SampleContext* context ) ImGui::TextColored( HexColor( b3_colorLightGray ), "%s", entry.Category ); ImGui::Separator(); + if ( context->pause ) + { + ImGui::TextColored( HexColor( b3_colorRed ), "PAUSED" ); + ImGui::SameLine(); + ImGui::TextDisabled( "(p)" ); + ImGui::Separator(); + } + const float frameMs = (float)( sapp_frame_duration() * 1000.0 ); ImGui::TextColored( HexColor( b3_colorSeaGreen ), "%.1f ms", frameMs ); ImGui::TextColored( HexColor( b3_colorSeaGreen ), "step %d", context->sample->m_stepCount ); @@ -1966,6 +1995,12 @@ static void DrawHud( SampleContext* context ) float fontSize = ImGui::GetFontSize(); DrawScreenStringFormat( 5, (int)( 1.5f * fontSize ), MakeColor( b3_colorYellow ), "%s : %s", entry.Category, entry.Name ); + + if ( context->pause ) + { + DrawScreenString( 5, (int)( 3.0f * fontSize ), MakeColor( b3_colorRed ), "****PAUSED****" ); + } + DrawScreenStringFormat( 5, context->camera.m_height - (int)( 1.5f * fontSize ), MakeColor( b3_colorSeaGreen ), "%.1f ms step %d", 1000.0f * (float)sapp_frame_duration(), context->sample->m_stepCount ); } diff --git a/samples/sample.h b/samples/sample.h index 74e2453..3281fd3 100644 --- a/samples/sample.h +++ b/samples/sample.h @@ -74,6 +74,16 @@ struct SampleContext bool showMetrics = false; bool openSamplePicker = false; + // Controls help window (Help > Controls, toggled with ?). Promoted to the + // context so the key handler can reach it. Seeded from newUser after Load. + bool showControls = false; + + // Deferred request from the Replay > Open menu. The native file dialog + // blocks on a nested run loop, so it must run outside the frame (top of + // OnFrame) rather than mid-frame inside the ImGui callback, which would + // re-enter the render loop. See OpenReplayFileDialog. + bool openReplayPicker = false; + // Render toggles fed into FrameInput each frame. They live here, not in // main.cpp, so the Render menu and the frame loop share one source. bool enableShadows = true; @@ -87,6 +97,10 @@ struct SampleContext int debugView = 0; int sampleIndex = 0; + + // No settings file found yet. The first run opens the replay viewer with the + // controls window up, so there is something to watch and a key to every action. + bool newUser = true; }; class Sample @@ -240,6 +254,11 @@ int RegisterReplay( const char* category, const char* name, SampleCreateFcn* fcn // by leaving the restart flag set while the new sample constructs. void SelectSample( SampleContext* context, int selection, bool restart ); +// Run the native "open replay" file picker and, on success, hand the chosen +// file to the Replay viewer. Must be called outside the frame (the dialog spins +// a blocking nested run loop), driven by SampleContext::openReplayPicker. +void OpenReplayFileDialog( SampleContext* context ); + // The single host UI callback: menu bar, sample picker, info panel, and the // bottom diagnostics drawer. void DrawUI( SampleContext* context ); diff --git a/samples/sample_collision.cpp b/samples/sample_collision.cpp index c96a0c1..34f1390 100644 --- a/samples/sample_collision.cpp +++ b/samples/sample_collision.cpp @@ -660,7 +660,7 @@ public: else if ( m_castType == e_sphereCast ) { DrawLine( point, head, MakeColor( color1 ) ); - //DrawWireSphere( transform, &sphere, 32, MakeColorAlpha( colors[i], 0.5f ) ); + // DrawWireSphere( transform, &sphere, 32, MakeColorAlpha( colors[i], 0.5f ) ); DrawSolidSphere( transform, sphere, MakeColorAlpha( colors[i], 0.5f ) ); } else if ( m_castType == e_capsuleCast ) @@ -1328,6 +1328,250 @@ public: static int sampleOverlapWorld = RegisterSample( "Collision", "Overlap World", OverlapWorld::Create ); +// Casts very long rays at a row of shapes to exercise the far-origin accuracy of the ray cast +// solvers. Each ray sweeps a small cone over time, so an accurate solver traces a smooth loop of +// hit points and normals even when the origin is kilometers away. +class LongRayCast : public Sample +{ +public: + enum + { + SHAPE_COUNT = 5, + TRAIL_COUNT = 180 + }; + + static Sample* Create( SampleContext* context ) + { + return new LongRayCast( context ); + } + + explicit LongRayCast( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( -35.0f, 22.0f, 34.0f, { 0.0f, 1.0f, 0.0f } ); + } + + b3World_SetGravity( m_worldId, b3Vec3_zero ); + + m_hull = b3CreateRock( 1.0f ); + m_mesh = b3CreateWaveMesh( 8, 8, 0.5f, 0.25f, 0.2f, 0.2f ); + + int hfCount = 9; + b3Vec3 hfScale = 0.5f * b3Vec3_one; + m_heightField = b3CreateWave( hfCount, hfCount, hfScale, 0.08f, 0.16f, false ); + + // Aim each ray at a point above its shape so the cone sweeps the hit across the surface. + float spacing = 5.0f; + float aimHeight = 2.5f; + for ( int i = 0; i < SHAPE_COUNT; ++i ) + { + float x = ( i - 2 ) * spacing; + m_targets[i] = { x, aimHeight, 0.0f }; + m_trailNext[i] = 0; + m_trailCount[i] = 0; + m_failRate[i] = 0.0f; + } + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_staticBody; + // bodyDef.position.y = 1.0f; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + // Sphere + bodyDef.position.x = m_targets[0].x; + { + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3Sphere sphere = { b3Vec3_zero, 1.0f }; + b3CreateSphereShape( body, &shapeDef, &sphere ); + } + + // Capsule along the x-axis + bodyDef.position.x = m_targets[1].x; + { + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3Capsule capsule = { { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, 0.7f }; + b3CreateCapsuleShape( body, &shapeDef, &capsule ); + } + + // Hull + bodyDef.position.x = m_targets[2].x; + { + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHullShape( body, &shapeDef, m_hull ); + } + + // Wave mesh, centered on its origin and facing up + bodyDef.position.x = m_targets[3].x; + { + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3CreateMeshShape( body, &shapeDef, m_mesh, b3Vec3_one ); + } + + // Height field grows from a corner, so offset the body to center the patch under the ray + { + float extentX = hfScale.x * ( hfCount - 1 ); + float extentZ = hfScale.z * ( hfCount - 1 ); + bodyDef.position = { m_targets[4].x - 0.5f * extentX, 0.0f, -0.5f * extentZ }; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3CreateHeightFieldShape( body, &shapeDef, m_heightField ); + } + + m_rayLengthKilometers = 1.0f; + m_coneAngle = 5.0f; + m_phase = 0.0f; + + memset( m_trail, 0, sizeof( m_trail ) ); + } + + ~LongRayCast() override + { + b3DestroyHull( m_hull ); + b3DestroyMesh( m_mesh ); + b3DestroyHeightField( m_heightField ); + } + + bool DrawControls() override + { + ImGui::SliderFloat( "Ray Length", &m_rayLengthKilometers, 1.0f, 10000.0f, "%.0f km", ImGuiSliderFlags_Logarithmic ); + ImGui::SliderFloat( "Cone Angle", &m_coneAngle, 0.0f, 12.0f, "%.1f deg" ); + return true; + } + + void Step() override + { + Sample::Step(); + + // Advance the cone so it completes one loop per trail buffer. + m_phase += 2.0f * B3_PI / float( TRAIL_COUNT ); + if ( m_phase > 2.0f * B3_PI ) + { + m_phase -= 2.0f * B3_PI; + } + + // Unit direction precessing on a small cone about the up axis. + float halfAngle = m_coneAngle * ( B3_PI / 180.0f ); + b3Vec3 tilted = b3RotateVector( b3MakeQuatFromAxisAngle( b3Vec3_axisX, halfAngle ), b3Vec3_axisY ); + b3Vec3 coneDir = b3RotateVector( b3MakeQuatFromAxisAngle( b3Vec3_axisY, m_phase ), tilted ); + + float reach = 5.0f; + float farDistance = 1000.0f * m_rayLengthKilometers; + b3QueryFilter filter = b3DefaultQueryFilter(); + + for ( int i = 0; i < SHAPE_COUNT; ++i ) + { + // The long ray under test and a short ray on the same line. The short ray is near + // enough to be accurate, so it is the ground truth: if it hits where the long ray + // misses, the miss is an accuracy failure, not the cone tilting off the shape. + CastHit truth = CastAlong( m_targets[i], coneDir, 50.0f, reach, filter ); + CastHit cast = CastAlong( m_targets[i], coneDir, farDistance, reach, filter ); + + float fail = 0.0f; + + if ( cast.hit ) + { + // Color the hit by how far it drifts from the ground truth. + float error = truth.hit ? b3Length( cast.point - truth.point ) : 0.0f; + b3HexColor color = error < 0.05f ? b3_colorGreen : b3_colorOrange; + + m_trail[i][m_trailNext[i]] = cast.point; + m_trailNext[i] = ( m_trailNext[i] + 1 ) % TRAIL_COUNT; + if ( m_trailCount[i] < TRAIL_COUNT ) + { + m_trailCount[i] += 1; + } + + DrawLine( b3OffsetPos( cast.point, b3MulSV( 3.0f, coneDir ) ), cast.point, MakeColor( b3_colorAqua ) ); + DrawLine( cast.point, b3OffsetPos( cast.point, b3MulSV( 1.5f, cast.normal ) ), MakeColor( b3_colorYellow ) ); + DrawPoint( cast.point, 8.0f, MakeColor( color ) ); + } + else if ( truth.hit ) + { + // Accuracy failure: the line does hit, but single precision lost it at distance. + // Mark where the hit should have been and slash the empty ray red. + fail = 1.0f; + b3Pos expected = truth.point; + DrawPoint( expected, 14.0f, MakeColor( b3_colorRed ) ); + DrawLine( b3OffsetPos( expected, b3MulSV( 2.0f, coneDir ) ), b3OffsetPos( expected, b3MulSV( -2.0f, coneDir ) ), + MakeColor( b3_colorRed ) ); + } + else + { + // Geometric miss: the cone tilted the ray off the shape. Not an accuracy problem. + b3Pos aim = m_targets[i]; + DrawLine( b3OffsetPos( aim, b3MulSV( 2.0f, coneDir ) ), b3OffsetPos( aim, b3MulSV( -4.0f, coneDir ) ), + MakeColorAlpha( b3_colorGray, 0.4f ) ); + } + + m_failRate[i] = 0.95f * m_failRate[i] + 0.05f * fail; + + // Fade the trail from oldest to newest so the loop reads as a path. + int start = ( m_trailNext[i] - m_trailCount[i] + TRAIL_COUNT ) % TRAIL_COUNT; + for ( int j = 0; j < m_trailCount[i]; ++j ) + { + int index = ( start + j ) % TRAIL_COUNT; + float alpha = float( j + 1 ) / float( m_trailCount[i] ); + DrawPoint( m_trail[i][index], 4.0f, MakeColorAlpha( b3_colorGreen, alpha ) ); + } + } + + DrawTextLine( "Long ray casts" ); + DrawTextLine( "Origin %.0f km. Green: accurate, Orange: drifting, Red: miss.", + m_rayLengthKilometers ); + DrawTextLine( "Failures: sphere %.0f%% capsule %.0f%% hull %.0f%% mesh %.0f%% hf %.0f%%", + 100.0f * m_failRate[0], 100.0f * m_failRate[1], 100.0f * m_failRate[2], 100.0f * m_failRate[3], + 100.0f * m_failRate[4] ); + } + + struct CastHit + { + b3Pos point; + b3Vec3 normal; + bool hit; + }; + + // Cast a ray that passes through the aim point along a cone direction, starting at the given + // distance above it. Returns the closest hit. + CastHit CastAlong( b3Pos aim, b3Vec3 coneDir, float distance, float reach, b3QueryFilter filter ) const + { + b3Pos origin = b3OffsetPos( aim, b3MulSV( distance, coneDir ) ); + b3Vec3 translation = b3MulSV( -( distance + reach ), coneDir ); + + CastContext context = {}; + context.fractions[0] = FLT_MAX; + context.fractions[1] = FLT_MAX; + context.fractions[2] = FLT_MAX; + b3World_CastRay( m_worldId, origin, translation, filter, RayCastClosestCallback, &context ); + + CastHit output = {}; + output.hit = context.count > 0; + if ( output.hit ) + { + output.point = context.points[0]; + output.normal = context.normals[0]; + } + return output; + } + + b3HullData* m_hull; + b3MeshData* m_mesh; + b3HeightFieldData* m_heightField; + + b3Pos m_targets[SHAPE_COUNT]; + b3Pos m_trail[SHAPE_COUNT][TRAIL_COUNT]; + int m_trailNext[SHAPE_COUNT]; + int m_trailCount[SHAPE_COUNT]; + float m_failRate[SHAPE_COUNT]; + + float m_rayLengthKilometers; + float m_coneAngle; + float m_phase; +}; + +static int sampleLongRayCast = RegisterSample( "Collision", "Long Ray Cast", LongRayCast::Create ); + class InitialOverlap : public Sample { public: diff --git a/samples/sample_replay.cpp b/samples/sample_replay.cpp index d30eaa5..cc8b3e1 100644 --- a/samples/sample_replay.cpp +++ b/samples/sample_replay.cpp @@ -253,10 +253,8 @@ public: m_camera->SetView( 30.0f, 22.0f, 14.0f, { 0.0f, 2.0f, 0.0f } ); } - // The timeline scrubber lives in the diagnostics drawer, so open it and start paused. m_prevShowMetrics = m_context->showMetrics; m_context->showMetrics = true; - m_context->pause = true; m_selectTimelineTab = true; // Z-up is a replay-only view choice and has no toggle elsewhere, so restore it on exit diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 3184204..d9cd14f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -234,7 +234,7 @@ install( ) install( - FILES ${BOX3D_API_FILES} + FILES ${BOX3D_INCLUDE_FILES} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/box3d ) @@ -242,7 +242,7 @@ include(CMakePackageConfigHelpers) write_basic_package_version_file( "${CMAKE_CURRENT_BINARY_DIR}/box3dConfigVersion.cmake" - VERSION ${BOX3D_VERSION} + VERSION ${PROJECT_VERSION} COMPATIBILITY SameMajorVersion ) diff --git a/src/capsule.c b/src/capsule.c index f9e4f29..cd3f363 100644 --- a/src/capsule.c +++ b/src/capsule.c @@ -81,27 +81,6 @@ b3AABB b3ComputeSweptCapsuleAABB( const b3Capsule* shape, b3Transform xf1, b3Tra 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; @@ -115,11 +94,12 @@ bool b3OverlapCapsule( const b3Capsule* shape, b3Transform shapeTransform, const 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 ) { + B3_ASSERT( b3IsValidRay( input ) ); + b3Vec3 c1 = shape->center1; b3Vec3 c2 = shape->center2; float r = shape->radius; @@ -127,127 +107,231 @@ b3CastOutput b3RayCastCapsule( const b3Capsule* shape, const b3RayCastInput* inp // Initialize result structure b3CastOutput output = { 0 }; - // Compute height and handle degenerate capsules - float height = b3Distance( c1, c2 ); - if ( height < 1000.0f * FLT_MIN ) + b3Vec3 d = b3Sub( c2, c1 ); + + // Fall back to sphere if the capsule is short + float tol = 0.01f * B3_LINEAR_SLOP; + float lengthSquared = b3LengthSquared( d ); + if ( lengthSquared < tol * tol ) { 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; + // Vector from first center to ray origin. + b3Vec3 s = b3Sub( input->origin, 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 ); + // Capsule axis + float length = sqrtf( lengthSquared ); + b3Vec3 axis = b3MulSV( 1.0f / length, d ); - // 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 ); + // Project ray origin onto capsule axis. + float u = b3Dot( s, axis ); - // Ray 2D translation length squared - float k1 = pq.x * pq.x + pq.z * pq.z; + // Closest point on infinite capsule axis, relative to c1. + b3Vec3 c = b3MulSV( u, axis ); - // Ray start point 2D separation squared from circle - float k3 = p.x * p.x + p.z * p.z - r * r; + // Vector from closest point to ray origin + b3Vec3 sc = b3Sub( s, c ); - // Parallel case (2D ray translation is zero) - if ( k1 < 1000.0f * FLT_MIN ) + // Squared distance from ray origin to capsule axis + float sc2 = b3LengthSquared( sc ); + + // Is the ray origin within the infinite cylinder along the capsule axis? + if ( sc2 < r * r ) { - if ( k3 > 0.0f ) - { - // Parallel and outside - return output; - } + // Clamped barycentric coordinate of ray origin projected onto capsule axis. + float uClamped = b3ClampFloat( u, 0.0f, length ); - if ( 0.0f <= p.y && p.y <= height ) + // The closest point on the bounded capsule segment, relative to c1. + b3Vec3 cp = b3MulSV( uClamped, axis ); + + // Vector from ray origin to closest point on segment. + b3Vec3 scp = b3Sub( s, cp ); + + // Squared distance of ray origin from capsule segment. + float scp2 = b3LengthSquared( scp ); + + // Is the ray origin within the capsule? + if ( scp2 < r * r ) { - // 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 ) + // The ray can hit an endcap. + b3Sphere sphere = { + .center = b3Add( c1, cp ), + .radius = r, + }; + + return b3RayCastSphere( &sphere, input ); + } + + // Ray axis. A zero length ray reaching here starts outside the capsule, so it misses. + // Same zero length convention as b3RayCastSphere. + b3Vec3 dr = input->translation; + float rayLength; + b3Vec3 rayAxis = b3GetLengthAndNormalize( &rayLength, dr ); + if ( rayLength == 0.0f ) + { + return output; + } + + // Barycentric coordinate of ray end point. + float v = u + input->maxFraction * b3Dot( dr, axis ); + + // Early out: does the projected ray fall outside the capsule? + if ( ( u < -r && v < -r ) || ( length + r < u && length + r < v ) ) + { + return output; + } + + // Compute the closest point between the ray segment and the capsule segment. + // See Real-Time Collision Detection, section 5.1.9 + + // Closest point on capsule : a1 = segment unit axis, t1 = unknown fraction + // p1 = t1 * a1 + + // Closet point on ray : a2 = ray unit axis, t2 = unknown fraction + // p2 = s + t2 * a2 + + // Closest point perpendicularity conditions. + // dot(p2 - p1, a1) = 0 + // dot(p2 - p1, a2) = 0 + + // Expand + // dot(t1 * a1 - s - t2 * a2, a1) = 0 + // dot(t1 * a1 - s - t2 * a2, a2) = 0 + + // Expand + // t1 - dot(s, a1) - t2 * dot(a1, a2) = 0 + // t1 * dot(a1, a2) - dot(s, a2) - t2 = 0 + + // Group : a12 = dot(a1, a2), sa1 = dot(s, a1), sa2 = dot(s, a2) + // t1 - a12 * t2 = sa1 + // a12 * t1 - t2 = sa2 + + // Solve + // https://en.wikipedia.org/wiki/Cramer%27s_rule + // I've flipped the signs of the numerator and denominator to give a positive determinant. + // det = 1 - a12 * a12 + // t1 = (sa1 - a12 * sa2) / det + // t2 = (a12 * sa1 - sa2) / det + + b3Vec3 a1 = axis; + b3Vec3 a2 = rayAxis; + float a12 = b3Dot( a1, a2 ); + + // Ray distance to the near intersection with the infinite cylinder. Length units. + float tr; + + float det = 1.0f - a12 * a12; + if ( det < FLT_EPSILON ) + { + // Ray nearly parallel to the capsule axis. The closest point solve below divides by det, + // so it loses all precision here and a slowly converging ray would be missed. Intersect the + // ray with the infinite cylinder directly using the components perpendicular to the axis. + // The origin is outside the cylinder, so a hit needs the ray to close in on it. + + // Instead of a cross product, subtract the parallel part to get a perpendicular vector. Non-dimensional. + b3Vec3 perp = b3MulSub( a2, a12, a1 ); + float perp2 = b3LengthSquared( perp ); + + // Project to origin to c1 vector onto the perpendicular vector. beta has length units. + float beta = b3Dot( sc, perp ); + + float gamma = sc2 - r * r; + + // Casting away from the axis, or the perpendicular gap never closes to the radius. + float disc = beta * beta - perp2 * gamma; + if ( beta >= 0.0f || disc < 0.0f ) { - output = b3CastRayAgainstCap( p, q, a, r, input->maxFraction ); - return b3TransformCapsuleResult( output, rotation, offset ); + return output; } - // Above cylinder and casting downwards - if ( p.y > height && pq.y < 0.0f ) + // Near root, written to dodge the (-beta - sqrt) cancellation as the ray nears parallel. + tr = gamma / ( -beta + sqrtf( disc ) ); + } + else + { + // Closest points between the infinite ray and the infinite capsule axis. + float invDet = 1.0f / det; + float sa1 = u; + float sa2 = b3Dot( s, a2 ); + + float t1 = ( sa1 - a12 * sa2 ) * invDet; + float t2 = ( a12 * sa1 - sa2 ) * invDet; + + // Closest points + b3Vec3 p1 = b3MulSV( t1, a1 ); + b3Vec3 p2 = b3MulAdd( s, t2, a2 ); + + // Vector from closest point on infinite capsule to infinite ray. + b3Vec3 g = b3Sub( p2, p1 ); + + float g2 = b3LengthSquared( g ); + if ( g2 > r * r ) { - output = b3CastRayAgainstCap( p, q, b, r, input->maxFraction ); - return b3TransformCapsuleResult( output, rotation, offset ); + // Early out: closest point on infinite ray is outside infinite cylinder. + return output; } - // Above or below and casting away from cylinder + // Intersect the infinite ray with the infinite cylinder. Like ray versus sphere this is done + // relative to the closest point to avoid round-off errors. Length units, not a fraction. + // https://en.wikipedia.org/wiki/Line-cylinder_intersection + float h = sqrtf( ( r * r - g2 ) * invDet ); + + tr = t2 - h; + } + + // Outside ray? + if ( tr < 0.0f || input->maxFraction * rayLength < tr ) + { return output; } - // Non-parallel case - float k2 = pq.x * p.x + pq.z * p.z; + // The corresponding distance on the capsule axis. Length units. + float tc = u + tr * a12; - float discriminant = k2 * k2 - k1 * k3; - if ( discriminant < 0.0f ) + // Outside c1 end? + if ( tc < 0.0f ) { - // No real roots - no intersection - return output; + // Ray cast sphere 1. + b3Sphere sphere = { + .center = c1, + .radius = r, + }; + + return b3RayCastSphere( &sphere, input ); } - float t = ( -k2 - sqrtf( discriminant ) ) / k1; - if ( t > input->maxFraction ) + // Outside c2 end? + if (length < tc) { - // Segment approaching cylinder, but not quite getting there. - return output; + // Ray cast sphere 2. + b3Sphere sphere = { + .center = c2, + .radius = r, + }; + + return b3RayCastSphere( &sphere, input ); } - // Don't skip t < 0. This means that we start in the *infinite* cylinder and still might hit a cap + // Hit point on capsule side, relative to c1. + b3Vec3 p = b3MulAdd( s, tr, rayAxis ); - // This is the point on the ray that hits the infinite cylinder - b3Vec3 c = b3MulAdd( p, t, pq ); + // Hit normal. + b3Vec3 normal = b3MulSub( p, tc, axis ); + normal = b3Normalize( normal ); - // 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.point = b3Add( c1, p ); + output.normal = normal; + output.fraction = b3ClampFloat( tr / rayLength, 0.0f, input->maxFraction ); output.hit = true; - - return b3TransformCapsuleResult( output, rotation, offset ); + return output; } b3CastOutput b3ShapeCastCapsule( const b3Capsule* capsule, const b3ShapeCastInput* input ) @@ -268,8 +352,7 @@ int b3CollideMoverAndCapsule( b3PlaneResult* result, const b3Capsule* shape, con { float totalRadius = mover->radius + shape->radius; - b3SegmentDistanceResult approach = - b3SegmentDistance( shape->center1, shape->center2, mover->center1, mover->center2 ); + b3SegmentDistanceResult approach = b3SegmentDistance( shape->center1, shape->center2, mover->center1, mover->center2 ); // The normal points from the shape toward the mover. float distance; diff --git a/src/core.c b/src/core.c index ff629db..d6a09b0 100644 --- a/src/core.c +++ b/src/core.c @@ -115,7 +115,7 @@ void b3Log( const char* format, ... ) b3Version b3GetVersion( void ) { - return (b3Version){ 0, 2, 0 }; + return (b3Version){ 0, 1, 0 }; } bool b3IsDoublePrecision( void ) diff --git a/test/test_shape.c b/test/test_shape.c index 743a666..db07f83 100644 --- a/test/test_shape.c +++ b/test/test_shape.c @@ -7,6 +7,7 @@ #include "box3d/math_functions.h" #include +#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 }; @@ -272,6 +273,547 @@ static int PointInShapeTest( void ) } #endif +// Shared assertions for a surface hit. The normal points outward toward the ray, +// the point sits on the surface, and the point lies on the ray at the reported fraction. +static int CheckCastHit( b3CastOutput out, b3Vec3 origin, b3Vec3 translation, b3Vec3 point, b3Vec3 normal, + float fraction, float tol ) +{ + ENSURE( out.hit ); + ENSURE_SMALL( out.fraction - fraction, tol ); + ENSURE_SMALL( out.point.x - point.x, tol ); + ENSURE_SMALL( out.point.y - point.y, tol ); + ENSURE_SMALL( out.point.z - point.z, tol ); + ENSURE_SMALL( out.normal.x - normal.x, tol ); + ENSURE_SMALL( out.normal.y - normal.y, tol ); + ENSURE_SMALL( out.normal.z - normal.z, tol ); + + b3Vec3 onRay = b3MulAdd( origin, out.fraction, translation ); + ENSURE_SMALL( b3Distance( out.point, onRay ), tol ); + return 0; +} + +// The shared initial overlap convention: a ray starting inside a solid reports the origin +// with zero fraction and no normal. +static int CheckInitialOverlap( b3CastOutput out, b3Vec3 origin ) +{ + ENSURE( out.hit ); + ENSURE( out.fraction == 0.0f ); + ENSURE_SMALL( b3Distance( out.point, origin ), FLT_EPSILON ); + ENSURE( out.normal.x == 0.0f && out.normal.y == 0.0f && out.normal.z == 0.0f ); + return 0; +} + +static int RayCastSphereHitTest( void ) +{ + b3Sphere s = { { 0.0f, 0.0f, 0.0f }, 1.0f }; + + // Hit along each principal axis. Surface at distance 3 over a length 8 ray. + { + b3RayCastInput input = { { -4.0f, 0.0f, 0.0f }, { 8.0f, 0.0f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastSphere( &s, &input ); + if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ -1.0f, 0.0f, 0.0f }, + ( b3Vec3 ){ -1.0f, 0.0f, 0.0f }, 3.0f / 8.0f, 1e-5f ) ) + return 1; + } + { + b3RayCastInput input = { { 0.0f, 4.0f, 0.0f }, { 0.0f, -8.0f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastSphere( &s, &input ); + if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ 0.0f, 1.0f, 0.0f }, + ( b3Vec3 ){ 0.0f, 1.0f, 0.0f }, 3.0f / 8.0f, 1e-5f ) ) + return 1; + } + { + b3RayCastInput input = { { 0.0f, 0.0f, -4.0f }, { 0.0f, 0.0f, 8.0f }, 1.0f }; + b3CastOutput out = b3RayCastSphere( &s, &input ); + if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ 0.0f, 0.0f, -1.0f }, + ( b3Vec3 ){ 0.0f, 0.0f, -1.0f }, 3.0f / 8.0f, 1e-5f ) ) + return 1; + } + + // Offset center, hit partway along the ray. + { + b3Sphere s2 = { { 5.0f, 0.0f, 0.0f }, 2.0f }; + b3RayCastInput input = { { 0.0f, 0.0f, 0.0f }, { 10.0f, 0.0f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastSphere( &s2, &input ); + if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ 3.0f, 0.0f, 0.0f }, + ( b3Vec3 ){ -1.0f, 0.0f, 0.0f }, 0.3f, 1e-5f ) ) + return 1; + } + + // Diagonal ray straight through the center. + { + float k = 0.70710678f; + b3RayCastInput input = { { -3.0f, -3.0f, 0.0f }, { 6.0f, 6.0f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastSphere( &s, &input ); + if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ -k, -k, 0.0f }, + ( b3Vec3 ){ -k, -k, 0.0f }, 0.382149f, 1e-4f ) ) + return 1; + } + + return 0; +} + +static int RayCastSphereMissTest( void ) +{ + b3Sphere s = { { 0.0f, 0.0f, 0.0f }, 1.0f }; + + // Pointing away. + { + b3RayCastInput input = { { -4.0f, 0.0f, 0.0f }, { -8.0f, 0.0f, 0.0f }, 1.0f }; + ENSURE( b3RayCastSphere( &s, &input ).hit == false ); + } + // Passes wide of the sphere. + { + b3RayCastInput input = { { -4.0f, 3.0f, 0.0f }, { 8.0f, 0.0f, 0.0f }, 1.0f }; + ENSURE( b3RayCastSphere( &s, &input ).hit == false ); + } + // Aimed at the sphere but the translation stops short. + { + b3RayCastInput input = { { -4.0f, 0.0f, 0.0f }, { 8.0f, 0.0f, 0.0f }, 0.3f }; + ENSURE( b3RayCastSphere( &s, &input ).hit == false ); + } + return 0; +} + +static int RayCastSphereClipTest( void ) +{ + b3Sphere s = { { 0.0f, 0.0f, 0.0f }, 1.0f }; + + // The surface is reached at fraction 3/8. Straddle it with maxFraction. + { + b3RayCastInput input = { { -4.0f, 0.0f, 0.0f }, { 8.0f, 0.0f, 0.0f }, 0.374f }; + ENSURE( b3RayCastSphere( &s, &input ).hit == false ); + } + { + b3RayCastInput input = { { -4.0f, 0.0f, 0.0f }, { 8.0f, 0.0f, 0.0f }, 0.376f }; + b3CastOutput out = b3RayCastSphere( &s, &input ); + ENSURE( out.hit ); + ENSURE_SMALL( out.fraction - 3.0f / 8.0f, 1e-5f ); + } + return 0; +} + +static int RayCastSphereInteriorTest( void ) +{ + b3Sphere s = { { 0.0f, 0.0f, 0.0f }, 1.0f }; + + // Origin inside reports the origin with zero fraction. + { + b3RayCastInput input = { { 0.3f, 0.0f, 0.0f }, { 8.0f, 0.0f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastSphere( &s, &input ); + ENSURE( out.hit ); + ENSURE( out.fraction == 0.0f ); + ENSURE_SMALL( b3Distance( out.point, input.origin ), FLT_EPSILON ); + } + // Zero length ray inside. + { + b3RayCastInput input = { { 0.5f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastSphere( &s, &input ); + ENSURE( out.hit ); + ENSURE_SMALL( b3Distance( out.point, input.origin ), FLT_EPSILON ); + } + // Zero length ray outside. + { + b3RayCastInput input = { { 3.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, 1.0f }; + ENSURE( b3RayCastSphere( &s, &input ).hit == false ); + } + return 0; +} + +static int RayCastSphereGrazeTest( void ) +{ + b3Sphere s = { { 0.0f, 0.0f, 0.0f }, 1.0f }; + + // Just inside the radius grazes a hit, just outside misses. + { + b3RayCastInput input = { { -4.0f, 0.999f, 0.0f }, { 8.0f, 0.0f, 0.0f }, 1.0f }; + ENSURE( b3RayCastSphere( &s, &input ).hit ); + } + { + b3RayCastInput input = { { -4.0f, 1.001f, 0.0f }, { 8.0f, 0.0f, 0.0f }, 1.0f }; + ENSURE( b3RayCastSphere( &s, &input ).hit == false ); + } + return 0; +} + +// Capsule along x from -2 to 2, radius 1. Reused by the capsule ray cast subtests. +static const b3Capsule rayCapsule = { { -2.0f, 0.0f, 0.0f }, { 2.0f, 0.0f, 0.0f }, 1.0f }; + +static int RayCastCapsuleSideTest( void ) +{ + // Perpendicular hit on the cylindrical side. Surface at distance 2 over a length 6 ray. + { + b3RayCastInput input = { { 0.0f, 3.0f, 0.0f }, { 0.0f, -6.0f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input ); + if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ 0.0f, 1.0f, 0.0f }, + ( b3Vec3 ){ 0.0f, 1.0f, 0.0f }, 1.0f / 3.0f, 1e-5f ) ) + return 1; + } + // Same from +z to exercise the other transverse direction. + { + b3RayCastInput input = { { 0.0f, 0.0f, 3.0f }, { 0.0f, 0.0f, -6.0f }, 1.0f }; + b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input ); + if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ 0.0f, 0.0f, 1.0f }, + ( b3Vec3 ){ 0.0f, 0.0f, 1.0f }, 1.0f / 3.0f, 1e-5f ) ) + return 1; + } + // Side hit nearer the c1 end. + { + b3RayCastInput input = { { -1.0f, 3.0f, 0.0f }, { 0.0f, -6.0f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input ); + if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ -1.0f, 1.0f, 0.0f }, + ( b3Vec3 ){ 0.0f, 1.0f, 0.0f }, 1.0f / 3.0f, 1e-5f ) ) + return 1; + } + return 0; +} + +static int RayCastCapsuleObliqueTest( void ) +{ + // Oblique ray in the z=0 plane. It crosses y=1 inside the cylinder span, so the + // normal stays transverse. Exercises the non perpendicular ray/axis solve where + // dot(axis, rayAxis) != 0. + b3RayCastInput input = { { -3.0f, 3.0f, 0.0f }, { 4.0f, -4.0f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input ); + return CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ -1.0f, 1.0f, 0.0f }, + ( b3Vec3 ){ 0.0f, 1.0f, 0.0f }, 0.5f, 1e-4f ); +} + +static int RayCastCapsuleCapTest( void ) +{ + float k = 0.70710678f; + + // Collinear ray hits the c2 hemisphere from beyond the end. + { + b3RayCastInput input = { { 5.0f, 0.0f, 0.0f }, { -8.0f, 0.0f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input ); + if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ 3.0f, 0.0f, 0.0f }, + ( b3Vec3 ){ 1.0f, 0.0f, 0.0f }, 1.0f / 4.0f, 1e-5f ) ) + return 1; + } + // Off-axis ray through the c2 cap center, approaching from outside the cylinder. + { + b3RayCastInput input = { { 4.0f, 2.0f, 0.0f }, { -4.0f, -4.0f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input ); + if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ 2.0f + k, k, 0.0f }, + ( b3Vec3 ){ k, k, 0.0f }, 0.323223f, 1e-4f ) ) + return 1; + } + // Mirror through the c1 cap center. + { + b3RayCastInput input = { { -4.0f, 2.0f, 0.0f }, { 4.0f, -4.0f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input ); + if ( CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ -2.0f - k, k, 0.0f }, + ( b3Vec3 ){ -k, k, 0.0f }, 0.323223f, 1e-4f ) ) + return 1; + } + return 0; +} + +static int RayCastCapsuleMissTest( void ) +{ + // Pointing away. + { + b3RayCastInput input = { { 0.0f, 3.0f, 0.0f }, { 0.0f, 4.0f, 0.0f }, 1.0f }; + ENSURE( b3RayCastCapsule( &rayCapsule, &input ).hit == false ); + } + // Crosses above the axis more than a radius away. + { + b3RayCastInput input = { { 0.0f, 4.0f, 2.0f }, { 0.0f, -8.0f, 0.0f }, 1.0f }; + ENSURE( b3RayCastCapsule( &rayCapsule, &input ).hit == false ); + } + // Aimed at the side but the translation stops short. + { + b3RayCastInput input = { { 0.0f, 5.0f, 0.0f }, { 0.0f, -1.0f, 0.0f }, 1.0f }; + ENSURE( b3RayCastCapsule( &rayCapsule, &input ).hit == false ); + } + // Parallel to the axis and outside the cylinder. + { + b3RayCastInput input = { { 0.0f, 3.0f, 0.0f }, { 8.0f, 0.0f, 0.0f }, 1.0f }; + ENSURE( b3RayCastCapsule( &rayCapsule, &input ).hit == false ); + } + // Descends past the rounded c2 end, beyond cap reach. + { + b3RayCastInput input = { { 4.0f, 3.0f, 0.0f }, { 0.0f, -6.0f, 0.0f }, 1.0f }; + ENSURE( b3RayCastCapsule( &rayCapsule, &input ).hit == false ); + } + return 0; +} + +static int RayCastCapsuleInteriorTest( void ) +{ + // Origin on the axis between the caps. + { + b3RayCastInput input = { { 0.0f, 0.0f, 0.0f }, { 0.0f, -5.0f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input ); + ENSURE( out.hit ); + ENSURE( out.fraction == 0.0f ); + ENSURE_SMALL( b3Distance( out.point, input.origin ), FLT_EPSILON ); + } + // Origin inside the c2 hemisphere, past the cylinder end. + { + b3RayCastInput input = { { 2.5f, 0.0f, 0.0f }, { 0.0f, 0.0f, 5.0f }, 1.0f }; + b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input ); + ENSURE( out.hit ); + ENSURE( out.fraction == 0.0f ); + ENSURE_SMALL( b3Distance( out.point, input.origin ), FLT_EPSILON ); + } + // Zero length ray inside. + { + b3RayCastInput input = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input ); + ENSURE( out.hit ); + ENSURE_SMALL( b3Distance( out.point, input.origin ), FLT_EPSILON ); + } + // Zero length ray outside. + { + b3RayCastInput input = { { 0.0f, 3.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, 1.0f }; + ENSURE( b3RayCastCapsule( &rayCapsule, &input ).hit == false ); + } + return 0; +} + +static int RayCastCapsuleDegenerateTest( void ) +{ + // Coincident centers collapse to a sphere. + b3Capsule c = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, 1.0f }; + b3RayCastInput input = { { -4.0f, 0.0f, 0.0f }, { 8.0f, 0.0f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastCapsule( &c, &input ); + return CheckCastHit( out, input.origin, input.translation, ( b3Vec3 ){ -1.0f, 0.0f, 0.0f }, + ( b3Vec3 ){ -1.0f, 0.0f, 0.0f }, 3.0f / 8.0f, 1e-5f ); +} + +static int RayCastCapsuleClipTest( void ) +{ + // The side hit occurs at fraction 1/3. Straddle it with maxFraction. + { + b3RayCastInput input = { { 0.0f, 3.0f, 0.0f }, { 0.0f, -6.0f, 0.0f }, 0.3f }; + ENSURE( b3RayCastCapsule( &rayCapsule, &input ).hit == false ); + } + { + b3RayCastInput input = { { 0.0f, 3.0f, 0.0f }, { 0.0f, -6.0f, 0.0f }, 0.5f }; + b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input ); + ENSURE( out.hit ); + ENSURE_SMALL( out.fraction - 1.0f / 3.0f, 1e-5f ); + } + return 0; +} + +// A ray within a hair of the capsule axis must still hit when it slowly converges onto the +// surface. The closest point solver is ill conditioned in this band, so this guards the near +// parallel fallback that intersects the infinite cylinder directly. +static int RayCastCapsuleParallelTest( void ) +{ + // Capsule along y. A long ray almost parallel to the axis drifts inward from just outside the + // cylinder and dips through the far endcap. The naive solve loses this hit to a determinant of zero. + b3Capsule axisY = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 10.0f, 0.0f }, 1.0f }; + { + b3RayCastInput input = { { 1.0001f, 100.0f, 0.0f }, { -0.001f, -200.0f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastCapsule( &axisY, &input ); + ENSURE( out.hit ); + + // The hit lands on the capsule surface and on the ray. + b3Vec3 onSeg = b3PointToSegmentDistance( axisY.center1, axisY.center2, out.point ); + ENSURE_SMALL( b3Distance( out.point, onSeg ) - axisY.radius, 1e-3f ); + b3Vec3 onRay = b3MulAdd( input.origin, out.fraction, input.translation ); + ENSURE_SMALL( b3Distance( out.point, onRay ), 1e-3f ); + } + + // Near parallel ray converging onto the x-axis capsule from far away. + { + b3RayCastInput input = { { -1000.0f, 1.0001f, 0.0f }, { 2000.0f, -0.001f, 0.0f }, 1.0f }; + b3CastOutput out = b3RayCastCapsule( &rayCapsule, &input ); + ENSURE( out.hit ); + b3Vec3 onSeg = b3PointToSegmentDistance( rayCapsule.center1, rayCapsule.center2, out.point ); + ENSURE_SMALL( b3Distance( out.point, onSeg ) - rayCapsule.radius, 1e-3f ); + } + + // Exactly parallel and outside the cylinder still misses. + { + b3RayCastInput input = { { 0.0f, 3.0f, 0.0f }, { 8.0f, 0.0f, 0.0f }, 1.0f }; + ENSURE( b3RayCastCapsule( &rayCapsule, &input ).hit == false ); + } + + return 0; +} + +// Zero length rays and initial overlap behave the same across the solid shapes. A moving ray +// and a zero length ray that both start inside report the origin with zero fraction, and a zero +// length ray that starts outside misses. +static int RayCastOverlapConventionTest( void ) +{ + b3Vec3 zero = { 0.0f, 0.0f, 0.0f }; + b3Vec3 ray = { 8.0f, 0.0f, 0.0f }; + + // Sphere + { + b3Sphere s = { { 0.0f, 0.0f, 0.0f }, 1.0f }; + b3Vec3 inside = { 0.2f, 0.0f, 0.0f }; + b3Vec3 outside = { 3.0f, 0.0f, 0.0f }; + b3RayCastInput moving = { inside, ray, 1.0f }; + b3RayCastInput pointInside = { inside, zero, 1.0f }; + b3RayCastInput pointOutside = { outside, zero, 1.0f }; + if ( CheckInitialOverlap( b3RayCastSphere( &s, &moving ), inside ) ) + return 1; + if ( CheckInitialOverlap( b3RayCastSphere( &s, &pointInside ), inside ) ) + return 1; + ENSURE( b3RayCastSphere( &s, &pointOutside ).hit == false ); + } + + // Capsule + { + b3Vec3 inside = { 0.0f, 0.0f, 0.0f }; + b3Vec3 outside = { 0.0f, 3.0f, 0.0f }; + b3RayCastInput moving = { inside, ray, 1.0f }; + b3RayCastInput pointInside = { inside, zero, 1.0f }; + b3RayCastInput pointOutside = { outside, zero, 1.0f }; + if ( CheckInitialOverlap( b3RayCastCapsule( &rayCapsule, &moving ), inside ) ) + return 1; + if ( CheckInitialOverlap( b3RayCastCapsule( &rayCapsule, &pointInside ), inside ) ) + return 1; + ENSURE( b3RayCastCapsule( &rayCapsule, &pointOutside ).hit == false ); + } + + // Hull + { + b3Vec3 inside = { 0.3f, 0.2f, 0.1f }; + b3Vec3 outside = { 3.0f, 0.0f, 0.0f }; + b3RayCastInput moving = { inside, ray, 1.0f }; + b3RayCastInput pointInside = { inside, zero, 1.0f }; + b3RayCastInput pointOutside = { outside, zero, 1.0f }; + if ( CheckInitialOverlap( b3RayCastHull( &box.base, &moving ), inside ) ) + return 1; + if ( CheckInitialOverlap( b3RayCastHull( &box.base, &pointInside ), inside ) ) + return 1; + ENSURE( b3RayCastHull( &box.base, &pointOutside ).hit == false ); + } + + return 0; +} + +// Distance, in double precision, from a single precision hit point to the analytic first +// ray/sphere intersection of the same float ray. Isolates the single precision method error: +// the reference carries no float rounding, so what remains is purely what the method lost. +static double SphereHitError( b3Sphere shape, b3RayCastInput input, b3Vec3 point ) +{ + double r = shape.radius; + double sx = (double)input.origin.x - shape.center.x; + double sy = (double)input.origin.y - shape.center.y; + double sz = (double)input.origin.z - shape.center.z; + double tx = input.translation.x, ty = input.translation.y, tz = input.translation.z; + double len = sqrt( tx * tx + ty * ty + tz * tz ); + double dx = tx / len, dy = ty / len, dz = tz / len; + double b = sx * dx + sy * dy + sz * dz; + double c = sx * sx + sy * sy + sz * sz - r * r; + double t = -b - sqrt( b * b - c ); + double ex = point.x - ( input.origin.x + t * dx ); + double ey = point.y - ( input.origin.y + t * dy ); + double ez = point.z - ( input.origin.z + t * dz ); + return sqrt( ex * ex + ey * ey + ez * ez ); +} + +// Same idea for the ray/infinite-cylinder intersection, used where the hit lands on the side. +static double CapsuleHitError( b3Capsule shape, b3RayCastInput input, b3Vec3 point ) +{ + double ax = (double)shape.center2.x - shape.center1.x; + double ay = (double)shape.center2.y - shape.center1.y; + double az = (double)shape.center2.z - shape.center1.z; + double alen = sqrt( ax * ax + ay * ay + az * az ); + ax /= alen, ay /= alen, az /= alen; + + double sx = (double)input.origin.x - shape.center1.x; + double sy = (double)input.origin.y - shape.center1.y; + double sz = (double)input.origin.z - shape.center1.z; + double tx = input.translation.x, ty = input.translation.y, tz = input.translation.z; + double tlen = sqrt( tx * tx + ty * ty + tz * tz ); + double dx = tx / tlen, dy = ty / tlen, dz = tz / tlen; + + double sa = sx * ax + sy * ay + sz * az; + double da = dx * ax + dy * ay + dz * az; + double spx = sx - sa * ax, spy = sy - sa * ay, spz = sz - sa * az; + double dpx = dx - da * ax, dpy = dy - da * ay, dpz = dz - da * az; + double A = dpx * dpx + dpy * dpy + dpz * dpz; + double B = 2.0 * ( spx * dpx + spy * dpy + spz * dpz ); + double r = shape.radius; + double C = spx * spx + spy * spy + spz * spz - r * r; + double tau = ( -B - sqrt( B * B - 4.0 * A * C ) ) / ( 2.0 * A ); + double ex = point.x - ( input.origin.x + tau * dx ); + double ey = point.y - ( input.origin.y + tau * dy ); + double ez = point.z - ( input.origin.z + tau * dz ); + return sqrt( ex * ex + ey * ey + ez * ez ); +} + +// A miss is the worst possible outcome, so fold it into the error as a large sentinel. +#define RAY_MISS 1.0e30 + +static int RayCastFarOriginTest( void ) +{ + b3Sphere s = { { 0.0f, 0.0f, 0.0f }, 1.0f }; + b3Capsule c = { { -2.0f, 0.0f, 0.0f }, { 2.0f, 0.0f, 0.0f }, 1.0f }; + + // (0,0,1) lies on the unit sphere and on the capsule side. The ray dives in from a far origin + // along H + D*u for a fan of directions u skewed off the surface normal, so the capsule solve + // sees a real perpendicular gap rather than a free exact cancellation. + b3Vec3 h = { 0.0f, 0.0f, 1.0f }; + float offsets[] = { -0.7f, 0.0f, 0.7f }; + float distances[] = { 1e1f, 1e2f, 1e3f, 1e4f, 1e5f, 1e6f, 1e7f }; + + double worstSphere[ARRAY_COUNT( distances )]; + double worstCapsule[ARRAY_COUNT( distances )]; + + printf( " worst hit point error over a fan of skew rays, by origin distance:\n" ); + printf( " %-9s %-13s %-13s\n", "distance", "sphere", "capsule" ); + for ( int i = 0; i < ARRAY_COUNT( distances ); ++i ) + { + float d = distances[i]; + double maxS = 0.0, maxC = 0.0; + + for ( int ia = 0; ia < ARRAY_COUNT( offsets ); ++ia ) + { + for ( int ib = 0; ib < ARRAY_COUNT( offsets ); ++ib ) + { + b3Vec3 u = b3Normalize( ( b3Vec3 ){ offsets[ia], offsets[ib], 1.0f } ); + b3Vec3 origin = b3MulAdd( h, d, u ); + b3Vec3 translation = b3MulSV( -2.0f * d, u ); + b3RayCastInput input = { origin, translation, 1.0f }; + + b3CastOutput os = b3RayCastSphere( &s, &input ); + b3CastOutput oc = b3RayCastCapsule( &c, &input ); + + double errS = os.hit ? SphereHitError( s, input, os.point ) : RAY_MISS; + double errC = oc.hit ? CapsuleHitError( c, input, oc.point ) : RAY_MISS; + + maxS = errS > maxS ? errS : maxS; + maxC = errC > maxC ? errC : maxC; + } + } + + worstSphere[i] = maxS; + worstCapsule[i] = maxC; + printf( " %-9.0e %-13.3e %-13.3e\n", d, maxS, maxC ); + } + + // The closest point formulation keeps the error at the single precision floor: it grows only + // linearly with origin distance, error ~ distance * FLT_EPSILON, with no catastrophic loss. This + // holds out to a million units. At ten million the origin coordinates carry a meter sized ULP, + // larger than the unit radius, so the ray genuinely drops the hit. That row is printed for insight + // but left unasserted rather than baking in the breakdown. + for ( int i = 0; i < ARRAY_COUNT( distances ); ++i ) + { + if ( distances[i] < 1.0e7f ) + { + double floor = 16.0 * distances[i] * FLT_EPSILON + 2.0e-6; + ENSURE( worstSphere[i] < floor ); + ENSURE( worstCapsule[i] < floor ); + } + } + + // Still a clean sub-meter hit at a million units out. + ENSURE( worstSphere[5] < 0.5 && worstCapsule[5] < 0.5 ); + + return 0; +} + static int RayCastShapeTest( void ) { b3RayCastInput input = { @@ -319,5 +861,23 @@ int ShapeTest( void ) // RUN_SUBTEST( PointInShapeTest ); RUN_SUBTEST( RayCastShapeTest ); + RUN_SUBTEST( RayCastSphereHitTest ); + RUN_SUBTEST( RayCastSphereMissTest ); + RUN_SUBTEST( RayCastSphereClipTest ); + RUN_SUBTEST( RayCastSphereInteriorTest ); + RUN_SUBTEST( RayCastSphereGrazeTest ); + + RUN_SUBTEST( RayCastCapsuleSideTest ); + RUN_SUBTEST( RayCastCapsuleObliqueTest ); + RUN_SUBTEST( RayCastCapsuleCapTest ); + RUN_SUBTEST( RayCastCapsuleMissTest ); + RUN_SUBTEST( RayCastCapsuleInteriorTest ); + RUN_SUBTEST( RayCastCapsuleDegenerateTest ); + RUN_SUBTEST( RayCastCapsuleClipTest ); + RUN_SUBTEST( RayCastCapsuleParallelTest ); + + RUN_SUBTEST( RayCastOverlapConventionTest ); + RUN_SUBTEST( RayCastFarOriginTest ); + return 0; }