initial commit

This commit is contained in:
Erin Catto 2026-05-10 13:36:52 -07:00
commit 573e1a9fa3
220 changed files with 150440 additions and 0 deletions

149
samples/CMakeLists.txt Normal file
View file

@ -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}")

330
samples/camera.cpp Normal file
View file

@ -0,0 +1,330 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#include "camera.h"
#include <glad/glad.h>
// prevent clang format sorting glad.h with glfw3.h
#include <GLFW/glfw3.h>
// ImGui
#include <imgui.h>
#include <imgui_internal.h>
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;
}

85
samples/camera.h Normal file
View file

@ -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;
};

820
samples/earcut.h Normal file
View file

@ -0,0 +1,820 @@
#pragma once
#include <algorithm>
#include <cassert>
#include <cmath>
#include <memory>
#include <vector>
namespace mapbox {
namespace util {
template <std::size_t I, typename T> struct nth {
inline static typename std::tuple_element<I, T>::type
get(const T& t) { return std::get<I>(t); };
};
}
namespace detail {
template <typename N = uint32_t>
class Earcut {
public:
std::vector<N> indices;
std::size_t vertices = 0;
template <typename Polygon>
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 <typename Ring> 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 <typename Polygon> 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 <typename Point> 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 <typename T, typename Alloc = std::allocator<T>>
class ObjectPool {
public:
ObjectPool() { }
ObjectPool(std::size_t blockSize_) {
reset(blockSize_);
}
~ObjectPool() {
clear();
}
template <typename... Args>
T* construct(Args&&... args) {
if (currentIndex >= blockSize) {
currentBlock = alloc_traits::allocate(alloc, blockSize);
allocations.emplace_back(currentBlock);
currentIndex = 0;
}
T* object = &currentBlock[currentIndex++];
alloc_traits::construct(alloc, object, std::forward<Args>(args)...);
return object;
}
void reset(std::size_t newBlockSize) {
for (auto allocation : allocations) {
alloc_traits::deallocate(alloc, allocation, blockSize);
}
allocations.clear();
blockSize = std::max<std::size_t>(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<T*> allocations;
Alloc alloc;
typedef typename std::allocator_traits<Alloc> alloc_traits;
};
ObjectPool<Node> nodes;
};
template <typename N> template <typename Polygon>
void Earcut<N>::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<int>(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<double>(minX, x);
minY = std::min<double>(minY, y);
maxX = std::max<double>(maxX, x);
maxY = std::max<double>(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<double>(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 <typename N> template <typename Ring>
typename Earcut<N>::Node*
Earcut<N>::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 N>
typename Earcut<N>::Node*
Earcut<N>::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 <typename N>
void Earcut<N>::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 <typename N>
bool Earcut<N>::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 <typename N>
bool Earcut<N>::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<double>(a->x, std::min<double>(b->x, c->x));
const double minTY = std::min<double>(a->y, std::min<double>(b->y, c->y));
const double maxTX = std::max<double>(a->x, std::max<double>(b->x, c->x));
const double maxTY = std::max<double>(a->y, std::max<double>(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 N>
typename Earcut<N>::Node*
Earcut<N>::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 <typename N>
void Earcut<N>::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 <typename N> template <typename Polygon>
typename Earcut<N>::Node*
Earcut<N>::eliminateHoles(const Polygon& points, Node* outerNode) {
const size_t len = points.size();
std::vector<Node*> 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 N>
typename Earcut<N>::Node*
Earcut<N>::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 N>
typename Earcut<N>::Node*
Earcut<N>::findHoleBridge(Node* hole, Node* outerNode) {
Node* p = outerNode;
double hx = hole->x;
double hy = hole->y;
double qx = -std::numeric_limits<double>::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<double>::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 <typename N>
bool Earcut<N>::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 <typename N>
void Earcut<N>::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 N>
typename Earcut<N>::Node*
Earcut<N>::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 <typename N>
int32_t Earcut<N>::zOrder(const double x_, const double y_) {
// coords are transformed into non-negative 15-bit integer range
int32_t x = static_cast<int32_t>(32767.0 * (x_ - minX) * inv_size);
int32_t y = static_cast<int32_t>(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 N>
typename Earcut<N>::Node*
Earcut<N>::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 <typename N>
bool Earcut<N>::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 <typename N>
bool Earcut<N>::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 <typename N>
double Earcut<N>::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 <typename N>
bool Earcut<N>::equals(const Node* p1, const Node* p2) {
return p1->x == p2->x && p1->y == p2->y;
}
// check if two segments intersect
template <typename N>
bool Earcut<N>::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 <typename N>
bool Earcut<N>::onSegment(const Node* p, const Node* q, const Node* r) {
return q->x <= std::max<double>(p->x, r->x) &&
q->x >= std::min<double>(p->x, r->x) &&
q->y <= std::max<double>(p->y, r->y) &&
q->y >= std::min<double>(p->y, r->y);
}
template <typename N>
int Earcut<N>::sign(double val) {
return (0.0 < val) - (val < 0.0);
}
// check if a polygon diagonal intersects any polygon segments
template <typename N>
bool Earcut<N>::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 <typename N>
bool Earcut<N>::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 <typename N>
bool Earcut<N>::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 N>
typename Earcut<N>::Node*
Earcut<N>::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 <typename N> template <typename Point>
typename Earcut<N>::Node*
Earcut<N>::insertNode(std::size_t i, const Point& pt, Node* last) {
Node* p = nodes.construct(static_cast<N>(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 <typename N>
void Earcut<N>::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 <typename N = uint32_t, typename Polygon>
std::vector<N> earcut(const Polygon& poly) {
mapbox::detail::Earcut<N> earcut;
earcut(poly);
return std::move(earcut.indices);
}
}

276
samples/font.cpp Normal file
View file

@ -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 <stdio.h>
#include <vector>
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;
}

51
samples/font.h Normal file
View file

@ -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 <vector>
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<Vertex> m_vertices;
unsigned int m_textureId;
uint32_t m_vaoId;
uint32_t m_vboId;
uint32_t m_programId;
};

150
samples/geo_buffer.cpp Normal file
View file

@ -0,0 +1,150 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#include "geo_buffer.h"
#include <glad/glad.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
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;
}

17
samples/geo_buffer.h Normal file
View file

@ -0,0 +1,17 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include <stdint.h>
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);

156
samples/imconfig.h Normal file
View file

@ -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);
}
*/

471
samples/jsmn.h Normal file
View file

@ -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 <stddef.h>
#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 */

356
samples/main.cpp Normal file
View file

@ -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 <crtdbg.h>
#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 <stdio.h>
#ifdef TRACY_ENABLE
#include <client/TracyProfiler.hpp>
#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;
}

172
samples/mesh_loader.cpp Normal file
View file

@ -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 <iostream>
// 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<tinyobj::shape_t>& shapes = reader.GetShapes();
// const std::vector<tinyobj::material_t>& 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<tinyobj::shape_t>& shapes = reader.GetShapes();
// const std::vector<tinyobj::material_t>& 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;
}

21
samples/mesh_loader.h Normal file
View file

@ -0,0 +1,21 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "box3d/math_functions.h"
#include <vector>
struct b3MeshData;
b3MeshData* CreateMeshData( const char* path, float scale, bool zUp, bool useMedianSplit, bool identifyConvexEdges,
bool weldVertices );
struct TempMesh
{
std::vector<b3Vec3> vertices;
std::vector<int> indices;
std::vector<uint8_t> materialIndices;
};
void LoadTempMesh( const char* path, TempMesh* tempMesh, float scale, bool zUp );

783
samples/renderer.cpp Normal file
View file

@ -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 <glad/glad.h>
#include <GLFW/glfw3.h>
// clang-format on
#include "box3d/box3d.h"
#include <algorithm>
#include <assert.h>
#include <stdarg.h>
#include <string.h>
#include <vector>
struct PointData
{
b3Vec3 position;
float size;
RGBA8 rgba;
};
struct PointDraw
{
enum
{
e_batchSize = 2048
};
std::vector<PointData> 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<LinePoint> 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<SampleContext*>( 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<DebugShape*>( 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 );
}

44
samples/renderer.h Normal file
View file

@ -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 );

1757
samples/sample.cpp Normal file

File diff suppressed because it is too large Load diff

215
samples/sample.h Normal file
View file

@ -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;
};

1468
samples/sample_benchmark.cpp Normal file

File diff suppressed because it is too large Load diff

965
samples/sample_bodies.cpp Normal file
View file

@ -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 );

View file

@ -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 <glad/glad.h>
// prevent clang format sorting glad.h with glfw3.h
#include <GLFW/glfw3.h>
#include <imgui.h>
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<CapsulePlane*>( 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 );

2821
samples/sample_collision.cpp Normal file

File diff suppressed because it is too large Load diff

800
samples/sample_compound.cpp Normal file
View file

@ -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 <imgui.h>
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 );

File diff suppressed because it is too large Load diff

View file

@ -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 <stdio.h>
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 );

918
samples/sample_events.cpp Normal file
View file

@ -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 <assert.h>
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 );

651
samples/sample_geometry.cpp Normal file
View file

@ -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 <imgui.h>
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 );

401
samples/sample_issues.cpp Normal file
View file

@ -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 <vector>
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<b3MeshData*> 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 );

2784
samples/sample_joint.cpp Normal file

File diff suppressed because it is too large Load diff

940
samples/sample_manifold.cpp Normal file
View file

@ -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 <imgui.h>
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<b3Vec3*>( 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 );

1523
samples/sample_mesh.cpp Normal file

File diff suppressed because it is too large Load diff

484
samples/sample_ragdoll.cpp Normal file
View file

@ -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

View file

@ -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 <imgui.h>
#include <stdlib.h>
// 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 );

1145
samples/sample_shapes.cpp Normal file

File diff suppressed because it is too large Load diff

955
samples/sample_stacking.cpp Normal file
View file

@ -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 );

848
samples/sample_tree.cpp Normal file
View file

@ -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 <queue>
#include <stdio.h>
#include <unordered_map>
#include <vector>
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 <immintrin.h>
// 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<TreeBenchmark*>( 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<TreeBenchmark*>( 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<TreeBenchmark*>( 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<uint64_t, Proxy> m_proxies;
std::vector<uint16_t> 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 );

2320
samples/scene.cpp Normal file

File diff suppressed because it is too large Load diff

147
samples/scene.h Normal file
View file

@ -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 );

465
samples/shader.cpp Normal file
View file

@ -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 <assert.h>
#include <glad/glad.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <string>
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<char*>( 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 );
}
}

39
samples/shader.h Normal file
View file

@ -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 );

163
samples/ssao_buffer.cpp Normal file
View file

@ -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 <glad/glad.h>
#include <stdlib.h>
#include <random>
#include <stdint.h>
#include <stdio.h>
#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<float> 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);
}

21
samples/ssao_buffer.h Normal file
View file

@ -0,0 +1,21 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include <stdint.h>
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);

1724
samples/stb_image_write.h Normal file

File diff suppressed because it is too large Load diff

5079
samples/stb_truetype.h Normal file

File diff suppressed because it is too large Load diff

3499
samples/tiny_obj_loader.h Normal file

File diff suppressed because it is too large Load diff

118
samples/utility.h Normal file
View file

@ -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;
};